Skip to main content

vtcode_ui/tui/core_tui/widgets/
transcript.rs

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
14/// Widget for rendering the transcript area with conversation history
15///
16/// This widget handles:
17/// - Scroll viewport management
18/// - Content caching and optimization
19/// - Text wrapping and overflow
20/// - Queue overlay rendering
21///
22/// # Example
23/// ```ignore
24/// TranscriptWidget::new(session)
25///     .show_scrollbar(true)
26///     .custom_style(style)
27///     .render(area, buf);
28/// ```
29pub struct TranscriptWidget<'a> {
30    session: &'a mut Session,
31    show_scrollbar: bool,
32    custom_style: Option<Style>,
33}
34
35impl<'a> TranscriptWidget<'a> {
36    /// Create a new TranscriptWidget with required parameters
37    pub fn new(session: &'a mut Session) -> Self {
38        Self { session, show_scrollbar: false, custom_style: None }
39    }
40
41    /// Enable or disable scrollbar rendering
42    #[must_use]
43    pub fn show_scrollbar(mut self, show: bool) -> Self {
44        self.show_scrollbar = show;
45        self
46    }
47
48    /// Set a custom style for the transcript
49    #[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        // Use cached visible lines to avoid rebuilding on every frame
91        let cached_lines = self
92            .session
93            .collect_transcript_window_cached(content_width, visible_start, viewport_rows);
94
95        // Check if we need to mutate the lines (queue overlay). Bottom padding
96        // rows need no mutation — the buffer is already default-styled empty
97        // space, so padding the line list only forced a per-frame clone.
98        let needs_mutation = !self.session.queued_inputs.is_empty();
99
100        // Fast path: no queue overlay, no live indicator shimmer, no
101        // explicit links, and no landing tint — paint cached rows in place
102        // without cloning Lines into Paragraph (hotpath: that clone was
103        // ~15KB/frame). The tint forces the slow path only while it lives.
104        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            // Need to mutate (queue overlay), so clone, pad to the viewport
123            // (overlay paints at the bottom), and modify.
124            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        // Only clear if content actually changed, not on viewport-only scroll
142        // This is a significant optimization: avoids expensive Clear operation on most scrolls
143        if self.session.transcript_clear_required {
144            Clear.render(scroll_area, buf);
145            self.session.transcript_clear_required = false;
146        }
147        // Paint full-width line tints AFTER Paragraph. Paragraph::render
148        // first fills the whole area with `default_style` (terminal bg),
149        // which would wipe a pre-painted band on cells past the line text.
150        // Precompute per-row tints so the owned lines can move into Paragraph
151        // without a second clone.
152        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        // Lines are already wrapped to `content_width` == `scroll_area.width` in
156        // reflow. Re-wrapping in Paragraph every frame was the dominant
157        // steady-state render cost (hotpath: ~21KB/frame).
158        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
202/// Paint pre-wrapped transcript rows by writing spans directly into the buffer.
203/// Avoids cloning `Line`s into `Paragraph` on the common no-link path.
204/// Span styles patch `default_style` (same merge order as Paragraph).
205fn 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
226/// Fill untinted cells on a diff row using `line_background` from borrowed rows.
227fn 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
256/// File-operation verbs in verb callouts (`Running Read …`, lowercased with
257/// the status line). `Ran` runs never shimmer the transcript row.
258const FILE_OPERATION_VERBS: &[&str] = &["read", "edited"];
259
260const FILE_OPERATION_INDICATORS: &[&str] = &[
261    "❋ Writing ",
262    "❋ Editing ",
263    "❋ Applying patch to ",
264    "❋ Search/replace in ",
265    "❋ Deleting ",
266    "❋ Drafting plan",
267    "❋ Validating plan",
268    "❋ Persisting plan",
269    "❋ Preparing approval",
270];
271
272/// Bold the spans of every visible line inside the jump-landing row range.
273/// Operates on the owned slow-path lines only; the cached rows are never
274/// mutated, so the tint vanishes without a trace once it expires.
275fn apply_transcript_flash(lines: &mut [Line<'static>], visible_start: usize, range: (usize, usize)) {
276    for (offset, line) in lines.iter_mut().enumerate() {
277        let row = visible_start.saturating_add(offset);
278        if row < range.0 || row >= range.1 {
279            continue;
280        }
281        for span in line.spans.iter_mut() {
282            span.style = span.style.add_modifier(Modifier::BOLD);
283        }
284    }
285}
286
287fn apply_active_file_operation_spinner(session: &Session, lines: &mut [Line<'static>]) {
288    let Some(phase) = active_indicator_shimmer_phase(session) else {
289        return;
290    };
291
292    // Sweep a shimmer across the whole indicator line (icon + verb + target)
293    // at the shared shimmer phase, so the transcript pulses in sync with the
294    // footer. Only the newest indicator row animates and only while its work
295    // is live; the cached transcript is never mutated, so the static `❋`
296    // row (with its links/colors) returns untouched when activity ends.
297    for line in lines.iter_mut().rev() {
298        if !is_file_operation_indicator_line(line) {
299            continue;
300        }
301        let text = line.spans.iter().map(|span| span.content.as_ref()).collect::<String>();
302        let base_style = line.spans.first().map(|span| span.style).unwrap_or_default();
303        line.spans = shimmer_spans_with_style_at_phase(&text, base_style, phase);
304        break;
305    }
306}
307
308/// Shimmer phase for the active transcript indicator row, if any.
309///
310/// Returns `None` when animation is suppressed (reduced motion, screen
311/// reader) or nothing is live, so idle frames skip the span rebuild
312/// entirely. File tools key off `Running tool: <name>`; planning phases key
313/// off their footer statuses (`Drafting/Validating/Persisting plan...`,
314/// `Preparing approval...`), which the runloop keeps live while the long
315/// synthesis runs.
316fn active_indicator_shimmer_phase(session: &Session) -> Option<f32> {
317    if !session.appearance.should_animate_progress_status() {
318        return None;
319    }
320
321    let left = session.input_status_left.as_deref()?.to_ascii_lowercase();
322    if let Some(tool_name) = left.strip_prefix("running tool: ") {
323        return FILE_OPERATION_STATUS_TOOLS
324            .contains(&tool_name)
325            .then(|| session.shimmer_state.phase());
326    }
327    // Verb callouts (`Running Read main.rs`) carry the verb where the raw
328    // name used to: file verbs read like edits, `Ran` never does.
329    if let Some(verb) = left.strip_prefix("running ").and_then(|rest| rest.split_whitespace().next()) {
330        if FILE_OPERATION_VERBS.contains(&verb) {
331            return Some(session.shimmer_state.phase());
332        }
333    }
334
335    let is_planning_status = left.contains("drafting plan")
336        || left.contains("validating plan")
337        || left.contains("persisting plan")
338        || left.contains("preparing approval");
339    is_planning_status.then(|| session.shimmer_state.phase())
340}
341
342fn is_file_operation_indicator_line(line: &Line<'_>) -> bool {
343    let text = line.spans.iter().map(|span| span.content.as_ref()).collect::<String>();
344    FILE_OPERATION_INDICATORS.iter().any(|pattern| text.contains(pattern))
345}
346
347/// Full-row tint for a diff line.
348///
349/// Uses the marker/gutter background rather than a changed-word chip so a row
350/// with several syntax spans does not extend the stronger chip across padding.
351///
352/// Returns `None` for side-by-side rows — those mix coloured panes with an
353/// uncoloured sibling (or two different colours), and full-width fill would
354/// paint the empty pane with the other side's tint.
355fn line_background(line: &Line<'_>) -> Option<Color> {
356    // Fast reject: plain prose has no tinted spans and no side-by-side divider.
357    if !line.spans.iter().any(|span| span.style.bg.is_some()) {
358        return None;
359    }
360    let mut first_background = None;
361    let mut marker_background = None;
362    let mut has_uncolored_divider = false;
363    for span in &line.spans {
364        match span.style.bg {
365            Some(Color::Reset) if span.content.trim() == "│" => has_uncolored_divider = true,
366            Some(Color::Reset) => {}
367            Some(bg) => {
368                first_background.get_or_insert(bg);
369                if marker_background.is_none() && matches!(span.content.chars().next(), Some('+' | '-')) {
370                    marker_background = Some(bg);
371                }
372            }
373            None if span.content.trim() == "│" => has_uncolored_divider = true,
374            None => {}
375        }
376    }
377    // Side-by-side rows carry an uncoloured divider. Full-width fill would
378    // bleed one pane's tint into the other. Do not inspect every later span
379    // for a marker: a changed word can legitimately begin with `+` or `-`
380    // (for example `--last`) without turning a unified row into two panes.
381    if has_uncolored_divider {
382        return None;
383    }
384    marker_background.or(first_background)
385}
386
387/// Fill untinted cells on a diff row with the line tint.
388///
389/// Only cells still on the terminal default background are painted. Word-chip
390/// cells (stronger red/green) must keep their colour so the two-level band
391/// survives the full-width fill.
392fn apply_precomputed_line_backgrounds(
393    buf: &mut Buffer,
394    area: Rect,
395    row_tints: &[Option<Color>],
396    default_bg: Option<Color>,
397) {
398    if area.width == 0 || area.height == 0 {
399        return;
400    }
401
402    let max_rows = usize::from(area.height).min(row_tints.len());
403    for (row, bg) in row_tints.iter().take(max_rows).enumerate() {
404        let Some(bg) = bg else {
405            continue;
406        };
407        let y = area.y + row as u16;
408        for x in area.left()..area.right() {
409            let cell = &mut buf[(x, y)];
410            // Reset / terminal default → line tint. Any explicit paint
411            // (word chip, already-tinted span, etc.) is left alone.
412            if cell.bg == Color::Reset || Some(cell.bg) == default_bg {
413                cell.bg = *bg;
414            }
415        }
416    }
417}
418
419/// Fill untinted cells on a diff row with the line tint (test helper).
420#[cfg(test)]
421fn apply_full_width_line_backgrounds(buf: &mut Buffer, area: Rect, lines: &[Line<'_>], default_bg: Option<Color>) {
422    let row_tints: Vec<Option<Color>> = lines.iter().map(line_background).collect();
423    apply_precomputed_line_backgrounds(buf, area, &row_tints, default_bg);
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429    use crate::tui::core_tui::types::{InlineMessageKind, InlineSegment, InlineTextStyle, InlineTheme};
430    use std::sync::Arc;
431
432    fn segment(text: &str) -> InlineSegment {
433        InlineSegment {
434            text: text.to_string(),
435            style: Arc::new(InlineTextStyle::default()),
436        }
437    }
438
439    #[test]
440    fn transcript_flash_bolds_only_landed_rows_at_both_boundaries() {
441        use ratatui::style::Modifier as RatModifier;
442        use ratatui::text::Line as RatLine;
443
444        let mut lines = vec![
445            RatLine::raw("r0"),
446            RatLine::raw("r1"),
447            RatLine::raw("r2"),
448            RatLine::raw("r3"),
449        ];
450        // Viewport starts at global row 1; the landed message spans rows 1..3.
451        apply_transcript_flash(&mut lines, 1, (1, 3));
452        let bolded: Vec<bool> = lines
453            .iter()
454            .map(|line| {
455                line.spans
456                    .iter()
457                    .any(|span| span.style.add_modifier.contains(RatModifier::BOLD))
458            })
459            .collect();
460        assert_eq!(bolded, vec![true, true, false, false], "only rows 1..3 bold");
461        // A range outside the window paints nothing.
462        let mut lines = vec![RatLine::raw("r0"), RatLine::raw("r1")];
463        apply_transcript_flash(&mut lines, 10, (0, 2));
464        assert!(
465            lines
466                .iter()
467                .flat_map(|line| line.spans.iter())
468                .all(|span| !span.style.add_modifier.contains(RatModifier::BOLD)),
469            "off-window range paints nothing"
470        );
471    }
472
473    #[test]
474    fn full_width_diff_tint_survives_paragraph_default_bg() {
475        use ratatui::style::Style as RatStyle;
476        use ratatui::text::{Line as RatLine, Span as RatSpan};
477
478        let area = Rect::new(0, 0, 20, 1);
479        let mut buf = Buffer::empty(area);
480        // Simulate Paragraph painting the whole area with the terminal default.
481        buf.set_style(area, RatStyle::default().bg(Color::Black));
482        let line = RatLine::from(vec![RatSpan::styled("+ hi", RatStyle::default().bg(Color::Rgb(20, 58, 45)))]);
483        let lines = vec![line];
484        // Correct order: Paragraph (already simulated) then full-width tint.
485        apply_full_width_line_backgrounds(&mut buf, area, &lines, Some(Color::Black));
486
487        let bg = Color::Rgb(20, 58, 45);
488        assert_eq!(buf[(0, 0)].bg, bg, "left edge must keep the tint");
489        assert_eq!(buf[(19, 0)].bg, bg, "right edge must be full-width tinted");
490    }
491
492    #[test]
493    fn full_width_fill_preserves_word_chip_backgrounds() {
494        use ratatui::style::Style as RatStyle;
495        use ratatui::text::{Line as RatLine, Span as RatSpan};
496
497        let area = Rect::new(0, 0, 20, 1);
498        let mut buf = Buffer::empty(area);
499        let line_bg = Color::Rgb(20, 58, 45);
500        let chip_bg = Color::Rgb(36, 100, 70);
501        buf.set_style(area, RatStyle::default().bg(Color::Black));
502        // Simulate Paragraph writing: line tint on part, chip on "words".
503        buf[(3, 0)].bg = chip_bg;
504        buf[(4, 0)].bg = chip_bg;
505        buf[(5, 0)].bg = line_bg;
506
507        let line = RatLine::from(vec![RatSpan::styled("ab", RatStyle::default().bg(line_bg))]);
508        apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
509
510        assert_eq!(buf[(3, 0)].bg, chip_bg, "word chip must not be overwritten");
511        assert_eq!(buf[(4, 0)].bg, chip_bg, "word chip must not be overwritten");
512        assert_eq!(buf[(19, 0)].bg, line_bg, "empty cells fill with line tint");
513        assert_eq!(buf[(0, 0)].bg, line_bg);
514    }
515
516    #[test]
517    fn full_width_fill_uses_the_row_tint_when_word_chips_are_present() {
518        use ratatui::style::Style as RatStyle;
519        use ratatui::text::{Line as RatLine, Span as RatSpan};
520
521        let area = Rect::new(0, 0, 20, 1);
522        let mut buf = Buffer::empty(area);
523        let line_bg = Color::Rgb(20, 58, 45);
524        let chip_bg = Color::Rgb(36, 100, 70);
525        buf.set_style(area, RatStyle::default().bg(Color::Black));
526        for x in 1..8 {
527            buf[(x, 0)].bg = chip_bg;
528        }
529        let line = RatLine::from(vec![
530            RatSpan::styled("+", RatStyle::default().bg(line_bg)),
531            RatSpan::styled("changed", RatStyle::default().bg(chip_bg)),
532            RatSpan::styled(" ", RatStyle::default().bg(line_bg)),
533        ]);
534
535        apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
536
537        assert_eq!(buf[(1, 0)].bg, chip_bg, "word chip must remain stronger");
538        assert_eq!(buf[(19, 0)].bg, line_bg, "row tint must fill after word chip");
539    }
540
541    #[test]
542    fn full_width_fill_uses_the_marker_tint_when_syntax_chips_outnumber_it() {
543        use ratatui::style::Style as RatStyle;
544        use ratatui::text::{Line as RatLine, Span as RatSpan};
545
546        let area = Rect::new(0, 0, 20, 1);
547        let mut buf = Buffer::empty(area);
548        let line_bg = Color::Rgb(20, 58, 45);
549        let chip_bg = Color::Rgb(36, 100, 70);
550        buf.set_style(area, RatStyle::default().bg(Color::Black));
551        let line = RatLine::from(vec![
552            RatSpan::styled("+", RatStyle::default().bg(line_bg)),
553            RatSpan::styled("changed", RatStyle::default().bg(chip_bg)),
554            RatSpan::styled(" syntax", RatStyle::default().bg(chip_bg)),
555            RatSpan::styled(" tokens", RatStyle::default().bg(chip_bg)),
556        ]);
557
558        apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
559
560        assert_eq!(buf[(19, 0)].bg, line_bg, "padding must use the marker tint");
561    }
562
563    #[test]
564    fn full_width_fill_does_not_misclassify_dash_prefixed_word_chip() {
565        use ratatui::style::Style as RatStyle;
566        use ratatui::text::{Line as RatLine, Span as RatSpan};
567
568        let area = Rect::new(0, 0, 36, 1);
569        let mut buf = Buffer::empty(area);
570        let line_bg = Color::Rgb(70, 38, 42);
571        let chip_bg = Color::Rgb(140, 52, 58);
572        buf.set_style(area, RatStyle::default().bg(Color::Black));
573        let line = RatLine::from(vec![
574            RatSpan::styled("-", RatStyle::default().bg(line_bg)),
575            RatSpan::styled(" 256 │ vtcode trajectory ", RatStyle::default().bg(line_bg)),
576            RatSpan::styled("--last", RatStyle::default().bg(chip_bg)),
577        ]);
578        for x in 25..31 {
579            buf[(x, 0)].bg = chip_bg;
580        }
581
582        apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
583
584        assert_eq!(buf[(26, 0)].bg, chip_bg, "intraline chip must remain stronger");
585        assert_eq!(buf[(35, 0)].bg, line_bg, "a dash-prefixed chip must not create a tint gap");
586    }
587
588    #[test]
589    fn full_width_fill_survives_an_uncolored_indent_before_the_marker() {
590        use ratatui::style::Style as RatStyle;
591        use ratatui::text::{Line as RatLine, Span as RatSpan};
592
593        let area = Rect::new(0, 0, 20, 1);
594        let mut buf = Buffer::empty(area);
595        let line_bg = Color::Rgb(20, 58, 45);
596        buf.set_style(area, RatStyle::default().bg(Color::Black));
597        let line = RatLine::from(vec![
598            RatSpan::raw("    "),
599            RatSpan::styled("+", RatStyle::default().bg(line_bg)),
600            RatSpan::styled("new", RatStyle::default().bg(line_bg)),
601        ]);
602
603        apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
604
605        assert_eq!(buf[(19, 0)].bg, line_bg, "indentation must not disable row tinting");
606    }
607
608    #[test]
609    fn full_width_fill_skips_side_by_side_dividers() {
610        use ratatui::style::Style as RatStyle;
611        use ratatui::text::{Line as RatLine, Span as RatSpan};
612
613        let area = Rect::new(0, 0, 20, 1);
614        let mut buf = Buffer::empty(area);
615        let left_bg = Color::Rgb(70, 38, 42);
616        let right_bg = Color::Rgb(20, 58, 45);
617        buf.set_style(area, RatStyle::default().bg(Color::Black));
618        let line = RatLine::from(vec![
619            RatSpan::styled("-", RatStyle::default().bg(left_bg)),
620            RatSpan::raw("old       "),
621            RatSpan::raw("│"),
622            RatSpan::styled("+", RatStyle::default().bg(right_bg)),
623            RatSpan::styled("new", RatStyle::default().bg(right_bg)),
624        ]);
625
626        apply_full_width_line_backgrounds(&mut buf, area, &[line], Some(Color::Black));
627
628        assert_eq!(buf[(19, 0)].bg, Color::Black, "pane tint must not bleed across the row");
629    }
630
631    fn row_text(buf: &Buffer, area: Rect, row: u16) -> String {
632        (area.left()..area.right()).map(|x| buf[(x, row)].symbol()).collect::<String>()
633    }
634
635    #[test]
636    fn transcript_gutters_adapt_to_available_width() {
637        assert_eq!(
638            transcript_content_area(Rect::new(7, 3, 120, 12)),
639            Rect::new(9, 3, 116, 12),
640            "wide terminals get a modest two-column gutter",
641        );
642        assert_eq!(
643            transcript_content_area(Rect::new(7, 3, 80, 12)),
644            Rect::new(8, 3, 78, 12),
645            "standard terminals use a smaller gutter",
646        );
647        assert_eq!(
648            transcript_content_area(Rect::new(7, 3, 48, 12)),
649            Rect::new(7, 3, 48, 12),
650            "very narrow terminals keep the full width",
651        );
652
653        let area = Rect::new(0, 0, 120, 6);
654        let mut session = Session::new(InlineTheme::default(), None, 12);
655        session.push_line(InlineMessageKind::Agent, vec![segment("wide transcript")]);
656        let mut buf = Buffer::empty(area);
657        for x in [0, 1, 118, 119] {
658            buf[(x, 0)].set_symbol("X");
659        }
660
661        TranscriptWidget::new(&mut session).render(area, &mut buf);
662
663        assert_eq!(session.transcript_area(), Some(Rect::new(2, 0, 116, 6)));
664        assert_eq!(buf[(0, 0)].symbol(), " ", "left gutter must stay clear");
665        assert_eq!(buf[(1, 0)].symbol(), " ", "left gutter must stay clear");
666        assert_eq!(buf[(2, 0)].symbol(), "w", "message text starts inside the gutter");
667        assert_eq!(buf[(118, 0)].symbol(), " ", "right gutter must stay clear");
668        assert_eq!(buf[(119, 0)].symbol(), " ", "right gutter must stay clear");
669    }
670
671    #[test]
672    fn transcript_content_area_keeps_link_and_render_coordinates_aligned() {
673        let area = Rect::new(10, 2, 80, 8);
674        let content_area = transcript_content_area(area);
675        let url = "https://example.com/docs";
676        let mut session = Session::new(InlineTheme::default(), None, 12);
677        session.push_line(InlineMessageKind::Agent, vec![segment(&format!("Open {url}"))]);
678        let mut buf = Buffer::empty(area);
679
680        TranscriptWidget::new(&mut session).render(area, &mut buf);
681
682        assert_eq!(session.transcript_area(), Some(content_area));
683        let link_start = content_area.x + "Open ".len() as u16;
684        assert_eq!(buf[(link_start, area.y)].symbol(), "h");
685        assert!(
686            session.update_transcript_file_link_hover(link_start, area.y),
687            "the rendered URL cell should hit the matching transcript link target",
688        );
689        assert_eq!(row_text(&buf, area, area.y).chars().next(), Some(' '));
690    }
691
692    #[test]
693    fn very_narrow_transcript_keeps_wrapped_content_inside_the_viewport() {
694        let area = Rect::new(0, 0, 40, 6);
695        let mut session = Session::new(InlineTheme::default(), None, 12);
696        session.push_line(
697            InlineMessageKind::Agent,
698            vec![segment("alpha beta gamma delta epsilon zeta eta theta iota kappa")],
699        );
700        let mut buf = Buffer::empty(area);
701
702        TranscriptWidget::new(&mut session).render(area, &mut buf);
703
704        assert_eq!(session.transcript_area(), Some(area));
705        let rows: Vec<String> = (area.y..area.bottom())
706            .map(|row| row_text(&buf, area, row).trim_end().to_string())
707            .filter(|row| !row.is_empty())
708            .collect();
709        assert!(rows.len() >= 2, "narrow transcript should wrap into multiple rows: {rows:?}");
710        assert!(rows.iter().all(|row| row.chars().count() <= usize::from(area.width)));
711    }
712
713    #[test]
714    fn scroll_metric_invalidation_does_not_request_transcript_clear() {
715        let mut session = Session::new(InlineTheme::default(), None, 12);
716        session.transcript_clear_required = false;
717
718        session.invalidate_scroll_metrics();
719
720        assert!(!session.transcript_clear_required);
721    }
722
723    #[test]
724    fn render_clears_stale_wrapped_rows_when_requested() {
725        let area = Rect::new(0, 0, 14, 6);
726        let inner = area;
727        let mut buf = Buffer::empty(area);
728        let mut session = Session::new(InlineTheme::default(), None, 12);
729        session.push_line(InlineMessageKind::Agent, vec![segment("this line wraps across several rows")]);
730
731        TranscriptWidget::new(&mut session).render(area, &mut buf);
732
733        let revision = session.next_revision();
734        session.lines[0].segments = vec![segment("short")];
735        session.lines[0].revision = revision;
736        session.mark_line_dirty(0);
737        session.invalidate_transcript_cache();
738        for row in inner.y + 1..inner.bottom() {
739            for x in inner.left()..inner.right() {
740                buf[(x, row)].set_symbol("X");
741            }
742        }
743
744        TranscriptWidget::new(&mut session).render(area, &mut buf);
745
746        assert!((inner.y + 1..inner.bottom()).all(|row| row_text(&buf, inner, row).trim().is_empty()));
747    }
748
749    #[test]
750    fn render_preserves_queue_overlay_lines() {
751        let area = Rect::new(0, 0, 20, 6);
752        let inner = area;
753        let mut buf = Buffer::empty(area);
754        let mut session = Session::new(InlineTheme::default(), None, 12);
755        session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
756        session.push_queued_input("queued follow-up".to_string());
757
758        TranscriptWidget::new(&mut session).render(area, &mut buf);
759
760        let has_queued = (inner.y..inner.bottom()).any(|row| row_text(&buf, inner, row).contains("queued"));
761        assert!(has_queued, "queued overlay should be visible");
762    }
763
764    #[test]
765    fn render_queue_overlay_orders_items_fifo_oldest_on_top() {
766        let area = Rect::new(0, 0, 30, 8);
767        let inner = area;
768        let mut buf = Buffer::empty(area);
769        let mut session = Session::new(InlineTheme::default(), None, 12);
770        session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
771        session.push_queued_input("first".to_string());
772        session.push_queued_input("second".to_string());
773        session.push_queued_input("third".to_string());
774
775        TranscriptWidget::new(&mut session).render(area, &mut buf);
776
777        // The queue is strict FIFO, so the overlay shows the oldest message at
778        // the top and the newest directly above the input field.
779        let overlay_rows: Vec<String> = (inner.y..inner.bottom())
780            .map(|row| row_text(&buf, inner, row))
781            .map(|text| text.trim().to_string())
782            .filter(|text| !text.is_empty())
783            .collect();
784        let first_row = overlay_rows.iter().position(|row| row.contains("first"));
785        let second_row = overlay_rows.iter().position(|row| row.contains("second"));
786        let third_row = overlay_rows.iter().position(|row| row.contains("third"));
787        assert!(
788            first_row.is_some() && second_row.is_some() && third_row.is_some(),
789            "all three queued items must be visible in the overlay, got: {overlay_rows:?}"
790        );
791        assert!(
792            first_row.unwrap() < second_row.unwrap() && second_row.unwrap() < third_row.unwrap(),
793            "expected FIFO order first < second < third, got: {overlay_rows:?}"
794        );
795    }
796
797    #[test]
798    fn render_queue_overlay_flattens_multiline_entries() {
799        let area = Rect::new(0, 0, 40, 8);
800        let inner = area;
801        let mut buf = Buffer::empty(area);
802        let mut session = Session::new(InlineTheme::default(), None, 12);
803        session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
804        session.push_queued_input("line one\nline two".to_string());
805
806        TranscriptWidget::new(&mut session).render(area, &mut buf);
807
808        let overlay_text: String = (inner.y..inner.bottom()).map(|row| row_text(&buf, inner, row)).collect();
809        assert!(
810            overlay_text.contains("line one") && overlay_text.contains("line two"),
811            "both lines of the queued entry must be visible, got: {overlay_text:?}"
812        );
813        assert!(
814            overlay_text.contains("⏎"),
815            "newlines must be flattened into a visible separator, got: {overlay_text:?}"
816        );
817    }
818
819    #[test]
820    fn render_clears_stale_queue_overlay_rows_when_queue_is_removed() {
821        let area = Rect::new(0, 0, 20, 6);
822        let inner = area;
823        let mut buf = Buffer::empty(area);
824        let mut session = Session::new(InlineTheme::default(), None, 12);
825        session.push_line(InlineMessageKind::Agent, vec![segment("alpha")]);
826        session.push_queued_input("queued follow-up".to_string());
827
828        TranscriptWidget::new(&mut session).render(area, &mut buf);
829        let has_queued_before = (inner.y..inner.bottom()).any(|row| row_text(&buf, inner, row).contains("queued"));
830        assert!(has_queued_before, "queued should be visible before pop");
831
832        let _ = session.pop_latest_queued_input();
833
834        TranscriptWidget::new(&mut session).render(area, &mut buf);
835
836        let has_queued_after = (inner.y..inner.bottom()).any(|row| row_text(&buf, inner, row).contains("queued"));
837        assert!(!has_queued_after, "queued should be cleared after pop");
838    }
839
840    #[test]
841    fn resize_larger_keeps_existing_transcript_lines_visible() {
842        let small_area = Rect::new(0, 0, 20, 4);
843        let large_area = Rect::new(0, 0, 20, 10);
844        let small_inner = small_area;
845        let large_inner = large_area;
846        let mut small_buf = Buffer::empty(small_area);
847        let mut large_buf = Buffer::empty(large_area);
848        let mut session = Session::new(InlineTheme::default(), None, 12);
849
850        for index in 0..6 {
851            session.push_line(InlineMessageKind::Agent, vec![segment(&format!("line {index}"))]);
852        }
853
854        TranscriptWidget::new(&mut session).render(small_area, &mut small_buf);
855        let small_rendered: Vec<String> = (small_inner.y..small_inner.bottom())
856            .map(|row| row_text(&small_buf, small_inner, row).trim().to_string())
857            .filter(|row| !row.is_empty())
858            .collect();
859        TranscriptWidget::new(&mut session).render(large_area, &mut large_buf);
860
861        let rendered: Vec<String> = (large_inner.y..large_inner.bottom())
862            .map(|row| row_text(&large_buf, large_inner, row).trim().to_string())
863            .filter(|row| !row.is_empty())
864            .collect();
865
866        assert!(rendered.len() > small_rendered.len());
867        assert!(rendered.iter().any(|row| row == "line 1"));
868        assert!(rendered.iter().any(|row| row == "line 5"));
869    }
870
871    #[test]
872    fn width_resize_keeps_transcript_visible() {
873        let wide_area = Rect::new(0, 0, 28, 8);
874        let narrow_area = Rect::new(0, 0, 16, 8);
875        let narrow_inner = narrow_area;
876        let mut wide_buf = Buffer::empty(wide_area);
877        let mut narrow_buf = Buffer::empty(narrow_area);
878        let mut session = Session::new(InlineTheme::default(), None, 12);
879
880        for index in 0..4 {
881            session.push_line(InlineMessageKind::Agent, vec![segment(&format!("line {index}"))]);
882        }
883
884        TranscriptWidget::new(&mut session).render(wide_area, &mut wide_buf);
885        TranscriptWidget::new(&mut session).render(narrow_area, &mut narrow_buf);
886
887        let rendered: Vec<String> = (narrow_inner.y..narrow_inner.bottom())
888            .map(|row| row_text(&narrow_buf, narrow_inner, row).trim().to_string())
889            .filter(|row| !row.is_empty())
890            .collect();
891
892        assert!(!rendered.is_empty());
893        assert!(rendered.iter().any(|row| row == "line 1"));
894        assert!(rendered.iter().any(|row| row == "line 3"));
895    }
896
897    fn shimmer_session_with_status(status: &str) -> Session {
898        let mut session = Session::new(InlineTheme::default(), None, 12);
899        session.input_status_left = Some(status.to_string());
900        session
901    }
902
903    fn shimmer_line_text(line: &Line) -> String {
904        line.spans.iter().map(|span| span.content.as_ref()).collect()
905    }
906
907    #[test]
908    fn indicator_shimmer_preserves_text_and_restyles_active_row() {
909        use ratatui::text::Line as RatLine;
910        let session = shimmer_session_with_status("Running tool: edit_file");
911        let original = RatLine::from("❋ Editing vtcode.toml...");
912        let mut lines = vec![original.clone()];
913        apply_active_file_operation_spinner(&session, &mut lines);
914
915        assert_eq!(shimmer_line_text(&lines[0]), "❋ Editing vtcode.toml...");
916        assert_ne!(lines[0].spans, original.spans, "active row must shimmer");
917    }
918
919    #[test]
920    fn indicator_shimmer_sweep_moves_with_phase() {
921        use ratatui::text::Line as RatLine;
922        let mut session = shimmer_session_with_status("Drafting plan... (42 chars)");
923        // The sweep head starts off-text (10 chars of padding), so advance
924        // until it has travelled into the line. Bounded: ~12 ticks minimum.
925        for _ in 0..40 {
926            std::thread::sleep(std::time::Duration::from_millis(40));
927            session.handle_tick();
928            if session.shimmer_state.phase() >= 0.2 {
929                break;
930            }
931        }
932        assert!(
933            session.shimmer_state.phase() >= 0.2,
934            "phase must advance while drafting, got {}",
935            session.shimmer_state.phase()
936        );
937
938        let mut advanced = vec![RatLine::from("❋ Drafting plan — researching codebase...")];
939        apply_active_file_operation_spinner(&session, &mut advanced);
940
941        let fresh = shimmer_session_with_status("Drafting plan... (42 chars)");
942        let mut at_zero = vec![RatLine::from("❋ Drafting plan — researching codebase...")];
943        apply_active_file_operation_spinner(&fresh, &mut at_zero);
944
945        assert_eq!(shimmer_line_text(&advanced[0]), "❋ Drafting plan — researching codebase...");
946        assert_ne!(advanced[0].spans, at_zero[0].spans, "sweep position must follow the shared shimmer phase");
947    }
948
949    #[test]
950    fn indicator_shimmer_animates_only_the_newest_row() {
951        use ratatui::text::Line as RatLine;
952        let session = shimmer_session_with_status("Validating plan...");
953        let first = RatLine::from("❋ Drafting plan — researching codebase...");
954        let second = RatLine::from("❋ Validating plan...");
955        let mut lines = vec![first.clone(), second.clone()];
956        apply_active_file_operation_spinner(&session, &mut lines);
957
958        assert_eq!(lines[0].spans, first.spans, "older row must stay static");
959        assert_ne!(lines[1].spans, second.spans, "newest row must shimmer");
960    }
961
962    #[test]
963    fn indicator_shimmer_accepts_verb_callouts() {
964        use ratatui::text::Line as RatLine;
965        // File verbs shimmer like their raw-name twins; `Ran` never does.
966        for status in ["Running Read main.rs", "Running Edited main.rs"] {
967            let session = shimmer_session_with_status(status);
968            let original = RatLine::from("❋ Editing vtcode.toml...");
969            let mut lines = vec![original.clone()];
970            apply_active_file_operation_spinner(&session, &mut lines);
971            assert_ne!(lines[0].spans, original.spans, "file verb must shimmer for {status:?}");
972        }
973        let session = shimmer_session_with_status("Running Ran cargo check");
974        let original = RatLine::from("❋ Editing vtcode.toml...");
975        let mut lines = vec![original.clone()];
976        apply_active_file_operation_spinner(&session, &mut lines);
977        assert_eq!(lines[0].spans, original.spans, "runs must not shimmer the row");
978    }
979
980    #[test]
981    fn indicator_shimmer_stays_static_without_live_status() {
982        use ratatui::text::Line as RatLine;
983        for status in ["Running tool: code_search", "main*", "Ready"] {
984            let session = shimmer_session_with_status(status);
985            let original = RatLine::from("❋ Drafting plan — researching codebase...");
986            let mut lines = vec![original.clone()];
987            apply_active_file_operation_spinner(&session, &mut lines);
988            assert_eq!(lines[0].spans, original.spans, "stale row must not shimmer for {status:?}");
989        }
990
991        let mut session = shimmer_session_with_status("Drafting plan... (42 chars)");
992        session.appearance.reduce_motion_mode = true;
993        let original = RatLine::from("❋ Drafting plan — researching codebase...");
994        let mut lines = vec![original.clone()];
995        apply_active_file_operation_spinner(&session, &mut lines);
996        assert_eq!(lines[0].spans, original.spans, "reduced motion must keep the row static");
997    }
998}