返回 CodeWhale
mouse_ui.rs
根目录 / crates / tui / src / tui / mouse_ui.rs
1 use std::time::{Duration, Instant};
2
3 /// Timing trace of the last left-click in the composer. crossterm never
4 /// decodes click counts, so double/triple-click detection keeps the prior
5 /// click's time and position; a fast click within the slop window increments
6 /// the count, anything else resets it.
7 #[derive(Debug, Clone, Copy)]
8 pub(crate) struct ComposerClickTrace {
9 at: Instant,
10 column: u16,
11 row: u16,
12 count: u8,
13 }
14
15 /// Two clicks closer than this are one double-click (composer word select,
16 /// and the context menu's guard against confirming a destructive row).
17 pub(crate) const DOUBLE_CLICK_MS: u64 = 400;
18 const COMPOSER_CLICK_SLOP_CELLS: u16 = 1;
19
20 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
21 pub(crate) enum ComposerClickGesture {
22 Caret,
23 Word,
24 Line,
25 }
26
27 fn classify_composer_click(
28 trace: &mut Option<ComposerClickTrace>,
29 column: u16,
30 row: u16,
31 ) -> ComposerClickGesture {
32 let at = Instant::now();
33 let next = match trace.as_ref() {
34 Some(prev)
35 if at.duration_since(prev.at).as_millis() <= u128::from(DOUBLE_CLICK_MS)
36 && prev.row.abs_diff(row) <= COMPOSER_CLICK_SLOP_CELLS
37 && prev.column.abs_diff(column) <= COMPOSER_CLICK_SLOP_CELLS =>
38 {
39 ComposerClickTrace {
40 at,
41 column,
42 row,
43 count: prev.count.saturating_add(1),
44 }
45 }
46 _ => ComposerClickTrace {
47 at,
48 column,
49 row,
50 count: 1,
51 },
52 };
53 let count = next.count;
54 *trace = Some(next);
55 match count {
56 2 => ComposerClickGesture::Word,
57 n if n >= 3 => ComposerClickGesture::Line,
58 _ => ComposerClickGesture::Caret,
59 }
60 }
61
62 /// Char-index bounds of the word (or CJK run) containing char `pos`.
63 ///
64 /// Takes and returns char indices, the unit of `App::cursor_position` and
65 /// `App::selection_anchor`, so a multi-byte composer never mixes the two.
66 fn composer_word_bounds(text: &str, pos: usize) -> (usize, usize) {
67 let chars: Vec<char> = text.chars().collect();
68 if chars.is_empty() {
69 return (0, 0);
70 }
71 let is_word = |ch: char| ch.is_alphanumeric() || (ch as u32) >= 0x80;
72 let idx = pos.min(chars.len() - 1);
73 if !is_word(chars[idx]) {
74 return (idx, idx + 1);
75 }
76 let mut start = idx;
77 while start > 0 && is_word(chars[start - 1]) {
78 start -= 1;
79 }
80 let mut end = idx + 1;
81 while end < chars.len() && is_word(chars[end]) {
82 end += 1;
83 }
84 (start, end)
85 }
86
87 /// Char-index bounds of the logical line containing char `pos` (excluding
88 /// the newline).
89 fn composer_line_bounds(text: &str, pos: usize) -> (usize, usize) {
90 let chars: Vec<char> = text.chars().collect();
91 let pos = pos.min(chars.len());
92 let start = chars[..pos]
93 .iter()
94 .rposition(|&ch| ch == '\n')
95 .map_or(0, |i| i + 1);
96 let end = chars[pos..]
97 .iter()
98 .position(|&ch| ch == '\n')
99 .map_or(chars.len(), |offset| pos + offset);
100 (start, end)
101 }
102
103 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
104 use ratatui::layout::Rect;
105
106 use crate::tui::app::{App, SidebarRowAction, StatusToastLevel};
107 use crate::tui::command_palette::{
108 CommandPaletteView, build_entries_with_plugins as build_command_palette_entries,
109 };
110 use crate::tui::context_menu::{ContextMenuEntry, ContextMenuView};
111 use crate::tui::history::text::{history_cell_to_clipboard_text, history_cell_to_text};
112 use crate::tui::selection::{SelectionAutoscroll, TranscriptSelectionPoint};
113 use crate::tui::tideline::InteractionAction;
114 use crate::tui::views::{ContextMenuAction, HelpView, ModalKind, ViewEvent};
115 use codewhale_localization::{MessageId, tr};
116 use codewhale_models::{ContentBlock, Message};
117 use codewhale_tui_kit::scrolling::{ScrollDirection, TranscriptScroll};
118 use codewhale_tui_kit::ui_text::{
119 line_to_plain, slice_visible_columns, text_display_width, text_visible_width,
120 truncate_line_to_width,
121 };
122
123 // These functions will need to be imported from ui.rs or we can just import crate::tui::ui::*.
124 use crate::tui::ui::{
125 copy_cell_to_clipboard, detail_target_label, open_context_inspector,
126 open_details_pager_for_cell, open_pager_for_selection,
127 };
128
129 const COMPOSER_MOUSE_SCROLL_LINES: usize = 3;
130
131 pub(crate) fn should_drop_loading_mouse_motion(app: &App, mouse: MouseEvent) -> bool {
132 if !app.is_loading {
133 return false;
134 }
135
136 match mouse.kind {
137 // v0.9.1: keep a cheap hover hit-test alive while streaming. Motion
138 // events are no longer dropped wholesale — the frame limiter bounds
139 // redraw cost. Only expensive transcript reflow stays deferred.
140 MouseEventKind::Moved => false,
141 MouseEventKind::Drag(_) => {
142 // Divider drags must stay live during active turns — dropping
143 // these events wedges the resize state mid-drag (#3063).
144 !app.viewport.transcript_selection.dragging
145 && !app.viewport.transcript_scrollbar_dragging
146 && !app.work_surface.is_resizing()
147 }
148 _ => false,
149 }
150 }
151
152 fn toggle_tool_run_expand(app: &mut App, mouse: MouseEvent) -> bool {
153 if !app.tool_collapse_active() {
154 return false;
155 }
156 let Some(rendered_idx) = transcript_cell_index_from_mouse(app, mouse) else {
157 return false;
158 };
159 let original_idx = app.original_cell_index_for_rendered(rendered_idx);
160 if !app.transcript_fold_header_at(original_idx) {
161 return false;
162 }
163 app.toggle_tool_run_expansion_at(original_idx)
164 }
165
166 /// Map a mouse (column, row) within the composer area to a char index
167 /// in the composer input string. Uses the canonical prompt-adjusted text rect
168 /// for coordinate mapping, and accounts for vertical padding and scroll offset.
169 fn mouse_pos_to_char_index(app: &App, col: u16, row: u16, text_area: Rect) -> Option<usize> {
170 Some(codewhale_ratatui::native_composer_source_at(
171 &app.input,
172 usize::from(text_area.width.max(1)),
173 usize::from(col.saturating_sub(text_area.x)),
174 usize::from(row.saturating_sub(text_area.y)),
175 app.viewport.last_composer_scroll_offset,
176 app.viewport.last_composer_top_padding,
177 ))
178 }
179
180 /// Wheel dispatch stays with the existing editor; row projection is shared
181 /// with painting and caret geometry, preserving its scalar-column policy.
182 fn move_composer_cursor_by_wrapped_rows(app: &mut App, text_area: Rect, rows: isize) -> bool {
183 let Some(cursor) = codewhale_ratatui::native_composer_step_row(
184 &app.input,
185 app.cursor_position,
186 usize::from(text_area.width.max(1)),
187 rows,
188 codewhale_ratatui::NativeComposerRowColumn::SourceScalars,
189 ) else {
190 return false;
191 };
192 app.clear_selection();
193 app.cursor_position = cursor;
194 app.needs_redraw = true;
195 true
196 }
197
198 /// A click on the workbar opens `/workflows`, the view that lists every run
199 /// with its agents and cancels one.
200 fn handle_workbar_mouse(app: &mut App, mouse: MouseEvent) -> bool {
201 if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left))
202 || !mouse_hits_rect(mouse, app.viewport.last_workbar_area)
203 || app.workflow_runs.is_empty()
204 {
205 return false;
206 }
207 crate::tui::views::workflows_manager::open(app);
208 true
209 }
210
211 fn handle_plugin_cta_mouse(app: &mut App, mouse: MouseEvent) -> Option<Vec<ViewEvent>> {
212 if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
213 return None;
214 }
215 if !mouse_hits_rect(mouse, app.viewport.last_plugin_cta_area) {
216 return None;
217 }
218 if mouse_hits_rect(mouse, app.viewport.last_plugin_cta_dismiss_area) {
219 // "Don't suggest again": the explicit, persisted dismissal.
220 let _ = app.dismiss_plugin_cta();
221 return Some(Vec::new());
222 }
223 // Only the labelled Review button opens the existing inventory. A click
224 // elsewhere is consumed; no suggested command or mutation is dispatched.
225 if mouse_hits_rect(mouse, app.viewport.last_plugin_cta_review_area)
226 && let Some(tab) = app.accept_plugin_cta_review()
227 && app.view_stack.top_kind() != Some(crate::tui::views::ModalKind::Extensions)
228 {
229 app.view_stack
230 .push(crate::tui::views::extensions::ExtensionsView::new(app, tab));
231 }
232 Some(Vec::new())
233 }
234
235 /// Slash-autocomplete rows painted inside the composer. Click selects
236 /// (second click on the same row applies, matching the command palette);
237 /// wheel moves the highlight. Returns true when the event was consumed so
238 /// the composer caret / draft-scroll path does not also handle it.
239 fn handle_slash_autocomplete_mouse(app: &mut App, mouse: MouseEvent) -> bool {
240 let hitboxes = app.viewport.last_slash_menu_hitboxes.borrow();
241 if hitboxes.is_empty() {
242 return false;
243 }
244 let over_row = hitboxes
245 .iter()
246 .find_map(|(idx, rect)| mouse_hits_rect(mouse, Some(*rect)).then_some(*idx));
247 let over_menu = over_row.is_some()
248 || hitboxes.iter().any(|(_, rect)| {
249 mouse.row >= rect.y
250 && mouse.row < rect.y.saturating_add(rect.height)
251 && mouse.column >= rect.x
252 && mouse.column < rect.x.saturating_add(rect.width)
253 });
254 // Wheel over any painted slash row moves selection (mouse == keys).
255 // Clicks only fire when the pointer is on a row rect.
256 match mouse.kind {
257 MouseEventKind::ScrollUp if over_menu => {
258 drop(hitboxes);
259 let entries = crate::tui::slash_menu::visible_slash_menu_entries(app, 128);
260 if entries.is_empty() {
261 return false;
262 }
263 crate::tui::composer_ui::select_previous_slash_menu_entry(app, entries.len());
264 app.needs_redraw = true;
265 true
266 }
267 MouseEventKind::ScrollDown if over_menu => {
268 drop(hitboxes);
269 let entries = crate::tui::slash_menu::visible_slash_menu_entries(app, 128);
270 if entries.is_empty() {
271 return false;
272 }
273 crate::tui::composer_ui::select_next_slash_menu_entry(app, entries.len());
274 app.needs_redraw = true;
275 true
276 }
277 MouseEventKind::Down(MouseButton::Left) => {
278 let Some(idx) = over_row else {
279 return false;
280 };
281 drop(hitboxes);
282 let entries = crate::tui::slash_menu::visible_slash_menu_entries(app, 128);
283 if entries.is_empty() || idx >= entries.len() {
284 return false;
285 }
286 // Same as command palette: click the highlighted row to apply;
287 // click another row to move the highlight (mouse == keys).
288 if app.slash_menu_selected == idx {
289 let _ = crate::tui::slash_menu::apply_slash_menu_selection(app, &entries, true);
290 } else {
291 app.slash_menu_selected = idx;
292 app.slash_menu_hidden = false;
293 }
294 app.needs_redraw = true;
295 true
296 }
297 _ => false,
298 }
299 }
300
301 /// Handle mouse events within the composer area.
302 /// Returns true if the event was consumed.
303 pub(crate) fn handle_composer_mouse(app: &mut App, mouse: MouseEvent, now: Instant) -> bool {
304 if !app.view_stack.is_empty() {
305 return false;
306 }
307 // A transcript selection or scrollbar drag that ends over the composer
308 // belongs to the surface that started it: the transcript handler must
309 // still see the release to clear its drag state and publish the text.
310 if matches!(
311 mouse.kind,
312 MouseEventKind::Drag(MouseButton::Left) | MouseEventKind::Up(MouseButton::Left)
313 ) && (app.viewport.transcript_selection.dragging
314 || app.viewport.transcript_scrollbar_dragging)
315 {
316 return false;
317 }
318 // Use outer area for hit-testing (includes border).
319 let Some(area) = app.viewport.last_composer_area else {
320 return false;
321 };
322 if mouse.column < area.x
323 || mouse.column >= area.x + area.width
324 || mouse.row < area.y
325 || mouse.row >= area.y + area.height
326 {
327 return false;
328 }
329 // Slash autocomplete owns its painted rows before caret placement or
330 // draft scroll — otherwise a click on `/model` would only move the caret.
331 if handle_slash_autocomplete_mouse(app, mouse) {
332 return true;
333 }
334 // Resolve the border- and submit-aware input plane through the same
335 // persistent prompt geometry used by rendering, cursor placement, and
336 // viewport bookkeeping. The frame records it after reserving `[↵]`.
337 let input_plane = app.viewport.last_composer_content.unwrap_or(area);
338 let text_area =
339 crate::tui::widgets::composer_content_geometry(input_plane, app.is_history_search_active())
340 .text_area;
341
342 match mouse.kind {
343 // Only claim the wheel while the caret still has somewhere to go. At
344 // the top or bottom of the draft — or with no wrapped draft at all —
345 // fall through so the transcript scrolls instead of the event being
346 // silently swallowed by the composer rect (#5223).
347 MouseEventKind::ScrollUp => move_composer_cursor_by_wrapped_rows(
348 app,
349 text_area,
350 -(COMPOSER_MOUSE_SCROLL_LINES as isize),
351 ),
352 MouseEventKind::ScrollDown => move_composer_cursor_by_wrapped_rows(
353 app,
354 text_area,
355 COMPOSER_MOUSE_SCROLL_LINES as isize,
356 ),
357 MouseEventKind::Down(MouseButton::Left) => {
358 clear_transcript_selection(app);
359 crate::tui::work_surface::release_focus(app);
360 if let Some(submit) = crate::tui::widgets::active_composer_submit_rect(app, area)
361 && mouse_hits_rect(mouse, Some(submit))
362 {
363 // Same chord the keyboard Enter path uses. Empty / paste-burst
364 // clicks are consumed so they cannot also move the caret.
365 let action =
366 app.decide_composer_submit(crate::tui::app::ComposerSubmitChord::Enter);
367 if !matches!(action, crate::tui::app::ComposerSubmitAction::Noop)
368 && (app.composer_enter_would_submit(true, now)
369 || matches!(action, crate::tui::app::ComposerSubmitAction::SendQueuedNow))
370 {
371 app.pending_composer_submit = Some(crate::tui::app::ComposerSubmitChord::Enter);
372 }
373 app.needs_redraw = true;
374 return true;
375 }
376 if let Some(pos) = mouse_pos_to_char_index(app, mouse.column, mouse.row, text_area) {
377 match classify_composer_click(
378 &mut app.viewport.composer_click_trace,
379 mouse.column,
380 mouse.row,
381 ) {
382 ComposerClickGesture::Word => {
383 let (start, end) = composer_word_bounds(&app.input, pos);
384 app.selection_anchor = Some(start);
385 app.cursor_position = end;
386 }
387 ComposerClickGesture::Line => {
388 let (start, end) = composer_line_bounds(&app.input, pos);
389 app.selection_anchor = Some(start);
390 app.cursor_position = end;
391 }
392 ComposerClickGesture::Caret => {
393 app.cursor_position = pos;
394 app.selection_anchor = None;
395 }
396 }
397 app.needs_redraw = true;
398 }
399 true
400 }
401 MouseEventKind::Drag(MouseButton::Left) => {
402 if let Some(pos) = mouse_pos_to_char_index(app, mouse.column, mouse.row, text_area) {
403 if app.selection_anchor.is_none() {
404 app.selection_anchor = Some(app.cursor_position);
405 }
406 app.cursor_position = pos;
407 app.needs_redraw = true;
408 }
409 true
410 }
411 MouseEventKind::Up(MouseButton::Left) => {
412 if app.selection_anchor == Some(app.cursor_position) {
413 app.selection_anchor = None;
414 }
415 true
416 }
417 MouseEventKind::Down(MouseButton::Middle) if app.clipboard.uses_primary_selection() => {
418 if let Some(text) = app.clipboard.read_primary_text() {
419 // Flush already-typed bytes at their original caret first.
420 app.insert_paste_text("");
421 let Some(position) =
422 mouse_pos_to_char_index(app, mouse.column, mouse.row, text_area)
423 else {
424 return true;
425 };
426 // PRIMARY often contains this very selection. Insert at the
427 // pointer, preserving the selected original rather than cutting it.
428 crate::tui::work_surface::release_focus(app);
429 crate::tui::paste::handle_paste(
430 app,
431 crate::tui::paste::PasteSource::Primary {
432 text: &text,
433 position,
434 },
435 );
436 }
437 true
438 }
439 _ => false,
440 }
441 }
442
443 pub(crate) fn handle_mouse_event(app: &mut App, mouse: MouseEvent, now: Instant) -> Vec<ViewEvent> {
444 if app.view_stack.top_kind() == Some(ModalKind::ContextMenu) {
445 if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Right)) {
446 app.view_stack.pop();
447 // A menu opened over a modal (the Extensions row menu) hands the
448 // new right-click back to that modal, not to the transcript.
449 if !app.view_stack.is_empty() {
450 app.needs_redraw = true;
451 return app.view_stack.handle_mouse(mouse);
452 }
453 open_context_menu(app, mouse);
454 return Vec::new();
455 }
456 return app.view_stack.handle_mouse(mouse);
457 }
458
459 // Decision prompts leave transcript evidence visible above them. A question
460 // sheet owns the wheel over its content; approval cards retain their existing
461 // transcript-scroll behavior. Visible side surfaces keep their ownership.
462 // Other modals still own wheel input exclusively (#4371, #6045).
463 if matches!(
464 app.view_stack.top_kind(),
465 Some(ModalKind::Approval | ModalKind::UserInput)
466 ) {
467 let over_prompt = mouse_hits_rect(mouse, app.viewport.last_prompt_area);
468 let over_side_surface = mouse_hits_rect(mouse, app.work_surface.last_area);
469 let direction = match mouse.kind {
470 MouseEventKind::ScrollUp => Some(ScrollDirection::Up),
471 MouseEventKind::ScrollDown => Some(ScrollDirection::Down),
472 _ => None,
473 };
474 if let Some(direction) = direction {
475 if over_prompt && app.view_stack.top_kind() == Some(ModalKind::UserInput) {
476 app.needs_redraw = true;
477 return app.view_stack.handle_mouse(mouse);
478 }
479 if over_prompt || !over_side_surface {
480 scroll_transcript_with_mouse(app, direction);
481 }
482 return Vec::new();
483 }
484 }
485
486 if !app.view_stack.is_empty() {
487 app.needs_redraw = true;
488 return app.view_stack.handle_mouse(mouse);
489 }
490
491 if crate::tui::pet_watch::main_view(app) {
492 if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left))
493 && mouse_hits_rect(mouse, app.pet_watch.inspect_area)
494 {
495 crate::tui::pet_watch::open_habitat(app);
496 return Vec::new();
497 }
498 if mouse_hits_rect(mouse, app.pet_watch.area) {
499 crate::tui::pet_watch::command(app, crate::tui::pet_watch::Control::Mouse(mouse));
500 return Vec::new();
501 }
502 }
503
504 // A drag can finish outside the composer/transcript that started it.
505 // Publish once before other visible surfaces consume the release event.
506 if matches!(mouse.kind, MouseEventKind::Up(MouseButton::Left))
507 && app.clipboard.uses_primary_selection()
508 {
509 let text = if app.viewport.transcript_selection.dragging {
510 selection_to_text(app).unwrap_or_default()
511 } else {
512 app.selected_text()
513 };
514 if let Err(error) = app.clipboard.write_primary_text(&text) {
515 tracing::debug!(%error, "primary selection write failed");
516 }
517 }
518
519 // Topbar facts are typed controls, not decorative text. Route this before
520 // either launch or session content so a segment painted in the one shared
521 // header has identical mouse behavior in both shell states.
522 if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
523 let action = app
524 .viewport
525 .interaction_targets
526 .target_at(mouse.column, mouse.row)
527 .and_then(|target| target.mouse_action);
528 if let Some(action) = action
529 && !matches!(
530 action,
531 InteractionAction::ShowDockPanel(_) | InteractionAction::DismissDock
532 )
533 {
534 app.needs_redraw = true;
535 return match action {
536 InteractionAction::InspectContext => {
537 open_context_inspector(app);
538 Vec::new()
539 }
540 InteractionAction::OpenProviderPicker => {
541 vec![ViewEvent::TopbarRoutePickerRequested]
542 }
543 InteractionAction::OpenAutomations => apply_sidebar_row_action(
544 app,
545 SidebarRowAction::Command("/automation".to_string()),
546 ),
547 InteractionAction::OpenModelPicker => {
548 vec![ViewEvent::TopbarModelPickerRequested]
549 }
550 InteractionAction::OpenUpdate => {
551 apply_sidebar_row_action(app, SidebarRowAction::Command("/update".to_string()))
552 }
553 InteractionAction::ShowDockPanel(_) | InteractionAction::DismissDock => {
554 unreachable!("dock targets defer to the strip")
555 }
556 };
557 }
558 }
559
560 // The launch card is content on the ordinary screen, not a surface that
561 // owns the frame. It used to consume every mouse event and return, which
562 // was right when it *was* a separate surface and became a bug the moment
563 // it stopped being one: scrolling, the real composer, the work surface
564 // and every other target were unreachable while it was up, and the
565 // send-glyph branch pointed at a `send_area` the deleted launch composer
566 // used to set. So the card takes its own rows and lets everything else
567 // fall through to the handlers that own it.
568 if app.launch.visible && !app.launch.row_hitboxes.is_empty() {
569 let hit = app
570 .launch
571 .row_hitboxes
572 .iter()
573 .position(|(_, area)| mouse_hits_rect(mouse, Some(*area)));
574 match mouse.kind {
575 MouseEventKind::Moved => {
576 if hit != app.launch.hovered_row {
577 app.launch.hovered_row = hit;
578 app.needs_redraw = true;
579 }
580 }
581 MouseEventKind::Down(MouseButton::Left) => {
582 if let Some(index) = hit {
583 let id = app.launch.row_hitboxes[index].0.clone();
584 match &id {
585 // Resuming replaces the whole session context —
586 // founder live-test: "you just click it and boom
587 // you're there ... you don't realize it's happening".
588 // It asks first. New session and See all stay one
589 // click, because neither discards anything.
590 crate::tui::app::LaunchRowId::Recent(session_id) => {
591 app.launch.menu_selected = Some(index);
592 crate::tui::underwater::open_launch_resume_confirm(app, session_id);
593 }
594 _ => {
595 app.launch.status = None;
596 app.pending_launch_action =
597 Some(crate::tui::underwater::launch_row_click_action(&id));
598 }
599 }
600 app.needs_redraw = true;
601 return Vec::new();
602 }
603 }
604 _ => {}
605 }
606 }
607
608 // Ocean work surface owns its rect, scrolling, focus, and row actions.
609 // Route it before workflow/composer/transcript so wheel events never leak
610 // into an unrelated viewport.
611 let work_surface = crate::tui::work_surface::handle_mouse(app, mouse);
612 if let Some(action) = work_surface.action {
613 return apply_sidebar_row_action(app, action);
614 }
615 if work_surface.consumed {
616 return Vec::new();
617 }
618 // The posture bar's live counts open the dock view they count. The
619 // strip's own tabs were consumed above; anything left carrying a dock
620 // action is a footer chip.
621 if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left))
622 && let Some(InteractionAction::ShowDockPanel(panel)) = app
623 .viewport
624 .interaction_targets
625 .target_at(mouse.column, mouse.row)
626 .and_then(|target| target.mouse_action)
627 {
628 crate::tui::work_surface::select_dock_panel(app, panel);
629 return Vec::new();
630 }
631
632 if handle_workbar_mouse(app, mouse) {
633 return Vec::new();
634 }
635
636 if let Some(events) = handle_plugin_cta_mouse(app, mouse) {
637 return events;
638 }
639
640 // Composer mouse events take priority over transcript.
641 if handle_composer_mouse(app, mouse, now) {
642 return Vec::new();
643 }
644
645 match mouse.kind {
646 MouseEventKind::Moved => {
647 // Update last mouse position for tooltip rendering + hover layer.
648 app.last_mouse_pos = Some((mouse.column, mouse.row));
649 let previous_hover = crate::tui::hover_layer::current_hover();
650 crate::tui::hover_layer::set_pointer(mouse.column, mouse.row);
651 crate::tui::hover_layer::resolve_hover();
652 if crate::tui::hover_layer::current_hover() != previous_hover {
653 app.needs_redraw = true;
654 }
655
656 // Check sidebar sections for hover popovers. Only surface a
657 // popover when the hovered row lost information in the compact
658 // sidebar view.
659 let mut found = false;
660 for section in &app.sidebar_hover.sections {
661 if mouse.column >= section.content_area.x
662 && mouse.column
663 < section
664 .content_area
665 .x
666 .saturating_add(section.content_area.width)
667 && mouse.row >= section.content_area.y
668 && mouse.row
669 < section
670 .content_area
671 .y
672 .saturating_add(section.content_area.height)
673 {
674 if let Some(row) = section.rows.iter().find(|row| row.row_y == mouse.row) {
675 let desired = row.is_truncated.then(|| {
676 if let Some(detail) = row.detail.as_deref()
677 && !detail.trim().is_empty()
678 {
679 format!("{}\n{detail}", row.full_text)
680 } else {
681 row.full_text.clone()
682 }
683 });
684 if app.sidebar_hover_tooltip != desired {
685 app.sidebar_hover_tooltip = desired;
686 app.needs_redraw = true;
687 }
688 found = true;
689 break;
690 } else if section.rows.is_empty() {
691 let line_idx = (mouse.row.saturating_sub(section.content_area.y)) as usize;
692 if let Some(full) = section.lines.get(line_idx) {
693 let truncated =
694 text_display_width(full) > section.content_area.width as usize;
695 let desired = truncated.then(|| full.clone());
696 if app.sidebar_hover_tooltip != desired {
697 app.sidebar_hover_tooltip = desired;
698 app.needs_redraw = true;
699 }
700 found = true;
701 break;
702 }
703 }
704 }
705 }
706 if !found && app.sidebar_hover_tooltip.is_some() {
707 app.sidebar_hover_tooltip = None;
708 app.needs_redraw = true;
709 }
710 }
711 MouseEventKind::ScrollUp => {
712 scroll_transcript_with_mouse(app, ScrollDirection::Up);
713 }
714 MouseEventKind::ScrollDown => {
715 scroll_transcript_with_mouse(app, ScrollDirection::Down);
716 }
717 MouseEventKind::Down(MouseButton::Left) => {
718 app.viewport.transcript_scrollbar_dragging = false;
719 app.viewport.selection_autoscroll = None;
720
721 // #3028/#4009: Check sidebar hover state for clickable rows before
722 // falling through to transcript selection. Command rows still use
723 // the command-palette pipeline; agent rows are direct UI actions.
724 if let Some(action) = sidebar_click_action(app, mouse) {
725 return apply_sidebar_row_action(app, action);
726 }
727
728 // Click on the transcript scrollbar gutter starts a scrollbar
729 // drag so the visible thumb remains interactive for users who
730 // prefer mouse-based navigation.
731 if mouse_hits_transcript_scrollbar(app, mouse) {
732 app.viewport.transcript_scrollbar_dragging = true;
733 return Vec::new();
734 }
735
736 if mouse_hits_rect(mouse, app.viewport.jump_to_latest_button_area) {
737 app.scroll_to_bottom();
738 return Vec::new();
739 }
740
741 // The pinned prompt header names the user message scrolled just
742 // above the viewport; a click returns to it. Resolve the message
743 // against the current layout so a rewrite between paint and click
744 // cannot jump to a stale line offset.
745 if mouse_hits_rect(mouse, app.viewport.pinned_prompt_area) {
746 if let Some(line) = app.pinned_prompt_target_line() {
747 app.scroll_to_transcript_line(line);
748 }
749 return Vec::new();
750 }
751
752 if toggle_tool_run_expand(app, mouse) {
753 return Vec::new();
754 }
755
756 if let Some(point) = selection_point_from_mouse(app, mouse) {
757 let gesture = classify_composer_click(
758 &mut app.viewport.transcript_click_trace,
759 mouse.column,
760 mouse.row,
761 );
762 match gesture {
763 ComposerClickGesture::Word => {
764 if let Some((start_col, end_col)) = transcript_double_click_span(app, point)
765 {
766 app.viewport.transcript_selection.anchor =
767 Some(crate::tui::selection::TranscriptSelectionPoint {
768 line_index: point.line_index,
769 column: start_col,
770 });
771 app.viewport.transcript_selection.head =
772 Some(crate::tui::selection::TranscriptSelectionPoint {
773 line_index: point.line_index,
774 column: end_col,
775 });
776 app.viewport.transcript_selection.dragging = false;
777 app.viewport.transcript_selection.owner =
778 app.transcript_owner_at_line(point.line_index);
779 if selection_has_content(app) && !app.clipboard.uses_primary_selection()
780 {
781 copy_active_selection(app);
782 }
783 } else {
784 app.viewport.transcript_selection.anchor = Some(point);
785 app.viewport.transcript_selection.head = Some(point);
786 app.viewport.transcript_selection.dragging = true;
787 app.viewport.transcript_selection.owner =
788 app.transcript_owner_at_line(point.line_index);
789 }
790 }
791 ComposerClickGesture::Line => {
792 if let Some((start_col, end_col)) =
793 content_column_span(app, point.line_index)
794 {
795 app.viewport.transcript_selection.anchor =
796 Some(crate::tui::selection::TranscriptSelectionPoint {
797 line_index: point.line_index,
798 column: start_col,
799 });
800 app.viewport.transcript_selection.head =
801 Some(crate::tui::selection::TranscriptSelectionPoint {
802 line_index: point.line_index,
803 column: end_col,
804 });
805 app.viewport.transcript_selection.dragging = false;
806 app.viewport.transcript_selection.owner =
807 app.transcript_owner_at_line(point.line_index);
808 if selection_has_content(app) && !app.clipboard.uses_primary_selection()
809 {
810 copy_active_selection(app);
811 }
812 } else {
813 app.viewport.transcript_selection.anchor = Some(point);
814 app.viewport.transcript_selection.head = Some(point);
815 app.viewport.transcript_selection.dragging = true;
816 app.viewport.transcript_selection.owner =
817 app.transcript_owner_at_line(point.line_index);
818 }
819 }
820 ComposerClickGesture::Caret => {
821 app.viewport.transcript_selection.anchor = Some(point);
822 app.viewport.transcript_selection.head = Some(point);
823 app.viewport.transcript_selection.dragging = true;
824 app.viewport.transcript_selection.owner =
825 app.transcript_owner_at_line(point.line_index);
826 }
827 }
828 app.needs_redraw = true;
829
830 if app.is_loading
831 && app.viewport.transcript_scroll.is_at_tail()
832 && let Some(anchor) = TranscriptScroll::anchor_for(
833 app.viewport.transcript_cache.line_meta(),
834 app.viewport.last_transcript_top,
835 )
836 {
837 app.viewport.transcript_scroll = anchor;
838 }
839 } else {
840 app.viewport.transcript_click_trace = None;
841 clear_transcript_selection(app);
842 }
843 }
844 MouseEventKind::Drag(MouseButton::Left) => {
845 if app.viewport.transcript_scrollbar_dragging {
846 scroll_transcript_to_mouse_row(app, mouse.row);
847 return Vec::new();
848 }
849
850 if app.viewport.transcript_selection.dragging {
851 update_selection_drag(app, mouse);
852 }
853 }
854 MouseEventKind::Up(MouseButton::Left) if app.viewport.transcript_scrollbar_dragging => {
855 app.viewport.transcript_scrollbar_dragging = false;
856 app.viewport.selection_autoscroll = None;
857 app.needs_redraw = true;
858 }
859 MouseEventKind::Up(MouseButton::Left) if app.viewport.transcript_selection.dragging => {
860 app.viewport.transcript_selection.dragging = false;
861 app.viewport.selection_autoscroll = None;
862 if selection_has_content(app) && !app.clipboard.uses_primary_selection() {
863 copy_active_selection(app);
864 } else if !mouse
865 .modifiers
866 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT)
867 && let Some(point) = app.viewport.transcript_selection.anchor
868 && app.viewport.transcript_selection.head == Some(point)
869 && selection_point_from_mouse(app, mouse) == Some(point)
870 && let Some(link) = transcript_link_at_point(app, point)
871 {
872 return activate_transcript_link(app, &link);
873 }
874 }
875 MouseEventKind::Down(MouseButton::Right) => {
876 open_context_menu(app, mouse);
877 }
878 _ => {}
879 }
880
881 Vec::new()
882 }
883
884 fn scroll_transcript_with_mouse(app: &mut App, direction: ScrollDirection) {
885 let update = app.viewport.mouse_scroll.on_scroll(direction);
886 app.viewport.pending_scroll_delta = app
887 .viewport
888 .pending_scroll_delta
889 .saturating_add(update.delta_lines);
890 if update.delta_lines != 0 {
891 app.user_scrolled_during_stream = true;
892 app.needs_redraw = true;
893 }
894 }
895
896 /// Resolve a right-click in the sidebar to the hovered row's full copyable
897 /// text: the row's untruncated text plus its hover detail when present.
898 fn sidebar_row_copy_text(app: &App, mouse: MouseEvent) -> Option<String> {
899 for section in &app.sidebar_hover.sections {
900 if !mouse_hits_rect(mouse, Some(section.content_area)) {
901 continue;
902 }
903 if let Some(row) = section.rows.iter().find(|row| row.row_y == mouse.row) {
904 let mut text = row.full_text.clone();
905 if let Some(detail) = row.detail.as_deref()
906 && !detail.trim().is_empty()
907 {
908 text.push('\n');
909 text.push_str(detail);
910 }
911 return Some(text).filter(|text| !text.trim().is_empty());
912 }
913 let line_idx = (mouse.row.saturating_sub(section.content_area.y)) as usize;
914 if let Some(full) = section.lines.get(line_idx) {
915 return Some(full.clone()).filter(|text| !text.trim().is_empty());
916 }
917 }
918 None
919 }
920
921 fn first_line(text: &str) -> &str {
922 text.lines().next().unwrap_or(text)
923 }
924
925 /// Resolve a left-click in the sidebar to a typed row action, if the clicked
926 /// row has a click action assigned (#3028, #4009).
927 fn sidebar_click_action(app: &App, mouse: MouseEvent) -> Option<SidebarRowAction> {
928 let row = sidebar_row_at(app, mouse)?;
929 if let (Some(action), Some(start), Some(end)) = (
930 row.stop_action.as_ref(),
931 row.stop_zone_start_col,
932 row.stop_zone_end_col,
933 ) && mouse.column >= start
934 && mouse.column < end
935 {
936 return Some(action.clone());
937 }
938 row.click_action.clone()
939 }
940
941 /// The work-surface row under the pointer, if any.
942 fn sidebar_row_at(app: &App, mouse: MouseEvent) -> Option<&crate::tui::app::SidebarHoverRow> {
943 for section in &app.sidebar_hover.sections {
944 if mouse.column >= section.content_area.x
945 && mouse.column
946 < section
947 .content_area
948 .x
949 .saturating_add(section.content_area.width)
950 && mouse.row >= section.content_area.y
951 && mouse.row
952 < section
953 .content_area
954 .y
955 .saturating_add(section.content_area.height)
956 && let Some(row) = section.rows.iter().find(|row| row.row_y == mouse.row)
957 {
958 return Some(row);
959 }
960 }
961 None
962 }
963
964 pub(crate) fn apply_sidebar_row_action(app: &mut App, action: SidebarRowAction) -> Vec<ViewEvent> {
965 match action {
966 SidebarRowAction::Command(command) => {
967 use crate::tui::views::CommandPaletteAction;
968 vec![ViewEvent::CommandPaletteSelected {
969 action: CommandPaletteAction::ExecuteCommand { command },
970 }]
971 }
972 SidebarRowAction::ShowSubagentsPanel => {
973 use crate::tui::work_surface::RailPanel;
974 // The register header is a two-way door: opening the Agents panel
975 // from anywhere, and returning to Tasks when it is already open,
976 // so the to-do list is never one click away with no way back.
977 let target = match app.work_surface.panel {
978 RailPanel::Agents => RailPanel::Tasks,
979 _ => RailPanel::Agents,
980 };
981 crate::tui::work_surface::select_dock_panel(app, target);
982 let message = match target {
983 RailPanel::Agents => MessageId::SidebarShowingSubagents,
984 _ => MessageId::SidebarShowingTasks,
985 };
986 app.show_input_hint(tr(app.ui_locale, message).into_owned());
987 app.needs_redraw = true;
988 Vec::new()
989 }
990 SidebarRowAction::OpenAgentDetail { agent_id } => {
991 if !crate::tui::agent_details::open_agent_details(app, &agent_id) {
992 crate::tui::work_surface::agent_details_closed(app, &agent_id);
993 app.show_input_hint(
994 tr(app.ui_locale, MessageId::SidebarAgentDetailsUnavailable).into_owned(),
995 );
996 }
997 app.needs_redraw = true;
998 Vec::new()
999 }
1000 SidebarRowAction::OpenAgentTranscript { agent_id } => {
1001 // The primary agent destination: focus the worker in place. The
1002 // focused view explains a missing capture instead of dead-ending.
1003 crate::tui::agent_focus::focus_agent(app, &agent_id);
1004 app.needs_redraw = true;
1005 Vec::new()
1006 }
1007 SidebarRowAction::CancelAgent { agent_id } => {
1008 vec![ViewEvent::SidebarAgentCancel { agent_id }]
1009 }
1010 SidebarRowAction::InspectWork {
1011 title,
1012 body,
1013 stop_action,
1014 } => {
1015 let width = app
1016 .viewport
1017 .last_transcript_area
1018 .map(|area| area.width)
1019 .unwrap_or(80);
1020 let mut pager =
1021 crate::tui::pager::PagerView::from_text(title, &body, width.saturating_sub(2))
1022 .with_copy_text(body);
1023 let stop_event = stop_action.and_then(|action| match *action {
1024 SidebarRowAction::Command(command) => {
1025 use crate::tui::views::CommandPaletteAction;
1026 Some(ViewEvent::CommandPaletteSelected {
1027 action: CommandPaletteAction::ExecuteCommand { command },
1028 })
1029 }
1030 SidebarRowAction::CancelAgent { agent_id } => {
1031 Some(ViewEvent::SidebarAgentCancel { agent_id })
1032 }
1033 _ => None,
1034 });
1035 if let Some(event) = stop_event {
1036 pager = pager.with_destructive_action(
1037 's',
1038 app.tr(MessageId::SidebarStopControl),
1039 app.tr(MessageId::WorkSurfaceStopConfirmHint),
1040 event,
1041 );
1042 }
1043 app.view_stack.push(pager);
1044 app.needs_redraw = true;
1045 Vec::new()
1046 }
1047 }
1048 }
1049
1050 pub(crate) fn resolve_agent_transcript_text(app: &App, agent_id: &str) -> Option<String> {
1051 use codewhale_engine::tools::handle::{HandleValue, VarHandle};
1052
1053 let lookup = VarHandle {
1054 kind: "var_handle".to_string(),
1055 session_id: format!("agent:{agent_id}"),
1056 name: "full_transcript".to_string(),
1057 type_name: String::new(),
1058 length: 0,
1059 repr_preview: String::new(),
1060 sha256: String::new(),
1061 };
1062 let payload = match app.runtime_services.handle_store.try_lock() {
1063 Ok(store) => match store.get(&lookup) {
1064 Some(record) => match &record.value {
1065 HandleValue::Json(value) => Some(value.clone()),
1066 HandleValue::Text(_) => None,
1067 },
1068 None => None,
1069 },
1070 Err(_) => return None,
1071 };
1072
1073 // The handle is a deliberately bounded live projection. Prefer the private
1074 // on-disk message stream so Open means the entire chat, including early
1075 // turns that no longer fit in the 1 MiB resident tail. While the worker is
1076 // live, require its artifact count to match the latest handle count; a
1077 // failed/stale append must fall back to the explicit omission banner. With
1078 // no process-local handle (for example after restart), the validated
1079 // artifact remains the durable source of truth.
1080 if let Ok(display) =
1081 codewhale_engine::tools::subagent::load_subagent_transcript_display_artifact(
1082 &app.workspace,
1083 agent_id,
1084 )
1085 {
1086 let matches_resident_count = payload.as_ref().is_none_or(|resident| {
1087 resident
1088 .get("message_count")
1089 .and_then(serde_json::Value::as_u64)
1090 .and_then(|count| usize::try_from(count).ok())
1091 == Some(display.conversation_count)
1092 && resident
1093 .get("complete_transcript_artifact")
1094 .and_then(|artifact| artifact.get("complete"))
1095 .and_then(serde_json::Value::as_bool)
1096 .unwrap_or(true)
1097 });
1098 if matches_resident_count {
1099 let text = agent_messages_text(&display.messages);
1100 if !text.trim().is_empty() {
1101 return Some(text);
1102 }
1103 }
1104 }
1105
1106 let payload = payload?;
1107 let text = agent_transcript_text(&payload);
1108 if text.trim().is_empty() {
1109 return None;
1110 }
1111 Some(text)
1112 }
1113
1114 pub(crate) fn agent_transcript_evidence_available(app: &App, agent_id: &str) -> bool {
1115 resolve_agent_transcript_text(app, agent_id).is_some()
1116 }
1117
1118 /// Turn the agent transcript handle into a readable conversation. The worker
1119 /// may retain tool calls and results, but private model thinking never appears
1120 /// here; the parent transcript has the same default privacy behavior.
1121 fn agent_transcript_text(payload: &serde_json::Value) -> String {
1122 let Some(messages) = payload
1123 .get("messages")
1124 .and_then(serde_json::Value::as_array)
1125 else {
1126 return String::new();
1127 };
1128
1129 let omitted = payload
1130 .get("omitted_messages")
1131 .and_then(serde_json::Value::as_u64)
1132 .unwrap_or_default();
1133 let total = payload
1134 .get("message_count")
1135 .and_then(serde_json::Value::as_u64)
1136 .unwrap_or(messages.len() as u64);
1137 let mut text = String::new();
1138 if omitted > 0 {
1139 text.push_str(&format!(
1140 "Showing the latest {} of {total} worker messages. Earlier messages were omitted from the in-memory transcript.\n\n",
1141 messages.len()
1142 ));
1143 }
1144
1145 let parsed: Vec<Message> = messages
1146 .iter()
1147 .filter_map(|raw| serde_json::from_value::<Message>(raw.clone()).ok())
1148 .collect();
1149 text.push_str(&agent_messages_text(&parsed));
1150 text
1151 }
1152
1153 fn agent_messages_text(messages: &[Message]) -> String {
1154 let mut text = String::new();
1155 for message in messages {
1156 let body = agent_message_text(message);
1157 if body.trim().is_empty() {
1158 continue;
1159 }
1160 text.push_str(&format!("── {} ──\n{body}\n\n", message.role));
1161 }
1162 text
1163 }
1164
1165 fn agent_message_text(message: &Message) -> String {
1166 let mut text = String::new();
1167 for block in &message.content {
1168 match block {
1169 ContentBlock::Text { text: body, .. } => {
1170 if !body.trim().is_empty() {
1171 text.push_str(body);
1172 text.push('\n');
1173 }
1174 }
1175 ContentBlock::ToolUse { name, input, .. }
1176 | ContentBlock::ServerToolUse { name, input, .. } => {
1177 text.push_str(&format!(
1178 "→ {name}\n{}\n",
1179 serde_json::to_string_pretty(input).unwrap_or_else(|_| input.to_string())
1180 ));
1181 }
1182 ContentBlock::ToolResult {
1183 tool_use_id,
1184 content,
1185 is_error,
1186 ..
1187 } => {
1188 let label = match is_error {
1189 Some(true) => "← tool error",
1190 Some(false) => "← tool result",
1191 None => {
1192 tracing::warn!(
1193 target: "codewhale_tui::mouse_ui",
1194 %tool_use_id,
1195 "worker tool result missing is_error flag"
1196 );
1197 "← tool result (status unknown)"
1198 }
1199 };
1200 text.push_str(&format!("{label} ({tool_use_id})\n{content}\n"));
1201 }
1202 ContentBlock::ImageUrl { image_url } => {
1203 text.push_str(&format!("[image: {}]\n", image_url.url));
1204 }
1205 // Thinking blocks are deliberately not surfaced in the main TUI
1206 // and should not leak through a worker detail view either.
1207 ContentBlock::Thinking { .. } => {}
1208 other => {
1209 text.push_str(&format!(
1210 "{}\n",
1211 serde_json::to_string_pretty(other).unwrap_or_else(|_| "[worker event]".into())
1212 ));
1213 }
1214 }
1215 }
1216 text.trim_end().to_string()
1217 }
1218
1219 pub(crate) fn mouse_hits_transcript_scrollbar(app: &App, mouse: MouseEvent) -> bool {
1220 let Some(area) = app.viewport.last_transcript_area else {
1221 return false;
1222 };
1223 if area.width <= 1 || app.viewport.last_transcript_total <= app.viewport.last_transcript_visible
1224 {
1225 return false;
1226 }
1227
1228 let scrollbar_col = area.x.saturating_add(area.width.saturating_sub(1));
1229 mouse.column == scrollbar_col
1230 && mouse.row >= area.y
1231 && mouse.row < area.y.saturating_add(area.height)
1232 }
1233
1234 pub(crate) fn scroll_transcript_to_mouse_row(app: &mut App, row: u16) -> bool {
1235 let Some(area) = app.viewport.last_transcript_area else {
1236 return false;
1237 };
1238 let total = app.viewport.last_transcript_total;
1239 let visible = app.viewport.last_transcript_visible;
1240 if area.height == 0 || total <= visible {
1241 return false;
1242 }
1243
1244 let max_start = total.saturating_sub(visible);
1245 if max_start == 0 {
1246 app.scroll_to_bottom();
1247 return true;
1248 }
1249
1250 let max_row = usize::from(area.height.saturating_sub(1));
1251 let relative_row = usize::from(row.saturating_sub(area.y)).min(max_row);
1252 let numerator = relative_row
1253 .saturating_mul(max_start)
1254 .saturating_add(max_row / 2);
1255 // Round to the nearest transcript offset so short thumbs still feel
1256 // responsive on compact terminals.
1257 let top = numerator.checked_div(max_row).unwrap_or(0);
1258
1259 app.viewport.transcript_scroll = if top >= max_start {
1260 TranscriptScroll::to_bottom()
1261 } else {
1262 TranscriptScroll::at_line(top)
1263 };
1264 app.viewport.pending_scroll_delta = 0;
1265 app.user_scrolled_during_stream = !app.viewport.transcript_scroll.is_at_tail();
1266 app.needs_redraw = true;
1267 true
1268 }
1269
1270 /// Cadence between auto-scroll ticks while drag-selecting past the
1271 /// transcript edge (#1163). 30 ms ≈ 33 lines/sec, comparable to the feel
1272 /// of a steady scroll-wheel drag.
1273 const SELECTION_AUTOSCROLL_INTERVAL: Duration = Duration::from_millis(30);
1274
1275 /// Update the transcript selection while the left button is dragging.
1276 /// When the mouse leaves the transcript rect vertically, arm
1277 /// `selection_autoscroll` so the main loop can advance the viewport on a
1278 /// fixed cadence; when the mouse returns inside, disarm it.
1279 pub(crate) fn update_selection_drag(app: &mut App, mouse: MouseEvent) {
1280 if let Some(point) = selection_point_from_mouse(app, mouse) {
1281 app.viewport.transcript_selection.head = Some(point);
1282 app.viewport.selection_autoscroll = None;
1283 app.needs_redraw = true;
1284 return;
1285 }
1286
1287 let Some(area) = app.viewport.last_transcript_area else {
1288 return;
1289 };
1290 if area.height == 0 || area.width == 0 {
1291 return;
1292 }
1293
1294 let direction = if mouse.row < area.y {
1295 -1
1296 } else if mouse.row >= area.y.saturating_add(area.height) {
1297 1
1298 } else {
1299 // Outside horizontally only — leave selection head where it is.
1300 return;
1301 };
1302
1303 let max_col = area.x.saturating_add(area.width.saturating_sub(1));
1304 let column = mouse.column.clamp(area.x, max_col);
1305
1306 // Fire on the next tick immediately by setting `next_tick` to now.
1307 app.viewport.selection_autoscroll = Some(SelectionAutoscroll {
1308 direction,
1309 column,
1310 next_tick: Instant::now(),
1311 });
1312 app.needs_redraw = true;
1313 }
1314
1315 /// Advance the drag-edge auto-scroll one step if its cadence has elapsed.
1316 /// Called once per main-loop iteration.
1317 pub(crate) fn tick_selection_autoscroll(app: &mut App) {
1318 let Some(state) = app.viewport.selection_autoscroll else {
1319 return;
1320 };
1321
1322 if !app.viewport.transcript_selection.dragging {
1323 app.viewport.selection_autoscroll = None;
1324 return;
1325 }
1326
1327 let Some(area) = app.viewport.last_transcript_area else {
1328 return;
1329 };
1330 if area.height == 0 {
1331 return;
1332 }
1333
1334 let now = Instant::now();
1335 if now < state.next_tick {
1336 return;
1337 }
1338
1339 app.viewport.pending_scroll_delta = app
1340 .viewport
1341 .pending_scroll_delta
1342 .saturating_add(state.direction);
1343 app.user_scrolled_during_stream = true;
1344
1345 let edge_row = if state.direction < 0 {
1346 area.y
1347 } else {
1348 area.y.saturating_add(area.height.saturating_sub(1))
1349 };
1350 if let Some(point) = selection_point_from_position(
1351 area,
1352 state.column,
1353 edge_row,
1354 app.viewport.last_transcript_top,
1355 app.viewport.last_transcript_total,
1356 app.viewport.last_transcript_padding_top,
1357 ) {
1358 app.viewport.transcript_selection.head = Some(point);
1359 }
1360
1361 app.viewport.selection_autoscroll = Some(SelectionAutoscroll {
1362 next_tick: now + SELECTION_AUTOSCROLL_INTERVAL,
1363 ..state
1364 });
1365 app.needs_redraw = true;
1366 }
1367
1368 pub(crate) fn mouse_hits_rect(mouse: MouseEvent, area: Option<Rect>) -> bool {
1369 point_hits_rect(mouse.column, mouse.row, area)
1370 }
1371
1372 fn point_hits_rect(column: u16, row: u16, area: Option<Rect>) -> bool {
1373 let Some(area) = area else {
1374 return false;
1375 };
1376
1377 column >= area.x
1378 && column < area.x.saturating_add(area.width)
1379 && row >= area.y
1380 && row < area.y.saturating_add(area.height)
1381 }
1382
1383 pub(crate) fn open_context_menu(app: &mut App, mouse: MouseEvent) {
1384 let entries = build_context_menu_entries(app, mouse);
1385 if entries.is_empty() {
1386 return;
1387 }
1388 let title = app.tr(MessageId::CtxMenuTitle).to_string();
1389 push_context_menu(app, entries, mouse.column, mouse.row, title);
1390 }
1391
1392 /// Open a context menu at a screen position. Shared by the transcript/work
1393 /// surface menu and by modal views that ask for one over themselves.
1394 pub(crate) fn push_context_menu(
1395 app: &mut App,
1396 entries: Vec<ContextMenuEntry>,
1397 column: u16,
1398 row: u16,
1399 title: String,
1400 ) {
1401 let reduced = app.motion_policy().as_low_motion();
1402 app.view_stack.push(ContextMenuView::new_with_motion(
1403 entries, column, row, title, reduced,
1404 ));
1405 app.needs_redraw = true;
1406 }
1407
1408 fn transcript_link_at_point(
1409 app: &App,
1410 point: crate::tui::selection::TranscriptSelectionPoint,
1411 ) -> Option<codewhale_tui_kit::osc8::LineLink> {
1412 app.viewport
1413 .transcript_cache
1414 .line_links()
1415 .get(point.line_index)?
1416 .iter()
1417 .find(|link| point.column >= link.col_start && point.column <= link.col_end)
1418 .cloned()
1419 }
1420
1421 fn transcript_double_click_span(
1422 app: &App,
1423 point: crate::tui::selection::TranscriptSelectionPoint,
1424 ) -> Option<(usize, usize)> {
1425 if let Some(link) = transcript_link_at_point(app, point) {
1426 return Some((link.col_start, link.col_end.saturating_add(1)));
1427 }
1428 let line = app
1429 .viewport
1430 .transcript_cache
1431 .lines()
1432 .get(point.line_index)?;
1433 let plain = line_to_plain(line);
1434 transcript_token_span_at_column(&plain, point.column)
1435 }
1436
1437 fn is_transcript_token_char(ch: char) -> bool {
1438 !ch.is_whitespace()
1439 && !matches!(
1440 ch,
1441 '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '"' | '\'' | '`' | ',' | ';'
1442 )
1443 }
1444
1445 fn transcript_token_span_at_column(line: &str, target_col: usize) -> Option<(usize, usize)> {
1446 let mut cols: Vec<(usize, usize, char)> = Vec::new();
1447 let mut col = 0usize;
1448 for ch in line.chars() {
1449 let width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
1450 cols.push((col, col.saturating_add(width), ch));
1451 col = col.saturating_add(width);
1452 }
1453 if cols.is_empty() {
1454 return None;
1455 }
1456 let idx = cols
1457 .iter()
1458 .position(|(start, end, _)| target_col >= *start && target_col < (*end).max(*start + 1))
1459 .unwrap_or_else(|| cols.len().saturating_sub(1));
1460 let (_, _, ch) = cols[idx];
1461 if !is_transcript_token_char(ch) {
1462 return Some((cols[idx].0, cols[idx].1.max(cols[idx].0 + 1)));
1463 }
1464 let mut left = idx;
1465 while left > 0 && is_transcript_token_char(cols[left - 1].2) {
1466 left -= 1;
1467 }
1468 let mut right = idx;
1469 while right + 1 < cols.len() && is_transcript_token_char(cols[right + 1].2) {
1470 right += 1;
1471 }
1472 Some((cols[left].0, cols[right].1))
1473 }
1474
1475 fn transcript_token_at_column(line: &str, target_col: usize) -> Option<String> {
1476 let (start_col, end_col) = transcript_token_span_at_column(line, target_col)?;
1477 let mut out = String::new();
1478 let mut col = 0usize;
1479 for ch in line.chars() {
1480 let width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
1481 let next = col.saturating_add(width);
1482 if col >= start_col && next <= end_col {
1483 out.push(ch);
1484 }
1485 col = next;
1486 }
1487 (!out.is_empty()).then_some(out)
1488 }
1489
1490 fn activate_transcript_link(
1491 app: &mut App,
1492 link: &codewhale_tui_kit::osc8::LineLink,
1493 ) -> Vec<ViewEvent> {
1494 if link.target.starts_with("http://") || link.target.starts_with("https://") {
1495 return vec![ViewEvent::ContextMenuSelected {
1496 action: ContextMenuAction::OpenExternalUrl {
1497 url: link.target.clone(),
1498 },
1499 }];
1500 }
1501 if link.target.starts_with("file://") {
1502 if let Some(target) =
1503 crate::tui::history::workspace_target_from_file_uri(&app.workspace, &link.target)
1504 {
1505 if target.is_dir {
1506 return vec![ViewEvent::ContextMenuSelected {
1507 action: ContextMenuAction::OpenPath { path: target.path },
1508 }];
1509 }
1510 return vec![ViewEvent::ContextMenuSelected {
1511 action: ContextMenuAction::OpenFileAtLine {
1512 path: target.path,
1513 line: link.line.unwrap_or(1),
1514 },
1515 }];
1516 }
1517 app.push_status_toast(
1518 app.tr(MessageId::CtxMenuEditorRefused)
1519 .replace("{path}", &link.target),
1520 StatusToastLevel::Warning,
1521 Some(5_000),
1522 );
1523 }
1524 Vec::new()
1525 }
1526
1527 #[derive(Debug, Clone, PartialEq, Eq)]
1528 enum RightClickTarget {
1529 File { path: std::path::PathBuf, line: u32 },
1530 Directory { path: std::path::PathBuf },
1531 Url { url: String },
1532 }
1533
1534 fn reveal_label_id() -> MessageId {
1535 if cfg!(target_os = "macos") {
1536 MessageId::CtxMenuRevealInFinder
1537 } else {
1538 MessageId::CtxMenuRevealInFileManager
1539 }
1540 }
1541
1542 fn context_menu_target_at_mouse(
1543 app: &App,
1544 mouse: MouseEvent,
1545 cell_index: usize,
1546 ) -> Option<RightClickTarget> {
1547 if let Some(point) = selection_point_from_mouse(app, mouse) {
1548 if let Some(link) = transcript_link_at_point(app, point) {
1549 if link.target.starts_with("http://") || link.target.starts_with("https://") {
1550 return Some(RightClickTarget::Url { url: link.target });
1551 }
1552 if link.target.starts_with("file://")
1553 && let Some(target) = crate::tui::history::workspace_target_from_file_uri(
1554 &app.workspace,
1555 &link.target,
1556 )
1557 {
1558 return Some(if target.is_dir {
1559 RightClickTarget::Directory { path: target.path }
1560 } else {
1561 RightClickTarget::File {
1562 path: target.path,
1563 line: link.line.unwrap_or(1),
1564 }
1565 });
1566 }
1567 }
1568 if let Some(line) = app.viewport.transcript_cache.lines().get(point.line_index) {
1569 let plain = line_to_plain(line);
1570 if let Some(token) = transcript_token_at_column(&plain, point.column) {
1571 let cleaned = token
1572 .trim_start_matches(['`', '\'', '"', '(', '[', '<'])
1573 .trim_end_matches(['`', '\'', '"', ')', ']', '>', ',', ';', '.']);
1574 if cleaned.starts_with("http://") || cleaned.starts_with("https://") {
1575 return Some(RightClickTarget::Url {
1576 url: cleaned.to_string(),
1577 });
1578 }
1579 if let Some((target, line_no)) =
1580 crate::tui::history::parse_workspace_link_candidate(cleaned, &app.workspace)
1581 {
1582 return Some(if target.is_dir {
1583 RightClickTarget::Directory { path: target.path }
1584 } else {
1585 RightClickTarget::File {
1586 path: target.path,
1587 line: line_no.unwrap_or(1),
1588 }
1589 });
1590 }
1591 }
1592 }
1593 }
1594 context_menu_file_reference(app, mouse, cell_index)
1595 .map(|(path, line)| RightClickTarget::File { path, line })
1596 }
1597
1598 fn context_menu_code_block_at_mouse(
1599 app: &App,
1600 mouse: MouseEvent,
1601 cell_index: usize,
1602 ) -> Option<String> {
1603 let point = selection_point_from_mouse(app, mouse)?;
1604 let clicked_line = app
1605 .viewport
1606 .transcript_cache
1607 .lines()
1608 .get(point.line_index)
1609 .map(line_to_plain)?;
1610 let clicked_trimmed = clicked_line.trim();
1611 if clicked_trimmed.is_empty() {
1612 return None;
1613 }
1614 let crate::tui::history::HistoryCell::Assistant { content, .. } =
1615 app.cell_at_virtual_index(cell_index)?
1616 else {
1617 return None;
1618 };
1619 let mut in_fence: Option<char> = None;
1620 let mut current_block: Vec<&str> = Vec::new();
1621 let mut blocks: Vec<String> = Vec::new();
1622 for raw_line in content.lines() {
1623 let trimmed = raw_line.trim_start();
1624 if let Some(fence_ch) = in_fence {
1625 if trimmed.starts_with(fence_ch)
1626 && trimmed.chars().take_while(|c| *c == fence_ch).count() >= 3
1627 && trimmed.trim_matches(fence_ch).trim().is_empty()
1628 {
1629 if !current_block.is_empty() {
1630 blocks.push(current_block.join("\n"));
1631 current_block.clear();
1632 }
1633 in_fence = None;
1634 continue;
1635 }
1636 current_block.push(raw_line);
1637 } else if trimmed.starts_with("```") {
1638 in_fence = Some('`');
1639 } else if trimmed.starts_with("~~~") {
1640 in_fence = Some('~');
1641 }
1642 }
1643 if !current_block.is_empty() {
1644 blocks.push(current_block.join("\n"));
1645 }
1646 blocks.into_iter().find(|block| {
1647 block
1648 .lines()
1649 .any(|line| !line.trim().is_empty() && line.trim() == clicked_trimmed)
1650 })
1651 }
1652
1653 pub(crate) fn build_context_menu_entries(app: &App, mouse: MouseEvent) -> Vec<ContextMenuEntry> {
1654 let mut entries = Vec::new();
1655 let on_work_surface = mouse_hits_rect(mouse, app.work_surface.last_area);
1656 let on_composer = mouse_hits_rect(mouse, app.viewport.last_composer_area);
1657 let has_selection = selection_has_content(app);
1658 let clicked_cell = (!on_work_surface && !on_composer)
1659 .then(|| transcript_cell_index_from_mouse(app, mouse))
1660 .flatten()
1661 .map(|filtered| app.original_cell_index_for_rendered(filtered));
1662 let clicked_target =
1663 clicked_cell.and_then(|cell_index| context_menu_target_at_mouse(app, mouse, cell_index));
1664 let clicked_code = clicked_cell
1665 .and_then(|cell_index| context_menu_code_block_at_mouse(app, mouse, cell_index));
1666 let paste_first = !on_work_surface && !has_selection && clicked_target.is_none();
1667
1668 if on_work_surface {
1669 push_work_row_entries(app, mouse, &mut entries);
1670 } else if paste_first {
1671 entries.push(
1672 ContextMenuEntry::new(
1673 app.tr(MessageId::CtxMenuPaste),
1674 app.tr(MessageId::CtxMenuPasteDesc),
1675 ContextMenuAction::Paste,
1676 )
1677 .with_glyph("📋")
1678 .with_hint("p")
1679 .primary(),
1680 );
1681 }
1682 let mut targeted = !entries.is_empty() && on_work_surface;
1683
1684 if has_selection {
1685 targeted = true;
1686 let mut copy_entry = ContextMenuEntry::new(
1687 app.tr(MessageId::CtxMenuCopySelection),
1688 app.tr(MessageId::CtxMenuCopySelectionDesc),
1689 ContextMenuAction::CopySelection,
1690 )
1691 .with_glyph("⎘")
1692 .with_hint("y")
1693 .primary();
1694 if !entries.is_empty() {
1695 copy_entry = copy_entry.section_start();
1696 }
1697 entries.push(copy_entry);
1698 entries.push(
1699 ContextMenuEntry::new(
1700 app.tr(MessageId::CtxMenuOpenSelection),
1701 app.tr(MessageId::CtxMenuOpenSelectionDesc),
1702 ContextMenuAction::OpenSelection,
1703 )
1704 .with_glyph("↗"),
1705 );
1706 entries.push(
1707 ContextMenuEntry::new(
1708 app.tr(MessageId::CtxMenuClearSelection),
1709 "",
1710 ContextMenuAction::ClearSelection,
1711 )
1712 .with_glyph("×"),
1713 );
1714 }
1715
1716 if let Some(target) = clicked_target {
1717 targeted = true;
1718 let target_is_primary = !has_selection;
1719 let section_start = !entries.is_empty();
1720 match target {
1721 RightClickTarget::File { path, line } => {
1722 let shown = path
1723 .strip_prefix(&app.workspace)
1724 .unwrap_or(&path)
1725 .display()
1726 .to_string();
1727 let mut open_entry = ContextMenuEntry::new(
1728 app.tr(MessageId::CtxMenuOpenInEditor),
1729 format!("{shown}:{line}"),
1730 ContextMenuAction::OpenFileAtLine {
1731 path: path.clone(),
1732 line,
1733 },
1734 )
1735 .with_glyph("↗")
1736 .with_hint("e");
1737 if target_is_primary {
1738 open_entry = open_entry.primary();
1739 }
1740 if section_start {
1741 open_entry = open_entry.section_start();
1742 }
1743 entries.push(open_entry);
1744 entries.push(
1745 ContextMenuEntry::new(
1746 app.tr(reveal_label_id()),
1747 shown.clone(),
1748 ContextMenuAction::RevealPath { path },
1749 )
1750 .with_glyph("◈"),
1751 );
1752 entries.push(
1753 ContextMenuEntry::new(
1754 app.tr(MessageId::CtxMenuCopyPath),
1755 shown.clone(),
1756 ContextMenuAction::CopyText { text: shown },
1757 )
1758 .with_glyph("⎘"),
1759 );
1760 }
1761 RightClickTarget::Directory { path } => {
1762 let shown = path
1763 .strip_prefix(&app.workspace)
1764 .unwrap_or(&path)
1765 .display()
1766 .to_string();
1767 let mut open_entry = ContextMenuEntry::new(
1768 app.tr(MessageId::CtxMenuOpenFolder),
1769 shown.clone(),
1770 ContextMenuAction::OpenPath { path: path.clone() },
1771 )
1772 .with_glyph("↗")
1773 .with_hint("o");
1774 if target_is_primary {
1775 open_entry = open_entry.primary();
1776 }
1777 if section_start {
1778 open_entry = open_entry.section_start();
1779 }
1780 entries.push(open_entry);
1781 entries.push(
1782 ContextMenuEntry::new(
1783 app.tr(reveal_label_id()),
1784 shown.clone(),
1785 ContextMenuAction::RevealPath { path },
1786 )
1787 .with_glyph("◈"),
1788 );
1789 entries.push(
1790 ContextMenuEntry::new(
1791 app.tr(MessageId::CtxMenuCopyPath),
1792 shown.clone(),
1793 ContextMenuAction::CopyText { text: shown },
1794 )
1795 .with_glyph("⎘"),
1796 );
1797 }
1798 RightClickTarget::Url { url } => {
1799 let desc = truncate_line_to_width(url.as_str(), 32);
1800 let mut open_entry = ContextMenuEntry::new(
1801 app.tr(MessageId::CtxMenuOpenLink),
1802 desc.clone(),
1803 ContextMenuAction::OpenExternalUrl { url: url.clone() },
1804 )
1805 .with_glyph("↗")
1806 .with_hint("o");
1807 if target_is_primary {
1808 open_entry = open_entry.primary();
1809 }
1810 if section_start {
1811 open_entry = open_entry.section_start();
1812 }
1813 entries.push(open_entry);
1814 entries.push(
1815 ContextMenuEntry::new(
1816 app.tr(MessageId::CtxMenuCopyLink),
1817 desc,
1818 ContextMenuAction::CopyText { text: url },
1819 )
1820 .with_glyph("⎘"),
1821 );
1822 }
1823 }
1824 }
1825
1826 if let Some(code) = clicked_code {
1827 targeted = true;
1828 let mut entry = ContextMenuEntry::new(
1829 app.tr(MessageId::CtxMenuCopyCode),
1830 "",
1831 ContextMenuAction::CopyText { text: code },
1832 )
1833 .with_glyph("⎘");
1834 if !entries.is_empty() {
1835 entry = entry.section_start();
1836 }
1837 entries.push(entry);
1838 }
1839
1840 if let Some(cell_index) = clicked_cell {
1841 targeted = true;
1842 let target = detail_target_label(app, cell_index)
1843 .map(|label| truncate_line_to_width(label.as_str(), 28))
1844 .unwrap_or_else(|| "message".to_string());
1845 entries.push(
1846 ContextMenuEntry::new(
1847 app.tr(MessageId::CtxMenuOpenDetails),
1848 target,
1849 ContextMenuAction::OpenDetails { cell_index },
1850 )
1851 .with_glyph("▣")
1852 .section_start(),
1853 );
1854 entries.push(
1855 ContextMenuEntry::new(
1856 app.tr(MessageId::CtxMenuCopyMessage),
1857 app.tr(MessageId::CtxMenuCopyMessageDesc),
1858 ContextMenuAction::CopyCell { cell_index },
1859 )
1860 .with_glyph("⎘"),
1861 );
1862 if app.collapsed_cells.contains(&cell_index) {
1863 entries.push(
1864 ContextMenuEntry::new(
1865 app.tr(MessageId::CtxMenuShowCell),
1866 app.tr(MessageId::CtxMenuShowCellDesc),
1867 ContextMenuAction::ShowCell { cell_index },
1868 )
1869 .with_glyph("◇"),
1870 );
1871 } else {
1872 entries.push(
1873 ContextMenuEntry::new(
1874 app.tr(MessageId::CtxMenuHideCell),
1875 app.tr(MessageId::CtxMenuHideCellDesc),
1876 ContextMenuAction::HideCell { cell_index },
1877 )
1878 .with_glyph("○"),
1879 );
1880 }
1881 }
1882
1883 if !on_work_surface && !paste_first {
1884 entries.push(
1885 ContextMenuEntry::new(
1886 app.tr(MessageId::CtxMenuPaste),
1887 app.tr(MessageId::CtxMenuPasteDesc),
1888 ContextMenuAction::Paste,
1889 )
1890 .with_glyph("📋")
1891 .with_hint("p")
1892 .section_start(),
1893 );
1894 }
1895
1896 // When cells are hidden, offer a way to show them all.
1897 if !app.collapsed_cells.is_empty() {
1898 let count = app.collapsed_cells.len();
1899 let label = app.tr(MessageId::CtxMenuShowHidden).to_string();
1900 entries.push(
1901 ContextMenuEntry::new(
1902 format!("{label} ({count})"),
1903 app.tr(MessageId::CtxMenuShowHiddenDesc),
1904 ContextMenuAction::ShowAllHidden,
1905 )
1906 .with_glyph("◇")
1907 .section_start(),
1908 );
1909 }
1910
1911 // App chrome belongs to empty space. On a message, a row or a selection
1912 // it only pushed the target's own actions off the bottom of the menu.
1913 if !targeted {
1914 push_chrome_entries(app, &mut entries);
1915 }
1916 entries
1917 }
1918
1919 fn push_chrome_entries(app: &App, entries: &mut Vec<ContextMenuEntry>) {
1920 entries.push(
1921 ContextMenuEntry::new(
1922 app.tr(MessageId::CtxMenuCmdPalette),
1923 app.tr(MessageId::CtxMenuCmdPaletteDesc),
1924 ContextMenuAction::OpenCommandPalette,
1925 )
1926 .with_glyph("⌘")
1927 .section_start(),
1928 );
1929 entries.push(
1930 ContextMenuEntry::new(
1931 app.tr(MessageId::CtxMenuContextInspector),
1932 app.tr(MessageId::CtxMenuContextInspectorDesc),
1933 ContextMenuAction::OpenContextInspector,
1934 )
1935 .with_glyph("ⓘ"),
1936 );
1937 entries.push(
1938 ContextMenuEntry::new(
1939 app.tr(MessageId::CtxMenuHelp),
1940 app.tr(MessageId::CtxMenuHelpDesc),
1941 ContextMenuAction::OpenHelp,
1942 )
1943 .with_glyph("?"),
1944 );
1945
1946 // Host window control (Windows only): pin/unpin the terminal window into
1947 // an always-on-top mini window. The label flips while pinned ("还原窗口"
1948 // instead of "弹出置顶小窗") so the entry always describes what the click
1949 // will do.
1950 if crate::tui::window_control::available() {
1951 let pinned = crate::tui::window_control::pinned();
1952 entries.push(
1953 ContextMenuEntry::new(
1954 app.tr(if pinned {
1955 MessageId::CtxMenuWindowUnpin
1956 } else {
1957 MessageId::CtxMenuWindowPin
1958 }),
1959 app.tr(MessageId::CtxMenuWindowPinDesc),
1960 ContextMenuAction::ToggleWindowPin,
1961 )
1962 .with_glyph(if pinned { "↩" } else { "📌" }),
1963 );
1964 }
1965 }
1966
1967 /// A work-surface row's menu: the row's own action first (what a left click
1968 /// does), then the agent or work item's other doors, then Copy, and any stop
1969 /// last behind an in-menu confirm. Each entry carries a typed row action, so
1970 /// the menu runs exactly what the row runs; nothing is a free-form command.
1971 ///
1972 /// Focus is the one agent destination: focusing shows the agent's chat and
1973 /// addresses the composer to it, so "Message agent" and "Open transcript"
1974 /// would be the same action under three names.
1975 fn push_work_row_entries(app: &App, mouse: MouseEvent, entries: &mut Vec<ContextMenuEntry>) {
1976 let confirm = || app.tr(MessageId::CtxMenuConfirmArmed).into_owned();
1977 let row = |label: String, action: SidebarRowAction| {
1978 ContextMenuEntry::new(label, "", ContextMenuAction::Row(action))
1979 };
1980 // The menu is built from the row's own action, never from its inline
1981 // stop zone: a right-click there must not make an unconfirmed stop the
1982 // primary entry. The row's stop, if any, goes last behind the confirm.
1983 let hovered = sidebar_row_at(app, mouse);
1984 let mut stop = hovered
1985 .and_then(|hovered| hovered.stop_action.clone())
1986 .map(|action| {
1987 let label = match action {
1988 SidebarRowAction::CancelAgent { .. } => MessageId::CtxMenuStopAgent,
1989 _ => MessageId::CtxMenuStopWork,
1990 };
1991 row(app.tr(label).into_owned(), action).confirm(confirm())
1992 });
1993 match hovered.and_then(|hovered| hovered.click_action.clone()) {
1994 Some(SidebarRowAction::OpenAgentTranscript { agent_id }) => {
1995 entries.push(
1996 ContextMenuEntry::new(
1997 app.tr(MessageId::CtxMenuFocusAgent),
1998 app.tr(MessageId::CtxMenuFocusAgentDesc),
1999 ContextMenuAction::Row(SidebarRowAction::OpenAgentTranscript {
2000 agent_id: agent_id.clone(),
2001 }),
2002 )
2003 .with_glyph("▶")
2004 .primary(),
2005 );
2006 entries.push(row(
2007 app.tr(MessageId::CtxMenuOpenDetails).into_owned(),
2008 SidebarRowAction::OpenAgentDetail {
2009 agent_id: agent_id.clone(),
2010 },
2011 ));
2012 entries.push(ContextMenuEntry::new(
2013 app.tr(MessageId::CtxMenuCopyId),
2014 agent_id.clone(),
2015 ContextMenuAction::CopyText {
2016 text: agent_id.clone(),
2017 },
2018 ));
2019 let running = app.subagent_cache.iter().any(|agent| {
2020 agent.agent_id == agent_id
2021 && matches!(
2022 agent.status,
2023 codewhale_engine::tools::subagent::SubAgentStatus::Running
2024 )
2025 });
2026 if running {
2027 stop = Some(
2028 row(
2029 app.tr(MessageId::CtxMenuStopAgent).into_owned(),
2030 SidebarRowAction::CancelAgent { agent_id },
2031 )
2032 .confirm(confirm()),
2033 );
2034 }
2035 }
2036 Some(SidebarRowAction::CancelAgent { agent_id }) => {
2037 stop = Some(
2038 row(
2039 app.tr(MessageId::CtxMenuStopAgent).into_owned(),
2040 SidebarRowAction::CancelAgent { agent_id },
2041 )
2042 .confirm(confirm()),
2043 );
2044 }
2045 Some(action @ SidebarRowAction::InspectWork { .. }) => {
2046 if let SidebarRowAction::InspectWork {
2047 stop_action: Some(stop_action),
2048 ..
2049 } = &action
2050 {
2051 stop = Some(
2052 row(
2053 app.tr(MessageId::CtxMenuStopWork).into_owned(),
2054 (**stop_action).clone(),
2055 )
2056 .confirm(confirm()),
2057 );
2058 }
2059 entries.push(row(app.tr(MessageId::CtxMenuOpenDetails).into_owned(), action).primary());
2060 }
2061 Some(action @ SidebarRowAction::OpenAgentDetail { .. }) => {
2062 entries.push(row(app.tr(MessageId::CtxMenuOpenDetails).into_owned(), action).primary());
2063 }
2064 Some(action @ SidebarRowAction::ShowSubagentsPanel) => {
2065 entries.push(row(app.tr(MessageId::CtxMenuOpen).into_owned(), action).primary());
2066 }
2067 Some(SidebarRowAction::Command(command)) => {
2068 if let Some(id) = command.strip_prefix("/jobs show ")
2069 && app.task_panel.iter().any(|entry| {
2070 entry.id == id && crate::tui::background_indicator::is_live_shell_entry(entry)
2071 })
2072 {
2073 stop = Some(
2074 row(
2075 app.tr(MessageId::CtxMenuStopWork).into_owned(),
2076 SidebarRowAction::Command(format!("/jobs cancel {id}")),
2077 )
2078 .confirm(confirm()),
2079 );
2080 }
2081 let label = app
2082 .tr(MessageId::CtxMenuRunCommand)
2083 .replace("{command}", &command);
2084 entries.push(row(label, SidebarRowAction::Command(command)).primary());
2085 }
2086 None => {}
2087 }
2088 // Copy the row's full text (rows can't be mouse-selected, so the menu is
2089 // the only copy path).
2090 if let Some(text) = sidebar_row_copy_text(app, mouse) {
2091 entries.push(
2092 ContextMenuEntry::new(
2093 app.tr(MessageId::CtxMenuCopyRow),
2094 truncate_line_to_width(first_line(&text), 28),
2095 ContextMenuAction::CopyText { text },
2096 )
2097 .with_glyph("⎘")
2098 .with_hint("y"),
2099 );
2100 }
2101 if let Some(stop) = stop {
2102 entries.push(stop.with_glyph("■").section_start());
2103 }
2104 }
2105
2106 /// The workspace file a right-click on a transcript cell points at: the first
2107 /// `path:line` on the clicked line, else a bare path there at line 1, else
2108 /// the same search over its displayed preview; hidden references are not
2109 /// enumerated for this click. All must be
2110 /// regular files inside the workspace, reached without links
2111 /// (`history::workspace_file`); `open_file_in_editor` checks again.
2112 fn context_menu_file_reference(
2113 app: &App,
2114 mouse: MouseEvent,
2115 cell_index: usize,
2116 ) -> Option<(std::path::PathBuf, u32)> {
2117 let clicked_line = selection_point_from_mouse(app, mouse).and_then(|point| {
2118 app.viewport
2119 .transcript_cache
2120 .lines()
2121 .get(point.line_index)
2122 .map(line_to_plain)
2123 });
2124 if let Some(found) = clicked_line.as_deref().and_then(|line| {
2125 crate::tui::history::file_line_reference(line, &app.workspace)
2126 .or_else(|| crate::tui::history::bare_file_reference(line, &app.workspace))
2127 }) {
2128 return Some(found);
2129 }
2130 let width = app
2131 .viewport
2132 .last_transcript_area
2133 .map(|area| area.width)
2134 .unwrap_or(80);
2135 let text = history_cell_to_text(app.cell_at_virtual_index(cell_index)?, width);
2136 crate::tui::history::first_file_line_reference(&text, &app.workspace)
2137 }
2138
2139 pub(crate) fn transcript_cell_index_from_mouse(app: &App, mouse: MouseEvent) -> Option<usize> {
2140 let point = selection_point_from_mouse(app, mouse)?;
2141 app.viewport
2142 .transcript_cache
2143 .line_meta()
2144 .get(point.line_index)
2145 .and_then(|meta| meta.cell_line())
2146 .map(|(cell_index, _)| cell_index)
2147 }
2148
2149 /// What a context-menu action needs from the host after `App` state changed.
2150 #[derive(Debug)]
2151 pub(crate) enum ContextMenuOutcome {
2152 Done,
2153 /// Row actions produce the same view events a left click on the row does;
2154 /// the host runs them through its view-event dispatcher.
2155 Events(Vec<ViewEvent>),
2156 /// Open a workspace file in `$EDITOR`. That needs the terminal (the TUI
2157 /// suspends while the editor owns it), so the host does it.
2158 OpenInEditor {
2159 path: std::path::PathBuf,
2160 line: u32,
2161 },
2162 }
2163
2164 /// Apply a context-menu action to `App`. Terminal work comes back as an
2165 /// outcome for the caller, so every action path is testable without one.
2166 pub(crate) fn apply_context_menu_action(
2167 app: &mut App,
2168 action: ContextMenuAction,
2169 ) -> ContextMenuOutcome {
2170 let mut outcome = ContextMenuOutcome::Done;
2171 match action {
2172 ContextMenuAction::CopySelection => {
2173 copy_active_selection(app);
2174 }
2175 ContextMenuAction::OpenSelection => {
2176 if !open_active_selection(app) {
2177 app.show_input_hint(
2178 tr(app.ui_locale, MessageId::CtxMenuNoSelectionToOpen).into_owned(),
2179 );
2180 }
2181 }
2182 ContextMenuAction::ClearSelection => {
2183 let message = if clear_active_selection(app) {
2184 MessageId::CtxMenuSelectionCleared
2185 } else {
2186 MessageId::CtxMenuNoSelectionToClear
2187 };
2188 app.show_input_hint(tr(app.ui_locale, message).into_owned());
2189 }
2190 ContextMenuAction::CopyCell { cell_index } => {
2191 copy_cell_to_clipboard(app, cell_index);
2192 }
2193 ContextMenuAction::OpenDetails { cell_index } => {
2194 if !open_details_pager_for_cell(app, cell_index) {
2195 app.show_input_hint(
2196 tr(app.ui_locale, MessageId::CtxMenuNoDetailsForLine).into_owned(),
2197 );
2198 }
2199 }
2200 ContextMenuAction::Paste => {
2201 crate::tui::paste::handle_paste(app, crate::tui::paste::PasteSource::Shortcut);
2202 }
2203 ContextMenuAction::Row(action) => {
2204 outcome = ContextMenuOutcome::Events(apply_sidebar_row_action(app, action));
2205 }
2206 ContextMenuAction::Extension { item_id, verb } => {
2207 match app.view_stack.extensions_menu_action(&item_id, verb) {
2208 Some(events) => outcome = ContextMenuOutcome::Events(events),
2209 None => {
2210 app.show_input_hint(
2211 tr(app.ui_locale, MessageId::CtxMenuExtensionUnlisted).into_owned(),
2212 );
2213 }
2214 }
2215 }
2216 ContextMenuAction::CopyText { text } => match app.clipboard.write_text_status(&text) {
2217 Ok(transport) => {
2218 let receipt = copy_receipt(app, transport, app.tr(MessageId::ClipboardCopied));
2219 app.show_copy_notice(receipt, StatusToastLevel::Info, 8_000);
2220 }
2221 Err(error) => {
2222 let receipt = copy_failed_receipt(app, error);
2223 app.show_copy_notice(receipt, StatusToastLevel::Error, App::STICKY_ERROR_TTL_MS);
2224 }
2225 },
2226 ContextMenuAction::ToggleWindowPin => {
2227 crate::tui::window_control::toggle_pin(app);
2228 }
2229 ContextMenuAction::OpenCommandPalette => {
2230 codewhale_telemetry::session_counters()
2231 .bump(codewhale_telemetry::Counter::CommandPaletteOpen);
2232 app.view_stack.push(CommandPaletteView::new_for_locale(
2233 app.ui_locale,
2234 build_command_palette_entries(
2235 app.ui_locale,
2236 &app.skills_dir,
2237 &app.skills_config,
2238 &app.workspace,
2239 &app.mcp_config_path,
2240 app.mcp_snapshot.as_ref(),
2241 app.extension_plugin_view().as_ref(),
2242 ),
2243 ));
2244 }
2245 ContextMenuAction::OpenContextInspector => {
2246 open_context_inspector(app);
2247 }
2248 ContextMenuAction::OpenHelp => {
2249 let help =
2250 HelpView::new_for_app(app, false).with_groups_expanded(app.help_expand_groups);
2251 app.view_stack.push(help);
2252 }
2253 ContextMenuAction::OpenFileAtLine { path, line } => {
2254 outcome = ContextMenuOutcome::OpenInEditor { path, line };
2255 }
2256 ContextMenuAction::OpenExternalUrl { url } => {
2257 if url.starts_with("http://") || url.starts_with("https://") {
2258 match codewhale_runtime::browser::open_url(&url) {
2259 Ok(()) => {
2260 app.push_status_toast(
2261 app.tr(MessageId::CtxMenuLinkOpened)
2262 .replace("{target}", &url),
2263 StatusToastLevel::Info,
2264 Some(4_000),
2265 );
2266 }
2267 Err(error) => {
2268 app.push_status_toast(
2269 app.tr(MessageId::CtxMenuOpenFailed)
2270 .replace("{target}", &url)
2271 .replace("{error}", &error.to_string()),
2272 StatusToastLevel::Warning,
2273 Some(5_000),
2274 );
2275 }
2276 }
2277 }
2278 }
2279 ContextMenuAction::OpenPath { path } => {
2280 let Some(target) = path
2281 .to_str()
2282 .and_then(|raw| crate::tui::history::workspace_target(&app.workspace, raw))
2283 else {
2284 app.push_status_toast(
2285 app.tr(MessageId::CtxMenuEditorRefused)
2286 .replace("{path}", &path.display().to_string()),
2287 StatusToastLevel::Warning,
2288 Some(5_000),
2289 );
2290 app.needs_redraw = true;
2291 return outcome;
2292 };
2293 let shown = target
2294 .path
2295 .strip_prefix(&app.workspace)
2296 .unwrap_or(&target.path)
2297 .display()
2298 .to_string();
2299 match codewhale_runtime::browser::open_path(&target.path) {
2300 Ok(()) => {
2301 app.push_status_toast(
2302 app.tr(MessageId::CtxMenuLinkOpened)
2303 .replace("{target}", &shown),
2304 StatusToastLevel::Info,
2305 Some(4_000),
2306 );
2307 }
2308 Err(error) => {
2309 app.push_status_toast(
2310 app.tr(MessageId::CtxMenuOpenFailed)
2311 .replace("{target}", &shown)
2312 .replace("{error}", &error.to_string()),
2313 StatusToastLevel::Warning,
2314 Some(5_000),
2315 );
2316 }
2317 }
2318 }
2319 ContextMenuAction::RevealPath { path } => {
2320 let Some(target) = path
2321 .to_str()
2322 .and_then(|raw| crate::tui::history::workspace_target(&app.workspace, raw))
2323 else {
2324 app.push_status_toast(
2325 app.tr(MessageId::CtxMenuEditorRefused)
2326 .replace("{path}", &path.display().to_string()),
2327 StatusToastLevel::Warning,
2328 Some(5_000),
2329 );
2330 app.needs_redraw = true;
2331 return outcome;
2332 };
2333 let shown = target
2334 .path
2335 .strip_prefix(&app.workspace)
2336 .unwrap_or(&target.path)
2337 .display()
2338 .to_string();
2339 match codewhale_runtime::browser::reveal_path(&target.path) {
2340 Ok(()) => {
2341 app.push_status_toast(
2342 app.tr(MessageId::CtxMenuLinkOpened)
2343 .replace("{target}", &shown),
2344 StatusToastLevel::Info,
2345 Some(4_000),
2346 );
2347 }
2348 Err(error) => {
2349 app.push_status_toast(
2350 app.tr(MessageId::CtxMenuOpenFailed)
2351 .replace("{target}", &shown)
2352 .replace("{error}", &error.to_string()),
2353 StatusToastLevel::Warning,
2354 Some(5_000),
2355 );
2356 }
2357 }
2358 }
2359 ContextMenuAction::HideCell { cell_index } => {
2360 app.collapsed_cells.insert(cell_index);
2361 app.show_input_hint(tr(app.ui_locale, MessageId::CtxMenuCellHidden).into_owned());
2362 }
2363 ContextMenuAction::ShowCell { cell_index } => {
2364 app.collapsed_cells.remove(&cell_index);
2365 app.show_input_hint(tr(app.ui_locale, MessageId::CtxMenuCellShown).into_owned());
2366 }
2367 ContextMenuAction::ShowAllHidden => {
2368 let count = app.collapsed_cells.len();
2369 app.collapsed_cells.clear();
2370 app.show_input_hint(
2371 tr(app.ui_locale, MessageId::CtxMenuHiddenCellsRestored)
2372 .replace("{count}", &count.to_string()),
2373 );
2374 }
2375 }
2376 app.needs_redraw = true;
2377 outcome
2378 }
2379
2380 /// Open a workspace file at a line in `$EDITOR`. The editor gets the terminal
2381 /// through the same suspend path the composer and `/hooks edit` use, one at a
2382 /// time, and we wait for it. It used to be spawned detached while the TUI
2383 /// still held raw mode, the alt screen and mouse capture (#6235).
2384 /// The path `open_file_in_editor` may hand to the editor: `path` only while it
2385 /// is still a regular file inside `workspace` reached without links
2386 /// (`history::workspace_file`), else `None`.
2387 fn editor_target(
2388 workspace: &std::path::Path,
2389 path: &std::path::Path,
2390 ) -> Option<std::path::PathBuf> {
2391 path.to_str()
2392 .and_then(|raw| crate::tui::history::workspace_file(workspace, raw))
2393 }
2394
2395 pub(crate) fn open_file_in_editor(
2396 terminal: &mut ratatui::Terminal<crate::tui::color_compat::ColorCompatBackend<std::io::Stdout>>,
2397 app: &mut App,
2398 path: &std::path::Path,
2399 line: u32,
2400 ) {
2401 // The menu checked this path when it was built; a link can be swapped in
2402 // before the click, so check again right before the editor gets it.
2403 let Some(path) = editor_target(&app.workspace, path) else {
2404 app.push_status_toast(
2405 app.tr(MessageId::CtxMenuEditorRefused)
2406 .replace("{path}", &path.display().to_string()),
2407 StatusToastLevel::Warning,
2408 Some(5_000),
2409 );
2410 return;
2411 };
2412 let path = path.as_path();
2413 let outcome = crate::tui::external_editor::spawn_editor_for_path(
2414 terminal,
2415 app.use_mouse_capture,
2416 app.use_bracketed_paste,
2417 path,
2418 Some(line),
2419 );
2420 app.needs_redraw = true;
2421 match outcome {
2422 Ok(crate::tui::external_editor::EditorOutcome::Cancelled) => {
2423 app.show_input_hint(format!("Editor exited without opening {}", path.display()));
2424 }
2425 Ok(_) => app.show_input_hint(format!("Closed editor for {}:{line}", path.display())),
2426 Err(error) => app.set_sticky_status(
2427 format!("Could not open the editor: {error}"),
2428 StatusToastLevel::Error,
2429 None,
2430 ),
2431 }
2432 }
2433
2434 pub(crate) fn selection_point_from_mouse(
2435 app: &App,
2436 mouse: MouseEvent,
2437 ) -> Option<TranscriptSelectionPoint> {
2438 selection_point_from_position(
2439 app.viewport.last_transcript_area?,
2440 mouse.column,
2441 mouse.row,
2442 app.viewport.last_transcript_top,
2443 app.viewport.last_transcript_total,
2444 app.viewport.last_transcript_padding_top,
2445 )
2446 }
2447
2448 pub(crate) fn selection_point_from_position(
2449 area: Rect,
2450 column: u16,
2451 row: u16,
2452 transcript_top: usize,
2453 transcript_total: usize,
2454 padding_top: usize,
2455 ) -> Option<TranscriptSelectionPoint> {
2456 if column < area.x
2457 || column >= area.x + area.width
2458 || row < area.y
2459 || row >= area.y + area.height
2460 {
2461 return None;
2462 }
2463
2464 if transcript_total == 0 {
2465 return None;
2466 }
2467
2468 let row = row.saturating_sub(area.y) as usize;
2469 if row < padding_top {
2470 return None;
2471 }
2472 let row = row.saturating_sub(padding_top);
2473
2474 let col = column.saturating_sub(area.x) as usize;
2475 let line_index = transcript_top
2476 .saturating_add(row)
2477 .min(transcript_total.saturating_sub(1));
2478
2479 Some(TranscriptSelectionPoint {
2480 line_index,
2481 column: col,
2482 })
2483 }
2484
2485 /// The one selection Copy, Open and Clear act on: the composer's when it has
2486 /// one, else the transcript's. The menu entries and Ctrl+C all read it here,
2487 /// so Copy cannot take the composer's text while Clear clears the
2488 /// transcript's and reports "Selection cleared".
2489 #[derive(Debug, Clone, PartialEq, Eq)]
2490 pub(crate) enum ActiveSelection {
2491 Composer(String),
2492 Transcript,
2493 }
2494
2495 pub(crate) fn active_selection(app: &App) -> Option<ActiveSelection> {
2496 let composer = app.selected_text();
2497 if !composer.is_empty() {
2498 return Some(ActiveSelection::Composer(composer));
2499 }
2500 selection_to_text(app)
2501 .is_some_and(|text| !text.is_empty())
2502 .then_some(ActiveSelection::Transcript)
2503 }
2504
2505 pub(crate) fn selection_has_content(app: &App) -> bool {
2506 active_selection(app).is_some()
2507 }
2508
2509 /// The receipt for a clipboard write. `native` is said only when a native
2510 /// clipboard took the text; a terminal (OSC 52 / tmux) write is never
2511 /// acknowledged, so its receipt says where the text went, not that it
2512 /// arrived. An asynchronous failure still replaces either receipt through
2513 /// the event loop's `poll_write_completion` drain.
2514 pub(crate) fn copy_receipt(
2515 app: &App,
2516 transport: crate::tui::clipboard::CopyTransport,
2517 native: impl Into<String>,
2518 ) -> String {
2519 match transport {
2520 crate::tui::clipboard::CopyTransport::Native => native.into(),
2521 crate::tui::clipboard::CopyTransport::Terminal => {
2522 app.tr(MessageId::ClipboardSentToTerminal).into_owned()
2523 }
2524 }
2525 }
2526
2527 pub(crate) fn report_copy_result(
2528 app: &mut App,
2529 result: anyhow::Result<crate::tui::clipboard::CopyTransport>,
2530 native: impl Into<String>,
2531 failure: impl Into<String>,
2532 ) -> bool {
2533 match result {
2534 Ok(transport) => {
2535 let text = copy_receipt(app, transport, native);
2536 app.show_copy_notice(text, StatusToastLevel::Info, 4_000);
2537 true
2538 }
2539 Err(_) => {
2540 app.show_copy_notice(failure, StatusToastLevel::Error, App::STICKY_ERROR_TTL_MS);
2541 false
2542 }
2543 }
2544 }
2545
2546 pub(crate) fn copy_failed_receipt(app: &App, error: impl std::fmt::Display) -> String {
2547 app.tr(MessageId::ClipboardCopyFailed)
2548 .replace("{error}", &error.to_string())
2549 }
2550
2551 /// Ctrl+X on a composer selection. The text is deleted only after a native
2552 /// clipboard confirmed the copy; an OSC 52 / tmux copy is never confirmed,
2553 /// so the text stays and the receipt says why.
2554 pub(crate) fn cut_selection(app: &mut App) {
2555 let sel = app.selected_text();
2556 if sel.is_empty() {
2557 return;
2558 }
2559 match app.clipboard.write_text_status(&sel) {
2560 Ok(crate::tui::clipboard::CopyTransport::Native) => {
2561 app.show_copy_notice(
2562 app.tr(MessageId::ClipboardCopied),
2563 StatusToastLevel::Info,
2564 8_000,
2565 );
2566 app.delete_selection();
2567 }
2568 Ok(crate::tui::clipboard::CopyTransport::Terminal) => {
2569 let receipt = app.tr(MessageId::ClipboardCutKeptText).into_owned();
2570 app.show_copy_notice(receipt, StatusToastLevel::Info, 8_000);
2571 }
2572 Err(error) => {
2573 let receipt = copy_failed_receipt(app, error);
2574 app.show_copy_notice(receipt, StatusToastLevel::Error, App::STICKY_ERROR_TTL_MS);
2575 }
2576 }
2577 }
2578
2579 fn open_active_selection(app: &mut App) -> bool {
2580 match active_selection(app) {
2581 Some(ActiveSelection::Composer(text)) => {
2582 let width = app
2583 .viewport
2584 .last_transcript_area
2585 .map(|area| area.width)
2586 .unwrap_or(80);
2587 app.view_stack.push(crate::tui::pager::PagerView::from_text(
2588 "Selection",
2589 &text,
2590 width.saturating_sub(2),
2591 ));
2592 true
2593 }
2594 Some(ActiveSelection::Transcript) => open_pager_for_selection(app),
2595 None => false,
2596 }
2597 }
2598
2599 fn clear_active_selection(app: &mut App) -> bool {
2600 match active_selection(app) {
2601 Some(ActiveSelection::Composer(_)) => {
2602 app.clear_selection();
2603 app.needs_redraw = true;
2604 true
2605 }
2606 Some(ActiveSelection::Transcript) => {
2607 clear_transcript_selection(app);
2608 true
2609 }
2610 None => false,
2611 }
2612 }
2613
2614 /// Branches taken by the Ctrl+C key handler. The order encodes priority and is
2615 /// the unit-tested contract for #1337 / #1367: a transcript selection always
2616 /// wins (so users learn that Ctrl+C copies when there's something to copy);
2617 /// otherwise an active turn is interrupted; otherwise a non-empty composer is
2618 /// cleared recoverably; otherwise the quit-arm flow runs.
2619 #[derive(Debug, PartialEq, Eq)]
2620 pub(crate) enum CtrlCDisposition {
2621 CopySelection,
2622 CancelTurn,
2623 ClearInput,
2624 ConfirmExit,
2625 ArmExit,
2626 }
2627
2628 pub(crate) fn ctrl_c_disposition(app: &App) -> CtrlCDisposition {
2629 if selection_has_content(app) {
2630 CtrlCDisposition::CopySelection
2631 } else if app.is_loading
2632 || app.is_compacting
2633 || app.manual_compaction_queued
2634 || app.goal_continuation_waiting
2635 {
2636 CtrlCDisposition::CancelTurn
2637 } else if !app.input.is_empty() {
2638 CtrlCDisposition::ClearInput
2639 } else if app.quit_is_armed() {
2640 CtrlCDisposition::ConfirmExit
2641 } else {
2642 CtrlCDisposition::ArmExit
2643 }
2644 }
2645
2646 /// Normalize the raw Ctrl+C control byte to canonical `Ctrl+C`.
2647 ///
2648 /// In PTY/raw-mode the terminal driver delivers Ctrl+C as the literal byte
2649 /// `0x03` (the ETX control character). crossterm usually decodes that to
2650 /// `Char('c') + CONTROL`, but some terminal / kitty-keyboard-protocol
2651 /// combinations surface it as `Char('\u{3}')` instead, where it slips past the
2652 /// `Char('c') + CONTROL` arm of the key handler and never reaches the
2653 /// quit-arm flow (#4090). Rewriting every encoding of Ctrl+C to the canonical
2654 /// form here keeps the double-press-to-exit behavior consistent across PTY,
2655 /// raw-mode, and kitty-enhanced terminals.
2656 pub(crate) fn normalize_raw_ctrl_c(key: &mut KeyEvent) {
2657 if matches!(key.code, KeyCode::Char('\u{3}')) {
2658 key.code = KeyCode::Char('c');
2659 key.modifiers.insert(KeyModifiers::CONTROL);
2660 }
2661 }
2662
2663 pub(crate) fn copy_active_selection(app: &mut App) {
2664 // Composer selection takes priority.
2665 let sel = app.selected_text();
2666 if !sel.is_empty() {
2667 match app.clipboard.write_text_status(&sel) {
2668 Ok(transport) => {
2669 let receipt = copy_receipt(app, transport, app.tr(MessageId::ClipboardCopied));
2670 app.show_copy_notice(receipt, StatusToastLevel::Info, 8_000);
2671 app.clear_selection();
2672 }
2673 Err(error) => {
2674 let receipt = copy_failed_receipt(app, error);
2675 app.show_copy_notice(receipt, StatusToastLevel::Error, App::STICKY_ERROR_TTL_MS);
2676 }
2677 }
2678 return;
2679 }
2680 if !app.viewport.transcript_selection.is_active() {
2681 app.show_copy_notice(
2682 app.tr(MessageId::CtxMenuNoSelectionToCopy).into_owned(),
2683 StatusToastLevel::Info,
2684 4_000,
2685 );
2686 return;
2687 }
2688 // Markdown source first (#6156): project every intersected cell through
2689 // the canonical clean-copy path. Falls back to rendered text when the
2690 // `[tui] selection_copy_markdown` key is off or no cell metadata
2691 // intersects the range.
2692 let payload = if app.viewport.selection_copy_markdown {
2693 selection_to_markdown(app).map(|(text, cells)| (text, Some(cells)))
2694 } else {
2695 None
2696 };
2697 let payload = payload.or_else(|| {
2698 selection_to_text(app)
2699 .filter(|text| !text.is_empty())
2700 .map(|text| (text, None))
2701 });
2702 if let Some((text, markdown_cells)) = payload {
2703 match app.clipboard.write_text_status(&text) {
2704 Ok(transport) => {
2705 let receipt = match (transport, markdown_cells) {
2706 (crate::tui::clipboard::CopyTransport::Native, Some(cells)) => app
2707 .tr(MessageId::SelectionCopiedAsMarkdown)
2708 .replace("{count}", &cells.to_string()),
2709 (transport, _) => {
2710 copy_receipt(app, transport, app.tr(MessageId::ClipboardCopied))
2711 }
2712 };
2713 app.show_copy_notice(receipt, StatusToastLevel::Info, 8_000);
2714 }
2715 Err(error) => {
2716 let receipt = copy_failed_receipt(app, error);
2717 app.show_copy_notice(receipt, StatusToastLevel::Error, App::STICKY_ERROR_TTL_MS);
2718 }
2719 }
2720 } else {
2721 clear_transcript_selection(app);
2722 app.show_copy_notice(
2723 tr(app.ui_locale, MessageId::CtxMenuNoSelectionToCopy).into_owned(),
2724 StatusToastLevel::Info,
2725 4_000,
2726 );
2727 }
2728 }
2729
2730 /// Whether a drag selection covers every cell it touches end to end (#6228).
2731 ///
2732 /// Two checks: the edge columns must reach the content edges on the boundary
2733 /// lines, and the line range must not cut a cell in half at either end.
2734 /// Middle lines are fully covered by construction, and cells render as
2735 /// contiguous spans, so the two edge cells decide for the whole range.
2736 fn selection_covers_cells_fully(
2737 app: &App,
2738 start: &TranscriptSelectionPoint,
2739 end: &TranscriptSelectionPoint,
2740 start_index: usize,
2741 end_index: usize,
2742 ) -> bool {
2743 let (first_head, _) = match content_column_span(app, start_index) {
2744 Some(span) => span,
2745 None => return false,
2746 };
2747 if start.column > first_head {
2748 return false;
2749 }
2750 let (_, last_tail) = match content_column_span(app, end_index) {
2751 Some(span) => span,
2752 None => return false,
2753 };
2754 if end.column < last_tail {
2755 return false;
2756 }
2757 let line_meta = app.viewport.transcript_cache.line_meta();
2758 let mut edge_cells = (start_index..=end_index).filter_map(|line_index| {
2759 line_meta
2760 .get(line_index)
2761 .and_then(|meta| meta.cell_line())
2762 .map(|(cell_index, _)| cell_index)
2763 });
2764 let Some(first_cell) = edge_cells.next() else {
2765 return false;
2766 };
2767 let last_cell = edge_cells.next_back().unwrap_or(first_cell);
2768 [first_cell, last_cell].into_iter().all(|cell| {
2769 let mut span = line_meta
2770 .iter()
2771 .enumerate()
2772 .filter_map(|(line_index, meta)| {
2773 meta.cell_line()
2774 .filter(|(cell_index, _)| *cell_index == cell)
2775 .map(|_| line_index)
2776 });
2777 match (span.next(), span.next_back()) {
2778 (Some(cell_first), Some(cell_last)) => {
2779 cell_first >= start_index && cell_last <= end_index
2780 }
2781 (Some(only), None) => start_index <= only && only <= end_index,
2782 (None, _) => false,
2783 }
2784 })
2785 }
2786
2787 /// Rendered-column span of selectable content on one transcript cache line.
2788 ///
2789 /// Mirrors the prefix math in [`selection_to_text`]: rail decorations plus
2790 /// copy-only prefixes are visual, so content runs from their combined width
2791 /// to that width plus the content's display width.
2792 fn content_column_span(app: &App, line_index: usize) -> Option<(usize, usize)> {
2793 let cache = &app.viewport.transcript_cache;
2794 let full_width = text_visible_width(&line_to_plain(cache.lines().get(line_index)?));
2795 let rail_width = cache.rail_prefix_width(line_index).min(full_width);
2796 let copy_prefix = cache
2797 .line_meta()
2798 .get(line_index)
2799 .map(|meta| meta.copy_prefix_width())
2800 .unwrap_or(0)
2801 .min(full_width.saturating_sub(rail_width));
2802 let head = rail_width.saturating_add(copy_prefix);
2803 let tail = head.saturating_add(
2804 full_width
2805 .saturating_sub(rail_width)
2806 .saturating_sub(copy_prefix),
2807 );
2808 Some((head, tail))
2809 }
2810
2811 /// Project a transcript drag selection to Markdown source (#6156).
2812 ///
2813 /// Collects every history cell intersecting the selection's rendered line
2814 /// range, in order, and serializes each through
2815 /// `history_cell_to_clipboard_text` — the same canonical projection Ctrl-Y
2816 /// and `/copy` use — joined with a blank line. Returns the payload plus the
2817 /// projected cell count for the toast.
2818 ///
2819 /// Markdown source is only truthful for whole cells, so a selection that
2820 /// cuts a cell in half is not projected here at all — it keeps its exact
2821 /// rendered text through the caller's [`selection_to_text`] fallback (#6228).
2822 ///
2823 /// Returns `None` when the selection is a fragment, when no cell metadata
2824 /// intersects the range, or when every projection is blank.
2825 pub(crate) fn selection_to_markdown(app: &App) -> Option<(String, usize)> {
2826 let (start, end) = app.viewport.transcript_selection.ordered_endpoints()?;
2827 let lines = app.viewport.transcript_cache.lines();
2828 if lines.is_empty() {
2829 return None;
2830 }
2831 let end_index = end.line_index.min(lines.len().saturating_sub(1));
2832 let start_index = start.line_index.min(end_index);
2833 if !selection_covers_cells_fully(app, &start, &end, start_index, end_index) {
2834 return None;
2835 }
2836 let line_meta = app.viewport.transcript_cache.line_meta();
2837 let width = app
2838 .viewport
2839 .last_transcript_area
2840 .map(|area| area.width)
2841 .unwrap_or(80);
2842 let mut rendered = Vec::new();
2843 for line_index in start_index..=end_index {
2844 if let Some((cell_index, _)) = line_meta.get(line_index).and_then(|meta| meta.cell_line())
2845 && !rendered.contains(&cell_index)
2846 {
2847 rendered.push(cell_index);
2848 }
2849 }
2850 let mut seen_original = Vec::new();
2851 let mut parts = Vec::new();
2852 for rendered_index in rendered {
2853 let original = app.original_cell_index_for_rendered(rendered_index);
2854 if seen_original.contains(&original) {
2855 continue;
2856 }
2857 seen_original.push(original);
2858 let Some(cell) = app.cell_at_virtual_index(original) else {
2859 continue;
2860 };
2861 let text = history_cell_to_clipboard_text(cell, width);
2862 if !text.trim().is_empty() {
2863 parts.push(text);
2864 }
2865 }
2866 if parts.is_empty() {
2867 return None;
2868 }
2869 let count = parts.len();
2870 Some((parts.join("\n\n"), count))
2871 }
2872 pub(crate) fn clear_transcript_selection(app: &mut App) {
2873 app.needs_redraw |= app.viewport.transcript_selection.is_active();
2874 app.viewport.transcript_selection.clear();
2875 }
2876 pub(crate) fn selection_to_text(app: &App) -> Option<String> {
2877 let (start, end) = app.viewport.transcript_selection.ordered_endpoints()?;
2878 let lines = app.viewport.transcript_cache.lines();
2879 if lines.is_empty() {
2880 return None;
2881 }
2882 let end_index = end.line_index.min(lines.len().saturating_sub(1));
2883 let start_index = start.line_index.min(end_index);
2884
2885 let line_meta = app.viewport.transcript_cache.line_meta();
2886 let mut selected = String::new();
2887 let mut separator_before = None;
2888 #[allow(clippy::needless_range_loop)]
2889 for line_index in start_index..=end_index {
2890 if let Some(separator) = separator_before {
2891 selected.push_str(separator);
2892 }
2893 // Rail-prefix decorations are stored as cache metadata rather than
2894 // detected from glyphs, so new decoration types are covered without
2895 // changes to the copy path (#1163).
2896 let rail_width = app.viewport.transcript_cache.rail_prefix_width(line_index);
2897 // Convert the rendered line to plain text (strips OSC-8), then
2898 // slice off the rail prefix so subsequent column offsets operate
2899 // on content-only text.
2900 let full_text = line_to_plain(&lines[line_index]);
2901 // Selection columns are painted terminal cells, where control
2902 // characters are invisible (ratatui strips them). Measure and slice
2903 // in that space so columns after a tab stay aligned with what the
2904 // user dragged over; the fixed-width fallback would shift every
2905 // downstream column.
2906 let line_after_rail = if rail_width > 0 {
2907 slice_visible_columns(&full_text, rail_width, text_visible_width(&full_text))
2908 } else {
2909 full_text
2910 };
2911 let line_after_rail_width = text_visible_width(&line_after_rail);
2912 let copy_prefix_width = line_meta
2913 .get(line_index)
2914 .map(|meta| meta.copy_prefix_width())
2915 .unwrap_or(0)
2916 .min(line_after_rail_width);
2917 let line_text = if copy_prefix_width > 0 {
2918 slice_visible_columns(&line_after_rail, copy_prefix_width, line_after_rail_width)
2919 } else {
2920 line_after_rail
2921 };
2922 let visual_prefix_width = rail_width.saturating_add(copy_prefix_width);
2923 let line_width = text_visible_width(&line_text);
2924 // Selection coordinates are recorded in rendered-column space, which
2925 // includes visual prefixes. Add them back so the column window maps
2926 // correctly into copy-only text.
2927 let (raw_col_start, raw_col_end) = if start_index == end_index {
2928 (start.column, end.column)
2929 } else if line_index == start_index {
2930 (start.column, line_width.saturating_add(visual_prefix_width))
2931 } else if line_index == end_index {
2932 (0, end.column)
2933 } else {
2934 (0, line_width.saturating_add(visual_prefix_width))
2935 };
2936
2937 let col_start = raw_col_start
2938 .saturating_sub(visual_prefix_width)
2939 .min(line_width);
2940 let col_end = raw_col_end
2941 .saturating_sub(visual_prefix_width)
2942 .min(line_width);
2943
2944 let slice = slice_visible_columns(&line_text, col_start, col_end);
2945 selected.push_str(&slice);
2946 separator_before = line_meta
2947 .get(line_index)
2948 .map(|meta| meta.copy_separator_after().as_str())
2949 .or(Some("\n"));
2950 }
2951 Some(selected)
2952 }
2953
2954 #[cfg(test)]
2955 mod tests {
2956 use std::time::Instant;
2957
2958 use super::{
2959 agent_transcript_text, build_context_menu_entries, handle_composer_mouse,
2960 handle_mouse_event, sidebar_click_action,
2961 };
2962 use crate::tui::app::{
2963 App, SidebarHoverRow, SidebarHoverSection, SidebarRowAction, TuiOptions,
2964 };
2965 use crate::tui::tideline::{
2966 ContextBudgetSnapshot, InspectDetail, InteractionAction, InteractionFocus,
2967 InteractionTarget, InteractionTargetId,
2968 };
2969 use crate::tui::views::{ContextMenuAction, ModalKind, ViewEvent};
2970 use codewhale_models::Role;
2971 use codewhale_models::{ContentBlock, Message};
2972 use codewhale_runtime::config::Config;
2973 use crossterm::event::{
2974 KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
2975 };
2976 use ratatui::layout::Rect;
2977 use serde_json::json;
2978 use std::path::PathBuf;
2979 use tempfile::tempdir;
2980
2981 fn last_toast(app: &App) -> Option<&str> {
2982 app.status_toasts.back().map(|toast| toast.text.as_str())
2983 }
2984
2985 pub(super) fn create_test_app() -> App {
2986 let options = TuiOptions {
2987 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
2988 };
2989 let mut app = App::new(options, &Config::default());
2990 // Legacy strip geometry (see ui.rs); Bottom default has its own tests.
2991 app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Top;
2992 app
2993 }
2994
2995 #[test]
2996 fn plugin_review_click_opens_inventory_and_emits_no_install_or_trust_command() {
2997 let _lock = crate::test_support::lock_test_env();
2998 let root = tempdir().unwrap();
2999 let _home =
3000 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path().join("home"));
3001 let mut app = App::new(
3002 crate::tui::test_support::test_tui_options(root.path()),
3003 &Config::default(),
3004 );
3005 app.surface_plugin_review_request("catalog-only", "/plugin install arbitrary-source");
3006 assert!(app.plugin_cta.phase.is_visible());
3007 let before = app.plugin_registry.list().len();
3008 let area = Rect::new(0, 0, 140, 1);
3009 let mut buffer = ratatui::buffer::Buffer::empty(area);
3010 crate::tui::plugin_suggestions::draw_plugin_cta(&mut app, area, &mut buffer);
3011 assert!(
3012 super::handle_plugin_cta_mouse(&mut app, left_click(0, 0))
3013 .unwrap()
3014 .is_empty()
3015 );
3016 assert!(app.view_stack.is_empty());
3017 assert!(app.plugin_cta.phase.is_visible());
3018 let button = app.viewport.last_plugin_cta_review_area.unwrap();
3019 let events =
3020 super::handle_plugin_cta_mouse(&mut app, left_click(button.x, button.y)).unwrap();
3021 assert!(
3022 events.is_empty(),
3023 "review navigation must not dispatch commands"
3024 );
3025 assert_eq!(app.view_stack.top_kind(), Some(ModalKind::Extensions));
3026 assert!(!app.plugin_cta.phase.is_visible());
3027 assert_eq!(app.plugin_registry.list().len(), before);
3028 assert!(app.plugin_registry.get("catalog-only").is_none());
3029 }
3030
3031 #[test]
3032 fn workbar_click_opens_the_workflows_view() {
3033 let mut app = create_test_app();
3034 app.workflow_runs
3035 .push(crate::tui::widgets::workflow_panel::WorkflowPanel::new(
3036 "workflow_1",
3037 "audit",
3038 1,
3039 ));
3040 app.viewport.last_workbar_area = Some(Rect::new(0, 20, 80, 1));
3041 assert!(!super::handle_workbar_mouse(&mut app, left_click(10, 5)));
3042 assert!(app.view_stack.is_empty());
3043 assert!(super::handle_workbar_mouse(&mut app, left_click(10, 20)));
3044 assert_eq!(
3045 app.view_stack.top_kind(),
3046 Some(crate::tui::views::ModalKind::WorkflowsManager)
3047 );
3048 }
3049
3050 #[test]
3051 fn composer_click_maps_tabs_as_painted() {
3052 // A tab paints no cells, so clicking the visible char after one
3053 // must resolve past it instead of stopping on the tab itself.
3054 let mut app = create_test_app();
3055 let area = Rect::new(0, 0, 80, 10);
3056 app.input = "a\tb".to_string();
3057 assert_eq!(super::mouse_pos_to_char_index(&app, 1, 0, area), Some(2));
3058 app.input = "\ta".to_string();
3059 assert_eq!(super::mouse_pos_to_char_index(&app, 0, 0, area), Some(1));
3060 }
3061
3062 fn hover_row(row_y: u16, action: Option<&str>) -> SidebarHoverRow {
3063 SidebarHoverRow {
3064 row_y,
3065 display_text: "row".to_string(),
3066 full_text: "row".to_string(),
3067 detail: None,
3068 is_truncated: false,
3069 click_action: action.map(|action| SidebarRowAction::Command(action.to_string())),
3070 stop_action: None,
3071 stop_zone_start_col: None,
3072 stop_zone_end_col: None,
3073 }
3074 }
3075
3076 fn hover_row_with_stop(row_y: u16, action: &str, stop_action: &str) -> SidebarHoverRow {
3077 SidebarHoverRow {
3078 row_y,
3079 display_text: "job row [x]".to_string(),
3080 full_text: "job row [x]".to_string(),
3081 detail: None,
3082 is_truncated: false,
3083 click_action: Some(SidebarRowAction::Command(action.to_string())),
3084 stop_action: Some(SidebarRowAction::Command(stop_action.to_string())),
3085 stop_zone_start_col: Some(68),
3086 stop_zone_end_col: Some(71),
3087 }
3088 }
3089
3090 fn action_command(action: Option<SidebarRowAction>) -> Option<String> {
3091 match action? {
3092 SidebarRowAction::Command(command) => Some(command),
3093 _ => None,
3094 }
3095 }
3096
3097 fn left_click(column: u16, row: u16) -> MouseEvent {
3098 MouseEvent {
3099 kind: MouseEventKind::Down(MouseButton::Left),
3100 column,
3101 row,
3102 modifiers: KeyModifiers::NONE,
3103 }
3104 }
3105
3106 fn right_click(column: u16, row: u16) -> MouseEvent {
3107 MouseEvent {
3108 kind: MouseEventKind::Down(MouseButton::Right),
3109 column,
3110 row,
3111 modifiers: KeyModifiers::NONE,
3112 }
3113 }
3114
3115 fn mouse_move(column: u16, row: u16) -> MouseEvent {
3116 MouseEvent {
3117 kind: MouseEventKind::Moved,
3118 column,
3119 row,
3120 modifiers: KeyModifiers::NONE,
3121 }
3122 }
3123
3124 #[test]
3125 fn the_launch_card_does_not_swallow_the_rest_of_the_screen() {
3126 // Founder live-test: "the clickability and the mouse pointing thing
3127 // isn't working". While the opening screen was a separate surface it
3128 // was right for it to consume every mouse event and return; the
3129 // moment it became content on the ordinary screen that gate made
3130 // scrolling, the composer and the work surface unreachable. A click
3131 // that misses the card's rows must fall through.
3132 let mut app = create_test_app();
3133 app.launch.visible = true;
3134 app.launch.row_hitboxes = vec![(
3135 crate::tui::app::LaunchRowId::NewSession,
3136 Rect::new(2, 5, 30, 1),
3137 )];
3138 app.viewport.last_transcript_area = Some(Rect::new(0, 0, 80, 20));
3139 app.viewport.pending_scroll_delta = 0;
3140
3141 // A wheel tick on the launch screen still scrolls.
3142 handle_mouse_event(
3143 &mut app,
3144 MouseEvent {
3145 kind: MouseEventKind::ScrollDown,
3146 column: 10,
3147 row: 10,
3148 modifiers: KeyModifiers::NONE,
3149 },
3150 Instant::now(),
3151 );
3152 assert_ne!(
3153 app.viewport.pending_scroll_delta, 0,
3154 "the wheel must reach the transcript on the opening screen"
3155 );
3156
3157 // A click away from the card's rows starts no launch action.
3158 app.pending_launch_action = None;
3159 handle_mouse_event(&mut app, left_click(60, 15), Instant::now());
3160 assert_eq!(
3161 app.pending_launch_action, None,
3162 "a click off the card must not be read as a card action"
3163 );
3164
3165 // A click on a row still runs it.
3166 handle_mouse_event(&mut app, left_click(4, 5), Instant::now());
3167 assert_eq!(
3168 app.pending_launch_action,
3169 Some(crate::tui::underwater::LaunchAction::NewSession),
3170 "the card's own rows still work"
3171 );
3172 }
3173
3174 #[test]
3175 fn clicking_a_recent_row_opens_the_resume_confirmation_popup() {
3176 // Founder live-test: "you just click it and boom you're there ... you
3177 // don't realize it's happening", then, on the first fix: "the
3178 // resuming confirmation needs to be a popup not something in the
3179 // composer that's even more confusing". Resuming replaces the whole
3180 // session context, so the click opens a popup that names the session
3181 // and asks; nothing resumes until that is confirmed.
3182 let mut app = create_test_app();
3183 app.launch.visible = true;
3184 app.launch.recent = vec![crate::tui::app::LaunchRecentSession {
3185 id: "sess-1".to_string(),
3186 title: "refactor the parser".to_string(),
3187 updated_at: chrono::Utc::now(),
3188 message_count: 12,
3189 interrupted: false,
3190 }];
3191 app.launch.row_hitboxes = vec![(
3192 crate::tui::app::LaunchRowId::Recent("sess-1".to_string()),
3193 Rect::new(2, 5, 30, 1),
3194 )];
3195 app.pending_launch_action = None;
3196
3197 handle_mouse_event(&mut app, left_click(4, 5), Instant::now());
3198 assert_eq!(
3199 app.pending_launch_action, None,
3200 "the click must not resume anything on its own"
3201 );
3202 assert_eq!(
3203 app.view_stack.top_kind(),
3204 Some(crate::tui::views::ModalKind::LaunchResumeConfirm),
3205 "it opens the confirmation popup instead"
3206 );
3207 assert!(
3208 app.launch.status.is_none(),
3209 "and nothing is written over the composer dock"
3210 );
3211 }
3212
3213 #[test]
3214 fn a_new_session_row_still_takes_one_click() {
3215 // Only resuming discards context, so New session keeps its single
3216 // click; adding a confirm step there would be friction for nothing.
3217 let mut app = create_test_app();
3218 app.launch.visible = true;
3219 app.launch.row_hitboxes = vec![(
3220 crate::tui::app::LaunchRowId::NewSession,
3221 Rect::new(2, 5, 30, 1),
3222 )];
3223 app.pending_launch_action = None;
3224
3225 handle_mouse_event(&mut app, left_click(4, 5), Instant::now());
3226 assert_eq!(
3227 app.pending_launch_action,
3228 Some(crate::tui::underwater::LaunchAction::NewSession),
3229 "New session runs on the first click"
3230 );
3231 }
3232
3233 #[test]
3234 fn idle_pointer_enter_and_leave_request_hover_redraws() {
3235 let _guard = crate::tui::hover_layer::HOVER_TEST_LOCK.lock().unwrap();
3236 crate::tui::hover_layer::clear_pointer();
3237 crate::tui::hover_layer::begin_frame();
3238 crate::tui::hover_layer::register_rect(
3239 crate::tui::hover_hit::HoverTargetKind::TruncatedText,
3240 Rect::new(10, 5, 20, 1),
3241 "full clipped row",
3242 false,
3243 );
3244
3245 let mut app = create_test_app();
3246 app.launch.visible = false;
3247 app.needs_redraw = false;
3248 handle_mouse_event(&mut app, mouse_move(12, 5), Instant::now());
3249 assert!(
3250 app.needs_redraw,
3251 "entering a target must repaint while idle"
3252 );
3253 assert_eq!(
3254 crate::tui::hover_layer::current_hover().map(|hit| hit.kind),
3255 Some(crate::tui::hover_hit::HoverTargetKind::TruncatedText)
3256 );
3257
3258 app.needs_redraw = false;
3259 handle_mouse_event(&mut app, mouse_move(40, 5), Instant::now());
3260 assert!(app.needs_redraw, "leaving a target must clear its popover");
3261 assert!(crate::tui::hover_layer::current_hover().is_none());
3262 crate::tui::hover_layer::clear_pointer();
3263 }
3264
3265 #[test]
3266 fn slash_autocomplete_click_selects_and_second_click_applies() {
3267 let mut app = create_test_app();
3268 app.launch.visible = false;
3269 app.work_surface.last_area = None;
3270 app.input = "/he".to_string();
3271 app.cursor_position = app.input.chars().count();
3272 app.slash_menu_hidden = false;
3273 app.slash_menu_selected = 0;
3274 // Simulate two painted rows from ComposerWidget.
3275 app.viewport.last_composer_area = Some(Rect::new(0, 18, 80, 6));
3276 *app.viewport.last_slash_menu_hitboxes.borrow_mut() =
3277 vec![(0, Rect::new(1, 20, 78, 1)), (1, Rect::new(1, 21, 78, 1))];
3278
3279 assert!(
3280 handle_composer_mouse(&mut app, left_click(5, 21), Instant::now()),
3281 "slash row click must be consumed by the composer"
3282 );
3283 assert_eq!(
3284 app.slash_menu_selected, 1,
3285 "click on another row highlights it"
3286 );
3287 let before = app.input.clone();
3288 assert_eq!(
3289 before, "/he",
3290 "select-only click must not rewrite the composer"
3291 );
3292
3293 assert!(handle_composer_mouse(
3294 &mut app,
3295 left_click(5, 21),
3296 Instant::now()
3297 ));
3298 assert_ne!(app.input, before, "click on the highlighted row applies it");
3299 assert!(
3300 app.input.starts_with('/'),
3301 "applied slash entry must replace the composer: {:?}",
3302 app.input
3303 );
3304 }
3305
3306 #[test]
3307 fn slash_autocomplete_wheel_moves_selection() {
3308 let mut app = create_test_app();
3309 app.launch.visible = false;
3310 app.work_surface.last_area = None;
3311 app.input = "/he".to_string();
3312 app.cursor_position = app.input.chars().count();
3313 app.slash_menu_hidden = false;
3314 app.slash_menu_selected = 0;
3315 app.viewport.last_composer_area = Some(Rect::new(0, 18, 80, 6));
3316 *app.viewport.last_slash_menu_hitboxes.borrow_mut() =
3317 vec![(0, Rect::new(1, 20, 78, 1)), (1, Rect::new(1, 21, 78, 1))];
3318 let entries = crate::tui::slash_menu::visible_slash_menu_entries(&app, 128);
3319 assert!(entries.len() >= 2, "prefix must offer multiple entries");
3320
3321 assert!(handle_composer_mouse(
3322 &mut app,
3323 MouseEvent {
3324 kind: MouseEventKind::ScrollDown,
3325 column: 5,
3326 row: 20,
3327 modifiers: KeyModifiers::NONE,
3328 },
3329 Instant::now()
3330 ));
3331 assert_eq!(app.slash_menu_selected, 1);
3332
3333 assert!(handle_composer_mouse(
3334 &mut app,
3335 MouseEvent {
3336 kind: MouseEventKind::ScrollUp,
3337 column: 5,
3338 row: 20,
3339 modifiers: KeyModifiers::NONE,
3340 },
3341 Instant::now()
3342 ));
3343 assert_eq!(app.slash_menu_selected, 0);
3344 }
3345
3346 #[test]
3347 fn active_composer_send_click_queues_the_keyboard_submit_chord() {
3348 let mut app = create_test_app();
3349 app.launch.visible = false;
3350 app.composer_border = true;
3351 app.input = "ship it".to_string();
3352 app.cursor_position = app.input.chars().count();
3353 let area = Rect::new(0, 20, 80, 4);
3354 app.viewport.last_composer_area = Some(area);
3355 // Match the frame's submit-aware input plane: x=74 stays blank,
3356 // then the shared `[↵]` target begins at x=75.
3357 app.viewport.last_composer_content = Some(Rect::new(1, 21, 73, 2));
3358 let submit = crate::tui::widgets::active_composer_submit_rect(&app, area)
3359 .expect("enclosed composer submit");
3360
3361 handle_mouse_event(&mut app, left_click(submit.x, submit.y), Instant::now());
3362 assert_eq!(
3363 app.pending_composer_submit,
3364 Some(crate::tui::app::ComposerSubmitChord::Enter)
3365 );
3366 assert_eq!(app.input, "ship it");
3367 assert_eq!(app.cursor_position, app.input.chars().count());
3368
3369 app.pending_composer_submit = None;
3370 handle_mouse_event(&mut app, left_click(area.x + 4, area.y + 1), Instant::now());
3371 assert_eq!(app.pending_composer_submit, None);
3372
3373 app.input.clear();
3374 app.cursor_position = 0;
3375 handle_mouse_event(&mut app, left_click(submit.x, submit.y), Instant::now());
3376 assert_eq!(app.pending_composer_submit, None);
3377 assert!(app.input.is_empty());
3378 }
3379
3380 #[test]
3381 fn context_meter_click_uses_the_same_inspector_as_the_keyboard_shortcut() {
3382 let mut app = create_test_app();
3383 app.launch.visible = false;
3384 app.viewport
3385 .interaction_targets
3386 .register(InteractionTarget {
3387 id: InteractionTargetId::HEADER_CONTEXT,
3388 area: Rect::new(52, 0, 20, 1),
3389 focus: InteractionFocus::Direct,
3390 keyboard_action: Some(InteractionAction::InspectContext),
3391 mouse_action: Some(InteractionAction::InspectContext),
3392 inspect_detail: InspectDetail::ContextBudget(ContextBudgetSnapshot {
3393 used_tokens: 3_000,
3394 max_tokens: 10_000,
3395 percent_basis_points: 3_000,
3396 }),
3397 });
3398
3399 handle_mouse_event(&mut app, left_click(60, 0), Instant::now());
3400
3401 assert_eq!(app.view_stack.top_kind(), Some(ModalKind::ContextInspector));
3402 assert!(
3403 crate::tui::shell_key_routing::is_context_inspector_shortcut(&KeyEvent::new(
3404 KeyCode::Char('c'),
3405 KeyModifiers::ALT
3406 ))
3407 );
3408 }
3409
3410 #[test]
3411 fn topbar_route_click_emits_provider_picker_request() {
3412 let mut app = create_test_app();
3413 // The launch screen shares the same header, so this specifically
3414 // protects against its old catch-all mouse route swallowing the
3415 // topbar affordance before it reached the event handler.
3416 app.launch.visible = true;
3417 app.viewport
3418 .interaction_targets
3419 .register(InteractionTarget {
3420 id: InteractionTargetId::HEADER_ROUTE,
3421 area: Rect::new(20, 0, 24, 1),
3422 focus: InteractionFocus::Direct,
3423 keyboard_action: Some(InteractionAction::OpenProviderPicker),
3424 mouse_action: Some(InteractionAction::OpenProviderPicker),
3425 inspect_detail: InspectDetail::Route,
3426 });
3427
3428 let events = handle_mouse_event(&mut app, left_click(24, 0), Instant::now());
3429
3430 assert!(matches!(
3431 events.as_slice(),
3432 [ViewEvent::TopbarRoutePickerRequested]
3433 ));
3434 assert!(app.view_stack.is_empty());
3435 }
3436
3437 #[test]
3438 fn context_menu_keeps_paste_first_outside_sidebar() {
3439 let mut app = create_test_app();
3440 app.work_surface.last_area = Some(Rect::new(60, 4, 20, 6));
3441
3442 let entries = build_context_menu_entries(&app, right_click(10, 4));
3443
3444 assert!(matches!(
3445 entries.first().map(|entry| &entry.action),
3446 Some(ContextMenuAction::Paste)
3447 ));
3448 }
3449
3450 #[test]
3451 fn sidebar_context_menu_omits_paste_without_row_action() {
3452 let mut app = create_test_app();
3453 app.work_surface.last_area = Some(Rect::new(60, 4, 20, 6));
3454 app.sidebar_hover.sections.push(SidebarHoverSection {
3455 content_area: Rect::new(60, 4, 20, 6),
3456 lines: vec!["header".to_string()],
3457 rows: vec![hover_row(4, None)],
3458 });
3459
3460 let entries = build_context_menu_entries(&app, right_click(65, 4));
3461
3462 assert!(
3463 !entries
3464 .iter()
3465 .any(|entry| matches!(entry.action, ContextMenuAction::Paste)),
3466 "sidebar menu should not offer paste: {entries:?}"
3467 );
3468 }
3469
3470 #[test]
3471 fn sidebar_context_menu_runs_clickable_row_action() {
3472 let mut app = create_test_app();
3473 app.work_surface.last_area = Some(Rect::new(60, 4, 20, 6));
3474 app.sidebar_hover.sections.push(SidebarHoverSection {
3475 content_area: Rect::new(60, 4, 20, 6),
3476 lines: vec!["job row".to_string()],
3477 rows: vec![hover_row(4, Some("/jobs show shell_x"))],
3478 });
3479
3480 let entries = build_context_menu_entries(&app, right_click(65, 4));
3481
3482 // The row's own command, named, and run as the same typed row action
3483 // a left click runs — not a free-form command string.
3484 let first = entries.first().expect("sidebar row should have menu");
3485 assert_eq!(first.label, "Run /jobs show shell_x");
3486 assert_eq!(
3487 first.action,
3488 ContextMenuAction::Row(SidebarRowAction::Command("/jobs show shell_x".to_string()))
3489 );
3490 assert!(
3491 !entries
3492 .iter()
3493 .any(|entry| matches!(entry.action, ContextMenuAction::Paste)),
3494 "clickable sidebar menu should not offer paste: {entries:?}"
3495 );
3496 }
3497
3498 #[test]
3499 fn sidebar_click_resolves_row_actions_inside_section() {
3500 let mut app = create_test_app();
3501 app.sidebar_hover.sections.push(SidebarHoverSection {
3502 content_area: Rect::new(60, 4, 20, 6),
3503 lines: vec![
3504 "header".to_string(),
3505 "job row".to_string(),
3506 "job detail".to_string(),
3507 "agent row".to_string(),
3508 ],
3509 rows: vec![
3510 hover_row(4, None),
3511 hover_row(5, Some("/jobs show shell_x")),
3512 hover_row(6, Some("/jobs cancel shell_x")),
3513 SidebarHoverRow {
3514 row_y: 7,
3515 display_text: "agent row".to_string(),
3516 full_text: "agent row".to_string(),
3517 detail: None,
3518 is_truncated: false,
3519 click_action: Some(SidebarRowAction::OpenAgentDetail {
3520 agent_id: "agent_123".to_string(),
3521 }),
3522 stop_action: None,
3523 stop_zone_start_col: None,
3524 stop_zone_end_col: None,
3525 },
3526 ],
3527 });
3528
3529 assert_eq!(
3530 action_command(sidebar_click_action(&app, left_click(65, 5))).as_deref(),
3531 Some("/jobs show shell_x"),
3532 "job label row resolves to its show action"
3533 );
3534 assert_eq!(
3535 action_command(sidebar_click_action(&app, left_click(79, 6))).as_deref(),
3536 Some("/jobs cancel shell_x"),
3537 "job detail row resolves to its cancel action"
3538 );
3539 assert!(matches!(
3540 sidebar_click_action(&app, left_click(60, 7)),
3541 Some(SidebarRowAction::OpenAgentDetail { agent_id })
3542 if agent_id == "agent_123"
3543 ));
3544 assert_eq!(
3545 sidebar_click_action(&app, left_click(65, 4)),
3546 None,
3547 "header row has no action"
3548 );
3549 }
3550
3551 #[test]
3552 fn sidebar_click_routes_inline_stop_zone_before_row_action() {
3553 let mut app = create_test_app();
3554 app.work_surface.last_area = Some(Rect::new(60, 4, 20, 4));
3555 app.sidebar_hover.sections.push(SidebarHoverSection {
3556 content_area: Rect::new(60, 4, 20, 4),
3557 lines: vec!["job row [x]".to_string()],
3558 rows: vec![hover_row_with_stop(
3559 4,
3560 "/jobs show shell_x",
3561 "/jobs cancel shell_x",
3562 )],
3563 });
3564
3565 assert_eq!(
3566 action_command(sidebar_click_action(&app, left_click(62, 4))).as_deref(),
3567 Some("/jobs show shell_x"),
3568 "clicking the label opens the job"
3569 );
3570 assert_eq!(
3571 action_command(sidebar_click_action(&app, left_click(69, 4))).as_deref(),
3572 Some("/jobs cancel shell_x"),
3573 "clicking [x] cancels the job"
3574 );
3575 }
3576
3577 #[test]
3578 fn sidebar_click_routes_agent_inline_stop_zone_before_peek_action() {
3579 let mut app = create_test_app();
3580 app.work_surface.last_area = Some(Rect::new(60, 4, 24, 4));
3581 app.sidebar_hover.sections.push(SidebarHoverSection {
3582 content_area: Rect::new(60, 4, 24, 4),
3583 lines: vec!["[~] worker Agent 1 [x]".to_string()],
3584 rows: vec![SidebarHoverRow {
3585 row_y: 4,
3586 display_text: "[~] Agent 1 is working [x]".to_string(),
3587 full_text: "[~] Agent 1 is working [x]".to_string(),
3588 detail: None,
3589 is_truncated: false,
3590 click_action: Some(SidebarRowAction::OpenAgentDetail {
3591 agent_id: "agent_123".to_string(),
3592 }),
3593 stop_action: Some(SidebarRowAction::CancelAgent {
3594 agent_id: "agent_123".to_string(),
3595 }),
3596 stop_zone_start_col: Some(68),
3597 stop_zone_end_col: Some(71),
3598 }],
3599 });
3600
3601 assert!(matches!(
3602 sidebar_click_action(&app, left_click(62, 4)),
3603 Some(SidebarRowAction::OpenAgentDetail { agent_id })
3604 if agent_id == "agent_123"
3605 ));
3606 assert!(matches!(
3607 sidebar_click_action(&app, left_click(69, 4)),
3608 Some(SidebarRowAction::CancelAgent { agent_id }) if agent_id == "agent_123"
3609 ));
3610 }
3611
3612 #[test]
3613 fn sidebar_context_menu_offers_copy_of_hovered_row() {
3614 let mut app = create_test_app();
3615 app.work_surface.last_area = Some(Rect::new(60, 4, 20, 6));
3616 app.sidebar_hover.sections.push(SidebarHoverSection {
3617 content_area: Rect::new(60, 4, 20, 6),
3618 lines: vec!["agent row".to_string()],
3619 rows: vec![SidebarHoverRow {
3620 row_y: 4,
3621 display_text: "[~] worker doc-che…".to_string(),
3622 full_text: "[~] worker doc-checker".to_string(),
3623 detail: Some("id: agent_123 · 2 step(s)".to_string()),
3624 is_truncated: true,
3625 click_action: None,
3626 stop_action: None,
3627 stop_zone_start_col: None,
3628 stop_zone_end_col: None,
3629 }],
3630 });
3631
3632 let entries = build_context_menu_entries(&app, right_click(65, 4));
3633
3634 let copy = entries
3635 .iter()
3636 .find(|entry| matches!(entry.action, ContextMenuAction::CopyText { .. }))
3637 .expect("sidebar row should offer Copy");
3638 assert_eq!(copy.label, "Copy row");
3639 assert!(matches!(
3640 &copy.action,
3641 ContextMenuAction::CopyText { text }
3642 if text == "[~] worker doc-checker\nid: agent_123 · 2 step(s)"
3643 ));
3644 }
3645
3646 #[test]
3647 fn sidebar_click_outside_section_resolves_to_none() {
3648 let mut app = create_test_app();
3649 app.sidebar_hover.sections.push(SidebarHoverSection {
3650 content_area: Rect::new(60, 4, 20, 6),
3651 lines: vec!["job row".to_string()],
3652 rows: vec![hover_row(4, Some("/jobs show shell_x"))],
3653 });
3654
3655 // Left of the sidebar (transcript area).
3656 assert_eq!(sidebar_click_action(&app, left_click(10, 4)), None);
3657 // Below the section's content area.
3658 assert_eq!(sidebar_click_action(&app, left_click(65, 30)), None);
3659 // Inside the section but on an empty row without metadata.
3660 assert_eq!(sidebar_click_action(&app, left_click(65, 8)), None);
3661 }
3662
3663 fn work_row_section(app: &mut App, action: SidebarRowAction) {
3664 app.work_surface.last_area = Some(Rect::new(60, 4, 20, 6));
3665 app.sidebar_hover.sections.push(SidebarHoverSection {
3666 content_area: Rect::new(60, 4, 20, 6),
3667 lines: vec!["row".to_string()],
3668 rows: vec![SidebarHoverRow {
3669 row_y: 4,
3670 display_text: "row".to_string(),
3671 full_text: "row text".to_string(),
3672 detail: None,
3673 is_truncated: false,
3674 click_action: Some(action),
3675 stop_action: None,
3676 stop_zone_start_col: None,
3677 stop_zone_end_col: None,
3678 }],
3679 });
3680 }
3681
3682 /// N14: focusing an agent shows its chat and addresses the composer to
3683 /// it, so Focus, Message and Open transcript are one action. The menu
3684 /// offers it once, and every other entry does something different.
3685 #[test]
3686 fn agent_row_menu_offers_focus_once() {
3687 let mut app = create_test_app();
3688 work_row_section(
3689 &mut app,
3690 SidebarRowAction::OpenAgentTranscript {
3691 agent_id: "agent_1".to_string(),
3692 },
3693 );
3694
3695 let entries = build_context_menu_entries(&app, right_click(65, 4));
3696 let labels: Vec<&str> = entries.iter().map(|e| e.label.as_str()).collect();
3697 assert_eq!(
3698 labels,
3699 ["Focus agent", "Open details", "Copy id", "Copy row"]
3700 );
3701 assert!(entries[0].primary);
3702 assert_eq!(
3703 entries[0].action,
3704 ContextMenuAction::Row(SidebarRowAction::OpenAgentTranscript {
3705 agent_id: "agent_1".to_string()
3706 })
3707 );
3708 for (index, entry) in entries.iter().enumerate() {
3709 assert!(
3710 entries[index + 1..]
3711 .iter()
3712 .all(|e| e.action != entry.action),
3713 "two rows do the same thing: {labels:?}"
3714 );
3715 }
3716 }
3717
3718 /// A work item with a stop carries it last, behind the menu's confirm,
3719 /// as the same typed action the inspector's stop runs.
3720 #[test]
3721 fn work_item_menu_puts_a_confirmed_stop_last() {
3722 let mut app = create_test_app();
3723 work_row_section(
3724 &mut app,
3725 SidebarRowAction::InspectWork {
3726 title: "job".to_string(),
3727 body: "body".to_string(),
3728 stop_action: Some(Box::new(SidebarRowAction::Command(
3729 "/jobs cancel shell_x".to_string(),
3730 ))),
3731 },
3732 );
3733
3734 let entries = build_context_menu_entries(&app, right_click(65, 4));
3735 assert_eq!(entries[0].label, "Open details");
3736 let stop = entries.last().expect("stop entry");
3737 assert_eq!(stop.label, "Stop…");
3738 assert!(stop.confirm_label.is_some());
3739 assert_eq!(
3740 stop.action,
3741 ContextMenuAction::Row(SidebarRowAction::Command(
3742 "/jobs cancel shell_x".to_string()
3743 ))
3744 );
3745 }
3746
3747 /// T8: "Run" used to run through a dedicated arm while a dead arm's
3748 /// status claimed the command was "staged in composer". A row action now
3749 /// returns exactly the events a left click on the row produces.
3750 #[test]
3751 fn row_action_returns_what_a_left_click_runs() {
3752 let mut app = create_test_app();
3753 let outcome = super::apply_context_menu_action(
3754 &mut app,
3755 ContextMenuAction::Row(SidebarRowAction::Command("/cost".to_string())),
3756 );
3757 let super::ContextMenuOutcome::Events(events) = outcome else {
3758 panic!("row actions hand their events to the host: {outcome:?}");
3759 };
3760 assert!(matches!(
3761 events.as_slice(),
3762 [ViewEvent::CommandPaletteSelected {
3763 action: crate::tui::views::CommandPaletteAction::ExecuteCommand { command },
3764 }] if command == "/cost"
3765 ));
3766 assert!(app.input.is_empty(), "nothing is staged in the composer");
3767
3768 let outcome = super::apply_context_menu_action(
3769 &mut app,
3770 ContextMenuAction::Row(SidebarRowAction::CancelAgent {
3771 agent_id: "agent_1".to_string(),
3772 }),
3773 );
3774 assert!(matches!(
3775 outcome,
3776 super::ContextMenuOutcome::Events(ref events)
3777 if matches!(events.as_slice(), [ViewEvent::SidebarAgentCancel { agent_id }] if agent_id == "agent_1")
3778 ));
3779 }
3780
3781 #[test]
3782 fn open_file_hands_the_editor_to_the_host() {
3783 let mut app = create_test_app();
3784 let path = PathBuf::from("/ws/src/a.rs");
3785 let outcome = super::apply_context_menu_action(
3786 &mut app,
3787 ContextMenuAction::OpenFileAtLine {
3788 path: path.clone(),
3789 line: 12,
3790 },
3791 );
3792 assert!(matches!(
3793 outcome,
3794 super::ContextMenuOutcome::OpenInEditor { path: ref p, line: 12 } if *p == path
3795 ));
3796 }
3797
3798 #[test]
3799 fn hide_and_restore_cells_report_what_changed() {
3800 let mut app = create_test_app();
3801 super::apply_context_menu_action(&mut app, ContextMenuAction::HideCell { cell_index: 3 });
3802 assert!(app.collapsed_cells.contains(&3));
3803 assert_eq!(last_toast(&app), Some("Cell hidden"));
3804 super::apply_context_menu_action(&mut app, ContextMenuAction::ShowAllHidden);
3805 assert!(app.collapsed_cells.is_empty());
3806 assert_eq!(last_toast(&app), Some("1 hidden cell(s) restored"));
3807 }
3808
3809 #[test]
3810 fn extension_action_without_the_panel_says_so() {
3811 let mut app = create_test_app();
3812 let outcome = super::apply_context_menu_action(
3813 &mut app,
3814 ContextMenuAction::Extension {
3815 item_id: "gone".to_string(),
3816 verb: crate::tui::views::ExtensionMenuVerb::Remove,
3817 },
3818 );
3819 assert!(matches!(outcome, super::ContextMenuOutcome::Done));
3820 assert_eq!(last_toast(&app), Some("That plugin is no longer listed"));
3821 }
3822
3823 fn app_with_answer(workspace: &std::path::Path, content: &str) -> App {
3824 let mut app = create_test_app();
3825 app.workspace = workspace.to_path_buf();
3826 app.history = vec![crate::tui::history::HistoryCell::Assistant {
3827 content: content.to_string(),
3828 streaming: false,
3829 }];
3830 app.resync_history_revisions();
3831 app.viewport
3832 .transcript_cache
3833 .set_workspace(Some(&app.workspace));
3834 app.viewport.transcript_cache.ensure(
3835 &app.history,
3836 &app.history_revisions,
3837 80,
3838 app.transcript_render_options(),
3839 );
3840 app.viewport.last_transcript_area = Some(Rect::new(0, 0, 80, 8));
3841 app.viewport.last_transcript_top = 0;
3842 app.viewport.last_transcript_total = app.viewport.transcript_cache.total_lines();
3843 app
3844 }
3845
3846 fn line_of(app: &App, needle: &str) -> u16 {
3847 let index = app
3848 .viewport
3849 .transcript_cache
3850 .lines()
3851 .iter()
3852 .position(|line| codewhale_tui_kit::ui_text::line_to_plain(line).contains(needle))
3853 .expect("rendered line");
3854 u16::try_from(index).unwrap()
3855 }
3856
3857 /// T4: Open in editor used to follow any absolute path in model output,
3858 /// and `..` escaped through `workspace.join`. It is offered only for a
3859 /// file inside the workspace, and the clicked line wins over the cell.
3860 #[test]
3861 fn open_in_editor_is_offered_only_inside_the_workspace() {
3862 let root = tempdir().expect("tempdir");
3863 let workspace = root.path().join("ws");
3864 std::fs::create_dir_all(workspace.join("src")).unwrap();
3865 std::fs::write(workspace.join("src/a.rs"), "fn a() {}\n").unwrap();
3866 std::fs::write(workspace.join("src/b.rs"), "fn b() {}\n").unwrap();
3867 std::fs::write(root.path().join("secret.rs"), "outside\n").unwrap();
3868 let outside = root.path().join("secret.rs");
3869
3870 let app = app_with_answer(
3871 &workspace,
3872 &format!(
3873 "first `src/a.rs:3`\n\nthen --> src/b.rs:7:2\n\nand {}:1",
3874 outside.display()
3875 ),
3876 );
3877 let open = |app: &App, row: u16| {
3878 build_context_menu_entries(app, right_click(4, row))
3879 .into_iter()
3880 .find_map(|entry| match entry.action {
3881 ContextMenuAction::OpenFileAtLine { path, line } => Some((path, line)),
3882 _ => None,
3883 })
3884 };
3885 assert_eq!(
3886 open(&app, line_of(&app, "src/b.rs")),
3887 Some((workspace.join("src/b.rs"), 7)),
3888 "the clicked line wins"
3889 );
3890 assert_eq!(
3891 open(&app, line_of(&app, "secret.rs")),
3892 Some((workspace.join("src/a.rs"), 3)),
3893 "an outside path on the clicked line falls back to the cell's own"
3894 );
3895
3896 let app = app_with_answer(
3897 &workspace,
3898 &format!("{}:1 and ../secret.rs:2", outside.display()),
3899 );
3900 assert_eq!(open(&app, line_of(&app, "secret.rs")), None);
3901 }
3902
3903 /// App chrome (palette, inspector, help) belongs to empty space; on a
3904 /// message it only pushed the message's own actions down.
3905 #[test]
3906 fn chrome_entries_only_on_empty_space() {
3907 let root = tempdir().expect("tempdir");
3908 let app = app_with_answer(root.path(), "alpha beta");
3909 let has_palette = |entries: &[crate::tui::context_menu::ContextMenuEntry]| {
3910 entries
3911 .iter()
3912 .any(|e| e.action == ContextMenuAction::OpenCommandPalette)
3913 };
3914 assert!(!has_palette(&build_context_menu_entries(
3915 &app,
3916 right_click(4, line_of(&app, "alpha"))
3917 )));
3918 let empty = create_test_app();
3919 let entries = build_context_menu_entries(&empty, right_click(4, 4));
3920 assert!(has_palette(&entries));
3921 assert_eq!(entries[0].action, ContextMenuAction::Paste);
3922 }
3923
3924 /// T6: Copy took the composer selection while Clear cleared only the
3925 /// transcript's and still said "Selection cleared", and Open ignored the
3926 /// composer. All three now act on the same selection.
3927 #[test]
3928 fn copy_open_and_clear_act_on_the_composer_selection() {
3929 let root = tempdir().expect("tempdir");
3930 let mut app = app_with_answer(root.path(), "alpha beta");
3931 // A transcript selection too: the composer's must still win.
3932 app.viewport.transcript_selection.anchor =
3933 Some(crate::tui::selection::TranscriptSelectionPoint {
3934 line_index: 0,
3935 column: 0,
3936 });
3937 app.viewport.transcript_selection.head =
3938 Some(crate::tui::selection::TranscriptSelectionPoint {
3939 line_index: 0,
3940 column: 6,
3941 });
3942 let select = |app: &mut App| {
3943 app.input = "hello world".to_string();
3944 app.selection_anchor = Some(0);
3945 app.cursor_position = 5;
3946 };
3947
3948 select(&mut app);
3949 super::apply_context_menu_action(&mut app, ContextMenuAction::CopySelection);
3950 assert_eq!(app.clipboard.last_written_text(), Some("hello"));
3951 assert_eq!(
3952 app.status_toasts.back().map(|toast| toast.text.as_str()),
3953 Some("Copied to the clipboard")
3954 );
3955
3956 select(&mut app);
3957 super::apply_context_menu_action(&mut app, ContextMenuAction::OpenSelection);
3958 assert_eq!(app.view_stack.top_kind(), Some(ModalKind::Pager));
3959 app.view_stack.pop();
3960
3961 super::apply_context_menu_action(&mut app, ContextMenuAction::ClearSelection);
3962 assert!(
3963 app.selected_text().is_empty(),
3964 "the composer selection cleared"
3965 );
3966 assert_eq!(last_toast(&app), Some("Selection cleared"));
3967 assert!(
3968 app.viewport.transcript_selection.is_active(),
3969 "Clear acts on the selection Copy would take, not both"
3970 );
3971
3972 super::clear_transcript_selection(&mut app);
3973 super::apply_context_menu_action(&mut app, ContextMenuAction::ClearSelection);
3974 assert_eq!(
3975 last_toast(&app),
3976 Some("No selection to clear"),
3977 "nothing cleared is not reported as cleared"
3978 );
3979 }
3980
3981 /// The menu resolved the file when it opened; a link swapped in before
3982 /// the click (to a real key file outside the workspace, or to `/`) must
3983 /// be refused at launch. The key is one the test creates, so the check
3984 /// does not depend on what the host has in `~/.ssh`.
3985 #[cfg(unix)]
3986 #[test]
3987 fn editor_target_rechecks_links_swapped_in_after_the_menu_opened() {
3988 let dir = tempfile::tempdir().unwrap();
3989 let workspace = &dir.path().join("ws");
3990 let key = dir.path().join("home/.ssh/id_ed25519");
3991 std::fs::create_dir_all(key.parent().unwrap()).unwrap();
3992 std::fs::write(&key, "PRIVATE KEY\n").unwrap();
3993 std::fs::create_dir_all(workspace.join("src")).unwrap();
3994 let file = workspace.join("src/a.rs");
3995 std::fs::write(&file, "fn a() {}\n").unwrap();
3996 assert!(super::editor_target(workspace, &file).is_some());
3997
3998 // The file becomes a link to the key.
3999 std::fs::remove_file(&file).unwrap();
4000 std::os::unix::fs::symlink(&key, &file).unwrap();
4001 assert!(file.is_file(), "the link resolves to a real file");
4002 assert_eq!(super::editor_target(workspace, &file), None);
4003
4004 // The directory becomes a link to /.
4005 std::fs::remove_file(&file).unwrap();
4006 std::fs::remove_dir(workspace.join("src")).unwrap();
4007 std::os::unix::fs::symlink("/", workspace.join("src")).unwrap();
4008 assert_eq!(
4009 super::editor_target(workspace, &workspace.join("src/etc/hosts")),
4010 None
4011 );
4012 assert_eq!(
4013 super::editor_target(workspace, std::path::Path::new("/etc/hosts")),
4014 None
4015 );
4016
4017 // The refusal the user sees names the file and why.
4018 let refusal = codewhale_localization::tr(
4019 codewhale_localization::Locale::En,
4020 codewhale_localization::MessageId::CtxMenuEditorRefused,
4021 )
4022 .replace("{path}", "src/a.rs");
4023 assert_eq!(
4024 refusal,
4025 "Did not open src/a.rs: it is no longer a file inside the workspace"
4026 );
4027 }
4028
4029 /// Ctrl+X deletes the selection only when a native clipboard confirmed
4030 /// the copy. A terminal (OSC 52 / tmux) copy keeps the text and says why;
4031 /// a failed copy keeps it and says the copy failed.
4032 #[test]
4033 fn cut_deletes_only_after_a_native_copy() {
4034 fn select_all(app: &mut App, text: &str) {
4035 app.input = text.to_string();
4036 app.selection_anchor = Some(0);
4037 app.cursor_position = text.chars().count();
4038 }
4039
4040 let mut app = create_test_app();
4041 select_all(&mut app, "hello");
4042 super::cut_selection(&mut app);
4043 assert_eq!(app.clipboard.last_written_text(), Some("hello"));
4044 assert_eq!(app.input, "", "a native copy cuts");
4045 assert_eq!(last_toast(&app), Some("Copied to the clipboard"));
4046
4047 app.clipboard = crate::tui::clipboard::ClipboardHandler::terminal_only_for_test();
4048 select_all(&mut app, "kept");
4049 super::cut_selection(&mut app);
4050 assert_eq!(
4051 app.input, "kept",
4052 "an unconfirmed terminal copy keeps the text"
4053 );
4054 assert_eq!(
4055 last_toast(&app),
4056 Some(
4057 "Sent to the terminal clipboard; the text stays because terminals do not confirm copies"
4058 )
4059 );
4060
4061 app.clipboard = crate::tui::clipboard::ClipboardHandler::unavailable_for_test(false);
4062 select_all(&mut app, "also kept");
4063 super::cut_selection(&mut app);
4064 assert_eq!(app.input, "also kept", "a failed copy keeps the text");
4065 assert!(
4066 last_toast(&app).is_some_and(|toast| toast.starts_with("Clipboard copy failed: ")),
4067 "{:?}",
4068 last_toast(&app)
4069 );
4070 }
4071
4072 /// A right-click on a row's inline stop zone opens the row's own menu;
4073 /// the stop is offered last behind the confirm, never as the primary
4074 /// entry that one click would run.
4075 #[test]
4076 fn right_click_on_a_stop_zone_keeps_the_stop_confirmed() {
4077 let mut app = create_test_app();
4078 work_row_section(
4079 &mut app,
4080 SidebarRowAction::Command("/jobs show shell_x".to_string()),
4081 );
4082 let row = &mut app.sidebar_hover.sections[0].rows[0];
4083 row.stop_action = Some(SidebarRowAction::Command(
4084 "/jobs cancel shell_x".to_string(),
4085 ));
4086 row.stop_zone_start_col = Some(76);
4087 row.stop_zone_end_col = Some(79);
4088
4089 let entries = build_context_menu_entries(&app, right_click(77, 4));
4090 let primary = entries.iter().find(|entry| entry.primary).expect("primary");
4091 assert_eq!(
4092 primary.action,
4093 ContextMenuAction::Row(SidebarRowAction::Command("/jobs show shell_x".to_string()))
4094 );
4095 assert!(primary.confirm_label.is_none());
4096 let stop = entries.last().expect("stop entry");
4097 assert_eq!(stop.label, "Stop…");
4098 assert_eq!(
4099 stop.action,
4100 ContextMenuAction::Row(SidebarRowAction::Command(
4101 "/jobs cancel shell_x".to_string()
4102 ))
4103 );
4104 assert!(stop.confirm_label.is_some(), "the stop needs the confirm");
4105 }
4106
4107 /// N9: an OSC 52 / tmux write is never acknowledged, so its receipt says
4108 /// the text was sent to the terminal, not that it was copied.
4109 #[test]
4110 fn copy_receipts_name_the_transport() {
4111 let mut app = create_test_app();
4112 super::apply_context_menu_action(
4113 &mut app,
4114 ContextMenuAction::CopyText {
4115 text: "agent_1".to_string(),
4116 },
4117 );
4118 assert_eq!(app.clipboard.last_written_text(), Some("agent_1"));
4119 assert_eq!(last_toast(&app), Some("Copied to the clipboard"));
4120
4121 app.clipboard = crate::tui::clipboard::ClipboardHandler::terminal_only_for_test();
4122 super::apply_context_menu_action(
4123 &mut app,
4124 ContextMenuAction::CopyText {
4125 text: "agent_1".to_string(),
4126 },
4127 );
4128 assert_eq!(
4129 last_toast(&app),
4130 Some("Sent to the terminal clipboard (terminals do not confirm it)")
4131 );
4132
4133 // The terminal lane holds one write at a time; let the first land.
4134 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
4135 while app.clipboard.poll_write_completion().is_none() {
4136 assert!(
4137 std::time::Instant::now() < deadline,
4138 "terminal write landed"
4139 );
4140 std::thread::sleep(std::time::Duration::from_millis(1));
4141 }
4142 app.input = "hello".to_string();
4143 app.selection_anchor = Some(0);
4144 app.cursor_position = 5;
4145 super::apply_context_menu_action(&mut app, ContextMenuAction::CopySelection);
4146 assert_eq!(
4147 last_toast(&app),
4148 Some("Sent to the terminal clipboard (terminals do not confirm it)")
4149 );
4150
4151 app.clipboard = crate::tui::clipboard::ClipboardHandler::unavailable_for_test(false);
4152 super::apply_context_menu_action(
4153 &mut app,
4154 ContextMenuAction::CopyText {
4155 text: "agent_1".to_string(),
4156 },
4157 );
4158 assert!(
4159 last_toast(&app).is_some_and(|toast| toast.starts_with("Clipboard copy failed: ")),
4160 "{:?}",
4161 last_toast(&app)
4162 );
4163 }
4164
4165 /// T11: Paste with nothing to paste used to do nothing and say nothing.
4166 #[test]
4167 fn paste_with_nothing_to_paste_says_so() {
4168 let mut app = create_test_app();
4169 app.clipboard = crate::tui::clipboard::ClipboardHandler::unavailable_for_test(false);
4170 app.input = "draft".to_string();
4171 super::apply_context_menu_action(&mut app, ContextMenuAction::Paste);
4172 assert_eq!(app.input, "draft");
4173 assert_eq!(
4174 last_toast(&app),
4175 Some("Nothing to paste: the clipboard is empty or could not be read")
4176 );
4177 }
4178
4179 #[test]
4180 fn worker_transcript_formats_visible_activity_without_thinking() {
4181 let transcript = agent_transcript_text(&json!({
4182 "message_count": 2,
4183 "messages": [
4184 {"role": "user", "content": [{"type": "text", "text": "Survey Harnesses", "cache_control": null}]},
4185 {"role": "assistant", "content": [
4186 {"type": "thinking", "thinking": "private chain of thought", "signature": null},
4187 {"type": "tool_use", "id": "call_1", "name": "list_dir", "input": {"path": "/tmp"}, "caller": null},
4188 {"type": "text", "text": "I found the workspace.", "cache_control": null}
4189 ]}
4190 ]
4191 }));
4192
4193 assert!(transcript.contains("── user ──\nSurvey Harnesses"));
4194 assert!(transcript.contains("→ list_dir"));
4195 assert!(transcript.contains("I found the workspace."));
4196 assert!(!transcript.contains("private chain of thought"));
4197 }
4198
4199 #[test]
4200 fn worker_tool_result_missing_is_error_renders_as_unknown() {
4201 let transcript = agent_transcript_text(&json!({
4202 "message_count": 1,
4203 "messages": [
4204 {"role": "user", "content": [
4205 {"type": "tool_result", "tool_use_id": "call_ok", "content": "done", "is_error": false},
4206 {"type": "tool_result", "tool_use_id": "call_err", "content": "boom", "is_error": true},
4207 {"type": "tool_result", "tool_use_id": "call_unknown", "content": "maybe"}
4208 ]}
4209 ]
4210 }));
4211
4212 assert!(transcript.contains("← tool result (call_ok)\ndone"));
4213 assert!(transcript.contains("← tool error (call_err)\nboom"));
4214 assert!(transcript.contains("← tool result (status unknown) (call_unknown)\nmaybe"));
4215 }
4216
4217 #[test]
4218 fn sidebar_and_context_menu_status_messages_respect_ui_locale() {
4219 use codewhale_localization::{Locale, MessageId, tr};
4220
4221 let mut app = create_test_app();
4222 app.ui_locale = Locale::Fr;
4223
4224 super::apply_sidebar_row_action(&mut app, SidebarRowAction::ShowSubagentsPanel);
4225 assert_eq!(
4226 last_toast(&app),
4227 Some(tr(Locale::Fr, MessageId::SidebarShowingSubagents).as_ref())
4228 );
4229
4230 super::apply_context_menu_action(&mut app, ContextMenuAction::OpenSelection);
4231 assert_eq!(
4232 last_toast(&app),
4233 Some(tr(Locale::Fr, MessageId::CtxMenuNoSelectionToOpen).as_ref())
4234 );
4235
4236 super::apply_context_menu_action(&mut app, ContextMenuAction::ClearSelection);
4237 assert_eq!(
4238 last_toast(&app),
4239 Some(tr(Locale::Fr, MessageId::CtxMenuNoSelectionToClear).as_ref())
4240 );
4241
4242 super::apply_context_menu_action(
4243 &mut app,
4244 ContextMenuAction::OpenDetails { cell_index: 99 },
4245 );
4246 assert_eq!(
4247 last_toast(&app),
4248 Some(tr(Locale::Fr, MessageId::CtxMenuNoDetailsForLine).as_ref())
4249 );
4250
4251 super::apply_context_menu_action(&mut app, ContextMenuAction::HideCell { cell_index: 0 });
4252 assert_eq!(
4253 last_toast(&app),
4254 Some(tr(Locale::Fr, MessageId::CtxMenuCellHidden).as_ref())
4255 );
4256
4257 super::apply_context_menu_action(&mut app, ContextMenuAction::ShowCell { cell_index: 0 });
4258 assert_eq!(
4259 last_toast(&app),
4260 Some(tr(Locale::Fr, MessageId::CtxMenuCellShown).as_ref())
4261 );
4262
4263 app.collapsed_cells.insert(0);
4264 super::apply_context_menu_action(&mut app, ContextMenuAction::ShowAllHidden);
4265 assert_eq!(
4266 last_toast(&app),
4267 Some(
4268 tr(Locale::Fr, MessageId::CtxMenuHiddenCellsRestored)
4269 .replace("{count}", "1")
4270 .as_str()
4271 )
4272 );
4273
4274 app.viewport.transcript_selection.anchor =
4275 Some(crate::tui::selection::TranscriptSelectionPoint {
4276 line_index: 0,
4277 column: 0,
4278 });
4279 app.viewport.transcript_selection.head =
4280 Some(crate::tui::selection::TranscriptSelectionPoint {
4281 line_index: 0,
4282 column: 1,
4283 });
4284 super::apply_context_menu_action(&mut app, ContextMenuAction::CopySelection);
4285 assert_eq!(
4286 last_toast(&app),
4287 Some(tr(Locale::Fr, MessageId::CtxMenuNoSelectionToCopy).as_ref())
4288 );
4289 }
4290
4291 #[test]
4292 fn worker_open_reads_first_and_last_turns_from_complete_artifact() {
4293 let tmp = tempdir().expect("tempdir");
4294 let agent_id = "agent_large_chat";
4295 let early = format!("EARLY-OPEN-MARKER\n{}", "a".repeat(1_100_000));
4296 let messages = vec![
4297 Message {
4298 role: Role::User,
4299 content: vec![ContentBlock::Text {
4300 text: early,
4301 cache_control: None,
4302 }],
4303 },
4304 Message {
4305 role: Role::Assistant,
4306 content: vec![ContentBlock::Text {
4307 text: "LAST-OPEN-MARKER".to_string(),
4308 cache_control: None,
4309 }],
4310 },
4311 ];
4312 let artifact =
4313 codewhale_engine::tools::subagent::write_subagent_transcript_artifact_for_test(
4314 tmp.path(),
4315 agent_id,
4316 &messages,
4317 )
4318 .expect("write complete worker transcript");
4319 assert!(
4320 std::fs::metadata(artifact)
4321 .expect("artifact metadata")
4322 .len()
4323 > 1024 * 1024,
4324 "regression requires a transcript larger than the resident handle budget"
4325 );
4326
4327 let mut app = create_test_app();
4328 app.workspace = tmp.path().to_path_buf();
4329 {
4330 let mut store = app
4331 .runtime_services
4332 .handle_store
4333 .try_lock()
4334 .expect("handle store");
4335 let _ = store.insert_json(
4336 format!("agent:{agent_id}"),
4337 "full_transcript",
4338 json!({
4339 "kind": "subagent_full_transcript",
4340 "message_count": 2,
4341 "omitted_messages": 1,
4342 "messages_complete": false,
4343 "messages": [messages[1].clone()],
4344 }),
4345 );
4346 }
4347
4348 crate::tui::agent_focus::focus_agent(&mut app, agent_id);
4349 let focus = app.agent_focus.as_ref().expect("Open focuses the worker");
4350 let body = focus
4351 .cells
4352 .iter()
4353 .flat_map(|cell| cell.transcript_lines(120))
4354 .map(|line| line.to_string())
4355 .collect::<Vec<_>>()
4356 .join("\n");
4357 assert!(body.contains("EARLY-OPEN-MARKER"), "{body}");
4358 assert!(body.contains("LAST-OPEN-MARKER"), "{body}");
4359 assert_eq!(
4360 focus.omitted_messages, 0,
4361 "Open must use the complete artifact, not the compacted resident tail"
4362 );
4363 }
4364
4365 #[cfg(test)]
4366 mod composer_selection_tests {
4367 use super::super::*;
4368
4369 #[test]
4370 fn word_bounds_select_words_and_respect_cjk() {
4371 // Chars: fix(0-2) sp(3) the(4-6) sp(7) 深(8) 海(9) sp(10) test.rs(11-17)
4372 let text = "fix the 深海 test.rs";
4373 assert_eq!(composer_word_bounds(text, 2), (0, 3)); // 'fix'
4374 assert_eq!(composer_word_bounds(text, 5), (4, 7)); // 'the'
4375 assert_eq!(composer_word_bounds(text, 9), (8, 10)); // '深海' (space at 10)
4376 assert_eq!(composer_word_bounds(text, 11), (11, 15)); // 'test' (stops at '.')
4377 assert_eq!(composer_word_bounds(text, 15), (15, 16)); // '.'
4378 assert_eq!(composer_word_bounds(text, 16), (16, 18)); // 'rs'
4379 }
4380
4381 #[test]
4382 fn click_bounds_are_char_indices_on_multibyte_text() {
4383 // The click maps to a char index and the result becomes the
4384 // char-indexed cursor/anchor. Byte math here panicked on a
4385 // triple-click inside CJK text and skewed double-click spans.
4386 let text = "你好\n世界 ok";
4387 assert_eq!(composer_line_bounds(text, 1), (0, 2));
4388 assert_eq!(composer_line_bounds(text, 4), (3, 8));
4389 assert_eq!(composer_word_bounds(text, 3), (3, 5)); // '世界'
4390 assert_eq!(composer_word_bounds(text, 6), (6, 8)); // 'ok'
4391 let mixed = "fix 深海 test";
4392 assert_eq!(composer_word_bounds(mixed, 8), (7, 11)); // 'test'
4393 }
4394
4395 #[test]
4396 fn word_bounds_at_punctuation_returns_the_single_char() {
4397 let text = "a, b";
4398 assert_eq!(composer_word_bounds(text, 1), (1, 2)); // ','
4399 }
4400
4401 #[test]
4402 fn line_bounds_exclude_the_newline() {
4403 let text = "first\nsecond third\nfourth";
4404 assert_eq!(composer_line_bounds(text, 2), (0, 5));
4405 assert_eq!(composer_line_bounds(text, 9), (6, 18));
4406 assert_eq!(composer_line_bounds(text, 20), (19, 25));
4407 assert_eq!(composer_line_bounds(text, 0), (0, 5));
4408 }
4409
4410 #[test]
4411 fn click_classification_resets_outside_the_window_or_slop() {
4412 let mut trace = None;
4413 assert_eq!(
4414 classify_composer_click(&mut trace, 10, 4),
4415 ComposerClickGesture::Caret
4416 );
4417 assert_eq!(
4418 classify_composer_click(&mut trace, 10, 4),
4419 ComposerClickGesture::Word
4420 );
4421 assert_eq!(
4422 classify_composer_click(&mut trace, 10, 4),
4423 ComposerClickGesture::Line
4424 );
4425 // A click far away resets the chain back to a caret.
4426 assert_eq!(
4427 classify_composer_click(&mut trace, 10, 40),
4428 ComposerClickGesture::Caret
4429 );
4430 assert_eq!(
4431 classify_composer_click(&mut trace, 10, 40),
4432 ComposerClickGesture::Word
4433 );
4434 }
4435 }
4436
4437 fn link_col_of(app: &App, row: u16, needle: &str) -> u16 {
4438 let plain = super::line_to_plain(&app.viewport.transcript_cache.lines()[usize::from(row)]);
4439 let byte_idx = plain
4440 .find(needle)
4441 .unwrap_or_else(|| panic!("missing {needle:?} in {plain:?}"));
4442 let col = unicode_width::UnicodeWidthStr::width(&plain[..byte_idx]);
4443 u16::try_from(col).expect("u16 col")
4444 }
4445
4446 fn left_event(
4447 kind: MouseEventKind,
4448 column: u16,
4449 row: u16,
4450 modifiers: KeyModifiers,
4451 ) -> MouseEvent {
4452 MouseEvent {
4453 kind,
4454 column,
4455 row,
4456 modifiers,
4457 }
4458 }
4459
4460 #[test]
4461 fn plain_left_click_activates_http_file_and_dir_links_and_guards_drag_and_modifiers() {
4462 let root = tempdir().expect("tempdir");
4463 let workspace = root.path().join("ws");
4464 std::fs::create_dir_all(workspace.join("dynamis/build/support-final")).unwrap();
4465 std::fs::write(workspace.join("src_main.rs"), "fn main() {}\n").unwrap();
4466
4467 let mut app = app_with_answer(
4468 &workspace,
4469 "see `src_main.rs:42` and `dynamis/build/support-final/` and `https://example.com`",
4470 );
4471 let row = line_of(&app, "src_main.rs:42");
4472 let file_col = link_col_of(&app, row, "src_main.rs:42") + 2;
4473 let dir_col = link_col_of(&app, row, "dynamis/build/support-final/") + 2;
4474 let url_col = link_col_of(&app, row, "https://example.com") + 2;
4475
4476 let now = Instant::now();
4477 let _ = handle_mouse_event(
4478 &mut app,
4479 left_event(
4480 MouseEventKind::Down(MouseButton::Left),
4481 file_col,
4482 row,
4483 KeyModifiers::NONE,
4484 ),
4485 now,
4486 );
4487 let events = handle_mouse_event(
4488 &mut app,
4489 left_event(
4490 MouseEventKind::Up(MouseButton::Left),
4491 file_col,
4492 row,
4493 KeyModifiers::NONE,
4494 ),
4495 now,
4496 );
4497 assert!(matches!(
4498 events.as_slice(),
4499 [ViewEvent::ContextMenuSelected {
4500 action: ContextMenuAction::OpenFileAtLine { path, line: 42 },
4501 }] if *path == workspace.join("src_main.rs")
4502 ));
4503
4504 app.viewport.transcript_click_trace = None;
4505 let _ = handle_mouse_event(
4506 &mut app,
4507 left_event(
4508 MouseEventKind::Down(MouseButton::Left),
4509 dir_col,
4510 row,
4511 KeyModifiers::NONE,
4512 ),
4513 now,
4514 );
4515 let events = handle_mouse_event(
4516 &mut app,
4517 left_event(
4518 MouseEventKind::Up(MouseButton::Left),
4519 dir_col,
4520 row,
4521 KeyModifiers::NONE,
4522 ),
4523 now,
4524 );
4525 assert!(matches!(
4526 events.as_slice(),
4527 [ViewEvent::ContextMenuSelected {
4528 action: ContextMenuAction::OpenPath { path },
4529 }] if *path == workspace.join("dynamis/build/support-final")
4530 ));
4531
4532 app.viewport.transcript_click_trace = None;
4533 let _ = handle_mouse_event(
4534 &mut app,
4535 left_event(
4536 MouseEventKind::Down(MouseButton::Left),
4537 url_col,
4538 row,
4539 KeyModifiers::NONE,
4540 ),
4541 now,
4542 );
4543 let events = handle_mouse_event(
4544 &mut app,
4545 left_event(
4546 MouseEventKind::Up(MouseButton::Left),
4547 url_col,
4548 row,
4549 KeyModifiers::NONE,
4550 ),
4551 now,
4552 );
4553 assert!(matches!(
4554 events.as_slice(),
4555 [ViewEvent::ContextMenuSelected {
4556 action: ContextMenuAction::OpenExternalUrl { url },
4557 }] if url == "https://example.com"
4558 ));
4559
4560 app.viewport.transcript_click_trace = None;
4561 let _ = handle_mouse_event(
4562 &mut app,
4563 left_event(
4564 MouseEventKind::Down(MouseButton::Left),
4565 file_col,
4566 row,
4567 KeyModifiers::NONE,
4568 ),
4569 now,
4570 );
4571 let _ = handle_mouse_event(
4572 &mut app,
4573 left_event(
4574 MouseEventKind::Drag(MouseButton::Left),
4575 file_col + 4,
4576 row,
4577 KeyModifiers::NONE,
4578 ),
4579 now,
4580 );
4581 let drag_events = handle_mouse_event(
4582 &mut app,
4583 left_event(
4584 MouseEventKind::Up(MouseButton::Left),
4585 file_col + 4,
4586 row,
4587 KeyModifiers::NONE,
4588 ),
4589 now,
4590 );
4591 assert!(
4592 drag_events.is_empty(),
4593 "drag must select, not activate link"
4594 );
4595
4596 app.viewport.transcript_click_trace = None;
4597 super::clear_transcript_selection(&mut app);
4598 let _ = handle_mouse_event(
4599 &mut app,
4600 left_event(
4601 MouseEventKind::Down(MouseButton::Left),
4602 file_col,
4603 row,
4604 KeyModifiers::CONTROL,
4605 ),
4606 now,
4607 );
4608 let mod_events = handle_mouse_event(
4609 &mut app,
4610 left_event(
4611 MouseEventKind::Up(MouseButton::Left),
4612 file_col,
4613 row,
4614 KeyModifiers::CONTROL,
4615 ),
4616 now,
4617 );
4618 assert!(mod_events.is_empty(), "modified click stays terminal-owned");
4619 }
4620
4621 #[cfg(unix)]
4622 #[test]
4623 fn plain_click_refuses_file_link_replaced_by_symlink() {
4624 let root = tempdir().expect("tempdir");
4625 let workspace = root.path().join("ws");
4626 let outside = root.path().join("outside");
4627 std::fs::create_dir_all(&workspace).unwrap();
4628 std::fs::create_dir_all(&outside).unwrap();
4629 let file = workspace.join("target.rs");
4630 let secret = outside.join("secret.rs");
4631 std::fs::write(&file, "ok\n").unwrap();
4632 std::fs::write(&secret, "secret\n").unwrap();
4633
4634 let mut app = app_with_answer(&workspace, "open `target.rs:3`");
4635 let row = line_of(&app, "target.rs:3");
4636 let col = link_col_of(&app, row, "target.rs:3") + 1;
4637
4638 std::fs::remove_file(&file).unwrap();
4639 std::os::unix::fs::symlink(&secret, &file).unwrap();
4640
4641 let now = Instant::now();
4642 let _ = handle_mouse_event(
4643 &mut app,
4644 left_event(
4645 MouseEventKind::Down(MouseButton::Left),
4646 col,
4647 row,
4648 KeyModifiers::NONE,
4649 ),
4650 now,
4651 );
4652 let events = handle_mouse_event(
4653 &mut app,
4654 left_event(
4655 MouseEventKind::Up(MouseButton::Left),
4656 col,
4657 row,
4658 KeyModifiers::NONE,
4659 ),
4660 now,
4661 );
4662 assert!(events.is_empty(), "symlink replacement must be refused");
4663 }
4664
4665 #[test]
4666 fn double_click_selects_full_link_or_word_and_triple_click_selects_line() {
4667 let root = tempdir().expect("tempdir");
4668 let workspace = root.path().join("ws");
4669 std::fs::create_dir_all(&workspace).unwrap();
4670 std::fs::write(workspace.join("app.rs"), "fn main() {}\n").unwrap();
4671
4672 let mut app = app_with_answer(&workspace, "alpha `app.rs:9` omega");
4673 let row = line_of(&app, "app.rs:9");
4674 let link_col = link_col_of(&app, row, "app.rs:9") + 2;
4675 let now = Instant::now();
4676
4677 let _ = handle_mouse_event(
4678 &mut app,
4679 left_event(
4680 MouseEventKind::Down(MouseButton::Left),
4681 link_col,
4682 row,
4683 KeyModifiers::NONE,
4684 ),
4685 now,
4686 );
4687 let _ = handle_mouse_event(
4688 &mut app,
4689 left_event(
4690 MouseEventKind::Down(MouseButton::Left),
4691 link_col,
4692 row,
4693 KeyModifiers::NONE,
4694 ),
4695 now,
4696 );
4697 assert_eq!(super::selection_to_text(&app).as_deref(), Some("app.rs:9"));
4698
4699 let _ = handle_mouse_event(
4700 &mut app,
4701 left_event(
4702 MouseEventKind::Down(MouseButton::Left),
4703 link_col,
4704 row,
4705 KeyModifiers::NONE,
4706 ),
4707 now,
4708 );
4709 let line_selected = super::selection_to_text(&app).unwrap_or_default();
4710 assert!(
4711 line_selected.contains("alpha") && line_selected.contains("omega"),
4712 "{line_selected:?}"
4713 );
4714
4715 app.viewport.transcript_click_trace = None;
4716 super::clear_transcript_selection(&mut app);
4717 let word_col = link_col_of(&app, row, "omega") + 1;
4718 let _ = handle_mouse_event(
4719 &mut app,
4720 left_event(
4721 MouseEventKind::Down(MouseButton::Left),
4722 word_col,
4723 row,
4724 KeyModifiers::NONE,
4725 ),
4726 now,
4727 );
4728 let _ = handle_mouse_event(
4729 &mut app,
4730 left_event(
4731 MouseEventKind::Down(MouseButton::Left),
4732 word_col,
4733 row,
4734 KeyModifiers::NONE,
4735 ),
4736 now,
4737 );
4738 assert_eq!(super::selection_to_text(&app).as_deref(), Some("omega"));
4739 }
4740
4741 #[test]
4742 fn right_click_menu_is_column_accurate_and_target_aware() {
4743 let root = tempdir().expect("tempdir");
4744 let workspace = root.path().join("ws");
4745 std::fs::create_dir_all(workspace.join("src")).unwrap();
4746 std::fs::create_dir_all(workspace.join("dynamis/build/support-final")).unwrap();
4747 std::fs::write(workspace.join("src/a.rs"), "a\n").unwrap();
4748 std::fs::write(workspace.join("src/b.rs"), "b\n").unwrap();
4749
4750 let app = app_with_answer(
4751 &workspace,
4752 "files `src/a.rs:3` and `src/b.rs:9`\ndir `dynamis/build/support-final/`\nurl `https://example.com/docs`\n```rust\nlet answer = 42;\n```",
4753 );
4754
4755 let files_row = line_of(&app, "src/a.rs:3");
4756 let col_a = link_col_of(&app, files_row, "src/a.rs:3") + 2;
4757 let col_b = link_col_of(&app, files_row, "src/b.rs:9") + 2;
4758
4759 let entries_a = build_context_menu_entries(&app, right_click(col_a, files_row));
4760 assert_eq!(
4761 entries_a[0].action,
4762 ContextMenuAction::OpenFileAtLine {
4763 path: workspace.join("src/a.rs"),
4764 line: 3,
4765 }
4766 );
4767 assert!(entries_a[0].primary);
4768 assert_eq!(entries_a[0].hint, "e");
4769 assert!(matches!(
4770 entries_a[1].action,
4771 ContextMenuAction::RevealPath { .. }
4772 ));
4773 assert!(matches!(
4774 entries_a[2].action,
4775 ContextMenuAction::CopyText { .. }
4776 ));
4777
4778 let entries_b = build_context_menu_entries(&app, right_click(col_b, files_row));
4779 assert_eq!(
4780 entries_b[0].action,
4781 ContextMenuAction::OpenFileAtLine {
4782 path: workspace.join("src/b.rs"),
4783 line: 9,
4784 }
4785 );
4786
4787 let dir_row = line_of(&app, "dynamis/build/support-final/");
4788 let dir_col = link_col_of(&app, dir_row, "dynamis/build/support-final/") + 2;
4789 let dir_entries = build_context_menu_entries(&app, right_click(dir_col, dir_row));
4790 assert_eq!(
4791 dir_entries[0].action,
4792 ContextMenuAction::OpenPath {
4793 path: workspace.join("dynamis/build/support-final"),
4794 }
4795 );
4796 assert!(dir_entries[0].primary);
4797 assert_eq!(dir_entries[0].hint, "o");
4798 assert!(matches!(
4799 dir_entries[1].action,
4800 ContextMenuAction::RevealPath { .. }
4801 ));
4802 assert!(matches!(
4803 dir_entries[2].action,
4804 ContextMenuAction::CopyText { .. }
4805 ));
4806
4807 let url_row = line_of(&app, "https://example.com/docs");
4808 let url_col = link_col_of(&app, url_row, "https://example.com/docs") + 2;
4809 let url_entries = build_context_menu_entries(&app, right_click(url_col, url_row));
4810 assert_eq!(
4811 url_entries[0].action,
4812 ContextMenuAction::OpenExternalUrl {
4813 url: "https://example.com/docs".to_string(),
4814 }
4815 );
4816 assert!(url_entries[0].primary);
4817 assert_eq!(url_entries[0].hint, "o");
4818 assert_eq!(
4819 url_entries[1].action,
4820 ContextMenuAction::CopyText {
4821 text: "https://example.com/docs".to_string(),
4822 }
4823 );
4824
4825 let code_row = line_of(&app, "let answer = 42;");
4826 let code_col = link_col_of(&app, code_row, "let answer = 42;") + 2;
4827 let code_entries = build_context_menu_entries(&app, right_click(code_col, code_row));
4828 assert!(code_entries.iter().any(|entry| {
4829 entry.action
4830 == ContextMenuAction::CopyText {
4831 text: "let answer = 42;".to_string(),
4832 }
4833 }));
4834 }
4835
4836 #[test]
4837 fn right_click_with_active_selection_makes_copy_selection_primary() {
4838 let root = tempdir().expect("tempdir");
4839 let mut app = app_with_answer(root.path(), "alpha beta gamma");
4840 app.viewport.transcript_selection.anchor =
4841 Some(crate::tui::selection::TranscriptSelectionPoint {
4842 line_index: 0,
4843 column: 2,
4844 });
4845 app.viewport.transcript_selection.head =
4846 Some(crate::tui::selection::TranscriptSelectionPoint {
4847 line_index: 0,
4848 column: 7,
4849 });
4850
4851 let entries = build_context_menu_entries(&app, right_click(4, 0));
4852 assert_eq!(entries[0].action, ContextMenuAction::CopySelection);
4853 assert!(entries[0].primary);
4854 assert_eq!(entries[0].hint, "y");
4855 }
4856 }
4857
4858 #[cfg(test)]
4859 mod primary_tests;
4860
4860 lines RUST