Skip to main content

trusty_code_tui/widgets/
scrollback.rs

1//! The chat scrollback pane — generalized port of tagent's
2//! `repl/tui/chat.rs` (`build_chat_lines`/`chat_line_count`/`draw_chat`).
3//!
4//! Why: DOC-50 §5 Slice 4 migrates this file's markdown-aware chat rendering
5//! (fenced code blocks, tables, the banner-as-scrollback-prefix trick) since
6//! it's the single largest, most product-agnostic piece of tagent's TUI.
7//! Generalization removed exactly one thing: tagent's `AgentScope`-driven
8//! cyan/yellow leader color became [`crate::app::ReplApp::accent_color`], a
9//! plain engine-set field (see that field's doc comment) — everything else
10//! (fence/table detection via [`crate::render::markdown`], blank-line
11//! collapsing) is a direct, behavior-preserving port.
12//!
13//! What: [`build_chat_lines`] walks `app.chat` and returns the rendered
14//! `Vec<Line>` (banner prepended when `app.show_banner`); [`chat_line_count`]
15//! is the pre-layout height query [`crate::layout::draw`] uses to size the
16//! chat `Constraint`; [`draw_chat`] renders into a `Frame` with
17//! bottom-pinned padding and publishes the scroll cap to
18//! `app.last_max_scroll`.
19//!
20//! # Spec References
21//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 4 deliverable (§5, Slice 4): migrate `chat.rs`.
22
23use ratatui::layout::Rect;
24use ratatui::style::{Color, Modifier, Style};
25use ratatui::text::{Line, Span};
26use ratatui::widgets::{Paragraph, Wrap};
27
28use crate::app::{ChatRole, ReplApp};
29use crate::render::markdown::{
30    code_fence_lang, is_executable_shell_lang, is_md_table_row, is_md_table_separator,
31    parse_md_table_cells, render_markdown_table,
32};
33use crate::widgets::banner::banner_lines;
34
35/// Drop runs of 2+ consecutive whitespace-only `Line`s, keeping at most one.
36///
37/// Why: markdown-style `\n\n` paragraph breaks and the renderer's own
38/// inter-message spacer can compound into a run of several blank rows;
39/// collapsing them to one keeps the scrollback dense.
40/// What: operates after wrapping decisions but before pad/scroll math, so
41/// the geometry math sees the post-collapse line count.
42/// Test: `tests::collapse_blank_lines_drops_consecutive_empty_lines`.
43pub fn collapse_blank_lines(lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
44    let mut out: Vec<Line<'static>> = Vec::with_capacity(lines.len());
45    let mut prev_blank = false;
46    for line in lines {
47        let is_blank = line.spans.iter().all(|s| s.content.trim().is_empty());
48        if is_blank && prev_blank {
49            continue;
50        }
51        prev_blank = is_blank;
52        out.push(line);
53    }
54    out
55}
56
57/// Build the chat leader spans (`⏺ <label> · `) shared by every "first body
58/// line" branch below — table, fenced code, and plain-text alike.
59fn leader_spans(app: &ReplApp, body_color: Option<Color>) -> Vec<Span<'static>> {
60    let mut spans = vec![
61        Span::styled("⏺", Style::default().fg(Color::Indexed(208))),
62        Span::raw(" "),
63    ];
64    if body_color.is_none() {
65        spans.push(Span::styled(
66            app.label.clone(),
67            Style::default()
68                .fg(app.accent_color)
69                .add_modifier(Modifier::BOLD),
70        ));
71        spans.push(Span::styled(
72            " · ",
73            Style::default().add_modifier(Modifier::DIM),
74        ));
75    }
76    spans
77}
78
79/// Build the rendered `Vec<Line>` for the chat pane.
80///
81/// Why: extracted so layout code can compute the chat content height
82/// *before* the vertical layout split, letting the input row follow content
83/// height instead of being pinned to the screen bottom.
84/// What: replicates the banner + chat entry line-building logic; returns the
85/// post-collapse, pre-pad lines. Width-dependent rendering (banner wrapping,
86/// markdown table column sizing) uses `terminal_width`.
87/// Test: `tests::build_chat_lines_renders_user_and_assistant_entries`,
88/// `tests::build_chat_lines_renders_fenced_code_block`,
89/// `tests::build_chat_lines_renders_markdown_table`,
90/// `tests::build_chat_lines_prepends_banner_when_shown`.
91pub fn build_chat_lines(app: &ReplApp, terminal_width: usize) -> Vec<Line<'static>> {
92    let mut lines: Vec<Line<'static>> = Vec::new();
93
94    if app.show_banner {
95        lines.extend(banner_lines(app, terminal_width));
96        lines.push(Line::from(""));
97    }
98
99    let chat_len = app.chat.len();
100    for (idx, entry) in app.chat.iter().enumerate() {
101        match entry.role {
102            ChatRole::User => {
103                let mut iter = entry.text.lines();
104                if let Some(first) = iter.next() {
105                    lines.push(Line::from(vec![
106                        Span::styled("❯", Style::default().fg(Color::Green)),
107                        Span::raw(" "),
108                        Span::raw(first.to_string()),
109                    ]));
110                }
111                for cont in iter {
112                    lines.push(Line::from(format!("  {}", cont)));
113                }
114            }
115            ChatRole::Assistant | ChatRole::Error => {
116                let body_color = if entry.role == ChatRole::Error {
117                    Some(Color::Red)
118                } else {
119                    None
120                };
121                let body_lines: Vec<&str> = entry.text.lines().collect();
122                let mut i = 0usize;
123                let mut emitted_first = false;
124                while i < body_lines.len() {
125                    if let Some(lang) = code_fence_lang(body_lines[i]) {
126                        let is_shell = is_executable_shell_lang(&lang);
127                        if !emitted_first {
128                            lines.push(Line::from(leader_spans(app, body_color)));
129                            emitted_first = true;
130                        }
131                        let header_label = if lang.is_empty() {
132                            "code".to_string()
133                        } else {
134                            lang.clone()
135                        };
136                        if is_shell {
137                            lines.push(Line::from(vec![
138                                Span::raw("   "),
139                                Span::styled(
140                                    format!("▶ {}", header_label),
141                                    Style::default()
142                                        .fg(Color::LightGreen)
143                                        .add_modifier(Modifier::BOLD),
144                                ),
145                            ]));
146                        } else {
147                            lines.push(Line::from(vec![
148                                Span::raw("   "),
149                                Span::styled(
150                                    format!("⬡ {}", header_label),
151                                    Style::default().fg(Color::Indexed(75)),
152                                ),
153                            ]));
154                        }
155                        let mut j = i + 1;
156                        let body_style = Style::default().fg(Color::Indexed(244));
157                        while j < body_lines.len() {
158                            if code_fence_lang(body_lines[j]).is_some() {
159                                break;
160                            }
161                            lines.push(Line::from(Span::styled(
162                                format!("   {}", body_lines[j]),
163                                body_style,
164                            )));
165                            j += 1;
166                        }
167                        let j_is_closer = j < body_lines.len()
168                            && code_fence_lang(body_lines[j]).is_some_and(|lang| lang.is_empty());
169                        if j_is_closer {
170                            lines.push(Line::from(vec![
171                                Span::raw("   "),
172                                Span::styled(
173                                    "─".repeat(20),
174                                    Style::default().fg(Color::Indexed(240)),
175                                ),
176                            ]));
177                            i = j + 1;
178                        } else {
179                            i = j;
180                        }
181                        continue;
182                    }
183
184                    let is_table_start = i + 1 < body_lines.len()
185                        && is_md_table_row(body_lines[i])
186                        && is_md_table_separator(body_lines[i + 1]);
187
188                    if is_table_start {
189                        let header = parse_md_table_cells(body_lines[i]);
190                        let mut j = i + 2;
191                        let mut body_rows: Vec<Vec<String>> = Vec::new();
192                        while j < body_lines.len() && is_md_table_row(body_lines[j]) {
193                            body_rows.push(parse_md_table_cells(body_lines[j]));
194                            j += 1;
195                        }
196                        let indent = "   ";
197                        let avail = terminal_width.saturating_sub(1);
198                        let table_lines =
199                            render_markdown_table(&header, &body_rows, avail, indent, body_color);
200                        if !emitted_first {
201                            lines.push(Line::from(leader_spans(app, body_color)));
202                            emitted_first = true;
203                        }
204                        for tl in table_lines {
205                            lines.push(tl);
206                        }
207                        i = j;
208                        continue;
209                    }
210
211                    let raw = body_lines[i];
212                    if !emitted_first {
213                        let mut spans = leader_spans(app, body_color);
214                        spans.push(match body_color {
215                            Some(c) => Span::styled(raw.to_string(), Style::default().fg(c)),
216                            None => Span::raw(raw.to_string()),
217                        });
218                        lines.push(Line::from(spans));
219                        emitted_first = true;
220                    } else {
221                        let line = if raw.trim().is_empty() {
222                            Line::from("")
223                        } else {
224                            match body_color {
225                                Some(c) => Line::from(Span::styled(
226                                    format!("   {}", raw),
227                                    Style::default().fg(c),
228                                )),
229                                None => Line::from(Span::raw(format!("   {}", raw))),
230                            }
231                        };
232                        lines.push(line);
233                    }
234                    i += 1;
235                }
236            }
237            ChatRole::Status => {
238                lines.push(Line::from(vec![
239                    Span::styled(app.status_prefix.clone(), Style::default().fg(Color::Green)),
240                    Span::raw(entry.text.clone()),
241                ]));
242            }
243        }
244        let is_last = idx + 1 == chat_len;
245        if !is_last {
246            lines.push(Line::from(""));
247        }
248    }
249
250    let mut lines = collapse_blank_lines(lines);
251
252    if !app.chat.is_empty() {
253        lines.push(Line::from(""));
254    }
255
256    lines
257}
258
259/// Count chat content lines for layout sizing.
260///
261/// Why: [`crate::layout::draw`] needs to know the rendered content height
262/// *before* the vertical layout split so the chat pane can use
263/// `Constraint::Length(h)` instead of `Constraint::Min` — `Min` expands to
264/// fill all available space, pinning the input row to the screen bottom even
265/// when the conversation is short.
266/// What: returns the post-collapse, pre-pad line count from
267/// [`build_chat_lines`].
268/// Test: `tests::chat_line_count_is_zero_for_empty_chat_without_banner`.
269pub fn chat_line_count(app: &ReplApp, terminal_width: usize) -> usize {
270    build_chat_lines(app, terminal_width).len()
271}
272
273/// Render the chat pane into `area`, bottom-pinned when content fits.
274///
275/// Why: mirrors an iMessage/Slack-style chat feel — short conversations sit
276/// flush at the bottom of the pane rather than floating at the top with a
277/// sea of blank space below.
278/// What: pads with blank lines above the content when it fits; otherwise
279/// scrolls so the newest line stays in view (clamped by
280/// `app.scroll_offset`). Publishes the computed max scroll offset to
281/// `app.last_max_scroll` so `ReplApp::scroll` can clamp future deltas.
282/// Test: exercised via `draw` in [`crate::layout`]; the pure geometry
283/// (padding decision, max-offset computation) is covered indirectly through
284/// [`build_chat_lines`]'s tests plus [`ReplApp::scroll`]'s own tests in
285/// `crate::app::reduce`.
286pub fn draw_chat(f: &mut ratatui::Frame, app: &ReplApp, area: Rect) {
287    let lines = build_chat_lines(app, area.width as usize);
288
289    let visible = area.height as usize;
290    let total = lines.len();
291
292    let final_lines = if !app.chat.is_empty() && total < visible {
293        let pad = visible - total;
294        let mut padded = Vec::with_capacity(visible);
295        for _ in 0..pad {
296            padded.push(Line::from(""));
297        }
298        padded.extend(lines);
299        padded
300    } else {
301        lines
302    };
303
304    let final_total = final_lines.len();
305    let max_offset = final_total.saturating_sub(visible);
306    app.last_max_scroll
307        .store(max_offset, std::sync::atomic::Ordering::Relaxed);
308    let effective_offset = max_offset.saturating_sub(app.scroll_offset);
309
310    let paragraph = Paragraph::new(final_lines)
311        .wrap(Wrap { trim: false })
312        .scroll((effective_offset as u16, 0));
313    f.render_widget(paragraph, area);
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use crate::app::ReplApp;
320
321    fn line_text(line: &Line<'_>) -> String {
322        line.spans.iter().map(|s| s.content.as_ref()).collect()
323    }
324
325    fn all_text(lines: &[Line<'_>]) -> String {
326        lines.iter().map(line_text).collect::<Vec<_>>().join("\n")
327    }
328
329    fn app_without_banner() -> ReplApp {
330        let mut app = ReplApp::new("demo", "bob");
331        app.show_banner = false;
332        app
333    }
334
335    #[test]
336    fn chat_line_count_is_zero_for_empty_chat_without_banner() {
337        let app = app_without_banner();
338        assert_eq!(chat_line_count(&app, 80), 0);
339    }
340
341    #[test]
342    fn build_chat_lines_renders_user_and_assistant_entries() {
343        let mut app = app_without_banner();
344        app.push_user("hello");
345        app.push_assistant("hi there", false);
346        let text = all_text(&build_chat_lines(&app, 80));
347        assert!(text.contains("❯ hello"));
348        assert!(text.contains("demo"));
349        assert!(text.contains("hi there"));
350    }
351
352    #[test]
353    fn build_chat_lines_renders_fenced_code_block() {
354        let mut app = app_without_banner();
355        app.push_assistant("Run:\n```bash\necho hi\n```\nDone.", false);
356        let text = all_text(&build_chat_lines(&app, 80));
357        assert!(
358            text.contains("▶ bash"),
359            "missing shell fence header: {text}"
360        );
361        assert!(text.contains("echo hi"));
362    }
363
364    #[test]
365    fn build_chat_lines_renders_markdown_table() {
366        let mut app = app_without_banner();
367        app.push_assistant("| a | b |\n|---|---|\n| 1 | 2 |", false);
368        let text = all_text(&build_chat_lines(&app, 80));
369        assert!(text.contains('┌'), "missing table border: {text}");
370        assert!(text.contains('1'));
371        assert!(text.contains('2'));
372    }
373
374    #[test]
375    fn build_chat_lines_prepends_banner_when_shown() {
376        let app = ReplApp::new("demo", "bob");
377        assert!(app.show_banner);
378        let lines = build_chat_lines(&app, 80);
379        assert!(!lines.is_empty(), "banner must render even with no chat");
380    }
381
382    #[test]
383    fn build_chat_lines_error_role_renders_red_body() {
384        let mut app = app_without_banner();
385        app.push_assistant("boom", true);
386        // The error body carries a distinct color from a normal response —
387        // spot-check via the raw text still round-tripping (styling itself
388        // is asserted indirectly by `ReplApp::push_assistant`'s role test).
389        let text = all_text(&build_chat_lines(&app, 80));
390        assert!(text.contains("boom"));
391    }
392
393    #[test]
394    fn build_chat_lines_status_role_uses_configured_prefix() {
395        let mut app = app_without_banner();
396        app.status_prefix = "[custom] ".to_string();
397        app.push_status("hello");
398        let text = all_text(&build_chat_lines(&app, 80));
399        assert!(text.contains("[custom] hello"));
400    }
401
402    #[test]
403    fn collapse_blank_lines_drops_consecutive_empty_lines() {
404        let input: Vec<Line<'static>> = vec![
405            Line::from("a"),
406            Line::from(""),
407            Line::from(""),
408            Line::from("b"),
409            Line::from("   "),
410            Line::from(""),
411            Line::from("c"),
412        ];
413        let out = collapse_blank_lines(input);
414        assert_eq!(out.len(), 5);
415        assert_eq!(out[0].spans[0].content, "a");
416        assert!(out[1].spans.iter().all(|s| s.content.trim().is_empty()));
417        assert_eq!(out[2].spans[0].content, "b");
418        assert!(out[3].spans.iter().all(|s| s.content.trim().is_empty()));
419        assert_eq!(out[4].spans[0].content, "c");
420    }
421}