1use ratatui::{
2 buffer::Buffer,
3 layout::Rect,
4 style::{Color, Modifier, Style},
5 text::{Line, Span},
6 widgets::{Clear, Paragraph, Widget},
7};
8
9use crate::tui::config::constants::ui;
10use crate::tui::ui::tui::session::{Session, TranscriptLine};
11use tui_shimmer::shimmer_spans_with_style_at_phase;
12use vtcode_config::constants::tools;
13
14pub struct TranscriptWidget<'a> {
30 session: &'a mut Session,
31 show_scrollbar: bool,
32 custom_style: Option<Style>,
33}
34
35impl<'a> TranscriptWidget<'a> {
36 pub fn new(session: &'a mut Session) -> Self {
38 Self { session, show_scrollbar: false, custom_style: None }
39 }
40
41 #[must_use]
43 pub fn show_scrollbar(mut self, show: bool) -> Self {
44 self.show_scrollbar = show;
45 self
46 }
47
48 #[must_use]
50 pub fn custom_style(mut self, style: Style) -> Self {
51 self.custom_style = Some(style);
52 self
53 }
54}
55
56impl<'a> Widget for TranscriptWidget<'a> {
57 #[cfg_attr(feature = "profiling", hotpath::measure)]
58 fn render(self, area: Rect, buf: &mut Buffer) {
59 self.session.set_progress_area(None);
60 if area.height == 0 || area.width == 0 {
61 self.session.set_transcript_area(None);
62 self.session.clear_transcript_file_link_targets();
63 return;
64 }
65
66 let mut inner = transcript_content_area(area);
67 if self.session.progress.is_active() && inner.height > 0 && inner.width > 0 {
68 let progress_area = Rect::new(inner.x, inner.bottom().saturating_sub(1), inner.width, 1);
69 self.session.render_progress(progress_area, buf);
70 inner.height = inner.height.saturating_sub(1);
71 }
72
73 if inner.height == 0 || inner.width == 0 {
74 self.session.set_transcript_area(None);
75 self.session.clear_transcript_file_link_targets();
76 return;
77 }
78 let layout = self.session.layout_sticky_prompt(inner);
79 let scroll_area = layout.body;
80 let content_width = scroll_area.width;
81 let viewport_rows = usize::from(scroll_area.height);
82 let visible_start = layout.source_row;
83 if let Some(header) = layout.header {
84 let header_area = Rect::new(inner.x, inner.y, inner.width, 1);
85 let style = self.session.styles.sticky_prompt_style();
86 Clear.render(header_area, buf);
87 Paragraph::new(header).style(style).render(header_area, buf);
88 }
89
90 let cached_lines = self
92 .session
93 .collect_transcript_window_cached(content_width, visible_start, viewport_rows);
94
95 let needs_mutation = !self.session.queued_inputs.is_empty();
99
100 let has_links = cached_lines.iter().any(|line| !line.explicit_links.is_empty());
105 let spinner_active = active_indicator_shimmer_phase(self.session).is_some();
106 let flash_rows = self.session.transcript_flash_rows(content_width);
107 if !needs_mutation && !has_links && !spinner_active && flash_rows.is_none() {
108 self.session.clear_transcript_file_link_targets();
109 if self.session.transcript_clear_required {
110 Clear.render(scroll_area, buf);
111 self.session.transcript_clear_required = false;
112 }
113 let default_style = self.session.styles.default_style();
114 let default_bg = default_style.bg;
115 paint_pre_wrapped_lines(cached_lines.as_slice(), scroll_area, buf, default_style);
116 apply_borrowed_line_backgrounds(buf, scroll_area, cached_lines.as_slice(), default_bg);
117 clear_transcript_gutters(area, inner, default_style, buf);
118 return;
119 }
120
121 let mut visible_lines = if needs_mutation {
122 let mut lines = cached_lines.to_vec();
125 let fill_count = viewport_rows.saturating_sub(lines.len());
126 if fill_count > 0 {
127 let target_len = lines.len() + fill_count;
128 lines.resize_with(target_len, TranscriptLine::default);
129 }
130 self.session.overlay_queue_lines(&mut lines, content_width);
131 self.session.decorate_visible_cached_transcript_links(lines, scroll_area)
132 } else {
133 self.session
134 .decorate_borrowed_cached_transcript_links(cached_lines.as_slice(), scroll_area)
135 };
136 apply_active_file_operation_spinner(self.session, &mut visible_lines);
137 if let Some(range) = flash_rows {
138 apply_transcript_flash(&mut visible_lines, visible_start, range);
139 }
140
141 if self.session.transcript_clear_required {
144 Clear.render(scroll_area, buf);
145 self.session.transcript_clear_required = false;
146 }
147 let default_style = self.session.styles.default_style();
153 let default_bg = default_style.bg;
154 let row_tints: Vec<Option<Color>> = visible_lines.iter().map(line_background).collect();
155 let paragraph = Paragraph::new(visible_lines).style(default_style);
159 paragraph.render(scroll_area, buf);
160 apply_precomputed_line_backgrounds(buf, scroll_area, &row_tints, default_bg);
161 clear_transcript_gutters(area, inner, default_style, buf);
162 }
163}
164
165fn transcript_content_area(area: Rect) -> Rect {
166 let gutter = transcript_horizontal_gutter(area.width);
167 Rect::new(
168 area.x.saturating_add(gutter),
169 area.y,
170 area.width.saturating_sub(gutter.saturating_mul(2)),
171 area.height,
172 )
173}
174
175fn transcript_horizontal_gutter(width: u16) -> u16 {
176 if width >= ui::INLINE_TRANSCRIPT_WIDE_GUTTER_MIN_WIDTH {
177 ui::INLINE_TRANSCRIPT_WIDE_GUTTER_COLUMNS
178 } else if width >= ui::INLINE_TRANSCRIPT_STANDARD_GUTTER_MIN_WIDTH {
179 ui::INLINE_TRANSCRIPT_STANDARD_GUTTER_COLUMNS
180 } else {
181 0
182 }
183}
184
185fn clear_transcript_gutters(area: Rect, content_area: Rect, style: Style, buf: &mut Buffer) {
186 let left_width = content_area.x.saturating_sub(area.x);
187 if left_width > 0 {
188 let left = Rect::new(area.x, area.y, left_width, area.height);
189 Clear.render(left, buf);
190 buf.set_style(left, style);
191 }
192
193 let right_x = content_area.right();
194 let right_width = area.right().saturating_sub(right_x);
195 if right_width > 0 {
196 let right = Rect::new(right_x, area.y, right_width, area.height);
197 Clear.render(right, buf);
198 buf.set_style(right, style);
199 }
200}
201
202fn paint_pre_wrapped_lines(lines: &[TranscriptLine], area: Rect, buf: &mut Buffer, default_style: Style) {
206 buf.set_style(area, default_style);
207 let max_rows = usize::from(area.height).min(lines.len());
208 for (row, transcript_line) in lines.iter().take(max_rows).enumerate() {
209 let y = area.y + row as u16;
210 let mut x = area.x;
211 for span in &transcript_line.line.spans {
212 if x >= area.right() {
213 break;
214 }
215 let remaining = area.right().saturating_sub(x);
216 if remaining == 0 {
217 break;
218 }
219 let merged = default_style.patch(span.style);
220 let (end_x, _end_y) = buf.set_stringn(x, y, span.content.as_ref(), remaining as usize, merged);
221 x = end_x;
222 }
223 }
224}
225
226fn apply_borrowed_line_backgrounds(buf: &mut Buffer, area: Rect, lines: &[TranscriptLine], default_bg: Option<Color>) {
228 if area.width == 0 || area.height == 0 {
229 return;
230 }
231 let max_rows = usize::from(area.height).min(lines.len());
232 for (row, transcript_line) in lines.iter().take(max_rows).enumerate() {
233 let Some(bg) = line_background(&transcript_line.line) else {
234 continue;
235 };
236 let y = area.y + row as u16;
237 for x in area.left()..area.right() {
238 let cell = &mut buf[(x, y)];
239 if cell.bg == Color::Reset || Some(cell.bg) == default_bg {
240 cell.bg = bg;
241 }
242 }
243 }
244}
245
246const FILE_OPERATION_STATUS_TOOLS: &[&str] = &[
247 tools::WRITE_FILE,
248 tools::CREATE_FILE,
249 tools::EDIT_FILE,
250 tools::APPLY_PATCH,
251 tools::SEARCH_REPLACE,
252 tools::DELETE_FILE,
253 tools::UNIFIED_FILE,
254];
255
256const FILE_OPERATION_INDICATORS: &[&str] = &[
257 "❋ Writing ",
258 "❋ Editing ",
259 "❋ Applying patch to ",
260 "❋ Search/replace in ",
261 "❋ Deleting ",
262 "❋ Drafting plan",
263 "❋ Validating plan",
264 "❋ Persisting plan",
265 "❋ Preparing approval",
266];
267
268fn apply_transcript_flash(lines: &mut [Line<'static>], visible_start: usize, range: (usize, usize)) {
272 for (offset, line) in lines.iter_mut().enumerate() {
273 let row = visible_start.saturating_add(offset);
274 if row < range.0 || row >= range.1 {
275 continue;
276 }
277 for span in line.spans.iter_mut() {
278 span.style = span.style.add_modifier(Modifier::BOLD);
279 }
280 }
281}
282
283fn apply_active_file_operation_spinner(session: &Session, lines: &mut [Line<'static>]) {
284 let Some(phase) = active_indicator_shimmer_phase(session) else {
285 return;
286 };
287
288 for line in lines.iter_mut().rev() {
294 if !is_file_operation_indicator_line(line) {
295 continue;
296 }
297 let text = line.spans.iter().map(|span| span.content.as_ref()).collect::<String>();
298 let base_style = line.spans.first().map(|span| span.style).unwrap_or_default();
299 line.spans = shimmer_spans_with_style_at_phase(&text, base_style, phase);
300 break;
301 }
302}
303
304fn active_indicator_shimmer_phase(session: &Session) -> Option<f32> {
313 if !session.appearance.should_animate_progress_status() {
314 return None;
315 }
316
317 let left = session.input_status_left.as_deref()?.to_ascii_lowercase();
318 if let Some(tool_name) = left.strip_prefix("running tool: ") {
319 return FILE_OPERATION_STATUS_TOOLS
320 .contains(&tool_name)
321 .then(|| session.shimmer_state.phase());
322 }
323
324 let is_planning_status = left.contains("drafting plan")
325 || left.contains("validating plan")
326 || left.contains("persisting plan")
327 || left.contains("preparing approval");
328 is_planning_status.then(|| session.shimmer_state.phase())
329}
330
331fn is_file_operation_indicator_line(line: &Line<'_>) -> bool {
332 let text = line.spans.iter().map(|span| span.content.as_ref()).collect::<String>();
333 FILE_OPERATION_INDICATORS.iter().any(|pattern| text.contains(pattern))
334}
335
336fn line_background(line: &Line<'_>) -> Option<Color> {
345 if !line.spans.iter().any(|span| span.style.bg.is_some()) {
347 return None;
348 }
349 let mut first_background = None;
350 let mut marker_background = None;
351 let mut has_uncolored_divider = false;
352 for span in &line.spans {
353 match span.style.bg {
354 Some(Color::Reset) if span.content.trim() == "│" => has_uncolored_divider = true,
355 Some(Color::Reset) => {}
356 Some(bg) => {
357 first_background.get_or_insert(bg);
358 if marker_background.is_none() && matches!(span.content.chars().next(), Some('+' | '-')) {
359 marker_background = Some(bg);
360 }
361 }
362 None if span.content.trim() == "│" => has_uncolored_divider = true,
363 None => {}
364 }
365 }
366 if has_uncolored_divider {
371 return None;
372 }
373 marker_background.or(first_background)
374}
375
376fn apply_precomputed_line_backgrounds(
382 buf: &mut Buffer,
383 area: Rect,
384 row_tints: &[Option<Color>],
385 default_bg: Option<Color>,
386) {
387 if area.width == 0 || area.height == 0 {
388 return;
389 }
390
391 let max_rows = usize::from(area.height).min(row_tints.len());
392 for (row, bg) in row_tints.iter().take(max_rows).enumerate() {
393 let Some(bg) = bg else {
394 continue;
395 };
396 let y = area.y + row as u16;
397 for x in area.left()..area.right() {
398 let cell = &mut buf[(x, y)];
399 if cell.bg == Color::Reset || Some(cell.bg) == default_bg {
402 cell.bg = *bg;
403 }
404 }
405 }
406}
407
408#[cfg(test)]
410fn apply_full_width_line_backgrounds(buf: &mut Buffer, area: Rect, lines: &[Line<'_>], default_bg: Option<Color>) {
411 let row_tints: Vec<Option<Color>> = lines.iter().map(line_background).collect();
412 apply_precomputed_line_backgrounds(buf, area, &row_tints, default_bg);
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418 use crate::tui::core_tui::types::{InlineMessageKind, InlineSegment, InlineTextStyle, InlineTheme};
419 use std::sync::Arc;
420
421 fn segment(text: &str) -> InlineSegment {
422 InlineSegment {
423 text: text.to_string(),
424 style: Arc::new(InlineTextStyle::default()),
425 }
426 }
427
428 #[test]
429 fn transcript_flash_bolds_only_landed_rows_at_both_boundaries() {
430 use ratatui::style::Modifier as RatModifier;
431 use ratatui::text::Line as RatLine;
432
433 let mut lines = vec![
434 RatLine::raw("r0"),
435 RatLine::raw("r1"),
436 RatLine::raw("r2"),
437 RatLine::raw("r3"),
438 ];
439 apply_transcript_flash(&mut lines, 1, (1, 3));
441 let bolded: Vec<bool> = lines
442 .iter()
443 .map(|line| {
444 line.spans
445 .iter()
446 .any(|span| span.style.add_modifier.contains(RatModifier::BOLD))
447 })
448 .collect();
449 assert_eq!(bolded, vec![true, true, false, false], "only rows 1..3 bold");
450 let mut lines = vec![RatLine::raw("r0"), RatLine::raw("r1")];
452 apply_transcript_flash(&mut lines, 10, (0, 2));
453 assert!(
454 lines
455 .iter()
456 .flat_map(|line| line.spans.iter())
457 .all(|span| !span.style.add_modifier.contains(RatModifier::BOLD)),
458 "off-window range paints nothing"
459 );
460 }
461
462 #[test]
463 fn full_width_diff_tint_survives_paragraph_default_bg() {
464 use ratatui::style::Style as RatStyle;
465 use ratatui::text::{Line as RatLine, Span as RatSpan};
466
467 let area = Rect::new(0, 0, 20, 1);
468 let mut buf = Buffer::empty(area);
469 buf.set_style(area, RatStyle::default().bg(Color::Black));
471 let line = RatLine::from(vec![RatSpan::styled("+ hi", RatStyle::default().bg(Color::Rgb(20, 58, 45)))]);
472 let lines = vec![line];
473 apply_full_width_line_backgrounds(&mut buf, area, &lines, Some(Color::Black));
475
476 let bg = Color::Rgb(20, 58, 45);
477 assert_eq!(buf[(0, 0)].bg, bg, "left edge must keep the tint");
478 assert_eq!(buf[(19, 0)].bg, bg, "right edge must be full-width tinted");
479 }
480
481 #[test]
482 fn full_width_fill_preserves_word_chip_backgrounds() {
483 use ratatui::style::Style as RatStyle;
484 use ratatui::text::{Line as RatLine, Span as RatSpan};
485
486 let area = Rect::new(0, 0, 20, 1);
487 let mut buf = Buffer::empty(area);
488 let line_bg = Color::Rgb(20, 58, 45);
489 let chip_bg = Color::Rgb(36, 100, 70);
490 buf.set_style(area, RatStyle::default().bg(Color::Black));
491 buf[(3, 0)].bg = chip_bg;
493 buf[(4, 0)].bg = chip_bg;
494 buf[(5, 0)].bg = line_bg;
495
496 let line = RatLine::from(vec![RatSpan::styled("ab", RatStyle::default().bg(line_bg))]);
497 apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
498
499 assert_eq!(buf[(3, 0)].bg, chip_bg, "word chip must not be overwritten");
500 assert_eq!(buf[(4, 0)].bg, chip_bg, "word chip must not be overwritten");
501 assert_eq!(buf[(19, 0)].bg, line_bg, "empty cells fill with line tint");
502 assert_eq!(buf[(0, 0)].bg, line_bg);
503 }
504
505 #[test]
506 fn full_width_fill_uses_the_row_tint_when_word_chips_are_present() {
507 use ratatui::style::Style as RatStyle;
508 use ratatui::text::{Line as RatLine, Span as RatSpan};
509
510 let area = Rect::new(0, 0, 20, 1);
511 let mut buf = Buffer::empty(area);
512 let line_bg = Color::Rgb(20, 58, 45);
513 let chip_bg = Color::Rgb(36, 100, 70);
514 buf.set_style(area, RatStyle::default().bg(Color::Black));
515 for x in 1..8 {
516 buf[(x, 0)].bg = chip_bg;
517 }
518 let line = RatLine::from(vec![
519 RatSpan::styled("+", RatStyle::default().bg(line_bg)),
520 RatSpan::styled("changed", RatStyle::default().bg(chip_bg)),
521 RatSpan::styled(" ", RatStyle::default().bg(line_bg)),
522 ]);
523
524 apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
525
526 assert_eq!(buf[(1, 0)].bg, chip_bg, "word chip must remain stronger");
527 assert_eq!(buf[(19, 0)].bg, line_bg, "row tint must fill after word chip");
528 }
529
530 #[test]
531 fn full_width_fill_uses_the_marker_tint_when_syntax_chips_outnumber_it() {
532 use ratatui::style::Style as RatStyle;
533 use ratatui::text::{Line as RatLine, Span as RatSpan};
534
535 let area = Rect::new(0, 0, 20, 1);
536 let mut buf = Buffer::empty(area);
537 let line_bg = Color::Rgb(20, 58, 45);
538 let chip_bg = Color::Rgb(36, 100, 70);
539 buf.set_style(area, RatStyle::default().bg(Color::Black));
540 let line = RatLine::from(vec![
541 RatSpan::styled("+", RatStyle::default().bg(line_bg)),
542 RatSpan::styled("changed", RatStyle::default().bg(chip_bg)),
543 RatSpan::styled(" syntax", RatStyle::default().bg(chip_bg)),
544 RatSpan::styled(" tokens", RatStyle::default().bg(chip_bg)),
545 ]);
546
547 apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
548
549 assert_eq!(buf[(19, 0)].bg, line_bg, "padding must use the marker tint");
550 }
551
552 #[test]
553 fn full_width_fill_does_not_misclassify_dash_prefixed_word_chip() {
554 use ratatui::style::Style as RatStyle;
555 use ratatui::text::{Line as RatLine, Span as RatSpan};
556
557 let area = Rect::new(0, 0, 36, 1);
558 let mut buf = Buffer::empty(area);
559 let line_bg = Color::Rgb(70, 38, 42);
560 let chip_bg = Color::Rgb(140, 52, 58);
561 buf.set_style(area, RatStyle::default().bg(Color::Black));
562 let line = RatLine::from(vec![
563 RatSpan::styled("-", RatStyle::default().bg(line_bg)),
564 RatSpan::styled(" 256 │ vtcode trajectory ", RatStyle::default().bg(line_bg)),
565 RatSpan::styled("--last", RatStyle::default().bg(chip_bg)),
566 ]);
567 for x in 25..31 {
568 buf[(x, 0)].bg = chip_bg;
569 }
570
571 apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
572
573 assert_eq!(buf[(26, 0)].bg, chip_bg, "intraline chip must remain stronger");
574 assert_eq!(buf[(35, 0)].bg, line_bg, "a dash-prefixed chip must not create a tint gap");
575 }
576
577 #[test]
578 fn full_width_fill_survives_an_uncolored_indent_before_the_marker() {
579 use ratatui::style::Style as RatStyle;
580 use ratatui::text::{Line as RatLine, Span as RatSpan};
581
582 let area = Rect::new(0, 0, 20, 1);
583 let mut buf = Buffer::empty(area);
584 let line_bg = Color::Rgb(20, 58, 45);
585 buf.set_style(area, RatStyle::default().bg(Color::Black));
586 let line = RatLine::from(vec![
587 RatSpan::raw(" "),
588 RatSpan::styled("+", RatStyle::default().bg(line_bg)),
589 RatSpan::styled("new", RatStyle::default().bg(line_bg)),
590 ]);
591
592 apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
593
594 assert_eq!(buf[(19, 0)].bg, line_bg, "indentation must not disable row tinting");
595 }
596
597 #[test]
598 fn full_width_fill_skips_side_by_side_dividers() {
599 use ratatui::style::Style as RatStyle;
600 use ratatui::text::{Line as RatLine, Span as RatSpan};
601
602 let area = Rect::new(0, 0, 20, 1);
603 let mut buf = Buffer::empty(area);
604 let left_bg = Color::Rgb(70, 38, 42);
605 let right_bg = Color::Rgb(20, 58, 45);
606 buf.set_style(area, RatStyle::default().bg(Color::Black));
607 let line = RatLine::from(vec![
608 RatSpan::styled("-", RatStyle::default().bg(left_bg)),
609 RatSpan::raw("old "),
610 RatSpan::raw("│"),
611 RatSpan::styled("+", RatStyle::default().bg(right_bg)),
612 RatSpan::styled("new", RatStyle::default().bg(right_bg)),
613 ]);
614
615 apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
616
617 assert_eq!(buf[(19, 0)].bg, Color::Black, "pane tint must not bleed across the row");
618 }
619
620 fn row_text(buf: &Buffer, area: Rect, row: u16) -> String {
621 (area.left()..area.right()).map(|x| buf[(x, row)].symbol()).collect::<String>()
622 }
623
624 #[test]
625 fn transcript_gutters_adapt_to_available_width() {
626 assert_eq!(
627 transcript_content_area(Rect::new(7, 3, 120, 12)),
628 Rect::new(9, 3, 116, 12),
629 "wide terminals get a modest two-column gutter",
630 );
631 assert_eq!(
632 transcript_content_area(Rect::new(7, 3, 80, 12)),
633 Rect::new(8, 3, 78, 12),
634 "standard terminals use a smaller gutter",
635 );
636 assert_eq!(
637 transcript_content_area(Rect::new(7, 3, 48, 12)),
638 Rect::new(7, 3, 48, 12),
639 "very narrow terminals keep the full width",
640 );
641
642 let area = Rect::new(0, 0, 120, 6);
643 let mut session = Session::new(InlineTheme::default(), None, 12);
644 session.push_line(InlineMessageKind::Agent, vec![segment("wide transcript")]);
645 let mut buf = Buffer::empty(area);
646 for x in [0, 1, 118, 119] {
647 buf[(x, 0)].set_symbol("X");
648 }
649
650 TranscriptWidget::new(&mut session).render(area, &mut buf);
651
652 assert_eq!(session.transcript_area(), Some(Rect::new(2, 0, 116, 6)));
653 assert_eq!(buf[(0, 0)].symbol(), " ", "left gutter must stay clear");
654 assert_eq!(buf[(1, 0)].symbol(), " ", "left gutter must stay clear");
655 assert_eq!(buf[(2, 0)].symbol(), "w", "message text starts inside the gutter");
656 assert_eq!(buf[(118, 0)].symbol(), " ", "right gutter must stay clear");
657 assert_eq!(buf[(119, 0)].symbol(), " ", "right gutter must stay clear");
658 }
659
660 #[test]
661 fn transcript_content_area_keeps_link_and_render_coordinates_aligned() {
662 let area = Rect::new(10, 2, 80, 8);
663 let content_area = transcript_content_area(area);
664 let url = "https://example.com/docs";
665 let mut session = Session::new(InlineTheme::default(), None, 12);
666 session.push_line(InlineMessageKind::Agent, vec![segment(&format!("Open {url}"))]);
667 let mut buf = Buffer::empty(area);
668
669 TranscriptWidget::new(&mut session).render(area, &mut buf);
670
671 assert_eq!(session.transcript_area(), Some(content_area));
672 let link_start = content_area.x + "Open ".len() as u16;
673 assert_eq!(buf[(link_start, area.y)].symbol(), "h");
674 assert!(
675 session.update_transcript_file_link_hover(link_start, area.y),
676 "the rendered URL cell should hit the matching transcript link target",
677 );
678 assert_eq!(row_text(&buf, area, area.y).chars().next(), Some(' '));
679 }
680
681 #[test]
682 fn very_narrow_transcript_keeps_wrapped_content_inside_the_viewport() {
683 let area = Rect::new(0, 0, 40, 6);
684 let mut session = Session::new(InlineTheme::default(), None, 12);
685 session.push_line(
686 InlineMessageKind::Agent,
687 vec![segment("alpha beta gamma delta epsilon zeta eta theta iota kappa")],
688 );
689 let mut buf = Buffer::empty(area);
690
691 TranscriptWidget::new(&mut session).render(area, &mut buf);
692
693 assert_eq!(session.transcript_area(), Some(area));
694 let rows: Vec<String> = (area.y..area.bottom())
695 .map(|row| row_text(&buf, area, row).trim_end().to_string())
696 .filter(|row| !row.is_empty())
697 .collect();
698 assert!(rows.len() >= 2, "narrow transcript should wrap into multiple rows: {rows:?}");
699 assert!(rows.iter().all(|row| row.chars().count() <= usize::from(area.width)));
700 }
701
702 #[test]
703 fn scroll_metric_invalidation_does_not_request_transcript_clear() {
704 let mut session = Session::new(InlineTheme::default(), None, 12);
705 session.transcript_clear_required = false;
706
707 session.invalidate_scroll_metrics();
708
709 assert!(!session.transcript_clear_required);
710 }
711
712 #[test]
713 fn render_clears_stale_wrapped_rows_when_requested() {
714 let area = Rect::new(0, 0, 14, 6);
715 let inner = area;
716 let mut buf = Buffer::empty(area);
717 let mut session = Session::new(InlineTheme::default(), None, 12);
718 session.push_line(InlineMessageKind::Agent, vec![segment("this line wraps across several rows")]);
719
720 TranscriptWidget::new(&mut session).render(area, &mut buf);
721
722 let revision = session.next_revision();
723 session.lines[0].segments = vec![segment("short")];
724 session.lines[0].revision = revision;
725 session.mark_line_dirty(0);
726 session.invalidate_transcript_cache();
727 for row in inner.y + 1..inner.bottom() {
728 for x in inner.left()..inner.right() {
729 buf[(x, row)].set_symbol("X");
730 }
731 }
732
733 TranscriptWidget::new(&mut session).render(area, &mut buf);
734
735 assert!((inner.y + 1..inner.bottom()).all(|row| row_text(&buf, inner, row).trim().is_empty()));
736 }
737
738 #[test]
739 fn render_preserves_queue_overlay_lines() {
740 let area = Rect::new(0, 0, 20, 6);
741 let inner = area;
742 let mut buf = Buffer::empty(area);
743 let mut session = Session::new(InlineTheme::default(), None, 12);
744 session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
745 session.push_queued_input("queued follow-up".to_string());
746
747 TranscriptWidget::new(&mut session).render(area, &mut buf);
748
749 let has_queued = (inner.y..inner.bottom()).any(|row| row_text(&buf, inner, row).contains("queued"));
750 assert!(has_queued, "queued overlay should be visible");
751 }
752
753 #[test]
754 fn render_queue_overlay_orders_items_fifo_oldest_on_top() {
755 let area = Rect::new(0, 0, 30, 8);
756 let inner = area;
757 let mut buf = Buffer::empty(area);
758 let mut session = Session::new(InlineTheme::default(), None, 12);
759 session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
760 session.push_queued_input("first".to_string());
761 session.push_queued_input("second".to_string());
762 session.push_queued_input("third".to_string());
763
764 TranscriptWidget::new(&mut session).render(area, &mut buf);
765
766 let overlay_rows: Vec<String> = (inner.y..inner.bottom())
769 .map(|row| row_text(&buf, inner, row))
770 .map(|text| text.trim().to_string())
771 .filter(|text| !text.is_empty())
772 .collect();
773 let first_row = overlay_rows.iter().position(|row| row.contains("first"));
774 let second_row = overlay_rows.iter().position(|row| row.contains("second"));
775 let third_row = overlay_rows.iter().position(|row| row.contains("third"));
776 assert!(
777 first_row.is_some() && second_row.is_some() && third_row.is_some(),
778 "all three queued items must be visible in the overlay, got: {overlay_rows:?}"
779 );
780 assert!(
781 first_row.unwrap() < second_row.unwrap() && second_row.unwrap() < third_row.unwrap(),
782 "expected FIFO order first < second < third, got: {overlay_rows:?}"
783 );
784 }
785
786 #[test]
787 fn render_queue_overlay_flattens_multiline_entries() {
788 let area = Rect::new(0, 0, 40, 8);
789 let inner = area;
790 let mut buf = Buffer::empty(area);
791 let mut session = Session::new(InlineTheme::default(), None, 12);
792 session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
793 session.push_queued_input("line one\nline two".to_string());
794
795 TranscriptWidget::new(&mut session).render(area, &mut buf);
796
797 let overlay_text: String = (inner.y..inner.bottom()).map(|row| row_text(&buf, inner, row)).collect();
798 assert!(
799 overlay_text.contains("line one") && overlay_text.contains("line two"),
800 "both lines of the queued entry must be visible, got: {overlay_text:?}"
801 );
802 assert!(
803 overlay_text.contains("⏎"),
804 "newlines must be flattened into a visible separator, got: {overlay_text:?}"
805 );
806 }
807
808 #[test]
809 fn render_clears_stale_queue_overlay_rows_when_queue_is_removed() {
810 let area = Rect::new(0, 0, 20, 6);
811 let inner = area;
812 let mut buf = Buffer::empty(area);
813 let mut session = Session::new(InlineTheme::default(), None, 12);
814 session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
815 session.push_queued_input("queued follow-up".to_string());
816
817 TranscriptWidget::new(&mut session).render(area, &mut buf);
818 let has_queued_before = (inner.y..inner.bottom()).any(|row| row_text(&buf, inner, row).contains("queued"));
819 assert!(has_queued_before, "queued should be visible before pop");
820
821 let _ = session.pop_latest_queued_input();
822
823 TranscriptWidget::new(&mut session).render(area, &mut buf);
824
825 let has_queued_after = (inner.y..inner.bottom()).any(|row| row_text(&buf, inner, row).contains("queued"));
826 assert!(!has_queued_after, "queued should be cleared after pop");
827 }
828
829 #[test]
830 fn resize_larger_keeps_existing_transcript_lines_visible() {
831 let small_area = Rect::new(0, 0, 20, 4);
832 let large_area = Rect::new(0, 0, 20, 10);
833 let small_inner = small_area;
834 let large_inner = large_area;
835 let mut small_buf = Buffer::empty(small_area);
836 let mut large_buf = Buffer::empty(large_area);
837 let mut session = Session::new(InlineTheme::default(), None, 12);
838
839 for index in 0..6 {
840 session.push_line(InlineMessageKind::Agent, vec![segment(&format!("line {index}"))]);
841 }
842
843 TranscriptWidget::new(&mut session).render(small_area, &mut small_buf);
844 let small_rendered: Vec<String> = (small_inner.y..small_inner.bottom())
845 .map(|row| row_text(&small_buf, small_inner, row).trim().to_string())
846 .filter(|row| !row.is_empty())
847 .collect();
848 TranscriptWidget::new(&mut session).render(large_area, &mut large_buf);
849
850 let rendered: Vec<String> = (large_inner.y..large_inner.bottom())
851 .map(|row| row_text(&large_buf, large_inner, row).trim().to_string())
852 .filter(|row| !row.is_empty())
853 .collect();
854
855 assert!(rendered.len() > small_rendered.len());
856 assert!(rendered.iter().any(|row| row == "line 1"));
857 assert!(rendered.iter().any(|row| row == "line 5"));
858 }
859
860 #[test]
861 fn width_resize_keeps_transcript_visible() {
862 let wide_area = Rect::new(0, 0, 28, 8);
863 let narrow_area = Rect::new(0, 0, 16, 8);
864 let narrow_inner = narrow_area;
865 let mut wide_buf = Buffer::empty(wide_area);
866 let mut narrow_buf = Buffer::empty(narrow_area);
867 let mut session = Session::new(InlineTheme::default(), None, 12);
868
869 for index in 0..4 {
870 session.push_line(InlineMessageKind::Agent, vec![segment(&format!("line {index}"))]);
871 }
872
873 TranscriptWidget::new(&mut session).render(wide_area, &mut wide_buf);
874 TranscriptWidget::new(&mut session).render(narrow_area, &mut narrow_buf);
875
876 let rendered: Vec<String> = (narrow_inner.y..narrow_inner.bottom())
877 .map(|row| row_text(&narrow_buf, narrow_inner, row).trim().to_string())
878 .filter(|row| !row.is_empty())
879 .collect();
880
881 assert!(!rendered.is_empty());
882 assert!(rendered.iter().any(|row| row == "line 1"));
883 assert!(rendered.iter().any(|row| row == "line 3"));
884 }
885
886 fn shimmer_session_with_status(status: &str) -> Session {
887 let mut session = Session::new(InlineTheme::default(), None, 12);
888 session.input_status_left = Some(status.to_string());
889 session
890 }
891
892 fn shimmer_line_text(line: &Line) -> String {
893 line.spans.iter().map(|span| span.content.as_ref()).collect()
894 }
895
896 #[test]
897 fn indicator_shimmer_preserves_text_and_restyles_active_row() {
898 use ratatui::text::Line as RatLine;
899 let session = shimmer_session_with_status("Running tool: edit_file");
900 let original = RatLine::from("❋ Editing vtcode.toml...");
901 let mut lines = vec![original.clone()];
902 apply_active_file_operation_spinner(&session, &mut lines);
903
904 assert_eq!(shimmer_line_text(&lines[0]), "❋ Editing vtcode.toml...");
905 assert_ne!(lines[0].spans, original.spans, "active row must shimmer");
906 }
907
908 #[test]
909 fn indicator_shimmer_sweep_moves_with_phase() {
910 use ratatui::text::Line as RatLine;
911 let mut session = shimmer_session_with_status("Drafting plan... (42 chars)");
912 for _ in 0..40 {
915 std::thread::sleep(std::time::Duration::from_millis(40));
916 session.handle_tick();
917 if session.shimmer_state.phase() >= 0.2 {
918 break;
919 }
920 }
921 assert!(
922 session.shimmer_state.phase() >= 0.2,
923 "phase must advance while drafting, got {}",
924 session.shimmer_state.phase()
925 );
926
927 let mut advanced = vec![RatLine::from("❋ Drafting plan — researching codebase...")];
928 apply_active_file_operation_spinner(&session, &mut advanced);
929
930 let fresh = shimmer_session_with_status("Drafting plan... (42 chars)");
931 let mut at_zero = vec![RatLine::from("❋ Drafting plan — researching codebase...")];
932 apply_active_file_operation_spinner(&fresh, &mut at_zero);
933
934 assert_eq!(shimmer_line_text(&advanced[0]), "❋ Drafting plan — researching codebase...");
935 assert_ne!(advanced[0].spans, at_zero[0].spans, "sweep position must follow the shared shimmer phase");
936 }
937
938 #[test]
939 fn indicator_shimmer_animates_only_the_newest_row() {
940 use ratatui::text::Line as RatLine;
941 let session = shimmer_session_with_status("Validating plan...");
942 let first = RatLine::from("❋ Drafting plan — researching codebase...");
943 let second = RatLine::from("❋ Validating plan...");
944 let mut lines = vec![first.clone(), second.clone()];
945 apply_active_file_operation_spinner(&session, &mut lines);
946
947 assert_eq!(lines[0].spans, first.spans, "older row must stay static");
948 assert_ne!(lines[1].spans, second.spans, "newest row must shimmer");
949 }
950
951 #[test]
952 fn indicator_shimmer_stays_static_without_live_status() {
953 use ratatui::text::Line as RatLine;
954 for status in ["Running tool: code_search", "main*", "Ready"] {
955 let session = shimmer_session_with_status(status);
956 let original = RatLine::from("❋ Drafting plan — researching codebase...");
957 let mut lines = vec![original.clone()];
958 apply_active_file_operation_spinner(&session, &mut lines);
959 assert_eq!(lines[0].spans, original.spans, "stale row must not shimmer for {status:?}");
960 }
961
962 let mut session = shimmer_session_with_status("Drafting plan... (42 chars)");
963 session.appearance.reduce_motion_mode = true;
964 let original = RatLine::from("❋ Drafting plan — researching codebase...");
965 let mut lines = vec![original.clone()];
966 apply_active_file_operation_spinner(&session, &mut lines);
967 assert_eq!(lines[0].spans, original.spans, "reduced motion must keep the row static");
968 }
969}