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;
34use crate::widgets::tool_card::tool_card_lines;
35
36/// Drop runs of 2+ consecutive whitespace-only `Line`s, keeping at most one.
37///
38/// Why: markdown-style `\n\n` paragraph breaks and the renderer's own
39/// inter-message spacer can compound into a run of several blank rows;
40/// collapsing them to one keeps the scrollback dense.
41/// What: operates after wrapping decisions but before pad/scroll math, so
42/// the geometry math sees the post-collapse line count.
43/// Test: `tests::collapse_blank_lines_drops_consecutive_empty_lines`.
44pub fn collapse_blank_lines(lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
45    let mut out: Vec<Line<'static>> = Vec::with_capacity(lines.len());
46    let mut prev_blank = false;
47    for line in lines {
48        let is_blank = line.spans.iter().all(|s| s.content.trim().is_empty());
49        if is_blank && prev_blank {
50            continue;
51        }
52        prev_blank = is_blank;
53        out.push(line);
54    }
55    out
56}
57
58/// Build the chat leader spans (`⏺ <label> · `) shared by every "first body
59/// line" branch below — table, fenced code, and plain-text alike.
60fn leader_spans(app: &ReplApp, body_color: Option<Color>) -> Vec<Span<'static>> {
61    let mut spans = vec![
62        Span::styled("⏺", Style::default().fg(Color::Indexed(208))),
63        Span::raw(" "),
64    ];
65    if body_color.is_none() {
66        spans.push(Span::styled(
67            app.label.clone(),
68            Style::default()
69                .fg(app.accent_color)
70                .add_modifier(Modifier::BOLD),
71        ));
72        spans.push(Span::styled(
73            " · ",
74            Style::default().add_modifier(Modifier::DIM),
75        ));
76    }
77    spans
78}
79
80/// The gutter drawn to the left of every line inside a delegated
81/// sub-agent's block (#7940).
82pub(crate) const DELEGATED_GUTTER: &str = "  │ ";
83
84/// [`DELEGATED_GUTTER`] styled in the delegation accent — shared by
85/// delegated text and delegated tool cards (#4596).
86pub(crate) fn delegated_gutter_span() -> Span<'static> {
87    Span::styled(DELEGATED_GUTTER, Style::default().fg(Color::Indexed(141)))
88}
89
90/// Render one delegation frame or body entry (#7940).
91///
92/// Why: a delegated sub-agent's work has to read as a block, not as more
93/// top-level chat — the whole point of issue #7940 is that an operator
94/// watching `tcode tui` can see the PM hand work to an engineer. A frame
95/// line ([`ChatRole::Delegation`], the `▶ …` header and `└ …` footer) sits
96/// flush left in the delegation accent; every body line
97/// ([`ChatRole::Delegated`] — the sub-agent's streamed words and its tool
98/// notices) is prefixed with [`DELEGATED_GUTTER`] so it is visibly inside
99/// the frame.
100/// What: markdown-aware rendering (fenced code, tables) is deliberately NOT
101/// applied here — the fancy panel is a later slice of requirement R9; this
102/// is the minimal readable form. Multi-line text is split so the gutter
103/// reaches every line, not just the first.
104/// Test: `tests::build_chat_lines_frames_a_delegation_block`,
105/// `tests::build_chat_lines_gutters_every_delegated_line`.
106fn delegation_lines(entry: &crate::app::ChatLine) -> Vec<Line<'static>> {
107    let frame = entry.role == ChatRole::Delegation;
108    let style = if frame {
109        Style::default()
110            .fg(Color::Indexed(141))
111            .add_modifier(Modifier::BOLD)
112    } else {
113        Style::default().fg(Color::Indexed(146))
114    };
115    entry
116        .text
117        .lines()
118        .map(|raw| {
119            if frame {
120                Line::from(Span::styled(raw.to_string(), style))
121            } else {
122                Line::from(vec![
123                    delegated_gutter_span(),
124                    Span::styled(raw.to_string(), style),
125                ])
126            }
127        })
128        .collect()
129}
130
131/// Build the rendered `Vec<Line>` for the chat pane.
132///
133/// Why: extracted so layout code can compute the chat content height
134/// *before* the vertical layout split, letting the input row follow content
135/// height instead of being pinned to the screen bottom.
136/// What: replicates the banner + chat entry line-building logic; returns the
137/// post-collapse, pre-pad lines. Width-dependent rendering (banner wrapping,
138/// markdown table column sizing) uses `terminal_width`.
139/// Test: `tests::build_chat_lines_renders_user_and_assistant_entries`,
140/// `tests::build_chat_lines_renders_fenced_code_block`,
141/// `tests::build_chat_lines_renders_markdown_table`,
142/// `tests::build_chat_lines_prepends_banner_when_shown`.
143pub fn build_chat_lines(app: &ReplApp, terminal_width: usize) -> Vec<Line<'static>> {
144    let mut lines: Vec<Line<'static>> = Vec::new();
145
146    if app.show_banner {
147        lines.extend(banner_lines(app, terminal_width));
148        lines.push(Line::from(""));
149    }
150
151    for (idx, entry) in app.chat.iter().enumerate() {
152        if idx > 0 {
153            lines.push(Line::from(""));
154        }
155        // #4596: a tool call renders as a card; its role only says whether
156        // the card sits inside a delegation block.
157        if let Some(card) = &entry.tool {
158            lines.extend(tool_card_lines(card, entry.role == ChatRole::Delegated));
159            continue;
160        }
161        match entry.role {
162            ChatRole::User => {
163                let mut iter = entry.text.lines();
164                if let Some(first) = iter.next() {
165                    lines.push(Line::from(vec![
166                        Span::styled("❯", Style::default().fg(Color::Green)),
167                        Span::raw(" "),
168                        Span::raw(first.to_string()),
169                    ]));
170                }
171                for cont in iter {
172                    lines.push(Line::from(format!("  {}", cont)));
173                }
174            }
175            ChatRole::Assistant | ChatRole::Error => {
176                let body_color = if entry.role == ChatRole::Error {
177                    Some(Color::Red)
178                } else {
179                    None
180                };
181                let body_lines: Vec<&str> = entry.text.lines().collect();
182                let mut i = 0usize;
183                let mut emitted_first = false;
184                while i < body_lines.len() {
185                    if let Some(lang) = code_fence_lang(body_lines[i]) {
186                        let is_shell = is_executable_shell_lang(&lang);
187                        if !emitted_first {
188                            lines.push(Line::from(leader_spans(app, body_color)));
189                            emitted_first = true;
190                        }
191                        let header_label = if lang.is_empty() {
192                            "code".to_string()
193                        } else {
194                            lang.clone()
195                        };
196                        if is_shell {
197                            lines.push(Line::from(vec![
198                                Span::raw("   "),
199                                Span::styled(
200                                    format!("▶ {}", header_label),
201                                    Style::default()
202                                        .fg(Color::LightGreen)
203                                        .add_modifier(Modifier::BOLD),
204                                ),
205                            ]));
206                        } else {
207                            lines.push(Line::from(vec![
208                                Span::raw("   "),
209                                Span::styled(
210                                    format!("⬡ {}", header_label),
211                                    Style::default().fg(Color::Indexed(75)),
212                                ),
213                            ]));
214                        }
215                        let mut j = i + 1;
216                        let body_style = Style::default().fg(Color::Indexed(244));
217                        while j < body_lines.len() {
218                            if code_fence_lang(body_lines[j]).is_some() {
219                                break;
220                            }
221                            lines.push(Line::from(Span::styled(
222                                format!("   {}", body_lines[j]),
223                                body_style,
224                            )));
225                            j += 1;
226                        }
227                        let j_is_closer = j < body_lines.len()
228                            && code_fence_lang(body_lines[j]).is_some_and(|lang| lang.is_empty());
229                        if j_is_closer {
230                            lines.push(Line::from(vec![
231                                Span::raw("   "),
232                                Span::styled(
233                                    "─".repeat(20),
234                                    Style::default().fg(Color::Indexed(240)),
235                                ),
236                            ]));
237                            i = j + 1;
238                        } else {
239                            i = j;
240                        }
241                        continue;
242                    }
243
244                    let is_table_start = i + 1 < body_lines.len()
245                        && is_md_table_row(body_lines[i])
246                        && is_md_table_separator(body_lines[i + 1]);
247
248                    if is_table_start {
249                        let header = parse_md_table_cells(body_lines[i]);
250                        let mut j = i + 2;
251                        let mut body_rows: Vec<Vec<String>> = Vec::new();
252                        while j < body_lines.len() && is_md_table_row(body_lines[j]) {
253                            body_rows.push(parse_md_table_cells(body_lines[j]));
254                            j += 1;
255                        }
256                        let indent = "   ";
257                        let avail = terminal_width.saturating_sub(1);
258                        let table_lines =
259                            render_markdown_table(&header, &body_rows, avail, indent, body_color);
260                        if !emitted_first {
261                            lines.push(Line::from(leader_spans(app, body_color)));
262                            emitted_first = true;
263                        }
264                        for tl in table_lines {
265                            lines.push(tl);
266                        }
267                        i = j;
268                        continue;
269                    }
270
271                    let raw = body_lines[i];
272                    if !emitted_first {
273                        let mut spans = leader_spans(app, body_color);
274                        spans.push(match body_color {
275                            Some(c) => Span::styled(raw.to_string(), Style::default().fg(c)),
276                            None => Span::raw(raw.to_string()),
277                        });
278                        lines.push(Line::from(spans));
279                        emitted_first = true;
280                    } else {
281                        let line = if raw.trim().is_empty() {
282                            Line::from("")
283                        } else {
284                            match body_color {
285                                Some(c) => Line::from(Span::styled(
286                                    format!("   {}", raw),
287                                    Style::default().fg(c),
288                                )),
289                                None => Line::from(Span::raw(format!("   {}", raw))),
290                            }
291                        };
292                        lines.push(line);
293                    }
294                    i += 1;
295                }
296            }
297            ChatRole::Status => {
298                lines.push(Line::from(vec![
299                    Span::styled(app.status_prefix.clone(), Style::default().fg(Color::Green)),
300                    Span::raw(entry.text.clone()),
301                ]));
302            }
303            // #7940: the two roles that frame and fill a delegated
304            // sub-agent's block — see `delegation_lines`.
305            ChatRole::Delegation | ChatRole::Delegated => {
306                lines.extend(delegation_lines(entry));
307            }
308        }
309    }
310
311    let mut lines = collapse_blank_lines(lines);
312
313    if !app.chat.is_empty() {
314        lines.push(Line::from(""));
315    }
316
317    lines
318}
319
320/// Terminal ROWS `lines` occupy once [`draw_chat`]'s `Wrap { trim: false }`
321/// has re-flowed them.
322///
323/// Why (#8205): the pane's height came from counting logical lines while the
324/// pane renders through a WRAPPING `Paragraph`, so every line wider than the
325/// pane was under-reserved by a row and ratatui dropped its continuation past
326/// the pane's bottom edge. That is how the connect line lost `home <path>` at
327/// 80 columns — nothing clipped the string, the pane was simply one row too
328/// short to show the rest of it. `Paragraph::scroll` also advances by wrapped
329/// rows, so the same count is what keeps the bottom-pinning and the published
330/// scroll cap honest.
331/// What: asks ratatui for the answer. `Paragraph::line_count` measures through
332/// the very `WordWrapper` the renderer then wraps with, so cell width (a CJK
333/// glyph costs two columns), runs of interior whitespace (the banner's
334/// `/{:<12}` command column), and a preserved leading indent (the assistant
335/// continuation's three spaces, [`DELEGATED_GUTTER`]) are all counted the way
336/// they are drawn. A re-implementation has to re-derive each of those and got
337/// all three wrong. `width == 0` answers one row per line rather than the zero
338/// `line_count` reports, so a degenerate width cannot collapse the pane.
339/// Test: `tests::rendered_row_count_counts_the_rows_a_long_line_needs`, and
340/// `wrapped_row_geometry::row_count_agrees_with_a_real_render`, which checks
341/// every one of those shapes against a `TestBackend` render rather than
342/// against a hand-computed number.
343fn rendered_row_count(lines: &[Line<'_>], width: usize) -> usize {
344    if width == 0 {
345        return lines.len();
346    }
347    let width = u16::try_from(width).unwrap_or(u16::MAX);
348    Paragraph::new(lines.to_vec())
349        .wrap(Wrap { trim: false })
350        .line_count(width)
351}
352
353/// Count chat content ROWS for layout sizing.
354///
355/// Why: [`crate::layout::draw`] needs to know the rendered content height
356/// *before* the vertical layout split so the chat pane can use
357/// `Constraint::Length(h)` instead of `Constraint::Min` — `Min` expands to
358/// fill all available space, pinning the input row to the screen bottom even
359/// when the conversation is short.
360/// What: measures [`build_chat_lines`]'s post-collapse, pre-pad lines with
361/// [`rendered_row_count`], so a line the pane will wrap is reserved every row
362/// it actually needs (#8205).
363/// Test: `tests::chat_line_count_is_zero_for_empty_chat_without_banner`,
364/// `tests::chat_line_count_counts_wrapped_rows_not_logical_lines`.
365pub fn chat_line_count(app: &ReplApp, terminal_width: usize) -> usize {
366    rendered_row_count(&build_chat_lines(app, terminal_width), terminal_width)
367}
368
369/// Render the chat pane into `area`, bottom-pinned when content fits.
370///
371/// Why: mirrors an iMessage/Slack-style chat feel — short conversations sit
372/// flush at the bottom of the pane rather than floating at the top with a
373/// sea of blank space below.
374/// What: pads with blank lines above the content when it fits; otherwise
375/// scrolls so the newest line stays in view (clamped by
376/// `app.scroll_offset`). Publishes the computed max scroll offset to
377/// `app.last_max_scroll` so `ReplApp::scroll` can clamp future deltas. Every
378/// one of those numbers counts WRAPPED rows ([`rendered_row_count`]), matching
379/// what the `Paragraph` renders and what its `scroll` advances by (#8205).
380/// Test: exercised via `draw` in [`crate::layout`], including
381/// `crate::layout::tests::draw_keeps_the_connect_line_home_segment_at_80_columns`;
382/// the pure geometry (padding decision, max-offset computation) is covered
383/// indirectly through [`build_chat_lines`]'s tests plus [`ReplApp::scroll`]'s
384/// own tests in `crate::app::reduce`.
385pub fn draw_chat(f: &mut ratatui::Frame, app: &ReplApp, area: Rect) {
386    let lines = build_chat_lines(app, area.width as usize);
387
388    let visible = area.height as usize;
389    // #8205: rows, not logical lines — `Paragraph` below wraps, and both the
390    // padding decision and the scroll offset are measured in rendered rows.
391    let total = rendered_row_count(&lines, area.width as usize);
392
393    let mut pad = 0usize;
394    let final_lines = if !app.chat.is_empty() && total < visible {
395        pad = visible - total;
396        let mut padded = Vec::with_capacity(pad + lines.len());
397        for _ in 0..pad {
398            padded.push(Line::from(""));
399        }
400        padded.extend(lines);
401        padded
402    } else {
403        lines
404    };
405
406    let final_total = total + pad;
407    let max_offset = final_total.saturating_sub(visible);
408    app.last_max_scroll
409        .store(max_offset, std::sync::atomic::Ordering::Relaxed);
410    let effective_offset = max_offset.saturating_sub(app.scroll_offset);
411
412    let paragraph = Paragraph::new(final_lines)
413        .wrap(Wrap { trim: false })
414        .scroll((effective_offset as u16, 0));
415    f.render_widget(paragraph, area);
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::app::ReplApp;
422
423    fn line_text(line: &Line<'_>) -> String {
424        line.spans.iter().map(|s| s.content.as_ref()).collect()
425    }
426
427    fn all_text(lines: &[Line<'_>]) -> String {
428        lines.iter().map(line_text).collect::<Vec<_>>().join("\n")
429    }
430
431    fn app_without_banner() -> ReplApp {
432        let mut app = ReplApp::new("demo", "bob");
433        app.show_banner = false;
434        app
435    }
436
437    #[test]
438    fn chat_line_count_is_zero_for_empty_chat_without_banner() {
439        let app = app_without_banner();
440        assert_eq!(chat_line_count(&app, 80), 0);
441    }
442
443    /// #8205: a line the pane will wrap costs every row it wraps onto. A
444    /// blank line and a fitting line each cost exactly one.
445    #[test]
446    fn rendered_row_count_counts_the_rows_a_long_line_needs() {
447        let rows = |line: Line<'static>, w: usize| rendered_row_count(&[line], w);
448        assert_eq!(rows(Line::from(""), 80), 1);
449        assert_eq!(rows(Line::from("short"), 80), 1);
450        // 12 words of 9 columns: 8 fit the first row, the rest wrap.
451        assert_eq!(rows(Line::from(["123456789"; 12].join(" ")), 80), 2);
452        // One unbreakable token three panes wide spans three rows.
453        assert_eq!(rows(Line::from("x".repeat(30)), 10), 3);
454        // A zero-width pane must answer a row per line, not zero — the count
455        // sizes a pane, and a zero would collapse it.
456        assert_eq!(rendered_row_count(&[Line::from("anything")], 0), 1);
457        assert_eq!(rendered_row_count(&[], 80), 0);
458    }
459
460    /// #8205 regression: the height query must report ROWS. A status line
461    /// wider than the pane used to report 1, leaving the pane a row short and
462    /// the continuation clipped away by ratatui.
463    #[test]
464    fn chat_line_count_counts_wrapped_rows_not_logical_lines() {
465        let mut app = app_without_banner();
466        app.push_status(
467            "connected to tcode daemon at /Users/dev0/Library/Application Support/tcode/tcode.sock \
468             — home /private/tmp/q8230/repoA, solo agent (no delegation)",
469        );
470        let logical = build_chat_lines(&app, 80).len();
471        let rows = chat_line_count(&app, 80);
472        assert!(
473            rows > logical,
474            "a status line this wide must cost more rows ({rows}) than logical lines ({logical})"
475        );
476        // At 160 columns the same line fits, so the two counts agree — the
477        // extra rows are width-driven, not a constant fudge.
478        assert_eq!(
479            chat_line_count(&app, 160),
480            build_chat_lines(&app, 160).len(),
481            "a line that fits costs exactly one row"
482        );
483    }
484
485    #[test]
486    fn build_chat_lines_renders_user_and_assistant_entries() {
487        let mut app = app_without_banner();
488        app.push_user("hello");
489        app.push_assistant("hi there", false);
490        let text = all_text(&build_chat_lines(&app, 80));
491        assert!(text.contains("❯ hello"));
492        assert!(text.contains("demo"));
493        assert!(text.contains("hi there"));
494    }
495
496    #[test]
497    fn build_chat_lines_renders_fenced_code_block() {
498        let mut app = app_without_banner();
499        app.push_assistant("Run:\n```bash\necho hi\n```\nDone.", false);
500        let text = all_text(&build_chat_lines(&app, 80));
501        assert!(
502            text.contains("▶ bash"),
503            "missing shell fence header: {text}"
504        );
505        assert!(text.contains("echo hi"));
506    }
507
508    #[test]
509    fn build_chat_lines_renders_markdown_table() {
510        let mut app = app_without_banner();
511        app.push_assistant("| a | b |\n|---|---|\n| 1 | 2 |", false);
512        let text = all_text(&build_chat_lines(&app, 80));
513        assert!(text.contains('┌'), "missing table border: {text}");
514        assert!(text.contains('1'));
515        assert!(text.contains('2'));
516    }
517
518    #[test]
519    fn build_chat_lines_prepends_banner_when_shown() {
520        let app = ReplApp::new("demo", "bob");
521        assert!(app.show_banner);
522        let lines = build_chat_lines(&app, 80);
523        assert!(!lines.is_empty(), "banner must render even with no chat");
524    }
525
526    #[test]
527    fn build_chat_lines_error_role_renders_red_body() {
528        let mut app = app_without_banner();
529        app.push_assistant("boom", true);
530        // The error body carries a distinct color from a normal response —
531        // spot-check via the raw text still round-tripping (styling itself
532        // is asserted indirectly by `ReplApp::push_assistant`'s role test).
533        let text = all_text(&build_chat_lines(&app, 80));
534        assert!(text.contains("boom"));
535    }
536
537    #[test]
538    fn build_chat_lines_status_role_uses_configured_prefix() {
539        let mut app = app_without_banner();
540        app.status_prefix = "[custom] ".to_string();
541        app.push_status("hello");
542        let text = all_text(&build_chat_lines(&app, 80));
543        assert!(text.contains("[custom] hello"));
544    }
545
546    #[test]
547    fn collapse_blank_lines_drops_consecutive_empty_lines() {
548        let input: Vec<Line<'static>> = vec![
549            Line::from("a"),
550            Line::from(""),
551            Line::from(""),
552            Line::from("b"),
553            Line::from("   "),
554            Line::from(""),
555            Line::from("c"),
556        ];
557        let out = collapse_blank_lines(input);
558        assert_eq!(out.len(), 5);
559        assert_eq!(out[0].spans[0].content, "a");
560        assert!(out[1].spans.iter().all(|s| s.content.trim().is_empty()));
561        assert_eq!(out[2].spans[0].content, "b");
562        assert!(out[3].spans.iter().all(|s| s.content.trim().is_empty()));
563        assert_eq!(out[4].spans[0].content, "c");
564    }
565
566    /// #7940: a delegation reads as a block — a flush-left header, gutter-
567    /// prefixed body, and a flush-left footer naming the outcome.
568    #[test]
569    fn build_chat_lines_frames_a_delegation_block() {
570        let mut app = app_without_banner();
571        app.chat.push(crate::app::ChatLine {
572            role: ChatRole::Delegation,
573            text: "▶ engineer — add the renderer".into(),
574            tool: None,
575        });
576        app.chat.push(crate::app::ChatLine {
577            role: ChatRole::Delegated,
578            text: "reading the spec".into(),
579            tool: None,
580        });
581        app.chat.push(crate::app::ChatLine {
582            role: ChatRole::Delegation,
583            text: "└ engineer — success".into(),
584            tool: None,
585        });
586        let lines = build_chat_lines(&app, 80);
587        let text = all_text(&lines);
588        assert!(text.contains("▶ engineer — add the renderer"), "{text}");
589        assert!(
590            text.contains(&format!("{DELEGATED_GUTTER}reading the spec")),
591            "{text}"
592        );
593        assert!(text.contains("└ engineer — success"), "{text}");
594    }
595
596    /// The gutter has to reach EVERY line of a multi-line sub-agent message,
597    /// not just the first — otherwise a wrapped answer falls out of the
598    /// block after one line.
599    #[test]
600    fn build_chat_lines_gutters_every_delegated_line() {
601        let mut app = app_without_banner();
602        app.chat.push(crate::app::ChatLine {
603            role: ChatRole::Delegated,
604            text: "one\ntwo\nthree".into(),
605            tool: None,
606        });
607        let lines = build_chat_lines(&app, 80);
608        for expected in ["one", "two", "three"] {
609            assert!(
610                lines
611                    .iter()
612                    .any(|l| line_text(l) == format!("{DELEGATED_GUTTER}{expected}")),
613                "missing gutter on {expected}"
614            );
615        }
616    }
617}