返回 CodeWhale
overlays.rs
根目录 / crates / tui / src / tui / ui / overlays.rs
1 //! Opening, closing, and refreshing the overlay surfaces (pagers, inspectors,
2 //! backtrack, hotbar) layered over the transcript.
3 //!
4 //! Moved verbatim out of `ui.rs`.
5
6 use super::*;
7
8 pub(crate) fn open_setup_checkpoint_if_due(
9 app: &mut App,
10 config: &Config,
11 skip_onboarding: bool,
12 ) -> bool {
13 if skip_onboarding {
14 if crate::tui::setup::should_open_update_checkpoint(app, config)
15 && let Err(err) = crate::tui::setup::defer_update_checkpoint_for_app(app, config)
16 {
17 tracing::warn!(
18 target: "tui::setup",
19 "failed to record deferred setup checkpoint: {err}"
20 );
21 }
22 return false;
23 }
24 if app.onboarding != crate::tui::app::OnboardingState::None
25 || app.view_stack.top_kind() == Some(ModalKind::SetupWizard)
26 || !crate::tui::setup::should_open_update_checkpoint(app, config)
27 {
28 return false;
29 }
30
31 // A fresh wizard invalidates any in-flight model draft from a prior one.
32 let _ = app.next_draft_gen();
33 app.view_stack
34 .push(crate::tui::setup::SetupWizardView::new_checkpoint_for_app(
35 app, config,
36 ));
37 true
38 }
39
40 /// Ctrl+O — the one gesture that selects "explore offline".
41 ///
42 /// A plain letter cannot be used: the provider picker key-entry stage is a
43 /// text field and would swallow it into the draft secret.
44 pub(crate) fn is_explore_offline_shortcut(key: &KeyEvent) -> bool {
45 matches!(key.code, KeyCode::Char('o') | KeyCode::Char('O'))
46 && key.modifiers.contains(KeyModifiers::CONTROL)
47 }
48
49 /// Open the one canonical theme surface (`/theme`) as an ordinary modal.
50 ///
51 /// Onboarding's ready screen exposes this as the optional "customize later"
52 /// secondary action: onboarding is finished first, so the picker is a normal
53 /// modal over the live product. It reuses the same `ThemePickerView`, so the
54 /// preview is live and transactional (Enter persists, Escape reverts) and
55 /// there is no second theme registry.
56 pub(crate) fn open_theme_picker(app: &mut App) {
57 if app.view_stack.top_kind() == Some(ModalKind::ThemePicker) {
58 return;
59 }
60 let original = app.theme_id.name().to_string();
61 app.view_stack
62 .push_boxed(crate::tui::theme_picker::ThemePickerView::boxed(
63 original,
64 app.ui_locale,
65 app.background_color_override,
66 ));
67 app.needs_redraw = true;
68 }
69
70 /// Toggle the one canonical keyboard-oriented Help index.
71 ///
72 /// Launch, onboarding, and the live shell all route here so opening Help from
73 /// a startup row cannot drift into a second catalog or ordering policy.
74 pub(crate) fn toggle_help_view(app: &mut App) {
75 if app.view_stack.top_kind() == Some(ModalKind::Help) {
76 app.view_stack.pop();
77 } else {
78 let help = HelpView::new_for_app(app, true).with_groups_expanded(app.help_expand_groups);
79 app.view_stack.push(help);
80 }
81 app.needs_redraw = true;
82 }
83
84 /// After a shared view closes over the launch screen, bring the launch card
85 /// back: Esc out of the resume picker or the changelog pager returns to the
86 /// card rather than stranding the user on an empty stage. A view that began
87 /// a session (`launch.visible == false`) or a draft in the composer leaves
88 /// the dissolved card alone.
89 pub(crate) fn restore_launch_card_after_view_close(app: &mut App) {
90 if app.launch.visible
91 && app.view_stack.is_empty()
92 && app.launch.dissolve_started_ms.is_some()
93 && app.input.is_empty()
94 {
95 app.launch.restore_card();
96 app.needs_redraw = true;
97 }
98 }
99
100 /// Choose which durable-task summaries should appear in the Work
101 /// sidebar's Tasks panel.
102 ///
103 /// Tasks stamped with the current session owner stay visible on that session's
104 /// live surface. Tasks owned by a different session stay in explicit history
105 /// (`/tasks`) instead of appearing as live workspace work. Legacy unowned
106 /// records fall back to the v0.9.1 timestamp gate: active tasks remain visible,
107 /// while terminal receipts must have both creation and completion times inside
108 /// this TUI session. Durable tasks are stored per user rather than per TUI
109 /// process, and startup recovery can stamp an old running record with a fresh
110 /// `ended_at`. Treating that as a current receipt makes a new same-workspace
111 /// instance look failed (#4416).
112 ///
113 /// A terminal task missing `ended_at` is treated as not current and
114 /// dropped: durable tasks always stamp `ended_at` when they reach a
115 /// terminal state, so absence of it indicates a record from a much
116 /// older schema and isn't worth surfacing.
117 pub(crate) fn select_work_sidebar_tasks(
118 tasks: Vec<TaskSummary>,
119 session_started_at: chrono::DateTime<chrono::Utc>,
120 current_session_id: Option<&str>,
121 ) -> Vec<TaskSummary> {
122 tasks
123 .into_iter()
124 .filter(|task| {
125 let owner_matches_current = current_session_id
126 .zip(task.owner_session_id.as_deref())
127 .is_some_and(|(current, owner)| current == owner);
128 let owned_by_other_session = current_session_id.is_some()
129 && task
130 .owner_session_id
131 .as_deref()
132 .is_some_and(|owner| Some(owner) != current_session_id);
133 if owned_by_other_session {
134 return false;
135 }
136 match task.status {
137 TaskStatus::Queued | TaskStatus::Running => {
138 owner_matches_current || task.owner_session_id.is_none()
139 }
140 TaskStatus::Completed | TaskStatus::Failed | TaskStatus::Canceled => {
141 // A terminal task missing `ended_at` predates the schema
142 // that always stamps it; never surface it as a live
143 // receipt, even when it names this session as owner.
144 if task.ended_at.is_none() {
145 return false;
146 }
147 owner_matches_current
148 || (task.owner_session_id.is_none()
149 && task.created_at >= session_started_at
150 && task
151 .ended_at
152 .is_some_and(|ended_at| ended_at >= session_started_at))
153 }
154 }
155 })
156 .collect()
157 }
158
159 pub(crate) fn toggle_settings_view(app: &mut App) {
160 if app.view_stack.contains_kind(ModalKind::Config) {
161 app.view_stack.pop_through_kind(ModalKind::Config);
162 } else {
163 app.view_stack.push(ConfigView::new_for_app(app));
164 }
165 app.needs_redraw = true;
166 }
167
168 pub(crate) fn clear_work_inspector_after_pager_close(app: &mut App, was_work_inspector: bool) {
169 if was_work_inspector && app.view_stack.top_kind() != Some(ModalKind::Pager) {
170 app.work_surface.opened = None;
171 }
172 }
173
174 pub(crate) fn hotbar_slot_from_key(app: &App, key: &event::KeyEvent) -> Option<u8> {
175 let KeyCode::Char(c) = key.code else {
176 return None;
177 };
178 if !('1'..='8').contains(&c) {
179 return None;
180 }
181 let slot = c.to_digit(10).and_then(|digit| u8::try_from(digit).ok())?;
182
183 if key.modifiers.contains(KeyModifiers::ALT)
184 && !key.modifiers.contains(KeyModifiers::CONTROL)
185 && !key.modifiers.contains(KeyModifiers::SUPER)
186 {
187 if app.onboarding != OnboardingState::None
188 || !app.view_stack.is_empty()
189 || app.is_history_search_active()
190 || !visible_slash_menu_entries(app, SLASH_MENU_LIMIT).is_empty()
191 {
192 return None;
193 }
194
195 return Some(slot);
196 }
197
198 None
199 }
200
201 pub(crate) async fn cycle_permission_posture(
202 app: &mut App,
203 config: &mut Config,
204 engine_handle: &EngineHandle,
205 ) {
206 let control = config.approval_policy_control(
207 app.config_path.as_deref(),
208 app.config_profile.as_deref(),
209 &app.workspace,
210 );
211 let root_control = control == codewhale_runtime::config::ApprovalPolicyControl::RootConfig;
212 let step = app.step_permission_dial(root_control);
213 if step.posture_changed && root_control {
214 config.approval_policy = None;
215 }
216 if step.changed() {
217 sync_mode_update(app, engine_handle).await;
218 refresh_config_view_if_open(app, "permission_posture");
219 }
220 }
221
222 /// Open the one canonical provider setup surface for onboarding. Fresh
223 /// onboarding opens on the full provider catalog, hosted providers included
224 /// (#5563). Local runtimes are always listed, as not checked until one answers
225 /// the startup probe; during onboarding, `L` filters to them only after a local
226 /// runtime is detected. Missing-key
227 /// recovery instead focuses the already-configured route so an exact Kimi
228 /// Code K3 configuration can expose its plan route before a secret is entered.
229 /// Either way the picker opens on the navigable list (#4763): onboarding never
230 /// drops a user straight into a key/OAuth prompt for a route they were not
231 /// shown.
232 pub(crate) async fn open_model_connection_setup(
233 app: &mut App,
234 config: &Config,
235 engine_handle: &EngineHandle,
236 recover_configured_route: bool,
237 ) {
238 if recover_configured_route {
239 open_onboarding_provider_picker(app, config, engine_handle, true).await;
240 } else if !crate::tui::account_login::ACCOUNT_SIGN_IN_ENABLED {
241 open_provider_picker(app, config, engine_handle).await;
242 } else if app.view_stack.is_empty() {
243 app.view_stack
244 .push(crate::tui::account_login::ConnectionSetupView::new(
245 app.ui_locale,
246 ));
247 app.needs_redraw = true;
248 }
249 }
250
251 pub(crate) async fn open_onboarding_provider_picker(
252 app: &mut App,
253 config: &Config,
254 engine_handle: &EngineHandle,
255 recover_configured_route: bool,
256 ) {
257 if app.onboarding != OnboardingState::Provider
258 || app.view_stack.top_kind() == Some(ModalKind::ProviderPicker)
259 {
260 return;
261 }
262 let runtime_status = query_provider_runtime_status(engine_handle).await;
263 app.view_stack.push(
264 crate::tui::provider_picker::ProviderPickerView::new_for_onboarding(
265 app.api_provider,
266 recover_configured_route.then(|| app.onboarding_provider.as_str().into()),
267 config,
268 runtime_status,
269 )
270 .with_locale(app.ui_locale)
271 .with_local_runtime_detected(app.local_runtime_detected)
272 .with_provider_health(&app.provider_health),
273 );
274 app.needs_redraw = true;
275 }
276
277 /// Open the existing provider picker from the post-onboarding launch screen.
278 ///
279 /// The launch row contributes only a `ProviderSetupIntent`; provider catalog,
280 /// health, selection memory, and apply semantics remain owned by
281 /// `ProviderPickerView` and the normal provider event handlers.
282 pub(crate) async fn open_launch_provider_picker(
283 app: &mut App,
284 config: &Config,
285 engine_handle: &EngineHandle,
286 ) {
287 if app.view_stack.top_kind() == Some(ModalKind::ProviderPicker) {
288 return;
289 }
290 let runtime_status = query_provider_runtime_status(engine_handle).await;
291 app.view_stack.push(
292 crate::tui::provider_picker::ProviderPickerView::new_with_runtime_status_and_memory(
293 app.api_provider,
294 config,
295 runtime_status,
296 app.provider_picker_memory.as_ref(),
297 )
298 .with_locale(app.ui_locale)
299 .with_provider_health(&app.provider_health),
300 );
301 app.needs_redraw = true;
302 }
303
304 /// Open the existing provider/route surface from any shell entry point.
305 ///
306 /// The chrome and `/provider` command both delegate here, so they expose the
307 /// same picker without duplicating catalog or runtime-readiness facts. A
308 /// picker preview remains non-authoritative until its normal apply handler
309 /// commits a route.
310 pub(crate) async fn open_provider_picker(
311 app: &mut App,
312 config: &Config,
313 engine_handle: &EngineHandle,
314 ) {
315 if app.onboarding == OnboardingState::Provider {
316 let recover_configured_route = app.onboarding_recovers_configured_route();
317 open_onboarding_provider_picker(app, config, engine_handle, recover_configured_route).await;
318 } else {
319 open_launch_provider_picker(app, config, engine_handle).await;
320 }
321 }
322
323 pub(crate) fn open_text_pager(app: &mut App, title: String, content: String) {
324 let width = app
325 .viewport
326 .last_transcript_area
327 .map(|area| area.width)
328 .unwrap_or(80);
329 app.view_stack.push(PagerView::from_text(
330 title,
331 &content,
332 width.saturating_sub(2),
333 ));
334 }
335
336 /// Open a unified diff in a pager, rendered like an edit in the transcript.
337 pub(crate) fn open_diff_pager(app: &mut App, title: String, diff: &str) {
338 let width = app
339 .viewport
340 .last_transcript_area
341 .map(|area| area.width)
342 .unwrap_or(80);
343 // A patch is file content. Keep the terminal-injection boundary
344 // `PagerView::from_text` applies to every other pager body.
345 let mut sanitized = String::with_capacity(diff.len());
346 codewhale_sanitize::sanitize::strip_ansi_into(diff, &mut sanitized);
347 app.view_stack.push(PagerView::from_diff(
348 title,
349 sanitized,
350 width.saturating_sub(2),
351 ));
352 }
353
354 pub(crate) fn open_context_inspector(app: &mut App) {
355 app.view_stack.push(ContextInspectorView::new(app));
356 }
357
358 pub(crate) fn open_external_url(url: &str) -> Result<()> {
359 codewhale_runtime::browser::open_url(url)
360 }
361
362 /// Pull the latest snapshot of cells / revisions / render options into the
363 /// live transcript overlay sitting on top of the view stack. No-op if the
364 /// top view isn't a `LiveTranscriptOverlay`.
365 pub(crate) fn refresh_live_transcript_overlay(app: &mut App) {
366 // Pop+push lets us hold &mut to the overlay while also borrowing `app`
367 // mutably for the snapshot — direct re-borrow through `view_stack`
368 // would otherwise alias `app`.
369 let Some(mut overlay) = app.view_stack.pop() else {
370 return;
371 };
372 if let Some(typed) = overlay.as_any_mut().downcast_mut::<LiveTranscriptOverlay>() {
373 typed.refresh_from_app(app);
374 }
375 app.view_stack.push_boxed(overlay);
376 }
377
378 pub(crate) fn refresh_context_inspector_overlay(app: &mut App) {
379 let Some(mut overlay) = app.view_stack.pop() else {
380 return;
381 };
382 if let Some(typed) = overlay.as_any_mut().downcast_mut::<ContextInspectorView>() {
383 typed.refresh_from_app(app);
384 }
385 app.view_stack.push_boxed(overlay);
386 }
387
388 /// Open the live transcript overlay in backtrack-preview mode (#133).
389 /// The overlay starts highlighting the most recent user message
390 /// (`selected_idx = 0`) and routes Left/Right/Enter/Esc through
391 /// `ViewEvent::Backtrack*` so the main key dispatcher can advance the
392 /// `BacktrackState` and apply the rewind on confirm.
393 pub(crate) fn open_backtrack_overlay(app: &mut App) {
394 open_history_rewind_overlay(app, false);
395 }
396
397 pub(crate) fn open_undo_overlay(app: &mut App) {
398 open_history_rewind_overlay(app, true);
399 }
400
401 fn open_history_rewind_overlay(app: &mut App, undo: bool) {
402 app.undo_selection = undo;
403 let mut overlay = LiveTranscriptOverlay::new();
404 overlay.refresh_from_app(app);
405 overlay.set_backtrack_preview(0);
406 if undo {
407 overlay.set_undo_selection();
408 }
409 app.view_stack.push(overlay);
410 app.show_command_result(if undo {
411 "Undo selection: ←/→ choose first request to undo Enter restore files and conversation Esc cancel".to_string()
412 } else {
413 "Backtrack: ←/→ step Enter rewind Esc cancel".to_string()
414 }, StatusToastLevel::Info);
415 app.needs_redraw = true;
416 }
417
418 /// Open a fresh live transcript overlay in sticky-tail mode.
419 pub(crate) fn open_live_transcript_overlay(app: &mut App) {
420 if app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) {
421 return;
422 }
423 let mut overlay = LiveTranscriptOverlay::new();
424 overlay.refresh_from_app(app);
425 app.view_stack.push(overlay);
426 app.show_command_result(
427 "Live transcript: tailing (Esc to close)".to_string(),
428 StatusToastLevel::Info,
429 );
430 app.needs_redraw = true;
431 }
432
433 /// Toggle the live transcript overlay on `Ctrl+Shift+T`. Closes the overlay if it's
434 /// already on top; otherwise uses the same open path as `/transcript`.
435 pub(crate) fn toggle_live_transcript_overlay(app: &mut App) {
436 if app.view_stack.top_kind() == Some(ModalKind::LiveTranscript) {
437 app.view_stack.pop();
438 app.needs_redraw = true;
439 return;
440 }
441 open_live_transcript_overlay(app);
442 }
443
444 /// Open the `/model` picker pre-filtered to `provider` (#3083). The model
445 /// picker's search already scopes rows by provider display name, so we reuse
446 /// the standard "open model picker" path and seed its query by replaying the
447 /// provider's display name as character input through the public view-stack
448 /// key path — no model-picker internals are touched.
449 pub(crate) fn open_model_picker_for_provider(
450 app: &mut App,
451 config: &Config,
452 identity: &codewhale_runtime::config::ProviderIdentity,
453 ) {
454 if let Err(reason) = config.verify_provider_identity(identity) {
455 app.push_status_toast(reason, StatusToastLevel::Error, Some(8_000));
456 return;
457 }
458 if app.view_stack.top_kind() != Some(ModalKind::ModelPicker) {
459 app.view_stack
460 .push(crate::tui::model_picker::ModelPickerView::new(app, config));
461 }
462 for ch in identity.key.as_str().chars() {
463 // Char input updates the query and never emits a ViewEvent, so the
464 // returned (empty) event list is safe to drop.
465 let _ = app.view_stack.handle_key(crossterm::event::KeyEvent::new(
466 KeyCode::Char(ch),
467 KeyModifiers::NONE,
468 ));
469 }
470 app.needs_redraw = true;
471 }
472
473 /// Hide the Hotbar: persist `hotbar = []` (the canonical "disabled" state) and
474 /// clear the live in-memory slots so the panel disappears immediately. The
475 /// explicit empty array — not a missing key — is what disables defaults, so we
476 /// store `Some(vec![])` rather than `None`.
477 pub(crate) fn disable_hotbar(app: &mut App, config: &mut Config) {
478 match codewhale_runtime::config_persistence::persist_hotbar_bindings(
479 app.config_path.as_deref(),
480 &[],
481 ) {
482 Ok(path) => {
483 config.hotbar = Some(Vec::new());
484 app.show_owned_command_result(
485 StatusToastKind::HotbarSettings,
486 format!(
487 "Hotbar hidden (hotbar = [] in {}). Bring it back with `/hotbar on`.",
488 path.display()
489 ),
490 StatusToastLevel::Success,
491 );
492 }
493 Err(err) => {
494 app.show_owned_command_result(
495 StatusToastKind::HotbarSettings,
496 format!("Failed to hide Hotbar: {err}"),
497 StatusToastLevel::Error,
498 );
499 app.add_message(HistoryCell::System {
500 content: format!("Failed to hide Hotbar: {err}"),
501 });
502 }
503 }
504 app.needs_redraw = true;
505 }
506
507 pub(crate) fn refresh_config_view_if_open(app: &mut App, focus_key: &str) {
508 refresh_config_view_after_commit(app, focus_key, false);
509 }
510
511 /// Rebuild an open settings view from disk truth after a commit. When the host
512 /// rejected the value, the editor reopens with what the user typed.
513 pub(crate) fn refresh_config_view_after_commit(app: &mut App, focus_key: &str, rejected: bool) {
514 if app.view_stack.top_kind() != Some(ModalKind::Config) {
515 return;
516 }
517 let Some(mut boxed) = app.view_stack.pop() else {
518 return;
519 };
520 let rebuilt = match boxed.as_any_mut().downcast_ref::<ConfigView>() {
521 Some(previous) => {
522 let mut view = ConfigView::rebuild_preserving(app, previous, focus_key);
523 if rejected {
524 view.restore_rejected_commit(previous);
525 }
526 view
527 }
528 // Not a `ConfigView`: rebuild from scratch rather than restoring an
529 // unknown modal, matching how the stack got here.
530 None => {
531 let mut fresh = ConfigView::new_for_app(app);
532 fresh.focus_key(focus_key);
533 fresh
534 }
535 };
536 app.view_stack.push(rebuilt);
537 }
538
539 pub(crate) fn refresh_skills_manager_if_open(
540 app: &mut App,
541 status: Option<String>,
542 focus: Option<&codewhale_skills::audit::AuditedSkillId>,
543 ) {
544 if app.view_stack.top_kind() != Some(ModalKind::SkillsManager) {
545 return;
546 }
547 let Some(mut boxed) = app.view_stack.pop() else {
548 return;
549 };
550 let rebuilt = if let Some(prev) = boxed
551 .as_any_mut()
552 .downcast_mut::<crate::tui::views::skills_manager::SkillsManagerView>(
553 ) {
554 crate::tui::views::skills_manager::SkillsManagerView::rebuild_preserving(
555 app, prev, status, focus,
556 )
557 } else {
558 crate::tui::views::skills_manager::SkillsManagerView::new(app)
559 };
560 app.view_stack.push(rebuilt);
561 }
562
563 #[allow(clippy::too_many_arguments)]
564 pub(crate) fn push_approval_request_view(
565 app: &mut App,
566 id: &str,
567 tool_name: &str,
568 description: &str,
569 tool_input: &serde_json::Value,
570 approval_key: &str,
571 approval_grouping_key: &str,
572 intent_summary: Option<&str>,
573 default_selection: codewhale_runtime::config::ApprovalDefaultSelection,
574 timeout: Option<std::time::Duration>,
575 ) {
576 let mut request = ApprovalRequest::new_with_intent(
577 id,
578 tool_name,
579 description,
580 tool_input,
581 approval_key,
582 intent_summary,
583 &app.workspace,
584 );
585 // The engine owns the grant scope: a child's grouping key is prefixed
586 // with its agent so "allow for this conversation" never covers the
587 // parent or a sibling (C3). Keep the card's own key only when the
588 // event carries none.
589 if !approval_grouping_key.is_empty() {
590 request.approval_grouping_key = approval_grouping_key.to_string();
591 }
592 // A child's gate never consults saved repo allow rules, so a child card
593 // must not offer "Always for this command" — it would do nothing. The
594 // card names its agent (approvals C1).
595 if codewhale_engine::tools::subagent::SubAgentManager::is_child_approval_id(id) {
596 request.persistent_allow_rules.clear();
597 if let Some(agent_id) = crate::tui::pending_requests::child_agent_id(id) {
598 request.owner = Some(crate::tui::pending_requests::owner_for(app, agent_id));
599 }
600 } else if !request.is_repo_law_prompt() {
601 // The same edit runs without a card inside a git repository. Say why
602 // this folder asks, so two folders behaving differently is explained
603 // on the card. The engine already decided to ask; this only labels it.
604 request.asks_without_git = codewhale_engine::core::authority::file_write_asks_without_git(
605 app.mode,
606 app.approval_mode,
607 &app.workspace,
608 tool_name,
609 tool_input,
610 );
611 }
612 app.view_stack.push(
613 ApprovalView::new_with_default_selection(request, app.ui_locale, default_selection)
614 .with_timeout(timeout),
615 );
616 }
617
618 /// Push the new `selected_idx` into the live transcript overlay so the
619 /// highlight follows the user's Left/Right input. No-op if the overlay is
620 /// no longer on top (e.g. it was closed underneath us).
621 pub(crate) fn update_backtrack_overlay_selection(app: &mut App, selected_idx: usize) {
622 if app.view_stack.top_kind() != Some(ModalKind::LiveTranscript) {
623 return;
624 }
625 let Some(mut overlay) = app.view_stack.pop() else {
626 return;
627 };
628 if let Some(typed) = overlay.as_any_mut().downcast_mut::<LiveTranscriptOverlay>() {
629 typed.set_backtrack_preview(selected_idx);
630 }
631 app.view_stack.push_boxed(overlay);
632 app.needs_redraw = true;
633 }
634
635 pub(crate) fn backtrack_api_cut_index(app: &App, depth: usize) -> Option<usize> {
636 let selected = find_user_cell_index_from_tail(app, depth)?;
637 let HistoryCell::User { content: target } = &app.history[selected] else {
638 return None;
639 };
640 let same_prompt =
641 |cell: &HistoryCell| matches!(cell, HistoryCell::User { content } if content == target);
642 let earlier = app.history[..selected]
643 .iter()
644 .filter(|cell| same_prompt(cell))
645 .count();
646 let later = app.history[selected + 1..]
647 .iter()
648 .filter(|cell| same_prompt(cell))
649 .count();
650 let mut recorded = app.api_messages.iter().enumerate().filter(|(_, message)| {
651 !matches!(
652 codewhale_models::turn_classify::classify_user_turn_prompt(message),
653 codewhale_models::turn_classify::UserTurnPromptKind::NotPrompt
654 ) && history_cells_from_message(message).iter().any(same_prompt)
655 });
656 let (cut, _) = recorded.nth(earlier)?;
657 (recorded.count() == later).then_some(cut)
658 }
659
660 pub(crate) fn jump_to_adjacent_tool_cell(app: &mut App, direction: SearchDirection) -> bool {
661 let line_meta = app.viewport.transcript_cache.line_meta();
662 if line_meta.is_empty() {
663 return false;
664 }
665
666 let top = app
667 .viewport
668 .last_transcript_top
669 .min(line_meta.len().saturating_sub(1));
670 let current_cell = line_meta
671 .get(top)
672 .and_then(codewhale_tui_kit::scrolling::TranscriptLineMeta::cell_line)
673 .map(|(cell_index, _)| app.original_cell_index_for_rendered(cell_index));
674
675 let mut scan_indices = Vec::new();
676 match direction {
677 SearchDirection::Forward => {
678 scan_indices.extend((top.saturating_add(1))..line_meta.len());
679 }
680 SearchDirection::Backward => {
681 scan_indices.extend((0..top).rev());
682 }
683 }
684
685 for idx in scan_indices {
686 let Some((cell_index, _)) = line_meta[idx].cell_line() else {
687 continue;
688 };
689 let cell_index = app.original_cell_index_for_rendered(cell_index);
690 if current_cell.is_some_and(|current| current == cell_index) {
691 continue;
692 }
693 if !matches!(app.history.get(cell_index), Some(HistoryCell::Tool(_))) {
694 continue;
695 }
696 if let Some(anchor) = TranscriptScroll::anchor_for(line_meta, idx) {
697 app.viewport.transcript_scroll = anchor;
698 app.viewport.pending_scroll_delta = 0;
699 app.needs_redraw = true;
700 return true;
701 }
702 }
703
704 false
705 }
706
707 pub(crate) fn open_pager_for_selection(app: &mut App) -> bool {
708 let Some(text) = selection_to_text(app) else {
709 return false;
710 };
711 let width = app
712 .viewport
713 .last_transcript_area
714 .map(|area| area.width)
715 .unwrap_or(80);
716 let pager = PagerView::from_text("Selection", &text, width.saturating_sub(2));
717 app.view_stack.push(pager);
718 true
719 }
720
721 pub(crate) fn open_pager_for_last_message(app: &mut App) -> bool {
722 let Some(cell) = app.history.last() else {
723 return false;
724 };
725 let width = app
726 .viewport
727 .last_transcript_area
728 .map(|area| area.width)
729 .unwrap_or(80);
730 let text = if matches!(cell, HistoryCell::Tool(_)) {
731 crate::tui::history::text::history_cell_to_clipboard_text(cell, width)
732 } else {
733 history_cell_to_text(cell, width)
734 };
735 let mut pager = PagerView::from_text("Message", &text, width.saturating_sub(2));
736 // When the last message is a completed assistant answer, expose the
737 // clean answer-only payload via `a` (copy answer) — the rendered body
738 // that `c`/`y` copies still carries the glyph/label line.
739 if let Some(answer) = completed_assistant_answer_text(cell, width) {
740 pager = pager.with_copy_answer(answer);
741 }
742 app.view_stack.push(pager);
743 true
744 }
745
746 /// Compatibility wrapper for tests that exercise Ctrl+O on a thinking cell.
747 /// The user-facing Ctrl+O surface is now the turn-scoped Reasoning Detail
748 /// pager (#v092-reasoning-fix).
749 #[cfg(test)]
750 pub(crate) fn open_thinking_pager(app: &mut App) -> bool {
751 open_reasoning_detail_pager(app)
752 }
753
753 lines RUST