| 1 | //! `apply_*` helpers: committing an already-resolved choice to `App`, the |
| 2 | //! engine, and persisted settings. |
| 3 | //! |
| 4 | //! Moved verbatim out of `ui.rs`. |
| 5 | |
| 6 | use super::observer_hooks::{ |
| 7 | execute_subagent_observer_hook, subagent_failure_notice, |
| 8 | surface_observer_hook_submission_failure, |
| 9 | }; |
| 10 | use super::task_projection::refresh_active_task_panel; |
| 11 | use super::*; |
| 12 | |
| 13 | pub(super) fn apply_approve_auto_review_retry( |
| 14 | app: &mut App, |
| 15 | engine_handle: &EngineHandle, |
| 16 | target: &str, |
| 17 | ) { |
| 18 | match engine_handle.approve_auto_review_retry(target) { |
| 19 | Ok(grant) => { |
| 20 | app.mark_auto_review_receipt_approved(&grant.receipt_id); |
| 21 | let msg = tr(app.ui_locale, MessageId::AutoReviewRetryApprovedStatus) |
| 22 | .replace("{tool}", &grant.tool_name) |
| 23 | .replace("{id}", &grant.receipt_id); |
| 24 | app.add_message(HistoryCell::System { |
| 25 | content: msg.clone(), |
| 26 | }); |
| 27 | app.show_command_result(msg, StatusToastLevel::Success); |
| 28 | app.needs_redraw = true; |
| 29 | } |
| 30 | Err(error) => { |
| 31 | let msg = tr(app.ui_locale, MessageId::AutoReviewRetryFailedStatus) |
| 32 | .replace("{id}", target) |
| 33 | .replace("{error}", &error.to_string()); |
| 34 | app.push_status_toast(msg, StatusToastLevel::Warning, Some(8_000)); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | /// Record the model frozen into a child's runtime at spawn time. |
| 40 | /// |
| 41 | /// This is child-route evidence, not an inference from the parent session. A |
| 42 | /// later usage envelope may confirm or replace it with the provider's |
| 43 | /// effective route while also adding provider and token facts. |
| 44 | pub(crate) fn record_agent_spawned_route(app: &mut App, agent_id: &str, model: &str) { |
| 45 | let model = bound_agent_activity_text( |
| 46 | &codewhale_runtime::safe_label::sanitize_persisted_route_label(model), |
| 47 | ); |
| 48 | app.agent_progress_meta |
| 49 | .entry(agent_id.to_string()) |
| 50 | .or_default() |
| 51 | .resolved_model = Some(model).filter(|model| !model.trim().is_empty()); |
| 52 | } |
| 53 | |
| 54 | /// Apply the normal spawn status first, then submit its observer event. |
| 55 | /// Submission diagnostics go to the independent toast queue, so they remain |
| 56 | /// visible without replacing the agent's authoritative lifecycle status. |
| 57 | pub(crate) fn apply_agent_spawned_status_and_observer( |
| 58 | app: &mut App, |
| 59 | agent_id: &str, |
| 60 | prompt: &str, |
| 61 | prompt_summary: &str, |
| 62 | ) { |
| 63 | let label = app.ensure_agent_label(agent_id); |
| 64 | app.push_status_toast_record( |
| 65 | StatusToast::new( |
| 66 | format!( |
| 67 | "{} · {label} · {}", |
| 68 | app.tr(MessageId::SubagentsStatusRunning), |
| 69 | bound_agent_activity_text(prompt_summary) |
| 70 | ), |
| 71 | StatusToastLevel::Info, |
| 72 | Some(4_000), |
| 73 | ) |
| 74 | .for_event(format!("subagent-start:{agent_id}")), |
| 75 | ); |
| 76 | if let Err(error) = |
| 77 | execute_subagent_observer_hook(app, HookEvent::SubagentSpawn, agent_id, "prompt", prompt) |
| 78 | { |
| 79 | surface_observer_hook_submission_failure(app, error); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Completion counterpart to [`apply_agent_spawned_status_and_observer`]. |
| 84 | pub(crate) fn apply_agent_complete_status_and_observer( |
| 85 | app: &mut App, |
| 86 | agent_id: &str, |
| 87 | result: &str, |
| 88 | status: &SubAgentStatus, |
| 89 | ) { |
| 90 | let label = app.agent_display_label(agent_id); |
| 91 | let level = match status { |
| 92 | SubAgentStatus::Completed => StatusToastLevel::Success, |
| 93 | SubAgentStatus::Failed(_) | SubAgentStatus::BudgetExhausted => StatusToastLevel::Error, |
| 94 | SubAgentStatus::Interrupted(_) | SubAgentStatus::Cancelled => StatusToastLevel::Warning, |
| 95 | SubAgentStatus::Running => StatusToastLevel::Info, |
| 96 | }; |
| 97 | let failure = subagent_failure_notice(result); |
| 98 | let detail = failure.as_deref().unwrap_or(result); |
| 99 | let message = format!( |
| 100 | "{} · {label} · {}", |
| 101 | app.tr(notifications::subagent_terminal_label(status)), |
| 102 | bound_agent_activity_text(detail) |
| 103 | ); |
| 104 | if level == StatusToastLevel::Error { |
| 105 | app.set_sticky_status(message, level, Some(App::STICKY_ERROR_TTL_MS)); |
| 106 | } else { |
| 107 | app.push_status_toast_record( |
| 108 | StatusToast::new(message, level, Some(5_000)) |
| 109 | .for_event(format!("subagent-terminal:{agent_id}")), |
| 110 | ); |
| 111 | } |
| 112 | if let Err(error) = |
| 113 | execute_subagent_observer_hook(app, HookEvent::SubagentComplete, agent_id, "result", result) |
| 114 | { |
| 115 | surface_observer_hook_submission_failure(app, error); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | const COORDINATION_LOCK_NOTICE: &str = "coordination-lock"; |
| 120 | |
| 121 | pub(crate) fn apply_coordination_detail_projection( |
| 122 | app: &mut App, |
| 123 | projection: codewhale_engine::tools::subagent::CoordinationDetailProjection, |
| 124 | ) { |
| 125 | let changed = app.coordination_detail.as_ref().is_none_or(|previous| { |
| 126 | previous.process_lock_held != projection.process_lock_held |
| 127 | || previous.process_lock_note != projection.process_lock_note |
| 128 | }); |
| 129 | if changed { |
| 130 | app.retire_event_notices(COORDINATION_LOCK_NOTICE); |
| 131 | if !projection.process_lock_held { |
| 132 | let note = projection.process_lock_note.as_deref().unwrap_or_default(); |
| 133 | let same_process_handover = note |
| 134 | .starts_with(codewhale_engine::tools::subagent::COORDINATION_SAME_PROCESS_HANDOVER); |
| 135 | if !same_process_handover { |
| 136 | let message = if note.starts_with( |
| 137 | codewhale_engine::tools::subagent::COORDINATION_LOCK_TIMEOUT_MARKER, |
| 138 | ) { |
| 139 | "Timed out claiming delegated coordination — see Work for the reason." |
| 140 | } else if note |
| 141 | .starts_with("Runtime coordination was opened without its writer lock") |
| 142 | { |
| 143 | "Delegated coordination is read-only — resolve the lock issue and restart this Runtime. Details in Work." |
| 144 | } else if note |
| 145 | .starts_with(codewhale_engine::tools::subagent::SESSION_PRIVATE_COORDINATION) |
| 146 | { |
| 147 | "Sub-agents here keep private state while another Codewhale session uses this folder — see Work." |
| 148 | } else { |
| 149 | "Delegated coordination unavailable — see Work for the reason." |
| 150 | }; |
| 151 | app.push_status_toast_record( |
| 152 | StatusToast::new(message, StatusToastLevel::Info, Some(5_000)) |
| 153 | .for_event(COORDINATION_LOCK_NOTICE), |
| 154 | ); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | app.needs_redraw |= changed; |
| 159 | app.coordination_detail = Some(projection); |
| 160 | } |
| 161 | |
| 162 | pub(crate) fn apply_alt_4_shortcut(app: &mut App, _modifiers: KeyModifiers) { |
| 163 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Files); |
| 164 | } |
| 165 | |
| 166 | pub(crate) fn apply_alt_0_shortcut(app: &mut App, modifiers: KeyModifiers) { |
| 167 | // Ctrl+Alt+0 toggles the rail off and back to the default bottom |
| 168 | // placement. Plain Alt+0 is unbound: it used to select the retired |
| 169 | // auto-collapse mode. |
| 170 | if modifiers.contains(KeyModifiers::CONTROL) { |
| 171 | if app.work_surface.placement == crate::tui::work_surface::WorkSurfacePlacement::Off { |
| 172 | app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Bottom; |
| 173 | app.show_command_result( |
| 174 | "Workbar: bottom placement".to_string(), |
| 175 | StatusToastLevel::Info, |
| 176 | ); |
| 177 | } else { |
| 178 | app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Off; |
| 179 | app.show_command_result("Workbar is off".to_string(), StatusToastLevel::Info); |
| 180 | } |
| 181 | app.needs_redraw = true; |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | pub(crate) fn apply_picker_session_rename_to_active_app( |
| 186 | app: &mut App, |
| 187 | metadata: codewhale_engine::session_manager::SessionMetadata, |
| 188 | ) -> bool { |
| 189 | if app.current_session_id.as_deref() != Some(metadata.id.as_str()) { |
| 190 | return false; |
| 191 | } |
| 192 | app.adopt_session_mutation(&metadata); |
| 193 | app.session_title = Some(metadata.title.clone()); |
| 194 | app.current_session_metadata = Some(metadata); |
| 195 | true |
| 196 | } |
| 197 | |
| 198 | /// Translate an `EngineEvent::Error` into UI state updates. |
| 199 | /// |
| 200 | /// The engine's `recoverable` flag (mirrored on `ErrorEnvelope`) decides |
| 201 | /// whether an active turn stays live. Only an environment-only authentication |
| 202 | /// failure enables offline queueing here while reopening provider setup. |
| 203 | /// |
| 204 | /// `severity` drives transcript color: red for `Error`/`Critical`, amber for |
| 205 | /// `Warning`, dim for `Info`. |
| 206 | pub(crate) fn apply_engine_error_to_app( |
| 207 | app: &mut App, |
| 208 | envelope: codewhale_error_taxonomy::ErrorEnvelope, |
| 209 | ) { |
| 210 | let recoverable = envelope.recoverable; |
| 211 | let message = envelope.message.clone(); |
| 212 | let history_message = envelope.request_transmission.map_or_else( |
| 213 | || message.clone(), |
| 214 | |transmission| format!("{message} [{transmission}]"), |
| 215 | ); |
| 216 | let severity = envelope.severity; |
| 217 | let turn_was_in_progress = |
| 218 | app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")); |
| 219 | // A recoverable error can precede tool decisions in the same turn. Keep |
| 220 | // routing those events until TurnComplete; marking the UI idle here drops |
| 221 | // ApprovalRequired and leaves the engine waiting for an invisible decision. |
| 222 | // An idle or locally cancelled turn must never be reactivated by an error. |
| 223 | let turn_remains_active = |
| 224 | recoverable && turn_was_in_progress && !app.suppress_stream_events_until_turn_complete; |
| 225 | // The engine decides whether the question was taken back out of the |
| 226 | // session; the host only follows, so the two cannot disagree (#6566). |
| 227 | let credential_rejected_before_output = turn_was_in_progress |
| 228 | && envelope.code == codewhale_error_taxonomy::CREDENTIAL_REJECTED_UNSENT_CODE; |
| 229 | streaming_thinking::finalize_current(app); |
| 230 | if turn_was_in_progress { |
| 231 | app.finalize_streaming_assistant_as_interrupted(); |
| 232 | app.finalize_active_cell_as_interrupted(); |
| 233 | if !turn_remains_active { |
| 234 | app.runtime_turn_status = Some("failed".to_string()); |
| 235 | } |
| 236 | } |
| 237 | app.streaming_state.reset(); |
| 238 | app.streaming_message_index = None; |
| 239 | app.streaming_thinking_active_entry = None; |
| 240 | // Before the error line lands, so the question's bubble is still the last |
| 241 | // cell and can come out with it. A draft the person already started in |
| 242 | // the composer is left alone, and so is the bubble that holds their text. |
| 243 | let unsent_message = if credential_rejected_before_output && app.input.is_empty() { |
| 244 | take_back_unsent_submission(app) |
| 245 | } else { |
| 246 | None |
| 247 | }; |
| 248 | |
| 249 | // #455 (observer-only): fire `on_error` hooks so operators can |
| 250 | // page on auth / billing / invalid-request failures without |
| 251 | // tailing the audit log. Read-only — the hook can react but not |
| 252 | // suppress the error from reaching the transcript. Fast-path |
| 253 | // skip when no hooks configured. |
| 254 | if app |
| 255 | .hooks |
| 256 | .has_hooks_for_event(codewhale_config::hooks::HookEvent::OnError) |
| 257 | { |
| 258 | let context = app.base_hook_context().with_error(&message); |
| 259 | if let Err(error) = app.submit_hooks(codewhale_config::hooks::HookEvent::OnError, context) { |
| 260 | surface_observer_hook_submission_failure(app, error); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | let turn_error_notice = history_message.clone(); |
| 265 | app.add_message(HistoryCell::Error { |
| 266 | message: history_message, |
| 267 | severity, |
| 268 | code: crate::tui::history::normalize_error_code(&envelope.code), |
| 269 | }); |
| 270 | app.is_loading = turn_remains_active; |
| 271 | if !turn_remains_active { |
| 272 | app.dispatch_started_at = None; |
| 273 | } |
| 274 | app.turn_error_posted = true; |
| 275 | app.turn_error_notice = Some(turn_error_notice); |
| 276 | app.turn_error_cause = Some( |
| 277 | codewhale_engine::llm_error_envelope::ProviderFailureCause::from_envelope(&envelope, None), |
| 278 | ); |
| 279 | if credential_rejected_before_output { |
| 280 | // #6566: the provider refused the key before any model output, so the |
| 281 | // engine takes the question back out of the session. Give it back to |
| 282 | // the person with the one next step, instead of an error with no way |
| 283 | // forward and a message they must retype. The whole message comes |
| 284 | // back, a skill it invoked included. |
| 285 | match unsent_message { |
| 286 | Some(message) => app.restore_unsent_message(message), |
| 287 | None => { |
| 288 | app.restore_last_submitted_prompt_if_empty(); |
| 289 | } |
| 290 | } |
| 291 | app.add_message(HistoryCell::System { |
| 292 | content: app.tr(MessageId::AuthRejectedRecovery).into_owned(), |
| 293 | }); |
| 294 | } |
| 295 | if matches!( |
| 296 | envelope.category, |
| 297 | codewhale_error_taxonomy::ErrorCategory::Authentication |
| 298 | ) && app.api_key_env_only |
| 299 | { |
| 300 | app.offline_mode = true; |
| 301 | app.onboarding_needs_api_key = true; |
| 302 | // The key was rejected, not missing: Esc returns to the composer and |
| 303 | // the picker focuses the configured route, as missing-key recovery |
| 304 | // does, instead of walking back through first-run screens. |
| 305 | app.onboarding_missing_key_recovery = true; |
| 306 | app.onboarding = OnboardingState::Provider; |
| 307 | let provider = app.api_provider; |
| 308 | let config_path = |
| 309 | match codewhale_runtime::config::resolve_load_config_path(app.config_path.clone()) { |
| 310 | Ok(Some(path)) => path.display().to_string(), |
| 311 | Ok(None) => "~/.codewhale/config.toml".to_string(), |
| 312 | Err(error) => error.to_string(), |
| 313 | }; |
| 314 | let notice = tr(app.ui_locale, MessageId::OnboardApiKeyRejectedEnv) |
| 315 | .replace("{provider}", provider.as_str()) |
| 316 | .replace("{env}", &provider.provider().env_vars().join(" / ")) |
| 317 | .replace("{path}", &config_path); |
| 318 | // The setup screen covers the transcript, so it must say why it |
| 319 | // opened. The log records the reason without the provider's message, |
| 320 | // which the transcript already carries. |
| 321 | codewhale_runtime::logging::warn(format!( |
| 322 | "{} rejected the environment API key; opening provider setup", |
| 323 | provider.as_str() |
| 324 | )); |
| 325 | app.onboarding_key_rejected = Some(notice.clone()); |
| 326 | app.push_status_toast( |
| 327 | notice, |
| 328 | StatusToastLevel::Error, |
| 329 | Some(App::STICKY_ERROR_TTL_MS), |
| 330 | ); |
| 331 | return; |
| 332 | } |
| 333 | if recoverable |
| 334 | && matches!( |
| 335 | envelope.category, |
| 336 | codewhale_error_taxonomy::ErrorCategory::Network |
| 337 | | codewhale_error_taxonomy::ErrorCategory::RateLimit |
| 338 | | codewhale_error_taxonomy::ErrorCategory::Timeout |
| 339 | ) |
| 340 | && app.advance_fallback(message.clone()).is_some() |
| 341 | { |
| 342 | let position = app.fallback_chain_position().unwrap_or(0); |
| 343 | let total = app.fallback_chain_len(); |
| 344 | app.push_status_toast( |
| 345 | app.tr(MessageId::NotificationProviderFallback) |
| 346 | .replace("{provider}", app.api_provider.as_str()) |
| 347 | .replace("{position}", &position.to_string()) |
| 348 | .replace("{total}", &total.saturating_sub(1).to_string()), |
| 349 | StatusToastLevel::Warning, |
| 350 | Some(8_000), |
| 351 | ); |
| 352 | } |
| 353 | // Error is already in the transcript as HistoryCell::Error above; |
| 354 | // don't emit a redundant notice that would become a sticky |
| 355 | // toast in the footer — that duplicates the transcript entry. |
| 356 | } |
| 357 | |
| 358 | pub(crate) fn apply_message_submit_outcome( |
| 359 | app: &mut App, |
| 360 | message: &mut QueuedMessage, |
| 361 | outcome: codewhale_engine::hooks::MessageSubmitOutcome, |
| 362 | ) -> Result<(), String> { |
| 363 | if let Some(warning) = outcome.warning() { |
| 364 | app.push_status_toast(warning, StatusToastLevel::Warning, Some(6_000)); |
| 365 | } |
| 366 | match outcome { |
| 367 | codewhale_engine::hooks::MessageSubmitOutcome::Unchanged { .. } => Ok(()), |
| 368 | codewhale_engine::hooks::MessageSubmitOutcome::Replaced { text, .. } => { |
| 369 | // A queued message was already echoed with its pre-hook text. |
| 370 | // Retarget that one cell so dispatch reuses it instead of adding a |
| 371 | // second User cell beside the stale echo (U02-03). |
| 372 | if message.history_echoed |
| 373 | && let Some(idx) = |
| 374 | crate::tui::ui::dispatch::echoed_user_turn_cell(app, &message.display) |
| 375 | { |
| 376 | app.history[idx] = HistoryCell::User { |
| 377 | content: text.clone(), |
| 378 | }; |
| 379 | app.bump_history_cell(idx); |
| 380 | } |
| 381 | message.display = text; |
| 382 | message.owner_input = false; |
| 383 | Ok(()) |
| 384 | } |
| 385 | codewhale_engine::hooks::MessageSubmitOutcome::Blocked { reason } => Err(reason), |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | fn visible_goal_as_durable( |
| 390 | app: &App, |
| 391 | ) -> Result<Option<codewhale_engine::session_manager::SessionGoalState>, String> { |
| 392 | let Some(objective) = app.goal.objective.as_deref() else { |
| 393 | return Ok(None); |
| 394 | }; |
| 395 | let elapsed_seconds = app |
| 396 | .goal |
| 397 | .started_at |
| 398 | .map(|started| started.elapsed().as_secs()) |
| 399 | .unwrap_or(app.goal.time_used_seconds) |
| 400 | .max(app.goal.time_used_seconds); |
| 401 | codewhale_engine::session_manager::SessionGoalState::from_runtime(&GoalSnapshot { |
| 402 | objective: Some(objective.to_string()), |
| 403 | status: app.goal.status.as_str().to_string(), |
| 404 | token_budget: app.goal.token_budget, |
| 405 | tokens_used: app.goal.tokens_used, |
| 406 | time_used_seconds: app.goal.time_used_seconds, |
| 407 | continuation_count: app.goal.continuation_count, |
| 408 | elapsed_seconds: Some(elapsed_seconds), |
| 409 | pause_reason: app.goal.pause_reason, |
| 410 | ..Default::default() |
| 411 | }) |
| 412 | .map_err(|error| error.to_string()) |
| 413 | } |
| 414 | |
| 415 | fn desired_goal_state( |
| 416 | app: &App, |
| 417 | intent: &GoalControlIntent, |
| 418 | ) -> Result<Option<codewhale_engine::session_manager::SessionGoalState>, String> { |
| 419 | let mut base = if app.pending_goal_controls.is_empty() { |
| 420 | match app.last_known_goal_state.clone() { |
| 421 | Some(goal) => Some(goal), |
| 422 | None => visible_goal_as_durable(app)?, |
| 423 | } |
| 424 | } else { |
| 425 | // Accepted controls compose over the latest durable target, not the |
| 426 | // older visible projection that is still waiting on GoalUpdated. |
| 427 | app.last_known_goal_state.clone() |
| 428 | }; |
| 429 | match intent { |
| 430 | GoalControlIntent::SetStatus { clear: true, .. } => Ok(None), |
| 431 | GoalControlIntent::SetStatus { |
| 432 | status, |
| 433 | clear: false, |
| 434 | } => { |
| 435 | let goal = base |
| 436 | .as_mut() |
| 437 | .ok_or_else(|| "No goal is available for this control.".to_string())?; |
| 438 | let was_active = |
| 439 | goal.status == codewhale_engine::session_manager::SessionGoalStatus::Active; |
| 440 | goal.status = match status { |
| 441 | GoalStatus::Active => codewhale_engine::session_manager::SessionGoalStatus::Active, |
| 442 | GoalStatus::Paused => codewhale_engine::session_manager::SessionGoalStatus::Paused, |
| 443 | GoalStatus::Complete => { |
| 444 | codewhale_engine::session_manager::SessionGoalStatus::Complete |
| 445 | } |
| 446 | GoalStatus::Blocked => { |
| 447 | codewhale_engine::session_manager::SessionGoalStatus::Blocked |
| 448 | } |
| 449 | }; |
| 450 | if *status == GoalStatus::Active && !was_active { |
| 451 | goal.goal_id = Some(uuid::Uuid::new_v4().to_string()); |
| 452 | goal.last_gap_fingerprint = None; |
| 453 | goal.repeated_gap_count = 0; |
| 454 | goal.last_gap_pass = None; |
| 455 | } |
| 456 | goal.pause_reason = (*status == GoalStatus::Paused) |
| 457 | .then_some(codewhale_engine::tools::goal::GoalPauseReason::User); |
| 458 | Ok(base) |
| 459 | } |
| 460 | GoalControlIntent::SetObjective { |
| 461 | objective, |
| 462 | token_budget, |
| 463 | } => codewhale_engine::session_manager::SessionGoalState::from_runtime(&GoalSnapshot { |
| 464 | goal_id: Some(uuid::Uuid::new_v4().to_string()), |
| 465 | objective: Some(objective.clone()), |
| 466 | status: GoalStatus::Active.as_str().to_string(), |
| 467 | token_budget: *token_budget, |
| 468 | elapsed_seconds: Some(0), |
| 469 | ..Default::default() |
| 470 | }) |
| 471 | .map_err(|error| error.to_string()), |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | fn persist_accepted_goal_state( |
| 476 | app: &mut App, |
| 477 | desired: Option<&codewhale_engine::session_manager::SessionGoalState>, |
| 478 | ) -> Result<(), String> { |
| 479 | let manager = SessionManager::default_location() |
| 480 | .map_err(|error| format!("could not open the session store: {error}"))?; |
| 481 | if app.current_session_id.is_none() { |
| 482 | let session = build_session_snapshot(app, &manager)?; |
| 483 | let session_id = session.metadata.id.clone(); |
| 484 | if !super::session_state::try_persist_session( |
| 485 | app, |
| 486 | PersistRequest::SaveCheckpoint { session }, |
| 487 | ) { |
| 488 | return Err("the persistence worker is unavailable".to_string()); |
| 489 | } |
| 490 | app.set_current_session_id(Some(session_id)); |
| 491 | } |
| 492 | let session_id = app |
| 493 | .current_session_id |
| 494 | .as_deref() |
| 495 | .ok_or_else(|| "session id is not established".to_string())?; |
| 496 | manager |
| 497 | .save_session_goal(session_id, desired) |
| 498 | .map_err(|error| error.to_string()) |
| 499 | } |
| 500 | |
| 501 | fn goal_control_op(intent: &GoalControlIntent, goal_id: Option<String>) -> Op { |
| 502 | match intent { |
| 503 | GoalControlIntent::SetStatus { status, clear } => Op::SetGoalStatus { |
| 504 | goal_id, |
| 505 | status: *status, |
| 506 | clear: *clear, |
| 507 | }, |
| 508 | GoalControlIntent::SetObjective { |
| 509 | objective, |
| 510 | token_budget, |
| 511 | } => Op::SetGoalObjective { |
| 512 | goal_id, |
| 513 | objective: objective.clone(), |
| 514 | token_budget: *token_budget, |
| 515 | }, |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | /// Retry accepted goal controls without ever awaiting mailbox capacity on the |
| 520 | /// input loop. FIFO order is retained until each authoritative receipt lands. |
| 521 | pub(crate) fn flush_pending_goal_controls(app: &mut App, engine_handle: &EngineHandle) -> bool { |
| 522 | for pending in &mut app.pending_goal_controls { |
| 523 | if pending.dispatched { |
| 524 | continue; |
| 525 | } |
| 526 | if engine_handle |
| 527 | .try_send(goal_control_op(&pending.intent, pending.goal_id.clone())) |
| 528 | .is_err() |
| 529 | { |
| 530 | return engine_handle.tx_op.is_closed(); |
| 531 | } |
| 532 | pending.dispatched = true; |
| 533 | } |
| 534 | false |
| 535 | } |
| 536 | |
| 537 | fn goal_control_matches( |
| 538 | intent: &GoalControlIntent, |
| 539 | durable: Option<&codewhale_engine::session_manager::SessionGoalState>, |
| 540 | ) -> bool { |
| 541 | match intent { |
| 542 | GoalControlIntent::SetStatus { clear: true, .. } => durable.is_none(), |
| 543 | GoalControlIntent::SetStatus { |
| 544 | status, |
| 545 | clear: false, |
| 546 | } => durable.is_some_and(|goal| { |
| 547 | goal.status |
| 548 | == match status { |
| 549 | GoalStatus::Active => { |
| 550 | codewhale_engine::session_manager::SessionGoalStatus::Active |
| 551 | } |
| 552 | GoalStatus::Paused => { |
| 553 | codewhale_engine::session_manager::SessionGoalStatus::Paused |
| 554 | } |
| 555 | GoalStatus::Complete => { |
| 556 | codewhale_engine::session_manager::SessionGoalStatus::Complete |
| 557 | } |
| 558 | GoalStatus::Blocked => { |
| 559 | codewhale_engine::session_manager::SessionGoalStatus::Blocked |
| 560 | } |
| 561 | } |
| 562 | }), |
| 563 | GoalControlIntent::SetObjective { |
| 564 | objective, |
| 565 | token_budget, |
| 566 | } => durable.is_some_and(|goal| { |
| 567 | goal.objective == *objective |
| 568 | && goal.status == codewhale_engine::session_manager::SessionGoalStatus::Active |
| 569 | && goal.token_budget == *token_budget |
| 570 | }), |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | fn accept_goal_control(app: &mut App, engine_handle: &EngineHandle, intent: GoalControlIntent) { |
| 575 | let desired = match desired_goal_state(app, &intent) { |
| 576 | Ok(desired) => desired, |
| 577 | Err(error) => { |
| 578 | surface_goal_persistence_failure(app, &error); |
| 579 | return; |
| 580 | } |
| 581 | }; |
| 582 | if let Err(error) = persist_accepted_goal_state(app, desired.as_ref()) { |
| 583 | surface_goal_persistence_failure(app, &error); |
| 584 | return; |
| 585 | } |
| 586 | |
| 587 | if matches!( |
| 588 | intent, |
| 589 | GoalControlIntent::SetStatus { |
| 590 | status: GoalStatus::Complete, |
| 591 | clear: false |
| 592 | } |
| 593 | ) { |
| 594 | codewhale_runtime::audit::log_sensitive_event( |
| 595 | "goal.user_completed", |
| 596 | serde_json::json!({ "accepted": true }), |
| 597 | ); |
| 598 | } |
| 599 | app.last_known_goal_state = desired; |
| 600 | app.pending_goal_controls.push_back(PendingGoalControl { |
| 601 | goal_id: app |
| 602 | .last_known_goal_state |
| 603 | .as_ref() |
| 604 | .and_then(|goal| goal.goal_id.clone()), |
| 605 | intent, |
| 606 | dispatched: false, |
| 607 | }); |
| 608 | let runtime_closed = flush_pending_goal_controls(app, engine_handle); |
| 609 | app.add_message(HistoryCell::System { |
| 610 | content: app.tr(MessageId::GoalControlAccepted).to_string(), |
| 611 | }); |
| 612 | if runtime_closed { |
| 613 | app.push_status_toast( |
| 614 | app.tr(MessageId::GoalControlRuntimeUnavailable).to_string(), |
| 615 | StatusToastLevel::Warning, |
| 616 | None, |
| 617 | ); |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | pub(crate) fn apply_goal_snapshot_to_app(app: &mut App, snapshot: &GoalSnapshot) -> bool { |
| 622 | let durable_goal = |
| 623 | match codewhale_engine::session_manager::SessionGoalState::from_runtime(snapshot) { |
| 624 | Ok(goal) => goal, |
| 625 | Err(error) => { |
| 626 | tracing::warn!("ignoring invalid runtime goal snapshot: {error}"); |
| 627 | return false; |
| 628 | } |
| 629 | }; |
| 630 | let pending_desired = app.last_known_goal_state.clone(); |
| 631 | let matched_pending = app.pending_goal_controls.front().is_some_and(|pending| { |
| 632 | pending.dispatched |
| 633 | && pending.goal_id.as_deref().is_none_or(|id| { |
| 634 | Some(id) |
| 635 | == durable_goal |
| 636 | .as_ref() |
| 637 | .and_then(|goal| goal.goal_id.as_deref()) |
| 638 | }) |
| 639 | && goal_control_matches(&pending.intent, durable_goal.as_ref()) |
| 640 | }); |
| 641 | // Accepted controls own the durable target until their exact revision's |
| 642 | // receipt arrives. An earlier pass cannot restore pre-resume stall state. |
| 643 | if !app.pending_goal_controls.is_empty() && !matched_pending { |
| 644 | return false; |
| 645 | } |
| 646 | let durable_changed = app.last_known_goal_state != durable_goal; |
| 647 | if matched_pending { |
| 648 | app.pending_goal_controls.pop_front(); |
| 649 | } |
| 650 | // An explicit engine-side clear is represented by the one canonical empty |
| 651 | // state emitted by GoalState::snapshot. Require both fields so a malformed |
| 652 | // objective-less Active/Blocked update cannot erase valid visible state. |
| 653 | if snapshot.objective.is_none() && snapshot.status.trim() == "none" { |
| 654 | let changed = app.goal.objective.is_some() |
| 655 | || app.goal.token_budget.is_some() |
| 656 | || app.goal.tokens_used != 0 |
| 657 | || app.goal.time_used_seconds != 0 |
| 658 | || app.goal.continuation_count != 0 |
| 659 | || app.goal.started_at.is_some() |
| 660 | || app.goal.finished_at.is_some() |
| 661 | || app.goal.status != GoalStatus::default(); |
| 662 | app.goal = crate::tui::app::HostGoalState::default(); |
| 663 | app.last_known_goal_state = if app.pending_goal_controls.is_empty() { |
| 664 | None |
| 665 | } else { |
| 666 | pending_desired |
| 667 | }; |
| 668 | return changed || matched_pending || durable_changed; |
| 669 | } |
| 670 | |
| 671 | let Some(objective) = snapshot |
| 672 | .objective |
| 673 | .as_deref() |
| 674 | .map(str::trim) |
| 675 | .filter(|objective| !objective.is_empty()) |
| 676 | else { |
| 677 | tracing::warn!( |
| 678 | "ignoring objective-less runtime goal snapshot with non-clear status: {}", |
| 679 | snapshot.status |
| 680 | ); |
| 681 | return false; |
| 682 | }; |
| 683 | let Some(status) = goal_status_from_snapshot(snapshot) else { |
| 684 | tracing::warn!("ignoring unknown runtime goal status: {}", snapshot.status); |
| 685 | return false; |
| 686 | }; |
| 687 | let verdict = status; |
| 688 | let objective_changed = app.goal.objective.as_deref() != Some(objective); |
| 689 | let progress_changed = app.goal.progress != snapshot.progress; |
| 690 | let changed = objective_changed |
| 691 | || app.goal.token_budget != snapshot.token_budget |
| 692 | || app.goal.tokens_used != snapshot.tokens_used |
| 693 | || app.goal.time_used_seconds != snapshot.time_used_seconds |
| 694 | || app.goal.continuation_count != snapshot.continuation_count |
| 695 | || app.goal.pause_reason != snapshot.pause_reason |
| 696 | || progress_changed |
| 697 | || app.goal.status != verdict; |
| 698 | if !changed { |
| 699 | app.last_known_goal_state = if app.pending_goal_controls.is_empty() { |
| 700 | durable_goal |
| 701 | } else { |
| 702 | pending_desired |
| 703 | }; |
| 704 | return matched_pending || durable_changed; |
| 705 | } |
| 706 | |
| 707 | // The runtime introduced a new active objective (the model called |
| 708 | // `create_goal`, or a restored session carried one): say so once, in one |
| 709 | // line, so the user knows a persistent goal is now driving turns and how |
| 710 | // to stop it. `/goal <objective>` sets the objective before this snapshot lands, |
| 711 | // so a user-declared goal does not repeat its own receipt. |
| 712 | if objective_changed && verdict == GoalStatus::Active { |
| 713 | let content = app |
| 714 | .tr(codewhale_localization::MessageId::GoalReceiptSet) |
| 715 | .replace("{objective}", objective); |
| 716 | app.add_message(crate::tui::history::HistoryCell::System { content }); |
| 717 | } |
| 718 | // A fresh reported-progress receipt reads like the model's own status |
| 719 | // line: percent with a bar, then the optional now/next lines it wrote. |
| 720 | // Paused/complete goals keep their last report silent — the lifecycle |
| 721 | // receipt already spoke — except a yield, whose progress is the stage |
| 722 | // report the user is handed back with. |
| 723 | if progress_changed |
| 724 | && (verdict == GoalStatus::Active |
| 725 | || snapshot.pause_reason |
| 726 | == Some(codewhale_engine::tools::goal::GoalPauseReason::Yielded)) |
| 727 | && let Some(progress) = snapshot.progress.as_ref() |
| 728 | { |
| 729 | let mut content = app |
| 730 | .tr(codewhale_localization::MessageId::GoalProgressReceipt) |
| 731 | .replace("{percent}", &progress.percent.to_string()) |
| 732 | .replace( |
| 733 | "{bar}", |
| 734 | &codewhale_engine::tools::goal::goal_progress_bar(progress.percent), |
| 735 | ); |
| 736 | if let Some(now) = progress.now.as_deref() { |
| 737 | content.push('\n'); |
| 738 | content.push_str( |
| 739 | &app.tr(codewhale_localization::MessageId::GoalProgressNow) |
| 740 | .replace("{note}", now), |
| 741 | ); |
| 742 | } |
| 743 | if let Some(next) = progress.next.as_deref() { |
| 744 | content.push('\n'); |
| 745 | content.push_str( |
| 746 | &app.tr(codewhale_localization::MessageId::GoalProgressNext) |
| 747 | .replace("{note}", next), |
| 748 | ); |
| 749 | } |
| 750 | app.add_message(crate::tui::history::HistoryCell::System { content }); |
| 751 | } |
| 752 | app.goal.progress = snapshot.progress.clone(); |
| 753 | app.goal.objective = Some(objective.to_string()); |
| 754 | app.goal.token_budget = snapshot.token_budget; |
| 755 | app.goal.tokens_used = snapshot.tokens_used; |
| 756 | app.goal.time_used_seconds = snapshot.time_used_seconds; |
| 757 | app.goal.continuation_count = snapshot.continuation_count; |
| 758 | app.goal.pause_reason = snapshot.pause_reason; |
| 759 | app.goal.status = verdict; |
| 760 | if objective_changed || app.goal.started_at.is_none() { |
| 761 | let now = Instant::now(); |
| 762 | let elapsed = std::time::Duration::from_secs(snapshot.elapsed_seconds.unwrap_or_default()); |
| 763 | app.goal.started_at = now.checked_sub(elapsed).or(Some(now)); |
| 764 | } |
| 765 | // Freeze the elapsed timer the first time a goal leaves the active state. |
| 766 | // Paused (Wounded) goals freeze too — usage snapshots keep arriving while |
| 767 | // paused, and clearing here would silently un-freeze a timer the user just |
| 768 | // paused (matching close_hunt, which records the pause instant). Only an |
| 769 | // explicit resume back to Hunting re-arms the timer. |
| 770 | match verdict { |
| 771 | GoalStatus::Complete | GoalStatus::Blocked | GoalStatus::Paused => { |
| 772 | if app.goal.finished_at.is_none() { |
| 773 | app.goal.finished_at = Some(Instant::now()); |
| 774 | } |
| 775 | } |
| 776 | GoalStatus::Active => app.goal.finished_at = None, |
| 777 | } |
| 778 | app.last_known_goal_state = if app.pending_goal_controls.is_empty() { |
| 779 | durable_goal |
| 780 | } else { |
| 781 | pending_desired |
| 782 | }; |
| 783 | true |
| 784 | } |
| 785 | |
| 786 | /// Apply an explicit mode selection from a user shortcut (Alt+A/P/Y). |
| 787 | /// |
| 788 | /// Uses `select_mode`, not `set_mode`, so an explicitly chosen mode is also the |
| 789 | /// startup default next launch – matching the permission dial and hotbar paths. |
| 790 | pub(crate) async fn apply_mode_update( |
| 791 | app: &mut App, |
| 792 | engine_handle: &EngineHandle, |
| 793 | mode: AppMode, |
| 794 | ) -> bool { |
| 795 | let outcome = app.select_mode(mode); |
| 796 | app.report_mode_selection(mode, outcome); |
| 797 | if outcome.changed_live_state() { |
| 798 | sync_mode_update(app, engine_handle).await; |
| 799 | true |
| 800 | } else { |
| 801 | false |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | pub(crate) async fn apply_model_and_compaction_update( |
| 806 | engine_handle: &EngineHandle, |
| 807 | compaction: codewhale_engine::compaction::CompactionConfig, |
| 808 | mode: AppMode, |
| 809 | route_limits: Option<codewhale_config::route::RouteLimits>, |
| 810 | ) { |
| 811 | let _ = engine_handle |
| 812 | .send(Op::SetModel { |
| 813 | model: compaction.model.clone(), |
| 814 | mode, |
| 815 | route_limits, |
| 816 | }) |
| 817 | .await; |
| 818 | let _ = engine_handle |
| 819 | .send(Op::SetCompaction { config: compaction }) |
| 820 | .await; |
| 821 | } |
| 822 | |
| 823 | /// Apply the choice made in the `/model` picker (#39): mutate App state so |
| 824 | /// the next turn uses the new model/effort, push the change to the running |
| 825 | /// engine via `Op::SetModel`/`Op::SetCompaction`, and surface a one-line |
| 826 | /// status describing what changed. Startup persistence is intentionally owned |
| 827 | /// by the picker's explicit Shift+D action in the view-event handler. |
| 828 | // The model/effort transition needs both the previous and next model+effort |
| 829 | // plus the engine, app, and config handles; bundling them into a struct here |
| 830 | // would only obscure a straightforward orchestration step. |
| 831 | #[allow(clippy::too_many_arguments)] |
| 832 | pub(crate) async fn apply_model_picker_choice( |
| 833 | app: &mut App, |
| 834 | engine_handle: &mut EngineHandle, |
| 835 | config: &mut Config, |
| 836 | model: String, |
| 837 | target_identity: Option<codewhale_runtime::config::ProviderIdentity>, |
| 838 | effort: codewhale_engine::reasoning_preference::ReasoningEffort, |
| 839 | previous_model: String, |
| 840 | previous_effort: codewhale_engine::reasoning_preference::ReasoningEffort, |
| 841 | save_as_startup_default: bool, |
| 842 | ) -> bool { |
| 843 | app.clear_setup_notice(); |
| 844 | if app.is_loading { |
| 845 | let message = app.setting_locked_message( |
| 846 | codewhale_localization::MessageId::SettingSubjectModelAndThinking, |
| 847 | ); |
| 848 | app.show_route_receipt(message, StatusToastLevel::Warning); |
| 849 | note_startup_default_not_saved(app, save_as_startup_default); |
| 850 | return false; |
| 851 | } |
| 852 | let Some(target_identity) = target_identity else { |
| 853 | app.show_route_receipt( |
| 854 | "The selected model has no admitted provider route.", |
| 855 | StatusToastLevel::Error, |
| 856 | ); |
| 857 | note_startup_default_not_saved(app, save_as_startup_default); |
| 858 | return false; |
| 859 | }; |
| 860 | if let Err(reason) = config.verify_provider_identity(&target_identity) { |
| 861 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 862 | note_startup_default_not_saved(app, save_as_startup_default); |
| 863 | return false; |
| 864 | } |
| 865 | let target_provider = target_identity.provider; |
| 866 | let target_key = target_identity.key.to_string(); |
| 867 | let model_is_auto = model.trim().eq_ignore_ascii_case("auto"); |
| 868 | let preserve_auto_effort = |
| 869 | app.reasoning_effort_preference.is_some() || effort != previous_effort; |
| 870 | if app.admitted_provider_identity().ok() != Some(&target_identity) { |
| 871 | switch_provider( |
| 872 | app, |
| 873 | engine_handle, |
| 874 | config, |
| 875 | target_identity.clone(), |
| 876 | (!model_is_auto).then_some(model.clone()), |
| 877 | ) |
| 878 | .await; |
| 879 | if app.api_provider != target_provider |
| 880 | || app.provider_identity_for_persistence() != target_key |
| 881 | { |
| 882 | // The switch was refused (missing credentials, bad route). The |
| 883 | // live route is still the old one, so persisting it as the startup |
| 884 | // default would silently pin the route the user just tried to leave. |
| 885 | note_startup_default_not_saved(app, save_as_startup_default); |
| 886 | return false; |
| 887 | } |
| 888 | if !model_is_auto { |
| 889 | apply_picker_effort_choice(app, engine_handle, effort, previous_effort).await; |
| 890 | if save_as_startup_default { |
| 891 | save_picker_route_as_default(app, config, effort); |
| 892 | } |
| 893 | return true; |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | let current_identity = match app.admitted_provider_identity().cloned() { |
| 898 | Ok(identity) => identity, |
| 899 | Err(reason) => { |
| 900 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 901 | note_startup_default_not_saved(app, save_as_startup_default); |
| 902 | return false; |
| 903 | } |
| 904 | }; |
| 905 | let model_changed = model != previous_model || app.auto_model != model_is_auto; |
| 906 | let mut resolved_model = model.clone(); |
| 907 | let mut route_base_url = config.active_route_base_url(); |
| 908 | let mut resolved_budget = None; |
| 909 | if !model_is_auto { |
| 910 | match codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 911 | config, |
| 912 | ¤t_identity, |
| 913 | Some(&model), |
| 914 | ) { |
| 915 | Ok(resolution) => { |
| 916 | resolved_model = resolution.candidate.wire_model_id().as_str().to_string(); |
| 917 | route_base_url = resolution.candidate.endpoint().base_url.clone(); |
| 918 | if model_changed { |
| 919 | resolved_budget = |
| 920 | Some((resolution.candidate.limits(), resolution.context_window)); |
| 921 | } |
| 922 | } |
| 923 | Err(reason) => { |
| 924 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 925 | note_startup_default_not_saved(app, save_as_startup_default); |
| 926 | return false; |
| 927 | } |
| 928 | } |
| 929 | } |
| 930 | |
| 931 | let effective_effort = if model_is_auto { |
| 932 | effort |
| 933 | } else { |
| 934 | effort.normalize_for_route_identity( |
| 935 | app.api_provider, |
| 936 | current_identity.key.as_str(), |
| 937 | &route_base_url, |
| 938 | &resolved_model, |
| 939 | ) |
| 940 | }; |
| 941 | let effort_changed = effort != previous_effort; |
| 942 | |
| 943 | if model_changed { |
| 944 | app.set_model_selection(resolved_model.clone()); |
| 945 | app.set_active_context_window_override(config, ¤t_identity); |
| 946 | if let Some((limits, context_window)) = resolved_budget { |
| 947 | app.set_active_route_resolution(route_base_url.clone(), limits, context_window); |
| 948 | } else { |
| 949 | app.active_route_limits = app.context_window_override_limits(); |
| 950 | app.active_route_base_url = route_base_url.clone(); |
| 951 | app.active_context_window_source = app.active_context_window.map_or( |
| 952 | codewhale_engine::route_runtime::ContextWindowSource::Fallback, |
| 953 | |window| window.source, |
| 954 | ); |
| 955 | } |
| 956 | let provider_identity = app.provider_identity_for_persistence().to_string(); |
| 957 | app.provider_models |
| 958 | .insert(provider_identity.clone(), resolved_model.clone()); |
| 959 | app.note_route_used(&provider_identity, &resolved_model); |
| 960 | app.clear_model_scoped_telemetry(); |
| 961 | } |
| 962 | let preference_changed = if model_is_auto && !preserve_auto_effort { |
| 963 | app.reasoning_effort_preference.take().is_some() |
| 964 | } else { |
| 965 | let changed = app.reasoning_effort_preference != Some(effort); |
| 966 | app.reasoning_effort_preference = Some(effort); |
| 967 | changed |
| 968 | }; |
| 969 | let live_effort_changed = effective_effort != app.reasoning_effort; |
| 970 | if !model_is_auto || preserve_auto_effort { |
| 971 | app.reasoning_effort = effective_effort; |
| 972 | } else { |
| 973 | app.reasoning_effort = ReasoningEffort::Auto; |
| 974 | } |
| 975 | if live_effort_changed || preference_changed { |
| 976 | app.invalidate_route_receipts_for_reasoning_change(); |
| 977 | } |
| 978 | if model_changed || live_effort_changed || preference_changed { |
| 979 | app.update_model_compaction_budget(); |
| 980 | maybe_warn_context_pressure(app); |
| 981 | } |
| 982 | |
| 983 | // A model pick is session-local by default. Keep the exact live route in |
| 984 | // memory and offer an explicit save decision; only Shift+D in the picker |
| 985 | // writes a startup default. |
| 986 | let route_provider = app.provider_identity_for_persistence().to_string(); |
| 987 | app.note_session_route_change(&route_provider, &resolved_model); |
| 988 | |
| 989 | if model_changed { |
| 990 | apply_model_and_compaction_update( |
| 991 | engine_handle, |
| 992 | app.compaction_config(), |
| 993 | app.mode, |
| 994 | app.active_route_limits, |
| 995 | ) |
| 996 | .await; |
| 997 | } |
| 998 | |
| 999 | let model_summary = if model_is_auto { |
| 1000 | "auto (per-turn model)".to_string() |
| 1001 | } else { |
| 1002 | resolved_model.clone() |
| 1003 | }; |
| 1004 | let previous_effort_summary = previous_effort.display_label_for_provider(app.api_provider); |
| 1005 | let applied_effort = app.reasoning_effort; |
| 1006 | let effort_summary = if applied_effort == ReasoningEffort::Auto { |
| 1007 | "auto (per-turn thinking)".to_string() |
| 1008 | } else { |
| 1009 | applied_effort |
| 1010 | .display_label_for_provider(app.api_provider) |
| 1011 | .to_string() |
| 1012 | }; |
| 1013 | |
| 1014 | let summary = match (model_changed, effort_changed) { |
| 1015 | (true, true) => format!( |
| 1016 | "Model: {previous_model} → {model_summary} · thinking: {previous_effort_summary} → {effort_summary}" |
| 1017 | ), |
| 1018 | (true, false) => { |
| 1019 | format!("Model: {previous_model} → {model_summary} · thinking {effort_summary}") |
| 1020 | } |
| 1021 | (false, true) => format!( |
| 1022 | "Thinking: {previous_effort_summary} → {effort_summary} · model {model_summary}" |
| 1023 | ), |
| 1024 | (false, false) => { |
| 1025 | format!("Model unchanged: {model_summary} · thinking {effort_summary}") |
| 1026 | } |
| 1027 | }; |
| 1028 | app.show_route_receipt(summary, StatusToastLevel::Info); |
| 1029 | // Setup progress records that a concrete route was selected successfully; |
| 1030 | // it is a local receipt, not a claim that the route became the default. |
| 1031 | if model_changed || !model_is_auto { |
| 1032 | record_provider_model_setup_progress(app, config); |
| 1033 | } |
| 1034 | if save_as_startup_default { |
| 1035 | save_picker_route_as_default(app, config, effort); |
| 1036 | } |
| 1037 | true |
| 1038 | } |
| 1039 | |
| 1040 | fn save_picker_route_as_default(app: &mut App, config: &Config, effort: ReasoningEffort) { |
| 1041 | use codewhale_localization::MessageId; |
| 1042 | if config.project_model.as_deref() == Some(app.model.as_str()) { |
| 1043 | app.finish_route_step( |
| 1044 | app.tr(MessageId::ProjectModelNotSavedAsDefault) |
| 1045 | .replace("{model}", &app.model), |
| 1046 | StatusToastLevel::Warning, |
| 1047 | ); |
| 1048 | return; |
| 1049 | } |
| 1050 | let (mut receipt, mut level) = match app.try_save_live_route_as_startup_default() { |
| 1051 | Ok(receipt) => (receipt, StatusToastLevel::Success), |
| 1052 | Err(err) => ( |
| 1053 | app.tr(MessageId::RouteSaveFailed) |
| 1054 | .replace("{error}", &err.to_string()), |
| 1055 | StatusToastLevel::Error, |
| 1056 | ), |
| 1057 | }; |
| 1058 | if let Err(error) = app.startup_defaults.apply_blocking( |
| 1059 | crate::tui::startup_defaults::StartupDefaults::reasoning_effort(effort.as_setting()), |
| 1060 | ) { |
| 1061 | level = StatusToastLevel::Error; |
| 1062 | receipt.push_str(" · "); |
| 1063 | receipt.push_str( |
| 1064 | &app.tr(MessageId::StartupDefaultNotSaved) |
| 1065 | .replace("{setting}", &app.tr(MessageId::SettingSubjectThinking)) |
| 1066 | .replace("{error}", &error.to_string()), |
| 1067 | ); |
| 1068 | } |
| 1069 | if let Some(project_model) = config.project_model.as_deref() { |
| 1070 | receipt.push_str(" · "); |
| 1071 | receipt.push_str( |
| 1072 | &app.tr(MessageId::ProjectConfigStillPinsModel) |
| 1073 | .replace("{model}", project_model), |
| 1074 | ); |
| 1075 | } |
| 1076 | app.finish_route_step(receipt, level); |
| 1077 | } |
| 1078 | |
| 1079 | pub(crate) async fn apply_picker_effort_choice( |
| 1080 | app: &mut App, |
| 1081 | engine_handle: &EngineHandle, |
| 1082 | effort: ReasoningEffort, |
| 1083 | previous_effort: ReasoningEffort, |
| 1084 | ) { |
| 1085 | if app |
| 1086 | .reject_setting_change_while_busy(codewhale_localization::MessageId::SettingSubjectThinking) |
| 1087 | { |
| 1088 | return; |
| 1089 | } |
| 1090 | let effective_effort = if app.auto_model { |
| 1091 | effort |
| 1092 | } else { |
| 1093 | effort.normalize_for_route(app.api_provider, &app.active_route_base_url, &app.model) |
| 1094 | }; |
| 1095 | let live_changed = effective_effort != app.reasoning_effort; |
| 1096 | let preference_changed = app.reasoning_effort_preference != Some(effort); |
| 1097 | let selection_changed = effort != previous_effort || live_changed; |
| 1098 | |
| 1099 | if live_changed || preference_changed { |
| 1100 | app.reasoning_effort = effective_effort; |
| 1101 | app.reasoning_effort_preference = Some(effort); |
| 1102 | } |
| 1103 | if selection_changed { |
| 1104 | app.invalidate_route_receipts_for_reasoning_change(); |
| 1105 | app.update_model_compaction_budget(); |
| 1106 | } |
| 1107 | |
| 1108 | if live_changed { |
| 1109 | apply_model_and_compaction_update( |
| 1110 | engine_handle, |
| 1111 | app.compaction_config(), |
| 1112 | app.mode, |
| 1113 | app.active_route_limits, |
| 1114 | ) |
| 1115 | .await; |
| 1116 | } |
| 1117 | |
| 1118 | let summary = if selection_changed { |
| 1119 | format!( |
| 1120 | "Thinking: {} → {} · model {}", |
| 1121 | previous_effort.display_label_for_provider(app.api_provider), |
| 1122 | effort.display_label_for_provider(app.api_provider), |
| 1123 | app.model_display_label() |
| 1124 | ) |
| 1125 | } else { |
| 1126 | format!( |
| 1127 | "Thinking unchanged: {} · model {}", |
| 1128 | effort.display_label_for_provider(app.api_provider), |
| 1129 | app.model_display_label() |
| 1130 | ) |
| 1131 | }; |
| 1132 | app.finish_route_step(summary, StatusToastLevel::Info); |
| 1133 | } |
| 1134 | |
| 1135 | pub(crate) async fn apply_provider_fallback_switch( |
| 1136 | app: &mut App, |
| 1137 | engine_handle: &mut EngineHandle, |
| 1138 | config: &mut Config, |
| 1139 | rollback: ProviderFallbackRollback, |
| 1140 | ) { |
| 1141 | let ProviderFallbackRollback { |
| 1142 | identity: previous_identity, |
| 1143 | chain: previous_chain, |
| 1144 | } = rollback; |
| 1145 | let previous_provider = previous_identity.provider; |
| 1146 | let target = app.api_provider; |
| 1147 | let previous_model = app.model.clone(); |
| 1148 | |
| 1149 | let target_capture = match app.admitted_provider_identity().cloned() { |
| 1150 | Ok(identity) => identity, |
| 1151 | Err(reason) => { |
| 1152 | app.set_provider_identity_record(previous_identity); |
| 1153 | app.provider_chain = previous_chain; |
| 1154 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 1155 | return; |
| 1156 | } |
| 1157 | }; |
| 1158 | let resolved_route = match resolve_runtime_route_for_identity(config, &target_capture, None) { |
| 1159 | Ok(route) => route, |
| 1160 | Err(reason) => { |
| 1161 | app.set_provider_identity_record(previous_identity.clone()); |
| 1162 | app.provider_chain = previous_chain.clone(); |
| 1163 | app.last_fallback_reason = Some(format!( |
| 1164 | "Fallback provider {} route was rejected: {reason}", |
| 1165 | target.as_str() |
| 1166 | )); |
| 1167 | app.show_route_receipt( |
| 1168 | format!( |
| 1169 | "Fallback provider {} rejected; provider remains {}.", |
| 1170 | target.as_str(), |
| 1171 | previous_provider.as_str() |
| 1172 | ), |
| 1173 | StatusToastLevel::Error, |
| 1174 | ); |
| 1175 | return; |
| 1176 | } |
| 1177 | }; |
| 1178 | let engine_route = resolved_route.clone(); |
| 1179 | let target_identity = resolved_route.identity.clone(); |
| 1180 | let resolved_endpoint = resolved_route.candidate.endpoint().base_url.clone(); |
| 1181 | let next_config = resolved_route.config; |
| 1182 | let new_model = resolved_route.model; |
| 1183 | let context_window = resolved_route.context_window; |
| 1184 | |
| 1185 | if let Err(err) = CodewhaleClient::from_candidate(&next_config, &resolved_route.candidate) { |
| 1186 | app.set_provider_identity_record(previous_identity); |
| 1187 | app.provider_chain = previous_chain; |
| 1188 | app.last_fallback_reason = Some(format!( |
| 1189 | "Fallback provider {} was unavailable: {err}", |
| 1190 | target.as_str() |
| 1191 | )); |
| 1192 | app.show_route_receipt( |
| 1193 | format!( |
| 1194 | "Fallback provider {} unavailable; provider remains {}.", |
| 1195 | target.as_str(), |
| 1196 | previous_provider.as_str() |
| 1197 | ), |
| 1198 | StatusToastLevel::Error, |
| 1199 | ); |
| 1200 | return; |
| 1201 | } |
| 1202 | *config = *next_config; |
| 1203 | app.refresh_notification_settings(config); |
| 1204 | app.set_provider_identity_record(target_identity.clone()); |
| 1205 | app.billing_presentation = codewhale_engine::route_billing::for_route(config, &target_identity); |
| 1206 | |
| 1207 | let new_base_url = resolved_endpoint; |
| 1208 | let new_endpoint = display_base_url_host(&new_base_url); |
| 1209 | let cache_scope_changed = previous_provider != target || previous_model != new_model; |
| 1210 | app.model_ids_passthrough = config.model_ids_pass_through(); |
| 1211 | app.set_model_selection(new_model.clone()); |
| 1212 | app.apply_provider_switch_reasoning_effort(target, &new_base_url, None); |
| 1213 | app.set_active_context_window_override(config, &target_identity); |
| 1214 | app.set_active_route_resolution( |
| 1215 | new_base_url.clone(), |
| 1216 | resolved_route.candidate.limits(), |
| 1217 | context_window, |
| 1218 | ); |
| 1219 | app.update_model_compaction_budget(); |
| 1220 | if cache_scope_changed { |
| 1221 | app.clear_model_scoped_telemetry(); |
| 1222 | } else { |
| 1223 | app.session.last_prompt_tokens = None; |
| 1224 | app.session.last_completion_tokens = None; |
| 1225 | } |
| 1226 | maybe_warn_context_pressure(app); |
| 1227 | |
| 1228 | let _ = engine_handle |
| 1229 | .send(Op::SetRoute { |
| 1230 | route: Box::new(engine_route), |
| 1231 | mode: app.mode, |
| 1232 | }) |
| 1233 | .await; |
| 1234 | let _ = engine_handle |
| 1235 | .send(Op::SetCompaction { |
| 1236 | config: app.compaction_config(), |
| 1237 | }) |
| 1238 | .await; |
| 1239 | |
| 1240 | app.add_message(HistoryCell::System { |
| 1241 | content: format!( |
| 1242 | "Provider fallback: {} -> {}\nModel: {} -> {}\nEndpoint: {}", |
| 1243 | previous_provider.as_str(), |
| 1244 | target.as_str(), |
| 1245 | previous_model, |
| 1246 | new_model, |
| 1247 | new_endpoint |
| 1248 | ), |
| 1249 | }); |
| 1250 | app.show_route_receipt( |
| 1251 | format!( |
| 1252 | "Fallback provider: {} via {}", |
| 1253 | target.as_str(), |
| 1254 | new_endpoint |
| 1255 | ), |
| 1256 | StatusToastLevel::Warning, |
| 1257 | ); |
| 1258 | } |
| 1259 | |
| 1260 | pub(super) fn reject_inline_inference_while_runtime_chat_owns_run( |
| 1261 | app: &mut App, |
| 1262 | result: &commands::CommandResult, |
| 1263 | ) -> bool { |
| 1264 | let blocked_inline_inference = matches!( |
| 1265 | result.action.as_ref(), |
| 1266 | Some(AppAction::VoiceCapture | AppAction::CacheWarmup) |
| 1267 | ) && app.remote_control.runtime_chat_blocks_local_dispatch(); |
| 1268 | if !blocked_inline_inference { |
| 1269 | return false; |
| 1270 | } |
| 1271 | if matches!(result.action.as_ref(), Some(AppAction::VoiceCapture)) { |
| 1272 | // `/voice` toggles this before returning the action. Restore the state |
| 1273 | // so a retry after relay settlement starts capture rather than merely |
| 1274 | // toggling the stale flag off. |
| 1275 | app.voice_enabled = false; |
| 1276 | } |
| 1277 | let notice = app |
| 1278 | .tr(MessageId::SettingLockedDuringTurn) |
| 1279 | .replace("{setting}", "Codewhale Runtime"); |
| 1280 | app.push_status_toast(notice, crate::tui::app::StatusToastLevel::Info, Some(6_000)); |
| 1281 | true |
| 1282 | } |
| 1283 | |
| 1284 | pub(crate) fn apply_notification_update( |
| 1285 | app: &mut App, |
| 1286 | config: &mut Config, |
| 1287 | update: codewhale_config::notifications::NotificationConfigUpdate, |
| 1288 | ) -> Result<()> { |
| 1289 | let mut notifications = config.notifications_config(); |
| 1290 | let setting = update.setting(); |
| 1291 | notifications.apply_update(update).map_err(|_| { |
| 1292 | anyhow::anyhow!( |
| 1293 | app.tr(MessageId::ConfigCommandInvalidValue) |
| 1294 | .replace("{key}", &format!("notifications.{}", setting.key())) |
| 1295 | .replace("{value}", &app.tr(MessageId::ConfigUnavailable)) |
| 1296 | .replace("{choices}", setting.choices()) |
| 1297 | ) |
| 1298 | })?; |
| 1299 | config.notifications = Some(notifications); |
| 1300 | app.refresh_notification_settings(config); |
| 1301 | Ok(()) |
| 1302 | } |
| 1303 | |
| 1304 | pub(super) enum ConversationRewind { |
| 1305 | Command(codewhale_command_contract::facets::SessionSyncPayload), |
| 1306 | Backtrack(usize), |
| 1307 | FileRange(usize), |
| 1308 | } |
| 1309 | |
| 1310 | /// Roll back only this idle Engine conversation, then require a durability |
| 1311 | /// receipt before a retry can reach inference. A save failure leaves the |
| 1312 | /// acknowledged undo visible, reports the error, and sends no replacement turn. |
| 1313 | pub(super) async fn apply_conversation_undo( |
| 1314 | app: &mut App, |
| 1315 | engine: &EngineHandle, |
| 1316 | target: ConversationRewind, |
| 1317 | ) -> Result<Option<anyhow::Error>> { |
| 1318 | anyhow::ensure!( |
| 1319 | !app.is_loading |
| 1320 | && !app.dispatch_in_flight |
| 1321 | && !app.remote_control.runtime_chat_blocks_local_dispatch(), |
| 1322 | "wait for the active turn to finish before undoing its conversation" |
| 1323 | ); |
| 1324 | let control = codewhale_engine::core::ops::SessionControlId::new(); |
| 1325 | let captured_source = app.session_write_receipt.clone(); |
| 1326 | let captured_owner = app.session_write_owner.clone(); |
| 1327 | let backtrack = !matches!(target, ConversationRewind::Command(_)); |
| 1328 | let before = if backtrack { |
| 1329 | let (tx, receive) = tokio::sync::oneshot::channel(); |
| 1330 | engine.try_send(Op::GetSessionSnapshot { |
| 1331 | tx: Arc::new(std::sync::Mutex::new(Some(tx))), |
| 1332 | })?; |
| 1333 | receive.await? |
| 1334 | } else { |
| 1335 | engine.get_session_snapshot().await? |
| 1336 | }; |
| 1337 | let before_prompt = |
| 1338 | codewhale_engine::compaction::strip_compaction_summaries(before.system_prompt.as_ref()); |
| 1339 | let changed = || { |
| 1340 | app.tr(MessageId::ConversationChangedBeforeUndo) |
| 1341 | .into_owned() |
| 1342 | }; |
| 1343 | anyhow::ensure!( |
| 1344 | app.current_session_id |
| 1345 | .as_deref() |
| 1346 | .is_none_or(|id| id == before.session_id) |
| 1347 | && app.workspace == before.workspace |
| 1348 | && app.model == before.model |
| 1349 | && before.mode == app.mode.as_setting() |
| 1350 | && codewhale_engine::compaction::strip_compaction_summaries(app.system_prompt.as_ref()) |
| 1351 | == before_prompt |
| 1352 | && before.messages.as_slice() == app.api_messages.as_slice() |
| 1353 | && captured_owner |
| 1354 | .as_ref() |
| 1355 | .zip(before.source.as_ref()) |
| 1356 | .is_some_and(|(owner, source)| owner.matches_source(source)), |
| 1357 | "{}", |
| 1358 | changed() |
| 1359 | ); |
| 1360 | let (messages, backtrack_depth) = match target { |
| 1361 | ConversationRewind::Command(sync) => { |
| 1362 | anyhow::ensure!( |
| 1363 | sync.session_id == app.current_session_id |
| 1364 | && sync.workspace == before.workspace |
| 1365 | && sync.model == before.model |
| 1366 | && codewhale_engine::compaction::strip_compaction_summaries( |
| 1367 | sync.system_prompt.as_ref() |
| 1368 | ) == before_prompt, |
| 1369 | "{}", |
| 1370 | changed() |
| 1371 | ); |
| 1372 | (sync.messages, None) |
| 1373 | } |
| 1374 | ConversationRewind::Backtrack(depth) | ConversationRewind::FileRange(depth) => { |
| 1375 | let cut = |
| 1376 | backtrack_api_cut_index(app, depth).ok_or_else(|| anyhow::anyhow!(changed()))?; |
| 1377 | (app.api_messages[..cut].to_vec(), Some(depth)) |
| 1378 | } |
| 1379 | }; |
| 1380 | anyhow::ensure!( |
| 1381 | messages.len() < before.messages.len() && before.messages.starts_with(&messages), |
| 1382 | "{}", |
| 1383 | changed() |
| 1384 | ); |
| 1385 | let id = before.session_id.clone(); |
| 1386 | // A live rewind retains the checkpoint already owned by these messages. |
| 1387 | // The Engine alone restores it and invalidates dependent caches. |
| 1388 | let expected = |
| 1389 | codewhale_engine::runtime_handoff::project_owned_messages_for_restore(messages.clone()); |
| 1390 | let (tx, receive) = tokio::sync::oneshot::channel(); |
| 1391 | let rewind = Op::RewindConversation { |
| 1392 | control: control.clone(), |
| 1393 | expected: Box::new(before), |
| 1394 | messages, |
| 1395 | tx, |
| 1396 | }; |
| 1397 | if backtrack { |
| 1398 | engine.try_send(rewind)?; |
| 1399 | } else { |
| 1400 | engine.send(rewind).await?; |
| 1401 | } |
| 1402 | // This receipt comes from the same Engine operation that compares and |
| 1403 | // installs history. A queued update between preflight and rewind refuses. |
| 1404 | let installed = receive.await?.ok_or_else(|| { |
| 1405 | anyhow::anyhow!( |
| 1406 | app.tr(MessageId::ConversationChangedBeforeUndo) |
| 1407 | .into_owned() |
| 1408 | ) |
| 1409 | })?; |
| 1410 | anyhow::ensure!( |
| 1411 | installed.session_id == id |
| 1412 | && installed.messages == expected |
| 1413 | && installed.source.as_ref() |
| 1414 | == Some( |
| 1415 | &codewhale_engine::core::ops::SessionSnapshotSource::control(control.clone()) |
| 1416 | ), |
| 1417 | "the Engine did not acknowledge the conversation rollback" |
| 1418 | ); |
| 1419 | if let Some(depth) = backtrack_depth { |
| 1420 | apply_backtrack(app, depth); |
| 1421 | } else { |
| 1422 | while !app.history.is_empty() { |
| 1423 | let last_is_user = matches!(app.history.last(), Some(HistoryCell::User { .. })); |
| 1424 | app.pop_history(); |
| 1425 | if last_is_user { |
| 1426 | break; |
| 1427 | } |
| 1428 | } |
| 1429 | } |
| 1430 | app.session_write_owner = |
| 1431 | Some(codewhale_engine::session_manager::SessionWriteOwner::Control(control)); |
| 1432 | app.session_write_receipt = captured_source; |
| 1433 | let previous_had_messages = !app.api_messages.is_empty(); |
| 1434 | let has_journal_entries = !app.session_journal.entries.is_empty(); |
| 1435 | let rollback_empty = installed.messages.is_empty(); |
| 1436 | let exact = app.set_api_messages(Arc::new(installed.messages)); |
| 1437 | if previous_had_messages || has_journal_entries { |
| 1438 | if rollback_empty { |
| 1439 | app.window_reroot_cause = Some("rollback_to_empty"); |
| 1440 | } else if exact == 0 { |
| 1441 | app.window_reroot_cause = Some("rollback"); |
| 1442 | } |
| 1443 | } |
| 1444 | maybe_warn_context_pressure(app); |
| 1445 | app.set_current_session_id(Some(id)); |
| 1446 | app.tool_cells.clear(); |
| 1447 | app.tool_details_by_cell.clear(); |
| 1448 | app.exploring_entries.clear(); |
| 1449 | app.ignored_tool_calls.clear(); |
| 1450 | app.mark_history_updated(); |
| 1451 | let persistence = async { |
| 1452 | #[cfg(test)] |
| 1453 | let env_scope = crate::test_support::env_scope_ticket(); |
| 1454 | let manager = tokio::task::spawn_blocking(move || { |
| 1455 | #[cfg(test)] |
| 1456 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 1457 | SessionManager::default_location() |
| 1458 | }) |
| 1459 | .await??; |
| 1460 | let session = build_session_snapshot(app, &manager).map_err(anyhow::Error::msg)?; |
| 1461 | let projection = saved_work_projection(app, &session); |
| 1462 | anyhow::ensure!( |
| 1463 | super::session_state::try_persist_session( |
| 1464 | app, |
| 1465 | PersistRequest::CompletedCommit { session } |
| 1466 | ), |
| 1467 | "the session persistence worker is unavailable" |
| 1468 | ); |
| 1469 | let (reply, receive) = tokio::sync::oneshot::channel(); |
| 1470 | anyhow::ensure!( |
| 1471 | persistence_actor::try_persist(PersistRequest::FlushAndReport { reply }), |
| 1472 | "could not request the session save receipt" |
| 1473 | ); |
| 1474 | let report = receive.await?; |
| 1475 | anyhow::ensure!( |
| 1476 | report.failures.is_empty(), |
| 1477 | "the session save failed: {:?}", |
| 1478 | report.failures |
| 1479 | ); |
| 1480 | publish_saved_work_projection(app, &projection) |
| 1481 | .await |
| 1482 | .map_err(anyhow::Error::msg)?; |
| 1483 | Ok::<(), anyhow::Error>(()) |
| 1484 | } |
| 1485 | .await; |
| 1486 | Ok(persistence.err()) |
| 1487 | } |
| 1488 | |
| 1489 | pub(super) async fn apply_range_undo( |
| 1490 | terminal: &mut AppTerminal, |
| 1491 | app: &mut App, |
| 1492 | engine: &EngineHandle, |
| 1493 | config: &Config, |
| 1494 | depth: usize, |
| 1495 | ) -> Result<()> { |
| 1496 | anyhow::ensure!( |
| 1497 | !app.is_loading |
| 1498 | && !app.is_compacting |
| 1499 | && !app.dispatch_in_flight |
| 1500 | && !app.remote_control.runtime_chat_blocks_local_dispatch(), |
| 1501 | "Wait for all active work in this workspace to finish; nothing was undone." |
| 1502 | ); |
| 1503 | let restore_guard = app |
| 1504 | .remote_control |
| 1505 | .workspace_restore_guard(&app.workspace) |
| 1506 | .await |
| 1507 | .map_err(anyhow::Error::msg)?; |
| 1508 | anyhow::ensure!( |
| 1509 | engine.get_subagent_settlement().await?.is_settled(), |
| 1510 | "Wait for delegated work to settle; nothing was undone." |
| 1511 | ); |
| 1512 | anyhow::ensure!( |
| 1513 | app.goal.objective.is_none() |
| 1514 | || app.goal.status != codewhale_engine::tools::goal::GoalStatus::Active, |
| 1515 | "Pause the active goal before undoing workspace files; nothing was undone." |
| 1516 | ); |
| 1517 | if let Some(shells) = app.runtime_services.shell_manager.clone() { |
| 1518 | let session_id = app.current_session_id.clone().unwrap_or_default(); |
| 1519 | let running = tokio::task::spawn_blocking(move || { |
| 1520 | shells |
| 1521 | .lock() |
| 1522 | .map(|mut manager| { |
| 1523 | let running = manager.list_jobs().iter().any(|job| { |
| 1524 | job.status == codewhale_engine::tools::shell::ShellStatus::Running |
| 1525 | }); |
| 1526 | running || manager.may_have_undelivered_completion_for_session(&session_id) |
| 1527 | }) |
| 1528 | .map_err(|_| anyhow::anyhow!("Shell tracking is unavailable; nothing was undone.")) |
| 1529 | }) |
| 1530 | .await??; |
| 1531 | anyhow::ensure!( |
| 1532 | !running, |
| 1533 | "Wait for background shell work and pending completion receipts to settle before undoing files; nothing was undone." |
| 1534 | ); |
| 1535 | } |
| 1536 | let cut = backtrack_api_cut_index(app, depth).ok_or_else(|| { |
| 1537 | anyhow::anyhow!( |
| 1538 | "The selected request no longer matches the conversation; nothing was undone." |
| 1539 | ) |
| 1540 | })?; |
| 1541 | let before = engine.get_session_snapshot().await?; |
| 1542 | anyhow::ensure!( |
| 1543 | before.messages == *app.api_messages |
| 1544 | && before.workspace == app.workspace |
| 1545 | && before.model == app.model |
| 1546 | && before.mode == app.mode.as_setting() |
| 1547 | && codewhale_engine::compaction::strip_compaction_summaries( |
| 1548 | before.system_prompt.as_ref() |
| 1549 | ) == codewhale_engine::compaction::strip_compaction_summaries( |
| 1550 | app.system_prompt.as_ref() |
| 1551 | ) |
| 1552 | && app.current_session_id.as_deref() == Some(before.session_id.as_str()), |
| 1553 | "The conversation changed before undo; nothing was undone." |
| 1554 | ); |
| 1555 | if app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) { |
| 1556 | app.view_stack.pop(); |
| 1557 | } |
| 1558 | let progress = format!("Checking restore points for {} requests…", depth + 1); |
| 1559 | |
| 1560 | app.push_status_toast_record( |
| 1561 | StatusToast::new(progress, StatusToastLevel::Info, Some(4_000)).for_command_receipt(), |
| 1562 | ); |
| 1563 | draw_app_frame_inner(terminal, app, config, FrameRepaint::Diff)?; |
| 1564 | let input = commands::undo_range_input(app, cut)?; |
| 1565 | #[cfg(test)] |
| 1566 | let env_scope = crate::test_support::env_scope_ticket(); |
| 1567 | let plan = tokio::task::spawn_blocking(move || { |
| 1568 | #[cfg(test)] |
| 1569 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 1570 | commands::plan_undo_range(input) |
| 1571 | }) |
| 1572 | .await??; |
| 1573 | let undone_turn_seqs = plan.undone_turn_seqs.clone(); |
| 1574 | anyhow::ensure!( |
| 1575 | engine.get_session_snapshot().await? == before, |
| 1576 | "The conversation changed during undo preparation; nothing was undone." |
| 1577 | ); |
| 1578 | let progress = format!("Restoring workspace files for {} requests…", depth + 1); |
| 1579 | |
| 1580 | app.push_status_toast_record( |
| 1581 | StatusToast::new(progress, StatusToastLevel::Info, Some(4_000)).for_command_receipt(), |
| 1582 | ); |
| 1583 | draw_app_frame_inner(terminal, app, config, FrameRepaint::Diff)?; |
| 1584 | #[cfg(test)] |
| 1585 | let env_scope = crate::test_support::env_scope_ticket(); |
| 1586 | let (restored, _restore_guard) = tokio::task::spawn_blocking(move || { |
| 1587 | #[cfg(test)] |
| 1588 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 1589 | (commands::restore_undo_range(plan), restore_guard) |
| 1590 | }) |
| 1591 | .await?; |
| 1592 | let summary = restored?; |
| 1593 | let removed_delegated_writes: Vec<((String, u64), std::collections::BTreeSet<String>)> = |
| 1594 | if let Some(session_id) = app.current_session_id.as_deref() { |
| 1595 | undone_turn_seqs |
| 1596 | .iter() |
| 1597 | .filter_map(|seq| { |
| 1598 | let key = (session_id.to_string(), *seq); |
| 1599 | app.delegated_writes.remove(&key).map(|paths| (key, paths)) |
| 1600 | }) |
| 1601 | .collect() |
| 1602 | } else { |
| 1603 | Vec::new() |
| 1604 | }; |
| 1605 | let progress = format!("Saving conversation rewind for {} requests…", depth + 1); |
| 1606 | |
| 1607 | app.push_status_toast_record( |
| 1608 | StatusToast::new(progress, StatusToastLevel::Info, Some(4_000)).for_command_receipt(), |
| 1609 | ); |
| 1610 | let _ = draw_app_frame_inner(terminal, app, config, FrameRepaint::Diff); |
| 1611 | match apply_conversation_undo(app, engine, ConversationRewind::FileRange(depth)).await { |
| 1612 | Ok(None) => { |
| 1613 | let message = format!("Undid {} request(s). {summary}", depth + 1); |
| 1614 | app.add_message(HistoryCell::System { |
| 1615 | content: message.clone(), |
| 1616 | }); |
| 1617 | |
| 1618 | app.push_status_toast_record( |
| 1619 | StatusToast::new(message, StatusToastLevel::Success, Some(4_000)) |
| 1620 | .for_command_receipt(), |
| 1621 | ); |
| 1622 | app.needs_redraw = true; |
| 1623 | Ok(()) |
| 1624 | } |
| 1625 | Ok(Some(error)) => anyhow::bail!( |
| 1626 | "{summary} Conversation rewound, but could not be saved: {error:#}. The pre-restore safety snapshot retains the former workspace files." |
| 1627 | ), |
| 1628 | Err(error) => { |
| 1629 | app.delegated_writes.extend(removed_delegated_writes); |
| 1630 | anyhow::bail!( |
| 1631 | "{summary} Conversation rewind failed: {error:#}. The original conversation and pre-restore safety snapshot retain recovery evidence." |
| 1632 | ) |
| 1633 | } |
| 1634 | } |
| 1635 | } |
| 1636 | |
| 1637 | // The event loop awaits this dispatcher at several call sites. In debug |
| 1638 | // builds, embedding its entire state machine at each site gives the caller |
| 1639 | // separate large stack slots even though only one action runs at a time. |
| 1640 | // Construct it here so callers carry one pointer, as modal dispatch already does. |
| 1641 | pub(crate) fn apply_command_result<'a>( |
| 1642 | terminal: &'a mut AppTerminal, |
| 1643 | app: &'a mut App, |
| 1644 | engine_handle: &'a mut EngineHandle, |
| 1645 | config: &'a mut Config, |
| 1646 | result: commands::CommandResult, |
| 1647 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + 'a>> { |
| 1648 | Box::pin(async move { |
| 1649 | let outcome = |
| 1650 | apply_command_result_inner(terminal, app, engine_handle, config, result).await; |
| 1651 | // A save the command made may have moved legacy top-level `base_url` / |
| 1652 | // `api_key` into their provider tables (#6394); say so once. |
| 1653 | for notice in codewhale_config::legacy_root::take_notices() { |
| 1654 | app.push_status_toast(notice, StatusToastLevel::Info, Some(10_000)); |
| 1655 | } |
| 1656 | outcome |
| 1657 | }) |
| 1658 | } |
| 1659 | |
| 1660 | async fn apply_command_result_inner( |
| 1661 | terminal: &mut AppTerminal, |
| 1662 | app: &mut App, |
| 1663 | engine_handle: &mut EngineHandle, |
| 1664 | config: &mut Config, |
| 1665 | result: commands::CommandResult, |
| 1666 | ) -> Result<bool> { |
| 1667 | // Read the slot for this dispatch. Only the task actions below consume it, |
| 1668 | // and they each report their own failure, so a host between managers |
| 1669 | // (`None`) must not swallow an unrelated command such as `/quit`. A switch |
| 1670 | // cannot land between these reads and their use: the dispatcher owns the |
| 1671 | // command result being applied. |
| 1672 | let task_manager = app.task_manager(); |
| 1673 | if app.pending_fresh_session.is_some() |
| 1674 | && !matches!( |
| 1675 | result.action.as_ref(), |
| 1676 | None | Some( |
| 1677 | AppAction::Quit |
| 1678 | | AppAction::CancelSubAgent { .. } |
| 1679 | | AppAction::TaskCancel { .. } |
| 1680 | | AppAction::ShellJob( |
| 1681 | crate::tui::app::ShellJobAction::Cancel { .. } |
| 1682 | | crate::tui::app::ShellJobAction::CancelAll |
| 1683 | ) |
| 1684 | | AppAction::RemoteControl( |
| 1685 | codewhale_app_server::remote_control::RemoteControlAction::Stop |
| 1686 | ) |
| 1687 | | AppAction::Automation(crate::tui::app::AutomationAction::Pause(_)) |
| 1688 | | AppAction::SetGoalStatus { |
| 1689 | status: GoalStatus::Paused, |
| 1690 | clear: false, |
| 1691 | } |
| 1692 | | AppAction::SetAdvisorEnabled { enabled: false } |
| 1693 | ) |
| 1694 | ) |
| 1695 | { |
| 1696 | app.show_command_result("A new session is awaiting Engine confirmation; the current draft and transcript are preserved.".to_string(), StatusToastLevel::Warning); |
| 1697 | return Ok(false); |
| 1698 | } |
| 1699 | // These two actions await participant inference inline on the UI event |
| 1700 | // loop. Waiting behind Runtime Chat's exclusive writer here would |
| 1701 | // deadlock: this same loop must drain the terminal projection/server |
| 1702 | // cursor that releases the writer. Fail closed before displaying the |
| 1703 | // command's optimistic message or invoking recorder/provider code. |
| 1704 | if reject_inline_inference_while_runtime_chat_owns_run(app, &result) { |
| 1705 | return Ok(false); |
| 1706 | } |
| 1707 | let conversation_message = matches!(result.action, Some(AppAction::ConversationUndo { .. })) |
| 1708 | .then(|| result.message.clone()) |
| 1709 | .flatten(); |
| 1710 | if let Some(msg) = result.message |
| 1711 | && !matches!( |
| 1712 | result.action, |
| 1713 | Some(AppAction::OpenCommandReview { .. } | AppAction::ConversationUndo { .. }) |
| 1714 | ) |
| 1715 | { |
| 1716 | app.add_message(HistoryCell::System { content: msg }); |
| 1717 | } |
| 1718 | |
| 1719 | if let Some(action) = result.action { |
| 1720 | match action { |
| 1721 | AppAction::Quit => { |
| 1722 | let _ = engine_handle.send(Op::Shutdown).await; |
| 1723 | return Ok(true); |
| 1724 | } |
| 1725 | AppAction::LoadSession(path) => { |
| 1726 | // Session files can be large; this is the UI action path, so |
| 1727 | // the read must not park a Tokio worker (blocking-call |
| 1728 | // convention, #6149). |
| 1729 | use crate::commands::contract::MAX_LOAD_SESSION_BYTES; |
| 1730 | let read = async { |
| 1731 | let len = tokio::fs::metadata(&path) |
| 1732 | .await |
| 1733 | .map_err(|err| err.to_string())? |
| 1734 | .len(); |
| 1735 | if len > MAX_LOAD_SESSION_BYTES { |
| 1736 | return Err(format!( |
| 1737 | "session file is {len} bytes, over the {MAX_LOAD_SESSION_BYTES}-byte load limit" |
| 1738 | )); |
| 1739 | } |
| 1740 | let mut raw = String::new(); |
| 1741 | tokio::io::AsyncReadExt::read_to_string( |
| 1742 | &mut tokio::io::AsyncReadExt::take( |
| 1743 | tokio::fs::File::open(&path) |
| 1744 | .await |
| 1745 | .map_err(|err| err.to_string())?, |
| 1746 | MAX_LOAD_SESSION_BYTES + 1, |
| 1747 | ), |
| 1748 | &mut raw, |
| 1749 | ) |
| 1750 | .await |
| 1751 | .map_err(|err| err.to_string())?; |
| 1752 | if raw.len() as u64 > MAX_LOAD_SESSION_BYTES { |
| 1753 | return Err(format!( |
| 1754 | "session file is over the {MAX_LOAD_SESSION_BYTES}-byte load limit" |
| 1755 | )); |
| 1756 | } |
| 1757 | serde_json::from_str::<SavedSession>(&raw).map_err(|err| err.to_string()) |
| 1758 | }; |
| 1759 | let parsed: SavedSession = match read.await { |
| 1760 | Ok(session) => session, |
| 1761 | Err(err) => { |
| 1762 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1763 | app, |
| 1764 | format!("Failed to load session from {}: {err}", path.display()), |
| 1765 | ); |
| 1766 | return Ok(false); |
| 1767 | } |
| 1768 | }; |
| 1769 | // `/load` shares the attach contract of `resume` and the |
| 1770 | // picker (`SessionManager::attach_session_file`); the lease is |
| 1771 | // committed only once the session is applied. |
| 1772 | let attached = SessionManager::default_location() |
| 1773 | .and_then(|manager| manager.attach_session_file(parsed, &path)); |
| 1774 | let (session, lease) = match attached { |
| 1775 | Ok(attached) => attached, |
| 1776 | Err(err) => { |
| 1777 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1778 | app, |
| 1779 | format!("Failed to resume session {}: {err}", path.display()), |
| 1780 | ); |
| 1781 | return Ok(false); |
| 1782 | } |
| 1783 | }; |
| 1784 | let fresh_config = match codewhale_plugins::providers::load_config( |
| 1785 | app.config_path.clone(), |
| 1786 | app.config_profile.as_deref(), |
| 1787 | ) { |
| 1788 | Ok(config) => config, |
| 1789 | Err(err) => { |
| 1790 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1791 | app, |
| 1792 | format!("Failed to load live config for session restore: {err}"), |
| 1793 | ); |
| 1794 | return Ok(false); |
| 1795 | } |
| 1796 | }; |
| 1797 | let resumed_id = session.metadata.id.clone(); |
| 1798 | let title = codewhale_engine::session_manager::sanitize_session_title( |
| 1799 | &session.metadata.title, |
| 1800 | ); |
| 1801 | codewhale_engine::runtime_threads::prepare_canonical_sessions_root().await; |
| 1802 | // Adoption happens inside the load call, as preflight: a |
| 1803 | // refusal or a failed open returns here with the live session |
| 1804 | // still installed, so a failure is reported and nothing else |
| 1805 | // runs. |
| 1806 | let outcome = match apply_loaded_session_config_snapshot( |
| 1807 | app, |
| 1808 | config, |
| 1809 | session, |
| 1810 | fresh_config, |
| 1811 | true, |
| 1812 | ) |
| 1813 | .await |
| 1814 | { |
| 1815 | Ok(outcome) => { |
| 1816 | lease.commit(); |
| 1817 | outcome |
| 1818 | } |
| 1819 | Err(err) => { |
| 1820 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1821 | app, |
| 1822 | format!("Failed to restore session: {err}"), |
| 1823 | ); |
| 1824 | return Ok(false); |
| 1825 | } |
| 1826 | }; |
| 1827 | let respawn = outcome.respawn; |
| 1828 | sync_runtime_workspace_state(app, app.workspace.clone()).await; |
| 1829 | if respawn { |
| 1830 | replace_tui_engine(app, config, engine_handle).await; |
| 1831 | } else { |
| 1832 | let _ = engine_handle |
| 1833 | .send(Op::SetModel { |
| 1834 | model: app.model.clone(), |
| 1835 | mode: app.mode, |
| 1836 | route_limits: app.active_route_limits, |
| 1837 | }) |
| 1838 | .await; |
| 1839 | } |
| 1840 | let _ = engine_handle |
| 1841 | .send(Op::SyncSession { |
| 1842 | expected: None, |
| 1843 | control: app.session_sync_control(), |
| 1844 | session_id: app.current_session_id.clone(), |
| 1845 | messages: app.api_messages.as_ref().clone(), |
| 1846 | system_prompt: app.system_prompt.clone(), |
| 1847 | system_prompt_override: false, |
| 1848 | model: app.model.clone(), |
| 1849 | workspace: app.workspace.clone(), |
| 1850 | mode: app.mode, |
| 1851 | agent_preset: app.agent_preset(), |
| 1852 | }) |
| 1853 | .await; |
| 1854 | let _ = engine_handle |
| 1855 | .send(Op::SetCompaction { |
| 1856 | config: app.compaction_config(), |
| 1857 | }) |
| 1858 | .await; |
| 1859 | let _ = engine_handle.try_send(Op::ListSubAgents); |
| 1860 | app.push_status_toast_record( |
| 1861 | StatusToast::new( |
| 1862 | app.tr(MessageId::SessionsResumed) |
| 1863 | .replace("{title}", &title), |
| 1864 | StatusToastLevel::Success, |
| 1865 | Some(4_000), |
| 1866 | ) |
| 1867 | .for_event(format!("session-resumed:{resumed_id}")), |
| 1868 | ); |
| 1869 | // A loaded session is the working screen. The launch card's |
| 1870 | // recent rows reach here through `/resume`-shaped dispatch; |
| 1871 | // leaving the launch stage visible over the restored |
| 1872 | // transcript is what made those rows read as dead (#4). |
| 1873 | app.launch.dismiss(); |
| 1874 | app.launch.status = None; |
| 1875 | } |
| 1876 | AppAction::NewSession { sync, force, draft } => { |
| 1877 | if let Err(error) = begin_fresh_session(app, engine_handle, sync, force, draft) { |
| 1878 | surface_session_load_failure(app, error); |
| 1879 | } |
| 1880 | } |
| 1881 | AppAction::SyncSession { |
| 1882 | session_id, |
| 1883 | messages, |
| 1884 | system_prompt, |
| 1885 | model, |
| 1886 | workspace, |
| 1887 | mode, |
| 1888 | agent_preset, |
| 1889 | } => { |
| 1890 | let mut session_id = session_id; |
| 1891 | let is_full_reset = messages.is_empty() && system_prompt.is_none(); |
| 1892 | if is_full_reset && session_id.is_none() { |
| 1893 | let new_session_id = uuid::Uuid::new_v4().to_string(); |
| 1894 | session_id = Some(new_session_id); |
| 1895 | } |
| 1896 | if let Some(session_id) = session_id.as_deref() { |
| 1897 | let transition = match prepare_offline_queue_transition(app, session_id) { |
| 1898 | Ok(transition) => transition, |
| 1899 | Err(error) => { |
| 1900 | app.push_status_toast(error, StatusToastLevel::Error, Some(6_000)); |
| 1901 | return Ok(false); |
| 1902 | } |
| 1903 | }; |
| 1904 | install_offline_queue_transition(app, transition); |
| 1905 | } |
| 1906 | let workspace_changed = match task_manager.as_ref() { |
| 1907 | Some(manager) => manager.default_workspace().await != workspace, |
| 1908 | None => true, |
| 1909 | }; |
| 1910 | if workspace_changed { |
| 1911 | apply_workspace_runtime_state(app, config, workspace.clone()); |
| 1912 | sync_runtime_workspace_state(app, workspace.clone()).await; |
| 1913 | } |
| 1914 | let identity = |
| 1915 | match app |
| 1916 | .admitted_provider_identity() |
| 1917 | .cloned() |
| 1918 | .and_then(|identity| { |
| 1919 | config.verify_provider_identity(&identity)?; |
| 1920 | Ok(identity) |
| 1921 | }) { |
| 1922 | Ok(identity) => identity, |
| 1923 | Err(reason) => { |
| 1924 | app.show_command_result( |
| 1925 | format!("Failed to restore saved session provider: {reason}"), |
| 1926 | StatusToastLevel::Error, |
| 1927 | ); |
| 1928 | return Ok(false); |
| 1929 | } |
| 1930 | }; |
| 1931 | let provider_changed = |
| 1932 | config.active_provider_identity().as_ref().ok() != Some(&identity); |
| 1933 | if provider_changed { |
| 1934 | restore_loaded_session_provider(app, config, identity.clone()) |
| 1935 | .map_err(anyhow::Error::msg)?; |
| 1936 | config.set_provider_model_override(&identity, Some(model.clone()))?; |
| 1937 | let prepared = config |
| 1938 | .active_provider_identity() |
| 1939 | .map_err(anyhow::Error::msg)?; |
| 1940 | app.set_provider_identity_record(prepared); |
| 1941 | } |
| 1942 | // Re-resolve from the live config even when the provider did |
| 1943 | // not change. The command layer intentionally has no Config |
| 1944 | // handle, so its provisional limits cannot include current |
| 1945 | // provider overrides. |
| 1946 | resolve_loaded_session_route(app, config); |
| 1947 | app.update_model_compaction_budget(); |
| 1948 | if provider_changed || workspace_changed { |
| 1949 | replace_tui_engine(app, config, engine_handle).await; |
| 1950 | } |
| 1951 | // SyncSession carries the conversation but not resolved route |
| 1952 | // limits. Refresh the engine's model first so a loaded, |
| 1953 | // forked, or freshly reset session cannot retain the previous |
| 1954 | // route's context/output facts. |
| 1955 | let _ = engine_handle |
| 1956 | .send(Op::SetModel { |
| 1957 | model: model.clone(), |
| 1958 | mode, |
| 1959 | route_limits: app.active_route_limits, |
| 1960 | }) |
| 1961 | .await; |
| 1962 | let _ = engine_handle |
| 1963 | .send(Op::SyncSession { |
| 1964 | expected: None, |
| 1965 | control: app.session_sync_control(), |
| 1966 | session_id, |
| 1967 | messages, |
| 1968 | system_prompt, |
| 1969 | system_prompt_override: false, |
| 1970 | model, |
| 1971 | workspace, |
| 1972 | mode, |
| 1973 | agent_preset, |
| 1974 | }) |
| 1975 | .await; |
| 1976 | let _ = engine_handle |
| 1977 | .send(Op::SetCompaction { |
| 1978 | config: app.compaction_config(), |
| 1979 | }) |
| 1980 | .await; |
| 1981 | let _ = engine_handle.try_send(Op::ListSubAgents); |
| 1982 | if is_full_reset { |
| 1983 | persist_full_reset_snapshot(app); |
| 1984 | } |
| 1985 | } |
| 1986 | AppAction::SetWorkspaceTrust { trusted, save } => { |
| 1987 | let result = crate::commands::set_workspace_trust(app, trusted, save).await; |
| 1988 | sync_mode_update(app, engine_handle).await; |
| 1989 | match result { |
| 1990 | Ok(()) => { |
| 1991 | app.push_status_toast( |
| 1992 | format!( |
| 1993 | "/trust: {} ({})", |
| 1994 | tr( |
| 1995 | app.ui_locale, |
| 1996 | if trusted { |
| 1997 | MessageId::ConfigValueOn |
| 1998 | } else { |
| 1999 | MessageId::ConfigValueOff |
| 2000 | } |
| 2001 | ), |
| 2002 | tr( |
| 2003 | app.ui_locale, |
| 2004 | if save { |
| 2005 | MessageId::ConfigScopeSaved |
| 2006 | } else { |
| 2007 | MessageId::ConfigScopeSession |
| 2008 | } |
| 2009 | ), |
| 2010 | ), |
| 2011 | StatusToastLevel::Info, |
| 2012 | None, |
| 2013 | ); |
| 2014 | // The toast fades and the footer does not show trust |
| 2015 | // mode: leave a line that says what changed. |
| 2016 | app.add_message(HistoryCell::System { |
| 2017 | content: crate::commands::trust_change_note(trusted, save), |
| 2018 | }); |
| 2019 | } |
| 2020 | Err(error) => app.push_status_toast( |
| 2021 | tr(app.ui_locale, MessageId::AutomationEditorSaveFailed) |
| 2022 | .replace("{error}", &format!("/trust: {error:#}")), |
| 2023 | StatusToastLevel::Error, |
| 2024 | None, |
| 2025 | ), |
| 2026 | } |
| 2027 | } |
| 2028 | AppAction::ModeChanged(_mode) => { |
| 2029 | sync_mode_update(app, engine_handle).await; |
| 2030 | } |
| 2031 | AppAction::ApprovalPolicyPersisted { policy } => { |
| 2032 | config.approval_policy = policy; |
| 2033 | sync_mode_update(app, engine_handle).await; |
| 2034 | } |
| 2035 | AppAction::PermissionRulesChanged => { |
| 2036 | match codewhale_config::load_permissions_snapshot(app.config_path.clone()) { |
| 2037 | Ok(snapshot) => { |
| 2038 | let ruleset = snapshot.permissions().ruleset(); |
| 2039 | // Config and every running EngineConfig share this |
| 2040 | // policy store. Publish once: replaying an older Op |
| 2041 | // after a later edit would roll the live policy back. |
| 2042 | config.exec_policy_engine.set_ruleset(ruleset); |
| 2043 | } |
| 2044 | Err(error) => { |
| 2045 | app.show_command_result( |
| 2046 | tr(app.ui_locale, MessageId::PermissionsOperationFailed) |
| 2047 | .replace("{error}", &format!("{error:#}")), |
| 2048 | StatusToastLevel::Error, |
| 2049 | ); |
| 2050 | } |
| 2051 | } |
| 2052 | } |
| 2053 | AppAction::ApproveAutoReviewRetry { target } => { |
| 2054 | apply_approve_auto_review_retry(app, engine_handle, &target); |
| 2055 | } |
| 2056 | AppAction::PluginRegistryChanged => { |
| 2057 | // Revoke a disabled or untrusted plugin's host code now, not at |
| 2058 | // the next turn's rebuild. |
| 2059 | codewhale_engine::extension_host::plugins_changed(std::sync::Arc::clone( |
| 2060 | &app.plugin_registry, |
| 2061 | )); |
| 2062 | let command_errors = crate::commands::user_registry::install_plugin_registry( |
| 2063 | &app.workspace, |
| 2064 | app.plugin_registry.as_ref(), |
| 2065 | ); |
| 2066 | app.hooks = app.hooks.rebind( |
| 2067 | codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 2068 | config.hooks_config(), |
| 2069 | &app.workspace, |
| 2070 | Some(app.plugin_registry.as_ref()), |
| 2071 | ), |
| 2072 | app.workspace.clone(), |
| 2073 | ); |
| 2074 | app.runtime_services.hook_executor = Some(std::sync::Arc::new(app.hooks.clone())); |
| 2075 | if !command_errors.is_empty() { |
| 2076 | app.set_sticky_status( |
| 2077 | format!( |
| 2078 | "Plugin runtime activation failed: {}", |
| 2079 | command_errors.join("; ") |
| 2080 | ), |
| 2081 | StatusToastLevel::Error, |
| 2082 | None, |
| 2083 | ); |
| 2084 | } |
| 2085 | replace_tui_engine(app, config, engine_handle).await; |
| 2086 | if !app.api_messages.is_empty() { |
| 2087 | let _ = engine_handle |
| 2088 | .send(Op::SyncSession { |
| 2089 | expected: None, |
| 2090 | control: app.session_sync_control(), |
| 2091 | session_id: app.current_session_id.clone(), |
| 2092 | messages: app.api_messages.as_ref().clone(), |
| 2093 | system_prompt: app.system_prompt.clone(), |
| 2094 | system_prompt_override: false, |
| 2095 | model: app.model.clone(), |
| 2096 | workspace: app.workspace.clone(), |
| 2097 | mode: app.mode, |
| 2098 | agent_preset: app.agent_preset(), |
| 2099 | }) |
| 2100 | .await; |
| 2101 | } |
| 2102 | } |
| 2103 | AppAction::ConversationUndo { |
| 2104 | sync, |
| 2105 | restored_files, |
| 2106 | retry_input, |
| 2107 | edit_replacement, |
| 2108 | } => { |
| 2109 | let persistence_error = match apply_conversation_undo( |
| 2110 | app, |
| 2111 | engine_handle, |
| 2112 | ConversationRewind::Command(sync), |
| 2113 | ) |
| 2114 | .await |
| 2115 | { |
| 2116 | Ok(error) => error, |
| 2117 | Err(error) => { |
| 2118 | // A refused `/edit` rollback has already consumed the |
| 2119 | // revision from the composer: hand it back, with edit mode |
| 2120 | // re-armed, so the user can retry instead of retyping. |
| 2121 | if edit_replacement && let Some(content) = retry_input { |
| 2122 | let restored = build_queued_message(app, content); |
| 2123 | restore_failed_immediate_submit(app, restored, &error); |
| 2124 | app.edit_in_progress = true; |
| 2125 | } |
| 2126 | let message = if restored_files > 0 { |
| 2127 | format!( |
| 2128 | "Restored {restored_files} file changes. Conversation rollback failed: {error:#}" |
| 2129 | ) |
| 2130 | } else { |
| 2131 | format!("Conversation rollback failed; retry was not sent: {error:#}") |
| 2132 | }; |
| 2133 | app.push_status_toast(message, StatusToastLevel::Error, None); |
| 2134 | return Ok(false); |
| 2135 | } |
| 2136 | }; |
| 2137 | if let Some(error) = persistence_error { |
| 2138 | let mut retry_note = ""; |
| 2139 | let mut recovery = ""; |
| 2140 | if let Some(message) = conversation_message { |
| 2141 | app.add_message(HistoryCell::System { content: message }); |
| 2142 | } |
| 2143 | if let Some(content) = retry_input { |
| 2144 | retry_note = "; retry was not sent"; |
| 2145 | if edit_replacement { |
| 2146 | let restored = build_queued_message(app, content); |
| 2147 | restore_failed_immediate_submit(app, restored, &error); |
| 2148 | app.edit_in_progress = false; |
| 2149 | recovery = " The replacement is in the composer."; |
| 2150 | } else { |
| 2151 | app.add_message(HistoryCell::System { |
| 2152 | content: format!("Retry prompt was not sent. Copy it from here to retry:\n{content}"), |
| 2153 | }); |
| 2154 | recovery = " The retry prompt is in the conversation above; copy it before leaving this session."; |
| 2155 | } |
| 2156 | } |
| 2157 | app.push_status_toast( |
| 2158 | format!("Conversation was rewound, but its save or Work update needs attention{retry_note}: {error:#}.{recovery}"), |
| 2159 | StatusToastLevel::Error, |
| 2160 | None, |
| 2161 | ); |
| 2162 | return Ok(false); |
| 2163 | } |
| 2164 | if let Some(message) = conversation_message { |
| 2165 | app.add_message(HistoryCell::System { content: message }); |
| 2166 | } |
| 2167 | if let Some(content) = retry_input { |
| 2168 | let queued = build_queued_message(app, content); |
| 2169 | // The rollback required an idle app, so this always resolves to an |
| 2170 | // immediate send; the disposition is kept for parity with `SendMessage`. |
| 2171 | dispatch_composer_message( |
| 2172 | app, |
| 2173 | config, |
| 2174 | engine_handle, |
| 2175 | queued, |
| 2176 | DispatchRecovery::Immediate, |
| 2177 | ComposerSubmitAction::Submit(app.decide_submit_disposition()), |
| 2178 | ) |
| 2179 | .await?; |
| 2180 | } |
| 2181 | } |
| 2182 | AppAction::RunExtensionCommand { |
| 2183 | command, |
| 2184 | name, |
| 2185 | input, |
| 2186 | } => { |
| 2187 | use codewhale_engine::extension_host::command::CommandOutcome; |
| 2188 | // The origin labels the output: it is the plugin's text, not |
| 2189 | // Codewhale's. |
| 2190 | let origin = command.origin.clone(); |
| 2191 | app.replace_progress_notice( |
| 2192 | StatusToastKind::ExtensionCommand, |
| 2193 | format!("Running /{name} ({origin})..."), |
| 2194 | ); |
| 2195 | // Awaited here like `/balance`; the call is bounded by its |
| 2196 | // deadline and cancelled in the host when it expires. |
| 2197 | match codewhale_engine::extension_host::run_command_for_plugins( |
| 2198 | &command, |
| 2199 | &input, |
| 2200 | app.current_session_id.as_deref(), |
| 2201 | app.extension_plugin_view().as_ref(), |
| 2202 | ) |
| 2203 | .await |
| 2204 | { |
| 2205 | Ok(CommandOutcome::Show { text }) => { |
| 2206 | app.retire_progress_notice(StatusToastKind::ExtensionCommand); |
| 2207 | if text.trim().is_empty() { |
| 2208 | app.show_command_result( |
| 2209 | format!("/{name} completed"), |
| 2210 | StatusToastLevel::Success, |
| 2211 | ); |
| 2212 | } else { |
| 2213 | app.add_message(HistoryCell::System { |
| 2214 | content: format!("/{name} ({origin})\n{text}"), |
| 2215 | }); |
| 2216 | } |
| 2217 | } |
| 2218 | Ok(CommandOutcome::Submit { prompt, note }) => { |
| 2219 | app.retire_progress_notice(StatusToastKind::ExtensionCommand); |
| 2220 | let mut content = format!("/{name} ({origin}) submitted a prompt"); |
| 2221 | if let Some(note) = note { |
| 2222 | content.push_str(&format!("\n{note}")); |
| 2223 | } |
| 2224 | app.add_message(HistoryCell::System { content }); |
| 2225 | let Some(session_id) = app.current_session_id.clone() else { |
| 2226 | app.add_message(HistoryCell::System { |
| 2227 | content: |
| 2228 | "Plugin command prompt was not submitted: no active session" |
| 2229 | .into(), |
| 2230 | }); |
| 2231 | return Ok(false); |
| 2232 | }; |
| 2233 | let mut queued = QueuedMessage::new(prompt, None); |
| 2234 | queued.extension_command = Some((command, session_id)); |
| 2235 | dispatch_composer_message( |
| 2236 | app, |
| 2237 | config, |
| 2238 | engine_handle, |
| 2239 | queued, |
| 2240 | DispatchRecovery::Immediate, |
| 2241 | ComposerSubmitAction::Submit(app.decide_submit_disposition()), |
| 2242 | ) |
| 2243 | .await?; |
| 2244 | } |
| 2245 | Err(error) => { |
| 2246 | app.retire_progress_notice(StatusToastKind::ExtensionCommand); |
| 2247 | app.add_message(HistoryCell::System { |
| 2248 | content: format!("Error: /{name} ({origin}): {error}"), |
| 2249 | }); |
| 2250 | } |
| 2251 | } |
| 2252 | } |
| 2253 | AppAction::SendMessage(content) => { |
| 2254 | let queued = build_queued_message(app, content); |
| 2255 | dispatch_composer_message( |
| 2256 | app, |
| 2257 | config, |
| 2258 | engine_handle, |
| 2259 | queued, |
| 2260 | DispatchRecovery::Immediate, |
| 2261 | ComposerSubmitAction::Submit(app.decide_submit_disposition()), |
| 2262 | ) |
| 2263 | .await?; |
| 2264 | } |
| 2265 | AppAction::WorkflowInstruction { |
| 2266 | display, |
| 2267 | instruction, |
| 2268 | } => { |
| 2269 | let queued = QueuedMessage::new(display, Some(instruction)); |
| 2270 | dispatch_composer_message( |
| 2271 | app, |
| 2272 | config, |
| 2273 | engine_handle, |
| 2274 | queued, |
| 2275 | DispatchRecovery::Immediate, |
| 2276 | ComposerSubmitAction::Submit(app.decide_submit_disposition()), |
| 2277 | ) |
| 2278 | .await?; |
| 2279 | } |
| 2280 | AppAction::SetGoalStatus { status, clear } => { |
| 2281 | accept_goal_control( |
| 2282 | app, |
| 2283 | engine_handle, |
| 2284 | GoalControlIntent::SetStatus { status, clear }, |
| 2285 | ); |
| 2286 | } |
| 2287 | AppAction::SetGoalObjective { |
| 2288 | objective, |
| 2289 | token_budget, |
| 2290 | } => { |
| 2291 | accept_goal_control( |
| 2292 | app, |
| 2293 | engine_handle, |
| 2294 | GoalControlIntent::SetObjective { |
| 2295 | objective, |
| 2296 | token_budget, |
| 2297 | }, |
| 2298 | ); |
| 2299 | } |
| 2300 | AppAction::OpenTextPager { title, content } => { |
| 2301 | open_text_pager(app, title, content); |
| 2302 | } |
| 2303 | AppAction::OpenDiffPager { title, diff } => { |
| 2304 | open_diff_pager(app, title, &diff); |
| 2305 | app.needs_redraw = true; |
| 2306 | } |
| 2307 | AppAction::OpenCommandReview { |
| 2308 | title, |
| 2309 | content, |
| 2310 | command, |
| 2311 | } => { |
| 2312 | let width = app |
| 2313 | .viewport |
| 2314 | .last_transcript_area |
| 2315 | .map_or(80, |area| area.width); |
| 2316 | app.view_stack |
| 2317 | .push(crate::tui::pager::PagerView::command_review( |
| 2318 | title, |
| 2319 | &content, |
| 2320 | width.saturating_sub(2), |
| 2321 | command, |
| 2322 | app.ui_locale, |
| 2323 | )); |
| 2324 | app.needs_redraw = true; |
| 2325 | } |
| 2326 | AppAction::VoiceCapture => { |
| 2327 | use commands::voice::VoiceCaptureOutcome; |
| 2328 | let result = commands::voice::capture_and_transcribe(app, config).await; |
| 2329 | app.retire_progress_notice(StatusToastKind::VoiceCapture); |
| 2330 | match result { |
| 2331 | Ok(VoiceCaptureOutcome::Insert(text)) => { |
| 2332 | app.insert_str(&text); |
| 2333 | app.show_command_result( |
| 2334 | format!("{}: {text}", tr(app.ui_locale, MessageId::VoiceTranscribed)), |
| 2335 | StatusToastLevel::Info, |
| 2336 | ); |
| 2337 | } |
| 2338 | Ok(VoiceCaptureOutcome::Send(content)) => { |
| 2339 | app.show_command_result( |
| 2340 | tr(app.ui_locale, MessageId::VoiceTranscribed).to_string(), |
| 2341 | StatusToastLevel::Success, |
| 2342 | ); |
| 2343 | let queued = build_queued_message(app, content); |
| 2344 | dispatch_composer_message( |
| 2345 | app, |
| 2346 | config, |
| 2347 | engine_handle, |
| 2348 | queued, |
| 2349 | DispatchRecovery::Immediate, |
| 2350 | ComposerSubmitAction::Submit(app.decide_submit_disposition()), |
| 2351 | ) |
| 2352 | .await?; |
| 2353 | } |
| 2354 | Err(err) => { |
| 2355 | app.voice_enabled = false; |
| 2356 | app.show_command_result(err, StatusToastLevel::Error); |
| 2357 | } |
| 2358 | } |
| 2359 | } |
| 2360 | AppAction::AgentProfiles { arguments } => { |
| 2361 | let result = match crate::agent_profiles::parse_slash(&arguments) { |
| 2362 | Ok(args) => { |
| 2363 | let workspace = app.workspace.clone(); |
| 2364 | let config = config.clone(); |
| 2365 | let plugins = std::sync::Arc::clone(&app.plugin_registry); |
| 2366 | codewhale_runtime::runtime_control::owner_work(move || { |
| 2367 | crate::agent_profiles::run(&workspace, &config, &plugins, args) |
| 2368 | }) |
| 2369 | .await |
| 2370 | } |
| 2371 | Err(error) => Err(error), |
| 2372 | }; |
| 2373 | match result { |
| 2374 | Ok(text) => app.view_stack.push(crate::tui::pager::PagerView::from_text( |
| 2375 | "Agent profiles", |
| 2376 | &text, |
| 2377 | 80, |
| 2378 | )), |
| 2379 | Err(error) => { |
| 2380 | app.show_command_result(error.to_string(), StatusToastLevel::Error) |
| 2381 | } |
| 2382 | } |
| 2383 | } |
| 2384 | AppAction::ListSubAgents => { |
| 2385 | // #3802: non-blocking send — refresh op, safe to drop. |
| 2386 | let _ = engine_handle.try_send(Op::ListSubAgents); |
| 2387 | } |
| 2388 | AppAction::PreviewOutboundRequest { |
| 2389 | json, |
| 2390 | base_prompt_only, |
| 2391 | hypothetical_prompt, |
| 2392 | } => { |
| 2393 | start_request_preview( |
| 2394 | app, |
| 2395 | config, |
| 2396 | engine_handle, |
| 2397 | hypothetical_prompt, |
| 2398 | json, |
| 2399 | base_prompt_only, |
| 2400 | ); |
| 2401 | } |
| 2402 | AppAction::CancelSubAgent { agent_id } => { |
| 2403 | app.show_command_result( |
| 2404 | format!("Cancelling {agent_id}..."), |
| 2405 | StatusToastLevel::Info, |
| 2406 | ); |
| 2407 | if engine_handle |
| 2408 | .try_send(Op::CancelSubAgent { |
| 2409 | agent_id: agent_id.clone(), |
| 2410 | }) |
| 2411 | .is_err() |
| 2412 | { |
| 2413 | app.show_command_result( |
| 2414 | format!("Could not cancel {agent_id}"), |
| 2415 | StatusToastLevel::Error, |
| 2416 | ); |
| 2417 | } |
| 2418 | } |
| 2419 | AppAction::RouterSetup { request } => { |
| 2420 | crate::tui::views::router_setup::handle_router_request(app, config, request).await; |
| 2421 | } |
| 2422 | AppAction::FetchBalance => { |
| 2423 | let provider = app.api_provider; |
| 2424 | if !codewhale_runtime::config::provider_has_balance_api(provider) { |
| 2425 | app.add_message(HistoryCell::System { |
| 2426 | content: format!( |
| 2427 | "Balance check is not supported for {} yet. Check the provider dashboard for account balance details.", |
| 2428 | provider.provider().display_name() |
| 2429 | ), |
| 2430 | }); |
| 2431 | } else { |
| 2432 | let api_key = config.active_route_api_key().unwrap_or_default(); |
| 2433 | if api_key.trim().is_empty() { |
| 2434 | app.add_message(HistoryCell::System { |
| 2435 | content: format!( |
| 2436 | "No API key configured for {}.", |
| 2437 | provider.provider().display_name() |
| 2438 | ), |
| 2439 | }); |
| 2440 | } else { |
| 2441 | let base_url = config.active_route_base_url(); |
| 2442 | match fetch_provider_balance(provider, &api_key, &base_url).await { |
| 2443 | Ok(info) => { |
| 2444 | if let Ok(mut guard) = |
| 2445 | balance_cell_for_route(app, provider, &api_key, &base_url) |
| 2446 | .lock() |
| 2447 | { |
| 2448 | *guard = Some(info.clone()); |
| 2449 | } |
| 2450 | app.last_balance_fetch = Some(Instant::now()); |
| 2451 | app.add_message(HistoryCell::System { |
| 2452 | content: info.report(provider.provider().display_name()), |
| 2453 | }); |
| 2454 | } |
| 2455 | Err(reason) => { |
| 2456 | let fallback = app |
| 2457 | .balance_cell |
| 2458 | .lock() |
| 2459 | .ok() |
| 2460 | .and_then(|guard| guard.clone()) |
| 2461 | .and_then(|info| { |
| 2462 | info.chip_label().map(|amount| { |
| 2463 | format!( |
| 2464 | "Could not refresh {} balance ({reason}); last known: {amount}", |
| 2465 | provider.provider().display_name() |
| 2466 | ) |
| 2467 | }) |
| 2468 | }); |
| 2469 | app.add_message(HistoryCell::System { |
| 2470 | content: fallback.unwrap_or_else(|| { |
| 2471 | format!( |
| 2472 | "Could not fetch {} account balance ({reason}). Check the provider dashboard.", |
| 2473 | provider.provider().display_name() |
| 2474 | ) |
| 2475 | }), |
| 2476 | }); |
| 2477 | } |
| 2478 | } |
| 2479 | } |
| 2480 | } |
| 2481 | } |
| 2482 | AppAction::FetchModels => { |
| 2483 | app.show_command_result("Fetching models...".to_string(), StatusToastLevel::Info); |
| 2484 | match fetch_available_models(config).await { |
| 2485 | Ok(models) => { |
| 2486 | app.add_message(HistoryCell::System { |
| 2487 | content: format_helpers::available_models_message( |
| 2488 | app.ui_locale, |
| 2489 | app.provider_identity_for_persistence(), |
| 2490 | &app.model, |
| 2491 | &models, |
| 2492 | &codewhale_engine::fleet::members::fleet_models(&app.workspace), |
| 2493 | ), |
| 2494 | }); |
| 2495 | app.show_command_result( |
| 2496 | format!("Found {} model(s)", models.len()), |
| 2497 | StatusToastLevel::Success, |
| 2498 | ); |
| 2499 | } |
| 2500 | Err(error) => { |
| 2501 | app.add_message(HistoryCell::System { |
| 2502 | content: format!( |
| 2503 | "Failed to fetch models from {}: {error}", |
| 2504 | config |
| 2505 | .active_provider_identity() |
| 2506 | .ok() |
| 2507 | .as_ref() |
| 2508 | .map(|identity| identity |
| 2509 | .compatibility() |
| 2510 | .map(|row| row.label) |
| 2511 | .unwrap_or(identity.key.as_str())) |
| 2512 | .unwrap_or("unavailable") |
| 2513 | ), |
| 2514 | }); |
| 2515 | } |
| 2516 | } |
| 2517 | } |
| 2518 | AppAction::RefreshModelsDevCatalog => { |
| 2519 | app.show_command_result( |
| 2520 | "Refreshing Models.dev catalog...".to_string(), |
| 2521 | StatusToastLevel::Info, |
| 2522 | ); |
| 2523 | let refresh = codewhale_engine::models_dev_live::refresh(true).await; |
| 2524 | let level = if refresh.is_ok() { |
| 2525 | StatusToastLevel::Success |
| 2526 | } else { |
| 2527 | StatusToastLevel::Warning |
| 2528 | }; |
| 2529 | let message = match refresh { |
| 2530 | Ok(count) => { |
| 2531 | let status = codewhale_engine::models_dev_live::status(); |
| 2532 | let source = if status.source_label.is_empty() { |
| 2533 | "unknown" |
| 2534 | } else { |
| 2535 | status.source_label.as_str() |
| 2536 | }; |
| 2537 | format!( |
| 2538 | "Models.dev catalog refreshed: {count} offerings ({:?}, source {source})", |
| 2539 | status.freshness |
| 2540 | ) |
| 2541 | } |
| 2542 | Err(err) => { |
| 2543 | let status = codewhale_engine::models_dev_live::status(); |
| 2544 | format!( |
| 2545 | "Models.dev refresh failed ({err}); keeping prior/bundled rows ({} offerings, {:?})", |
| 2546 | status.offering_count, status.freshness |
| 2547 | ) |
| 2548 | } |
| 2549 | }; |
| 2550 | app.add_message(HistoryCell::System { |
| 2551 | content: message.clone(), |
| 2552 | }); |
| 2553 | app.show_command_result(message, level); |
| 2554 | // `/model refresh` also forces the cloud facts overlay when the |
| 2555 | // (off-by-default) channel is enabled. |
| 2556 | let cloud_settings = config.cloud_facts_config().settings(); |
| 2557 | codewhale_cloud_facts::configure(&cloud_settings); |
| 2558 | if cloud_settings.enabled { |
| 2559 | let now = codewhale_config::catalog::now_unix(); |
| 2560 | let cloud = match codewhale_cloud_facts::refresh(&cloud_settings, true).await { |
| 2561 | Ok(outcome) => { |
| 2562 | format!( |
| 2563 | "Cloud facts refreshed: {outcome:?} ({})", |
| 2564 | codewhale_cloud_facts::status().label(now) |
| 2565 | ) |
| 2566 | } |
| 2567 | Err(err) => format!( |
| 2568 | "Cloud facts refresh failed ({err}); {}", |
| 2569 | codewhale_cloud_facts::status().label(now) |
| 2570 | ), |
| 2571 | }; |
| 2572 | app.add_message(HistoryCell::System { content: cloud }); |
| 2573 | } |
| 2574 | if sync_active_session_after_catalog_refresh(app, config) { |
| 2575 | apply_model_and_compaction_update( |
| 2576 | engine_handle, |
| 2577 | app.compaction_config(), |
| 2578 | app.mode, |
| 2579 | app.active_route_limits, |
| 2580 | ) |
| 2581 | .await; |
| 2582 | } |
| 2583 | } |
| 2584 | AppAction::CacheWarmup => { |
| 2585 | app.show_command_result( |
| 2586 | "Warming prompt cache...".to_string(), |
| 2587 | StatusToastLevel::Info, |
| 2588 | ); |
| 2589 | match run_cache_warmup(app, config).await { |
| 2590 | Ok(outcome) => { |
| 2591 | app.session.last_base_url = Some(outcome.base_url.clone()); |
| 2592 | app.session.last_warmup_key = Some(CacheWarmupKey::from_inspection( |
| 2593 | &outcome.provider_identity, |
| 2594 | &outcome.model, |
| 2595 | &outcome.base_url, |
| 2596 | &outcome.inspection, |
| 2597 | )); |
| 2598 | let mut message = format_helpers::cache_warmup_result( |
| 2599 | app.ui_locale, |
| 2600 | &outcome.usage, |
| 2601 | outcome.tool_projection_warning.as_ref(), |
| 2602 | ); |
| 2603 | if let Some(key) = app.session.last_warmup_key.as_ref() { |
| 2604 | message.push_str(&format!("\nWarmup key: {}", key.hash_short())); |
| 2605 | } |
| 2606 | // Append prefix-cache stability info. |
| 2607 | if app.prefix_checks_total > 0 { |
| 2608 | let changes = app.prefix_change_count; |
| 2609 | let total = app.prefix_checks_total; |
| 2610 | let stable = total.saturating_sub(changes); |
| 2611 | let pct = app |
| 2612 | .prefix_stability_pct |
| 2613 | .map(|p| format!("{p}%")) |
| 2614 | .unwrap_or_else(|| "--".to_string()); |
| 2615 | message.push_str(&format!( |
| 2616 | "\n\nPrefix stability: {pct} ({stable}/{total} checks stable, {changes} change{})", |
| 2617 | if changes == 1 { "" } else { "s" } |
| 2618 | )); |
| 2619 | if let Some(ref desc) = app.last_prefix_change_desc { |
| 2620 | message.push_str(&format!("\nLast prefix change: {desc}")); |
| 2621 | } |
| 2622 | } |
| 2623 | app.add_message(HistoryCell::System { content: message }); |
| 2624 | app.show_command_result( |
| 2625 | "Cache warmup complete".to_string(), |
| 2626 | StatusToastLevel::Success, |
| 2627 | ); |
| 2628 | } |
| 2629 | Err(error) => { |
| 2630 | app.add_message(HistoryCell::System { |
| 2631 | content: format!("Cache warmup failed: {error}"), |
| 2632 | }); |
| 2633 | app.show_command_result( |
| 2634 | "Cache warmup failed".to_string(), |
| 2635 | StatusToastLevel::Error, |
| 2636 | ); |
| 2637 | } |
| 2638 | } |
| 2639 | } |
| 2640 | AppAction::SwitchProvider { provider, model } => { |
| 2641 | let identity = match config.resolve_provider_selection_identity(provider.as_str()) { |
| 2642 | Ok(identity) => identity, |
| 2643 | Err(reason) => { |
| 2644 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 2645 | return Ok(false); |
| 2646 | } |
| 2647 | }; |
| 2648 | if model.is_none() |
| 2649 | && identity.provider == ProviderKind::Ollama |
| 2650 | && identity.key.as_str() == "ollama" |
| 2651 | && app.api_provider == ProviderKind::Ollama |
| 2652 | && matches!( |
| 2653 | codewhale_runtime::config::resolve_credential_source(config, &identity) |
| 2654 | .source, |
| 2655 | codewhale_runtime::credentials::CredentialSource::KeylessRoute { .. } |
| 2656 | ) |
| 2657 | && app.start_local_ollama_probe(config, true) |
| 2658 | { |
| 2659 | return Ok(false); |
| 2660 | } |
| 2661 | switch_provider(app, engine_handle, config, identity, model).await; |
| 2662 | let api_key = config.active_route_api_key().unwrap_or_default(); |
| 2663 | let base_url = config.active_route_base_url(); |
| 2664 | schedule_balance_fetch(app, &api_key, &base_url, false); |
| 2665 | } |
| 2666 | AppAction::SwitchModelRoute { identity, model } => { |
| 2667 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 2668 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 2669 | return Ok(false); |
| 2670 | } |
| 2671 | let previous_model = if app.auto_model { |
| 2672 | "auto".to_string() |
| 2673 | } else { |
| 2674 | app.model.clone() |
| 2675 | }; |
| 2676 | // Hotbar route actions do not carry an effort choice. Preserve |
| 2677 | // the raw global preference instead of feeding a fixed |
| 2678 | // route's normalized live tier back through the picker path. |
| 2679 | let previous_effort = app |
| 2680 | .reasoning_effort_preference |
| 2681 | .unwrap_or(app.reasoning_effort); |
| 2682 | apply_model_picker_choice( |
| 2683 | app, |
| 2684 | engine_handle, |
| 2685 | config, |
| 2686 | model, |
| 2687 | Some(identity), |
| 2688 | previous_effort, |
| 2689 | previous_model, |
| 2690 | previous_effort, |
| 2691 | // A hotbar route switch is a session action, not a |
| 2692 | // statement about what the next launch should open with. |
| 2693 | false, |
| 2694 | ) |
| 2695 | .await; |
| 2696 | } |
| 2697 | AppAction::UpdateCompaction(compaction) => { |
| 2698 | if app.is_loading || app.is_compacting { |
| 2699 | let queued = try_apply_model_and_compaction_update( |
| 2700 | engine_handle, |
| 2701 | compaction, |
| 2702 | app.mode, |
| 2703 | app.active_route_limits, |
| 2704 | ); |
| 2705 | app.show_command_result( |
| 2706 | if queued { |
| 2707 | "Config change queued; the active turn remains responsive.".to_string() |
| 2708 | } else { |
| 2709 | "Config change deferred; it will apply to the next turn.".to_string() |
| 2710 | }, |
| 2711 | if queued { |
| 2712 | StatusToastLevel::Success |
| 2713 | } else { |
| 2714 | StatusToastLevel::Warning |
| 2715 | }, |
| 2716 | ); |
| 2717 | } else { |
| 2718 | apply_model_and_compaction_update( |
| 2719 | engine_handle, |
| 2720 | compaction, |
| 2721 | app.mode, |
| 2722 | app.active_route_limits, |
| 2723 | ) |
| 2724 | .await; |
| 2725 | } |
| 2726 | } |
| 2727 | AppAction::UpdateStreamChunkTimeout(timeout_secs) => { |
| 2728 | // #6150: the input path never awaits a full op channel. |
| 2729 | if engine_handle |
| 2730 | .try_send(Op::SetStreamChunkTimeout { timeout_secs }) |
| 2731 | .is_err() |
| 2732 | { |
| 2733 | app.show_command_result( |
| 2734 | "Engine busy — setting not applied; try again".to_string(), |
| 2735 | StatusToastLevel::Warning, |
| 2736 | ); |
| 2737 | } |
| 2738 | } |
| 2739 | AppAction::UpdateSubagentRuntimeConfig { |
| 2740 | enabled, |
| 2741 | max_subagents, |
| 2742 | launch_concurrency, |
| 2743 | max_spawn_depth, |
| 2744 | api_timeout_secs, |
| 2745 | heartbeat_timeout_secs, |
| 2746 | } => { |
| 2747 | if engine_handle |
| 2748 | .try_send(Op::SetSubagentRuntimeConfig { |
| 2749 | enabled, |
| 2750 | max_subagents, |
| 2751 | launch_concurrency, |
| 2752 | max_spawn_depth, |
| 2753 | api_timeout_secs, |
| 2754 | heartbeat_timeout_secs, |
| 2755 | }) |
| 2756 | .is_err() |
| 2757 | { |
| 2758 | app.show_command_result( |
| 2759 | "Engine busy — setting not applied; try again".to_string(), |
| 2760 | StatusToastLevel::Warning, |
| 2761 | ); |
| 2762 | } |
| 2763 | } |
| 2764 | AppAction::UpdateSearchProvider { provider } => { |
| 2765 | // Reserve before committing the config change so a full |
| 2766 | // channel cannot desync the engine from it. |
| 2767 | match engine_handle.tx_op.clone().try_reserve_owned() { |
| 2768 | Ok(permit) => { |
| 2769 | let effective_provider = config.set_search_provider(provider); |
| 2770 | engine_handle.send_reserved_op( |
| 2771 | permit, |
| 2772 | Op::SetSearchProvider { |
| 2773 | provider: effective_provider, |
| 2774 | }, |
| 2775 | ); |
| 2776 | } |
| 2777 | Err(_) => { |
| 2778 | app.show_command_result( |
| 2779 | "Engine busy — provider not applied; try again".to_string(), |
| 2780 | StatusToastLevel::Warning, |
| 2781 | ); |
| 2782 | } |
| 2783 | } |
| 2784 | } |
| 2785 | AppAction::UpdatePromptSuggestion { enabled } => { |
| 2786 | config.prompt_suggestion = Some(enabled); |
| 2787 | } |
| 2788 | AppAction::SetAutoReviewReviewerModel { reviewer_model } => { |
| 2789 | app.auto_review_reviewer_model = reviewer_model.clone(); |
| 2790 | config |
| 2791 | .auto_review |
| 2792 | .get_or_insert_with(Default::default) |
| 2793 | .reviewer_model = reviewer_model.clone(); |
| 2794 | if engine_handle |
| 2795 | .try_send(Op::SetAutoReviewReviewerModel { reviewer_model }) |
| 2796 | .is_err() |
| 2797 | { |
| 2798 | app.show_command_result( |
| 2799 | "Engine busy — setting not applied; try again".to_string(), |
| 2800 | StatusToastLevel::Warning, |
| 2801 | ); |
| 2802 | } |
| 2803 | } |
| 2804 | AppAction::UpdateNotification { update } => { |
| 2805 | if let Err(error) = apply_notification_update(app, config, update) { |
| 2806 | app.push_status_toast(error.to_string(), StatusToastLevel::Error, Some(6_000)); |
| 2807 | } |
| 2808 | } |
| 2809 | AppAction::SetAdvisorEnabled { enabled } => { |
| 2810 | if engine_handle |
| 2811 | .try_send(Op::SetAdvisorEnabled { enabled }) |
| 2812 | .is_err() |
| 2813 | { |
| 2814 | app.show_command_result( |
| 2815 | "Engine busy — setting not applied; try again".to_string(), |
| 2816 | StatusToastLevel::Warning, |
| 2817 | ); |
| 2818 | } |
| 2819 | } |
| 2820 | AppAction::OpenConfigView => { |
| 2821 | if app.view_stack.top_kind() != Some(ModalKind::Config) { |
| 2822 | app.view_stack.push(ConfigView::new_for_app(app)); |
| 2823 | } |
| 2824 | } |
| 2825 | AppAction::OpenWorktreeManager => { |
| 2826 | if app.view_stack.top_kind() != Some(ModalKind::WorktreeManager) { |
| 2827 | // Non-blocking: git_status caches; manager never shells on paint. |
| 2828 | codewhale_engine::git_status::refresh_if_stale(&app.workspace); |
| 2829 | app.view_stack |
| 2830 | .push(crate::tui::worktree_manager::WorktreeManagerView::new( |
| 2831 | app.workspace.clone(), |
| 2832 | )); |
| 2833 | } |
| 2834 | } |
| 2835 | AppAction::OpenAgentBoard => { |
| 2836 | crate::tui::agent_board::open_from_app(app); |
| 2837 | } |
| 2838 | AppAction::OpenPlanArtifact { arg } => { |
| 2839 | crate::tui::plan_artifact::open_from_app(app, arg.as_deref()); |
| 2840 | } |
| 2841 | AppAction::UndoLatestRequest { force } => { |
| 2842 | if !app |
| 2843 | .history |
| 2844 | .iter() |
| 2845 | .any(|cell| matches!(cell, HistoryCell::User { .. })) |
| 2846 | { |
| 2847 | app.show_command_result("Nothing to undo".to_string(), StatusToastLevel::Info); |
| 2848 | app.push_status_toast_record( |
| 2849 | StatusToast::new("Nothing to undo", StatusToastLevel::Info, Some(4_000)) |
| 2850 | .for_command_receipt(), |
| 2851 | ); |
| 2852 | } else { |
| 2853 | match apply_range_undo(terminal, app, engine_handle, config, 0).await { |
| 2854 | Ok(()) => app.clear_input(), |
| 2855 | Err(error) => { |
| 2856 | let force_note = if force { |
| 2857 | " Force cannot replace missing request identity or restore receipts; use /restore for an explicit file restore." |
| 2858 | } else { |
| 2859 | "" |
| 2860 | }; |
| 2861 | let message = format!("Undo failed: {error:#}{force_note}"); |
| 2862 | app.add_message(HistoryCell::System { |
| 2863 | content: message.clone(), |
| 2864 | }); |
| 2865 | app.push_status_toast(message, StatusToastLevel::Error, None); |
| 2866 | } |
| 2867 | } |
| 2868 | } |
| 2869 | } |
| 2870 | AppAction::OpenUndoSelector => { |
| 2871 | let total = app |
| 2872 | .history |
| 2873 | .iter() |
| 2874 | .filter(|cell| matches!(cell, HistoryCell::User { .. })) |
| 2875 | .count(); |
| 2876 | if total == 0 { |
| 2877 | app.show_command_result("Nothing to undo".to_string(), StatusToastLevel::Info); |
| 2878 | app.push_status_toast_record( |
| 2879 | StatusToast::new("Nothing to undo", StatusToastLevel::Info, Some(4_000)) |
| 2880 | .for_command_receipt(), |
| 2881 | ); |
| 2882 | } else if app.is_loading |
| 2883 | || app.is_compacting |
| 2884 | || app.dispatch_in_flight |
| 2885 | || app.remote_control.runtime_chat_blocks_local_dispatch() |
| 2886 | { |
| 2887 | app.push_status_toast( |
| 2888 | "Wait for the active turn to finish before undoing files.", |
| 2889 | StatusToastLevel::Error, |
| 2890 | None, |
| 2891 | ); |
| 2892 | } else { |
| 2893 | app.backtrack.phase = crate::tui::backtrack::BacktrackPhase::Selecting { |
| 2894 | selected_idx: 0, |
| 2895 | total, |
| 2896 | }; |
| 2897 | open_undo_overlay(app); |
| 2898 | } |
| 2899 | } |
| 2900 | AppAction::OpenModelPicker => { |
| 2901 | if app.view_stack.top_kind() != Some(ModalKind::ModelPicker) { |
| 2902 | app.clear_input(); |
| 2903 | app.paste_burst.clear_after_explicit_paste(); |
| 2904 | crate::tui::external_agent::start_external_agent_discovery(app); |
| 2905 | app.view_stack |
| 2906 | .push(crate::tui::model_picker::ModelPickerView::new(app, config)); |
| 2907 | } |
| 2908 | } |
| 2909 | AppAction::OpenProviderPicker => { |
| 2910 | open_provider_picker(app, config, engine_handle).await; |
| 2911 | } |
| 2912 | AppAction::OpenProviderSetup { provider } => { |
| 2913 | if app.view_stack.top_kind() != Some(ModalKind::ProviderPicker) { |
| 2914 | let runtime_status = query_provider_runtime_status(engine_handle).await; |
| 2915 | app.view_stack.push( |
| 2916 | crate::tui::provider_picker::ProviderPickerView::new_for_setup( |
| 2917 | app.api_provider, |
| 2918 | provider, |
| 2919 | config, |
| 2920 | runtime_status, |
| 2921 | ) |
| 2922 | .with_locale(app.ui_locale) |
| 2923 | .with_provider_health(&app.provider_health), |
| 2924 | ); |
| 2925 | app.show_command_result( |
| 2926 | "Provider setup catalog opened.".to_string(), |
| 2927 | StatusToastLevel::Info, |
| 2928 | ); |
| 2929 | } |
| 2930 | } |
| 2931 | AppAction::OpenDs4Setup => { |
| 2932 | if app.view_stack.top_kind() != Some(ModalKind::ProviderPicker) { |
| 2933 | let runtime_status = query_provider_runtime_status(engine_handle).await; |
| 2934 | app.view_stack.push( |
| 2935 | crate::tui::provider_picker::ProviderPickerView::new_for_ds4_setup( |
| 2936 | app.api_provider, |
| 2937 | config, |
| 2938 | runtime_status, |
| 2939 | ) |
| 2940 | .with_locale(app.ui_locale) |
| 2941 | .with_provider_health(&app.provider_health), |
| 2942 | ); |
| 2943 | } |
| 2944 | } |
| 2945 | AppAction::EditProjectHooks => { |
| 2946 | edit_project_hooks_from_tui(terminal, app, config); |
| 2947 | } |
| 2948 | AppAction::OpenModelConnectionSetup |
| 2949 | if !crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED => |
| 2950 | { |
| 2951 | begin_first_connection_setup(app); |
| 2952 | open_provider_picker(app, config, engine_handle).await; |
| 2953 | } |
| 2954 | AppAction::OpenModelConnectionSetup => { |
| 2955 | begin_first_connection_setup(app); |
| 2956 | app.view_stack |
| 2957 | .push(crate::tui::account_login::ConnectionSetupView::new( |
| 2958 | app.ui_locale, |
| 2959 | )); |
| 2960 | } |
| 2961 | AppAction::StartAccountConnect => { |
| 2962 | begin_first_connection_setup(app); |
| 2963 | if app.view_stack.contains_kind(ModalKind::AccountLogin) { |
| 2964 | app.view_stack.pop_through_kind(ModalKind::AccountLogin); |
| 2965 | } |
| 2966 | app.view_stack |
| 2967 | .push(crate::tui::account_login::AccountLoginView::connect( |
| 2968 | app.config_profile.clone(), |
| 2969 | app.ui_locale, |
| 2970 | )); |
| 2971 | } |
| 2972 | AppAction::StartAccountLogin | AppAction::StartAccountLogout => { |
| 2973 | if app.view_stack.top_kind() != Some(ModalKind::AccountLogin) { |
| 2974 | if app.view_stack.contains_kind(ModalKind::AccountLogin) { |
| 2975 | app.view_stack.pop_through_kind(ModalKind::AccountLogin); |
| 2976 | } |
| 2977 | app.view_stack |
| 2978 | .push(crate::tui::account_login::AccountLoginView::new( |
| 2979 | app.config_profile.clone(), |
| 2980 | matches!(action, AppAction::StartAccountLogout), |
| 2981 | app.ui_locale, |
| 2982 | )); |
| 2983 | } |
| 2984 | } |
| 2985 | AppAction::StartXaiDeviceLogin => { |
| 2986 | let _switched = |
| 2987 | run_xai_device_login_from_tui(terminal, app, engine_handle, config).await?; |
| 2988 | } |
| 2989 | AppAction::StartChatgptPkceLogin => { |
| 2990 | let _switched = |
| 2991 | run_chatgpt_pkce_login_from_tui(terminal, app, engine_handle, config).await?; |
| 2992 | } |
| 2993 | AppAction::StartChatgptRevoke => { |
| 2994 | run_chatgpt_revoke_from_tui(app, config).await; |
| 2995 | } |
| 2996 | AppAction::StartPluginLogin { provider } => { |
| 2997 | run_plugin_oauth_from_tui(terminal, app, config, provider, false).await?; |
| 2998 | } |
| 2999 | AppAction::StartPluginLogout { provider } => { |
| 3000 | run_plugin_oauth_from_tui(terminal, app, config, provider, true).await?; |
| 3001 | } |
| 3002 | AppAction::StartOrcarouterPkceLogin => { |
| 3003 | let _switched = |
| 3004 | run_orcarouter_pkce_login_from_tui(terminal, app, engine_handle, config) |
| 3005 | .await?; |
| 3006 | } |
| 3007 | AppAction::StartOrcarouterRevoke => { |
| 3008 | run_orcarouter_revoke_from_tui(app, config).await; |
| 3009 | } |
| 3010 | AppAction::OpenModePicker => { |
| 3011 | if app.view_stack.top_kind() != Some(ModalKind::ModePicker) { |
| 3012 | let view = |
| 3013 | crate::tui::views::mode_picker::ModePickerView::for_app(app, config).await; |
| 3014 | app.view_stack.push(view); |
| 3015 | } |
| 3016 | } |
| 3017 | AppAction::SetConversationMode { id } => { |
| 3018 | let content = match crate::tui::conversation_mode::set_in_place( |
| 3019 | app, |
| 3020 | config, |
| 3021 | engine_handle, |
| 3022 | &id, |
| 3023 | ) |
| 3024 | .await |
| 3025 | { |
| 3026 | Ok(message) | Err(message) => message, |
| 3027 | }; |
| 3028 | app.add_message(HistoryCell::System { content }); |
| 3029 | } |
| 3030 | AppAction::OpenStatusPicker => { |
| 3031 | if app.view_stack.top_kind() != Some(ModalKind::StatusPicker) { |
| 3032 | app.view_stack |
| 3033 | .push(crate::tui::views::status_picker::StatusPickerView::new( |
| 3034 | &app.status_items, |
| 3035 | app.api_provider, |
| 3036 | app.ui_locale, |
| 3037 | )); |
| 3038 | } |
| 3039 | } |
| 3040 | AppAction::ReviewIssueReport { id, change } => { |
| 3041 | if let Err(error) = super::feedback_host::start(app, config, id, change) { |
| 3042 | tracing::warn!(target:"feedback_host",%error,"feedback request refused before admission"); |
| 3043 | app.add_message(HistoryCell::System { |
| 3044 | content: app.tr(MessageId::FeedbackUnavailable).into_owned(), |
| 3045 | }); |
| 3046 | } |
| 3047 | } |
| 3048 | AppAction::OpenFeedbackPicker => { |
| 3049 | if app.view_stack.top_kind() != Some(ModalKind::FeedbackPicker) { |
| 3050 | app.view_stack |
| 3051 | .push(crate::tui::feedback_picker::FeedbackPickerView::new()); |
| 3052 | } |
| 3053 | } |
| 3054 | AppAction::OpenThemePicker => { |
| 3055 | if app.view_stack.top_kind() != Some(ModalKind::ThemePicker) { |
| 3056 | // Capture the active theme name straight from `app` so |
| 3057 | // Esc can revert through the same ConfigUpdated channel. |
| 3058 | // Avoids re-reading settings.toml from disk on every |
| 3059 | // `/theme` invocation. |
| 3060 | let original = app.theme_name.clone(); |
| 3061 | app.view_stack |
| 3062 | .push_boxed(crate::tui::theme_picker::ThemePickerView::boxed( |
| 3063 | original, |
| 3064 | app.ui_locale, |
| 3065 | app.background_color_override, |
| 3066 | )); |
| 3067 | } |
| 3068 | } |
| 3069 | AppAction::OpenSkillsManager => { |
| 3070 | if app.view_stack.top_kind() != Some(ModalKind::SkillsManager) { |
| 3071 | app.view_stack |
| 3072 | .push(crate::tui::views::skills_manager::SkillsManagerView::new( |
| 3073 | app, |
| 3074 | )); |
| 3075 | } |
| 3076 | } |
| 3077 | AppAction::OpenWorkflowsManager => { |
| 3078 | crate::tui::views::workflows_manager::open(app); |
| 3079 | } |
| 3080 | AppAction::OpenExtensions { tab } => { |
| 3081 | if app.view_stack.top_kind() != Some(ModalKind::Extensions) { |
| 3082 | app.view_stack |
| 3083 | .push(crate::tui::views::extensions::ExtensionsView::new(app, tab)); |
| 3084 | } |
| 3085 | } |
| 3086 | AppAction::OpenFleetMissions => { |
| 3087 | if app.view_stack.top_kind() != Some(ModalKind::FleetMissions) { |
| 3088 | app.view_stack |
| 3089 | .push(crate::tui::views::fleet_missions::FleetMissionsView::new( |
| 3090 | app.workspace.clone(), |
| 3091 | app.ui_locale, |
| 3092 | )); |
| 3093 | } |
| 3094 | app.maybe_show_feature_intro(); |
| 3095 | } |
| 3096 | AppAction::OpenFleetList => { |
| 3097 | if app.view_stack.top_kind() != Some(ModalKind::FleetList) { |
| 3098 | let view = |
| 3099 | crate::tui::views::fleet_list::FleetListView::load(app, config).await; |
| 3100 | app.view_stack.push(view); |
| 3101 | } |
| 3102 | } |
| 3103 | AppAction::OpenFleetRoster => { |
| 3104 | if app.view_stack.top_kind() != Some(ModalKind::FleetRoster) { |
| 3105 | app.view_stack |
| 3106 | .push(crate::tui::views::fleet_roster::FleetRosterView::new( |
| 3107 | app, config, |
| 3108 | )); |
| 3109 | } |
| 3110 | } |
| 3111 | AppAction::OpenFleetSetup => { |
| 3112 | open_fleet_setup_target(app, config, None).await; |
| 3113 | } |
| 3114 | AppAction::FleetAddModel { |
| 3115 | provider, |
| 3116 | model, |
| 3117 | roles, |
| 3118 | } => { |
| 3119 | use crate::commands::{fleet_catalog_rejection, fleet_provider_rejection}; |
| 3120 | let locale = app.ui_locale; |
| 3121 | // The live `config` is the provider truth: the startup |
| 3122 | // snapshot went stale after any in-session provider change. |
| 3123 | let rejection = fleet_provider_rejection(app, config, &provider) |
| 3124 | .or_else(|| fleet_catalog_rejection(locale, &provider, &model)); |
| 3125 | let content = match rejection { |
| 3126 | Some(rejection) => rejection, |
| 3127 | None => match codewhale_engine::fleet::members::add_fleet_model( |
| 3128 | &app.workspace, |
| 3129 | &provider, |
| 3130 | &model, |
| 3131 | &roles, |
| 3132 | ) { |
| 3133 | Ok(change) => { |
| 3134 | if !matches!( |
| 3135 | change, |
| 3136 | codewhale_engine::fleet::members::FleetModelChange::Unchanged { .. } |
| 3137 | ) { |
| 3138 | app.fleet_roster_stale = true; |
| 3139 | } |
| 3140 | codewhale_engine::fleet::members::change_receipt( |
| 3141 | locale, &provider, &model, &change, |
| 3142 | ) |
| 3143 | } |
| 3144 | Err(error) => tr(locale, MessageId::FleetAddFailed) |
| 3145 | .replace("{error}", &error.message(locale)), |
| 3146 | }, |
| 3147 | }; |
| 3148 | app.add_message(HistoryCell::System { content }); |
| 3149 | } |
| 3150 | AppAction::FleetRemoveModel { provider, model } => { |
| 3151 | let locale = app.ui_locale; |
| 3152 | let content = match codewhale_engine::fleet::members::remove_fleet_model( |
| 3153 | &app.workspace, |
| 3154 | &provider, |
| 3155 | &model, |
| 3156 | ) { |
| 3157 | Ok(change) => { |
| 3158 | app.fleet_roster_stale = true; |
| 3159 | codewhale_engine::fleet::members::change_receipt( |
| 3160 | locale, &provider, &model, &change, |
| 3161 | ) |
| 3162 | } |
| 3163 | Err(error) => tr(locale, MessageId::FleetRemoveFailed) |
| 3164 | .replace("{error}", &error.message(locale)), |
| 3165 | }; |
| 3166 | app.add_message(HistoryCell::System { content }); |
| 3167 | } |
| 3168 | AppAction::OpenHotbarSetup => { |
| 3169 | if app.view_stack.top_kind() != Some(ModalKind::HotbarSetup) { |
| 3170 | app.view_stack |
| 3171 | .push(crate::tui::hotbar::setup::HotbarSetupView::new(app, config)); |
| 3172 | } |
| 3173 | } |
| 3174 | AppAction::OpenSetupWizard => { |
| 3175 | if app.view_stack.top_kind() != Some(ModalKind::SetupWizard) { |
| 3176 | let _ = app.next_draft_gen(); |
| 3177 | let view = crate::tui::setup::SetupWizardView::load_for_app(app, config).await; |
| 3178 | app.view_stack.push(view); |
| 3179 | } |
| 3180 | } |
| 3181 | AppAction::OpenSetupWizardAt { step } => { |
| 3182 | if app.view_stack.top_kind() != Some(ModalKind::SetupWizard) { |
| 3183 | let _ = app.next_draft_gen(); |
| 3184 | let view = |
| 3185 | crate::tui::setup::SetupWizardView::load_for_app_at(app, config, step) |
| 3186 | .await; |
| 3187 | app.view_stack.push(view); |
| 3188 | } |
| 3189 | } |
| 3190 | AppAction::OpenConstitutionManager { review } => { |
| 3191 | let profile = config.account_profile.clone(); |
| 3192 | let account = tokio::task::spawn_blocking(move || { |
| 3193 | codewhale_engine::profile_constitution::account_is_present(profile.as_deref()) |
| 3194 | .map_err(|error| error.to_string()) |
| 3195 | }) |
| 3196 | .await |
| 3197 | .unwrap_or_else(|error| Err(error.to_string())); |
| 3198 | crate::commands::open_constitution_manager(app, review, account); |
| 3199 | } |
| 3200 | AppAction::UseBundledConstitution => use_bundled_constitution(app, config), |
| 3201 | AppAction::PreviewEffectiveBasePrompt => preview_effective_base_prompt(app, config), |
| 3202 | AppAction::DisableHotbar => disable_hotbar(app, config), |
| 3203 | AppAction::RestoreHotbarDefaults => restore_hotbar_defaults(app, config), |
| 3204 | AppAction::OpenExternalUrl { url, label } => match open_external_url(&url) { |
| 3205 | Ok(()) => { |
| 3206 | app.show_command_result( |
| 3207 | format!("Opened {label} in your browser"), |
| 3208 | StatusToastLevel::Success, |
| 3209 | ); |
| 3210 | } |
| 3211 | Err(err) => { |
| 3212 | app.add_message(HistoryCell::System { |
| 3213 | content: format!( |
| 3214 | "Could not open {label} automatically: {err}\n\nThe URL is printed above." |
| 3215 | ), |
| 3216 | }); |
| 3217 | } |
| 3218 | }, |
| 3219 | AppAction::OpenContextInspector => { |
| 3220 | open_context_inspector(app); |
| 3221 | } |
| 3222 | AppAction::SetActiveModelContextWindow { tokens } => { |
| 3223 | apply_active_model_context_window_override(app, engine_handle, config, tokens) |
| 3224 | .await; |
| 3225 | } |
| 3226 | AppAction::OpenLiveTranscript => { |
| 3227 | open_live_transcript_overlay(app); |
| 3228 | } |
| 3229 | AppAction::OpenTurnInspector => { |
| 3230 | open_turn_inspector_pager(app); |
| 3231 | } |
| 3232 | AppAction::CompactContext { focus } => { |
| 3233 | try_queue_manual_compaction(app, config, engine_handle, focus); |
| 3234 | } |
| 3235 | AppAction::PurgeContext => { |
| 3236 | if engine_handle.try_send(Op::PurgeContext).is_err() { |
| 3237 | app.show_command_result( |
| 3238 | "Engine busy — purge not sent; try again".to_string(), |
| 3239 | StatusToastLevel::Warning, |
| 3240 | ); |
| 3241 | } else { |
| 3242 | app.show_command_result( |
| 3243 | "Agent purging context...".to_string(), |
| 3244 | StatusToastLevel::Info, |
| 3245 | ); |
| 3246 | } |
| 3247 | } |
| 3248 | AppAction::TaskAdd { prompt } => { |
| 3249 | let owner_session_id = app |
| 3250 | .current_session_id |
| 3251 | .clone() |
| 3252 | .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); |
| 3253 | app.set_current_session_id(Some(owner_session_id.clone())); |
| 3254 | let request = NewTaskRequest { |
| 3255 | destination_thread_id: None, |
| 3256 | prompt: prompt.clone(), |
| 3257 | name: None, |
| 3258 | model: Some(app.model.clone()), |
| 3259 | model_provider: Some(app.api_provider.as_str().to_string()), |
| 3260 | model_provider_id: Some(app.provider_identity_for_persistence().to_string()), |
| 3261 | workspace: Some(app.workspace.clone()), |
| 3262 | mode: Some(task_mode_label(app.mode).to_string()), |
| 3263 | allow_shell: Some(app.allow_shell), |
| 3264 | trust_mode: Some(app.trust_mode), |
| 3265 | auto_approve: Some(app_auto_approve_enabled(app)), |
| 3266 | // Same as the task tool: the task's own thread runs under |
| 3267 | // the posture this session is in, not under whatever a |
| 3268 | // legacy bit happens to mean today. |
| 3269 | permission_posture: Some( |
| 3270 | codewhale_runtime::runtime_policy::approval_wire(app.approval_mode) |
| 3271 | .to_string(), |
| 3272 | ), |
| 3273 | owner_session_id: Some(owner_session_id), |
| 3274 | disallowed_tools: Vec::new(), |
| 3275 | }; |
| 3276 | let Some(task_manager) = task_manager.as_ref() else { |
| 3277 | app.add_message(HistoryCell::System { |
| 3278 | content: codewhale_localization::tr( |
| 3279 | app.ui_locale, |
| 3280 | codewhale_localization::MessageId::TaskInventoryUnavailable, |
| 3281 | ) |
| 3282 | .to_string(), |
| 3283 | }); |
| 3284 | return Ok(false); |
| 3285 | }; |
| 3286 | match task_manager.add_task(request).await { |
| 3287 | Ok(task) => { |
| 3288 | app.add_message(HistoryCell::System { |
| 3289 | content: format!( |
| 3290 | "Task queued: {} ({})", |
| 3291 | task.id, |
| 3292 | summarize_tool_output(&task.prompt) |
| 3293 | ), |
| 3294 | }); |
| 3295 | app.show_command_result( |
| 3296 | format!("Queued {}", task.id), |
| 3297 | StatusToastLevel::Success, |
| 3298 | ); |
| 3299 | } |
| 3300 | Err(err) => { |
| 3301 | app.add_message(HistoryCell::System { |
| 3302 | content: format!("Failed to queue task: {err}"), |
| 3303 | }); |
| 3304 | } |
| 3305 | } |
| 3306 | refresh_active_task_panel(app).await; |
| 3307 | } |
| 3308 | AppAction::TaskList => { |
| 3309 | let tasks = match app.current_session_id.as_deref() { |
| 3310 | Some(session_id) => match task_manager.as_ref() { |
| 3311 | Some(manager) => { |
| 3312 | manager |
| 3313 | .list_tasks_for_owner(Some(30), None, session_id) |
| 3314 | .await |
| 3315 | } |
| 3316 | None => Ok(Vec::new()), |
| 3317 | }, |
| 3318 | None => Ok(Vec::new()), |
| 3319 | }; |
| 3320 | refresh_active_task_panel(app).await; |
| 3321 | app.add_message(HistoryCell::System { |
| 3322 | content: match tasks { |
| 3323 | Ok(tasks) => format_task_list(&tasks), |
| 3324 | Err(_) => codewhale_localization::tr( |
| 3325 | app.ui_locale, |
| 3326 | codewhale_localization::MessageId::TaskInventoryUnavailable, |
| 3327 | ) |
| 3328 | .to_string(), |
| 3329 | }, |
| 3330 | }); |
| 3331 | } |
| 3332 | AppAction::RemoteControl(action) => match action { |
| 3333 | codewhale_app_server::remote_control::RemoteControlAction::Start => { |
| 3334 | start_remote_control_session(app, config).await; |
| 3335 | } |
| 3336 | codewhale_app_server::remote_control::RemoteControlAction::Stop => { |
| 3337 | app.remote_control.stop_async().await; |
| 3338 | let status = app.remote_control.status_line(); |
| 3339 | app.retire_progress_notice(StatusToastKind::RemoteMirror); |
| 3340 | app.show_command_result(status, StatusToastLevel::Info); |
| 3341 | } |
| 3342 | }, |
| 3343 | AppAction::TaskShow { id } => { |
| 3344 | let task = match app.current_session_id.as_deref() { |
| 3345 | Some(session_id) => match task_manager.as_ref() { |
| 3346 | Some(manager) => { |
| 3347 | manager |
| 3348 | .get_task_for_interactive_session(&id, session_id) |
| 3349 | .await |
| 3350 | } |
| 3351 | None => Err(anyhow::anyhow!("Task not found: {id}")), |
| 3352 | }, |
| 3353 | None => Err(anyhow::anyhow!("Task not found: {id}")), |
| 3354 | }; |
| 3355 | match task { |
| 3356 | Ok(task) => open_task_pager(app, &task), |
| 3357 | Err(err) => { |
| 3358 | app.add_message(HistoryCell::System { |
| 3359 | content: format!("Task lookup failed: {err}"), |
| 3360 | }); |
| 3361 | } |
| 3362 | } |
| 3363 | } |
| 3364 | AppAction::TaskCancel { id } => { |
| 3365 | let cancellation = match app.current_session_id.as_deref() { |
| 3366 | Some(session_id) => match task_manager.as_ref() { |
| 3367 | Some(manager) => { |
| 3368 | manager |
| 3369 | .cancel_task_for_interactive_session(&id, session_id) |
| 3370 | .await |
| 3371 | } |
| 3372 | None => Err(anyhow::anyhow!("Task not found: {id}")), |
| 3373 | }, |
| 3374 | None => Err(anyhow::anyhow!("Task not found: {id}")), |
| 3375 | }; |
| 3376 | match cancellation { |
| 3377 | Ok(cancellation) => { |
| 3378 | app.add_message(HistoryCell::System { |
| 3379 | content: format!( |
| 3380 | "Task {} status: {:?}", |
| 3381 | cancellation.task.id, cancellation.task.status |
| 3382 | ), |
| 3383 | }); |
| 3384 | } |
| 3385 | Err(err) => { |
| 3386 | app.add_message(HistoryCell::System { |
| 3387 | content: format!("Task cancel failed: {err}"), |
| 3388 | }); |
| 3389 | } |
| 3390 | } |
| 3391 | refresh_active_task_panel(app).await; |
| 3392 | } |
| 3393 | AppAction::Automation(action) => { |
| 3394 | crate::tui::automation_routing::handle_action(app, config, action).await; |
| 3395 | } |
| 3396 | AppAction::ShellJob(action) => { |
| 3397 | handle_shell_job_action(app, action); |
| 3398 | // Immediately sync the task panel after cancel/poll so the |
| 3399 | // Activity sidebar stays accurate without waiting for the |
| 3400 | // next 2.5 s periodic refresh (#2937). |
| 3401 | refresh_active_task_panel(app).await; |
| 3402 | } |
| 3403 | AppAction::Mcp(action) => { |
| 3404 | handle_mcp_ui_action(app, engine_handle, config, action).await; |
| 3405 | } |
| 3406 | AppAction::SwitchWorkspace { workspace } => { |
| 3407 | switch_workspace(app, engine_handle, config, workspace).await; |
| 3408 | } |
| 3409 | AppAction::SwitchProfile { profile } => { |
| 3410 | let previous_profile = app.config_profile.clone(); |
| 3411 | match codewhale_plugins::providers::load_config( |
| 3412 | app.config_path.clone(), |
| 3413 | Some(&profile), |
| 3414 | ) |
| 3415 | .and_then(|new_config| { |
| 3416 | validated_profile_default_route(&new_config) |
| 3417 | .map(|validated_route| (new_config, validated_route)) |
| 3418 | }) { |
| 3419 | Ok((new_config, validated_route)) => { |
| 3420 | let new_model = validated_route.model.clone(); |
| 3421 | apply_validated_profile_config( |
| 3422 | app, |
| 3423 | config, |
| 3424 | &profile, |
| 3425 | new_config, |
| 3426 | &validated_route, |
| 3427 | ); |
| 3428 | codewhale_runtime::config::initialize_cloud_facts(config); |
| 3429 | // Rebuild the engine with the new config so API key/model/base URL take effect. |
| 3430 | replace_tui_engine(app, config, engine_handle).await; |
| 3431 | if !app.api_messages.is_empty() { |
| 3432 | let _ = engine_handle |
| 3433 | .send(Op::SyncSession { |
| 3434 | expected: None, |
| 3435 | control: app.session_sync_control(), |
| 3436 | session_id: app.current_session_id.clone(), |
| 3437 | messages: app.api_messages.as_ref().clone(), |
| 3438 | system_prompt: app.system_prompt.clone(), |
| 3439 | system_prompt_override: false, |
| 3440 | model: app.model.clone(), |
| 3441 | workspace: app.workspace.clone(), |
| 3442 | mode: app.mode, |
| 3443 | agent_preset: app.agent_preset(), |
| 3444 | }) |
| 3445 | .await; |
| 3446 | } |
| 3447 | let provider = app.provider_identity_for_persistence(); |
| 3448 | let content = app |
| 3449 | .tr(MessageId::ProfileSwitched) |
| 3450 | .replace("{model}", &new_model) |
| 3451 | .replace("{provider}", provider) |
| 3452 | .replace("{name}", &profile); |
| 3453 | app.add_message(HistoryCell::System { content }); |
| 3454 | app.show_command_result( |
| 3455 | app.tr(MessageId::ProfileStatus).replace("{name}", &profile), |
| 3456 | StatusToastLevel::Success, |
| 3457 | ); |
| 3458 | } |
| 3459 | Err(err) => { |
| 3460 | app.config_profile = previous_profile; |
| 3461 | app.show_command_result( |
| 3462 | app.tr(MessageId::ProfileSwitchFailed) |
| 3463 | .replace("{name}", &profile) |
| 3464 | .replace("{error}", &err.to_string()), |
| 3465 | StatusToastLevel::Error, |
| 3466 | ); |
| 3467 | } |
| 3468 | } |
| 3469 | } |
| 3470 | AppAction::ShareSession { html } => { |
| 3471 | // The page was rendered and redacted by `/share confirm` |
| 3472 | // through the `/export` projection; only upload happens here. |
| 3473 | let share = crate::commands::share::perform_share(html).await; |
| 3474 | let level = if share.is_ok() { |
| 3475 | StatusToastLevel::Success |
| 3476 | } else { |
| 3477 | StatusToastLevel::Error |
| 3478 | }; |
| 3479 | let status = match share { |
| 3480 | Ok(url) => { |
| 3481 | format!("Session shared as a secret gist (unlisted, not private): {url}") |
| 3482 | } |
| 3483 | Err(err) => format!("Share failed: {err}"), |
| 3484 | }; |
| 3485 | app.add_message(HistoryCell::System { |
| 3486 | content: status.clone(), |
| 3487 | }); |
| 3488 | app.show_command_result(status, level); |
| 3489 | } |
| 3490 | } |
| 3491 | } |
| 3492 | |
| 3493 | Ok(false) |
| 3494 | } |
| 3495 | |
| 3496 | pub(crate) async fn apply_active_model_context_window_override( |
| 3497 | app: &mut App, |
| 3498 | engine_handle: &mut EngineHandle, |
| 3499 | config: &mut Config, |
| 3500 | tokens: Option<u32>, |
| 3501 | ) { |
| 3502 | let identity = match app.admitted_provider_identity().cloned() { |
| 3503 | Ok(identity) => identity, |
| 3504 | Err(reason) => { |
| 3505 | app.show_command_result(reason, StatusToastLevel::Error); |
| 3506 | return; |
| 3507 | } |
| 3508 | }; |
| 3509 | if app.auto_model |
| 3510 | || app.model.trim().is_empty() |
| 3511 | || app.model.trim().eq_ignore_ascii_case("auto") |
| 3512 | { |
| 3513 | app.show_command_result( |
| 3514 | "Select a concrete model before setting a per-model context window override." |
| 3515 | .to_string(), |
| 3516 | StatusToastLevel::Warning, |
| 3517 | ); |
| 3518 | return; |
| 3519 | } |
| 3520 | let model = app.model.clone(); |
| 3521 | let _ = persist_and_apply_model_context_window( |
| 3522 | app, |
| 3523 | engine_handle, |
| 3524 | config, |
| 3525 | &identity, |
| 3526 | &model, |
| 3527 | tokens, |
| 3528 | true, |
| 3529 | ) |
| 3530 | .await; |
| 3531 | } |
| 3532 | |
| 3533 | async fn persist_and_apply_model_context_window( |
| 3534 | app: &mut App, |
| 3535 | engine_handle: &mut EngineHandle, |
| 3536 | config: &mut Config, |
| 3537 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 3538 | model: &str, |
| 3539 | tokens: Option<u32>, |
| 3540 | emit_receipt: bool, |
| 3541 | ) -> bool { |
| 3542 | let mut next_config = config.clone(); |
| 3543 | let prepared = next_config |
| 3544 | .set_model_context_window_for(identity, model, tokens) |
| 3545 | .and_then(|next_identity| { |
| 3546 | let route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 3547 | &next_config, |
| 3548 | &next_identity, |
| 3549 | Some(model), |
| 3550 | )?; |
| 3551 | Ok((next_identity, route)) |
| 3552 | }); |
| 3553 | let (next_identity, route) = match prepared { |
| 3554 | Ok(prepared) => prepared, |
| 3555 | Err(err) => { |
| 3556 | app.show_command_result( |
| 3557 | format!("Failed to apply context window for {model}: {err}"), |
| 3558 | StatusToastLevel::Error, |
| 3559 | ); |
| 3560 | return false; |
| 3561 | } |
| 3562 | }; |
| 3563 | if let Err(err) = codewhale_runtime::config_persistence::persist_provider_model_context_window( |
| 3564 | app.config_path.as_deref(), |
| 3565 | config.account_profile.as_deref(), |
| 3566 | identity, |
| 3567 | model, |
| 3568 | tokens, |
| 3569 | ) { |
| 3570 | app.show_command_result( |
| 3571 | format!("Failed to save context window for {model}: {err}"), |
| 3572 | StatusToastLevel::Error, |
| 3573 | ); |
| 3574 | return false; |
| 3575 | } |
| 3576 | *config = next_config; |
| 3577 | app.set_provider_identity_record(next_identity.clone()); |
| 3578 | app.set_active_context_window_override(config, &next_identity); |
| 3579 | app.set_active_route_resolution( |
| 3580 | route.candidate.endpoint().base_url.clone(), |
| 3581 | route.candidate.limits(), |
| 3582 | route.context_window, |
| 3583 | ); |
| 3584 | app.update_model_compaction_budget(); |
| 3585 | apply_model_and_compaction_update( |
| 3586 | engine_handle, |
| 3587 | app.compaction_config(), |
| 3588 | app.mode, |
| 3589 | app.active_route_limits, |
| 3590 | ) |
| 3591 | .await; |
| 3592 | if emit_receipt { |
| 3593 | let effective = |
| 3594 | codewhale_util::utils::format_context_window(u64::from(app.effective_context_window())); |
| 3595 | let message = match tokens { |
| 3596 | Some(tokens) => format!( |
| 3597 | "Context window for {model} set to {effective} ({tokens} tokens; saved to model_context_windows)." |
| 3598 | ), |
| 3599 | None => format!("Context window override for {model} cleared; using {effective}."), |
| 3600 | }; |
| 3601 | app.show_command_result(message, StatusToastLevel::Success); |
| 3602 | } |
| 3603 | true |
| 3604 | } |
| 3605 | |
| 3606 | fn sync_active_session_after_catalog_refresh(app: &mut App, config: &Config) -> bool { |
| 3607 | let identity = app |
| 3608 | .admitted_provider_identity() |
| 3609 | .ok() |
| 3610 | .cloned() |
| 3611 | .or_else(|| config.active_provider_identity().ok()); |
| 3612 | let Some(identity) = identity else { |
| 3613 | return false; |
| 3614 | }; |
| 3615 | let model_selector = if app.auto_model { |
| 3616 | Some("auto") |
| 3617 | } else if !app.model.trim().is_empty() { |
| 3618 | Some(app.model.as_str()) |
| 3619 | } else { |
| 3620 | None |
| 3621 | }; |
| 3622 | let Ok(resolved) = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 3623 | config, |
| 3624 | &identity, |
| 3625 | model_selector, |
| 3626 | ) else { |
| 3627 | return false; |
| 3628 | }; |
| 3629 | app.set_active_context_window_override(config, &resolved.identity); |
| 3630 | app.set_active_route_resolution( |
| 3631 | resolved.candidate.endpoint().base_url.clone(), |
| 3632 | resolved.candidate.limits(), |
| 3633 | resolved.context_window, |
| 3634 | ); |
| 3635 | app.update_model_compaction_budget(); |
| 3636 | true |
| 3637 | } |
| 3638 | |
| 3639 | /// Commit a successfully loaded profile and its validated route as one snapshot. |
| 3640 | fn apply_validated_profile_config( |
| 3641 | app: &mut App, |
| 3642 | config: &mut Config, |
| 3643 | profile: &str, |
| 3644 | next_config: Config, |
| 3645 | route: &codewhale_engine::route_runtime::ValidatedRuntimeRoute, |
| 3646 | ) { |
| 3647 | *config = next_config; |
| 3648 | app.config_profile = Some(profile.to_string()); |
| 3649 | app.configured_models = config.custom_models.clone().unwrap_or_default(); |
| 3650 | app.refresh_notification_settings(config); |
| 3651 | app.set_provider_identity_record(route.identity.clone()); |
| 3652 | app.billing_presentation = codewhale_engine::route_billing::for_route(config, &route.identity); |
| 3653 | app.set_model_selection(route.model.clone()); |
| 3654 | app.set_active_context_window_override(config, &route.identity); |
| 3655 | app.set_active_route_resolution( |
| 3656 | route.candidate.endpoint().base_url.clone(), |
| 3657 | route.candidate.limits(), |
| 3658 | route.context_window, |
| 3659 | ); |
| 3660 | app.update_model_compaction_budget(); |
| 3661 | app.last_billed_input_tokens = None; |
| 3662 | app.session.last_prompt_tokens = None; |
| 3663 | app.session.last_completion_tokens = None; |
| 3664 | maybe_warn_context_pressure(app); |
| 3665 | } |
| 3666 | |
| 3667 | /// Open this workspace's `.codewhale/hooks.toml` in `$EDITOR`. |
| 3668 | /// |
| 3669 | /// The Hooks screen could only ever be read: it listed what was configured |
| 3670 | /// and offered no way to configure anything. Rather than grow a second |
| 3671 | /// authority over hook definitions inside the TUI, this hands the file to the |
| 3672 | /// editor the user already has, seeds it with a commented template the first |
| 3673 | /// time, and reloads the hook set on return so the screen reflects the edit |
| 3674 | /// immediately. |
| 3675 | fn edit_project_hooks_from_tui(terminal: &mut AppTerminal, app: &mut App, config: &Config) { |
| 3676 | // A home workspace may keep `.codewhale` on another volume behind a junction |
| 3677 | // the user made; the walk starts at the real directory there, so the user's |
| 3678 | // own relocation is not refused, while a link below it still is. Every other |
| 3679 | // workspace keeps itself as the root with `.codewhale` in the walked path. |
| 3680 | let (state_root, path) = codewhale_util::files::workspace_state_path( |
| 3681 | &app.workspace, |
| 3682 | std::path::Path::new("hooks.toml"), |
| 3683 | ); |
| 3684 | // The editor takes the spelling the user would type. A resolved root is a |
| 3685 | // verbatim path on Windows, which several terminal editors will not open, |
| 3686 | // and the file is the same one either way. |
| 3687 | let editor_path = app.workspace.join(".codewhale").join("hooks.toml"); |
| 3688 | // A link in `.codewhale` or at hooks.toml is never created through, and the |
| 3689 | // editor is not pointed at one: the file must really live in the state |
| 3690 | // directory. |
| 3691 | if let Err(error) = codewhale_util::files::reject_linked_path(&state_root, &path) { |
| 3692 | app.push_status_toast( |
| 3693 | format!("Could not use {}: {error}", path.display()), |
| 3694 | StatusToastLevel::Warning, |
| 3695 | Some(8_000), |
| 3696 | ); |
| 3697 | return; |
| 3698 | } |
| 3699 | if !path.exists() |
| 3700 | && let Err(error) = codewhale_util::fs_confined::write( |
| 3701 | &state_root, |
| 3702 | &path, |
| 3703 | codewhale_engine::hooks::PROJECT_HOOKS_TEMPLATE.as_bytes(), |
| 3704 | ) |
| 3705 | { |
| 3706 | app.push_status_toast( |
| 3707 | format!("Could not create {}: {error}", path.display()), |
| 3708 | StatusToastLevel::Warning, |
| 3709 | Some(8_000), |
| 3710 | ); |
| 3711 | return; |
| 3712 | } |
| 3713 | |
| 3714 | let outcome = crate::tui::external_editor::spawn_editor_for_path( |
| 3715 | terminal, |
| 3716 | app.use_mouse_capture, |
| 3717 | app.use_bracketed_paste, |
| 3718 | &editor_path, |
| 3719 | // Open the file, not a position in it: this edits hooks.toml whole. |
| 3720 | None, |
| 3721 | ); |
| 3722 | app.needs_redraw = true; |
| 3723 | |
| 3724 | match outcome { |
| 3725 | Ok(crate::tui::external_editor::EditorOutcome::Edited(_)) => { |
| 3726 | app.hooks = app.hooks.rebind( |
| 3727 | codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 3728 | config.hooks_config(), |
| 3729 | &app.workspace, |
| 3730 | Some(app.plugin_registry.as_ref()), |
| 3731 | ), |
| 3732 | app.workspace.clone(), |
| 3733 | ); |
| 3734 | app.runtime_services.hook_executor = Some(std::sync::Arc::new(app.hooks.clone())); |
| 3735 | let reloaded = app.hooks.config(); |
| 3736 | let mut content = format!( |
| 3737 | "Reloaded hooks from {} — {} configured.", |
| 3738 | editor_path.display(), |
| 3739 | reloaded.hooks.len() |
| 3740 | ); |
| 3741 | // Project hooks are executable repository configuration; an |
| 3742 | // untrusted workspace parses them and then ignores them, which is |
| 3743 | // a silent no-op unless it is said out loud. |
| 3744 | if !codewhale_engine::hooks::workspace_allows_project_hooks(&app.workspace) { |
| 3745 | content.push_str( |
| 3746 | " Project hooks are not approved for these exact contents. Use /hooks review, \ |
| 3747 | then /hooks approve <digest> after reviewing the commands.", |
| 3748 | ); |
| 3749 | } |
| 3750 | if !reloaded.problems.is_empty() { |
| 3751 | content.push_str(&format!( |
| 3752 | " {} entr{} rejected — see the Hooks screen.", |
| 3753 | reloaded.problems.len(), |
| 3754 | if reloaded.problems.len() == 1 { |
| 3755 | "y" |
| 3756 | } else { |
| 3757 | "ies" |
| 3758 | } |
| 3759 | )); |
| 3760 | } |
| 3761 | app.add_message(HistoryCell::System { content }); |
| 3762 | } |
| 3763 | Ok(crate::tui::external_editor::EditorOutcome::Unchanged) => { |
| 3764 | app.push_status_toast( |
| 3765 | "Hooks unchanged.".to_string(), |
| 3766 | StatusToastLevel::Info, |
| 3767 | Some(4_000), |
| 3768 | ); |
| 3769 | } |
| 3770 | Ok(crate::tui::external_editor::EditorOutcome::Cancelled) | Err(_) => { |
| 3771 | app.push_status_toast( |
| 3772 | format!("Editor did not save {}", path.display()), |
| 3773 | StatusToastLevel::Warning, |
| 3774 | Some(6_000), |
| 3775 | ); |
| 3776 | } |
| 3777 | } |
| 3778 | } |
| 3779 | |
| 3780 | pub(crate) fn apply_workspace_runtime_state(app: &mut App, config: &Config, workspace: PathBuf) { |
| 3781 | app.workspace = workspace.clone(); |
| 3782 | app.retire_event_notices(COORDINATION_LOCK_NOTICE); |
| 3783 | app.coordination_detail = None; |
| 3784 | app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace); |
| 3785 | app.refresh_agent_approved_plugins_notice(); |
| 3786 | for error in crate::commands::user_registry::install_plugin_registry( |
| 3787 | &workspace, |
| 3788 | app.plugin_registry.as_ref(), |
| 3789 | ) { |
| 3790 | tracing::warn!(target: "plugins", "{error}"); |
| 3791 | } |
| 3792 | // A plugin that failed to load used to be invisible until someone |
| 3793 | // happened to open /plugin. Surface a one-line hint instead of leaving |
| 3794 | // the discovery result buried in the trace log; warnings stay quiet. |
| 3795 | let plugin_load_errors = app |
| 3796 | .plugin_registry |
| 3797 | .diagnostics() |
| 3798 | .iter() |
| 3799 | .filter(|diagnostic| { |
| 3800 | diagnostic.level == codewhale_plugins::types::PluginDiagnosticLevel::Error |
| 3801 | }) |
| 3802 | .count(); |
| 3803 | if plugin_load_errors > 0 { |
| 3804 | app.show_command_result( |
| 3805 | if plugin_load_errors == 1 { |
| 3806 | "1 plugin failed to load — /plugin for details".to_string() |
| 3807 | } else { |
| 3808 | format!("{plugin_load_errors} plugins failed to load — /plugin for details") |
| 3809 | }, |
| 3810 | StatusToastLevel::Warning, |
| 3811 | ); |
| 3812 | } |
| 3813 | app.active_skill = None; |
| 3814 | app.active_skill_provenance = None; |
| 3815 | // Switching workspace reloads the hook set (project hooks are per-repo) |
| 3816 | // but stays inside the same TUI session, so the session id is preserved. |
| 3817 | app.hooks = app.hooks.rebind( |
| 3818 | codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 3819 | config.hooks_config(), |
| 3820 | &workspace, |
| 3821 | Some(app.plugin_registry.as_ref()), |
| 3822 | ), |
| 3823 | workspace.clone(), |
| 3824 | ); |
| 3825 | app.skills_dir = crate::tui::app::resolve_skills_dir(&workspace, &config.skills_dir(), config); |
| 3826 | app.skills_config = std::sync::Arc::new(config.skills_config()); |
| 3827 | app.project_context_pack_enabled = config.project_context_pack_enabled(); |
| 3828 | app.refresh_skill_cache(); |
| 3829 | app.workspace_context = None; |
| 3830 | app.workspace_is_linked_worktree = false; |
| 3831 | if let Ok(mut cell) = app.workspace_context_cell.lock() { |
| 3832 | *cell = None; |
| 3833 | } |
| 3834 | app.workspace_context_refreshed_at = None; |
| 3835 | app.file_tree = None; |
| 3836 | |
| 3837 | let shell_manager = codewhale_engine::tools::shell::new_shared_shell_manager(workspace); |
| 3838 | app.runtime_services.shell_manager = Some(shell_manager); |
| 3839 | app.runtime_services.hook_executor = Some(std::sync::Arc::new(app.hooks.clone())); |
| 3840 | } |
| 3841 | |
| 3842 | pub(crate) fn apply_hotbar_setup_saved( |
| 3843 | app: &mut App, |
| 3844 | config: &mut Config, |
| 3845 | bindings: Vec<codewhale_config::HotbarBindingToml>, |
| 3846 | ) { |
| 3847 | match codewhale_runtime::config_persistence::persist_hotbar_bindings( |
| 3848 | app.config_path.as_deref(), |
| 3849 | &bindings, |
| 3850 | ) { |
| 3851 | Ok(path) => { |
| 3852 | config.hotbar = Some(bindings); |
| 3853 | app.show_owned_command_result( |
| 3854 | StatusToastKind::HotbarSettings, |
| 3855 | format!("Hotbar bindings saved to {}", path.display()), |
| 3856 | StatusToastLevel::Success, |
| 3857 | ); |
| 3858 | } |
| 3859 | Err(err) => { |
| 3860 | app.show_owned_command_result( |
| 3861 | StatusToastKind::HotbarSettings, |
| 3862 | format!("Failed to save Hotbar bindings: {err}"), |
| 3863 | StatusToastLevel::Error, |
| 3864 | ); |
| 3865 | app.add_message(HistoryCell::System { |
| 3866 | content: format!("Failed to save Hotbar bindings: {err}"), |
| 3867 | }); |
| 3868 | } |
| 3869 | } |
| 3870 | app.needs_redraw = true; |
| 3871 | } |
| 3872 | |
| 3873 | pub(crate) fn settle_user_input_request(app: &mut App, tool_id: &str) -> bool { |
| 3874 | app.retire_action_notices(Some(tool_id)); |
| 3875 | let removed_view = app.view_stack.remove_user_input_by_id(tool_id); |
| 3876 | let matched = app |
| 3877 | .pending_user_input_prompt |
| 3878 | .as_ref() |
| 3879 | .is_some_and(|(id, _)| id == tool_id); |
| 3880 | if matched { |
| 3881 | app.pending_user_input_prompt = None; |
| 3882 | } |
| 3883 | app.needs_redraw |= removed_view || matched; |
| 3884 | matched |
| 3885 | } |
| 3886 | |
| 3887 | pub(crate) fn settle_pending_human_requests(app: &mut App) { |
| 3888 | if let Some((id, _)) = app.pending_user_input_prompt.as_ref() { |
| 3889 | let id = id.clone(); |
| 3890 | settle_user_input_request(app, &id); |
| 3891 | } |
| 3892 | // A completed/cancelled parent turn cannot still await an approval. |
| 3893 | // Children own their separate lifecycle and may legitimately remain live. |
| 3894 | for id in app.view_stack.tool_decision_request_ids() { |
| 3895 | if !codewhale_engine::tools::subagent::SubAgentManager::is_child_approval_id(&id) { |
| 3896 | crate::tui::pending_requests::retire(app, &id); |
| 3897 | app.retire_action_notices(Some(&id)); |
| 3898 | } |
| 3899 | } |
| 3900 | } |
| 3901 | |
| 3902 | /// The Engine's terminal tool event retires the exact request even when its |
| 3903 | /// presentation is filtered after a local cancel. An outer Code Mode call's |
| 3904 | /// completion cannot settle a different, inner request id. |
| 3905 | pub(crate) fn observe_human_request_settlement(app: &mut App, event: &EngineEvent) { |
| 3906 | match event { |
| 3907 | EngineEvent::UserInputClosed { id, .. } => { |
| 3908 | settle_user_input_request(app, id); |
| 3909 | } |
| 3910 | EngineEvent::ToolCallComplete { id, .. } => { |
| 3911 | settle_user_input_request(app, id); |
| 3912 | crate::tui::pending_requests::retire(app, id); |
| 3913 | } |
| 3914 | EngineEvent::TurnComplete { .. } |
| 3915 | if !(app.suppress_stream_events_until_turn_complete && app.is_loading) => |
| 3916 | { |
| 3917 | settle_pending_human_requests(app); |
| 3918 | } |
| 3919 | _ => {} |
| 3920 | } |
| 3921 | } |
| 3922 | |
| 3923 | pub(crate) fn note_human_decision_delivered(app: &mut App, tool_id: &str) { |
| 3924 | crate::tui::tool_routing::clear_exec_card_approval_hold(app, tool_id); |
| 3925 | if (app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))) |
| 3926 | && !app.suppress_stream_events_until_turn_complete |
| 3927 | && !crate::tui::pending_requests::is_foreign_child_request(app, tool_id) |
| 3928 | { |
| 3929 | // The reply resumes Engine work before its next event reaches this |
| 3930 | // frame. Give that work its own inactivity window after a long wait. |
| 3931 | app.turn_last_activity_at = Some(Instant::now()); |
| 3932 | } |
| 3933 | } |
| 3934 | |
| 3935 | pub(crate) fn apply_user_input_submission_result(app: &mut App, tool_id: &str, result: Result<()>) { |
| 3936 | match result { |
| 3937 | Ok(()) => { |
| 3938 | if settle_user_input_request(app, tool_id) { |
| 3939 | note_human_decision_delivered(app, tool_id); |
| 3940 | } |
| 3941 | } |
| 3942 | Err(error) => { |
| 3943 | tracing::warn!(tool_id, error = %error, "user input submit failed"); |
| 3944 | if let Some((id, request)) = app |
| 3945 | .pending_user_input_prompt |
| 3946 | .as_ref() |
| 3947 | .filter(|(id, _)| id == tool_id) |
| 3948 | .cloned() |
| 3949 | { |
| 3950 | app.view_stack |
| 3951 | .push(UserInputView::new(id, request, app.ui_locale)); |
| 3952 | } |
| 3953 | app.push_status_toast_record( |
| 3954 | StatusToast::new( |
| 3955 | app.tr(MessageId::NotificationInputSubmitFailed) |
| 3956 | .replace("{error}", &error.to_string()), |
| 3957 | StatusToastLevel::Error, |
| 3958 | Some(App::STICKY_ERROR_TTL_MS), |
| 3959 | ) |
| 3960 | .for_event(format!("input-submit:{tool_id}")), |
| 3961 | ); |
| 3962 | } |
| 3963 | } |
| 3964 | } |
| 3965 | |
| 3966 | pub(crate) async fn apply_approval_decision( |
| 3967 | app: &mut App, |
| 3968 | engine_handle: &mut EngineHandle, |
| 3969 | config: &mut Config, |
| 3970 | event: ApprovalDecisionEvent, |
| 3971 | ) -> bool { |
| 3972 | if let Some(handled) = crate::tui::external_agent::handle_external_approval_decision( |
| 3973 | app, |
| 3974 | &event.tool_id, |
| 3975 | &event.decision, |
| 3976 | ) { |
| 3977 | return handled; |
| 3978 | } |
| 3979 | let approved = matches!( |
| 3980 | event.decision, |
| 3981 | ReviewDecision::Approved | ReviewDecision::ApprovedForSession |
| 3982 | ); |
| 3983 | let result = match event.decision { |
| 3984 | ReviewDecision::Abort |
| 3985 | if codewhale_engine::tools::subagent::SubAgentManager::is_child_approval_id( |
| 3986 | &event.tool_id, |
| 3987 | ) => |
| 3988 | { |
| 3989 | return false; |
| 3990 | } |
| 3991 | ReviewDecision::Abort => { |
| 3992 | engine_handle.cancel(); |
| 3993 | mark_active_turn_cancelled_locally(app); |
| 3994 | app.show_command_result( |
| 3995 | parent_stop_status(app, "Request cancelled"), |
| 3996 | StatusToastLevel::Warning, |
| 3997 | ); |
| 3998 | return false; |
| 3999 | } |
| 4000 | ReviewDecision::Approved | ReviewDecision::ApprovedForSession => { |
| 4001 | engine_handle.approve_tool_call(event.tool_id.clone()).await |
| 4002 | } |
| 4003 | ReviewDecision::Denied if event.timed_out => { |
| 4004 | engine_handle |
| 4005 | .deny_tool_call_timed_out(event.tool_id.clone()) |
| 4006 | .await |
| 4007 | } |
| 4008 | ReviewDecision::Denied => engine_handle.deny_tool_call(event.tool_id.clone()).await, |
| 4009 | }; |
| 4010 | if let Err(error) = result { |
| 4011 | app.show_command_result( |
| 4012 | format!("Approval was not accepted: {error}"), |
| 4013 | StatusToastLevel::Error, |
| 4014 | ); |
| 4015 | return false; |
| 4016 | } |
| 4017 | if event.decision == ReviewDecision::ApprovedForSession { |
| 4018 | // Only the lossy grouping key is stored: a session grant is scoped to |
| 4019 | // the command family (e.g. `shell:git status`), never to the whole |
| 4020 | // tool — approving one shell command must not approve every shell |
| 4021 | // command for the session (ops R2). The tool name is recorded as |
| 4022 | // audit evidence, not as a grant. |
| 4023 | codewhale_runtime::audit::log_sensitive_event( |
| 4024 | "tool.approval.session_grant", |
| 4025 | serde_json::json!({ |
| 4026 | "tool_name": event.tool_name, |
| 4027 | "grouping_key": event.approval_grouping_key, |
| 4028 | }), |
| 4029 | ); |
| 4030 | app.approval_session_approved |
| 4031 | .insert(event.approval_grouping_key.clone()); |
| 4032 | } |
| 4033 | |
| 4034 | let rules_persisted = matches!( |
| 4035 | event.decision, |
| 4036 | ReviewDecision::Approved | ReviewDecision::ApprovedForSession |
| 4037 | ) && !event.persistent_rules.is_empty() |
| 4038 | && !event.timed_out |
| 4039 | && persist_rules_from_approval(app, config, &event.persistent_rules); |
| 4040 | |
| 4041 | if event.decision == ReviewDecision::Denied && !event.timed_out { |
| 4042 | app.approval_session_denied.insert(event.approval_key); |
| 4043 | } |
| 4044 | crate::tui::pending_requests::resolve(app, &event.tool_id); |
| 4045 | app.remote_control |
| 4046 | .resolve_pending_approval(&event.tool_id, approved); |
| 4047 | note_human_decision_delivered(app, &event.tool_id); |
| 4048 | app.retire_action_notices(Some(&event.tool_id)); |
| 4049 | if !event.timed_out |
| 4050 | && let Some(subject) = event.subject |
| 4051 | { |
| 4052 | let (outcome, receipt_subject) = if event.decision == ReviewDecision::Approved |
| 4053 | && rules_persisted |
| 4054 | && event |
| 4055 | .persistent_rules |
| 4056 | .iter() |
| 4057 | .any(|rule| rule.action == codewhale_execpolicy::PermissionAction::Allow) |
| 4058 | { |
| 4059 | let pattern = crate::tui::approval::format_allow_rules_pattern(&event.persistent_rules) |
| 4060 | .unwrap_or(subject); |
| 4061 | ( |
| 4062 | crate::tui::history::ApprovalReceiptOutcome::AlwaysAllowedInRepo, |
| 4063 | pattern, |
| 4064 | ) |
| 4065 | } else { |
| 4066 | let outcome = match event.decision { |
| 4067 | ReviewDecision::Approved => { |
| 4068 | crate::tui::history::ApprovalReceiptOutcome::AllowedOnce |
| 4069 | } |
| 4070 | ReviewDecision::ApprovedForSession => { |
| 4071 | crate::tui::history::ApprovalReceiptOutcome::AllowedInConversation |
| 4072 | } |
| 4073 | ReviewDecision::Denied => crate::tui::history::ApprovalReceiptOutcome::Denied, |
| 4074 | ReviewDecision::Abort => unreachable!(), |
| 4075 | }; |
| 4076 | (outcome, subject) |
| 4077 | }; |
| 4078 | let receipt = HistoryCell::ApprovalReceipt(crate::tui::history::ApprovalReceiptCell::new( |
| 4079 | outcome, |
| 4080 | receipt_subject, |
| 4081 | )); |
| 4082 | if let Some(active_cell) = app.active_cell.as_mut() { |
| 4083 | active_cell.push_untracked(receipt); |
| 4084 | app.bump_active_cell_revision(); |
| 4085 | } else { |
| 4086 | app.add_message(receipt); |
| 4087 | } |
| 4088 | } |
| 4089 | true |
| 4090 | } |
| 4091 | |
| 4092 | pub(crate) fn validate_setup_runtime_preset( |
| 4093 | app: &App, |
| 4094 | config: &Config, |
| 4095 | preset: crate::tui::setup::SetupRuntimePreset, |
| 4096 | ) -> Result<()> { |
| 4097 | if let Some(source) = config.runtime_preset_blocker( |
| 4098 | app.config_path.as_deref(), |
| 4099 | app.config_profile.as_deref(), |
| 4100 | &app.workspace, |
| 4101 | ) { |
| 4102 | anyhow::bail!( |
| 4103 | "Runtime presets cannot override {source}; change that controlling source first" |
| 4104 | ); |
| 4105 | } |
| 4106 | if preset == crate::tui::setup::SetupRuntimePreset::HighTrustLocal { |
| 4107 | let approval = config.approval_policy_control( |
| 4108 | app.config_path.as_deref(), |
| 4109 | app.config_profile.as_deref(), |
| 4110 | &app.workspace, |
| 4111 | ); |
| 4112 | if !approval.editable_root() { |
| 4113 | anyhow::bail!( |
| 4114 | "Full Access cannot override {}; change that controlling source first", |
| 4115 | approval.label() |
| 4116 | ); |
| 4117 | } |
| 4118 | } |
| 4119 | Ok(()) |
| 4120 | } |
| 4121 | |
| 4122 | pub(crate) fn persist_setup_runtime_preset( |
| 4123 | app_config_path: Option<PathBuf>, |
| 4124 | preset: crate::tui::setup::SetupRuntimePreset, |
| 4125 | state: codewhale_config::SetupState, |
| 4126 | ) -> Result<()> { |
| 4127 | let settings_path = Settings::path().context("failed to resolve settings path")?; |
| 4128 | let settings_snapshot = RuntimePresetFileSnapshot::capture(settings_path)?; |
| 4129 | // The preset's settings read, its config-document write, and its settings |
| 4130 | // write are one durable transaction with file-snapshot rollback. Hold the |
| 4131 | // settings transaction lock across all of it so a concurrent writer (a queued |
| 4132 | // mode/thinking drain, the Shift+Tab posture write) can neither be lost by |
| 4133 | // this save nor be reverted by the rollback. |
| 4134 | // Every durable write happens inside this closure, so the settings lock is |
| 4135 | // released before live state moves below. |
| 4136 | codewhale_runtime::settings::with_settings_transaction(|settings_transaction| { |
| 4137 | let mut settings = settings_transaction |
| 4138 | .load() |
| 4139 | .context("failed to load settings")?; |
| 4140 | settings.default_mode = preset.default_mode().to_string(); |
| 4141 | settings.permission_posture = Some(preset.permission_posture().to_string()); |
| 4142 | |
| 4143 | // Persist into the same file Config::load actually selected. A missing |
| 4144 | // explicit env target remains authoritative for both reads and writes; |
| 4145 | // an invalid target fails here instead of selecting a different file. |
| 4146 | let selected_config_path = |
| 4147 | codewhale_runtime::config::resolve_load_config_path(app_config_path.clone())? |
| 4148 | .or_else(|| app_config_path.clone()); |
| 4149 | let config_path = codewhale_runtime::config_persistence::config_toml_path( |
| 4150 | selected_config_path.as_deref(), |
| 4151 | ) |
| 4152 | .context("failed to resolve config path")?; |
| 4153 | let config_snapshot = RuntimePresetFileSnapshot::capture(config_path.clone())?; |
| 4154 | if let Err(error) = codewhale_runtime::config_persistence::mutate_config_document( |
| 4155 | &config_path, |
| 4156 | |document| { |
| 4157 | if let Some(policy) = preset.approval_policy() { |
| 4158 | codewhale_runtime::config_persistence::set_document_value( |
| 4159 | document, |
| 4160 | &["approval_policy"], |
| 4161 | policy, |
| 4162 | )?; |
| 4163 | } else { |
| 4164 | codewhale_runtime::config_persistence::unset_document_value( |
| 4165 | document, |
| 4166 | &["approval_policy"], |
| 4167 | )?; |
| 4168 | } |
| 4169 | codewhale_runtime::config_persistence::set_document_value( |
| 4170 | document, |
| 4171 | &["allow_shell"], |
| 4172 | preset.allow_shell(), |
| 4173 | )?; |
| 4174 | codewhale_runtime::config_persistence::set_document_value( |
| 4175 | document, |
| 4176 | &["sandbox_mode"], |
| 4177 | preset.sandbox_mode(), |
| 4178 | ) |
| 4179 | }, |
| 4180 | ) |
| 4181 | .context("failed to persist runtime posture") |
| 4182 | { |
| 4183 | return Err(runtime_preset_error_with_rollback( |
| 4184 | error, |
| 4185 | &[&settings_snapshot, &config_snapshot], |
| 4186 | )); |
| 4187 | } |
| 4188 | if let Err(error) = settings_transaction |
| 4189 | .save(&settings) |
| 4190 | .context("failed to save settings") |
| 4191 | { |
| 4192 | return Err(runtime_preset_error_with_rollback( |
| 4193 | error, |
| 4194 | &[&settings_snapshot, &config_snapshot], |
| 4195 | )); |
| 4196 | } |
| 4197 | if let Err(error) = state |
| 4198 | .save() |
| 4199 | .context("failed to persist setup runtime posture state") |
| 4200 | { |
| 4201 | return Err(runtime_preset_error_with_rollback( |
| 4202 | error, |
| 4203 | &[&settings_snapshot, &config_snapshot], |
| 4204 | )); |
| 4205 | } |
| 4206 | Ok(()) |
| 4207 | }) |
| 4208 | } |
| 4209 | |
| 4210 | pub(crate) fn commit_setup_runtime_preset_live_state( |
| 4211 | app: &mut App, |
| 4212 | config: &mut Config, |
| 4213 | preset: crate::tui::setup::SetupRuntimePreset, |
| 4214 | ) -> String { |
| 4215 | // Durable writes succeeded as one transaction. Only now may live state |
| 4216 | // move to the new posture. |
| 4217 | if let Some(policy) = preset.approval_policy() { |
| 4218 | config.approval_policy = Some(policy.to_string()); |
| 4219 | app.mark_approval_policy_locked(); |
| 4220 | } else { |
| 4221 | config.approval_policy = None; |
| 4222 | app.clear_saved_approval_policy_lock(); |
| 4223 | } |
| 4224 | config.allow_shell = Some(preset.allow_shell()); |
| 4225 | config.sandbox_mode = Some(preset.sandbox_mode().to_string()); |
| 4226 | app.configured_sandbox_mode = config.sandbox_mode.clone(); |
| 4227 | app.configured_sandbox_network = config.sandbox_network_access; |
| 4228 | |
| 4229 | let approval_mode = ApprovalMode::from_config_value( |
| 4230 | preset |
| 4231 | .approval_policy() |
| 4232 | .unwrap_or(preset.permission_posture()), |
| 4233 | ) |
| 4234 | .unwrap_or(ApprovalMode::Suggest); |
| 4235 | let trust_mode = match preset { |
| 4236 | crate::tui::setup::SetupRuntimePreset::AskFirst => false, |
| 4237 | crate::tui::setup::SetupRuntimePreset::NormalAgent => app.agent_trust_baseline(), |
| 4238 | crate::tui::setup::SetupRuntimePreset::HighTrustLocal => true, |
| 4239 | }; |
| 4240 | app.set_agent_runtime_baseline(preset.allow_shell(), trust_mode, approval_mode); |
| 4241 | let mode = AppMode::from_setting(preset.default_mode()); |
| 4242 | app.set_mode(mode); |
| 4243 | app.needs_redraw = true; |
| 4244 | |
| 4245 | format!("Applied {}.", preset.result_summary()) |
| 4246 | } |
| 4247 | |
| 4248 | #[cfg(test)] |
| 4249 | pub(crate) fn apply_setup_runtime_preset( |
| 4250 | app: &mut App, |
| 4251 | config: &mut Config, |
| 4252 | preset: crate::tui::setup::SetupRuntimePreset, |
| 4253 | state: codewhale_config::SetupState, |
| 4254 | ) -> Result<String> { |
| 4255 | validate_setup_runtime_preset(app, config, preset)?; |
| 4256 | persist_setup_runtime_preset(app.config_path.clone(), preset, state)?; |
| 4257 | Ok(commit_setup_runtime_preset_live_state(app, config, preset)) |
| 4258 | } |
| 4259 | |
| 4260 | pub(crate) fn apply_backtrack(app: &mut App, depth: usize) { |
| 4261 | let Some(history_idx) = find_user_cell_index_from_tail(app, depth) else { |
| 4262 | app.show_command_result( |
| 4263 | "Backtrack target no longer present".to_string(), |
| 4264 | StatusToastLevel::Warning, |
| 4265 | ); |
| 4266 | return; |
| 4267 | }; |
| 4268 | |
| 4269 | // Snapshot the user text before truncating so we can refill the |
| 4270 | // composer. |
| 4271 | let user_text = match app.history.get(history_idx) { |
| 4272 | Some(HistoryCell::User { content }) => content.clone(), |
| 4273 | _ => String::new(), |
| 4274 | }; |
| 4275 | |
| 4276 | // Trim the visible transcript at the chosen user cell. Per-cell |
| 4277 | // revisions and tool-cell maps are kept consistent through |
| 4278 | // `App::truncate_history_to`. |
| 4279 | app.truncate_history_to(history_idx); |
| 4280 | |
| 4281 | // Hand the dropped text back to the user so they can edit + resend. |
| 4282 | app.input = user_text; |
| 4283 | app.cursor_position = app.input.chars().count(); |
| 4284 | |
| 4285 | // Close the overlay, refresh sticky-tail flag, and surface a hint. |
| 4286 | if app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) { |
| 4287 | app.view_stack.pop(); |
| 4288 | } |
| 4289 | // Backtrack rewinds the conversation only. State the file fact first, |
| 4290 | // and name the command that rolls the files back. |
| 4291 | app.show_command_result( |
| 4292 | "Files not changed. Use /restore. Conversation rewound.".to_string(), |
| 4293 | StatusToastLevel::Info, |
| 4294 | ); |
| 4295 | app.scroll_to_bottom(); |
| 4296 | app.mark_history_updated(); |
| 4297 | app.needs_redraw = true; |
| 4298 | } |
| 4299 | |
| 4300 | pub(crate) async fn apply_provider_picker_custom_provider( |
| 4301 | app: &mut App, |
| 4302 | engine_handle: &mut EngineHandle, |
| 4303 | config: &mut Config, |
| 4304 | provider_id: String, |
| 4305 | base_url: String, |
| 4306 | model: Option<String>, |
| 4307 | api_key_env: Option<String>, |
| 4308 | ) -> bool { |
| 4309 | let written = match codewhale_runtime::config_persistence::persist_custom_provider( |
| 4310 | app.config_path.as_deref(), |
| 4311 | &provider_id, |
| 4312 | &base_url, |
| 4313 | model.as_deref(), |
| 4314 | api_key_env.as_deref(), |
| 4315 | ) { |
| 4316 | Ok(path) => path, |
| 4317 | Err(err) => { |
| 4318 | app.add_message(HistoryCell::System { |
| 4319 | content: format!("Failed to save custom provider {provider_id}: {err}"), |
| 4320 | }); |
| 4321 | app.show_route_receipt( |
| 4322 | "Custom provider was not saved.".to_string(), |
| 4323 | StatusToastLevel::Warning, |
| 4324 | ); |
| 4325 | return false; |
| 4326 | } |
| 4327 | }; |
| 4328 | |
| 4329 | config.provider = Some(provider_id.clone()); |
| 4330 | let entry = config |
| 4331 | .providers |
| 4332 | .get_or_insert_with(ProvidersConfig::default) |
| 4333 | .custom |
| 4334 | .entry(provider_id.clone()) |
| 4335 | .or_default(); |
| 4336 | entry.kind = Some("openai-compatible".to_string()); |
| 4337 | entry.base_url = Some(base_url.trim().trim_end_matches('/').to_string()); |
| 4338 | if provider_id == "ds4" && codewhale_runtime::config::base_url_uses_local_host(&base_url) { |
| 4339 | entry.context_window = Some(100_000); |
| 4340 | } |
| 4341 | entry.model = model.clone().and_then(|value| { |
| 4342 | let value = value.trim().to_string(); |
| 4343 | (!value.is_empty()).then_some(value) |
| 4344 | }); |
| 4345 | let keyless_local = provider_id == "ds4" |
| 4346 | && api_key_env |
| 4347 | .as_deref() |
| 4348 | .is_none_or(|value| value.trim().is_empty()) |
| 4349 | && codewhale_runtime::config::base_url_uses_local_host(&base_url); |
| 4350 | entry.api_key_env = api_key_env.and_then(|value| { |
| 4351 | let value = value.trim().to_string(); |
| 4352 | (!value.is_empty()).then_some(value) |
| 4353 | }); |
| 4354 | entry.auth_mode = keyless_local.then(|| "none".to_string()); |
| 4355 | |
| 4356 | app.show_route_receipt( |
| 4357 | format!( |
| 4358 | "Custom provider {provider_id} saved to {}", |
| 4359 | written.display() |
| 4360 | ), |
| 4361 | StatusToastLevel::Success, |
| 4362 | ); |
| 4363 | let identity = match config.resolve_provider_pin_identity(&provider_id) { |
| 4364 | Ok(identity) if identity.provider == ProviderKind::Custom => identity, |
| 4365 | Ok(_) => { |
| 4366 | app.push_status_toast( |
| 4367 | "Saved custom route changed transport identity.", |
| 4368 | StatusToastLevel::Error, |
| 4369 | Some(8_000), |
| 4370 | ); |
| 4371 | sync_config_provider_from_app(config, app); |
| 4372 | return false; |
| 4373 | } |
| 4374 | Err(reason) => { |
| 4375 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4376 | sync_config_provider_from_app(config, app); |
| 4377 | return false; |
| 4378 | } |
| 4379 | }; |
| 4380 | let switched = switch_provider(app, engine_handle, config, identity, model).await; |
| 4381 | if !switched { |
| 4382 | sync_config_provider_from_app(config, app); |
| 4383 | } |
| 4384 | switched |
| 4385 | } |
| 4386 | |
| 4387 | async fn reopen_provider_picker_list( |
| 4388 | app: &mut App, |
| 4389 | engine_handle: &mut EngineHandle, |
| 4390 | config: &Config, |
| 4391 | selected_provider_id: Option<String>, |
| 4392 | catalog_view: bool, |
| 4393 | ) { |
| 4394 | let runtime_status = query_provider_runtime_status(engine_handle).await; |
| 4395 | app.provider_picker_memory = Some(crate::tui::app::ProviderPickerMemory { |
| 4396 | catalog_view, |
| 4397 | selected_provider_id, |
| 4398 | }); |
| 4399 | app.view_stack.push( |
| 4400 | crate::tui::provider_picker::ProviderPickerView::new_with_runtime_status_and_memory( |
| 4401 | app.api_provider, |
| 4402 | config, |
| 4403 | runtime_status, |
| 4404 | app.provider_picker_memory.as_ref(), |
| 4405 | ) |
| 4406 | .with_locale(app.ui_locale) |
| 4407 | .with_provider_health(&app.provider_health), |
| 4408 | ); |
| 4409 | app.needs_redraw = true; |
| 4410 | } |
| 4411 | |
| 4412 | pub(crate) async fn apply_provider_picker_test_connection( |
| 4413 | app: &mut App, |
| 4414 | engine_handle: &mut EngineHandle, |
| 4415 | config: &mut Config, |
| 4416 | identity: codewhale_runtime::config::ProviderIdentity, |
| 4417 | catalog_view: bool, |
| 4418 | ) { |
| 4419 | apply_provider_picker_test_connection_with_verifier( |
| 4420 | app, |
| 4421 | engine_handle, |
| 4422 | config, |
| 4423 | identity, |
| 4424 | catalog_view, |
| 4425 | &LiveProviderKeyVerifier, |
| 4426 | ) |
| 4427 | .await; |
| 4428 | } |
| 4429 | |
| 4430 | /// One plain sentence for a key the provider did not accept, with the next |
| 4431 | /// step, in place of the provider's raw reply (#6566). Only a failure with no |
| 4432 | /// plain reading keeps a sanitized, bounded excerpt of that reply. |
| 4433 | fn plain_key_verification_error(app: &App, reason: &str, api_key: &str) -> String { |
| 4434 | use codewhale_error_taxonomy::ErrorCategory; |
| 4435 | match provider_verification_error_category(reason) { |
| 4436 | ErrorCategory::Authentication => app.tr(MessageId::ProviderKeyRejected).into_owned(), |
| 4437 | ErrorCategory::Authorization => app.tr(MessageId::ProviderKeyForbidden).into_owned(), |
| 4438 | ErrorCategory::Network | ErrorCategory::Timeout => { |
| 4439 | app.tr(MessageId::ProviderKeyUnreachable).into_owned() |
| 4440 | } |
| 4441 | _ => app |
| 4442 | .tr(MessageId::ProviderKeyCheckFailed) |
| 4443 | .replace("{reason}", &sanitize_probe_status(reason, api_key)), |
| 4444 | } |
| 4445 | } |
| 4446 | |
| 4447 | fn sanitize_probe_status(reason: &str, api_key: &str) -> String { |
| 4448 | let mut text = reason.to_string(); |
| 4449 | if let Some(rest) = reason.strip_prefix("HTTP ") |
| 4450 | && let Some((code, body)) = rest.split_once(':') |
| 4451 | && let Ok(status) = code.trim().parse::<u16>() |
| 4452 | { |
| 4453 | text = codewhale_engine::llm_client::sanitize_http_error_body(None, status, body.trim()); |
| 4454 | } |
| 4455 | let secret = api_key.trim(); |
| 4456 | if !secret.is_empty() { |
| 4457 | text = text.replace(secret, "***"); |
| 4458 | } |
| 4459 | codewhale_util::utils::truncate_with_ellipsis(text.trim(), 120, "…") |
| 4460 | } |
| 4461 | |
| 4462 | pub(crate) async fn apply_provider_picker_test_connection_with_verifier( |
| 4463 | app: &mut App, |
| 4464 | engine_handle: &mut EngineHandle, |
| 4465 | config: &mut Config, |
| 4466 | identity: codewhale_runtime::config::ProviderIdentity, |
| 4467 | catalog_view: bool, |
| 4468 | verifier: &dyn ProviderKeyVerifier, |
| 4469 | ) { |
| 4470 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 4471 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4472 | return; |
| 4473 | } |
| 4474 | let provider = identity.provider; |
| 4475 | let mut scoped_config = config.clone(); |
| 4476 | if let Err(reason) = scoped_config.scope_to_provider_identity(&identity) { |
| 4477 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4478 | return; |
| 4479 | } |
| 4480 | let selected_id = Some(identity.key.to_string()); |
| 4481 | let base_url = scoped_config.active_route_base_url(); |
| 4482 | if !codewhale_engine::client::provider_api_key_verification_is_observed_for_route( |
| 4483 | provider, &base_url, |
| 4484 | ) { |
| 4485 | app.push_status_toast( |
| 4486 | app.tr(MessageId::ProviderTestConnectionNoEndpoint) |
| 4487 | .replace("{provider}", identity.key.as_str()), |
| 4488 | StatusToastLevel::Warning, |
| 4489 | Some(8_000), |
| 4490 | ); |
| 4491 | reopen_provider_picker_list(app, engine_handle, config, selected_id, catalog_view).await; |
| 4492 | return; |
| 4493 | } |
| 4494 | let api_key = match scoped_config.active_route_api_key_read_only() { |
| 4495 | Ok(key) if !key.trim().is_empty() => key, |
| 4496 | _ => { |
| 4497 | app.push_status_toast( |
| 4498 | app.tr(MessageId::ProviderTestConnectionNeedKey) |
| 4499 | .replace("{provider}", identity.key.as_str()), |
| 4500 | StatusToastLevel::Warning, |
| 4501 | Some(8_000), |
| 4502 | ); |
| 4503 | reopen_provider_picker_list(app, engine_handle, config, selected_id, catalog_view) |
| 4504 | .await; |
| 4505 | return; |
| 4506 | } |
| 4507 | }; |
| 4508 | let model = scoped_config.default_model(); |
| 4509 | let outcome = verifier.verify(provider, &api_key, &base_url).await; |
| 4510 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 4511 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4512 | return; |
| 4513 | } |
| 4514 | match outcome { |
| 4515 | Ok(roster) => { |
| 4516 | if scoped_config |
| 4517 | .active_route_api_key_read_only() |
| 4518 | .is_ok_and(|current| current == api_key) |
| 4519 | { |
| 4520 | publish_verified_roster(&scoped_config, &identity, &base_url, roster); |
| 4521 | } |
| 4522 | app.provider_health.record_models_probe_success( |
| 4523 | &scoped_config, |
| 4524 | &identity, |
| 4525 | &model, |
| 4526 | codewhale_config::credentials::CredentialGeneration::derive( |
| 4527 | &base_url, |
| 4528 | &codewhale_secrets::normalize_api_key(&api_key), |
| 4529 | ), |
| 4530 | ); |
| 4531 | app.push_status_toast( |
| 4532 | app.tr(MessageId::ProviderConnectionChecked).into_owned(), |
| 4533 | StatusToastLevel::Success, |
| 4534 | Some(8_000), |
| 4535 | ); |
| 4536 | } |
| 4537 | Err(reason) => { |
| 4538 | let safe = sanitize_probe_status(&reason, &api_key); |
| 4539 | app.provider_health.record_models_probe_failure( |
| 4540 | &scoped_config, |
| 4541 | &identity, |
| 4542 | &model, |
| 4543 | codewhale_config::credentials::CredentialGeneration::derive( |
| 4544 | &base_url, |
| 4545 | &codewhale_secrets::normalize_api_key(&api_key), |
| 4546 | ), |
| 4547 | provider_verification_error_category(&reason), |
| 4548 | &safe, |
| 4549 | ); |
| 4550 | app.push_status_toast( |
| 4551 | app.tr(MessageId::ProviderTestConnectionFailed) |
| 4552 | .replace("{provider}", identity.key.as_str()) |
| 4553 | .replace("{error}", &safe), |
| 4554 | StatusToastLevel::Error, |
| 4555 | Some(8_000), |
| 4556 | ); |
| 4557 | } |
| 4558 | } |
| 4559 | reopen_provider_picker_list(app, engine_handle, config, selected_id, catalog_view).await; |
| 4560 | } |
| 4561 | |
| 4562 | pub(crate) async fn apply_provider_picker_api_key( |
| 4563 | app: &mut App, |
| 4564 | engine_handle: &mut EngineHandle, |
| 4565 | config: &mut Config, |
| 4566 | identity: codewhale_runtime::config::ProviderIdentity, |
| 4567 | api_key: String, |
| 4568 | base_url: Option<String>, |
| 4569 | ) { |
| 4570 | apply_provider_picker_api_key_with_verifier( |
| 4571 | app, |
| 4572 | engine_handle, |
| 4573 | config, |
| 4574 | identity, |
| 4575 | api_key, |
| 4576 | base_url, |
| 4577 | &LiveProviderKeyVerifier, |
| 4578 | ) |
| 4579 | .await; |
| 4580 | } |
| 4581 | |
| 4582 | pub(crate) async fn apply_provider_picker_api_key_with_verifier( |
| 4583 | app: &mut App, |
| 4584 | engine_handle: &mut EngineHandle, |
| 4585 | config: &mut Config, |
| 4586 | identity: codewhale_runtime::config::ProviderIdentity, |
| 4587 | api_key: String, |
| 4588 | base_url_override: Option<String>, |
| 4589 | verifier: &dyn ProviderKeyVerifier, |
| 4590 | ) { |
| 4591 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 4592 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4593 | return; |
| 4594 | } |
| 4595 | let provider = identity.provider; |
| 4596 | let mut scoped_config = config.clone(); |
| 4597 | if let Err(reason) = scoped_config.scope_to_provider_identity(&identity) { |
| 4598 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4599 | return; |
| 4600 | } |
| 4601 | // #4526: a billing route chosen in the wizard is applied to the scoped |
| 4602 | // clone only, so the key is probed against the endpoint it will be saved |
| 4603 | // for without touching the on-disk config before the user confirms. |
| 4604 | if let Some(base_url) = base_url_override.clone() |
| 4605 | && let Err(reason) = scoped_config.set_provider_base_url_override(&identity, Some(base_url)) |
| 4606 | { |
| 4607 | app.push_status_toast(reason.to_string(), StatusToastLevel::Error, Some(8_000)); |
| 4608 | return; |
| 4609 | } |
| 4610 | // #3875: verify the key against the provider before opening the rest of |
| 4611 | // the guided flow. Nothing is persisted until the confirm stage. |
| 4612 | // Resolve the effective route, including compatibility routes whose |
| 4613 | // endpoint is selected by auth mode (notably a legacy Kimi CLI import). |
| 4614 | // This prevents a replacement Kimi Code API key from being probed against |
| 4615 | // the ordinary Moonshot endpoint. |
| 4616 | let base_url = scoped_config.active_route_base_url(); |
| 4617 | let outcome = verifier.verify(provider, &api_key, &base_url).await; |
| 4618 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 4619 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 4620 | return; |
| 4621 | } |
| 4622 | match outcome { |
| 4623 | Ok(roster) => { |
| 4624 | // Before the model pick reads the route roster: list what this |
| 4625 | // key can call today, not catalog rows the provider has retired. |
| 4626 | if scoped_config |
| 4627 | .set_provider_api_key_override(&identity, Some(api_key.clone())) |
| 4628 | .is_ok() |
| 4629 | && scoped_config |
| 4630 | .active_route_api_key_read_only() |
| 4631 | .is_ok_and(|current| current == codewhale_secrets::normalize_api_key(&api_key)) |
| 4632 | { |
| 4633 | publish_verified_roster(&scoped_config, &identity, &base_url, roster); |
| 4634 | } |
| 4635 | // Keep the readiness row aligned with the live check the wizard |
| 4636 | // just completed. This probe only proves the endpoint and |
| 4637 | // credentials are reachable: the model is chosen after the probe, |
| 4638 | // so record a distinct connection-checked state rather than |
| 4639 | // claiming the model is ready. Providers without a real `/models` |
| 4640 | // probe remain unchecked. |
| 4641 | if codewhale_engine::client::provider_api_key_verification_is_observed_for_route( |
| 4642 | provider, &base_url, |
| 4643 | ) { |
| 4644 | let verified_model = scoped_config.default_model(); |
| 4645 | app.provider_health.record_models_probe_success( |
| 4646 | &scoped_config, |
| 4647 | &identity, |
| 4648 | &verified_model, |
| 4649 | codewhale_config::credentials::CredentialGeneration::derive( |
| 4650 | &base_url, |
| 4651 | &codewhale_secrets::normalize_api_key(&api_key), |
| 4652 | ), |
| 4653 | ); |
| 4654 | } |
| 4655 | // Key is valid — continue the guided flow at model pick without |
| 4656 | // writing the secret yet. |
| 4657 | let runtime_status = query_provider_runtime_status(engine_handle).await; |
| 4658 | if let Some(picker) = |
| 4659 | crate::tui::provider_picker::ProviderPickerView::new_for_model_pick_after_validation( |
| 4660 | app.api_provider, |
| 4661 | &identity, |
| 4662 | &scoped_config, |
| 4663 | runtime_status, |
| 4664 | api_key, |
| 4665 | base_url_override, |
| 4666 | ) |
| 4667 | .map(|picker| { |
| 4668 | picker |
| 4669 | .with_locale(app.ui_locale) |
| 4670 | .with_provider_health(&app.provider_health) |
| 4671 | }) |
| 4672 | { |
| 4673 | app.view_stack.push(picker); |
| 4674 | app.show_route_receipt(app.tr(MessageId::ProviderConnectionCheckedPickModel) |
| 4675 | .into_owned(), StatusToastLevel::Success); |
| 4676 | } else { |
| 4677 | app.show_route_receipt(format!( |
| 4678 | "{} {}", |
| 4679 | app.tr(MessageId::ProviderConnectionChecked), |
| 4680 | app.tr(MessageId::ProviderPickerNotReopened) |
| 4681 | ), StatusToastLevel::Warning); |
| 4682 | } |
| 4683 | app.needs_redraw = true; |
| 4684 | } |
| 4685 | Err(reason) => { |
| 4686 | // Verification failed - keep the picker open at the key-entry |
| 4687 | // stage with the provider's actual error so the user can fix |
| 4688 | // the key instead of dead-ending with a status toast. Name the |
| 4689 | // endpoint the probe actually used: a 401 from the wrong host |
| 4690 | // (a legacy root `base_url` leaking into this route, say) is |
| 4691 | // otherwise indistinguishable from a bad key. The provider's raw |
| 4692 | // reply (often truncated JSON) is not the message: say what went |
| 4693 | // wrong and what to do next in plain words (#6566). |
| 4694 | let plain = plain_key_verification_error(app, &reason, &api_key); |
| 4695 | let reason = match codewhale_engine::llm_client::base_url_authority(&base_url) { |
| 4696 | Some(authority) => format!("{plain} ({authority})"), |
| 4697 | None => plain.clone(), |
| 4698 | }; |
| 4699 | let runtime_status = query_provider_runtime_status(engine_handle).await; |
| 4700 | if let Some(picker) = |
| 4701 | crate::tui::provider_picker::ProviderPickerView::new_for_key_entry_with_error( |
| 4702 | app.api_provider, |
| 4703 | &identity, |
| 4704 | &scoped_config, |
| 4705 | runtime_status, |
| 4706 | reason, |
| 4707 | ) |
| 4708 | .map(|picker| { |
| 4709 | picker |
| 4710 | .with_locale(app.ui_locale) |
| 4711 | .with_provider_health(&app.provider_health) |
| 4712 | }) |
| 4713 | { |
| 4714 | app.view_stack.push(picker); |
| 4715 | app.show_route_receipt(plain, StatusToastLevel::Error); |
| 4716 | } else { |
| 4717 | app.show_route_receipt( |
| 4718 | format!("{plain} {}", app.tr(MessageId::ProviderPickerNotReopened)), |
| 4719 | StatusToastLevel::Error, |
| 4720 | ); |
| 4721 | } |
| 4722 | app.needs_redraw = true; |
| 4723 | } |
| 4724 | } |
| 4725 | } |
| 4726 | |
| 4727 | #[allow(clippy::too_many_arguments)] |
| 4728 | pub(crate) async fn apply_provider_picker_setup_confirmed( |
| 4729 | app: &mut App, |
| 4730 | engine_handle: &mut EngineHandle, |
| 4731 | config: &mut Config, |
| 4732 | identity: codewhale_runtime::config::ProviderIdentity, |
| 4733 | api_key: String, |
| 4734 | model: String, |
| 4735 | context_window: Option<u32>, |
| 4736 | base_url: Option<String>, |
| 4737 | ) -> bool { |
| 4738 | use codewhale_runtime::config::{ |
| 4739 | save_api_key_for_identity, save_provider_base_url_for_identity, |
| 4740 | save_provider_context_window_for_identity, save_provider_model_for_identity, |
| 4741 | }; |
| 4742 | |
| 4743 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 4744 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 4745 | return false; |
| 4746 | } |
| 4747 | if identity.persisted_id().is_none() { |
| 4748 | app.show_route_receipt( |
| 4749 | "Choose the exact custom provider table before changing its credentials or endpoint.", |
| 4750 | StatusToastLevel::Error, |
| 4751 | ); |
| 4752 | return false; |
| 4753 | } |
| 4754 | let provider = identity.provider; |
| 4755 | |
| 4756 | let model = model.trim().to_string(); |
| 4757 | if model.is_empty() { |
| 4758 | let message = format!( |
| 4759 | "Cannot finish {} setup: default model is empty.\nProvider unchanged.", |
| 4760 | provider.as_str() |
| 4761 | ); |
| 4762 | app.add_message(HistoryCell::System { |
| 4763 | content: message.clone(), |
| 4764 | }); |
| 4765 | app.show_route_receipt(message, StatusToastLevel::Error); |
| 4766 | return false; |
| 4767 | } |
| 4768 | |
| 4769 | // #4526: the wizard's billing-route choice is written before the key so the |
| 4770 | // credential is saved onto the route it was verified against. It lands only |
| 4771 | // in that provider's own `base_url`; failing here aborts before any secret |
| 4772 | // is persisted rather than leaving a key on the wrong endpoint. |
| 4773 | if let Some(base_url) = base_url.as_deref() { |
| 4774 | if let Err(err) = save_provider_base_url_for_identity(&identity, config, base_url) { |
| 4775 | let message = format!( |
| 4776 | "Failed to save {} endpoint `{base_url}`: {err}\nProvider unchanged.", |
| 4777 | provider.as_str() |
| 4778 | ); |
| 4779 | app.add_message(HistoryCell::System { |
| 4780 | content: message.clone(), |
| 4781 | }); |
| 4782 | app.show_route_receipt(message, StatusToastLevel::Error); |
| 4783 | return false; |
| 4784 | } |
| 4785 | if let Err(reason) = |
| 4786 | config.set_provider_base_url_override(&identity, Some(base_url.to_string())) |
| 4787 | { |
| 4788 | app.show_route_receipt(reason.to_string(), StatusToastLevel::Error); |
| 4789 | return false; |
| 4790 | } |
| 4791 | } |
| 4792 | |
| 4793 | // Persist key first via the existing comment-preserving path, then pin the |
| 4794 | // chosen default model on the same document when the provider uses a |
| 4795 | // `[providers.<name>]` table. |
| 4796 | let save_confirmation; |
| 4797 | match save_api_key_for_identity(&identity, config, &api_key) { |
| 4798 | Ok(saved) => { |
| 4799 | // #5195: name where the key actually landed (secret store backend |
| 4800 | // + credential-free config metadata) and the scope it is visible |
| 4801 | // from — credential writes are rescoped to the user-global config, |
| 4802 | // so the key is available in every folder. |
| 4803 | let destination = saved.describe(); |
| 4804 | if let Err(err) = save_provider_model_for_identity(&identity, config, &model) { |
| 4805 | let note = format!( |
| 4806 | "Saved {} API key to {destination} (available in all folders), but failed to pin model `{model}`: {err}", |
| 4807 | provider.as_str(), |
| 4808 | ); |
| 4809 | app.add_message(HistoryCell::System { |
| 4810 | content: note.clone(), |
| 4811 | }); |
| 4812 | save_confirmation = (note, StatusToastLevel::Warning); |
| 4813 | } else if let Some(context_window) = context_window { |
| 4814 | if let Err(err) = |
| 4815 | save_provider_context_window_for_identity(&identity, config, context_window) |
| 4816 | { |
| 4817 | let note = format!( |
| 4818 | "Saved {} API key and model to {destination} (available in all folders), but failed to save context window: {err}", |
| 4819 | provider.as_str(), |
| 4820 | ); |
| 4821 | app.add_message(HistoryCell::System { |
| 4822 | content: note.clone(), |
| 4823 | }); |
| 4824 | save_confirmation = (note, StatusToastLevel::Warning); |
| 4825 | } else { |
| 4826 | save_confirmation = ( |
| 4827 | format!( |
| 4828 | "Saved {} API key, model, and context window to {destination} (available in all folders)", |
| 4829 | provider.as_str(), |
| 4830 | ), |
| 4831 | StatusToastLevel::Success, |
| 4832 | ); |
| 4833 | } |
| 4834 | } else { |
| 4835 | save_confirmation = ( |
| 4836 | format!( |
| 4837 | "Saved {} API key and model to {destination} (available in all folders)", |
| 4838 | provider.as_str(), |
| 4839 | ), |
| 4840 | StatusToastLevel::Success, |
| 4841 | ); |
| 4842 | } |
| 4843 | app.api_key_env_only = false; |
| 4844 | } |
| 4845 | Err(err) => { |
| 4846 | let message = format!( |
| 4847 | "Failed to save {} API key: {err}\nProvider unchanged.", |
| 4848 | provider.as_str() |
| 4849 | ); |
| 4850 | app.add_message(HistoryCell::System { |
| 4851 | content: message.clone(), |
| 4852 | }); |
| 4853 | app.show_route_receipt(message, StatusToastLevel::Error); |
| 4854 | return false; |
| 4855 | } |
| 4856 | } |
| 4857 | |
| 4858 | if let Err(reason) = config |
| 4859 | .scope_to_provider_identity(&identity) |
| 4860 | .and_then(|()| mirror_saved_model_in_config(config, &identity, model.clone())) |
| 4861 | .and_then(|()| { |
| 4862 | context_window.map_or(Ok(()), |window| { |
| 4863 | mirror_saved_context_window_in_config(config, &identity, window) |
| 4864 | }) |
| 4865 | }) |
| 4866 | .and_then(|()| mirror_saved_api_key_in_config(config, &identity, api_key)) |
| 4867 | { |
| 4868 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 4869 | return false; |
| 4870 | } |
| 4871 | let switched = switch_provider(app, engine_handle, config, identity, Some(model)).await; |
| 4872 | // The switch overwrites the status line with the route summary (the full |
| 4873 | // summary also lands in the transcript), so the save confirmation is |
| 4874 | // applied last — it is the answer to the action the user just confirmed. |
| 4875 | if switched { |
| 4876 | app.finish_route_step(save_confirmation.0, save_confirmation.1); |
| 4877 | } |
| 4878 | switched |
| 4879 | } |
| 4880 | |
| 4881 | pub(crate) async fn apply_codewhale_owned_login( |
| 4882 | app: &mut App, |
| 4883 | engine_handle: &mut EngineHandle, |
| 4884 | config: &mut Config, |
| 4885 | provider: ProviderKind, |
| 4886 | pending: codewhale_runtime::oauth::PendingOAuthLogin, |
| 4887 | status_prefix: &str, |
| 4888 | login_kind: &str, |
| 4889 | ) -> bool { |
| 4890 | let path = app.config_path.clone(); |
| 4891 | let mut live = config.clone(); |
| 4892 | let activation = tokio::task::spawn_blocking(move || { |
| 4893 | codewhale_runtime::oauth::activate_login(pending, path.as_deref(), Some(&mut live)) |
| 4894 | .map(|activation| (activation, live)) |
| 4895 | }) |
| 4896 | .await |
| 4897 | .map_err(|error| anyhow::anyhow!("OAuth activation worker failed: {error}")) |
| 4898 | .and_then(|result| result); |
| 4899 | match activation { |
| 4900 | Ok((activation, live)) => { |
| 4901 | config.refresh_provider_routes_from(&live); |
| 4902 | // The account line goes to the transcript: the status line is |
| 4903 | // overwritten by the route summary once the switch lands. |
| 4904 | let locale = app.ui_locale; |
| 4905 | let content = match activation.env_override_warning(locale) { |
| 4906 | Some(warning) => format!("{}\n{warning}", activation.summary(locale)), |
| 4907 | None => activation.summary(locale), |
| 4908 | }; |
| 4909 | app.add_message(HistoryCell::System { content }); |
| 4910 | app.show_route_receipt( |
| 4911 | format!( |
| 4912 | "{status_prefix}; activated {} via {}", |
| 4913 | codewhale_config::quote_os_path(&activation.auth_path), |
| 4914 | codewhale_config::quote_os_path(&activation.config_path) |
| 4915 | ), |
| 4916 | StatusToastLevel::Success, |
| 4917 | ); |
| 4918 | app.api_key_env_only = false; |
| 4919 | } |
| 4920 | Err(err) => { |
| 4921 | let message = format!( |
| 4922 | "Failed to finalize {} {login_kind}: {err:#}\nProvider unchanged.", |
| 4923 | provider.as_str() |
| 4924 | ); |
| 4925 | app.add_message(HistoryCell::System { |
| 4926 | content: message.clone(), |
| 4927 | }); |
| 4928 | app.show_route_receipt(message, StatusToastLevel::Error); |
| 4929 | return false; |
| 4930 | } |
| 4931 | } |
| 4932 | |
| 4933 | if provider == ProviderKind::OpenaiCodex { |
| 4934 | let mut selected = config.clone(); |
| 4935 | selected.provider = Some(provider.as_str().to_string()); |
| 4936 | if codewhale_engine::codex_model_cache::update_from_chatgpt(&selected) |
| 4937 | .await |
| 4938 | .is_err() |
| 4939 | { |
| 4940 | app.show_route_receipt( |
| 4941 | format!( |
| 4942 | "{} codewhale models --update --provider openai-codex", |
| 4943 | app.tr(MessageId::ProviderNoCatalogModels) |
| 4944 | ), |
| 4945 | StatusToastLevel::Warning, |
| 4946 | ); |
| 4947 | return false; |
| 4948 | } |
| 4949 | } |
| 4950 | let identity = match config.builtin_provider_identity(provider) { |
| 4951 | Ok(identity) => identity, |
| 4952 | Err(reason) => { |
| 4953 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 4954 | return false; |
| 4955 | } |
| 4956 | }; |
| 4957 | switch_provider(app, engine_handle, config, identity, None).await |
| 4958 | } |
| 4959 | |
| 4960 | pub(crate) async fn apply_codewhale_owned_xai_login( |
| 4961 | app: &mut App, |
| 4962 | engine_handle: &mut EngineHandle, |
| 4963 | config: &mut Config, |
| 4964 | pending: codewhale_runtime::oauth::PendingOAuthLogin, |
| 4965 | status_prefix: &str, |
| 4966 | ) -> bool { |
| 4967 | apply_codewhale_owned_login( |
| 4968 | app, |
| 4969 | engine_handle, |
| 4970 | config, |
| 4971 | ProviderKind::Xai, |
| 4972 | pending, |
| 4973 | status_prefix, |
| 4974 | "device login", |
| 4975 | ) |
| 4976 | .await |
| 4977 | } |
| 4978 | |
| 4979 | pub(crate) async fn apply_codewhale_owned_chatgpt_login( |
| 4980 | app: &mut App, |
| 4981 | engine_handle: &mut EngineHandle, |
| 4982 | config: &mut Config, |
| 4983 | pending: codewhale_runtime::oauth::PendingOAuthLogin, |
| 4984 | status_prefix: &str, |
| 4985 | ) -> bool { |
| 4986 | apply_codewhale_owned_login( |
| 4987 | app, |
| 4988 | engine_handle, |
| 4989 | config, |
| 4990 | ProviderKind::OpenaiCodex, |
| 4991 | pending, |
| 4992 | status_prefix, |
| 4993 | "ChatGPT sign-in", |
| 4994 | ) |
| 4995 | .await |
| 4996 | } |
| 4997 | |
| 4998 | /// `/auth chatgpt-revoke`. The remote revoke is one blocking HTTP round trip |
| 4999 | /// per stored token under the OAuth lifecycle lock, so it runs on the blocking |
| 5000 | /// pool instead of the event loop. It targets the session's own config file |
| 5001 | /// and clears the live route afterwards so the header stops claiming OAuth. |
| 5002 | pub(crate) async fn run_chatgpt_revoke_from_tui(app: &mut App, config: &mut Config) { |
| 5003 | let config_path = app.config_path.clone(); |
| 5004 | let outcome = tokio::task::spawn_blocking(move || { |
| 5005 | codewhale_runtime::oauth::revoke_owned_login( |
| 5006 | codewhale_runtime::oauth::OAuthProvider::Chatgpt, |
| 5007 | config_path.as_deref(), |
| 5008 | None, |
| 5009 | ) |
| 5010 | }) |
| 5011 | .await |
| 5012 | .map_err(|err| anyhow::anyhow!("ChatGPT revoke task was lost: {err}")) |
| 5013 | .and_then(|result| result); |
| 5014 | // Clear the live route even when remote revocation could not be confirmed; |
| 5015 | // local credential removal may already have succeeded in that outcome. |
| 5016 | let live_clear = config.clear_codewhale_owned_chatgpt_oauth(); |
| 5017 | let level = if outcome.is_err() { |
| 5018 | StatusToastLevel::Error |
| 5019 | } else if live_clear.is_err() { |
| 5020 | StatusToastLevel::Warning |
| 5021 | } else { |
| 5022 | StatusToastLevel::Success |
| 5023 | }; |
| 5024 | let message = match (outcome, live_clear) { |
| 5025 | (Ok(()), Ok(())) => { |
| 5026 | "Revoked Codewhale-owned ChatGPT tokens. Codex CLI consent is unchanged.".to_string() |
| 5027 | } |
| 5028 | (Ok(()), Err(err)) => format!( |
| 5029 | "ChatGPT tokens were revoked, but the live route could not be refreshed: {err:#}" |
| 5030 | ), |
| 5031 | (Err(err), Ok(())) => format!("ChatGPT revoke failed: {err:#}"), |
| 5032 | (Err(err), Err(live_err)) => format!( |
| 5033 | "ChatGPT revoke failed: {err:#}. The live route could not be refreshed: {live_err:#}" |
| 5034 | ), |
| 5035 | }; |
| 5036 | app.add_message(HistoryCell::System { |
| 5037 | content: message.clone(), |
| 5038 | }); |
| 5039 | app.show_command_result(message, level); |
| 5040 | app.needs_redraw = true; |
| 5041 | } |
| 5042 | |
| 5043 | /// `/auth orcarouter-revoke`. OrcaRouter mints a durable API key with no remote |
| 5044 | /// revocation endpoint this client owns, so revoke is local-only: clear the |
| 5045 | /// `orcarouter` secret-store slot, the route's saved key, and the in-memory |
| 5046 | /// override. Re-authenticating is a fresh PKCE sign-in or a freshly pasted key. |
| 5047 | pub(crate) async fn run_orcarouter_revoke_from_tui(app: &mut App, config: &mut Config) { |
| 5048 | let provider = ProviderKind::Orcarouter; |
| 5049 | let provider_name = provider.as_str().to_string(); |
| 5050 | let outcome = tokio::task::spawn_blocking(move || { |
| 5051 | codewhale_runtime::config::clear_active_provider_api_key(&provider_name) |
| 5052 | }) |
| 5053 | .await |
| 5054 | .map_err(|err| anyhow::anyhow!("OrcaRouter revoke task was lost: {err}")) |
| 5055 | .and_then(|result| result); |
| 5056 | let live_clear = match config.builtin_provider_identity(provider) { |
| 5057 | Ok(identity) => config |
| 5058 | .set_provider_api_key_override(&identity, None) |
| 5059 | .map_err(|error| anyhow::anyhow!(error.to_string())), |
| 5060 | Err(err) => Err(anyhow::anyhow!(err)), |
| 5061 | }; |
| 5062 | let level = if outcome.is_err() { |
| 5063 | StatusToastLevel::Error |
| 5064 | } else if live_clear.is_err() { |
| 5065 | StatusToastLevel::Warning |
| 5066 | } else { |
| 5067 | StatusToastLevel::Success |
| 5068 | }; |
| 5069 | let message = match (outcome, live_clear) { |
| 5070 | (Ok(()), Ok(())) => "Removed Codewhale's saved OrcaRouter credential.".to_string(), |
| 5071 | (Ok(()), Err(err)) => { |
| 5072 | format!("OrcaRouter credential removed; the live route could not be refreshed: {err:#}") |
| 5073 | } |
| 5074 | (Err(err), Ok(())) => format!("OrcaRouter revoke failed: {err:#}"), |
| 5075 | (Err(err), Err(live_err)) => format!( |
| 5076 | "OrcaRouter revoke failed: {err:#}. The live route could not be refreshed: {live_err:#}" |
| 5077 | ), |
| 5078 | }; |
| 5079 | app.add_message(HistoryCell::System { |
| 5080 | content: message.clone(), |
| 5081 | }); |
| 5082 | app.show_command_result(message, level); |
| 5083 | app.needs_redraw = true; |
| 5084 | } |
| 5085 | |
| 5086 | #[cfg(test)] |
| 5087 | pub(crate) fn apply_loaded_session( |
| 5088 | app: &mut App, |
| 5089 | config: &mut Config, |
| 5090 | session: &SavedSession, |
| 5091 | ) -> Result<(), String> { |
| 5092 | apply_loaded_session_with_goal(app, config, session.clone(), None).map(|_| ()) |
| 5093 | } |
| 5094 | |
| 5095 | /// Decide which Runtime store the loaded conversation needs, and whether this |
| 5096 | /// host may take it over — without changing anything. |
| 5097 | /// |
| 5098 | /// Split out from [`apply_loaded_session_with_goal`] so the decision can be |
| 5099 | /// made *before* the conversation state moves. Adoption is the one step here |
| 5100 | /// that can fail after it has already released the previous manager, so it has |
| 5101 | /// to run as preflight: a refusal must leave the displayed session, its |
| 5102 | /// workspace and its usable manager exactly as they were. |
| 5103 | /// |
| 5104 | /// `Ok(Some(binding))` means this host must move onto `binding`. |
| 5105 | /// `Ok(None)` covers the three cases that need no move: the conversation |
| 5106 | /// names no store, it names the one this host already holds, or its store is |
| 5107 | /// missing or stale and the document is repaired onto this host instead. |
| 5108 | fn plan_store_adoption( |
| 5109 | app: &App, |
| 5110 | session: &SavedSession, |
| 5111 | ) -> Result<Option<codewhale_engine::runtime_threads::RuntimeStoreBinding>, String> { |
| 5112 | let Some(binding) = session.metadata.runtime_store.as_ref() else { |
| 5113 | return Ok(None); |
| 5114 | }; |
| 5115 | let Some(tasks) = app.runtime_services.task_manager.as_ref() else { |
| 5116 | return Ok(None); |
| 5117 | }; |
| 5118 | if tasks.session_store_binding().as_ref() == Some(binding) { |
| 5119 | return Ok(None); |
| 5120 | } |
| 5121 | // A missing store is repaired into this host's own store; that is the |
| 5122 | // opposite direction from adopting the target, and the two must not both |
| 5123 | // run. |
| 5124 | let target_is_missing = binding |
| 5125 | .is_missing_session_store() |
| 5126 | .map_err(|error| error.to_string())?; |
| 5127 | if target_is_missing { |
| 5128 | return Ok(None); |
| 5129 | } |
| 5130 | if let Some(codewhale_engine::runtime_threads::StoreAdoptionRefusal::HeldByLiveProcess) = |
| 5131 | binding |
| 5132 | .adoption_refusal() |
| 5133 | .map_err(|error| error.to_string())? |
| 5134 | { |
| 5135 | // A fresh `codewhale resume` would meet the same live holder, so name |
| 5136 | // the step that actually frees the store (#6418). |
| 5137 | return Err(format!( |
| 5138 | "This session's saved Runtime store is open in another running \ |
| 5139 | Codewhale process. Close that session there, then open this one \ |
| 5140 | again, or run `codewhale resume {}` after it exits.", |
| 5141 | session.metadata.id |
| 5142 | )); |
| 5143 | } |
| 5144 | // A store whose recorded scope no longer matches its own owner file is not |
| 5145 | // adoptable: the binding is stale, and adopting it would claim an authority |
| 5146 | // the store does not carry. `apply_loaded_session_with_goal` repairs the |
| 5147 | // document onto this host's store instead (#6144, #6207). |
| 5148 | if binding.validate_existing_store().is_err() { |
| 5149 | return Ok(None); |
| 5150 | } |
| 5151 | // A populated store is no longer a reason to refuse. |
| 5152 | // |
| 5153 | // The old rule refused any target whose `threads/` directory held a single |
| 5154 | // record, on the theory that a switch "cannot carry that store's queued |
| 5155 | // work across". It still cannot — but it does not have to. A switch never |
| 5156 | // discards a store: the host keeps the one it holds, and the target stays |
| 5157 | // on disk for whichever process opens it next. What a switch must not do is |
| 5158 | // release a store that still needs *this* process, which is a property of |
| 5159 | // the store being left, not of the one being entered. |
| 5160 | // |
| 5161 | // The refusals that remain are the ones that make the target unusable from |
| 5162 | // here: another process holds its lock, the path is not a confined store |
| 5163 | // directory, or an automation is pinned to its execution scope. |
| 5164 | if let Some(refusal) = binding |
| 5165 | .adoption_refusal() |
| 5166 | .map_err(|error| error.to_string())? |
| 5167 | .filter(|refusal| { |
| 5168 | matches!( |
| 5169 | refusal, |
| 5170 | codewhale_engine::runtime_threads::StoreAdoptionRefusal::Unconfined |
| 5171 | | codewhale_engine::runtime_threads::StoreAdoptionRefusal::NotADirectory |
| 5172 | | codewhale_engine::runtime_threads::StoreAdoptionRefusal::ScopePinnedAutomation |
| 5173 | ) |
| 5174 | }) |
| 5175 | { |
| 5176 | return Err(format!( |
| 5177 | "This session's saved Runtime store cannot be opened from here ({refusal}): \ |
| 5178 | run `codewhale resume {}` from your shell.", |
| 5179 | session.metadata.id |
| 5180 | )); |
| 5181 | } |
| 5182 | if app.session_transition_blocked() { |
| 5183 | return Err( |
| 5184 | "runtime work is active; wait for the current turn, maintenance, and background tasks to finish, or cancel that specific work before switching sessions".to_string(), |
| 5185 | ); |
| 5186 | } |
| 5187 | // Releasing the store this host holds is only safe when nothing in it still |
| 5188 | // waits on this process. Approvals and user-input prompts live in memory, |
| 5189 | // so a restart could not recover them either — dropping them here would |
| 5190 | // strand every waiter. The engine half of the check needs the Runtime's |
| 5191 | // `active` lock, so `adopt_runtime_store` performs it. |
| 5192 | if tasks.has_unsettled_requests() { |
| 5193 | return Err( |
| 5194 | "This session's Runtime store has tool approvals or user input still waiting. \ |
| 5195 | Answer them, or stop that work, before switching sessions." |
| 5196 | .to_string(), |
| 5197 | ); |
| 5198 | } |
| 5199 | Ok(Some(binding.clone())) |
| 5200 | } |
| 5201 | |
| 5202 | /// Install a loaded session as the live conversation. The session is taken |
| 5203 | /// by value because it is consumed: its journal, history, artifacts and |
| 5204 | /// metadata move into `app` instead of being cloned beside a copy the caller |
| 5205 | /// would drop right after (memory note M3). On `Err` nothing was installed. |
| 5206 | pub(crate) fn apply_loaded_session_with_goal( |
| 5207 | app: &mut App, |
| 5208 | config: &mut Config, |
| 5209 | mut session: SavedSession, |
| 5210 | goal: Option<&codewhale_engine::session_manager::SessionGoalState>, |
| 5211 | ) -> Result<Option<codewhale_engine::runtime_threads::RuntimeStoreBinding>, String> { |
| 5212 | // A switch never runs over live work, whether or not it also changes |
| 5213 | // stores. This belongs here rather than in `plan_store_adoption` because a |
| 5214 | // plain resume takes this path too, and it must refuse for the same reason. |
| 5215 | if app.session_transition_blocked() { |
| 5216 | return Err( |
| 5217 | "runtime work is active; wait for the current turn, maintenance, and background tasks to finish, or cancel that specific work before switching sessions".to_string(), |
| 5218 | ); |
| 5219 | } |
| 5220 | // Whether this load must move the host onto another store is decided by |
| 5221 | // `plan_store_adoption` before anything is installed; by the time state |
| 5222 | // changes, the host already owns the store the conversation names. |
| 5223 | let mut recovered_binding = None; |
| 5224 | if let Some(binding) = session.metadata.runtime_store.as_ref() |
| 5225 | && let Some(tasks) = app.runtime_services.task_manager.as_ref() |
| 5226 | && tasks.session_store_binding().as_ref() != Some(binding) |
| 5227 | { |
| 5228 | // The two repairs that keep the document pointing at this host: a |
| 5229 | // missing store, and one whose recorded scope no longer matches its own |
| 5230 | // owner file. Both are the opposite direction from adopting the target, |
| 5231 | // and `plan_store_adoption` deliberately reports neither as adoptable. |
| 5232 | let target_is_missing = binding |
| 5233 | .is_missing_session_store() |
| 5234 | .map_err(|error| error.to_string())?; |
| 5235 | let binding_is_stale = !target_is_missing && binding.validate_existing_store().is_err(); |
| 5236 | if target_is_missing || binding_is_stale { |
| 5237 | recovered_binding = tasks.session_store_binding(); |
| 5238 | } |
| 5239 | } |
| 5240 | |
| 5241 | if let Some(goal) = goal { |
| 5242 | goal.validate() |
| 5243 | .map_err(|error| format!("saved session goal is invalid: {error}"))?; |
| 5244 | } |
| 5245 | let provider_identity = config |
| 5246 | .resolve_persisted_provider_identity( |
| 5247 | Some(&session.metadata.model_provider), |
| 5248 | session.metadata.model_provider_id.as_deref(), |
| 5249 | ) |
| 5250 | .map_err(|reason| { |
| 5251 | format!( |
| 5252 | "{reason}. {}", |
| 5253 | codewhale_engine::session_export::export_recovery_hint(&session.metadata.id) |
| 5254 | ) |
| 5255 | })?; |
| 5256 | let restored_route = resolve_runtime_route_for_identity( |
| 5257 | config, |
| 5258 | &provider_identity, |
| 5259 | Some(&session.metadata.model), |
| 5260 | ) |
| 5261 | .map_err(|reason| { |
| 5262 | format!( |
| 5263 | "saved session provider '{}' could not be resolved from the live config: {reason}. Codewhale will not fall back", |
| 5264 | provider_identity.key |
| 5265 | ) |
| 5266 | })?; |
| 5267 | // Restore/validate the contended state before mutating conversation or |
| 5268 | // workspace fields. A failed session switch must leave the current session |
| 5269 | // wholly intact. |
| 5270 | let queue_transition = prepare_offline_queue_transition(app, &session.metadata.id)?; |
| 5271 | if let Some(binding) = recovered_binding.as_ref() { |
| 5272 | // Only the conversation is recovered into this idle host. Its missing |
| 5273 | // runtime's tasks and approvals are never imported or re-admitted. |
| 5274 | // Repair its binding before changing live Work state. If Work restore |
| 5275 | // is contended, the current conversation stays intact and a retry can |
| 5276 | // use this durably repaired binding to the same host. |
| 5277 | let mut recovered = session.clone(); |
| 5278 | recovered |
| 5279 | .capture_publication(codewhale_engine::session_manager::SessionWriteOwner::control()) |
| 5280 | .map_err(|error| error.to_string())?; |
| 5281 | let abandoned = recovered.metadata.runtime_store.replace(binding.clone()); |
| 5282 | let manager = SessionManager::default_location() |
| 5283 | .map_err(|error| format!("Session recovery could not be saved: {error}"))?; |
| 5284 | let publication = manager |
| 5285 | .publish_session(&recovered) |
| 5286 | .map_err(|error| format!("Session recovery could not be saved: {error}"))?; |
| 5287 | session.adopt_publication(&publication); |
| 5288 | // The conversation now lives in this host's store. The empty store it |
| 5289 | // left is set aside here, where it is abandoned, unless another |
| 5290 | // document still binds it (#6144 P1a) — otherwise it stayed on disk |
| 5291 | // with nothing pointing at it. |
| 5292 | if let Some(abandoned) = abandoned { |
| 5293 | codewhale_engine::session_reconcile::retire_unbound_store_in_background( |
| 5294 | manager, |
| 5295 | abandoned.data_dir, |
| 5296 | "conversation rebound to another host's store", |
| 5297 | ); |
| 5298 | } |
| 5299 | } |
| 5300 | app.restore_work_state( |
| 5301 | &session.metadata.id, |
| 5302 | &session.metadata.workspace, |
| 5303 | session.work_state.as_ref(), |
| 5304 | )?; |
| 5305 | install_offline_queue_transition(app, queue_transition); |
| 5306 | // All fallible preflight is complete. Retire the old session's background |
| 5307 | // accounting atomically before mutating live state; any late old-scope |
| 5308 | // provider response is rejected by `cost_status::report`. |
| 5309 | let _settled_old_cost_scope = codewhale_engine::cost_status::close_current_scope(); |
| 5310 | *config = *restored_route.config; |
| 5311 | app.refresh_notification_settings(config); |
| 5312 | app.restore_api_messages_from_owned(&mut session); |
| 5313 | app.clear_history(); |
| 5314 | app.tool_cells.clear(); |
| 5315 | app.tool_details_by_cell.clear(); |
| 5316 | app.active_cell = None; |
| 5317 | app.active_tool_details.clear(); |
| 5318 | app.active_tool_entry_completed_at.clear(); |
| 5319 | app.active_cell_revision = app.active_cell_revision.wrapping_add(1); |
| 5320 | app.exploring_entries.clear(); |
| 5321 | app.ignored_tool_calls.clear(); |
| 5322 | app.pending_tool_uses.clear(); |
| 5323 | app.last_exec_wait_command = None; |
| 5324 | let messages = app.api_messages.clone(); |
| 5325 | let mut message_to_cell = std::collections::HashMap::new(); |
| 5326 | // Failed-turn notices are replayed where they happened: after the |
| 5327 | // messages that existed when the turn ended (clamped to the transcript). |
| 5328 | let mut turn_outcomes = session.turn_outcomes.iter().peekable(); |
| 5329 | let mut replay_outcomes_through = |app: &mut App, message_count: usize, last: bool| { |
| 5330 | while let Some(outcome) = |
| 5331 | turn_outcomes.next_if(|outcome| last || outcome.after_message_count <= message_count) |
| 5332 | { |
| 5333 | app.extend_history(std::iter::once(HistoryCell::Error { |
| 5334 | message: outcome.error.clone(), |
| 5335 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 5336 | code: outcome.code.clone(), |
| 5337 | })); |
| 5338 | } |
| 5339 | }; |
| 5340 | replay_outcomes_through(app, 0, messages.is_empty()); |
| 5341 | for (message_index, msg) in messages.iter().enumerate() { |
| 5342 | let mut cells = |
| 5343 | crate::tui::history::history_cells_from_message_with_results(msg, &messages); |
| 5344 | if msg.role == "user" |
| 5345 | && session |
| 5346 | .context_references |
| 5347 | .iter() |
| 5348 | .any(|record| record.message_index == message_index) |
| 5349 | { |
| 5350 | for cell in &mut cells { |
| 5351 | if let HistoryCell::User { content } = cell { |
| 5352 | *content = compact_user_context_display(content); |
| 5353 | } |
| 5354 | } |
| 5355 | } |
| 5356 | let base = app.history.len(); |
| 5357 | if msg.role == "user" |
| 5358 | && let Some(offset) = cells |
| 5359 | .iter() |
| 5360 | .position(|cell| matches!(cell, HistoryCell::User { .. })) |
| 5361 | { |
| 5362 | message_to_cell.insert(message_index, base + offset); |
| 5363 | } |
| 5364 | app.extend_restored_history(msg, cells); |
| 5365 | replay_outcomes_through(app, message_index + 1, message_index + 1 == messages.len()); |
| 5366 | } |
| 5367 | app.sync_context_references_from_session(&session.context_references, &message_to_cell); |
| 5368 | app.mark_history_updated(); |
| 5369 | app.viewport.transcript_selection.clear(); |
| 5370 | // Goal state is session-owned just like Work state. A legacy/no-goal |
| 5371 | // session clears the previous session's objective; a durable sidecar |
| 5372 | // rebuilds both the visible hunt and the EngineConfig seeded below. |
| 5373 | app.goal = crate::tui::app::HostGoalState::default(); |
| 5374 | app.last_known_goal_state = None; |
| 5375 | app.pending_goal_controls.clear(); |
| 5376 | if let Some(goal) = goal { |
| 5377 | let snapshot = goal.to_runtime_snapshot(); |
| 5378 | let _ = apply_goal_snapshot_to_app(app, &snapshot); |
| 5379 | } |
| 5380 | restore_loaded_session_provider(app, config, provider_identity)?; |
| 5381 | // Session records do not own a reasoning preference. `set_model_selection` |
| 5382 | // restores the raw explicit global preference for Auto (or releases an |
| 5383 | // implicit fixed-route default) instead of reusing normalized live state. |
| 5384 | app.set_model_selection(session.metadata.model.clone()); |
| 5385 | if app.auto_model |
| 5386 | && let Some(saved) = session.last_auto_route.as_ref() |
| 5387 | && !saved.provider_identity.trim().is_empty() |
| 5388 | && !saved.model.trim().is_empty() |
| 5389 | { |
| 5390 | app.last_effective_provider = Some(saved.provider); |
| 5391 | app.last_effective_provider_identity = Some(saved.provider_identity.clone()); |
| 5392 | app.last_effective_model = Some(saved.model.clone()); |
| 5393 | app.last_auto_route_receipt = Some(saved.receipt.clone()); |
| 5394 | app.last_effective_budget = |
| 5395 | saved |
| 5396 | .context_window |
| 5397 | .map(|window| crate::tui::app::AutoRouteBudget { |
| 5398 | provider: saved.provider, |
| 5399 | provider_identity: saved.provider_identity.clone(), |
| 5400 | model: saved.model.clone(), |
| 5401 | limits: None, |
| 5402 | window, |
| 5403 | restored: true, |
| 5404 | }); |
| 5405 | app.last_effective_reasoning_effort = saved.effective_reasoning_effort.map(Into::into); |
| 5406 | } |
| 5407 | resolve_loaded_session_route(app, config); |
| 5408 | if !app.auto_model { |
| 5409 | let requested = app |
| 5410 | .reasoning_effort_preference |
| 5411 | .unwrap_or(app.reasoning_effort); |
| 5412 | app.reasoning_effort = requested.normalize_for_route_identity( |
| 5413 | app.api_provider, |
| 5414 | app.provider_identity_for_persistence(), |
| 5415 | &app.active_route_base_url, |
| 5416 | &app.model, |
| 5417 | ); |
| 5418 | } |
| 5419 | app.provider_models.insert( |
| 5420 | app.provider_identity_for_persistence().to_string(), |
| 5421 | app.model_selection_for_persistence(), |
| 5422 | ); |
| 5423 | app.update_model_compaction_budget(); |
| 5424 | apply_workspace_runtime_state(app, config, session.metadata.workspace.clone()); |
| 5425 | if let Some(mode) = session.metadata.mode.as_deref().and_then(AppMode::parse) { |
| 5426 | app.set_mode(mode); |
| 5427 | } |
| 5428 | let saved_mode_unavailable = match session.agent_preset.clone() { |
| 5429 | Some(stored) => { |
| 5430 | let table = crate::tui::conversation_mode::current_table_blocking(Some(config)); |
| 5431 | let reason = crate::tui::conversation_mode::unavailable_reason( |
| 5432 | Some(&stored), |
| 5433 | &table, |
| 5434 | app.ui_locale, |
| 5435 | ); |
| 5436 | app.install_conversation_mode(Some(stored), reason.clone()); |
| 5437 | reason |
| 5438 | } |
| 5439 | None => { |
| 5440 | app.install_conversation_mode(None, None); |
| 5441 | None |
| 5442 | } |
| 5443 | }; |
| 5444 | app.session.total_tokens = u32::try_from(session.metadata.total_tokens).unwrap_or(u32::MAX); |
| 5445 | app.session.total_conversation_tokens = app.session.total_tokens; |
| 5446 | app.session.displayed_cost_high_water = 0.0; |
| 5447 | app.session.displayed_cost_high_water_cny = 0.0; |
| 5448 | app.last_billed_input_tokens = None; |
| 5449 | app.clear_context_pressure_sticky_status(); |
| 5450 | app.restore_cost_snapshot(&session.metadata.cost); |
| 5451 | codewhale_engine::cost_status::restore_accounted_usage_sources_with_pins( |
| 5452 | &session.metadata.cost.accounted_usage_sources, |
| 5453 | &session.metadata.cost.usage_source_fingerprints, |
| 5454 | &session.metadata.cost.pinned_late_usage_fingerprints, |
| 5455 | ); |
| 5456 | app.session.last_prompt_tokens = None; |
| 5457 | app.session.last_completion_tokens = None; |
| 5458 | app.session.last_prompt_cache_hit_tokens = None; |
| 5459 | app.session.last_prompt_cache_miss_tokens = None; |
| 5460 | app.session.last_reasoning_replay_tokens = None; |
| 5461 | // Accumulated token breakdown is per-runtime-session; reset on load. |
| 5462 | app.session.reset_token_breakdown(); |
| 5463 | // The metrics strip shares that scope: it describes this runtime |
| 5464 | // session's calls, not the restored transcript's. |
| 5465 | app.session_metrics = crate::tui::session_metrics::SessionMetrics::default(); |
| 5466 | app.session.turn_cache_history.clear(); |
| 5467 | // Restore cumulative turn duration so the footer "worked" chip |
| 5468 | // persists across session restarts (#2038). |
| 5469 | app.cumulative_turn_duration = |
| 5470 | std::time::Duration::from_secs(session.metadata.cumulative_turn_secs); |
| 5471 | app.set_current_session_id(Some(session.metadata.id.clone())); |
| 5472 | app.session_write_receipt = session.write_receipt.clone(); |
| 5473 | app.session_write_owner = session |
| 5474 | .write_receipt |
| 5475 | .as_ref() |
| 5476 | .map(|_| codewhale_engine::session_manager::SessionWriteOwner::control()); |
| 5477 | app.session_title = Some(session.metadata.title.clone()); |
| 5478 | app.current_session_metadata = Some(session.metadata); |
| 5479 | reset_approval_scope_for_new_conversation(app); |
| 5480 | if let Some(binding) = recovered_binding { |
| 5481 | if let Some(metadata) = app.current_session_metadata.as_mut() { |
| 5482 | metadata.runtime_store = Some(binding); |
| 5483 | } |
| 5484 | app.push_status_toast( |
| 5485 | app.tr(MessageId::RuntimeStoreRecovered).into_owned(), |
| 5486 | StatusToastLevel::Warning, |
| 5487 | None, |
| 5488 | ); |
| 5489 | } |
| 5490 | app.session_artifacts = session.artifacts; |
| 5491 | app.session_turn_outcomes = session.turn_outcomes; |
| 5492 | app.delegated_writes = app |
| 5493 | .current_session_id |
| 5494 | .as_ref() |
| 5495 | .map(|owner| { |
| 5496 | session |
| 5497 | .delegated_writes |
| 5498 | .into_iter() |
| 5499 | .map(|(seq, paths)| ((owner.clone(), seq), paths.into_iter().collect())) |
| 5500 | .collect() |
| 5501 | }) |
| 5502 | .unwrap_or_default(); |
| 5503 | app.window_title = session.window_title; |
| 5504 | app.composer_color = session.composer_color; |
| 5505 | app.workspace_context = None; |
| 5506 | app.workspace_is_linked_worktree = false; |
| 5507 | app.workspace_context_refreshed_at = None; |
| 5508 | app.system_prompt = session.system_prompt.map(SystemPrompt::Text); |
| 5509 | app.retire_event_notices(super::event_loop::STARTUP_NOTICE_TOAST); |
| 5510 | if let Some(reason) = saved_mode_unavailable { |
| 5511 | let name = crate::tui::conversation_mode::name_for_stored( |
| 5512 | app.ui_locale, |
| 5513 | app.conversation_mode.as_deref(), |
| 5514 | None, |
| 5515 | ); |
| 5516 | app.add_message(HistoryCell::System { |
| 5517 | content: crate::tui::conversation_mode::saved_unavailable_notice( |
| 5518 | app.ui_locale, |
| 5519 | &name, |
| 5520 | &reason, |
| 5521 | ), |
| 5522 | }); |
| 5523 | } |
| 5524 | app.refresh_agent_approved_plugins_notice(); |
| 5525 | app.scroll_to_bottom(); |
| 5526 | // Any adoption already happened: `plan_store_adoption` decided it and the |
| 5527 | // async caller moved the host before this ran. What is left is the repair |
| 5528 | // direction — a `recovered_binding` rewrites the *document* to name this |
| 5529 | // host's store — and that is reported through the App, not returned. |
| 5530 | Ok(None) |
| 5531 | } |
| 5532 | |
| 5533 | #[derive(Debug)] |
| 5534 | pub(crate) struct LoadedSessionOutcome { |
| 5535 | /// Whether the engine must be rebuilt (provider, workspace, or route |
| 5536 | /// changed, or a file `/load` supplied a fresh snapshot). |
| 5537 | pub(crate) respawn: bool, |
| 5538 | } |
| 5539 | |
| 5540 | /// Switch the live conversation to a saved session, adopting its Runtime |
| 5541 | /// store when the conversation names one this host does not hold. |
| 5542 | /// |
| 5543 | /// Async because adoption is a real state transition, not a bookkeeping |
| 5544 | /// change: it settles the engines this host was running, releases its |
| 5545 | /// process-owner lock and opens another. Doing it after the conversation |
| 5546 | /// state had already moved — the original shape of this function — left the |
| 5547 | /// displayed session and the Runtime owner free to disagree, and a failed |
| 5548 | /// adoption had no way back because the previous manager was already shut |
| 5549 | /// down. It now runs as preflight: a refusal or a failed open returns the |
| 5550 | /// error with the live session untouched. |
| 5551 | pub(crate) fn apply_loaded_session_config_snapshot<'a>( |
| 5552 | app: &'a mut App, |
| 5553 | config: &'a mut Config, |
| 5554 | session: SavedSession, |
| 5555 | next_config: Config, |
| 5556 | force_engine_respawn: bool, |
| 5557 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<LoadedSessionOutcome, String>> + 'a>> |
| 5558 | { |
| 5559 | Box::pin(apply_loaded_session_config_snapshot_inner( |
| 5560 | app, |
| 5561 | config, |
| 5562 | session, |
| 5563 | next_config, |
| 5564 | force_engine_respawn, |
| 5565 | )) |
| 5566 | } |
| 5567 | |
| 5568 | async fn apply_loaded_session_config_snapshot_inner( |
| 5569 | app: &mut App, |
| 5570 | config: &mut Config, |
| 5571 | session: SavedSession, |
| 5572 | mut next_config: Config, |
| 5573 | force_engine_respawn: bool, |
| 5574 | ) -> Result<LoadedSessionOutcome, String> { |
| 5575 | if force_engine_respawn { |
| 5576 | // File `/load` supplies a freshly loaded disk snapshot, but the live |
| 5577 | // Config also contains CLI and workspace/project overlays that are not |
| 5578 | // represented by that file. Refresh the provider registry atomically |
| 5579 | // over the effective Config instead of dropping permission controls. |
| 5580 | let mut effective_config = config.clone(); |
| 5581 | effective_config.refresh_provider_routes_from(&next_config); |
| 5582 | next_config = effective_config; |
| 5583 | } |
| 5584 | let previous_provider = app.api_provider; |
| 5585 | let previous_provider_identity = app.provider_identity_for_persistence().to_string(); |
| 5586 | let previous_workspace = app.workspace.clone(); |
| 5587 | let goal = SessionManager::default_location() |
| 5588 | .and_then(|manager| manager.load_session_goal(&session.metadata.id)) |
| 5589 | .map_err(|error| format!("saved session goal could not be loaded: {error}"))?; |
| 5590 | |
| 5591 | // Decide, without touching the live conversation, whether this load needs |
| 5592 | // another Runtime store and whether this host may release its own. Every |
| 5593 | // refusal below leaves the App, its workspace and its manager as they |
| 5594 | // were. |
| 5595 | if let Some(binding) = plan_store_adoption(app, &session)? { |
| 5596 | adopt_runtime_store(app, config, binding).await?; |
| 5597 | } |
| 5598 | // Only now, with the host already owning the store the conversation names, |
| 5599 | // does anything about the live session move. |
| 5600 | apply_loaded_session_with_goal(app, &mut next_config, session, goal.as_ref())?; |
| 5601 | // A file load reads a fresh disk snapshot. Even when the route's enum and |
| 5602 | // exact identity are unchanged, endpoint, key, headers, TLS, or retry |
| 5603 | // settings may have changed. Rebuild from that same validated snapshot so |
| 5604 | // compaction and other pre-turn engine work cannot retain the old client. |
| 5605 | let respawn = force_engine_respawn |
| 5606 | || loaded_session_requires_engine_respawn( |
| 5607 | app, |
| 5608 | previous_provider, |
| 5609 | &previous_provider_identity, |
| 5610 | &previous_workspace, |
| 5611 | ); |
| 5612 | *config = next_config; |
| 5613 | app.configured_models = config.custom_models.clone().unwrap_or_default(); |
| 5614 | codewhale_runtime::config::initialize_cloud_facts(config); |
| 5615 | app.refresh_notification_settings(config); |
| 5616 | Ok(LoadedSessionOutcome { respawn }) |
| 5617 | } |
| 5618 | |
| 5619 | /// Point this host's task manager at the Runtime store the loaded session |
| 5620 | /// names, releasing the one it held. |
| 5621 | /// |
| 5622 | /// A session switch used to refuse this outright: `TaskManager` was built at |
| 5623 | /// launch and never replaced, so a target store with any history read as "work |
| 5624 | /// this switch would abandon". It would not have abandoned anything — the |
| 5625 | /// conversation it was leaving keeps its store, and the target keeps its own — |
| 5626 | /// but the process could not *become* the target's owner either. Rebuilding the |
| 5627 | /// manager is what makes the target usable rather than merely readable. |
| 5628 | /// |
| 5629 | /// Ordering is load-bearing: `shutdown_and_wait` settles the turns this host |
| 5630 | /// was running and drops its engines, then `drop` releases the process-owner |
| 5631 | /// lock, and only then can `TaskManager::start` acquire the target's lock |
| 5632 | /// (`open_for_session` takes it before the store opens and holds it for the |
| 5633 | /// manager's lifetime). Callers must already have established that nothing in |
| 5634 | /// the current store still needs this process — see the checks in |
| 5635 | /// `apply_loaded_session_with_goal`. |
| 5636 | /// Rebinding onto a store returns a boxed future on purpose. |
| 5637 | /// |
| 5638 | /// It contains `TaskManager::start`, whose state machine is large enough on |
| 5639 | /// its own to matter to a caller's stack frame (the launch path already |
| 5640 | /// documents ~1.1 MiB for the task-manager futures). An `async fn` here would |
| 5641 | /// inline that machine into every caller's frame — including the session-load |
| 5642 | /// path, which libtest runs on a 2 MiB thread. Boxing pins the machine on the |
| 5643 | /// heap and leaves the caller holding a pointer. |
| 5644 | pub(crate) fn adopt_runtime_store<'a>( |
| 5645 | app: &'a mut App, |
| 5646 | config: &'a Config, |
| 5647 | binding: crate::runtime_threads::RuntimeStoreBinding, |
| 5648 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + 'a>> { |
| 5649 | Box::pin(adopt_runtime_store_inner(app, config, binding)) |
| 5650 | } |
| 5651 | |
| 5652 | async fn adopt_runtime_store_inner( |
| 5653 | app: &mut App, |
| 5654 | config: &Config, |
| 5655 | binding: crate::runtime_threads::RuntimeStoreBinding, |
| 5656 | ) -> Result<(), String> { |
| 5657 | let Some(previous) = app.runtime_services.task_manager.clone() else { |
| 5658 | return Err( |
| 5659 | "This session needs its own Runtime store, but this host has no task manager to rebind." |
| 5660 | .to_string(), |
| 5661 | ); |
| 5662 | }; |
| 5663 | let release = previous |
| 5664 | .prepare_store_release() |
| 5665 | .await |
| 5666 | .map_err(|error| error.to_string())?; |
| 5667 | let abandoned = previous.session_store_binding(); |
| 5668 | |
| 5669 | // Open the target *before* releasing the store this host holds. |
| 5670 | // |
| 5671 | // The previous shape took the manager out of the App, shut it down and then |
| 5672 | // tried to open the target, so a failed open left the host with no manager |
| 5673 | // at all and no way back. Ordering it this way means a refusal or a failed |
| 5674 | // open costs nothing: the old manager is still running, still holds its |
| 5675 | // lock, and the caller reports the error with the live session intact. |
| 5676 | // |
| 5677 | // The two stores are distinct paths with distinct owner locks, so holding |
| 5678 | // both briefly is legal — that is what makes the trial possible. |
| 5679 | let session_id = crate::tui::ui::event_loop::ensure_runtime_session_id(app); |
| 5680 | let manager = crate::task_manager::TaskManager::start( |
| 5681 | crate::task_manager::TaskManagerConfig::from_runtime( |
| 5682 | config, |
| 5683 | app.workspace.clone(), |
| 5684 | Some(app.model.clone()), |
| 5685 | Some(app.max_subagents.clamp(1, 4)), |
| 5686 | ), |
| 5687 | config.clone(), |
| 5688 | std::sync::Arc::clone(&app.plugin_registry), |
| 5689 | &session_id, |
| 5690 | Some(&binding), |
| 5691 | ) |
| 5692 | .await |
| 5693 | .map_err(|error| { |
| 5694 | format!( |
| 5695 | "This session's Runtime store could not be opened ({error}). \ |
| 5696 | The current session is unchanged." |
| 5697 | ) |
| 5698 | })?; |
| 5699 | |
| 5700 | // Committed: the target opened. Now settle and release the old store. |
| 5701 | if let Some(release) = release { |
| 5702 | release.close(); |
| 5703 | } |
| 5704 | previous.shutdown_and_wait().await.map_err(|error| { |
| 5705 | format!("Could not settle the Runtime work this session was running: {error}") |
| 5706 | })?; |
| 5707 | app.runtime_services.task_manager = Some(manager); |
| 5708 | drop(previous); |
| 5709 | |
| 5710 | // The store just released holds nothing this host still needs (the caller |
| 5711 | // checked), so let the reconciler set it aside if no document binds it. It |
| 5712 | // never unlinks: `retire_unbound_store` moves to `.set-aside/` and writes a |
| 5713 | // manifest, and refuses a store any document still names. |
| 5714 | if let Some(abandoned) = abandoned |
| 5715 | && abandoned.data_dir != binding.data_dir |
| 5716 | && let Ok(manager) = crate::session_manager::SessionManager::default_location() |
| 5717 | { |
| 5718 | codewhale_engine::session_reconcile::retire_unbound_store_in_background( |
| 5719 | manager, |
| 5720 | abandoned.data_dir, |
| 5721 | "conversation switched to another session's store", |
| 5722 | ); |
| 5723 | } |
| 5724 | Ok(()) |
| 5725 | } |
| 5726 | |
| 5727 | #[cfg(test)] |
| 5728 | mod profile_snapshot_tests { |
| 5729 | use super::*; |
| 5730 | |
| 5731 | fn profile_fixture(model: &str, base_url: &str) -> Config { |
| 5732 | let mut config: Config = toml::from_str(include_str!( |
| 5733 | "../../../../config/tests/fixtures/custom_models.toml" |
| 5734 | )) |
| 5735 | .expect("profile fixture"); |
| 5736 | config.set_legacy_root(Some("profile-snapshot-local-fixture".to_string()), None); |
| 5737 | config.default_text_model = Some(model.to_string()); |
| 5738 | config.providers.as_mut().unwrap().deepseek.base_url = Some(base_url.to_string()); |
| 5739 | let declaration = &mut config.custom_models.as_mut().unwrap()[0]; |
| 5740 | declaration.id = model.to_string(); |
| 5741 | declaration.base_url = base_url.to_string(); |
| 5742 | config |
| 5743 | } |
| 5744 | |
| 5745 | #[test] |
| 5746 | fn profile_switch_replaces_metadata_and_validated_route_snapshot() { |
| 5747 | std::thread::Builder::new() |
| 5748 | .stack_size(16 * 1024 * 1024) |
| 5749 | .spawn(|| { |
| 5750 | let _env = crate::test_support::lock_test_env(); |
| 5751 | let home = tempfile::tempdir().unwrap(); |
| 5752 | let _home = crate::test_support::EnvVarGuard::set( |
| 5753 | "CODEWHALE_HOME", |
| 5754 | home.path().as_os_str(), |
| 5755 | ); |
| 5756 | let mut config = profile_fixture("old-preview", "https://old.example.test/v1"); |
| 5757 | let mut options = crate::tui::test_support::test_tui_options(home.path()); |
| 5758 | options.model = config.default_model(); |
| 5759 | let mut app = App::new(options, &config); |
| 5760 | assert_eq!(app.configured_models[0].id, "old-preview"); |
| 5761 | |
| 5762 | let next = profile_fixture("new-preview", "https://new.example.test/v1"); |
| 5763 | let route = validated_profile_default_route(&next).unwrap(); |
| 5764 | assert_eq!( |
| 5765 | route.context_window.source, |
| 5766 | codewhale_engine::route_runtime::ContextWindowSource::UserDeclared, |
| 5767 | ); |
| 5768 | let expected_models = next.custom_models.clone().unwrap(); |
| 5769 | apply_validated_profile_config(&mut app, &mut config, "new", next, &route); |
| 5770 | assert_eq!(app.config_profile.as_deref(), Some("new")); |
| 5771 | assert_eq!(app.configured_models, expected_models); |
| 5772 | assert_eq!(app.configured_models, config.custom_models.clone().unwrap()); |
| 5773 | assert_eq!(app.model, "new-preview"); |
| 5774 | assert_eq!( |
| 5775 | app.active_route_base_url, |
| 5776 | route.candidate.endpoint().base_url |
| 5777 | ); |
| 5778 | assert_eq!(app.active_route_limits, Some(route.candidate.limits())); |
| 5779 | assert_eq!( |
| 5780 | app.active_context_window_source, |
| 5781 | route.context_window.source |
| 5782 | ); |
| 5783 | |
| 5784 | let mut empty = profile_fixture("no-metadata", "https://empty.example.test/v1"); |
| 5785 | empty.custom_models = None; |
| 5786 | let empty_route = validated_profile_default_route(&empty).unwrap(); |
| 5787 | apply_validated_profile_config(&mut app, &mut config, "empty", empty, &empty_route); |
| 5788 | assert!(app.configured_models.is_empty()); |
| 5789 | assert!(config.custom_models.is_none()); |
| 5790 | assert_eq!(app.config_profile.as_deref(), Some("empty")); |
| 5791 | assert_eq!(app.model, "no-metadata"); |
| 5792 | assert_eq!( |
| 5793 | app.active_route_base_url, |
| 5794 | empty_route.candidate.endpoint().base_url |
| 5795 | ); |
| 5796 | assert_eq!( |
| 5797 | app.active_context_window_source, |
| 5798 | empty_route.context_window.source |
| 5799 | ); |
| 5800 | assert_ne!( |
| 5801 | app.active_context_window_source, |
| 5802 | codewhale_engine::route_runtime::ContextWindowSource::UserDeclared, |
| 5803 | ); |
| 5804 | }) |
| 5805 | .unwrap() |
| 5806 | .join() |
| 5807 | .unwrap(); |
| 5808 | } |
| 5809 | } |
| 5810 |