| 1 | //! The TUI event loops. |
| 2 | //! |
| 3 | //! Moved verbatim out of `ui.rs`, which had grown past 19k lines. `run_tui` |
| 4 | //! owns terminal setup and teardown; `run_event_loop` is the frame, input, and |
| 5 | //! engine-event pump it drives. |
| 6 | |
| 7 | use super::clamp_event_poll_timeout; |
| 8 | use super::observer_hooks::{ |
| 9 | execute_session_error_hook, execute_session_state_transition_hooks, |
| 10 | execute_turn_end_observer_hook, surface_observer_hook_submission_failure, |
| 11 | }; |
| 12 | use super::task_projection::{ |
| 13 | AUTOMATION_SCAN_BUSY_INTERVAL, LiveRefresh, automation_scan_is_due, refresh_active_task_panel, |
| 14 | refresh_automation_panel, refresh_automation_panel_blocking, refresh_shell_exec_live_output, |
| 15 | }; |
| 16 | use super::*; |
| 17 | use crate::tui::shell_key_routing::ShellBindingId; |
| 18 | use codewhale_models::Role; |
| 19 | |
| 20 | use crate::tui::control_socket::SessionControl; |
| 21 | |
| 22 | type SkillCacheRefresh = ( |
| 23 | crate::tui::app::SkillCacheScope, |
| 24 | tokio::task::JoinHandle<Vec<(String, String)>>, |
| 25 | ); |
| 26 | |
| 27 | pub(super) fn event_owner_is_active( |
| 28 | current_session_id: Option<&str>, |
| 29 | owner_session_id: &str, |
| 30 | ) -> bool { |
| 31 | !owner_session_id.is_empty() && current_session_id == Some(owner_session_id) |
| 32 | } |
| 33 | |
| 34 | fn apply_recovery_messages( |
| 35 | app: &mut App, |
| 36 | session_id: &str, |
| 37 | workspace: &std::path::Path, |
| 38 | messages: Arc<Vec<Message>>, |
| 39 | ) -> bool { |
| 40 | if !event_owner_is_active(app.current_session_id.as_deref(), session_id) |
| 41 | || workspace != app.workspace |
| 42 | || !messages.starts_with(&app.api_messages) |
| 43 | { |
| 44 | return false; |
| 45 | } |
| 46 | app.set_api_messages(messages); |
| 47 | true |
| 48 | } |
| 49 | |
| 50 | /// Terminal data captured directly from an engine completion event. |
| 51 | /// |
| 52 | /// `runtime_turn_id` deliberately survives a completed turn for saved-session |
| 53 | /// and remote-control projections. It is therefore not an authority for a |
| 54 | /// later `TurnComplete`: a preflight rejection or manual compaction has no |
| 55 | /// model turn id and must not inherit the preceding model turn. |
| 56 | pub(super) struct TurnEndLifecycleReceipt { |
| 57 | turn_id: Option<String>, |
| 58 | status: &'static str, |
| 59 | error: Option<String>, |
| 60 | } |
| 61 | |
| 62 | impl TurnEndLifecycleReceipt { |
| 63 | pub(super) fn capture(event: &EngineEvent) -> Option<Self> { |
| 64 | let EngineEvent::TurnComplete { |
| 65 | turn_id, |
| 66 | status, |
| 67 | error, |
| 68 | .. |
| 69 | } = event |
| 70 | else { |
| 71 | return None; |
| 72 | }; |
| 73 | let status = match status { |
| 74 | codewhale_engine::core::events::TurnOutcomeStatus::Completed => "completed", |
| 75 | codewhale_engine::core::events::TurnOutcomeStatus::Failed => "failed", |
| 76 | codewhale_engine::core::events::TurnOutcomeStatus::Interrupted => "interrupted", |
| 77 | }; |
| 78 | Some(Self { |
| 79 | turn_id: turn_id.clone(), |
| 80 | status, |
| 81 | error: error.clone(), |
| 82 | }) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Build the lifecycle receipt from terminal data captured before dispatch. |
| 87 | pub(super) fn turn_end_lifecycle_event( |
| 88 | app: &App, |
| 89 | receipt: TurnEndLifecycleReceipt, |
| 90 | turn_elapsed: Duration, |
| 91 | ) -> codewhale_hooks::LifecycleEvent { |
| 92 | let kind = match receipt.status { |
| 93 | "completed" => "turn.completed", |
| 94 | "failed" => "turn.failed", |
| 95 | "interrupted" => "turn.interrupted", |
| 96 | _ => "turn.ended", |
| 97 | }; |
| 98 | codewhale_hooks::LifecycleEvent { |
| 99 | event: "turn_end".to_string(), |
| 100 | kind: kind.to_string(), |
| 101 | thread_id: app.hooks.session_id().to_string(), |
| 102 | turn_id: receipt.turn_id, |
| 103 | item_id: None, |
| 104 | payload: serde_json::json!({ |
| 105 | "status": receipt.status, |
| 106 | "duration_ms": turn_elapsed.as_millis() as u64, |
| 107 | "workspace": app.workspace.display().to_string(), |
| 108 | "error": receipt.error.as_deref().map(|message| codewhale_hooks::bounded_text( |
| 109 | message, |
| 110 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 111 | )), |
| 112 | }), |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// Apply only the projection owned by this host session. A delayed SetModel |
| 117 | /// receipt from the previous session cannot replace the current transcript. |
| 118 | pub(super) fn apply_engine_session_projection( |
| 119 | app: &mut App, |
| 120 | config: &Config, |
| 121 | event: EngineEvent, |
| 122 | ) -> bool { |
| 123 | let EngineEvent::SessionUpdated { |
| 124 | session_id, |
| 125 | messages, |
| 126 | system_prompt, |
| 127 | instruction_assembly, |
| 128 | model, |
| 129 | workspace, |
| 130 | checkpoint, |
| 131 | source, |
| 132 | } = event |
| 133 | else { |
| 134 | return false; |
| 135 | }; |
| 136 | if super::session_state::acknowledge_fresh_session( |
| 137 | app, |
| 138 | &session_id, |
| 139 | source.as_ref(), |
| 140 | &workspace, |
| 141 | &model, |
| 142 | ) { |
| 143 | super::session_state::persist_full_reset_snapshot(app); |
| 144 | } |
| 145 | if !app.owns_session_projection(source.as_ref()) { |
| 146 | if let Some(request) = checkpoint.as_ref() { |
| 147 | request.fail("checkpoint projection belongs to another native source"); |
| 148 | } |
| 149 | tracing::debug!( |
| 150 | ?source, |
| 151 | "session projection did not match its admitted native owner" |
| 152 | ); |
| 153 | return false; |
| 154 | } |
| 155 | if let Some(request) = checkpoint.as_ref() { |
| 156 | if request.is_stale() |
| 157 | || request.caller.agent_id.is_some() |
| 158 | || app.current_session_id.as_deref() != Some(request.caller.session_id.as_str()) |
| 159 | || app.runtime_turn_id.as_deref() != Some(request.caller.turn_id.as_str()) |
| 160 | || app.workspace != request.caller.workspace |
| 161 | || !app.is_loading |
| 162 | || app.suppress_stream_events_until_turn_complete |
| 163 | { |
| 164 | request.fail("checkpoint does not belong to the active terminal turn"); |
| 165 | return false; |
| 166 | } |
| 167 | if let Err(error) = request.validate_prefix(&session_id, &workspace, &messages) { |
| 168 | request.fail(error); |
| 169 | return false; |
| 170 | } |
| 171 | } |
| 172 | // SetModel can emit the old session while a host-owned |
| 173 | // SyncSession is still queued. Reject that entire stale |
| 174 | // projection before changing transcript or persistence. |
| 175 | if !event_owner_is_active(app.current_session_id.as_deref(), &session_id) { |
| 176 | tracing::debug!( |
| 177 | expected = ?app.current_session_id, |
| 178 | received = %session_id, |
| 179 | "ignoring stale engine session projection" |
| 180 | ); |
| 181 | return false; |
| 182 | } |
| 183 | if app.last_known_goal_state.is_some() |
| 184 | && let Err(error) = persist_current_session_goal(app) |
| 185 | { |
| 186 | surface_goal_persistence_failure(app, &error); |
| 187 | } |
| 188 | app.set_api_messages(messages); |
| 189 | // #6190: the projection is the engine's own record, so it is where a |
| 190 | // steer's acceptance becomes observable — and the only place the steer's |
| 191 | // real message index is known. Promote before anything else reads the |
| 192 | // transcript, so live order equals record order by construction. |
| 193 | crate::tui::ui::dispatch::settle_accepted_steers(app); |
| 194 | app.system_prompt = system_prompt; |
| 195 | app.instruction_assembly = instruction_assembly; |
| 196 | if !app.auto_model { |
| 197 | let accepted_route = |
| 198 | app.pending_turn_route |
| 199 | .as_ref() |
| 200 | .is_some_and(|(provider, accepted_model, auto)| { |
| 201 | !auto && *provider == app.api_provider && accepted_model == &model |
| 202 | }); |
| 203 | let budget = accepted_route.then_some(( |
| 204 | app.active_route_limits, |
| 205 | app.active_context_window, |
| 206 | app.active_context_window_source, |
| 207 | )); |
| 208 | app.set_model_selection(model); |
| 209 | if let Some((limits, window, source)) = budget { |
| 210 | app.active_route_limits = limits; |
| 211 | app.active_context_window = window; |
| 212 | app.active_context_window_source = source; |
| 213 | } |
| 214 | } |
| 215 | app.update_model_compaction_budget(); |
| 216 | maybe_warn_context_pressure(app); |
| 217 | if app.workspace != workspace { |
| 218 | apply_workspace_runtime_state(app, config, workspace); |
| 219 | } |
| 220 | if let Some(request) = checkpoint { |
| 221 | let prepared = SessionManager::default_location() |
| 222 | .map_err(|error| error.to_string()) |
| 223 | .and_then(|manager| build_session_snapshot(app, &manager)); |
| 224 | let mut session = match prepared { |
| 225 | Ok(session) => session, |
| 226 | Err(error) => { |
| 227 | request.fail(error); |
| 228 | return false; |
| 229 | } |
| 230 | }; |
| 231 | let projection = saved_work_projection(app, &session); |
| 232 | session.make_storage_compatible(); |
| 233 | if let Err(error) = request.validate_prefix( |
| 234 | &session.metadata.id, |
| 235 | &session.metadata.workspace, |
| 236 | &session.messages, |
| 237 | ) { |
| 238 | request.fail(error); |
| 239 | return false; |
| 240 | } |
| 241 | let (reply, receiver) = tokio::sync::oneshot::channel(); |
| 242 | if !super::session_state::try_persist_session( |
| 243 | app, |
| 244 | PersistRequest::AcknowledgedCheckpoint { session, reply }, |
| 245 | ) { |
| 246 | request.fail("terminal persistence actor is unavailable"); |
| 247 | return false; |
| 248 | } |
| 249 | if let Some(work) = app.runtime_services.work.as_ref() |
| 250 | && work.has_pending_publish() |
| 251 | { |
| 252 | match work.publish_pending_sync_matching( |
| 253 | projection.owner.as_deref(), |
| 254 | projection |
| 255 | .state |
| 256 | .as_ref() |
| 257 | .and_then(|state| state.graph.as_ref()), |
| 258 | ) { |
| 259 | Ok(false) if work.has_pending_publish() => { |
| 260 | app.show_event_notice( |
| 261 | "A newer Work update remains pending".to_string(), |
| 262 | StatusToastLevel::Warning, |
| 263 | ); |
| 264 | } |
| 265 | Ok(_) => {} |
| 266 | Err(error) => { |
| 267 | request.fail(format!( |
| 268 | "checkpoint queued but Work projection failed: {error}" |
| 269 | )); |
| 270 | return false; |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | codewhale_util::utils::spawn_supervised( |
| 275 | "terminal-session-checkpoint", |
| 276 | std::panic::Location::caller(), |
| 277 | async move { |
| 278 | tokio::select! { |
| 279 | biased; |
| 280 | () = request.withdraw.cancelled() => request.fail("checkpoint withdrawn; a write already in progress may have completed"), |
| 281 | result = receiver => match result { |
| 282 | Ok(Ok(publication)) => request.succeed(publication.checkpoint_receipt), |
| 283 | Ok(Err(error)) => request.fail(error), |
| 284 | Err(_) => request.fail("terminal persistence actor dropped checkpoint acknowledgement"), |
| 285 | }, |
| 286 | } |
| 287 | }, |
| 288 | ); |
| 289 | return true; |
| 290 | } |
| 291 | if (app.is_loading || app.is_compacting || app.is_purging) |
| 292 | && !app.dispatch_in_flight |
| 293 | && let Ok(manager) = SessionManager::default_location() |
| 294 | { |
| 295 | if let Ok(session) = build_session_snapshot(app, &manager) { |
| 296 | let projection = saved_work_projection(app, &session); |
| 297 | app.session_title = Some(session.metadata.title.clone()); |
| 298 | // The engine's session id was pinned above, so |
| 299 | // every checkpoint of this session lands in the |
| 300 | // same per-session file. |
| 301 | if let Err(err) = persist_with_pending_work_boundary( |
| 302 | app, |
| 303 | PersistRequest::SaveCheckpoint { session }, |
| 304 | &projection, |
| 305 | ) { |
| 306 | app.show_event_notice( |
| 307 | format!("To-do list update pending while saving checkpoint ({err})"), |
| 308 | StatusToastLevel::Warning, |
| 309 | ); |
| 310 | } |
| 311 | } |
| 312 | } else if app.session_title.is_none() { |
| 313 | // Never synchronously reload the growing session |
| 314 | // JSON on the event-loop task just to recover a |
| 315 | // title. The in-memory metadata cache is authoritative. |
| 316 | let cached = app |
| 317 | .current_session_metadata |
| 318 | .as_ref() |
| 319 | .filter(|metadata| metadata.id == session_id) |
| 320 | .map(|metadata| metadata.title.clone()); |
| 321 | app.session_title = cached.or_else(|| derive_session_title(&app.api_messages)); |
| 322 | } |
| 323 | true |
| 324 | } |
| 325 | |
| 326 | fn current_session_fleet_workers_status( |
| 327 | locale: codewhale_localization::Locale, |
| 328 | count: usize, |
| 329 | ) -> String { |
| 330 | codewhale_localization::tr( |
| 331 | locale, |
| 332 | codewhale_localization::MessageId::SubagentsCurrentSessionFleetWorkersStatus, |
| 333 | ) |
| 334 | .replace("{count}", &count.to_string()) |
| 335 | } |
| 336 | |
| 337 | /// A turn is unsettled until its authoritative terminal event lands. A local |
| 338 | /// cancel clears `is_loading` at once, but the engine's `TurnComplete` is still |
| 339 | /// owed: until it arrives the recovery checkpoint is the only complete record |
| 340 | /// of that turn, so shutdown must not declare the session settled (U02-09). |
| 341 | fn turn_unsettled_for_shutdown(app: &App) -> bool { |
| 342 | app.is_loading || app.dispatch_in_flight || app.suppress_stream_events_until_turn_complete |
| 343 | } |
| 344 | |
| 345 | /// Host state can change without a model turn, including learning the Runtime |
| 346 | /// binding of a resumed legacy session. Save that state through its captured |
| 347 | /// source; the shutdown snapshot retains its recovery checkpoint. |
| 348 | pub(super) fn persist_settled_session_on_shutdown( |
| 349 | app: &mut App, |
| 350 | handle: &persistence_actor::PersistActorHandle, |
| 351 | ) -> Result<bool, String> { |
| 352 | if turn_unsettled_for_shutdown(app) || app.current_session_id.is_none() { |
| 353 | return Ok(false); |
| 354 | } |
| 355 | let manager = SessionManager::default_location().map_err(|error| error.to_string())?; |
| 356 | let session = build_session_snapshot(app, &manager)?; |
| 357 | let mut request = PersistRequest::SessionSnapshot(session); |
| 358 | super::session_state::prepare_session_publication(app, &mut request)?; |
| 359 | if !handle.try_send(request) { |
| 360 | return Err("persistence actor is unavailable during shutdown".into()); |
| 361 | } |
| 362 | Ok(true) |
| 363 | } |
| 364 | |
| 365 | #[derive(Debug)] |
| 366 | struct TranslationAccountingContext { |
| 367 | source: codewhale_engine::cost_status::NativeUsageSource, |
| 368 | } |
| 369 | |
| 370 | struct SettledTranslation { |
| 371 | translated: anyhow::Result<String>, |
| 372 | usage: Option<codewhale_models::Usage>, |
| 373 | } |
| 374 | |
| 375 | impl TranslationAccountingContext { |
| 376 | fn capture(app: &App, kind: &str, sequence: u64) -> Self { |
| 377 | let origin = app.session_write_receipt.as_ref().and_then(|receipt| { |
| 378 | receipt |
| 379 | .usage_origin(codewhale_engine::cost_status::scope_token()) |
| 380 | .ok() |
| 381 | }); |
| 382 | Self { |
| 383 | source: codewhale_engine::cost_status::NativeUsageSource::capture_with_origin( |
| 384 | format!("translation:{kind}:{sequence}:{}", uuid::Uuid::new_v4()), |
| 385 | codewhale_engine::cost_status::UsageSpendOwner::Auxiliary, |
| 386 | origin, |
| 387 | ), |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | fn settle( |
| 392 | self, |
| 393 | response: anyhow::Result<codewhale_engine::client::TranslationProviderResponse>, |
| 394 | ) -> SettledTranslation { |
| 395 | match response { |
| 396 | Ok(response) => SettledTranslation { |
| 397 | translated: response.translated, |
| 398 | usage: if response.accounting.is_some() { |
| 399 | None |
| 400 | } else { |
| 401 | response.usage |
| 402 | }, |
| 403 | }, |
| 404 | Err(error) => SettledTranslation { |
| 405 | translated: Err(error), |
| 406 | usage: None, |
| 407 | }, |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | fn accrue_translation_usage(app: &mut App, usage: &codewhale_models::Usage) { |
| 413 | let turn_tokens = usage.input_tokens.saturating_add(usage.output_tokens); |
| 414 | app.session.total_tokens = app.session.total_tokens.saturating_add(turn_tokens); |
| 415 | app.session.total_conversation_tokens = app |
| 416 | .session |
| 417 | .total_conversation_tokens |
| 418 | .saturating_add(turn_tokens); |
| 419 | app.session.total_input_tokens = app |
| 420 | .session |
| 421 | .total_input_tokens |
| 422 | .saturating_add(usage.input_tokens); |
| 423 | app.session.total_output_tokens = app |
| 424 | .session |
| 425 | .total_output_tokens |
| 426 | .saturating_add(usage.output_tokens); |
| 427 | if usage.prompt_cache_hit_tokens.is_some() |
| 428 | || usage.prompt_cache_miss_tokens.is_some() |
| 429 | || usage.prompt_cache_write_tokens.is_some() |
| 430 | { |
| 431 | let classes = codewhale_engine::pricing::token_usage_for_pricing(usage); |
| 432 | app.session.total_cache_hit_tokens = app |
| 433 | .session |
| 434 | .total_cache_hit_tokens |
| 435 | .saturating_add(u32::try_from(classes.cache_read).unwrap_or(u32::MAX)); |
| 436 | app.session.total_cache_miss_tokens = app |
| 437 | .session |
| 438 | .total_cache_miss_tokens |
| 439 | .saturating_add(u32::try_from(classes.input).unwrap_or(u32::MAX)); |
| 440 | app.session.total_cache_write_tokens = app |
| 441 | .session |
| 442 | .total_cache_write_tokens |
| 443 | .saturating_add(u32::try_from(classes.cache_write).unwrap_or(u32::MAX)); |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fn translation_origin(app: &App) -> (Option<String>, Option<String>) { |
| 448 | // Fixed-size one-way identities avoid retaining raw imported ids in a |
| 449 | // detached completion envelope without introducing truncation aliases. |
| 450 | let fingerprint = |
| 451 | |value: Option<&str>| value.map(codewhale_engine::cost_status::usage_source_fingerprint); |
| 452 | ( |
| 453 | fingerprint(app.current_session_id.as_deref()), |
| 454 | fingerprint(app.runtime_turn_id.as_deref()), |
| 455 | ) |
| 456 | } |
| 457 | |
| 458 | fn translation_origin_is_current( |
| 459 | app: &App, |
| 460 | origin_session_fingerprint: Option<&str>, |
| 461 | origin_turn_fingerprint: Option<&str>, |
| 462 | ) -> bool { |
| 463 | let current = translation_origin(app); |
| 464 | current.0.as_deref() == origin_session_fingerprint |
| 465 | && current.1.as_deref() == origin_turn_fingerprint |
| 466 | } |
| 467 | |
| 468 | fn translation_session_is_current(app: &App, origin_session_fingerprint: Option<&str>) -> bool { |
| 469 | translation_origin(app).0.as_deref() == origin_session_fingerprint |
| 470 | } |
| 471 | |
| 472 | async fn exact_translation_client( |
| 473 | config: &Config, |
| 474 | route: &codewhale_engine::core::events::TurnRoute, |
| 475 | ) -> anyhow::Result<Arc<CodewhaleClient>> { |
| 476 | let identity = config |
| 477 | .resolve_persisted_provider_identity( |
| 478 | Some(route.provider.as_str()), |
| 479 | Some(&route.provider_identity), |
| 480 | ) |
| 481 | .map_err(anyhow::Error::msg)?; |
| 482 | let validated = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 483 | config, |
| 484 | &identity, |
| 485 | Some(&route.model), |
| 486 | ) |
| 487 | .map_err(anyhow::Error::msg)? |
| 488 | .validate_async() |
| 489 | .await |
| 490 | .map_err(anyhow::Error::msg)?; |
| 491 | if validated.identity.key.as_str() != route.provider_identity |
| 492 | || validated.model != route.model |
| 493 | || validated.candidate.endpoint().base_url != route.base_url |
| 494 | { |
| 495 | anyhow::bail!( |
| 496 | "translation route changed after turn dispatch; refusing to reuse a different provider client" |
| 497 | ); |
| 498 | } |
| 499 | if let Some(receipt) = route.receipt.as_ref() |
| 500 | && &validated.client.turn_route_receipt() != receipt |
| 501 | { |
| 502 | anyhow::bail!( |
| 503 | "translation credential or endpoint changed after turn dispatch; refusing stale completion ownership" |
| 504 | ); |
| 505 | } |
| 506 | Ok(Arc::new(validated.client)) |
| 507 | } |
| 508 | |
| 509 | /// Bind the Runtime thread store to a session before the process-owner lock |
| 510 | /// is taken, so a second Codewhale on the same machine does not collide on |
| 511 | /// the default root (#5630). This id is only the initial store anchor; saved |
| 512 | /// metadata retains the actual store binding when launch creates a new id. |
| 513 | pub(crate) fn ensure_runtime_session_id(app: &mut App) -> String { |
| 514 | if let Some(existing) = app |
| 515 | .current_session_id |
| 516 | .as_deref() |
| 517 | .map(str::trim) |
| 518 | .filter(|id| !id.is_empty()) |
| 519 | { |
| 520 | return existing.to_string(); |
| 521 | } |
| 522 | let session_id = uuid::Uuid::new_v4().to_string(); |
| 523 | app.set_current_session_id(Some(session_id.clone())); |
| 524 | if let Err(error) = super::session_state::expect_fresh_session(app, &session_id) { |
| 525 | tracing::warn!(%error, "new session publication source could not be established"); |
| 526 | } |
| 527 | session_id |
| 528 | } |
| 529 | |
| 530 | /// How long session confirmation may wait before the UI reports it pending. |
| 531 | pub(super) const LAUNCH_SESSION_SYNC_WAIT: Duration = Duration::from_secs(2); |
| 532 | |
| 533 | const TURN_COMPLETE_SNAPSHOT_WAIT: Duration = LAUNCH_SESSION_SYNC_WAIT; |
| 534 | |
| 535 | async fn await_terminal_snapshot_with_timeout<T>( |
| 536 | timeout: Duration, |
| 537 | snapshot: impl std::future::Future<Output = anyhow::Result<T>>, |
| 538 | ) -> anyhow::Result<T> { |
| 539 | tokio::time::timeout(timeout, snapshot).await.map_err(|_| { |
| 540 | anyhow::anyhow!( |
| 541 | "Engine session snapshot timed out after {} ms", |
| 542 | timeout.as_millis() |
| 543 | ) |
| 544 | })? |
| 545 | } |
| 546 | |
| 547 | /// Require the exact Engine identity before a startup submit consumes its draft. |
| 548 | pub(crate) async fn await_engine_session_sync( |
| 549 | engine_handle: &EngineHandle, |
| 550 | session_id: Option<&str>, |
| 551 | owner: Option<&codewhale_engine::session_manager::SessionWriteOwner>, |
| 552 | ) -> Result<()> { |
| 553 | let snapshot = tokio::time::timeout( |
| 554 | LAUNCH_SESSION_SYNC_WAIT, |
| 555 | engine_handle.get_session_snapshot(), |
| 556 | ) |
| 557 | .await |
| 558 | .map_err(|_| { |
| 559 | anyhow::anyhow!("The Engine session has not been confirmed; the draft is preserved.") |
| 560 | })??; |
| 561 | anyhow::ensure!( |
| 562 | session_id == Some(snapshot.session_id.as_str()) |
| 563 | && owner |
| 564 | .zip(snapshot.source.as_ref()) |
| 565 | .is_some_and(|(owner, source)| owner.matches_source(source)), |
| 566 | "The Engine session acknowledgement does not match this UI; the draft is preserved." |
| 567 | ); |
| 568 | Ok(()) |
| 569 | } |
| 570 | |
| 571 | fn persist_current_session_goal(app: &App) -> Result<(), String> { |
| 572 | let session_id = app |
| 573 | .current_session_id |
| 574 | .as_deref() |
| 575 | .ok_or_else(|| "session id is not established".to_string())?; |
| 576 | let manager = SessionManager::default_location() |
| 577 | .map_err(|error| format!("could not open the session store: {error}"))?; |
| 578 | manager |
| 579 | .save_session_goal(session_id, app.last_known_goal_state.as_ref()) |
| 580 | .map_err(|error| error.to_string()) |
| 581 | } |
| 582 | |
| 583 | pub(crate) fn surface_goal_persistence_failure(app: &mut App, error: &str) { |
| 584 | app.push_status_toast( |
| 585 | format!("Goal progress is not durable yet: {error}"), |
| 586 | StatusToastLevel::Warning, |
| 587 | None, |
| 588 | ); |
| 589 | } |
| 590 | |
| 591 | /// Apply Space only to the owner stored by the final render pass. |
| 592 | pub(super) fn handle_transcript_space(app: &mut App) -> bool { |
| 593 | let Some((owner, fold_target)) = app.viewport.transcript_cache.take_transcript_action() else { |
| 594 | return false; |
| 595 | }; |
| 596 | let idx = owner.cell_index; |
| 597 | if owner.identity_epoch != app.transcript_identity_epoch { |
| 598 | return false; |
| 599 | } |
| 600 | let Some(cell) = app.cell_at_virtual_index(idx) else { |
| 601 | return false; |
| 602 | }; |
| 603 | let is_thinking = matches!(cell, HistoryCell::Thinking { .. }); |
| 604 | let selected_first_line = app |
| 605 | .viewport |
| 606 | .transcript_selection |
| 607 | .ordered_endpoints() |
| 608 | .filter(|(start, _)| { |
| 609 | app.viewport |
| 610 | .transcript_cache |
| 611 | .line_meta() |
| 612 | .get(start.line_index) |
| 613 | .and_then(|meta| meta.cell_line()) |
| 614 | .is_some_and(|(rendered, _)| app.original_cell_index_for_rendered(rendered) == idx) |
| 615 | }) |
| 616 | .and_then(|_| { |
| 617 | app.viewport |
| 618 | .transcript_cache |
| 619 | .line_meta() |
| 620 | .iter() |
| 621 | .position(|meta| { |
| 622 | meta.cell_line().is_some_and(|(rendered, _)| { |
| 623 | app.original_cell_index_for_rendered(rendered) == idx |
| 624 | }) |
| 625 | }) |
| 626 | }); |
| 627 | if let Some(target) = fold_target.filter(|_| !app.collapsed_cells.contains(&idx)) { |
| 628 | if target.owner != owner { |
| 629 | return false; |
| 630 | } |
| 631 | if is_thinking && !app.show_thinking { |
| 632 | return false; |
| 633 | } |
| 634 | // The rendered action names the state the user is asking for, so |
| 635 | // record that outright. A relative bit would be re-read as its |
| 636 | // opposite the next time a display preference changed (#5847). |
| 637 | let intent = match target.action { |
| 638 | CellFoldAction::Expand => TranscriptFold::Expanded, |
| 639 | CellFoldAction::Collapse => TranscriptFold::Collapsed, |
| 640 | }; |
| 641 | app.cell_folds.insert(idx, intent); |
| 642 | } else if app.toggle_tool_run_expansion_at(idx) { |
| 643 | return true; |
| 644 | } else if !app.collapsed_cells.remove(&idx) { |
| 645 | if is_thinking { |
| 646 | return false; |
| 647 | } |
| 648 | app.cell_folds.insert(idx, TranscriptFold::Collapsed); |
| 649 | } |
| 650 | if let Some(line_index) = selected_first_line { |
| 651 | // A middle-body row may disappear or become another cell after the |
| 652 | // fold. Keep the selected owner at its stable first row (#6876). |
| 653 | let point = crate::tui::selection::TranscriptSelectionPoint { |
| 654 | line_index, |
| 655 | column: 0, |
| 656 | }; |
| 657 | app.viewport.transcript_selection.clear(); |
| 658 | app.viewport.transcript_selection.anchor = Some(point); |
| 659 | app.viewport.transcript_selection.head = Some(point); |
| 660 | app.viewport.transcript_selection.owner = Some(owner); |
| 661 | } |
| 662 | app.mark_history_updated(); |
| 663 | true |
| 664 | } |
| 665 | |
| 666 | async fn apply_launch_action( |
| 667 | terminal: &mut AppTerminal, |
| 668 | app: &mut App, |
| 669 | engine_handle: &mut EngineHandle, |
| 670 | config: &mut Config, |
| 671 | action: crate::tui::underwater::LaunchAction, |
| 672 | ) -> Result<bool> { |
| 673 | match action { |
| 674 | crate::tui::underwater::LaunchAction::None => {} |
| 675 | crate::tui::underwater::LaunchAction::ConnectModel => { |
| 676 | app.launch.dissolve_card(app.ambient_clock_ms); |
| 677 | app.view_stack |
| 678 | .push(crate::tui::account_login::ConnectionSetupView::new( |
| 679 | app.ui_locale, |
| 680 | )); |
| 681 | } |
| 682 | crate::tui::underwater::LaunchAction::ReturnToSession => app.launch.dismiss(), |
| 683 | crate::tui::underwater::LaunchAction::NewSession => { |
| 684 | let result = begin_launch_session(app, None); |
| 685 | if apply_command_result(terminal, app, engine_handle, config, result).await? { |
| 686 | return Ok(true); |
| 687 | } |
| 688 | } |
| 689 | crate::tui::underwater::LaunchAction::ResumeSession(session_id) => { |
| 690 | crate::tui::underwater::open_launch_resume_confirm(app, &session_id); |
| 691 | } |
| 692 | crate::tui::underwater::LaunchAction::ShowRecent => { |
| 693 | app.launch.expand_recent(); |
| 694 | } |
| 695 | crate::tui::underwater::LaunchAction::BrowseSessions => { |
| 696 | app.launch.dissolve_card(app.ambient_clock_ms); |
| 697 | app.view_stack.push( |
| 698 | SessionPickerView::new(&app.workspace, app.ui_locale) |
| 699 | .with_current_session(app.current_session_id.as_deref()), |
| 700 | ); |
| 701 | } |
| 702 | crate::tui::underwater::LaunchAction::McpManager => { |
| 703 | app.launch.dissolve_card(app.ambient_clock_ms); |
| 704 | open_mcp_extensions(app); |
| 705 | } |
| 706 | crate::tui::underwater::LaunchAction::Skills => { |
| 707 | app.launch.dissolve_card(app.ambient_clock_ms); |
| 708 | let result = commands::CommandResult::action(AppAction::OpenExtensions { |
| 709 | tab: crate::tui::views::extensions::ExtensionsTab::Skills, |
| 710 | }); |
| 711 | if apply_command_result(terminal, app, engine_handle, config, result).await? { |
| 712 | return Ok(true); |
| 713 | } |
| 714 | } |
| 715 | crate::tui::underwater::LaunchAction::Help => { |
| 716 | toggle_help_view(app); |
| 717 | } |
| 718 | } |
| 719 | app.needs_redraw = true; |
| 720 | Ok(false) |
| 721 | } |
| 722 | |
| 723 | /// Route plain input that must be decided before the composer sees it. |
| 724 | /// |
| 725 | /// The raw-paste fallback intentionally holds the first ASCII character for |
| 726 | /// a few milliseconds. Space must use that same ambiguity window: a second |
| 727 | /// rapid character proves it was paste payload, while a lone held Space can |
| 728 | /// become the rendered transcript action when the hold expires. |
| 729 | pub(super) fn handle_plain_key_before_composer( |
| 730 | app: &mut App, |
| 731 | key: &KeyEvent, |
| 732 | now: Instant, |
| 733 | ) -> bool { |
| 734 | crate::tui::paste::handle_paste_burst_key(app, key, now) |
| 735 | } |
| 736 | |
| 737 | /// Flush a raw-paste ambiguity window without losing a leading Space. |
| 738 | /// |
| 739 | /// `FlushResult::Paste` is always composer payload. A lone typed Space is a |
| 740 | /// transcript action only when the composer is still empty and the last |
| 741 | /// rendered owner accepts it; otherwise it remains ordinary input. |
| 742 | pub(super) fn flush_paste_burst_before_composer(app: &mut App, now: Instant) -> bool { |
| 743 | if !app.view_stack.is_empty() { |
| 744 | // One grammar buffer: a modal owns keys. Held burst must not leak |
| 745 | // into the composer (leaky `/model` after the picker opens). |
| 746 | app.paste_burst.clear_after_explicit_paste(); |
| 747 | return false; |
| 748 | } |
| 749 | match app.take_paste_burst_flush_if_enabled(now) { |
| 750 | codewhale_tui_kit::paste_burst::FlushResult::Paste(text) => { |
| 751 | // Terminals without bracketed paste deliver a dropped file the |
| 752 | // same way; attach it exactly as `insert_paste_text` would. |
| 753 | if !app.attach_pasted_image_paths(&text) { |
| 754 | app.insert_str(&text); |
| 755 | } |
| 756 | true |
| 757 | } |
| 758 | codewhale_tui_kit::paste_burst::FlushResult::TextContinuation(text) => { |
| 759 | app.insert_str(&text); |
| 760 | true |
| 761 | } |
| 762 | codewhale_tui_kit::paste_burst::FlushResult::Typed(' ') |
| 763 | if app.input.is_empty() && handle_transcript_space(app) => |
| 764 | { |
| 765 | true |
| 766 | } |
| 767 | codewhale_tui_kit::paste_burst::FlushResult::Typed(ch) => { |
| 768 | let mention_menu_limit = app.mention_menu_limit; |
| 769 | if app.vim_is_normal_mode() |
| 770 | && visible_slash_menu_entries(app, SLASH_MENU_LIMIT).is_empty() |
| 771 | && crate::tui::file_mention::visible_mention_menu_entries(app, mention_menu_limit) |
| 772 | .is_empty() |
| 773 | { |
| 774 | vim_mode::handle_vim_normal_key(app, ch); |
| 775 | app.needs_redraw = true; |
| 776 | } else { |
| 777 | app.insert_char(ch); |
| 778 | } |
| 779 | true |
| 780 | } |
| 781 | codewhale_tui_kit::paste_burst::FlushResult::SuppressionExpired => { |
| 782 | app.needs_redraw = true; |
| 783 | true |
| 784 | } |
| 785 | codewhale_tui_kit::paste_burst::FlushResult::None => false, |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | /// The shell's key admission, asked exactly as the event loop asks it: which |
| 790 | /// binding does this key press, for whoever owns the keyboard right now? |
| 791 | /// |
| 792 | /// Every seam below calls this instead of re-deriving focus from |
| 793 | /// `view_stack`, `launch.visible`, or — the bug this replaces — whether the |
| 794 | /// composer happens to hold text. |
| 795 | pub(crate) fn shell_binding_for_key(app: &App, key: &KeyEvent) -> Option<ShellBindingId> { |
| 796 | let focus = app.focus(); |
| 797 | crate::tui::shell_key_routing::route(focus, key).filter(|binding| { |
| 798 | !(*binding == ShellBindingId::PermissionCycle |
| 799 | && focus == crate::tui::shell_key_routing::Focus::Modal(ModalKind::Config) |
| 800 | && app.view_stack.contains_kind(ModalKind::Approval)) |
| 801 | }) |
| 802 | } |
| 803 | |
| 804 | /// What pressing Tab did — see [`dispatch_tab_key`]. |
| 805 | #[derive(Debug, PartialEq, Eq)] |
| 806 | pub(crate) enum TabDispatch { |
| 807 | /// One of the composer's own completions consumed the key. |
| 808 | Completion, |
| 809 | /// Nobody owns Tab in this focus state. |
| 810 | Ignored, |
| 811 | } |
| 812 | |
| 813 | /// Tab dispatch, lifted out of the event loop body so a test can press Tab. |
| 814 | /// |
| 815 | /// The composer's completions get the key first: a mention menu, a slash |
| 816 | /// menu, an in-progress command or file mention, a waiting prompt |
| 817 | /// suggestion. Tab never changes the mode: the permission dial on Shift+Tab |
| 818 | /// owns that. |
| 819 | pub(crate) fn dispatch_tab_key( |
| 820 | app: &mut App, |
| 821 | mention_menu_entries: &[String], |
| 822 | slash_menu_entries: &[crate::tui::widgets::SlashMenuEntry], |
| 823 | ) -> TabDispatch { |
| 824 | if !mention_menu_entries.is_empty() |
| 825 | && crate::tui::file_mention::apply_mention_menu_selection(app, mention_menu_entries) |
| 826 | { |
| 827 | return TabDispatch::Completion; |
| 828 | } |
| 829 | if !slash_menu_entries.is_empty() && apply_slash_menu_selection(app, slash_menu_entries, true) { |
| 830 | return TabDispatch::Completion; |
| 831 | } |
| 832 | if try_autocomplete_slash_command(app) { |
| 833 | return TabDispatch::Completion; |
| 834 | } |
| 835 | if crate::tui::file_mention::try_autocomplete_file_mention(app) { |
| 836 | return TabDispatch::Completion; |
| 837 | } |
| 838 | if app.input.is_empty() |
| 839 | && let Some(suggestion) = app.prompt_suggestion.take() |
| 840 | { |
| 841 | app.input = suggestion; |
| 842 | app.cursor_position = app.input.chars().count(); |
| 843 | app.needs_redraw = true; |
| 844 | return TabDispatch::Completion; |
| 845 | } |
| 846 | TabDispatch::Ignored |
| 847 | } |
| 848 | |
| 849 | /// Whether a mouse event is a wheel/trackpad scroll in any direction. |
| 850 | fn is_scroll_event(mouse: &crossterm::event::MouseEvent) -> bool { |
| 851 | matches!( |
| 852 | mouse.kind, |
| 853 | crossterm::event::MouseEventKind::ScrollUp |
| 854 | | crossterm::event::MouseEventKind::ScrollDown |
| 855 | | crossterm::event::MouseEventKind::ScrollLeft |
| 856 | | crossterm::event::MouseEventKind::ScrollRight |
| 857 | ) |
| 858 | } |
| 859 | |
| 860 | /// Bound on how many scroll events one gesture may fold into a single frame, |
| 861 | /// so a stuck wheel cannot starve the draw. |
| 862 | const MAX_COALESCED_SCROLLS: usize = 64; |
| 863 | |
| 864 | /// Apply every queued scroll event of the current gesture except the last, |
| 865 | /// and return that last one for the caller to handle normally. |
| 866 | /// |
| 867 | /// A trackpad emits a burst of scroll events. Handling them one per loop |
| 868 | /// iteration meant one frame each, and the frame limiter then spaced those |
| 869 | /// frames out, so the scroll arrived as a slow crawl long after the fingers |
| 870 | /// stopped. Resize events have been coalesced this way since #65; scroll |
| 871 | /// never was. The scroll handlers only accumulate into |
| 872 | /// `viewport.pending_scroll_delta`, so folding the burst in costs one cheap |
| 873 | /// call each and exactly one draw for the whole gesture. |
| 874 | /// |
| 875 | /// A non-scroll event ends the burst and is pushed back unread. |
| 876 | pub(crate) fn coalesce_scroll_burst( |
| 877 | app: &mut App, |
| 878 | first: crossterm::event::MouseEvent, |
| 879 | input: &TerminalInputPump, |
| 880 | pending: &mut VecDeque<ObservedTerminalEvent>, |
| 881 | ) -> std::io::Result<crossterm::event::MouseEvent> { |
| 882 | if !is_scroll_event(&first) { |
| 883 | return Ok(first); |
| 884 | } |
| 885 | let mut latest = first; |
| 886 | for _ in 0..MAX_COALESCED_SCROLLS { |
| 887 | let Some(next_observed) = try_next_terminal_event(input, pending)? else { |
| 888 | break; |
| 889 | }; |
| 890 | match &next_observed.event { |
| 891 | Event::Mouse(next) if is_scroll_event(next) => { |
| 892 | let _ = handle_mouse_event(app, latest, next_observed.observed_at); |
| 893 | latest = *next; |
| 894 | } |
| 895 | _ => { |
| 896 | // Back to the head, not the tail: `pending` may already hold |
| 897 | // later input (typed text, Enter), and this event came first. |
| 898 | pending.push_front(next_observed); |
| 899 | break; |
| 900 | } |
| 901 | } |
| 902 | } |
| 903 | Ok(latest) |
| 904 | } |
| 905 | |
| 906 | /// Wheel input and scrollbar dragging need the same cadence as text selection. |
| 907 | pub(crate) fn transcript_cadence_tier( |
| 908 | app: &App, |
| 909 | has_running_agents: bool, |
| 910 | ) -> crate::tui::display_refresh::DrawCadenceTier { |
| 911 | crate::tui::display_refresh::cadence_tier_from_signals( |
| 912 | app.is_loading || has_running_agents, |
| 913 | app.viewport.transcript_selection.is_active() |
| 914 | || app.viewport.pending_scroll_delta != 0 |
| 915 | || app.viewport.transcript_scrollbar_dragging, |
| 916 | !app.input.is_empty(), |
| 917 | crate::tui::hover_layer::current_hover().is_some(), |
| 918 | ) |
| 919 | } |
| 920 | |
| 921 | /// Fold every queued `Resize` behind the one in hand into the final size, so |
| 922 | /// one clear and redraw serves the whole drag (#65). |
| 923 | /// |
| 924 | /// The first non-resize event ends the fold and goes back to the head of the |
| 925 | /// queue, ahead of any later input already drained into `pending`. |
| 926 | pub(crate) fn coalesce_resize_burst( |
| 927 | width: u16, |
| 928 | height: u16, |
| 929 | input: &TerminalInputPump, |
| 930 | pending: &mut VecDeque<ObservedTerminalEvent>, |
| 931 | ) -> std::io::Result<(u16, u16)> { |
| 932 | let (mut final_w, mut final_h) = (width, height); |
| 933 | while let Some(next_observed) = try_next_terminal_event(input, pending)? { |
| 934 | if let Event::Resize(w, h) = next_observed.event { |
| 935 | final_w = w; |
| 936 | final_h = h; |
| 937 | } else { |
| 938 | pending.push_front(next_observed); |
| 939 | break; |
| 940 | } |
| 941 | } |
| 942 | Ok((final_w, final_h)) |
| 943 | } |
| 944 | |
| 945 | /// Toast identity for a failing session save, so recovery can retire it. |
| 946 | const SESSION_SAVE_FAILURE_TOAST: &str = "session-save-failure"; |
| 947 | |
| 948 | pub(crate) const STARTUP_NOTICE_TOAST: &str = "startup-notice"; |
| 949 | |
| 950 | pub(crate) fn surface_session_save_failure(app: &mut App, session_id: Option<&str>, error: &str) { |
| 951 | let text = app |
| 952 | .tr(MessageId::SessionSaveFailed) |
| 953 | .replace( |
| 954 | "{id}", |
| 955 | session_id |
| 956 | .map(codewhale_engine::session_manager::truncate_id) |
| 957 | .unwrap_or("—"), |
| 958 | ) |
| 959 | .replace("{error}", error); |
| 960 | app.push_status_toast_record(StatusToast::standing( |
| 961 | text, |
| 962 | StatusToastLevel::Error, |
| 963 | SESSION_SAVE_FAILURE_TOAST, |
| 964 | )); |
| 965 | } |
| 966 | |
| 967 | /// Keep the save-failure notice in step with the persistence actor's session |
| 968 | /// save health. Saves run off the UI thread, so a full disk or an unwritable |
| 969 | /// sessions directory used to reach only the log while the user kept working |
| 970 | /// unsaved. The notice stays while a session's latest save is failing and is |
| 971 | /// withdrawn once a later save lands. |
| 972 | pub(crate) fn surface_session_save_health( |
| 973 | app: &mut App, |
| 974 | reading: Option<crate::tui::persistence_actor::SaveHealthReading>, |
| 975 | seen: &mut u64, |
| 976 | ) { |
| 977 | let Some(reading) = reading.filter(|reading| reading.generation != *seen) else { |
| 978 | return; |
| 979 | }; |
| 980 | *seen = reading.generation; |
| 981 | app.retire_event_notices(SESSION_SAVE_FAILURE_TOAST); |
| 982 | if let Some((session_id, kind)) = reading.failing { |
| 983 | // Standing, not timed: it must outlast the failure, and only the |
| 984 | // recovery reading above withdraws it. |
| 985 | surface_session_save_failure(app, Some(&session_id), &kind.to_string()); |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | /// The exit line when a session's latest save failed and was never replaced |
| 990 | /// by a successful one. |
| 991 | pub(crate) fn shutdown_persistence_notice( |
| 992 | locale: codewhale_localization::Locale, |
| 993 | reading: &crate::tui::persistence_actor::SaveHealthReading, |
| 994 | ) -> Option<String> { |
| 995 | reading.failing.as_ref().map(|(session_id, kind)| { |
| 996 | codewhale_localization::tr(locale, MessageId::SessionSaveFailedAtExit) |
| 997 | .replace("{id}", session_id) |
| 998 | .replace("{error}", &kind.to_string()) |
| 999 | }) |
| 1000 | } |
| 1001 | |
| 1002 | /// Run the interactive TUI event loop. |
| 1003 | /// |
| 1004 | /// # Examples |
| 1005 | /// |
| 1006 | /// ```ignore |
| 1007 | /// # use codewhale_runtime::config::Config; |
| 1008 | /// # use crate::tui::TuiOptions; |
| 1009 | /// # async fn example(config: &Config, options: TuiOptions) -> anyhow::Result<()> { |
| 1010 | /// crate::tui::run_tui(config, options).await |
| 1011 | /// # } |
| 1012 | /// ``` |
| 1013 | pub async fn run_tui( |
| 1014 | config: &Config, |
| 1015 | options: TuiOptions, |
| 1016 | plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 1017 | pending_telemetry_notice: Option<codewhale_engine::telemetry_notice::PendingTelemetryNotice>, |
| 1018 | launch_conversation_mode: Option<String>, |
| 1019 | permission_mode: Option<codewhale_engine::runtime_options::PermissionMode>, |
| 1020 | launch_external_agent: Option<Box<crate::tui::external_agent::ExternalAgentSession>>, |
| 1021 | ) -> Result<()> { |
| 1022 | // Install notification, sound, category, and attention policy before any |
| 1023 | // producer (including the model-facing notify tool) can emit an event. |
| 1024 | let _ = crate::tui::notifications::settings(config); |
| 1025 | let use_mouse_capture = options.use_mouse_capture; |
| 1026 | let use_bracketed_paste = options.use_bracketed_paste; |
| 1027 | |
| 1028 | // Apply OSC 8 hyperlink toggle from config. |
| 1029 | // |
| 1030 | // #3029: OSC 8 hyperlinks are emitted out-of-band. Markdown wrapping keeps |
| 1031 | // visible spans and per-line targets in separate structures; each render |
| 1032 | // seam translates those targets into absolute `LinkRegion`s without ever |
| 1033 | // placing an escape byte in a ratatui buffer cell. `ColorCompatBackend` |
| 1034 | // then emits the OSC 8 escapes through its `Write` impl around the matching |
| 1035 | // cell runs. Hyperlinks are on by default for terminals that handle the OSC |
| 1036 | // terminator (`ESC \`) cleanly. Windows legacy consoles (conhost) still |
| 1037 | // mishandle the terminator, so the default stays off there; opt in via |
| 1038 | // `[tui] osc8_links = true` on any platform. |
| 1039 | let osc8_default_on = !cfg!(target_os = "windows"); |
| 1040 | codewhale_tui_kit::osc8::set_enabled( |
| 1041 | config |
| 1042 | .tui |
| 1043 | .as_ref() |
| 1044 | .and_then(|tui| tui.osc8_links) |
| 1045 | .unwrap_or(osc8_default_on), |
| 1046 | ); |
| 1047 | |
| 1048 | // Fail fast with a clear message when the interactive TUI is launched |
| 1049 | // without a controlling TTY (#4716). Without this, enable_raw_mode fails |
| 1050 | // with opaque "Device not configured" / "Input/output error" and some |
| 1051 | // terminal hosts surface only "[Process completed]". |
| 1052 | require_interactive_terminal(io::stdin().is_terminal(), io::stdout().is_terminal())?; |
| 1053 | require_foreground_terminal_owner()?; |
| 1054 | |
| 1055 | // The dispatcher resets SIGPIPE to SIG_DFL so `codewhale doctor | head` |
| 1056 | // exits quietly (#4030). A full-screen session is the opposite case: it |
| 1057 | // writes to pipes whose far end it does not own — stdio MCP servers, shell |
| 1058 | // tools, hooks, LSP — and a peer that exits first must surface as an |
| 1059 | // `EPIPE` error on that one write, not kill the whole TUI with the terminal |
| 1060 | // left in raw mode and nothing in the runtime log. Reproduced with a stdio |
| 1061 | // MCP server that exits before `initialize` is written: the process died |
| 1062 | // of SIGPIPE before its first frame, and the PTY harness reported it as a |
| 1063 | // plain exit 1. Children are unaffected: the standard library resets |
| 1064 | // SIGPIPE to SIG_DFL before exec, so `| head` inside a shell tool still |
| 1065 | // terminates the way a shell expects. Non-TUI subcommands keep SIG_DFL. |
| 1066 | // SAFETY: a plain disposition change, no handler; it runs before this |
| 1067 | // session spawns anything that writes to a pipe. |
| 1068 | #[cfg(unix)] |
| 1069 | unsafe { |
| 1070 | libc::signal(libc::SIGPIPE, libc::SIG_IGN); |
| 1071 | } |
| 1072 | |
| 1073 | // #6169: install the suspend/resume handshake here — after the |
| 1074 | // foreground-ownership check (the termios snapshot needs the still-cooked |
| 1075 | // tty) and before raw mode, so every mode enabled below has a handler that |
| 1076 | // can undo it. Not in `lib.rs`: this must not run for the non-TUI |
| 1077 | // subcommands. |
| 1078 | job_control_guard::install_job_control_guard(); |
| 1079 | let _ = take_terminal_restored_by_panic(); |
| 1080 | |
| 1081 | // This sets local terminal attributes; it is not a terminal-response probe. |
| 1082 | // Do it on the owning thread, as on resume, so blocking-pool scheduling |
| 1083 | // cannot abort startup or leave a detached worker enabling raw mode later. |
| 1084 | enable_raw_mode().context("Failed to enable raw mode")?; |
| 1085 | |
| 1086 | #[cfg(target_os = "windows")] |
| 1087 | enable_windows_ime_console_mode(); |
| 1088 | |
| 1089 | let mut stdout = io::stdout(); |
| 1090 | // Initialize the file-backed TUI log and redirect raw stderr away from |
| 1091 | // the alt-screen for the lifetime of this guard. MUST run BEFORE |
| 1092 | // EnterAlternateScreen; otherwise logging between alt-screen entry and |
| 1093 | // redirect init leaks raw bytes into the TUI buffer, causing the "scroll |
| 1094 | // demon" on Windows (#1909) and garbled output on all platforms (#1085). |
| 1095 | // The guard is held until the function returns; dropping it after |
| 1096 | // LeaveAlternateScreen restores the original stderr handle/fd so shutdown |
| 1097 | // messages reach the user's terminal. We accept the init failing (e.g., |
| 1098 | // read-only $HOME) and continue without the redirect rather than refusing |
| 1099 | // to start the TUI. |
| 1100 | let _tui_log_guard = match codewhale_runtime::runtime_log::init() { |
| 1101 | Ok(guard) => Some(guard), |
| 1102 | Err(err) => { |
| 1103 | tracing::warn!(target: "runtime_log", ?err, "TUI log init failed; stderr leaks may render as scroll-demon"); |
| 1104 | None |
| 1105 | } |
| 1106 | }; |
| 1107 | enter_alt_screen(&mut stdout)?; |
| 1108 | // Windows also suppresses Codewhale's own verbose CLI logger while |
| 1109 | // the alt-screen is active. The stderr redirect above catches raw |
| 1110 | // writes; this prevents the known verbose source at the origin. |
| 1111 | #[cfg(windows)] |
| 1112 | codewhale_runtime::logging::snapshot_verbose_state(); |
| 1113 | #[cfg(windows)] |
| 1114 | codewhale_runtime::logging::set_verbose(false); |
| 1115 | // Mouse capture, bracketed paste, focus events, and the Kitty |
| 1116 | // keyboard-protocol escape-disambiguation flag (#442). Single source |
| 1117 | // of truth shared with the FocusGained recovery path and |
| 1118 | // resume_terminal — see recover_terminal_modes. |
| 1119 | // |
| 1120 | // Focus events are necessary for IME compositor re-activation on |
| 1121 | // macOS when the user switches away (Cmd+Tab) and returns. The Kitty |
| 1122 | // keyboard protocol opt-in is best-effort: terminals that don't |
| 1123 | // support it (iTerm2, Terminal.app, Windows 10 conhost) silently |
| 1124 | // discard the escape, while supporting terminals (Kitty, Ghostty, |
| 1125 | // Alacritty 0.13+, WezTerm, recent Konsole, recent xterm) report |
| 1126 | // unambiguous events for Option/Alt-modified keys and plain Esc. |
| 1127 | // |
| 1128 | // Only `DISAMBIGUATE_ESCAPE_CODES` is pushed — the higher tiers |
| 1129 | // (`REPORT_EVENT_TYPES`, `REPORT_ALL_KEYS_AS_ESCAPE_CODES`) emit |
| 1130 | // release events that the existing key handlers would mis-route |
| 1131 | // as duplicate presses. |
| 1132 | // |
| 1133 | // On Windows, crossterm's `PushKeyboardEnhancementFlags` command always |
| 1134 | // reports the terminal as unsupported (`is_ansi_code_supported` returns |
| 1135 | // false), so the escape is written directly instead. VSCode's integrated |
| 1136 | // terminal and Windows Terminal ≥1.17 honour the kitty keyboard protocol |
| 1137 | // and will correctly disambiguate Shift+Enter from plain Enter once this |
| 1138 | // sequence is received. Terminals that do not understand it silently |
| 1139 | // ignore it. |
| 1140 | recover_terminal_modes(&mut stdout, use_mouse_capture, use_bracketed_paste); |
| 1141 | // The guard reads the *live* screen and disables capture unconditionally, |
| 1142 | // so a runtime `/inline` or `/fullscreen` switch cannot leave it emitting |
| 1143 | // the wrong teardown escape. |
| 1144 | let mut cleanup_guard = TerminalCleanupGuard { |
| 1145 | use_bracketed_paste, |
| 1146 | defused: false, |
| 1147 | }; |
| 1148 | let color_depth = palette::ColorDepth::detect(); |
| 1149 | // Raw mode is on and the event loop has not started, which is the only |
| 1150 | // window where the OSC 11 background query is safe to issue — see |
| 1151 | // `palette::probe_terminal_background`. The result is cached process-wide, |
| 1152 | // so every later `PaletteMode::detect()` sees the same answer. |
| 1153 | let background = palette::probe_terminal_background(); |
| 1154 | // Same window, same reason: the kitty graphics capability query answers |
| 1155 | // on stdin, so it is asked before the input pump exists. |
| 1156 | let kitty_graphics = codewhale_tui_kit::mark::probe_kitty_graphics(); |
| 1157 | // Same window again: the sixel probe is a primary-DA query whose reply |
| 1158 | // also arrives on stdin. Keep both capability receipts before input starts. |
| 1159 | let sixel_graphics = codewhale_tui_kit::mark::probe_sixel_graphics(); |
| 1160 | crate::tui::composer_ui::probe_terminal_keyboard_enhancement(); |
| 1161 | let palette_mode = background.mode(); |
| 1162 | tracing::debug!( |
| 1163 | ?color_depth, |
| 1164 | ?palette_mode, |
| 1165 | background_source = ?background.source(), |
| 1166 | background_color = ?background.color(), |
| 1167 | kitty_graphics, |
| 1168 | sixel_graphics, |
| 1169 | "terminal color profile detected" |
| 1170 | ); |
| 1171 | let mut backend = ColorCompatBackend::new(stdout, color_depth, palette_mode); |
| 1172 | backend.set_detected_background(background.color()); |
| 1173 | let mut terminal = build_app_terminal(backend)?; |
| 1174 | // At this point Settings hasn't loaded yet, so we can't read the |
| 1175 | // user's `synchronized_output` knob. Use the same env-based terminal |
| 1176 | // quirk detection that `Settings::apply_env_overrides` uses, so the |
| 1177 | // startup viewport reset matches what every later draw will do on |
| 1178 | // flicker-sensitive hosts. A user who has explicitly set |
| 1179 | // `synchronized_output = "on"` to override detection will get sync wrap |
| 1180 | // from the main draw loop onward; the one-time startup viewport reset |
| 1181 | // stays opt-out for them, which is the safe default because the cost is |
| 1182 | // at most brief tearing on the first frame. |
| 1183 | let sync_output_at_init = !codewhale_runtime::settings::detected_ptyxis_terminal() |
| 1184 | && !codewhale_runtime::settings::detected_legacy_windows_console_host(); |
| 1185 | reset_terminal_viewport(&mut terminal, sync_output_at_init)?; |
| 1186 | let event_broker = EventBroker::new(); |
| 1187 | |
| 1188 | // Local mutable copy so runtime config flips (e.g. `/provider` switch) |
| 1189 | // can rebuild the API client without restarting the process. |
| 1190 | let mut config = config.clone(); |
| 1191 | let config = &mut config; |
| 1192 | let mut app = App::new_with_plugin_registry(options.clone(), config, plugin_registry); |
| 1193 | app.install_conversation_mode(launch_conversation_mode, None); |
| 1194 | if let Some(session) = launch_external_agent { |
| 1195 | let notice = app |
| 1196 | .tr(MessageId::ExternalAgentSessionStarted) |
| 1197 | .replace("{agent}", &session.agent_name); |
| 1198 | app.external_agent = Some(*session); |
| 1199 | app.add_message(HistoryCell::System { |
| 1200 | content: notice.clone(), |
| 1201 | }); |
| 1202 | app.show_event_notice(notice, StatusToastLevel::Info); |
| 1203 | } |
| 1204 | app.apply_cli_permission_mode(permission_mode); |
| 1205 | let _cursor_accent_guard = codewhale_tui_kit::cursor_accent::CursorAccentGuard::install( |
| 1206 | app.low_motion || !app.fancy_animations, |
| 1207 | app.ui_theme.accent_primary, |
| 1208 | ); |
| 1209 | codewhale_runtime::startup_trace::mark("app_constructed"); |
| 1210 | sync_config_provider_from_app(config, &app); |
| 1211 | if let Err(error) = crate::tui::setup::record_configured_route(&app).await { |
| 1212 | app.push_status_toast( |
| 1213 | format!( |
| 1214 | "{} · {}: {error}", |
| 1215 | app.tr(MessageId::SetupStepProviderModelTitle), |
| 1216 | app.tr(MessageId::SetupStatusFailed), |
| 1217 | ), |
| 1218 | StatusToastLevel::Error, |
| 1219 | Some(App::STICKY_ERROR_TTL_MS), |
| 1220 | ); |
| 1221 | } |
| 1222 | surface_prompt_override_notices(&mut app); |
| 1223 | |
| 1224 | if options.resume_session_id.is_none() |
| 1225 | && !app.launch.visible |
| 1226 | && !app.onboarding_missing_key_recovery |
| 1227 | { |
| 1228 | // The one-time Fleet intro is no longer a launch push: it appears the |
| 1229 | // first time the user opens `/fleet` (apply.rs). |
| 1230 | let _ = open_setup_checkpoint_if_due(&mut app, config, options.skip_onboarding); |
| 1231 | } |
| 1232 | |
| 1233 | // Load existing session if resuming. |
| 1234 | if let Some(ref session_id) = options.resume_session_id |
| 1235 | && let Ok(manager) = SessionManager::default_location() |
| 1236 | { |
| 1237 | // Try to load by prefix or full ID |
| 1238 | let load_result: std::io::Result< |
| 1239 | Option<( |
| 1240 | codewhale_engine::session_manager::SavedSession, |
| 1241 | codewhale_engine::session_manager::SessionLease, |
| 1242 | )>, |
| 1243 | > = |
| 1244 | // `attach_*` reserves the session's live lease first, and refuses |
| 1245 | // a session another window has open instead of becoming its second |
| 1246 | // autosaving writer. The lease is committed once the session is |
| 1247 | // applied. |
| 1248 | if session_id == "latest" { |
| 1249 | // Special case: resume the most recent session in this workspace. |
| 1250 | match manager.get_latest_session_for_workspace(&options.workspace) { |
| 1251 | Ok(Some(meta)) => manager |
| 1252 | .attach_session(&meta.id) |
| 1253 | .map(|(recovery, lease)| Some((recovery.session, lease))), |
| 1254 | Ok(None) => Ok(None), |
| 1255 | Err(e) => Err(e), |
| 1256 | } |
| 1257 | } else { |
| 1258 | manager |
| 1259 | .attach_session_by_prefix(session_id) |
| 1260 | .map(|(recovery, lease)| Some((recovery.session, lease))) |
| 1261 | }; |
| 1262 | |
| 1263 | match load_result { |
| 1264 | Ok(Some((saved, lease))) => match manager.load_session_goal(&saved.metadata.id) { |
| 1265 | Ok(goal) => { |
| 1266 | let saved_id = saved.metadata.id.clone(); |
| 1267 | match apply_loaded_session_with_goal(&mut app, config, saved, goal.as_ref()) { |
| 1268 | // A store cannot be adopted here: this runs before |
| 1269 | // `TaskManager::start`, so the binding the launch path |
| 1270 | // uses is read from the same metadata below (#6207). |
| 1271 | Ok(_) => { |
| 1272 | lease.commit(); |
| 1273 | app.replace_progress_notice( |
| 1274 | StatusToastKind::SessionResume, |
| 1275 | format!( |
| 1276 | "Resumed session: {}", |
| 1277 | codewhale_engine::session_manager::truncate_id(&saved_id) |
| 1278 | ), |
| 1279 | ); |
| 1280 | } |
| 1281 | Err(err) => { |
| 1282 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1283 | &mut app, |
| 1284 | format!("Failed to restore session: {err}"), |
| 1285 | ); |
| 1286 | } |
| 1287 | } |
| 1288 | } |
| 1289 | Err(err) => { |
| 1290 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1291 | &mut app, |
| 1292 | format!("Failed to restore session goal: {err}"), |
| 1293 | ); |
| 1294 | } |
| 1295 | }, |
| 1296 | Ok(None) => { |
| 1297 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1298 | &mut app, |
| 1299 | "No sessions found to resume".to_string(), |
| 1300 | ); |
| 1301 | } |
| 1302 | Err(e) => { |
| 1303 | crate::tui::ui::session_state::surface_session_load_failure( |
| 1304 | &mut app, |
| 1305 | format!("Failed to load session: {e}"), |
| 1306 | ); |
| 1307 | } |
| 1308 | } |
| 1309 | } |
| 1310 | |
| 1311 | // Auto-resume's receipt (#2934) or the interrupted-session hint (#7095). |
| 1312 | // It replaces the generic resume message because it is the more specific |
| 1313 | // truth, but never a *failure* message from the load path above. It stands |
| 1314 | // until the first turn starts or a session is opened, so later status |
| 1315 | // updates cannot hide it. |
| 1316 | if let Some(notice) = options.startup_notice.clone() { |
| 1317 | app.retire_progress_notice(StatusToastKind::SessionResume); |
| 1318 | app.push_status_toast_record(StatusToast::standing( |
| 1319 | notice, |
| 1320 | StatusToastLevel::Info, |
| 1321 | STARTUP_NOTICE_TOAST, |
| 1322 | )); |
| 1323 | } |
| 1324 | |
| 1325 | let session_id = ensure_runtime_session_id(&mut app); |
| 1326 | let transition = |
| 1327 | prepare_offline_queue_transition(&app, &session_id).map_err(anyhow::Error::msg)?; |
| 1328 | let restored_offline_queue = install_offline_queue_transition(&mut app, transition) |
| 1329 | || !app.queued_messages.is_empty() |
| 1330 | || app.queued_draft.is_some(); |
| 1331 | if restored_offline_queue && app.queued_message_count() > 0 { |
| 1332 | let restored = app |
| 1333 | .tr(MessageId::QueueRestoredFromPreviousSession) |
| 1334 | .replace("{count}", &app.queued_message_count().to_string()); |
| 1335 | app.add_message(HistoryCell::System { |
| 1336 | content: restored.clone(), |
| 1337 | }); |
| 1338 | app.push_status_toast(restored, StatusToastLevel::Warning, None); |
| 1339 | } |
| 1340 | |
| 1341 | let task_manager = TaskManager::start( |
| 1342 | TaskManagerConfig::from_runtime( |
| 1343 | config, |
| 1344 | app.workspace.clone(), |
| 1345 | Some(app.model.clone()), |
| 1346 | Some(app.max_subagents.clamp(1, 4)), |
| 1347 | ), |
| 1348 | config.clone(), |
| 1349 | std::sync::Arc::clone(&app.plugin_registry), |
| 1350 | &session_id, |
| 1351 | app.current_session_metadata |
| 1352 | .as_ref() |
| 1353 | .and_then(|metadata| metadata.runtime_store.as_ref()), |
| 1354 | ) |
| 1355 | .await?; |
| 1356 | if let Some(saved) = app |
| 1357 | .current_session_metadata |
| 1358 | .as_ref() |
| 1359 | .and_then(|meta| meta.runtime_store.as_ref()) |
| 1360 | && task_manager |
| 1361 | .session_store_binding() |
| 1362 | .as_ref() |
| 1363 | .is_some_and(|current| current != saved) |
| 1364 | { |
| 1365 | app.push_status_toast( |
| 1366 | app.tr(MessageId::RuntimeStoreRecovered).into_owned(), |
| 1367 | StatusToastLevel::Warning, |
| 1368 | None, |
| 1369 | ); |
| 1370 | } |
| 1371 | let _task_shutdown = task_manager.shutdown_guard(); |
| 1372 | // The store this host holds, remembered for exit (#6144 P1b). |
| 1373 | let own_store = task_manager.session_store_binding(); |
| 1374 | // Repair the session store in the background now that this host holds |
| 1375 | // its own Runtime store — and any store it resumed or recovered into — so |
| 1376 | // those read as in use, never as candidates (#6144). |
| 1377 | codewhale_engine::session_reconcile::spawn_background_reconcile(app.current_session_id.clone()); |
| 1378 | let mut automation_service = AutomationManager::default_location()?; |
| 1379 | automation_service.bind_task_manager(&task_manager)?; |
| 1380 | let automations = std::sync::Arc::new(tokio::sync::Mutex::new(automation_service)); |
| 1381 | let automation_cancel = tokio_util::sync::CancellationToken::new(); |
| 1382 | let automation_scheduler = spawn_scheduler( |
| 1383 | automations.clone(), |
| 1384 | task_manager.clone(), |
| 1385 | automation_cancel.clone(), |
| 1386 | AutomationSchedulerConfig::default(), |
| 1387 | ); |
| 1388 | let shell_manager = app |
| 1389 | .runtime_services |
| 1390 | .shell_manager |
| 1391 | .clone() |
| 1392 | .unwrap_or_else(|| { |
| 1393 | codewhale_engine::tools::shell::new_shared_shell_manager(app.workspace.clone()) |
| 1394 | }); |
| 1395 | // #2511: ensure hook_executor is initialized for fresh sessions — it is |
| 1396 | // only set by apply_workspace_runtime_state (session resume / workspace |
| 1397 | // switch), so a brand-new session would otherwise leave it None and both |
| 1398 | // exec_shell shell_env hooks and ToolCallBefore gate would silently no-op. |
| 1399 | if app.runtime_services.hook_executor.is_none() { |
| 1400 | app.runtime_services.hook_executor = Some(std::sync::Arc::new(app.hooks.clone())); |
| 1401 | } |
| 1402 | app.runtime_services = RuntimeToolServices { |
| 1403 | accounting_origin: None, |
| 1404 | owner_accounting_origin: None, |
| 1405 | runtime_mcp_servers: app.runtime_services.runtime_mcp_servers.clone(), |
| 1406 | |
| 1407 | shell_manager: Some(shell_manager), |
| 1408 | persist_services_enabled: true, |
| 1409 | task_manager: Some(task_manager.clone()), |
| 1410 | automations: Some(automations), |
| 1411 | task_data_dir: Some(task_manager.data_dir()), |
| 1412 | active_task_id: None, |
| 1413 | active_thread_id: None, |
| 1414 | dynamic_tool_executor: None, |
| 1415 | work: app.runtime_services.work.clone(), |
| 1416 | // #456: plumb the App's HookExecutor so `exec_shell` can surface |
| 1417 | // the configured `shell_env` hooks. Clone the shared Arc. |
| 1418 | hook_executor: app.runtime_services.hook_executor.clone(), |
| 1419 | handle_store: app.runtime_services.handle_store.clone(), |
| 1420 | rlm_sessions: app.runtime_services.rlm_sessions.clone(), |
| 1421 | media_originals_dir: codewhale_runtime::media_originals::default_store_dir(), |
| 1422 | }; |
| 1423 | codewhale_runtime::startup_trace::mark("task_manager_ready"); |
| 1424 | refresh_active_task_panel(&mut app).await; |
| 1425 | refresh_automation_panel_blocking(&mut app).await; |
| 1426 | |
| 1427 | // A `[redaction] model_bound = "disabled"` request lowers the model-bound |
| 1428 | // masking boundary only after an explicit one-time confirmation on this |
| 1429 | // startup gate. Arm the gate before the engine spawns so it owns the first |
| 1430 | // screen; answering it rebuilds the engine with the confirmed mode. |
| 1431 | app.redaction_gate = config.redaction_confirmation_required(); |
| 1432 | |
| 1433 | // Restore before admitting initial input, including resumed conversations. |
| 1434 | let engine_handle = spawn_tui_engine_with_session(&mut app, config, None).await?; |
| 1435 | let _ = engine_handle.try_send(Op::ListSubAgents); |
| 1436 | codewhale_runtime::startup_trace::mark("engine_spawned"); |
| 1437 | // The translation client is optional: it never crashes the TUI on |
| 1438 | // startup, even when the API key is missing, the base URL is malformed, |
| 1439 | // or the network is unavailable. |
| 1440 | // Translations are skipped with a logged warning until a key is saved. |
| 1441 | let translation_client = match crate::active_route_client(config).await { |
| 1442 | Ok(client) => Some(Arc::new(client)), |
| 1443 | Err(err) => { |
| 1444 | if app.onboarding == OnboardingState::None { |
| 1445 | tracing::warn!("Translation client initialization failed: {err}"); |
| 1446 | } |
| 1447 | None |
| 1448 | } |
| 1449 | }; |
| 1450 | |
| 1451 | // Fire session start hook |
| 1452 | { |
| 1453 | let context = app.base_hook_context(); |
| 1454 | // Captured before the hook executor moves `context` into its blocking |
| 1455 | // task; the outbox emit below needs the same session identity. |
| 1456 | let outbox_thread_id = context.session_id.clone().unwrap_or_default(); |
| 1457 | let outbox_mode = context.mode.clone(); |
| 1458 | let outbox_model = context.model.clone(); |
| 1459 | let outbox_workspace = context.workspace.clone(); |
| 1460 | let hooks = app.hooks.clone(); |
| 1461 | if let Err(error) = |
| 1462 | tokio::task::spawn_blocking(move || hooks.execute(HookEvent::SessionStart, &context)) |
| 1463 | .await |
| 1464 | { |
| 1465 | tracing::error!(target: "hooks", %error, "session_start executor task was lost"); |
| 1466 | app.show_event_notice( |
| 1467 | "session_start hook executor did not run".to_string(), |
| 1468 | StatusToastLevel::Warning, |
| 1469 | ); |
| 1470 | } |
| 1471 | // Lifecycle outbox (`[lifecycle_outbox]`): fires alongside the |
| 1472 | // session_start hook, with the same session identity. No-op when |
| 1473 | // the feature is disabled. |
| 1474 | app.lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1475 | event: "session_start".to_string(), |
| 1476 | kind: "session.started".to_string(), |
| 1477 | thread_id: outbox_thread_id, |
| 1478 | turn_id: None, |
| 1479 | item_id: None, |
| 1480 | payload: serde_json::json!({ |
| 1481 | "mode": outbox_mode, |
| 1482 | "model": outbox_model, |
| 1483 | "workspace": outbox_workspace |
| 1484 | .as_ref() |
| 1485 | .map(|path| path.display().to_string()), |
| 1486 | }), |
| 1487 | }); |
| 1488 | } |
| 1489 | |
| 1490 | // Spawn the persistence actor so checkpoint/session-save I/O stays off |
| 1491 | // the UI thread. The actor serialises + writes to disk in a dedicated |
| 1492 | // task; the UI just `try_send`s a request and returns immediately. |
| 1493 | let persistence_runtime = SessionManager::default_location() |
| 1494 | .ok() |
| 1495 | .map(|persist_manager| { |
| 1496 | let (handle, task) = persistence_actor::spawn_persistence_actor(persist_manager); |
| 1497 | persistence_actor::init_actor(handle.clone()); |
| 1498 | (handle, task) |
| 1499 | }); |
| 1500 | |
| 1501 | // #4605: create the dispatch completion channel before any submit path so |
| 1502 | // initial input and queued follow-ups can dispatch without blocking the |
| 1503 | // startup sequence. |
| 1504 | // At most one user dispatch is allowed in flight. A two-slot completion |
| 1505 | // mailbox covers the hook stage plus the send stage without turning a |
| 1506 | // stalled UI into an unbounded queue of captured App mutations. |
| 1507 | let (dispatch_completion_tx, dispatch_completion_rx) = |
| 1508 | tokio::sync::mpsc::channel::<crate::tui::app::DispatchApplyFn>(2); |
| 1509 | app.dispatch_completion_tx = Some(dispatch_completion_tx); |
| 1510 | |
| 1511 | if std::mem::take(&mut app.start_remote_control_on_launch) { |
| 1512 | start_remote_control_session(&mut app, config).await; |
| 1513 | } |
| 1514 | submit_initial_input_if_ready(&mut app, config, &engine_handle).await?; |
| 1515 | |
| 1516 | codewhale_runtime::startup_trace::log_summary(); |
| 1517 | // Pin the cold-start measurement at the same moment the summary is logged. |
| 1518 | // `log_summary` computes the same number into a local, emits it, clears its |
| 1519 | // buffer, and returns `()`, so this reads `PROCESS_START` directly rather |
| 1520 | // than through it. Only this path calls it, which is what keeps the |
| 1521 | // cold-start bucket absent on surfaces with no event loop. |
| 1522 | codewhale_runtime::startup_trace::mark_cold_start(); |
| 1523 | if let Some(millis) = codewhale_runtime::startup_trace::cold_start_ms() { |
| 1524 | codewhale_telemetry::set_cold_start_ms(millis); |
| 1525 | } |
| 1526 | let result = Box::pin(run_event_loop( |
| 1527 | &mut terminal, |
| 1528 | &mut app, |
| 1529 | config, |
| 1530 | engine_handle, |
| 1531 | task_manager.clone(), |
| 1532 | &event_broker, |
| 1533 | translation_client, |
| 1534 | pending_telemetry_notice, |
| 1535 | dispatch_completion_rx, |
| 1536 | )) |
| 1537 | .await; |
| 1538 | automation_cancel.cancel(); |
| 1539 | automation_scheduler.abort(); |
| 1540 | // Settle the store this host actually owns at exit. A session switch may |
| 1541 | // have adopted another store, and shutting down the launch-time handle |
| 1542 | // would leave the adopted one undrained — its queued work never settled |
| 1543 | // and its process-owner lock released only by the process ending. |
| 1544 | if let Some(current_tasks) = app |
| 1545 | .runtime_services |
| 1546 | .task_manager |
| 1547 | .clone() |
| 1548 | .or_else(|| Some(task_manager.clone())) |
| 1549 | && let Err(error) = current_tasks.shutdown_and_wait().await |
| 1550 | { |
| 1551 | tracing::error!(%error, "Task manager shutdown remains incomplete"); |
| 1552 | } |
| 1553 | if let Some(session) = app.external_agent.take() { |
| 1554 | match tokio::time::timeout(Duration::from_secs(5), session.runtime.shutdown_and_wait()) |
| 1555 | .await |
| 1556 | { |
| 1557 | Ok(Ok(())) => {} |
| 1558 | Ok(Err(error)) => { |
| 1559 | tracing::warn!(%error, "External agent shutdown remains incomplete"); |
| 1560 | } |
| 1561 | Err(_) => { |
| 1562 | tracing::warn!("External agent shutdown timed out"); |
| 1563 | } |
| 1564 | } |
| 1565 | } |
| 1566 | |
| 1567 | // Join the startup-default writer before anything else tears down. |
| 1568 | // |
| 1569 | // The last thing a user does before quitting is very often the selection |
| 1570 | // they most want to survive — Shift+Tab into Plan, then Ctrl+C. Those writes |
| 1571 | // are queued off the event loop on purpose, so at this point one may still |
| 1572 | // be in flight or not yet started. Draining here is what makes "the last |
| 1573 | // immediate selection lands" true rather than a race against process exit. |
| 1574 | // |
| 1575 | // Failures are collected, not toasted: the event loop has already drawn its |
| 1576 | // final frame, so a toast would never be painted. They are printed below, |
| 1577 | // after the alternate screen is gone and stderr is back on the user's real |
| 1578 | // terminal. |
| 1579 | let startup_default_failures = app.startup_defaults.shutdown(); |
| 1580 | for failure in &startup_default_failures { |
| 1581 | tracing::warn!( |
| 1582 | target: "settings", |
| 1583 | subjects = ?failure.subjects, |
| 1584 | detail = %failure.detail, |
| 1585 | "startup default was not persisted before shutdown", |
| 1586 | ); |
| 1587 | } |
| 1588 | let startup_default_failures: Vec<String> = startup_default_failures |
| 1589 | .iter() |
| 1590 | .map(|failure| app.startup_default_failure_message(failure)) |
| 1591 | .collect(); |
| 1592 | |
| 1593 | // Fire session end hook |
| 1594 | { |
| 1595 | let context = app.base_hook_context(); |
| 1596 | let hooks = app.hooks.clone(); |
| 1597 | let hook_context = context.clone(); |
| 1598 | if tokio::task::spawn_blocking(move || hooks.execute(HookEvent::SessionEnd, &hook_context)) |
| 1599 | .await |
| 1600 | .is_err() |
| 1601 | { |
| 1602 | tracing::warn!(target:"hooks","session_end hook executor task was lost"); |
| 1603 | } |
| 1604 | // Lifecycle outbox (`[lifecycle_outbox]`): fires alongside the |
| 1605 | // session_end hook, with the same session identity. No-op when |
| 1606 | // the feature is disabled. |
| 1607 | app.lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1608 | event: "session_end".to_string(), |
| 1609 | kind: "session.ended".to_string(), |
| 1610 | thread_id: context.session_id.clone().unwrap_or_default(), |
| 1611 | turn_id: None, |
| 1612 | item_id: None, |
| 1613 | payload: serde_json::json!({ |
| 1614 | "workspace": context.workspace |
| 1615 | .as_ref() |
| 1616 | .map(|path| path.display().to_string()), |
| 1617 | "total_tokens": context.total_tokens, |
| 1618 | }), |
| 1619 | }); |
| 1620 | } |
| 1621 | |
| 1622 | // Keep the final session/turn receipts ahead of runtime teardown. A failed |
| 1623 | // observability sink must not prevent the user's session from shutting down. |
| 1624 | if let Err(error) = app.lifecycle_outbox.flush(Duration::from_secs(2)).await { |
| 1625 | tracing::warn!(target: "lifecycle_outbox", %error, "TUI lifecycle outbox did not drain before exit"); |
| 1626 | } |
| 1627 | |
| 1628 | // The pane is ours until the process leaves it: release it before the |
| 1629 | // terminal is restored so Herdr clears the agent immediately instead of |
| 1630 | // waiting for its idle-prompt safety net. |
| 1631 | crate::tui::herdr::release().await; |
| 1632 | |
| 1633 | // Flush the persistence actor, collect the durability report (write |
| 1634 | // failures are surfaced, not discarded), then shut down gracefully. |
| 1635 | // |
| 1636 | // The session's crash-recovery checkpoint is cleared only for a settled |
| 1637 | // session. While a turn is in flight (or a spawned dispatch has not yet |
| 1638 | // applied), the checkpoint is the only durable record of that work: |
| 1639 | // clearing it here unconditionally could erase in-flight progress that |
| 1640 | // never reached a snapshot, so it survives for startup recovery review. |
| 1641 | let mut shutdown_save_health = None; |
| 1642 | if let Some((handle, task)) = persistence_runtime { |
| 1643 | // A quit key can leave the frame before its usual queue comparison. |
| 1644 | // Capture the final edited draft before the shutdown durability barrier. |
| 1645 | persist_offline_queue_state(&app); |
| 1646 | let turn_in_flight = turn_unsettled_for_shutdown(&app); |
| 1647 | if turn_in_flight { |
| 1648 | tracing::info!( |
| 1649 | target: "persistence", |
| 1650 | "shutdown preserves the in-flight checkpoint for recovery review" |
| 1651 | ); |
| 1652 | } else if let Err(error) = persist_settled_session_on_shutdown(&mut app, &handle) { |
| 1653 | tracing::warn!( |
| 1654 | target: "persistence", |
| 1655 | %error, |
| 1656 | "session snapshot could not be queued during shutdown; checkpoint retained" |
| 1657 | ); |
| 1658 | } |
| 1659 | let (report_tx, report_rx) = tokio::sync::oneshot::channel(); |
| 1660 | handle.try_send(PersistRequest::FlushAndReport { reply: report_tx }); |
| 1661 | if let Ok(report) = report_rx.await |
| 1662 | && !report.failures.is_empty() |
| 1663 | { |
| 1664 | tracing::warn!( |
| 1665 | target: "persistence", |
| 1666 | failures = ?report.failures, |
| 1667 | "session persistence reported write failures during shutdown", |
| 1668 | ); |
| 1669 | } |
| 1670 | // Read after the final flush: whether each session's latest save |
| 1671 | // landed, not every failure this run has ever seen. |
| 1672 | shutdown_save_health = Some(handle.session_save_health()); |
| 1673 | handle.try_send(PersistRequest::Shutdown); |
| 1674 | let _ = task.await; |
| 1675 | } |
| 1676 | |
| 1677 | // A host that never bound a document to its own store leaves it empty |
| 1678 | // (#6144 P1b). Set it aside on the way out. A document binding it, work |
| 1679 | // in it, or anything in this process still holding it keeps it; the next |
| 1680 | // launch's repair applies the same exact rule to whatever remains. |
| 1681 | if let Some(store) = own_store { |
| 1682 | app.runtime_services.task_manager = None; |
| 1683 | drop(task_manager); |
| 1684 | let _ = tokio::task::spawn_blocking(move || { |
| 1685 | if let Ok(manager) = SessionManager::default_location() { |
| 1686 | codewhale_engine::session_reconcile::retire_unbound_store( |
| 1687 | &manager, |
| 1688 | &store.data_dir, |
| 1689 | "host exited without binding its store", |
| 1690 | ); |
| 1691 | } |
| 1692 | }) |
| 1693 | .await; |
| 1694 | } |
| 1695 | |
| 1696 | cleanup_guard.defused = true; |
| 1697 | codewhale_tui_kit::cursor_accent::restore_cursor_accent(); |
| 1698 | pop_keyboard_enhancement_flags(terminal.backend_mut()); |
| 1699 | disable_alternate_scroll_mode(terminal.backend_mut()); |
| 1700 | execute!(terminal.backend_mut(), DisableFocusChange)?; |
| 1701 | disable_raw_mode()?; |
| 1702 | leave_alt_screen(terminal.backend_mut())?; |
| 1703 | #[cfg(windows)] |
| 1704 | codewhale_runtime::logging::restore_verbose_state(); |
| 1705 | if app.use_mouse_capture { |
| 1706 | execute!(terminal.backend_mut(), DisableMouseCapture)?; |
| 1707 | } |
| 1708 | if use_bracketed_paste { |
| 1709 | disable_bracketed_paste_mode(terminal.backend_mut()); |
| 1710 | } |
| 1711 | terminal.show_cursor()?; |
| 1712 | drop(terminal); |
| 1713 | |
| 1714 | // Back on the primary screen, so this is somewhere the user can actually |
| 1715 | // read. A settings write that did not land would otherwise be invisible |
| 1716 | // until the next launch quietly came up in the old mode. |
| 1717 | for failure in &startup_default_failures { |
| 1718 | tracing::error!(target: "settings", "{failure}"); |
| 1719 | // Printed AFTER `LeaveAlternateScreen` / `drop(terminal)`, so this is on |
| 1720 | // the restored primary screen. The module-level |
| 1721 | // `#![deny(clippy::print_stderr)]` would otherwise refuse it. |
| 1722 | #[allow(clippy::print_stderr)] |
| 1723 | { |
| 1724 | eprintln!("codewhale: {failure}"); |
| 1725 | } |
| 1726 | } |
| 1727 | |
| 1728 | if let Some(notice) = shutdown_save_health |
| 1729 | .as_ref() |
| 1730 | .and_then(|reading| shutdown_persistence_notice(app.ui_locale, reading)) |
| 1731 | { |
| 1732 | // Primary screen, like the settings failures above. |
| 1733 | #[allow(clippy::print_stderr)] |
| 1734 | { |
| 1735 | eprintln!("{notice}"); |
| 1736 | } |
| 1737 | } |
| 1738 | |
| 1739 | // `codewhale resume <id>` for a document that never reached disk (every |
| 1740 | // save failed, or nothing was ever saved) only fails with NotFound. |
| 1741 | let session_document_exists = app.current_session_id.as_deref().is_some_and(|id| { |
| 1742 | SessionManager::default_location().is_ok_and(|manager| manager.session_document_exists(id)) |
| 1743 | }); |
| 1744 | if result.is_ok() |
| 1745 | && session_document_exists |
| 1746 | && let Some(hint) = resume_hint_text( |
| 1747 | app.ui_locale, |
| 1748 | app.current_session_id.as_deref(), |
| 1749 | io::stdout().is_terminal(), |
| 1750 | ) |
| 1751 | { |
| 1752 | // Printed AFTER `LeaveAlternateScreen` / `drop(terminal)` above, |
| 1753 | // so we're back on the primary screen — this is the one |
| 1754 | // legitimate stdout write in the TUI module tree. The |
| 1755 | // module-level `#![deny(clippy::print_stdout)]` would otherwise |
| 1756 | // refuse it. |
| 1757 | #[allow(clippy::print_stdout)] |
| 1758 | { |
| 1759 | println!("{hint}"); |
| 1760 | } |
| 1761 | } |
| 1762 | |
| 1763 | result |
| 1764 | } |
| 1765 | |
| 1766 | /// Whether a composer guard owns this launch-screen Enter. Every guard is |
| 1767 | /// applied here, before a session exists, so a held submit never leaves the |
| 1768 | /// user in a new empty session. |
| 1769 | pub(super) fn launch_submit_held(app: &mut App, protect_paste: bool, now: Instant) -> bool { |
| 1770 | if !protect_paste |
| 1771 | && let Some(pending) = app.flush_paste_burst_before_modified_input_if_enabled() |
| 1772 | { |
| 1773 | app.insert_str(&pending); |
| 1774 | } |
| 1775 | if app.startup_input_unproven || !app.composer_enter_would_submit(protect_paste, now) { |
| 1776 | // A paste burst, empty composer or startup integrity hold. |
| 1777 | app.handle_composer_enter(protect_paste, now); |
| 1778 | return true; |
| 1779 | } |
| 1780 | // An oversized draft is backed up to a paste file now; if that fails the |
| 1781 | // submit is held with the full text in the composer. |
| 1782 | !app.consolidate_large_input_if_oversized() |
| 1783 | } |
| 1784 | |
| 1785 | /// Show why a turn ended without success. The composer status line always |
| 1786 | /// names it; a turn the Engine stopped itself (wall-clock or step budget, no |
| 1787 | /// progress, an incomplete response) posts no error event, so its reason also |
| 1788 | /// goes into the transcript — a footer line alone is replaced by the next |
| 1789 | /// notice, and the session then reads as hung. When an error event already |
| 1790 | /// put the message in the transcript, nothing is repeated. |
| 1791 | pub(super) fn present_turn_failure( |
| 1792 | app: &mut App, |
| 1793 | status: codewhale_engine::core::events::TurnOutcomeStatus, |
| 1794 | error: Option<&str>, |
| 1795 | ) { |
| 1796 | let failed = matches!( |
| 1797 | status, |
| 1798 | codewhale_engine::core::events::TurnOutcomeStatus::Failed |
| 1799 | ); |
| 1800 | let mut error_code = None; |
| 1801 | if failed |
| 1802 | && app.turn_error_posted |
| 1803 | && let Some(notice) = app.turn_error_notice.clone() |
| 1804 | && let Some(index) = (0..app.virtual_cell_count()).rev().find(|&index| { |
| 1805 | matches!( |
| 1806 | app.cell_at_virtual_index(index), |
| 1807 | Some(HistoryCell::Error { message, .. }) if *message == notice |
| 1808 | ) |
| 1809 | }) |
| 1810 | && let Some(HistoryCell::Error { severity, code, .. }) = |
| 1811 | app.cell_at_virtual_index_mut(index) |
| 1812 | { |
| 1813 | *severity = codewhale_error_taxonomy::ErrorSeverity::Error; |
| 1814 | error_code = code.clone(); |
| 1815 | } |
| 1816 | // What the transcript shows for this turn's failure: the error cell an |
| 1817 | // earlier `Event::Error` already posted, or the notice added here. |
| 1818 | let shown = if app.turn_error_posted { |
| 1819 | app.turn_error_notice.clone() |
| 1820 | } else if let Some(error) = error { |
| 1821 | let notice = format!("{}: {error}", app.tr(MessageId::NotificationTurnFailed)); |
| 1822 | if failed { |
| 1823 | app.add_message(HistoryCell::Error { |
| 1824 | message: notice.clone(), |
| 1825 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 1826 | code: None, |
| 1827 | }); |
| 1828 | } |
| 1829 | app.set_sticky_status(notice.clone(), StatusToastLevel::Error, None); |
| 1830 | Some(notice) |
| 1831 | } else { |
| 1832 | None |
| 1833 | }; |
| 1834 | // Persist the failure with the session (redacted), so resume, export, |
| 1835 | // and the Runtime API can say why the turn stopped after the TUI closes. |
| 1836 | if failed && let Some(shown) = shown { |
| 1837 | let outcome = codewhale_engine::session_manager::SavedTurnOutcome::failed_with_cause( |
| 1838 | &shown, |
| 1839 | error_code.as_deref(), |
| 1840 | app.turn_error_cause.take(), |
| 1841 | app.api_messages.len(), |
| 1842 | ); |
| 1843 | codewhale_engine::session_manager::push_turn_outcome( |
| 1844 | &mut app.session_turn_outcomes, |
| 1845 | outcome, |
| 1846 | ); |
| 1847 | } |
| 1848 | } |
| 1849 | |
| 1850 | /// Submit a mouse or keyboard composer gesture on its current surface. |
| 1851 | /// |
| 1852 | /// Mouse `[↵]` sets `pending_composer_submit`; this consumes that chord without |
| 1853 | /// duplicating draft consumption or opening transcript-only Enter shortcuts. |
| 1854 | /// Its own gates (`SendQueuedNow`, the paste-burst probe) run here; everything |
| 1855 | /// from slash-menu selection onward is the shared `submit_decided_composer_input` |
| 1856 | /// tail the keyboard Enter arm also uses, so the two surfaces cannot drift. |
| 1857 | #[allow(clippy::too_many_arguments)] |
| 1858 | async fn dispatch_composer_submit( |
| 1859 | terminal: &mut AppTerminal, |
| 1860 | app: &mut App, |
| 1861 | engine_handle: &mut EngineHandle, |
| 1862 | config: &mut Config, |
| 1863 | chord: ComposerSubmitChord, |
| 1864 | protect_paste: bool, |
| 1865 | now: Instant, |
| 1866 | ) -> Result<bool> { |
| 1867 | let action = app.decide_composer_submit(chord); |
| 1868 | if app.launch.visible { |
| 1869 | let mentions = crate::tui::file_mention::visible_mention_menu_entries(app, 1); |
| 1870 | if !mentions.is_empty() |
| 1871 | && crate::tui::file_mention::apply_mention_menu_selection(app, &mentions) |
| 1872 | { |
| 1873 | return Ok(false); |
| 1874 | } |
| 1875 | if app.launch.return_to_session || action == ComposerSubmitAction::SendQueuedNow { |
| 1876 | app.launch.dismiss(); |
| 1877 | } |
| 1878 | } |
| 1879 | if matches!(action, ComposerSubmitAction::SendQueuedNow) { |
| 1880 | let _ = send_next_queued_message_now(app, config, engine_handle).await?; |
| 1881 | return Ok(false); |
| 1882 | } |
| 1883 | if !app.launch.visible && !app.composer_enter_would_submit(protect_paste, now) { |
| 1884 | return Ok(false); |
| 1885 | } |
| 1886 | submit_decided_composer_input( |
| 1887 | terminal, |
| 1888 | app, |
| 1889 | engine_handle, |
| 1890 | config, |
| 1891 | action, |
| 1892 | protect_paste, |
| 1893 | now, |
| 1894 | ) |
| 1895 | .await |
| 1896 | } |
| 1897 | |
| 1898 | /// Shared tail of a decided composer submit: slash-menu selection, draft |
| 1899 | /// consumption, and the memory/`!`/`/`/message branches. |
| 1900 | /// |
| 1901 | /// Keyboard Enter and the mouse `[↵]` dispatcher both end here. Each caller |
| 1902 | /// keeps its own gates — transcript-only shortcuts and forced-submit chords |
| 1903 | /// stay keyboard-only, `SendQueuedNow` and the paste-burst probe stay in the |
| 1904 | /// dispatcher — so this tail is the one place either surface can change. |
| 1905 | /// Returns `true` only when a command asked the event loop to exit. |
| 1906 | #[allow(clippy::too_many_arguments)] |
| 1907 | async fn submit_decided_composer_input( |
| 1908 | terminal: &mut AppTerminal, |
| 1909 | app: &mut App, |
| 1910 | engine_handle: &mut EngineHandle, |
| 1911 | config: &mut Config, |
| 1912 | action: ComposerSubmitAction, |
| 1913 | protect_paste: bool, |
| 1914 | now: Instant, |
| 1915 | ) -> Result<bool> { |
| 1916 | if app.pending_fresh_session.is_some() { |
| 1917 | if looks_like_slash_command_input(&app.input) |
| 1918 | && commands::pending_session_control_command(&app.input) |
| 1919 | && app.composer_enter_would_submit(protect_paste, now) |
| 1920 | { |
| 1921 | let input = app.input.clone(); |
| 1922 | return execute_command_input(terminal, app, engine_handle, config, &input).await; |
| 1923 | } |
| 1924 | app.show_event_notice( |
| 1925 | "A new session is awaiting Engine confirmation; the draft is preserved.".to_string(), |
| 1926 | StatusToastLevel::Warning, |
| 1927 | ); |
| 1928 | return Ok(false); |
| 1929 | } |
| 1930 | // #573: when the user typed a slash-command prefix that the popup is |
| 1931 | // matching (e.g. `/mo` → `/model`), submit runs the *highlighted match* |
| 1932 | // rather than sending the literal `/mo` text. Only kick in when the |
| 1933 | // popup has at least one entry; otherwise fall through to the legacy |
| 1934 | // submit path. |
| 1935 | let slash_menu_entries = visible_slash_menu_entries(app, SLASH_MENU_LIMIT); |
| 1936 | let slash_menu_open = !slash_menu_entries.is_empty(); |
| 1937 | let selecting_inline_skill = slash_menu_open |
| 1938 | && partial_inline_skill_mention_at_cursor(&app.input, app.cursor_position).is_some(); |
| 1939 | let typed_before_selection = app.input.trim().to_string(); |
| 1940 | let typed_exact_command = |
| 1941 | !selecting_inline_skill && names_a_builtin_command(&typed_before_selection); |
| 1942 | if slash_menu_open |
| 1943 | && !typed_exact_command |
| 1944 | && apply_slash_menu_selection(app, &slash_menu_entries, false) |
| 1945 | { |
| 1946 | app.close_slash_menu(); |
| 1947 | let resolved = app |
| 1948 | .input |
| 1949 | .trim() |
| 1950 | .trim_start_matches('/') |
| 1951 | .to_ascii_lowercase(); |
| 1952 | if !selecting_inline_skill |
| 1953 | && !typed_before_selection.eq_ignore_ascii_case(app.input.trim()) |
| 1954 | && matches!( |
| 1955 | resolved.as_str(), |
| 1956 | "exit" | "quit" | "clear" | "new" | "logout" | "restore" |
| 1957 | ) |
| 1958 | { |
| 1959 | app.cursor_position = app.input.chars().count(); |
| 1960 | return Ok(false); |
| 1961 | } |
| 1962 | if selecting_inline_skill { |
| 1963 | return Ok(false); |
| 1964 | } |
| 1965 | } |
| 1966 | |
| 1967 | if app.launch.visible { |
| 1968 | app.launch.dissolve_card(app.ambient_clock_ms); |
| 1969 | if launch_submit_held(app, protect_paste, now) { |
| 1970 | return Ok(false); |
| 1971 | } |
| 1972 | let result = begin_launch_session(app, None); |
| 1973 | if result.is_error { |
| 1974 | return apply_command_result(terminal, app, engine_handle, config, result).await; |
| 1975 | } |
| 1976 | if apply_command_result(terminal, app, engine_handle, config, result).await? { |
| 1977 | return Ok(true); |
| 1978 | } |
| 1979 | if let Err(error) = await_engine_session_sync( |
| 1980 | engine_handle, |
| 1981 | app.current_session_id.as_deref(), |
| 1982 | app.session_write_owner.as_ref(), |
| 1983 | ) |
| 1984 | .await |
| 1985 | { |
| 1986 | super::session_state::surface_session_load_failure(app, error.to_string()); |
| 1987 | return Ok(false); |
| 1988 | } |
| 1989 | } |
| 1990 | let Some(input) = app.handle_composer_enter(protect_paste, now) else { |
| 1991 | return Ok(false); |
| 1992 | }; |
| 1993 | // `# foo` quick-add (#492) — when memory is enabled, a single line |
| 1994 | // starting with `#` (but not `##` / `#!` shebangs / Markdown headings |
| 1995 | // the user might be pasting in) is intercepted: the text is appended to |
| 1996 | // the user memory file and the input is consumed without firing a turn. |
| 1997 | // Disabled behaviour falls through to normal turn submit. |
| 1998 | if should_intercept_memory_quick_add(config, &input) { |
| 1999 | handle_memory_quick_add(app, &input, config); |
| 2000 | return Ok(false); |
| 2001 | } |
| 2002 | if handle_bang_shell_input(app, engine_handle, &input).await? { |
| 2003 | return Ok(false); |
| 2004 | } |
| 2005 | if looks_like_slash_command_input(&input) { |
| 2006 | // Opening a view is not a conversation turn. SendMessage actions |
| 2007 | // record their real prompt through dispatch_composer_message instead. |
| 2008 | if execute_command_input(terminal, app, engine_handle, config, &input).await? { |
| 2009 | return Ok(true); |
| 2010 | } |
| 2011 | } else { |
| 2012 | return dispatch_submitted_composer_message( |
| 2013 | terminal, |
| 2014 | app, |
| 2015 | engine_handle, |
| 2016 | config, |
| 2017 | input, |
| 2018 | action, |
| 2019 | ) |
| 2020 | .await; |
| 2021 | } |
| 2022 | Ok(false) |
| 2023 | } |
| 2024 | |
| 2025 | async fn dispatch_submitted_composer_message( |
| 2026 | terminal: &mut AppTerminal, |
| 2027 | app: &mut App, |
| 2028 | engine_handle: &mut EngineHandle, |
| 2029 | config: &mut Config, |
| 2030 | input: String, |
| 2031 | action: ComposerSubmitAction, |
| 2032 | ) -> Result<bool> { |
| 2033 | // #383: /edit — if the user invoked /edit to revise the last |
| 2034 | // message, undo the last exchange before dispatching the |
| 2035 | // replacement. Sync the engine session so it also drops the old |
| 2036 | // exchange. |
| 2037 | if let Some(result) = edit_replacement_result(app, &input) { |
| 2038 | return apply_command_result(terminal, app, engine_handle, config, result).await; |
| 2039 | } |
| 2040 | let (queued, recovery) = message_from_submitted_input(app, input); |
| 2041 | dispatch_composer_message(app, config, engine_handle, queued, recovery, action).await?; |
| 2042 | Ok(false) |
| 2043 | } |
| 2044 | |
| 2045 | /// The replacement for an exchange being revised with `/edit`: roll the last |
| 2046 | /// exchange back through the same Engine-acknowledged, durably saved path as |
| 2047 | /// `/retry`, then send `input` in its place. `None` when no edit is pending |
| 2048 | /// or there is nothing to replace, so the input is sent as a normal turn. |
| 2049 | /// |
| 2050 | /// The rollback is staged, not applied, by the command layer (#6788); running |
| 2051 | /// `/undo` here and discarding its result left the old exchange in the |
| 2052 | /// transcript, the model context and the saved session. |
| 2053 | pub(super) fn edit_replacement_result( |
| 2054 | app: &mut App, |
| 2055 | input: &str, |
| 2056 | ) -> Option<commands::CommandResult> { |
| 2057 | if !std::mem::take(&mut app.edit_in_progress) { |
| 2058 | return None; |
| 2059 | } |
| 2060 | let sync = crate::commands::staged_conversation_undo(app)?; |
| 2061 | Some(commands::CommandResult { |
| 2062 | message: None, |
| 2063 | action: Some(AppAction::ConversationUndo { |
| 2064 | sync, |
| 2065 | restored_files: 0, |
| 2066 | retry_input: Some(input.to_string()), |
| 2067 | edit_replacement: true, |
| 2068 | }), |
| 2069 | is_error: false, |
| 2070 | }) |
| 2071 | } |
| 2072 | |
| 2073 | #[allow(clippy::too_many_lines, clippy::too_many_arguments)] |
| 2074 | /// Whether the git probe may run this tick: whenever the workspace-context |
| 2075 | /// refresh may, and also during a live turn or agent run while the Git view |
| 2076 | /// is the one showing (#6565). The probe is off-thread, on a 2s TTL, and |
| 2077 | /// takes no optional locks, so running it mid-turn cannot block the user's |
| 2078 | /// own git. |
| 2079 | pub(crate) fn git_probe_allowed(app: &App, workspace_context_refresh_allowed: bool) -> bool { |
| 2080 | workspace_context_refresh_allowed || git_panel_visible(app) |
| 2081 | } |
| 2082 | |
| 2083 | /// The quiet time the git probe schedule sees: none at all while the Git |
| 2084 | /// panel is showing, so that live view keeps the fast cadence (#6728). |
| 2085 | pub(crate) fn git_probe_quiet_for(app: &App, quiet_for: Duration) -> Duration { |
| 2086 | if git_panel_visible(app) { |
| 2087 | Duration::ZERO |
| 2088 | } else { |
| 2089 | quiet_for |
| 2090 | } |
| 2091 | } |
| 2092 | |
| 2093 | /// The Git rail panel is showing: it is the live repository state, so the |
| 2094 | /// probe keeps its fast cadence however quiet the session is (#6728). |
| 2095 | pub(crate) fn git_panel_visible(app: &App) -> bool { |
| 2096 | app.work_surface.panel == crate::tui::work_surface::RailPanel::Git |
| 2097 | && app.work_surface.effective_placement() |
| 2098 | != crate::tui::work_surface::WorkSurfacePlacement::Off |
| 2099 | } |
| 2100 | |
| 2101 | fn names_a_builtin_command(input: &str) -> bool { |
| 2102 | input |
| 2103 | .strip_prefix('/') |
| 2104 | .and_then(|rest| rest.split_whitespace().next()) |
| 2105 | .is_some_and(|name| { |
| 2106 | codewhale_engine::command_catalog::CommandCatalog::answers_to( |
| 2107 | &crate::commands::CommandTable, |
| 2108 | &name.to_ascii_lowercase(), |
| 2109 | ) |
| 2110 | }) |
| 2111 | } |
| 2112 | |
| 2113 | #[cfg(test)] |
| 2114 | mod typed_command_tests { |
| 2115 | #[test] |
| 2116 | fn an_exactly_typed_alias_is_not_replaced_by_the_menu_highlight() { |
| 2117 | assert!(super::names_a_builtin_command("/pet")); |
| 2118 | assert!(super::names_a_builtin_command("/whale")); |
| 2119 | assert!(!super::names_a_builtin_command("/pe")); |
| 2120 | assert!(!super::names_a_builtin_command("pet")); |
| 2121 | } |
| 2122 | } |
| 2123 | |
| 2124 | pub(crate) async fn run_event_loop( |
| 2125 | terminal: &mut AppTerminal, |
| 2126 | app: &mut App, |
| 2127 | config: &mut Config, |
| 2128 | mut engine_handle: EngineHandle, |
| 2129 | task_manager: SharedTaskManager, |
| 2130 | event_broker: &EventBroker, |
| 2131 | translation_client: Option<Arc<CodewhaleClient>>, |
| 2132 | mut pending_telemetry_notice: Option< |
| 2133 | codewhale_engine::telemetry_notice::PendingTelemetryNotice, |
| 2134 | >, |
| 2135 | mut dispatch_completion_rx: tokio::sync::mpsc::Receiver<crate::tui::app::DispatchApplyFn>, |
| 2136 | ) -> Result<()> { |
| 2137 | // Track streaming state |
| 2138 | let mut signal_checkpoint = persistence_actor::register_signal_checkpoint(); |
| 2139 | let mut current_streaming_text = String::new(); |
| 2140 | let mut stream_display_clock = StreamDisplayClock::default(); |
| 2141 | let (translation_tx, mut translation_rx) = |
| 2142 | tokio::sync::mpsc::unbounded_channel::<TranslationEvent>(); |
| 2143 | let fallback_translation_client = translation_client; |
| 2144 | // Set when the telemetry disclosure cell is queued; cleared (and the |
| 2145 | // disclosure recorded) by the first draw that paints it. |
| 2146 | let mut telemetry_notice_awaiting_render = false; |
| 2147 | let mut background_commands_shown: Vec<&'static str> = Vec::new(); |
| 2148 | let mut active_translation_client = fallback_translation_client.clone(); |
| 2149 | let mut active_translation_route: Option<codewhale_engine::core::events::TurnRoute> = None; |
| 2150 | let mut translation_sequence = 0_u64; |
| 2151 | let mut pending_translations = 0usize; |
| 2152 | // #5931: the background runtime's own store faults arrive on its event |
| 2153 | // channel, which nothing else in this loop reads. |
| 2154 | let mut runtime_event_rx = task_manager.subscribe_runtime_events(); |
| 2155 | let mut pending_thinking_translations = 0usize; |
| 2156 | let mut last_queue_state = offline_queue_projection(app); |
| 2157 | let mut last_queue_was_empty = offline_queue_is_empty(app); |
| 2158 | let mut last_task_refresh = Instant::now() |
| 2159 | .checked_sub(Duration::from_secs(2)) |
| 2160 | .unwrap_or_else(Instant::now); |
| 2161 | let mut last_status_frame = Instant::now() |
| 2162 | .checked_sub(Duration::from_millis(UI_STATUS_ANIMATION_MS)) |
| 2163 | .unwrap_or_else(Instant::now); |
| 2164 | let mut last_live_motion_mark = last_status_frame; |
| 2165 | let mut idle_clock = IdleClock::new(Instant::now()); |
| 2166 | let mut skill_registry_epoch = None; |
| 2167 | let mut skill_cache_refresh: Option<SkillCacheRefresh> = None; |
| 2168 | let mut last_automation_scan = Instant::now() |
| 2169 | .checked_sub(AUTOMATION_SCAN_BUSY_INTERVAL) |
| 2170 | .unwrap_or_else(Instant::now); |
| 2171 | // 120 FPS draw cap. Without this we redraw on every SSE chunk during a |
| 2172 | // long stream — wasted work the user can't perceive. See |
| 2173 | // `tui::frame_rate_limiter` for the rationale; ports the small piece of |
| 2174 | // codex's frame coalescing that maps cleanly onto our poll-based loop. |
| 2175 | // Measured display Hz may raise the floor toward the panel refresh rate |
| 2176 | // (still never faster than MIN_FRAME_INTERVAL); low_motion always wins. |
| 2177 | let mut frame_rate_limiter = crate::tui::frame_rate_limiter::FrameRateLimiter::default(); |
| 2178 | { |
| 2179 | let probe = crate::tui::display_refresh::probe_display_refresh(); |
| 2180 | frame_rate_limiter.set_adaptive_interval(Some( |
| 2181 | crate::tui::display_refresh::draw_min_interval_for_hz(probe.hz, false), |
| 2182 | )); |
| 2183 | } |
| 2184 | // Widgets request future animation frames here; the poll loop remains the |
| 2185 | // sole `terminal.draw` emitter (no competing animation loop). |
| 2186 | let mut frame_requester = FrameRequester::new(); |
| 2187 | // Per-session control socket (`[control_socket]`): disabled unless the |
| 2188 | // config enables it; even then, nothing binds until the owned session id |
| 2189 | // appears (see the per-iteration reconcile below). |
| 2190 | let mut session_control = SessionControl::new( |
| 2191 | config |
| 2192 | .control_socket |
| 2193 | .as_ref() |
| 2194 | .is_some_and(|socket| socket.enabled), |
| 2195 | ); |
| 2196 | let mut prev_input_snapshot = String::new(); |
| 2197 | let mut terminal_paused_at: Option<Instant> = None; |
| 2198 | // Last observed coarse turn state for the session-state hook transitions |
| 2199 | // (#6004); `None` until the first publish records it without firing. |
| 2200 | let mut previous_turn_state = None; |
| 2201 | let mut terminal_repaint = FrameRepaint::Diff; |
| 2202 | // #6311: while the terminal reports unfocused, frames are pure backlog |
| 2203 | // (GTK3 defers all VTE damage on occlusion and replays it on return). |
| 2204 | // Event ingestion continues; only `terminal.draw` emission is gated. |
| 2205 | let mut terminal_unfocused = false; |
| 2206 | let defer_frames_on_focus_loss = focus_loss_defers_frames( |
| 2207 | std::env::var("VTE_VERSION").ok().as_deref(), |
| 2208 | std::env::var("TMUX").ok().as_deref(), |
| 2209 | ); |
| 2210 | // FocusGained debounce: some terminal emulators (e.g. Tabby) re-trigger |
| 2211 | // FocusGained when we re-arm focus-change reporting inside |
| 2212 | // recover_terminal_modes, creating a tight repaint loop. Skip |
| 2213 | // mode recovery (but still mark a repaint) within the debounce window. |
| 2214 | const FOCUS_RECOVERY_DEBOUNCE: Duration = Duration::from_millis(200); |
| 2215 | let mut last_focus_recovery = Instant::now() |
| 2216 | .checked_sub(Duration::from_secs(60)) |
| 2217 | .unwrap_or_else(Instant::now); |
| 2218 | // #5925: the startup terminal probes (OSC 11 background, kitty graphics, |
| 2219 | // sixel primary-DA) were the only readers of the tty until now, and they |
| 2220 | // consumed whatever the user had already typed. Replay it into the same |
| 2221 | // queue the pump feeds — and do it *before* the pump is spawned, so those |
| 2222 | // keys are delivered ahead of anything still sitting in the tty rather |
| 2223 | // than behind it. |
| 2224 | let mut replayed_startup_events = VecDeque::new(); |
| 2225 | let startup_input_receipt = |
| 2226 | crate::tui::startup_input::replay_into(&mut replayed_startup_events); |
| 2227 | let startup_input_observed_at = Instant::now(); |
| 2228 | let mut pending_terminal_events: VecDeque<ObservedTerminalEvent> = replayed_startup_events |
| 2229 | .into_iter() |
| 2230 | .map(|event| ObservedTerminalEvent::new(event, startup_input_observed_at)) |
| 2231 | .collect(); |
| 2232 | // When startup could not account for every byte it consumed, the shell |
| 2233 | // cannot prove it saw the whole line. The composer holds the next submit |
| 2234 | // instead of sending text it cannot vouch for. |
| 2235 | app.startup_input_unproven = !startup_input_receipt.whole_line_proven(); |
| 2236 | let mut terminal_input = TerminalInputPump::spawn()?; |
| 2237 | let mut last_terminal_input_recovery = Instant::now() |
| 2238 | .checked_sub(TERMINAL_INPUT_RECOVERY_COOLDOWN) |
| 2239 | .unwrap_or_else(Instant::now); |
| 2240 | let mut last_recovery_snapshot_at: Option<Instant> = None; |
| 2241 | // Fire-and-forget version check — runs once per session in the |
| 2242 | // background. On success, a short status toast advertises the update |
| 2243 | // without replacing the user's configured footer/status-line chips. |
| 2244 | let mut version_check: Option<tokio::task::JoinHandle<Option<UpdateNotice>>> = |
| 2245 | spawn_startup_version_check(config.update_config()); |
| 2246 | // First-run / missing-key: if a live local Ollama catalog answers, adopt a |
| 2247 | // real /api/tags model into chrome instead of leaving the DeepSeek costume. |
| 2248 | app.start_local_ollama_probe(config, false); |
| 2249 | |
| 2250 | app.launch.whats_new = |
| 2251 | crate::whats_new::take_after_update(app.ui_locale, config.update_config().show_whats_new); |
| 2252 | |
| 2253 | // Fire a one-shot initial remaining-credit fetch for prepaid |
| 2254 | // providers so the footer chip can show on the first frame without |
| 2255 | // waiting for a turn to complete. |
| 2256 | if !app.balance_initiated { |
| 2257 | let api_key = config.active_route_api_key().unwrap_or_default(); |
| 2258 | let base_url = config.active_route_base_url(); |
| 2259 | schedule_balance_fetch(app, &api_key, &base_url, false); |
| 2260 | app.balance_initiated = true; |
| 2261 | } |
| 2262 | |
| 2263 | let mut pending_subagent_list_refresh = false; |
| 2264 | let mut session_save_health_seen = 0u64; |
| 2265 | |
| 2266 | loop { |
| 2267 | // #6169: first statement of every iteration. The job-control handler can |
| 2268 | // stop this process mid-turn (SIGTSTP, or SIGTTIN once the group is |
| 2269 | // backgrounded) after restoring the terminal from inside the handler. |
| 2270 | // SIGCONT only records that the stop happened; the rebuild happens here, |
| 2271 | // in normal context, where crossterm is safe to call. |
| 2272 | // |
| 2273 | // Two deferrals, both deliberate: a child owning the tty is handled by |
| 2274 | // the pause/resume block further down (it rebuilds the modes itself), and |
| 2275 | // a group that is still background (a plain `bg`) must not touch the |
| 2276 | // terminal at all — re-entering raw mode and the alternate screen would |
| 2277 | // steal the shell's tty. The state is left pending either way, so the |
| 2278 | // rebuild still runs on the iteration after `fg`. |
| 2279 | if job_control_guard::take_resume() |
| 2280 | && !event_broker.is_paused() |
| 2281 | && require_foreground_terminal_owner().is_ok() |
| 2282 | { |
| 2283 | job_control_guard::mark_resumed(); |
| 2284 | resume_terminal( |
| 2285 | terminal, |
| 2286 | app.use_mouse_capture, |
| 2287 | app.use_bracketed_paste, |
| 2288 | app.synchronized_output_enabled, |
| 2289 | )?; |
| 2290 | event_broker.resume_events(); |
| 2291 | // The input pump is deliberately not told about this: it is only |
| 2292 | // ever gated by `pause_terminal_input_for_child` / |
| 2293 | // `resume_after_child_terminal`, and calling the latter here would |
| 2294 | // falsely clear a child's gate. |
| 2295 | app.show_event_notice("Resumed after suspend".to_string(), StatusToastLevel::Info); |
| 2296 | app.needs_redraw = true; |
| 2297 | terminal_repaint = FrameRepaint::Clear; |
| 2298 | } |
| 2299 | |
| 2300 | if rearm_terminal_if_restored_by_panic( |
| 2301 | event_broker.is_paused(), |
| 2302 | || require_foreground_terminal_owner().is_ok(), |
| 2303 | || { |
| 2304 | resume_terminal( |
| 2305 | terminal, |
| 2306 | app.use_mouse_capture, |
| 2307 | app.use_bracketed_paste, |
| 2308 | app.synchronized_output_enabled, |
| 2309 | ) |
| 2310 | }, |
| 2311 | )? { |
| 2312 | app.needs_redraw = true; |
| 2313 | terminal_repaint = FrameRepaint::Clear; |
| 2314 | } |
| 2315 | |
| 2316 | // The background session-store repair's one-line result (#6144). |
| 2317 | if let Some(notice) = codewhale_engine::session_reconcile::take_pending_notice() { |
| 2318 | app.push_status_toast(notice, StatusToastLevel::Info, None); |
| 2319 | app.needs_redraw = true; |
| 2320 | } |
| 2321 | |
| 2322 | if app.onboarding == OnboardingState::None |
| 2323 | && telemetry_notice_may_enter_transcript(app) |
| 2324 | && let Some(notice) = app.launch.whats_new.take() |
| 2325 | { |
| 2326 | let content = format!("{}\n{}", notice.headline(), notice.notes_with_command()); |
| 2327 | app.add_message(HistoryCell::System { content }); |
| 2328 | app.needs_redraw = true; |
| 2329 | } |
| 2330 | |
| 2331 | // The disclosure is a transcript cell, not a toast: a 12 s toast |
| 2332 | // showed only its first sentence at 100 columns and hid the opt-out. |
| 2333 | // A transcript cell would also replace the launch card, whose |
| 2334 | // "no model connected" line is the first-run recovery, so the cell |
| 2335 | // waits until the card starts to leave. It counts as presented only |
| 2336 | // once a frame containing it was drawn; quitting first re-owes it. |
| 2337 | if app.onboarding == OnboardingState::None |
| 2338 | && telemetry_notice_may_enter_transcript(app) |
| 2339 | && pending_telemetry_notice.take().is_some() |
| 2340 | { |
| 2341 | let notice = app.tr(MessageId::TelemetryNoticeDefaultOn).into_owned(); |
| 2342 | app.add_message(HistoryCell::System { content: notice }); |
| 2343 | app.needs_redraw = true; |
| 2344 | telemetry_notice_awaiting_render = true; |
| 2345 | } |
| 2346 | |
| 2347 | if let Ok(acknowledge) = signal_checkpoint.try_recv() { |
| 2348 | persist_offline_queue_state(app); |
| 2349 | if turn_unsettled_for_shutdown(app) { |
| 2350 | app.cancel_in_flight_dispatch(); |
| 2351 | engine_handle |
| 2352 | .cancel_with_reason(codewhale_engine::core::engine::CancelReason::External); |
| 2353 | let drain = async { |
| 2354 | let mut events = engine_handle.rx_event.write().await; |
| 2355 | while events.recv().await.is_some() {} |
| 2356 | }; |
| 2357 | let snapshot = tokio::select! { |
| 2358 | biased; |
| 2359 | result = engine_handle.get_session_snapshot() => result.ok(), |
| 2360 | () = drain => None, |
| 2361 | }; |
| 2362 | if let Some(snapshot) = snapshot |
| 2363 | && snapshot.source.as_ref().is_some_and(|source| { |
| 2364 | app.session_write_owner |
| 2365 | .as_ref() |
| 2366 | .is_some_and(|owner| owner.matches_source(source)) |
| 2367 | }) |
| 2368 | && !acknowledge.is_closed() |
| 2369 | && apply_recovery_messages( |
| 2370 | app, |
| 2371 | &snapshot.session_id, |
| 2372 | &snapshot.workspace, |
| 2373 | Arc::new(snapshot.messages), |
| 2374 | ) |
| 2375 | { |
| 2376 | persist_recovery_snapshot(app); |
| 2377 | } else { |
| 2378 | tracing::warn!( |
| 2379 | "signal exit kept the preceding checkpoint because the Engine snapshot did not settle on this session" |
| 2380 | ); |
| 2381 | } |
| 2382 | } |
| 2383 | let _ = acknowledge.send(()); |
| 2384 | return std::future::pending().await; |
| 2385 | } |
| 2386 | |
| 2387 | // A manual compaction deferred by a full engine mailbox retries here |
| 2388 | // each iteration until a slot frees or a live pass supersedes it. |
| 2389 | flush_deferred_manual_compaction(app, config, &engine_handle); |
| 2390 | // Any fleet mutation since the last iteration (`/fleet add|remove`, |
| 2391 | // ⇧F, auto-enroll) reaches the engine here, through the one roster |
| 2392 | // path the saved-fleet views already use. |
| 2393 | flush_stale_fleet_roster(app, config, &engine_handle); |
| 2394 | // Goal controls are accepted only after their bounded sidecar is |
| 2395 | // durable. Mailbox backpressure must therefore defer delivery, never |
| 2396 | // block keyboard input or silently drop the accepted control. |
| 2397 | flush_pending_goal_controls(app, &engine_handle); |
| 2398 | |
| 2399 | // Per-session control socket: rebind when the owned session id |
| 2400 | // changes, republish the `status` snapshot, and execute queued |
| 2401 | // verbs on the UI thread. |
| 2402 | session_control.reconcile(app.current_session_id.as_deref()); |
| 2403 | session_control.update_status(app); |
| 2404 | execute_session_state_transition_hooks(app, &mut previous_turn_state); |
| 2405 | session_control |
| 2406 | .drain( |
| 2407 | app, |
| 2408 | config, |
| 2409 | &engine_handle, |
| 2410 | &mut current_streaming_text, |
| 2411 | &mut stream_display_clock, |
| 2412 | ) |
| 2413 | .await; |
| 2414 | |
| 2415 | while let Some(completion) = app.clipboard.poll_write_completion() { |
| 2416 | if let Err(err) = completion { |
| 2417 | tracing::warn!(error = %err, "background terminal clipboard write failed"); |
| 2418 | app.push_status_toast( |
| 2419 | crate::tui::mouse_ui::copy_failed_receipt(app, &err), |
| 2420 | StatusToastLevel::Error, |
| 2421 | None, |
| 2422 | ); |
| 2423 | app.needs_redraw = true; |
| 2424 | } |
| 2425 | } |
| 2426 | |
| 2427 | crate::tui::paste::poll_pending_paste(app); |
| 2428 | |
| 2429 | // Drain dispatch completions from spawned send tasks (#4605). The |
| 2430 | // closure receives `&mut App` and applies success state or rollback. |
| 2431 | while let Ok(apply) = dispatch_completion_rx.try_recv() { |
| 2432 | let _ = apply(app, &engine_handle, &*config); |
| 2433 | // Drain this completion immediately: a later completion cannot replace an edit. |
| 2434 | super::feedback_host::dispatch_ready(app, config, &engine_handle).await?; |
| 2435 | for result in crate::commands::background_host::take_ready() { |
| 2436 | if apply_command_result(terminal, app, &mut engine_handle, config, result).await? { |
| 2437 | return Ok(()); |
| 2438 | } |
| 2439 | } |
| 2440 | } |
| 2441 | sync_background_command_notices(app, &mut background_commands_shown); |
| 2442 | |
| 2443 | if app.onboarding == OnboardingState::Provider && app.view_stack.top_kind().is_none() { |
| 2444 | let recover_configured_route = app.onboarding_recovers_configured_route(); |
| 2445 | open_model_connection_setup(app, &*config, &engine_handle, recover_configured_route) |
| 2446 | .await; |
| 2447 | } |
| 2448 | |
| 2449 | // Drain the version-check handle once; re-assign None so we |
| 2450 | // don't poll it again. |
| 2451 | let mut done = false; |
| 2452 | if let Some(ref handle) = version_check { |
| 2453 | done = handle.is_finished(); |
| 2454 | } |
| 2455 | if done && let Ok(Some(notice)) = version_check.take().unwrap().await { |
| 2456 | // Transient toast for immediate visibility, plus a durable |
| 2457 | // in-transcript notice so the prompt survives the toast TTL and |
| 2458 | // stays actionable during a busy session (#3961). The persistent |
| 2459 | // metrics-line notice keeps a quiet affordance after both (#14). |
| 2460 | // Which command to advertise depends on who owns this binary on |
| 2461 | // disk, so resolve that here rather than hardcoding our own |
| 2462 | // updater into the wording. |
| 2463 | let install = codewhale_release::current_install_method(); |
| 2464 | app.update_available = Some(notice.chip_label()); |
| 2465 | app.push_status_toast( |
| 2466 | notice.toast_line(install), |
| 2467 | StatusToastLevel::Info, |
| 2468 | Some(VERSION_HINT_TOAST_TTL_MS), |
| 2469 | ); |
| 2470 | app.add_message(HistoryCell::System { |
| 2471 | content: notice.notice_block(install), |
| 2472 | }); |
| 2473 | } |
| 2474 | |
| 2475 | // Adopt a live local Ollama tag into first-run / missing-key chrome. |
| 2476 | if app |
| 2477 | .local_ollama_probe |
| 2478 | .as_ref() |
| 2479 | .is_some_and(|probe| probe.task.is_finished()) |
| 2480 | && let Some(probe) = app.local_ollama_probe.take() |
| 2481 | { |
| 2482 | let retry_current = probe.requested |
| 2483 | && app.api_provider == ProviderKind::Ollama |
| 2484 | && app.should_adopt_live_local_ollama(); |
| 2485 | if let Ok(Some(catalog)) = probe.task.await { |
| 2486 | app.local_runtime_detected = true; |
| 2487 | if retry_current && catalog.preferred_tag().is_none() { |
| 2488 | app.push_status_toast( |
| 2489 | app.tr(MessageId::RouteNoModels), |
| 2490 | StatusToastLevel::Warning, |
| 2491 | None, |
| 2492 | ); |
| 2493 | } else if !probe.requested || retry_current { |
| 2494 | adopt_live_local_ollama_catalog(app, &mut engine_handle, config, catalog).await; |
| 2495 | } |
| 2496 | } else if retry_current { |
| 2497 | app.push_status_toast( |
| 2498 | app.tr(MessageId::ModelsUpdatePartial), |
| 2499 | StatusToastLevel::Warning, |
| 2500 | None, |
| 2501 | ); |
| 2502 | } |
| 2503 | } |
| 2504 | |
| 2505 | // Non-blocking startup-default writes (mode / thinking) report their |
| 2506 | // failures here rather than at the keystroke, so a settings file we |
| 2507 | // could not write is visible instead of silently reverting next launch. |
| 2508 | app.drain_startup_default_failures(); |
| 2509 | |
| 2510 | while let Ok(event) = translation_rx.try_recv() { |
| 2511 | match event { |
| 2512 | TranslationEvent::AssistantMessage { |
| 2513 | origin_session_fingerprint, |
| 2514 | origin_turn_fingerprint, |
| 2515 | history_index, |
| 2516 | original_text, |
| 2517 | translated, |
| 2518 | usage, |
| 2519 | thinking, |
| 2520 | tool_uses, |
| 2521 | } => { |
| 2522 | pending_translations = pending_translations.saturating_sub(1); |
| 2523 | if translation_session_is_current(app, origin_session_fingerprint.as_deref()) |
| 2524 | && let Some(usage) = usage.as_ref() |
| 2525 | { |
| 2526 | accrue_translation_usage(app, usage); |
| 2527 | } |
| 2528 | if !translation_origin_is_current( |
| 2529 | app, |
| 2530 | origin_session_fingerprint.as_deref(), |
| 2531 | origin_turn_fingerprint.as_deref(), |
| 2532 | ) { |
| 2533 | tracing::debug!( |
| 2534 | "discarded assistant translation completed for a stale session/turn" |
| 2535 | ); |
| 2536 | continue; |
| 2537 | } |
| 2538 | let text = match translated { |
| 2539 | Ok(text) => { |
| 2540 | app.show_event_notice( |
| 2541 | codewhale_localization::tr( |
| 2542 | app.ui_locale, |
| 2543 | codewhale_localization::MessageId::TranslationComplete, |
| 2544 | ) |
| 2545 | .to_string(), |
| 2546 | StatusToastLevel::Success, |
| 2547 | ); |
| 2548 | text |
| 2549 | } |
| 2550 | Err(err) => { |
| 2551 | tracing::warn!("assistant translation failed: {err}"); |
| 2552 | app.show_event_notice( |
| 2553 | format!( |
| 2554 | "{}: {err}", |
| 2555 | codewhale_localization::tr( |
| 2556 | app.ui_locale, |
| 2557 | codewhale_localization::MessageId::TranslationFailed, |
| 2558 | ) |
| 2559 | ), |
| 2560 | StatusToastLevel::Error, |
| 2561 | ); |
| 2562 | codewhale_localization::hidden_translation_failed(app.ui_locale) |
| 2563 | .to_string() |
| 2564 | } |
| 2565 | }; |
| 2566 | |
| 2567 | if let Some(index) = history_index |
| 2568 | && let Some(HistoryCell::Assistant { content, .. }) = |
| 2569 | app.history.get_mut(index) |
| 2570 | { |
| 2571 | *content = text.clone(); |
| 2572 | app.record_completed_assistant_output(index, &text); |
| 2573 | app.bump_history_cell(index); |
| 2574 | } |
| 2575 | if !replace_matching_assistant_text(app, &original_text, text.clone()) { |
| 2576 | push_assistant_message(app, text, thinking, tool_uses); |
| 2577 | } |
| 2578 | if pending_translations == 0 |
| 2579 | && !matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) |
| 2580 | { |
| 2581 | app.is_loading = pending_translations > 0; |
| 2582 | } |
| 2583 | app.needs_redraw = true; |
| 2584 | } |
| 2585 | TranslationEvent::Thinking { |
| 2586 | origin_session_fingerprint, |
| 2587 | origin_turn_fingerprint, |
| 2588 | translation_id, |
| 2589 | translated, |
| 2590 | usage, |
| 2591 | } => { |
| 2592 | pending_translations = pending_translations.saturating_sub(1); |
| 2593 | pending_thinking_translations = pending_thinking_translations.saturating_sub(1); |
| 2594 | let cell_index = app |
| 2595 | .pending_thinking_translation_cells |
| 2596 | .remove(&translation_id); |
| 2597 | if translation_session_is_current(app, origin_session_fingerprint.as_deref()) |
| 2598 | && let Some(usage) = usage.as_ref() |
| 2599 | { |
| 2600 | accrue_translation_usage(app, usage); |
| 2601 | } |
| 2602 | if !translation_origin_is_current( |
| 2603 | app, |
| 2604 | origin_session_fingerprint.as_deref(), |
| 2605 | origin_turn_fingerprint.as_deref(), |
| 2606 | ) { |
| 2607 | tracing::debug!( |
| 2608 | "discarded thinking translation completed for a stale session/turn" |
| 2609 | ); |
| 2610 | continue; |
| 2611 | } |
| 2612 | let text = match translated { |
| 2613 | Ok(text) => { |
| 2614 | app.show_event_notice( |
| 2615 | codewhale_localization::thinking_translation_complete( |
| 2616 | app.ui_locale, |
| 2617 | ) |
| 2618 | .to_string(), |
| 2619 | StatusToastLevel::Success, |
| 2620 | ); |
| 2621 | text |
| 2622 | } |
| 2623 | Err(err) => { |
| 2624 | tracing::warn!("thinking translation failed: {err}"); |
| 2625 | app.show_event_notice( |
| 2626 | format!( |
| 2627 | "{}: {err}", |
| 2628 | codewhale_localization::thinking_translation_failed( |
| 2629 | app.ui_locale |
| 2630 | ) |
| 2631 | ), |
| 2632 | StatusToastLevel::Error, |
| 2633 | ); |
| 2634 | codewhale_localization::hidden_translation_failed(app.ui_locale) |
| 2635 | .to_string() |
| 2636 | } |
| 2637 | }; |
| 2638 | if let Some(cell_index) = cell_index { |
| 2639 | streaming_thinking::replace_pending_translation(app, cell_index, text); |
| 2640 | } |
| 2641 | if pending_translations == 0 |
| 2642 | && !matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) |
| 2643 | { |
| 2644 | app.is_loading = false; |
| 2645 | } |
| 2646 | app.needs_redraw = true; |
| 2647 | } |
| 2648 | } |
| 2649 | } |
| 2650 | |
| 2651 | if last_task_refresh.elapsed() >= Duration::from_millis(2500) { |
| 2652 | // Reads through the App's slot: a session switch can replace the |
| 2653 | // manager, and a launch-time handle would then describe a store |
| 2654 | // this host no longer holds. |
| 2655 | match refresh_active_task_panel(app).await { |
| 2656 | LiveRefresh::Changed => app.needs_redraw = true, |
| 2657 | LiveRefresh::ElapsedOnly => idle_clock.note_elapsed_only_change(), |
| 2658 | LiveRefresh::Unchanged => {} |
| 2659 | } |
| 2660 | // Shells and tasks that finished join the batched notice; a batch |
| 2661 | // held for finite work or a busy parent turn goes out once that |
| 2662 | // work settles (#6565). |
| 2663 | flush_background_finished(app, config, false); |
| 2664 | // A finished scan is folded on every tick; the next one starts |
| 2665 | // only when due. A quiet UI with nothing scheduled or live |
| 2666 | // rescans on the long cadence (#6728). |
| 2667 | let automation_scan_due = automation_scan_is_due( |
| 2668 | app, |
| 2669 | idle_clock.ui_quiet(), |
| 2670 | Instant::now().saturating_duration_since(last_automation_scan), |
| 2671 | ); |
| 2672 | if refresh_automation_panel(app, automation_scan_due).await { |
| 2673 | app.needs_redraw = true; |
| 2674 | } |
| 2675 | if automation_scan_due { |
| 2676 | last_automation_scan = Instant::now(); |
| 2677 | } |
| 2678 | match refresh_shell_exec_live_output(app) { |
| 2679 | LiveRefresh::Changed => app.needs_redraw = true, |
| 2680 | LiveRefresh::ElapsedOnly => idle_clock.note_elapsed_only_change(), |
| 2681 | LiveRefresh::Unchanged => {} |
| 2682 | } |
| 2683 | if crate::tui::shell_job_routing::refresh_live_shell_job_pager(app) { |
| 2684 | app.needs_redraw = true; |
| 2685 | } |
| 2686 | if app |
| 2687 | .runtime_services |
| 2688 | .work |
| 2689 | .as_ref() |
| 2690 | .is_some_and(|work| work.has_pending_publish()) |
| 2691 | && let Err(err) = persist_pending_work_checkpoint(app).await |
| 2692 | { |
| 2693 | tracing::warn!(error = %err, "background Work lifecycle checkpoint remains pending"); |
| 2694 | } |
| 2695 | last_task_refresh = Instant::now(); |
| 2696 | } |
| 2697 | |
| 2698 | // Clear suggestion when the user modifies the input. |
| 2699 | if app.input != prev_input_snapshot { |
| 2700 | app.prompt_suggestion = None; |
| 2701 | prev_input_snapshot = app.input.clone(); |
| 2702 | } |
| 2703 | |
| 2704 | // Poll prompt suggestion cell from background generation task. |
| 2705 | // Discard stale results whose generation token no longer matches. |
| 2706 | if let Ok(mut guard) = app.prompt_suggestion_cell.try_lock() |
| 2707 | && let Some((gen_token, suggestion)) = guard.take() |
| 2708 | && gen_token |
| 2709 | == app |
| 2710 | .prompt_suggestion_gen |
| 2711 | .load(std::sync::atomic::Ordering::Relaxed) |
| 2712 | { |
| 2713 | app.prompt_suggestion = Some(suggestion); |
| 2714 | } |
| 2715 | |
| 2716 | // Poll the fleet-profile model-draft cell filled by the background |
| 2717 | // drafting task (#3757 review: the draft must not park the loop). |
| 2718 | let fleet_draft_delivery = app |
| 2719 | .fleet_draft_cell |
| 2720 | .try_lock() |
| 2721 | .ok() |
| 2722 | .and_then(|mut guard| guard.take()); |
| 2723 | if let Some((draft_gen, model_label, picked_route, reasoning_effort, outcome)) = |
| 2724 | fleet_draft_delivery |
| 2725 | && draft_gen == app.current_draft_gen() |
| 2726 | { |
| 2727 | deliver_fleet_draft_result( |
| 2728 | app, |
| 2729 | model_label, |
| 2730 | picked_route, |
| 2731 | reasoning_effort, |
| 2732 | outcome, |
| 2733 | app.ui_locale, |
| 2734 | ); |
| 2735 | } |
| 2736 | |
| 2737 | // Poll the constitution model-draft cell (same background pattern). |
| 2738 | let constitution_draft_delivery = app |
| 2739 | .constitution_draft_cell |
| 2740 | .try_lock() |
| 2741 | .ok() |
| 2742 | .and_then(|mut guard| guard.take()); |
| 2743 | if let Some((draft_gen, model_label, draft_locale, outcome)) = constitution_draft_delivery |
| 2744 | && draft_gen == app.current_draft_gen() |
| 2745 | { |
| 2746 | deliver_constitution_draft_result(app, model_label, draft_locale, outcome); |
| 2747 | } |
| 2748 | |
| 2749 | surface_session_save_health( |
| 2750 | app, |
| 2751 | crate::tui::persistence_actor::session_save_health(), |
| 2752 | &mut session_save_health_seen, |
| 2753 | ); |
| 2754 | |
| 2755 | // Discovery and callback delivery never park terminal input. |
| 2756 | poll_mcp_login(app); |
| 2757 | if let Some(server) = app.mcp_login_reconnect.take() { |
| 2758 | start_mcp_retry(app, &engine_handle, server); |
| 2759 | } |
| 2760 | poll_mcp_retries(app); |
| 2761 | if super::session_state::poll_fresh_session(app, &engine_handle) { |
| 2762 | super::session_state::persist_full_reset_snapshot(app); |
| 2763 | } |
| 2764 | |
| 2765 | // #1830/#2317: service any already-arrived terminal keys before a |
| 2766 | // potentially long engine batch so composer/modal input stays live. |
| 2767 | collect_pending_terminal_events(&terminal_input, &mut pending_terminal_events)?; |
| 2768 | if let Some(change) = app.poll_external_catalog_changes(mcp_engine_busy(app)) { |
| 2769 | apply_external_catalog_change(terminal, app, &mut engine_handle, config, change) |
| 2770 | .await?; |
| 2771 | } |
| 2772 | |
| 2773 | if drain_remote_control_events(app, config, &engine_handle).await? { |
| 2774 | app.needs_redraw = true; |
| 2775 | } |
| 2776 | if crate::tui::external_agent::poll_external_agent_discovery(app, config) { |
| 2777 | app.needs_redraw = true; |
| 2778 | } |
| 2779 | if crate::tui::external_agent::drain_external_agent_events( |
| 2780 | app, |
| 2781 | config.approval_default_selection(), |
| 2782 | ) { |
| 2783 | app.needs_redraw = true; |
| 2784 | } |
| 2785 | |
| 2786 | // First, poll for engine events (non-blocking) |
| 2787 | let mut received_engine_event = false; |
| 2788 | // Any engine event at all, including ones that asked for no redraw: |
| 2789 | // it is activity for the idle backoff (#6728). |
| 2790 | let mut engine_event_seen = false; |
| 2791 | let mut transcript_batch_updated = false; |
| 2792 | // #freeze: coalesce per-event `Op::ListSubAgents` sends into a single |
| 2793 | // trailing-edge refresh per drain. At high fanout, many spawn/complete/ |
| 2794 | // mailbox events in one drain otherwise each take the manager write |
| 2795 | // lock and trigger a full O(N) list reconcile. |
| 2796 | let mut subagent_list_refresh_requested = false; |
| 2797 | let mut queued_to_send: Option<QueuedMessage> = None; |
| 2798 | let mut respawn_after_provider_rollback: Option<String> = None; |
| 2799 | let mut fallback_after_engine_error: Option<ProviderFallbackRollback> = None; |
| 2800 | { |
| 2801 | let mut progress_redraw_agents: HashSet<String> = HashSet::new(); |
| 2802 | let drain_started = Instant::now(); |
| 2803 | let mut events_drained = 0usize; |
| 2804 | loop { |
| 2805 | if events_drained > 0 |
| 2806 | && engine_drain_budget_exhausted(events_drained, drain_started, Instant::now()) |
| 2807 | { |
| 2808 | break; |
| 2809 | } |
| 2810 | let next = engine_handle.rx_event.write().await.try_recv(); |
| 2811 | let event = match next { |
| 2812 | Ok(event) => event, |
| 2813 | Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break, |
| 2814 | Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => { |
| 2815 | if recover_engine_event_disconnect(app) { |
| 2816 | received_engine_event = true; |
| 2817 | transcript_batch_updated = true; |
| 2818 | } |
| 2819 | break; |
| 2820 | } |
| 2821 | }; |
| 2822 | if let EngineEvent::SessionUpdated { |
| 2823 | session_id, |
| 2824 | source, |
| 2825 | workspace, |
| 2826 | model, |
| 2827 | .. |
| 2828 | } = &event |
| 2829 | && super::session_state::acknowledge_fresh_session( |
| 2830 | app, |
| 2831 | session_id, |
| 2832 | source.as_ref(), |
| 2833 | workspace, |
| 2834 | model, |
| 2835 | ) |
| 2836 | { |
| 2837 | super::session_state::persist_full_reset_snapshot(app); |
| 2838 | } |
| 2839 | // Count every received event before any filter can `continue` |
| 2840 | // past it (U02-02). Filtered deltas, suppressed post-cancel |
| 2841 | // events and stale requests used to skip the counter, so a |
| 2842 | // producer flooding them never tripped the drain budget and |
| 2843 | // the loop never returned to render or read the cancel key. |
| 2844 | events_drained = events_drained.saturating_add(1); |
| 2845 | engine_event_seen = true; |
| 2846 | // #3033: remember whether an EARLIER event in this drain batch |
| 2847 | // already requested a redraw. The AgentProgress throttle below |
| 2848 | // may opt the current event out of repainting, but it must not |
| 2849 | // cancel redraws owed to other events in the same batch. |
| 2850 | let redraw_requested_before_event = received_engine_event; |
| 2851 | received_engine_event = true; |
| 2852 | if matches!( |
| 2853 | &event, |
| 2854 | EngineEvent::SessionUpdated { |
| 2855 | checkpoint: Some(_), |
| 2856 | .. |
| 2857 | } |
| 2858 | ) { |
| 2859 | apply_engine_session_projection(app, config, event); |
| 2860 | continue; |
| 2861 | } |
| 2862 | if !capture_turn_started_metadata(app, &event) { |
| 2863 | tracing::debug!("ignored a start from another native source"); |
| 2864 | continue; |
| 2865 | } |
| 2866 | observe_human_request_settlement(app, &event); |
| 2867 | // Child approval bookkeeping runs before every filter: it is |
| 2868 | // keyed by approval id and agent, not by the active session, |
| 2869 | // so a withdrawal always retires its card (approvals M1). |
| 2870 | if crate::tui::pending_requests::observe_engine_event(app, &event) { |
| 2871 | continue; |
| 2872 | } |
| 2873 | if app.suppress_stream_events_until_turn_complete { |
| 2874 | if matches!(event, EngineEvent::TurnStarted { .. }) { |
| 2875 | // Ctrl+C can race with the engine's per-turn token |
| 2876 | // reset: the first cancel may hit the previous token |
| 2877 | // if SendMessage is queued but TurnStarted has not |
| 2878 | // arrived yet. Reassert cancellation once the real |
| 2879 | // turn starts, then keep hiding its queued deltas. |
| 2880 | engine_handle.cancel(); |
| 2881 | continue; |
| 2882 | } |
| 2883 | if let EngineEvent::SessionUpdated { |
| 2884 | session_id, |
| 2885 | workspace, |
| 2886 | messages, |
| 2887 | checkpoint: None, |
| 2888 | source, |
| 2889 | .. |
| 2890 | } = &event |
| 2891 | && app.owns_session_projection(source.as_ref()) |
| 2892 | && messages.len().checked_sub(app.api_messages.len()) == Some(1) |
| 2893 | && messages |
| 2894 | .last() |
| 2895 | .is_some_and(|message| message.role == Role::InterruptedAssistant) |
| 2896 | { |
| 2897 | apply_recovery_messages(app, session_id, workspace, Arc::clone(messages)); |
| 2898 | } |
| 2899 | if suppress_engine_event_after_local_cancel(&event) { |
| 2900 | continue; |
| 2901 | } |
| 2902 | } else if !app.is_loading && ignore_stale_stream_event_while_idle(&event) { |
| 2903 | continue; |
| 2904 | } |
| 2905 | if resolve_stale_parent_request(app, &engine_handle, &event).await { |
| 2906 | continue; |
| 2907 | } |
| 2908 | if !matches!(event, EngineEvent::ApprovalRequired { .. }) { |
| 2909 | app.remote_control.observe_engine_event(&event); |
| 2910 | // A terminal boundary reached after deltas were shed under |
| 2911 | // pressure repairs account truth with a bounded snapshot. |
| 2912 | while let Some(resync_run) = app.remote_control.take_pending_resync() { |
| 2913 | app.remote_control |
| 2914 | .upload_resync_snapshot(&resync_run, &app.api_messages); |
| 2915 | } |
| 2916 | } |
| 2917 | let pet_event_applies = match &event { |
| 2918 | EngineEvent::AgentSpawned { |
| 2919 | owner_session_id, .. |
| 2920 | } |
| 2921 | | EngineEvent::AgentProgress { |
| 2922 | owner_session_id, .. |
| 2923 | } |
| 2924 | | EngineEvent::AgentComplete { |
| 2925 | owner_session_id, .. |
| 2926 | } => event_owner_is_active(app.current_session_id.as_deref(), owner_session_id), |
| 2927 | EngineEvent::ApprovalRequired { |
| 2928 | tool_name, |
| 2929 | approval_grouping_key, |
| 2930 | approval_key, |
| 2931 | approval_force_prompt, |
| 2932 | .. |
| 2933 | } => { |
| 2934 | matches!( |
| 2935 | resolve_ui_approval_disposition( |
| 2936 | app, |
| 2937 | tool_name, |
| 2938 | approval_grouping_key, |
| 2939 | approval_key, |
| 2940 | *approval_force_prompt |
| 2941 | ), |
| 2942 | codewhale_engine::core::authority::ApprovalRequestDisposition::Prompt |
| 2943 | ) |
| 2944 | } |
| 2945 | _ => true, |
| 2946 | }; |
| 2947 | if pet_event_applies { |
| 2948 | crate::tui::pet_watch::observe(app, &event); |
| 2949 | } |
| 2950 | record_turn_activity(app, &event, Instant::now()); |
| 2951 | let turn_end_lifecycle = TurnEndLifecycleReceipt::capture(&event); |
| 2952 | let active_agent_lifecycle_event = observe_terminal_agent_lifecycle_event( |
| 2953 | app.current_session_id.as_deref(), |
| 2954 | &event, |
| 2955 | ); |
| 2956 | match event { |
| 2957 | EngineEvent::MessageStarted { .. } => { |
| 2958 | // #7123: deliver a live reasoning block's tail BEFORE |
| 2959 | // `flush_active_cell`, which clears |
| 2960 | // `streaming_thinking_active_entry` on every path |
| 2961 | // (`App::flush_active_cell`). It only marks the cell |
| 2962 | // finished; a delta that never reached it is not |
| 2963 | // delivered by the flush, so draining afterwards would |
| 2964 | // be dead code and the tail would be lost by the reset |
| 2965 | // below. |
| 2966 | if app.streaming_thinking_active_entry.is_some() { |
| 2967 | if streaming_thinking::finalize_current(app) { |
| 2968 | transcript_batch_updated = true; |
| 2969 | } |
| 2970 | streaming_thinking::stash_reasoning_buffer_into_last_reasoning(app); |
| 2971 | } |
| 2972 | // Assistant text starting after parallel tool work |
| 2973 | // means the tool group is done. Flush the active |
| 2974 | // cell first so the message lands BELOW the |
| 2975 | // committed tool group (Codex pattern: streamed |
| 2976 | // assistant content always flows after work). |
| 2977 | app.flush_active_cell(); |
| 2978 | current_streaming_text.clear(); |
| 2979 | app.streaming_output_token_estimate = 0; |
| 2980 | app.streaming_state.reset(); |
| 2981 | app.streaming_state.start_text(0); |
| 2982 | app.streaming_message_index = None; |
| 2983 | stream_display_clock.reset(); |
| 2984 | } |
| 2985 | EngineEvent::MessageDelta { content, .. } => { |
| 2986 | let sanitized = sanitize_stream_chunk(&content); |
| 2987 | if sanitized.is_empty() { |
| 2988 | continue; |
| 2989 | } |
| 2990 | // A gateway can open a text block inside a |
| 2991 | // thinking stream; a live reasoning tail must reach |
| 2992 | // its card before this block is relabeled text. |
| 2993 | streaming_thinking::resync_block_kind(app, false); |
| 2994 | // First delta of a fresh stream has no streaming |
| 2995 | // cell yet; flush active so the tool group settles |
| 2996 | // before the assistant prose appears below it. |
| 2997 | if app.streaming_message_index.is_none() { |
| 2998 | app.flush_active_cell(); |
| 2999 | } |
| 3000 | current_streaming_text.push_str(&sanitized); |
| 3001 | ensure_streaming_assistant_history_cell(app); |
| 3002 | app.streaming_state.push_content(0, &sanitized); |
| 3003 | stream_display_clock.note_delta(Instant::now()); |
| 3004 | received_engine_event = redraw_requested_before_event; |
| 3005 | } |
| 3006 | EngineEvent::MessageComplete { .. } => { |
| 3007 | // #861 RC3: defensive drain of a still-active thinking |
| 3008 | // entry. Normally `ThinkingComplete` arrives first and |
| 3009 | // populates `last_reasoning` before we get here, but |
| 3010 | // when the engine bursts events the channel can |
| 3011 | // deliver `MessageComplete` first, in which case |
| 3012 | // `last_reasoning.take()` below would be `None` and |
| 3013 | // the thinking block would be dropped from |
| 3014 | // `api_messages` — causing a DeepSeek HTTP 400 on the |
| 3015 | // next turn (V4 thinking-mode requires |
| 3016 | // `reasoning_content` replay). Inline-finalize the |
| 3017 | // thinking entry here so this branch is order- |
| 3018 | // independent. |
| 3019 | if app.streaming_thinking_active_entry.is_some() { |
| 3020 | if streaming_thinking::finalize_current(app) { |
| 3021 | transcript_batch_updated = true; |
| 3022 | } |
| 3023 | streaming_thinking::stash_reasoning_buffer_into_last_reasoning(app); |
| 3024 | } |
| 3025 | let mut completed_message_index = None; |
| 3026 | if let Some(index) = app.streaming_message_index.take() { |
| 3027 | completed_message_index = Some(index); |
| 3028 | stream_display_clock.flush_now(Instant::now()); |
| 3029 | let remaining = drain_text_block(&mut app.streaming_state); |
| 3030 | if !remaining.is_empty() { |
| 3031 | append_streaming_text(app, index, &remaining); |
| 3032 | accrue_streaming_token_estimate(app, &remaining); |
| 3033 | } |
| 3034 | if let Some(HistoryCell::Assistant { streaming, .. }) = |
| 3035 | app.history.get_mut(index) |
| 3036 | { |
| 3037 | *streaming = false; |
| 3038 | } |
| 3039 | // Streaming flag flipped — the cell's compact / |
| 3040 | // transcript variants render slightly |
| 3041 | // differently, so bump its revision so the cache |
| 3042 | // refreshes this row only. |
| 3043 | app.bump_history_cell(index); |
| 3044 | transcript_batch_updated = true; |
| 3045 | stream_display_clock.reset(); |
| 3046 | } |
| 3047 | |
| 3048 | let thinking = app.last_reasoning.take(); |
| 3049 | let tool_uses = std::mem::take(&mut app.pending_tool_uses); |
| 3050 | let history_index = completed_message_index; |
| 3051 | if let Some(index) = history_index { |
| 3052 | app.record_completed_assistant_output(index, ¤t_streaming_text); |
| 3053 | } |
| 3054 | |
| 3055 | if app.translation_enabled |
| 3056 | && !current_streaming_text.is_empty() |
| 3057 | && codewhale_tui_kit::translation::needs_translation( |
| 3058 | ¤t_streaming_text, |
| 3059 | ) |
| 3060 | && let Some(translation_client) = active_translation_client.as_ref() |
| 3061 | { |
| 3062 | app.show_event_notice( |
| 3063 | codewhale_localization::tr( |
| 3064 | app.ui_locale, |
| 3065 | codewhale_localization::MessageId::TranslationInProgress, |
| 3066 | ) |
| 3067 | .to_string(), |
| 3068 | StatusToastLevel::Info, |
| 3069 | ); |
| 3070 | app.is_loading = true; |
| 3071 | pending_translations = pending_translations.saturating_add(1); |
| 3072 | let tx = translation_tx.clone(); |
| 3073 | let client = translation_client.clone(); |
| 3074 | let original_text = current_streaming_text.clone(); |
| 3075 | let translation_model = active_translation_route |
| 3076 | .as_ref() |
| 3077 | .map(|route| route.model.clone()) |
| 3078 | .or_else(|| app.last_effective_model.clone()) |
| 3079 | .unwrap_or_else(|| app.model.clone()); |
| 3080 | translation_sequence = translation_sequence.saturating_add(1); |
| 3081 | let accounting = TranslationAccountingContext::capture( |
| 3082 | app, |
| 3083 | "assistant", |
| 3084 | translation_sequence, |
| 3085 | ); |
| 3086 | let (origin_session_fingerprint, origin_turn_fingerprint) = |
| 3087 | translation_origin(app); |
| 3088 | let target_language = |
| 3089 | app.ui_locale.translation_target_name().to_string(); |
| 3090 | tokio::spawn(async move { |
| 3091 | let response = client |
| 3092 | .translate_with_usage( |
| 3093 | &original_text, |
| 3094 | &translation_model, |
| 3095 | &target_language, |
| 3096 | &accounting.source, |
| 3097 | ) |
| 3098 | .await; |
| 3099 | let settled = accounting.settle(response); |
| 3100 | let _ = tx.send(TranslationEvent::AssistantMessage { |
| 3101 | origin_session_fingerprint, |
| 3102 | origin_turn_fingerprint, |
| 3103 | history_index, |
| 3104 | original_text, |
| 3105 | translated: settled.translated, |
| 3106 | usage: settled.usage, |
| 3107 | thinking, |
| 3108 | tool_uses, |
| 3109 | }); |
| 3110 | }); |
| 3111 | } else { |
| 3112 | push_assistant_message( |
| 3113 | app, |
| 3114 | current_streaming_text.clone(), |
| 3115 | thinking, |
| 3116 | tool_uses, |
| 3117 | ); |
| 3118 | } |
| 3119 | } |
| 3120 | EngineEvent::ThinkingStarted { .. } => { |
| 3121 | stream_display_clock.reset(); |
| 3122 | // P2.3: thinking lives in the active cell so it groups |
| 3123 | // visually with the tool calls that follow until the |
| 3124 | // next assistant prose chunk flushes the group. |
| 3125 | if streaming_thinking::start_block(app) { |
| 3126 | transcript_batch_updated = true; |
| 3127 | } |
| 3128 | if app.translation_enabled { |
| 3129 | let entry_idx = streaming_thinking::ensure_active_entry(app); |
| 3130 | streaming_thinking::set_placeholder(app, entry_idx); |
| 3131 | transcript_batch_updated = true; |
| 3132 | } |
| 3133 | } |
| 3134 | EngineEvent::ThinkingDelta { content, .. } => { |
| 3135 | let sanitized = sanitize_stream_chunk(&content); |
| 3136 | if sanitized.is_empty() { |
| 3137 | continue; |
| 3138 | } |
| 3139 | // The kind comes from the start event alone, so a |
| 3140 | // gateway that opened a text block mid-reasoning |
| 3141 | // leaves block 0 marked text (#7123). |
| 3142 | streaming_thinking::resync_block_kind(app, true); |
| 3143 | // #7454: split before recording the delta. The split |
| 3144 | // writes the settled card's text from `reasoning_buffer`, |
| 3145 | // so a delta recorded first would be attributed to the |
| 3146 | // card above the tool and the new card would start empty. |
| 3147 | streaming_thinking::ensure_active_entry(app); |
| 3148 | app.reasoning_buffer.push_str(&sanitized); |
| 3149 | if app.reasoning_header.is_none() { |
| 3150 | app.reasoning_header = extract_reasoning_header(&app.reasoning_buffer); |
| 3151 | } |
| 3152 | app.streaming_state.push_content(0, &sanitized); |
| 3153 | stream_display_clock.note_delta(Instant::now()); |
| 3154 | received_engine_event = redraw_requested_before_event; |
| 3155 | } |
| 3156 | EngineEvent::ThinkingComplete { .. } => { |
| 3157 | stream_display_clock.flush_now(Instant::now()); |
| 3158 | if app.translation_enabled { |
| 3159 | let cell_index = app |
| 3160 | .streaming_thinking_active_entry |
| 3161 | .map(|entry_idx| app.history.len() + entry_idx); |
| 3162 | let original_thinking = app.reasoning_buffer.clone(); |
| 3163 | // #7123: only the reasoning block may be drained |
| 3164 | // here. A text block that lost its boundary event |
| 3165 | // would otherwise be consumed and dropped. |
| 3166 | if app.streaming_state.block_is_thinking(0) { |
| 3167 | let _ = app.streaming_state.finalize_block_text(0); |
| 3168 | } |
| 3169 | let duration = app |
| 3170 | .thinking_started_at |
| 3171 | .take() |
| 3172 | .map(|t| t.elapsed().as_secs_f32()); |
| 3173 | if streaming_thinking::finalize_active_entry(app, duration, "") { |
| 3174 | transcript_batch_updated = true; |
| 3175 | } |
| 3176 | if !original_thinking.is_empty() |
| 3177 | && codewhale_tui_kit::translation::needs_translation( |
| 3178 | &original_thinking, |
| 3179 | ) |
| 3180 | && let Some(translation_client) = active_translation_client.as_ref() |
| 3181 | && let Some(cell_index) = cell_index |
| 3182 | { |
| 3183 | app.show_event_notice( |
| 3184 | codewhale_localization::thinking_translation_in_progress( |
| 3185 | app.ui_locale, |
| 3186 | ) |
| 3187 | .to_string(), |
| 3188 | StatusToastLevel::Info, |
| 3189 | ); |
| 3190 | app.is_loading = true; |
| 3191 | pending_translations = pending_translations.saturating_add(1); |
| 3192 | pending_thinking_translations = |
| 3193 | pending_thinking_translations.saturating_add(1); |
| 3194 | let tx = translation_tx.clone(); |
| 3195 | let client = translation_client.clone(); |
| 3196 | let translation_model = active_translation_route |
| 3197 | .as_ref() |
| 3198 | .map(|route| route.model.clone()) |
| 3199 | .or_else(|| app.last_effective_model.clone()) |
| 3200 | .unwrap_or_else(|| app.model.clone()); |
| 3201 | translation_sequence = translation_sequence.saturating_add(1); |
| 3202 | let accounting = TranslationAccountingContext::capture( |
| 3203 | app, |
| 3204 | "thinking", |
| 3205 | translation_sequence, |
| 3206 | ); |
| 3207 | let translation_id = translation_sequence; |
| 3208 | app.pending_thinking_translation_cells |
| 3209 | .insert(translation_id, cell_index); |
| 3210 | let (origin_session_fingerprint, origin_turn_fingerprint) = |
| 3211 | translation_origin(app); |
| 3212 | let target_language = |
| 3213 | app.ui_locale.translation_target_name().to_string(); |
| 3214 | tokio::spawn(async move { |
| 3215 | let response = client |
| 3216 | .translate_with_usage( |
| 3217 | &original_thinking, |
| 3218 | &translation_model, |
| 3219 | &target_language, |
| 3220 | &accounting.source, |
| 3221 | ) |
| 3222 | .await; |
| 3223 | let settled = accounting.settle(response); |
| 3224 | let _ = tx.send(TranslationEvent::Thinking { |
| 3225 | origin_session_fingerprint, |
| 3226 | origin_turn_fingerprint, |
| 3227 | translation_id, |
| 3228 | translated: settled.translated, |
| 3229 | usage: settled.usage, |
| 3230 | }); |
| 3231 | }); |
| 3232 | } else if let Some(cell_index) = cell_index { |
| 3233 | streaming_thinking::replace_pending_translation( |
| 3234 | app, |
| 3235 | cell_index, |
| 3236 | original_thinking, |
| 3237 | ); |
| 3238 | } |
| 3239 | } else if streaming_thinking::finalize_current(app) { |
| 3240 | transcript_batch_updated = true; |
| 3241 | } |
| 3242 | streaming_thinking::stash_reasoning_buffer_into_last_reasoning(app); |
| 3243 | stream_display_clock.reset(); |
| 3244 | } |
| 3245 | EngineEvent::ToolCallStarted { |
| 3246 | id, |
| 3247 | name, |
| 3248 | input, |
| 3249 | model_call, |
| 3250 | } => { |
| 3251 | if let Some(model_call) = model_call { |
| 3252 | app.pending_tool_uses.push(ContentBlock::ToolUse { |
| 3253 | id: model_call.provider_id, |
| 3254 | execution_id: Some(id.clone()), |
| 3255 | name: name.clone(), |
| 3256 | input: input.clone(), |
| 3257 | caller: model_call.caller, |
| 3258 | thought_signature: model_call.thought_signature, |
| 3259 | }); |
| 3260 | } |
| 3261 | // Note this dispatch so the next sub-agent `Started` |
| 3262 | // mailbox envelope routes into the right card kind |
| 3263 | // (delegate vs fanout). |
| 3264 | if matches!( |
| 3265 | name.as_str(), |
| 3266 | "agent" | "rlm_open" | "rlm_eval" | "rlm" | "delegate" |
| 3267 | ) { |
| 3268 | app.pending_subagent_dispatch = Some(name.clone()); |
| 3269 | if matches!(name.as_str(), "rlm_open" | "rlm_eval" | "rlm") { |
| 3270 | // New fanout invocation — children should |
| 3271 | // group under a fresh card, not the |
| 3272 | // previous fanout's leftover. |
| 3273 | app.last_fanout_card_index = None; |
| 3274 | } |
| 3275 | } |
| 3276 | handle_tool_call_started(app, &id, &name, &input); |
| 3277 | } |
| 3278 | EngineEvent::ToolExecutionStarted { id } => { |
| 3279 | app.session_metrics.record_tool_started(&id); |
| 3280 | crate::tui::tool_routing::handle_tool_execution_started(app, &id); |
| 3281 | } |
| 3282 | EngineEvent::ToolResultContent { .. } => {} |
| 3283 | EngineEvent::ToolCallHeartbeat => {} |
| 3284 | // Typed owner activity is a pet-facing projection; |
| 3285 | // `pet_watch::observe` above already consumed it. The |
| 3286 | // transcript renders from the ToolCall* events, except |
| 3287 | // that a start updates a running execute_tools card's |
| 3288 | // active inner call. |
| 3289 | EngineEvent::OperationActivityStarted { |
| 3290 | span_id, action_id, .. |
| 3291 | } => { |
| 3292 | if let Some((call_id, _)) = span_id.rsplit_once('#') |
| 3293 | && let Some(action_id) = action_id.as_deref() |
| 3294 | { |
| 3295 | crate::tui::tool_routing::record_execute_tools_nested_call( |
| 3296 | app, call_id, action_id, |
| 3297 | ); |
| 3298 | } |
| 3299 | } |
| 3300 | EngineEvent::OperationActivityCompleted { .. } => {} |
| 3301 | EngineEvent::ToolCallComplete { |
| 3302 | id, |
| 3303 | name, |
| 3304 | result, |
| 3305 | model_call, |
| 3306 | } => { |
| 3307 | if crate::tui::tool_routing::evidence_completion_should_be_ignored( |
| 3308 | app, &id, &result, |
| 3309 | ) { |
| 3310 | tracing::debug!(tool_id = %id, tool_name = %name, "ignored foreign or replayed evidence completion"); |
| 3311 | continue; |
| 3312 | } |
| 3313 | app.session_metrics.record_tool_completed(&id); |
| 3314 | if let Some(model_call) = model_call { |
| 3315 | let tool_content = match &result { |
| 3316 | Ok(output) => sanitize_stream_chunk( |
| 3317 | &tool_result_content_for_api_message(app, &name, output), |
| 3318 | ), |
| 3319 | Err(err) => sanitize_stream_chunk(&format!("Error: {err}")), |
| 3320 | }; |
| 3321 | app.push_api_message(Message { |
| 3322 | role: Role::User, |
| 3323 | content: vec![ContentBlock::ToolResult { |
| 3324 | execution_id: Some(id.clone()), |
| 3325 | tool_use_id: model_call.provider_id, |
| 3326 | content: tool_content, |
| 3327 | is_error: Some(provisional_tool_result_is_error(&result)), |
| 3328 | content_blocks: None, |
| 3329 | }], |
| 3330 | }); |
| 3331 | } else { |
| 3332 | app.pending_tool_uses.retain(|block| { |
| 3333 | block.tool_call_key() |
| 3334 | != Some(codewhale_models::ToolCallKey::Execution(&id)) |
| 3335 | }); |
| 3336 | } |
| 3337 | handle_tool_call_complete(app, &id, &name, &result); |
| 3338 | if name |
| 3339 | == codewhale_engine::tools::request_plugin_install::REQUEST_PLUGIN_INSTALL_TOOL_NAME |
| 3340 | && let Ok(output) = &result |
| 3341 | && output.success |
| 3342 | && let Some(meta) = output.metadata.as_ref() |
| 3343 | { |
| 3344 | let plugin = meta |
| 3345 | .get("plugin") |
| 3346 | .and_then(serde_json::Value::as_str) |
| 3347 | .unwrap_or(""); |
| 3348 | let command = meta |
| 3349 | .get("command") |
| 3350 | .and_then(serde_json::Value::as_str) |
| 3351 | .unwrap_or(""); |
| 3352 | app.surface_plugin_review_request(plugin, command); |
| 3353 | } |
| 3354 | if flush_gate_receipts_for(app, Some(&id)) { |
| 3355 | transcript_batch_updated = true; |
| 3356 | } |
| 3357 | if codewhale_engine::mcp::McpPool::is_mcp_tool(&name) |
| 3358 | && match &result { |
| 3359 | Ok(output) => !output.success, |
| 3360 | Err(_) => true, |
| 3361 | } |
| 3362 | { |
| 3363 | let _ = app.maybe_show_behavioral_tip( |
| 3364 | crate::tui::behavioral_tips::BehavioralTip::McpValidation, |
| 3365 | ); |
| 3366 | } |
| 3367 | |
| 3368 | // Every `remember` action mutates durable memory, so a |
| 3369 | // successful call is the moment the first-run tip |
| 3370 | // points at /memory (one-shot per session, lifetime-capped). |
| 3371 | if name == "remember" && matches!(&result, Ok(output) if output.success) { |
| 3372 | let _ = app.maybe_show_behavioral_tip( |
| 3373 | crate::tui::behavioral_tips::BehavioralTip::DurableStateWritten, |
| 3374 | ); |
| 3375 | } |
| 3376 | |
| 3377 | if result.is_ok() |
| 3378 | && is_work_graph_mutation_tool(&name) |
| 3379 | && let Err(err) = persist_pending_work_checkpoint(app).await |
| 3380 | { |
| 3381 | tracing::warn!( |
| 3382 | tool = %name, |
| 3383 | error = %err, |
| 3384 | "Work Graph checkpoint did not complete; projections remain unpublished" |
| 3385 | ); |
| 3386 | app.push_status_toast( |
| 3387 | format!( |
| 3388 | "To-do list update pending: checkpoint or Work update did not complete ({err})" |
| 3389 | ), |
| 3390 | StatusToastLevel::Error, |
| 3391 | Some(12_000), |
| 3392 | ); |
| 3393 | } |
| 3394 | |
| 3395 | // Immediately refresh the task panel sidebar when a |
| 3396 | // tool that changes task state completes, so the |
| 3397 | // Tasks panel stays in sync with tool execution |
| 3398 | // rather than waiting up to 2.5 s for the periodic |
| 3399 | // poll. Also merge shell jobs (#373). |
| 3400 | // Only tools that actually change durable tasks or |
| 3401 | // background shell jobs force a jobs-panel refresh. |
| 3402 | // Checklist/todo/plan tools drive the To-do panel, |
| 3403 | // which reads `app.todos` directly and repaints on the |
| 3404 | // normal redraw — no forced refresh needed (avoids the |
| 3405 | // old per-checklist Tasks-panel churn). |
| 3406 | if matches!( |
| 3407 | name.as_str(), |
| 3408 | "agent" |
| 3409 | | "task_shell_start" |
| 3410 | | "exec_shell" |
| 3411 | | "exec_shell_cancel" |
| 3412 | | "exec_shell_wait" |
| 3413 | | "task_cancel" |
| 3414 | // Unified durable-task tool (piagent phase B): |
| 3415 | // create/cancel actions mutate task state, so |
| 3416 | // any `tasks` completion refreshes the panel. |
| 3417 | | "tasks" |
| 3418 | ) { |
| 3419 | refresh_active_task_panel(app).await; |
| 3420 | last_task_refresh = Instant::now(); |
| 3421 | } |
| 3422 | if matches!(name.as_str(), "agent") { |
| 3423 | subagent_list_refresh_requested = true; |
| 3424 | } |
| 3425 | } |
| 3426 | EngineEvent::TurnStarted { turn_id, route, .. } => { |
| 3427 | app.prune_settled_workflow_runs(); |
| 3428 | // A prior turn that died without its `TurnComplete` |
| 3429 | // must not leak its provisional estimate into this one. |
| 3430 | app.clear_pending_turn_cost(); |
| 3431 | // A Deny is scoped to the turn it answered (UX-8). |
| 3432 | end_turn_scoped_denials(app); |
| 3433 | app.goal_continuation_waiting = false; |
| 3434 | app.session.last_tool_request_snapshot = None; |
| 3435 | app.ocean_completion_started_at = None; |
| 3436 | app.ocean_receipt_settle_start = None; |
| 3437 | app.ocean_turn_history_start = app.history.len(); |
| 3438 | app.pending_plan_handoff = None; |
| 3439 | app.suppress_stream_events_until_turn_complete = false; |
| 3440 | app.is_loading = true; |
| 3441 | app.offline_mode = false; |
| 3442 | app.turn_error_posted = false; |
| 3443 | app.turn_error_notice = None; |
| 3444 | app.turn_error_cause = None; |
| 3445 | app.lsp_repair = crate::tui::app::LspRepairState::default(); |
| 3446 | app.prompt_suggestion = None; |
| 3447 | app.prompt_suggestion_gen |
| 3448 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3449 | app.dispatch_started_at = None; |
| 3450 | current_streaming_text.clear(); |
| 3451 | app.streaming_output_token_estimate = 0; |
| 3452 | app.streaming_state.reset(); |
| 3453 | app.streaming_message_index = None; |
| 3454 | app.streaming_thinking_active_entry = None; |
| 3455 | stream_display_clock.reset(); |
| 3456 | let now = Instant::now(); |
| 3457 | app.turn_started_at = Some(now); |
| 3458 | app.turn_last_activity_at = Some(now); |
| 3459 | app.retire_event_notices(STARTUP_NOTICE_TOAST); |
| 3460 | app.session.clear_pending_turn_usage(); |
| 3461 | app.streaming_output_token_estimate = 0; |
| 3462 | app.provider_wait_incident_logged = false; |
| 3463 | active_translation_client = match route.as_ref() { |
| 3464 | Some(route) => match exact_translation_client(config, route).await { |
| 3465 | Ok(client) => Some(client), |
| 3466 | Err(error) => { |
| 3467 | tracing::warn!( |
| 3468 | "translation client rejected the frozen turn route: {error}" |
| 3469 | ); |
| 3470 | None |
| 3471 | } |
| 3472 | }, |
| 3473 | None => fallback_translation_client.clone(), |
| 3474 | }; |
| 3475 | active_translation_route = route; |
| 3476 | app.runtime_turn_id = Some(turn_id); |
| 3477 | app.runtime_turn_status = Some("in_progress".to_string()); |
| 3478 | app.turn_counter = app.turn_counter.saturating_add(1); |
| 3479 | app.reasoning_buffer.clear(); |
| 3480 | app.reasoning_header = None; |
| 3481 | app.last_reasoning = None; |
| 3482 | app.pending_tool_uses.clear(); |
| 3483 | last_status_frame = Instant::now(); |
| 3484 | // Lifecycle outbox (`[lifecycle_outbox]`): the turn |
| 3485 | // boundary the shell-hook system deliberately lacks. |
| 3486 | // No-op when the feature is disabled. |
| 3487 | app.lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 3488 | event: "turn_start".to_string(), |
| 3489 | kind: "turn.started".to_string(), |
| 3490 | thread_id: app.hooks.session_id().to_string(), |
| 3491 | turn_id: app.runtime_turn_id.clone(), |
| 3492 | item_id: None, |
| 3493 | payload: serde_json::json!({ |
| 3494 | "model": codewhale_hooks::bounded_text( |
| 3495 | &app.model, |
| 3496 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 3497 | ), |
| 3498 | "workspace": app.workspace.display().to_string(), |
| 3499 | }), |
| 3500 | }); |
| 3501 | } |
| 3502 | EngineEvent::ToolRequestSnapshot { snapshot } => { |
| 3503 | app.session.last_tool_request_snapshot = Some(snapshot); |
| 3504 | } |
| 3505 | // Runtime-API hosts record restore-point receipts on their |
| 3506 | // turn records; the TUI's `/undo` resolves its own session's |
| 3507 | // snapshots from the store. |
| 3508 | EngineEvent::WorkspaceSnapshotTaken { .. } => {} |
| 3509 | EngineEvent::RouteDispatched { turn_id, route } => { |
| 3510 | if app.runtime_turn_id.as_deref() == Some(turn_id.as_str()) { |
| 3511 | active_translation_client = match exact_translation_client( |
| 3512 | config, &route, |
| 3513 | ) |
| 3514 | .await |
| 3515 | { |
| 3516 | Ok(client) => Some(client), |
| 3517 | Err(error) => { |
| 3518 | tracing::warn!( |
| 3519 | "translation client rejected the dispatched turn route: {error}" |
| 3520 | ); |
| 3521 | None |
| 3522 | } |
| 3523 | }; |
| 3524 | active_translation_route = Some(route); |
| 3525 | } |
| 3526 | } |
| 3527 | EngineEvent::TurnComplete { |
| 3528 | turn_id, |
| 3529 | submission_id, |
| 3530 | compaction_id, |
| 3531 | usage, |
| 3532 | parent_route_usage, |
| 3533 | source_accounting, |
| 3534 | routed_usage_dropped_records, |
| 3535 | status, |
| 3536 | error, |
| 3537 | tool_catalog, |
| 3538 | base_url, |
| 3539 | .. |
| 3540 | } => { |
| 3541 | let terminal_source = |
| 3542 | codewhale_engine::core::ops::SessionSnapshotSource::terminal( |
| 3543 | turn_id.clone(), |
| 3544 | submission_id.clone(), |
| 3545 | compaction_id.clone(), |
| 3546 | ); |
| 3547 | let terminal_owner_matches = |
| 3548 | terminal_source.as_ref().is_some_and(|source| { |
| 3549 | app.session_write_owner |
| 3550 | .as_ref() |
| 3551 | .is_some_and(|owner| owner.matches_source(source)) |
| 3552 | }); |
| 3553 | // A decision whose tool never reported completion |
| 3554 | // still gets its receipt before the turn closes. |
| 3555 | if flush_gate_receipts_for(app, None) { |
| 3556 | transcript_batch_updated = true; |
| 3557 | } |
| 3558 | // A steer the turn never accepted was dropped by the |
| 3559 | // engine. Report it instead of leaving it "sending" |
| 3560 | // (#6190). |
| 3561 | crate::tui::ui::dispatch::settle_unaccepted_steers_at_turn_end(app); |
| 3562 | let completed_turn = app.active_turn.take(); |
| 3563 | let newer_dispatch_owns_turn_state = |
| 3564 | app.suppress_stream_events_until_turn_complete && app.is_loading; |
| 3565 | if !newer_dispatch_owns_turn_state { |
| 3566 | app.unanswered_submission = None; |
| 3567 | } |
| 3568 | // The in-flight provisional estimate hands off to the |
| 3569 | // authoritative cumulative price accrued below; the |
| 3570 | // high-water mark keeps the displayed total monotonic |
| 3571 | // through the swap (#244). |
| 3572 | app.clear_pending_turn_cost(); |
| 3573 | app.session.clear_pending_turn_usage(); |
| 3574 | app.session.last_tool_catalog = tool_catalog; |
| 3575 | // The endpoint this turn's client actually used. Kept |
| 3576 | // separately from the mutable session/config surfaces |
| 3577 | // so the prompt-suggestion gate below can require it. |
| 3578 | let turn_actual_base_url = base_url.clone(); |
| 3579 | app.session.last_base_url = base_url; |
| 3580 | let was_locally_cancelled = app.suppress_stream_events_until_turn_complete; |
| 3581 | app.suppress_stream_events_until_turn_complete = false; |
| 3582 | app.active_allowed_tools = None; |
| 3583 | if app.paused_goal_objective.is_none() { |
| 3584 | app.pausable = false; |
| 3585 | app.paused = false; |
| 3586 | } |
| 3587 | // Turn completion is an ordinary state transition. |
| 3588 | // Clearing all 7,900 cells after a long stream was the |
| 3589 | // visible end-of-turn flash in the rejected build. |
| 3590 | // Ratatui's diff is sufficient here; full repaints stay |
| 3591 | // reserved for real terminal boundary changes (resize, |
| 3592 | // focus recovery, theme, child-terminal return). |
| 3593 | // Finalize any in-flight tool group. Cancellation |
| 3594 | // marks still-running entries as Failed so the user |
| 3595 | // sees they were interrupted rather than the spinner |
| 3596 | // hanging forever. |
| 3597 | if matches!( |
| 3598 | status, |
| 3599 | codewhale_engine::core::events::TurnOutcomeStatus::Interrupted |
| 3600 | | codewhale_engine::core::events::TurnOutcomeStatus::Failed |
| 3601 | ) { |
| 3602 | app.finalize_active_cell_as_interrupted(); |
| 3603 | // Also mark the streaming Assistant cell (if any) |
| 3604 | // so partial reasoning/text isn't left with a |
| 3605 | // permanent spinner. Idempotent with the |
| 3606 | // optimistic call in the Esc handler. |
| 3607 | app.finalize_streaming_assistant_as_interrupted(); |
| 3608 | } else { |
| 3609 | app.flush_active_cell(); |
| 3610 | } |
| 3611 | if !newer_dispatch_owns_turn_state { |
| 3612 | app.is_loading = false; |
| 3613 | app.dispatch_started_at = None; |
| 3614 | } |
| 3615 | app.pending_provider_switch = None; |
| 3616 | app.offline_mode = false; |
| 3617 | app.streaming_state.reset(); |
| 3618 | stream_display_clock.reset(); |
| 3619 | if was_locally_cancelled { |
| 3620 | current_streaming_text.clear(); |
| 3621 | } |
| 3622 | // Capture elapsed before clearing turn_started_at so |
| 3623 | // notifications can use the real wall-clock duration. |
| 3624 | let turn_elapsed = |
| 3625 | app.turn_started_at.map(|t| t.elapsed()).unwrap_or_default(); |
| 3626 | app.turn_started_at = None; |
| 3627 | let completed_user_index = if !newer_dispatch_owns_turn_state { |
| 3628 | app.active_turn_user_index.take() |
| 3629 | } else { |
| 3630 | None |
| 3631 | }; |
| 3632 | if !newer_dispatch_owns_turn_state |
| 3633 | && !turn_elapsed.is_zero() |
| 3634 | && let Some(user_index) = completed_user_index |
| 3635 | { |
| 3636 | app.turn_work_durations.insert(user_index, turn_elapsed); |
| 3637 | app.turn_durations_revision = |
| 3638 | app.turn_durations_revision.wrapping_add(1); |
| 3639 | } |
| 3640 | if status == codewhale_engine::core::events::TurnOutcomeStatus::Interrupted |
| 3641 | && !newer_dispatch_owns_turn_state |
| 3642 | { |
| 3643 | let worked = if turn_elapsed.is_zero() { |
| 3644 | completed_user_index |
| 3645 | .and_then(|index| app.turn_work_durations.get(&index).copied()) |
| 3646 | .unwrap_or_default() |
| 3647 | } else { |
| 3648 | turn_elapsed |
| 3649 | }; |
| 3650 | push_turn_interrupted_record(app, worked); |
| 3651 | } |
| 3652 | app.turn_last_activity_at = None; |
| 3653 | app.streaming_output_token_estimate = 0; |
| 3654 | // Roll the just-finished turn's elapsed time into the |
| 3655 | // cumulative session work-time (#448 follow-up). The |
| 3656 | // footer's `worked Nh Mm` chip reads this so the |
| 3657 | // label reflects actual model work, not idle |
| 3658 | // uptime since launch. |
| 3659 | app.cumulative_turn_duration = |
| 3660 | app.cumulative_turn_duration.saturating_add(turn_elapsed); |
| 3661 | // A turn that ended with tools still open (interrupt, |
| 3662 | // failure) must not carry their timers forward. |
| 3663 | app.session_metrics.clear_in_flight(); |
| 3664 | // Stream lock applies per-turn; clear it so the next |
| 3665 | // turn's chunks pull the view down again until the |
| 3666 | // user opts out by scrolling up. |
| 3667 | app.user_scrolled_during_stream = false; |
| 3668 | let turn_status_label = match status { |
| 3669 | codewhale_engine::core::events::TurnOutcomeStatus::Completed => { |
| 3670 | app.ocean_completion_started_at = Some(Instant::now()); |
| 3671 | app.ocean_receipt_settle_start = |
| 3672 | Some(app.ocean_turn_history_start.min(app.history.len())); |
| 3673 | "completed".to_string() |
| 3674 | } |
| 3675 | codewhale_engine::core::events::TurnOutcomeStatus::Interrupted => { |
| 3676 | app.ocean_completion_started_at = None; |
| 3677 | app.ocean_receipt_settle_start = None; |
| 3678 | "interrupted".to_string() |
| 3679 | } |
| 3680 | codewhale_engine::core::events::TurnOutcomeStatus::Failed => { |
| 3681 | app.ocean_completion_started_at = None; |
| 3682 | app.ocean_receipt_settle_start = None; |
| 3683 | "failed".to_string() |
| 3684 | } |
| 3685 | }; |
| 3686 | if !newer_dispatch_owns_turn_state { |
| 3687 | app.runtime_turn_status = Some(turn_status_label.clone()); |
| 3688 | } |
| 3689 | if matches!( |
| 3690 | status, |
| 3691 | codewhale_engine::core::events::TurnOutcomeStatus::Interrupted |
| 3692 | | codewhale_engine::core::events::TurnOutcomeStatus::Failed |
| 3693 | ) { |
| 3694 | subagent_list_refresh_requested = true; |
| 3695 | } |
| 3696 | // #6004: only a turn that *ended* failed is a session |
| 3697 | // error; transient tool failures the agent absorbed |
| 3698 | // never fire it. |
| 3699 | if matches!( |
| 3700 | status, |
| 3701 | codewhale_engine::core::events::TurnOutcomeStatus::Failed |
| 3702 | ) { |
| 3703 | execute_session_error_hook(app, error.as_deref()); |
| 3704 | } |
| 3705 | crate::tui::notifications::clear_taskbar_progress(); |
| 3706 | if status != codewhale_engine::core::events::TurnOutcomeStatus::Completed { |
| 3707 | codewhale_runtime::retry_status::clear(); |
| 3708 | crate::tui::notifications::stop_title_animation_quietly(); |
| 3709 | } |
| 3710 | if source_accounting { |
| 3711 | let pending = codewhale_engine::cost_status::drain(); |
| 3712 | app.absorb_pending_background_cost(&pending); |
| 3713 | } else { |
| 3714 | let turn_tokens = |
| 3715 | usage.input_tokens.saturating_add(usage.output_tokens); |
| 3716 | app.session.total_tokens = |
| 3717 | app.session.total_tokens.saturating_add(turn_tokens); |
| 3718 | app.session.total_conversation_tokens = app |
| 3719 | .session |
| 3720 | .total_conversation_tokens |
| 3721 | .saturating_add(turn_tokens); |
| 3722 | app.session.total_input_tokens = app |
| 3723 | .session |
| 3724 | .total_input_tokens |
| 3725 | .saturating_add(usage.input_tokens); |
| 3726 | app.session.total_output_tokens = app |
| 3727 | .session |
| 3728 | .total_output_tokens |
| 3729 | .saturating_add(usage.output_tokens); |
| 3730 | // Only accumulate cache telemetry when the provider |
| 3731 | // reported at least one cache class. Use pricing's |
| 3732 | // canonical mutually-exclusive hit/miss/write split so |
| 3733 | // cache writes are never counted again as misses. |
| 3734 | if usage.prompt_cache_hit_tokens.is_some() |
| 3735 | || usage.prompt_cache_miss_tokens.is_some() |
| 3736 | || usage.prompt_cache_write_tokens.is_some() |
| 3737 | { |
| 3738 | let classes = |
| 3739 | codewhale_engine::pricing::token_usage_for_pricing(&usage); |
| 3740 | let hit_tokens = |
| 3741 | u32::try_from(classes.cache_read).unwrap_or(u32::MAX); |
| 3742 | let miss_tokens = u32::try_from(classes.input).unwrap_or(u32::MAX); |
| 3743 | let write_tokens = |
| 3744 | u32::try_from(classes.cache_write).unwrap_or(u32::MAX); |
| 3745 | app.session.total_cache_hit_tokens = app |
| 3746 | .session |
| 3747 | .total_cache_hit_tokens |
| 3748 | .saturating_add(hit_tokens); |
| 3749 | app.session.total_cache_miss_tokens = app |
| 3750 | .session |
| 3751 | .total_cache_miss_tokens |
| 3752 | .saturating_add(miss_tokens); |
| 3753 | app.session.total_cache_write_tokens = app |
| 3754 | .session |
| 3755 | .total_cache_write_tokens |
| 3756 | .saturating_add(write_tokens); |
| 3757 | } |
| 3758 | } |
| 3759 | app.session.last_prompt_tokens = Some(usage.input_tokens); |
| 3760 | app.session.last_completion_tokens = Some(usage.output_tokens); |
| 3761 | app.session.last_prompt_cache_hit_tokens = usage.prompt_cache_hit_tokens; |
| 3762 | app.session.last_prompt_cache_miss_tokens = usage.prompt_cache_miss_tokens; |
| 3763 | app.session.last_reasoning_replay_tokens = usage.reasoning_replay_tokens; |
| 3764 | let (provider, provider_identity, model, auto_model) = completed_turn |
| 3765 | .as_ref() |
| 3766 | .and_then(|turn| turn.route.as_ref()) |
| 3767 | .map(|route| { |
| 3768 | ( |
| 3769 | Some(route.provider), |
| 3770 | Some(route.provider_identity.clone()), |
| 3771 | Some(route.model.clone()), |
| 3772 | route.auto_model, |
| 3773 | ) |
| 3774 | }) |
| 3775 | .unwrap_or((None, None, None, false)); |
| 3776 | let effective_turn_provider = provider.unwrap_or(app.api_provider); |
| 3777 | let effective_turn_model = model |
| 3778 | .as_deref() |
| 3779 | .filter(|model| !model.trim().is_empty()) |
| 3780 | .unwrap_or_else(|| { |
| 3781 | app.last_effective_model.as_deref().unwrap_or(&app.model) |
| 3782 | }) |
| 3783 | .to_string(); |
| 3784 | app.last_effective_provider = Some(effective_turn_provider); |
| 3785 | app.last_effective_provider_identity = provider_identity.clone(); |
| 3786 | if completed_turn |
| 3787 | .as_ref() |
| 3788 | .and_then(|turn| turn.route.as_ref()) |
| 3789 | .is_some_and(|route| route.auto_model) |
| 3790 | { |
| 3791 | app.last_auto_route_receipt = completed_turn |
| 3792 | .as_ref() |
| 3793 | .and_then(|turn| turn.auto_route_receipt.clone()); |
| 3794 | } else if completed_turn |
| 3795 | .as_ref() |
| 3796 | .is_some_and(|turn| turn.route.is_some()) |
| 3797 | { |
| 3798 | app.last_auto_route_receipt = None; |
| 3799 | } |
| 3800 | if status == codewhale_engine::core::events::TurnOutcomeStatus::Completed |
| 3801 | && let Some(receipt) = completed_turn |
| 3802 | .as_ref() |
| 3803 | .and_then(|turn| turn.route.as_ref()) |
| 3804 | .and_then(|route| route.receipt.as_ref()) |
| 3805 | && config |
| 3806 | .verify_provider_identity(receipt.admitted_identity()) |
| 3807 | .is_ok() |
| 3808 | && receipt.endpoint_identity() |
| 3809 | == codewhale_engine::route_receipt::endpoint_identity( |
| 3810 | &config.base_url_for_route(receipt.admitted_identity()), |
| 3811 | ) |
| 3812 | { |
| 3813 | app.provider_health.record_success( |
| 3814 | config, |
| 3815 | receipt, |
| 3816 | &effective_turn_model, |
| 3817 | ); |
| 3818 | } |
| 3819 | if auto_model { |
| 3820 | app.last_effective_model = Some(effective_turn_model.clone()); |
| 3821 | } |
| 3822 | // Price the turn exactly once. The same audit feeds the |
| 3823 | // session total, the `/cache` row, and the `/cost` |
| 3824 | // completeness counters, so those three surfaces can |
| 3825 | // never disagree about what was counted (#4318). |
| 3826 | let cost_audit = completed_turn |
| 3827 | .as_ref() |
| 3828 | .and_then(|turn| turn.route.as_ref()) |
| 3829 | .and_then(codewhale_engine::core::events::TurnRoute::cost_envelope) |
| 3830 | .filter(|_| { |
| 3831 | !source_accounting |
| 3832 | && parent_route_usage != codewhale_models::Usage::default() |
| 3833 | }) |
| 3834 | .map(|route| route.audit(&parent_route_usage)); |
| 3835 | app.push_turn_cache_record(crate::tui::app::TurnCacheRecord { |
| 3836 | provider, |
| 3837 | provider_identity, |
| 3838 | model, |
| 3839 | auto_model, |
| 3840 | input_tokens: parent_route_usage.input_tokens, |
| 3841 | output_tokens: parent_route_usage.output_tokens, |
| 3842 | cache_hit_tokens: parent_route_usage.prompt_cache_hit_tokens, |
| 3843 | cache_miss_tokens: parent_route_usage.prompt_cache_miss_tokens, |
| 3844 | reasoning_replay_tokens: parent_route_usage.reasoning_replay_tokens, |
| 3845 | cache_write_tokens: parent_route_usage.prompt_cache_write_tokens, |
| 3846 | reasoning_tokens: parent_route_usage.reasoning_tokens, |
| 3847 | cost_audit: cost_audit.clone(), |
| 3848 | recorded_at: Instant::now(), |
| 3849 | }); |
| 3850 | app.retire_action_notices(None); |
| 3851 | present_turn_failure(app, status, error.as_deref()); |
| 3852 | maybe_warn_context_pressure(app); |
| 3853 | |
| 3854 | // Update session cost, and record what the total does |
| 3855 | // *not* cover so `/cost` can stay honest about it. |
| 3856 | // |
| 3857 | // `cost_audit` above came from `cost_envelope()`, i.e. |
| 3858 | // the billing envelope frozen at CodeWhale's |
| 3859 | // pre-permit application-dispatch boundary and |
| 3860 | // classified from this turn's frozen receipt. It |
| 3861 | // is `None` for a route that was never dispatched, and |
| 3862 | // a route whose receipt named no product classified as |
| 3863 | // Unknown — either way nothing accrues. A `/provider` |
| 3864 | // or custom-table switch since dispatch cannot |
| 3865 | // retro-bill this turn onto another route, because no |
| 3866 | // ambient `Config` is read here at all. |
| 3867 | let turn_cost = cost_audit.as_ref().and_then(|audit| audit.estimate); |
| 3868 | if let Some(audit) = cost_audit.as_ref() { |
| 3869 | app.record_turn_cost_audit(audit); |
| 3870 | // Redacted receipt for the route this money came |
| 3871 | // from: provider identity, wire model, billing |
| 3872 | // surface, and the endpoint *fingerprint* — never the |
| 3873 | // URL or any credential. |
| 3874 | if let Some(receipt) = |
| 3875 | completed_turn_cost_route_receipt(completed_turn.as_ref(), audit) |
| 3876 | { |
| 3877 | app.record_turn_cost_route_receipt(receipt); |
| 3878 | } |
| 3879 | } |
| 3880 | if let Some(cost) = turn_cost { |
| 3881 | app.accrue_session_cost_estimate(cost); |
| 3882 | } |
| 3883 | if routed_usage_dropped_records > 0 { |
| 3884 | let dropped = |
| 3885 | u32::try_from(routed_usage_dropped_records).unwrap_or(u32::MAX); |
| 3886 | app.session.cost_unpriced_turns = |
| 3887 | app.session.cost_unpriced_turns.saturating_add(dropped); |
| 3888 | app.session.cost_cny_unpriced_turns = |
| 3889 | app.session.cost_cny_unpriced_turns.saturating_add(dropped); |
| 3890 | app.session |
| 3891 | .cost_unpriced_reasons |
| 3892 | .insert("routed_usage_receipt_missing".to_string()); |
| 3893 | app.session |
| 3894 | .cost_cny_unpriced_reasons |
| 3895 | .insert("routed_usage_receipt_missing".to_string()); |
| 3896 | } |
| 3897 | |
| 3898 | // The parent turn is idle now (#6565). |
| 3899 | settle_background_finished_at_turn_end( |
| 3900 | app, |
| 3901 | config, |
| 3902 | status == codewhale_engine::core::events::TurnOutcomeStatus::Completed, |
| 3903 | ); |
| 3904 | |
| 3905 | // Emit OSC 9 / BEL desktop notification for long turns, and |
| 3906 | // always stop the title animation that began on TurnStarted. |
| 3907 | if status == codewhale_engine::core::events::TurnOutcomeStatus::Completed { |
| 3908 | if let Some((method, threshold, include_summary)) = |
| 3909 | notifications::settings(config) |
| 3910 | { |
| 3911 | let in_tmux = std::env::var("TMUX").is_ok_and(|v| !v.is_empty()); |
| 3912 | let payload = notifications::completed_turn_payload( |
| 3913 | app, |
| 3914 | ¤t_streaming_text, |
| 3915 | include_summary, |
| 3916 | turn_elapsed, |
| 3917 | turn_cost, |
| 3918 | ); |
| 3919 | crate::tui::notifications::notify_done( |
| 3920 | method, |
| 3921 | in_tmux, |
| 3922 | &payload, |
| 3923 | threshold, |
| 3924 | turn_elapsed, |
| 3925 | ); |
| 3926 | crate::tui::notifications::stop_title_animation(); |
| 3927 | } else { |
| 3928 | crate::tui::notifications::stop_title_animation_quietly(); |
| 3929 | } |
| 3930 | } |
| 3931 | |
| 3932 | // Generate ghost-text follow-up suggestion asynchronously. |
| 3933 | // |
| 3934 | // Privacy (#4404/#4411): the request is anchored to the |
| 3935 | // completed turn's route snapshot and to the receipt the |
| 3936 | // engine minted from the client it installed for that |
| 3937 | // turn — never to live UI selection, and never to |
| 3938 | // authority re-derived from mutable config. |
| 3939 | // Conversation context is only ever sent to that exact |
| 3940 | // endpoint with that exact credential. Providers whose |
| 3941 | // wire shape this helper does not speak produce no |
| 3942 | // background request at all — and never reach another |
| 3943 | // provider's credentials while deciding that. |
| 3944 | let suggestion_launch = completed_turn |
| 3945 | .as_ref() |
| 3946 | .and_then(|turn| { |
| 3947 | let route = turn.route.as_ref()?; |
| 3948 | let authority = turn.suggestion_authority.as_ref()?; |
| 3949 | Some(crate::tui::prompt_suggestion::SuggestionRouteSnapshot { |
| 3950 | provider: route.provider, |
| 3951 | provider_identity: route.provider_identity.as_str(), |
| 3952 | model: route.model.as_str(), |
| 3953 | authority, |
| 3954 | actual_base_url: turn_actual_base_url.as_deref(), |
| 3955 | }) |
| 3956 | }) |
| 3957 | .and_then(|snapshot| { |
| 3958 | crate::tui::prompt_suggestion::plan_suggestion_launch_with_config( |
| 3959 | config, |
| 3960 | status == codewhale_engine::core::events::TurnOutcomeStatus::Completed, |
| 3961 | config.prompt_suggestion_enabled(), |
| 3962 | app.api_messages.len(), |
| 3963 | Some(snapshot), |
| 3964 | ) |
| 3965 | }); |
| 3966 | if let Some(launch) = suggestion_launch { |
| 3967 | let suggestion_cell = app.prompt_suggestion_cell.clone(); |
| 3968 | let messages: std::sync::Arc<Vec<codewhale_models::Message>> = |
| 3969 | app.api_messages.clone(); |
| 3970 | let gen_token = app |
| 3971 | .prompt_suggestion_gen |
| 3972 | .load(std::sync::atomic::Ordering::Relaxed); |
| 3973 | tokio::spawn(async move { |
| 3974 | let summary = |
| 3975 | crate::tui::prompt_suggestion::summarize_recent_messages( |
| 3976 | &messages, 8, |
| 3977 | ); |
| 3978 | if let Some(suggestion) = |
| 3979 | crate::tui::prompt_suggestion::generate_suggestion( |
| 3980 | &launch.api_key, |
| 3981 | &launch.base_url, |
| 3982 | &launch.model, |
| 3983 | &summary, |
| 3984 | launch.openrouter_vendor.as_deref(), |
| 3985 | ) |
| 3986 | .await |
| 3987 | && let Ok(mut guard) = suggestion_cell.lock() |
| 3988 | { |
| 3989 | *guard = Some((gen_token, suggestion)); |
| 3990 | } |
| 3991 | }); |
| 3992 | } |
| 3993 | |
| 3994 | // Generate post-turn receipt for completed turns. |
| 3995 | // Also push a persistent status toast so users always |
| 3996 | // see the outcome in the footer (not just the 8-second |
| 3997 | // composer receipt), regardless of notification method |
| 3998 | // or platform. |
| 3999 | if status == codewhale_engine::core::events::TurnOutcomeStatus::Completed { |
| 4000 | let tool_count = app.tool_evidence.len(); |
| 4001 | let mut receipt = "✓ turn completed".to_string(); |
| 4002 | if tool_count > 0 { |
| 4003 | let _ = write!(receipt, " · {tool_count} tool(s) used"); |
| 4004 | for evidence in &app.tool_evidence { |
| 4005 | let summary = codewhale_util::utils::truncate_with_ellipsis( |
| 4006 | &evidence.summary, |
| 4007 | 60, |
| 4008 | "…", |
| 4009 | ); |
| 4010 | let _ = write!(receipt, " · {}: {summary}", evidence.tool_name); |
| 4011 | } |
| 4012 | } |
| 4013 | app.set_receipt_text(receipt.clone()); |
| 4014 | // Mirror as a persistent status toast (10s TTL). |
| 4015 | // The footer bar visibly shows status toasts, |
| 4016 | // which is more glanceable than the composer |
| 4017 | // border receipt alone. |
| 4018 | app.push_status_toast( |
| 4019 | receipt, |
| 4020 | crate::tui::app::StatusToastLevel::Info, |
| 4021 | Some(10_000), |
| 4022 | ); |
| 4023 | } |
| 4024 | |
| 4025 | // Auto-save completed turn and clear crash checkpoint. |
| 4026 | // Offloaded to the persistence actor so the UI |
| 4027 | // stays responsive. |
| 4028 | let mut snapshot_error = None; |
| 4029 | let terminal_snapshot = if terminal_owner_matches |
| 4030 | && !newer_dispatch_owns_turn_state |
| 4031 | { |
| 4032 | let snapshot = match await_terminal_snapshot_with_timeout( |
| 4033 | TURN_COMPLETE_SNAPSHOT_WAIT, |
| 4034 | engine_handle.get_session_snapshot(), |
| 4035 | ) |
| 4036 | .await |
| 4037 | { |
| 4038 | Ok(snapshot) => Some(snapshot), |
| 4039 | Err(error) => { |
| 4040 | snapshot_error = Some(error.to_string()); |
| 4041 | None |
| 4042 | } |
| 4043 | }; |
| 4044 | let snapshot = snapshot.filter(|snapshot| { |
| 4045 | snapshot.source.as_ref() == terminal_source.as_ref() |
| 4046 | && app.session_write_owner.as_ref().is_some_and(|owner| { |
| 4047 | snapshot |
| 4048 | .source |
| 4049 | .as_ref() |
| 4050 | .is_some_and(|source| owner.matches_source(source)) |
| 4051 | }) |
| 4052 | && app.current_session_id.as_deref() |
| 4053 | == Some(snapshot.session_id.as_str()) |
| 4054 | && snapshot.workspace == app.workspace |
| 4055 | && snapshot.messages.as_slice() == app.api_messages.as_slice() |
| 4056 | }); |
| 4057 | if snapshot.is_none() && snapshot_error.is_none() { |
| 4058 | snapshot_error = Some( |
| 4059 | "Engine session snapshot no longer matches the active terminal session" |
| 4060 | .to_string(), |
| 4061 | ); |
| 4062 | } |
| 4063 | snapshot |
| 4064 | } else { |
| 4065 | None |
| 4066 | }; |
| 4067 | if terminal_owner_matches && terminal_snapshot.is_none() { |
| 4068 | let session_id = app.current_session_id.clone(); |
| 4069 | let error = snapshot_error.unwrap_or_else(|| { |
| 4070 | "Engine session snapshot was unavailable; checkpoint retained" |
| 4071 | .to_string() |
| 4072 | }); |
| 4073 | tracing::warn!( |
| 4074 | ?terminal_source, |
| 4075 | %error, |
| 4076 | "terminal session save skipped; checkpoint retained" |
| 4077 | ); |
| 4078 | if let Some(session_id) = session_id.as_deref() { |
| 4079 | crate::tui::persistence_actor::record_skipped_session_save( |
| 4080 | session_id, &error, |
| 4081 | ); |
| 4082 | } |
| 4083 | surface_session_save_failure(app, session_id.as_deref(), &error); |
| 4084 | } |
| 4085 | if terminal_snapshot.is_some() |
| 4086 | && let Ok(manager) = SessionManager::default_location() |
| 4087 | && let Ok(session) = build_session_snapshot(app, &manager) |
| 4088 | { |
| 4089 | let projection = saved_work_projection(app, &session); |
| 4090 | app.set_current_session_id(Some(session.metadata.id.clone())); |
| 4091 | // Compound completion commit: the actor writes the |
| 4092 | // completed snapshot and clears this session's |
| 4093 | // crash checkpoint only after that write succeeds. |
| 4094 | // A failed save now retains the checkpoint as the |
| 4095 | // sole recovery record instead of erasing it. |
| 4096 | let queued = super::session_state::try_persist_session( |
| 4097 | app, |
| 4098 | PersistRequest::CompletedCommit { session }, |
| 4099 | ); |
| 4100 | if queued { |
| 4101 | if let Err(err) = |
| 4102 | publish_saved_work_projection(app, &projection).await |
| 4103 | { |
| 4104 | tracing::warn!( |
| 4105 | error = %err, |
| 4106 | "completed-turn Work projections remain unpublished" |
| 4107 | ); |
| 4108 | app.show_event_notice(format!( |
| 4109 | "Session queued, but Work views could not publish ({err})" |
| 4110 | ), StatusToastLevel::Warning); |
| 4111 | } |
| 4112 | } else if app |
| 4113 | .runtime_services |
| 4114 | .work |
| 4115 | .as_ref() |
| 4116 | .is_some_and(|work| work.has_pending_publish()) |
| 4117 | { |
| 4118 | app.show_event_notice("To-do list update pending: session snapshot could not be queued" |
| 4119 | .to_string(), StatusToastLevel::Warning); |
| 4120 | } |
| 4121 | } |
| 4122 | // The checkpoint clear is owned by the compound |
| 4123 | // `CompletedCommit` above: it applies only after this |
| 4124 | // session's snapshot safely landed. When the snapshot |
| 4125 | // could not be built or queued, the in-flight |
| 4126 | // checkpoint survives for startup recovery review. |
| 4127 | |
| 4128 | // Refresh prepaid remaining credit after each completed |
| 4129 | // turn so the footer balance chip stays current without |
| 4130 | // adding latency to any request path. |
| 4131 | let api_key = config.active_route_api_key().unwrap_or_default(); |
| 4132 | let base_url = config.active_route_base_url(); |
| 4133 | schedule_balance_fetch(app, &api_key, &base_url, false); |
| 4134 | |
| 4135 | if let Err(error) = execute_turn_end_observer_hook( |
| 4136 | app, |
| 4137 | completed_turn.as_ref(), |
| 4138 | &usage, |
| 4139 | completed_turn |
| 4140 | .as_ref() |
| 4141 | .and_then(|turn| turn.route.as_ref()) |
| 4142 | .and_then(|route| route.billing.as_ref()) |
| 4143 | .and_then(|billing| billing.billing_surface.as_deref()), |
| 4144 | turn_elapsed, |
| 4145 | error.as_deref(), |
| 4146 | ) { |
| 4147 | surface_observer_hook_submission_failure(app, error); |
| 4148 | } |
| 4149 | |
| 4150 | // Lifecycle outbox (`[lifecycle_outbox]`): one |
| 4151 | // `turn_end` event per completed turn, with the kind |
| 4152 | // projected from the turn status — `turn.failed` for |
| 4153 | // failed turns, `turn.completed` for completed ones, |
| 4154 | // `turn.interrupted` for locally cancelled ones. |
| 4155 | // The receipt's turn identity comes from the terminal |
| 4156 | // event itself, never from the stale-surviving |
| 4157 | // `runtime_turn_id`: a preflight rejection or manual |
| 4158 | // compaction must not close the preceding model turn. |
| 4159 | // No-op when the feature is disabled. |
| 4160 | { |
| 4161 | let event = turn_end_lifecycle_event( |
| 4162 | app, |
| 4163 | turn_end_lifecycle |
| 4164 | .expect("TurnComplete must capture lifecycle data"), |
| 4165 | turn_elapsed, |
| 4166 | ); |
| 4167 | app.lifecycle_outbox.emit(event); |
| 4168 | } |
| 4169 | |
| 4170 | // Plan hand-off freezes this successful turn's exact |
| 4171 | // completed response, including prose-only plans. |
| 4172 | // Only on an idle screen — a modal that takes digit |
| 4173 | // keys must never land on a draft, a queued follow-up |
| 4174 | // or another open view, and the answer goes to this |
| 4175 | // session, not to a focused agent. |
| 4176 | if queued_to_send.is_none() |
| 4177 | && !newer_dispatch_owns_turn_state |
| 4178 | && !app.is_loading |
| 4179 | && !app.dispatch_in_flight |
| 4180 | && !app.remote_control.runtime_chat_blocks_local_dispatch() |
| 4181 | && app.queued_message_count() == 0 |
| 4182 | && app.queued_draft.is_none() |
| 4183 | && app.input.is_empty() |
| 4184 | && app.view_stack.is_empty() |
| 4185 | && app.agent_focus.is_none() |
| 4186 | { |
| 4187 | let todos = app.todos.lock().await.snapshot(); |
| 4188 | let has_open_todos = |
| 4189 | todos.items.iter().any(|item| !item.status.is_settled()); |
| 4190 | if !was_locally_cancelled |
| 4191 | && let Some(request_id) = app.prepare_plan_handoff( |
| 4192 | status, |
| 4193 | completed_turn.as_ref().map(|turn| turn.turn_id.as_str()), |
| 4194 | has_open_todos, |
| 4195 | ) |
| 4196 | { |
| 4197 | app.view_stack.push(UserInputView::new( |
| 4198 | request_id, |
| 4199 | crate::tui::plan_handoff::request(app.ui_locale), |
| 4200 | app.ui_locale, |
| 4201 | )); |
| 4202 | app.needs_redraw = true; |
| 4203 | } |
| 4204 | } |
| 4205 | |
| 4206 | if queued_to_send.is_none() && !newer_dispatch_owns_turn_state { |
| 4207 | queued_to_send = app.settle_queue_after_turn(status); |
| 4208 | } |
| 4209 | } |
| 4210 | EngineEvent::Error { |
| 4211 | envelope, |
| 4212 | recoverable: _, |
| 4213 | } => { |
| 4214 | let provider_before_error = app.api_provider; |
| 4215 | let identity_before_error = app.admitted_provider_identity().ok().cloned(); |
| 4216 | let fallback_chain_before_error = app.provider_chain.clone(); |
| 4217 | if let Some((identity, health_model)) = error_health_route(app) |
| 4218 | && config.verify_provider_identity(&identity).is_ok() |
| 4219 | && app |
| 4220 | .active_turn |
| 4221 | .as_ref() |
| 4222 | .and_then(|turn| turn.route.as_ref()) |
| 4223 | .and_then(|route| route.receipt.as_ref()) |
| 4224 | .is_some_and(|receipt| { |
| 4225 | receipt.endpoint_identity() |
| 4226 | == codewhale_engine::route_receipt::endpoint_identity( |
| 4227 | &config.base_url_for_route(&identity), |
| 4228 | ) |
| 4229 | }) |
| 4230 | { |
| 4231 | app.provider_health.record_failure( |
| 4232 | config, |
| 4233 | app.active_turn |
| 4234 | .as_ref() |
| 4235 | .and_then(|turn| turn.route.as_ref()) |
| 4236 | .and_then(|route| route.receipt.as_ref()) |
| 4237 | .expect("health route has captured receipt"), |
| 4238 | &health_model, |
| 4239 | &envelope, |
| 4240 | ); |
| 4241 | } |
| 4242 | let rollback_after_auth_failure = |
| 4243 | matches!( |
| 4244 | envelope.category, |
| 4245 | codewhale_error_taxonomy::ErrorCategory::Authentication |
| 4246 | ) && app.pending_provider_switch.is_some(); |
| 4247 | apply_engine_error_to_app(app, envelope); |
| 4248 | if app.api_provider != provider_before_error |
| 4249 | && app.is_fallback_active() |
| 4250 | && let Some(identity_before_error) = identity_before_error |
| 4251 | { |
| 4252 | // Several queued errors can be drained together. |
| 4253 | // The first route remains the rollback authority; |
| 4254 | // later chain advances must not overwrite it with |
| 4255 | // an enum/key pair from the half-applied fallback. |
| 4256 | fallback_after_engine_error.get_or_insert(ProviderFallbackRollback { |
| 4257 | identity: identity_before_error, |
| 4258 | chain: fallback_chain_before_error, |
| 4259 | }); |
| 4260 | } |
| 4261 | if rollback_after_auth_failure |
| 4262 | && let Some(rollback_warning) = |
| 4263 | rollback_provider_after_auth_failure(app, config) |
| 4264 | { |
| 4265 | respawn_after_provider_rollback = Some(rollback_warning); |
| 4266 | } |
| 4267 | } |
| 4268 | EngineEvent::Status { message } => { |
| 4269 | transcript_batch_updated |= apply_engine_status(app, message); |
| 4270 | } |
| 4271 | EngineEvent::ToolProjectionWarning { |
| 4272 | provider, |
| 4273 | omitted_tool_names, |
| 4274 | omitted_tool_count, |
| 4275 | } => { |
| 4276 | let message = format_helpers::tool_projection_warning( |
| 4277 | app.ui_locale, |
| 4278 | &provider, |
| 4279 | &omitted_tool_names, |
| 4280 | omitted_tool_count, |
| 4281 | ); |
| 4282 | app.push_status_toast(message, StatusToastLevel::Warning, Some(12_000)); |
| 4283 | } |
| 4284 | EngineEvent::RequestImageWindow { message, .. } => { |
| 4285 | app.push_status_toast(message, StatusToastLevel::Warning, Some(12_000)); |
| 4286 | } |
| 4287 | EngineEvent::SnapshotsDisabled { reason, .. } => { |
| 4288 | // The engine already rendered the one localized line; |
| 4289 | // show it once as a toast and leave the durable copy |
| 4290 | // to `/status` rather than pinning it in the |
| 4291 | // transcript too (#6042). |
| 4292 | app.push_status_toast(reason, StatusToastLevel::Warning, Some(12_000)); |
| 4293 | } |
| 4294 | EngineEvent::McpSessionBoot { |
| 4295 | generation, |
| 4296 | snapshot, |
| 4297 | connecting, |
| 4298 | finished, |
| 4299 | } => { |
| 4300 | apply_mcp_session_boot_event( |
| 4301 | app, generation, snapshot, connecting, finished, |
| 4302 | ); |
| 4303 | } |
| 4304 | EngineEvent::RequestManifestReady { rendered } => { |
| 4305 | // Typed manifest text, or the explicitly requested |
| 4306 | // base-prompt-only disclosure. Rendered as a system cell. |
| 4307 | app.add_message(HistoryCell::System { content: rendered }); |
| 4308 | transcript_batch_updated = true; |
| 4309 | } |
| 4310 | EngineEvent::GoalUpdated { snapshot } => { |
| 4311 | if apply_goal_snapshot_to_app(app, &snapshot) { |
| 4312 | transcript_batch_updated = true; |
| 4313 | if let Err(error) = persist_current_session_goal(app) { |
| 4314 | surface_goal_persistence_failure(app, &error); |
| 4315 | } |
| 4316 | } |
| 4317 | } |
| 4318 | EngineEvent::GoalContinuationWaiting { delay_seconds } => { |
| 4319 | app.goal_continuation_waiting = true; |
| 4320 | let delay = |
| 4321 | codewhale_command_contract::elapsed::format_elapsed_secs(delay_seconds); |
| 4322 | app.show_event_notice( |
| 4323 | app.tr(MessageId::GoalContinuationWaiting) |
| 4324 | .replace("{delay}", &delay), |
| 4325 | StatusToastLevel::Info, |
| 4326 | ); |
| 4327 | } |
| 4328 | EngineEvent::GoalContinuationWaitEnded { interrupted } => { |
| 4329 | app.goal_continuation_waiting = false; |
| 4330 | let message_id = if interrupted { |
| 4331 | MessageId::GoalContinuationStopped |
| 4332 | } else { |
| 4333 | MessageId::GoalContinuationReady |
| 4334 | }; |
| 4335 | app.show_event_notice( |
| 4336 | app.tr(message_id).to_string(), |
| 4337 | StatusToastLevel::Info, |
| 4338 | ); |
| 4339 | } |
| 4340 | event @ EngineEvent::SessionUpdated { .. } => { |
| 4341 | apply_engine_session_projection(app, config, event); |
| 4342 | } |
| 4343 | EngineEvent::CompactionStarted { id, auto, .. } => { |
| 4344 | apply_compaction_started(app, id, auto); |
| 4345 | } |
| 4346 | EngineEvent::CompactionCompleted { |
| 4347 | id, |
| 4348 | auto, |
| 4349 | message, |
| 4350 | messages_before, |
| 4351 | messages_after, |
| 4352 | summary_prompt, |
| 4353 | .. |
| 4354 | } => { |
| 4355 | apply_compaction_completed( |
| 4356 | app, |
| 4357 | &id, |
| 4358 | auto, |
| 4359 | message, |
| 4360 | messages_before, |
| 4361 | messages_after, |
| 4362 | summary_prompt, |
| 4363 | ); |
| 4364 | } |
| 4365 | EngineEvent::CompactionCancelled { id, auto, message } => { |
| 4366 | apply_compaction_cancelled(app, &id, auto, message); |
| 4367 | } |
| 4368 | EngineEvent::CompactionFailed { id, auto, message } => { |
| 4369 | apply_compaction_failed(app, &id, auto, message); |
| 4370 | } |
| 4371 | EngineEvent::PurgeStarted { message } => { |
| 4372 | app.is_purging = true; |
| 4373 | app.show_event_notice(message, StatusToastLevel::Info); |
| 4374 | } |
| 4375 | EngineEvent::PurgeCompleted { message, .. } => { |
| 4376 | app.is_purging = false; |
| 4377 | app.show_event_notice(message, StatusToastLevel::Success); |
| 4378 | } |
| 4379 | EngineEvent::PurgeFailed { message } => { |
| 4380 | app.is_purging = false; |
| 4381 | app.show_event_notice(message, StatusToastLevel::Error); |
| 4382 | } |
| 4383 | EngineEvent::PrefixCacheChange { |
| 4384 | description, |
| 4385 | stability_pct, |
| 4386 | changed, |
| 4387 | pinned_combined_hash, |
| 4388 | pin_reason, |
| 4389 | last_miss_reason, |
| 4390 | context_updates, |
| 4391 | .. |
| 4392 | } => { |
| 4393 | app.prefix_context_updates = context_updates; |
| 4394 | app.prefix_checks_total = app.prefix_checks_total.saturating_add(1); |
| 4395 | app.prefix_stability_pct = Some(stability_pct); |
| 4396 | app.last_pinned_prefix_hash = |
| 4397 | (!pinned_combined_hash.is_empty()).then_some(pinned_combined_hash); |
| 4398 | app.prefix_pin_reason = (!pin_reason.is_empty()).then_some(pin_reason); |
| 4399 | // A declared re-pin or reset is an expected miss, not a |
| 4400 | // silent-cache-death drift; only an undeclared drift is |
| 4401 | // a real problem. |
| 4402 | let is_drift = description.starts_with("drift"); |
| 4403 | app.prefix_last_miss_reason = |
| 4404 | (!last_miss_reason.is_empty()).then_some(last_miss_reason); |
| 4405 | if changed { |
| 4406 | app.prefix_change_count = app.prefix_change_count.saturating_add(1); |
| 4407 | if is_drift { |
| 4408 | app.prefix_drift_count = app.prefix_drift_count.saturating_add(1); |
| 4409 | } |
| 4410 | if !description.is_empty() { |
| 4411 | app.last_prefix_change_desc = Some(description); |
| 4412 | } |
| 4413 | } |
| 4414 | } |
| 4415 | EngineEvent::ConversationTitle { title } => { |
| 4416 | apply_conversation_title(app, &title); |
| 4417 | } |
| 4418 | EngineEvent::ContentFilterRefusal { reason, refusal } => { |
| 4419 | apply_content_filter_refusal(app, &reason, refusal.as_deref()); |
| 4420 | } |
| 4421 | EngineEvent::PluginChanged { |
| 4422 | plugin, |
| 4423 | action, |
| 4424 | decided_by, |
| 4425 | .. |
| 4426 | } => { |
| 4427 | apply_plugin_changed_notice(app, &plugin, &action, decided_by.as_deref()); |
| 4428 | reload_terminal_plugin_registry(app, config).await; |
| 4429 | transcript_batch_updated = true; |
| 4430 | } |
| 4431 | EngineEvent::LspRepairUpdate { |
| 4432 | diagnostics_found, |
| 4433 | files, |
| 4434 | injected, |
| 4435 | } => { |
| 4436 | let repair = &mut app.lsp_repair; |
| 4437 | repair.diagnostics_found = |
| 4438 | repair.diagnostics_found.saturating_add(diagnostics_found); |
| 4439 | repair.files_touched = repair.files_touched.saturating_add(files); |
| 4440 | if injected { |
| 4441 | // Injection itself is not a repair attempt — the model |
| 4442 | // has only been shown the diagnostics so far (#4107). |
| 4443 | repair.injected = true; |
| 4444 | if repair.latest == "unavailable" || repair.latest.is_empty() { |
| 4445 | repair.latest = "unknown"; |
| 4446 | } |
| 4447 | } else if repair.injected { |
| 4448 | // Diagnostics after a prior injection imply the model |
| 4449 | // edited again (a repair attempt). Zero findings = resolved. |
| 4450 | repair.repair_attempted = true; |
| 4451 | repair.latest = if diagnostics_found == 0 { |
| 4452 | "resolved" |
| 4453 | } else { |
| 4454 | "still_failing" |
| 4455 | }; |
| 4456 | } else { |
| 4457 | repair.latest = "unknown"; |
| 4458 | } |
| 4459 | } |
| 4460 | EngineEvent::PauseEvents { ack } => { |
| 4461 | if !event_broker.is_paused() { |
| 4462 | let input_handoff = |
| 4463 | match terminal_input.pause_for_child_terminal().await { |
| 4464 | Ok(()) => prepare_terminal_input_handoff( |
| 4465 | &terminal_input, |
| 4466 | &mut pending_terminal_events, |
| 4467 | ), |
| 4468 | Err(err) => Err(err), |
| 4469 | }; |
| 4470 | match input_handoff { |
| 4471 | Ok(true) => {} |
| 4472 | Ok(false) => { |
| 4473 | terminal_input.resume_after_child_terminal(); |
| 4474 | tracing::debug!( |
| 4475 | "refusing interactive child because cancellation input is pending" |
| 4476 | ); |
| 4477 | // Preserve Esc/Ctrl+C for the ordinary |
| 4478 | // key path and withhold the ack so the |
| 4479 | // child cannot race ahead of cancellation. |
| 4480 | continue; |
| 4481 | } |
| 4482 | Err(err) => { |
| 4483 | terminal_input.resume_after_child_terminal(); |
| 4484 | tracing::warn!( |
| 4485 | error = %err, |
| 4486 | "refusing interactive child after terminal input handoff failed" |
| 4487 | ); |
| 4488 | let recovery = match terminal_input.restart_detached() { |
| 4489 | Ok(()) => "Terminal input recovered.".to_string(), |
| 4490 | Err(restart_err) => { |
| 4491 | tracing::warn!( |
| 4492 | error = %restart_err, |
| 4493 | "failed to restart terminal input after handoff refusal" |
| 4494 | ); |
| 4495 | format!( |
| 4496 | "Terminal input recovery also failed ({restart_err}); restart Codewhale if keys stop responding." |
| 4497 | ) |
| 4498 | } |
| 4499 | }; |
| 4500 | app.push_status_toast( |
| 4501 | format!( |
| 4502 | "Interactive terminal handoff refused ({err}). {recovery}" |
| 4503 | ), |
| 4504 | StatusToastLevel::Error, |
| 4505 | None, |
| 4506 | ); |
| 4507 | app.needs_redraw = true; |
| 4508 | last_terminal_input_recovery = Instant::now(); |
| 4509 | // Do not acknowledge the pause. The |
| 4510 | // engine guard times out, refuses the |
| 4511 | // child, and queues a harmless resume. |
| 4512 | continue; |
| 4513 | } |
| 4514 | } |
| 4515 | if let Err(err) = pause_terminal( |
| 4516 | terminal, |
| 4517 | app.use_mouse_capture, |
| 4518 | app.use_bracketed_paste, |
| 4519 | ) { |
| 4520 | terminal_input.resume_after_child_terminal(); |
| 4521 | tracing::warn!( |
| 4522 | error = %err, |
| 4523 | "refusing interactive child after terminal mode handoff failed" |
| 4524 | ); |
| 4525 | resume_terminal( |
| 4526 | terminal, |
| 4527 | app.use_mouse_capture, |
| 4528 | app.use_bracketed_paste, |
| 4529 | app.synchronized_output_enabled, |
| 4530 | ) |
| 4531 | .with_context(|| { |
| 4532 | format!( |
| 4533 | "terminal handoff failed ({err}) and Codewhale could not restore terminal controls" |
| 4534 | ) |
| 4535 | })?; |
| 4536 | app.push_status_toast( |
| 4537 | format!("Interactive terminal handoff refused ({err})."), |
| 4538 | StatusToastLevel::Error, |
| 4539 | None, |
| 4540 | ); |
| 4541 | app.needs_redraw = true; |
| 4542 | terminal_repaint = FrameRepaint::Clear; |
| 4543 | // As above, withholding the acknowledgement |
| 4544 | // keeps the child from launching. |
| 4545 | continue; |
| 4546 | } |
| 4547 | event_broker.pause_events(); |
| 4548 | terminal_paused_at = Some(Instant::now()); |
| 4549 | } |
| 4550 | if let Some(ack) = ack { |
| 4551 | ack.notify_one(); |
| 4552 | } |
| 4553 | } |
| 4554 | EngineEvent::ResumeEvents => { |
| 4555 | if event_broker.is_paused() { |
| 4556 | resume_terminal( |
| 4557 | terminal, |
| 4558 | app.use_mouse_capture, |
| 4559 | app.use_bracketed_paste, |
| 4560 | app.synchronized_output_enabled, |
| 4561 | )?; |
| 4562 | event_broker.resume_events(); |
| 4563 | terminal_input.resume_after_child_terminal(); |
| 4564 | terminal_paused_at = None; |
| 4565 | } |
| 4566 | } |
| 4567 | EngineEvent::AgentSpawned { |
| 4568 | owner_session_id, |
| 4569 | id, |
| 4570 | prompt, |
| 4571 | worker_status, |
| 4572 | parent_run_id, |
| 4573 | spawn_depth, |
| 4574 | model, |
| 4575 | route_source: _, |
| 4576 | display_name, |
| 4577 | } if active_agent_lifecycle_event => { |
| 4578 | let prompt_summary = bound_agent_activity_text(&prompt); |
| 4579 | app.agent_progress |
| 4580 | .insert(id.clone(), format!("starting: {prompt_summary}")); |
| 4581 | let now = Instant::now(); |
| 4582 | let meta = app.agent_progress_meta.entry(id.clone()).or_default(); |
| 4583 | meta.started_at.get_or_insert(now); |
| 4584 | meta.parent_run_id = parent_run_id.clone(); |
| 4585 | meta.spawn_depth = spawn_depth; |
| 4586 | // The engine's name for the child, before any snapshot |
| 4587 | // arrives, so the first label is already the right one. |
| 4588 | meta.display_name = display_name.clone(); |
| 4589 | meta.current_activity = worker_status.map(|status| { |
| 4590 | AgentCurrentActivity::bounded( |
| 4591 | status.into(), |
| 4592 | Some(prompt_summary.clone()), |
| 4593 | None, |
| 4594 | None, |
| 4595 | ) |
| 4596 | }); |
| 4597 | meta.current_tool = None; |
| 4598 | record_agent_spawned_route(app, &id, &model); |
| 4599 | if app.agent_activity_started_at.is_none() { |
| 4600 | app.agent_activity_started_at = Some(now); |
| 4601 | } |
| 4602 | // #3030: Assign a stable user-facing label for this |
| 4603 | // agent and keep the raw id out of the status bar. |
| 4604 | apply_agent_spawned_status_and_observer(app, &id, &prompt, &prompt_summary); |
| 4605 | crate::tui::subagent_routing::upsert_roster_spawn( |
| 4606 | app, |
| 4607 | &owner_session_id, |
| 4608 | &id, |
| 4609 | &prompt_summary, |
| 4610 | worker_status, |
| 4611 | parent_run_id.as_deref(), |
| 4612 | &model, |
| 4613 | display_name.as_deref(), |
| 4614 | ); |
| 4615 | subagent_list_refresh_requested = true; |
| 4616 | } |
| 4617 | EngineEvent::AgentProgress { |
| 4618 | owner_session_id, |
| 4619 | id, |
| 4620 | status, |
| 4621 | activity, |
| 4622 | parent_run_id, |
| 4623 | spawn_depth, |
| 4624 | } if event_owner_is_active( |
| 4625 | app.current_session_id.as_deref(), |
| 4626 | &owner_session_id, |
| 4627 | ) => |
| 4628 | { |
| 4629 | let display = bound_agent_activity_text(&friendly_subagent_progress( |
| 4630 | app, |
| 4631 | &id, |
| 4632 | &status, |
| 4633 | activity.routine_wait, |
| 4634 | )); |
| 4635 | if activity.routine_wait { |
| 4636 | app.agent_progress |
| 4637 | .entry(id.clone()) |
| 4638 | .or_insert_with(|| display.clone()); |
| 4639 | } else { |
| 4640 | app.agent_progress.insert(id.clone(), display.clone()); |
| 4641 | } |
| 4642 | let now = Instant::now(); |
| 4643 | let meta = app.agent_progress_meta.entry(id.clone()).or_default(); |
| 4644 | meta.started_at.get_or_insert(now); |
| 4645 | meta.last_progress_at = Some(now); |
| 4646 | meta.parent_run_id = parent_run_id.clone(); |
| 4647 | meta.spawn_depth = spawn_depth; |
| 4648 | let current_tool = activity |
| 4649 | .tool_name |
| 4650 | .as_deref() |
| 4651 | .map(subagent_progress_tool_display_name) |
| 4652 | .map(str::to_string); |
| 4653 | meta.current_activity = Some(AgentCurrentActivity::bounded( |
| 4654 | activity.worker_status.into(), |
| 4655 | Some(display.clone()), |
| 4656 | current_tool.clone(), |
| 4657 | activity.step, |
| 4658 | )); |
| 4659 | meta.current_tool = current_tool; |
| 4660 | if app.agent_activity_started_at.is_none() { |
| 4661 | app.agent_activity_started_at = Some(now); |
| 4662 | } |
| 4663 | // #3030: progress can arrive before AgentSpawned is |
| 4664 | // observed — assign the stable label on first sight. |
| 4665 | // The label and the step stay on the agent row. They |
| 4666 | // used to overwrite the parent status line, so every |
| 4667 | // child tool call looked like the turn being watched |
| 4668 | // (#6565). |
| 4669 | let _ = app.ensure_agent_label(&id); |
| 4670 | crate::tui::subagent_routing::upsert_roster_progress( |
| 4671 | app, |
| 4672 | &owner_session_id, |
| 4673 | &id, |
| 4674 | &display, |
| 4675 | &activity, |
| 4676 | parent_run_id.as_deref(), |
| 4677 | ); |
| 4678 | // A progress-first agent (its AgentSpawned was dropped |
| 4679 | // under channel pressure) exists only in agent_progress |
| 4680 | // until a ListSubAgents refresh promotes it into |
| 4681 | // subagent_cache. Request that refresh like the |
| 4682 | // AgentSpawned arm does, so the sidebar row survives |
| 4683 | // reconciliation instead of flickering out. |
| 4684 | if !app.subagent_cache.iter().any(|agent| agent.agent_id == id) { |
| 4685 | subagent_list_refresh_requested = true; |
| 4686 | } |
| 4687 | // #3033: Throttle redraws from rapid AgentProgress events. |
| 4688 | // When 4+ sub-agents are running concurrently, each firing |
| 4689 | // progress events, the per-event `needs_redraw = true` saturates |
| 4690 | // the render loop and starves terminal input. Limit |
| 4691 | // progress-driven repaints to at most one per 100ms; the |
| 4692 | // status-animation timer (80ms cadence) provides a guaranteed |
| 4693 | // floor for sidebar updates. Data is still recorded immediately; |
| 4694 | // the sidebar picks it up on the next permitted redraw. |
| 4695 | if !agent_progress_redraw_permitted_for_drain( |
| 4696 | &mut app.last_agent_progress_redraw, |
| 4697 | &mut progress_redraw_agents, |
| 4698 | &id, |
| 4699 | Instant::now(), |
| 4700 | ) { |
| 4701 | // Restore the pre-event accumulator value: a |
| 4702 | // throttled progress event contributes no redraw of |
| 4703 | // its own, but earlier events' redraws survive. |
| 4704 | received_engine_event = redraw_requested_before_event; |
| 4705 | } |
| 4706 | } |
| 4707 | EngineEvent::AgentComplete { |
| 4708 | owner_session_id, |
| 4709 | id, |
| 4710 | result, |
| 4711 | outcome, |
| 4712 | parent_run_id, |
| 4713 | usage, |
| 4714 | display_name, |
| 4715 | .. |
| 4716 | } if active_agent_lifecycle_event => { |
| 4717 | if display_name.is_some() { |
| 4718 | app.agent_progress_meta |
| 4719 | .entry(id.clone()) |
| 4720 | .or_default() |
| 4721 | .display_name = display_name.clone(); |
| 4722 | } |
| 4723 | let agent_elapsed_ms = app |
| 4724 | .work_surface |
| 4725 | .frozen_agent_elapsed_ms(&id) |
| 4726 | .or_else(|| { |
| 4727 | app.subagent_cache |
| 4728 | .iter() |
| 4729 | .find(|agent| agent.agent_id == id) |
| 4730 | .map(|agent| agent.duration_ms) |
| 4731 | }) |
| 4732 | .or_else(|| { |
| 4733 | app.agent_progress_meta |
| 4734 | .get(&id) |
| 4735 | .and_then(|meta| meta.started_at) |
| 4736 | .map(|started| { |
| 4737 | u64::try_from(started.elapsed().as_millis()) |
| 4738 | .unwrap_or(u64::MAX) |
| 4739 | }) |
| 4740 | }); |
| 4741 | let subagent_elapsed = app |
| 4742 | .agent_activity_started_at |
| 4743 | .or(app.turn_started_at) |
| 4744 | .map(|started| started.elapsed()) |
| 4745 | .unwrap_or_default(); |
| 4746 | let has_other_running_subagents = |
| 4747 | app.agent_progress.keys().any(|agent_id| agent_id != &id) |
| 4748 | || app.subagent_cache.iter().any(|agent| { |
| 4749 | agent.agent_id != id |
| 4750 | && matches!(agent.status, SubAgentStatus::Running) |
| 4751 | }); |
| 4752 | app.agent_progress.remove(&id); |
| 4753 | crate::tui::pending_requests::clear_for_agent(app, &id); |
| 4754 | let terminal_status = outcome; |
| 4755 | crate::tui::subagent_routing::upsert_roster_terminal( |
| 4756 | app, |
| 4757 | &owner_session_id, |
| 4758 | &id, |
| 4759 | terminal_status.as_ref(), |
| 4760 | &result, |
| 4761 | parent_run_id.as_deref(), |
| 4762 | usage.as_ref(), |
| 4763 | display_name.as_deref(), |
| 4764 | agent_elapsed_ms, |
| 4765 | ); |
| 4766 | if let Some(terminal_status) = terminal_status.as_ref() { |
| 4767 | apply_subagent_terminal_projection( |
| 4768 | app, |
| 4769 | &id, |
| 4770 | terminal_status.clone(), |
| 4771 | Some(bound_agent_activity_text(&result)), |
| 4772 | ); |
| 4773 | apply_agent_complete_status_and_observer( |
| 4774 | app, |
| 4775 | &id, |
| 4776 | &result, |
| 4777 | terminal_status, |
| 4778 | ); |
| 4779 | } else { |
| 4780 | let label = app.ensure_agent_label(&id); |
| 4781 | app.show_event_notice( |
| 4782 | format!( |
| 4783 | "{label} settled; outcome unconfirmed. Refreshing worker state." |
| 4784 | ), |
| 4785 | StatusToastLevel::Warning, |
| 4786 | ); |
| 4787 | } |
| 4788 | let should_recapture_terminal = !has_other_running_subagents; |
| 4789 | // #6565: the finished child joins the batch under the |
| 4790 | // name every surface shows; the notice names every |
| 4791 | // child of the batch and waits only on finite work. |
| 4792 | if let Some(terminal_status) = terminal_status.as_ref() { |
| 4793 | let label = app.ensure_agent_label(&id); |
| 4794 | app.background_finished.push( |
| 4795 | crate::tui::background_finished::FinishedWork::agent( |
| 4796 | &label, |
| 4797 | terminal_status, |
| 4798 | &result, |
| 4799 | subagent_elapsed, |
| 4800 | ), |
| 4801 | ); |
| 4802 | } |
| 4803 | flush_background_finished(app, config, false); |
| 4804 | if should_recapture_terminal && event_broker.is_paused() { |
| 4805 | resume_terminal( |
| 4806 | terminal, |
| 4807 | app.use_mouse_capture, |
| 4808 | app.use_bracketed_paste, |
| 4809 | app.synchronized_output_enabled, |
| 4810 | )?; |
| 4811 | event_broker.resume_events(); |
| 4812 | terminal_input.resume_after_child_terminal(); |
| 4813 | terminal_paused_at = None; |
| 4814 | app.needs_redraw = true; |
| 4815 | } |
| 4816 | subagent_list_refresh_requested = true; |
| 4817 | } |
| 4818 | EngineEvent::SubAgentFollowUp { |
| 4819 | owner_session_id, |
| 4820 | agent_id, |
| 4821 | outcome, |
| 4822 | } if event_owner_is_active( |
| 4823 | app.current_session_id.as_deref(), |
| 4824 | &owner_session_id, |
| 4825 | ) => |
| 4826 | { |
| 4827 | crate::tui::agent_focus::apply_follow_up_receipt(app, &agent_id, &outcome); |
| 4828 | } |
| 4829 | EngineEvent::AgentList { |
| 4830 | owner_session_id, |
| 4831 | agents, |
| 4832 | coordination, |
| 4833 | queued_follow_ups, |
| 4834 | roster, |
| 4835 | } if event_owner_is_active( |
| 4836 | app.current_session_id.as_deref(), |
| 4837 | &owner_session_id, |
| 4838 | ) => |
| 4839 | { |
| 4840 | app.agent_queued_follow_ups = queued_follow_ups; |
| 4841 | app.subagent_cache_received_at = Some(Instant::now()); |
| 4842 | app.agent_roster = roster; |
| 4843 | app.agent_roster_session_id = Some(owner_session_id); |
| 4844 | if std::mem::take(&mut app.agent_roster_print_requested) { |
| 4845 | let content = crate::tui::agent_roster::render_agent_roster( |
| 4846 | app.current_agent_roster(), |
| 4847 | "main", |
| 4848 | ); |
| 4849 | app.add_message(crate::tui::history::HistoryCell::System { content }); |
| 4850 | } |
| 4851 | let mut sorted = agents.clone(); |
| 4852 | sort_subagents_in_place(&mut sorted); |
| 4853 | sorted.retain(|a| !a.from_prior_session); |
| 4854 | app.subagent_cache = sorted.clone(); |
| 4855 | apply_coordination_detail_projection(app, coordination); |
| 4856 | reconcile_subagent_activity_state(app); |
| 4857 | let view_agents = subagent_view_agents(app, &app.subagent_cache); |
| 4858 | if app.view_stack.update_subagents(&view_agents) { |
| 4859 | app.show_event_notice( |
| 4860 | current_session_fleet_workers_status( |
| 4861 | app.ui_locale, |
| 4862 | view_agents.len(), |
| 4863 | ), |
| 4864 | StatusToastLevel::Info, |
| 4865 | ); |
| 4866 | } |
| 4867 | // Individual spawn/complete events already log to history; |
| 4868 | // full list available via /agents command. |
| 4869 | } |
| 4870 | EngineEvent::AgentSpawned { .. } |
| 4871 | | EngineEvent::AgentProgress { .. } |
| 4872 | | EngineEvent::AgentComplete { .. } |
| 4873 | | EngineEvent::SubAgentFollowUp { .. } |
| 4874 | | EngineEvent::AgentList { .. } => { |
| 4875 | // Process-local senders can outlive a session switch. |
| 4876 | // A foreign event must not mutate the active transcript, |
| 4877 | // sidebar, status, observer, or notification surface. |
| 4878 | received_engine_event = redraw_requested_before_event; |
| 4879 | } |
| 4880 | EngineEvent::SubAgentMailbox { |
| 4881 | owner_session_id, |
| 4882 | turn_id, |
| 4883 | seq, |
| 4884 | message, |
| 4885 | } if event_owner_is_active( |
| 4886 | app.current_session_id.as_deref(), |
| 4887 | &owner_session_id, |
| 4888 | ) => |
| 4889 | { |
| 4890 | let should_refresh_subagents = |
| 4891 | subagent_message_refreshes_workspace_context(&message); |
| 4892 | let updated_transcript = |
| 4893 | handle_subagent_mailbox_for_turn(app, &turn_id, seq, &message); |
| 4894 | crate::tui::subagent_routing::upsert_roster_from_mailbox( |
| 4895 | app, |
| 4896 | &owner_session_id, |
| 4897 | &message, |
| 4898 | ); |
| 4899 | if let Some((agent_id, status, result)) = |
| 4900 | subagent_terminal_projection_from_mailbox(&message) |
| 4901 | { |
| 4902 | apply_subagent_terminal_projection(app, agent_id, status, result); |
| 4903 | subagent_list_refresh_requested = true; |
| 4904 | } |
| 4905 | if should_refresh_subagents { |
| 4906 | subagent_list_refresh_requested = true; |
| 4907 | } |
| 4908 | if updated_transcript { |
| 4909 | transcript_batch_updated = true; |
| 4910 | } else if !should_refresh_subagents |
| 4911 | && matches!( |
| 4912 | message, |
| 4913 | codewhale_engine::tools::subagent::MailboxMessage::Progress { .. } |
| 4914 | ) |
| 4915 | { |
| 4916 | // Progress mailbox envelopes mirror AgentProgress. |
| 4917 | // When the card state did not visibly change, do |
| 4918 | // not let the duplicate envelope bypass the |
| 4919 | // AgentProgress redraw throttle. |
| 4920 | received_engine_event = redraw_requested_before_event; |
| 4921 | } |
| 4922 | } |
| 4923 | EngineEvent::SubAgentMailbox { .. } => { |
| 4924 | received_engine_event = redraw_requested_before_event; |
| 4925 | } |
| 4926 | EngineEvent::WorkflowUi { |
| 4927 | owner_session_id, |
| 4928 | run_id, |
| 4929 | event, |
| 4930 | } => { |
| 4931 | if !apply_owned_workflow_ui_event(app, &owner_session_id, &run_id, &event) { |
| 4932 | tracing::debug!("discarding workflow UI event for an inactive session"); |
| 4933 | received_engine_event = redraw_requested_before_event; |
| 4934 | continue; |
| 4935 | } |
| 4936 | // Coalesce progress (#4095): a 75-agent fan-out streams |
| 4937 | // task events far faster than a frame. The |
| 4938 | // state is already applied; only a run's start and end |
| 4939 | // paint at once, the rest share the AgentProgress pace. |
| 4940 | // The transcript is not marked here — the only cells a |
| 4941 | // workflow event touches mark it themselves. |
| 4942 | let lifecycle = |
| 4943 | event.get("type").and_then(|v| v.as_str()).is_some_and(|t| { |
| 4944 | matches!(t, "run_started" | "run_completed" | "run_cancelled") |
| 4945 | }); |
| 4946 | if lifecycle |
| 4947 | || agent_progress_redraw_permitted( |
| 4948 | &mut app.last_agent_progress_redraw, |
| 4949 | Instant::now(), |
| 4950 | ) |
| 4951 | { |
| 4952 | app.needs_redraw = true; |
| 4953 | } else { |
| 4954 | received_engine_event = redraw_requested_before_event; |
| 4955 | } |
| 4956 | } |
| 4957 | EngineEvent::ApprovalRequired { |
| 4958 | publication: _, |
| 4959 | id, |
| 4960 | tool_name, |
| 4961 | description, |
| 4962 | input, |
| 4963 | approval_key, |
| 4964 | approval_grouping_key, |
| 4965 | intent_summary, |
| 4966 | approval_force_prompt, |
| 4967 | } => { |
| 4968 | handle_approval_required_event( |
| 4969 | app, |
| 4970 | &engine_handle, |
| 4971 | config, |
| 4972 | ApprovalRequiredEvent { |
| 4973 | id, |
| 4974 | tool_name, |
| 4975 | description, |
| 4976 | input, |
| 4977 | approval_key, |
| 4978 | approval_grouping_key, |
| 4979 | intent_summary, |
| 4980 | approval_force_prompt, |
| 4981 | }, |
| 4982 | ) |
| 4983 | .await; |
| 4984 | } |
| 4985 | // Retired by pending_requests before session/idle filters. |
| 4986 | EngineEvent::ApprovalWithdrawn { .. } => {} |
| 4987 | EngineEvent::UserInputClosed { .. } => {} |
| 4988 | EngineEvent::UserInputRequired { id, request } => { |
| 4989 | app.pending_user_input_prompt = Some((id.clone(), request.clone())); |
| 4990 | app.view_stack |
| 4991 | .push(UserInputView::new(id.clone(), request, app.ui_locale)); |
| 4992 | let payload = notifications::input_needed_payload(app.ui_locale); |
| 4993 | if let Some((method, _, _)) = crate::tui::notifications::settings(config) { |
| 4994 | let in_tmux = std::env::var("TMUX").is_ok_and(|v| !v.is_empty()); |
| 4995 | crate::tui::notifications::notify_done( |
| 4996 | method, |
| 4997 | in_tmux, |
| 4998 | &payload, |
| 4999 | Duration::ZERO, |
| 5000 | Duration::ZERO, |
| 5001 | ); |
| 5002 | } |
| 5003 | app.push_status_toast_record( |
| 5004 | StatusToast::new( |
| 5005 | payload.headline(), |
| 5006 | StatusToastLevel::Warning, |
| 5007 | Some(12_000), |
| 5008 | ) |
| 5009 | .for_action(id.clone()), |
| 5010 | ); |
| 5011 | } |
| 5012 | EngineEvent::ElevationRequired { |
| 5013 | tool_id, |
| 5014 | tool_name, |
| 5015 | command, |
| 5016 | denial_reason, |
| 5017 | blocked_network, |
| 5018 | blocked_write, |
| 5019 | } => { |
| 5020 | // Auto-approved modes may retry denied tools without another prompt. |
| 5021 | if app_auto_approve_enabled(app) { |
| 5022 | log_sensitive_event( |
| 5023 | "tool.sandbox.auto_elevate", |
| 5024 | serde_json::json!({ |
| 5025 | "tool_name": tool_name, |
| 5026 | "tool_id": tool_id, |
| 5027 | "reason": denial_reason, |
| 5028 | "session_id": app.current_session_id, |
| 5029 | }), |
| 5030 | ); |
| 5031 | app.add_message(HistoryCell::System { |
| 5032 | content: app |
| 5033 | .tr(MessageId::SandboxAutoElevating) |
| 5034 | .replace("{tool_name}", tool_name.as_str()) |
| 5035 | .replace("{denial_reason}", denial_reason.as_str()), |
| 5036 | }); |
| 5037 | // Auto-elevate to full access (no sandbox) |
| 5038 | let policy = codewhale_sandbox::SandboxPolicy::DangerFullAccess; |
| 5039 | let _ = engine_handle |
| 5040 | .retry_tool_with_policy_by( |
| 5041 | tool_id, |
| 5042 | policy, |
| 5043 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 5044 | ) |
| 5045 | .await; |
| 5046 | } else { |
| 5047 | log_sensitive_event( |
| 5048 | "tool.sandbox.prompt_elevation", |
| 5049 | serde_json::json!({ |
| 5050 | "tool_name": tool_name, |
| 5051 | "tool_id": tool_id, |
| 5052 | "reason": denial_reason, |
| 5053 | "session_id": app.current_session_id, |
| 5054 | }), |
| 5055 | ); |
| 5056 | // Show elevation dialog |
| 5057 | let request = ElevationRequest::for_shell( |
| 5058 | &tool_id, |
| 5059 | command.as_deref().unwrap_or(&tool_name), |
| 5060 | &denial_reason, |
| 5061 | blocked_network, |
| 5062 | blocked_write, |
| 5063 | ); |
| 5064 | app.view_stack |
| 5065 | .push(ElevationView::new(request, app.ui_locale)); |
| 5066 | let payload = notifications::elevation_needed_payload( |
| 5067 | app.ui_locale, |
| 5068 | &tool_name, |
| 5069 | &denial_reason, |
| 5070 | ); |
| 5071 | if let Some((method, _, _)) = |
| 5072 | crate::tui::notifications::settings(config) |
| 5073 | { |
| 5074 | let in_tmux = std::env::var("TMUX").is_ok_and(|v| !v.is_empty()); |
| 5075 | crate::tui::notifications::notify_done( |
| 5076 | method, |
| 5077 | in_tmux, |
| 5078 | &payload, |
| 5079 | Duration::ZERO, |
| 5080 | Duration::ZERO, |
| 5081 | ); |
| 5082 | } |
| 5083 | app.push_status_toast_record( |
| 5084 | StatusToast::new( |
| 5085 | payload.headline(), |
| 5086 | StatusToastLevel::Warning, |
| 5087 | Some(12_000), |
| 5088 | ) |
| 5089 | .for_action(tool_id.clone()), |
| 5090 | ); |
| 5091 | } |
| 5092 | } |
| 5093 | EngineEvent::ProviderRequestReceipt { receipt } => { |
| 5094 | if receipt["primary"].as_bool() == Some(true) |
| 5095 | && receipt["session_id"].as_str() == app.current_session_id.as_deref() |
| 5096 | { |
| 5097 | let coverage = receipt.get("coverage").cloned().and_then(|value| { |
| 5098 | serde_json::from_value::< |
| 5099 | codewhale_engine::llm_client::ProviderUsageCoverage, |
| 5100 | >(value) |
| 5101 | .ok() |
| 5102 | }); |
| 5103 | if receipt["source_accounting"].as_bool() != Some(true) |
| 5104 | && let Some(source) = receipt["source_id"].as_str() |
| 5105 | { |
| 5106 | if receipt["usage_reported"].as_bool() == Some(true) { |
| 5107 | app.session.subagent_usage_sources.insert( |
| 5108 | codewhale_engine::cost_status::usage_source_fingerprint( |
| 5109 | source, |
| 5110 | ), |
| 5111 | ); |
| 5112 | app.compact_subagent_usage_sources(); |
| 5113 | codewhale_engine::cost_status::mark_retired_usage_source( |
| 5114 | codewhale_engine::cost_status::scope_token(), |
| 5115 | source, |
| 5116 | ); |
| 5117 | } |
| 5118 | if matches!(coverage, Some(codewhale_engine::llm_client::ProviderUsageCoverage::Missing | codewhale_engine::llm_client::ProviderUsageCoverage::Incomplete)) |
| 5119 | && let Some(route) = receipt.get("route").cloned().and_then(|value| serde_json::from_value::<codewhale_engine::cost_status::EffectiveRouteEnvelope>(value).ok()) |
| 5120 | { |
| 5121 | let reason = if receipt["outcome"] == "completed" || receipt["outcome"] == "review_response" { |
| 5122 | codewhale_engine::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage |
| 5123 | } else { |
| 5124 | codewhale_engine::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 5125 | }; |
| 5126 | let pool = codewhale_engine::cost_status::background_cost_for_runtime_drop(&codewhale_engine::cost_status::RuntimeUsageDropRecord { |
| 5127 | source_id: source.to_string(), route, reason, |
| 5128 | }); |
| 5129 | app.absorb_pending_background_cost(&pool); |
| 5130 | } |
| 5131 | } |
| 5132 | if let Some(error) = receipt["accounting_error"].as_str() { |
| 5133 | app.mark_usage_uncertain("usage_settlement_unacknowledged"); |
| 5134 | app.show_event_notice( |
| 5135 | format!("Provider usage settlement is uncertain: {error}"), |
| 5136 | StatusToastLevel::Warning, |
| 5137 | ); |
| 5138 | } |
| 5139 | let leaf = app.session_journal.leaf_id.clone(); |
| 5140 | app.session_journal.append( |
| 5141 | codewhale_runtime::session_tree::SessionEntryKind::System { |
| 5142 | content: format!("Provider request receipt: {receipt}"), |
| 5143 | }, |
| 5144 | ); |
| 5145 | app.session_journal.leaf_id = leaf; |
| 5146 | } |
| 5147 | |
| 5148 | if receipt["outcome"] == "steered" |
| 5149 | || receipt["outcome"] == "steered_before_stream" |
| 5150 | { |
| 5151 | stream_display_clock.flush_now(Instant::now()); |
| 5152 | if app.streaming_thinking_active_entry.is_some() |
| 5153 | && streaming_thinking::finalize_current(app) |
| 5154 | { |
| 5155 | transcript_batch_updated = true; |
| 5156 | } |
| 5157 | if let Some(index) = app.streaming_message_index.take() { |
| 5158 | let remaining = drain_text_block(&mut app.streaming_state); |
| 5159 | if !remaining.is_empty() { |
| 5160 | append_streaming_text(app, index, &remaining); |
| 5161 | accrue_streaming_token_estimate(app, &remaining); |
| 5162 | } |
| 5163 | if let Some(HistoryCell::Assistant { streaming, .. }) = |
| 5164 | app.history.get_mut(index) |
| 5165 | { |
| 5166 | *streaming = false; |
| 5167 | } |
| 5168 | app.bump_history_cell(index); |
| 5169 | transcript_batch_updated = true; |
| 5170 | } |
| 5171 | app.reasoning_buffer.clear(); |
| 5172 | app.reasoning_header = None; |
| 5173 | app.last_reasoning = None; |
| 5174 | current_streaming_text.clear(); |
| 5175 | app.streaming_state.reset(); |
| 5176 | app.streaming_output_token_estimate = 0; |
| 5177 | stream_display_clock.reset(); |
| 5178 | app.flush_active_cell(); |
| 5179 | } |
| 5180 | if receipt |
| 5181 | .get("wire_observations") |
| 5182 | .and_then(serde_json::Value::as_array) |
| 5183 | .is_some_and(|observations| { |
| 5184 | observations.iter().any(|observation| { |
| 5185 | observation.get("image_projection").is_some() |
| 5186 | }) |
| 5187 | }) |
| 5188 | { |
| 5189 | let leaf = app.session_journal.leaf_id.clone(); |
| 5190 | app.session_journal.append( |
| 5191 | codewhale_runtime::session_tree::SessionEntryKind::System { |
| 5192 | content: format!( |
| 5193 | "Provider request image projection: {receipt}" |
| 5194 | ), |
| 5195 | }, |
| 5196 | ); |
| 5197 | app.session_journal.leaf_id = leaf; |
| 5198 | } |
| 5199 | } |
| 5200 | EngineEvent::TurnUsage { |
| 5201 | accounting, |
| 5202 | max_output_tokens: _, |
| 5203 | usage, |
| 5204 | duration_ms, |
| 5205 | first_token_ms, |
| 5206 | request_ms, |
| 5207 | .. |
| 5208 | } => { |
| 5209 | // Per-step usage receipt. The session metrics strip |
| 5210 | // folds each model call's timing (stream time, TTFT, |
| 5211 | // whole-call time) here. |
| 5212 | app.session_metrics.record_model_call( |
| 5213 | usage.output_tokens, |
| 5214 | duration_ms, |
| 5215 | first_token_ms, |
| 5216 | request_ms, |
| 5217 | ); |
| 5218 | // Billed prompt receipt for the context meter: what |
| 5219 | // the provider says the model actually processed |
| 5220 | // (#5577). Reviewer/REPL child receipts also arrive |
| 5221 | // here, but their prompt is never larger than the |
| 5222 | // parent context, and the meter takes a max. |
| 5223 | let prompt_tokens = usage |
| 5224 | .request_usages |
| 5225 | .last() |
| 5226 | .map_or(usage.input_tokens, |last| last.input_tokens); |
| 5227 | if prompt_tokens > 0 { |
| 5228 | app.last_billed_input_tokens = Some( |
| 5229 | app.last_billed_input_tokens |
| 5230 | .map_or(prompt_tokens, |prior| prior.max(prompt_tokens)), |
| 5231 | ); |
| 5232 | } |
| 5233 | // Live cost: price this call against the route that |
| 5234 | // was actually dispatched so the cost surfaces move |
| 5235 | // during a long agentic turn instead of only at its |
| 5236 | // end. Provisional by design — `TurnComplete` clears |
| 5237 | // this and lands the authoritative cumulative price |
| 5238 | // through the same audit path, so nothing counts |
| 5239 | // twice and the two can never disagree on route. |
| 5240 | if accounting.is_none() { |
| 5241 | let step_cost = app |
| 5242 | .active_turn |
| 5243 | .as_ref() |
| 5244 | .and_then(|turn| turn.route.as_ref()) |
| 5245 | .and_then(codewhale_engine::core::events::TurnRoute::cost_envelope) |
| 5246 | .and_then(|route| route.audit(&usage).estimate); |
| 5247 | if let Some(cost) = step_cost { |
| 5248 | app.accrue_pending_turn_cost_estimate(cost); |
| 5249 | } |
| 5250 | app.session.accrue_pending_turn_usage(&usage); |
| 5251 | } else { |
| 5252 | let pending = codewhale_engine::cost_status::drain(); |
| 5253 | app.absorb_pending_background_cost(&pending); |
| 5254 | } |
| 5255 | } |
| 5256 | EngineEvent::RoutedTurnUsage { |
| 5257 | usage, |
| 5258 | duration_ms, |
| 5259 | first_token_ms, |
| 5260 | request_ms, |
| 5261 | } => { |
| 5262 | // Routed calls own separate immutable cost receipts. |
| 5263 | // Preserve model-call telemetry without pricing them |
| 5264 | // provisionally under the active parent route or |
| 5265 | // incrementally adding tokens that TurnComplete will |
| 5266 | // reconcile authoritatively. |
| 5267 | app.session_metrics.record_model_call( |
| 5268 | usage.output_tokens, |
| 5269 | duration_ms, |
| 5270 | first_token_ms, |
| 5271 | request_ms, |
| 5272 | ); |
| 5273 | } |
| 5274 | EngineEvent::AdvisoryNote { note, .. } => { |
| 5275 | // Advisor background watcher note. Display as a |
| 5276 | // concise system message in the transcript so the |
| 5277 | // user can see it without it blocking the parent turn. |
| 5278 | if note.trim() != "ok" { |
| 5279 | app.add_message(HistoryCell::System { |
| 5280 | content: format!("⚑ Advisor: {note}"), |
| 5281 | }); |
| 5282 | } |
| 5283 | } |
| 5284 | EngineEvent::ToolGateDecision { |
| 5285 | agent_id, |
| 5286 | tool_id, |
| 5287 | tool_name, |
| 5288 | gate, |
| 5289 | decision, |
| 5290 | risk, |
| 5291 | reviewer_model, |
| 5292 | reason, |
| 5293 | rule, |
| 5294 | receipt_id, |
| 5295 | call_digest, |
| 5296 | action_summary, |
| 5297 | } => { |
| 5298 | let mut audit = |
| 5299 | crate::tui::gate_receipts::tool_gate_audit_record_with_metadata( |
| 5300 | agent_id.as_deref(), |
| 5301 | &tool_id, |
| 5302 | &tool_name, |
| 5303 | gate, |
| 5304 | decision, |
| 5305 | risk.as_deref(), |
| 5306 | reviewer_model.as_deref(), |
| 5307 | &reason, |
| 5308 | rule.as_deref(), |
| 5309 | receipt_id.as_deref(), |
| 5310 | call_digest.as_deref(), |
| 5311 | action_summary.as_deref(), |
| 5312 | ); |
| 5313 | audit["session_id"] = serde_json::json!(app.current_session_id); |
| 5314 | tokio::task::spawn_blocking(move || { |
| 5315 | log_sensitive_event("tool.gate.decision", audit); |
| 5316 | }); |
| 5317 | let is_block = matches!( |
| 5318 | decision, |
| 5319 | codewhale_engine::core::events::ToolGateVerdict::Denied |
| 5320 | | codewhale_engine::core::events::ToolGateVerdict::Unavailable |
| 5321 | ); |
| 5322 | let is_auto_review_gate = matches!( |
| 5323 | gate, |
| 5324 | codewhale_engine::core::events::ToolGate::AutoReviewDeterministic |
| 5325 | | codewhale_engine::core::events::ToolGate::AutoReviewGuardian |
| 5326 | ); |
| 5327 | let verdict_label = match decision { |
| 5328 | codewhale_engine::core::events::ToolGateVerdict::Unavailable => { |
| 5329 | "unavailable" |
| 5330 | } |
| 5331 | codewhale_engine::core::events::ToolGateVerdict::Denied => "denied", |
| 5332 | codewhale_engine::core::events::ToolGateVerdict::Allowed => "allowed", |
| 5333 | } |
| 5334 | .to_string(); |
| 5335 | let receipt_hint_id = if agent_id.is_none() { |
| 5336 | if is_block { |
| 5337 | let summary = |
| 5338 | action_summary.clone().unwrap_or_else(|| tool_name.clone()); |
| 5339 | app.record_auto_review_blocked_receipt( |
| 5340 | receipt_id.clone(), |
| 5341 | tool_id.clone(), |
| 5342 | tool_name.clone(), |
| 5343 | gate.as_str().to_string(), |
| 5344 | verdict_label, |
| 5345 | rule.clone(), |
| 5346 | reason.clone(), |
| 5347 | call_digest.clone(), |
| 5348 | summary, |
| 5349 | ); |
| 5350 | } |
| 5351 | receipt_id.as_deref() |
| 5352 | } else { |
| 5353 | if is_block |
| 5354 | && is_auto_review_gate |
| 5355 | && let Some(ref child_id) = agent_id |
| 5356 | { |
| 5357 | let base_summary = |
| 5358 | action_summary.clone().unwrap_or_else(|| tool_name.clone()); |
| 5359 | let summary = format!("[sub-agent {child_id}] {base_summary}"); |
| 5360 | app.record_auto_review_blocked_receipt_for_agent( |
| 5361 | Some(child_id.clone()), |
| 5362 | None, |
| 5363 | tool_id.clone(), |
| 5364 | tool_name.clone(), |
| 5365 | gate.as_str().to_string(), |
| 5366 | verdict_label, |
| 5367 | rule.clone(), |
| 5368 | reason.clone(), |
| 5369 | None, |
| 5370 | summary, |
| 5371 | ); |
| 5372 | } |
| 5373 | None |
| 5374 | }; |
| 5375 | let receipt = crate::tui::gate_receipts::tool_gate_receipt_with_retry_info( |
| 5376 | app.ui_locale, |
| 5377 | &tool_name, |
| 5378 | gate, |
| 5379 | decision, |
| 5380 | risk.as_deref(), |
| 5381 | reviewer_model.as_deref(), |
| 5382 | &reason, |
| 5383 | receipt_hint_id, |
| 5384 | ); |
| 5385 | if let Some(agent_id) = agent_id { |
| 5386 | app.child_gate_receipts |
| 5387 | .entry(agent_id.clone()) |
| 5388 | .or_default() |
| 5389 | .push((tool_id, receipt)); |
| 5390 | if app |
| 5391 | .agent_focus |
| 5392 | .as_ref() |
| 5393 | .is_some_and(|focus| focus.is(&agent_id)) |
| 5394 | { |
| 5395 | crate::tui::agent_focus::refresh_focus(app); |
| 5396 | } |
| 5397 | } else { |
| 5398 | app.pending_gate_receipts.push((tool_id, receipt)); |
| 5399 | } |
| 5400 | } |
| 5401 | EngineEvent::AutoReviewPaused { |
| 5402 | reason, |
| 5403 | approval_mode, |
| 5404 | } => { |
| 5405 | app.sync_auto_review_paused_posture(approval_mode); |
| 5406 | let notice = crate::tui::gate_receipts::auto_review_paused_receipt( |
| 5407 | app.ui_locale, |
| 5408 | &reason, |
| 5409 | ); |
| 5410 | app.add_message(HistoryCell::System { |
| 5411 | content: notice.clone(), |
| 5412 | }); |
| 5413 | app.push_status_toast_record( |
| 5414 | StatusToast::new(notice, StatusToastLevel::Warning, Some(12_000)) |
| 5415 | .for_event("auto-review-paused"), |
| 5416 | ); |
| 5417 | } |
| 5418 | } |
| 5419 | } |
| 5420 | } |
| 5421 | if let Some(rollback) = fallback_after_engine_error { |
| 5422 | apply_provider_fallback_switch(app, &mut engine_handle, config, rollback).await; |
| 5423 | } |
| 5424 | if let Some(rollback_warning) = respawn_after_provider_rollback { |
| 5425 | replace_tui_engine(app, config, &mut engine_handle).await; |
| 5426 | if !app.api_messages.is_empty() { |
| 5427 | let _ = engine_handle |
| 5428 | .send(Op::SyncSession { |
| 5429 | expected: None, |
| 5430 | control: app.session_sync_control(), |
| 5431 | session_id: app.current_session_id.clone(), |
| 5432 | messages: app.api_messages.as_ref().clone(), |
| 5433 | system_prompt: app.system_prompt.clone(), |
| 5434 | system_prompt_override: false, |
| 5435 | model: app.model.clone(), |
| 5436 | workspace: app.workspace.clone(), |
| 5437 | mode: app.mode, |
| 5438 | agent_preset: app.agent_preset(), |
| 5439 | }) |
| 5440 | .await; |
| 5441 | } |
| 5442 | let _ = engine_handle |
| 5443 | .send(Op::SetCompaction { |
| 5444 | config: app.compaction_config(), |
| 5445 | }) |
| 5446 | .await; |
| 5447 | app.show_event_notice(rollback_warning, StatusToastLevel::Warning); |
| 5448 | } |
| 5449 | let current_skill_epoch = codewhale_engine::extension_host::command::epoch(); |
| 5450 | if skill_cache_refresh |
| 5451 | .as_ref() |
| 5452 | .is_some_and(|(_, job)| job.is_finished()) |
| 5453 | { |
| 5454 | let (scope, job) = skill_cache_refresh.take().expect("finished skill refresh"); |
| 5455 | if let Ok(skills) = job.await |
| 5456 | && app.install_skill_cache_if_current(&scope, current_skill_epoch, skills) |
| 5457 | { |
| 5458 | skill_registry_epoch = Some(scope.epoch); |
| 5459 | } |
| 5460 | } |
| 5461 | if skill_cache_refresh.is_none() && skill_registry_epoch != Some(current_skill_epoch) { |
| 5462 | let scope = app.skill_cache_scope(current_skill_epoch); |
| 5463 | let scan = scope.clone(); |
| 5464 | let policy = codewhale_plugins::activation::extension_host_policy_enabled(); |
| 5465 | #[cfg(test)] |
| 5466 | let env_scope = crate::test_support::env_scope_ticket(); |
| 5467 | #[cfg(test)] |
| 5468 | let manager = codewhale_engine::extension_host::manager(); |
| 5469 | let job = tokio::task::spawn_blocking(move || { |
| 5470 | #[cfg(test)] |
| 5471 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 5472 | #[cfg(test)] |
| 5473 | let _manager = codewhale_engine::extension_host::TestManagerGuard::install(manager); |
| 5474 | let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy); |
| 5475 | codewhale_skills::clear_skill_discovery_cache(); |
| 5476 | App::discover_cached_skills( |
| 5477 | &scan.workspace, |
| 5478 | &scan.skills_dir, |
| 5479 | &scan.config, |
| 5480 | &scan.plugins, |
| 5481 | ) |
| 5482 | }); |
| 5483 | skill_cache_refresh = Some((scope, job)); |
| 5484 | } |
| 5485 | if commit_streaming_display_tick(app, &mut stream_display_clock, Instant::now()) { |
| 5486 | transcript_batch_updated = true; |
| 5487 | } |
| 5488 | // #4022: `/lane interrupt` answers immediately with a queued receipt, |
| 5489 | // which is not an outcome. The terminal receipt lands here, under the |
| 5490 | // ticket the composer printed, so a queued write is never left looking |
| 5491 | // like it succeeded. Drain is non-blocking: it only takes the queue |
| 5492 | // mutex, and a poisoned one yields nothing rather than panicking the |
| 5493 | // event loop. |
| 5494 | for receipt in app.lane_control.drain_completed() { |
| 5495 | app.add_message(HistoryCell::System { |
| 5496 | content: receipt.render(), |
| 5497 | }); |
| 5498 | transcript_batch_updated = true; |
| 5499 | } |
| 5500 | if drain_runtime_store_failures(app, &mut runtime_event_rx) { |
| 5501 | transcript_batch_updated = true; |
| 5502 | } |
| 5503 | if transcript_batch_updated { |
| 5504 | app.mark_history_updated(); |
| 5505 | } |
| 5506 | if received_engine_event { |
| 5507 | // ListSubAgents can wait behind the parent's active turn. The |
| 5508 | // open register must also reflect the already-received, session- |
| 5509 | // scoped lifecycle events, using the same projection as opening it. |
| 5510 | if app.view_stack.contains_kind(ModalKind::SubAgents) { |
| 5511 | let agents = subagent_view_agents(app, &app.subagent_cache); |
| 5512 | app.view_stack.update_subagents(&agents); |
| 5513 | } |
| 5514 | app.needs_redraw = true; |
| 5515 | } |
| 5516 | if subagent_list_refresh_requested { |
| 5517 | pending_subagent_list_refresh = true; |
| 5518 | } |
| 5519 | // #freeze: one trailing-edge sub-agent list refresh per drain, no |
| 5520 | // matter how many spawn/complete/mailbox events arrived this batch. |
| 5521 | // #3837: keep a sticky pending bit when the op channel is full so a |
| 5522 | // terminal lifecycle event cannot permanently lose the authoritative |
| 5523 | // ListSubAgents refresh. |
| 5524 | if pending_subagent_list_refresh { |
| 5525 | match engine_handle.try_send(Op::ListSubAgents) { |
| 5526 | Ok(()) => pending_subagent_list_refresh = false, |
| 5527 | Err(err) => { |
| 5528 | if err |
| 5529 | .downcast_ref::<tokio::sync::mpsc::error::TrySendError<Op>>() |
| 5530 | .is_some_and(|send_err| { |
| 5531 | matches!(send_err, tokio::sync::mpsc::error::TrySendError::Closed(_)) |
| 5532 | }) |
| 5533 | { |
| 5534 | pending_subagent_list_refresh = false; |
| 5535 | } |
| 5536 | } |
| 5537 | } |
| 5538 | } |
| 5539 | |
| 5540 | if let Some(next) = queued_to_send { |
| 5541 | let _ = dispatch_user_message_with_recovery( |
| 5542 | app, |
| 5543 | config, |
| 5544 | &engine_handle, |
| 5545 | next, |
| 5546 | DispatchRecovery::Queued { |
| 5547 | restore_index: None, |
| 5548 | was_held: false, |
| 5549 | }, |
| 5550 | ) |
| 5551 | .await; |
| 5552 | |
| 5553 | app.needs_redraw = true; |
| 5554 | } |
| 5555 | |
| 5556 | // Avoid cloning the queued messages/draft every loop iteration |
| 5557 | // (~20-40 Hz) purely for change detection. When the queue is empty and |
| 5558 | // was empty last time — the overwhelmingly common case — there is |
| 5559 | // nothing to compare, so skip the clone entirely. A multi-KB queued |
| 5560 | // draft is only cloned while one is actually pending. |
| 5561 | let queue_now_empty = offline_queue_is_empty(app); |
| 5562 | if !(queue_now_empty && last_queue_was_empty) { |
| 5563 | let queue_state = offline_queue_projection(app); |
| 5564 | if queue_state != last_queue_state { |
| 5565 | persist_offline_queue_state(app); |
| 5566 | last_queue_state = queue_state; |
| 5567 | app.needs_redraw = true; |
| 5568 | } |
| 5569 | last_queue_was_empty = queue_now_empty; |
| 5570 | } |
| 5571 | |
| 5572 | let mut help_key_motion = false; |
| 5573 | if !app.view_stack.is_empty() { |
| 5574 | let tick = app.view_stack.tick(); |
| 5575 | help_key_motion = tick.redraw && app.view_stack.top_kind() == Some(ModalKind::Help); |
| 5576 | if tick.redraw { |
| 5577 | app.needs_redraw = true; |
| 5578 | } |
| 5579 | if !tick.events.is_empty() |
| 5580 | && handle_view_events_boxed(terminal, app, config, &mut engine_handle, tick.events) |
| 5581 | .await? |
| 5582 | { |
| 5583 | return Ok(()); |
| 5584 | } |
| 5585 | } |
| 5586 | |
| 5587 | let has_running_agents = running_agent_count(app) > 0; |
| 5588 | let turn_heartbeat = engine_handle.turn_heartbeat().snapshot(); |
| 5589 | if reconcile_turn_liveness_supervised(app, Instant::now(), &turn_heartbeat, &engine_handle) |
| 5590 | { |
| 5591 | app.needs_redraw = true; |
| 5592 | } |
| 5593 | maybe_throttled_recovery_snapshot(app, Instant::now(), &mut last_recovery_snapshot_at); |
| 5594 | let history_has_live_motion = history_has_live_motion(&app.history); |
| 5595 | crate::tui::pet_watch::tick(app, Instant::now()); |
| 5596 | crate::tui::herdr::sync( |
| 5597 | crate::tui::underwater::ShellPhase::from_app(app), |
| 5598 | app.current_session_id.as_deref(), |
| 5599 | ); |
| 5600 | let active_cell_has_live_motion = active_cell_has_live_motion(app); |
| 5601 | let translation_placeholder_has_live_motion = app.translation_enabled |
| 5602 | && (pending_thinking_translations > 0 || app.streaming_thinking_active_entry.is_some()); |
| 5603 | // The ordinary terminal stays quiet. Only the underwater theme earns |
| 5604 | // ambient redraws; its column can breathe at any usable size and its |
| 5605 | // life needs the collision-safe water budget. |
| 5606 | let underwater_atmosphere_enabled = app.theme_id == codewhale_palette::ThemeId::Underwater; |
| 5607 | let deepsea_field_breathes = underwater_atmosphere_enabled |
| 5608 | && crate::tui::ocean::OceanRamp::for_theme(&app.ui_theme).is_some(); |
| 5609 | let browsing_history = !app.viewport.transcript_scroll.is_at_tail(); |
| 5610 | let empty_water_visible = app.history.is_empty() |
| 5611 | && app |
| 5612 | .active_cell |
| 5613 | .as_ref() |
| 5614 | .is_none_or(crate::tui::active_cell::ActiveCell::is_empty) |
| 5615 | && !app.is_loading; |
| 5616 | // A paused terminal owns the eye. Modal/launch/onboarding visibility |
| 5617 | // and attention stillness are centralized in the shell motion gate. |
| 5618 | let underwater_surface_obscured = event_broker.is_paused(); |
| 5619 | let underwater_motion_visible = underwater_motion_surface_visible( |
| 5620 | app.viewport.last_transcript_area, |
| 5621 | underwater_atmosphere_enabled, |
| 5622 | deepsea_field_breathes, |
| 5623 | empty_water_visible, |
| 5624 | underwater_surface_obscured, |
| 5625 | ); |
| 5626 | let shell_motion_enabled = crate::tui::underwater::decorative_shell_motion_enabled(app); |
| 5627 | let shell_phase_working = matches!( |
| 5628 | crate::tui::underwater::ShellPhase::from_app(app), |
| 5629 | crate::tui::underwater::ShellPhase::Working |
| 5630 | | crate::tui::underwater::ShellPhase::Verifying |
| 5631 | ); |
| 5632 | // A fully idle shell settles: no live turn, no sub-agents, no active |
| 5633 | // durable tasks, completion exhale finished, and the user isn't |
| 5634 | // browsing. After a short grace the aquarium stops requesting frames |
| 5635 | // and the scene is genuinely still until real activity resumes |
| 5636 | // (owner pain, captains-log #16). |
| 5637 | let durable_tasks_active = has_live_durable_tasks(app); |
| 5638 | let ambient_busy = shell_phase_working |
| 5639 | || app.turn_started_at.is_some() |
| 5640 | || has_running_agents |
| 5641 | || durable_tasks_active |
| 5642 | || app.is_loading |
| 5643 | || app.ocean_completion_started_at.is_some_and(|started| { |
| 5644 | started.elapsed() |
| 5645 | < Duration::from_millis(crate::tui::ocean::COMPLETION_SETTLE_MS as u64) |
| 5646 | }); |
| 5647 | let ambient_settled = app.ambient_idle_settled(ambient_busy, Instant::now()); |
| 5648 | let underwater_ambient_motion = shell_motion_enabled |
| 5649 | && underwater_motion_visible |
| 5650 | && !ambient_settled |
| 5651 | && !browsing_history |
| 5652 | && crate::tui::underwater::ambient_motion_terminal_supported(app) |
| 5653 | && (shell_phase_working || empty_water_visible); |
| 5654 | let underwater_completion_motion = shell_motion_enabled |
| 5655 | && underwater_atmosphere_enabled |
| 5656 | && !underwater_surface_obscured |
| 5657 | && !browsing_history |
| 5658 | && matches!(app.runtime_turn_status.as_deref(), Some("completed")) |
| 5659 | && app.ocean_completion_started_at.is_some_and(|started| { |
| 5660 | started.elapsed() |
| 5661 | < Duration::from_millis(crate::tui::ocean::COMPLETION_SETTLE_MS as u64) |
| 5662 | }); |
| 5663 | // The launch screen has no transcript widget to drive the ambient |
| 5664 | // clock, so it asks for frames itself: while the mark surfaces or |
| 5665 | // the card dissolves, and while the underwater field is alive |
| 5666 | // (settling on the same idle grace as the transcript's empty water). |
| 5667 | let launch_motion = crate::tui::underwater::launch_motion_active( |
| 5668 | app, |
| 5669 | underwater_surface_obscured, |
| 5670 | ambient_settled, |
| 5671 | ); |
| 5672 | let status_motion = should_tick_status_animation( |
| 5673 | app, |
| 5674 | has_running_agents, |
| 5675 | history_has_live_motion, |
| 5676 | active_cell_has_live_motion, |
| 5677 | translation_placeholder_has_live_motion, |
| 5678 | ); |
| 5679 | // Content-driven cadence: atmosphere rate when only ocean life moves; |
| 5680 | // full interactive rate while streaming, selecting, typing, or hovering. |
| 5681 | // Read once here so the animation tick and the frame limiter below |
| 5682 | // agree on the same tier for this frame. |
| 5683 | let cadence_tier = transcript_cadence_tier(app, has_running_agents); |
| 5684 | let underwater_life_motion = |
| 5685 | underwater_life_motion_requested(app, underwater_surface_obscured, ambient_settled); |
| 5686 | let underwater_life_only = underwater_life_motion |
| 5687 | && !(status_motion |
| 5688 | || underwater_ambient_motion |
| 5689 | || underwater_completion_motion |
| 5690 | || launch_motion); |
| 5691 | let underwater_motion = underwater_ambient_motion |
| 5692 | || underwater_completion_motion |
| 5693 | || launch_motion |
| 5694 | || underwater_life_motion; |
| 5695 | let animation_active = status_motion || underwater_motion || help_key_motion; |
| 5696 | let animation_interval = Duration::from_millis(if underwater_life_only { |
| 5697 | crate::tui::ocean::AMBIENT_LIFE_INTERVAL_MS |
| 5698 | } else { |
| 5699 | animation_interval_ms(app, status_motion, underwater_motion, cadence_tier) |
| 5700 | }); |
| 5701 | let animation_interval = if help_key_motion { |
| 5702 | animation_interval.min(Duration::from_millis(32)) |
| 5703 | } else { |
| 5704 | animation_interval |
| 5705 | }; |
| 5706 | let idle_facts = IdleFacts { |
| 5707 | has_running_agents, |
| 5708 | animation_active: animation_active |
| 5709 | && animation_interval < Duration::from_millis(UI_QUIESCENT_POLL_MS), |
| 5710 | input_pending: !pending_terminal_events.is_empty(), |
| 5711 | pending_engine_op: pending_subagent_list_refresh, |
| 5712 | }; |
| 5713 | { |
| 5714 | let tick_now = Instant::now(); |
| 5715 | idle_clock.settle(app, &idle_facts, tick_now, engine_event_seen, status_motion); |
| 5716 | // The git cache TTL follows the probe's input and engine-event |
| 5717 | // clock, set every iteration so a stale back-off can never outlive |
| 5718 | // the activity that ended it (a turn does not reach the probe |
| 5719 | // block below). |
| 5720 | codewhale_engine::git_status::set_probe_backoff( |
| 5721 | codewhale_engine::git_status::probe_is_backed_off(git_probe_quiet_for( |
| 5722 | app, |
| 5723 | idle_clock.input_quiet_for(tick_now), |
| 5724 | )), |
| 5725 | ); |
| 5726 | } |
| 5727 | let motion_policy = app.motion_policy(); |
| 5728 | if animation_active && last_status_frame.elapsed() >= animation_interval { |
| 5729 | let translation_animated = streaming_thinking::animate_pending_translation( |
| 5730 | app, |
| 5731 | pending_thinking_translations > 0, |
| 5732 | ); |
| 5733 | if !matches!(motion_policy.mode(), MotionMode::Still) |
| 5734 | && (history_has_live_motion || active_cell_has_live_motion) |
| 5735 | && last_live_motion_mark.elapsed() |
| 5736 | >= Duration::from_millis(UI_STATUS_ANIMATION_MS - UI_ACTIVITY_ANIMATION_MS / 2) |
| 5737 | { |
| 5738 | last_live_motion_mark = Instant::now(); |
| 5739 | if translation_animated { |
| 5740 | if history_has_live_motion { |
| 5741 | app.mark_live_history_motion_updated(); |
| 5742 | } |
| 5743 | } else { |
| 5744 | app.mark_live_motion_updated(); |
| 5745 | } |
| 5746 | } |
| 5747 | // Coalesce decorative animation wakes through the shared requester. |
| 5748 | // Reduced/Still drop these requests; state-change redraws still set |
| 5749 | // needs_redraw directly below for phase/working chrome. |
| 5750 | frame_requester.request_frame(Instant::now(), motion_policy); |
| 5751 | if frame_requester.take_due(Instant::now(), motion_policy) |
| 5752 | || !motion_policy.should_request_animation_frames() |
| 5753 | { |
| 5754 | // Full: emit only when the requester fires. Reduced/Still: keep |
| 5755 | // the existing calm redraw so working/phase chrome stays truthful |
| 5756 | // without decorative spin (TUI-DOG-008). |
| 5757 | app.needs_redraw = true; |
| 5758 | } |
| 5759 | last_status_frame = Instant::now(); |
| 5760 | } |
| 5761 | if animation_active { |
| 5762 | // Aim the poll at the next tick. Without a deadline the tick only |
| 5763 | // ran when the idle/active poll happened to return, which |
| 5764 | // quantized an 80 ms cadence to 96 ms and a 120 ms one to 144 ms. |
| 5765 | frame_requester.request_at( |
| 5766 | Instant::now(), |
| 5767 | last_status_frame + animation_interval, |
| 5768 | motion_policy, |
| 5769 | ); |
| 5770 | } else { |
| 5771 | // Consume a deadline armed before motion stopped so an orphaned |
| 5772 | // request cannot hold the poll timeout at zero. |
| 5773 | let _ = frame_requester.take_due(Instant::now(), motion_policy); |
| 5774 | } |
| 5775 | |
| 5776 | if event_broker.is_paused() { |
| 5777 | let grace_active = terminal_paused_at |
| 5778 | .map(|paused_at| paused_at.elapsed() < Duration::from_millis(500)) |
| 5779 | .unwrap_or(false); |
| 5780 | if terminal_pause_has_live_owner(app) || grace_active { |
| 5781 | tokio::time::sleep(std::time::Duration::from_millis(50)).await; |
| 5782 | continue; |
| 5783 | } |
| 5784 | resume_terminal( |
| 5785 | terminal, |
| 5786 | app.use_mouse_capture, |
| 5787 | app.use_bracketed_paste, |
| 5788 | app.synchronized_output_enabled, |
| 5789 | )?; |
| 5790 | event_broker.resume_events(); |
| 5791 | terminal_input.resume_after_child_terminal(); |
| 5792 | terminal_paused_at = None; |
| 5793 | app.show_event_notice( |
| 5794 | "Terminal controls restored".to_string(), |
| 5795 | StatusToastLevel::Info, |
| 5796 | ); |
| 5797 | app.needs_redraw = true; |
| 5798 | terminal_repaint = FrameRepaint::Clear; |
| 5799 | } |
| 5800 | |
| 5801 | collect_pending_terminal_events(&terminal_input, &mut pending_terminal_events)?; |
| 5802 | let paste_now = pending_terminal_events |
| 5803 | .front() |
| 5804 | .map_or_else(Instant::now, |event| event.observed_at); |
| 5805 | flush_paste_burst_before_composer(app, paste_now); |
| 5806 | let now = Instant::now(); |
| 5807 | crate::tui::work_surface::poll_terminal(app); |
| 5808 | app.prune_expired_status_toasts(Instant::now()); |
| 5809 | // Drain background-LLM cost (compaction summaries, seam |
| 5810 | // recompaction, cycle briefings) accumulated since the last |
| 5811 | // tick and fold it into the session-cost counter (#526). |
| 5812 | // Background callers populate `cost_status::report`; we sweep |
| 5813 | // the pool once per loop iteration so the footer chip matches |
| 5814 | // the DeepSeek website's billing. |
| 5815 | // Money and its completeness are drained as one value, so the footer |
| 5816 | // total and the `/cost` coverage line can never come from different |
| 5817 | // observations of the pool (#4318). |
| 5818 | let pending_bg = codewhale_engine::cost_status::drain(); |
| 5819 | if !pending_bg.is_empty() { |
| 5820 | let runtime_usage_arrived = app.absorb_pending_background_cost(&pending_bg); |
| 5821 | if pending_bg.estimate.is_positive() { |
| 5822 | app.needs_redraw = true; |
| 5823 | } |
| 5824 | // Runtime-owned child usage can land after the parent's |
| 5825 | // TurnComplete snapshot. Queue a fresh snapshot from the same |
| 5826 | // drained money+identity batch so an immediate reload agrees with |
| 5827 | // the live footer and worker record. |
| 5828 | if runtime_usage_arrived |
| 5829 | && !app.dispatch_in_flight |
| 5830 | && let Ok(manager) = SessionManager::default_location() |
| 5831 | && let Ok(session) = build_session_snapshot(app, &manager) |
| 5832 | { |
| 5833 | app.set_current_session_id(Some(session.metadata.id.clone())); |
| 5834 | if !super::session_state::try_persist_session( |
| 5835 | app, |
| 5836 | PersistRequest::SessionSnapshot(session), |
| 5837 | ) { |
| 5838 | tracing::warn!( |
| 5839 | "late usage snapshot was not queued; canonical usage evidence retained" |
| 5840 | ); |
| 5841 | } |
| 5842 | } |
| 5843 | } |
| 5844 | // Drain completed file-tree walks (initial build / expands) so the |
| 5845 | // spliced children repaint without waiting for an input event (#3900). |
| 5846 | if let Some(tree) = app.file_tree.as_mut() |
| 5847 | && tree.poll_background() |
| 5848 | { |
| 5849 | app.needs_redraw = true; |
| 5850 | } |
| 5851 | // Completion discovery is serialized off-thread. Polling is |
| 5852 | // non-blocking and makes a finished initial `@` scan visible even |
| 5853 | // after the user stops typing (#4365). |
| 5854 | if crate::tui::file_mention::poll_background_mention_discovery(app) { |
| 5855 | app.needs_redraw = true; |
| 5856 | } |
| 5857 | // Expire the "Press Ctrl+C again to quit" prompt silently after its |
| 5858 | // window. Triggers a redraw if the prompt was visible. |
| 5859 | app.tick_quit_armed(); |
| 5860 | app.tick_receipt(); |
| 5861 | crate::tui::footer_ui::maybe_log_provider_wait_incident(app); |
| 5862 | // While the user is drag-selecting past the transcript edge, advance |
| 5863 | // the viewport on a fixed cadence and extend the selection head so a |
| 5864 | // long passage can be selected in one drag (#1163). |
| 5865 | tick_selection_autoscroll(app); |
| 5866 | let allow_workspace_context_refresh = |
| 5867 | !app.is_loading && !has_running_agents && !app.is_compacting && !app.is_purging; |
| 5868 | workspace_context::refresh_if_needed(app, now, allow_workspace_context_refresh); |
| 5869 | // Native git chrome: at most one background probe per interval, never |
| 5870 | // on the render path. While a turn is live it waits, unless the Git |
| 5871 | // view is showing: that view is the live repository state (#6565). |
| 5872 | // Every probe is about a dozen `git` processes, so an untouched |
| 5873 | // session backs off to a slow cadence and the next input or engine |
| 5874 | // event (a tool finishing, say) brings the fast one back (#6728). |
| 5875 | if git_probe_allowed(app, allow_workspace_context_refresh) { |
| 5876 | static GIT_PROBE_LOCK: std::sync::OnceLock<std::sync::Mutex<Option<Instant>>> = |
| 5877 | std::sync::OnceLock::new(); |
| 5878 | let slot = GIT_PROBE_LOCK.get_or_init(|| std::sync::Mutex::new(None)); |
| 5879 | let quiet_for = git_probe_quiet_for(app, idle_clock.input_quiet_for(now)); |
| 5880 | let should_probe = slot |
| 5881 | .lock() |
| 5882 | .map(|mut last| { |
| 5883 | let due = codewhale_engine::git_status::probe_due( |
| 5884 | last.map(|t| t.elapsed()), |
| 5885 | quiet_for, |
| 5886 | ); |
| 5887 | if due { |
| 5888 | *last = Some(Instant::now()); |
| 5889 | } |
| 5890 | due |
| 5891 | }) |
| 5892 | .unwrap_or(false); |
| 5893 | if should_probe { |
| 5894 | let workspace = app.workspace.clone(); |
| 5895 | std::thread::spawn(move || { |
| 5896 | codewhale_engine::git_status::refresh_if_stale(&workspace); |
| 5897 | }); |
| 5898 | } |
| 5899 | } |
| 5900 | |
| 5901 | // Draw is gated by the frame-rate limiter (120 FPS cap). When a |
| 5902 | // redraw is needed but the limiter says we're inside the cooldown |
| 5903 | // window, leave `needs_redraw = true` and shorten the poll timeout |
| 5904 | // so the loop wakes up exactly when drawing is allowed. |
| 5905 | |
| 5906 | // Central motion contract: frame cap and stream catch-up both read |
| 5907 | // from MotionPolicy so reduced motion stays semantically calm (not a |
| 5908 | // slow typewriter) and Full motion keeps the steady display clock. |
| 5909 | let motion_policy = app.motion_policy(); |
| 5910 | frame_rate_limiter.set_low_motion(motion_policy.uses_constrained_frame_rate()); |
| 5911 | stream_display_clock.set_allow_catch_up(motion_policy.allows_catch_up_bursts()); |
| 5912 | |
| 5913 | // The draw limiter follows the same content-driven tier the |
| 5914 | // animation tick above read for this frame. |
| 5915 | { |
| 5916 | use crate::tui::display_refresh::{ |
| 5917 | content_driven_draw_interval, probe_display_refresh, |
| 5918 | }; |
| 5919 | let probe = probe_display_refresh(); |
| 5920 | frame_rate_limiter.set_adaptive_interval(Some(content_driven_draw_interval( |
| 5921 | cadence_tier, |
| 5922 | probe.hz, |
| 5923 | motion_policy.uses_constrained_frame_rate(), |
| 5924 | ))); |
| 5925 | } |
| 5926 | |
| 5927 | app.settle_stale_mcp_boot_prediction(); |
| 5928 | |
| 5929 | // An image preview decoded since the last frame needs a repaint of its |
| 5930 | // own: the frame that handled the paste was already drawn when the |
| 5931 | // worker finished, and an idle session may not draw again for a long |
| 5932 | // time. Polling here, before the draw decision, makes the flag survive |
| 5933 | // the `needs_redraw = false` that follows every paint. |
| 5934 | if app.attachment_preview.poll() { |
| 5935 | app.needs_redraw = true; |
| 5936 | } |
| 5937 | |
| 5938 | let draw_wait = if app.needs_redraw { |
| 5939 | frame_rate_limiter.time_until_next_draw(now) |
| 5940 | } else { |
| 5941 | None |
| 5942 | }; |
| 5943 | // Merge the per-app full-repaint hint (set by theme switches) |
| 5944 | // into the loop-level flag before the draw decision. |
| 5945 | if app.force_next_full_repaint { |
| 5946 | terminal_repaint = FrameRepaint::Clear; |
| 5947 | app.force_next_full_repaint = false; |
| 5948 | } |
| 5949 | if app.needs_redraw && draw_wait.is_none() && !terminal_unfocused { |
| 5950 | draw_app_frame_inner(terminal, app, config, terminal_repaint)?; |
| 5951 | terminal_repaint = FrameRepaint::Diff; |
| 5952 | frame_rate_limiter.mark_emitted(Instant::now()); |
| 5953 | app.needs_redraw = false; |
| 5954 | if std::mem::take(&mut telemetry_notice_awaiting_render) { |
| 5955 | codewhale_engine::telemetry_notice::record_presented(); |
| 5956 | } |
| 5957 | } |
| 5958 | |
| 5959 | let mut poll_timeout = if (app.is_loading && !decision_prompt_waiting(app)) |
| 5960 | || has_running_agents |
| 5961 | || app.is_compacting |
| 5962 | || app.is_purging |
| 5963 | { |
| 5964 | Duration::from_millis(active_poll_ms(app)) |
| 5965 | } else { |
| 5966 | // Relaxes only once the UI has been quiescent and quiet for |
| 5967 | // `UI_QUIESCENT_AFTER` (#6728); every deadline below still |
| 5968 | // shortens it, and input returns the loop at once. |
| 5969 | idle_clock.poll(app, &idle_facts, now) |
| 5970 | }; |
| 5971 | if let Some(until_flush) = app.paste_burst_next_flush_delay_if_enabled(now) { |
| 5972 | poll_timeout = poll_timeout.min(until_flush); |
| 5973 | } |
| 5974 | if let Some(until_paste) = crate::tui::paste::pending_paste_poll_delay(app) { |
| 5975 | poll_timeout = poll_timeout.min(until_paste); |
| 5976 | } |
| 5977 | if let Some(until_draw) = draw_wait { |
| 5978 | poll_timeout = poll_timeout.min(until_draw); |
| 5979 | } |
| 5980 | if let Some(until_settle) = app.mcp_boot_prediction_due_in(now) { |
| 5981 | poll_timeout = poll_timeout.min(until_settle); |
| 5982 | } |
| 5983 | if let Some(until_stream_commit) = stream_display_clock.due_in(now) { |
| 5984 | poll_timeout = poll_timeout.min(until_stream_commit); |
| 5985 | } |
| 5986 | if let Some(until_anim) = frame_requester.due_in(now) { |
| 5987 | poll_timeout = poll_timeout.min(until_anim); |
| 5988 | } |
| 5989 | if let Some(until_pet) = app.pet_watch.next_frame_in(Instant::now()) { |
| 5990 | poll_timeout = poll_timeout.min(until_pet); |
| 5991 | } |
| 5992 | // While the quit-confirmation prompt is armed, ensure we wake up to |
| 5993 | // expire it on time even if no input event arrives. |
| 5994 | if let Some(deadline) = app.quit_armed_until { |
| 5995 | let remaining = deadline.saturating_duration_since(now); |
| 5996 | poll_timeout = poll_timeout.min(remaining.max(Duration::from_millis(50))); |
| 5997 | } |
| 5998 | // Drag-edge auto-scroll wakes the loop on its own cadence so the |
| 5999 | // viewport keeps advancing while the user holds the mouse outside |
| 6000 | // the transcript rect (#1163). |
| 6001 | if let Some(state) = app.viewport.selection_autoscroll { |
| 6002 | let remaining = state.next_tick.saturating_duration_since(now); |
| 6003 | poll_timeout = poll_timeout.min(remaining); |
| 6004 | } |
| 6005 | if app.work_surface.panel == crate::tui::work_surface::RailPanel::Terminal |
| 6006 | && app.work_surface.last_area.is_some() |
| 6007 | { |
| 6008 | poll_timeout = poll_timeout.min(Duration::from_millis(100)); |
| 6009 | } |
| 6010 | poll_timeout = clamp_event_poll_timeout(poll_timeout); |
| 6011 | |
| 6012 | // #549/#3216: give the engine task a scheduler turn before waiting on |
| 6013 | // the terminal-input channel. Crossterm's blocking poll/read runs on |
| 6014 | // `TerminalInputPump`, so engine floods cannot pin the OS input read. |
| 6015 | tokio::task::yield_now().await; |
| 6016 | |
| 6017 | let maybe_terminal_event = |
| 6018 | next_terminal_event(&terminal_input, &mut pending_terminal_events, poll_timeout)?; |
| 6019 | if maybe_terminal_event.is_some() { |
| 6020 | idle_clock.note_input(Instant::now()); |
| 6021 | } |
| 6022 | if maybe_terminal_event.is_none() { |
| 6023 | let now = Instant::now(); |
| 6024 | let input_stalled_for = terminal_input.stalled_for(now); |
| 6025 | if terminal_input_recovery_relevant(app, has_running_agents) |
| 6026 | && input_stalled_for >= TERMINAL_INPUT_STALL_TIMEOUT |
| 6027 | && now.duration_since(last_terminal_input_recovery) |
| 6028 | >= TERMINAL_INPUT_RECOVERY_COOLDOWN |
| 6029 | { |
| 6030 | tracing::warn!( |
| 6031 | stalled_ms = input_stalled_for.as_millis(), |
| 6032 | "terminal input pump heartbeat stalled; attempting terminal input recovery" |
| 6033 | ); |
| 6034 | recover_terminal_modes( |
| 6035 | terminal.backend_mut(), |
| 6036 | app.use_mouse_capture, |
| 6037 | app.use_bracketed_paste, |
| 6038 | ); |
| 6039 | match terminal_input.restart_detached() { |
| 6040 | Ok(()) => { |
| 6041 | tracing::info!("terminal input pump recovered"); |
| 6042 | } |
| 6043 | Err(err) => { |
| 6044 | tracing::warn!(error = %err, "failed to restart terminal input pump"); |
| 6045 | app.push_status_toast( |
| 6046 | "Terminal input stalled; recovery failed. Restart Codewhale if keys stop responding.", |
| 6047 | StatusToastLevel::Error, |
| 6048 | None, |
| 6049 | ); |
| 6050 | } |
| 6051 | } |
| 6052 | terminal_input.mark_alive(); |
| 6053 | last_terminal_input_recovery = now; |
| 6054 | if app.is_loading |
| 6055 | || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) |
| 6056 | { |
| 6057 | persist_recovery_snapshot(app); |
| 6058 | last_recovery_snapshot_at = Some(now); |
| 6059 | } |
| 6060 | terminal_repaint = FrameRepaint::Clear; |
| 6061 | app.needs_redraw = true; |
| 6062 | } |
| 6063 | } |
| 6064 | |
| 6065 | if let Some(observed_terminal_event) = maybe_terminal_event { |
| 6066 | let event_observed_at = observed_terminal_event.observed_at; |
| 6067 | let evt = observed_terminal_event.event; |
| 6068 | if app.launch.mark_reveal_started_at.is_some() |
| 6069 | && matches!(&evt, Event::Key(_) | Event::Paste(_) | Event::Resize(_, _)) |
| 6070 | { |
| 6071 | app.launch.mark_reveal_started_at = |
| 6072 | Some(Instant::now() - codewhale_ratatui::whale_motion::arrival::DURATION); |
| 6073 | } |
| 6074 | app.needs_redraw = true; |
| 6075 | if defer_frames_on_focus_loss { |
| 6076 | terminal_unfocused = next_unfocused(terminal_unfocused, &evt); |
| 6077 | } |
| 6078 | |
| 6079 | // Handle bracketed paste events |
| 6080 | if app.redaction_gate && app.onboarding == OnboardingState::None { |
| 6081 | if let Event::Mouse(mouse) = &evt { |
| 6082 | match mouse.kind { |
| 6083 | event::MouseEventKind::ScrollDown => app |
| 6084 | .redaction_gate_scroll |
| 6085 | .set(app.redaction_gate_scroll.get().saturating_add(1)), |
| 6086 | event::MouseEventKind::ScrollUp => app |
| 6087 | .redaction_gate_scroll |
| 6088 | .set(app.redaction_gate_scroll.get().saturating_sub(1)), |
| 6089 | _ => {} |
| 6090 | } |
| 6091 | app.needs_redraw = true; |
| 6092 | continue; |
| 6093 | } |
| 6094 | if matches!(&evt, Event::Paste(_)) { |
| 6095 | continue; |
| 6096 | } |
| 6097 | } |
| 6098 | if let Event::Paste(text) = &evt { |
| 6099 | if app.launch.return_to_session |
| 6100 | && app.view_stack.is_empty() |
| 6101 | && app.focus() != crate::tui::shell_key_routing::Focus::TerminalPanel |
| 6102 | { |
| 6103 | app.launch.dismiss(); |
| 6104 | } |
| 6105 | crate::tui::paste::handle_paste( |
| 6106 | app, |
| 6107 | crate::tui::paste::PasteSource::Terminal(text), |
| 6108 | ); |
| 6109 | continue; |
| 6110 | } |
| 6111 | |
| 6112 | // Re-establish terminal mode flags on focus-gain and recapture the |
| 6113 | // viewport without clearing it first. App-switching and interactive |
| 6114 | // handoffs can leave the host terminal scrolled away from row 0 |
| 6115 | // and (on macOS) can drop the keyboard, mouse-tracking, or |
| 6116 | // bracketed-paste modes — recover_terminal_modes() is the |
| 6117 | // canonical place those flags live. |
| 6118 | if terminal_event_needs_viewport_recapture(&evt) { |
| 6119 | let now = Instant::now(); |
| 6120 | if now.duration_since(last_focus_recovery) >= FOCUS_RECOVERY_DEBOUNCE { |
| 6121 | recover_terminal_modes( |
| 6122 | terminal.backend_mut(), |
| 6123 | app.use_mouse_capture, |
| 6124 | app.use_bracketed_paste, |
| 6125 | ); |
| 6126 | last_focus_recovery = now; |
| 6127 | } |
| 6128 | terminal_repaint = terminal_repaint.max(FrameRepaint::Recapture); |
| 6129 | app.needs_redraw = true; |
| 6130 | } |
| 6131 | if let Event::Resize(width, height) = evt { |
| 6132 | tracing::debug!(width, height, "Event::Resize received; clearing terminal"); |
| 6133 | // Drain any further Resize events queued in this poll cycle so we |
| 6134 | // act on the final size only, then issue a single clear + redraw. |
| 6135 | // crossterm coalesces some resize events but rapid drag-resizes |
| 6136 | // can still queue several; processing them all here avoids the |
| 6137 | // common "stale art on the right edge" symptom (#65) caused by |
| 6138 | // the diff renderer skipping cells that match a stale back |
| 6139 | // buffer between intermediate sizes. |
| 6140 | let (final_w, final_h) = coalesce_resize_burst( |
| 6141 | width, |
| 6142 | height, |
| 6143 | &terminal_input, |
| 6144 | &mut pending_terminal_events, |
| 6145 | )?; |
| 6146 | |
| 6147 | if final_w == 0 || final_h == 0 { |
| 6148 | tracing::debug!( |
| 6149 | final_w, |
| 6150 | final_h, |
| 6151 | "zero-size Resize event ignored while terminal is hidden/minimized" |
| 6152 | ); |
| 6153 | terminal_repaint = FrameRepaint::Clear; |
| 6154 | app.needs_redraw = true; |
| 6155 | continue; |
| 6156 | } |
| 6157 | |
| 6158 | // The event-reported size is authoritative (#582). Applying |
| 6159 | // it may clear the terminal, so defer it into the synchronized |
| 6160 | // draw instead of exposing an empty frame while resizing. |
| 6161 | app.handle_resize(final_w, final_h); |
| 6162 | // #6311: a resize that lands while unfocused records the size |
| 6163 | // but must not emit the frame — same deferral as zero-size. |
| 6164 | if terminal_unfocused { |
| 6165 | terminal_repaint = FrameRepaint::Clear; |
| 6166 | app.needs_redraw = true; |
| 6167 | continue; |
| 6168 | } |
| 6169 | draw_app_frame_inner(terminal, app, config, FrameRepaint::Clear)?; |
| 6170 | app.needs_redraw = false; |
| 6171 | continue; |
| 6172 | } |
| 6173 | |
| 6174 | if app.use_mouse_capture |
| 6175 | && let Event::Mouse(mouse) = evt |
| 6176 | { |
| 6177 | // Mouse interaction clears the ✅ completion marker. |
| 6178 | crate::tui::notifications::reset_title_on_interaction(); |
| 6179 | if should_drop_loading_mouse_motion(app, mouse) { |
| 6180 | continue; |
| 6181 | } |
| 6182 | // Fold the rest of this wheel gesture into one frame. |
| 6183 | let mouse = coalesce_scroll_burst( |
| 6184 | app, |
| 6185 | mouse, |
| 6186 | &terminal_input, |
| 6187 | &mut pending_terminal_events, |
| 6188 | )?; |
| 6189 | let events = handle_mouse_event(app, mouse, event_observed_at); |
| 6190 | if handle_view_events_boxed(terminal, app, config, &mut engine_handle, events) |
| 6191 | .await? |
| 6192 | { |
| 6193 | return Ok(()); |
| 6194 | } |
| 6195 | if app.pending_launch_action.is_none() { |
| 6196 | restore_launch_card_after_view_close(app); |
| 6197 | } |
| 6198 | if let Some(action) = app.pending_launch_action.take() |
| 6199 | && apply_launch_action(terminal, app, &mut engine_handle, config, action) |
| 6200 | .await? |
| 6201 | { |
| 6202 | return Ok(()); |
| 6203 | } |
| 6204 | if let Some(chord) = app.pending_composer_submit.take() { |
| 6205 | if dispatch_composer_submit( |
| 6206 | terminal, |
| 6207 | app, |
| 6208 | &mut engine_handle, |
| 6209 | config, |
| 6210 | chord, |
| 6211 | true, |
| 6212 | event_observed_at, |
| 6213 | ) |
| 6214 | .await? |
| 6215 | { |
| 6216 | return Ok(()); |
| 6217 | } |
| 6218 | app.needs_redraw = true; |
| 6219 | } |
| 6220 | if let Some(slot) = app.pending_hotbar_slot.take() |
| 6221 | && let Some(dispatch) = dispatch_hotbar_slot(app, config, slot)? |
| 6222 | { |
| 6223 | match dispatch { |
| 6224 | HotbarDispatch::Handled => app.needs_redraw = true, |
| 6225 | HotbarDispatch::AppAction(action) => { |
| 6226 | if apply_command_result( |
| 6227 | terminal, |
| 6228 | app, |
| 6229 | &mut engine_handle, |
| 6230 | config, |
| 6231 | commands::CommandResult::action(action), |
| 6232 | ) |
| 6233 | .await? |
| 6234 | { |
| 6235 | return Ok(()); |
| 6236 | } |
| 6237 | if let Err(err) = persist_pending_work_checkpoint(app).await { |
| 6238 | app.show_event_notice(format!( |
| 6239 | "Hotbar change applied, but its Work receipt is pending ({err})" |
| 6240 | ), StatusToastLevel::Warning); |
| 6241 | } |
| 6242 | app.needs_redraw = true; |
| 6243 | } |
| 6244 | } |
| 6245 | } |
| 6246 | continue; |
| 6247 | } |
| 6248 | |
| 6249 | // User interaction — clear the ✅ completion marker from the title. |
| 6250 | crate::tui::notifications::reset_title_on_interaction(); |
| 6251 | |
| 6252 | let Event::Key(mut key) = evt else { |
| 6253 | continue; |
| 6254 | }; |
| 6255 | |
| 6256 | // Windows Terminal consumes the key-down of any chord it handles |
| 6257 | // itself (its own paste action, and any global hotkey) and |
| 6258 | // forwards only the key-up. A release whose press was seen is the |
| 6259 | // second edge of a paste already handled. A release with no press |
| 6260 | // means the terminal took the chord and delivers any text itself, |
| 6261 | // so that edge only picks up an image the terminal cannot send. |
| 6262 | match key_shortcuts::paste_edge(&key, &mut app.paste_shortcut_press_seen) { |
| 6263 | key_shortcuts::PasteEdge::Route => {} |
| 6264 | key_shortcuts::PasteEdge::Ignore => continue, |
| 6265 | key_shortcuts::PasteEdge::ImageOnly => { |
| 6266 | crate::tui::paste::handle_paste( |
| 6267 | app, |
| 6268 | crate::tui::paste::PasteSource::ReleaseOnly, |
| 6269 | ); |
| 6270 | continue; |
| 6271 | } |
| 6272 | } |
| 6273 | |
| 6274 | // Normalize macOS modifiers: map SUPER (Cmd) to CONTROL so that |
| 6275 | // keyboard shortcuts work consistently across terminal emulators |
| 6276 | // (Terminal.app, iTerm2, Kitty, etc.) that may report different |
| 6277 | // modifier flags (#2938). The select-all chord is exempt: `Cmd+A` |
| 6278 | // must stay distinguishable from readline `Ctrl+A` (start of |
| 6279 | // input) on terminals that forward Cmd, so it keeps its SUPER |
| 6280 | // modifier and routes through `is_select_all_shortcut`. |
| 6281 | if !key_shortcuts::is_select_all_shortcut(&key) { |
| 6282 | let mapped = crate::tui::composer_ui::normalize_macos_modifiers(key.modifiers); |
| 6283 | key.modifiers = mapped; |
| 6284 | } |
| 6285 | |
| 6286 | // Normalize the raw Ctrl+C control byte (0x03) delivered in |
| 6287 | // PTY/raw-mode — and by some kitty-keyboard-protocol terminals — |
| 6288 | // to canonical Ctrl+C so the quit-arm flow always runs (#4090). |
| 6289 | normalize_raw_ctrl_c(&mut key); |
| 6290 | |
| 6291 | // The `[redaction] model_bound` opt-out gate owns every key until |
| 6292 | // it is answered, exactly like onboarding above. Enter never |
| 6293 | // confirms by reflex (same discipline as workspace trust): the |
| 6294 | // three explicit choices are advertised in the action rail. |
| 6295 | if app.redaction_gate && app.onboarding == OnboardingState::None { |
| 6296 | let gate_binding = shell_binding_for_key(app, &key); |
| 6297 | match key.code { |
| 6298 | KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 6299 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6300 | return Ok(()); |
| 6301 | } |
| 6302 | _ if gate_binding == Some(ShellBindingId::RedactionGateConfirm) => { |
| 6303 | if !app.redaction_gate_confirming { |
| 6304 | // First confirm only advances to the final |
| 6305 | // confirmation stage; nothing is persisted yet. |
| 6306 | app.retire_redaction_gate_notice(RedactionGateNotice::EnterGuidance); |
| 6307 | app.redaction_gate_confirming = true; |
| 6308 | app.redaction_gate_scroll.set(0); |
| 6309 | } else { |
| 6310 | match config.record_redaction_confirmation() { |
| 6311 | Ok(_) => { |
| 6312 | // The engine already spawned with masking on |
| 6313 | // (the unconfirmed safe default). Rebuild it so |
| 6314 | // its client picks up the confirmed opt-out. |
| 6315 | let mcp_handoff = retire_tui_engine(app, &engine_handle).await; |
| 6316 | engine_handle = |
| 6317 | spawn_tui_engine_with_session(app, config, mcp_handoff) |
| 6318 | .await?; |
| 6319 | app.retire_redaction_gate_notice( |
| 6320 | RedactionGateNotice::EnterGuidance, |
| 6321 | ); |
| 6322 | app.retire_redaction_gate_notice( |
| 6323 | RedactionGateNotice::WriteFailure, |
| 6324 | ); |
| 6325 | app.retire_action_notices(None); |
| 6326 | app.redaction_gate = false; |
| 6327 | app.redaction_gate_confirming = false; |
| 6328 | app.needs_redraw = true; |
| 6329 | } |
| 6330 | Err(err) => { |
| 6331 | tracing::warn!( |
| 6332 | "redaction confirmation could not be saved: {err}" |
| 6333 | ); |
| 6334 | app.push_status_toast_record( |
| 6335 | StatusToast::new( |
| 6336 | app.tr(MessageId::RedactionGateSaveFailed).into_owned(), |
| 6337 | StatusToastLevel::Error, |
| 6338 | None, |
| 6339 | ) |
| 6340 | .for_redaction_gate(RedactionGateNotice::WriteFailure), |
| 6341 | ); |
| 6342 | app.redaction_gate_scroll.set(0); |
| 6343 | } |
| 6344 | } |
| 6345 | } |
| 6346 | } |
| 6347 | _ if gate_binding == Some(ShellBindingId::RedactionGateKeepOrBack) => { |
| 6348 | if app.redaction_gate_confirming { |
| 6349 | // Second-stage "back": return to the first stage |
| 6350 | // without recording anything. |
| 6351 | app.retire_redaction_gate_notice(RedactionGateNotice::EnterGuidance); |
| 6352 | app.redaction_gate_confirming = false; |
| 6353 | app.redaction_gate_scroll.set(0); |
| 6354 | } else { |
| 6355 | // Keep masking on for this launch. Nothing is |
| 6356 | // persisted and no config file is rewritten; |
| 6357 | // because the config field still requests |
| 6358 | // "disabled", the next launch asks again. |
| 6359 | app.retire_redaction_gate_notice(RedactionGateNotice::EnterGuidance); |
| 6360 | app.retire_redaction_gate_notice(RedactionGateNotice::WriteFailure); |
| 6361 | app.redaction_gate = false; |
| 6362 | app.needs_redraw = true; |
| 6363 | } |
| 6364 | } |
| 6365 | _ if gate_binding == Some(ShellBindingId::RedactionGateQuit) => { |
| 6366 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6367 | return Ok(()); |
| 6368 | } |
| 6369 | // Esc on the final-confirmation stage steps back to the |
| 6370 | // first stage (the user was mid-decision); on the first |
| 6371 | // stage it quits, matching the trust screen. |
| 6372 | KeyCode::Esc if app.redaction_gate_confirming => { |
| 6373 | app.retire_redaction_gate_notice(RedactionGateNotice::EnterGuidance); |
| 6374 | app.redaction_gate_confirming = false; |
| 6375 | app.redaction_gate_scroll.set(0); |
| 6376 | } |
| 6377 | KeyCode::Esc => { |
| 6378 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6379 | return Ok(()); |
| 6380 | } |
| 6381 | KeyCode::Enter => { |
| 6382 | app.push_status_toast_record( |
| 6383 | StatusToast::new( |
| 6384 | app.tr(MessageId::RedactionGateEnterHint).into_owned(), |
| 6385 | StatusToastLevel::Info, |
| 6386 | Some(12_000), |
| 6387 | ) |
| 6388 | .for_redaction_gate(RedactionGateNotice::EnterGuidance), |
| 6389 | ); |
| 6390 | app.redaction_gate_scroll.set(0); |
| 6391 | } |
| 6392 | KeyCode::Down | KeyCode::PageDown |
| 6393 | if gate_binding == Some(ShellBindingId::RedactionGateScroll) => |
| 6394 | { |
| 6395 | app.redaction_gate_scroll |
| 6396 | .set(app.redaction_gate_scroll.get().saturating_add(1)) |
| 6397 | } |
| 6398 | KeyCode::Up | KeyCode::PageUp |
| 6399 | if gate_binding == Some(ShellBindingId::RedactionGateScroll) => |
| 6400 | { |
| 6401 | app.redaction_gate_scroll |
| 6402 | .set(app.redaction_gate_scroll.get().saturating_sub(1)) |
| 6403 | } |
| 6404 | KeyCode::Home => app.redaction_gate_scroll.set(0), |
| 6405 | KeyCode::End => app.redaction_gate_scroll.set(usize::MAX), |
| 6406 | _ => {} |
| 6407 | } |
| 6408 | app.needs_redraw = true; |
| 6409 | submit_initial_input_if_ready(app, config, &engine_handle).await?; |
| 6410 | continue; |
| 6411 | } |
| 6412 | |
| 6413 | // Login cancellation precedes modal/focus dispatch: Extensions |
| 6414 | // must not consume the Esc promised by the authorization notice. |
| 6415 | if handle_mcp_login_key(app, &key) { |
| 6416 | continue; |
| 6417 | } |
| 6418 | |
| 6419 | // A route change made in-session is temporary and stays that way |
| 6420 | // until the user EXPLICITLY persists it with a command |
| 6421 | // (/fleet save updates the selected Fleet, /fleet save-as saves a |
| 6422 | // new Fleet, /model save-default remembers the startup default). |
| 6423 | // Nothing here intercepts keys: a scripted or automated terminal |
| 6424 | // types exactly what it types, and plain typing can never trigger |
| 6425 | // a fleet write by accident. |
| 6426 | |
| 6427 | // Decision prompts keep their ordinary option/typing keys while |
| 6428 | // explicit transcript navigation reviews the evidence above them |
| 6429 | // (#4371, #6045). Bare arrows still belong to the question sheet. |
| 6430 | if handle_prompt_transcript_key(app, &key) { |
| 6431 | continue; |
| 6432 | } |
| 6433 | |
| 6434 | // The Ocean work surface is a real focus owner. Route its keys |
| 6435 | // before global transcript/composer navigation so PageUp/Down, |
| 6436 | // Home/End, arrows, and row actions stay panel-local. |
| 6437 | if app.view_stack.is_empty() |
| 6438 | && let Some(action) = crate::tui::work_surface::handle_key(app, key) |
| 6439 | { |
| 6440 | if let Some(action) = action { |
| 6441 | match action { |
| 6442 | crate::tui::app::SidebarRowAction::Command(command) => { |
| 6443 | if execute_command_input( |
| 6444 | terminal, |
| 6445 | app, |
| 6446 | &mut engine_handle, |
| 6447 | config, |
| 6448 | &command, |
| 6449 | ) |
| 6450 | .await? |
| 6451 | { |
| 6452 | return Ok(()); |
| 6453 | } |
| 6454 | } |
| 6455 | crate::tui::app::SidebarRowAction::CancelAgent { agent_id } => { |
| 6456 | app.show_event_notice( |
| 6457 | format!("Cancelling {agent_id}..."), |
| 6458 | StatusToastLevel::Info, |
| 6459 | ); |
| 6460 | if engine_handle |
| 6461 | .send(Op::CancelSubAgent { |
| 6462 | agent_id: agent_id.clone(), |
| 6463 | }) |
| 6464 | .await |
| 6465 | .is_err() |
| 6466 | { |
| 6467 | app.show_event_notice( |
| 6468 | format!("Could not cancel {agent_id}"), |
| 6469 | StatusToastLevel::Error, |
| 6470 | ); |
| 6471 | } |
| 6472 | } |
| 6473 | other => { |
| 6474 | let _ = crate::tui::mouse_ui::apply_sidebar_row_action(app, other); |
| 6475 | } |
| 6476 | } |
| 6477 | } |
| 6478 | submit_initial_input_if_ready(app, config, &engine_handle).await?; |
| 6479 | continue; |
| 6480 | } |
| 6481 | |
| 6482 | if crate::tui::pet_watch::handle_key(app, &key) { |
| 6483 | continue; |
| 6484 | } |
| 6485 | |
| 6486 | // The shell's key admission runs through one table |
| 6487 | // (`shell_key_routing::SHELL_BINDINGS`) keyed by one focus owner |
| 6488 | // (`app.focus()`) — never by whether the composer happens to hold |
| 6489 | // text. Help and Settings are shell-global, including onboarding, |
| 6490 | // launch, and modal surfaces (`/help` and `/provider` remain the |
| 6491 | // guaranteed textual routes); Shift+Tab is a shell-level |
| 6492 | // permission control and is claimed here, before the launch |
| 6493 | // screen swallows it. The remaining bindings are admitted by the |
| 6494 | // same table at their owners' seams below, where the composer's |
| 6495 | // completions and the agent-focus projection get the key first. |
| 6496 | match shell_binding_for_key(app, &key) { |
| 6497 | Some(ShellBindingId::Help) => { |
| 6498 | app.note_footer_hint_used(crate::tui::footer_hints::HELP_ROUTE); |
| 6499 | toggle_help_view(app); |
| 6500 | continue; |
| 6501 | } |
| 6502 | Some(ShellBindingId::Settings) => { |
| 6503 | toggle_settings_view(app); |
| 6504 | continue; |
| 6505 | } |
| 6506 | Some(ShellBindingId::PermissionCycle) => { |
| 6507 | cycle_permission_posture(app, config, &engine_handle).await; |
| 6508 | app.note_footer_hint_used(crate::tui::footer_hints::PERMISSION_CYCLE); |
| 6509 | continue; |
| 6510 | } |
| 6511 | Some(ShellBindingId::ViewCycle) => { |
| 6512 | crate::tui::work_surface::cycle_view(app, true); |
| 6513 | continue; |
| 6514 | } |
| 6515 | Some(ShellBindingId::ViewCycleBack) => { |
| 6516 | crate::tui::work_surface::cycle_view(app, false); |
| 6517 | continue; |
| 6518 | } |
| 6519 | _ => {} |
| 6520 | } |
| 6521 | |
| 6522 | // Provider onboarding is a real ProviderPickerView, not a |
| 6523 | // parallel ten-provider key handler. Route its keys before the |
| 6524 | // legacy onboarding switch so List/Key/Model/Confirm retain the |
| 6525 | // same behavior as `/provider` and `/setup`. |
| 6526 | match onboarding_key_route(app.onboarding, app.view_stack.top_kind(), &key) { |
| 6527 | // #4763: onboarding must never be a trap. Ctrl+C terminates |
| 6528 | // from every onboarding state, including while the picker |
| 6529 | // owns the keys — the legacy handler below is unreachable |
| 6530 | // once a modal is on the stack. |
| 6531 | OnboardingKeyRoute::Quit => { |
| 6532 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6533 | return Ok(()); |
| 6534 | } |
| 6535 | // #3927: no provider is selected and no route is activated. |
| 6536 | // The picker (a preview surface, never route authority) is |
| 6537 | // popped without applying anything it was showing. |
| 6538 | OnboardingKeyRoute::ExploreOffline => { |
| 6539 | if app.view_stack.top_kind() == Some(ModalKind::ProviderPicker) { |
| 6540 | let _ = app.view_stack.pop(); |
| 6541 | } |
| 6542 | onboarding::choose_offline_explore(app); |
| 6543 | continue; |
| 6544 | } |
| 6545 | // Every other key, Escape included, belongs to the picker. |
| 6546 | // The picker's own per-stage Escape walks key/OAuth entry |
| 6547 | // back to the list and only dismisses from the list, where |
| 6548 | // `ProviderPickerDismissed` runs the same non-mutating |
| 6549 | // onboarding back-transition the shell used to force. |
| 6550 | OnboardingKeyRoute::ProviderPicker | OnboardingKeyRoute::AccountLogin => { |
| 6551 | if key_shortcuts::is_paste_shortcut(&key) |
| 6552 | && crate::tui::paste::handle_paste( |
| 6553 | app, |
| 6554 | crate::tui::paste::PasteSource::Shortcut, |
| 6555 | ) |
| 6556 | { |
| 6557 | app.needs_redraw = true; |
| 6558 | continue; |
| 6559 | } |
| 6560 | let events = app.view_stack.handle_key(key); |
| 6561 | app.needs_redraw = true; |
| 6562 | if handle_view_events_boxed(terminal, app, config, &mut engine_handle, events) |
| 6563 | .await? |
| 6564 | { |
| 6565 | return Ok(()); |
| 6566 | } |
| 6567 | continue; |
| 6568 | } |
| 6569 | OnboardingKeyRoute::Legacy => {} |
| 6570 | } |
| 6571 | |
| 6572 | // Handle onboarding flow |
| 6573 | if app.onboarding != OnboardingState::None { |
| 6574 | match key.code { |
| 6575 | KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 6576 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6577 | return Ok(()); |
| 6578 | } |
| 6579 | KeyCode::Esc if app.onboarding == OnboardingState::Provider => { |
| 6580 | back_from_provider_onboarding(app); |
| 6581 | } |
| 6582 | KeyCode::Esc if app.onboarding == OnboardingState::Language => { |
| 6583 | app.onboarding = OnboardingState::Welcome; |
| 6584 | app.clear_setup_notice(); |
| 6585 | } |
| 6586 | // Language picker hotkeys select + persist (#566). |
| 6587 | // |
| 6588 | // Note: this used to be a single match-guard with `&& let`, |
| 6589 | // but `if_let_guard` is a nightly-only feature on Rust |
| 6590 | // before 1.94. Rewriting as a plain guard + nested `if let` |
| 6591 | // keeps `cargo install` working on stable. |
| 6592 | KeyCode::Char(c) |
| 6593 | if app.onboarding == OnboardingState::Language |
| 6594 | && (c.is_ascii_digit() || c.is_ascii_lowercase()) => |
| 6595 | { |
| 6596 | if let Some((_, tag, _, _)) = onboarding::language::LANGUAGE_OPTIONS |
| 6597 | .iter() |
| 6598 | .find(|(hotkey, _, _, _)| *hotkey == c) |
| 6599 | { |
| 6600 | match app.set_locale_from_onboarding(tag) { |
| 6601 | Ok(()) => { |
| 6602 | app.push_status_toast( |
| 6603 | format!("Language set to {tag}"), |
| 6604 | StatusToastLevel::Info, |
| 6605 | Some(2_500), |
| 6606 | ); |
| 6607 | onboarding::advance_onboarding_after_language(app); |
| 6608 | } |
| 6609 | Err(err) => { |
| 6610 | app.show_onboarding_notice( |
| 6611 | format!("Failed to save locale: {err}"), |
| 6612 | StatusToastLevel::Error, |
| 6613 | ); |
| 6614 | } |
| 6615 | } |
| 6616 | } |
| 6617 | } |
| 6618 | KeyCode::Enter => match app.onboarding { |
| 6619 | OnboardingState::Welcome => { |
| 6620 | onboarding::advance_onboarding_from_welcome(app); |
| 6621 | } |
| 6622 | OnboardingState::Language => { |
| 6623 | // Enter without a digit pick keeps the existing |
| 6624 | // setting (which defaults to "auto"). |
| 6625 | onboarding::advance_onboarding_after_language(app); |
| 6626 | } |
| 6627 | OnboardingState::Provider => { |
| 6628 | let recover_configured_route = |
| 6629 | app.onboarding_recovers_configured_route(); |
| 6630 | open_model_connection_setup( |
| 6631 | app, |
| 6632 | config, |
| 6633 | &engine_handle, |
| 6634 | recover_configured_route, |
| 6635 | ) |
| 6636 | .await; |
| 6637 | } |
| 6638 | OnboardingState::TrustDirectory => { |
| 6639 | // Trusting a workspace is a security boundary, so it |
| 6640 | // must be a deliberate choice. Enter — the "advance" |
| 6641 | // key on every other onboarding screen — must NOT |
| 6642 | // grant trust by reflex (accidental-trust risk). Nor |
| 6643 | // is it a silent dead key: point the user at the |
| 6644 | // explicit keys the rail advertises. |
| 6645 | app.show_onboarding_notice( |
| 6646 | app.tr(MessageId::OnboardTrustEnterHint).to_string(), |
| 6647 | StatusToastLevel::Info, |
| 6648 | ); |
| 6649 | } |
| 6650 | OnboardingState::Ready => { |
| 6651 | // Enter opens the product: the real composer, |
| 6652 | // pre-seeded with a first task for this folder — |
| 6653 | // never another educational surface. |
| 6654 | onboarding::finish_ready_and_open_composer(app); |
| 6655 | } |
| 6656 | OnboardingState::None => {} |
| 6657 | }, |
| 6658 | // "Customize later": the appearance choice from the ready |
| 6659 | // screen, as an optional secondary action. Onboarding is |
| 6660 | // finished first so the theme picker is an ordinary modal |
| 6661 | // over the live product, not a required step. |
| 6662 | KeyCode::Char('c') | KeyCode::Char('C') |
| 6663 | if app.onboarding == OnboardingState::Ready => |
| 6664 | { |
| 6665 | onboarding::finish_ready_and_open_composer(app); |
| 6666 | open_theme_picker(app); |
| 6667 | } |
| 6668 | _ if app.onboarding == OnboardingState::TrustDirectory => { |
| 6669 | match onboarding::trust_directory::choice_for_key(key.code, key.modifiers) { |
| 6670 | Some(onboarding::trust_directory::TrustChoice::Trust) => { |
| 6671 | if let Err(err) = complete_trust_directory_onboarding(app, config) { |
| 6672 | app.show_onboarding_notice( |
| 6673 | format!("Failed to trust workspace: {err}"), |
| 6674 | StatusToastLevel::Error, |
| 6675 | ); |
| 6676 | } |
| 6677 | } |
| 6678 | Some(onboarding::trust_directory::TrustChoice::ContinueUntrusted) => { |
| 6679 | continue_without_trusting_directory(app); |
| 6680 | } |
| 6681 | Some(onboarding::trust_directory::TrustChoice::Quit) => { |
| 6682 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6683 | return Ok(()); |
| 6684 | } |
| 6685 | None => {} |
| 6686 | } |
| 6687 | } |
| 6688 | _ => {} |
| 6689 | } |
| 6690 | continue; |
| 6691 | } |
| 6692 | |
| 6693 | // F3 is the non-printable keyboard counterpart to the clickable |
| 6694 | // route segment in the shared topbar. Route it through the same |
| 6695 | // typed event as mouse input; `/provider` remains the portable |
| 6696 | // direct command path for terminals that do not forward F-keys. |
| 6697 | if shell_binding_for_key(app, &key) == Some(ShellBindingId::ProviderRoute) { |
| 6698 | if handle_view_events_boxed( |
| 6699 | terminal, |
| 6700 | app, |
| 6701 | config, |
| 6702 | &mut engine_handle, |
| 6703 | vec![ViewEvent::TopbarRoutePickerRequested], |
| 6704 | ) |
| 6705 | .await? |
| 6706 | { |
| 6707 | return Ok(()); |
| 6708 | } |
| 6709 | continue; |
| 6710 | } |
| 6711 | |
| 6712 | // The pre-session launch menu owns every key until the user has |
| 6713 | // chosen a real session/worktree action. Resume and changelog may |
| 6714 | // place a shared surface above it; those views keep their normal |
| 6715 | // handlers while the launch screen remains the stable backdrop. |
| 6716 | if app.launch.visible { |
| 6717 | if !app.view_stack.is_empty() { |
| 6718 | let events = app.view_stack.handle_key(key); |
| 6719 | app.needs_redraw = true; |
| 6720 | if handle_view_events_boxed(terminal, app, config, &mut engine_handle, events) |
| 6721 | .await? |
| 6722 | { |
| 6723 | return Ok(()); |
| 6724 | } |
| 6725 | restore_launch_card_after_view_close(app); |
| 6726 | continue; |
| 6727 | } |
| 6728 | |
| 6729 | let launch_locale = app.ui_locale; |
| 6730 | // The pre-session composer is the session's own composer. |
| 6731 | // While it holds focus, this admission guard only claims the |
| 6732 | // launch-specific keys (list navigation/run, F1 help, |
| 6733 | // submit); every editing key falls through to the |
| 6734 | // conversation composer match below — the single composer |
| 6735 | // input authority — so word motion, selection, completion |
| 6736 | // menus, attachments, history, and vim behavior cannot drift |
| 6737 | // from the shell. |
| 6738 | let mut composer_authority = false; |
| 6739 | // A menu-run Enter defers its action to the chord match |
| 6740 | // below, which owns every launch action's execution. |
| 6741 | let mut menu_run_action: Option<crate::tui::underwater::LaunchAction> = None; |
| 6742 | if app.launch.composer_focus { |
| 6743 | match crate::tui::underwater::handle_launch_composer_key(app, key) { |
| 6744 | crate::tui::underwater::LaunchComposerKey::Consumed => { |
| 6745 | app.needs_redraw = true; |
| 6746 | continue; |
| 6747 | } |
| 6748 | crate::tui::underwater::LaunchComposerKey::MenuChord => { |
| 6749 | // The same key then drives the launch chords. |
| 6750 | } |
| 6751 | crate::tui::underwater::LaunchComposerKey::ComposerAuthority => { |
| 6752 | // Skip the menu handler; the conversation |
| 6753 | // composer match below owns this key. |
| 6754 | composer_authority = true; |
| 6755 | } |
| 6756 | crate::tui::underwater::LaunchComposerKey::MenuNavigate(delta) => { |
| 6757 | // The card is up: Up/Down move its row selection |
| 6758 | // over the painted row list. |
| 6759 | let rows = crate::tui::underwater::launch_rows_for_app(app); |
| 6760 | if delta < 0 |
| 6761 | && app.launch.menu_selected.is_none() |
| 6762 | && rows |
| 6763 | .iter() |
| 6764 | .any(|row| row.id == crate::tui::app::LaunchRowId::ShowRecent) |
| 6765 | { |
| 6766 | app.launch.expand_recent(); |
| 6767 | app.needs_redraw = true; |
| 6768 | continue; |
| 6769 | } |
| 6770 | let entries = rows.len().max(1) as i32; |
| 6771 | // First arrow lands on the first row; Up lands on |
| 6772 | // the newest recent session, else the last row. |
| 6773 | app.launch.menu_selected = Some(match app.launch.menu_selected { |
| 6774 | None if delta < 0 => rows |
| 6775 | .iter() |
| 6776 | .position(|row| { |
| 6777 | matches!( |
| 6778 | row.id, |
| 6779 | crate::tui::app::LaunchRowId::Recent(_) |
| 6780 | | crate::tui::app::LaunchRowId::SeeAll |
| 6781 | ) |
| 6782 | }) |
| 6783 | .unwrap_or((entries - 1) as usize), |
| 6784 | None => 0, |
| 6785 | Some(current) => { |
| 6786 | (current as i32 + delta).rem_euclid(entries) as usize |
| 6787 | } |
| 6788 | }); |
| 6789 | app.needs_redraw = true; |
| 6790 | continue; |
| 6791 | } |
| 6792 | crate::tui::underwater::LaunchComposerKey::MenuRun => { |
| 6793 | // Enter with an empty composer while the card is |
| 6794 | // up runs the highlighted row below, through the |
| 6795 | // same arms clicks use. |
| 6796 | let rows = crate::tui::underwater::launch_rows_for_app(app); |
| 6797 | menu_run_action = Some(crate::tui::underwater::run_launch_card_row( |
| 6798 | &rows, |
| 6799 | app.launch.menu_selected, |
| 6800 | )); |
| 6801 | } |
| 6802 | crate::tui::underwater::LaunchComposerKey::Submit => { |
| 6803 | let chord = composer_submit_chord(key, app.composer_multiline_mode) |
| 6804 | .unwrap_or(ComposerSubmitChord::Enter); |
| 6805 | if dispatch_composer_submit( |
| 6806 | terminal, |
| 6807 | app, |
| 6808 | &mut engine_handle, |
| 6809 | config, |
| 6810 | chord, |
| 6811 | key.modifiers == KeyModifiers::NONE, |
| 6812 | event_observed_at, |
| 6813 | ) |
| 6814 | .await? |
| 6815 | { |
| 6816 | return Ok(()); |
| 6817 | } |
| 6818 | app.needs_redraw = true; |
| 6819 | continue; |
| 6820 | } |
| 6821 | } |
| 6822 | } |
| 6823 | if composer_authority { |
| 6824 | // Fall out of the launch branch: the global chords and |
| 6825 | // the conversation composer match below handle this key |
| 6826 | // exactly as they would in a live session. |
| 6827 | } else { |
| 6828 | // Ctrl+C on the launch screen follows the same two-tap |
| 6829 | // contract as the session shell (`CtrlCDisposition`): |
| 6830 | // first press arms the visible exit prompt, the second |
| 6831 | // inside QUIT_CONFIRMATION_WINDOW exits. Selection |
| 6832 | // copy and turn cancel cannot apply before a session |
| 6833 | // exists, so every other disposition arms. |
| 6834 | if key.code == KeyCode::Char('c') |
| 6835 | && key.modifiers.contains(KeyModifiers::CONTROL) |
| 6836 | { |
| 6837 | match ctrl_c_disposition(app) { |
| 6838 | CtrlCDisposition::ConfirmExit => { |
| 6839 | let _ = engine_handle.send(Op::Shutdown).await; |
| 6840 | return Ok(()); |
| 6841 | } |
| 6842 | _ => app.arm_quit(), |
| 6843 | } |
| 6844 | app.needs_redraw = true; |
| 6845 | continue; |
| 6846 | } |
| 6847 | let action = menu_run_action.take().unwrap_or_else(|| { |
| 6848 | crate::tui::underwater::handle_launch_key( |
| 6849 | &mut app.launch, |
| 6850 | key, |
| 6851 | launch_locale, |
| 6852 | ) |
| 6853 | }); |
| 6854 | if apply_launch_action(terminal, app, &mut engine_handle, config, action) |
| 6855 | .await? |
| 6856 | { |
| 6857 | return Ok(()); |
| 6858 | } |
| 6859 | continue; |
| 6860 | } |
| 6861 | } |
| 6862 | |
| 6863 | if key.code == KeyCode::Char('x') |
| 6864 | && key.modifiers.contains(KeyModifiers::CONTROL) |
| 6865 | && prefill_jobs_cancel_all_if_tasks_sidebar(app) |
| 6866 | { |
| 6867 | continue; |
| 6868 | } |
| 6869 | |
| 6870 | if key.code == KeyCode::Char('k') && key.modifiers.contains(KeyModifiers::CONTROL) { |
| 6871 | // When the composer is the active input target (no modal/pager |
| 6872 | // intercepting keys), Ctrl+K performs an emacs-style kill to |
| 6873 | // end-of-line. If the kill is a no-op (cursor at end of empty |
| 6874 | // input), fall through to the existing command palette. |
| 6875 | if app.view_stack.is_empty() && app.kill_to_end_of_line() { |
| 6876 | continue; |
| 6877 | } |
| 6878 | codewhale_telemetry::session_counters() |
| 6879 | .bump(codewhale_telemetry::Counter::CommandPaletteOpen); |
| 6880 | app.view_stack.push(CommandPaletteView::new_for_locale( |
| 6881 | app.ui_locale, |
| 6882 | build_command_palette_entries( |
| 6883 | app.ui_locale, |
| 6884 | &app.skills_dir, |
| 6885 | &app.skills_config, |
| 6886 | &app.workspace, |
| 6887 | &app.mcp_config_path, |
| 6888 | app.mcp_snapshot.as_ref(), |
| 6889 | app.extension_plugin_view().as_ref(), |
| 6890 | ), |
| 6891 | )); |
| 6892 | continue; |
| 6893 | } |
| 6894 | |
| 6895 | // Shifted shortcuts toggle the file-tree pane. Keep plain Ctrl+E |
| 6896 | // reserved for the composer end-of-line binding used by shells. |
| 6897 | if key_shortcuts::is_file_tree_toggle_shortcut(&key) { |
| 6898 | key_actions::toggle_file_tree(app); |
| 6899 | continue; |
| 6900 | } |
| 6901 | |
| 6902 | if key_shortcuts::is_agent_board_shortcut(&key) { |
| 6903 | crate::tui::agent_board::open_from_app(app); |
| 6904 | app.needs_redraw = true; |
| 6905 | continue; |
| 6906 | } |
| 6907 | |
| 6908 | // Ctrl+P opens the fuzzy file-picker overlay. Bound only when the |
| 6909 | // composer is focused (no other modal or inline popup on top) and the |
| 6910 | // engine is not actively streaming a turn. |
| 6911 | if key.code == KeyCode::Char('p') |
| 6912 | && key.modifiers.contains(KeyModifiers::CONTROL) |
| 6913 | && visible_slash_menu_entries(app, SLASH_MENU_LIMIT).is_empty() |
| 6914 | && app.view_stack.is_empty() |
| 6915 | && !app.is_loading |
| 6916 | { |
| 6917 | file_picker_relevance::open_file_picker(app); |
| 6918 | continue; |
| 6919 | } |
| 6920 | |
| 6921 | if matches!(key.code, KeyCode::Char('l') | KeyCode::Char('L')) |
| 6922 | && key.modifiers.contains(KeyModifiers::CONTROL) |
| 6923 | && app.view_stack.is_empty() |
| 6924 | { |
| 6925 | try_queue_manual_compaction(app, config, &engine_handle, None); |
| 6926 | continue; |
| 6927 | } |
| 6928 | |
| 6929 | if matches!(key.code, KeyCode::Char('b') | KeyCode::Char('B')) |
| 6930 | && key_shortcuts::has_control_like_modifier(key.modifiers) |
| 6931 | && app.view_stack.is_empty() |
| 6932 | { |
| 6933 | // Release foreground or background shell waits in this session |
| 6934 | // without canceling their commands (#3032/#3859/#6909). |
| 6935 | request_shell_wait_detach(app); |
| 6936 | app.needs_redraw = true; |
| 6937 | continue; |
| 6938 | } |
| 6939 | |
| 6940 | if shell_binding_for_key(app, &key) == Some(ShellBindingId::ContextInspector) { |
| 6941 | open_context_inspector(app); |
| 6942 | continue; |
| 6943 | } |
| 6944 | |
| 6945 | if !app.view_stack.is_empty() { |
| 6946 | if key_shortcuts::is_paste_shortcut(&key) |
| 6947 | && crate::tui::paste::handle_paste( |
| 6948 | app, |
| 6949 | crate::tui::paste::PasteSource::Shortcut, |
| 6950 | ) |
| 6951 | { |
| 6952 | app.needs_redraw = true; |
| 6953 | continue; |
| 6954 | } |
| 6955 | let closing_work_inspector = app.work_surface.opened.is_some() |
| 6956 | && app.view_stack.top_kind() == Some(ModalKind::Pager); |
| 6957 | let Some(events) = route_key_to_view_stack(app, key, event_observed_at) else { |
| 6958 | app.needs_redraw = true; |
| 6959 | continue; |
| 6960 | }; |
| 6961 | clear_work_inspector_after_pager_close(app, closing_work_inspector); |
| 6962 | app.needs_redraw = true; |
| 6963 | if handle_view_events_boxed(terminal, app, config, &mut engine_handle, events) |
| 6964 | .await? |
| 6965 | { |
| 6966 | return Ok(()); |
| 6967 | } |
| 6968 | continue; |
| 6969 | } |
| 6970 | |
| 6971 | if let Some(slot) = hotbar_slot_from_key(app, &key) { |
| 6972 | if let Some(dispatch) = dispatch_hotbar_slot(app, config, slot)? { |
| 6973 | match dispatch { |
| 6974 | HotbarDispatch::Handled => { |
| 6975 | app.needs_redraw = true; |
| 6976 | } |
| 6977 | HotbarDispatch::AppAction(action) => { |
| 6978 | if apply_command_result( |
| 6979 | terminal, |
| 6980 | app, |
| 6981 | &mut engine_handle, |
| 6982 | config, |
| 6983 | commands::CommandResult::action(action), |
| 6984 | ) |
| 6985 | .await? |
| 6986 | { |
| 6987 | return Ok(()); |
| 6988 | } |
| 6989 | if let Err(err) = persist_pending_work_checkpoint(app).await { |
| 6990 | app.show_event_notice(format!( |
| 6991 | "Hotbar change applied, but its Work receipt is pending ({err})" |
| 6992 | ), StatusToastLevel::Warning); |
| 6993 | } |
| 6994 | app.needs_redraw = true; |
| 6995 | } |
| 6996 | } |
| 6997 | } |
| 6998 | continue; |
| 6999 | } |
| 7000 | |
| 7001 | // File-tree navigation: delegated to key_actions module. |
| 7002 | if key_actions::handle_file_tree_key(app, &key) { |
| 7003 | continue; |
| 7004 | } |
| 7005 | |
| 7006 | if app.is_history_search_active() { |
| 7007 | handle_history_search_key(app, key); |
| 7008 | continue; |
| 7009 | } |
| 7010 | |
| 7011 | if matches!(key.code, KeyCode::Char('r') | KeyCode::Char('R')) |
| 7012 | && key.modifiers.contains(KeyModifiers::ALT) |
| 7013 | && !key.modifiers.contains(KeyModifiers::CONTROL) |
| 7014 | && !key.modifiers.contains(KeyModifiers::SUPER) |
| 7015 | { |
| 7016 | app.start_history_search(); |
| 7017 | continue; |
| 7018 | } |
| 7019 | |
| 7020 | let now = event_observed_at; |
| 7021 | flush_paste_burst_before_composer(app, now); |
| 7022 | |
| 7023 | // On Windows, AltGr is delivered as `Ctrl+Alt`; treat |
| 7024 | // AltGr-typed chars (e.g. European layouts producing `@`, `\`, |
| 7025 | // `|`) as plain text rather than swallowing them as a modified |
| 7026 | // shortcut. `key_hint::has_ctrl_or_alt` filters AltGr out. |
| 7027 | let has_ctrl_alt_or_super = |
| 7028 | crate::tui::widgets::key_hint::has_ctrl_or_alt(key.modifiers) |
| 7029 | || key.modifiers.contains(KeyModifiers::SUPER); |
| 7030 | let is_plain_char = matches!(key.code, KeyCode::Char(_)) && !has_ctrl_alt_or_super; |
| 7031 | // Only bare Enter participates in trailing-newline paste-burst |
| 7032 | // protection. Modified Enter chords are deliberate composer |
| 7033 | // actions: flush any buffered text, then route the chord normally |
| 7034 | // so Shift/Alt+Enter newline or submit and Ctrl+Enter steer are |
| 7035 | // never eaten after fast typing or an unbracketed paste. |
| 7036 | let is_plain_enter = |
| 7037 | matches!(key.code, KeyCode::Enter) && key.modifiers == KeyModifiers::NONE; |
| 7038 | |
| 7039 | // Tool details: Alt+V / Option+V only. Bare `v` always types `v` |
| 7040 | // in every focus state (TUI-DOG-002). |
| 7041 | if shell_binding_for_key(app, &key) == Some(ShellBindingId::ToolDetails) { |
| 7042 | // While a worker is focused the details chord is that |
| 7043 | // worker's bounded Agent Details projection. |
| 7044 | if let Some(agent_id) = app.agent_focus.as_ref().map(|f| f.agent_id.clone()) { |
| 7045 | if !crate::tui::agent_details::open_agent_details(app, &agent_id) { |
| 7046 | app.show_event_notice( |
| 7047 | "Agent details are unavailable".to_string(), |
| 7048 | StatusToastLevel::Warning, |
| 7049 | ); |
| 7050 | } |
| 7051 | app.needs_redraw = true; |
| 7052 | continue; |
| 7053 | } |
| 7054 | open_tool_details_pager(app); |
| 7055 | continue; |
| 7056 | } |
| 7057 | |
| 7058 | if !is_plain_char |
| 7059 | && !is_plain_enter |
| 7060 | && let Some(pending) = app.flush_paste_burst_before_modified_input_if_enabled() |
| 7061 | { |
| 7062 | app.insert_str(&pending); |
| 7063 | } |
| 7064 | |
| 7065 | if (is_plain_char || is_plain_enter) && handle_plain_key_before_composer(app, &key, now) |
| 7066 | { |
| 7067 | continue; |
| 7068 | } |
| 7069 | |
| 7070 | let slash_menu_entries = visible_slash_menu_entries(app, SLASH_MENU_LIMIT); |
| 7071 | let slash_menu_open = !slash_menu_entries.is_empty(); |
| 7072 | if slash_menu_open && app.slash_menu_selected >= slash_menu_entries.len() { |
| 7073 | app.slash_menu_selected = slash_menu_entries.len().saturating_sub(1); |
| 7074 | } |
| 7075 | let mention_menu_limit = app.mention_menu_limit; |
| 7076 | let mention_menu_entries = |
| 7077 | crate::tui::file_mention::visible_mention_menu_entries(app, mention_menu_limit); |
| 7078 | let mention_menu_open = !mention_menu_entries.is_empty(); |
| 7079 | if mention_menu_open && app.mention_menu_selected >= mention_menu_entries.len() { |
| 7080 | app.mention_menu_selected = mention_menu_entries.len().saturating_sub(1); |
| 7081 | } |
| 7082 | |
| 7083 | // Cancel a pending Esc-Esc prime as soon as any non-Esc key |
| 7084 | // arrives. Without this the prime would hang around for the |
| 7085 | // rest of the session and the user's next genuine Esc would |
| 7086 | // suddenly skip straight into the backtrack overlay. |
| 7087 | if !matches!(key.code, KeyCode::Esc) |
| 7088 | && matches!( |
| 7089 | app.backtrack.phase, |
| 7090 | crate::tui::backtrack::BacktrackPhase::Primed |
| 7091 | ) |
| 7092 | { |
| 7093 | app.backtrack.reset(); |
| 7094 | } |
| 7095 | |
| 7096 | if handle_reasoning_effort_key(app, &key) { |
| 7097 | if let Err(err) = persist_pending_work_checkpoint(app).await { |
| 7098 | app.show_event_notice( |
| 7099 | format!( |
| 7100 | "Reasoning effort changed, but its Work receipt is pending ({err})" |
| 7101 | ), |
| 7102 | StatusToastLevel::Warning, |
| 7103 | ); |
| 7104 | } |
| 7105 | continue; |
| 7106 | } |
| 7107 | |
| 7108 | // An empty Enter with a queued follow-up sends it now. Handle it |
| 7109 | // before transcript/detail Enter shortcuts so it can never open an |
| 7110 | // unrelated overlay instead (#382). |
| 7111 | let portable_submit_chord = composer_submit_chord(key, app.composer_multiline_mode) |
| 7112 | .or_else(|| { |
| 7113 | composer_submit_chord(key, app.composer_multiline_mode && !app.input.is_empty()) |
| 7114 | }); |
| 7115 | if matches!(portable_submit_chord, Some(ComposerSubmitChord::Enter)) |
| 7116 | && matches!( |
| 7117 | app.decide_composer_submit(ComposerSubmitChord::Enter), |
| 7118 | ComposerSubmitAction::SendQueuedNow |
| 7119 | ) |
| 7120 | { |
| 7121 | let _ = send_next_queued_message_now(app, config, &engine_handle).await?; |
| 7122 | continue; |
| 7123 | } |
| 7124 | |
| 7125 | if let Some(shortcut) = crate::tui::agent_focus::shell_shortcut( |
| 7126 | app, |
| 7127 | &key, |
| 7128 | slash_menu_open || mention_menu_open, |
| 7129 | ) { |
| 7130 | app.note_footer_hint_used(crate::tui::footer_hints::AGENT_ARROWS); |
| 7131 | match shortcut { |
| 7132 | crate::tui::agent_focus::AgentShellShortcut::FocusAgents => { |
| 7133 | if !crate::tui::work_surface::enter_agents(app) { |
| 7134 | open_agents_register(app, &engine_handle).await; |
| 7135 | } |
| 7136 | } |
| 7137 | // `↓ to manage` opens the workflows view while the workbar |
| 7138 | // shows runs, else the agent register. |
| 7139 | crate::tui::agent_focus::AgentShellShortcut::ManageAgents => { |
| 7140 | if app.workflow_runs.is_empty() { |
| 7141 | open_agents_register(app, &engine_handle).await; |
| 7142 | } else { |
| 7143 | crate::tui::views::workflows_manager::open(app); |
| 7144 | } |
| 7145 | } |
| 7146 | } |
| 7147 | continue; |
| 7148 | } |
| 7149 | |
| 7150 | match key.code { |
| 7151 | KeyCode::Enter |
| 7152 | if key.modifiers == KeyModifiers::NONE |
| 7153 | && app.input.is_empty() |
| 7154 | && app.viewport.transcript_selection.is_active() |
| 7155 | && open_pager_for_selection(app) => |
| 7156 | { |
| 7157 | continue; |
| 7158 | } |
| 7159 | KeyCode::Enter |
| 7160 | if key.modifiers == KeyModifiers::NONE |
| 7161 | && app.input.is_empty() |
| 7162 | && detail_target_cell_index(app).is_some() |
| 7163 | && open_focused_cell_pager(app) => |
| 7164 | { |
| 7165 | continue; |
| 7166 | } |
| 7167 | KeyCode::Enter |
| 7168 | if key.modifiers == KeyModifiers::NONE |
| 7169 | && app.input.is_empty() |
| 7170 | && detail_target_cell_index(app) |
| 7171 | .is_some_and(|idx| app.toggle_tool_run_expansion_at(idx)) => |
| 7172 | { |
| 7173 | continue; |
| 7174 | } |
| 7175 | KeyCode::Char('l') |
| 7176 | if key_shortcuts::alt_nav_modifiers(key.modifiers) |
| 7177 | && open_pager_for_last_message(app) => |
| 7178 | { |
| 7179 | continue; |
| 7180 | } |
| 7181 | _ if key_shortcuts::is_reasoning_detail_shortcut(&key) |
| 7182 | && open_reasoning_detail_pager(app) => |
| 7183 | { |
| 7184 | continue; |
| 7185 | } |
| 7186 | _ if key_shortcuts::is_turn_inspector_shortcut(&key) |
| 7187 | && open_turn_inspector_pager(app) => |
| 7188 | { |
| 7189 | continue; |
| 7190 | } |
| 7191 | // Space toggles fold/unfold of the focused thinking block |
| 7192 | // when the composer is empty. For thinking cells, toggles |
| 7193 | // between summary and full content; for other cells, toggles |
| 7194 | // visibility (#1972, #2348). Uses virtual-cell lookup so |
| 7195 | // in-flight active reasoning works too. |
| 7196 | KeyCode::Char(' ') |
| 7197 | if key.modifiers == KeyModifiers::NONE |
| 7198 | && app.input.is_empty() |
| 7199 | && handle_transcript_space(app) => |
| 7200 | { |
| 7201 | continue; |
| 7202 | } |
| 7203 | KeyCode::Char('t') | KeyCode::Char('T') |
| 7204 | if key.modifiers.contains(KeyModifiers::CONTROL) |
| 7205 | && key.modifiers.contains(KeyModifiers::SHIFT) => |
| 7206 | { |
| 7207 | toggle_live_transcript_overlay(app); |
| 7208 | continue; |
| 7209 | } |
| 7210 | KeyCode::Char('1') |
| 7211 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7212 | && key_shortcuts::has_control_like_modifier(key.modifiers) => |
| 7213 | { |
| 7214 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Tasks); |
| 7215 | continue; |
| 7216 | } |
| 7217 | KeyCode::Char('2') |
| 7218 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7219 | && key_shortcuts::has_control_like_modifier(key.modifiers) => |
| 7220 | { |
| 7221 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Agents); |
| 7222 | continue; |
| 7223 | } |
| 7224 | KeyCode::Char('3') |
| 7225 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7226 | && key_shortcuts::has_control_like_modifier(key.modifiers) => |
| 7227 | { |
| 7228 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Context); |
| 7229 | continue; |
| 7230 | } |
| 7231 | KeyCode::Char('4') |
| 7232 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7233 | && key_shortcuts::has_control_like_modifier(key.modifiers) => |
| 7234 | { |
| 7235 | apply_alt_4_shortcut(app, key.modifiers); |
| 7236 | continue; |
| 7237 | } |
| 7238 | // Rail panel selection via Alt+! / Alt+@ / Alt+# / Alt+$ / Alt+% |
| 7239 | // AltGr on European keyboards emits Ctrl+Alt on Windows, so |
| 7240 | // exclude Ctrl to avoid swallowing AltGr-typed characters |
| 7241 | // like @ (AltGr+0 on French AZERTY) and # (AltGr+3). This |
| 7242 | // matches the has_ctrl_or_alt / is_altgr philosophy in |
| 7243 | // key_hint.rs: treat Ctrl+Alt as AltGr, not a shortcut. |
| 7244 | KeyCode::Char('!') |
| 7245 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7246 | && !key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7247 | { |
| 7248 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Tasks); |
| 7249 | continue; |
| 7250 | } |
| 7251 | KeyCode::Char('@') |
| 7252 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7253 | && !key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7254 | { |
| 7255 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Agents); |
| 7256 | continue; |
| 7257 | } |
| 7258 | KeyCode::Char('#') |
| 7259 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7260 | && !key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7261 | { |
| 7262 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Context); |
| 7263 | continue; |
| 7264 | } |
| 7265 | KeyCode::Char('$') | KeyCode::Char('%') |
| 7266 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7267 | && !key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7268 | { |
| 7269 | rail_panel_shortcut(app, crate::tui::work_surface::RailPanel::Files); |
| 7270 | continue; |
| 7271 | } |
| 7272 | KeyCode::Char('0') |
| 7273 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7274 | && key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7275 | { |
| 7276 | apply_alt_0_shortcut(app, key.modifiers); |
| 7277 | continue; |
| 7278 | } |
| 7279 | KeyCode::Char('r') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 7280 | // Scope the picker to the current workspace so Ctrl+R |
| 7281 | // never restores a different project's history by |
| 7282 | // surprise (#1395). Press `a` inside the picker to |
| 7283 | // broaden to every saved session. |
| 7284 | app.view_stack.push( |
| 7285 | SessionPickerView::new(&app.workspace, app.ui_locale) |
| 7286 | .with_current_session(app.current_session_id.as_deref()), |
| 7287 | ); |
| 7288 | continue; |
| 7289 | } |
| 7290 | KeyCode::Char('c') | KeyCode::Char('C') |
| 7291 | if key_shortcuts::is_copy_shortcut(&key) => |
| 7292 | { |
| 7293 | copy_active_selection(app); |
| 7294 | } |
| 7295 | KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 7296 | // Five behaviors layered on Ctrl+C in priority order — see |
| 7297 | // `CtrlCDisposition` for the unit-tested decision table. |
| 7298 | // 1. selection active → copy + clear (Windows convention, |
| 7299 | // #1337); 2. turn in flight → cancel; 3. non-empty |
| 7300 | // composer → recoverable clear; 4. quit-armed → exit; |
| 7301 | // 5. otherwise → arm the 2-second exit prompt. |
| 7302 | match ctrl_c_disposition(app) { |
| 7303 | CtrlCDisposition::CopySelection => { |
| 7304 | copy_active_selection(app); |
| 7305 | clear_transcript_selection(app); |
| 7306 | } |
| 7307 | CtrlCDisposition::CancelTurn => { |
| 7308 | let compacting = app.is_compacting || app.manual_compaction_queued; |
| 7309 | if compacting { |
| 7310 | try_cancel_compaction(app, &engine_handle); |
| 7311 | if !compact_interrupt_should_stop_turn(app) { |
| 7312 | app.disarm_quit(); |
| 7313 | continue; |
| 7314 | } |
| 7315 | } |
| 7316 | let was_waiting = app.goal_continuation_waiting; |
| 7317 | if !crate::tui::external_agent::interrupt_external_turn(app) { |
| 7318 | engine_handle.cancel(); |
| 7319 | } |
| 7320 | if was_waiting { |
| 7321 | app.goal_continuation_waiting = false; |
| 7322 | app.show_event_notice( |
| 7323 | app.tr(MessageId::GoalContinuationStopped).to_string(), |
| 7324 | StatusToastLevel::Info, |
| 7325 | ); |
| 7326 | app.disarm_quit(); |
| 7327 | continue; |
| 7328 | } |
| 7329 | bank_live_turn_time(app); |
| 7330 | mark_active_turn_cancelled_locally(app); |
| 7331 | current_streaming_text.clear(); |
| 7332 | stream_display_clock.reset(); |
| 7333 | let prompt_restored = app.restore_last_submitted_prompt_if_empty(); |
| 7334 | let base = if prompt_restored { |
| 7335 | "Request cancelled; prompt restored to composer" |
| 7336 | } else { |
| 7337 | "Request cancelled" |
| 7338 | }; |
| 7339 | app.show_event_notice( |
| 7340 | parent_stop_status(app, base), |
| 7341 | StatusToastLevel::Warning, |
| 7342 | ); |
| 7343 | app.disarm_quit(); |
| 7344 | } |
| 7345 | CtrlCDisposition::ClearInput => { |
| 7346 | app.clear_composer_draft(); |
| 7347 | } |
| 7348 | CtrlCDisposition::ConfirmExit => { |
| 7349 | let _ = engine_handle.send(Op::Shutdown).await; |
| 7350 | return Ok(()); |
| 7351 | } |
| 7352 | CtrlCDisposition::ArmExit => { |
| 7353 | if !cancel_background_commands(app) { |
| 7354 | app.arm_quit(); |
| 7355 | } |
| 7356 | } |
| 7357 | } |
| 7358 | } |
| 7359 | KeyCode::Char('d') |
| 7360 | if key.modifiers.contains(KeyModifiers::CONTROL) && app.input.is_empty() => |
| 7361 | { |
| 7362 | let _ = engine_handle.send(Op::Shutdown).await; |
| 7363 | return Ok(()); |
| 7364 | } |
| 7365 | // Agent focus: Esc on an empty composer returns to the main |
| 7366 | // conversation before any other Esc meaning applies. |
| 7367 | KeyCode::Esc |
| 7368 | if app.agent_focus.is_some() |
| 7369 | && app.input.is_empty() |
| 7370 | && !slash_menu_open |
| 7371 | && !mention_menu_open => |
| 7372 | { |
| 7373 | crate::tui::agent_focus::exit_focus(app); |
| 7374 | continue; |
| 7375 | } |
| 7376 | // Vim composer mode: Esc from Insert → Normal. |
| 7377 | // This arm runs before the generic Esc handler so Insert mode |
| 7378 | // Esc doesn't accidentally cancel an in-flight request. |
| 7379 | KeyCode::Esc |
| 7380 | if app.composer.vim_enabled |
| 7381 | && app.composer.vim_mode != crate::tui::app::VimMode::Normal => |
| 7382 | { |
| 7383 | app.vim_enter_normal(); |
| 7384 | continue; |
| 7385 | } |
| 7386 | KeyCode::Esc if app.clear_composer_attachment_selection() => { |
| 7387 | continue; |
| 7388 | } |
| 7389 | // An idle operator can dismiss the persistent context warning |
| 7390 | // or the account preferences notice without affecting vim or |
| 7391 | // attachment handling. While a turn is active Esc retains its |
| 7392 | // cancellation meaning. |
| 7393 | KeyCode::Esc |
| 7394 | if !app.is_loading |
| 7395 | && app.input.is_empty() |
| 7396 | && !slash_menu_open |
| 7397 | && !mention_menu_open |
| 7398 | && (app.dismiss_context_pressure_warning() |
| 7399 | || app.dismiss_account_preferences_notice()) => |
| 7400 | { |
| 7401 | continue; |
| 7402 | } |
| 7403 | KeyCode::Esc if mention_menu_open => { |
| 7404 | app.mention_menu_hidden = true; |
| 7405 | app.mention_menu_selected = 0; |
| 7406 | } |
| 7407 | KeyCode::Esc if app.sidebar_hover_tooltip.is_some() => { |
| 7408 | app.sidebar_hover_tooltip = None; |
| 7409 | app.needs_redraw = true; |
| 7410 | } |
| 7411 | KeyCode::Esc => { |
| 7412 | match next_escape_action(app, slash_menu_open) { |
| 7413 | EscapeAction::CloseSlashMenu => { |
| 7414 | // A popup-style action wins over backtrack — clear |
| 7415 | // any prime so a stale Primed state can't jump us |
| 7416 | // straight into Selecting on the next Esc. |
| 7417 | app.backtrack.reset(); |
| 7418 | app.close_slash_menu(); |
| 7419 | } |
| 7420 | EscapeAction::CancelRequest => { |
| 7421 | app.backtrack.reset(); |
| 7422 | app.note_footer_hint_used(crate::tui::footer_hints::ESC_INTERRUPT); |
| 7423 | if escape_cancel_request( |
| 7424 | app, |
| 7425 | &engine_handle, |
| 7426 | &mut current_streaming_text, |
| 7427 | &mut stream_display_clock, |
| 7428 | ) { |
| 7429 | continue; |
| 7430 | } |
| 7431 | } |
| 7432 | EscapeAction::PauseCommand => { |
| 7433 | app.backtrack.reset(); |
| 7434 | pause_pausable_command(app, &engine_handle); |
| 7435 | } |
| 7436 | EscapeAction::DiscardQueuedDraft => { |
| 7437 | app.backtrack.reset(); |
| 7438 | if app.cancel_queued_draft_edit() { |
| 7439 | app.show_input_feedback( |
| 7440 | "Queued edit canceled; follow-up restored", |
| 7441 | StatusToastLevel::Warning, |
| 7442 | 5_000, |
| 7443 | ); |
| 7444 | } |
| 7445 | } |
| 7446 | EscapeAction::DismissPluginCta => { |
| 7447 | app.backtrack.reset(); |
| 7448 | let _ = app.dismiss_plugin_cta_for_session(); |
| 7449 | } |
| 7450 | EscapeAction::ClearInput => { |
| 7451 | app.clear_composer_draft(); |
| 7452 | } |
| 7453 | EscapeAction::Noop => { |
| 7454 | if cancel_background_commands(app) { |
| 7455 | continue; |
| 7456 | } |
| 7457 | // Nothing else cares about this Esc — route it |
| 7458 | // through the backtrack state machine. While |
| 7459 | // streaming or with the live transcript already |
| 7460 | // open, fall through silently (#133 acceptance: |
| 7461 | // "during streaming Esc-Esc is a silent no-op"). |
| 7462 | if app.is_loading |
| 7463 | || app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) |
| 7464 | { |
| 7465 | continue; |
| 7466 | } |
| 7467 | let total = count_user_history_cells(app); |
| 7468 | match app.backtrack.handle_esc(total) { |
| 7469 | crate::tui::backtrack::EscEffect::None => {} |
| 7470 | crate::tui::backtrack::EscEffect::Prime => { |
| 7471 | app.show_input_hint("Press Esc again to backtrack"); |
| 7472 | app.needs_redraw = true; |
| 7473 | } |
| 7474 | crate::tui::backtrack::EscEffect::Cancel => { |
| 7475 | app.show_input_feedback( |
| 7476 | "Backtrack canceled", |
| 7477 | StatusToastLevel::Warning, |
| 7478 | 5_000, |
| 7479 | ); |
| 7480 | app.needs_redraw = true; |
| 7481 | } |
| 7482 | crate::tui::backtrack::EscEffect::OpenOverlay => { |
| 7483 | open_backtrack_overlay(app); |
| 7484 | } |
| 7485 | } |
| 7486 | } |
| 7487 | } |
| 7488 | } |
| 7489 | KeyCode::Up if key.modifiers.contains(KeyModifiers::SUPER) => { |
| 7490 | app.scroll_up(app.viewport.last_transcript_visible.max(3)); |
| 7491 | } |
| 7492 | KeyCode::Up if key.modifiers.contains(KeyModifiers::ALT) => { |
| 7493 | app.scroll_up(3); |
| 7494 | } |
| 7495 | KeyCode::Up if key.modifiers.contains(KeyModifiers::SHIFT) => { |
| 7496 | app.scroll_up(3); |
| 7497 | } |
| 7498 | KeyCode::Up |
| 7499 | if key.modifiers.is_empty() |
| 7500 | && mention_menu_open |
| 7501 | && app.mention_menu_selected > 0 => |
| 7502 | { |
| 7503 | app.mention_menu_selected = app.mention_menu_selected.saturating_sub(1); |
| 7504 | } |
| 7505 | KeyCode::Up if key.modifiers.is_empty() && slash_menu_open => { |
| 7506 | select_previous_slash_menu_entry(app, slash_menu_entries.len()); |
| 7507 | } |
| 7508 | KeyCode::Char('p') |
| 7509 | if key.modifiers.contains(KeyModifiers::CONTROL) && slash_menu_open => |
| 7510 | { |
| 7511 | select_previous_slash_menu_entry(app, slash_menu_entries.len()); |
| 7512 | } |
| 7513 | KeyCode::Up |
| 7514 | if key.modifiers.is_empty() |
| 7515 | && app.selected_composer_attachment_index().is_some() => |
| 7516 | { |
| 7517 | let _ = app.select_previous_composer_attachment(); |
| 7518 | } |
| 7519 | KeyCode::Up |
| 7520 | if key.modifiers.is_empty() |
| 7521 | && app.cursor_position == 0 |
| 7522 | && !mention_menu_open |
| 7523 | && !slash_menu_open |
| 7524 | && app.composer_attachment_count() > 0 => |
| 7525 | { |
| 7526 | let _ = app.select_previous_composer_attachment(); |
| 7527 | continue; |
| 7528 | } |
| 7529 | // #85: ↑ edits the most-recent queued message when the composer |
| 7530 | // is idle and the pending-input preview is showing queued work. |
| 7531 | KeyCode::Up |
| 7532 | if key.modifiers.is_empty() |
| 7533 | && app.input.is_empty() |
| 7534 | && app.cursor_position == 0 |
| 7535 | && app.queued_draft.is_none() |
| 7536 | && !app.queued_messages.is_empty() |
| 7537 | && !mention_menu_open |
| 7538 | && !slash_menu_open |
| 7539 | && app.selected_composer_attachment_index().is_none() => |
| 7540 | { |
| 7541 | let _ = app.pop_last_queued_into_draft(); |
| 7542 | } |
| 7543 | KeyCode::Down if key.modifiers.contains(KeyModifiers::SUPER) => { |
| 7544 | app.scroll_down(app.viewport.last_transcript_visible.max(3)); |
| 7545 | } |
| 7546 | KeyCode::Down if key.modifiers.contains(KeyModifiers::ALT) => { |
| 7547 | app.scroll_down(3); |
| 7548 | } |
| 7549 | KeyCode::Down if key.modifiers.contains(KeyModifiers::SHIFT) => { |
| 7550 | app.scroll_down(3); |
| 7551 | } |
| 7552 | KeyCode::Down if key.modifiers.is_empty() && mention_menu_open => { |
| 7553 | app.mention_menu_selected = (app.mention_menu_selected + 1) |
| 7554 | .min(mention_menu_entries.len().saturating_sub(1)); |
| 7555 | } |
| 7556 | KeyCode::Down if key.modifiers.is_empty() && slash_menu_open => { |
| 7557 | select_next_slash_menu_entry(app, slash_menu_entries.len()); |
| 7558 | } |
| 7559 | KeyCode::Char('n') |
| 7560 | if key.modifiers.contains(KeyModifiers::CONTROL) && slash_menu_open => |
| 7561 | { |
| 7562 | select_next_slash_menu_entry(app, slash_menu_entries.len()); |
| 7563 | } |
| 7564 | // Paging and edge motions from the shared vocabulary (#6290), |
| 7565 | // claimed before the unconditional transcript-scroll arms. |
| 7566 | KeyCode::PageUp if key.modifiers.is_empty() && slash_menu_open => { |
| 7567 | move_slash_menu_selection( |
| 7568 | app, |
| 7569 | slash_menu_entries.len(), |
| 7570 | codewhale_tui_kit::list_nav::Motion::PagePrev, |
| 7571 | ); |
| 7572 | } |
| 7573 | KeyCode::PageDown if key.modifiers.is_empty() && slash_menu_open => { |
| 7574 | move_slash_menu_selection( |
| 7575 | app, |
| 7576 | slash_menu_entries.len(), |
| 7577 | codewhale_tui_kit::list_nav::Motion::PageNext, |
| 7578 | ); |
| 7579 | } |
| 7580 | // Home/End deliberately stay cursor keys while the menu is open: |
| 7581 | // the composer is still the focused input (same as Left/Right |
| 7582 | // and the mention menu), so only vertical travel belongs to |
| 7583 | // the popup. |
| 7584 | KeyCode::Down |
| 7585 | if key.modifiers.is_empty() |
| 7586 | && app.selected_composer_attachment_index().is_some() => |
| 7587 | { |
| 7588 | let _ = app.select_next_composer_attachment(); |
| 7589 | } |
| 7590 | KeyCode::PageUp => { |
| 7591 | let page = app.viewport.last_transcript_visible.max(1); |
| 7592 | app.scroll_up(page); |
| 7593 | } |
| 7594 | KeyCode::PageDown => { |
| 7595 | let page = app.viewport.last_transcript_visible.max(1); |
| 7596 | app.scroll_down(page); |
| 7597 | } |
| 7598 | KeyCode::Tab => { |
| 7599 | dispatch_tab_key(app, &mention_menu_entries, &slash_menu_entries); |
| 7600 | continue; |
| 7601 | } |
| 7602 | // Transcript-nav shortcuts now require Alt, leaving most bare |
| 7603 | // letters free to insert as text. Requiring Alt is also why |
| 7604 | // none of them asks whether the composer is empty: an Alt |
| 7605 | // chord is never composer text, so `input.is_empty()` there |
| 7606 | // was guessing at focus and only ever broke the shortcut for |
| 7607 | // anyone mid-draft. Before v0.8.30, bare `g`, |
| 7608 | // `G`, `[`, `]`, `?`, and `l` on an empty composer were |
| 7609 | // hijacked for navigation — typing "good" yielded "ood" with |
| 7610 | // no whale and no warning. The Alt-prefixed shortcuts mirror |
| 7611 | // the Alt+R / Alt+C pattern already in use. Shift is |
| 7612 | // permitted for most capital-letter forms. |
| 7613 | KeyCode::Char('g') |
| 7614 | if key_shortcuts::alt_nav_modifiers(key.modifiers) && !slash_menu_open => |
| 7615 | { |
| 7616 | if let Some(anchor) = |
| 7617 | TranscriptScroll::anchor_for(app.viewport.transcript_cache.line_meta(), 0) |
| 7618 | { |
| 7619 | app.viewport.transcript_scroll = anchor; |
| 7620 | } |
| 7621 | } |
| 7622 | KeyCode::Char('G') |
| 7623 | if key_shortcuts::alt_nav_modifiers(key.modifiers) && !slash_menu_open => |
| 7624 | { |
| 7625 | app.scroll_to_bottom(); |
| 7626 | } |
| 7627 | KeyCode::Char('[') |
| 7628 | if key_shortcuts::alt_nav_modifiers(key.modifiers) |
| 7629 | && !slash_menu_open |
| 7630 | && !jump_to_adjacent_tool_cell(app, SearchDirection::Backward) => |
| 7631 | { |
| 7632 | app.show_input_hint("No previous tool output"); |
| 7633 | } |
| 7634 | KeyCode::Char(']') |
| 7635 | if key_shortcuts::alt_nav_modifiers(key.modifiers) |
| 7636 | && !slash_menu_open |
| 7637 | && !jump_to_adjacent_tool_cell(app, SearchDirection::Forward) => |
| 7638 | { |
| 7639 | app.show_input_hint("No next tool output"); |
| 7640 | } |
| 7641 | // Help chords (Alt+?, F1, Ctrl+/) are handled above via |
| 7642 | // shell_key_routing::is_help_shortcut so printable layout |
| 7643 | // characters stay text. |
| 7644 | // Input handling |
| 7645 | _ if is_composer_newline_key(key, app.composer_multiline_mode) |
| 7646 | && !(is_plain_enter && (slash_menu_open || mention_menu_open)) => |
| 7647 | { |
| 7648 | app.insert_char('\n'); |
| 7649 | } |
| 7650 | KeyCode::Enter |
| 7651 | if key.modifiers == KeyModifiers::NONE |
| 7652 | && mention_menu_open |
| 7653 | && crate::tui::file_mention::apply_mention_menu_selection( |
| 7654 | app, |
| 7655 | &mention_menu_entries, |
| 7656 | ) => |
| 7657 | { |
| 7658 | continue; |
| 7659 | } |
| 7660 | // Accept Ctrl+Enter when the terminal reports it distinctly. |
| 7661 | // It is deliberately not advertised because several common |
| 7662 | // terminals encode it exactly like bare Enter. |
| 7663 | _ if is_forced_submit_key(key) => { |
| 7664 | let action = app.decide_composer_submit(ComposerSubmitChord::CtrlEnter); |
| 7665 | if app.pending_fresh_session.is_some() { |
| 7666 | if submit_decided_composer_input( |
| 7667 | terminal, |
| 7668 | app, |
| 7669 | &mut engine_handle, |
| 7670 | config, |
| 7671 | action, |
| 7672 | false, |
| 7673 | event_observed_at, |
| 7674 | ) |
| 7675 | .await? |
| 7676 | { |
| 7677 | return Ok(()); |
| 7678 | } |
| 7679 | } else if let Some(input) = app.submit_input() { |
| 7680 | if handle_bang_shell_input(app, &engine_handle, &input).await? { |
| 7681 | continue; |
| 7682 | } |
| 7683 | if looks_like_slash_command_input(&input) { |
| 7684 | if execute_command_input( |
| 7685 | terminal, |
| 7686 | app, |
| 7687 | &mut engine_handle, |
| 7688 | config, |
| 7689 | &input, |
| 7690 | ) |
| 7691 | .await? |
| 7692 | { |
| 7693 | return Ok(()); |
| 7694 | } |
| 7695 | } else if dispatch_submitted_composer_message( |
| 7696 | terminal, |
| 7697 | app, |
| 7698 | &mut engine_handle, |
| 7699 | config, |
| 7700 | input, |
| 7701 | action, |
| 7702 | ) |
| 7703 | .await? |
| 7704 | { |
| 7705 | return Ok(()); |
| 7706 | } |
| 7707 | } |
| 7708 | } |
| 7709 | KeyCode::Enter => { |
| 7710 | let action = app.decide_composer_submit( |
| 7711 | portable_submit_chord.unwrap_or(ComposerSubmitChord::Enter), |
| 7712 | ); |
| 7713 | // Slash-menu selection, draft consumption, and the |
| 7714 | // memory/`!`/`/`/message branches are the shared tail the |
| 7715 | // mouse `[↵]` dispatcher also runs, so keyboard and pointer |
| 7716 | // submit behavior cannot drift apart. |
| 7717 | if submit_decided_composer_input( |
| 7718 | terminal, |
| 7719 | app, |
| 7720 | &mut engine_handle, |
| 7721 | config, |
| 7722 | action, |
| 7723 | is_plain_enter, |
| 7724 | event_observed_at, |
| 7725 | ) |
| 7726 | .await? |
| 7727 | { |
| 7728 | return Ok(()); |
| 7729 | } |
| 7730 | } |
| 7731 | KeyCode::Backspace |
| 7732 | if key.modifiers.contains(KeyModifiers::SUPER) |
| 7733 | && !app.remove_selected_composer_attachment() => |
| 7734 | { |
| 7735 | app.delete_to_start_of_line(); |
| 7736 | } |
| 7737 | KeyCode::Backspace if key.modifiers.contains(KeyModifiers::SUPER) => {} |
| 7738 | KeyCode::Backspace |
| 7739 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7740 | && !app.remove_selected_composer_attachment() => |
| 7741 | { |
| 7742 | app.delete_word_backward(); |
| 7743 | } |
| 7744 | KeyCode::Backspace if key.modifiers.contains(KeyModifiers::ALT) => {} |
| 7745 | KeyCode::Backspace |
| 7746 | if key.modifiers.contains(KeyModifiers::CONTROL) |
| 7747 | && !app.remove_selected_composer_attachment() => |
| 7748 | { |
| 7749 | app.delete_word_backward(); |
| 7750 | } |
| 7751 | KeyCode::Backspace if key.modifiers.contains(KeyModifiers::CONTROL) => {} |
| 7752 | KeyCode::Delete |
| 7753 | if key.modifiers.contains(KeyModifiers::ALT) |
| 7754 | && !app.remove_selected_composer_attachment() => |
| 7755 | { |
| 7756 | app.delete_word_forward(); |
| 7757 | } |
| 7758 | KeyCode::Delete if key.modifiers.contains(KeyModifiers::ALT) => {} |
| 7759 | KeyCode::Delete |
| 7760 | if key.modifiers.contains(KeyModifiers::CONTROL) |
| 7761 | && !app.remove_selected_composer_attachment() => |
| 7762 | { |
| 7763 | app.delete_word_forward(); |
| 7764 | } |
| 7765 | KeyCode::Delete if key.modifiers.contains(KeyModifiers::CONTROL) => {} |
| 7766 | KeyCode::Backspace if !app.remove_selected_composer_attachment() => { |
| 7767 | app.delete_char(); |
| 7768 | } |
| 7769 | KeyCode::Backspace => {} |
| 7770 | KeyCode::Char('h') |
| 7771 | if key_shortcuts::is_ctrl_h_backspace(&key) |
| 7772 | && !app.remove_selected_composer_attachment() => |
| 7773 | { |
| 7774 | app.delete_char(); |
| 7775 | } |
| 7776 | KeyCode::Char('h') if key_shortcuts::is_ctrl_h_backspace(&key) => {} |
| 7777 | KeyCode::Delete if !app.remove_selected_composer_attachment() => { |
| 7778 | app.delete_char_forward(); |
| 7779 | } |
| 7780 | KeyCode::Delete => {} |
| 7781 | _ if key_shortcuts::is_select_all_shortcut(&key) => { |
| 7782 | app.select_all(); |
| 7783 | } |
| 7784 | KeyCode::Left |
| 7785 | if key.modifiers.contains(KeyModifiers::SHIFT) |
| 7786 | && is_word_cursor_modifier(key.modifiers) => |
| 7787 | { |
| 7788 | if app.selection_anchor.is_none() { |
| 7789 | app.selection_anchor = Some(app.cursor_position); |
| 7790 | } |
| 7791 | app.move_cursor_word_backward(); |
| 7792 | } |
| 7793 | KeyCode::Left if key.modifiers.contains(KeyModifiers::SHIFT) => { |
| 7794 | if app.selection_anchor.is_none() { |
| 7795 | app.selection_anchor = Some(app.cursor_position); |
| 7796 | } |
| 7797 | app.move_cursor_left(); |
| 7798 | } |
| 7799 | KeyCode::Left if is_word_cursor_modifier(key.modifiers) => { |
| 7800 | app.clear_selection(); |
| 7801 | app.move_cursor_word_backward(); |
| 7802 | } |
| 7803 | KeyCode::Left => { |
| 7804 | app.clear_selection(); |
| 7805 | app.move_cursor_left(); |
| 7806 | } |
| 7807 | KeyCode::Right |
| 7808 | if key.modifiers.contains(KeyModifiers::SHIFT) |
| 7809 | && is_word_cursor_modifier(key.modifiers) => |
| 7810 | { |
| 7811 | if app.selection_anchor.is_none() { |
| 7812 | app.selection_anchor = Some(app.cursor_position); |
| 7813 | } |
| 7814 | app.move_cursor_word_forward(); |
| 7815 | } |
| 7816 | KeyCode::Right if key.modifiers.contains(KeyModifiers::SHIFT) => { |
| 7817 | if app.selection_anchor.is_none() { |
| 7818 | app.selection_anchor = Some(app.cursor_position); |
| 7819 | } |
| 7820 | app.move_cursor_right(); |
| 7821 | } |
| 7822 | KeyCode::Right if is_word_cursor_modifier(key.modifiers) => { |
| 7823 | app.clear_selection(); |
| 7824 | app.move_cursor_word_forward(); |
| 7825 | } |
| 7826 | KeyCode::Right => { |
| 7827 | app.clear_selection(); |
| 7828 | app.move_cursor_right(); |
| 7829 | } |
| 7830 | // Selection-extending Home/End. Ctrl+Shift extends to the |
| 7831 | // buffer edge, bare Shift to the logical line edge. These sit |
| 7832 | // above the Ctrl+Home/Ctrl+End transcript-scroll arms so the |
| 7833 | // shifted chords always edit the selection, never the |
| 7834 | // viewport. |
| 7835 | KeyCode::Home |
| 7836 | if key.modifiers.contains(KeyModifiers::SHIFT) |
| 7837 | && key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7838 | { |
| 7839 | if app.selection_anchor.is_none() { |
| 7840 | app.selection_anchor = Some(app.cursor_position); |
| 7841 | } |
| 7842 | app.move_cursor_start(); |
| 7843 | } |
| 7844 | KeyCode::End |
| 7845 | if key.modifiers.contains(KeyModifiers::SHIFT) |
| 7846 | && key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7847 | { |
| 7848 | if app.selection_anchor.is_none() { |
| 7849 | app.selection_anchor = Some(app.cursor_position); |
| 7850 | } |
| 7851 | app.move_cursor_end(); |
| 7852 | } |
| 7853 | KeyCode::Home if key.modifiers.contains(KeyModifiers::SHIFT) => { |
| 7854 | if app.selection_anchor.is_none() { |
| 7855 | app.selection_anchor = Some(app.cursor_position); |
| 7856 | } |
| 7857 | app.move_cursor_line_start(); |
| 7858 | } |
| 7859 | KeyCode::End if key.modifiers.contains(KeyModifiers::SHIFT) => { |
| 7860 | if app.selection_anchor.is_none() { |
| 7861 | app.selection_anchor = Some(app.cursor_position); |
| 7862 | } |
| 7863 | app.move_cursor_line_end(); |
| 7864 | } |
| 7865 | KeyCode::Home if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 7866 | if let Some(anchor) = |
| 7867 | TranscriptScroll::anchor_for(app.viewport.transcript_cache.line_meta(), 0) |
| 7868 | { |
| 7869 | app.viewport.transcript_scroll = anchor; |
| 7870 | } |
| 7871 | } |
| 7872 | KeyCode::End if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 7873 | app.scroll_to_bottom(); |
| 7874 | } |
| 7875 | KeyCode::Home | KeyCode::Char('a') |
| 7876 | if key.modifiers.contains(KeyModifiers::CONTROL) => |
| 7877 | { |
| 7878 | app.clear_selection(); |
| 7879 | app.move_cursor_start(); |
| 7880 | } |
| 7881 | KeyCode::Home => { |
| 7882 | app.clear_selection(); |
| 7883 | app.move_cursor_line_start(); |
| 7884 | } |
| 7885 | KeyCode::End => { |
| 7886 | app.clear_selection(); |
| 7887 | app.move_cursor_line_end(); |
| 7888 | } |
| 7889 | KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 7890 | app.clear_selection(); |
| 7891 | app.move_cursor_end(); |
| 7892 | } |
| 7893 | _ if handle_composer_alt_word_motion_key(app, key) => {} |
| 7894 | _ if crate::tui::shell_key_routing::binding( |
| 7895 | crate::tui::shell_key_routing::ShellBindingId::ExternalEditor, |
| 7896 | ) |
| 7897 | .matches(&key) => |
| 7898 | { |
| 7899 | // Ctrl+Shift+O (or F4 on terminals that cannot report the |
| 7900 | // shifted chord): spawn $EDITOR on the composer contents |
| 7901 | // (#91). Plain Ctrl+O belongs exclusively to the Turn |
| 7902 | // Inspector, even while the composer holds a draft (#4482). |
| 7903 | // Only fires when no modal is active (the !view_stack |
| 7904 | // branch above already returns early in that case) and |
| 7905 | // the composer is the focused input target. We accept the |
| 7906 | // shortcut whether or not a model turn is streaming — |
| 7907 | // editing the buffer never disturbs in-flight work. |
| 7908 | let seed = app.input.clone(); |
| 7909 | let editor_result = match terminal_input.pause_for_child_terminal().await { |
| 7910 | Err(err) => Err(err), |
| 7911 | Ok(()) => { |
| 7912 | let result = prepare_terminal_input_handoff( |
| 7913 | &terminal_input, |
| 7914 | &mut pending_terminal_events, |
| 7915 | ) |
| 7916 | .and_then(|ready| { |
| 7917 | if ready { |
| 7918 | crate::tui::external_editor::spawn_editor_for_input( |
| 7919 | terminal, |
| 7920 | app.use_mouse_capture, |
| 7921 | app.use_bracketed_paste, |
| 7922 | &seed, |
| 7923 | ) |
| 7924 | } else { |
| 7925 | Err(io::Error::new( |
| 7926 | io::ErrorKind::Interrupted, |
| 7927 | "editor handoff cancelled by pending terminal input", |
| 7928 | )) |
| 7929 | } |
| 7930 | }); |
| 7931 | terminal_input.resume_after_child_terminal(); |
| 7932 | terminal_repaint = FrameRepaint::Clear; |
| 7933 | result |
| 7934 | } |
| 7935 | }; |
| 7936 | match editor_result { |
| 7937 | Ok(crate::tui::external_editor::EditorOutcome::Edited(new)) => { |
| 7938 | app.apply_external_edit(new); |
| 7939 | let editor = std::env::var("VISUAL") |
| 7940 | .ok() |
| 7941 | .filter(|s| !s.trim().is_empty()) |
| 7942 | .or_else(|| { |
| 7943 | std::env::var("EDITOR") |
| 7944 | .ok() |
| 7945 | .filter(|s| !s.trim().is_empty()) |
| 7946 | }) |
| 7947 | .unwrap_or_else(|| "vi".to_string()); |
| 7948 | app.show_input_hint(format!("Edited in {editor}")); |
| 7949 | } |
| 7950 | Ok(crate::tui::external_editor::EditorOutcome::Unchanged) => { |
| 7951 | app.show_input_hint("Editor closed (no changes)"); |
| 7952 | } |
| 7953 | Ok(crate::tui::external_editor::EditorOutcome::Cancelled) => { |
| 7954 | app.show_input_feedback( |
| 7955 | "Editor cancelled", |
| 7956 | StatusToastLevel::Warning, |
| 7957 | 5_000, |
| 7958 | ); |
| 7959 | } |
| 7960 | Err(err) => { |
| 7961 | app.set_sticky_status( |
| 7962 | format!("Editor error: {err}"), |
| 7963 | StatusToastLevel::Error, |
| 7964 | None, |
| 7965 | ); |
| 7966 | } |
| 7967 | } |
| 7968 | app.needs_redraw = true; |
| 7969 | } |
| 7970 | KeyCode::Up => { |
| 7971 | let _ = |
| 7972 | handle_composer_history_arrow(app, key, slash_menu_open, mention_menu_open); |
| 7973 | } |
| 7974 | KeyCode::Down => { |
| 7975 | let _ = |
| 7976 | handle_composer_history_arrow(app, key, slash_menu_open, mention_menu_open); |
| 7977 | } |
| 7978 | // Ctrl+Shift+U is the shifted-Ctrl chord for `/update install` |
| 7979 | // (same family as Ctrl+Shift+A/E/O). It routes through the |
| 7980 | // exact typed-command path, so the managed-install gate and |
| 7981 | // the "already up to date" outcome are inherited from |
| 7982 | // `commands::update` rather than reimplemented here. Placed |
| 7983 | // above the readline Ctrl+U arm so the shifted chord is never |
| 7984 | // swallowed by clear-input. |
| 7985 | _ if key_shortcuts::is_update_install_shortcut(&key) => { |
| 7986 | if execute_command_input( |
| 7987 | terminal, |
| 7988 | app, |
| 7989 | &mut engine_handle, |
| 7990 | config, |
| 7991 | "/update install", |
| 7992 | ) |
| 7993 | .await? |
| 7994 | { |
| 7995 | return Ok(()); |
| 7996 | } |
| 7997 | } |
| 7998 | KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 7999 | app.clear_input_recoverable(); |
| 8000 | let _ = app.maybe_show_behavioral_tip( |
| 8001 | crate::tui::behavioral_tips::BehavioralTip::ClearedInputRestore, |
| 8002 | ); |
| 8003 | } |
| 8004 | KeyCode::Char('z') |
| 8005 | if key.modifiers.contains(KeyModifiers::CONTROL) |
| 8006 | && app.restore_last_cleared_input_if_empty() => |
| 8007 | { |
| 8008 | app.show_input_hint("Restored cleared draft"); |
| 8009 | } |
| 8010 | KeyCode::Char('w') | KeyCode::Char('W') |
| 8011 | if key.modifiers.contains(KeyModifiers::CONTROL) => |
| 8012 | { |
| 8013 | app.delete_word_backward(); |
| 8014 | } |
| 8015 | KeyCode::Char('s') |
| 8016 | | KeyCode::Char('S') |
| 8017 | | KeyCode::Char('g') |
| 8018 | | KeyCode::Char('G') |
| 8019 | if key.modifiers == KeyModifiers::CONTROL => |
| 8020 | { |
| 8021 | // #440: park the current draft to the persistent stash and |
| 8022 | // clear the composer. Ctrl+G is the terminal-safe alias for |
| 8023 | // hosts such as Cursor/VS Code that reserve Ctrl+S for Save. |
| 8024 | // Empty composers are a no-op so a stray shortcut cannot |
| 8025 | // pollute the file. Surface a toast so the user sees the |
| 8026 | // confirmation (no-op feels broken otherwise). |
| 8027 | if !app.input.is_empty() { |
| 8028 | crate::composer_stash::push_stash(&app.input); |
| 8029 | if app.queued_draft.is_some() { |
| 8030 | // Stash the edited text while preserving the |
| 8031 | // original queued follow-up in its queue slot. |
| 8032 | let _ = app.cancel_queued_draft_edit(); |
| 8033 | } else { |
| 8034 | app.clear_input_recoverable(); |
| 8035 | } |
| 8036 | app.push_status_toast( |
| 8037 | "Draft stashed — `/stash pop` to restore", |
| 8038 | StatusToastLevel::Info, |
| 8039 | Some(3_000), |
| 8040 | ); |
| 8041 | } |
| 8042 | } |
| 8043 | KeyCode::Char('y') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 8044 | // #379: context-sensitive Ctrl+Y. |
| 8045 | // When the composer has content → emacs-style yank |
| 8046 | // from the kill buffer at the cursor. |
| 8047 | // When the composer is empty (transcript focus) → |
| 8048 | // copy the focused cell text to the system clipboard. |
| 8049 | if app.input.is_empty() && app.view_stack.is_empty() { |
| 8050 | copy_focused_cell(app); |
| 8051 | } else { |
| 8052 | app.yank(); |
| 8053 | } |
| 8054 | } |
| 8055 | KeyCode::Char('x') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 8056 | crate::tui::mouse_ui::cut_selection(app); |
| 8057 | } |
| 8058 | _ if key_shortcuts::is_paste_shortcut(&key) => { |
| 8059 | crate::tui::paste::handle_paste(app, crate::tui::paste::PasteSource::Shortcut); |
| 8060 | } |
| 8061 | KeyCode::Char('a') if key.modifiers.contains(KeyModifiers::ALT) => { |
| 8062 | apply_mode_update(app, &engine_handle, AppMode::Agent).await; |
| 8063 | continue; |
| 8064 | } |
| 8065 | KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::ALT) => { |
| 8066 | apply_mode_update(app, &engine_handle, AppMode::Plan).await; |
| 8067 | continue; |
| 8068 | } |
| 8069 | KeyCode::Char('A') if key.modifiers.contains(KeyModifiers::ALT) => { |
| 8070 | apply_mode_update(app, &engine_handle, AppMode::Agent).await; |
| 8071 | continue; |
| 8072 | } |
| 8073 | KeyCode::Char('P') if key.modifiers.contains(KeyModifiers::ALT) => { |
| 8074 | apply_mode_update(app, &engine_handle, AppMode::Plan).await; |
| 8075 | continue; |
| 8076 | } |
| 8077 | // Vim composer: Normal-mode motion / operator keys. |
| 8078 | // Only fires when vim is enabled, the input is focused (no modal |
| 8079 | // open on top), and the key is a plain char (Shift allowed). |
| 8080 | KeyCode::Char(c) |
| 8081 | if app.vim_is_normal_mode() |
| 8082 | && is_plain_char |
| 8083 | && !slash_menu_open |
| 8084 | && !mention_menu_open |
| 8085 | && app.view_stack.is_empty() => |
| 8086 | { |
| 8087 | vim_mode::handle_vim_normal_key(app, c); |
| 8088 | continue; |
| 8089 | } |
| 8090 | KeyCode::Char(c) if is_plain_char => { |
| 8091 | app.insert_char(c); |
| 8092 | } |
| 8093 | KeyCode::Char(_) => {} |
| 8094 | _ => {} |
| 8095 | } |
| 8096 | |
| 8097 | if !is_plain_char && !is_plain_enter { |
| 8098 | app.paste_burst.deactivate_keep_window(); |
| 8099 | } |
| 8100 | } |
| 8101 | } |
| 8102 | } |
| 8103 | |
| 8104 | /// Apply one MCP session-boot event. Failures stay on the snapshot (and |
| 8105 | /// therefore the session page) rather than as toast-only Status copy. |
| 8106 | /// A direct `/mcp` snapshot invalidates only the event generation it |
| 8107 | /// superseded. Older spawn-time updates cannot overwrite it, while a later |
| 8108 | /// engine-authored generation can continue updating the live surface. |
| 8109 | pub(crate) fn apply_mcp_session_boot_event( |
| 8110 | app: &mut App, |
| 8111 | generation: u64, |
| 8112 | snapshot: codewhale_engine::mcp::McpManagerSnapshot, |
| 8113 | connecting: Vec<String>, |
| 8114 | finished: bool, |
| 8115 | ) { |
| 8116 | if generation < app.mcp_snapshot_generation |
| 8117 | || (generation == app.mcp_snapshot_generation && app.mcp_snapshot_generation_invalidated) |
| 8118 | { |
| 8119 | return; |
| 8120 | } |
| 8121 | app.mcp_snapshot_generation = generation; |
| 8122 | app.mcp_snapshot_generation_invalidated = false; |
| 8123 | app.mcp_configured_count = snapshot.servers.len(); |
| 8124 | app.hotbar_actions.replace_mcp_tools(Some(&snapshot)); |
| 8125 | if finished { |
| 8126 | announce_mcp_problem_changes(app, &snapshot); |
| 8127 | } |
| 8128 | if finished && app.mcp_reload_in_flight { |
| 8129 | // One completion receipt for the explicit reload that started this |
| 8130 | // pass; session boot never sets the flag. |
| 8131 | app.mcp_reload_in_flight = false; |
| 8132 | crate::tui::mcp_routing::add_mcp_message( |
| 8133 | app, |
| 8134 | crate::tui::ui::provider_routes::mcp_reload_summary(&snapshot), |
| 8135 | ); |
| 8136 | } |
| 8137 | app.mcp_snapshot = Some(snapshot); |
| 8138 | app.mcp_connecting = connecting; |
| 8139 | app.set_mcp_boot_initializing(!finished); |
| 8140 | app.needs_redraw = true; |
| 8141 | } |
| 8142 | |
| 8143 | fn announce_mcp_problem_changes( |
| 8144 | app: &mut App, |
| 8145 | snapshot: &codewhale_engine::mcp::McpManagerSnapshot, |
| 8146 | ) { |
| 8147 | use crate::tui::session_boot::{ |
| 8148 | PluginBootSummary, SessionBootActivityLevel, SessionBootSurface, |
| 8149 | }; |
| 8150 | let surface = SessionBootSurface::from_parts( |
| 8151 | Some(snapshot), |
| 8152 | false, |
| 8153 | &[], |
| 8154 | snapshot.servers.len(), |
| 8155 | PluginBootSummary::default(), |
| 8156 | ); |
| 8157 | let Some((chip, fallbacks)) = surface |
| 8158 | .announce_problem_changes_with_fallbacks(app.ui_locale, &mut app.mcp_announced_problems) |
| 8159 | else { |
| 8160 | return; |
| 8161 | }; |
| 8162 | if app.launch.visible || app.mcp_reload_in_flight { |
| 8163 | return; |
| 8164 | } |
| 8165 | let level = if chip.level == SessionBootActivityLevel::Active { |
| 8166 | StatusToastLevel::Info |
| 8167 | } else { |
| 8168 | StatusToastLevel::Warning |
| 8169 | }; |
| 8170 | app.push_status_toast_record( |
| 8171 | crate::tui::app::StatusToast::new(chip.text, level, Some(12_000)).with_fallbacks(fallbacks), |
| 8172 | ); |
| 8173 | } |
| 8174 | |
| 8175 | pub(crate) async fn run_cache_warmup(app: &App, config: &Config) -> Result<CacheWarmupOutcome> { |
| 8176 | let route = resolve_cache_replay_route(app, config)? |
| 8177 | .validate_async() |
| 8178 | .await |
| 8179 | .map_err(anyhow::Error::msg)?; |
| 8180 | let base_url = route.client.base_url().to_string(); |
| 8181 | let reasoning_effort = app |
| 8182 | .reasoning_effort_api_value_for_replay( |
| 8183 | route.identity.provider, |
| 8184 | route.identity.key.as_str(), |
| 8185 | &base_url, |
| 8186 | &route.model, |
| 8187 | ) |
| 8188 | .map(str::to_string); |
| 8189 | let request = MessageRequest { |
| 8190 | model: route.model.clone(), |
| 8191 | messages: app.api_messages.as_ref().clone(), |
| 8192 | max_tokens: CACHE_WARMUP_MAX_TOKENS, |
| 8193 | system: app.system_prompt.clone(), |
| 8194 | tools: app.session.last_tool_catalog.clone(), |
| 8195 | tool_choice: None, |
| 8196 | metadata: None, |
| 8197 | thinking: None, |
| 8198 | reasoning_effort, |
| 8199 | stream: None, |
| 8200 | temperature: None, |
| 8201 | top_p: None, |
| 8202 | safety_check: None, |
| 8203 | title: None, |
| 8204 | }; |
| 8205 | let warmup = build_cache_warmup_request(&request); |
| 8206 | let inspection = inspect_prompt_for_request(&warmup); |
| 8207 | let response = |
| 8208 | tokio::time::timeout(Duration::from_secs(45), route.client.create_message(warmup)) |
| 8209 | .await??; |
| 8210 | Ok(CacheWarmupOutcome { |
| 8211 | usage: response.usage, |
| 8212 | tool_projection_warning: response.tool_projection_warning, |
| 8213 | provider_identity: route.identity.key.to_string(), |
| 8214 | model: route.model, |
| 8215 | base_url, |
| 8216 | inspection, |
| 8217 | }) |
| 8218 | } |
| 8219 | |
| 8220 | /// Whether the telemetry disclosure may become a transcript cell now: never |
| 8221 | /// while the launch card can still come back, since a cell hides the card, |
| 8222 | /// and never under a live active cell, whose tool indices address |
| 8223 | /// `history ++ active_cell`. |
| 8224 | /// |
| 8225 | /// A dissolving card is not a departed one: Esc on an empty composer, or |
| 8226 | /// leaving the session picker, restores it, and it only renders over an |
| 8227 | /// empty history. So the cell waits until the card is dismissed or the |
| 8228 | /// conversation has its first entry. |
| 8229 | fn telemetry_notice_may_enter_transcript(app: &App) -> bool { |
| 8230 | let card_leaving = !app.launch.visible || !app.history.is_empty(); |
| 8231 | let no_live_cell = app |
| 8232 | .active_cell |
| 8233 | .as_ref() |
| 8234 | .is_none_or(crate::tui::active_cell::ActiveCell::is_empty); |
| 8235 | card_leaving && no_live_cell |
| 8236 | } |
| 8237 | |
| 8238 | /// Switch a first-run / missing-key session onto a live local Ollama tag. |
| 8239 | pub(super) async fn adopt_live_local_ollama_catalog( |
| 8240 | app: &mut App, |
| 8241 | engine_handle: &mut EngineHandle, |
| 8242 | config: &mut Config, |
| 8243 | catalog: codewhale_engine::local_ollama::LiveLocalOllamaCatalog, |
| 8244 | ) { |
| 8245 | if !app.should_adopt_live_local_ollama() { |
| 8246 | return; |
| 8247 | } |
| 8248 | let Some(tag) = catalog.preferred_tag().map(str::to_string) else { |
| 8249 | return; |
| 8250 | }; |
| 8251 | // switch_provider resolves against the lake we just refreshed. |
| 8252 | let identity = match config.builtin_provider_identity(ProviderKind::Ollama) { |
| 8253 | Ok(identity) => identity, |
| 8254 | Err(error) => { |
| 8255 | app.push_status_toast(error, StatusToastLevel::Error, None); |
| 8256 | return; |
| 8257 | } |
| 8258 | }; |
| 8259 | let switched = super::provider_routes::switch_provider_with_ollama_probe( |
| 8260 | app, |
| 8261 | engine_handle, |
| 8262 | config, |
| 8263 | identity, |
| 8264 | tag.clone(), |
| 8265 | &catalog.endpoint_v1, |
| 8266 | &catalog.ticket, |
| 8267 | ) |
| 8268 | .await; |
| 8269 | if !switched { |
| 8270 | return; |
| 8271 | } |
| 8272 | app.onboarding_needs_api_key = false; |
| 8273 | app.onboarding_missing_key_recovery = false; |
| 8274 | // A launch with no key opens the provider picker (#6566). The local model |
| 8275 | // just answered that question, so close the picker and advance past its |
| 8276 | // onboarding step rather than leave a stale "connect a model" screen whose |
| 8277 | // Esc would now walk back to the welcome screen. |
| 8278 | if app.onboarding == OnboardingState::Provider { |
| 8279 | if app.view_stack.top_kind() == Some(ModalKind::ProviderPicker) { |
| 8280 | app.view_stack.pop(); |
| 8281 | } |
| 8282 | crate::tui::onboarding::advance_onboarding_after_provider(app); |
| 8283 | } |
| 8284 | // Say plainly which model is in use and how to change it, instead of the |
| 8285 | // endpoint it was discovered from (#6566). |
| 8286 | let adopted = app |
| 8287 | .tr(MessageId::LocalModelAdopted) |
| 8288 | .replace("{model}", &tag); |
| 8289 | app.show_event_notice(adopted, StatusToastLevel::Success); |
| 8290 | app.needs_redraw = true; |
| 8291 | } |
| 8292 | |
| 8293 | pub(crate) async fn run_prepared_dispatch( |
| 8294 | app: &mut App, |
| 8295 | config: &Config, |
| 8296 | engine_handle: &EngineHandle, |
| 8297 | prepare: UserDispatchPrepare, |
| 8298 | recovery: DispatchRecovery, |
| 8299 | ) -> Result<()> { |
| 8300 | // Unit tests that intentionally omit the production completion mailbox |
| 8301 | // apply the result inline. Run the owned async phase as a task just like |
| 8302 | // production does so its large future is polled from a clean executor |
| 8303 | // stack instead of nesting under the test helper's call chain. |
| 8304 | let apply = tokio::spawn(spawned_dispatch_inner( |
| 8305 | prepare, |
| 8306 | recovery, |
| 8307 | engine_handle.clone(), |
| 8308 | )) |
| 8309 | .await |
| 8310 | .map_err(|err| anyhow::anyhow!("dispatch task was lost: {err}"))?; |
| 8311 | apply(app, engine_handle, config) |
| 8312 | } |
| 8313 | |
| 8314 | pub(crate) async fn run_xai_device_login_from_tui( |
| 8315 | terminal: &mut AppTerminal, |
| 8316 | app: &mut App, |
| 8317 | engine_handle: &mut EngineHandle, |
| 8318 | config: &mut Config, |
| 8319 | ) -> Result<bool> { |
| 8320 | pause_terminal(terminal, app.use_mouse_capture, app.use_bracketed_paste)?; |
| 8321 | let login_result = |
| 8322 | codewhale_runtime::oauth::login(codewhale_runtime::oauth::OAuthProvider::Xai).await; |
| 8323 | resume_terminal( |
| 8324 | terminal, |
| 8325 | app.use_mouse_capture, |
| 8326 | app.use_bracketed_paste, |
| 8327 | app.synchronized_output_enabled, |
| 8328 | )?; |
| 8329 | |
| 8330 | let switched = match login_result { |
| 8331 | Ok(pending) => { |
| 8332 | apply_codewhale_owned_xai_login( |
| 8333 | app, |
| 8334 | engine_handle, |
| 8335 | config, |
| 8336 | pending, |
| 8337 | "xAI device login complete", |
| 8338 | ) |
| 8339 | .await |
| 8340 | } |
| 8341 | Err(err) => { |
| 8342 | let message = format!("xAI device login failed: {err}"); |
| 8343 | app.add_message(HistoryCell::System { |
| 8344 | content: message.clone(), |
| 8345 | }); |
| 8346 | app.show_event_notice(message, StatusToastLevel::Error); |
| 8347 | false |
| 8348 | } |
| 8349 | }; |
| 8350 | app.needs_redraw = true; |
| 8351 | Ok(switched) |
| 8352 | } |
| 8353 | |
| 8354 | pub(crate) async fn run_plugin_oauth_from_tui( |
| 8355 | terminal: &mut AppTerminal, |
| 8356 | app: &mut App, |
| 8357 | config: &mut Config, |
| 8358 | provider: String, |
| 8359 | logout: bool, |
| 8360 | ) -> Result<()> { |
| 8361 | let entry = match codewhale_plugins::providers::plugin_auth_entry(config, &provider) { |
| 8362 | Ok(entry) => entry, |
| 8363 | Err(error) => { |
| 8364 | app.push_status_toast( |
| 8365 | error.to_string(), |
| 8366 | StatusToastLevel::Error, |
| 8367 | Some(App::STICKY_ERROR_TTL_MS), |
| 8368 | ); |
| 8369 | return Ok(()); |
| 8370 | } |
| 8371 | }; |
| 8372 | let identity = config |
| 8373 | .resolve_provider_pin_identity(&provider) |
| 8374 | .map_err(anyhow::Error::msg)?; |
| 8375 | pause_terminal(terminal, app.use_mouse_capture, app.use_bracketed_paste)?; |
| 8376 | let result: Result<()> = async { |
| 8377 | let base_url = entry.base_url.clone().context("Missing plugin endpoint")?; |
| 8378 | let oauth = entry |
| 8379 | .oauth |
| 8380 | .clone() |
| 8381 | .context("Missing plugin OAuth declaration")?; |
| 8382 | let authority = entry |
| 8383 | .plugin_authority |
| 8384 | .clone() |
| 8385 | .context("Missing plugin review")?; |
| 8386 | if logout { |
| 8387 | let provider = provider.clone(); |
| 8388 | let policy = codewhale_plugins::activation::extension_host_policy_enabled(); |
| 8389 | tokio::task::spawn_blocking(move || { |
| 8390 | let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy); |
| 8391 | codewhale_plugins::providers::verify_provider_binding( |
| 8392 | &authority, &provider, &base_url, &oauth, None, |
| 8393 | ) |
| 8394 | .map_err(anyhow::Error::msg)?; |
| 8395 | codewhale_runtime::oauth::plugin_oauth_logout(&provider, &base_url, &oauth) |
| 8396 | }) |
| 8397 | .await??; |
| 8398 | } else { |
| 8399 | codewhale_plugins::providers::plugin_oauth_login( |
| 8400 | provider.clone(), |
| 8401 | base_url, |
| 8402 | oauth, |
| 8403 | authority, |
| 8404 | ) |
| 8405 | .await?; |
| 8406 | } |
| 8407 | let base_url = config.base_url_for_route(&identity); |
| 8408 | codewhale_engine::provider_catalog_live::begin_refresh_for_identity( |
| 8409 | identity.provider, |
| 8410 | &provider, |
| 8411 | &base_url, |
| 8412 | ); |
| 8413 | if !logout { |
| 8414 | let mut scoped = config.clone(); |
| 8415 | scoped |
| 8416 | .scope_to_provider_identity(&identity) |
| 8417 | .map_err(anyhow::Error::msg)?; |
| 8418 | let ticket = codewhale_engine::provider_catalog_live::begin_scoped_refresh( |
| 8419 | &scoped, &identity, &base_url, |
| 8420 | ) |
| 8421 | .map_err(anyhow::Error::msg)?; |
| 8422 | let client = codewhale_engine::client::CodewhaleClient::for_catalog_refresh(&scoped)?; |
| 8423 | let delta = client |
| 8424 | .fetch_catalog_delta() |
| 8425 | .await |
| 8426 | .map_err(|error| anyhow::anyhow!("{error:?}"))?; |
| 8427 | codewhale_engine::provider_catalog_live::record_success_if_current(&ticket, delta) |
| 8428 | .context("Catalog refresh superseded")?; |
| 8429 | } |
| 8430 | Ok(()) |
| 8431 | } |
| 8432 | .await; |
| 8433 | resume_terminal( |
| 8434 | terminal, |
| 8435 | app.use_mouse_capture, |
| 8436 | app.use_bracketed_paste, |
| 8437 | app.synchronized_output_enabled, |
| 8438 | )?; |
| 8439 | match result { |
| 8440 | Ok(()) => { |
| 8441 | let message = if logout { |
| 8442 | MessageId::PluginOAuthLocalLogout |
| 8443 | } else { |
| 8444 | MessageId::PluginOAuthReady |
| 8445 | }; |
| 8446 | app.push_status_toast( |
| 8447 | tr(app.ui_locale, message).replace("{provider}", &provider), |
| 8448 | StatusToastLevel::Success, |
| 8449 | Some(8_000), |
| 8450 | ); |
| 8451 | if !logout { |
| 8452 | open_model_picker_for_provider(app, config, &identity); |
| 8453 | } |
| 8454 | } |
| 8455 | Err(error) => app.push_status_toast( |
| 8456 | format!("{provider}: {error}"), |
| 8457 | StatusToastLevel::Error, |
| 8458 | Some(App::STICKY_ERROR_TTL_MS), |
| 8459 | ), |
| 8460 | } |
| 8461 | app.needs_redraw = true; |
| 8462 | Ok(()) |
| 8463 | } |
| 8464 | |
| 8465 | pub(crate) async fn run_chatgpt_pkce_login_from_tui( |
| 8466 | terminal: &mut AppTerminal, |
| 8467 | app: &mut App, |
| 8468 | engine_handle: &mut EngineHandle, |
| 8469 | config: &mut Config, |
| 8470 | ) -> Result<bool> { |
| 8471 | pause_terminal(terminal, app.use_mouse_capture, app.use_bracketed_paste)?; |
| 8472 | let login_result = codewhale_runtime::oauth::login_with_config( |
| 8473 | codewhale_runtime::oauth::OAuthProvider::Chatgpt, |
| 8474 | config, |
| 8475 | ) |
| 8476 | .await; |
| 8477 | resume_terminal( |
| 8478 | terminal, |
| 8479 | app.use_mouse_capture, |
| 8480 | app.use_bracketed_paste, |
| 8481 | app.synchronized_output_enabled, |
| 8482 | )?; |
| 8483 | |
| 8484 | let switched = match login_result { |
| 8485 | Ok(pending) => { |
| 8486 | apply_codewhale_owned_chatgpt_login( |
| 8487 | app, |
| 8488 | engine_handle, |
| 8489 | config, |
| 8490 | pending, |
| 8491 | "ChatGPT sign-in complete", |
| 8492 | ) |
| 8493 | .await |
| 8494 | } |
| 8495 | Err(err) => { |
| 8496 | let message = format!("ChatGPT sign-in failed: {err}"); |
| 8497 | app.add_message(HistoryCell::System { |
| 8498 | content: message.clone(), |
| 8499 | }); |
| 8500 | app.show_event_notice(message, StatusToastLevel::Error); |
| 8501 | false |
| 8502 | } |
| 8503 | }; |
| 8504 | app.needs_redraw = true; |
| 8505 | Ok(switched) |
| 8506 | } |
| 8507 | |
| 8508 | /// OrcaRouter PKCE sign-in from the `/auth orcarouter` command and the provider |
| 8509 | /// picker's "Connect with OrcaRouter" option. |
| 8510 | /// |
| 8511 | /// The TUI is suspended for the same reason as ChatGPT/Xai sign-in: the flow |
| 8512 | /// prints the consent URL and blocks on a loopback callback, so it must own the |
| 8513 | /// terminal. Unlike those flows it returns an [`codewhale_runtime::oauth::OrcaCredential`] — |
| 8514 | /// a durable API key — which is stored through the ordinary provider credential |
| 8515 | /// path, so the live route ends up identical to the API-key adapter's. |
| 8516 | pub(crate) async fn run_orcarouter_pkce_login_from_tui( |
| 8517 | terminal: &mut AppTerminal, |
| 8518 | app: &mut App, |
| 8519 | engine_handle: &mut EngineHandle, |
| 8520 | config: &mut Config, |
| 8521 | ) -> Result<bool> { |
| 8522 | pause_terminal(terminal, app.use_mouse_capture, app.use_bracketed_paste)?; |
| 8523 | let login_result = tokio::task::spawn_blocking(|| { |
| 8524 | let inputs = codewhale_runtime::oauth::OrcaLoginInputs::from_env(); |
| 8525 | let mut challenge = codewhale_runtime::oauth::cli_challenge_writer()?; |
| 8526 | codewhale_runtime::oauth::orcarouter_pkce_login(&inputs, challenge.as_mut()) |
| 8527 | }) |
| 8528 | .await |
| 8529 | .context("OrcaRouter PKCE login worker failed") |
| 8530 | .and_then(|result| result); |
| 8531 | resume_terminal( |
| 8532 | terminal, |
| 8533 | app.use_mouse_capture, |
| 8534 | app.use_bracketed_paste, |
| 8535 | app.synchronized_output_enabled, |
| 8536 | )?; |
| 8537 | |
| 8538 | let mut login_message = "OrcaRouter sign-in complete".to_string(); |
| 8539 | let switched = match login_result { |
| 8540 | Ok(credential) => { |
| 8541 | let scope_note = (!credential.scope_satisfies_purpose()).then(|| { |
| 8542 | format!( |
| 8543 | "OrcaRouter granted scope \"{}\" while this client asked for \"{}\"; the narrower grant is reused as-is.", |
| 8544 | credential.granted_scope(), |
| 8545 | codewhale_runtime::oauth::ORCAROUTER_SCOPE |
| 8546 | ) |
| 8547 | }); |
| 8548 | match codewhale_runtime::oauth::activate_orcarouter_credential(&credential, config) { |
| 8549 | Ok(saved) => { |
| 8550 | login_message = format!( |
| 8551 | "OrcaRouter is ready; stored the key in {}", |
| 8552 | saved.describe() |
| 8553 | ); |
| 8554 | if let Some(note) = scope_note { |
| 8555 | login_message.push('\n'); |
| 8556 | login_message.push_str(¬e); |
| 8557 | } |
| 8558 | apply_orcarouter_credential_login(app, engine_handle, config).await |
| 8559 | } |
| 8560 | Err(err) => { |
| 8561 | let message = format!("OrcaRouter sign-in failed: {err:#}"); |
| 8562 | app.add_message(HistoryCell::System { |
| 8563 | content: message.clone(), |
| 8564 | }); |
| 8565 | app.show_event_notice(message, StatusToastLevel::Error); |
| 8566 | false |
| 8567 | } |
| 8568 | } |
| 8569 | } |
| 8570 | Err(err) => { |
| 8571 | let message = format!("OrcaRouter sign-in failed: {err:#}"); |
| 8572 | app.add_message(HistoryCell::System { |
| 8573 | content: message.clone(), |
| 8574 | }); |
| 8575 | app.show_event_notice(message, StatusToastLevel::Error); |
| 8576 | false |
| 8577 | } |
| 8578 | }; |
| 8579 | app.needs_redraw = true; |
| 8580 | if switched { |
| 8581 | app.add_message(HistoryCell::System { |
| 8582 | content: login_message, |
| 8583 | }); |
| 8584 | } |
| 8585 | Ok(switched) |
| 8586 | } |
| 8587 | |
| 8588 | /// Switch the live route onto OrcaRouter after its credential landed, using the |
| 8589 | /// same store the API-key adapter wrote to. The key itself never passes through |
| 8590 | /// here — only the identity. |
| 8591 | async fn apply_orcarouter_credential_login( |
| 8592 | app: &mut App, |
| 8593 | engine_handle: &mut EngineHandle, |
| 8594 | config: &mut Config, |
| 8595 | ) -> bool { |
| 8596 | let identity = match config.builtin_provider_identity(ProviderKind::Orcarouter) { |
| 8597 | Ok(identity) => identity, |
| 8598 | Err(reason) => { |
| 8599 | app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000)); |
| 8600 | return false; |
| 8601 | } |
| 8602 | }; |
| 8603 | switch_provider(app, engine_handle, config, identity, None).await |
| 8604 | } |
| 8605 | |
| 8606 | /// Move held permission receipts into the transcript: those for `tool_id` |
| 8607 | /// when given, otherwise every remaining one. Returns whether anything moved. |
| 8608 | pub(super) fn flush_gate_receipts_for(app: &mut App, tool_id: Option<&str>) -> bool { |
| 8609 | let (ready, held): (Vec<_>, Vec<_>) = std::mem::take(&mut app.pending_gate_receipts) |
| 8610 | .into_iter() |
| 8611 | .partition(|(id, _)| tool_id.is_none_or(|wanted| id == wanted)); |
| 8612 | app.pending_gate_receipts = held; |
| 8613 | let moved = !ready.is_empty(); |
| 8614 | for (_, content) in ready { |
| 8615 | app.add_message(HistoryCell::System { content }); |
| 8616 | } |
| 8617 | moved |
| 8618 | } |
| 8619 | |
| 8620 | /// Open the `/agents` register (the manage view: focus, stop, refresh) and ask |
| 8621 | /// the engine for a fresh listing. |
| 8622 | async fn open_agents_register(app: &mut App, engine_handle: &EngineHandle) { |
| 8623 | if app.view_stack.top_kind() != Some(ModalKind::SubAgents) { |
| 8624 | let agents = subagent_view_agents(app, &app.subagent_cache); |
| 8625 | app.view_stack |
| 8626 | .push(crate::tui::views::SubAgentsView::for_app(app, agents)); |
| 8627 | } |
| 8628 | let _ = engine_handle.try_send(Op::ListSubAgents); |
| 8629 | app.needs_redraw = true; |
| 8630 | } |
| 8631 | |
| 8632 | #[cfg(test)] |
| 8633 | mod session_boot_event_tests { |
| 8634 | use super::*; |
| 8635 | use codewhale_engine::mcp::{ |
| 8636 | McpManagerSnapshot, McpServerCapabilityMetadata, McpServerSnapshot, |
| 8637 | }; |
| 8638 | use std::path::PathBuf; |
| 8639 | |
| 8640 | fn server(name: &str, connected: bool) -> McpServerSnapshot { |
| 8641 | McpServerSnapshot { |
| 8642 | name: name.to_string(), |
| 8643 | enabled: true, |
| 8644 | required: false, |
| 8645 | transport: "stdio".to_string(), |
| 8646 | command_or_url: format!("cmd-{name}"), |
| 8647 | connect_timeout: 5, |
| 8648 | execute_timeout: 5, |
| 8649 | read_timeout: 5, |
| 8650 | connected, |
| 8651 | error: None, |
| 8652 | auth_required: false, |
| 8653 | capability_metadata: McpServerCapabilityMetadata::NotObserved, |
| 8654 | tools: Vec::new(), |
| 8655 | resources: Vec::new(), |
| 8656 | prompts: Vec::new(), |
| 8657 | } |
| 8658 | } |
| 8659 | |
| 8660 | fn snapshot(servers: Vec<McpServerSnapshot>) -> McpManagerSnapshot { |
| 8661 | McpManagerSnapshot { |
| 8662 | config_path: PathBuf::from("mcp.json"), |
| 8663 | config_exists: true, |
| 8664 | reload_required: false, |
| 8665 | servers, |
| 8666 | } |
| 8667 | } |
| 8668 | |
| 8669 | fn test_app() -> App { |
| 8670 | crate::tui::test_support::test_app_with_options(crate::tui::test_support::test_tui_options( |
| 8671 | PathBuf::from("."), |
| 8672 | )) |
| 8673 | } |
| 8674 | |
| 8675 | #[test] |
| 8676 | fn boot_event_names_every_connecting_server_on_the_app() { |
| 8677 | let mut app = test_app(); |
| 8678 | apply_mcp_session_boot_event( |
| 8679 | &mut app, |
| 8680 | 1, |
| 8681 | snapshot(vec![server("alpha", false), server("beta", false)]), |
| 8682 | vec!["alpha".into(), "beta".into()], |
| 8683 | false, |
| 8684 | ); |
| 8685 | assert!(app.mcp_initializing); |
| 8686 | assert_eq!(app.mcp_connecting, vec!["alpha", "beta"]); |
| 8687 | assert_eq!(app.mcp_configured_count, 2); |
| 8688 | let surface = crate::tui::session_boot::SessionBootSurface::from_app(&app); |
| 8689 | let chip = surface |
| 8690 | .activity_notice(80) |
| 8691 | .map(|notice| notice.text) |
| 8692 | .expect("chip"); |
| 8693 | assert!(chip.contains("alpha"), "{chip}"); |
| 8694 | assert!(chip.contains("beta"), "{chip}"); |
| 8695 | assert!(!chip.to_ascii_lowercase().contains("slack"), "{chip}"); |
| 8696 | } |
| 8697 | |
| 8698 | /// #7035: a boot prediction that outlives the pass must stop painting. |
| 8699 | /// The pass can die without ever posting its finished event, and the old |
| 8700 | /// flag had no age, so the surface said "connecting" indefinitely. |
| 8701 | #[test] |
| 8702 | fn a_boot_prediction_past_its_horizon_stops_claiming_to_connect() { |
| 8703 | use crate::tui::session_boot::MCP_BOOT_PREDICTION_HORIZON; |
| 8704 | use std::time::Duration; |
| 8705 | |
| 8706 | let mut app = test_app(); |
| 8707 | app.mcp_connecting = vec!["alpha".into()]; |
| 8708 | apply_mcp_session_boot_event( |
| 8709 | &mut app, |
| 8710 | 1, |
| 8711 | snapshot(vec![server("alpha", false)]), |
| 8712 | vec!["alpha".into()], |
| 8713 | false, |
| 8714 | ); |
| 8715 | let predicted_at = app.mcp_boot_predicted_at.expect("a stamp for the guess"); |
| 8716 | |
| 8717 | // A later progress event re-asserts the prediction without restarting |
| 8718 | // its clock, or a talkative pass that never finishes would live on. |
| 8719 | apply_mcp_session_boot_event( |
| 8720 | &mut app, |
| 8721 | 2, |
| 8722 | snapshot(vec![server("alpha", false)]), |
| 8723 | vec!["alpha".into()], |
| 8724 | false, |
| 8725 | ); |
| 8726 | assert_eq!(app.mcp_boot_predicted_at, Some(predicted_at)); |
| 8727 | |
| 8728 | assert!(app.mcp_boot_initializing_at(predicted_at)); |
| 8729 | assert!(!app.mcp_boot_initializing_at( |
| 8730 | predicted_at + MCP_BOOT_PREDICTION_HORIZON + Duration::from_secs(1) |
| 8731 | )); |
| 8732 | |
| 8733 | app.needs_redraw = false; |
| 8734 | let past_horizon = predicted_at + MCP_BOOT_PREDICTION_HORIZON + Duration::from_secs(1); |
| 8735 | app.settle_stale_mcp_boot_prediction_at(past_horizon); |
| 8736 | assert!(!app.mcp_initializing); |
| 8737 | assert_eq!(app.mcp_boot_predicted_at, None); |
| 8738 | assert!(app.mcp_connecting.is_empty()); |
| 8739 | assert!(app.needs_redraw, "the stale rows must leave the screen"); |
| 8740 | } |
| 8741 | |
| 8742 | #[test] |
| 8743 | fn direct_mcp_snapshot_rejects_an_unseen_older_boot_generation() { |
| 8744 | let mut app = test_app(); |
| 8745 | assert_eq!(app.mcp_snapshot_generation, 0); |
| 8746 | app.mcp_snapshot = Some(snapshot(vec![server("direct", true)])); |
| 8747 | // The direct engine response carries generation 2 even though the UI |
| 8748 | // has not rendered queued boot generation 1 yet. |
| 8749 | app.mcp_snapshot_generation = 2; |
| 8750 | app.mcp_snapshot_generation_invalidated = true; |
| 8751 | app.mcp_connecting = vec!["alpha".into()]; |
| 8752 | apply_mcp_session_boot_event( |
| 8753 | &mut app, |
| 8754 | 1, |
| 8755 | snapshot(vec![server("stale", true)]), |
| 8756 | vec!["stale".into()], |
| 8757 | true, |
| 8758 | ); |
| 8759 | assert_eq!(app.mcp_connecting, vec!["alpha"]); |
| 8760 | assert_eq!( |
| 8761 | app.mcp_snapshot |
| 8762 | .as_ref() |
| 8763 | .and_then(|snapshot| snapshot.servers.first()) |
| 8764 | .map(|server| server.name.as_str()), |
| 8765 | Some("direct") |
| 8766 | ); |
| 8767 | |
| 8768 | // A queued event emitted by the direct operation itself is the same |
| 8769 | // generation and cannot replace the already-applied response. |
| 8770 | apply_mcp_session_boot_event( |
| 8771 | &mut app, |
| 8772 | 2, |
| 8773 | snapshot(vec![server("same-pass", true)]), |
| 8774 | Vec::new(), |
| 8775 | true, |
| 8776 | ); |
| 8777 | assert_eq!( |
| 8778 | app.mcp_snapshot |
| 8779 | .as_ref() |
| 8780 | .and_then(|snapshot| snapshot.servers.first()) |
| 8781 | .map(|server| server.name.as_str()), |
| 8782 | Some("direct") |
| 8783 | ); |
| 8784 | |
| 8785 | apply_mcp_session_boot_event( |
| 8786 | &mut app, |
| 8787 | 3, |
| 8788 | snapshot(vec![server("fresh", true)]), |
| 8789 | Vec::new(), |
| 8790 | true, |
| 8791 | ); |
| 8792 | assert_eq!(app.mcp_snapshot_generation, 3); |
| 8793 | assert!(!app.mcp_snapshot_generation_invalidated); |
| 8794 | assert_eq!( |
| 8795 | app.mcp_snapshot |
| 8796 | .as_ref() |
| 8797 | .and_then(|snapshot| snapshot.servers.first()) |
| 8798 | .map(|server| server.name.as_str()), |
| 8799 | Some("fresh") |
| 8800 | ); |
| 8801 | } |
| 8802 | |
| 8803 | fn failed_server(name: &str, error: &str) -> McpServerSnapshot { |
| 8804 | let mut s = server(name, false); |
| 8805 | s.error = Some(error.to_string()); |
| 8806 | s |
| 8807 | } |
| 8808 | |
| 8809 | fn mcp_toasts(app: &App) -> Vec<String> { |
| 8810 | app.status_toasts |
| 8811 | .iter() |
| 8812 | .filter(|toast| toast.text.starts_with("MCP")) |
| 8813 | .map(|toast| toast.text.clone()) |
| 8814 | .collect() |
| 8815 | } |
| 8816 | |
| 8817 | #[test] |
| 8818 | fn mcp_toasts_are_suppressed_while_launch_card_is_visible() { |
| 8819 | let mut app = test_app(); |
| 8820 | app.launch.visible = true; |
| 8821 | let snap = snapshot(vec![failed_server("alpha", "transport closed")]); |
| 8822 | apply_mcp_session_boot_event(&mut app, 1, snap.clone(), Vec::new(), true); |
| 8823 | assert!(mcp_toasts(&app).is_empty()); |
| 8824 | assert!(app.mcp_announced_problems.contains_key("alpha")); |
| 8825 | |
| 8826 | app.launch.visible = false; |
| 8827 | apply_mcp_session_boot_event(&mut app, 2, snap, Vec::new(), true); |
| 8828 | assert!(mcp_toasts(&app).is_empty()); |
| 8829 | |
| 8830 | apply_mcp_session_boot_event( |
| 8831 | &mut app, |
| 8832 | 3, |
| 8833 | snapshot(vec![server("alpha", true)]), |
| 8834 | Vec::new(), |
| 8835 | true, |
| 8836 | ); |
| 8837 | assert_eq!(mcp_toasts(&app), vec!["MCP · alpha connected"]); |
| 8838 | } |
| 8839 | |
| 8840 | #[test] |
| 8841 | fn mcp_toasts_are_suppressed_during_mcp_reload() { |
| 8842 | let mut app = test_app(); |
| 8843 | app.launch.visible = false; |
| 8844 | app.mcp_reload_in_flight = true; |
| 8845 | let snap = snapshot(vec![failed_server("alpha", "transport closed")]); |
| 8846 | apply_mcp_session_boot_event(&mut app, 1, snap.clone(), Vec::new(), true); |
| 8847 | assert!(mcp_toasts(&app).is_empty()); |
| 8848 | assert!(!app.mcp_reload_in_flight); |
| 8849 | assert!(app.mcp_announced_problems.contains_key("alpha")); |
| 8850 | |
| 8851 | apply_mcp_session_boot_event(&mut app, 2, snap, Vec::new(), true); |
| 8852 | assert!(mcp_toasts(&app).is_empty()); |
| 8853 | } |
| 8854 | |
| 8855 | #[test] |
| 8856 | fn mcp_announced_problems_clear_on_session_change() { |
| 8857 | let mut app = test_app(); |
| 8858 | app.launch.visible = false; |
| 8859 | app.set_current_session_id(Some("session-1".to_string())); |
| 8860 | let snap = snapshot(vec![failed_server("alpha", "transport closed")]); |
| 8861 | apply_mcp_session_boot_event(&mut app, 1, snap.clone(), Vec::new(), true); |
| 8862 | assert_eq!(mcp_toasts(&app), vec!["MCP · failed: alpha · /mcp"]); |
| 8863 | app.status_toasts.clear(); |
| 8864 | |
| 8865 | app.set_current_session_id(Some("session-1".to_string())); |
| 8866 | apply_mcp_session_boot_event(&mut app, 2, snap.clone(), Vec::new(), true); |
| 8867 | assert!(mcp_toasts(&app).is_empty()); |
| 8868 | |
| 8869 | app.set_current_session_id(Some("session-2".to_string())); |
| 8870 | assert!(app.mcp_announced_problems.is_empty()); |
| 8871 | apply_mcp_session_boot_event(&mut app, 3, snap, Vec::new(), true); |
| 8872 | assert_eq!(mcp_toasts(&app), vec!["MCP · failed: alpha · /mcp"]); |
| 8873 | } |
| 8874 | |
| 8875 | fn translation_test_route() -> codewhale_engine::cost_status::EffectiveRouteEnvelope { |
| 8876 | codewhale_engine::cost_status::EffectiveRouteEnvelope { |
| 8877 | provider: codewhale_config::ProviderKind::Deepseek, |
| 8878 | provider_identity: "deepseek".to_string(), |
| 8879 | model: "deepseek-chat".to_string(), |
| 8880 | openrouter_vendor: None, |
| 8881 | billing_surface: codewhale_engine::pricing::billing_surface_for_route( |
| 8882 | codewhale_config::ProviderKind::Deepseek, |
| 8883 | Some("https://api.deepseek.com/v1"), |
| 8884 | ) |
| 8885 | .map(str::to_string), |
| 8886 | endpoint_fingerprint: codewhale_engine::cost_status::endpoint_fingerprint( |
| 8887 | "https://api.deepseek.com/v1", |
| 8888 | ), |
| 8889 | provider_live_pricing: None, |
| 8890 | billing_mode: codewhale_engine::cost_status::RouteBillingMode::Metered, |
| 8891 | dispatched_at: chrono::Utc::now(), |
| 8892 | } |
| 8893 | } |
| 8894 | |
| 8895 | #[test] |
| 8896 | fn assistant_and_thinking_translation_usage_each_accrue_once() { |
| 8897 | let _scope = codewhale_engine::cost_status::test_scope(); |
| 8898 | let directory = tempfile::tempdir().unwrap(); |
| 8899 | let manager = SessionManager::new(directory.path().to_path_buf()).unwrap(); |
| 8900 | let mut app = test_app(); |
| 8901 | app.current_session_id = Some("session-translation".to_string()); |
| 8902 | app.runtime_turn_id = Some("turn-translation".to_string()); |
| 8903 | app.session_write_receipt = Some( |
| 8904 | manager |
| 8905 | .expect_absent_session("session-translation") |
| 8906 | .unwrap(), |
| 8907 | ); |
| 8908 | let usage_a = codewhale_models::Usage { |
| 8909 | input_tokens: 5, |
| 8910 | output_tokens: 2, |
| 8911 | ..Default::default() |
| 8912 | }; |
| 8913 | let usage_b = codewhale_models::Usage { |
| 8914 | input_tokens: 3, |
| 8915 | output_tokens: 1, |
| 8916 | ..Default::default() |
| 8917 | }; |
| 8918 | let assistant = TranslationAccountingContext::capture(&app, "assistant", 1); |
| 8919 | let record_a = assistant |
| 8920 | .source |
| 8921 | .reported(&translation_test_route(), &usage_a); |
| 8922 | manager |
| 8923 | .persist_runtime_usage_record("session-translation", &record_a) |
| 8924 | .unwrap(); |
| 8925 | let assistant = |
| 8926 | assistant.settle(Ok(codewhale_engine::client::TranslationProviderResponse { |
| 8927 | accounting: Some(record_a.clone()), |
| 8928 | translated: Ok("助理".to_string()), |
| 8929 | route: record_a.usage.route.clone(), |
| 8930 | usage: Some(usage_a.clone()), |
| 8931 | })); |
| 8932 | let thinking = TranslationAccountingContext::capture(&app, "thinking", 2); |
| 8933 | let record_b = thinking |
| 8934 | .source |
| 8935 | .reported(&translation_test_route(), &usage_b); |
| 8936 | manager |
| 8937 | .persist_runtime_usage_record("session-translation", &record_b) |
| 8938 | .unwrap(); |
| 8939 | let thinking = thinking.settle(Ok(codewhale_engine::client::TranslationProviderResponse { |
| 8940 | accounting: Some(record_b.clone()), |
| 8941 | translated: Err(anyhow::anyhow!("incomplete: max_tokens")), |
| 8942 | route: record_b.usage.route.clone(), |
| 8943 | usage: Some(usage_b.clone()), |
| 8944 | })); |
| 8945 | assert_eq!(assistant.usage, None); |
| 8946 | assert_eq!(thinking.usage, None); |
| 8947 | assert!( |
| 8948 | thinking.translated.is_err(), |
| 8949 | "semantic rejection is preserved" |
| 8950 | ); |
| 8951 | for record in [&record_a, &record_b, &record_a, &record_b] { |
| 8952 | let _ = app.absorb_usage_source(record).unwrap(); |
| 8953 | } |
| 8954 | assert_eq!(app.session.total_input_tokens, 8); |
| 8955 | assert_eq!(app.session.total_output_tokens, 3); |
| 8956 | assert_eq!(app.session.total_tokens, 11); |
| 8957 | assert_eq!( |
| 8958 | app.session |
| 8959 | .cost_priced_turns |
| 8960 | .saturating_add(app.session.cost_unpriced_turns), |
| 8961 | 2 |
| 8962 | ); |
| 8963 | assert!( |
| 8964 | codewhale_engine::cost_status::drain() |
| 8965 | .source_records |
| 8966 | .is_empty() |
| 8967 | ); |
| 8968 | } |
| 8969 | |
| 8970 | #[test] |
| 8971 | fn translation_unreceipted_success_is_marked_once_but_transport_failure_is_not() { |
| 8972 | let _scope = codewhale_engine::cost_status::test_scope(); |
| 8973 | let directory = tempfile::tempdir().unwrap(); |
| 8974 | let manager = SessionManager::new(directory.path().to_path_buf()).unwrap(); |
| 8975 | let mut app = test_app(); |
| 8976 | app.current_session_id = Some("session-translation-missing-usage".to_string()); |
| 8977 | app.runtime_turn_id = Some("turn-translation-missing-usage".to_string()); |
| 8978 | app.session_write_receipt = Some( |
| 8979 | manager |
| 8980 | .expect_absent_session("session-translation-missing-usage") |
| 8981 | .unwrap(), |
| 8982 | ); |
| 8983 | let context = TranslationAccountingContext::capture(&app, "assistant", 7); |
| 8984 | let record = context.source.reported( |
| 8985 | &translation_test_route(), |
| 8986 | &codewhale_models::Usage::default(), |
| 8987 | ); |
| 8988 | manager |
| 8989 | .persist_runtime_usage_record("session-translation-missing-usage", &record) |
| 8990 | .unwrap(); |
| 8991 | for _ in 0..2 { |
| 8992 | let settled = TranslationAccountingContext { |
| 8993 | source: context.source.clone(), |
| 8994 | } |
| 8995 | .settle(Ok(codewhale_engine::client::TranslationProviderResponse { |
| 8996 | accounting: Some(record.clone()), |
| 8997 | translated: Ok("translation remains usable".to_string()), |
| 8998 | route: record.usage.route.clone(), |
| 8999 | usage: None, |
| 9000 | })); |
| 9001 | assert_eq!( |
| 9002 | settled.translated.expect("semantic output remains usable"), |
| 9003 | "translation remains usable" |
| 9004 | ); |
| 9005 | assert_eq!(settled.usage, None); |
| 9006 | let _ = app.absorb_usage_source(&record).unwrap(); |
| 9007 | } |
| 9008 | let transport = TranslationAccountingContext::capture(&app, "assistant", 8) |
| 9009 | .settle(Err(anyhow::anyhow!("HTTP 429"))); |
| 9010 | assert!(transport.translated.is_err()); |
| 9011 | assert_eq!(transport.usage, None); |
| 9012 | assert_eq!(app.session.cost_priced_turns, 0); |
| 9013 | assert_eq!(app.session.cost_unpriced_turns, 1); |
| 9014 | assert_eq!(app.session.cost_cny_unpriced_turns, 1); |
| 9015 | assert!( |
| 9016 | app.session |
| 9017 | .cost_unpriced_reasons |
| 9018 | .contains("provider_success_missing_usage") |
| 9019 | ); |
| 9020 | } |
| 9021 | |
| 9022 | #[test] |
| 9023 | fn late_translation_delivery_isolated_from_new_session_or_turn() { |
| 9024 | let mut app = test_app(); |
| 9025 | app.current_session_id = Some("session-a".to_string()); |
| 9026 | app.runtime_turn_id = Some("turn-a".to_string()); |
| 9027 | let (session, turn) = translation_origin(&app); |
| 9028 | assert!(translation_origin_is_current( |
| 9029 | &app, |
| 9030 | session.as_deref(), |
| 9031 | turn.as_deref() |
| 9032 | )); |
| 9033 | |
| 9034 | app.current_session_id = Some("session-b".to_string()); |
| 9035 | assert!(!translation_session_is_current(&app, session.as_deref())); |
| 9036 | assert!(!translation_origin_is_current( |
| 9037 | &app, |
| 9038 | session.as_deref(), |
| 9039 | turn.as_deref() |
| 9040 | )); |
| 9041 | app.current_session_id = Some("session-a".to_string()); |
| 9042 | app.runtime_turn_id = Some("turn-b".to_string()); |
| 9043 | assert!( |
| 9044 | translation_session_is_current(&app, session.as_deref()), |
| 9045 | "same-session late usage still belongs in session totals" |
| 9046 | ); |
| 9047 | assert!(!translation_origin_is_current( |
| 9048 | &app, |
| 9049 | session.as_deref(), |
| 9050 | turn.as_deref() |
| 9051 | )); |
| 9052 | |
| 9053 | let usage = codewhale_models::Usage { |
| 9054 | input_tokens: 4, |
| 9055 | output_tokens: 2, |
| 9056 | ..codewhale_models::Usage::default() |
| 9057 | }; |
| 9058 | if translation_session_is_current(&app, session.as_deref()) { |
| 9059 | accrue_translation_usage(&mut app, &usage); |
| 9060 | } |
| 9061 | assert_eq!(app.session.total_tokens, 6); |
| 9062 | app.current_session_id = Some("session-b".to_string()); |
| 9063 | if translation_session_is_current(&app, session.as_deref()) { |
| 9064 | accrue_translation_usage(&mut app, &usage); |
| 9065 | } |
| 9066 | assert_eq!( |
| 9067 | app.session.total_tokens, 6, |
| 9068 | "cross-session late usage must not pollute the new session" |
| 9069 | ); |
| 9070 | |
| 9071 | let shared_prefix = "x".repeat(300); |
| 9072 | app.current_session_id = Some(format!("{shared_prefix}:old")); |
| 9073 | app.runtime_turn_id = Some("turn-long".to_string()); |
| 9074 | let (long_session, long_turn) = translation_origin(&app); |
| 9075 | app.current_session_id = Some(format!("{shared_prefix}:new")); |
| 9076 | assert!( |
| 9077 | !translation_origin_is_current(&app, long_session.as_deref(), long_turn.as_deref()), |
| 9078 | "fixed fingerprints must distinguish ids with the same long prefix" |
| 9079 | ); |
| 9080 | } |
| 9081 | |
| 9082 | #[tokio::test] |
| 9083 | async fn translation_runs_without_a_usage_origin() { |
| 9084 | use wiremock::matchers::{method, path}; |
| 9085 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 9086 | |
| 9087 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 9088 | let _scope = codewhale_engine::cost_status::test_scope(); |
| 9089 | let server = MockServer::start().await; |
| 9090 | Mock::given(method("POST")) |
| 9091 | .and(path("/v1/chat/completions")) |
| 9092 | .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ |
| 9093 | "id": "chatcmpl-translation", |
| 9094 | "object": "chat.completion", |
| 9095 | "model": "deepseek-chat", |
| 9096 | "choices": [{ |
| 9097 | "index": 0, |
| 9098 | "message": { "role": "assistant", "content": "Hola" }, |
| 9099 | "finish_reason": "stop" |
| 9100 | }], |
| 9101 | "usage": { "prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7 } |
| 9102 | }))) |
| 9103 | .expect(1) |
| 9104 | .mount(&server) |
| 9105 | .await; |
| 9106 | |
| 9107 | let mut config = Config::default(); |
| 9108 | config.provider = Some("deepseek".to_string()); |
| 9109 | let providers = config.providers.get_or_insert_with(Default::default); |
| 9110 | providers.deepseek.api_key = Some("test-deepseek-key".to_string()); |
| 9111 | providers.deepseek.base_url = Some(format!("{}/v1", server.uri())); |
| 9112 | let client = codewhale_engine::client::CodewhaleClient::new(&config).expect("client"); |
| 9113 | |
| 9114 | let mut app = test_app(); |
| 9115 | app.session_write_receipt = None; |
| 9116 | let accounting = TranslationAccountingContext::capture(&app, "assistant", 1); |
| 9117 | assert!(accounting.source.origin().is_none()); |
| 9118 | |
| 9119 | let response = client |
| 9120 | .translate_with_usage("Hello", "deepseek-chat", "Spanish", &accounting.source) |
| 9121 | .await |
| 9122 | .expect("translation must run without an admitted usage origin"); |
| 9123 | let settled = accounting.settle(Ok(response)); |
| 9124 | assert_eq!(settled.translated.expect("translated text"), "Hola"); |
| 9125 | } |
| 9126 | } |
| 9127 | |
| 9128 | #[cfg(test)] |
| 9129 | mod launch_session_sync_tests { |
| 9130 | use super::await_engine_session_sync; |
| 9131 | use codewhale_config::AppMode; |
| 9132 | use codewhale_engine::core::engine::{Engine, EngineConfig}; |
| 9133 | use codewhale_engine::core::ops::Op; |
| 9134 | use codewhale_engine::extension_host::{ |
| 9135 | ExtensionHostManager, ExtensionHostOptions, TestManagerGuard, caller_view, |
| 9136 | }; |
| 9137 | use codewhale_plugins::PluginRegistry; |
| 9138 | use codewhale_plugins::activation::TestPolicyGuard; |
| 9139 | use codewhale_runtime::config::Config; |
| 9140 | use codewhale_runtime::features::Feature; |
| 9141 | use std::sync::Arc; |
| 9142 | |
| 9143 | /// A submit on the startup screen begins a session and runs its input in |
| 9144 | /// one keypress. The extension host knows this caller by the engine's |
| 9145 | /// session id, which only moves when the engine processes the sync: before |
| 9146 | /// the wait the App's new id finds no caller (the 0.10.1 "Unknown command" |
| 9147 | /// on a plugin command's first use), after it the caller is found. |
| 9148 | #[tokio::test] |
| 9149 | async fn launch_submit_waits_for_the_engine_to_install_the_new_session() { |
| 9150 | // No native code runs here: the caller identity is all this needs. |
| 9151 | let _policy = TestPolicyGuard::extension_host(false); |
| 9152 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions::default())); |
| 9153 | let _manager = TestManagerGuard::install(Arc::clone(&manager)); |
| 9154 | let workspace = tempfile::tempdir().expect("tempdir"); |
| 9155 | let mut engine_config = EngineConfig { |
| 9156 | workspace: workspace.path().to_path_buf(), |
| 9157 | session_id: Some("startup-session".to_string()), |
| 9158 | plugin_registry: Some(Arc::new(PluginRegistry::empty(workspace.path()))), |
| 9159 | snapshots_enabled: false, |
| 9160 | subagents_enabled: false, |
| 9161 | ..EngineConfig::default() |
| 9162 | }; |
| 9163 | engine_config.features.enable(Feature::ExtensionHost); |
| 9164 | let model = engine_config.model.clone(); |
| 9165 | let (engine, handle) = Engine::new(engine_config, &Config::default()); |
| 9166 | let run = tokio::spawn(engine.run()); |
| 9167 | assert!( |
| 9168 | caller_view(workspace.path(), Some("startup-session"), None).is_some(), |
| 9169 | "the engine attaches under the session it was started with" |
| 9170 | ); |
| 9171 | |
| 9172 | let control = codewhale_engine::core::ops::SessionControlId::new(); |
| 9173 | handle |
| 9174 | .send(Op::SyncSession { |
| 9175 | expected: None, |
| 9176 | control: control.clone(), |
| 9177 | session_id: Some("launch-session".to_string()), |
| 9178 | messages: Vec::new(), |
| 9179 | system_prompt: None, |
| 9180 | system_prompt_override: false, |
| 9181 | model, |
| 9182 | workspace: workspace.path().to_path_buf(), |
| 9183 | mode: AppMode::Agent, |
| 9184 | agent_preset: None, |
| 9185 | }) |
| 9186 | .await |
| 9187 | .expect("sync session"); |
| 9188 | assert!( |
| 9189 | caller_view(workspace.path(), Some("launch-session"), None).is_none(), |
| 9190 | "queued is not installed: the engine has not run the sync yet" |
| 9191 | ); |
| 9192 | |
| 9193 | await_engine_session_sync( |
| 9194 | &handle, |
| 9195 | Some("launch-session"), |
| 9196 | Some(&codewhale_engine::session_manager::SessionWriteOwner::Control(control)), |
| 9197 | ) |
| 9198 | .await |
| 9199 | .expect("exact Engine acknowledgement"); |
| 9200 | assert!( |
| 9201 | caller_view(workspace.path(), Some("launch-session"), None).is_some(), |
| 9202 | "after the wait the new session resolves to this engine's caller" |
| 9203 | ); |
| 9204 | assert!(caller_view(workspace.path(), Some("startup-session"), None).is_none()); |
| 9205 | |
| 9206 | run.abort(); |
| 9207 | } |
| 9208 | } |
| 9209 | |
| 9210 | fn background_command_notice_id(command: &str) -> String { |
| 9211 | format!("background-command:{command}") |
| 9212 | } |
| 9213 | |
| 9214 | pub(crate) fn sync_background_command_notices(app: &mut App, shown: &mut Vec<&'static str>) { |
| 9215 | use crate::commands::background_host as background; |
| 9216 | let running = background::running(); |
| 9217 | if running == *shown { |
| 9218 | return; |
| 9219 | } |
| 9220 | for command in shown.iter().filter(|command| !running.contains(command)) { |
| 9221 | app.retire_event_notices(&background_command_notice_id(command)); |
| 9222 | } |
| 9223 | for command in running.iter().filter(|command| !shown.contains(command)) { |
| 9224 | app.push_status_toast_record(crate::tui::app::StatusToast::standing( |
| 9225 | background::line(app.ui_locale, MessageId::CmdBackgroundWorking, command), |
| 9226 | StatusToastLevel::Info, |
| 9227 | background_command_notice_id(command), |
| 9228 | )); |
| 9229 | } |
| 9230 | *shown = running; |
| 9231 | app.needs_redraw = true; |
| 9232 | } |
| 9233 | |
| 9234 | pub(crate) fn cancel_background_commands(app: &mut App) -> bool { |
| 9235 | use crate::commands::background_host as background; |
| 9236 | let cancelled = background::cancel_all(); |
| 9237 | if cancelled.is_empty() { |
| 9238 | return false; |
| 9239 | } |
| 9240 | let lines: Vec<String> = cancelled |
| 9241 | .iter() |
| 9242 | .map(|command| background::line(app.ui_locale, MessageId::CmdBackgroundCancelled, command)) |
| 9243 | .collect(); |
| 9244 | app.show_event_notice(lines.join(" "), StatusToastLevel::Warning); |
| 9245 | app.needs_redraw = true; |
| 9246 | true |
| 9247 | } |
| 9248 | |
| 9249 | pub(crate) fn bank_live_turn_time(app: &mut App) { |
| 9250 | let Some(started) = app.turn_started_at.take() else { |
| 9251 | return; |
| 9252 | }; |
| 9253 | let elapsed = started.elapsed(); |
| 9254 | if elapsed.is_zero() { |
| 9255 | return; |
| 9256 | } |
| 9257 | app.cumulative_turn_duration = app.cumulative_turn_duration.saturating_add(elapsed); |
| 9258 | if let Some(user_index) = app.active_turn_user_index { |
| 9259 | app.turn_work_durations.insert(user_index, elapsed); |
| 9260 | app.turn_durations_revision = app.turn_durations_revision.wrapping_add(1); |
| 9261 | } |
| 9262 | } |
| 9263 | |
| 9264 | fn push_turn_interrupted_record(app: &mut App, worked: Duration) { |
| 9265 | let content = if worked.as_secs() == 0 { |
| 9266 | app.tr(MessageId::TurnInterruptedRecord).into_owned() |
| 9267 | } else { |
| 9268 | app.tr(MessageId::TurnInterruptedRecordWithWork).replace( |
| 9269 | "{duration}", |
| 9270 | &codewhale_command_contract::elapsed::format_elapsed_secs(worked.as_secs()), |
| 9271 | ) |
| 9272 | }; |
| 9273 | app.add_message(HistoryCell::System { content }); |
| 9274 | app.needs_redraw = true; |
| 9275 | } |
| 9276 | |
| 9277 | #[cfg(test)] |
| 9278 | mod turn_interrupt_record_tests { |
| 9279 | use super::{bank_live_turn_time, push_turn_interrupted_record}; |
| 9280 | use crate::tui::history::HistoryCell; |
| 9281 | use std::time::{Duration, Instant}; |
| 9282 | |
| 9283 | fn app() -> (tempfile::TempDir, crate::tui::app::App) { |
| 9284 | let temp = tempfile::tempdir().expect("tempdir"); |
| 9285 | let app = crate::tui::test_support::test_app_with_options( |
| 9286 | crate::tui::test_support::test_tui_options(temp.path()), |
| 9287 | ); |
| 9288 | (temp, app) |
| 9289 | } |
| 9290 | |
| 9291 | #[test] |
| 9292 | fn interrupt_record_is_a_durable_system_cell_with_work_time() { |
| 9293 | let _home = crate::test_support::SealedHome::new(); |
| 9294 | let (_temp, mut app) = app(); |
| 9295 | let before = app.history.len(); |
| 9296 | push_turn_interrupted_record(&mut app, Duration::from_secs(75)); |
| 9297 | push_turn_interrupted_record(&mut app, Duration::ZERO); |
| 9298 | assert_eq!(app.history.len(), before + 2); |
| 9299 | let HistoryCell::System { content } = &app.history[before] else { |
| 9300 | panic!("expected HistoryCell::System"); |
| 9301 | }; |
| 9302 | assert!(content.contains("1m 15s"), "{content}"); |
| 9303 | let HistoryCell::System { content } = &app.history[before + 1] else { |
| 9304 | panic!("expected HistoryCell::System"); |
| 9305 | }; |
| 9306 | assert!(!content.contains("{duration}"), "{content}"); |
| 9307 | } |
| 9308 | |
| 9309 | #[test] |
| 9310 | fn banking_the_live_turn_keeps_the_worked_total_from_dropping() { |
| 9311 | let _home = crate::test_support::SealedHome::new(); |
| 9312 | let (_temp, mut app) = app(); |
| 9313 | app.cumulative_turn_duration = Duration::from_secs(30); |
| 9314 | app.turn_started_at = Instant::now().checked_sub(Duration::from_secs(10)); |
| 9315 | app.active_turn_user_index = Some(0); |
| 9316 | bank_live_turn_time(&mut app); |
| 9317 | assert!(app.turn_started_at.is_none()); |
| 9318 | assert!(app.cumulative_turn_duration >= Duration::from_secs(40)); |
| 9319 | assert!(app.turn_work_durations.contains_key(&0)); |
| 9320 | let banked = app.cumulative_turn_duration; |
| 9321 | bank_live_turn_time(&mut app); |
| 9322 | assert_eq!(app.cumulative_turn_duration, banked); |
| 9323 | } |
| 9324 | } |
| 9325 | |
| 9326 | #[cfg(test)] |
| 9327 | mod terminal_snapshot_wait_tests { |
| 9328 | use super::await_terminal_snapshot_with_timeout; |
| 9329 | use std::time::Duration; |
| 9330 | |
| 9331 | #[tokio::test] |
| 9332 | async fn pending_terminal_snapshot_times_out() { |
| 9333 | let error = await_terminal_snapshot_with_timeout( |
| 9334 | Duration::ZERO, |
| 9335 | std::future::pending::<anyhow::Result<()>>(), |
| 9336 | ) |
| 9337 | .await |
| 9338 | .expect_err("a pending snapshot must not hold the UI indefinitely"); |
| 9339 | |
| 9340 | assert_eq!( |
| 9341 | error.to_string(), |
| 9342 | "Engine session snapshot timed out after 0 ms" |
| 9343 | ); |
| 9344 | } |
| 9345 | |
| 9346 | #[tokio::test] |
| 9347 | async fn completed_terminal_snapshot_is_returned() { |
| 9348 | let snapshot = await_terminal_snapshot_with_timeout(Duration::from_secs(1), async { |
| 9349 | Ok::<_, anyhow::Error>("snapshot") |
| 9350 | }) |
| 9351 | .await |
| 9352 | .expect("a ready snapshot must pass through"); |
| 9353 | |
| 9354 | assert_eq!(snapshot, "snapshot"); |
| 9355 | } |
| 9356 | } |
| 9357 | |
| 9358 | #[cfg(test)] |
| 9359 | mod plugin_change_tests { |
| 9360 | use super::{apply_plugin_changed_notice, reload_terminal_plugin_registry}; |
| 9361 | use crate::commands::user_registry; |
| 9362 | use crate::tui::history::HistoryCell; |
| 9363 | use codewhale_config::extension_host::ExtensionHostRuntime; |
| 9364 | use codewhale_config::hooks::{HookEvent, HooksConfig}; |
| 9365 | use codewhale_engine::extension_host::{ |
| 9366 | ExtensionHostManager, ExtensionHostOptions, TestManagerGuard, registry::OwnerState, |
| 9367 | }; |
| 9368 | use codewhale_engine::hooks::HookExecutor; |
| 9369 | use codewhale_engine::tools::spec::ToolContext; |
| 9370 | use codewhale_localization::MessageId; |
| 9371 | use codewhale_plugins::activation::TestPolicyGuard; |
| 9372 | use codewhale_plugins::discovery::{DiscoveryConfig, discover_with_config}; |
| 9373 | use std::fs; |
| 9374 | use std::sync::Arc; |
| 9375 | |
| 9376 | #[test] |
| 9377 | fn plugin_change_adds_one_line_with_the_name_defanged() { |
| 9378 | let _home = crate::test_support::SealedHome::new(); |
| 9379 | let temp = tempfile::tempdir().expect("tempdir"); |
| 9380 | let mut app = crate::tui::test_support::test_app_with_options( |
| 9381 | crate::tui::test_support::test_tui_options(temp.path()), |
| 9382 | ); |
| 9383 | let before = app.history.len(); |
| 9384 | apply_plugin_changed_notice( |
| 9385 | &mut app, |
| 9386 | "bad\nname\r\t\u{202E}evil\x1b[31m!long_suffix_to_test_bounding_over_eighty_characters_total_after_ansi_strip", |
| 9387 | "installed", |
| 9388 | Some("approved by you"), |
| 9389 | ); |
| 9390 | |
| 9391 | assert_eq!(app.history.len(), before + 1); |
| 9392 | assert!(app.needs_redraw); |
| 9393 | let HistoryCell::System { content } = app.history.last().expect("system line added") else { |
| 9394 | panic!("expected HistoryCell::System"); |
| 9395 | }; |
| 9396 | assert!( |
| 9397 | !content.chars().any(|ch| ch.is_control() |
| 9398 | || matches!(ch, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')), |
| 9399 | "control/bidi characters must be stripped: {content:?}" |
| 9400 | ); |
| 9401 | assert!(!content.contains('\x1b')); |
| 9402 | assert!(content.contains("bad name evil!")); |
| 9403 | assert!(content.contains("...")); |
| 9404 | let expected_decider = app.tr(MessageId::CmdPluginAuditApprovedByYou); |
| 9405 | assert!(content.contains(expected_decider.as_ref()), "{content}"); |
| 9406 | } |
| 9407 | |
| 9408 | #[tokio::test] |
| 9409 | async fn plugin_change_rereads_the_terminal_registry() { |
| 9410 | let _home = crate::test_support::SealedHome::new(); |
| 9411 | let temp = tempfile::tempdir().expect("tempdir"); |
| 9412 | let workspace = temp.path().join("ws"); |
| 9413 | let user_plugins_dir = temp.path().join("user-plugins"); |
| 9414 | let state_path = temp.path().join("state/plugin-state.json"); |
| 9415 | fs::create_dir_all(workspace.join(".codewhale/plugins")).expect("ws plugins"); |
| 9416 | fs::create_dir_all(&user_plugins_dir).expect("user plugins"); |
| 9417 | |
| 9418 | let cfg = DiscoveryConfig { |
| 9419 | workspace: workspace.clone(), |
| 9420 | user_plugins_dir: user_plugins_dir.clone(), |
| 9421 | workspace_plugins_dir: workspace.join(".codewhale/plugins"), |
| 9422 | builtin_plugin_dirs: Vec::new(), |
| 9423 | state_path, |
| 9424 | }; |
| 9425 | let hooks_cfg = HooksConfig { |
| 9426 | enabled: true, |
| 9427 | ..Default::default() |
| 9428 | }; |
| 9429 | let mut config = codewhale_runtime::config::Config::default(); |
| 9430 | config.hooks = Some(hooks_cfg.clone()); |
| 9431 | |
| 9432 | let mut app = crate::tui::test_support::test_app_with_options( |
| 9433 | crate::tui::test_support::test_tui_options(workspace.clone()), |
| 9434 | ); |
| 9435 | app.plugin_registry = Arc::new(discover_with_config(&cfg)); |
| 9436 | app.hooks = HookExecutor::new(hooks_cfg, workspace.clone()); |
| 9437 | |
| 9438 | assert!(user_registry::with_registry_for_app(&app, |reg| { |
| 9439 | reg.get("tui-cmd").is_none() |
| 9440 | })); |
| 9441 | assert!(!app.hooks.has_hooks_for_event(HookEvent::TurnEnd)); |
| 9442 | |
| 9443 | let plugin_dir = user_plugins_dir.join("alpha-tui"); |
| 9444 | fs::create_dir_all(plugin_dir.join("commands")).expect("commands dir"); |
| 9445 | fs::create_dir_all(plugin_dir.join("hooks")).expect("hooks dir"); |
| 9446 | fs::write( |
| 9447 | plugin_dir.join("plugin.toml"), |
| 9448 | "schema_version = 1\n[plugin]\nname = \"alpha-tui\"\nversion = \"1.0.0\"\n[commands]\npath = \"commands\"\n[hooks]\npath = \"hooks\"\n", |
| 9449 | ) |
| 9450 | .expect("manifest"); |
| 9451 | fs::write( |
| 9452 | plugin_dir.join("commands/tui-cmd.md"), |
| 9453 | "---\ndescription: Alpha command\n---\nhello from tui command\n", |
| 9454 | ) |
| 9455 | .expect("command md"); |
| 9456 | fs::write( |
| 9457 | plugin_dir.join("hooks/hooks.toml"), |
| 9458 | "enabled = true\n\n[[hooks]]\nname = \"alpha-end\"\nevent = \"turn_end\"\ncommand = \"echo done\"\n", |
| 9459 | ) |
| 9460 | .expect("hooks toml"); |
| 9461 | |
| 9462 | let mut on_disk = discover_with_config(&cfg); |
| 9463 | on_disk.trust("alpha-tui").expect("trust"); |
| 9464 | on_disk.enable("alpha-tui").expect("enable"); |
| 9465 | |
| 9466 | let before = app.history.len(); |
| 9467 | apply_plugin_changed_notice( |
| 9468 | &mut app, |
| 9469 | "alpha-tui", |
| 9470 | "installed", |
| 9471 | Some("approved by the agent in Auto-Review"), |
| 9472 | ); |
| 9473 | reload_terminal_plugin_registry(&mut app, &config).await; |
| 9474 | |
| 9475 | assert_eq!(app.history.len(), before + 1); |
| 9476 | assert!(app.plugin_registry.is_active("alpha-tui")); |
| 9477 | assert!(user_registry::with_registry_for_app(&app, |reg| { |
| 9478 | reg.get("tui-cmd").is_some() |
| 9479 | })); |
| 9480 | assert!(app.hooks.has_hooks_for_event(HookEvent::TurnEnd)); |
| 9481 | } |
| 9482 | |
| 9483 | #[tokio::test] |
| 9484 | async fn plugin_change_older_registry_does_not_undo_the_agents_change() { |
| 9485 | let _home = crate::test_support::SealedHome::new(); |
| 9486 | let Some(node) = codewhale_engine::extension_host::test_support::node_for_tests( |
| 9487 | "plugin_change_older_registry_does_not_undo_the_agents_change", |
| 9488 | ) else { |
| 9489 | return; |
| 9490 | }; |
| 9491 | let _policy = TestPolicyGuard::extension_host(true); |
| 9492 | let temp = tempfile::tempdir().expect("tempdir"); |
| 9493 | let workspace = temp.path().join("ws"); |
| 9494 | let agent_user_dir = temp.path().join("agent-user"); |
| 9495 | let agent_state = temp.path().join("agent-state/plugin-state.json"); |
| 9496 | let stale_user_dir = temp.path().join("stale-user"); |
| 9497 | let stale_state = temp.path().join("stale-state/plugin-state.json"); |
| 9498 | fs::create_dir_all(workspace.join(".codewhale/plugins")).expect("ws plugins"); |
| 9499 | fs::create_dir_all(&agent_user_dir).expect("agent user"); |
| 9500 | fs::create_dir_all(&stale_user_dir).expect("stale user"); |
| 9501 | |
| 9502 | let plugin_dir = agent_user_dir.join("agent-tool"); |
| 9503 | fs::create_dir_all(plugin_dir.join("native")).expect("native dir"); |
| 9504 | fs::write( |
| 9505 | plugin_dir.join("plugin.toml"), |
| 9506 | "schema_version = 1\n[plugin]\nname = \"agent-tool\"\nversion = \"1.0.0\"\n[native]\npath = \"native/index.mjs\"\n", |
| 9507 | ) |
| 9508 | .expect("manifest"); |
| 9509 | fs::write( |
| 9510 | plugin_dir.join("native/index.mjs"), |
| 9511 | "export const name = 'agent-tool';\nexport const inject = ['tools'];\nexport function apply(ctx) {\n ctx.tools.register({\n name: 'agent_ping',\n description: 'Ping',\n parameters: { type: 'object', properties: {}, additionalProperties: false },\n async execute() { return 'agent-ok'; },\n });\n}\n", |
| 9512 | ) |
| 9513 | .expect("index.mjs"); |
| 9514 | |
| 9515 | let agent_cfg = DiscoveryConfig { |
| 9516 | workspace: workspace.clone(), |
| 9517 | user_plugins_dir: agent_user_dir, |
| 9518 | workspace_plugins_dir: workspace.join(".codewhale/plugins"), |
| 9519 | builtin_plugin_dirs: Vec::new(), |
| 9520 | state_path: agent_state, |
| 9521 | }; |
| 9522 | let mut agent_reg = discover_with_config(&agent_cfg); |
| 9523 | let agent_plugin_id = agent_reg |
| 9524 | .get("agent-tool") |
| 9525 | .expect("agent-tool discovered") |
| 9526 | .id |
| 9527 | .clone(); |
| 9528 | agent_reg.trust("agent-tool").expect("trust"); |
| 9529 | agent_reg.enable("agent-tool").expect("enable"); |
| 9530 | |
| 9531 | let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions { |
| 9532 | runtime: ExtensionHostRuntime::Node, |
| 9533 | node_override: Some(node), |
| 9534 | root: Some(temp.path().join("ext-root")), |
| 9535 | ..Default::default() |
| 9536 | })); |
| 9537 | let _manager_guard = TestManagerGuard::install(Arc::clone(&manager)); |
| 9538 | let attachment = manager.attach(Arc::new(agent_reg)); |
| 9539 | attachment.sync().await.expect("agent host activation"); |
| 9540 | assert!( |
| 9541 | manager |
| 9542 | .owner_report(agent_plugin_id.as_str()) |
| 9543 | .is_some_and(|report| report.state == Some(OwnerState::Active)) |
| 9544 | ); |
| 9545 | |
| 9546 | let stale_cfg = DiscoveryConfig { |
| 9547 | workspace: workspace.clone(), |
| 9548 | user_plugins_dir: stale_user_dir, |
| 9549 | workspace_plugins_dir: workspace.join(".codewhale/plugins"), |
| 9550 | builtin_plugin_dirs: Vec::new(), |
| 9551 | state_path: stale_state, |
| 9552 | }; |
| 9553 | let mut app = crate::tui::test_support::test_app_with_options( |
| 9554 | crate::tui::test_support::test_tui_options(workspace.clone()), |
| 9555 | ); |
| 9556 | app.plugin_registry = Arc::new(discover_with_config(&stale_cfg)); |
| 9557 | let config = codewhale_runtime::config::Config::default(); |
| 9558 | |
| 9559 | apply_plugin_changed_notice(&mut app, "agent-tool", "installed", Some("approved by you")); |
| 9560 | reload_terminal_plugin_registry(&mut app, &config).await; |
| 9561 | |
| 9562 | assert!(app.plugin_registry.get("agent-tool").is_none()); |
| 9563 | assert!( |
| 9564 | manager |
| 9565 | .owner_report(agent_plugin_id.as_str()) |
| 9566 | .is_some_and(|report| report.state == Some(OwnerState::Active)), |
| 9567 | "older terminal registry must never deactivate agent-approved host plugin" |
| 9568 | ); |
| 9569 | assert!(attachment.plugin_view().is_active("agent-tool")); |
| 9570 | |
| 9571 | let tool = codewhale_engine::extension_host::test_support::host_tool( |
| 9572 | &attachment, |
| 9573 | &workspace, |
| 9574 | "agent_ping", |
| 9575 | ); |
| 9576 | let result = tool |
| 9577 | .execute( |
| 9578 | serde_json::json!({}), |
| 9579 | &ToolContext::new(&workspace).with_plugin_registry(attachment.plugin_view()), |
| 9580 | ) |
| 9581 | .await |
| 9582 | .expect("agent_ping remains callable"); |
| 9583 | assert!(result.content.contains("agent-ok"), "{}", result.content); |
| 9584 | |
| 9585 | manager.shutdown().await; |
| 9586 | } |
| 9587 | } |
| 9588 | |
| 9589 | #[cfg(test)] |
| 9590 | mod telemetry_notice_tests { |
| 9591 | use super::telemetry_notice_may_enter_transcript; |
| 9592 | |
| 9593 | #[test] |
| 9594 | fn telemetry_notice_waits_for_the_launch_card_to_leave() { |
| 9595 | let _home = crate::test_support::SealedHome::new(); |
| 9596 | let temp = tempfile::tempdir().expect("tempdir"); |
| 9597 | let mut app = crate::tui::test_support::test_app_with_options( |
| 9598 | crate::tui::test_support::test_tui_options(temp.path()), |
| 9599 | ); |
| 9600 | app.launch.visible = true; |
| 9601 | app.launch.dissolve_started_ms = None; |
| 9602 | assert!( |
| 9603 | !telemetry_notice_may_enter_transcript(&app), |
| 9604 | "a transcript cell would hide the launch card's no-model line" |
| 9605 | ); |
| 9606 | // A first keystroke only starts the dissolve; Esc on an empty |
| 9607 | // composer (or leaving the picker) restores the card, which renders |
| 9608 | // only over an empty history. A cell now would strand it. |
| 9609 | app.launch.dissolve_card(0); |
| 9610 | assert!(!telemetry_notice_may_enter_transcript(&app)); |
| 9611 | app.launch.restore_card(); |
| 9612 | assert!(crate::tui::widgets::should_render_empty_state(&app)); |
| 9613 | // Once the conversation has an entry, the card cannot come back. |
| 9614 | app.launch.dissolve_card(0); |
| 9615 | app.add_message(super::HistoryCell::System { |
| 9616 | content: "first entry".to_string(), |
| 9617 | }); |
| 9618 | assert!(telemetry_notice_may_enter_transcript(&app)); |
| 9619 | app.history.clear(); |
| 9620 | app.launch.visible = false; |
| 9621 | app.launch.dissolve_started_ms = None; |
| 9622 | assert!(telemetry_notice_may_enter_transcript(&app)); |
| 9623 | } |
| 9624 | } |
| 9625 | |
| 9626 | fn provisional_tool_result_is_error( |
| 9627 | result: &Result< |
| 9628 | codewhale_engine::tools::spec::ToolResult, |
| 9629 | codewhale_engine::tools::spec::ToolError, |
| 9630 | >, |
| 9631 | ) -> bool { |
| 9632 | !matches!(result, Ok(output) if output.success) |
| 9633 | } |
| 9634 | |
| 9635 | fn observe_terminal_agent_lifecycle_event( |
| 9636 | current_session_id: Option<&str>, |
| 9637 | event: &EngineEvent, |
| 9638 | ) -> bool { |
| 9639 | let owner_session_id = match event { |
| 9640 | EngineEvent::AgentSpawned { |
| 9641 | owner_session_id, .. |
| 9642 | } |
| 9643 | | EngineEvent::AgentComplete { |
| 9644 | owner_session_id, .. |
| 9645 | } => owner_session_id.as_str(), |
| 9646 | _ => return false, |
| 9647 | }; |
| 9648 | codewhale_engine::tools::subagent::log_subagent_lifecycle_audit(event); |
| 9649 | event_owner_is_active(current_session_id, owner_session_id) |
| 9650 | } |
| 9651 | |
| 9652 | #[cfg(test)] |
| 9653 | mod fleet_workers_status_tests { |
| 9654 | use super::{ |
| 9655 | current_session_fleet_workers_status, observe_terminal_agent_lifecycle_event, |
| 9656 | provisional_tool_result_is_error, |
| 9657 | }; |
| 9658 | use codewhale_engine::core::events::Event as EngineEvent; |
| 9659 | use codewhale_engine::tools::spec::{ToolError, ToolResult}; |
| 9660 | use codewhale_localization::Locale; |
| 9661 | |
| 9662 | #[test] |
| 9663 | fn current_session_fleet_worker_status_keeps_the_english_session_boundary() { |
| 9664 | assert_eq!( |
| 9665 | current_session_fleet_workers_status(Locale::En, 3), |
| 9666 | "Agents in this session: 3 total" |
| 9667 | ); |
| 9668 | } |
| 9669 | |
| 9670 | #[test] |
| 9671 | fn provisional_tool_result_records_success_and_failure() { |
| 9672 | assert!(!provisional_tool_result_is_error(&Ok(ToolResult::success( |
| 9673 | "ok" |
| 9674 | )))); |
| 9675 | assert!(provisional_tool_result_is_error(&Ok(ToolResult::error( |
| 9676 | "failed" |
| 9677 | )))); |
| 9678 | assert!(provisional_tool_result_is_error(&Err( |
| 9679 | ToolError::permission_denied("denied") |
| 9680 | ))); |
| 9681 | } |
| 9682 | |
| 9683 | #[test] |
| 9684 | fn terminal_agent_completed_audit_carries_status_and_usage() { |
| 9685 | let usage = codewhale_engine::tools::subagent::AgentRunUsage { |
| 9686 | status: "measured".to_string(), |
| 9687 | input_tokens: Some(1200), |
| 9688 | output_tokens: Some(340), |
| 9689 | total_tokens: Some(1540), |
| 9690 | cost_microusd: Some(420), |
| 9691 | note: String::new(), |
| 9692 | }; |
| 9693 | let event = EngineEvent::AgentComplete { |
| 9694 | owner_session_id: "sess-1".to_string(), |
| 9695 | id: "agent-1".to_string(), |
| 9696 | result: "done".to_string(), |
| 9697 | outcome: Some(codewhale_engine::tools::subagent::SubAgentStatus::Completed), |
| 9698 | limit_kind: None, |
| 9699 | parent_run_id: Some("run-1".to_string()), |
| 9700 | spawn_depth: Some(1), |
| 9701 | continuable: Some(false), |
| 9702 | usage: Some(usage), |
| 9703 | display_name: Some("worker".to_string()), |
| 9704 | }; |
| 9705 | let (event_name, details) = |
| 9706 | codewhale_engine::tools::subagent::subagent_lifecycle_audit_event(&event) |
| 9707 | .expect("audit event"); |
| 9708 | assert_eq!(event_name, "agent.completed"); |
| 9709 | assert_eq!(details["agent_id"], "agent-1"); |
| 9710 | assert_eq!(details["session_id"], "sess-1"); |
| 9711 | assert_eq!(details["worker_status"], "completed"); |
| 9712 | assert_eq!(details["usage"]["input_tokens"], 1200); |
| 9713 | assert_eq!(details["usage"]["output_tokens"], 340); |
| 9714 | assert_eq!(details["usage"]["total_tokens"], 1540); |
| 9715 | } |
| 9716 | |
| 9717 | #[test] |
| 9718 | fn session_switched_agent_completed_still_persists_audit_without_activating_ui() { |
| 9719 | let _lock = crate::test_support::lock_test_env(); |
| 9720 | let temp = tempfile::TempDir::new().expect("tempdir"); |
| 9721 | let home = temp.path().join(".codewhale"); |
| 9722 | let _guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 9723 | |
| 9724 | let completed = EngineEvent::AgentComplete { |
| 9725 | owner_session_id: "sess-original".to_string(), |
| 9726 | id: "agent-switched".to_string(), |
| 9727 | result: "done".to_string(), |
| 9728 | outcome: Some(codewhale_engine::tools::subagent::SubAgentStatus::Completed), |
| 9729 | limit_kind: None, |
| 9730 | parent_run_id: Some("run-9".to_string()), |
| 9731 | spawn_depth: Some(1), |
| 9732 | continuable: Some(false), |
| 9733 | usage: Some(codewhale_engine::tools::subagent::AgentRunUsage { |
| 9734 | status: "reported".to_string(), |
| 9735 | input_tokens: Some(900), |
| 9736 | output_tokens: Some(250), |
| 9737 | total_tokens: Some(1150), |
| 9738 | cost_microusd: Some(310), |
| 9739 | note: String::new(), |
| 9740 | }), |
| 9741 | display_name: Some("researcher".to_string()), |
| 9742 | }; |
| 9743 | |
| 9744 | let is_active = |
| 9745 | observe_terminal_agent_lifecycle_event(Some("sess-switched-to"), &completed); |
| 9746 | assert!(!is_active); |
| 9747 | |
| 9748 | let log = std::fs::read_to_string(home.join("audit.log")).expect("audit.log"); |
| 9749 | let entry: serde_json::Value = |
| 9750 | serde_json::from_str(log.lines().last().expect("audit line")).expect("audit json"); |
| 9751 | assert_eq!(entry["event"], "agent.completed"); |
| 9752 | assert_eq!(entry["details"]["session_id"], "sess-original"); |
| 9753 | assert_eq!(entry["details"]["agent_id"], "agent-switched"); |
| 9754 | assert_eq!(entry["details"]["worker_status"], "completed"); |
| 9755 | assert_eq!(entry["details"]["usage"]["input_tokens"], 900); |
| 9756 | assert_eq!(entry["details"]["usage"]["output_tokens"], 250); |
| 9757 | assert_eq!(entry["details"]["usage"]["total_tokens"], 1150); |
| 9758 | } |
| 9759 | } |
| 9760 | |
| 9761 | /// Per-tick budget for the runtime store-failure tap. These events are rare; |
| 9762 | /// the bound only keeps a burst from starving the frame. |
| 9763 | const RUNTIME_STORE_FAILURE_DRAIN_BUDGET: usize = 64; |
| 9764 | |
| 9765 | /// Drain the background runtime's event tap and show every |
| 9766 | /// `runtime.store_failure` (#5931). Other runtime events keep their own |
| 9767 | /// consumers (the task timeline, SSE); this reads only the operator's fault. |
| 9768 | fn drain_runtime_store_failures( |
| 9769 | app: &mut App, |
| 9770 | rx: &mut Option< |
| 9771 | tokio::sync::broadcast::Receiver<codewhale_engine::runtime_threads::RuntimeEventRecord>, |
| 9772 | >, |
| 9773 | ) -> bool { |
| 9774 | use tokio::sync::broadcast::error::TryRecvError; |
| 9775 | let Some(receiver) = rx.as_mut() else { |
| 9776 | return false; |
| 9777 | }; |
| 9778 | let mut shown = false; |
| 9779 | for _ in 0..RUNTIME_STORE_FAILURE_DRAIN_BUDGET { |
| 9780 | match receiver.try_recv() { |
| 9781 | Ok(event) => shown |= show_runtime_store_failure(app, &event), |
| 9782 | Err(TryRecvError::Empty) => break, |
| 9783 | Err(TryRecvError::Lagged(skipped)) => { |
| 9784 | tracing::warn!( |
| 9785 | skipped, |
| 9786 | "runtime event tap lagged; a store-failure notice may have been missed" |
| 9787 | ); |
| 9788 | } |
| 9789 | Err(TryRecvError::Closed) => { |
| 9790 | *rx = None; |
| 9791 | break; |
| 9792 | } |
| 9793 | } |
| 9794 | } |
| 9795 | shown |
| 9796 | } |
| 9797 | |
| 9798 | /// Show one `runtime.store_failure` event as a warning toast and a transcript |
| 9799 | /// line that names the file and the next action. Any other event is ignored. |
| 9800 | pub(crate) fn show_runtime_store_failure( |
| 9801 | app: &mut App, |
| 9802 | event: &codewhale_engine::runtime_threads::RuntimeEventRecord, |
| 9803 | ) -> bool { |
| 9804 | if event.event != codewhale_engine::runtime_threads::RUNTIME_STORE_FAILURE_EVENT { |
| 9805 | return false; |
| 9806 | } |
| 9807 | let notice = match serde_json::from_value::< |
| 9808 | codewhale_engine::runtime_threads::RuntimeStoreFailureNotice, |
| 9809 | >(event.payload.clone()) |
| 9810 | { |
| 9811 | Ok(notice) => notice, |
| 9812 | Err(error) => { |
| 9813 | tracing::warn!(%error, "runtime store failure notice had an unreadable payload"); |
| 9814 | return false; |
| 9815 | } |
| 9816 | }; |
| 9817 | let message = runtime_store_failure_notice(app, ¬ice); |
| 9818 | app.push_status_toast(message.clone(), StatusToastLevel::Warning, Some(12_000)); |
| 9819 | app.add_message(HistoryCell::System { content: message }); |
| 9820 | true |
| 9821 | } |
| 9822 | |
| 9823 | /// Text for a runtime store fault: the record, the file, the root cause, and |
| 9824 | /// the remedy the failed operation calls for. |
| 9825 | pub(crate) fn runtime_store_failure_notice( |
| 9826 | app: &App, |
| 9827 | notice: &codewhale_engine::runtime_threads::RuntimeStoreFailureNotice, |
| 9828 | ) -> String { |
| 9829 | use codewhale_engine::runtime_threads::RuntimeStoreOperation; |
| 9830 | let id = match notice.failure.operation { |
| 9831 | RuntimeStoreOperation::Write => MessageId::RuntimeStoreUnwritableNotice, |
| 9832 | RuntimeStoreOperation::Read | RuntimeStoreOperation::Parse => { |
| 9833 | MessageId::RuntimeStoreUnreadableNotice |
| 9834 | } |
| 9835 | }; |
| 9836 | app.tr(id) |
| 9837 | .replace( |
| 9838 | "{record}", |
| 9839 | &format!( |
| 9840 | "{} {}", |
| 9841 | notice.failure.record_kind, notice.failure.record_id |
| 9842 | ), |
| 9843 | ) |
| 9844 | .replace("{path}", ¬ice.failure.path.display().to_string()) |
| 9845 | .replace("{reason}", ¬ice.reason) |
| 9846 | } |
| 9847 | |
| 9848 | /// The fields of one [`EngineEvent::ApprovalRequired`], moved out of the |
| 9849 | /// drain so the handler can be driven directly by tests. |
| 9850 | pub(super) struct ApprovalRequiredEvent { |
| 9851 | pub id: String, |
| 9852 | pub tool_name: String, |
| 9853 | pub description: String, |
| 9854 | pub input: serde_json::Value, |
| 9855 | pub approval_key: String, |
| 9856 | pub approval_grouping_key: String, |
| 9857 | pub intent_summary: Option<String>, |
| 9858 | pub approval_force_prompt: bool, |
| 9859 | } |
| 9860 | |
| 9861 | /// Handle one approval request from the engine: resolve its disposition and, |
| 9862 | /// when a person must decide, raise the card. A child agent's card is also |
| 9863 | /// recorded in the pending store so hiding it never loses it (approvals C1). |
| 9864 | pub(super) async fn handle_approval_required_event( |
| 9865 | app: &mut App, |
| 9866 | engine_handle: &EngineHandle, |
| 9867 | config: &Config, |
| 9868 | event: ApprovalRequiredEvent, |
| 9869 | ) { |
| 9870 | let ApprovalRequiredEvent { |
| 9871 | id, |
| 9872 | tool_name, |
| 9873 | description, |
| 9874 | input, |
| 9875 | approval_key, |
| 9876 | approval_grouping_key, |
| 9877 | intent_summary, |
| 9878 | approval_force_prompt, |
| 9879 | } = event; |
| 9880 | // A count and nothing else. The tool name, the |
| 9881 | // description, the input, and the matched rule are all |
| 9882 | // user- or model-authored strings. |
| 9883 | codewhale_telemetry::session_counters().bump(codewhale_telemetry::Counter::ApprovalModalShown); |
| 9884 | // Mirror semantics: the approval is always shown |
| 9885 | // locally. When the web mirror is attached to this |
| 9886 | // turn, ALSO record it so the web can answer; the |
| 9887 | // first decision wins (`resolve_pending_approval` |
| 9888 | // vs `take_pending_approval`). |
| 9889 | let shared_with_web = if app.remote_control.can_share_approval_with_web() { |
| 9890 | app.remote_control.record_remote_approval( |
| 9891 | &id, |
| 9892 | &tool_name, |
| 9893 | &description, |
| 9894 | &input, |
| 9895 | &approval_key, |
| 9896 | intent_summary.as_deref(), |
| 9897 | ); |
| 9898 | true |
| 9899 | } else { |
| 9900 | false |
| 9901 | }; |
| 9902 | use codewhale_engine::core::authority::ApprovalRequestDisposition; |
| 9903 | // One disposition path for every ApprovalRequired (#4412): |
| 9904 | // session denial, Full Access policy hold, session/FA |
| 9905 | // auto-approve, Never posture, or modal prompt. |
| 9906 | match resolve_ui_approval_disposition( |
| 9907 | app, |
| 9908 | &tool_name, |
| 9909 | &approval_grouping_key, |
| 9910 | &approval_key, |
| 9911 | approval_force_prompt, |
| 9912 | ) { |
| 9913 | ApprovalRequestDisposition::AutoDenySessionDenied => { |
| 9914 | // The user already denied a matching approval key |
| 9915 | // during this process; auto-deny so the |
| 9916 | // model's retry loop doesn't keep re-prompting |
| 9917 | // (#360). |
| 9918 | auto_deny_session_approval(app, engine_handle, &id, &tool_name, &approval_key).await; |
| 9919 | } |
| 9920 | ApprovalRequestDisposition::AutoDenyFullAccessPolicyHold => { |
| 9921 | log_sensitive_event( |
| 9922 | "tool.approval.auto_deny_full_access_policy", |
| 9923 | serde_json::json!({ |
| 9924 | "tool_name": tool_name, |
| 9925 | "session_id": app.current_session_id, |
| 9926 | "mode": app.mode.label(), |
| 9927 | }), |
| 9928 | ); |
| 9929 | if let Err(error) = engine_handle |
| 9930 | .deny_tool_call_by( |
| 9931 | id.clone(), |
| 9932 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 9933 | ) |
| 9934 | .await |
| 9935 | { |
| 9936 | app.show_event_notice( |
| 9937 | format!("Approval was not accepted: {error}"), |
| 9938 | StatusToastLevel::Error, |
| 9939 | ); |
| 9940 | return; |
| 9941 | } |
| 9942 | let notice = app |
| 9943 | .tr(MessageId::ApprovalFullAccessPolicyBlocked) |
| 9944 | .replace("{tool}", &tool_name); |
| 9945 | app.push_status_toast(notice, StatusToastLevel::Warning, Some(12_000)); |
| 9946 | } |
| 9947 | ApprovalRequestDisposition::AutoApprove => { |
| 9948 | log_sensitive_event( |
| 9949 | "tool.approval.auto_approve_session", |
| 9950 | serde_json::json!({ |
| 9951 | "tool_name": tool_name, |
| 9952 | "approval_key": approval_key, |
| 9953 | "session_id": app.current_session_id, |
| 9954 | "mode": app.mode.label(), |
| 9955 | }), |
| 9956 | ); |
| 9957 | let by = auto_approval_decider(app, approval_force_prompt); |
| 9958 | if let Err(error) = engine_handle.approve_tool_call_by(id.clone(), by).await { |
| 9959 | app.show_event_notice( |
| 9960 | format!("Approval was not accepted: {error}"), |
| 9961 | StatusToastLevel::Error, |
| 9962 | ); |
| 9963 | } |
| 9964 | } |
| 9965 | ApprovalRequestDisposition::AutoDenyAutoReview => { |
| 9966 | log_sensitive_event( |
| 9967 | "tool.approval.auto_deny_auto_review", |
| 9968 | serde_json::json!({ |
| 9969 | "tool_name": tool_name, |
| 9970 | "session_id": app.current_session_id, |
| 9971 | "mode": app.mode.label(), |
| 9972 | }), |
| 9973 | ); |
| 9974 | if let Err(error) = engine_handle |
| 9975 | .deny_tool_call_by( |
| 9976 | id.clone(), |
| 9977 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 9978 | ) |
| 9979 | .await |
| 9980 | { |
| 9981 | app.show_event_notice( |
| 9982 | format!("Approval was not accepted: {error}"), |
| 9983 | StatusToastLevel::Error, |
| 9984 | ); |
| 9985 | return; |
| 9986 | } |
| 9987 | let held = |
| 9988 | crate::tui::gate_receipts::auto_review_held_receipt(app.ui_locale, &tool_name); |
| 9989 | app.add_message(HistoryCell::System { |
| 9990 | content: held.clone(), |
| 9991 | }); |
| 9992 | app.push_status_toast_record( |
| 9993 | StatusToast::new(held, StatusToastLevel::Warning, Some(12_000)) |
| 9994 | .for_event(format!("approval-held:{id}")), |
| 9995 | ); |
| 9996 | } |
| 9997 | ApprovalRequestDisposition::AutoDenyNeverPosture => { |
| 9998 | log_sensitive_event( |
| 9999 | "tool.approval.auto_deny", |
| 10000 | serde_json::json!({ |
| 10001 | "tool_name": tool_name, |
| 10002 | "session_id": app.current_session_id, |
| 10003 | "mode": app.mode.label(), |
| 10004 | }), |
| 10005 | ); |
| 10006 | if let Err(error) = engine_handle |
| 10007 | .deny_tool_call_by( |
| 10008 | id.clone(), |
| 10009 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 10010 | ) |
| 10011 | .await |
| 10012 | { |
| 10013 | app.show_event_notice( |
| 10014 | format!("Approval was not accepted: {error}"), |
| 10015 | StatusToastLevel::Error, |
| 10016 | ); |
| 10017 | return; |
| 10018 | } |
| 10019 | app.push_status_toast_record( |
| 10020 | StatusToast::new( |
| 10021 | app.tr(MessageId::ApprovalNeverPostureBlocked) |
| 10022 | .replace("{tool}", &tool_name), |
| 10023 | StatusToastLevel::Warning, |
| 10024 | Some(12_000), |
| 10025 | ) |
| 10026 | .for_event(format!("approval-blocked:{id}")), |
| 10027 | ); |
| 10028 | } |
| 10029 | ApprovalRequestDisposition::Prompt => { |
| 10030 | let tool_input = input; |
| 10031 | |
| 10032 | if let Some(request) = |
| 10033 | crate::tui::views::search_consent::SearchConsentRequest::from_approval( |
| 10034 | &id, |
| 10035 | &tool_name, |
| 10036 | &approval_key, |
| 10037 | &tool_input, |
| 10038 | ) |
| 10039 | { |
| 10040 | app.view_stack.push( |
| 10041 | crate::tui::views::search_consent::SearchConsentView::new( |
| 10042 | request, |
| 10043 | app.ui_locale, |
| 10044 | ) |
| 10045 | .with_timeout(config.approval_timeout()), |
| 10046 | ); |
| 10047 | } else { |
| 10048 | push_approval_request_view( |
| 10049 | app, |
| 10050 | &id, |
| 10051 | &tool_name, |
| 10052 | &description, |
| 10053 | &tool_input, |
| 10054 | &approval_key, |
| 10055 | &approval_grouping_key, |
| 10056 | intent_summary.as_deref(), |
| 10057 | config.approval_default_selection(), |
| 10058 | config.approval_timeout(), |
| 10059 | ); |
| 10060 | } |
| 10061 | crate::tui::tool_routing::hold_exec_cards_for_approval(app, &id); |
| 10062 | if let Some(agent_id) = crate::tui::pending_requests::child_agent_id(&id) { |
| 10063 | crate::tui::pending_requests::record( |
| 10064 | app, |
| 10065 | &id, |
| 10066 | crate::tui::pending_requests::PendingChildRequest { |
| 10067 | agent_id: agent_id.to_string(), |
| 10068 | tool_name: tool_name.clone(), |
| 10069 | description: description.clone(), |
| 10070 | input: tool_input.clone(), |
| 10071 | approval_key: approval_key.clone(), |
| 10072 | approval_grouping_key: approval_grouping_key.clone(), |
| 10073 | intent_summary: intent_summary.clone(), |
| 10074 | requested_at: Instant::now(), |
| 10075 | }, |
| 10076 | ); |
| 10077 | } |
| 10078 | log_sensitive_event( |
| 10079 | "tool.approval.prompted", |
| 10080 | serde_json::json!({ |
| 10081 | "tool_name": tool_name, |
| 10082 | "description": description, |
| 10083 | "session_id": app.current_session_id, |
| 10084 | "mode": app.mode.label(), |
| 10085 | }), |
| 10086 | ); |
| 10087 | let payload = notifications::approval_needed_payload(app.ui_locale, &tool_name); |
| 10088 | if let Some((method, _, _)) = crate::tui::notifications::settings(config) { |
| 10089 | let in_tmux = std::env::var("TMUX").is_ok_and(|v| !v.is_empty()); |
| 10090 | // #4834: the tool *description* is the |
| 10091 | // pending command. It stays in the |
| 10092 | // terminal, where the user can read it |
| 10093 | // in context; the banner names only the |
| 10094 | // tool. Copy is centralized (#5041) so |
| 10095 | // the action-first phrasing is tested. |
| 10096 | crate::tui::notifications::notify_done( |
| 10097 | method, |
| 10098 | in_tmux, |
| 10099 | &payload, |
| 10100 | Duration::ZERO, |
| 10101 | Duration::ZERO, |
| 10102 | ); |
| 10103 | } |
| 10104 | let mut notice = payload.headline().to_string(); |
| 10105 | if shared_with_web { |
| 10106 | notice.push_str(" · "); |
| 10107 | notice.push_str(&app.tr(MessageId::NotificationDecisionWebHint)); |
| 10108 | } |
| 10109 | app.push_status_toast_record( |
| 10110 | StatusToast::new(notice, StatusToastLevel::Warning, Some(12_000)) |
| 10111 | .for_action(id.clone()), |
| 10112 | ); |
| 10113 | } |
| 10114 | } |
| 10115 | } |
| 10116 | |
| 10117 | /// Route one key to the view stack, unless the terminal saw it before the |
| 10118 | /// approval card on top became visible (approvals M2): such a key was typed |
| 10119 | /// at something else — often the card that was just answered above this |
| 10120 | /// one — and must never answer this card. `None` means it was discarded. |
| 10121 | pub(super) fn route_key_to_view_stack( |
| 10122 | app: &mut App, |
| 10123 | key: KeyEvent, |
| 10124 | observed_at: Instant, |
| 10125 | ) -> Option<Vec<ViewEvent>> { |
| 10126 | if app.view_stack.key_predates_top_approval(observed_at) { |
| 10127 | return None; |
| 10128 | } |
| 10129 | Some(app.view_stack.handle_key(key)) |
| 10130 | } |
| 10131 | |
| 10132 | /// Keep Engine retry and image request receipts in the existing transcript. Ordinary |
| 10133 | /// status/footer behavior and internal/model-only status projection stay intact. |
| 10134 | pub(super) fn apply_engine_status(app: &mut App, message: String) -> bool { |
| 10135 | if codewhale_engine::core::events::is_retry_status_receipt(&message) |
| 10136 | || codewhale_engine::core::events::is_request_image_status_receipt(&message) |
| 10137 | { |
| 10138 | app.add_message(HistoryCell::System { content: message }); |
| 10139 | return true; |
| 10140 | } |
| 10141 | if app.tr(MessageId::ProfileConstitutionUnavailableLocal) == message.as_str() { |
| 10142 | app.notify_account_preferences_not_loaded(); |
| 10143 | return false; |
| 10144 | } |
| 10145 | app.report_engine_status(message); |
| 10146 | false |
| 10147 | } |
| 10148 | |
| 10149 | pub(super) fn sanitize_server_ui_text(raw: &str, single_line: bool) -> String { |
| 10150 | let mut stripped = String::new(); |
| 10151 | codewhale_sanitize::sanitize::strip_ansi_into(raw, &mut stripped); |
| 10152 | if single_line { |
| 10153 | stripped |
| 10154 | .chars() |
| 10155 | .map(|ch| match ch { |
| 10156 | '\n' | '\r' | '\t' => ' ', |
| 10157 | ch if ch.is_control() => ' ', |
| 10158 | ch => ch, |
| 10159 | }) |
| 10160 | .collect::<String>() |
| 10161 | .split_whitespace() |
| 10162 | .collect::<Vec<_>>() |
| 10163 | .join(" ") |
| 10164 | } else { |
| 10165 | stripped |
| 10166 | .chars() |
| 10167 | .filter(|&ch| ch == '\n' || ch == '\t' || !ch.is_control()) |
| 10168 | .collect() |
| 10169 | } |
| 10170 | } |
| 10171 | |
| 10172 | pub(super) fn apply_conversation_title(app: &mut App, title: &str) { |
| 10173 | let sanitized = sanitize_server_ui_text(title, true); |
| 10174 | app.show_event_notice(format!("Title: {sanitized}"), StatusToastLevel::Info); |
| 10175 | } |
| 10176 | |
| 10177 | pub(super) fn apply_content_filter_refusal(app: &mut App, reason: &str, refusal: Option<&str>) { |
| 10178 | let detail = sanitize_server_ui_text(refusal.unwrap_or(reason), false); |
| 10179 | app.add_message(HistoryCell::System { |
| 10180 | content: format!("Content filtered: {detail}"), |
| 10181 | }); |
| 10182 | } |
| 10183 | |
| 10184 | fn sanitize_plugin_change_field(raw: &str, max_chars: usize) -> String { |
| 10185 | let mut stripped = String::new(); |
| 10186 | codewhale_sanitize::sanitize::strip_ansi_into(raw, &mut stripped); |
| 10187 | let mut cleaned = String::with_capacity(stripped.len()); |
| 10188 | for ch in stripped.chars() { |
| 10189 | if codewhale_sanitize::sanitize::is_bidi_control(ch) { |
| 10190 | continue; |
| 10191 | } |
| 10192 | if matches!(ch, '\n' | '\r' | '\t') { |
| 10193 | cleaned.push(' '); |
| 10194 | } else if !ch.is_control() { |
| 10195 | cleaned.push(ch); |
| 10196 | } |
| 10197 | } |
| 10198 | let normalized = cleaned.split_whitespace().collect::<Vec<_>>().join(" "); |
| 10199 | let count = normalized.chars().count(); |
| 10200 | if count <= max_chars { |
| 10201 | normalized |
| 10202 | } else { |
| 10203 | let mut bounded: String = normalized |
| 10204 | .chars() |
| 10205 | .take(max_chars.saturating_sub(3)) |
| 10206 | .collect(); |
| 10207 | bounded.push_str("..."); |
| 10208 | bounded |
| 10209 | } |
| 10210 | } |
| 10211 | |
| 10212 | fn localize_plugin_change_action(app: &App, action: &str) -> String { |
| 10213 | match action.trim() { |
| 10214 | "installed" => app.tr(MessageId::PluginChangedActionInstalled).into_owned(), |
| 10215 | "enabled" => app.tr(MessageId::PluginChangedActionEnabled).into_owned(), |
| 10216 | "disabled" => app.tr(MessageId::PluginChangedActionDisabled).into_owned(), |
| 10217 | "removed" | "uninstalled" => app.tr(MessageId::PluginChangedActionRemoved).into_owned(), |
| 10218 | other => { |
| 10219 | let cleaned = sanitize_plugin_change_field(other, 40); |
| 10220 | if cleaned.is_empty() { |
| 10221 | "updated".to_string() |
| 10222 | } else { |
| 10223 | cleaned |
| 10224 | } |
| 10225 | } |
| 10226 | } |
| 10227 | } |
| 10228 | |
| 10229 | fn localize_plugin_change_decider(app: &App, raw: &str) -> String { |
| 10230 | match raw.trim() { |
| 10231 | "approved by you" => app.tr(MessageId::CmdPluginAuditApprovedByYou).into_owned(), |
| 10232 | "approved by the agent in Full Access" => app |
| 10233 | .tr(MessageId::CmdPluginAuditApprovedByAgentFullAccess) |
| 10234 | .into_owned(), |
| 10235 | "approved by the agent in Auto-Review" => app |
| 10236 | .tr(MessageId::CmdPluginAuditApprovedByAgentAutoReview) |
| 10237 | .into_owned(), |
| 10238 | "approved by the agent from a shell command" => app |
| 10239 | .tr(MessageId::CmdPluginAuditApprovedByAgentShell) |
| 10240 | .into_owned(), |
| 10241 | "trusted from the command line with --yes; no review was shown there" => app |
| 10242 | .tr(MessageId::CmdPluginAuditApprovedByCommandLine) |
| 10243 | .into_owned(), |
| 10244 | "approver not recorded (reviewed before 0.10.3)" => app |
| 10245 | .tr(MessageId::CmdPluginAuditApprovedByUnknown) |
| 10246 | .into_owned(), |
| 10247 | other => sanitize_plugin_change_field(other, 96), |
| 10248 | } |
| 10249 | } |
| 10250 | |
| 10251 | pub(super) fn apply_plugin_changed_notice( |
| 10252 | app: &mut App, |
| 10253 | plugin: &str, |
| 10254 | action: &str, |
| 10255 | decided_by: Option<&str>, |
| 10256 | ) { |
| 10257 | let clean_plugin = sanitize_plugin_change_field(plugin, 80); |
| 10258 | let plugin_label = if clean_plugin.is_empty() { |
| 10259 | "plugin" |
| 10260 | } else { |
| 10261 | clean_plugin.as_str() |
| 10262 | }; |
| 10263 | let action_label = localize_plugin_change_action(app, action); |
| 10264 | let decider_label = decided_by |
| 10265 | .map(|raw| localize_plugin_change_decider(app, raw)) |
| 10266 | .filter(|value| !value.is_empty()); |
| 10267 | let content = match decider_label { |
| 10268 | Some(decider) => app |
| 10269 | .tr(MessageId::PluginChangedWithDeciderReceipt) |
| 10270 | .replace("{plugin}", plugin_label) |
| 10271 | .replace("{action}", &action_label) |
| 10272 | .replace("{decider}", &decider), |
| 10273 | None => app |
| 10274 | .tr(MessageId::PluginChangedReceipt) |
| 10275 | .replace("{plugin}", plugin_label) |
| 10276 | .replace("{action}", &action_label), |
| 10277 | }; |
| 10278 | app.add_message(HistoryCell::System { content }); |
| 10279 | app.needs_redraw = true; |
| 10280 | } |
| 10281 | |
| 10282 | pub(super) async fn reload_terminal_plugin_registry(app: &mut App, config: &Config) { |
| 10283 | let prior = std::sync::Arc::clone(&app.plugin_registry); |
| 10284 | let workspace = app.workspace.clone(); |
| 10285 | let hooks_config = config.hooks_config(); |
| 10286 | let Ok((refreshed, loaded_hooks)) = tokio::task::spawn_blocking(move || { |
| 10287 | let refreshed = prior.rediscover_for_workspace(&workspace); |
| 10288 | let loaded_hooks = codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 10289 | hooks_config, |
| 10290 | &workspace, |
| 10291 | Some(refreshed.as_ref()), |
| 10292 | ); |
| 10293 | (refreshed, loaded_hooks) |
| 10294 | }) |
| 10295 | .await |
| 10296 | else { |
| 10297 | return; |
| 10298 | }; |
| 10299 | app.plugin_registry = std::sync::Arc::clone(&refreshed); |
| 10300 | app.refresh_agent_approved_plugins_notice(); |
| 10301 | for error in crate::commands::user_registry::install_plugin_registry( |
| 10302 | &app.workspace, |
| 10303 | app.plugin_registry.as_ref(), |
| 10304 | ) { |
| 10305 | tracing::warn!(target: "plugins", "{error}"); |
| 10306 | } |
| 10307 | app.hooks = app.hooks.rebind(loaded_hooks, app.workspace.clone()); |
| 10308 | app.runtime_services.hook_executor = Some(std::sync::Arc::new(app.hooks.clone())); |
| 10309 | } |
| 10310 |