返回 CodeWhale
handlers.rs
根目录 / crates / tui / src / tui / ui / handlers.rs
1 //! `handle_*` helpers: turning one input event, view event, or external
2 //! action into `App` state changes.
3 //!
4 //! Moved verbatim out of `ui.rs`.
5
6 use super::*;
7
8 /// How long the picker's ⇧F receipt stays in the footer: long enough to read
9 /// a route and its roles, short enough to leave the chrome still.
10 const FLEET_TOGGLE_TOAST_TTL_MS: u64 = 6_000;
11
12 /// Push the effective roster (saved fleet + config + plugins) to the running
13 /// engine through `Op::SetFleetRoster`. The one path every fleet mutation
14 /// takes: the saved-fleet views call it directly, and `/fleet add|remove`,
15 /// ⇧F, and auto-enroll reach it through `App::fleet_roster_stale`.
16 pub(crate) fn sync_fleet_roster(app: &mut App, config: &Config, engine_handle: &EngineHandle) {
17 let roster = codewhale_engine::fleet::identity::load_effective_roster(
18 &config.fleet_config(),
19 &app.workspace,
20 Some(app.extension_plugin_view().as_ref()),
21 );
22 if let Some(error) = roster.load_error() {
23 app.set_sticky_status(error.to_string(), StatusToastLevel::Error, None);
24 }
25 let _ = engine_handle.try_send(Op::SetFleetRoster {
26 roster: std::sync::Arc::new(roster),
27 });
28 }
29
30 /// Refresh the Fleet roster when it is parked on top of the stack after a
31 /// store mutation (#5954).
32 ///
33 /// The roster now stays open underneath the saved-teams list, so selecting or
34 /// deleting a team has to update the view the user pops back to — otherwise
35 /// it keeps painting the pre-change team. Cursor and detail scroll survive,
36 /// because losing them is the disruption the back path exists to avoid.
37 async fn refresh_parked_fleet_list(app: &mut App, config: &Config) {
38 if app.view_stack.top_kind() != Some(ModalKind::FleetList) {
39 return;
40 }
41 let Some(mut view) = app.view_stack.pop() else {
42 return;
43 };
44 if let Some(list) = view
45 .as_any_mut()
46 .downcast_mut::<crate::tui::views::fleet_list::FleetListView>()
47 {
48 list.reload_async(app, config).await;
49 }
50 app.view_stack.push_boxed(view);
51 }
52
53 pub(crate) fn refresh_parked_fleet_roster(app: &mut App, config: &Config) {
54 if app.view_stack.top_kind() != Some(ModalKind::FleetRoster) {
55 return;
56 }
57 let Some(mut view) = app.view_stack.pop() else {
58 return;
59 };
60 if let Some(roster) = view
61 .as_any_mut()
62 .downcast_mut::<crate::tui::views::fleet_roster::FleetRosterView>()
63 {
64 roster.reload(app, config);
65 }
66 app.view_stack.push_boxed(view);
67 }
68
69 /// Rebuild the open model picker from live state and show `notice` inside
70 /// it. The picker covers the status line, so a receipt written only there
71 /// made ⇧P and ⇧F look like they did nothing (#6500). Returns whether a
72 /// picker was open.
73 pub(super) fn refresh_open_model_picker(
74 app: &mut App,
75 config: &Config,
76 notice: Option<(String, StatusToastLevel)>,
77 ) -> bool {
78 if app.view_stack.top_kind() != Some(ModalKind::ModelPicker) {
79 return false;
80 }
81 let Some(mut boxed) = app.view_stack.pop() else {
82 return false;
83 };
84 if let Some(picker) = boxed
85 .as_any_mut()
86 .downcast_mut::<crate::tui::model_picker::ModelPickerView>()
87 {
88 picker.re_resolve_from_app(app, config);
89 if let Some((text, level)) = notice {
90 picker.set_notice(text, level);
91 }
92 }
93 app.view_stack.push_boxed(boxed);
94 true
95 }
96
97 /// The picker's ⇧P: toggle the exact route in `settings.toml`'s pins.
98 pub(super) fn toggle_model_picker_pin(
99 app: &mut App,
100 config: &Config,
101 provider_key: &str,
102 model: &str,
103 ) {
104 let locale = app.ui_locale;
105 let route = format!("{provider_key}/{model}");
106 let (receipt, level) = match codewhale_runtime::settings::Settings::transact(|settings| {
107 Ok(settings.toggle_pinned_model(provider_key, model))
108 }) {
109 Ok(true) => (
110 tr(locale, MessageId::ModelPickerPinned).replace("{route}", &route),
111 StatusToastLevel::Success,
112 ),
113 Ok(false) => (
114 tr(locale, MessageId::ModelPickerUnpinned).replace("{route}", &route),
115 StatusToastLevel::Success,
116 ),
117 Err(error) => (
118 tr(locale, MessageId::ModelPickerPinFailed).replace("{error}", &error.to_string()),
119 StatusToastLevel::Error,
120 ),
121 };
122 if let Ok(settings) = codewhale_runtime::settings::Settings::load_persisted() {
123 app.pinned_models = settings.pinned_models;
124 }
125 app.show_command_result(receipt.clone(), level);
126 refresh_open_model_picker(app, config, Some((receipt, level)));
127 app.needs_redraw = true;
128 }
129
130 /// The picker's ⇧F: add the exact route to the selected Fleet, or remove the
131 /// shortlist row it added. Same provider gate as `/fleet add`.
132 pub(super) fn toggle_model_picker_fleet(
133 app: &mut App,
134 config: &Config,
135 provider_key: &str,
136 model: &str,
137 ) {
138 use codewhale_engine::fleet::members::{FleetModelChange, change_receipt, toggle_fleet_model};
139 let locale = app.ui_locale;
140 let (receipt, level) = if let Some(rejection) =
141 crate::commands::fleet_provider_rejection(app, config, provider_key)
142 {
143 app.set_sticky_status(rejection.clone(), StatusToastLevel::Error, None);
144 (rejection, StatusToastLevel::Error)
145 } else {
146 match toggle_fleet_model(&app.workspace, provider_key, model) {
147 Ok(change) => {
148 let level = if matches!(change, FleetModelChange::Unchanged { .. }) {
149 StatusToastLevel::Info
150 } else {
151 app.fleet_roster_stale = true;
152 StatusToastLevel::Success
153 };
154 let receipt = change_receipt(locale, provider_key, model, &change);
155 app.push_status_toast(receipt.clone(), level, Some(FLEET_TOGGLE_TOAST_TTL_MS));
156 (receipt, level)
157 }
158 Err(error) => {
159 let message = tr(locale, MessageId::FleetToggleFailed)
160 .replace("{error}", &error.message(locale));
161 app.set_sticky_status(message.clone(), StatusToastLevel::Error, None);
162 (message, StatusToastLevel::Error)
163 }
164 }
165 };
166 refresh_open_model_picker(app, config, Some((receipt, level)));
167 app.needs_redraw = true;
168 }
169
170 pub(super) fn dismiss_fleet_assignment(app: &mut App, editor_id: uuid::Uuid) {
171 if let Some(mut boxed) = app.view_stack.pop() {
172 let remove = if let Some(view) = boxed
173 .as_any_mut()
174 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>(
175 ) {
176 view.route_selection(editor_id).is_some()
177 } else if let Some(view) = boxed
178 .as_any_mut()
179 .downcast_mut::<crate::tui::views::fleet_detail::FleetDetailView>(
180 ) {
181 view.is_direct_assignment(editor_id)
182 } else {
183 false
184 };
185 if !remove {
186 app.view_stack.push_boxed(boxed);
187 }
188 }
189 }
190
191 /// Once per event-loop iteration: deliver a pending fleet mutation to the
192 /// engine and clear the flag.
193 pub(crate) fn flush_stale_fleet_roster(
194 app: &mut App,
195 config: &Config,
196 engine_handle: &EngineHandle,
197 ) {
198 if std::mem::take(&mut app.fleet_roster_stale) {
199 sync_fleet_roster(app, config, engine_handle);
200 }
201 }
202
203 /// Persist a `# foo` quick-add through the native memory store and surface
204 /// a status note to the user. Errors land in the same status channel so a
205 /// missing memory directory becomes visible without crashing the composer.
206 pub(crate) fn handle_memory_quick_add(app: &mut App, input: &str, config: &Config) {
207 let path = config.memory_path();
208 let note = input.trim_start_matches('#').trim();
209 let result = codewhale_runtime::native_memory::NativeMemoryStore::from_global_path(&path)
210 .ok_or_else(|| format!("{} is not a native memory path", path.display()))
211 .and_then(|store| {
212 store
213 .remember(
214 codewhale_runtime::native_memory::MemoryScope::Global,
215 None,
216 note,
217 )
218 .map(|hit| hit.source)
219 .map_err(|err| err.to_string())
220 });
221 match result {
222 Ok(source) => {
223 app.show_command_result(
224 format!("memory: appended to {}", source.display()),
225 StatusToastLevel::Success,
226 );
227 }
228 Err(err) => {
229 app.show_command_result(
230 format!("memory: failed to write {}: {}", path.display(), err),
231 StatusToastLevel::Error,
232 );
233 }
234 }
235 }
236
237 /// The event-loop seam for Ctrl+T. Keeping the `KeyEvent` predicate and App
238 /// mutation together makes the real terminal route directly testable rather
239 /// than testing `cycle_effort` in isolation.
240 pub(crate) fn handle_reasoning_effort_key(app: &mut App, key: &event::KeyEvent) -> bool {
241 if !matches!(key.code, KeyCode::Char('t') | KeyCode::Char('T'))
242 || key.modifiers != KeyModifiers::CONTROL
243 {
244 return false;
245 }
246 let _ = app.cycle_effort();
247 true
248 }
249
250 /// Let the transcript remain reviewable while a decision prompt owns focus.
251 pub(crate) fn handle_prompt_transcript_key(app: &mut App, key: &event::KeyEvent) -> bool {
252 if !matches!(
253 app.view_stack.top_kind(),
254 Some(ModalKind::Approval | ModalKind::UserInput)
255 ) {
256 return false;
257 }
258
259 let page = app.viewport.last_transcript_visible.max(1);
260 match key.code {
261 KeyCode::PageUp => app.scroll_up(page),
262 KeyCode::PageDown => app.scroll_down(page),
263 KeyCode::Up
264 if key
265 .modifiers
266 .intersects(KeyModifiers::ALT | KeyModifiers::SHIFT | KeyModifiers::CONTROL) =>
267 {
268 app.scroll_up(3);
269 }
270 KeyCode::Down
271 if key
272 .modifiers
273 .intersects(KeyModifiers::ALT | KeyModifiers::SHIFT | KeyModifiers::CONTROL) =>
274 {
275 app.scroll_down(3);
276 }
277 KeyCode::Home => app.scroll_up(usize::MAX),
278 KeyCode::End => app.scroll_to_bottom(),
279 _ => return false,
280 }
281 true
282 }
283
284 /// One-shot "draft my constitution" call against the user's first configured
285 /// model, requested by `A` on the setup Constitution card. Runs inline in the
286 /// event loop like [`fetch_available_models`] (the wizard modal stays open
287 /// underneath) with a hard timeout so a slow provider cannot wedge setup.
288 ///
289 /// On success the sanitized, bounded draft is installed into the open wizard
290 /// and its ratification preview opens on top — nothing persists until the
291 /// user ratifies with `G`. Every failure (no client, timeout, request error,
292 /// invalid or empty JSON) is a status line, never an error state: the
293 /// deterministic guided draft remains the standing fallback.
294 pub(crate) async fn handle_setup_constitution_model_draft(
295 app: &mut App,
296 config: &Config,
297 draft: crate::tui::setup::GuidedConstitutionDraft,
298 freeform_note: Option<String>,
299 locale: codewhale_localization::Locale,
300 ) {
301 // Spawn the draft off the event loop (same pattern as the fleet drafter,
302 // #3757 review): awaiting it inline parked the whole TUI for up to the
303 // timeout. The loop polls constitution_draft_cell and delivers the result.
304 const DRAFT_TIMEOUT: Duration = Duration::from_secs(20);
305 let model_label = app.model_display_label();
306 let client = match crate::active_route_client(config).await {
307 Ok(client) => client,
308 Err(err) => {
309 deliver_constitution_draft_result(
310 app,
311 model_label.clone(),
312 locale,
313 Err(format!("provider not ready: {err:#}")),
314 );
315 return;
316 }
317 };
318 let request_model = app.model.clone();
319 let cell = app.constitution_draft_cell.clone();
320 let spawn_label = model_label.clone();
321 let request_gen = app.next_draft_gen();
322 app.show_command_result(
323 match locale {
324 codewhale_localization::Locale::ZhHans => {
325 format!(
326 "{model_label} 正在生成宪章草案……(最多 {}s)",
327 DRAFT_TIMEOUT.as_secs()
328 )
329 }
330 _ => format!(
331 "{model_label} is drafting your constitution… (up to {}s)",
332 DRAFT_TIMEOUT.as_secs()
333 ),
334 },
335 StatusToastLevel::Info,
336 );
337 app.needs_redraw = true;
338 tokio::spawn(async move {
339 let outcome = match tokio::time::timeout(
340 DRAFT_TIMEOUT,
341 crate::tui::setup::draft_constitution_with_model(
342 &client,
343 &request_model,
344 draft,
345 freeform_note,
346 locale,
347 ),
348 )
349 .await
350 {
351 Err(_) => Err(format!("timed out after {}s", DRAFT_TIMEOUT.as_secs())),
352 Ok(result) => result,
353 };
354 if let Ok(mut guard) = cell.lock() {
355 *guard = Some((request_gen, spawn_label, locale, outcome));
356 }
357 });
358 }
359
360 /// One-shot fleet-profile draft: same contract as the constitution drafter —
361 /// minimal payload out, untrusted gate in, preview before ratify, degrade to
362 /// the manual authoring flow on any failure.
363 pub(crate) async fn handle_fleet_profile_model_draft(
364 app: &mut App,
365 config: &Config,
366 role: String,
367 model: String,
368 provider: Option<String>,
369 reasoning_effort: Option<String>,
370 locale: codewhale_localization::Locale,
371 ) {
372 // The route the operator actually picked at `m`-press time (#4093). A
373 // model draft always comes back `provider: None` (the untrusted gate
374 // strips any provider), so this captured `(provider, model)` is what the
375 // ratified profile is pinned to — immune to the model omitting/altering
376 // the route AND to the selection changing while the draft is in flight.
377 // `None` for an `inherit` pick (no concrete route to keep).
378 let picked_route = provider.map(|provider| (provider, model.clone()));
379 // Do NOT await the network call on the event loop — that parks the whole
380 // TUI for up to the timeout (#3757 review). Spawn it into the shared
381 // fleet_draft_cell and let the loop poll + deliver the result, keeping
382 // the wizard interactive with a drafting status.
383 const DRAFT_TIMEOUT: Duration = Duration::from_secs(20);
384 let model_label = app.model_display_label();
385 let client = match crate::active_route_client(config).await {
386 Ok(client) => client,
387 Err(err) => {
388 deliver_fleet_draft_result(
389 app,
390 model_label.clone(),
391 picked_route.clone(),
392 reasoning_effort.clone(),
393 Err(format!("provider not ready: {err:#}")),
394 locale,
395 );
396 return;
397 }
398 };
399 let request_model = app.model.clone();
400 let cell = app.fleet_draft_cell.clone();
401 let spawn_label = model_label.clone();
402 let request_gen = app.next_draft_gen();
403 let workspace = app.workspace.clone();
404 app.show_command_result(
405 match locale {
406 codewhale_localization::Locale::ZhHans => {
407 format!(
408 "{model_label} 正在起草配置……(最多 {}s)",
409 DRAFT_TIMEOUT.as_secs()
410 )
411 }
412 _ => format!(
413 "{model_label} is drafting the profile… (up to {}s)",
414 DRAFT_TIMEOUT.as_secs()
415 ),
416 },
417 StatusToastLevel::Info,
418 );
419 app.needs_redraw = true;
420 tokio::spawn(async move {
421 // Redacted, bounded workspace fingerprint (manifest names, test
422 // commands, branch + dirty count — no contents, secrets, or absolute
423 // paths). Computed off the event loop; the untrusted-output gate on
424 // the reply is unchanged.
425 let fingerprint = tokio::task::spawn_blocking(move || {
426 crate::tui::setup::workspace_fingerprint(&workspace)
427 })
428 .await
429 .unwrap_or_default();
430 let outcome = match tokio::time::timeout(
431 DRAFT_TIMEOUT,
432 crate::tui::setup::draft_fleet_profile_with_model(
433 &client,
434 &request_model,
435 &role,
436 &model,
437 locale,
438 &fingerprint,
439 ),
440 )
441 .await
442 {
443 Err(_) => Err(format!("timed out after {}s", DRAFT_TIMEOUT.as_secs())),
444 Ok(result) => result,
445 };
446 if let Ok(mut guard) = cell.lock() {
447 *guard = Some((
448 request_gen,
449 spawn_label,
450 picked_route,
451 reasoning_effort,
452 outcome,
453 ));
454 }
455 });
456 }
457
458 pub(crate) async fn handle_bang_shell_input(
459 app: &mut App,
460 engine_handle: &EngineHandle,
461 input: &str,
462 ) -> Result<bool> {
463 let command = match shell_command_from_bang_input(input) {
464 Ok(Some(command)) => command,
465 Ok(None) => return Ok(false),
466 Err(message) => {
467 app.show_command_result(format!("Error: {message}"), StatusToastLevel::Error);
468 return Ok(true);
469 }
470 };
471
472 // #6150: composer input never awaits a full op channel — a saturated
473 // engine reports busy instead of freezing the loop.
474 match engine_handle.tx_op.clone().try_reserve_owned() {
475 Ok(permit) => {
476 engine_handle.send_reserved_op(
477 permit,
478 Op::RunShellCommand {
479 command: command.to_string(),
480 mode: app.mode,
481 allow_shell: app.allow_shell,
482 trust_mode: app.trust_mode,
483 auto_approve: app_auto_approve_enabled(app),
484 approval_mode: app.approval_mode,
485 },
486 );
487 app.show_command_result(
488 format!("Shell command submitted: {command}"),
489 StatusToastLevel::Info,
490 );
491 }
492 Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
493 app.show_command_result(
494 "Engine busy — shell command not sent; try again".to_string(),
495 StatusToastLevel::Warning,
496 );
497 }
498 Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
499 return Err(anyhow::anyhow!("engine channel closed"));
500 }
501 }
502 Ok(true)
503 }
504
505 fn report_mcp_login(app: &mut App, message: String, level: StatusToastLevel) {
506 app.push_status_toast(message.clone(), level, Some(12_000));
507 add_mcp_message(app, message);
508 app.needs_redraw = true;
509 }
510
511 fn start_mcp_login(
512 app: &mut App,
513 config: &Config,
514 engine_handle: &EngineHandle,
515 name: String,
516 scopes: Vec<String>,
517 ) {
518 use crate::tui::app::{McpLoginProgress, PendingMcpLogin};
519
520 if let Some(pending) = &app.mcp_login {
521 let server = pending.server.clone();
522 report_mcp_login(
523 app,
524 app.tr(MessageId::McpLoginInProgress)
525 .replace("{server}", &server)
526 .replace("{cancel_key}", "Esc"),
527 StatusToastLevel::Info,
528 );
529 return;
530 }
531
532 let path = app.mcp_config_path.clone();
533 let workspace = app.workspace.clone();
534 let plugin_registry = Arc::clone(&app.plugin_registry);
535 let network_policy = config.network.clone().map(|network| {
536 codewhale_net::network_policy::NetworkPolicyDecider::with_default_audit(
537 codewhale_net::network_policy::NetworkPolicy::from(network),
538 )
539 });
540 let callback_port = config.mcp_oauth_callback_port;
541 let callback_url = config.mcp_oauth_callback_url.clone();
542 let locale = app.ui_locale;
543 let auth_context = engine_handle.mcp_auth_context();
544 let pending = PendingMcpLogin {
545 server: name.clone(),
546 cancel: tokio_util::sync::CancellationToken::new(),
547 progress: Arc::new(std::sync::Mutex::new(None)),
548 };
549 let cancel = pending.cancel.clone();
550 let progress = Arc::clone(&pending.progress);
551 app.mcp_login = Some(pending);
552 report_mcp_login(
553 app,
554 app.tr(MessageId::McpLoginStarting)
555 .replace("{server}", &name)
556 .replace("{cancel_key}", "Esc"),
557 StatusToastLevel::Info,
558 );
559
560 tokio::spawn(async move {
561 let handshake = async {
562 let cfg = codewhale_engine::mcp::load_config_with_workspace_and_plugins(
563 &path,
564 &workspace,
565 plugin_registry.as_ref(),
566 )?;
567 let server = cfg.servers.get(&name).ok_or_else(|| {
568 anyhow::anyhow!(
569 codewhale_localization::tr(locale, MessageId::McpLoginServerNotFound)
570 .replace("{server}", &name)
571 )
572 })?;
573 codewhale_engine::mcp::oauth::begin_oauth_login_for_server_tool_with_auth_context(
574 &name,
575 server,
576 (!scopes.is_empty()).then_some(scopes),
577 callback_port,
578 callback_url.as_deref(),
579 network_policy.as_ref(),
580 auth_context,
581 )
582 .await
583 };
584 let operation = async {
585 // Bound the whole handshake as well as each guarded HTTP request.
586 // The timeout is in the background: even an unresponsive issuer
587 // cannot delay redraw, input or cancellation.
588 let login = tokio::time::timeout(Duration::from_secs(15), handshake)
589 .await
590 .with_context(|| {
591 codewhale_localization::tr(locale, MessageId::McpLoginHandshakeTimeout)
592 .into_owned()
593 })??;
594 if let Ok(mut cell) = progress.lock() {
595 *cell = Some(McpLoginProgress::AuthorizationUrl(
596 login.authorization_url().to_string(),
597 ));
598 }
599 login.finish().await
600 };
601 let outcome = tokio::select! {
602 biased;
603 () = cancel.cancelled() => return,
604 result = operation => result.map_err(|error| {
605 codewhale_engine::mcp::oauth::mask_oauth_secrets(&format!("{error:#}"))
606 }),
607 };
608 if let Ok(mut cell) = progress.lock() {
609 *cell = Some(McpLoginProgress::Finished(outcome));
610 }
611 });
612 }
613
614 pub(crate) fn poll_mcp_login(app: &mut App) {
615 use crate::tui::app::McpLoginProgress;
616
617 let delivery = app.mcp_login.as_ref().and_then(|pending| {
618 pending
619 .progress
620 .try_lock()
621 .ok()
622 .and_then(|mut cell| cell.take())
623 .map(|progress| (pending.server.clone(), progress))
624 });
625 let Some((server, progress)) = delivery else {
626 return;
627 };
628 let (message, level) = match progress {
629 McpLoginProgress::AuthorizationUrl(url) => (
630 app.tr(MessageId::McpLoginBrowser)
631 .replace("{server}", &server)
632 .replace("{cancel_key}", "Esc")
633 .replace("{url}", &url),
634 StatusToastLevel::Info,
635 ),
636 McpLoginProgress::Finished(outcome) => {
637 app.mcp_login = None;
638 match outcome {
639 Ok(()) if codewhale_engine::mcp::mcp_name_is_command_safe(&server) => {
640 app.mcp_login_reconnect = Some(server);
641 return;
642 }
643 Ok(()) => (
644 app.tr(MessageId::McpLoginStored)
645 .replace("{server}", &server)
646 .replace("{command}", "/mcp reload"),
647 StatusToastLevel::Success,
648 ),
649 Err(error) => (
650 app.tr(MessageId::McpLoginFailed)
651 .replace("{server}", &server)
652 .replace("{error}", &error),
653 StatusToastLevel::Error,
654 ),
655 }
656 }
657 };
658 report_mcp_login(app, message, level);
659 }
660
661 pub(crate) fn handle_mcp_login_key(app: &mut App, key: &KeyEvent) -> bool {
662 if key.kind == KeyEventKind::Press && key.code == KeyCode::Esc && app.mcp_login.is_some() {
663 cancel_mcp_login(app);
664 true
665 } else {
666 false
667 }
668 }
669
670 pub(crate) fn cancel_mcp_login(app: &mut App) {
671 if let Some(pending) = app.mcp_login.take() {
672 // Drop cancels before the next input event; future writes belong only
673 // to this abandoned mailbox, even if the same server starts again.
674 let server = pending.server.clone();
675 drop(pending);
676 report_mcp_login(
677 app,
678 app.tr(MessageId::McpLoginCancelled)
679 .replace("{server}", &server),
680 StatusToastLevel::Info,
681 );
682 }
683 }
684
685 /// The config file that owns `name`, for a mutation that must land where the
686 /// server is actually declared.
687 ///
688 /// A plugin-contributed server has no config file: it is switched off by
689 /// disabling the plugin that carries it, so say that instead of writing a
690 /// stray entry into the user's file under the synthesized name.
691 fn mcp_scoped_config_path(
692 app: &App,
693 global_path: &std::path::Path,
694 name: &str,
695 ) -> anyhow::Result<std::path::PathBuf> {
696 let scope = codewhale_engine::mcp::resolve_server_scope(global_path, &app.workspace, name);
697 scope.config_path(global_path).ok_or_else(|| {
698 anyhow::anyhow!(
699 "MCP server '{name}' is provided by a plugin, not by a config file. \
700 Disable the plugin that contributes it from /plugins."
701 )
702 })
703 }
704
705 /// Whether a turn (or its compaction work) owns the engine. The engine
706 /// services ops only between turns, so an op sent now waits for that turn.
707 pub(super) fn mcp_engine_busy(app: &App) -> bool {
708 app.is_loading
709 || app.dispatch_in_flight
710 || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))
711 || app.is_compacting
712 || app.manual_compaction_queued
713 }
714
715 /// Rebuild the open Extensions panel from live state, so a row's pending or
716 /// settled retry shows without waiting for the next MCP generation.
717 fn refresh_open_extensions(app: &mut App) {
718 if app.view_stack.extensions_is_top() {
719 let snapshot = crate::tui::views::extensions::ExtensionsSnapshot::from_app(app);
720 app.view_stack.refresh_extensions(snapshot);
721 }
722 app.needs_redraw = true;
723 }
724
725 /// Reconnect one MCP server through the engine-owned pool without awaiting it
726 /// on the UI loop. While a turn runs, the op waits in the engine mailbox and
727 /// runs as soon as the turn ends — the person asked once, so they are not
728 /// told to ask again.
729 pub(crate) fn start_mcp_retry(app: &mut App, engine_handle: &EngineHandle, name: String) {
730 use crate::tui::app::PendingMcpRetry;
731
732 let already = app
733 .mcp_retries
734 .iter()
735 .find(|pending| pending.server == name);
736 let queued = already.map_or_else(|| mcp_engine_busy(app), |pending| pending.queued);
737 if already.is_none() {
738 tracing::info!(target: "mcp", server = %name, queued, "MCP server retry requested");
739 let result = Arc::new(std::sync::Mutex::new(None));
740 app.mcp_retries.push(PendingMcpRetry {
741 server: name.clone(),
742 queued,
743 result: Arc::clone(&result),
744 });
745 let handle = engine_handle.clone();
746 let server = name.clone();
747 tokio::spawn(async move {
748 let outcome = handle
749 .retry_mcp_server(server)
750 .await
751 .map_err(|error| codewhale_engine::mcp::format_mcp_error_for_display(&error));
752 if let Ok(mut cell) = result.lock() {
753 *cell = Some(outcome);
754 }
755 });
756 }
757 let message = if queued {
758 app.tr(MessageId::McpRetryDeferredWhileTurnRuns)
759 } else {
760 app.tr(MessageId::McpRetryStarted)
761 }
762 .replace("{server}", &name);
763 report_mcp_login(app, message, StatusToastLevel::Info);
764 refresh_open_extensions(app);
765 }
766
767 /// Deliver every settled `/mcp retry`: apply its snapshot and say what
768 /// happened to that server — connected, needs a login, or why it failed.
769 pub(crate) fn poll_mcp_retries(app: &mut App) {
770 if app.mcp_retries.is_empty() {
771 return;
772 }
773 let mut settled = Vec::new();
774 app.mcp_retries.retain(|pending| {
775 match pending
776 .result
777 .try_lock()
778 .ok()
779 .and_then(|mut cell| cell.take())
780 {
781 Some(outcome) => {
782 settled.push((pending.server.clone(), outcome));
783 false
784 }
785 None => true,
786 }
787 });
788 if settled.is_empty() {
789 return;
790 }
791 for (server, outcome) in settled {
792 let (message, level) = match outcome {
793 Ok(update) => {
794 let receipt = mcp_retry_receipt(app, &server, &update.snapshot);
795 apply_mcp_session_boot_event(
796 app,
797 update.generation,
798 update.snapshot,
799 Vec::new(),
800 true,
801 );
802 receipt
803 }
804 Err(error) => {
805 tracing::warn!(target: "mcp", server = %server, error = %error, "MCP server retry could not run");
806 (
807 app.tr(MessageId::McpRetryFailed)
808 .replace("{server}", &server)
809 .replace("{error}", &error),
810 StatusToastLevel::Error,
811 )
812 }
813 };
814 report_mcp_login(app, message, level);
815 }
816 refresh_open_extensions(app);
817 }
818
819 /// The one-line outcome of a retry for `server`, read from the snapshot the
820 /// engine returned for it.
821 fn mcp_retry_receipt(
822 app: &App,
823 server: &str,
824 snapshot: &codewhale_engine::mcp::McpManagerSnapshot,
825 ) -> (String, StatusToastLevel) {
826 let Some(observed) = snapshot.servers.iter().find(|row| row.name == server) else {
827 return (
828 app.tr(MessageId::McpRetryFailed)
829 .replace("{server}", server)
830 .replace(
831 "{error}",
832 &app.tr(MessageId::McpLoginServerNotFound)
833 .replace("{server}", server),
834 ),
835 StatusToastLevel::Error,
836 );
837 };
838 if observed.connected {
839 (
840 app.tr(MessageId::McpRetryConnected)
841 .replace("{server}", server)
842 .replace("{tools}", &observed.tools.len().to_string()),
843 StatusToastLevel::Success,
844 )
845 } else if observed.auth_required {
846 (
847 app.tr(MessageId::McpRetryNeedsLogin)
848 .replace("{server}", server)
849 .replace(
850 "{command}",
851 &codewhale_engine::mcp::McpRecoveryKind::Reauth.slash_command(server),
852 ),
853 StatusToastLevel::Warning,
854 )
855 } else {
856 let error = observed
857 .error
858 .clone()
859 .unwrap_or_else(|| app.tr(MessageId::ExtensionsStateDisconnected).into_owned());
860 (
861 app.tr(MessageId::McpRetryFailed)
862 .replace("{server}", server)
863 .replace("{error}", &error),
864 StatusToastLevel::Error,
865 )
866 }
867 }
868
869 pub(crate) async fn handle_mcp_ui_action(
870 app: &mut App,
871 engine_handle: &EngineHandle,
872 config: &Config,
873 action: crate::tui::app::McpUiAction,
874 ) {
875 use codewhale_engine::mcp::{self, McpWriteStatus};
876
877 let path = app.mcp_config_path.clone();
878 let mut changed = false;
879 let mut message = None;
880 let is_reload = matches!(&action, crate::tui::app::McpUiAction::Reload);
881 // A reload already running owns the live surface, and starting a second
882 // pass restarts every server the first one is still connecting. `Extensions`
883 // rows read `[connecting]` while that happens and answer no key, so a user
884 // who presses Enter again gets another full reconnect and another receipt —
885 // four presses became four overlapping 12-server reloads and a wall of
886 // duplicate notes. The flag was already tracked; nothing ever read it.
887 if is_reload && app.mcp_reload_in_flight {
888 add_mcp_message(app, app.tr(MessageId::McpReloadAlreadyRunning).into_owned());
889 return;
890 }
891 // A retry never runs on this path: it is an engine op, and awaiting it
892 // here parked input behind the connect (or behind a running turn,
893 // #6159). It goes to the engine from a background task instead, so a
894 // running turn simply queues it; `poll_mcp_retries` reports the outcome.
895 if let crate::tui::app::McpUiAction::Retry { name } = &action {
896 start_mcp_retry(app, engine_handle, name.clone());
897 return;
898 }
899 let snapshot_live_pool = matches!(&action, crate::tui::app::McpUiAction::Show);
900 let discover = mcp_ui_action_refreshes_discovery(&action);
901
902 let approve_import = matches!(&action, crate::tui::app::McpUiAction::ImportApprove { .. });
903 let action_result = match action {
904 crate::tui::app::McpUiAction::Diagnose { name } => {
905 let receipt = mcp_server_diagnosis(app, &name);
906 if app.view_stack.extensions_is_top() {
907 open_text_pager(app, name.clone(), receipt.clone());
908 }
909 report_mcp_login(app, receipt, StatusToastLevel::Info);
910 return;
911 }
912 crate::tui::app::McpUiAction::Validate => {
913 let path = path.clone();
914 let workspace = app.workspace.clone();
915 let plugins = app.plugin_registry.clone();
916 #[cfg(test)]
917 let ticket = crate::test_support::env_scope_ticket();
918 let configured = tokio::task::spawn_blocking(move || {
919 #[cfg(test)]
920 let _membership = crate::test_support::join_env_scope(ticket);
921 mcp::load_config_with_workspace_and_plugins(&path, &workspace, plugins.as_ref())
922 })
923 .await
924 .unwrap_or_else(|_| Err(anyhow::anyhow!("MCP config read failed")));
925 let mut names: std::collections::BTreeSet<String> = app
926 .mcp_snapshot
927 .iter()
928 .flat_map(|snapshot| snapshot.servers.iter().map(|server| server.name.clone()))
929 .collect();
930 let mut sections = Vec::new();
931 let config_loaded = match configured {
932 Ok(config) => {
933 names.extend(config.servers.into_keys());
934 true
935 }
936 Err(err) => {
937 sections.push(format!(
938 "MCP config could not be loaded: {}. Fix it, then run /mcp reload.",
939 mcp::format_mcp_error_for_display(&err)
940 ));
941 false
942 }
943 };
944 if let Some(note) = crate::project_mcp_approval_note(&app.workspace) {
945 sections.push(note);
946 }
947 if app.mcp_reload_required {
948 sections.push(
949 "MCP config changed since the live pool loaded. Run /mcp reload to apply it."
950 .to_string(),
951 );
952 }
953 if names.is_empty() && config_loaded {
954 sections.push(app.tr(MessageId::ExtensionsMcpEmpty).into_owned());
955 }
956 sections.extend(names.iter().map(|name| mcp_server_diagnosis(app, name)));
957 let receipt = sections.join("\n\n");
958 if !app.view_stack.extensions_is_top() {
959 open_mcp_extensions(app);
960 }
961 open_text_pager(
962 app,
963 app.tr(MessageId::ConfigSectionMcp).into_owned(),
964 receipt.clone(),
965 );
966 add_mcp_message(app, receipt);
967 app.needs_redraw = true;
968 return;
969 }
970 crate::tui::app::McpUiAction::Show => Ok(()),
971 crate::tui::app::McpUiAction::ProjectReview => {
972 use codewhale_engine::mcp::project_authority::review_project_mcp;
973 match review_project_mcp(&app.workspace) {
974 Ok(reviewed) => {
975 message = Some(format!(
976 "Project MCP servers start processes and open connections as you. Review this file and any scripts it runs before approval.\n\n{}\n\nTo approve these exact contents: /mcp approve {}",
977 codewhale_engine::hooks::sanitize_hook_text(
978 &reviewed.contents,
979 reviewed.contents.chars().count()
980 ),
981 reviewed.digest
982 ));
983 Ok(())
984 }
985 Err(error) => Err(anyhow::anyhow!(error)),
986 }
987 }
988 crate::tui::app::McpUiAction::ProjectApprove { digest } => {
989 changed = true;
990 codewhale_engine::mcp::project_authority::approve_project_mcp(
991 &app.workspace,
992 digest.trim(),
993 )
994 .map_err(anyhow::Error::msg)
995 .map(|()| {
996 message = Some(
997 "Approved these exact project MCP servers. Changes to the file require another review."
998 .to_string(),
999 );
1000 })
1001 }
1002 crate::tui::app::McpUiAction::ProjectRevoke => {
1003 changed = true;
1004 codewhale_engine::mcp::project_authority::revoke_project_mcp(&app.workspace)
1005 .map_err(anyhow::Error::msg)
1006 .map(|()| {
1007 message = Some(
1008 "Project MCP approval revoked. Project servers are unloaded.".to_string(),
1009 );
1010 })
1011 }
1012 crate::tui::app::McpUiAction::Init { force } => {
1013 changed = true;
1014 match mcp::init_config(&path, force) {
1015 Ok(McpWriteStatus::Created) => {
1016 message = Some(format!("Created MCP config at {}", path.display()));
1017 Ok(())
1018 }
1019 Ok(McpWriteStatus::Overwritten) => {
1020 message = Some(format!("Overwrote MCP config at {}", path.display()));
1021 Ok(())
1022 }
1023 Ok(McpWriteStatus::SkippedExists) => {
1024 changed = false;
1025 message = Some(format!(
1026 "MCP config already exists at {} (use /mcp init --force to overwrite)",
1027 path.display()
1028 ));
1029 Ok(())
1030 }
1031 Err(err) => Err(err),
1032 }
1033 }
1034 crate::tui::app::McpUiAction::AddStdio {
1035 name,
1036 command,
1037 args,
1038 } => {
1039 changed = true;
1040 mcp::add_server_config(&path, name.clone(), Some(command), None, args, None)
1041 .map(|()| message = Some(format!("Added MCP stdio server '{name}'")))
1042 }
1043 crate::tui::app::McpUiAction::AddHttp {
1044 name,
1045 url,
1046 transport,
1047 } => {
1048 changed = true;
1049 mcp::add_server_config(&path, name.clone(), None, Some(url), Vec::new(), transport)
1050 .map(|()| message = Some(format!("Added MCP HTTP/SSE server '{name}'")))
1051 }
1052 // Write where the server actually lives. `path` is the user's global
1053 // file; a workspace-scoped server is declared in the trusted
1054 // workspace's own file and overrides a same-named global entry, so
1055 // editing the global file here reported success on the wrong server
1056 // or failed with "not found" on a row the panel had just offered.
1057 crate::tui::app::McpUiAction::Enable { name } => {
1058 changed = true;
1059 mcp_scoped_config_path(app, &path, &name)
1060 .and_then(|owner| mcp::set_server_enabled(&owner, &name, true))
1061 .map(|()| message = Some(format!("Enabled MCP server '{name}'")))
1062 }
1063 crate::tui::app::McpUiAction::Disable { name } => {
1064 changed = true;
1065 mcp_scoped_config_path(app, &path, &name)
1066 .and_then(|owner| mcp::set_server_enabled(&owner, &name, false))
1067 .map(|()| message = Some(format!("Disabled MCP server '{name}'")))
1068 }
1069 crate::tui::app::McpUiAction::Remove { name } => {
1070 changed = true;
1071 mcp_scoped_config_path(app, &path, &name)
1072 .and_then(|owner| mcp::remove_server_config(&owner, &name))
1073 .map(|()| message = Some(format!("Removed MCP server '{name}'")))
1074 }
1075 crate::tui::app::McpUiAction::Login { name, scopes } => {
1076 start_mcp_login(app, config, engine_handle, name, scopes);
1077 // Login owns its background discovery. Do not start a second
1078 // discovery here or await network work on the input loop.
1079 return;
1080 }
1081 crate::tui::app::McpUiAction::Logout { name } => {
1082 let result = (|| {
1083 let cfg = mcp::load_config_with_workspace_and_plugins(
1084 &path,
1085 &app.workspace,
1086 app.plugin_registry.as_ref(),
1087 )?;
1088 let server = cfg
1089 .servers
1090 .get(&name)
1091 .ok_or_else(|| anyhow::anyhow!("MCP server '{name}' not found"))?;
1092 mcp::oauth::delete_oauth_tokens_for_server(&name, server)
1093 })();
1094 result.map(|deleted| {
1095 changed = deleted;
1096 message = Some(if deleted {
1097 format!(
1098 "Deleted locally stored OAuth credentials for MCP server '{name}'. That clears this machine only — the provider may keep its grant; the next /mcp login re-prompts for consent. Run /mcp reload to reconnect."
1099 )
1100 } else {
1101 format!("No stored OAuth credentials found for MCP server '{name}'.")
1102 });
1103 })
1104 }
1105 crate::tui::app::McpUiAction::ImportList => {
1106 let path = path.clone();
1107 let workspace = app.workspace.clone();
1108 let plugins = app.plugin_registry.clone();
1109 #[cfg(test)]
1110 let ticket = crate::test_support::env_scope_ticket();
1111 match tokio::task::spawn_blocking(move || {
1112 #[cfg(test)]
1113 let _membership = crate::test_support::join_env_scope(ticket);
1114 mcp_external_import_status_text(&workspace, &path, plugins.as_ref())
1115 })
1116 .await
1117 {
1118 Ok(text) => {
1119 message = Some(text);
1120 Ok(())
1121 }
1122 Err(_) => Err(anyhow::anyhow!("MCP import preview failed")),
1123 }
1124 }
1125 crate::tui::app::McpUiAction::ImportApprove { name }
1126 | crate::tui::app::McpUiAction::ImportDecline { name } => {
1127 let approve = approve_import;
1128 let path = path.clone();
1129 let workspace = app.workspace.clone();
1130 let plugins = app.plugin_registry.clone();
1131 #[cfg(test)]
1132 let ticket = crate::test_support::env_scope_ticket();
1133 match tokio::task::spawn_blocking(move || {
1134 #[cfg(test)]
1135 let _membership = crate::test_support::join_env_scope(ticket);
1136 mcp_import_apply(&workspace, &path, plugins.as_ref(), &name, approve)
1137 })
1138 .await
1139 {
1140 Ok(Ok(msg)) => {
1141 changed = approve;
1142 message = Some(msg);
1143 Ok(())
1144 }
1145 Ok(Err(err)) => Err(err),
1146 Err(_) => Err(anyhow::anyhow!("MCP import failed")),
1147 }
1148 }
1149 crate::tui::app::McpUiAction::Reload => Ok(()),
1150 // Dispatched before this match.
1151 crate::tui::app::McpUiAction::Retry { .. } => Ok(()),
1152 };
1153
1154 if let Err(err) = action_result {
1155 add_mcp_message(app, format!("MCP action failed: {err}"));
1156 return;
1157 }
1158
1159 if changed {
1160 app.mcp_reload_required = true;
1161 }
1162 if let Some(message) = message {
1163 add_mcp_message(app, message);
1164 }
1165
1166 // Every branch below is an engine round-trip, and the engine services ops
1167 // only between turns (`Engine::run` runs a turn inline and never polls
1168 // `rx_op` mid-turn): awaiting one from this UI path parked every keypress
1169 // and repaint behind the running turn — a full console freeze (#6159).
1170 // While a turn (or its compaction work) owns the engine, serve the last
1171 // known snapshot and say so; mutations name the deferral instead of
1172 // freezing. `reject_inline_inference_while_runtime_chat_owns_run`
1173 // (apply.rs) is the same fail-closed rule for inline inference.
1174 let engine_busy = mcp_engine_busy(app);
1175 if engine_busy && (snapshot_live_pool || is_reload || changed) {
1176 if snapshot_live_pool {
1177 match app.mcp_snapshot.clone() {
1178 Some(snapshot) => {
1179 app.mcp_configured_count = snapshot.servers.len();
1180 app.mcp_snapshot = Some(snapshot);
1181 app.set_mcp_boot_initializing(false);
1182 app.mcp_connecting.clear();
1183 app.hotbar_actions
1184 .replace_mcp_tools(app.mcp_snapshot.as_ref());
1185 add_mcp_message(
1186 app,
1187 app.tr(MessageId::McpShowCachedWhileTurnRuns).into_owned(),
1188 );
1189 open_mcp_extensions(app);
1190 }
1191 None => add_mcp_message(
1192 app,
1193 app.tr(MessageId::McpShowUnavailableWhileTurnRuns)
1194 .into_owned(),
1195 ),
1196 }
1197 } else {
1198 add_mcp_message(
1199 app,
1200 app.tr(MessageId::McpLivePoolRefreshDeferredWhileTurnRuns)
1201 .into_owned(),
1202 );
1203 }
1204 return;
1205 }
1206
1207 // A successful MCP mutation is an explicit request to change the tools
1208 // available to this running session. Apply it to the engine-owned pool in
1209 // the same operation instead of leaving Extensions and `/mcp` users on a
1210 // second, easy-to-miss reload step. The standalone reload action remains
1211 // the retry/compatibility path for externally edited configuration.
1212 let rebuild_live_pool = is_reload || changed;
1213 let snapshot_result = if snapshot_live_pool {
1214 engine_handle
1215 .bootstrap_mcp()
1216 .await
1217 .map(|update| (update.snapshot, Some(update.generation)))
1218 } else if rebuild_live_pool {
1219 match engine_handle.reload_mcp(path.clone()).await {
1220 Ok(update) => {
1221 // The reload no longer waits for the connect batch. The
1222 // engine's supervised pass owns the live surface from here:
1223 // apply the interim snapshot without invalidating its own
1224 // generation, leave connecting/initializing to the pass's
1225 // progress events, and let its finished event post the
1226 // counts. A config mutation keeps its own receipt instead of
1227 // the reload-started line.
1228 app.mcp_reload_required = false;
1229 app.mcp_reload_in_flight = true;
1230 app.set_mcp_boot_initializing(true);
1231 if is_reload {
1232 add_mcp_message(
1233 app,
1234 format!(
1235 "MCP reload started in the background: {} configured server(s) reconnecting. The status bar tracks progress; the next model turn uses the catalog as it settles.",
1236 update.snapshot.servers.len()
1237 ),
1238 );
1239 }
1240 app.mcp_configured_count = update.snapshot.servers.len();
1241 app.mcp_snapshot_generation = update.generation;
1242 app.mcp_snapshot_generation_invalidated = false;
1243 app.hotbar_actions.replace_mcp_tools(Some(&update.snapshot));
1244 app.mcp_snapshot = Some(update.snapshot);
1245 open_mcp_extensions(app);
1246 return;
1247 }
1248 Err(error) => {
1249 app.mcp_reload_required = true;
1250 Err(error)
1251 }
1252 }
1253 } else if discover {
1254 let network_policy = config.network.clone().map(|toml_cfg| {
1255 codewhale_net::network_policy::NetworkPolicyDecider::with_default_audit(
1256 codewhale_net::network_policy::NetworkPolicy::from(toml_cfg),
1257 )
1258 });
1259 mcp::discover_manager_snapshot_with_workspace_and_plugins(
1260 &path,
1261 &app.workspace,
1262 network_policy,
1263 app.mcp_reload_required,
1264 std::sync::Arc::clone(&app.plugin_registry),
1265 config.mcp_backend(),
1266 )
1267 .await
1268 .map(|snapshot| (snapshot, None))
1269 } else {
1270 mcp::manager_snapshot_from_config_with_workspace_and_plugins(
1271 &path,
1272 &app.workspace,
1273 app.mcp_reload_required,
1274 app.plugin_registry.as_ref(),
1275 )
1276 .map(|snapshot| (snapshot, None))
1277 };
1278
1279 match snapshot_result {
1280 Ok((snapshot, generation)) => {
1281 if discover {
1282 add_mcp_message(
1283 app,
1284 "MCP discovery refreshed for the UI. Run /mcp reload after config or credential edits to rebuild the live model-visible tool pool.".to_string(),
1285 );
1286 }
1287 // Keep the boot-time MCP-count chip in sync with the live
1288 // snapshot so footers and panels reflect post-/mcp edits
1289 // (#502).
1290 app.mcp_configured_count = snapshot.servers.len();
1291 if let Some(generation) = generation {
1292 app.mcp_snapshot_generation = generation;
1293 app.mcp_snapshot_generation_invalidated = true;
1294 }
1295 app.mcp_snapshot = Some(snapshot.clone());
1296 app.set_mcp_boot_initializing(false);
1297 app.mcp_connecting.clear();
1298 // #2068: keep the hotbar's MCP-tool actions in sync with the tools
1299 // that are actually loaded; the hotbar never connects on its own.
1300 app.hotbar_actions.replace_mcp_tools(Some(&snapshot));
1301 open_mcp_extensions(app);
1302 }
1303 Err(err) if rebuild_live_pool => add_mcp_message(
1304 app,
1305 format!("MCP reload failed; the live tool pool is unchanged: {err}"),
1306 ),
1307 Err(err) => add_mcp_message(app, format!("MCP snapshot failed: {err}")),
1308 }
1309 }
1310
1311 pub(crate) fn handle_shell_job_action(app: &mut App, action: crate::tui::app::ShellJobAction) {
1312 let Some(shell_manager) = app.runtime_services.shell_manager.clone() else {
1313 add_shell_job_message(app, "No shell session is active.".to_string());
1314 return;
1315 };
1316
1317 let mut manager = match shell_manager.lock() {
1318 Ok(manager) => manager,
1319 Err(_) => {
1320 add_shell_job_message(
1321 app,
1322 "Shell tracking hit an internal error — restart Codewhale to recover.".to_string(),
1323 );
1324 return;
1325 }
1326 };
1327 let active_session_id = app.current_session_id.clone().unwrap_or_default();
1328
1329 match action {
1330 crate::tui::app::ShellJobAction::List => {
1331 let jobs = manager.list_jobs_for_session(&active_session_id);
1332 let text = format_shell_job_list(&jobs);
1333 add_shell_job_message(app, text);
1334 }
1335 crate::tui::app::ShellJobAction::Show { id } => {
1336 match manager.inspect_job_for_session(&active_session_id, &id) {
1337 Ok(detail) => open_shell_job_pager(app, &detail),
1338 Err(err) => add_shell_job_message(app, format!("Command lookup failed: {err}")),
1339 }
1340 }
1341 crate::tui::app::ShellJobAction::SendStdin { id, input, close } => {
1342 match manager.write_stdin_for_session(&active_session_id, &id, &input, close) {
1343 Ok(()) => match manager.inspect_job_for_session(&active_session_id, &id) {
1344 Ok(detail) => add_shell_job_message(
1345 app,
1346 format_shell_job_list(std::slice::from_ref(&detail.snapshot)),
1347 ),
1348 Err(err) => {
1349 add_shell_job_message(
1350 app,
1351 format!("Command input sent; poll failed: {err}"),
1352 );
1353 }
1354 },
1355 Err(err) => add_shell_job_message(app, format!("Command input failed: {err}")),
1356 }
1357 }
1358 crate::tui::app::ShellJobAction::Cancel { id } => {
1359 match manager.kill_for_session(&active_session_id, &id) {
1360 Ok(result) => {
1361 manager.mark_cancel_reported(&result);
1362 add_shell_job_message(app, format_shell_poll(&result));
1363 }
1364 Err(err) => add_shell_job_message(app, format!("Command cancel failed: {err}")),
1365 }
1366 }
1367 crate::tui::app::ShellJobAction::CancelAll => {
1368 match manager.kill_running_for_session(&active_session_id) {
1369 Ok(results) => {
1370 for result in &results {
1371 manager.mark_cancel_reported(result);
1372 }
1373 let count = results.len();
1374 if count == 0 {
1375 add_shell_job_message(app, "No running commands to cancel.".to_string());
1376 } else {
1377 let tasks: Vec<String> = results
1378 .iter()
1379 .filter_map(|result| result.task_id.clone())
1380 .collect();
1381 add_shell_job_message(
1382 app,
1383 format!("Canceled {count} command(s): {}", tasks.join(", ")),
1384 );
1385 }
1386 }
1387 Err(err) => add_shell_job_message(app, format!("Command cancel-all failed: {err}")),
1388 }
1389 }
1390 }
1391 }
1392
1393 pub(crate) async fn handle_skill_mutation_requested(
1394 app: &mut App,
1395 request: codewhale_skills::mutation::SkillMutationRequest,
1396 ) {
1397 use codewhale_skill_install::install::{DEFAULT_MAX_SIZE_BYTES, DEFAULT_REGISTRY_URL};
1398 use codewhale_skills::mutation::{MutationContext, SkillMutationOutcome, SkillMutationRequest};
1399
1400 let focus = match &request {
1401 SkillMutationRequest::ImportExternal { source_id, .. } => Some(source_id.clone()),
1402 SkillMutationRequest::Update { skill_id, .. }
1403 | SkillMutationRequest::Remove { skill_id, .. }
1404 | SkillMutationRequest::Trust { skill_id, .. } => Some(skill_id.clone()),
1405 SkillMutationRequest::InstallRemote { .. }
1406 | SkillMutationRequest::UpdateByName { .. }
1407 | SkillMutationRequest::RemoveByName { .. }
1408 | SkillMutationRequest::TrustByName { .. } => None,
1409 };
1410
1411 let workspace = app.workspace.clone();
1412 let home = codewhale_paths::user_home();
1413 let cfg = match codewhale_plugins::providers::load_config(None, None) {
1414 Ok(cfg) => cfg,
1415 Err(err) => {
1416 tracing::warn!(error = %err, "skills config unavailable; refusing skill mutation");
1417 let status = format!("Skill mutation refused: config could not be loaded ({err:#})");
1418 app.set_sticky_status(status.clone(), StatusToastLevel::Error, None);
1419 refresh_skills_manager_if_open(app, Some(status), focus.as_ref());
1420 app.needs_redraw = true;
1421 return;
1422 }
1423 };
1424 let network = cfg
1425 .network
1426 .clone()
1427 .map(codewhale_net::network_policy::NetworkPolicy::from)
1428 .unwrap_or_default();
1429 let skills_cfg = cfg.skills.as_ref();
1430 let max_size = skills_cfg
1431 .and_then(|s| s.max_install_size_bytes)
1432 .unwrap_or(DEFAULT_MAX_SIZE_BYTES);
1433 let registry_url = skills_cfg
1434 .and_then(|s| s.registry_url.clone())
1435 .unwrap_or_else(|| DEFAULT_REGISTRY_URL.to_string());
1436
1437 let skills_dir = app.skills_dir.clone();
1438 let result = {
1439 let ctx = MutationContext {
1440 workspace: &workspace,
1441 home: home.as_deref(),
1442 configured_skills_dir: Some(skills_dir.as_path()),
1443 network: &network,
1444 max_size,
1445 registry_url: &registry_url,
1446 };
1447 codewhale_skills::mutation::execute(request, &ctx).await
1448 };
1449
1450 let (status, level) = match result {
1451 Ok(receipt) => {
1452 let msg = match &receipt.outcome {
1453 SkillMutationOutcome::Installed => {
1454 format!(
1455 "Installed '{}' → {}",
1456 receipt.name, receipt.safe_target_path
1457 )
1458 }
1459 SkillMutationOutcome::Updated => format!("Updated '{}'", receipt.name),
1460 SkillMutationOutcome::NoChange => {
1461 format!("'{}': no upstream change", receipt.name)
1462 }
1463 SkillMutationOutcome::Removed => format!("Removed '{}'", receipt.name),
1464 SkillMutationOutcome::Trusted => format!("Trusted '{}'", receipt.name),
1465 SkillMutationOutcome::Imported => {
1466 format!("Imported '{}' → {}", receipt.name, receipt.safe_target_path)
1467 }
1468 SkillMutationOutcome::AlreadyPresent => {
1469 format!("'{}' already present (exact duplicate)", receipt.name)
1470 }
1471 SkillMutationOutcome::NeedsApproval(host) => {
1472 format!("Needs network approval for {host}")
1473 }
1474 SkillMutationOutcome::NetworkDenied(host) => {
1475 format!("Network denied for {host}")
1476 }
1477 };
1478 let level = match receipt.outcome {
1479 SkillMutationOutcome::NeedsApproval(_) => StatusToastLevel::Warning,
1480 SkillMutationOutcome::NetworkDenied(_) => StatusToastLevel::Error,
1481 _ => StatusToastLevel::Success,
1482 };
1483 (msg, level)
1484 }
1485 Err(err) => (
1486 format!("Skill mutation failed: {err:#}"),
1487 StatusToastLevel::Error,
1488 ),
1489 };
1490
1491 app.show_command_result(status.clone(), level);
1492 if level == StatusToastLevel::Success {
1493 app.refresh_skill_cache();
1494 }
1495 refresh_skills_manager_if_open(app, Some(status), focus.as_ref());
1496 app.needs_redraw = true;
1497 }
1498
1499 #[allow(clippy::too_many_arguments)]
1500 pub(crate) async fn handle_config_updated(
1501 terminal: &mut AppTerminal,
1502 app: &mut App,
1503 config: &mut Config,
1504 engine_handle: &mut EngineHandle,
1505 key: String,
1506 value: String,
1507 persist: bool,
1508 ) -> Result<bool> {
1509 let result = prepare_config_update_result(
1510 commands::set_config_value(app, &key, &value, persist),
1511 persist,
1512 );
1513 let telemetry_toast = (key == "telemetry")
1514 .then(|| {
1515 result.message.clone().map(|message| {
1516 let level = if result.is_error {
1517 StatusToastLevel::Error
1518 } else {
1519 StatusToastLevel::Success
1520 };
1521 (message, level)
1522 })
1523 })
1524 .flatten();
1525 let normalized_value = value.trim().to_ascii_lowercase().replace([' ', '_'], "-");
1526 let cleared_root_approval = !result.is_error
1527 && persist
1528 && key == "approval_policy"
1529 && matches!(
1530 normalized_value.as_str(),
1531 "default" | "tui-default" | "use-tui-default"
1532 );
1533 // Theme / background changes require a full terminal repaint because
1534 // ratatui's incremental diff cannot see colors remapped by the backend.
1535 if matches!(
1536 key.as_str(),
1537 "theme" | "ui_theme" | "background_color" | "background" | "bg"
1538 ) {
1539 app.force_next_full_repaint = true;
1540 }
1541 let rejected = result.is_error;
1542 if apply_command_result(terminal, app, engine_handle, config, result).await? {
1543 return Ok(true);
1544 }
1545
1546 let focus_key = if cleared_root_approval {
1547 "permission_posture"
1548 } else {
1549 &key
1550 };
1551 refresh_config_view_after_commit(app, focus_key, rejected);
1552 if let Some((message, level)) = telemetry_toast {
1553 // The modal stays open, so a transcript-only command receipt would be
1554 // invisible. Keep the durable disk truth in the rebuilt row and show
1555 // the localized result above it.
1556 app.push_status_toast(message, level, Some(12_000));
1557 }
1558 Ok(false)
1559 }
1560
1561 #[allow(clippy::too_many_arguments)]
1562 async fn handle_theme_selection_updated(
1563 terminal: &mut AppTerminal,
1564 app: &mut App,
1565 config: &mut Config,
1566 engine_handle: &mut EngineHandle,
1567 theme: String,
1568 persist: bool,
1569 ) -> Result<bool> {
1570 let result = prepare_config_update_result(
1571 commands::set_config_value(app, "theme", &theme, persist),
1572 persist,
1573 );
1574 // The theme owns the shell paint and must bypass ratatui's incremental
1575 // cell diff, including an Esc rollback.
1576 app.force_next_full_repaint = true;
1577 if apply_command_result(terminal, app, engine_handle, config, result).await? {
1578 return Ok(true);
1579 }
1580 refresh_config_view_if_open(app, "theme");
1581 Ok(false)
1582 }
1583
1584 /// Whether a settled question is the host's own Plan hand-off rather than an
1585 /// engine `request_user_input` call. The engine's request is recorded in
1586 /// `pending_user_input_prompt` before its view opens, so a provider-chosen
1587 /// tool-call id equal to the hand-off id still reaches the engine.
1588 pub(crate) fn is_plan_handoff_request(app: &App, tool_id: &str) -> bool {
1589 (tool_id == crate::tui::plan_handoff::REQUEST_ID
1590 || tool_id.starts_with(&format!("{}:", crate::tui::plan_handoff::REQUEST_ID)))
1591 && app
1592 .pending_user_input_prompt
1593 .as_ref()
1594 .is_none_or(|(id, _)| id != tool_id)
1595 }
1596
1597 fn plan_handoff_seed_title(plan: &crate::tui::plan_handoff::PendingPlanHandoff) -> String {
1598 // Match the graph's trimmed title without changing the approved message.
1599 let collapse = |text: &str| text.split_whitespace().collect::<Vec<_>>().join(" ");
1600 let mut in_fence = false;
1601 let title = plan
1602 .text
1603 .lines()
1604 .map(str::trim)
1605 .filter(|line| {
1606 if line.starts_with("```") || line.starts_with("~~~") {
1607 in_fence = !in_fence;
1608 return false;
1609 }
1610 !in_fence && !line.starts_with('#')
1611 })
1612 .map(|line| {
1613 collapse(
1614 &line
1615 .trim_start_matches(['-', '*', '+', '>'])
1616 .replace(['*', '`'], ""),
1617 )
1618 })
1619 .find(|line| !line.is_empty())
1620 .unwrap_or_else(|| collapse(&plan.text));
1621 title
1622 .chars()
1623 .take(1024)
1624 .collect::<String>()
1625 .trim()
1626 .to_string()
1627 }
1628
1629 fn plan_handoff_proceed_message(
1630 app: &App,
1631 plan: &crate::tui::plan_handoff::PendingPlanHandoff,
1632 ) -> String {
1633 let message = format!("{}\n\n{}", app.tr(MessageId::PlanHandoffProceed), plan.text);
1634 if plan.seeded_todo_id.is_none() {
1635 return message;
1636 }
1637 format!(
1638 "{message}\n\n{}",
1639 app.tr(MessageId::PlanHandoffTodoNote)
1640 .replace("{title}", &plan_handoff_seed_title(plan))
1641 )
1642 }
1643
1644 /// Stage one graph-owned item for a prose plan without replacing existing work.
1645 async fn seed_plan_handoff_todos(
1646 app: &App,
1647 plan: &mut crate::tui::plan_handoff::PendingPlanHandoff,
1648 ) -> Result<(), String> {
1649 if plan.has_current_checklist {
1650 return Ok(());
1651 }
1652 let work = app
1653 .runtime_services
1654 .work
1655 .as_ref()
1656 .ok_or_else(|| "Work state is unavailable".to_string())?;
1657 let mut todos = work.current_todos().await?;
1658 let content = plan_handoff_seed_title(plan);
1659 if let Some(id) = plan.seeded_todo_id {
1660 return if todos.items.iter().any(|item| {
1661 item.id == id
1662 && item.content == content
1663 && item.status == codewhale_engine::tools::todo::TodoStatus::Pending
1664 }) {
1665 Ok(())
1666 } else {
1667 Err("The approved plan's To-do changed; review the plan again".to_string())
1668 };
1669 }
1670 let id = todos
1671 .items
1672 .iter()
1673 .map(|item| item.id)
1674 .max()
1675 .unwrap_or(0)
1676 .checked_add(1)
1677 .ok_or_else(|| "To-do item IDs are exhausted".to_string())?;
1678 todos.items.push(codewhale_engine::tools::todo::TodoItem {
1679 id,
1680 content,
1681 status: codewhale_engine::tools::todo::TodoStatus::Pending,
1682 });
1683 work.apply_todo_update(&plan.session_id, "todo_write", &todos)
1684 .await?;
1685 plan.seeded_todo_id = Some(id);
1686 Ok(())
1687 }
1688
1689 /// Remove only this unchanged seed from the latest projection. Unprojected
1690 /// graph history remains; operation_parent cannot adopt an unprojected step.
1691 async fn rollback_plan_handoff_seed(
1692 app: &App,
1693 plan: &mut crate::tui::plan_handoff::PendingPlanHandoff,
1694 ) -> Result<(), String> {
1695 let Some(id) = plan.seeded_todo_id else {
1696 return Ok(());
1697 };
1698 if app.current_session_id.as_deref() != Some(plan.session_id.as_str()) {
1699 return Err("The plan belongs to another session".to_string());
1700 }
1701 let work = app
1702 .runtime_services
1703 .work
1704 .as_ref()
1705 .ok_or_else(|| "Work state is unavailable".to_string())?;
1706 let mut todos = work.current_todos().await?;
1707 if let Some(item) = todos.items.iter().find(|item| item.id == id) {
1708 if item.content != plan_handoff_seed_title(plan)
1709 || item.status != codewhale_engine::tools::todo::TodoStatus::Pending
1710 {
1711 return Err(
1712 "The approved plan's To-do changed; review it before continuing".to_string(),
1713 );
1714 }
1715 todos.items.retain(|item| item.id != id);
1716 work.apply_todo_update(&plan.session_id, "todo_write", &todos)
1717 .await?;
1718 }
1719 plan.seeded_todo_id = None;
1720 Ok(())
1721 }
1722
1723 fn reopen_plan_handoff(
1724 app: &mut App,
1725 plan: &crate::tui::plan_handoff::PendingPlanHandoff,
1726 reason: &str,
1727 ) {
1728 app.view_stack.push(UserInputView::new(
1729 plan.request_id.clone(),
1730 crate::tui::plan_handoff::request(app.ui_locale),
1731 app.ui_locale,
1732 ));
1733 let notice = app
1734 .tr(MessageId::SessionSaveFailed)
1735 .replace("{id}", &plan.session_id)
1736 .replace("{error}", reason);
1737 app.push_status_toast(notice, StatusToastLevel::Warning, Some(8_000));
1738 }
1739
1740 /// Carry out only the answer bound to this exact completed Plan response.
1741 pub(crate) async fn apply_plan_handoff(
1742 app: &mut App,
1743 config: &Config,
1744 engine_handle: &EngineHandle,
1745 request_id: &str,
1746 choice: crate::tui::plan_handoff::PlanHandoffChoice,
1747 ) -> Result<()> {
1748 apply_plan_handoff_with_checkpoint(app, config, engine_handle, request_id, choice, |app| {
1749 Box::pin(persist_pending_work_checkpoint(app))
1750 })
1751 .await
1752 }
1753
1754 type PlanHandoffCheckpoint =
1755 for<'a> fn(&'a mut App) -> Pin<Box<dyn Future<Output = Result<bool, String>> + 'a>>;
1756
1757 /// The checkpoint callback keeps the existing admission boundary explicit;
1758 /// tests can refuse admission without mutating the global persistence actor.
1759 pub(crate) async fn apply_plan_handoff_with_checkpoint(
1760 app: &mut App,
1761 config: &Config,
1762 engine_handle: &EngineHandle,
1763 request_id: &str,
1764 choice: crate::tui::plan_handoff::PlanHandoffChoice,
1765 checkpoint: PlanHandoffCheckpoint,
1766 ) -> Result<()> {
1767 use crate::tui::plan_handoff::PlanHandoffChoice;
1768
1769 let Some(mut plan) = app
1770 .pending_plan_handoff
1771 .clone()
1772 .filter(|plan| app.plan_handoff_is_current(plan, request_id))
1773 else {
1774 return Ok(());
1775 };
1776 let _ = crate::tui::plan_handoff::auto_save_plan_if_ready(
1777 &plan.session_id,
1778 AppMode::Plan,
1779 codewhale_engine::core::events::TurnOutcomeStatus::Completed,
1780 Some(&plan.text),
1781 );
1782 if !matches!(&choice, PlanHandoffChoice::Work(_))
1783 && let Err(reason) = rollback_plan_handoff_seed(app, &mut plan).await
1784 {
1785 app.pending_plan_handoff = Some(plan.clone());
1786 reopen_plan_handoff(app, &plan, &reason);
1787 return Ok(());
1788 }
1789 let message = match choice {
1790 PlanHandoffChoice::KeepPlanning => {
1791 app.pending_plan_handoff = None;
1792 return Ok(());
1793 }
1794 PlanHandoffChoice::Revise(feedback) => QueuedMessage::new(feedback, None),
1795 PlanHandoffChoice::Work(posture) => {
1796 if !enter_work_for_plan(app, engine_handle, posture).await {
1797 return Ok(());
1798 }
1799 let staged = seed_plan_handoff_todos(app, &mut plan).await;
1800 app.pending_plan_handoff = Some(plan.clone());
1801 let checkpoint = match staged {
1802 Ok(()) => checkpoint(app).await.map(|_| ()),
1803 Err(reason) => Err(reason),
1804 };
1805 if let Err(reason) = checkpoint {
1806 // Undo our unpublished projection before the event loop can
1807 // retry an ordinary checkpoint. Never roll back other work.
1808 // An already queued write cannot be recalled by this repair.
1809 let reason = match rollback_plan_handoff_seed(app, &mut plan).await {
1810 Ok(()) => reason,
1811 Err(cleanup) => format!("{reason}; {cleanup}"),
1812 };
1813 app.pending_plan_handoff = Some(plan.clone());
1814 apply_mode_update(app, engine_handle, AppMode::Plan).await;
1815 reopen_plan_handoff(app, &plan, &reason);
1816 return Ok(());
1817 }
1818 QueuedMessage::new(plan_handoff_proceed_message(app, &plan), None)
1819 .with_approved_plan(Some(plan.text))
1820 }
1821 };
1822 // Consume before ordinary composer admission. Its existing recovery owns
1823 // the exact user message on an offline/failed send; a repeated answer
1824 // cannot enqueue another execution.
1825 app.pending_plan_handoff = None;
1826 let action = ComposerSubmitAction::Submit(app.decide_submit_disposition());
1827 dispatch_composer_message(
1828 app,
1829 config,
1830 engine_handle,
1831 message,
1832 DispatchRecovery::Immediate,
1833 action,
1834 )
1835 .await
1836 }
1837
1838 /// Leave Plan for Work with the chosen permission. Returns `false`, with the
1839 /// reason on screen, when the permission or the mode could not be applied;
1840 /// the session then stays where it was and nothing is sent.
1841 pub(crate) async fn enter_work_for_plan(
1842 app: &mut App,
1843 engine_handle: &EngineHandle,
1844 posture: ApprovalMode,
1845 ) -> bool {
1846 if engine_handle.tx_op.is_closed() {
1847 return false;
1848 }
1849 if app.agent_approval_baseline() != posture
1850 && let Err(reason) = app.apply_agent_posture(posture)
1851 {
1852 app.push_status_toast(reason, StatusToastLevel::Warning, Some(8_000));
1853 return false;
1854 }
1855 apply_mode_update(app, engine_handle, AppMode::Agent).await;
1856 if engine_handle.tx_op.is_closed() {
1857 app.set_mode(AppMode::Plan);
1858 return false;
1859 }
1860 app.mode == AppMode::Agent
1861 }
1862
1863 pub(crate) async fn build_saved_plan_in_work_mode(
1864 app: &mut App,
1865 config: &Config,
1866 engine_handle: &EngineHandle,
1867 posture: ApprovalMode,
1868 plan_text: String,
1869 ) -> Result<()> {
1870 if plan_text.trim().is_empty() {
1871 return Ok(());
1872 }
1873 if !enter_work_for_plan(app, engine_handle, posture).await {
1874 return Ok(());
1875 }
1876 app.pending_plan_handoff = None;
1877 let proceed = format!("{}\n\n{plan_text}", app.tr(MessageId::PlanHandoffProceed));
1878 let message = QueuedMessage::new(proceed, None).with_approved_plan(Some(plan_text));
1879 let action = ComposerSubmitAction::Submit(app.decide_submit_disposition());
1880 dispatch_composer_message(
1881 app,
1882 config,
1883 engine_handle,
1884 message,
1885 DispatchRecovery::Immediate,
1886 action,
1887 )
1888 .await
1889 }
1890
1891 pub(crate) async fn enable_search_consent(
1892 app: &mut App,
1893 engine_handle: &mut EngineHandle,
1894 config: &mut Config,
1895 request: crate::tui::views::search_consent::SearchConsentRequest,
1896 ) -> bool {
1897 let chosen = request
1898 .chosen_provider()
1899 .and_then(codewhale_runtime::config::SearchProvider::parse)
1900 .filter(|_| engine_handle.approval_is_pending(&request.tool_id));
1901 let mut pin = None;
1902 if let Some(provider) = chosen {
1903 match codewhale_runtime::config_persistence::persist_table_string_key_undoable(
1904 app.config_path.as_deref(),
1905 "search",
1906 "provider",
1907 provider.as_str(),
1908 ) {
1909 Ok((_, undo)) => pin = Some((provider, undo)),
1910 Err(error) => {
1911 app.show_command_result(
1912 app.tr(MessageId::SearchConsentPinFailed)
1913 .replace("{error}", &error.to_string()),
1914 StatusToastLevel::Error,
1915 );
1916 app.view_stack.push(
1917 crate::tui::views::search_consent::SearchConsentView::new(
1918 request,
1919 app.ui_locale,
1920 )
1921 .with_timeout(config.approval_timeout()),
1922 );
1923 return false;
1924 }
1925 }
1926 }
1927 let accepted = apply_approval_decision(
1928 app,
1929 engine_handle,
1930 config,
1931 ApprovalDecisionEvent {
1932 tool_id: request.tool_id,
1933 tool_name: request.tool_name,
1934 decision: ReviewDecision::Approved,
1935 timed_out: false,
1936 approval_key: request.approval_key.clone(),
1937 approval_grouping_key: request.approval_key,
1938 persistent_rules: Vec::new(),
1939 subject: None,
1940 },
1941 )
1942 .await;
1943 if let Some((provider, undo)) = pin {
1944 if accepted {
1945 config.set_search_provider(provider);
1946 } else if let Err(error) = undo.undo() {
1947 tracing::warn!(%error, "could not take back the [search] provider pin");
1948 }
1949 }
1950 accepted
1951 }
1952
1953 pub(crate) async fn handle_view_events(
1954 terminal: &mut AppTerminal,
1955 app: &mut App,
1956 config: &mut Config,
1957 engine_handle: &mut EngineHandle,
1958 events: Vec<ViewEvent>,
1959 ) -> Result<bool> {
1960 for event in events {
1961 match event {
1962 ViewEvent::CommandPaletteSelected { action } => match action {
1963 crate::tui::views::CommandPaletteAction::ExecuteCommand { command } => {
1964 if execute_command_input(terminal, app, engine_handle, config, &command).await?
1965 {
1966 return Ok(true);
1967 }
1968 // A command review confirmed over the Extensions panel
1969 // (the plugin trust digest) closes its pager and lands
1970 // back on the list, which must show the state the
1971 // confirmation just changed.
1972 if app.view_stack.extensions_is_top() {
1973 let snapshot =
1974 crate::tui::views::extensions::ExtensionsSnapshot::from_app(app);
1975 app.view_stack.refresh_extensions(snapshot);
1976 }
1977 }
1978 crate::tui::views::CommandPaletteAction::InsertText { text } => {
1979 app.clear_input_recoverable();
1980 app.line_began_with_slash = text.starts_with('/');
1981 app.input = text;
1982 app.cursor_position = app.input.chars().count();
1983 app.show_command_result(
1984 "Inserted into composer. Finish the input or press Enter.".to_string(),
1985 StatusToastLevel::Info,
1986 );
1987 }
1988 crate::tui::views::CommandPaletteAction::OpenTextPager { title, content } => {
1989 open_text_pager(app, title, content);
1990 }
1991 },
1992 ViewEvent::ExecutePanelCommand { command, .. }
1993 if command.starts_with(crate::tui::plan_artifact::PANEL_COMMAND_PREFIX) =>
1994 {
1995 crate::tui::plan_artifact::handle_panel_command(
1996 terminal,
1997 app,
1998 config,
1999 engine_handle,
2000 &command,
2001 )
2002 .await?;
2003 }
2004 ViewEvent::ExecutePanelCommand {
2005 command,
2006 pager_title,
2007 } => {
2008 // The Extensions panel stays open for this command. Inspect
2009 // rows divert their text output into a pager stacked on the
2010 // panel instead of a transcript dump; mutations keep their
2011 // transcript receipt either way.
2012 let mut result = crate::commands::execute_with_config(&command, app, config);
2013 if let Some(title) = pager_title
2014 && let Some(text) = result.message.take()
2015 {
2016 open_text_pager(app, title, text);
2017 }
2018 if apply_command_result(terminal, app, engine_handle, config, result).await? {
2019 return Ok(true);
2020 }
2021 // The row the user just changed re-reads live state, and so
2022 // does every sibling — a plugin enable, an MCP retry, or an
2023 // install lands on the still-open list instead of leaving it
2024 // stale until reopen.
2025 let snapshot = crate::tui::views::extensions::ExtensionsSnapshot::from_app(app);
2026 app.view_stack.refresh_extensions(snapshot);
2027 }
2028 ViewEvent::RefreshExtensions {
2029 mcp_generation,
2030 mcp_initializing,
2031 } => {
2032 // Bounded poll from the open panel: rebuild only when the
2033 // MCP generation or the initializing flag moved past what
2034 // the panel's snapshot last saw.
2035 if app.view_stack.extensions_is_top()
2036 && (mcp_generation != app.mcp_snapshot_generation
2037 || app.mcp_snapshot_generation_invalidated
2038 || mcp_initializing != app.mcp_initializing)
2039 {
2040 let snapshot = crate::tui::views::extensions::ExtensionsSnapshot::from_app(app);
2041 app.view_stack.refresh_extensions(snapshot);
2042 }
2043 }
2044 ViewEvent::OpenPermissionSettings => {
2045 app.view_stack
2046 .push(ConfigView::open_permission_choices(app));
2047 app.needs_redraw = true;
2048 }
2049 ViewEvent::OpenTextPager { title, content } => {
2050 open_text_pager(app, title, content);
2051 }
2052 ViewEvent::AccountModelSelected {
2053 access,
2054 api_base,
2055 account_id,
2056 expected_revision,
2057 model,
2058 } => {
2059 if app.reject_setting_change_while_busy(MessageId::SettingSubjectProvider) {
2060 continue;
2061 }
2062 begin_first_connection_setup(app);
2063 let profile = app.config_profile.clone();
2064 let config_for_install = config.clone();
2065 let expected_session_id = config
2066 .account_model_access
2067 .read()
2068 .as_ref()
2069 .filter(|existing| existing.expires_at > chrono::Utc::now().timestamp())
2070 .map(|existing| existing.session_id.clone());
2071 let result = tokio::task::spawn_blocking(move || -> Result<()> {
2072 anyhow::ensure!(
2073 api_base
2074 == codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL,
2075 "Account models require the first-party Codewhale endpoint"
2076 );
2077 let client =
2078 codewhale_account_cli::AccountClient::new(profile.as_deref(), None)?;
2079 let status = client.status()?;
2080 anyhow::ensure!(
2081 status.api_base == codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE
2082 && status.revision == expected_revision
2083 && status.account.account_id.as_deref() == Some(account_id.as_str())
2084 && status.account.session_id.as_deref()
2085 == Some(access.session_id.as_str()),
2086 "The signed-in account changed. Reconnect account models"
2087 );
2088 codewhale_app_server::runtime_api::install_account_model_access(
2089 &config_for_install,
2090 profile.as_deref(),
2091 codewhale_app_server::runtime_api::SetAccountModelAccessRequest {
2092 api_base,
2093 session_id: access.session_id,
2094 expected_session_id,
2095 key: access.credential.expose_secret().to_string(),
2096 expires_at: access.expires_at,
2097 },
2098 )
2099 .map_err(|error| anyhow::anyhow!(error.message))?;
2100 Ok(())
2101 })
2102 .await
2103 .map_err(|error| anyhow::anyhow!("{error}"))
2104 .and_then(|result| result);
2105 match result {
2106 Ok(()) => {
2107 let identity = config
2108 .builtin_provider_identity(ProviderKind::Codewhale)
2109 .map_err(anyhow::Error::msg)?;
2110 let switched = Box::pin(switch_provider(
2111 app,
2112 engine_handle,
2113 config,
2114 identity,
2115 Some(model.clone()),
2116 ))
2117 .await;
2118 if switched {
2119 if app.onboarding == OnboardingState::Provider {
2120 complete_provider_picker_onboarding(app, ProviderKind::Codewhale);
2121 if app.onboarding_needs_api_key {
2122 continue;
2123 }
2124 }
2125 app.push_status_toast(
2126 app.tr(MessageId::AccountModelsReady)
2127 .replace("{model}", &model),
2128 StatusToastLevel::Success,
2129 Some(8_000),
2130 );
2131 }
2132 }
2133 Err(error) => app.push_status_toast(
2134 app.tr(MessageId::AccountModelsConnectFailed)
2135 .replace("{error}", &error.to_string()),
2136 StatusToastLevel::Error,
2137 Some(App::STICKY_ERROR_TTL_MS),
2138 ),
2139 }
2140 app.needs_redraw = true;
2141 }
2142 ViewEvent::AccountConnectionChoice { account } => {
2143 if account.is_some() {
2144 begin_first_connection_setup(app);
2145 }
2146 match account {
2147 Some(true) if crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED => app
2148 .view_stack
2149 .push(crate::tui::account_login::AccountLoginView::connect(
2150 app.config_profile.clone(),
2151 app.ui_locale,
2152 )),
2153 Some(_) => Box::pin(open_provider_picker(app, config, engine_handle)).await,
2154 None if app.onboarding == OnboardingState::Provider => {
2155 back_from_provider_onboarding(app)
2156 }
2157 None => {}
2158 }
2159 app.needs_redraw = true;
2160 }
2161 ViewEvent::AccountOperationCompleted {
2162 signing_out,
2163 outcome,
2164 } => {
2165 use crate::tui::account_login::AccountOperationOutcome;
2166 let needs_model = !signing_out
2167 && outcome == AccountOperationOutcome::Complete
2168 && app.onboarding_needs_api_key;
2169 let id = match (signing_out, outcome) {
2170 (true, AccountOperationOutcome::Complete) => MessageId::AccountLogoutSuccess,
2171 (true, AccountOperationOutcome::LocalSignOut) => MessageId::AccountLogoutLocal,
2172 (true, AccountOperationOutcome::Cancelled) => MessageId::AccountLogoutCancelled,
2173 (true, _) => MessageId::AccountLogoutFailed,
2174 (false, AccountOperationOutcome::Complete) if needs_model => {
2175 MessageId::AccountLoginNeedsModel
2176 }
2177 (false, AccountOperationOutcome::Complete) => MessageId::AccountLoginSuccess,
2178 (false, AccountOperationOutcome::Cancelled) => MessageId::AccountLoginCancelled,
2179 (false, AccountOperationOutcome::ModelCancelled) => {
2180 MessageId::AccountModelsCancelled
2181 }
2182 (false, AccountOperationOutcome::Expired) => MessageId::AccountLoginExpired,
2183 (false, AccountOperationOutcome::SignInClosed) => {
2184 MessageId::AccountSignInClosed
2185 }
2186 (false, _) => MessageId::AccountLoginFailed,
2187 };
2188 let level = match outcome {
2189 AccountOperationOutcome::Failed | AccountOperationOutcome::Expired => {
2190 StatusToastLevel::Error
2191 }
2192 AccountOperationOutcome::Complete => StatusToastLevel::Success,
2193 _ => StatusToastLevel::Info,
2194 };
2195 if !signing_out
2196 && matches!(
2197 outcome,
2198 AccountOperationOutcome::Cancelled
2199 | AccountOperationOutcome::ModelCancelled
2200 | AccountOperationOutcome::Expired
2201 | AccountOperationOutcome::Failed
2202 )
2203 && app.onboarding == OnboardingState::Provider
2204 {
2205 app.onboarding_missing_key_recovery = true;
2206 back_from_provider_onboarding(app);
2207 }
2208 let message = app
2209 .tr(id)
2210 .replace("{command}", if signing_out { "/logout" } else { "/login" });
2211 app.push_status_toast(message, level, Some(8_000));
2212 if !signing_out && outcome == AccountOperationOutcome::SignInClosed {
2213 Box::pin(open_provider_picker(app, config, engine_handle)).await;
2214 }
2215 if needs_model {
2216 begin_first_connection_setup(app);
2217 Box::pin(open_model_connection_setup(
2218 app,
2219 config,
2220 engine_handle,
2221 false,
2222 ))
2223 .await;
2224 }
2225 app.needs_redraw = true;
2226 }
2227 ViewEvent::CopyToClipboard { text, label } => {
2228 if text.is_empty() {
2229 app.show_copy_notice(
2230 format!("{label} is empty"),
2231 crate::tui::app::StatusToastLevel::Info,
2232 4_000,
2233 );
2234 } else {
2235 let result = app.clipboard.write_text_status(&text);
2236 crate::tui::mouse_ui::report_copy_result(
2237 app,
2238 result,
2239 format!("{label} copied"),
2240 format!("Copy failed ({label})"),
2241 );
2242 }
2243 }
2244 ViewEvent::ApprovalDecision {
2245 tool_id,
2246 tool_name,
2247 decision,
2248 timed_out,
2249 approval_key,
2250 approval_grouping_key,
2251 persistent_rules,
2252 subject,
2253 } => {
2254 let accepted = apply_approval_decision(
2255 app,
2256 engine_handle,
2257 config,
2258 ApprovalDecisionEvent {
2259 tool_id,
2260 tool_name,
2261 decision,
2262 timed_out,
2263 approval_key,
2264 approval_grouping_key,
2265 persistent_rules,
2266 subject,
2267 },
2268 )
2269 .await;
2270
2271 if timed_out && accepted {
2272 app.add_message(HistoryCell::System {
2273 content: app.tr(MessageId::ApprovalTimedOutDenied).into_owned(),
2274 });
2275 }
2276 }
2277 ViewEvent::SearchConsentEnabled { request } => {
2278 enable_search_consent(app, engine_handle, config, request).await;
2279 }
2280 ViewEvent::ElevationDecision {
2281 tool_id,
2282 tool_name,
2283 option,
2284 } => {
2285 use crate::tui::approval::ElevationOption;
2286 let receipt = match &option {
2287 ElevationOption::Abort => format!("Sandbox elevation aborted for {tool_name}"),
2288 ElevationOption::WithNetwork => {
2289 format!("Retrying {tool_name} with network access enabled")
2290 }
2291 ElevationOption::WithWriteAccess(_) => {
2292 format!("Retrying {tool_name} with write access enabled")
2293 }
2294 ElevationOption::FullAccess => {
2295 format!("Retrying {tool_name} with full access (no sandbox)")
2296 }
2297 };
2298 let result = match option {
2299 ElevationOption::Abort => engine_handle.deny_tool_call(tool_id.clone()).await,
2300 ElevationOption::WithNetwork => {
2301 let policy = option.to_policy(&app.workspace);
2302 engine_handle
2303 .retry_tool_with_policy(tool_id.clone(), policy)
2304 .await
2305 }
2306 ElevationOption::WithWriteAccess(_) => {
2307 let policy = option.to_policy(&app.workspace);
2308 engine_handle
2309 .retry_tool_with_policy(tool_id.clone(), policy)
2310 .await
2311 }
2312 ElevationOption::FullAccess => {
2313 let policy = option.to_policy(&app.workspace);
2314 engine_handle
2315 .retry_tool_with_policy(tool_id.clone(), policy)
2316 .await
2317 }
2318 };
2319 if result.is_ok() {
2320 app.add_message(HistoryCell::System { content: receipt });
2321 note_human_decision_delivered(app, &tool_id);
2322 app.retire_action_notices(Some(&tool_id));
2323 } else if let Err(error) = result {
2324 app.show_command_result(
2325 format!("Approval was not accepted: {error}"),
2326 StatusToastLevel::Error,
2327 );
2328 }
2329 }
2330 ViewEvent::UserInputSubmitted { tool_id, response }
2331 if is_plan_handoff_request(app, &tool_id) =>
2332 {
2333 let choice = crate::tui::plan_handoff::choice(app.ui_locale, &response);
2334 Box::pin(apply_plan_handoff(
2335 app,
2336 config,
2337 engine_handle,
2338 &tool_id,
2339 choice,
2340 ))
2341 .await?;
2342 }
2343 // Esc follows the same owned-seed cleanup as Keep planning.
2344 ViewEvent::UserInputCancelled { tool_id } if is_plan_handoff_request(app, &tool_id) => {
2345 Box::pin(apply_plan_handoff(
2346 app,
2347 config,
2348 engine_handle,
2349 &tool_id,
2350 crate::tui::plan_handoff::PlanHandoffChoice::KeepPlanning,
2351 ))
2352 .await?;
2353 }
2354 ViewEvent::UserInputSubmitted { tool_id, response } => {
2355 let result = engine_handle
2356 .submit_user_input(tool_id.clone(), response)
2357 .await;
2358 apply_user_input_submission_result(app, &tool_id, result);
2359 }
2360 ViewEvent::UserInputCancelled { tool_id } => {
2361 // A cancel is an answer too: when it cannot reach the engine
2362 // the question is still pending there, so reopen it the way a
2363 // failed submit does instead of recording a cancel (U02-04).
2364 let result = engine_handle.cancel_user_input(tool_id.clone()).await;
2365 let delivered = result.is_ok();
2366 apply_user_input_submission_result(app, &tool_id, result);
2367 if delivered {
2368 app.add_message(HistoryCell::System {
2369 content: "User input cancelled".to_string(),
2370 });
2371 }
2372 }
2373 ViewEvent::SessionSelected {
2374 session_id,
2375 workspace,
2376 } => {
2377 let manager = match SessionManager::default_location() {
2378 Ok(manager) => manager,
2379 Err(err) => {
2380 app.show_command_result(
2381 format!("Failed to open sessions directory: {err}"),
2382 StatusToastLevel::Error,
2383 );
2384 continue;
2385 }
2386 };
2387
2388 // Another window's open session is refused, not attached
2389 // as a second autosaving writer.
2390 match manager.attach_session_in_workspace(&session_id, Some(&workspace)) {
2391 Ok((recovery, lease)) => {
2392 let session = recovery.session;
2393 let next_config = config.clone();
2394 let message_count = session.metadata.message_count;
2395 // Keep the saved-store confinement check a pure
2396 // comparison on this runtime (#6522).
2397 codewhale_engine::runtime_threads::prepare_canonical_sessions_root().await;
2398 // Adoption happens inside the load call, as
2399 // preflight. A refusal or a failed open lands in the
2400 // `Err` arm below with the previous session still
2401 // installed and its manager still running, so this
2402 // path must not report success on the way out.
2403 let outcome = match apply_loaded_session_config_snapshot(
2404 app,
2405 config,
2406 session,
2407 next_config,
2408 false,
2409 )
2410 .await
2411 {
2412 Ok(outcome) => {
2413 // Only now does this window give up the
2414 // session it had open; a failed restore
2415 // above keeps that session's lease.
2416 lease.commit();
2417 outcome
2418 }
2419 Err(err) => {
2420 crate::tui::ui::session_state::surface_session_load_failure(
2421 app,
2422 format!("Failed to restore session: {err}"),
2423 );
2424 continue;
2425 }
2426 };
2427 let respawn = outcome.respawn;
2428 sync_runtime_workspace_state(app, app.workspace.clone()).await;
2429 // #6150 audit: these sends may await a full op channel,
2430 // and that await is load-bearing — the session switch
2431 // is already committed UI-side, so each op must land in
2432 // order (drop = engine/UI desync). A wedge is possible
2433 // only while a saturated engine finishes its turn.
2434 if respawn {
2435 replace_tui_engine(app, config, engine_handle).await;
2436 } else {
2437 let _ = engine_handle
2438 .send(Op::SetModel {
2439 model: app.model.clone(),
2440 mode: app.mode,
2441 route_limits: app.active_route_limits,
2442 })
2443 .await;
2444 }
2445 let _ = engine_handle
2446 .send(Op::SyncSession {
2447 expected: None,
2448 control: app.session_sync_control(),
2449 session_id: app.current_session_id.clone(),
2450 messages: app.api_messages.as_ref().clone(),
2451 system_prompt: app.system_prompt.clone(),
2452 system_prompt_override: false,
2453 model: app.model.clone(),
2454 workspace: app.workspace.clone(),
2455 mode: app.mode,
2456 agent_preset: app.agent_preset(),
2457 })
2458 .await;
2459 let _ = engine_handle
2460 .send(Op::SetCompaction {
2461 config: app.compaction_config(),
2462 })
2463 .await;
2464 // Durable receipt, matching `/load`: the status toast
2465 // alone is replaced by the next footer update, leaving
2466 // no findable record that the resume happened.
2467 let loaded_message = format!(
2468 "Session loaded (ID: {}, {} messages)",
2469 codewhale_engine::session_manager::truncate_id(&session_id),
2470 message_count
2471 );
2472 app.add_message(HistoryCell::System {
2473 content: loaded_message.clone(),
2474 });
2475 app.show_command_result(loaded_message, StatusToastLevel::Success);
2476 app.launch.dismiss();
2477 app.launch.status = None;
2478 }
2479 Err(err) => {
2480 crate::tui::ui::session_state::surface_session_load_failure(
2481 app,
2482 format!(
2483 "Failed to load session {}: {err}",
2484 codewhale_engine::session_manager::truncate_id(&session_id)
2485 ),
2486 );
2487 }
2488 }
2489 }
2490 ViewEvent::SessionRenamed { metadata } => {
2491 let session_id = metadata.id.clone();
2492 let title = metadata.title.clone();
2493 let mut work_snapshot_warning = None;
2494 if apply_picker_session_rename_to_active_app(app, *metadata)
2495 && let Ok(manager) = SessionManager::default_location()
2496 {
2497 match build_session_snapshot(app, &manager) {
2498 Ok(session) => {
2499 let projection = saved_work_projection(app, &session);
2500 if let Err(err) = persist_with_pending_work_boundary(
2501 app,
2502 PersistRequest::SessionSnapshot(session),
2503 &projection,
2504 ) {
2505 tracing::warn!(
2506 session_id = %session_id,
2507 error = %err,
2508 "Could not complete active session rename Work boundary"
2509 );
2510 work_snapshot_warning = Some(format!(
2511 "Session renamed, but Work snapshot is pending ({err})"
2512 ));
2513 }
2514 }
2515 Err(err) => {
2516 tracing::warn!(
2517 session_id = %session_id,
2518 error = %err,
2519 "Could not queue active session rename snapshot"
2520 );
2521 }
2522 }
2523 }
2524 let level = if work_snapshot_warning.is_some() {
2525 StatusToastLevel::Warning
2526 } else {
2527 StatusToastLevel::Success
2528 };
2529 app.show_command_result(
2530 work_snapshot_warning.unwrap_or_else(|| {
2531 format!(
2532 "Renamed session {} to \"{}\"",
2533 codewhale_engine::session_manager::truncate_id(&session_id),
2534 title
2535 )
2536 }),
2537 level,
2538 );
2539 }
2540 ViewEvent::SessionArchived { metadata } => {
2541 app.adopt_session_mutation(&metadata);
2542 // The manager already wrote the flag. Keep the active app's
2543 // cached metadata in step so the next autosave carries the new
2544 // state forward instead of reverting it, and drop the rail
2545 // cache so the row disappears (or returns) immediately.
2546 if let Some(cached) = app.current_session_metadata.as_mut()
2547 && cached.id == metadata.id
2548 {
2549 cached.archived = metadata.archived;
2550 }
2551 app.show_command_result(
2552 format!(
2553 "{} session {} ({})",
2554 if metadata.archived {
2555 "Archived"
2556 } else {
2557 "Restored"
2558 },
2559 codewhale_engine::session_manager::truncate_id(&metadata.id),
2560 metadata.title
2561 ),
2562 StatusToastLevel::Success,
2563 );
2564 }
2565 ViewEvent::SessionDeleted { session_id, title } => {
2566 app.show_command_result(
2567 format!(
2568 "Deleted session {} ({})",
2569 codewhale_engine::session_manager::truncate_id(&session_id),
2570 title
2571 ),
2572 StatusToastLevel::Success,
2573 );
2574 }
2575 ViewEvent::ConfigUpdated {
2576 key,
2577 value,
2578 persist,
2579 } => {
2580 if handle_config_updated(terminal, app, config, engine_handle, key, value, persist)
2581 .await?
2582 {
2583 return Ok(true);
2584 }
2585 }
2586 ViewEvent::ThemeSelectionUpdated { theme, persist } => {
2587 if handle_theme_selection_updated(
2588 terminal,
2589 app,
2590 config,
2591 engine_handle,
2592 theme,
2593 persist,
2594 )
2595 .await?
2596 {
2597 return Ok(true);
2598 }
2599 }
2600 ViewEvent::StatusItemsUpdated { items, final_save } => {
2601 // Apply to the live App immediately so the footer reflects
2602 // every keystroke (live preview).
2603 app.status_items = items.clone();
2604 app.needs_redraw = true;
2605 if final_save {
2606 match codewhale_runtime::config_persistence::persist_status_items(&items) {
2607 Ok(path) => {
2608 app.show_command_result(
2609 format!("Status line saved to {}", path.display()),
2610 StatusToastLevel::Success,
2611 );
2612 }
2613 Err(err) => {
2614 app.add_message(HistoryCell::System {
2615 content: format!("Failed to save status line: {err}"),
2616 });
2617 }
2618 }
2619 }
2620 }
2621 ViewEvent::HotbarSetupSaved { bindings } => {
2622 apply_hotbar_setup_saved(app, config, bindings);
2623 }
2624 ViewEvent::SetupStateCommitRequested { state, message } => match state.save() {
2625 Ok(()) => {
2626 app.show_command_result(message, StatusToastLevel::Success);
2627 }
2628 Err(err) => {
2629 app.show_command_result(
2630 format!("Setup state could not be saved: {err}"),
2631 StatusToastLevel::Error,
2632 );
2633 }
2634 },
2635 ViewEvent::SetupConstitutionCommitRequested {
2636 constitution,
2637 state,
2638 message,
2639 } => match crate::tui::setup::persist_user_constitution_choice(&constitution, &state) {
2640 Ok(()) => {
2641 app.show_command_result(message, StatusToastLevel::Success);
2642 }
2643 Err(err) => {
2644 app.show_command_result(
2645 format!("User constitution could not be saved: {err}"),
2646 StatusToastLevel::Error,
2647 );
2648 }
2649 },
2650 ViewEvent::SetupConstitutionModelDraftRequested {
2651 draft,
2652 freeform_note,
2653 locale,
2654 } => {
2655 handle_setup_constitution_model_draft(app, config, draft, freeform_note, locale)
2656 .await;
2657 }
2658 ViewEvent::FleetProfileModelDraftRequested {
2659 role,
2660 model,
2661 provider,
2662 reasoning_effort,
2663 locale,
2664 } => {
2665 handle_fleet_profile_model_draft(
2666 app,
2667 config,
2668 role,
2669 model,
2670 provider,
2671 reasoning_effort,
2672 locale,
2673 )
2674 .await;
2675 }
2676 ViewEvent::FleetRosterOpenCoordinatorRequested => {
2677 app.view_stack.push(
2678 crate::tui::model_picker::ModelPickerView::new(app, config)
2679 .with_assignment_context("Coordinator", "Current session"),
2680 );
2681 }
2682 ViewEvent::FleetProfileRoutePickRequested { editor_id } => {
2683 if app.view_stack.top_kind() == Some(ModalKind::FleetSetup)
2684 && let Some(mut boxed) = app.view_stack.pop()
2685 {
2686 let selection = boxed
2687 .as_any_mut()
2688 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>()
2689 .and_then(|view| {
2690 view.route_selection(editor_id)
2691 .map(|selection| (selection, view.assignment_context()))
2692 });
2693 app.view_stack.push_boxed(boxed);
2694 if let Some((selection, (role, scope))) = selection {
2695 app.view_stack.push(
2696 crate::tui::model_picker::ModelPickerView::new_for_fleet_profile(
2697 app, config, editor_id, selection,
2698 )
2699 .with_assignment_context(role, scope),
2700 );
2701 }
2702 }
2703 }
2704 ViewEvent::FleetProfileRoutePicked {
2705 editor_id,
2706 provider,
2707 provider_id,
2708 model,
2709 reasoning,
2710 } => {
2711 if app.view_stack.top_kind() == Some(ModalKind::FleetSetup)
2712 && let Some(mut boxed) = app.view_stack.pop()
2713 {
2714 if let Some(view) = boxed
2715 .as_any_mut()
2716 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>(
2717 ) {
2718 view.accept_route(
2719 editor_id,
2720 provider_id.unwrap_or_else(|| provider.as_str().into()),
2721 model,
2722 reasoning,
2723 );
2724 }
2725 app.view_stack.push_boxed(boxed);
2726 }
2727 }
2728 ViewEvent::FleetProfileRouteCommitRequested { editor_id } => {
2729 if app.view_stack.top_kind() == Some(ModalKind::FleetSetup)
2730 && let Some(mut boxed) = app.view_stack.pop()
2731 {
2732 let result = boxed
2733 .as_any_mut()
2734 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>()
2735 .map(|view| view.commit_route_assignment(editor_id, app, config));
2736 match result {
2737 Some(Ok(message)) => {
2738 sync_fleet_roster(app, config, engine_handle);
2739 refresh_parked_fleet_roster(app, config);
2740 app.push_status_toast(message, StatusToastLevel::Success, Some(8_000));
2741 }
2742 Some(Err(reason)) => {
2743 app.view_stack.push_boxed(boxed);
2744 app.set_sticky_status(reason, StatusToastLevel::Error, None);
2745 }
2746 None => app.view_stack.push_boxed(boxed),
2747 }
2748 }
2749 }
2750 ViewEvent::FleetAssignmentPickerDismissed { editor_id } => {
2751 dismiss_fleet_assignment(app, editor_id);
2752 refresh_parked_fleet_roster(app, config);
2753 }
2754 ViewEvent::FleetRosterOpenSetupRequested { member_id } => {
2755 // The shared router opens the selected v2 Fleet's exact editor
2756 // (focused on this member) or the legacy wizard when no named
2757 // Fleet is selected.
2758 open_fleet_setup_target(app, config, Some(&member_id)).await;
2759 }
2760 // Enter on a Fleet editor row: the standard `/model` picker opens
2761 // on top of the editor, and its pick comes back below as
2762 // `FleetRoutePicked` to land on the editor still on the stack.
2763 ViewEvent::FleetDetailRoutePickRequested { target, editor_id } => {
2764 let selection = if app.view_stack.top_kind() == Some(ModalKind::FleetDetail)
2765 && let Some(mut editor) = app.view_stack.pop()
2766 {
2767 let selection = editor
2768 .as_any_mut()
2769 .downcast_mut::<crate::tui::views::fleet_detail::FleetDetailView>()
2770 .and_then(|view| {
2771 view.route_selection(editor_id, target)
2772 .map(|selection| (selection, view.assignment_context()))
2773 });
2774 app.view_stack.push_boxed(editor);
2775 selection
2776 } else {
2777 None
2778 };
2779 if let Some((selection, (role, scope))) = selection {
2780 app.view_stack.push(
2781 crate::tui::model_picker::ModelPickerView::new_for_fleet_route(
2782 app, config, target, editor_id, selection,
2783 )
2784 .with_assignment_context(role, scope),
2785 );
2786 }
2787 }
2788 ViewEvent::FleetRoutePicked {
2789 target,
2790 editor_id,
2791 provider,
2792 provider_id,
2793 model,
2794 reasoning,
2795 } => {
2796 let provider_key = provider_id.unwrap_or_else(|| provider.as_str().to_string());
2797 // The picker's `auto` row is "inherit": the Fleet row follows
2798 // the session route again.
2799 let pin = (model != "auto").then_some((provider_key, model));
2800 if let Some((provider_key, _)) = &pin
2801 && let Some(rejection) =
2802 crate::commands::fleet_provider_rejection(app, config, provider_key)
2803 {
2804 // Same gate as `/fleet add` and ⇧F: an unconfigured route
2805 // never enters a team from the picker.
2806 app.set_sticky_status(rejection, StatusToastLevel::Error, None);
2807 } else if app.view_stack.top_kind() == Some(ModalKind::FleetDetail)
2808 && let Some(mut boxed) = app.view_stack.pop()
2809 {
2810 let outcome = boxed
2811 .as_any_mut()
2812 .downcast_mut::<crate::tui::views::fleet_detail::FleetDetailView>()
2813 .map(|view| {
2814 let (provider, model) = match pin {
2815 Some((provider, model)) => (Some(provider), Some(model)),
2816 None => (None, None),
2817 };
2818 view.apply_picked_route(editor_id, target, provider, model, reasoning)
2819 });
2820 app.view_stack.push_boxed(boxed);
2821 match outcome {
2822 Some(Ok(message)) => {
2823 if let Some(mut editor) = app.view_stack.pop() {
2824 let direct = editor.as_any_mut().downcast_mut::<crate::tui::views::fleet_detail::FleetDetailView>()
2825 .is_some_and(|view| view.is_direct_assignment(editor_id));
2826 if !direct {
2827 app.view_stack.push_boxed(editor);
2828 }
2829 }
2830 app.push_status_toast(message, StatusToastLevel::Success, Some(8_000));
2831 sync_fleet_roster(app, config, engine_handle);
2832 refresh_parked_fleet_roster(app, config);
2833 }
2834 Some(Err(reason)) => {
2835 app.set_sticky_status(reason, StatusToastLevel::Error, None);
2836 }
2837 None => {}
2838 }
2839 } else {
2840 app.set_sticky_status(
2841 codewhale_localization::tr(
2842 app.ui_locale,
2843 codewhale_localization::MessageId::FleetRoutePickUnavailable,
2844 )
2845 .into_owned(),
2846 StatusToastLevel::Error,
2847 None,
2848 );
2849 }
2850 app.needs_redraw = true;
2851 }
2852 ViewEvent::FleetStoreChanged { message } => {
2853 app.show_command_result(message, StatusToastLevel::Info);
2854 sync_fleet_roster(app, config, engine_handle);
2855 refresh_parked_fleet_list(app, config).await;
2856 refresh_parked_fleet_roster(app, config);
2857 }
2858 // #5954: the roster emits (rather than emit-and-closes) these, so
2859 // it is still on the stack right underneath. Pushing on top makes
2860 // the three Fleet views one stack: `Esc` pops back to the roster,
2861 // and only closes the window at the root.
2862 ViewEvent::FleetRosterOpenFleetsRequested => {
2863 if app.view_stack.top_kind() != Some(ModalKind::FleetList) {
2864 let over_roster = app.view_stack.top_kind() == Some(ModalKind::FleetRoster);
2865 let mut view =
2866 crate::tui::views::fleet_list::FleetListView::load(app, config).await;
2867 if over_roster {
2868 view = view.over_fleet_roster();
2869 }
2870 app.view_stack.push(view);
2871 }
2872 }
2873 ViewEvent::FleetRosterOpenWorkersRequested => {
2874 if app.view_stack.top_kind() != Some(ModalKind::SubAgents) {
2875 let over_roster = app.view_stack.top_kind() == Some(ModalKind::FleetRoster);
2876 let agents = subagent_view_agents(app, &app.subagent_cache);
2877 let mut view = crate::tui::views::SubAgentsView::for_app(app, agents);
2878 if over_roster {
2879 view = view.over_fleet_roster();
2880 }
2881 app.view_stack.push(view);
2882 }
2883 app.show_command_result(
2884 tr(app.ui_locale, MessageId::SubagentsFetching).to_string(),
2885 StatusToastLevel::Info,
2886 );
2887 let _ = engine_handle.try_send(Op::ListSubAgents);
2888 }
2889 ViewEvent::FleetSetupExternalConsentActivationRequested { provider_id, model } => {
2890 // Validate the selected Fleet route by minting the read-only
2891 // external credential capability only for this exact
2892 // provider/source/path. The check is route-scoped: a cloned
2893 // config has the target provider active so credential discovery
2894 // succeeds, but the parent session provider/model are never
2895 // mutated.
2896 let identity = match config.resolve_provider_selection_identity(&provider_id) {
2897 Ok(identity) => identity,
2898 Err(error) => {
2899 app.set_sticky_status(
2900 format!("Team route activation failed: {error}"),
2901 crate::tui::app::StatusToastLevel::Error,
2902 None,
2903 );
2904 app.needs_redraw = true;
2905 continue;
2906 }
2907 };
2908 let provider_label = identity
2909 .compatibility()
2910 .map_or(identity.key.as_str(), |row| row.label);
2911 let mut scoped = config.clone();
2912 let validation = match scoped.scope_to_provider_identity(&identity) {
2913 Ok(()) => {
2914 match codewhale_engine::route_runtime::resolve_runtime_route_for_identity(
2915 &scoped,
2916 &identity,
2917 Some(&model),
2918 ) {
2919 Ok(route) => route.validate_async().await,
2920 Err(err) => Err(err),
2921 }
2922 }
2923 Err(err) => Err(err),
2924 };
2925 match validation {
2926 Ok(validated) => {
2927 app.provider_health.record_success(
2928 &scoped,
2929 &validated.client.turn_route_receipt(),
2930 &validated.model,
2931 );
2932 app.push_status_toast(
2933 format!(
2934 "{provider_label} route activated for team: {}",
2935 validated.model
2936 ),
2937 crate::tui::app::StatusToastLevel::Success,
2938 Some(5_000),
2939 );
2940 }
2941 Err(error) => {
2942 let envelope = ErrorEnvelope::new(
2943 ErrorCategory::Authentication,
2944 ErrorSeverity::Error,
2945 false,
2946 "route_validation_failed",
2947 &error,
2948 );
2949 if let Some(generation) =
2950 scoped.readonly_health_credential_generation(&identity)
2951 {
2952 app.provider_health.record_models_probe_failure(
2953 &scoped,
2954 &identity,
2955 &model,
2956 generation,
2957 envelope.category,
2958 &envelope.message,
2959 );
2960 }
2961 app.push_status_toast(
2962 format!("{provider_label} route activation failed: {error}"),
2963 crate::tui::app::StatusToastLevel::Error,
2964 None,
2965 );
2966 }
2967 }
2968 // Refresh the Fleet setup view from a snapshot built against the
2969 // updated health state so the activated row becomes Ready
2970 // without closing the modal.
2971 if app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::FleetSetup)
2972 && let Some(view) = app.view_stack.pop()
2973 {
2974 let mut restored = view;
2975 if let Some(fleet_setup) = restored
2976 .as_any_mut()
2977 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>(
2978 ) {
2979 let fresh = crate::tui::views::fleet_setup::FleetSetupSnapshot::from_app(
2980 app, config,
2981 );
2982 fleet_setup.refresh_from_snapshot(fresh);
2983 }
2984 app.view_stack.push_boxed(restored);
2985 }
2986 app.needs_redraw = true;
2987 }
2988 ViewEvent::FleetProfileDraftCommitRequested {
2989 editor_id,
2990 draft,
2991 scope,
2992 expected,
2993 } => {
2994 if app.view_stack.top_kind() != Some(ModalKind::FleetSetup) {
2995 continue;
2996 }
2997 let Some(mut boxed) = app.view_stack.pop() else {
2998 continue;
2999 };
3000 let matches = boxed
3001 .as_any_mut()
3002 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>()
3003 .is_some_and(|view| view.profile_commit_matches(editor_id));
3004 if !matches {
3005 app.view_stack.push_boxed(boxed);
3006 continue;
3007 }
3008 let result = (|| -> Result<(), String> {
3009 // A project-scope save is refused (never silently redirected)
3010 // when project profiles are disabled for this launch: the file
3011 // would be written where nothing loads it.
3012 if scope == codewhale_engine::fleet::profile::FleetProfileScope::Project
3013 && !codewhale_engine::fleet::roster::project_agent_profiles_enabled()
3014 {
3015 return Err(
3016 tr(app.ui_locale, MessageId::FleetDestProjectDisabledSave).into_owned()
3017 );
3018 }
3019 // The TOML is rendered deterministically from the validated
3020 // draft and written atomically; the target path is derived
3021 // from the sanitized id, never model-chosen.
3022 let profile_dir =
3023 match codewhale_engine::fleet::profile::agent_profile_dir_for_scope(
3024 scope,
3025 &app.workspace,
3026 ) {
3027 Ok(dir) => dir,
3028 Err(err) => {
3029 return Err(format!(
3030 "Team {} scope is unavailable: {err:#}",
3031 scope.label()
3032 ));
3033 }
3034 };
3035 let target = profile_dir.join(draft.file_name());
3036 // #4093 AC #5: a profile may only pin a provider the operator
3037 // has actually configured/credentialed. The picker already
3038 // offers models only from configured providers, but a
3039 // model-drafted or hand-edited route (or credentials removed
3040 // after the pick) could still name an unconfigured one — which
3041 // would fail loudly at launch. Catch it at save time with a
3042 // clear message, reusing the SAME predicate the picker uses.
3043 if let Some(provider_id) = draft.provider.as_deref() {
3044 let checked =
3045 config
3046 .resolve_provider_pin_identity(provider_id)
3047 .and_then(|identity| {
3048 let active = app.admitted_provider_identity()?;
3049 if codewhale_engine::provider_readiness::provider_is_configured_for_active(
3050 config, &identity, active,
3051 ) {
3052 Ok(())
3053 } else {
3054 Err(tr(
3055 app.ui_locale,
3056 MessageId::FleetProfileProviderUnconfigured,
3057 )
3058 .replace("{provider}", provider_id)
3059 .replace(
3060 "{env}",
3061 &identity.provider.provider().env_vars().join(" / "),
3062 ))
3063 }
3064 });
3065 checked?;
3066 }
3067 codewhale_engine::fleet::profile::save_agent_profile_document(
3068 scope,
3069 &app.workspace,
3070 &target,
3071 expected.as_deref(),
3072 &draft.id,
3073 &draft.render_toml(),
3074 )
3075 .map_err(|err| {
3076 if let Some(conflict) = err.downcast_ref::<codewhale_engine::fleet::profile::AgentProfileIdentityConflict>() {
3077 tr(app.ui_locale, MessageId::FleetProfileIdConflict)
3078 .replace("{id}", &conflict.id)
3079 .replace("{path}", &conflict.path.display().to_string())
3080 } else if app.ui_locale == codewhale_localization::Locale::ZhHans {
3081 format!("无法保存团队配置:{err:#}")
3082 } else {
3083 format!("Team profile could not be saved: {err:#}")
3084 }
3085 })?;
3086 let roster = std::sync::Arc::new(
3087 codewhale_engine::fleet::identity::load_effective_roster(
3088 &config.fleet_config(),
3089 &app.workspace,
3090 Some(app.extension_plugin_view().as_ref()),
3091 ),
3092 );
3093 let roster_refresh_failed = engine_handle
3094 .try_send(Op::SetFleetRoster { roster })
3095 .is_err();
3096 let zh = app.ui_locale == codewhale_localization::Locale::ZhHans;
3097 app.add_message(HistoryCell::System {
3098 content: if zh {
3099 format!("已保存团队配置:{}", target.display())
3100 } else {
3101 format!("Team {} profile saved: {}", scope.label(), target.display())
3102 },
3103 });
3104 app.show_command_result(if zh && roster_refresh_failed {
3105 format!("团队配置已保存,但无法刷新当前团队名单。请在派发 {} 前重启。", draft.id)
3106 } else if zh {
3107 format!("已保存团队配置:{}", draft.file_name())
3108 } else if roster_refresh_failed {
3109 format!(
3110 "Team {} profile saved, but the live roster could not refresh; restart before dispatching {}",
3111 scope.label(),
3112 draft.id
3113 )
3114 } else {
3115 format!(
3116 "Team {} profile saved: {}",
3117 scope.label(),
3118 draft.file_name()
3119 )
3120 }, if roster_refresh_failed { StatusToastLevel::Warning } else { StatusToastLevel::Success });
3121 Ok(())
3122 })();
3123 if let Err(reason) = result {
3124 if let Some(view) = boxed
3125 .as_any_mut()
3126 .downcast_mut::<crate::tui::views::fleet_setup::FleetSetupView>(
3127 ) {
3128 view.profile_save_failed(reason.clone());
3129 }
3130 app.view_stack.push_boxed(boxed);
3131 app.set_sticky_status(reason, StatusToastLevel::Error, None);
3132 }
3133 app.needs_redraw = true;
3134 }
3135 ViewEvent::SetupRuntimePresetApplyRequested {
3136 preset,
3137 state,
3138 message,
3139 } => {
3140 let applied = match super::apply::validate_setup_runtime_preset(app, config, preset)
3141 {
3142 Ok(()) => {
3143 let config_path = app.config_path.clone();
3144 match tokio::task::spawn_blocking(move || {
3145 super::apply::persist_setup_runtime_preset(config_path, preset, state)
3146 })
3147 .await
3148 {
3149 Ok(Ok(())) => Ok(super::apply::commit_setup_runtime_preset_live_state(
3150 app, config, preset,
3151 )),
3152 Ok(Err(err)) => Err(err),
3153 Err(err) => Err(anyhow::anyhow!(
3154 "runtime preset persistence task failed: {err}"
3155 )),
3156 }
3157 }
3158 Err(err) => Err(err),
3159 };
3160 match applied {
3161 Ok(summary) => {
3162 sync_mode_update(app, engine_handle).await;
3163 app.push_status_toast(
3164 format!("{message} {summary}"),
3165 StatusToastLevel::Success,
3166 None,
3167 );
3168 }
3169 Err(err) => {
3170 app.set_sticky_status(
3171 format!("Runtime preset could not be applied: {err:#}"),
3172 StatusToastLevel::Error,
3173 None,
3174 );
3175 }
3176 }
3177 }
3178 ViewEvent::SetupOpenProviderRequested => {
3179 if app.view_stack.top_kind() != Some(ModalKind::ProviderPicker) {
3180 let runtime_status = query_provider_runtime_status(engine_handle).await;
3181 app.view_stack.push(
3182 crate::tui::provider_picker::ProviderPickerView::new_for_setup(
3183 app.api_provider,
3184 app.admitted_provider_identity()
3185 .ok()
3186 .map(|identity| identity.key.clone()),
3187 config,
3188 runtime_status,
3189 )
3190 .with_locale(app.ui_locale)
3191 .with_provider_health(&app.provider_health),
3192 );
3193 app.show_command_result(
3194 "Provider setup opened from /setup readiness.".to_string(),
3195 StatusToastLevel::Info,
3196 );
3197 }
3198 }
3199 ViewEvent::SetupOpenModelRequested => {
3200 if app.view_stack.top_kind() != Some(ModalKind::ModelPicker) {
3201 match app.admitted_provider_identity().cloned() {
3202 Ok(identity) => {
3203 open_model_picker_for_provider(app, config, &identity);
3204 if app.view_stack.top_kind() == Some(ModalKind::ModelPicker) {
3205 app.show_command_result(
3206 "Model route picker opened from /setup readiness.",
3207 StatusToastLevel::Info,
3208 );
3209 }
3210 }
3211 Err(reason) => app.show_command_result(reason, StatusToastLevel::Error),
3212 }
3213 }
3214 }
3215 ViewEvent::SetupOpenFleetRequested => {
3216 open_fleet_setup_target(app, config, None).await;
3217 }
3218 ViewEvent::SetupOpenHotbarRequested => {
3219 if app.view_stack.top_kind() != Some(ModalKind::HotbarSetup) {
3220 app.view_stack
3221 .push(crate::tui::hotbar::setup::HotbarSetupView::new(app, config));
3222 app.show_command_result(
3223 "Hotbar setup opened from /setup Hotbar readiness.".to_string(),
3224 StatusToastLevel::Info,
3225 );
3226 }
3227 }
3228 ViewEvent::SetupOpenModeRequested => {
3229 if app.view_stack.top_kind() != Some(ModalKind::ModePicker) {
3230 let view =
3231 crate::tui::views::mode_picker::ModePickerView::for_app(app, config).await;
3232 app.view_stack.push(view);
3233 app.show_command_result(
3234 "Work mode picker opened from /setup runtime posture.".to_string(),
3235 StatusToastLevel::Info,
3236 );
3237 }
3238 }
3239 ViewEvent::SetupOpenConfigRequested => {
3240 if app.view_stack.top_kind() != Some(ModalKind::Config) {
3241 app.view_stack.push(ConfigView::new_for_app(app));
3242 app.show_command_result(
3243 "Config view opened from /setup runtime posture.".to_string(),
3244 StatusToastLevel::Info,
3245 );
3246 }
3247 }
3248 ViewEvent::SetupOpenRemoteControlRequested => {
3249 start_remote_control_session(app, config).await;
3250 }
3251 ViewEvent::HotbarDisableRequested => {
3252 disable_hotbar(app, config);
3253 }
3254 ViewEvent::SubAgentsRefresh => {
3255 app.show_command_result(
3256 "Refreshing sub-agents...".to_string(),
3257 StatusToastLevel::Info,
3258 );
3259 // #3802: non-blocking send — refresh op, safe to drop.
3260 let _ = engine_handle.try_send(Op::ListSubAgents);
3261 }
3262 ViewEvent::SidebarAgentCancel { agent_id } => {
3263 app.show_command_result(
3264 format!("Cancelling {agent_id}..."),
3265 StatusToastLevel::Info,
3266 );
3267 // #6150: the input path never awaits a full op channel. The
3268 // cancel is retryable; a rejected send surfaces immediately.
3269 if engine_handle
3270 .try_send(Op::CancelSubAgent {
3271 agent_id: agent_id.clone(),
3272 })
3273 .is_err()
3274 {
3275 app.show_command_result(
3276 format!("Could not cancel {agent_id}"),
3277 StatusToastLevel::Error,
3278 );
3279 }
3280 }
3281 ViewEvent::OpenAgentTranscript { agent_id } => {
3282 open_agent_transcript(app, config, &agent_id);
3283 }
3284 ViewEvent::AgentDetailsClosed { agent_id } => {
3285 crate::tui::work_surface::agent_details_closed(app, &agent_id);
3286 }
3287 ViewEvent::FilePickerSelected { path } => {
3288 // Insert `@<path>` at the composer's cursor with surrounding
3289 // whitespace so the existing `@`-mention parser picks it up.
3290 let cursor = app.cursor_position;
3291 let needs_leading_space = cursor > 0
3292 && !app
3293 .input
3294 .chars()
3295 .nth(cursor.saturating_sub(1))
3296 .is_some_and(|c| c.is_whitespace());
3297 let mut insertion = String::new();
3298 if needs_leading_space {
3299 insertion.push(' ');
3300 }
3301 insertion.push('@');
3302 insertion.push_str(&crate::tui::file_mention::file_mention_body(&path));
3303 insertion.push(' ');
3304 app.insert_str(&insertion);
3305 app.show_input_hint(format!("Attached @{path}"));
3306 }
3307 ViewEvent::ModelPickerApplied {
3308 route_selection,
3309 model,
3310 identity,
3311 effort,
3312 previous_model,
3313 previous_effort,
3314 context_window_override,
3315 save_as_startup_default,
3316 } => {
3317 let was_external = app.external_agent.is_some();
3318 if was_external && (app.is_loading || app.dispatch_in_flight) {
3319 let message = app.tr(MessageId::ExternalAgentSwitchBusy).into_owned();
3320 app.push_status_toast(message, StatusToastLevel::Warning, Some(6_000));
3321 continue;
3322 }
3323 if let (Some(selection), Some(identity)) = (route_selection, identity.as_ref())
3324 && let Err(error) =
3325 codewhale_engine::model_inventory::validate_inventory_selection(
3326 config, identity, &model, &selection,
3327 )
3328 .await
3329 {
3330 app.push_status_toast(error, StatusToastLevel::Error, Some(12_000));
3331 continue;
3332 }
3333 if was_external {
3334 crate::tui::external_agent::clear_external_agent(app);
3335 if !app.history.is_empty() {
3336 app.history.clear();
3337 app.streaming_message_index = None;
3338 app.streaming_thinking_active_entry = None;
3339 app.mark_history_updated();
3340 }
3341 let notice = app
3342 .tr(MessageId::ExternalAgentSessionSwitchedBack)
3343 .replace("{model}", &model);
3344 app.add_message(HistoryCell::System { content: notice });
3345 }
3346 let applied = Box::pin(apply_model_picker_choice(
3347 app,
3348 engine_handle,
3349 config,
3350 model,
3351 identity,
3352 effort,
3353 previous_model,
3354 previous_effort,
3355 save_as_startup_default,
3356 ))
3357 .await;
3358 if applied && let Some(tokens) = context_window_override {
3359 apply_active_model_context_window_override(app, engine_handle, config, tokens)
3360 .await;
3361 }
3362 refresh_parked_fleet_roster(app, config);
3363 }
3364 ViewEvent::ExternalAgentSelected {
3365 agent_id,
3366 agent_name,
3367 } => {
3368 Box::pin(crate::tui::external_agent::switch_to_external_agent(
3369 app, config, agent_id, agent_name,
3370 ))
3371 .await;
3372 }
3373 ViewEvent::ModelPickerDismissed {
3374 catalog_view,
3375 view,
3376 selected_row_id,
3377 } => {
3378 sync_config_provider_from_app(config, app);
3379 app.model_picker_memory = Some(crate::tui::app::ModelPickerMemory {
3380 catalog_view,
3381 view: Some(view),
3382 selected_row_id,
3383 });
3384 refresh_parked_fleet_roster(app, config);
3385 }
3386 ViewEvent::ModelPickerRefresh => {
3387 sync_config_provider_from_app(config, app);
3388 crate::tui::external_agent::start_external_agent_discovery(app);
3389 let refreshed =
3390 tr(app.ui_locale, MessageId::ModelPickerReadinessRefreshed).into_owned();
3391 let notice = Some((refreshed.clone(), StatusToastLevel::Info));
3392 let refreshed_message = if refresh_open_model_picker(app, config, notice) {
3393 refreshed
3394 } else {
3395 tr(app.ui_locale, MessageId::ModelPickerOpenToRefresh).into_owned()
3396 };
3397 app.show_command_result(refreshed_message, StatusToastLevel::Info);
3398 app.needs_redraw = true;
3399 }
3400 ViewEvent::ModelPickerToggleFleet {
3401 provider,
3402 provider_id,
3403 model,
3404 } => {
3405 let provider_key = provider_id.unwrap_or_else(|| provider.as_str().to_string());
3406 toggle_model_picker_fleet(app, config, &provider_key, &model);
3407 }
3408 ViewEvent::ModelPickerTogglePin {
3409 provider,
3410 provider_id,
3411 model,
3412 } => {
3413 let provider_key = provider_id.unwrap_or_else(|| provider.as_str().to_string());
3414 toggle_model_picker_pin(app, config, &provider_key, &model);
3415 }
3416 ViewEvent::ModelPickerMovePin {
3417 provider,
3418 provider_id,
3419 model,
3420 delta,
3421 } => {
3422 let provider_key = provider_id.unwrap_or_else(|| provider.as_str().to_string());
3423 let reordered = codewhale_runtime::settings::Settings::transact_opt(|settings| {
3424 if !settings.move_pinned_model(&provider_key, &model, delta) {
3425 return Ok(None);
3426 }
3427 Ok(Some(settings.pinned_models.clone()))
3428 });
3429 match reordered {
3430 Ok(None) => {}
3431 Ok(Some(pinned_models)) => {
3432 app.pinned_models = pinned_models;
3433 let receipt =
3434 tr(app.ui_locale, MessageId::ModelPickerPinOrderUpdated).into_owned();
3435 app.show_command_result(receipt.clone(), StatusToastLevel::Success);
3436 refresh_open_model_picker(
3437 app,
3438 config,
3439 Some((receipt, StatusToastLevel::Success)),
3440 );
3441 }
3442 Err(error) => {
3443 let receipt = tr(app.ui_locale, MessageId::ModelPickerPinReorderFailed)
3444 .replace("{error}", &error.to_string());
3445 app.show_command_result(receipt.clone(), StatusToastLevel::Error);
3446 refresh_open_model_picker(
3447 app,
3448 config,
3449 Some((receipt, StatusToastLevel::Error)),
3450 );
3451 }
3452 }
3453 app.needs_redraw = true;
3454 }
3455 ViewEvent::ModelPickerNeedsAuth {
3456 identity,
3457 model,
3458 reason,
3459 } => {
3460 app.show_command_result(reason, StatusToastLevel::Warning);
3461 // Close the model picker if it is still open, then hand off to
3462 // the provider auth flow for the locked model's provider.
3463 while app.view_stack.top_kind() == Some(ModalKind::ModelPicker) {
3464 let _ = app.view_stack.pop();
3465 }
3466 if let Some(picker) =
3467 crate::tui::provider_picker::ProviderPickerView::new_for_missing_auth(
3468 app.api_provider,
3469 &identity,
3470 config,
3471 None,
3472 )
3473 {
3474 app.view_stack.push(picker);
3475 } else {
3476 app.show_command_result(
3477 format!(
3478 "🔒 {model} needs {} credentials — open /provider to authenticate.",
3479 identity.key
3480 ),
3481 StatusToastLevel::Warning,
3482 );
3483 }
3484 app.needs_redraw = true;
3485 }
3486 ViewEvent::StatusToast { message, level } => {
3487 apply_status_toast_event(app, message, level);
3488 }
3489 ViewEvent::TopbarRoutePickerRequested => {
3490 Box::pin(open_provider_picker(app, config, engine_handle)).await;
3491 }
3492 ViewEvent::TopbarModelPickerRequested => {
3493 if app.view_stack.top_kind() != Some(ModalKind::ModelPicker) {
3494 crate::tui::external_agent::start_external_agent_discovery(app);
3495 app.view_stack
3496 .push(crate::tui::model_picker::ModelPickerView::new(app, config));
3497 }
3498 }
3499 ViewEvent::ProviderPickerDismissed {
3500 catalog_view,
3501 selected_provider_id,
3502 } => {
3503 let onboarding_provider_picker = app.onboarding == OnboardingState::Provider;
3504 // A picker preview must never become route authority. During
3505 // onboarding Esc is deliberately non-mutating: it returns to
3506 // Language without touching config or the onboarding marker.
3507 if !onboarding_provider_picker {
3508 sync_config_provider_from_app(config, app);
3509 }
3510 app.provider_picker_memory = Some(crate::tui::app::ProviderPickerMemory {
3511 catalog_view,
3512 selected_provider_id,
3513 });
3514 if onboarding_provider_picker {
3515 back_from_provider_onboarding(app);
3516 }
3517 }
3518 ViewEvent::ProviderPickerApplied { identity } => {
3519 let provider = identity.provider;
3520 let model_override = provider_picker_model_override(app, config, &identity);
3521 let switched = Box::pin(switch_provider(
3522 app,
3523 engine_handle,
3524 config,
3525 identity,
3526 model_override,
3527 ))
3528 .await;
3529 if switched && app.onboarding == OnboardingState::Provider {
3530 complete_provider_picker_onboarding(app, provider);
3531 }
3532 refresh_config_view_if_open(app, "provider");
3533 }
3534 ViewEvent::ProviderPickerApiKeySubmitted {
3535 identity,
3536 api_key,
3537 base_url,
3538 } => {
3539 config
3540 .verify_provider_identity(&identity)
3541 .map_err(anyhow::Error::msg)?;
3542 apply_provider_picker_api_key(
3543 app,
3544 engine_handle,
3545 config,
3546 identity,
3547 api_key,
3548 base_url,
3549 )
3550 .await;
3551 refresh_config_view_if_open(app, "provider");
3552 }
3553 ViewEvent::ProviderPickerSetupConfirmed {
3554 identity,
3555 api_key,
3556 model,
3557 context_window,
3558 base_url,
3559 } => {
3560 config
3561 .verify_provider_identity(&identity)
3562 .map_err(anyhow::Error::msg)?;
3563 let provider = identity.provider;
3564 let completed = apply_provider_picker_setup_confirmed(
3565 app,
3566 engine_handle,
3567 config,
3568 identity,
3569 api_key,
3570 model,
3571 context_window,
3572 base_url,
3573 )
3574 .await;
3575 if completed && app.onboarding == OnboardingState::Provider {
3576 complete_provider_picker_onboarding(app, provider);
3577 }
3578 refresh_config_view_if_open(app, "provider");
3579 }
3580 ViewEvent::ProviderPickerCustomProviderSubmitted {
3581 provider_id,
3582 base_url,
3583 model,
3584 api_key_env,
3585 } => {
3586 let switched = apply_provider_picker_custom_provider(
3587 app,
3588 engine_handle,
3589 config,
3590 provider_id,
3591 base_url,
3592 model,
3593 api_key_env,
3594 )
3595 .await;
3596 complete_provider_picker_onboarding_if_switched(
3597 app,
3598 ProviderKind::Custom,
3599 switched,
3600 );
3601 refresh_config_view_if_open(app, "provider");
3602 }
3603 ViewEvent::ProviderPickerXaiOAuthRequested => {
3604 let switched =
3605 run_xai_device_login_from_tui(terminal, app, engine_handle, config).await?;
3606 complete_provider_picker_onboarding_if_switched(app, ProviderKind::Xai, switched);
3607 }
3608 ViewEvent::ProviderPickerChatgptOAuthRequested => {
3609 let switched =
3610 run_chatgpt_pkce_login_from_tui(terminal, app, engine_handle, config).await?;
3611 complete_provider_picker_onboarding_if_switched(
3612 app,
3613 ProviderKind::OpenaiCodex,
3614 switched,
3615 );
3616 }
3617 ViewEvent::ProviderPickerPluginOAuthRequested { provider } => {
3618 run_plugin_oauth_from_tui(terminal, app, config, provider, false).await?;
3619 }
3620 ViewEvent::ProviderPickerOrcarouterOAuthRequested => {
3621 let switched =
3622 run_orcarouter_pkce_login_from_tui(terminal, app, engine_handle, config)
3623 .await?;
3624 complete_provider_picker_onboarding_if_switched(
3625 app,
3626 ProviderKind::Orcarouter,
3627 switched,
3628 );
3629 }
3630 ViewEvent::ProviderPickerExternalConsentConfirmed {
3631 provider,
3632 consent_provider,
3633 source,
3634 path,
3635 } => {
3636 let identity = config
3637 .builtin_provider_identity(provider)
3638 .map_err(anyhow::Error::msg)?;
3639 match persist_external_credential_consent_for_at(
3640 app.config_path.as_deref(),
3641 config,
3642 &identity,
3643 consent_provider,
3644 source,
3645 &path,
3646 ) {
3647 Ok(_) => {
3648 let toast = app
3649 .tr(MessageId::ProviderExternalGrantedToast)
3650 .replace("{owner}", source.owner_label())
3651 .replace("{provider}", provider.as_str());
3652 app.push_status_toast(toast, StatusToastLevel::Success, Some(8_000));
3653 let model_override = provider_picker_model_override(app, config, &identity);
3654 let switched = Box::pin(switch_provider(
3655 app,
3656 engine_handle,
3657 config,
3658 identity,
3659 model_override,
3660 ))
3661 .await;
3662 // #4763: reusing an external CLI grant completes provider
3663 // onboarding exactly like a submitted key or an applied
3664 // route. Without this the picker closes on success and
3665 // the user is returned to the provider step they just
3666 // satisfied — the second half of the reported loop.
3667 if switched && app.onboarding == OnboardingState::Provider {
3668 complete_provider_picker_onboarding(app, provider);
3669 }
3670 refresh_config_view_if_open(app, "provider");
3671 }
3672 Err(error) => app.push_status_toast(
3673 app.tr(MessageId::ProviderExternalSaveFailedToast)
3674 .replace("{error}", &error.to_string()),
3675 StatusToastLevel::Error,
3676 None,
3677 ),
3678 }
3679 }
3680 ViewEvent::ProviderPickerExternalConsentRevoked { provider } => {
3681 let identity = config
3682 .builtin_provider_identity(provider)
3683 .map_err(anyhow::Error::msg)?;
3684 match revoke_external_credential_consent_for_at(
3685 app.config_path.as_deref(),
3686 config,
3687 &identity,
3688 ) {
3689 Ok(_) => app.push_status_toast(
3690 app.tr(MessageId::ProviderExternalRevokedToast)
3691 .replace("{provider}", provider.as_str()),
3692 StatusToastLevel::Success,
3693 Some(5_000),
3694 ),
3695 Err(error) => app.push_status_toast(
3696 app.tr(MessageId::ProviderExternalRevokeFailedToast)
3697 .replace("{error}", &error.to_string()),
3698 StatusToastLevel::Error,
3699 None,
3700 ),
3701 }
3702 refresh_config_view_if_open(app, "provider");
3703 }
3704 ViewEvent::ProviderPickerOpenModels { identity } => {
3705 open_model_picker_for_provider(app, config, &identity);
3706 }
3707 ViewEvent::ProviderPickerTestConnection {
3708 identity,
3709 catalog_view,
3710 } => {
3711 match config.verify_provider_identity(&identity) {
3712 Ok(()) => {
3713 apply_provider_picker_test_connection(
3714 app,
3715 engine_handle,
3716 config,
3717 identity,
3718 catalog_view,
3719 )
3720 .await
3721 }
3722 Err(error) => {
3723 app.push_status_toast(error, StatusToastLevel::Error, Some(8_000))
3724 }
3725 }
3726 refresh_config_view_if_open(app, "provider");
3727 }
3728 ViewEvent::ModeSelected { mode } => {
3729 let prior_mode = app.mode;
3730 let msg = commands::switch_mode(app, mode);
3731 if app.mode != prior_mode {
3732 sync_mode_update(app, engine_handle).await;
3733 }
3734 app.add_message(HistoryCell::System { content: msg });
3735 }
3736 ViewEvent::ConversationModeSelected { id } => {
3737 let content = match crate::tui::conversation_mode::set_in_place(
3738 app,
3739 config,
3740 engine_handle,
3741 &id,
3742 )
3743 .await
3744 {
3745 Ok(message) | Err(message) => message,
3746 };
3747 app.add_message(HistoryCell::System { content });
3748 }
3749 ViewEvent::BacktrackStep { direction } => {
3750 app.backtrack.step(direction);
3751 if let Some(idx) = app.backtrack.selected_idx() {
3752 update_backtrack_overlay_selection(app, idx);
3753 }
3754 }
3755 // Apply the accepted choice now, for keyboard and mouse alike.
3756 // Parking it in pending_launch_action left keyboard confirmation
3757 // waiting for an unrelated mouse event to drain that queue.
3758 ViewEvent::LaunchResumeConfirmed { session_id } => {
3759 let result = resume_launch_session(app, &session_id);
3760 if apply_command_result(terminal, app, engine_handle, config, result).await? {
3761 return Ok(true);
3762 }
3763 app.needs_redraw = true;
3764 }
3765 ViewEvent::BacktrackConfirm => {
3766 let undo = std::mem::take(&mut app.undo_selection);
3767 if let Some(depth) = app.backtrack.confirm() {
3768 if undo {
3769 if let Err(error) = Box::pin(apply_range_undo(
3770 terminal,
3771 app,
3772 engine_handle,
3773 config,
3774 depth,
3775 ))
3776 .await
3777 {
3778 let message = format!("Undo failed: {error:#}");
3779 app.add_message(HistoryCell::System {
3780 content: message.clone(),
3781 });
3782 app.push_status_toast(message, StatusToastLevel::Error, None);
3783 }
3784 app.needs_redraw = true;
3785 continue;
3786 }
3787 match apply_conversation_undo(app, engine_handle, ConversationRewind::Backtrack(depth)).await {
3788 Ok(None) => {}
3789 Ok(Some(error)) => app.push_status_toast(
3790 format!("Conversation rewound, but its save or Work update failed: {error:#}"),
3791 StatusToastLevel::Error,
3792 None,
3793 ),
3794 Err(error) => {
3795 if app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) {
3796 app.view_stack.pop();
3797 }
3798 app.push_status_toast(format!("Backtrack failed: {error:#}"), StatusToastLevel::Error, None);
3799 }
3800 }
3801 }
3802 }
3803 ViewEvent::BacktrackCancel => {
3804 app.undo_selection = false;
3805 app.backtrack.reset();
3806 app.push_status_toast("Backtrack canceled", StatusToastLevel::Warning, Some(5_000));
3807 app.needs_redraw = true;
3808 }
3809 ViewEvent::ContextMenuSelected { action } => {
3810 match apply_context_menu_action(app, action) {
3811 ContextMenuOutcome::Done => {}
3812 ContextMenuOutcome::Events(events) => {
3813 if handle_view_events_boxed(terminal, app, config, engine_handle, events)
3814 .await?
3815 {
3816 return Ok(true);
3817 }
3818 }
3819 ContextMenuOutcome::OpenInEditor { path, line } => {
3820 open_file_in_editor(terminal, app, &path, line);
3821 }
3822 }
3823 }
3824 ViewEvent::OpenContextMenu {
3825 title,
3826 entries,
3827 column,
3828 row,
3829 } => {
3830 push_context_menu(app, entries, column, row, title);
3831 }
3832 ViewEvent::SkillMutationRequested { request } => {
3833 handle_skill_mutation_requested(app, request).await;
3834 }
3835 ViewEvent::SkillsManagerToggleCompatible => {
3836 if app.view_stack.top_kind() == Some(ModalKind::SkillsManager)
3837 && let Some(mut boxed) = app.view_stack.pop()
3838 {
3839 if let Some(view) = boxed
3840 .as_any_mut()
3841 .downcast_mut::<crate::tui::views::skills_manager::SkillsManagerView>(
3842 ) {
3843 crate::tui::views::skills_manager::apply_toggle_compatible(view, app);
3844 }
3845 app.view_stack.push_boxed(boxed);
3846 }
3847 }
3848 }
3849 }
3850
3851 Ok(false)
3852 }
3853
3854 pub(super) fn apply_status_toast_event(app: &mut App, message: String, level: StatusToastLevel) {
3855 app.push_status_toast(message, level, None);
3856 }
3857
3858 /// Keep the very large modal-event dispatcher out of the already-large TUI
3859 /// loop future. Config previews take a dedicated small path: polling the full
3860 /// dispatcher on top of the event loop exceeds the macOS main-thread stack in
3861 /// debug builds before a theme preview can reach its next frame.
3862 #[allow(clippy::too_many_arguments)]
3863 pub(crate) fn handle_view_events_boxed<'a>(
3864 terminal: &'a mut AppTerminal,
3865 app: &'a mut App,
3866 config: &'a mut Config,
3867 engine_handle: &'a mut EngineHandle,
3868 events: Vec<ViewEvent>,
3869 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + 'a>> {
3870 Box::pin(async move {
3871 for event in events {
3872 match event {
3873 ViewEvent::ConfigUpdated {
3874 key,
3875 value,
3876 persist,
3877 } => {
3878 if handle_config_updated(
3879 terminal,
3880 app,
3881 config,
3882 engine_handle,
3883 key,
3884 value,
3885 persist,
3886 )
3887 .await?
3888 {
3889 return Ok(true);
3890 }
3891 }
3892 ViewEvent::ThemeSelectionUpdated { theme, persist } => {
3893 if handle_theme_selection_updated(
3894 terminal,
3895 app,
3896 config,
3897 engine_handle,
3898 theme,
3899 persist,
3900 )
3901 .await?
3902 {
3903 return Ok(true);
3904 }
3905 }
3906 other => {
3907 if Box::pin(handle_view_events(
3908 terminal,
3909 app,
3910 config,
3911 engine_handle,
3912 vec![other],
3913 ))
3914 .await?
3915 {
3916 return Ok(true);
3917 }
3918 }
3919 }
3920 }
3921 Ok(false)
3922 })
3923 }
3924
3925 /// `/agents` → an agent, or "Go to agent" on its card. One agent, one
3926 /// destination: focus the worker so its full transcript owns the main area
3927 /// and the composer addresses its fork; the register modal closes so the
3928 /// focus is visible. A hidden approval card for this agent comes back on top
3929 /// of its transcript so the person can answer it (approvals C1).
3930 pub(super) fn open_agent_transcript(app: &mut App, config: &Config, agent_id: &str) {
3931 if app.view_stack.top_kind() == Some(ModalKind::SubAgents) {
3932 app.view_stack.pop();
3933 }
3934 crate::tui::agent_focus::focus_agent(app, agent_id);
3935 crate::tui::pending_requests::repush_for_agent(
3936 app,
3937 agent_id,
3938 config.approval_default_selection(),
3939 config.approval_timeout(),
3940 );
3941 app.needs_redraw = true;
3942 }
3943
3943 lines RUST