返回 CodeWhale
pager.rs
根目录 / crates / tui / src / tui / pager.rs
1 //! Full-screen pager overlay for long outputs.
2 //!
3 //! Vim-style key bindings (mirroring the codex pager_overlay):
4 //! - `j` / Down — scroll down one line
5 //! - `k` / Up — scroll up one line
6 //! - `g g` / Home — jump to top
7 //! - `G` / End — jump to bottom
8 //! - `Ctrl+D` — half-page down
9 //! - `Ctrl+U` — half-page up
10 //! - `Ctrl+F` / PageDown / Space — full page down
11 //! - `Ctrl+B` / PageUp / Shift+Space — full page up
12 //! - `/` — start search; `n` / `N` — next / previous match
13 //! - `c` / `y` — copy the pager's source text (or its attached copy payload)
14 //! - `a` — copy the attached final assistant answer (answer-carrying pagers)
15 //! - `e` — copy the attached turn handoff markdown (Turn Inspector only)
16 //! - `q` / Esc — close pager
17
18 use std::cell::{Cell, RefCell};
19 use std::ops::Range;
20
21 use crossterm::event::{
22 KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
23 };
24 use ratatui::{
25 buffer::Buffer,
26 layout::Rect,
27 style::{Color, Modifier, Style},
28 text::{Line, Span},
29 widgets::{Paragraph, Widget, Wrap},
30 };
31 use unicode_segmentation::UnicodeSegmentation;
32 use unicode_width::UnicodeWidthStr;
33
34 use crate::tui::views::rounded::{render_rounded_footer, render_rounded_surface};
35 use crate::tui::views::{
36 ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, action_footer_lines,
37 render_panel_scroll_rail,
38 };
39 use codewhale_localization::{Locale, MessageId, tr};
40 use codewhale_palette as palette;
41 use codewhale_tui_kit::diff_render::DiffSummaryLabels;
42 use codewhale_tui_kit::ui_text::grapheme_display_width;
43
44 #[derive(Debug, Clone)]
45 struct PagerDestructiveAction {
46 key: char,
47 label: String,
48 confirm_label: String,
49 event: ViewEvent,
50 armed: bool,
51 }
52
53 const EVIDENCE_WINDOW_BYTES: usize = 128 * 1024;
54 const PAGER_RETAINED_ROWS: usize = 512;
55 const PAGER_ROW_BYTES: usize = 32 * 1024;
56
57 struct OwnedEvidence {
58 workspace: std::path::PathBuf,
59 session: String,
60 reference: String,
61 label: String,
62 page: usize,
63 body_start: usize,
64 binary: bool,
65 digest: Option<String>,
66 total: u64,
67 offset: u64,
68 end: u64,
69 previous: Vec<u64>,
70 encoding: &'static str,
71 ready: bool,
72 pending: Option<(
73 tokio_util::sync::CancellationToken,
74 tokio::sync::oneshot::Receiver<Result<EvidenceWindow, String>>,
75 )>,
76 }
77
78 struct EvidenceWindow {
79 binary: bool,
80 text: String,
81 copy: String,
82 digest: String,
83 total: u64,
84 offset: u64,
85 end: u64,
86 encoding: &'static str,
87 }
88
89 impl Drop for OwnedEvidence {
90 fn drop(&mut self) {
91 if let Some((cancel, _)) = self.pending.take() {
92 cancel.cancel();
93 }
94 }
95 }
96
97 impl OwnedEvidence {
98 fn request(&mut self, offset: u64) {
99 if let Some((cancel, _)) = self.pending.take() {
100 cancel.cancel();
101 }
102 let cancel = tokio_util::sync::CancellationToken::new();
103 let context = codewhale_engine::tools::ToolContext::new(self.workspace.clone())
104 .with_state_namespace(self.session.clone())
105 .with_cancel_token(cancel.clone());
106 let mut input = serde_json::json!({
107 "ref": self.reference,
108 "mode": "bytes",
109 "offset": offset,
110 "length": EVIDENCE_WINDOW_BYTES,
111 "max_bytes": EVIDENCE_WINDOW_BYTES,
112 });
113 if let Some(digest) = self.digest.as_ref() {
114 input["expected_sha256"] = serde_json::json!(digest);
115 }
116 let (send, receive) = tokio::sync::oneshot::channel();
117 self.ready = false;
118 if let Ok(runtime) = tokio::runtime::Handle::try_current() {
119 runtime.spawn(async move {
120 use codewhale_engine::tools::spec::ToolSpec as _;
121 let result = codewhale_engine::tools::tool_result_retrieval::RetrieveToolResultTool
122 .execute(input, &context)
123 .await
124 .map_err(|error| error.to_string())
125 .and_then(|result| evidence_window(&result.content, offset));
126 let _ = send.send(result);
127 });
128 }
129 self.pending = Some((cancel, receive));
130 }
131 }
132
133 fn evidence_window(content: &str, requested: u64) -> Result<EvidenceWindow, String> {
134 use base64::Engine as _;
135 if content.len()
136 > EVIDENCE_WINDOW_BYTES * 2
137 + codewhale_engine::tools::tool_result_retrieval::MAX_REFERENCE_BYTES * 6
138 {
139 return Err("evidence window rejected".to_string());
140 }
141 let value: serde_json::Value =
142 serde_json::from_str(content).map_err(|error| error.to_string())?;
143 let total = value
144 .get("total_bytes")
145 .and_then(serde_json::Value::as_u64)
146 .ok_or_else(|| "evidence window field missing".to_string())?;
147 let offset = value
148 .get("offset")
149 .and_then(serde_json::Value::as_u64)
150 .ok_or_else(|| "evidence window field missing".to_string())?;
151 let digest = value
152 .get("sha256")
153 .and_then(serde_json::Value::as_str)
154 .ok_or_else(|| "evidence window field missing".to_string())?;
155 let data = value
156 .get("data")
157 .and_then(serde_json::Value::as_str)
158 .ok_or_else(|| "evidence window field missing".to_string())?;
159 if value.get("mode").and_then(serde_json::Value::as_str) != Some("bytes")
160 || value.get("encoding").and_then(serde_json::Value::as_str) != Some("base64")
161 || offset != requested
162 || total > 512 * 1024 * 1024
163 || offset > total
164 || digest.len() != 64
165 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit())
166 {
167 return Err("evidence window rejected".to_string());
168 }
169 let bytes = base64::engine::general_purpose::STANDARD
170 .decode(data)
171 .map_err(|error| error.to_string())?;
172 if bytes.len() > EVIDENCE_WINDOW_BYTES
173 || bytes.len() as u64 > total - offset
174 || value
175 .get("returned_bytes")
176 .and_then(serde_json::Value::as_u64)
177 != Some(bytes.len() as u64)
178 {
179 return Err("evidence window rejected".to_string());
180 }
181 if bytes.is_empty() && offset < total {
182 return Err("evidence window rejected".to_string());
183 }
184 let text_prefix = match std::str::from_utf8(&bytes) {
185 Ok(text) => Some(text),
186 Err(error)
187 if error.error_len().is_none()
188 && error.valid_up_to() > 0
189 && offset + (bytes.len() as u64) < total =>
190 {
191 std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()
192 }
193 Err(_) => None,
194 };
195 let (text, copy, end, encoding, actual_offset, binary) = if let Some(text) = text_prefix {
196 let mut sanitized = String::with_capacity(text.len());
197 codewhale_sanitize::sanitize::strip_ansi_into(text, &mut sanitized);
198 let (copy, encoding) = if sanitized == text {
199 (text.to_string(), "UTF8")
200 } else {
201 (
202 base64::engine::general_purpose::STANDARD.encode(text.as_bytes()),
203 "base64",
204 )
205 };
206 (
207 sanitized,
208 copy,
209 offset + text.len() as u64,
210 encoding,
211 offset,
212 false,
213 )
214 } else {
215 let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
216 (
217 encoded.clone(),
218 encoded,
219 offset + bytes.len() as u64,
220 "base64",
221 offset,
222 true,
223 )
224 };
225 Ok(EvidenceWindow {
226 binary,
227 text,
228 copy,
229 digest: digest.to_ascii_lowercase(),
230 total,
231 offset: actual_offset,
232 end,
233 encoding,
234 })
235 }
236
237 /// One independently copyable document in a pager. Most pagers contain a
238 /// single page; Turn Inspector uses several so each turn stays isolated while
239 /// retaining the pager's existing scroll/search/copy behavior.
240 #[derive(Debug, Clone)]
241 pub(crate) struct PagerPage {
242 title: String,
243 /// What the page shows. Its display rows are wrapped from this to the
244 /// width the body really gets at render time, so one row is one scroll
245 /// step whatever the terminal width.
246 source: PagerSource,
247 /// Width to lay the page out at before its first render (`0`: unwrapped).
248 first_width: usize,
249 rows: RefCell<PagerRows>,
250 export_markdown: Option<String>,
251 copy_text: Option<String>,
252 answer_text: Option<String>,
253 }
254
255 #[derive(Debug, Clone)]
256 enum PagerSource {
257 /// Sanitized text; `c` / `y` copy it verbatim when no explicit copy
258 /// payload is attached.
259 Text(String),
260 /// Pre-styled lines, wrapped with their styles intact.
261 Lines(Vec<Line<'static>>),
262 Diff(String, DiffSummaryLabels),
263 }
264
265 #[derive(Debug, Clone, Default)]
266 pub(super) struct PagerRows {
267 width: Option<usize>,
268 pub(super) start: usize,
269 pub(super) total: usize,
270 pub(super) escaped: bool,
271 pub(super) continued: bool,
272 clipped_rows: usize,
273 clipped_bytes: usize,
274 plain: Vec<String>,
275 pub(super) styled: Vec<Line<'static>>,
276 pub(super) origin: Vec<usize>,
277 }
278
279 impl PagerRows {
280 fn push(
281 &mut self,
282 cells: &[(char, usize)],
283 range: Range<usize>,
284 origin: usize,
285 style: Option<&Line<'static>>,
286 ) {
287 let index = self.total;
288 self.total = self.total.saturating_add(1);
289 if index < self.start || self.plain.len() >= PAGER_RETAINED_ROWS {
290 return;
291 }
292 let text: String = cells[range.clone()].iter().map(|&(ch, _)| ch).collect();
293 if let Some(line) = style {
294 let mut spans = Vec::new();
295 let mut run = String::new();
296 let mut run_span: Option<usize> = None;
297 for &(ch, span) in &cells[range] {
298 if run_span.is_some_and(|current| current != span) {
299 spans.push(Span::styled(
300 std::mem::take(&mut run),
301 line.spans[run_span.unwrap()].style,
302 ));
303 }
304 run_span = Some(span);
305 run.push(ch);
306 }
307 if let Some(span) = run_span {
308 spans.push(Span::styled(run, line.spans[span].style));
309 }
310 let mut row = Line::from(spans).style(line.style);
311 row.alignment = line.alignment;
312 self.styled.push(row);
313 }
314 self.plain.push(text);
315 self.origin.push(origin);
316 }
317
318 fn wrap_text(source: &str, width: usize, start: usize) -> Self {
319 let mut rows = Self {
320 width: Some(width),
321 start,
322 ..Self::default()
323 };
324 for (origin, raw) in source.lines().enumerate() {
325 let (escaped, continued) =
326 for_each_wrapped_range(std::iter::once((raw, 0)), width, |cells, range| {
327 rows.push(cells, range, origin, None);
328 });
329 rows.escaped |= escaped;
330 rows.continued |= continued;
331 }
332 rows
333 }
334
335 #[cfg(test)]
336 pub(super) fn wrap_lines(lines: &[Line<'static>], width: usize) -> Self {
337 Self::wrap_lines_window(lines, width, 0)
338 }
339
340 pub(super) fn wrap_lines_window(lines: &[Line<'static>], width: usize, start: usize) -> Self {
341 let mut rows = Self {
342 width: Some(width),
343 start,
344 ..Self::default()
345 };
346 for (origin, line) in lines.iter().enumerate() {
347 let (escaped, continued) = for_each_wrapped_range(
348 line.spans
349 .iter()
350 .enumerate()
351 .map(|(i, span)| (span.content.as_ref(), i)),
352 width,
353 |cells, range| {
354 rows.push(cells, range, origin, Some(line));
355 },
356 );
357 rows.escaped |= escaped;
358 rows.continued |= continued;
359 }
360 rows
361 }
362
363 pub(super) fn line_range(
364 lines: &[Line<'static>],
365 width: usize,
366 from: usize,
367 to: usize,
368 ) -> (usize, usize, usize, bool, bool) {
369 let mut escaped = false;
370 let mut continued = false;
371 let mut total = 0usize;
372 let mut first = None;
373 let mut last = None;
374 for (origin, line) in lines.iter().enumerate() {
375 let flags = for_each_wrapped_range(
376 line.spans
377 .iter()
378 .enumerate()
379 .map(|(i, span)| (span.content.as_ref(), i)),
380 width,
381 |_, _| {
382 if origin >= from && first.is_none() {
383 first = Some(total);
384 }
385 if origin <= to {
386 last = Some(total);
387 }
388 total = total.saturating_add(1);
389 },
390 );
391 escaped |= flags.0;
392 continued |= flags.1;
393 }
394 (
395 first.unwrap_or(total),
396 last.unwrap_or(0),
397 total,
398 escaped,
399 continued,
400 )
401 }
402 pub(super) fn display_notice(&self, locale: Locale, questions: bool) -> Option<String> {
403 let mut notice = String::new();
404 if self.escaped {
405 notice.push_str(&tr(
406 locale,
407 if questions {
408 MessageId::UserInputUnicodeEscapes
409 } else {
410 MessageId::PagerUnicodeEscapes
411 },
412 ));
413 }
414 if self.continued {
415 if !notice.is_empty() {
416 notice.push_str(" · ");
417 }
418 notice.push_str(&tr(locale, MessageId::PagerDisplayContinuation));
419 }
420 (!notice.is_empty()).then_some(notice)
421 }
422 }
423
424 struct PageSearch {
425 total: usize,
426 index: usize,
427 row: Option<usize>,
428 origin: Option<usize>,
429 }
430
431 impl PagerPage {
432 pub(crate) fn from_text(title: impl Into<String>, text: &str, width: u16) -> Self {
433 // Pager bodies frequently carry tool output or worker transcripts.
434 // Keep the same terminal-injection boundary as the single-page path.
435 let mut sanitized = String::with_capacity(text.len());
436 codewhale_sanitize::sanitize::strip_ansi_into(text, &mut sanitized);
437 Self::new(title, PagerSource::Text(sanitized), usize::from(width))
438 }
439
440 fn from_lines(title: impl Into<String>, lines: Vec<Line<'static>>) -> Self {
441 Self::new(title, PagerSource::Lines(lines), 0)
442 }
443
444 fn new(title: impl Into<String>, source: PagerSource, first_width: usize) -> Self {
445 Self {
446 title: title.into(),
447 source,
448 first_width,
449 rows: RefCell::default(),
450 export_markdown: None,
451 copy_text: None,
452 answer_text: None,
453 }
454 }
455
456 fn layout(&self, width: usize, start: usize, needed: usize) -> bool {
457 {
458 let rows = self.rows.borrow();
459 if rows.width == Some(width)
460 && start >= rows.start
461 && start.saturating_add(needed).min(rows.total)
462 <= rows.start.saturating_add(rows.plain.len())
463 {
464 return false;
465 }
466 }
467 let scan = |start| match &self.source {
468 PagerSource::Text(source) => PagerRows::wrap_text(source, width, start),
469 PagerSource::Lines(lines) => PagerRows::wrap_lines_window(lines, width, start),
470 PagerSource::Diff(diff, labels) => {
471 let rendered = codewhale_tui_kit::diff_render::render_diff_window(
472 diff,
473 u16::try_from(width).unwrap_or(u16::MAX),
474 start,
475 PAGER_RETAINED_ROWS,
476 labels,
477 );
478 let total = rendered.lines.len().saturating_add(rendered.omitted_rows);
479 let plain = rendered.lines.iter().map(line_to_string).collect();
480 PagerRows {
481 width: Some(width),
482 start,
483 total,
484 clipped_rows: rendered.clipped_rows,
485 clipped_bytes: rendered.clipped_bytes,
486 escaped: false,
487 continued: false,
488 plain,
489 styled: rendered.lines,
490 origin: rendered.origins,
491 }
492 }
493 };
494 let mut rows = scan(start);
495 if start >= rows.total && rows.total > 0 {
496 rows = scan(rows.total.saturating_sub(needed.max(1)));
497 }
498 *self.rows.borrow_mut() = rows;
499 true
500 }
501
502 fn row_for_origin(&self, width: usize, origin: usize) -> usize {
503 match &self.source {
504 PagerSource::Text(source) => {
505 let mut rows = 0usize;
506 for raw in source.lines().take(origin) {
507 for_each_wrapped_range(std::iter::once((raw, 0)), width, |_, _| {
508 rows = rows.saturating_add(1);
509 });
510 }
511 rows
512 }
513 PagerSource::Lines(lines) => PagerRows::line_range(lines, width, origin, origin).0,
514 PagerSource::Diff(diff, labels) => codewhale_tui_kit::diff_render::diff_row_for_origin(
515 diff,
516 u16::try_from(width).unwrap_or(u16::MAX),
517 origin,
518 labels,
519 ),
520 }
521 }
522
523 fn search(
524 &self,
525 width: usize,
526 query: &str,
527 selected: usize,
528 anchor: Option<usize>,
529 ) -> PageSearch {
530 let query = query.trim().to_ascii_lowercase();
531 let mut result = PageSearch {
532 total: 0,
533 index: 0,
534 row: None,
535 origin: None,
536 };
537 if query.is_empty() {
538 return result;
539 }
540 if let PagerSource::Diff(diff, labels) = &self.source {
541 let found = if let Some(origin) = anchor {
542 codewhale_tui_kit::diff_render::search_diff_from_origin(
543 diff,
544 u16::try_from(width).unwrap_or(u16::MAX),
545 &query,
546 origin,
547 labels,
548 )
549 } else {
550 codewhale_tui_kit::diff_render::search_diff(
551 diff,
552 u16::try_from(width).unwrap_or(u16::MAX),
553 &query,
554 selected,
555 labels,
556 )
557 };
558 result.total = found.total_matches;
559 result.row = found.selected_row;
560 result.origin = found.selected_origin;
561 result.index = found.selected_index;
562 return result;
563 }
564 let mut row_index = 0usize;
565 let mut visit = |origin: usize, text: String| {
566 if text.to_ascii_lowercase().contains(&query) {
567 let choose = anchor.map_or(result.total == selected, |line| {
568 result.row.is_none() && origin >= line
569 });
570 if choose {
571 result.row = Some(row_index);
572 result.origin = Some(origin);
573 result.index = result.total;
574 }
575 result.total = result.total.saturating_add(1);
576 }
577 row_index = row_index.saturating_add(1);
578 };
579 match &self.source {
580 PagerSource::Text(source) => {
581 for (origin, raw) in source.lines().enumerate() {
582 for_each_wrapped_range(std::iter::once((raw, 0)), width, |cells, range| {
583 visit(origin, cells[range].iter().map(|&(ch, _)| ch).collect());
584 });
585 }
586 }
587 PagerSource::Lines(lines) => {
588 for (origin, line) in lines.iter().enumerate() {
589 for_each_wrapped_range(
590 line.spans
591 .iter()
592 .enumerate()
593 .map(|(i, span)| (span.content.as_ref(), i)),
594 width,
595 |cells, range| {
596 visit(origin, cells[range].iter().map(|&(ch, _)| ch).collect());
597 },
598 );
599 }
600 }
601 PagerSource::Diff(..) => unreachable!(),
602 }
603 if result.row.is_none() && result.total > 0 {
604 return self.search(width, &query, 0, None);
605 }
606 result
607 }
608
609 fn rows(&self) -> std::cell::Ref<'_, PagerRows> {
610 if self.rows.borrow().width.is_none() {
611 self.layout(self.first_width, 0, 1);
612 }
613 self.rows.borrow()
614 }
615
616 fn row_count(&self) -> usize {
617 self.rows().total
618 }
619
620 /// What `c` / `y` copy without an explicit payload: the source, never the
621 /// display wrapping.
622 fn source_text(&self) -> String {
623 match &self.source {
624 PagerSource::Text(source) | PagerSource::Diff(source, _) => source.clone(),
625 PagerSource::Lines(lines) => lines
626 .iter()
627 .map(line_to_string)
628 .collect::<Vec<_>>()
629 .join("\n"),
630 }
631 }
632
633 pub(crate) fn with_export_markdown(mut self, markdown: impl Into<String>) -> Self {
634 self.export_markdown = Some(markdown.into());
635 self
636 }
637
638 pub(crate) fn with_copy_text(mut self, text: impl Into<String>) -> Self {
639 self.copy_text = Some(text.into());
640 self
641 }
642
643 /// Attach the clean final assistant answer that the `a` key copies to
644 /// the clipboard. Only surfaces that can produce an answer-only payload
645 /// (Turn Inspector pages, assistant detail pagers) set this; the pager
646 /// body itself stays free to render scaffolding around the answer.
647 pub(crate) fn with_copy_answer(mut self, text: impl Into<String>) -> Self {
648 self.answer_text = Some(text.into());
649 self
650 }
651 }
652
653 pub struct PagerView {
654 locale: Locale,
655 pages: Vec<PagerPage>,
656 page_index: usize,
657 /// First visible row. A cell because a resize re-wraps the rows during
658 /// render, which remaps it to keep the same source line on top.
659 scroll: Cell<usize>,
660 search_input: String,
661 search_index: Cell<usize>,
662 search_total: Cell<usize>,
663 search_row: Cell<Option<usize>>,
664 search_origin: Cell<Option<usize>>,
665 search_mode: bool,
666 pending_g: bool,
667 /// Cached visible content height from the last render. Used by paging
668 /// keys (Ctrl+D/U, Ctrl+F/B, Space, etc.) to compute scroll deltas
669 /// without access to the render area.
670 last_visible_height: Cell<usize>,
671 /// Optional inspector-owned destructive action. It requires two presses
672 /// (or key then Enter); Esc disarms before it closes the pager.
673 destructive_action: Option<PagerDestructiveAction>,
674 action_area: Cell<Option<Rect>>,
675 live_shell_job: Option<String>,
676 follow: bool,
677 evidence: Option<OwnedEvidence>,
678 }
679
680 impl PagerView {
681 pub fn new(title: impl Into<String>, lines: Vec<Line<'static>>) -> Self {
682 Self::from_pages(vec![PagerPage::from_lines(title, lines)], 0)
683 }
684
685 /// Build an opt-in multi-page pager and open the requested page. Page
686 /// switching is deliberately unavailable to ordinary one-page pagers.
687 pub(crate) fn from_pages(pages: Vec<PagerPage>, initial_page: usize) -> Self {
688 assert!(!pages.is_empty(), "a pager needs at least one page");
689 let page_index = initial_page.min(pages.len().saturating_sub(1));
690 Self {
691 pages,
692 locale: Locale::En,
693 page_index,
694 scroll: Cell::new(0),
695 search_input: String::new(),
696 search_index: Cell::new(0),
697 search_total: Cell::new(0),
698 search_row: Cell::new(None),
699 search_origin: Cell::new(None),
700 search_mode: false,
701 pending_g: false,
702 last_visible_height: Cell::new(0),
703 destructive_action: None,
704 action_area: Cell::new(None),
705 live_shell_job: None,
706 follow: false,
707 evidence: None,
708 }
709 }
710
711 pub(crate) fn has_owned_evidence(&self) -> bool {
712 self.evidence.is_some()
713 }
714
715 pub(crate) fn with_owned_evidence(
716 mut self,
717 workspace: std::path::PathBuf,
718 session: String,
719 reference: String,
720 ) -> Self {
721 let page = self.pages.len();
722 let label = self.current_page().title.clone();
723 self.pages.push(PagerPage::from_text("", "", 80));
724 self.evidence = Some(OwnedEvidence {
725 workspace,
726 session,
727 reference,
728 label,
729 page,
730 body_start: 0,
731 binary: false,
732 digest: None,
733 total: 0,
734 offset: 0,
735 end: 0,
736 previous: Vec::new(),
737 encoding: "UTF8",
738 ready: false,
739 pending: None,
740 });
741 self.evidence.as_mut().unwrap().request(0);
742 self.localize_evidence_page();
743 self.switch_page(page);
744 self
745 }
746
747 fn evidence_request(&mut self, offset: u64) {
748 if let Some(evidence) = self.evidence.as_mut() {
749 evidence.request(offset);
750 let page = &mut self.pages[evidence.page];
751 page.copy_text = None;
752 *page.rows.get_mut() = PagerRows::default();
753 self.scroll.set(0);
754 self.search_input.clear();
755 self.search_index.set(0);
756 self.search_total.set(0);
757 self.search_row.set(None);
758 self.search_origin.set(None);
759 self.search_mode = false;
760 }
761 self.localize_evidence_page();
762 }
763
764 fn localize_evidence_page(&mut self) {
765 let Some(evidence) = self.evidence.as_mut() else {
766 return;
767 };
768 let page = &mut self.pages[evidence.page];
769 if evidence.pending.is_some() {
770 page.title = tr(self.locale, MessageId::PagerEvidenceLoadingTitle)
771 .replace("{label}", &evidence.label);
772 page.source =
773 PagerSource::Text(tr(self.locale, MessageId::PagerEvidenceVerifying).into_owned());
774 } else if evidence.ready {
775 if let PagerSource::Text(source) = &mut page.source {
776 let body = source.split_off(evidence.body_start);
777 page.title = tr(self.locale, MessageId::PagerEvidenceRangeTitle)
778 .replace("{start}", &evidence.offset.to_string())
779 .replace("{end}", &evidence.end.to_string())
780 .replace("{total}", &evidence.total.to_string())
781 .replace("{encoding}", evidence.encoding)
782 .replace("{label}", &evidence.label);
783 let mut header = tr(self.locale, MessageId::PagerEvidenceVerifiedRange)
784 .replace("{digest}", evidence.digest.as_deref().unwrap_or_default())
785 .replace("{start}", &evidence.offset.to_string())
786 .replace("{end}", &evidence.end.to_string())
787 .replace("{total}", &evidence.total.to_string())
788 .replace("{encoding}", evidence.encoding);
789 header.push_str("\n\n");
790 if evidence.binary {
791 header.push_str(&tr(self.locale, MessageId::PagerEvidenceBinary));
792 header.push_str("\n\n");
793 }
794 evidence.body_start = header.len();
795 header.push_str(&body);
796 *source = header;
797 }
798 } else {
799 page.title = tr(self.locale, MessageId::PagerEvidenceUnavailableTitle)
800 .replace("{label}", &evidence.label);
801 page.source = PagerSource::Text(
802 tr(self.locale, MessageId::PagerEvidenceUnavailable).into_owned(),
803 );
804 }
805 *page.rows.get_mut() = PagerRows::default();
806 }
807
808 pub(crate) fn with_live_shell_job(mut self, job_id: impl Into<String>) -> Self {
809 self.live_shell_job = Some(job_id.into());
810 self
811 }
812
813 pub(crate) fn live_shell_job(&self) -> Option<&str> {
814 self.live_shell_job.as_deref()
815 }
816
817 pub(crate) fn replace_live_text(&mut self, text: &str) -> bool {
818 let page = self.current_page();
819 if page.copy_text.as_deref() == Some(text) {
820 return false;
821 }
822 if self.scroll.get() >= self.max_scroll() {
823 self.follow = true;
824 }
825 let mut sanitized = String::with_capacity(text.len());
826 codewhale_sanitize::sanitize::strip_ansi_into(text, &mut sanitized);
827 let page = self.current_page_mut();
828 page.source = PagerSource::Text(sanitized);
829 page.copy_text = Some(text.to_string());
830 *page.rows.get_mut() = PagerRows::default();
831 if !self.search_input.trim().is_empty() {
832 self.update_search_matches();
833 }
834 true
835 }
836
837 pub(crate) fn end_live_shell_job(&mut self) {
838 self.live_shell_job = None;
839 self.destructive_action = None;
840 self.action_area.set(None);
841 }
842
843 /// Attach a compact Markdown export (e.g. the #4108 turn handoff) that the
844 /// `e` key copies to the clipboard. Only the Turn Inspector pager sets this;
845 /// other pagers leave `e` inert.
846 #[cfg(test)]
847 pub fn with_export_markdown(mut self, markdown: impl Into<String>) -> Self {
848 self.current_page_mut().export_markdown = Some(markdown.into());
849 self
850 }
851
852 /// Preserve a source-faithful payload for `c` / `y` while the rendered
853 /// pager remains free to wrap content to its viewport.
854 pub fn with_copy_text(mut self, text: impl Into<String>) -> Self {
855 self.current_page_mut().copy_text = Some(text.into());
856 self
857 }
858
859 /// Attach the clean final assistant answer that the `a` key copies
860 /// (see [`PagerPage::with_copy_answer`]).
861 pub fn with_copy_answer(mut self, text: impl Into<String>) -> Self {
862 self.current_page_mut().answer_text = Some(text.into());
863 self
864 }
865
866 /// Attach a two-step destructive action to this pager. Work Graph
867 /// inspectors use this to keep Stop inside the detail surface while
868 /// reusing the existing command/agent cancellation events.
869 pub fn with_destructive_action(
870 mut self,
871 key: char,
872 label: impl Into<String>,
873 confirm_label: impl Into<String>,
874 event: ViewEvent,
875 ) -> Self {
876 self.destructive_action = Some(PagerDestructiveAction {
877 key,
878 label: label.into(),
879 confirm_label: confirm_label.into(),
880 event,
881 armed: false,
882 });
883 self
884 }
885
886 pub fn from_text(title: impl Into<String>, text: &str, width: u16) -> Self {
887 Self::from_pages(vec![PagerPage::from_text(title, text, width)], 0)
888 }
889
890 pub(crate) fn from_diff(title: impl Into<String>, diff: String, width: u16) -> Self {
891 let page = PagerPage::new(
892 title,
893 PagerSource::Diff(diff, DiffSummaryLabels::default()),
894 usize::from(width),
895 );
896 Self::from_pages(vec![page], 0)
897 }
898
899 /// Reuse the inspector confirmation control for token-bound commands.
900 /// Copy exposes the exact command; confirmation dispatches it unchanged.
901 pub(crate) fn command_review(
902 title: impl Into<String>,
903 text: &str,
904 width: u16,
905 command: String,
906 locale: codewhale_localization::Locale,
907 ) -> Self {
908 let confirm = codewhale_localization::tr(
909 locale,
910 codewhale_localization::MessageId::PagerActionConfirm,
911 )
912 .into_owned();
913 let mut view = Self::from_text(title, text, width)
914 .with_copy_text(command.clone())
915 .with_destructive_action(
916 'y',
917 confirm.clone(),
918 confirm,
919 ViewEvent::CommandPaletteSelected {
920 action: crate::tui::views::CommandPaletteAction::ExecuteCommand { command },
921 },
922 );
923 view.locale = locale;
924 view
925 }
926
927 fn activate_destructive_action(&mut self) -> ViewAction {
928 self.pending_g = false;
929 let Some(action) = self.destructive_action.as_mut() else {
930 return ViewAction::None;
931 };
932 if action.armed {
933 ViewAction::EmitAndClose(action.event.clone())
934 } else {
935 action.armed = true;
936 ViewAction::None
937 }
938 }
939
940 fn current_page(&self) -> &PagerPage {
941 &self.pages[self.page_index]
942 }
943
944 fn current_page_mut(&mut self) -> &mut PagerPage {
945 &mut self.pages[self.page_index]
946 }
947
948 fn switch_page(&mut self, page_index: usize) {
949 let page_index = page_index.min(self.pages.len().saturating_sub(1));
950 if page_index == self.page_index {
951 return;
952 }
953 self.page_index = page_index;
954 self.scroll.set(0);
955 self.search_input.clear();
956 self.search_index.set(0);
957 self.search_total.set(0);
958 self.search_row.set(None);
959 self.search_origin.set(None);
960 self.search_mode = false;
961 self.pending_g = false;
962 self.follow = false;
963 }
964
965 fn scroll_up(&mut self, amount: usize) {
966 self.scroll.set(self.scroll.get().saturating_sub(amount));
967 self.follow = false;
968 }
969
970 fn scroll_down(&mut self, amount: usize, max_scroll: usize) {
971 self.scroll
972 .set(self.scroll.get().saturating_add(amount).min(max_scroll));
973 self.follow = self.live_shell_job.is_some() && self.scroll.get() >= max_scroll;
974 }
975
976 fn scroll_to_top(&mut self) {
977 self.scroll.set(0);
978 self.follow = false;
979 }
980
981 fn scroll_to_bottom(&mut self, max_scroll: usize) {
982 self.scroll.set(max_scroll);
983 self.follow = self.live_shell_job.is_some();
984 }
985
986 /// Plain-text rendered body of the pager joined with `\n`. This reflects
987 /// width-based display wrapping, so it is not what the clipboard gets:
988 /// an explicit copy payload wins, then the page's own source.
989 #[cfg(test)]
990 pub fn body_text(&self) -> String {
991 self.current_page().rows().plain.join("\n")
992 }
993
994 fn clipboard_text(&self) -> String {
995 let page = self.current_page();
996 page.copy_text.clone().unwrap_or_else(|| page.source_text())
997 }
998
999 /// The pager's title bar text. Used by tests to assert the raw-detail
1000 /// pager is framed at leaf scope (#4105).
1001 #[cfg(test)]
1002 pub(crate) fn title(&self) -> &str {
1003 &self.current_page().title
1004 }
1005
1006 /// Return the page height (in lines) used for paging keys.
1007 ///
1008 /// Falls back to a small constant (10) before the first render so the
1009 /// pager still responds to paging keys when invoked synthetically (e.g.
1010 /// in unit tests). After the first render, the cached value reflects
1011 /// the actual visible content area.
1012 fn page_height(&self) -> usize {
1013 let cached = self.last_visible_height.get();
1014 if cached == 0 { 10 } else { cached }
1015 }
1016
1017 /// Half a page, rounded up so a single press always moves at least one line.
1018 fn half_page_height(&self) -> usize {
1019 let page = self.page_height();
1020 page.div_ceil(2).max(1)
1021 }
1022
1023 fn max_scroll(&self) -> usize {
1024 // Match the render-side clamp so G/End land at the visible bottom and
1025 // k/Up immediately scroll back up by one line.
1026 self.current_page()
1027 .row_count()
1028 .saturating_sub(self.page_height())
1029 }
1030
1031 fn start_search(&mut self) {
1032 self.search_mode = true;
1033 self.search_input.clear();
1034 self.search_index.set(0);
1035 self.search_total.set(0);
1036 self.search_row.set(None);
1037 self.search_origin.set(None);
1038 }
1039
1040 fn install_search(&self, selected: usize, anchor: Option<usize>) {
1041 let page = self.current_page();
1042 let width = page.rows().width.unwrap_or(page.first_width);
1043 let found = page.search(width, &self.search_input, selected, anchor);
1044 self.search_total.set(found.total);
1045 self.search_index.set(found.index);
1046 self.search_row.set(found.row);
1047 self.search_origin.set(found.origin);
1048 }
1049
1050 fn update_search_matches(&mut self) {
1051 self.install_search(0, None);
1052 }
1053
1054 fn layout(&self, width: usize, needed: usize) {
1055 let page = self.current_page();
1056 let (old_width, top) = {
1057 let rows = page.rows.borrow();
1058 (
1059 rows.width,
1060 self.scroll
1061 .get()
1062 .checked_sub(rows.start)
1063 .and_then(|i| rows.origin.get(i))
1064 .copied(),
1065 )
1066 };
1067 if old_width != Some(width) {
1068 if let Some(top) = top {
1069 self.scroll.set(page.row_for_origin(width, top));
1070 }
1071 page.layout(width, self.scroll.get(), needed);
1072 if !self.search_input.trim().is_empty() {
1073 let found = page.search(
1074 width,
1075 &self.search_input,
1076 self.search_index.get(),
1077 self.search_origin.get(),
1078 );
1079 self.search_total.set(found.total);
1080 self.search_index.set(found.index);
1081 self.search_row.set(found.row);
1082 self.search_origin.set(found.origin);
1083 }
1084 } else {
1085 page.layout(width, self.scroll.get(), needed);
1086 }
1087 }
1088
1089 fn jump_to_match(&mut self) {
1090 if let Some(row) = self.search_row.get() {
1091 self.scroll.set(row);
1092 self.follow = false;
1093 }
1094 }
1095
1096 fn next_match(&mut self) {
1097 let total = self.search_total.get();
1098 if total == 0 {
1099 return;
1100 }
1101 self.install_search((self.search_index.get() + 1) % total, None);
1102 self.jump_to_match();
1103 }
1104
1105 fn prev_match(&mut self) {
1106 let total = self.search_total.get();
1107 if total == 0 {
1108 return;
1109 }
1110 self.install_search(
1111 if self.search_index.get() == 0 {
1112 total - 1
1113 } else {
1114 self.search_index.get() - 1
1115 },
1116 None,
1117 );
1118 self.jump_to_match();
1119 }
1120 }
1121
1122 impl ModalView for PagerView {
1123 fn set_locale(&mut self, locale: Locale) {
1124 if self.locale == locale {
1125 return;
1126 }
1127 self.locale = locale;
1128 for page in &mut self.pages {
1129 if let PagerSource::Diff(_, labels) = &mut page.source {
1130 *labels = crate::tui::history::diff_summary_labels(locale);
1131 page.rows = RefCell::default();
1132 }
1133 }
1134 self.localize_evidence_page();
1135 if !self.search_input.trim().is_empty() {
1136 self.update_search_matches();
1137 }
1138 }
1139
1140 fn kind(&self) -> ModalKind {
1141 ModalKind::Pager
1142 }
1143
1144 fn tick(&mut self) -> ViewAction {
1145 let completed = self.evidence.as_mut().and_then(|evidence| {
1146 evidence
1147 .pending
1148 .as_mut()
1149 .and_then(|(_, receive)| match receive.try_recv() {
1150 Ok(result) => Some(result),
1151 Err(tokio::sync::oneshot::error::TryRecvError::Empty) => None,
1152 Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
1153 Some(Err("evidence retrieval task ended".to_string()))
1154 }
1155 })
1156 });
1157 let Some(result) = completed else {
1158 return ViewAction::None;
1159 };
1160 let evidence = self.evidence.as_mut().unwrap();
1161 evidence.pending.take();
1162 let page = &mut self.pages[evidence.page];
1163 match result {
1164 Ok(window)
1165 if evidence
1166 .digest
1167 .as_ref()
1168 .is_none_or(|digest| digest == &window.digest) =>
1169 {
1170 page.source = PagerSource::Text(window.text);
1171 evidence.body_start = 0;
1172 evidence.binary = window.binary;
1173 page.copy_text = Some(window.copy);
1174 evidence.digest = Some(window.digest);
1175 evidence.total = window.total;
1176 evidence.offset = window.offset;
1177 evidence.end = window.end;
1178 evidence.encoding = window.encoding;
1179 evidence.ready = true;
1180 }
1181 Ok(_) => {
1182 tracing::warn!("evidence window digest changed during retrieval");
1183 page.copy_text = None;
1184 evidence.ready = false;
1185 }
1186 Err(error) => {
1187 tracing::warn!(%error, "evidence window retrieval failed");
1188 page.copy_text = None;
1189 evidence.ready = false;
1190 }
1191 }
1192 self.localize_evidence_page();
1193 ViewAction::Redraw
1194 }
1195
1196 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
1197 self
1198 }
1199
1200 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
1201 if self.search_mode {
1202 match key.code {
1203 KeyCode::Enter => {
1204 self.search_mode = false;
1205 self.update_search_matches();
1206 self.jump_to_match();
1207 return ViewAction::None;
1208 }
1209 KeyCode::Esc => {
1210 // Bail out of search mode AND drop the current match list
1211 // so the user gets back to the un-highlighted view —
1212 // codex-style behavior. To resume from where they left
1213 // off they re-enter `/` and re-type.
1214 self.search_mode = false;
1215 self.search_input.clear();
1216 self.search_index.set(0);
1217 self.search_total.set(0);
1218 self.search_row.set(None);
1219 self.search_origin.set(None);
1220 return ViewAction::None;
1221 }
1222 KeyCode::Backspace => {
1223 self.search_input.pop();
1224 return ViewAction::None;
1225 }
1226 // Ctrl+H is the legacy ASCII backspace many terminals emit.
1227 KeyCode::Char('h')
1228 if key.modifiers.contains(KeyModifiers::CONTROL)
1229 && !key.modifiers.contains(KeyModifiers::ALT) =>
1230 {
1231 self.search_input.pop();
1232 return ViewAction::None;
1233 }
1234 KeyCode::Char(c) => {
1235 self.search_input.push(c);
1236 return ViewAction::None;
1237 }
1238 // All other keys (Up/Down, PageUp/PageDown, etc.) are captured
1239 // in search mode so they don't fall through to the pager body.
1240 _ => return ViewAction::None,
1241 }
1242 }
1243
1244 if self
1245 .evidence
1246 .as_ref()
1247 .is_some_and(|evidence| evidence.page == self.page_index)
1248 {
1249 let control = key.modifiers.contains(KeyModifiers::CONTROL);
1250 let target = match key.code {
1251 KeyCode::Home if control => Some(0),
1252 KeyCode::End if control => self
1253 .evidence
1254 .as_ref()
1255 .filter(|evidence| evidence.ready)
1256 .map(|evidence| evidence.total.saturating_sub(EVIDENCE_WINDOW_BYTES as u64)),
1257 KeyCode::Right | KeyCode::Char(']') => {
1258 self.evidence.as_mut().and_then(|evidence| {
1259 if !evidence.ready || evidence.end >= evidence.total {
1260 return None;
1261 }
1262 if evidence.previous.len() < 8192 {
1263 evidence.previous.push(evidence.offset);
1264 }
1265 Some(evidence.end)
1266 })
1267 }
1268 KeyCode::Left | KeyCode::Char('[') => self.evidence.as_mut().and_then(|evidence| {
1269 if !evidence.ready {
1270 return None;
1271 }
1272 if evidence.offset == 0 {
1273 return None;
1274 }
1275 Some(evidence.previous.pop().unwrap_or_else(|| {
1276 evidence.offset.saturating_sub(EVIDENCE_WINDOW_BYTES as u64)
1277 }))
1278 }),
1279 _ => None,
1280 };
1281 if let Some(offset) = target {
1282 self.evidence_request(offset);
1283 return ViewAction::Redraw;
1284 }
1285 if matches!(
1286 key.code,
1287 KeyCode::Right | KeyCode::Char(']') | KeyCode::Char('[')
1288 ) {
1289 return ViewAction::None;
1290 }
1291 }
1292
1293 if let Some(action) = self.destructive_action.as_mut() {
1294 if key.code == KeyCode::Esc && action.armed {
1295 action.armed = false;
1296 self.pending_g = false;
1297 return ViewAction::None;
1298 }
1299 let matching_key =
1300 matches!(key.code, KeyCode::Char(ch) if ch.eq_ignore_ascii_case(&action.key));
1301 if matching_key || (key.code == KeyCode::Enter && action.armed) {
1302 if key.kind != KeyEventKind::Press
1303 || !key.modifiers.difference(KeyModifiers::SHIFT).is_empty()
1304 {
1305 return ViewAction::None;
1306 }
1307 return self.activate_destructive_action();
1308 }
1309 }
1310
1311 let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
1312 let shift = key.modifiers.contains(KeyModifiers::SHIFT);
1313 let max_scroll = self.max_scroll();
1314
1315 // Ctrl+chord paging keys are matched first because their KeyCode
1316 // also matches the bare `KeyCode::Char(c)` arms below.
1317 if ctrl {
1318 match key.code {
1319 KeyCode::Char('d') | KeyCode::Char('D') => {
1320 self.scroll_down(self.half_page_height(), max_scroll);
1321 self.pending_g = false;
1322 return ViewAction::None;
1323 }
1324 KeyCode::Char('u') | KeyCode::Char('U') => {
1325 self.scroll_up(self.half_page_height());
1326 self.pending_g = false;
1327 return ViewAction::None;
1328 }
1329 KeyCode::Char('f') | KeyCode::Char('F') => {
1330 self.scroll_down(self.page_height(), max_scroll);
1331 self.pending_g = false;
1332 return ViewAction::None;
1333 }
1334 KeyCode::Char('b') | KeyCode::Char('B') => {
1335 self.scroll_up(self.page_height());
1336 self.pending_g = false;
1337 return ViewAction::None;
1338 }
1339 _ => {}
1340 }
1341 }
1342
1343 match key.code {
1344 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
1345 KeyCode::Left if self.pages.len() > 1 => {
1346 self.switch_page(self.page_index.saturating_sub(1));
1347 ViewAction::None
1348 }
1349 KeyCode::Right if self.pages.len() > 1 => {
1350 self.switch_page(
1351 self.page_index
1352 .saturating_add(1)
1353 .min(self.pages.len().saturating_sub(1)),
1354 );
1355 ViewAction::None
1356 }
1357 KeyCode::Up | KeyCode::Char('k') => {
1358 self.scroll_up(1);
1359 self.pending_g = false;
1360 ViewAction::None
1361 }
1362 KeyCode::Down | KeyCode::Char('j') => {
1363 self.scroll_down(1, max_scroll);
1364 self.pending_g = false;
1365 ViewAction::None
1366 }
1367 KeyCode::PageUp => {
1368 self.scroll_up(self.page_height());
1369 self.pending_g = false;
1370 ViewAction::None
1371 }
1372 KeyCode::PageDown => {
1373 self.scroll_down(self.page_height(), max_scroll);
1374 self.pending_g = false;
1375 ViewAction::None
1376 }
1377 // Vim convention: Space pages down, Shift+Space pages up. Match
1378 // Shift+Space first so it is not absorbed by the bare ' ' arm.
1379 KeyCode::Char(' ') if shift => {
1380 self.scroll_up(self.page_height());
1381 self.pending_g = false;
1382 ViewAction::None
1383 }
1384 KeyCode::Char(' ') => {
1385 self.scroll_down(self.page_height(), max_scroll);
1386 self.pending_g = false;
1387 ViewAction::None
1388 }
1389 KeyCode::Home => {
1390 self.scroll_to_top();
1391 self.pending_g = false;
1392 ViewAction::None
1393 }
1394 KeyCode::End => {
1395 self.scroll_to_bottom(max_scroll);
1396 self.pending_g = false;
1397 ViewAction::None
1398 }
1399 KeyCode::Char('g') => {
1400 if self.pending_g {
1401 self.scroll_to_top();
1402 self.pending_g = false;
1403 } else {
1404 self.pending_g = true;
1405 }
1406 ViewAction::None
1407 }
1408 KeyCode::Char('G') => {
1409 self.scroll_to_bottom(max_scroll);
1410 self.pending_g = false;
1411 ViewAction::None
1412 }
1413 KeyCode::Char('/') => {
1414 self.start_search();
1415 self.pending_g = false;
1416 ViewAction::None
1417 }
1418 KeyCode::Char('n') => {
1419 self.next_match();
1420 self.pending_g = false;
1421 ViewAction::None
1422 }
1423 KeyCode::Char('N') => {
1424 self.prev_match();
1425 self.pending_g = false;
1426 ViewAction::None
1427 }
1428 // Copy the entire pager body to the clipboard. The pager
1429 // intercepts mouse capture so terminal-native selection is
1430 // disabled inside it; without this binding users with no
1431 // out-of-band copy path would have no way to extract content
1432 // they can see (#1354). Both `c` and `y` are wired so users
1433 // landing from either OS-clipboard or vim convention find a
1434 // working key.
1435 KeyCode::Char('c') | KeyCode::Char('y') => {
1436 if self
1437 .evidence
1438 .as_ref()
1439 .is_some_and(|evidence| evidence.page == self.page_index && !evidence.ready)
1440 {
1441 return ViewAction::None;
1442 }
1443 self.pending_g = false;
1444 ViewAction::Emit(ViewEvent::CopyToClipboard {
1445 text: self.clipboard_text(),
1446 label: self
1447 .evidence
1448 .as_ref()
1449 .filter(|evidence| evidence.page == self.page_index)
1450 .map_or_else(
1451 || tr(self.locale, MessageId::PagerCopyContentLabel).into_owned(),
1452 |evidence| {
1453 tr(self.locale, MessageId::PagerEvidenceCopyLabel)
1454 .replace("{start}", &evidence.offset.to_string())
1455 .replace("{end}", &evidence.end.to_string())
1456 .replace("{encoding}", evidence.encoding)
1457 },
1458 ),
1459 })
1460 }
1461 // `e` exports the compact turn handoff (#4108) when this pager
1462 // carries one — the Turn Inspector. Elsewhere the guard fails and
1463 // `e` falls through to the inert arm below.
1464 KeyCode::Char('e') | KeyCode::Char('E')
1465 if self.current_page().export_markdown.is_some() =>
1466 {
1467 self.pending_g = false;
1468 let text = self
1469 .current_page()
1470 .export_markdown
1471 .clone()
1472 .unwrap_or_default();
1473 ViewAction::Emit(ViewEvent::CopyToClipboard {
1474 text,
1475 label: tr(self.locale, MessageId::PagerCopyHandoffLabel).into_owned(),
1476 })
1477 }
1478 // `a` copies ONLY the final assistant answer — the clean
1479 // answer-only payload attached by the Turn Inspector and the
1480 // assistant detail pagers. Unlike `c`/`y` (rendered body) or `e`
1481 // (whole-turn handoff markdown), this payload carries no
1482 // reasoning, tool calls/results, runtime status, or transcript
1483 // scaffolding. Elsewhere the guard fails and `a` is inert.
1484 KeyCode::Char('a') if self.current_page().answer_text.is_some() => {
1485 self.pending_g = false;
1486 let text = self.current_page().answer_text.clone().unwrap_or_default();
1487 ViewAction::Emit(ViewEvent::CopyToClipboard {
1488 text,
1489 label: tr(self.locale, MessageId::PagerCopyAnswerLabel).into_owned(),
1490 })
1491 }
1492 _ => ViewAction::None,
1493 }
1494 }
1495
1496 fn handle_paste(&mut self, text: &str) -> bool {
1497 if !self.search_mode {
1498 return false;
1499 }
1500 let sanitized = text
1501 .trim_end_matches(['\r', '\n'])
1502 .replace("\r\n", "\n")
1503 .replace(char::is_control, " ");
1504 self.search_input.push_str(&sanitized);
1505 self.update_search_matches();
1506 true
1507 }
1508
1509 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
1510 if mouse.kind == MouseEventKind::Down(MouseButton::Left)
1511 && mouse.modifiers.is_empty()
1512 && self
1513 .action_area
1514 .get()
1515 .is_some_and(|area| area.contains((mouse.column, mouse.row).into()))
1516 {
1517 return self.activate_destructive_action();
1518 }
1519 match mouse.kind {
1520 MouseEventKind::ScrollUp => {
1521 self.scroll_up(3);
1522 self.pending_g = false;
1523 ViewAction::None
1524 }
1525 MouseEventKind::ScrollDown => {
1526 self.scroll_down(3, self.max_scroll());
1527 self.pending_g = false;
1528 ViewAction::None
1529 }
1530 _ => ViewAction::None,
1531 }
1532 }
1533
1534 fn render(&self, area: Rect, buf: &mut Buffer) {
1535 let page = self.current_page();
1536 let title = if self.pages.len() > 1 {
1537 format!(
1538 "{} · {}/{} · ←/→",
1539 page.title,
1540 self.page_index + 1,
1541 self.pages.len()
1542 )
1543 } else {
1544 page.title.clone()
1545 };
1546 let inner = render_rounded_surface(area, buf, title, None, self.search_mode);
1547
1548 // The wrapping action footer is anchored to the bottom of the inner
1549 // area; the body fills the rows above it.
1550 let mut hints = vec![
1551 ActionHint::new("q/Esc", tr(self.locale, MessageId::SessionsActionClose)),
1552 ActionHint::new("j/k", tr(self.locale, MessageId::PagerActionScroll)),
1553 ActionHint::new("Space", tr(self.locale, MessageId::PagerActionPage)),
1554 ActionHint::new("Ctrl+D/U", tr(self.locale, MessageId::PagerActionHalfPage)),
1555 ActionHint::new("g/G", tr(self.locale, MessageId::PagerActionTopBottom)),
1556 ActionHint::new("/", tr(self.locale, MessageId::SessionsActionSearch)),
1557 ActionHint::new("c", tr(self.locale, MessageId::PagerActionCopy)),
1558 ];
1559 if self
1560 .evidence
1561 .as_ref()
1562 .is_some_and(|evidence| evidence.page == self.page_index)
1563 {
1564 hints[5] = ActionHint::new(
1565 "/",
1566 tr(self.locale, MessageId::PagerActionSearchLoadedRange),
1567 );
1568 hints[6] = ActionHint::new("c", tr(self.locale, MessageId::PagerActionCopyLoadedRange));
1569 hints.push(ActionHint::new(
1570 "←/→",
1571 tr(self.locale, MessageId::PagerActionByteWindows),
1572 ));
1573 hints.push(ActionHint::new(
1574 "Ctrl+Home/End",
1575 tr(self.locale, MessageId::PagerActionFirstLastBytes),
1576 ));
1577 }
1578 if page.export_markdown.is_some() {
1579 hints.push(ActionHint::new(
1580 "e",
1581 tr(self.locale, MessageId::PagerActionCopyHandoff),
1582 ));
1583 }
1584 if page.answer_text.is_some() {
1585 hints.push(ActionHint::new(
1586 "a",
1587 tr(self.locale, MessageId::PagerActionCopyAnswer),
1588 ));
1589 }
1590 self.action_area.set(None);
1591 if let Some(action) = self.destructive_action.as_ref() {
1592 let key = if action.armed {
1593 format!("{}/Enter", action.key)
1594 } else {
1595 action.key.to_string()
1596 };
1597 let label = if action.armed {
1598 action.confirm_label.clone()
1599 } else {
1600 action.label.clone()
1601 };
1602 let action_width = key.width() + 2 + label.width();
1603 hints.push(ActionHint::new(key, label));
1604 let footer_lines = action_footer_lines(&hints, inner.width);
1605 if footer_lines.len() <= usize::from(inner.height)
1606 && inner.width > 0
1607 && let Some(last) = footer_lines.last()
1608 {
1609 let offset = last
1610 .width()
1611 .saturating_sub(action_width)
1612 .min(usize::from(inner.width));
1613 self.action_area.set(Some(Rect::new(
1614 inner.x.saturating_add(offset as u16),
1615 inner.bottom().saturating_sub(1),
1616 (action_width.min(usize::from(inner.width).saturating_sub(offset))) as u16,
1617 1,
1618 )));
1619 }
1620 }
1621 let content = render_rounded_footer(inner, buf, &hints);
1622
1623 // Re-wrap before reserving the search-status row: resizing can make
1624 // the first match appear or the last match disappear. Hold a column
1625 // for the scroll rail so it cannot cause another paragraph wrap.
1626 let body_width = if content.width >= 2 {
1627 content.width - 1
1628 } else {
1629 content.width
1630 };
1631 self.layout(
1632 usize::from(body_width),
1633 usize::from(content.height).min(PAGER_RETAINED_ROWS),
1634 );
1635
1636 // `content` already excludes the border, padding, and footer rows.
1637 let mut visible_height = usize::from(content.height).min(PAGER_RETAINED_ROWS);
1638 let diff_status = matches!(&page.source, PagerSource::Diff(..));
1639 let display_notice = page.rows.borrow().display_notice(self.locale, false);
1640 if diff_status || display_notice.is_some() {
1641 visible_height = visible_height.saturating_sub(1);
1642 }
1643 if self.search_mode {
1644 // Reserve a row for the search prompt that gets pushed below.
1645 visible_height = visible_height.saturating_sub(1);
1646 } else if self.search_total.get() > 0 {
1647 // Reserve a row for the "match X/Y (n/N)" status; without this
1648 // the status line gets clipped on small popup heights and the
1649 // user can't see how many matches there are.
1650 visible_height = visible_height.saturating_sub(1);
1651 }
1652 // Cache for paging keys; the value is treated as advisory and
1653 // clamped at use-time.
1654 self.last_visible_height.set(visible_height);
1655 let row_count = page.row_count();
1656 let max_scroll = row_count.saturating_sub(visible_height);
1657 let scroll = if self.follow {
1658 self.scroll.set(max_scroll);
1659 max_scroll
1660 } else {
1661 self.scroll.get().min(max_scroll)
1662 };
1663 self.scroll.set(scroll);
1664 page.layout(usize::from(body_width), scroll, visible_height);
1665 let rows = page.rows.borrow();
1666 let start = scroll.saturating_sub(rows.start).min(rows.plain.len());
1667 let end = start.saturating_add(visible_height).min(rows.plain.len());
1668 let mut visible_lines: Vec<Line<'static>> = if row_count == 0 {
1669 vec![Line::from("")]
1670 } else if rows.styled.is_empty() {
1671 rows.plain[start..end]
1672 .iter()
1673 .map(|row| Line::from(row.clone()))
1674 .collect()
1675 } else {
1676 rows.styled[start..end].to_vec()
1677 };
1678
1679 // Highlight matched lines while the search prompt is closed and the
1680 // user is navigating with `n` / `N`. Other matches get a subtle
1681 // background; the current match gets a louder one. Per-substring
1682 // highlighting is deferred to a follow-up — preserving the pre-styled
1683 // spans (assistant / system colors) through a substring re-style is
1684 // a separate concern.
1685 if !self.search_mode && self.search_total.get() > 0 {
1686 let current_match_line = self.search_row.get();
1687 let query = self.search_input.trim().to_ascii_lowercase();
1688 for (visible_idx, line) in visible_lines.iter_mut().enumerate() {
1689 let absolute_idx = scroll + visible_idx;
1690 if absolute_idx >= row_count {
1691 break;
1692 }
1693 if !rows.plain[start + visible_idx]
1694 .to_ascii_lowercase()
1695 .contains(&query)
1696 {
1697 continue;
1698 }
1699 let is_current = current_match_line == Some(absolute_idx);
1700 let bg = if is_current {
1701 Color::Yellow
1702 } else {
1703 Color::DarkGray
1704 };
1705 let fg = if is_current {
1706 Color::Black
1707 } else {
1708 Color::Yellow
1709 };
1710 let highlight = Style::default().bg(bg).fg(fg).add_modifier(Modifier::BOLD);
1711 for span in line.spans.iter_mut() {
1712 span.style = highlight;
1713 }
1714 }
1715 }
1716
1717 if self.search_mode {
1718 let prompt = format!("/{}", self.search_input);
1719 visible_lines.push(Line::from(Span::styled(
1720 prompt,
1721 Style::default()
1722 .fg(palette::WHALE_ACTION)
1723 .add_modifier(Modifier::BOLD),
1724 )));
1725 } else if self.search_total.get() > 0 {
1726 let status = tr(self.locale, MessageId::PagerSearchMatch)
1727 .replace("{current}", &(self.search_index.get() + 1).to_string())
1728 .replace("{total}", &self.search_total.get().to_string());
1729 visible_lines.push(Line::from(Span::styled(
1730 status,
1731 Style::default().fg(palette::TEXT_MUTED),
1732 )));
1733 }
1734
1735 if diff_status {
1736 let status = if rows.clipped_rows > 0 || rows.clipped_bytes > 0 {
1737 tr(self.locale, MessageId::PagerDiffRowsShortened)
1738 .replace("{rows}", &rows.clipped_rows.to_string())
1739 .replace("{bytes}", &rows.clipped_bytes.to_string())
1740 .replace("{key}", "c")
1741 } else {
1742 tr(self.locale, MessageId::PagerDiffCopySource).replace("{key}", "c")
1743 };
1744 visible_lines.push(Line::from(Span::styled(
1745 codewhale_tui_kit::ui_text::truncate_line_to_width(
1746 &status,
1747 usize::from(body_width),
1748 ),
1749 Style::default().fg(palette::TEXT_MUTED),
1750 )));
1751 }
1752
1753 if !diff_status && let Some(notice) = display_notice {
1754 visible_lines.push(Line::from(Span::styled(
1755 codewhale_tui_kit::ui_text::truncate_line_to_width(
1756 &notice,
1757 usize::from(body_width),
1758 ),
1759 Style::default().fg(palette::TEXT_MUTED),
1760 )));
1761 }
1762
1763 let content =
1764 render_panel_scroll_rail(content, buf, row_count, scroll, visible_height, true);
1765 let paragraph = Paragraph::new(visible_lines)
1766 .wrap(Wrap { trim: false })
1767 .style(Style::default().fg(palette::TEXT_PRIMARY));
1768 paragraph.render(content, buf);
1769 }
1770 }
1771
1772 fn line_to_string(line: &Line<'static>) -> String {
1773 line.spans
1774 .iter()
1775 .map(|span| span.content.to_string())
1776 .collect::<String>()
1777 }
1778
1779 fn for_each_wrapped_range<'a>(
1780 pieces: impl Iterator<Item = (&'a str, usize)>,
1781 width: usize,
1782 mut emit: impl FnMut(&[(char, usize)], Range<usize>),
1783 ) -> (bool, bool) {
1784 let mut escaped = false;
1785 let mut continued = false;
1786 let mut cells: Vec<(char, usize)> = Vec::new();
1787 let mut bytes = 0usize;
1788 let mut skip_space = false;
1789 codewhale_tui_kit::ui_text::display_graphemes_exact(pieces, 0, |grapheme| {
1790 escaped |= grapheme.escaped;
1791 if skip_space {
1792 if grapheme.text.chars().all(char::is_whitespace) {
1793 return;
1794 }
1795 skip_space = false;
1796 }
1797 if bytes.saturating_add(grapheme.text.len()) > PAGER_ROW_BYTES && !cells.is_empty() {
1798 let mut last = None;
1799 wrap_ranges_into(&cells, width, &mut |source, range| {
1800 if let Some(previous) = last.replace(range) {
1801 emit(source, previous);
1802 }
1803 });
1804 let last = last.unwrap_or(0..0);
1805 skip_space = last.is_empty() && cells.last().is_some_and(|&(ch, _)| ch.is_whitespace());
1806 cells = cells[last].to_vec();
1807 bytes = cells.iter().map(|&(ch, _)| ch.len_utf8()).sum();
1808 }
1809 if skip_space {
1810 if grapheme.text.chars().all(char::is_whitespace) {
1811 return;
1812 }
1813 skip_space = false;
1814 }
1815 if bytes.saturating_add(grapheme.text.len()) > PAGER_ROW_BYTES && !cells.is_empty() {
1816 wrap_ranges_into(&cells, width, &mut emit);
1817 cells.clear();
1818 continued = true;
1819 let notice: Vec<_> = "[…]".chars().map(|ch| (ch, 0)).collect();
1820 wrap_ranges_into(&notice, width, &mut emit);
1821 bytes = 0;
1822 }
1823 bytes = bytes.saturating_add(grapheme.text.len());
1824 cells.extend_from_slice(grapheme.cells);
1825 });
1826 wrap_ranges_into(&cells, width, &mut emit);
1827 (escaped, continued)
1828 }
1829
1830 #[cfg(test)]
1831 fn wrap_text(text: &str, width: usize) -> Vec<String> {
1832 let mut rows = Vec::new();
1833 for_each_wrapped_range(std::iter::once((text, 0)), width, |cells, range| {
1834 rows.push(cells[range].iter().map(|&(ch, _)| ch).collect());
1835 });
1836 rows
1837 }
1838
1839 fn wrap_ranges_into(
1840 cells: &[(char, usize)],
1841 width: usize,
1842 emit: &mut impl FnMut(&[(char, usize)], Range<usize>),
1843 ) {
1844 if width == 0 {
1845 emit(cells, 0..cells.len());
1846 return;
1847 }
1848 let text: String = cells.iter().map(|&(ch, _)| ch).collect();
1849 let mut character = 0;
1850 let graphemes: Vec<_> = text
1851 .graphemes(true)
1852 .map(|grapheme| {
1853 let start = character;
1854 character += grapheme.chars().count();
1855 (
1856 start,
1857 grapheme_display_width(grapheme),
1858 grapheme.chars().all(char::is_whitespace),
1859 )
1860 })
1861 .collect();
1862 let boundary = |index: usize| graphemes.get(index).map_or(cells.len(), |cell| cell.0);
1863 let mut current = 0..0;
1864 let mut current_width = 0usize;
1865 let mut has_content = false;
1866 let mut run_start = 0;
1867 while run_start < graphemes.len() {
1868 let is_space = graphemes[run_start].2;
1869 let run_end = graphemes[run_start..]
1870 .iter()
1871 .position(|&(_, _, space)| space != is_space)
1872 .map_or(graphemes.len(), |offset| run_start + offset);
1873 let run = run_start..run_end;
1874 run_start = run_end;
1875 let run_width: usize = run.clone().map(|i| graphemes[i].1).sum();
1876 if current_width + run_width <= width {
1877 current.end = run.end;
1878 current_width += run_width;
1879 has_content |= !is_space;
1880 continue;
1881 }
1882 if has_content {
1883 let mut kept = current.end;
1884 while kept > current.start && graphemes[kept - 1].2 {
1885 kept -= 1;
1886 }
1887 emit(cells, boundary(current.start)..boundary(kept));
1888 current_width = 0;
1889 has_content = false;
1890 current = run.end..run.end;
1891 if is_space {
1892 continue;
1893 }
1894 current = run.clone();
1895 if run_width <= width {
1896 current_width = run_width;
1897 has_content = true;
1898 continue;
1899 }
1900 current.end = run.start;
1901 }
1902 for index in run {
1903 let char_width = graphemes[index].1;
1904 if current_width + char_width > width && current_width > 0 {
1905 emit(cells, boundary(current.start)..boundary(current.end));
1906 current = index..index;
1907 current_width = 0;
1908 }
1909 current.end = index + 1;
1910 current_width += char_width;
1911 }
1912 has_content |= !is_space;
1913 }
1914 emit(cells, boundary(current.start)..boundary(current.end));
1915 }
1916
1917 #[cfg(test)]
1918 mod tests {
1919 use super::*;
1920 use ratatui::text::Line;
1921
1922 fn make_pager(lines: usize) -> PagerView {
1923 let lines: Vec<Line<'static>> = (0..lines)
1924 .map(|i| Line::from(format!("line-{i:03}")))
1925 .collect();
1926 PagerView::new("T", lines)
1927 }
1928
1929 fn key(code: KeyCode) -> KeyEvent {
1930 KeyEvent::new(code, KeyModifiers::NONE)
1931 }
1932
1933 fn key_mod(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
1934 KeyEvent::new(code, mods)
1935 }
1936
1937 #[test]
1938 fn diff_summary_follows_the_ui_locale() {
1939 let diff = "diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n@@ -1,2 +1,2 @@\n line\n+new\n-old\n";
1940 let mut view = PagerView::from_diff("diff", diff.to_string(), 80);
1941 let english = view.body_text();
1942 assert!(
1943 english.starts_with("summary: 1 file, +1 -1, 1 hunk\n"),
1944 "{english}"
1945 );
1946 assert!(english.contains("src/a.rs +1 -1 1 hunk"), "{english}");
1947
1948 view.set_locale(Locale::ZhHans);
1949 let chinese = view.body_text();
1950 assert!(
1951 chinese.starts_with("摘要:1个文件,+1 -1,1处改动\n"),
1952 "{chinese}"
1953 );
1954 assert!(chinese.contains("src/a.rs +1 -1 1处改动"), "{chinese}");
1955 }
1956
1957 fn ctrl(code: KeyCode) -> KeyEvent {
1958 KeyEvent::new(code, KeyModifiers::CONTROL)
1959 }
1960
1961 #[test]
1962 fn destructive_action_requires_two_steps_and_escape_only_disarms() {
1963 let mut pager = make_pager(2).with_destructive_action(
1964 's',
1965 "stop",
1966 "confirm stop · Esc cancels",
1967 ViewEvent::SidebarAgentCancel {
1968 agent_id: "agent_1".to_string(),
1969 },
1970 );
1971
1972 assert!(matches!(
1973 pager.handle_key(key(KeyCode::Char('s'))),
1974 ViewAction::None
1975 ));
1976 assert!(matches!(
1977 pager.handle_key(key(KeyCode::Esc)),
1978 ViewAction::None
1979 ));
1980 assert!(matches!(
1981 pager.handle_key(key(KeyCode::Esc)),
1982 ViewAction::Close
1983 ));
1984
1985 let _ = pager.handle_key(key(KeyCode::Char('s')));
1986 assert!(matches!(
1987 pager.handle_key(key(KeyCode::Enter)),
1988 ViewAction::EmitAndClose(ViewEvent::SidebarAgentCancel { agent_id })
1989 if agent_id == "agent_1"
1990 ));
1991 }
1992
1993 #[test]
1994 fn command_review_confirms_the_pinned_command_with_keys_or_painted_mouse_control() {
1995 let command = format!(
1996 "/plugin trust fixture {}.{}",
1997 "a".repeat(64),
1998 "b".repeat(64)
1999 );
2000 for (width, height) in [(40, 12), (80, 24), (140, 40)] {
2001 let mut pager = PagerView::command_review(
2002 "Review fixture",
2003 "Exact reviewed capabilities",
2004 width - 2,
2005 command.clone(),
2006 codewhale_localization::Locale::En,
2007 );
2008 for modifiers in [
2009 KeyModifiers::CONTROL,
2010 KeyModifiers::ALT,
2011 KeyModifiers::SUPER,
2012 ] {
2013 assert!(matches!(
2014 pager.handle_key(KeyEvent::new(KeyCode::Char('y'), modifiers)),
2015 ViewAction::None
2016 ));
2017 assert!(!pager.destructive_action.as_ref().unwrap().armed);
2018 }
2019 assert!(matches!(
2020 pager.handle_key(KeyEvent::new_with_kind(
2021 KeyCode::Char('y'),
2022 KeyModifiers::NONE,
2023 KeyEventKind::Repeat
2024 )),
2025 ViewAction::None
2026 ));
2027 assert!(!pager.destructive_action.as_ref().unwrap().armed);
2028 let ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) =
2029 pager.handle_key(key(KeyCode::Char('c')))
2030 else {
2031 panic!("copy exposes the pinned command");
2032 };
2033 assert_eq!(text, command);
2034 let area = Rect::new(0, 0, width, height);
2035 let mut buffer = Buffer::empty(area);
2036 pager.render(area, &mut buffer);
2037 let rendered: String = buffer.content.iter().map(|cell| cell.symbol()).collect();
2038 assert!(rendered.contains("Confirm"), "{rendered}");
2039 assert!(
2040 !rendered.contains("disable"),
2041 "generic review must not describe an unrelated action"
2042 );
2043 let button = pager
2044 .action_area
2045 .get()
2046 .expect("visible confirmation control");
2047 assert!(button.width > 0 && button.bottom() <= height);
2048 let click = |button: Rect| MouseEvent {
2049 kind: MouseEventKind::Down(MouseButton::Left),
2050 column: button.x,
2051 row: button.y,
2052 modifiers: KeyModifiers::NONE,
2053 };
2054 assert!(matches!(
2055 pager.handle_mouse(click(button)),
2056 ViewAction::None
2057 ));
2058 assert!(pager.destructive_action.as_ref().unwrap().armed);
2059 assert!(matches!(
2060 pager.handle_key(KeyEvent::new_with_kind(
2061 KeyCode::Enter,
2062 KeyModifiers::NONE,
2063 KeyEventKind::Repeat
2064 )),
2065 ViewAction::None
2066 ));
2067 pager.render(area, &mut buffer);
2068 let ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
2069 action: crate::tui::views::CommandPaletteAction::ExecuteCommand { command: actual },
2070 }) = pager.handle_mouse(click(pager.action_area.get().unwrap()))
2071 else {
2072 panic!("second click confirms the reviewed command");
2073 };
2074 assert_eq!(actual, command);
2075 }
2076 }
2077
2078 /// Drive a render once so `last_visible_height` is populated and paging
2079 /// keys use a deterministic page size.
2080 fn prime_layout(view: &mut PagerView, height: u16) {
2081 let area = Rect::new(0, 0, 40, height);
2082 let mut buf = Buffer::empty(area);
2083 view.render(area, &mut buf);
2084 }
2085
2086 #[test]
2087 fn j_scrolls_down_one_line() {
2088 let mut p = make_pager(50);
2089 let _ = p.handle_key(key(KeyCode::Char('j')));
2090 assert_eq!(p.scroll.get(), 1);
2091 }
2092
2093 #[test]
2094 fn k_scrolls_up_one_line() {
2095 let mut p = make_pager(50);
2096 p.scroll.set(5);
2097 let _ = p.handle_key(key(KeyCode::Char('k')));
2098 assert_eq!(p.scroll.get(), 4);
2099 }
2100
2101 #[test]
2102 fn gg_jumps_to_top() {
2103 let mut p = make_pager(50);
2104 p.scroll.set(30);
2105 let _ = p.handle_key(key(KeyCode::Char('g')));
2106 assert!(p.pending_g, "first 'g' should arm pending_g");
2107 assert_eq!(p.scroll.get(), 30, "first 'g' alone must not scroll");
2108 let _ = p.handle_key(key(KeyCode::Char('g')));
2109 assert_eq!(p.scroll.get(), 0);
2110 assert!(!p.pending_g);
2111 }
2112
2113 #[test]
2114 fn home_jumps_to_top() {
2115 let mut p = make_pager(50);
2116 p.scroll.set(30);
2117 let _ = p.handle_key(key(KeyCode::Home));
2118 assert_eq!(p.scroll.get(), 0);
2119 }
2120
2121 #[test]
2122 fn live_shell_job_pager_follows_new_output_until_scrolled_back() {
2123 let body = |rows: usize| {
2124 (0..rows)
2125 .map(|row| format!("out-{row:03}"))
2126 .collect::<Vec<_>>()
2127 .join("\n")
2128 };
2129 let mut p = PagerView::from_text("Bash Job shell_1", &body(5), 40)
2130 .with_copy_text(body(5))
2131 .with_live_shell_job("shell_1");
2132 prime_layout(&mut p, 12);
2133
2134 assert!(p.replace_live_text(&body(60)));
2135 prime_layout(&mut p, 12);
2136 assert!(p.max_scroll() > 0);
2137 assert_eq!(p.scroll.get(), p.max_scroll());
2138
2139 let _ = p.handle_key(key(KeyCode::Char('k')));
2140 let held = p.scroll.get();
2141 assert!(p.replace_live_text(&body(80)));
2142 prime_layout(&mut p, 12);
2143 assert_eq!(p.scroll.get(), held);
2144
2145 let _ = p.handle_key(key(KeyCode::Char('G')));
2146 assert!(p.replace_live_text(&body(90)));
2147 prime_layout(&mut p, 12);
2148 assert_eq!(p.scroll.get(), p.max_scroll());
2149 assert!(!p.replace_live_text(&body(90)));
2150 }
2151
2152 #[test]
2153 fn ending_a_live_shell_job_drops_stop() {
2154 let mut p = make_pager(2)
2155 .with_live_shell_job("shell_1")
2156 .with_destructive_action(
2157 's',
2158 "stop",
2159 "confirm stop · Esc cancels",
2160 ViewEvent::SidebarAgentCancel {
2161 agent_id: "agent_1".to_string(),
2162 },
2163 );
2164 p.end_live_shell_job();
2165 assert!(p.live_shell_job().is_none());
2166 for _ in 0..2 {
2167 assert!(matches!(
2168 p.handle_key(key(KeyCode::Char('s'))),
2169 ViewAction::None
2170 ));
2171 }
2172 }
2173
2174 #[test]
2175 fn shift_g_jumps_to_bottom() {
2176 let mut p = make_pager(50);
2177 let _ = p.handle_key(key(KeyCode::Char('G')));
2178 assert_eq!(p.scroll.get(), p.max_scroll());
2179 }
2180
2181 #[test]
2182 fn end_jumps_to_bottom() {
2183 let mut p = make_pager(50);
2184 let _ = p.handle_key(key(KeyCode::End));
2185 assert_eq!(p.scroll.get(), p.max_scroll());
2186 }
2187
2188 #[test]
2189 fn up_immediately_scrolls_after_shift_g_to_bottom() {
2190 let mut p = make_pager(50);
2191 prime_layout(&mut p, 22);
2192 let bottom = p.max_scroll();
2193
2194 let _ = p.handle_key(key(KeyCode::Char('G')));
2195 assert_eq!(p.scroll.get(), bottom);
2196 let _ = p.handle_key(key(KeyCode::Up));
2197 assert_eq!(p.scroll.get(), bottom - 1);
2198 let _ = p.handle_key(key(KeyCode::Char('k')));
2199 assert_eq!(p.scroll.get(), bottom - 2);
2200 }
2201
2202 #[test]
2203 fn k_immediately_scrolls_after_end_to_bottom() {
2204 let mut p = make_pager(50);
2205 prime_layout(&mut p, 22);
2206 let bottom = p.max_scroll();
2207
2208 let _ = p.handle_key(key(KeyCode::End));
2209 assert_eq!(p.scroll.get(), bottom);
2210 let _ = p.handle_key(key(KeyCode::Char('k')));
2211 assert_eq!(p.scroll.get(), bottom - 1);
2212 }
2213
2214 #[test]
2215 fn ctrl_d_half_page_down() {
2216 let mut p = make_pager(200);
2217 prime_layout(&mut p, 22);
2218 let half = p.half_page_height();
2219 assert!(half >= 1, "half-page must move at least one line");
2220 let _ = p.handle_key(ctrl(KeyCode::Char('d')));
2221 assert_eq!(p.scroll.get(), half);
2222 }
2223
2224 #[test]
2225 fn ctrl_u_half_page_up() {
2226 let mut p = make_pager(200);
2227 prime_layout(&mut p, 22);
2228 p.scroll.set(50);
2229 let half = p.half_page_height();
2230 let _ = p.handle_key(ctrl(KeyCode::Char('u')));
2231 assert_eq!(p.scroll.get(), 50 - half);
2232 }
2233
2234 #[test]
2235 fn ctrl_f_full_page_down() {
2236 let mut p = make_pager(200);
2237 prime_layout(&mut p, 22);
2238 let page = p.page_height();
2239 let _ = p.handle_key(ctrl(KeyCode::Char('f')));
2240 assert_eq!(p.scroll.get(), page);
2241 }
2242
2243 #[test]
2244 fn ctrl_b_full_page_up() {
2245 let mut p = make_pager(200);
2246 prime_layout(&mut p, 22);
2247 p.scroll.set(80);
2248 let page = p.page_height();
2249 let _ = p.handle_key(ctrl(KeyCode::Char('b')));
2250 assert_eq!(p.scroll.get(), 80 - page);
2251 }
2252
2253 #[test]
2254 fn space_pages_down() {
2255 let mut p = make_pager(200);
2256 prime_layout(&mut p, 22);
2257 let page = p.page_height();
2258 let _ = p.handle_key(key(KeyCode::Char(' ')));
2259 assert_eq!(p.scroll.get(), page);
2260 }
2261
2262 #[test]
2263 fn shift_space_pages_up() {
2264 let mut p = make_pager(200);
2265 prime_layout(&mut p, 22);
2266 p.scroll.set(80);
2267 let page = p.page_height();
2268 let _ = p.handle_key(key_mod(KeyCode::Char(' '), KeyModifiers::SHIFT));
2269 assert_eq!(p.scroll.get(), 80 - page);
2270 }
2271
2272 #[test]
2273 fn page_down_uses_cached_visible_height() {
2274 let mut p = make_pager(200);
2275 prime_layout(&mut p, 22);
2276 let page = p.page_height();
2277 let _ = p.handle_key(key(KeyCode::PageDown));
2278 assert_eq!(p.scroll.get(), page);
2279 }
2280
2281 #[test]
2282 fn q_closes_pager() {
2283 let mut p = make_pager(10);
2284 let action = p.handle_key(key(KeyCode::Char('q')));
2285 assert!(matches!(action, ViewAction::Close));
2286 }
2287
2288 #[test]
2289 fn esc_closes_pager() {
2290 let mut p = make_pager(10);
2291 let action = p.handle_key(key(KeyCode::Esc));
2292 assert!(matches!(action, ViewAction::Close));
2293 }
2294
2295 #[test]
2296 fn multi_page_switch_resets_view_state_and_keeps_copy_export_page_scoped() {
2297 let first =
2298 PagerPage::from_text("Turns", "first displayed", 80).with_copy_text("FIRST-SOURCE");
2299 let latest = PagerPage::from_text("Turns", "latest displayed", 80)
2300 .with_copy_text("LATEST-SOURCE")
2301 .with_export_markdown("LATEST-HANDOFF");
2302 let mut pager = PagerView::from_pages(vec![first, latest], 1);
2303 pager.scroll.set(4);
2304 pager.search_input = "latest".to_string();
2305 pager.search_total.set(1);
2306 pager.search_row.set(Some(0));
2307 pager.search_origin.set(Some(0));
2308
2309 assert!(matches!(
2310 pager.handle_key(key(KeyCode::Left)),
2311 ViewAction::None
2312 ));
2313 assert_eq!(pager.body_text(), "first displayed");
2314 assert_eq!(pager.scroll.get(), 0);
2315 assert!(pager.search_input.is_empty());
2316 assert_eq!(pager.search_total.get(), 0);
2317 assert!(matches!(
2318 pager.handle_key(key(KeyCode::Char('c'))),
2319 ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) if text == "FIRST-SOURCE"
2320 ));
2321 assert!(matches!(
2322 pager.handle_key(key(KeyCode::Char('e'))),
2323 ViewAction::None
2324 ));
2325
2326 let _ = pager.handle_key(key(KeyCode::Right));
2327 assert!(matches!(
2328 pager.handle_key(key(KeyCode::Char('e'))),
2329 ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) if text == "LATEST-HANDOFF"
2330 ));
2331 }
2332
2333 #[test]
2334 fn g_does_not_consume_search_input() {
2335 // While in search mode, 'g' must be treated as a search character,
2336 // not as the half of a `gg` jump-to-top sequence.
2337 let mut p = make_pager(50);
2338 p.scroll.set(10);
2339 let _ = p.handle_key(key(KeyCode::Char('/')));
2340 assert!(p.search_mode);
2341 let _ = p.handle_key(key(KeyCode::Char('g')));
2342 assert_eq!(p.search_input, "g");
2343 assert_eq!(p.scroll.get(), 10);
2344 }
2345
2346 #[test]
2347 fn footer_hint_includes_new_bindings() {
2348 // The rendered pager must surface the new vim-style bindings to the
2349 // user. The footer is now a wrapping ActionHint row inside the modal
2350 // body (not the bottom border), so assert against the rendered buffer.
2351 let p = make_pager(5);
2352 let area = Rect::new(0, 0, 100, 16);
2353 let mut buf = Buffer::empty(area);
2354 p.render(area, &mut buf);
2355 let mut text = String::new();
2356 for y in 0..area.height {
2357 for x in 0..area.width {
2358 text.push_str(buf[(x, y)].symbol());
2359 }
2360 text.push('\n');
2361 }
2362 for needle in &[
2363 "j/k",
2364 "scroll",
2365 "g/G",
2366 "top/bottom",
2367 "Space",
2368 "page",
2369 "Ctrl+D/U",
2370 "half",
2371 "search",
2372 "copy",
2373 "q/Esc",
2374 "close",
2375 ] {
2376 assert!(text.contains(needle), "footer hint missing {needle:?}");
2377 }
2378 }
2379
2380 #[test]
2381 fn body_cells_carry_explicit_ink_on_the_dark_surface() {
2382 let p = make_pager(3);
2383 let area = Rect::new(0, 0, 100, 16);
2384 let mut buf = Buffer::empty(area);
2385 p.render(area, &mut buf);
2386 let mut checked = 0;
2387 for y in 0..area.height {
2388 let mut row = String::new();
2389 for x in 0..area.width {
2390 row.push_str(buf[(x, y)].symbol());
2391 }
2392 if !row.contains("line-") {
2393 continue;
2394 }
2395 for x in 0..area.width {
2396 let cell = &buf[(x, y)];
2397 let symbol = cell.symbol();
2398 if symbol.trim().is_empty() || matches!(symbol, "│" | "|") {
2399 continue;
2400 }
2401 assert_eq!(
2402 cell.style().fg,
2403 Some(palette::TEXT_PRIMARY),
2404 "body cell ({x}, {y}) must carry explicit body ink",
2405 );
2406 checked += 1;
2407 }
2408 }
2409 assert!(checked > 0, "expected body rows in the rendered pager");
2410 }
2411
2412 #[test]
2413 fn c_emits_copy_event_with_full_body() {
2414 // #1354: the pager intercepts mouse capture, so users have no way to
2415 // copy content out without an in-app key. Both `c` and `y` should
2416 // emit a CopyToClipboard event carrying the whole body so the host
2417 // dispatcher (in ui.rs) can write through `app.clipboard` and toast
2418 // a confirmation.
2419 let mut p = make_pager(3);
2420 let action = p.handle_key(key(KeyCode::Char('c')));
2421 match action {
2422 ViewAction::Emit(ViewEvent::CopyToClipboard { text, label }) => {
2423 assert_eq!(text, "line-000\nline-001\nline-002");
2424 assert_eq!(label, "Pager content");
2425 }
2426 other => panic!("expected CopyToClipboard emit, got {other:?}"),
2427 }
2428 }
2429
2430 #[test]
2431 fn a_emits_copy_event_with_attached_answer_only() {
2432 // `a` copies the attached answer-only payload — never the rendered
2433 // body, which may carry scaffolding around the answer.
2434 let mut pager = PagerView::from_text("Turn Inspector", "[◆ · done] body", 40)
2435 .with_copy_answer("CLEAN-ANSWER");
2436 let action = pager.handle_key(key(KeyCode::Char('a')));
2437 match action {
2438 ViewAction::Emit(ViewEvent::CopyToClipboard { text, label }) => {
2439 assert_eq!(text, "CLEAN-ANSWER");
2440 assert_eq!(label, "Answer");
2441 }
2442 other => panic!("expected CopyToClipboard emit, got {other:?}"),
2443 }
2444
2445 // Without an attached answer `a` stays inert; it must never fall
2446 // back to copying the rendered body.
2447 let mut plain = PagerView::from_text("T", "body", 40);
2448 assert!(matches!(
2449 plain.handle_key(key(KeyCode::Char('a'))),
2450 ViewAction::None
2451 ));
2452 }
2453
2454 #[test]
2455 fn copy_override_preserves_indentation_tabs_and_blank_lines() {
2456 let source = "Result:\n indented\n\twith-tab\n\nnext";
2457 let mut pager = PagerView::from_text("T", source, 12).with_copy_text(source);
2458
2459 let action = pager.handle_key(key(KeyCode::Char('c')));
2460 match action {
2461 ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) => {
2462 assert_eq!(text, source);
2463 }
2464 other => panic!("expected CopyToClipboard emit, got {other:?}"),
2465 }
2466 }
2467
2468 #[test]
2469 fn from_text_keeps_one_display_row_per_blank_source_line() {
2470 let pager = PagerView::from_text("T", "first\n\nthird", 80);
2471 assert_eq!(pager.body_text(), "first\n\nthird");
2472 }
2473
2474 #[test]
2475 fn from_text_strips_csi_mouse_and_osc_sequences() {
2476 // A worker transcript can carry captured terminal bytes (a child TUI's
2477 // mouse-tracking handshake, SGR color, OSC hyperlinks). Rendering them
2478 // raw emits the escapes to the user's terminal, which re-enables mouse
2479 // reporting after exit and leaves the shell executing fragments.
2480 let hostile = "── assistant ──\n\
2481 enabling \u{1b}[?1003h\u{1b}[?1006h mouse tracking\n\
2482 click bytes \u{1b}[<65;72;17M\u{1b}[<35;131;42M arrived\n\
2483 \u{1b}[31mred text\u{1b}[0m and an \u{1b}]8;;https://example.com\u{7}OSC link\u{1b}]8;;\u{1b}\\\n\
2484 trailing stray \u{1b}\u{7}bytes\u{1b}c done";
2485 let pager = PagerView::from_text("Agent transcript", hostile, 200);
2486 let body = pager.body_text();
2487 assert!(
2488 !body.contains('\u{1b}'),
2489 "no ESC byte may survive into the pager body: {body:?}"
2490 );
2491 assert!(
2492 !body.contains('\u{7}'),
2493 "no BEL byte may survive into the pager body: {body:?}"
2494 );
2495 for fragment in ["?1003h", "?1006h", "<65;72;17M", "<35;131;42M", "]8;;"] {
2496 assert!(
2497 !body.contains(fragment),
2498 "escape fragment {fragment:?} must be stripped, not painted: {body:?}"
2499 );
2500 }
2501 assert!(body.contains("red text"), "visible text survives: {body:?}");
2502 assert!(body.contains("OSC link"), "link label survives: {body:?}");
2503 assert!(body.contains("done"), "trailing text survives: {body:?}");
2504 }
2505
2506 #[test]
2507 fn from_text_sanitizes_jsonl_transcript_shaped_content() {
2508 // Regression for the sub-agent transcript pager corrupting the parent
2509 // terminal: content shaped like the raw artifact lines, with embedded
2510 // mouse/CSI sequences inside a tool result, must render inert.
2511 let transcript_like = concat!(
2512 "── assistant ──\n",
2513 "I'll run the build now.\n",
2514 "← tool result (call-1)\n",
2515 // JSON-escaped text is literal backslash-u bytes — inert, kept as-is.
2516 "{\"line\":\"\\u{1b}[<0;9;4Mprogress done\"}\n",
2517 // Raw event bytes are the dangerous form and must be stripped.
2518 "raw \u{1b}[<0;10;5M event bytes\u{1b}[2K after\n",
2519 );
2520 let pager = PagerView::from_text("Agent transcript", transcript_like, 200);
2521 let body = pager.body_text();
2522 assert!(!body.contains('\u{1b}'), "inert body required: {body:?}");
2523 assert!(
2524 !body.contains("<0;10;5M"),
2525 "mouse event fragment must not render: {body:?}"
2526 );
2527 assert!(
2528 body.contains("progress") && body.contains("after"),
2529 "readable content survives: {body:?}"
2530 );
2531 }
2532
2533 #[test]
2534 fn y_emits_copy_event_for_vim_users() {
2535 let mut p = make_pager(3);
2536 let action = p.handle_key(key(KeyCode::Char('y')));
2537 assert!(
2538 matches!(action, ViewAction::Emit(ViewEvent::CopyToClipboard { .. })),
2539 "y must emit a copy event for vim-yank parity"
2540 );
2541 }
2542
2543 #[test]
2544 fn e_exports_turn_handoff_when_attached() {
2545 // #4108: the Turn Inspector pager carries a compact Markdown handoff;
2546 // `e` copies that artifact (not the visible inspector body) to the
2547 // clipboard via the host dispatcher.
2548 let mut p = make_pager(3).with_export_markdown("# Turn handoff\n\n## Intent\ndo the thing");
2549 let action = p.handle_key(key(KeyCode::Char('e')));
2550 match action {
2551 ViewAction::Emit(ViewEvent::CopyToClipboard { text, label }) => {
2552 assert!(text.contains("# Turn handoff"), "handoff text: {text}");
2553 assert_eq!(label, "Turn handoff");
2554 }
2555 other => panic!("expected CopyToClipboard emit, got {other:?}"),
2556 }
2557 }
2558
2559 #[test]
2560 fn e_is_inert_without_an_attached_handoff() {
2561 // Every other pager leaves `e` unbound so it never surprises the user.
2562 let mut p = make_pager(3);
2563 assert!(matches!(
2564 p.handle_key(key(KeyCode::Char('e'))),
2565 ViewAction::None
2566 ));
2567 }
2568
2569 #[test]
2570 fn copy_keys_inert_in_search_mode() {
2571 // Within `/`-search mode `c` and `y` must be treated as search
2572 // characters, not as a copy trigger — otherwise users typing a
2573 // query that contains either letter would lose their input.
2574 let mut p = make_pager(10);
2575 let _ = p.handle_key(key(KeyCode::Char('/')));
2576 assert!(p.search_mode);
2577 let action = p.handle_key(key(KeyCode::Char('c')));
2578 assert!(matches!(action, ViewAction::None));
2579 assert_eq!(p.search_input, "c");
2580 }
2581
2582 #[test]
2583 fn footer_hint_is_rendered_in_buffer() {
2584 let p = make_pager(5);
2585 let area = Rect::new(0, 0, 100, 10);
2586 let mut buf = Buffer::empty(area);
2587 p.render(area, &mut buf);
2588 // The footer is now anchored to the bottom of the modal body (above the
2589 // padding/border) rather than painted on the border, so scan the whole
2590 // frame for the action labels.
2591 let mut text = String::new();
2592 for y in 0..area.height {
2593 for x in 0..area.width {
2594 text.push_str(buf[(x, y)].symbol());
2595 }
2596 text.push('\n');
2597 }
2598 assert!(
2599 text.contains("close") || text.contains("scroll"),
2600 "expected footer hint in rendered pager, got:\n{text}"
2601 );
2602 }
2603
2604 /// `/` opens the search prompt; typing chars accumulates them; Enter
2605 /// commits and jumps to the first match. The matches index/count line
2606 /// must surface in the rendered buffer afterwards.
2607 #[test]
2608 fn search_finds_matches_and_renders_match_counter() {
2609 let mut p = make_pager(20);
2610 prime_layout(&mut p, 16);
2611
2612 // Open search.
2613 let _ = p.handle_key(key(KeyCode::Char('/')));
2614 // Type "5" to match line-005, line-015 (any line whose number contains
2615 // a 5 — make_pager produced "line-NNN" with three-digit indices).
2616 for ch in "5".chars() {
2617 let _ = p.handle_key(key(KeyCode::Char(ch)));
2618 }
2619 // Commit.
2620 let _ = p.handle_key(key(KeyCode::Enter));
2621
2622 // Render and look for the "match X/Y" status line.
2623 let area = Rect::new(0, 0, 60, 16);
2624 let mut buf = Buffer::empty(area);
2625 p.render(area, &mut buf);
2626 let mut full = String::new();
2627 for y in 0..area.height {
2628 for x in 0..area.width {
2629 full.push_str(buf[(x, y)].symbol());
2630 }
2631 full.push('\n');
2632 }
2633 assert!(
2634 full.contains("match 1/2") || full.contains("match 1/3"),
2635 "expected match counter; got buffer:\n{full}"
2636 );
2637 }
2638
2639 /// Esc while in search mode bails out AND clears the highlighted matches
2640 /// so the un-highlighted view returns. (Codex parity.)
2641 #[test]
2642 fn esc_in_search_mode_clears_matches() {
2643 let mut p = make_pager(20);
2644 prime_layout(&mut p, 16);
2645
2646 let _ = p.handle_key(key(KeyCode::Char('/')));
2647 let _ = p.handle_key(key(KeyCode::Char('5')));
2648 let _ = p.handle_key(key(KeyCode::Enter));
2649 assert!(p.search_total.get() > 0);
2650
2651 // Re-enter search mode and Esc out — matches must clear.
2652 let _ = p.handle_key(key(KeyCode::Char('/')));
2653 let _ = p.handle_key(key(KeyCode::Esc));
2654 assert_eq!(p.search_total.get(), 0);
2655 assert_eq!(p.search_input, "");
2656 assert!(!p.search_mode);
2657 }
2658
2659 /// `n` and `N` cycle forward and backward through matches, wrapping at
2660 /// the ends without panicking on out-of-bounds index.
2661 #[test]
2662 fn n_and_capital_n_cycle_matches_with_wrap() {
2663 let mut p = make_pager(50);
2664 prime_layout(&mut p, 16);
2665
2666 // Search "1" — matches every line whose printed index contains a 1.
2667 let _ = p.handle_key(key(KeyCode::Char('/')));
2668 let _ = p.handle_key(key(KeyCode::Char('1')));
2669 let _ = p.handle_key(key(KeyCode::Enter));
2670 let total = p.search_total.get();
2671 assert!(total > 1, "test needs multiple matches, got {total}");
2672
2673 let start = p.search_index.get();
2674 let _ = p.handle_key(key(KeyCode::Char('n')));
2675 assert_eq!(p.search_index.get(), (start + 1) % total);
2676 let _ = p.handle_key(key(KeyCode::Char('N')));
2677 assert_eq!(p.search_index.get(), start);
2678
2679 // Wrap backwards from 0 → last.
2680 let _ = p.handle_key(key(KeyCode::Char('N')));
2681 assert_eq!(p.search_index.get(), total - 1);
2682 let _ = p.handle_key(key(KeyCode::Char('n')));
2683 assert_eq!(p.search_index.get(), 0);
2684 }
2685
2686 /// While search matches exist and the prompt is closed, the matched
2687 /// lines are visually distinguished in the rendered buffer by their
2688 /// background color. We sample directly across the matched-line text
2689 /// columns rather than the whole row width because Paragraph leaves
2690 /// the trailing-area cells at the default background.
2691 #[test]
2692 fn matched_lines_get_highlight_background() {
2693 let mut p = make_pager(20);
2694 prime_layout(&mut p, 16);
2695
2696 let _ = p.handle_key(key(KeyCode::Char('/')));
2697 let _ = p.handle_key(key(KeyCode::Char('5')));
2698 let _ = p.handle_key(key(KeyCode::Enter));
2699 assert!(p.search_total.get() > 0);
2700
2701 let area = Rect::new(0, 0, 40, 16);
2702 let mut buf = Buffer::empty(area);
2703 p.render(area, &mut buf);
2704
2705 // Find the actual painted match: shared compact layout may move it.
2706 let row = (0..area.height)
2707 .find(|&y| {
2708 (0..area.width)
2709 .map(|x| buf[(x, y)].symbol())
2710 .collect::<String>()
2711 .contains("line-005")
2712 })
2713 .expect("matched text must be visible");
2714 let highlighted = (0..area.width)
2715 .filter(|&x| buf[(x, row)].style().bg == Some(Color::Yellow))
2716 .collect::<Vec<_>>();
2717 assert_eq!(highlighted.len(), "line-005".len());
2718 for x in highlighted {
2719 assert_eq!(buf[(x, row)].style().fg, Some(Color::Black));
2720 }
2721 }
2722
2723 #[test]
2724 fn mouse_scroll_up_scrolls_content() {
2725 let mut p = make_pager(50);
2726 p.scroll.set(10);
2727 let action = p.handle_mouse(MouseEvent {
2728 kind: MouseEventKind::ScrollUp,
2729 column: 0,
2730 row: 0,
2731 modifiers: KeyModifiers::NONE,
2732 });
2733
2734 assert_eq!(p.scroll.get(), 7);
2735 assert!(matches!(action, ViewAction::None));
2736 }
2737
2738 #[test]
2739 fn mouse_scroll_down_scrolls_content() {
2740 let mut p = make_pager(50);
2741 prime_layout(&mut p, 20);
2742 p.scroll.set(10);
2743 let action = p.handle_mouse(MouseEvent {
2744 kind: MouseEventKind::ScrollDown,
2745 column: 0,
2746 row: 0,
2747 modifiers: KeyModifiers::NONE,
2748 });
2749
2750 assert_eq!(p.scroll.get(), 13);
2751 assert!(matches!(action, ViewAction::None));
2752 }
2753
2754 #[test]
2755 fn mouse_scroll_down_clamps_to_pager_bottom() {
2756 let mut p = make_pager(50);
2757 prime_layout(&mut p, 20);
2758 let bottom = p.max_scroll();
2759
2760 for _ in 0..100 {
2761 let _ = p.handle_mouse(MouseEvent {
2762 kind: MouseEventKind::ScrollDown,
2763 column: 0,
2764 row: 0,
2765 modifiers: KeyModifiers::NONE,
2766 });
2767 }
2768
2769 assert_eq!(p.scroll.get(), bottom);
2770 }
2771
2772 #[test]
2773 fn pager_is_usable_and_opaque_at_blocker_sizes() {
2774 use crate::tui::views::ViewStack;
2775
2776 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
2777 for (w, h) in BLOCKER_SIZES {
2778 let area = Rect::new(0, 0, w, h);
2779 let mut buf = Buffer::empty(area);
2780 for y in 0..h {
2781 for x in 0..w {
2782 buf[(x, y)].set_symbol("X");
2783 }
2784 }
2785 let mut stack = ViewStack::new();
2786 stack.push(make_pager(60));
2787 stack.render(area, &mut buf);
2788
2789 let rows: Vec<String> = (0..h)
2790 .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
2791 .collect();
2792 let text = rows.join("\n");
2793
2794 // Footer keeps every action.
2795 for label in [
2796 "close",
2797 "scroll",
2798 "page",
2799 "half",
2800 "top/bottom",
2801 "search",
2802 "copy",
2803 ] {
2804 assert!(text.contains(label), "{w}x{h}: footer missing '{label}'");
2805 }
2806
2807 assert!(!text.contains('X'), "{w}x{h}: background bleed-through");
2808 assert_eq!(
2809 buf[(w / 2, h / 2)].bg,
2810 palette::COMPOSER_BG,
2811 "{w}x{h}: modal interior must be opaque"
2812 );
2813
2814 // No horizontal overflow.
2815 for (y, row) in rows.iter().enumerate() {
2816 assert!(
2817 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
2818 "{w}x{h}: row {y} overflows width: {row:?}"
2819 );
2820 }
2821 }
2822 }
2823
2824 #[test]
2825 fn wrap_text_keeps_indentation_columns_and_repeated_spaces() {
2826 assert_eq!(wrap_text(" return x", 40), [" return x"]);
2827 assert_eq!(wrap_text("\tif ok:", 40), [" if ok:"]);
2828 assert_eq!(wrap_text("name size", 40), ["name size"]);
2829 assert_eq!(wrap_text("10%\r20%\u{b}x\u{2028}y", 40), ["10% 20% x y"]);
2830 // Only the whitespace at a soft break is consumed.
2831 assert_eq!(wrap_text(" alpha beta", 9), [" alpha", "beta"]);
2832 // An indent wider than the row still keeps every column it can.
2833 assert_eq!(wrap_text(" word", 4), [" ", " wo", "rd"]);
2834 }
2835
2836 #[test]
2837 fn text_pager_displays_and_copies_code_with_its_indentation() {
2838 let source = "def f(x):\n if x:\n\treturn x\n\n| a | b |";
2839 let mut pager = PagerView::from_text("Selection", source, 80);
2840
2841 assert_eq!(
2842 pager.body_text(),
2843 "def f(x):\n if x:\n return x\n\n| a | b |"
2844 );
2845 match pager.handle_key(key(KeyCode::Char('y'))) {
2846 ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) => {
2847 assert_eq!(text, source, "copy must carry the source, not the display");
2848 }
2849 other => panic!("expected CopyToClipboard emit, got {other:?}"),
2850 }
2851 }
2852
2853 #[test]
2854 fn text_pager_rewraps_to_its_body_so_end_reaches_the_last_line() {
2855 // Callers wrap to the transcript width minus two; the pager body is
2856 // narrower (margins, padding, scroll rail). Rows that fit the caller's
2857 // width but not the body used to wrap again in the paragraph, which
2858 // the scroll arithmetic never counted.
2859 let mut text: Vec<String> = (0..39)
2860 .map(|i| format!("row {i:02} {}", "word ".repeat(14).trim_end()))
2861 .collect();
2862 text.push(format!(
2863 "row 39 {} END-MARKER",
2864 "word ".repeat(12).trim_end()
2865 ));
2866 let text = text.join("\n");
2867 let (width, height) = (80u16, 24u16);
2868 let mut pager = PagerView::from_text("Message", &text, width - 2);
2869 let area = Rect::new(0, 0, width, height);
2870 let mut buf = Buffer::empty(area);
2871 pager.render(area, &mut buf);
2872
2873 let _ = pager.handle_key(key(KeyCode::End));
2874 let mut buf = Buffer::empty(area);
2875 pager.render(area, &mut buf);
2876 let screen: String = (0..height)
2877 .map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>())
2878 .collect::<Vec<_>>()
2879 .join("\n");
2880 assert!(
2881 screen.contains("END-MARKER"),
2882 "End must reveal the last line:\n{screen}"
2883 );
2884 }
2885
2886 fn render_screen(pager: &PagerView, width: u16, height: u16) -> String {
2887 let area = Rect::new(0, 0, width, height);
2888 let mut buf = Buffer::empty(area);
2889 pager.render(area, &mut buf);
2890 (0..height)
2891 .map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>())
2892 .collect::<Vec<_>>()
2893 .join("\n")
2894 }
2895
2896 #[test]
2897 fn styled_pager_wraps_to_its_body_so_end_reaches_the_last_line() {
2898 // A styled row wider than the body used to be wrapped by the
2899 // paragraph but counted as one row, so End stopped short of the tail.
2900 let mut lines: Vec<Line<'static>> = (0..39)
2901 .map(|i| {
2902 Line::from(vec![
2903 Span::styled(format!("row {i:02} "), Style::default().fg(Color::Cyan)),
2904 Span::raw("word ".repeat(20)),
2905 ])
2906 })
2907 .collect();
2908 lines.push(Line::from(format!(
2909 "row 39 {}END-MARKER",
2910 "word ".repeat(20)
2911 )));
2912 let mut pager = PagerView::new("Models", lines);
2913 let (width, height) = (80u16, 24u16);
2914 render_screen(&pager, width, height);
2915
2916 let _ = pager.handle_key(key(KeyCode::End));
2917 let screen = render_screen(&pager, width, height);
2918 assert!(
2919 screen.contains("END-MARKER"),
2920 "End must reveal the last line:\n{screen}"
2921 );
2922 // Wrapping keeps each piece's style and copies the unwrapped source.
2923 let rows = pager.current_page().rows();
2924 assert!(
2925 rows.styled
2926 .iter()
2927 .flat_map(|row| &row.spans)
2928 .any(|span| span.style.fg == Some(Color::Cyan))
2929 );
2930 assert!(rows.total > 40, "rows must be wrapped: {}", rows.total);
2931 drop(rows);
2932 match pager.handle_key(key(KeyCode::Char('c'))) {
2933 ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) => {
2934 assert_eq!(text.lines().count(), 40);
2935 }
2936 other => panic!("expected CopyToClipboard emit, got {other:?}"),
2937 }
2938 }
2939
2940 #[test]
2941 fn wrap_text_advances_tabs_to_stops_and_drops_bidi_format_chars() {
2942 assert_eq!(wrap_text("a\tb", 40), ["a b"]);
2943 assert_eq!(wrap_text("abcd\tb", 40), ["abcd b"]);
2944 assert_eq!(wrap_text("会\tb", 40), ["会 b"]);
2945 assert_eq!(wrap_text("left\u{202E}right\u{2066}", 40), ["leftright"]);
2946 assert_eq!(wrap_text("👩‍💻\tx", 40), ["👩‍💻 x"]);
2947 }
2948
2949 #[test]
2950 fn pager_wraps_whole_graphemes_and_preserves_their_styles() {
2951 for grapheme in ["👩‍💻", "👍🏽", "🇨🇳", "1\u{fe0f}\u{20e3}"] {
2952 assert_eq!(wrap_text(grapheme, 2), [grapheme]);
2953 let source = grapheme.repeat(2);
2954 assert_eq!(wrap_text(&source, 2), [grapheme, grapheme]);
2955 let style = Style::default().fg(Color::Cyan);
2956 let rows = PagerRows::wrap_lines(&[Line::from(Span::styled(source, style))], 2);
2957 assert_eq!(rows.plain, [grapheme, grapheme]);
2958 assert!(
2959 rows.styled
2960 .iter()
2961 .all(|row| row.spans.len() == 1 && row.spans[0].style == style)
2962 );
2963 }
2964 assert_eq!(wrap_text("a\u{301}b", 1), ["a\u{301}", "b"]);
2965 }
2966
2967 #[test]
2968 fn resize_recomputes_zero_matches_before_reserving_the_status_row() {
2969 let query = "needle".repeat(10);
2970 let text = format!("{query}\n{}", "hay\n".repeat(40));
2971 let mut pager = PagerView::from_text("Output", &text, 38);
2972 let no_search = PagerView::from_text("Output", &text, 38);
2973 render_screen(&pager, 40, 24);
2974 let _ = pager.handle_key(key(KeyCode::Char('/')));
2975 for ch in query.chars() {
2976 let _ = pager.handle_key(key(KeyCode::Char(ch)));
2977 }
2978 let _ = pager.handle_key(key(KeyCode::Enter));
2979 assert_eq!(pager.search_total.get(), 0);
2980
2981 let wide = render_screen(&pager, 100, 24);
2982 render_screen(&no_search, 100, 24);
2983 assert!(wide.contains("match 1/1"), "{wide}");
2984 assert_eq!(pager.search_total.get(), 1);
2985 assert_eq!(pager.page_height() + 1, no_search.page_height());
2986
2987 let narrow = render_screen(&pager, 40, 24);
2988 render_screen(&no_search, 40, 24);
2989 assert!(!narrow.contains("match 1/1"), "{narrow}");
2990 assert_eq!(pager.search_total.get(), 0);
2991 assert_eq!(pager.page_height(), no_search.page_height());
2992 }
2993
2994 #[test]
2995 fn resize_keeps_the_top_line_and_the_current_match() {
2996 let text = (0..60)
2997 .map(|i| {
2998 let tag = if i == 40 { "needle" } else { "hay" };
2999 format!("row {i:02} {tag} {}", "word ".repeat(24).trim_end())
3000 })
3001 .collect::<Vec<_>>()
3002 .join("\n");
3003 let mut pager = PagerView::from_text("Output", &text, 98);
3004 render_screen(&pager, 100, 24);
3005 let _ = pager.handle_key(key(KeyCode::Char('/')));
3006 for ch in "needle".chars() {
3007 let _ = pager.handle_key(key(KeyCode::Char(ch)));
3008 }
3009 let _ = pager.handle_key(key(KeyCode::Enter));
3010
3011 // Narrowing re-wraps every line into more rows.
3012 let screen = render_screen(&pager, 60, 24);
3013 let first_body_row = screen
3014 .lines()
3015 .find(|row| row.contains("row "))
3016 .unwrap_or_default();
3017 assert!(
3018 first_body_row.contains("row 40 needle"),
3019 "the line on top must stay on top after a resize:\n{screen}"
3020 );
3021 assert!(screen.contains("match 1/1"), "{screen}");
3022 let rows = pager.current_page().rows();
3023 assert_eq!(pager.search_total.get(), 1);
3024 assert!(
3025 rows.plain[pager.search_row.get().expect("selected match") - rows.start]
3026 .contains("needle")
3027 );
3028 }
3029
3030 #[test]
3031 fn wrap_text_breaks_overlong_cjk_runs() {
3032 let text = "这是一个非常长的中文字符串".repeat(10);
3033 let lines = wrap_text(&text, 16);
3034
3035 for line in &lines {
3036 assert!(line.width() <= 16, "line {line:?} exceeds width 16");
3037 }
3038
3039 assert_eq!(lines.join(""), text);
3040 }
3041
3042 #[test]
3043 fn pager_handle_paste_only_applies_in_search_mode_and_updates_matches() {
3044 let mut pager = PagerView::from_text("Output", "alpha line\nneedle target\nomega line", 80);
3045 assert!(!pager.handle_paste("needle"));
3046 assert!(pager.search_input.is_empty());
3047 assert_eq!(pager.search_total.get(), 0);
3048
3049 let _ = pager.handle_key(key(KeyCode::Char('/')));
3050 assert!(pager.search_mode);
3051 assert!(pager.handle_paste("needle\r\ntarget\n"));
3052 assert_eq!(pager.search_input, "needle target");
3053 assert_eq!(pager.search_total.get(), 1);
3054 assert_eq!(pager.search_row.get(), Some(1));
3055 }
3056 }
3057
3057 lines RUST