Skip to main content

tea_cli/tui/
render.rs

1use std::collections::BTreeMap;
2use std::path::Path;
3
4use ratatui::buffer::Buffer;
5use ratatui::layout::Rect;
6use ratatui::style::Style;
7use tea_protocol::{ModelId, ToolCallId};
8use unicode_width::UnicodeWidthStr as _;
9
10use super::attachment::{format_byte_count, format_compact_byte_count};
11use super::bottom_pane::BottomPane;
12#[cfg(test)]
13use super::cells::MAX_VISIBLE_PLAN_BODY_ROWS;
14use super::cells::{CellBlock, CellContext, CellHost, CellList};
15use super::components::{
16    Component, Element, RenderContext, Text, truncate_cells, truncate_cells_with_ellipsis,
17};
18use super::hyperlink::HyperlinkBuffer;
19use super::layout::{
20    CursorState, Renderable, VerticalLayout, draw_lines, draw_lines_with_hyperlinks,
21};
22use super::overlay::Overlay;
23use super::presentation::{CellContent, CellId, CellNode, Presentation};
24#[cfg(test)]
25use super::presentation::{
26    LifecycleStatus, OutputFormat, PlanStep, PlanStepStatus, TimelineDetail, TimelineDetailKind,
27    TimelineSource,
28};
29use super::render_output::RenderedLine;
30#[cfg(test)]
31use super::render_output::RenderedSpan;
32use super::state::{ApprovalChoice, TuiState};
33use super::status::StatusIndicator;
34use super::theme::Theme;
35use super::transcript::Transcript;
36
37const MAX_CELL_RENDER_CACHE_ENTRIES: usize = 256;
38const MAX_APPROVAL_ARGUMENT_CELLS: usize = 480;
39const COMPOSER_VERTICAL_PADDING_ROWS: usize = 1;
40const COMPOSER_PROMPT_PREFIX: &str = "› ";
41const CONTENT_HORIZONTAL_MARGIN: u16 = 1;
42const CONTENT_VERTICAL_MARGIN: u16 = 1;
43const MIN_INLINE_VIEWPORT_HEIGHT: u16 = 8;
44const MAX_COMPOSER_EDITOR_ROWS: usize = 6;
45const MAX_BOTTOM_MODAL_OPTIONS: usize = 7;
46
47#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
48struct CellCacheKey {
49    id: CellId,
50    width: u16,
51    theme_generation: u64,
52    stylesheet_generation: u64,
53}
54
55impl CellCacheKey {
56    fn from_cell(cell: &CellNode, width: u16, theme: &Theme, stylesheet_generation: u64) -> Self {
57        Self {
58            id: cell.id(),
59            width,
60            theme_generation: theme.generation,
61            stylesheet_generation,
62        }
63    }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
67struct CellCacheEntry {
68    content: CellContent,
69    tool_call_id: Option<ToolCallId>,
70    block: CellBlock,
71}
72
73#[derive(Debug, Default)]
74struct CellRenderCache {
75    entries: BTreeMap<CellCacheKey, CellCacheEntry>,
76    #[cfg(test)]
77    hits: usize,
78    #[cfg(test)]
79    misses: usize,
80}
81
82impl CellRenderCache {
83    fn get_or_render(
84        &mut self,
85        key: CellCacheKey,
86        content: &CellContent,
87        tool_call_id: Option<ToolCallId>,
88        render: impl FnOnce() -> CellBlock,
89    ) -> CellBlock {
90        if let Some(entry) = self.entries.get(&key)
91            && entry.content == *content
92            && entry.tool_call_id == tool_call_id
93        {
94            #[cfg(test)]
95            {
96                self.hits = self.hits.saturating_add(1);
97            }
98            return entry.block.clone();
99        }
100        #[cfg(test)]
101        {
102            self.misses = self.misses.saturating_add(1);
103        }
104        let block = render();
105        if !self.entries.contains_key(&key)
106            && self.entries.len() >= MAX_CELL_RENDER_CACHE_ENTRIES
107            && let Some(first) = self.entries.keys().next().cloned()
108        {
109            self.entries.remove(&first);
110        }
111        self.entries.insert(
112            key,
113            CellCacheEntry {
114                content: content.clone(),
115                tool_call_id,
116                block: block.clone(),
117            },
118        );
119        block
120    }
121
122    fn clear(&mut self) {
123        self.entries.clear();
124        #[cfg(test)]
125        {
126            self.hits = 0;
127            self.misses = 0;
128        }
129    }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Default)]
133struct RenderSections {
134    timeline: Vec<RenderedLine>,
135    modal: Vec<RenderedLine>,
136}
137
138impl RenderSections {
139    fn all_lines(&self, composer: Vec<RenderedLine>) -> Vec<RenderedLine> {
140        let mut lines = self.timeline.clone();
141        lines.extend(self.modal.clone());
142        lines.extend(composer);
143        lines
144    }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
148struct ComposerFrame {
149    lines: Vec<RenderedLine>,
150    cursor: Option<CursorState>,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
154struct BottomPaneLines {
155    lines: Vec<RenderedLine>,
156    cursor: Option<CursorState>,
157}
158
159fn bottom_pane_lines(
160    status: Option<&StatusIndicator>,
161    modal: &[RenderedLine],
162    composer: ComposerFrame,
163) -> BottomPaneLines {
164    let status_lines = status.map_or(&[][..], StatusIndicator::lines);
165    let modal_len = modal.len();
166    let mut lines = Vec::with_capacity(
167        status_lines
168            .len()
169            .saturating_add(modal_len)
170            .saturating_add(composer.lines.len()),
171    );
172    lines.extend_from_slice(modal);
173    lines.extend_from_slice(status_lines);
174    let cursor = composer.cursor.map(|mut cursor| {
175        cursor.y = cursor.y.saturating_add(
176            u16::try_from(status_lines.len().saturating_add(modal_len)).unwrap_or(u16::MAX),
177        );
178        cursor
179    });
180    lines.extend(composer.lines);
181    BottomPaneLines { lines, cursor }
182}
183
184fn axis_margin(length: u16, preferred: u16) -> u16 {
185    preferred.min(length.saturating_sub(1) / 2)
186}
187
188fn content_area(area: Rect) -> Rect {
189    let vertical = if area.height >= MIN_INLINE_VIEWPORT_HEIGHT {
190        axis_margin(area.height, CONTENT_VERTICAL_MARGIN)
191    } else {
192        0
193    };
194    Rect::new(
195        area.x,
196        area.y.saturating_add(vertical),
197        area.width,
198        area.height.saturating_sub(vertical.saturating_mul(2)),
199    )
200}
201
202fn content_width(width: u16) -> u16 {
203    let horizontal = axis_margin(width, CONTENT_HORIZONTAL_MARGIN);
204    width.saturating_sub(horizontal.saturating_mul(2)).max(1)
205}
206
207fn modal_surface_in_viewport(
208    state: &TuiState,
209    screen_width: usize,
210    theme: &Theme,
211) -> Vec<RenderedLine> {
212    let screen_width = u16::try_from(screen_width).unwrap_or(u16::MAX).max(1);
213    let margin = axis_margin(screen_width, CONTENT_HORIZONTAL_MARGIN);
214    modal_surface(state, usize::from(content_width(screen_width)), theme)
215        .into_iter()
216        .map(|line| line.with_left_columns(usize::from(margin)))
217        .collect()
218}
219
220/// Deterministic terminal renderer with a bounded width/theme-aware cell cache.
221#[derive(Debug, Default)]
222pub struct Renderer {
223    cell_host: CellHost,
224    cache: CellRenderCache,
225}
226
227impl Renderer {
228    /// Creates an empty renderer cache.
229    #[must_use]
230    pub fn new() -> Self {
231        Self::default()
232    }
233
234    #[cfg(test)]
235    fn with_cell_host(mut self, cell_host: CellHost) -> Self {
236        self.cell_host = cell_host;
237        self
238    }
239
240    /// Projects state into width-safe rows without mutating application state.
241    #[must_use]
242    pub fn lines(&mut self, state: &TuiState, width: u16, theme: &Theme) -> Vec<RenderedLine> {
243        let width = width.max(1);
244        let sections = self.sections(state, width, theme);
245        let composer = composer_frame(
246            state,
247            usize::from(width),
248            usize::MAX,
249            state.editor.len(),
250            theme,
251        );
252        let status = StatusIndicator::from_state(state, usize::from(width), theme);
253        let bottom_pane = bottom_pane_lines(status.as_ref(), &sections.modal, composer);
254        sections.all_lines(bottom_pane.lines)
255    }
256
257    fn sections(&mut self, state: &TuiState, width: u16, theme: &Theme) -> RenderSections {
258        let width = width.max(1);
259        self.render_sections(state, usize::from(width), theme)
260    }
261
262    /// Renders one complete clipped frame into a Ratatui buffer with the cursor at the editor end.
263    pub fn render(&mut self, state: &TuiState, area: Rect, buffer: &mut Buffer, theme: &Theme) {
264        self.render_with_cursor(state, area, buffer, theme, state.editor.len());
265    }
266
267    /// Renders one complete clipped frame into a Ratatui buffer.
268    pub fn render_with_cursor(
269        &mut self,
270        state: &TuiState,
271        area: Rect,
272        buffer: &mut Buffer,
273        theme: &Theme,
274        cursor_byte: usize,
275    ) {
276        self.render_with_cursor_and_hyperlinks(state, area, buffer, None, theme, cursor_byte);
277    }
278
279    pub(crate) fn render_with_cursor_and_hyperlinks(
280        &mut self,
281        state: &TuiState,
282        area: Rect,
283        buffer: &mut Buffer,
284        hyperlinks: Option<&mut HyperlinkBuffer>,
285        theme: &Theme,
286        cursor_byte: usize,
287    ) {
288        if area.width == 0 || area.height == 0 {
289            return;
290        }
291        let cursor_byte =
292            if cursor_byte <= state.editor.len() && state.editor.is_char_boundary(cursor_byte) {
293                cursor_byte
294            } else {
295                state.editor.len()
296            };
297        let area = content_area(area);
298        let width = usize::from(area.width);
299        let presentation = Presentation::from_state(state);
300        let timeline = self.render_timeline(&presentation, width, theme);
301        let modal = modal_surface_in_viewport(state, width, theme);
302        let composer = composer_frame(state, width, usize::from(area.height), cursor_byte, theme);
303        let status = StatusIndicator::from_state(state, width, theme);
304        let pane_lines = bottom_pane_lines(status.as_ref(), &modal, composer);
305        let bottom_pane = BottomPane::new(&pane_lines.lines, pane_lines.cursor);
306        let layout = VerticalLayout::with_bottom_pane(area, bottom_pane.desired_height(area.width));
307        let transcript = Transcript::new(&timeline, state.transcript_viewport(), theme);
308        if let Some(hyperlinks) = hyperlinks {
309            transcript.render_with_hyperlinks(layout.transcript, buffer, hyperlinks);
310        } else {
311            transcript.render(layout.transcript, buffer);
312        }
313        bottom_pane.render(layout.bottom_pane, buffer);
314    }
315
316    /// Returns the dynamic Codex-style inline viewport height.
317    pub(crate) fn inline_height(
318        &mut self,
319        state: &TuiState,
320        width: u16,
321        max_height: u16,
322        theme: &Theme,
323        cursor_byte: usize,
324    ) -> u16 {
325        let max_height = max_height.max(1);
326        let outer_area = Rect::new(0, 0, width.max(1), max_height);
327        let area = content_area(outer_area);
328        let width = usize::from(area.width);
329        let presentation = Presentation::from_state(state);
330        let timeline = self.render_live_timeline(&presentation, width, theme);
331        let modal = modal_surface_in_viewport(state, width, theme);
332        let composer = composer_frame(state, width, usize::from(area.height), cursor_byte, theme);
333        let status = StatusIndicator::from_state(state, width, theme);
334        let pane_lines = bottom_pane_lines(status.as_ref(), &modal, composer);
335        let bottom_pane = BottomPane::new(&pane_lines.lines, pane_lines.cursor);
336        let bottom_height = bottom_pane.desired_height(u16::try_from(width).unwrap_or(u16::MAX));
337        let timeline_height = u16::try_from(timeline.len()).unwrap_or(u16::MAX);
338        let margins = max_height.saturating_sub(area.height);
339        timeline_height
340            .saturating_add(bottom_height)
341            .saturating_add(margins)
342            .clamp(MIN_INLINE_VIEWPORT_HEIGHT.min(max_height), max_height)
343    }
344
345    /// Renders only active content and the bottom pane into the inline viewport.
346    pub(crate) fn render_inline_with_cursor(
347        &mut self,
348        state: &TuiState,
349        area: Rect,
350        buffer: &mut Buffer,
351        hyperlinks: Option<&mut HyperlinkBuffer>,
352        theme: &Theme,
353        cursor_byte: usize,
354    ) {
355        if area.width == 0 || area.height == 0 {
356            return;
357        }
358        let area = content_area(area);
359        let width = usize::from(area.width);
360        let presentation = Presentation::from_state(state);
361        let timeline = self.render_live_timeline(&presentation, width, theme);
362        let modal = modal_surface_in_viewport(state, width, theme);
363        let composer = composer_frame(state, width, usize::from(area.height), cursor_byte, theme);
364        let status = StatusIndicator::from_state(state, width, theme);
365        let pane_lines = bottom_pane_lines(status.as_ref(), &modal, composer);
366        let bottom_pane = BottomPane::new(&pane_lines.lines, pane_lines.cursor);
367        let layout = VerticalLayout::with_bottom_pane(area, bottom_pane.desired_height(area.width));
368        let visible_start = timeline
369            .len()
370            .saturating_sub(usize::from(layout.transcript.height));
371        if let Some(hyperlinks) = hyperlinks {
372            draw_lines_with_hyperlinks(
373                &timeline[visible_start..],
374                layout.transcript,
375                buffer,
376                hyperlinks,
377            );
378        } else {
379            draw_lines(&timeline[visible_start..], layout.transcript, buffer);
380        }
381        bottom_pane.render(layout.bottom_pane, buffer);
382    }
383
384    /// Renders finalized source cells into pre-wrapped terminal rows.
385    pub(crate) fn history_lines(
386        &mut self,
387        cells: &[CellNode],
388        width: u16,
389        theme: &Theme,
390    ) -> Vec<RenderedLine> {
391        self.render_cell_nodes(cells.iter(), width, theme)
392    }
393
394    fn render_cell_nodes<'a>(
395        &mut self,
396        cells: impl IntoIterator<Item = &'a CellNode>,
397        width: u16,
398        theme: &Theme,
399    ) -> Vec<RenderedLine> {
400        let width = width.max(1);
401        let context = CellContext { theme };
402        let stylesheet_generation = self.cell_host.stylesheet_generation();
403        let host = &self.cell_host;
404        let cache = &mut self.cache;
405        let blocks = cells
406            .into_iter()
407            .map(|cell| {
408                let key = CellCacheKey::from_cell(cell, width, theme, stylesheet_generation);
409                cache.get_or_render(key, cell.content(), cell.tool_call_id(), || {
410                    host.render(cell.content().spec(), &context, width)
411                })
412            })
413            .collect();
414        CellList::new(blocks).render().into_lines()
415    }
416
417    /// Returns the visible display-cell cursor position for the editor.
418    #[must_use]
419    pub fn cursor_position(
420        &mut self,
421        state: &TuiState,
422        width: u16,
423        height: u16,
424        cursor_byte: usize,
425    ) -> Option<(u16, u16)> {
426        let area = content_area(Rect::new(0, 0, width.max(1), height.max(1)));
427        let width = usize::from(area.width);
428        let height = usize::from(area.height);
429        if cursor_byte > state.editor.len() || !state.editor.is_char_boundary(cursor_byte) {
430            return None;
431        }
432        let theme = Theme::default();
433        let sections = self.sections(state, u16::try_from(width).unwrap_or(u16::MAX), &theme);
434        let composer = composer_frame(state, width, height, cursor_byte, &theme);
435        let status = StatusIndicator::from_state(state, width, &theme);
436        let pane_lines = bottom_pane_lines(status.as_ref(), &sections.modal, composer);
437        let bottom_pane = BottomPane::new(&pane_lines.lines, pane_lines.cursor);
438        let layout = VerticalLayout::with_bottom_pane(
439            area,
440            bottom_pane.desired_height(u16::try_from(width).unwrap_or(u16::MAX)),
441        );
442        bottom_pane
443            .cursor(layout.bottom_pane)
444            .map(|cursor| (cursor.x, cursor.y))
445    }
446
447    /// Removes all cached wrapped rows, for example after terminal reprobe.
448    pub fn invalidate(&mut self) {
449        self.cache.clear();
450    }
451
452    #[allow(clippy::too_many_lines)] // Keep semantic regions visibly ordered.
453    fn render_sections(&mut self, state: &TuiState, width: usize, theme: &Theme) -> RenderSections {
454        let presentation = Presentation::from_state(state);
455        RenderSections {
456            timeline: self.render_timeline(&presentation, width, theme),
457            modal: modal_surface_in_viewport(state, width, theme),
458        }
459    }
460
461    fn render_timeline(
462        &mut self,
463        presentation: &Presentation,
464        width: usize,
465        theme: &Theme,
466    ) -> Vec<RenderedLine> {
467        let cells = presentation
468            .history()
469            .iter()
470            .chain(
471                presentation
472                    .active()
473                    .iter()
474                    .filter(|cell| cell.content().is_live_timeline_visible()),
475            )
476            .chain(presentation.notifications().iter());
477        self.render_cell_nodes(cells, u16::try_from(width).unwrap_or(u16::MAX), theme)
478    }
479
480    fn render_live_timeline(
481        &mut self,
482        presentation: &Presentation,
483        width: usize,
484        theme: &Theme,
485    ) -> Vec<RenderedLine> {
486        let cells = presentation
487            .active()
488            .iter()
489            .filter(|cell| cell.content().is_live_timeline_visible())
490            .chain(presentation.notifications().iter());
491        self.render_cell_nodes(cells, u16::try_from(width).unwrap_or(u16::MAX), theme)
492    }
493}
494
495fn modal_surface(state: &TuiState, width: usize, theme: &Theme) -> Vec<RenderedLine> {
496    if let Some(approval) = approval_panel(state, width, theme) {
497        return approval;
498    }
499    let Some(overlay) = &state.overlay else {
500        return Vec::new();
501    };
502    match overlay {
503        Overlay::Selector(selector) => {
504            let mut rows = Vec::new();
505            let query = selector.query();
506            let heading = if query.is_empty() {
507                selector.title().to_owned()
508            } else {
509                format!("{} · {query}", selector.title())
510            };
511            push_wrapped(&mut rows, "select", &heading, width, theme.footer, theme);
512            let items = selector.visible_items();
513            let selected = selector
514                .selected_label()
515                .and_then(|label| items.iter().position(|item| item.label() == label))
516                .unwrap_or(0);
517            let range = modal_option_range(items.len(), selected);
518            for item in &items[range] {
519                let marker = if selector.selected_label() == Some(item.label()) {
520                    "›"
521                } else {
522                    " "
523                };
524                push_wrapped(&mut rows, marker, item.label(), width, theme.editor, theme);
525            }
526            rows
527        }
528        Overlay::CommandCompletion(completion) => {
529            let mut rows = Vec::new();
530            push_wrapped(
531                &mut rows,
532                "commands",
533                "select command",
534                width,
535                theme.footer,
536                theme,
537            );
538            let selected = completion
539                .selected()
540                .and_then(|selected| {
541                    completion
542                        .options()
543                        .iter()
544                        .position(|option| option == selected)
545                })
546                .unwrap_or(0);
547            let range = modal_option_range(completion.options().len(), selected);
548            for option in &completion.options()[range] {
549                let marker = if completion.selected() == Some(option.as_str()) {
550                    "›"
551                } else {
552                    " "
553                };
554                push_wrapped(&mut rows, marker, option, width, theme.editor, theme);
555            }
556            rows
557        }
558    }
559}
560
561fn modal_option_range(length: usize, selected: usize) -> std::ops::Range<usize> {
562    let start = selected
563        .saturating_sub(MAX_BOTTOM_MODAL_OPTIONS / 2)
564        .min(length.saturating_sub(MAX_BOTTOM_MODAL_OPTIONS));
565    start..start.saturating_add(MAX_BOTTOM_MODAL_OPTIONS).min(length)
566}
567
568fn composer_frame(
569    state: &TuiState,
570    width: usize,
571    frame_height: usize,
572    cursor_byte: usize,
573    theme: &Theme,
574) -> ComposerFrame {
575    let width = width.max(1);
576    let cursor_byte = cursor_byte.min(state.editor.len());
577    let attachment_lines = composer_attachment_lines(state, width, theme);
578    let attachment_rows = attachment_lines.len();
579    let editor_lines = composer_content_lines(
580        &state.editor,
581        composer_content_width(width),
582        theme.composer,
583        theme,
584    );
585    let cursor_lines = composer_content_lines(
586        &state.editor[..cursor_byte],
587        composer_content_width(width),
588        theme.composer,
589        theme,
590    );
591    let cursor_row = cursor_lines.len().saturating_sub(1);
592    let max_editor_rows = max_composer_editor_rows(frame_height, attachment_rows);
593    let start = cursor_row
594        .saturating_add(1)
595        .saturating_sub(max_editor_rows)
596        .min(editor_lines.len().saturating_sub(max_editor_rows));
597    let end = start
598        .saturating_add(max_editor_rows)
599        .min(editor_lines.len());
600    let mut lines = Vec::with_capacity(
601        COMPOSER_VERTICAL_PADDING_ROWS
602            .saturating_mul(2)
603            .saturating_add(attachment_rows)
604            .saturating_add(end.saturating_sub(start))
605            .saturating_add(1),
606    );
607    lines.extend(attachment_lines);
608    for _ in 0..COMPOSER_VERTICAL_PADDING_ROWS {
609        lines.push(composer_blank_line(width, theme.composer));
610    }
611    if state.editor.is_empty() {
612        lines.push(composer_placeholder_line(
613            width,
614            theme.composer.patch(theme.footer),
615        ));
616    } else {
617        lines.extend(
618            editor_lines[start..end]
619                .iter()
620                .map(|line| fill_composer_line(line, width)),
621        );
622    }
623    for _ in 0..COMPOSER_VERTICAL_PADDING_ROWS {
624        lines.push(composer_blank_line(width, theme.composer));
625    }
626    lines.push(footer_line(state, width, theme.footer));
627
628    let column = cursor_lines
629        .last()
630        .map_or(0, |line| line.text.width())
631        .min(composer_content_width(width));
632    ComposerFrame {
633        lines,
634        cursor: Some(CursorState {
635            x: u16::try_from(column.min(width.saturating_sub(1))).unwrap_or(u16::MAX),
636            y: u16::try_from(
637                attachment_rows
638                    .saturating_add(COMPOSER_VERTICAL_PADDING_ROWS)
639                    .saturating_add(cursor_row.saturating_sub(start)),
640            )
641            .unwrap_or(u16::MAX),
642        }),
643    }
644}
645
646fn max_composer_editor_rows(frame_height: usize, attachment_rows: usize) -> usize {
647    let frame_limit = frame_height.saturating_sub(
648        COMPOSER_VERTICAL_PADDING_ROWS
649            .saturating_mul(2)
650            .saturating_add(attachment_rows)
651            .saturating_add(1),
652    );
653    frame_limit.clamp(1, MAX_COMPOSER_EDITOR_ROWS)
654}
655
656fn composer_attachment_lines(state: &TuiState, width: usize, theme: &Theme) -> Vec<RenderedLine> {
657    state
658        .attachments()
659        .iter()
660        .enumerate()
661        .map(|(index, attachment)| {
662            let index = index + 1;
663            let size = format_byte_count(attachment.decoded_bytes());
664            let full = format!(
665                "{index}. {} · {} · {size}",
666                attachment.display_name(),
667                attachment.mime_type()
668            );
669            let core = format!("{index}. {} {size}", attachment.mime_type());
670            let compact = format!(
671                "{index} {} {}",
672                attachment.mime_type(),
673                format_compact_byte_count(attachment.decoded_bytes())
674            );
675            let text = if full.width() <= width {
676                full
677            } else if core.width() <= width {
678                core
679            } else {
680                compact
681            };
682            fill_composer_line(
683                &RenderedLine::new(
684                    truncate_cells(&text, width),
685                    theme.composer.patch(theme.footer),
686                ),
687                width,
688            )
689        })
690        .collect()
691}
692
693fn composer_blank_line(width: usize, style: Style) -> RenderedLine {
694    RenderedLine::new(" ".repeat(width.max(1)), style)
695}
696
697fn composer_placeholder_line(width: usize, style: Style) -> RenderedLine {
698    fill_composer_line(
699        &RenderedLine::new(
700            truncate_cells(
701                &format!("{COMPOSER_PROMPT_PREFIX}Ask Tea to do anything"),
702                width,
703            ),
704            style,
705        ),
706        width,
707    )
708}
709
710fn fill_composer_line(line: &RenderedLine, width: usize) -> RenderedLine {
711    let padding = " ".repeat(width.saturating_sub(line.text.width()));
712    RenderedLine::new(format!("{}{padding}", line.text), line.style)
713}
714
715fn composer_content_lines(
716    text: &str,
717    width: usize,
718    style: Style,
719    theme: &Theme,
720) -> Vec<RenderedLine> {
721    component_lines(
722        Text::new(text, style).with_prefixes(COMPOSER_PROMPT_PREFIX, "  "),
723        width,
724        theme,
725    )
726}
727
728const fn composer_content_width(width: usize) -> usize {
729    width
730}
731
732#[allow(clippy::too_many_lines)] // Approval details remain ordered for policy review.
733fn approval_panel(state: &TuiState, width: usize, theme: &Theme) -> Option<Vec<RenderedLine>> {
734    let approval = state.approval.as_ref()?;
735    if width < 8 {
736        let mut rows = Vec::new();
737        push_wrapped(
738            &mut rows,
739            "approval",
740            &format!("{} [{}]", approval.tool_name, approval.target),
741            width,
742            theme.approval,
743            theme,
744        );
745        return Some(rows);
746    }
747
748    let inner_width = width.saturating_sub(4);
749    let mut content = Vec::new();
750    push_truncated(
751        &mut content,
752        "approval",
753        "approval required",
754        inner_width,
755        theme.approval,
756        theme,
757    );
758    push_wrapped(
759        &mut content,
760        "tool",
761        &approval.tool_name,
762        inner_width,
763        theme.approval,
764        theme,
765    );
766    push_wrapped(
767        &mut content,
768        "reason",
769        &approval.reason,
770        inner_width,
771        theme.approval,
772        theme,
773    );
774    push_wrapped(
775        &mut content,
776        "target",
777        &approval.target,
778        inner_width,
779        theme.approval,
780        theme,
781    );
782    push_wrapped(
783        &mut content,
784        "effects",
785        &approval.effects.join(", "),
786        inner_width,
787        theme.approval,
788        theme,
789    );
790    push_wrapped(
791        &mut content,
792        "resources",
793        &approval.resources.join(", "),
794        inner_width,
795        theme.approval,
796        theme,
797    );
798    push_wrapped(
799        &mut content,
800        "expires",
801        &approval.expires_at.to_string(),
802        inner_width,
803        theme.approval,
804        theme,
805    );
806    let arguments = truncate_cells_with_ellipsis(
807        &approval.arguments,
808        MAX_APPROVAL_ARGUMENT_CELLS.min(inner_width.saturating_mul(3)),
809    );
810    push_wrapped(
811        &mut content,
812        "arguments",
813        &arguments,
814        inner_width,
815        theme.approval,
816        theme,
817    );
818    if state.approval_submitting {
819        push_wrapped(
820            &mut content,
821            "decision",
822            &format!("{} [submitting]", state.approval_choice.label()),
823            inner_width,
824            theme.approval,
825            theme,
826        );
827    } else {
828        for choice in [
829            ApprovalChoice::AllowOnce,
830            ApprovalChoice::AllowSession,
831            ApprovalChoice::Deny,
832        ] {
833            let marker = if choice == state.approval_choice {
834                ">"
835            } else {
836                " "
837            };
838            push_wrapped(
839                &mut content,
840                marker,
841                &format!("{} ({})", choice.label(), approval_scope(choice)),
842                inner_width,
843                theme.approval,
844                theme,
845            );
846        }
847    }
848
849    Some(box_panel(content, width, theme.approval))
850}
851
852pub(crate) fn workspace_trust_panel(
853    workspace: &Path,
854    width: usize,
855    trust_selected: bool,
856    theme: &Theme,
857) -> Vec<RenderedLine> {
858    let inner_width = if width < 8 {
859        width
860    } else {
861        width.saturating_sub(4)
862    };
863    let mut content = Vec::new();
864    push_truncated(
865        &mut content,
866        "trust",
867        "workspace trust required",
868        inner_width,
869        theme.approval,
870        theme,
871    );
872    push_wrapped(
873        &mut content,
874        "folder",
875        &workspace.display().to_string(),
876        inner_width,
877        theme.approval,
878        theme,
879    );
880    push_wrapped(
881        &mut content,
882        "security",
883        "Tea will be able to read, edit, and execute files in this folder.",
884        inner_width,
885        theme.approval,
886        theme,
887    );
888    push_wrapped(
889        &mut content,
890        "",
891        "Only continue if you trust the files and their authors.",
892        inner_width,
893        theme.approval,
894        theme,
895    );
896    for (is_trust, label) in [(true, "Yes, trust this folder"), (false, "No, exit")] {
897        let marker = if is_trust == trust_selected { ">" } else { " " };
898        push_wrapped(
899            &mut content,
900            marker,
901            label,
902            inner_width,
903            theme.approval,
904            theme,
905        );
906    }
907    box_panel(content, width, theme.approval)
908}
909
910const fn approval_scope(choice: ApprovalChoice) -> &'static str {
911    match choice {
912        ApprovalChoice::AllowOnce | ApprovalChoice::Deny => "this call",
913        ApprovalChoice::AllowSession => "matching resources this session",
914    }
915}
916
917fn box_panel(content: Vec<RenderedLine>, width: usize, style: Style) -> Vec<RenderedLine> {
918    if width < 8 {
919        return content;
920    }
921    let inner_width = width - 4;
922    let mut panel = Vec::with_capacity(content.len() + 2);
923    panel.push(RenderedLine::new(
924        format!("+{}+", "-".repeat(width - 2)),
925        style,
926    ));
927    for line in content {
928        let padding = " ".repeat(inner_width.saturating_sub(line.text.width()));
929        panel.push(RenderedLine::new(
930            format!("| {}{padding} |", line.text),
931            line.style,
932        ));
933    }
934    panel.push(RenderedLine::new(
935        format!("+{}+", "-".repeat(width - 2)),
936        style,
937    ));
938    panel
939}
940
941fn footer_line(state: &TuiState, width: usize, style: Style) -> RenderedLine {
942    let model = state.model_id().map_or("default", ModelIdText::text);
943    let text = format!(
944        "{model} · {} · {}",
945        state.displayed_reasoning_effort(),
946        state.startup.workspace()
947    );
948    let margin = COMPOSER_PROMPT_PREFIX.width().min(width.saturating_sub(1));
949    let text = truncate_cells(&text, width.saturating_sub(margin).max(1));
950    RenderedLine::new(format!("{}{text}", " ".repeat(margin)), style)
951}
952
953trait ModelIdText {
954    fn text(&self) -> &str;
955}
956
957impl ModelIdText for ModelId {
958    fn text(&self) -> &str {
959        self.as_str()
960    }
961}
962
963fn component_lines(component: impl Component, width: usize, theme: &Theme) -> Vec<RenderedLine> {
964    let context = RenderContext { theme };
965    Element::new(component)
966        .render(&context, u16::try_from(width).unwrap_or(u16::MAX).max(1))
967        .into_lines()
968}
969
970fn push_wrapped(
971    output: &mut Vec<RenderedLine>,
972    label: &str,
973    text: &str,
974    width: usize,
975    style: Style,
976    theme: &Theme,
977) {
978    output.extend(component_lines(
979        Text::new(text, style).with_label(label),
980        width,
981        theme,
982    ));
983}
984
985fn push_truncated(
986    output: &mut Vec<RenderedLine>,
987    label: &str,
988    text: &str,
989    width: usize,
990    style: Style,
991    theme: &Theme,
992) {
993    output.extend(component_lines(
994        Text::truncated(text, style).with_label(label),
995        width,
996        theme,
997    ));
998}
999
1000#[cfg(test)]
1001mod tests {
1002    use std::fmt::Write as _;
1003
1004    use super::{
1005        CellCacheKey, CellRenderCache, LifecycleStatus, OutputFormat, PlanStep, PlanStepStatus,
1006        RenderedLine, RenderedSpan, Renderer, TimelineDetail, TimelineDetailKind, TimelineSource,
1007        component_lines,
1008    };
1009    use crate::tui::cells::{
1010        CellBlock, CellContext, CellHost, CellList, CellStylePatch, CellStyleSheet, InsetsPatch,
1011    };
1012    use crate::tui::components::Markdown;
1013    use crate::tui::components::style::Insets;
1014    use crate::tui::hyperlink::HyperlinkBuffer;
1015    use crate::tui::layout::draw_lines_with_hyperlinks;
1016    use crate::tui::presentation::{
1017        CellContent, CellId, CellLane, CellNode, DecisionCell, DecisionStatus, DiffCell,
1018        LifecycleCell, LifecycleKind, MessageAuthor, MessageCell, NoticeCell, NoticeKind,
1019        NoticeSeverity, PlanCell, QueuedInputCell, QueuedInputKind, ReasoningCell, ResultCell,
1020        SourcesCell,
1021    };
1022    use crate::tui::{TerminalCapabilities, Theme};
1023    use ratatui::buffer::Buffer;
1024    use ratatui::layout::{Position, Rect};
1025    use ratatui::style::{Color, Modifier, Style};
1026    use tea_protocol::{CodeChange, CodeChangeKind};
1027    use unicode_width::UnicodeWidthStr as _;
1028
1029    fn cache_key(index: u16) -> CellCacheKey {
1030        CellCacheKey {
1031            id: CellId::Synthetic {
1032                lane: CellLane::History,
1033                index,
1034            },
1035            width: 80,
1036            theme_generation: 0,
1037            stylesheet_generation: 0,
1038        }
1039    }
1040
1041    fn test_cell(content: CellContent) -> CellNode {
1042        test_cell_at(0, content)
1043    }
1044
1045    fn test_cell_at(index: u16, content: CellContent) -> CellNode {
1046        CellNode::new(
1047            CellId::Synthetic {
1048                lane: CellLane::History,
1049                index,
1050            },
1051            content,
1052            None,
1053        )
1054    }
1055
1056    fn test_cell_with_owner(content: CellContent, owner: tea_protocol::ToolCallId) -> CellNode {
1057        test_cell_at_with_owner(0, content, owner)
1058    }
1059
1060    fn test_cell_at_with_owner(
1061        index: u16,
1062        content: CellContent,
1063        owner: tea_protocol::ToolCallId,
1064    ) -> CellNode {
1065        CellNode::new(
1066            CellId::Synthetic {
1067                lane: CellLane::History,
1068                index,
1069            },
1070            content,
1071            Some(owner),
1072        )
1073    }
1074
1075    fn render_test_node(cell: &CellNode, width: usize, theme: &Theme) -> Vec<RenderedLine> {
1076        let host = CellHost::new(CellStyleSheet::default().with_global_patch(CellStylePatch {
1077            margin: InsetsPatch {
1078                right: Some(0),
1079                left: Some(0),
1080                ..InsetsPatch::default()
1081            },
1082            ..CellStylePatch::default()
1083        }));
1084        let context = CellContext { theme };
1085        let block = host.render(
1086            cell.content().spec(),
1087            &context,
1088            u16::try_from(width).unwrap_or(u16::MAX).max(1),
1089        );
1090        CellList::new(vec![block]).render().into_lines()
1091    }
1092
1093    fn message(author: MessageAuthor, source: &str, format: OutputFormat) -> CellContent {
1094        CellContent::Message(MessageCell::new(author, source, format))
1095    }
1096
1097    fn result(
1098        action: &str,
1099        source_name: Option<&str>,
1100        content: &str,
1101        format: OutputFormat,
1102        is_error: bool,
1103    ) -> CellContent {
1104        CellContent::Result(ResultCell::new(
1105            action,
1106            source_name,
1107            content,
1108            format,
1109            is_error,
1110        ))
1111    }
1112
1113    #[test]
1114    fn stable_cell_cache_reuses_matching_blocks_and_stays_bounded() {
1115        let mut cache = CellRenderCache::default();
1116        let key = cache_key(0);
1117        let content = message(
1118            MessageAuthor::Assistant,
1119            "stable response",
1120            OutputFormat::Markdown,
1121        );
1122        let expected = CellBlock::new(
1123            vec![RenderedLine::new(
1124                "stable response".to_owned(),
1125                Style::default(),
1126            )],
1127            Insets::default(),
1128        );
1129
1130        assert_eq!(
1131            cache.get_or_render(key.clone(), &content, None, || expected.clone()),
1132            expected
1133        );
1134        assert_eq!(
1135            cache.get_or_render(key, &content, None, || {
1136                panic!("matching cell must use cached rows")
1137            }),
1138            expected
1139        );
1140        assert_eq!(cache.hits, 1);
1141        assert_eq!(cache.misses, 1);
1142
1143        for index in 0..=super::MAX_CELL_RENDER_CACHE_ENTRIES {
1144            let text = index.to_string();
1145            let content = message(MessageAuthor::Assistant, &text, OutputFormat::Markdown);
1146            let _ = cache.get_or_render(
1147                cache_key(u16::try_from(index).unwrap_or(u16::MAX)),
1148                &content,
1149                None,
1150                CellBlock::empty,
1151            );
1152        }
1153        assert!(cache.entries.len() <= super::MAX_CELL_RENDER_CACHE_ENTRIES);
1154    }
1155
1156    #[test]
1157    fn stable_cell_cache_keys_width_theme_and_stylesheet_generations() {
1158        let theme = Theme::default();
1159        let cell = test_cell(message(
1160            MessageAuthor::Assistant,
1161            "A stable response that wraps differently when the viewport becomes narrow.",
1162            OutputFormat::Plain,
1163        ));
1164        let mut renderer = Renderer::new();
1165
1166        let wide = renderer.history_lines(std::slice::from_ref(&cell), 80, &theme);
1167        let cached = renderer.history_lines(std::slice::from_ref(&cell), 80, &theme);
1168        assert_eq!(wide, cached);
1169        assert_eq!((renderer.cache.hits, renderer.cache.misses), (1, 1));
1170
1171        let narrow = renderer.history_lines(std::slice::from_ref(&cell), 20, &theme);
1172        assert_ne!(wide, narrow);
1173        assert_eq!((renderer.cache.hits, renderer.cache.misses), (1, 2));
1174
1175        let mut changed_theme = theme;
1176        changed_theme.generation = changed_theme.generation.saturating_add(100);
1177        let themed = renderer.history_lines(std::slice::from_ref(&cell), 20, &changed_theme);
1178        assert_eq!(narrow, themed);
1179        assert_eq!((renderer.cache.hits, renderer.cache.misses), (1, 3));
1180
1181        let spaced_host =
1182            CellHost::new(CellStyleSheet::default().with_global_patch(CellStylePatch {
1183                margin: InsetsPatch {
1184                    top: Some(1),
1185                    ..InsetsPatch::default()
1186                },
1187                ..CellStylePatch::default()
1188            }));
1189        let stylesheet_generation = spaced_host.stylesheet_generation();
1190        renderer = renderer.with_cell_host(spaced_host);
1191        let spaced = renderer.history_lines(std::slice::from_ref(&cell), 20, &changed_theme);
1192
1193        assert_ne!(themed, spaced);
1194        assert_eq!((renderer.cache.hits, renderer.cache.misses), (1, 4));
1195        assert!(
1196            renderer
1197                .cache
1198                .entries
1199                .keys()
1200                .any(|key| key.stylesheet_generation == stylesheet_generation)
1201        );
1202        assert_eq!(
1203            spaced,
1204            renderer.history_lines(std::slice::from_ref(&cell), 20, &changed_theme)
1205        );
1206        assert_eq!((renderer.cache.hits, renderer.cache.misses), (2, 4));
1207    }
1208
1209    #[test]
1210    fn stable_cell_cache_guards_content_owner_role_and_state() {
1211        let theme = Theme::default();
1212        let owner_a = "0195a0b1-7e00-7000-8000-000000000001".parse().unwrap();
1213        let owner_b = "0195a0b1-7e00-7000-8000-000000000002".parse().unwrap();
1214        let original = test_cell_at_with_owner(
1215            4,
1216            message(MessageAuthor::Assistant, "same", OutputFormat::Plain),
1217            owner_a,
1218        );
1219        let mut renderer = Renderer::new();
1220
1221        let first = renderer.history_lines(std::slice::from_ref(&original), 40, &theme);
1222        assert_eq!(
1223            first,
1224            renderer.history_lines(std::slice::from_ref(&original), 40, &theme)
1225        );
1226
1227        let changed_content = test_cell_at_with_owner(
1228            4,
1229            message(MessageAuthor::Assistant, "changed", OutputFormat::Plain),
1230            owner_a,
1231        );
1232        let content_output =
1233            renderer.history_lines(std::slice::from_ref(&changed_content), 40, &theme);
1234        assert_ne!(first, content_output);
1235
1236        let changed_owner = test_cell_at_with_owner(
1237            4,
1238            message(MessageAuthor::Assistant, "changed", OutputFormat::Plain),
1239            owner_b,
1240        );
1241        let owner_output = renderer.history_lines(std::slice::from_ref(&changed_owner), 40, &theme);
1242
1243        let changed_role = test_cell_at_with_owner(
1244            4,
1245            CellContent::Notice(NoticeCell::new(
1246                NoticeKind::General,
1247                NoticeSeverity::Information,
1248                "changed",
1249                None,
1250            )),
1251            owner_b,
1252        );
1253        let role_output = renderer.history_lines(std::slice::from_ref(&changed_role), 40, &theme);
1254        assert_ne!(owner_output, role_output);
1255
1256        let changed_state = test_cell_at_with_owner(
1257            4,
1258            CellContent::Notice(NoticeCell::new(
1259                NoticeKind::General,
1260                NoticeSeverity::Warning,
1261                "changed",
1262                None,
1263            )),
1264            owner_b,
1265        );
1266        let state_output = renderer.history_lines(std::slice::from_ref(&changed_state), 40, &theme);
1267        assert_ne!(role_output, state_output);
1268        assert_eq!(renderer.cache.entries.len(), 1);
1269        assert_eq!((renderer.cache.hits, renderer.cache.misses), (1, 5));
1270
1271        assert_eq!(
1272            state_output,
1273            renderer.history_lines(std::slice::from_ref(&changed_state), 40, &theme)
1274        );
1275        assert_eq!((renderer.cache.hits, renderer.cache.misses), (2, 5));
1276    }
1277
1278    #[test]
1279    fn stable_cell_cache_rejects_active_tick_expansion_and_content_changes() {
1280        let theme = Theme::default();
1281        let lifecycle = |action: &str, expanded: bool, tick: u64| {
1282            test_cell_at(
1283                7,
1284                CellContent::Lifecycle(LifecycleCell::new(
1285                    LifecycleKind::ToolCall,
1286                    action,
1287                    Some("src/lib.rs"),
1288                    LifecycleStatus::Running,
1289                    vec![TimelineDetail::new(
1290                        TimelineDetailKind::Metadata,
1291                        Some("phase"),
1292                        "compiling",
1293                    )],
1294                    expanded,
1295                    tick,
1296                )),
1297            )
1298        };
1299        let mut renderer = Renderer::new();
1300
1301        let tick_zero = lifecycle("Building", false, 0);
1302        let first = renderer.history_lines(std::slice::from_ref(&tick_zero), 40, &theme);
1303        let tick_one = lifecycle("Building", false, 1);
1304        let tick_output = renderer.history_lines(std::slice::from_ref(&tick_one), 40, &theme);
1305        assert_ne!(first, tick_output);
1306
1307        let expanded = lifecycle("Building", true, 1);
1308        let expanded_output = renderer.history_lines(std::slice::from_ref(&expanded), 40, &theme);
1309        assert_ne!(tick_output, expanded_output);
1310        assert!(
1311            expanded_output
1312                .iter()
1313                .any(|line| line.text().contains("compiling"))
1314        );
1315
1316        let changed = lifecycle("Linking", true, 1);
1317        let changed_output = renderer.history_lines(std::slice::from_ref(&changed), 40, &theme);
1318        assert_ne!(expanded_output, changed_output);
1319        assert_eq!((renderer.cache.hits, renderer.cache.misses), (0, 4));
1320        assert_eq!(renderer.cache.entries.len(), 1);
1321
1322        assert_eq!(
1323            changed_output,
1324            renderer.history_lines(std::slice::from_ref(&changed), 40, &theme)
1325        );
1326        assert_eq!((renderer.cache.hits, renderer.cache.misses), (1, 4));
1327    }
1328
1329    #[test]
1330    fn stable_cell_cache_never_aliases_distinct_ids_with_identical_text() {
1331        let theme = Theme::default();
1332        let cells = vec![
1333            test_cell_at(
1334                8,
1335                message(MessageAuthor::Assistant, "identical", OutputFormat::Plain),
1336            ),
1337            test_cell_at(
1338                9,
1339                message(MessageAuthor::Assistant, "identical", OutputFormat::Plain),
1340            ),
1341        ];
1342        let mut renderer = Renderer::new();
1343
1344        let first = renderer.history_lines(&cells, 40, &theme);
1345        assert_eq!(renderer.cache.entries.len(), 2);
1346        assert_eq!((renderer.cache.hits, renderer.cache.misses), (0, 2));
1347        assert_eq!(first, renderer.history_lines(&cells, 40, &theme));
1348        assert_eq!((renderer.cache.hits, renderer.cache.misses), (2, 2));
1349    }
1350
1351    #[test]
1352    fn message_cells_end_with_one_default_spacing_row_while_tool_rows_stay_compact() {
1353        let theme = Theme::default();
1354        let render_message = |author, source: &str| {
1355            render_test_node(
1356                &test_cell(message(author, source, OutputFormat::Plain)),
1357                24,
1358                &theme,
1359            )
1360        };
1361
1362        let user = render_message(MessageAuthor::User, "first request");
1363        let assistant = render_message(MessageAuthor::Assistant, "first response");
1364
1365        for lines in [&user, &assistant] {
1366            assert_eq!(lines.last().unwrap().text(), "");
1367            assert_eq!(lines.last().unwrap().style(), Style::default());
1368            assert_ne!(lines[lines.len() - 2].text(), "");
1369            assert!(lines.iter().all(|line| line.text().width() <= 24));
1370        }
1371
1372        let tool = render_test_node(
1373            &test_cell(CellContent::Lifecycle(LifecycleCell::new(
1374                LifecycleKind::ToolCall,
1375                "Read",
1376                Some("README.md"),
1377                LifecycleStatus::Succeeded,
1378                Vec::new(),
1379                false,
1380                0,
1381            ))),
1382            24,
1383            &theme,
1384        );
1385        assert_ne!(tool.last().unwrap().text(), "");
1386    }
1387
1388    #[test]
1389    #[allow(clippy::too_many_lines)]
1390    fn mixed_cell_list_uses_the_component_pipeline() {
1391        let theme = Theme::default();
1392        let width = 24;
1393        let cells = [
1394            test_cell_at(
1395                0,
1396                message(MessageAuthor::User, "ship it", OutputFormat::Plain),
1397            ),
1398            test_cell_at(
1399                1,
1400                message(MessageAuthor::Assistant, "", OutputFormat::Plain),
1401            ),
1402            test_cell_at(
1403                2,
1404                message(
1405                    MessageAuthor::Assistant,
1406                    "See [docs](https://x.test).",
1407                    OutputFormat::Markdown,
1408                ),
1409            ),
1410            test_cell_at(
1411                3,
1412                CellContent::Lifecycle(LifecycleCell::new(
1413                    LifecycleKind::ToolCall,
1414                    "Read",
1415                    Some("README.md"),
1416                    LifecycleStatus::Succeeded,
1417                    Vec::new(),
1418                    false,
1419                    0,
1420                )),
1421            ),
1422            test_cell_at(
1423                4,
1424                result(
1425                    "Returned",
1426                    Some("cargo test"),
1427                    "1 passed",
1428                    OutputFormat::Plain,
1429                    false,
1430                ),
1431            ),
1432            test_cell_at(
1433                5,
1434                CellContent::Diff(DiffCell::new(
1435                    "Updated",
1436                    CodeChange::new(
1437                        "src/lib.rs",
1438                        CodeChangeKind::Update,
1439                        Vec::new(),
1440                        false,
1441                        None,
1442                        None,
1443                        None,
1444                    )
1445                    .unwrap(),
1446                )),
1447            ),
1448        ];
1449        let mut renderer = Renderer::new();
1450
1451        let output = renderer.render_cell_nodes(cells.iter(), width, &theme);
1452        let user = output
1453            .iter()
1454            .find(|line| line.text().contains("› ship it"))
1455            .unwrap();
1456        let assistant = output
1457            .iter()
1458            .find(|line| line.text().contains("docs"))
1459            .unwrap();
1460        let lifecycle = output
1461            .iter()
1462            .find(|line| line.text().contains("Read README.md"))
1463            .unwrap();
1464        let result = output
1465            .iter()
1466            .find(|line| line.text().contains("Returned cargo test"))
1467            .unwrap();
1468        let diff_body = output
1469            .iter()
1470            .find(|line| line.text().contains("(no textual change)"))
1471            .unwrap();
1472        let links = output
1473            .iter()
1474            .flat_map(super::super::render_output::RenderedLine::rendered_spans)
1475            .filter_map(|span| span.link())
1476            .collect::<Vec<_>>();
1477
1478        assert!(user.text().starts_with('›'));
1479        assert_eq!(user.text().width(), usize::from(width));
1480        assert!(assistant.text().starts_with(' '));
1481        assert!(lifecycle.text().starts_with(' '));
1482        assert!(result.text().starts_with(' '));
1483        assert_eq!(diff_body.text(), "(no textual change)");
1484        assert_eq!(
1485            output.iter().filter(|line| line.text().is_empty()).count(),
1486            2
1487        );
1488        assert!(
1489            output
1490                .windows(2)
1491                .all(|rows| !(rows[0].text().is_empty() && rows[1].text().is_empty()))
1492        );
1493        assert!(!links.is_empty());
1494        assert!(
1495            links
1496                .iter()
1497                .all(|destination| *destination == "https://x.test/")
1498        );
1499        assert!(
1500            output
1501                .iter()
1502                .all(|line| line.text().width() <= usize::from(width)),
1503            "{:?}",
1504            output
1505                .iter()
1506                .map(|line| (line.text(), line.text().width()))
1507                .collect::<Vec<_>>()
1508        );
1509    }
1510
1511    #[test]
1512    fn markdown_structure_survives_no_color_without_becoming_a_row_identity() {
1513        let theme = Theme::for_capabilities(TerminalCapabilities::from_environment(
1514            Some("dumb"),
1515            None,
1516            false,
1517            false,
1518        ));
1519        let output = component_lines(
1520            Markdown::new("## Result\n\n> quoted\n\n```rust\nlet ready = true;\n```"),
1521            80,
1522            &theme,
1523        );
1524        let text = output.iter().map(RenderedLine::text).collect::<Vec<_>>();
1525
1526        assert_eq!(text, ["## Result", "", "> quoted", "", "let ready = true;"]);
1527        assert!(output[0].style().add_modifier.contains(Modifier::BOLD));
1528        assert_eq!(output[2].style(), theme.markdown_quote);
1529        assert_eq!(output[4].style(), theme.markdown_code);
1530    }
1531
1532    #[test]
1533    fn fenced_syntax_highlighting_is_color_gated_and_cache_stable() {
1534        let source = "```rust\nfn main() { let answer = 42; }\n```";
1535        let render = |theme: &Theme| component_lines(Markdown::new(source), 80, theme);
1536        let color_theme = Theme::default();
1537        let colored = render(&color_theme);
1538        let no_color_theme = Theme::for_capabilities(TerminalCapabilities::from_environment(
1539            Some("dumb"),
1540            None,
1541            false,
1542            false,
1543        ));
1544        let plain = render(&no_color_theme);
1545
1546        assert_eq!(colored[0].text(), "fn main() { let answer = 42; }");
1547        assert_eq!(colored[0].text(), plain[0].text());
1548        assert!(
1549            colored[0]
1550                .spans
1551                .iter()
1552                .any(|span| span.style != color_theme.markdown_code)
1553        );
1554        assert!(
1555            plain[0]
1556                .spans
1557                .iter()
1558                .all(|span| span.style == no_color_theme.markdown_code)
1559        );
1560        let ansi16_theme = Theme::for_capabilities(TerminalCapabilities::from_environment(
1561            Some("xterm"),
1562            None,
1563            false,
1564            false,
1565        ));
1566        assert!(
1567            render(&ansi16_theme)[0]
1568                .spans
1569                .iter()
1570                .all(|span| { !matches!(span.style.fg, Some(Color::Indexed(_) | Color::Rgb(..))) })
1571        );
1572        let ansi256_theme = Theme::for_capabilities(TerminalCapabilities::from_environment(
1573            Some("xterm-256color"),
1574            None,
1575            false,
1576            false,
1577        ));
1578        let ansi256 = render(&ansi256_theme);
1579        assert!(
1580            ansi256[0]
1581                .spans
1582                .iter()
1583                .all(|span| !matches!(span.style.fg, Some(Color::Rgb(..))))
1584        );
1585        assert!(
1586            ansi256[0]
1587                .spans
1588                .iter()
1589                .any(|span| matches!(span.style.fg, Some(Color::Indexed(_))))
1590        );
1591
1592        let cell = test_cell(message(
1593            MessageAuthor::Assistant,
1594            source,
1595            OutputFormat::Markdown,
1596        ));
1597        let mut renderer = Renderer::new();
1598        let first = renderer.history_lines(std::slice::from_ref(&cell), 80, &color_theme);
1599        let cached = renderer.history_lines(&[cell], 80, &color_theme);
1600        assert_eq!(first, cached);
1601        assert_eq!(renderer.cache.hits, 1);
1602    }
1603
1604    #[test]
1605    fn inline_markdown_styles_reach_terminal_cells_without_source_markers() {
1606        let theme = Theme::default();
1607        let output = component_lines(
1608            Markdown::new("**bold** *italic* ~~old~~ `tea-cli` [docs](https://e.test)"),
1609            80,
1610            &theme,
1611        );
1612        assert_eq!(
1613            output[0].text(),
1614            "bold italic old tea-cli docs (https://e.test/)"
1615        );
1616        assert!(
1617            !output[0]
1618                .text()
1619                .chars()
1620                .any(|character| matches!(character, '`' | '*'))
1621        );
1622
1623        let area = Rect::new(0, 0, 80, 1);
1624        let mut buffer = Buffer::empty(area);
1625        crate::tui::layout::draw_lines(&output, area, &mut buffer);
1626        assert!(buffer[(0, 0)].modifier.contains(Modifier::BOLD));
1627        assert!(buffer[(5, 0)].modifier.contains(Modifier::ITALIC));
1628        assert!(buffer[(12, 0)].modifier.contains(Modifier::CROSSED_OUT));
1629        assert_eq!(Some(buffer[(16, 0)].fg), theme.markdown_inline_code.fg);
1630        assert!(buffer[(24, 0)].modifier.contains(Modifier::UNDERLINED));
1631    }
1632
1633    #[test]
1634    fn validated_link_metadata_reaches_rendered_rows_but_not_ratatui_text() {
1635        let theme = Theme::default();
1636        let output = component_lines(
1637            Markdown::new("Open [Tea](HTTPS://Example.COM:443/a/../docs) now."),
1638            24,
1639            &theme,
1640        );
1641
1642        let links = output
1643            .iter()
1644            .flat_map(|line| &line.spans)
1645            .filter_map(|span| span.link.as_deref())
1646            .collect::<Vec<_>>();
1647        assert!(!links.is_empty());
1648        assert!(links.iter().all(|link| *link == "https://example.com/docs"));
1649        let terminal_text = output
1650            .iter()
1651            .flat_map(|line| line.as_ratatui_line().spans)
1652            .map(|span| span.content.into_owned())
1653            .collect::<String>();
1654        assert!(!terminal_text.contains('\u{1b}'));
1655        assert!(!terminal_text.contains("]8;"));
1656    }
1657
1658    #[test]
1659    fn hyperlink_sidecar_tracks_wide_cells_and_clips_with_the_visible_line() {
1660        let theme = Theme::default();
1661        let output = component_lines(Markdown::new("[界A](https://example.test/)"), 80, &theme);
1662        let area = Rect::new(3, 4, 3, 1);
1663        let mut buffer = Buffer::empty(area);
1664        let mut hyperlinks = HyperlinkBuffer::empty(area);
1665
1666        draw_lines_with_hyperlinks(&output, area, &mut buffer, &mut hyperlinks);
1667
1668        assert_eq!(buffer[(3, 4)].symbol(), "界");
1669        assert_eq!(buffer[(5, 4)].symbol(), "A");
1670        for x in 3..=5 {
1671            assert_eq!(
1672                hyperlinks.get(Position::new(x, 4)).map(AsRef::as_ref),
1673                Some("https://example.test/")
1674            );
1675        }
1676        assert_eq!(hyperlinks.get(Position::new(6, 4)), None);
1677    }
1678
1679    #[test]
1680    fn hosted_sources_wrap_labels_and_retain_normalized_hyperlink_sidecar_metadata() {
1681        let source = tea_protocol::ExternalSource::new(
1682            "https://Example.COM:443/a/../docs?section=hosted-search",
1683        )
1684        .unwrap()
1685        .with_title("Hosted search architecture reference")
1686        .unwrap();
1687        let cell = test_cell(CellContent::Sources(SourcesCell::new(vec![
1688            TimelineSource::from_external(&source),
1689        ])));
1690        let theme = Theme::default();
1691        let output = render_test_node(&cell, 20, &theme);
1692
1693        assert!(output.iter().all(|line| line.text().width() <= 20));
1694        let links = output
1695            .iter()
1696            .flat_map(|line| line.spans.iter())
1697            .filter_map(|span| span.link.as_deref())
1698            .collect::<Vec<_>>();
1699        assert!(!links.is_empty());
1700        assert!(links.iter().all(|destination| {
1701            *destination == "https://example.com/docs?section=hosted-search"
1702        }));
1703
1704        let area = Rect::new(0, 0, 20, u16::try_from(output.len()).unwrap());
1705        let mut buffer = Buffer::empty(area);
1706        let mut hyperlinks = HyperlinkBuffer::empty(area);
1707        draw_lines_with_hyperlinks(&output, area, &mut buffer, &mut hyperlinks);
1708        assert!((0..area.height).any(|y| {
1709            (0..area.width).any(|x| {
1710                hyperlinks
1711                    .get(Position::new(x, y))
1712                    .is_some_and(|destination| {
1713                        destination.as_ref() == "https://example.com/docs?section=hosted-search"
1714                    })
1715            })
1716        }));
1717    }
1718
1719    #[test]
1720    fn rendered_link_metadata_survives_cell_cache_hits() {
1721        let theme = Theme::default();
1722        let cell = test_cell(message(
1723            MessageAuthor::Assistant,
1724            "See [Tea docs](https://example.com/docs).",
1725            OutputFormat::Markdown,
1726        ));
1727        let mut renderer = Renderer::new();
1728
1729        let first = renderer.history_lines(std::slice::from_ref(&cell), 80, &theme);
1730        let second = renderer.history_lines(&[cell], 80, &theme);
1731        let links = |lines: &[RenderedLine]| {
1732            lines
1733                .iter()
1734                .flat_map(|line| &line.spans)
1735                .filter_map(|span| span.link.clone())
1736                .collect::<Vec<_>>()
1737        };
1738
1739        assert_eq!(links(&first), links(&second));
1740        assert!(!links(&second).is_empty());
1741        let linked_line = second
1742            .iter()
1743            .find(|line| {
1744                line.rendered_spans()
1745                    .iter()
1746                    .any(|span| span.link().is_some())
1747            })
1748            .unwrap();
1749        assert!(linked_line.text().starts_with(' '));
1750        assert_eq!(linked_line.rendered_spans()[0].link(), None);
1751        assert_eq!(renderer.cache.hits, 1);
1752    }
1753
1754    #[test]
1755    fn rendered_table_reflows_by_width_and_survives_cell_cache_hits() {
1756        let theme = Theme::default();
1757        let source =
1758            "| Key | Value | Extra | More |\n|---|---|---|---|\n| item | alpha | beta | gamma |";
1759        let cell = test_cell(message(
1760            MessageAuthor::Assistant,
1761            source,
1762            OutputFormat::Markdown,
1763        ));
1764        let mut renderer = Renderer::new();
1765
1766        let wide = renderer.history_lines(std::slice::from_ref(&cell), 80, &theme);
1767        let cached = renderer.history_lines(std::slice::from_ref(&cell), 80, &theme);
1768        let narrow = renderer.history_lines(&[cell], 16, &theme);
1769
1770        assert_eq!(wide, cached);
1771        assert!(wide.iter().any(|line| line.text().contains('━')));
1772        assert!(narrow.iter().any(|line| line.text().trim() == "Key"));
1773        assert!(narrow.iter().any(|line| line.text().trim() == "item"));
1774        assert!(narrow.iter().all(|line| line.text().width() <= 16));
1775        assert_eq!(renderer.cache.hits, 1);
1776    }
1777
1778    #[test]
1779    fn adjacent_rendered_spans_do_not_merge_across_link_destinations() {
1780        let first = RenderedSpan::with_link(
1781            "one".to_owned(),
1782            Style::default(),
1783            "https://one.example/".to_owned(),
1784        );
1785        let second = RenderedSpan::with_link(
1786            "two".to_owned(),
1787            Style::default(),
1788            "https://two.example/".to_owned(),
1789        );
1790        let line = RenderedLine::from_spans(Style::default(), vec![first, second]);
1791
1792        assert_eq!(line.spans.len(), 2);
1793        assert_ne!(line.spans[0].link, line.spans[1].link);
1794    }
1795
1796    #[test]
1797    fn terminal_result_previews_stdout_and_stderr_separately() {
1798        let theme = Theme::default();
1799        let output = render_test_node(
1800            &test_cell_with_owner(
1801                result(
1802                    "Returned",
1803                    Some("cargo test"),
1804                    "exit code: Some(0)\nstdout:\n39 passed\nstderr:\nwarning: retrying",
1805                    OutputFormat::Terminal,
1806                    false,
1807                ),
1808                "0195a0b1-7e00-7000-8000-000000000002".parse().unwrap(),
1809            ),
1810            80,
1811            &theme,
1812        );
1813
1814        let text = output.iter().map(RenderedLine::text).collect::<Vec<_>>();
1815        assert_eq!(
1816            text,
1817            [
1818                "• Returned cargo test",
1819                "  └ exit code: Some(0)",
1820                "    39 passed",
1821                "    warning: retrying",
1822            ]
1823        );
1824        assert_eq!(output[1].style(), theme.footer);
1825        assert_eq!(output[2].style(), theme.normal);
1826        assert_eq!(output[3].style(), theme.error);
1827    }
1828
1829    #[test]
1830    fn terminal_result_omits_only_generated_empty_stream_markers() {
1831        let render = |content: &str| {
1832            let output = render_test_node(
1833                &test_cell(result(
1834                    "Returned",
1835                    Some("bash"),
1836                    content,
1837                    OutputFormat::Terminal,
1838                    false,
1839                )),
1840                80,
1841                &Theme::default(),
1842            );
1843            output
1844                .iter()
1845                .map(|line| line.text().to_owned())
1846                .collect::<Vec<_>>()
1847        };
1848
1849        assert_eq!(
1850            render("exit code: Some(0)\nstdout:\nlisting\nstderr:\n(empty)"),
1851            ["• Returned bash", "  └ exit code: Some(0)", "    listing",]
1852        );
1853        assert_eq!(
1854            render("exit code: Some(0)\nstdout:\n(empty)\nstderr:\n(empty)"),
1855            ["• Returned bash", "  └ exit code: Some(0)"]
1856        );
1857        assert_eq!(render("(empty)"), ["• Returned bash", "  └ (empty)"]);
1858    }
1859
1860    #[test]
1861    fn shell_command_result_keeps_exit_and_duration_visible() {
1862        let theme = Theme::default();
1863        let output = render_test_node(
1864            &test_cell_with_owner(
1865                result(
1866                    "Ran",
1867                    Some("cargo test -p tea-cli --test tui"),
1868                    "stdout: 39 passed\nexit 0 in 1.42s",
1869                    OutputFormat::Terminal,
1870                    false,
1871                ),
1872                "0195a0b1-7e00-7000-8000-000000000002".parse().unwrap(),
1873            ),
1874            80,
1875            &theme,
1876        );
1877
1878        let text = output.iter().map(RenderedLine::text).collect::<Vec<_>>();
1879        assert_eq!(
1880            text,
1881            [
1882                "• Ran cargo test -p tea-cli --test tui",
1883                "  └ 39 passed",
1884                "    exit 0 in 1.42s",
1885            ]
1886        );
1887        assert!(
1888            output[0]
1889                .spans
1890                .iter()
1891                .any(|span| span.style.add_modifier.contains(Modifier::BOLD))
1892        );
1893    }
1894
1895    #[test]
1896    fn terminal_result_keeps_bounded_head_and_tail_at_narrow_widths() {
1897        let theme = Theme::default();
1898        let content = (1..=14)
1899            .map(|line| {
1900                if line == 1 {
1901                    format!("line {line} {}", "long-token-".repeat(8))
1902                } else {
1903                    format!("line {line}")
1904                }
1905            })
1906            .collect::<Vec<_>>()
1907            .join("\n");
1908        let output = render_test_node(
1909            &test_cell(result(
1910                "Returned",
1911                Some("process"),
1912                &content,
1913                OutputFormat::Terminal,
1914                false,
1915            )),
1916            20,
1917            &theme,
1918        );
1919
1920        let text = output.iter().map(RenderedLine::text).collect::<Vec<_>>();
1921        assert_eq!(text.len(), 12);
1922        assert!(text[1].starts_with("  └ line 1"));
1923        assert_eq!(text[5], "    line 5");
1924        assert_eq!(text[6], "    ... +4 lines");
1925        assert_eq!(text[7], "    line 10");
1926        assert_eq!(text[11], "    line 14");
1927        assert!(text.iter().all(|line| line.width() <= 20));
1928    }
1929
1930    #[test]
1931    fn proposed_plan_reflows_markdown_and_retains_raw_source() {
1932        let theme = Theme::default();
1933        let source = "## Renderer migration\n\n1. Preserve narrow CJK 宽度 and a long continuation\n2. Run tests";
1934        let cell = test_cell(CellContent::Plan(PlanCell::new(
1935            "Proposed Plan",
1936            Some(source),
1937            Vec::new(),
1938            None,
1939        )));
1940        let output = render_test_node(&cell, 24, &theme);
1941
1942        assert_eq!(cell.raw_text(), source);
1943        assert_eq!(output[0].text(), "○ Proposed Plan");
1944        assert!(output[1].text().starts_with("  └ ## Renderer"));
1945        assert!(output.len() > 4, "proposal must reflow at narrow width");
1946        assert!(output.iter().all(|line| line.text().width() <= 24));
1947        assert!(output.len() <= 1 + super::MAX_VISIBLE_PLAN_BODY_ROWS);
1948    }
1949
1950    #[test]
1951    fn plan_progress_is_bounded_and_semantic_without_color() {
1952        let cell = test_cell(CellContent::Plan(PlanCell::new(
1953            "Updated Plan",
1954            None,
1955            std::iter::once(PlanStep::new(PlanStepStatus::Completed, "Freeze gallery"))
1956                .chain(std::iter::once(PlanStep::new(
1957                    PlanStepStatus::InProgress,
1958                    "Port typed plan cells",
1959                )))
1960                .chain(std::iter::repeat_n(
1961                    PlanStep::new(PlanStepStatus::Pending, "Run regression matrix"),
1962                    14,
1963                ))
1964                .collect(),
1965            Some("Protocol projection remains disabled."),
1966        )));
1967        let themes = [
1968            Theme::default(),
1969            Theme::for_capabilities(TerminalCapabilities::from_environment(
1970                Some("dumb"),
1971                None,
1972                false,
1973                false,
1974            )),
1975        ];
1976
1977        for theme in themes {
1978            let output = render_test_node(&cell, 32, &theme);
1979            assert_eq!(output[0].text(), "• Updated Plan");
1980            assert!(output[1].text().starts_with("  [x] Freeze gallery"));
1981            assert!(output[2].text().starts_with("  [>] Port typed plan cells"));
1982            assert!(output[3].text().starts_with("  [ ] Run regression matrix"));
1983            assert!(
1984                !output[1].spans[0]
1985                    .style
1986                    .add_modifier
1987                    .contains(Modifier::CROSSED_OUT)
1988            );
1989            assert!(
1990                output[1].spans[1]
1991                    .style
1992                    .add_modifier
1993                    .contains(Modifier::CROSSED_OUT)
1994            );
1995            assert!(
1996                output[2].spans[1]
1997                    .style
1998                    .add_modifier
1999                    .contains(Modifier::BOLD)
2000            );
2001            assert!(output.last().unwrap().text().contains("plan rows"));
2002            assert!(output.iter().all(|line| line.text().width() <= 32));
2003            assert!(output.len() <= 1 + super::MAX_VISIBLE_PLAN_BODY_ROWS);
2004        }
2005        assert!(cell.raw_text().contains("[x] Freeze gallery"));
2006        assert!(cell.raw_text().contains("[>] Port typed plan cells"));
2007        assert!(cell.raw_text().contains("[ ] Run regression matrix"));
2008    }
2009
2010    #[test]
2011    fn queued_input_uses_a_narrow_tree_continuation() {
2012        let output = render_test_node(
2013            &test_cell(CellContent::QueuedInput(QueuedInputCell::new(
2014                QueuedInputKind::FollowUp,
2015                "verify CJK 宽度 after the active run",
2016            ))),
2017            20,
2018            &Theme::default(),
2019        );
2020
2021        assert_eq!(output[0].text(), "○ Queued follow-up");
2022        assert!(output[1].text().starts_with("  └ verify"));
2023        assert!(output.iter().all(|line| line.text().width() <= 20));
2024    }
2025
2026    #[test]
2027    fn notice_severities_keep_distinct_markers_safe_hints_and_width_bounds() {
2028        let theme = Theme::default();
2029        for (severity, marker, expected_style) in [
2030            (NoticeSeverity::Information, "•", theme.information),
2031            (NoticeSeverity::Warning, "!", theme.warning),
2032            (NoticeSeverity::Error, "■", theme.error),
2033        ] {
2034            let output = render_test_node(
2035                &test_cell(CellContent::Notice(NoticeCell::new(
2036                    NoticeKind::General,
2037                    severity,
2038                    "diagnostic\u{1b}[31m CJK 宽度内容",
2039                    Some("bounded supporting hint"),
2040                ))),
2041                16,
2042                &theme,
2043            );
2044
2045            assert!(output[0].text().starts_with(marker));
2046            assert_eq!(output[0].style(), expected_style);
2047            assert!(output.iter().all(|line| line.text().width() <= 16));
2048            assert!(
2049                output
2050                    .iter()
2051                    .all(|line| { !line.text().chars().any(char::is_control) })
2052            );
2053            assert!(output.iter().any(|line| line.text().starts_with("  └ ")));
2054            assert_eq!(output.last().unwrap().style(), theme.footer);
2055        }
2056    }
2057
2058    struct GalleryCase {
2059        name: &'static str,
2060        readiness: &'static str,
2061        cell: CellNode,
2062    }
2063
2064    struct GalleryProfile {
2065        name: &'static str,
2066        width: usize,
2067        height: usize,
2068        theme: Theme,
2069    }
2070
2071    #[test]
2072    fn codex_aligned_output_gallery_matches_all_terminal_profiles() {
2073        let profiles = gallery_profiles();
2074        let cases = gallery_cases();
2075        let mut actual = String::from(
2076            "# Tea TUI output gallery\n# Codex reference: 1836ae0612052137d0cabaff7807ff8314cee940\n",
2077        );
2078
2079        for profile in profiles {
2080            writeln!(
2081                actual,
2082                "\n## profile {} {}x{} theme-generation={}",
2083                profile.name, profile.width, profile.height, profile.theme.generation
2084            )
2085            .unwrap();
2086            for case in &cases {
2087                let lines = render_test_node(&case.cell, profile.width, &profile.theme);
2088                assert!(
2089                    lines.len() <= profile.height,
2090                    "{} exceeds {} rows in {}",
2091                    case.name,
2092                    profile.height,
2093                    profile.name
2094                );
2095                assert!(
2096                    lines
2097                        .iter()
2098                        .all(|line| line.text().width() <= profile.width),
2099                    "{} exceeds {} columns in {}: {:?}",
2100                    case.name,
2101                    profile.width,
2102                    profile.name,
2103                    lines.iter().map(RenderedLine::text).collect::<Vec<_>>()
2104                );
2105                writeln!(actual, "\n### {} [{}]", case.name, case.readiness).unwrap();
2106                writeln!(actual, "raw |{}|", snapshot_text(&case.cell.raw_text())).unwrap();
2107                let display = lines
2108                    .iter()
2109                    .map(RenderedLine::text)
2110                    .collect::<Vec<_>>()
2111                    .join("\n");
2112                writeln!(actual, "display |{}|", snapshot_text(&display)).unwrap();
2113                let styles = lines
2114                    .iter()
2115                    .map(line_style_signature)
2116                    .collect::<Vec<_>>()
2117                    .join(" || ");
2118                writeln!(actual, "styles |{styles}|").unwrap();
2119            }
2120        }
2121
2122        let snapshot_path = concat!(
2123            env!("CARGO_MANIFEST_DIR"),
2124            "/tests/fixtures/tui/output-gallery.snap"
2125        );
2126        if std::env::var_os("TEA_UPDATE_TUI_SNAPSHOTS").is_some() {
2127            std::fs::write(snapshot_path, &actual).unwrap();
2128        }
2129        let expected = std::fs::read_to_string(snapshot_path).unwrap();
2130        assert_eq!(actual, expected);
2131    }
2132
2133    #[test]
2134    fn output_gallery_freezes_the_full_regression_sign_off_matrix() {
2135        let cases = gallery_cases();
2136        let names = cases.iter().map(|case| case.name).collect::<Vec<_>>();
2137        for expected in [
2138            "lifecycle-proposed",
2139            "lifecycle-approval-pending",
2140            "lifecycle-failed",
2141            "lifecycle-interrupted",
2142            "lifecycle-uncertain",
2143            "lifecycle-queued",
2144            "empty-tool-result",
2145            "malformed-tool-detail",
2146            "hostile-cjk-emoji",
2147            "long-process-output",
2148        ] {
2149            assert!(
2150                names.contains(&expected),
2151                "regression gallery is missing {expected}"
2152            );
2153        }
2154
2155        let mut statuses = cases
2156            .iter()
2157            .filter_map(|case| match case.cell.content() {
2158                CellContent::Lifecycle(lifecycle) => Some(lifecycle.status()),
2159                _ => None,
2160            })
2161            .collect::<Vec<_>>();
2162        statuses.sort_unstable();
2163        statuses.dedup();
2164        assert_eq!(
2165            statuses,
2166            vec![
2167                LifecycleStatus::Proposed,
2168                LifecycleStatus::Requested,
2169                LifecycleStatus::ApprovalPending,
2170                LifecycleStatus::Running,
2171                LifecycleStatus::Succeeded,
2172                LifecycleStatus::Failed,
2173                LifecycleStatus::Interrupted,
2174                LifecycleStatus::Uncertain,
2175                LifecycleStatus::Queued,
2176            ]
2177        );
2178
2179        for case in cases {
2180            let raw = case.cell.raw_text();
2181            if case.name == "empty-tool-result" {
2182                assert!(raw.is_empty(), "empty canonical output must stay empty");
2183            } else {
2184                assert!(!raw.is_empty(), "{} has no raw fallback", case.name);
2185            }
2186            assert!(
2187                raw.chars()
2188                    .all(|character| character == '\n' || !character.is_control()),
2189                "{} raw fallback contains a terminal control: {raw:?}",
2190                case.name
2191            );
2192        }
2193    }
2194
2195    fn gallery_profiles() -> Vec<GalleryProfile> {
2196        let mut profiles = Vec::new();
2197        for (width, height) in [(40, 16), (80, 24), (120, 32)] {
2198            profiles.push(GalleryProfile {
2199                name: "default",
2200                width,
2201                height,
2202                theme: Theme::for_capabilities(TerminalCapabilities::from_environment(
2203                    Some("xterm-truecolor"),
2204                    Some("truecolor"),
2205                    false,
2206                    false,
2207                )),
2208            });
2209            profiles.push(GalleryProfile {
2210                name: "no-color",
2211                width,
2212                height,
2213                theme: Theme::for_capabilities(TerminalCapabilities::from_environment(
2214                    Some("xterm"),
2215                    None,
2216                    true,
2217                    false,
2218                )),
2219            });
2220            profiles.push(GalleryProfile {
2221                name: "reduced-motion",
2222                width,
2223                height,
2224                theme: Theme::for_capabilities(TerminalCapabilities::from_environment(
2225                    Some("xterm-truecolor"),
2226                    Some("truecolor"),
2227                    false,
2228                    true,
2229                )),
2230            });
2231        }
2232        profiles
2233    }
2234
2235    #[allow(clippy::too_many_lines)]
2236    fn gallery_cases() -> Vec<GalleryCase> {
2237        vec![
2238            gallery(
2239                "user-prompt",
2240                "supported",
2241                message(
2242                    MessageAuthor::User,
2243                    "Refactor the renderer and preserve CJK 宽度.",
2244                    OutputFormat::Plain,
2245                ),
2246            ),
2247            gallery(
2248                "assistant-response",
2249                "supported",
2250                message(
2251                    MessageAuthor::Assistant,
2252                    "## Result\n\n- Added typed cells\n- Preserved **Markdown** output",
2253                    OutputFormat::Markdown,
2254                ),
2255            ),
2256            gallery(
2257                "thinking-reasoning",
2258                "supported-observable-events-only",
2259                CellContent::Reasoning(ReasoningCell::new(
2260                    "Checking the projection and terminal width constraints.",
2261                    false,
2262                )),
2263            ),
2264            gallery(
2265                "run-activity",
2266                "supported",
2267                lifecycle(
2268                    LifecycleKind::RunActivity,
2269                    "Working",
2270                    Some("renderer migration"),
2271                    LifecycleStatus::Running,
2272                    vec![detail(TimelineDetailKind::Progress, Some("elapsed"), "12s")],
2273                    2,
2274                ),
2275            ),
2276            gallery(
2277                "generic-tool-call",
2278                "supported",
2279                lifecycle(
2280                    LifecycleKind::ToolCall,
2281                    "Requested",
2282                    Some("custom_tool workspace/index"),
2283                    LifecycleStatus::Requested,
2284                    Vec::new(),
2285                    0,
2286                ),
2287            ),
2288            gallery(
2289                "lifecycle-proposed",
2290                "supported",
2291                lifecycle(
2292                    LifecycleKind::ToolCall,
2293                    "Proposed",
2294                    Some("custom_tool workspace/index"),
2295                    LifecycleStatus::Proposed,
2296                    Vec::new(),
2297                    0,
2298                ),
2299            ),
2300            gallery(
2301                "lifecycle-approval-pending",
2302                "supported",
2303                lifecycle(
2304                    LifecycleKind::ToolCall,
2305                    "Waiting for approval",
2306                    Some("write_text_file /workspace/notes.txt"),
2307                    LifecycleStatus::ApprovalPending,
2308                    Vec::new(),
2309                    0,
2310                ),
2311            ),
2312            gallery(
2313                "tool-arguments-progress-result",
2314                "supported-generic-fallback",
2315                lifecycle(
2316                    LifecycleKind::ToolCall,
2317                    "Running",
2318                    Some("custom_tool workspace/index"),
2319                    LifecycleStatus::Running,
2320                    vec![
2321                        detail(
2322                            TimelineDetailKind::Metadata,
2323                            Some("arguments"),
2324                            r#"{"path":"src","depth":3}"#,
2325                        ),
2326                        detail(
2327                            TimelineDetailKind::Progress,
2328                            Some("progress"),
2329                            "24/80 files indexed",
2330                        ),
2331                    ],
2332                    2,
2333                ),
2334            ),
2335            gallery(
2336                "lifecycle-failed",
2337                "supported",
2338                lifecycle(
2339                    LifecycleKind::ToolCall,
2340                    "Failed",
2341                    Some("cargo test -p tea-cli --test tui"),
2342                    LifecycleStatus::Failed,
2343                    vec![detail(
2344                        TimelineDetailKind::Error,
2345                        Some("exit"),
2346                        "101 after 1.42s",
2347                    )],
2348                    0,
2349                ),
2350            ),
2351            gallery(
2352                "lifecycle-interrupted",
2353                "supported",
2354                lifecycle(
2355                    LifecycleKind::ToolCall,
2356                    "Interrupted",
2357                    Some("cargo test"),
2358                    LifecycleStatus::Interrupted,
2359                    vec![detail(
2360                        TimelineDetailKind::Metadata,
2361                        Some("reason"),
2362                        "cancelled by user",
2363                    )],
2364                    0,
2365                ),
2366            ),
2367            gallery(
2368                "lifecycle-uncertain",
2369                "supported",
2370                lifecycle(
2371                    LifecycleKind::ToolCall,
2372                    "Interrupted",
2373                    Some("remote deploy"),
2374                    LifecycleStatus::Uncertain,
2375                    vec![detail(
2376                        TimelineDetailKind::Metadata,
2377                        Some("outcome"),
2378                        "unknown after disconnect",
2379                    )],
2380                    0,
2381                ),
2382            ),
2383            gallery(
2384                "lifecycle-queued",
2385                "supported",
2386                lifecycle(
2387                    LifecycleKind::ToolCall,
2388                    "Queued",
2389                    Some("follow-up validation"),
2390                    LifecycleStatus::Queued,
2391                    Vec::new(),
2392                    0,
2393                ),
2394            ),
2395            gallery(
2396                "empty-tool-result",
2397                "supported",
2398                result(
2399                    "Returned",
2400                    Some("custom_tool"),
2401                    "",
2402                    OutputFormat::Plain,
2403                    false,
2404                ),
2405            ),
2406            gallery(
2407                "malformed-tool-detail",
2408                "supported-generic-fallback",
2409                lifecycle(
2410                    LifecycleKind::ToolCall,
2411                    "Ran",
2412                    Some("custom_tool"),
2413                    LifecycleStatus::Succeeded,
2414                    vec![detail(
2415                        TimelineDetailKind::Metadata,
2416                        Some("arguments"),
2417                        "{\"path\":\u{1b}[31m",
2418                    )],
2419                    0,
2420                ),
2421            ),
2422            gallery(
2423                "hostile-cjk-emoji",
2424                "supported",
2425                notice(
2426                    NoticeSeverity::Warning,
2427                    "控制字符 \u{1b}[31m 保持可见,emoji 👩🏽‍💻 不破坏宽度",
2428                    Some("a-very-long-unbroken-token-0123456789-abcdefghijklmnopqrstuvwxyz"),
2429                ),
2430            ),
2431            gallery(
2432                "long-process-output",
2433                "supported-bounded-preview",
2434                result(
2435                    "Returned",
2436                    Some("long-running-command"),
2437                    &(1..=14)
2438                        .map(|line| format!("line {line} {}", "wide-output-".repeat(4)))
2439                        .collect::<Vec<_>>()
2440                        .join("\n"),
2441                    OutputFormat::Terminal,
2442                    false,
2443                ),
2444            ),
2445            gallery(
2446                "shell-command",
2447                "target-generic-until-command-metadata",
2448                lifecycle(
2449                    LifecycleKind::ToolCall,
2450                    "Ran",
2451                    Some("cargo test -p tea-cli --test tui"),
2452                    LifecycleStatus::Succeeded,
2453                    vec![
2454                        detail(TimelineDetailKind::Output, None, "39 passed; 0 failed"),
2455                        detail(TimelineDetailKind::Metadata, Some("exit"), "0 in 1.42s"),
2456                    ],
2457                    0,
2458                ),
2459            ),
2460            gallery(
2461                "background-terminal",
2462                "protocol-gated",
2463                lifecycle(
2464                    LifecycleKind::ToolCall,
2465                    "Waited",
2466                    Some("cargo test"),
2467                    LifecycleStatus::Running,
2468                    vec![detail(
2469                        TimelineDetailKind::Metadata,
2470                        Some("stdin"),
2471                        "waiting for process output",
2472                    )],
2473                    2,
2474                ),
2475            ),
2476            gallery(
2477                "file-search-list",
2478                "protocol-gated-generic-fallback",
2479                lifecycle(
2480                    LifecycleKind::ToolCall,
2481                    "Read",
2482                    Some("crates/tea-cli/src/tui"),
2483                    LifecycleStatus::Succeeded,
2484                    vec![detail(
2485                        TimelineDetailKind::Output,
2486                        None,
2487                        "presentation.rs, render.rs, theme.rs",
2488                    )],
2489                    0,
2490                ),
2491            ),
2492            gallery(
2493                "web-search",
2494                "protocol-gated-generic-fallback",
2495                lifecycle(
2496                    LifecycleKind::ToolCall,
2497                    "Searched the web for",
2498                    Some("ratatui styled wrapping"),
2499                    LifecycleStatus::Succeeded,
2500                    Vec::new(),
2501                    0,
2502                ),
2503            ),
2504            gallery(
2505                "mcp-lifecycle",
2506                "target-generic-until-mcp-call-events",
2507                lifecycle(
2508                    LifecycleKind::ToolCall,
2509                    "Called",
2510                    Some("docs.search query=ratatui"),
2511                    LifecycleStatus::Succeeded,
2512                    vec![detail(
2513                        TimelineDetailKind::Output,
2514                        None,
2515                        "Found styling guidance in styles.md",
2516                    )],
2517                    0,
2518                ),
2519            ),
2520            gallery(
2521                "fenced-code",
2522                "supported-semantic-style",
2523                message(
2524                    MessageAuthor::Assistant,
2525                    "```rust\nfn render() -> bool { true }\n```",
2526                    OutputFormat::Markdown,
2527                ),
2528            ),
2529            gallery(
2530                "process-code-output",
2531                "supported-generic-fallback",
2532                result(
2533                    "Returned",
2534                    Some("cargo test"),
2535                    "stdout: 39 passed\nstderr: warning: retrying",
2536                    OutputFormat::Terminal,
2537                    false,
2538                ),
2539            ),
2540            gallery(
2541                "plan-proposal",
2542                "renderer-ready-protocol-gated",
2543                CellContent::Plan(PlanCell::new(
2544                    "Proposed Plan",
2545                    Some(
2546                        "## Renderer migration\n\n1. Introduce typed cells\n2. Port output grammar\n3. Run PTY tests",
2547                    ),
2548                    Vec::new(),
2549                    None,
2550                )),
2551            ),
2552            gallery(
2553                "plan-progress",
2554                "renderer-ready-protocol-gated",
2555                CellContent::Plan(PlanCell::new(
2556                    "Updated Plan",
2557                    None,
2558                    vec![
2559                        PlanStep::new(PlanStepStatus::Completed, "Freeze gallery"),
2560                        PlanStep::new(PlanStepStatus::InProgress, "Port tool cells"),
2561                        PlanStep::new(PlanStepStatus::Pending, "Run PTY tests"),
2562                    ],
2563                    Some("Protocol projection remains disabled."),
2564                )),
2565            ),
2566            gallery(
2567                "patch-diff",
2568                "protocol-gated-generic-fallback",
2569                result(
2570                    "Updated",
2571                    Some("src/render.rs"),
2572                    "- label: text\n+ • Ran tool\n+   └ output",
2573                    OutputFormat::Terminal,
2574                    false,
2575                ),
2576            ),
2577            gallery(
2578                "approval",
2579                "supported-modal-and-durable-fallback",
2580                decision(
2581                    "Approval required",
2582                    "write_text_file",
2583                    DecisionStatus::Pending,
2584                    vec![
2585                        detail(TimelineDetailKind::Metadata, Some("target"), "native"),
2586                        detail(TimelineDetailKind::Metadata, Some("effects"), "fs.write"),
2587                    ],
2588                ),
2589            ),
2590            gallery(
2591                "error",
2592                "supported",
2593                notice(
2594                    NoticeSeverity::Error,
2595                    "Tool execution failed",
2596                    Some("permission denied"),
2597                ),
2598            ),
2599            gallery(
2600                "warning",
2601                "supported-typed-callers",
2602                notice(
2603                    NoticeSeverity::Warning,
2604                    "Session is approaching its context limit",
2605                    None,
2606                ),
2607            ),
2608            gallery(
2609                "information",
2610                "supported",
2611                notice(
2612                    NoticeSeverity::Information,
2613                    "Connection restored",
2614                    Some("session state reloaded"),
2615                ),
2616            ),
2617            gallery(
2618                "queued-steering-follow-up",
2619                "supported",
2620                CellContent::QueuedInput(QueuedInputCell::new(
2621                    QueuedInputKind::Steering,
2622                    "also update the narrow-terminal tests",
2623                )),
2624            ),
2625            gallery(
2626                "image-artifact",
2627                "protocol-gated-textual-fallback",
2628                result(
2629                    "Produced",
2630                    Some("screenshot.png"),
2631                    "image/png, 1280x720",
2632                    OutputFormat::Plain,
2633                    false,
2634                ),
2635            ),
2636            gallery(
2637                "hook",
2638                "protocol-gated-generic-fallback",
2639                lifecycle(
2640                    LifecycleKind::ToolCall,
2641                    "Ran hook",
2642                    Some("post-format"),
2643                    LifecycleStatus::Succeeded,
2644                    vec![detail(
2645                        TimelineDetailKind::Output,
2646                        None,
2647                        "cargo fmt --check",
2648                    )],
2649                    0,
2650                ),
2651            ),
2652            gallery(
2653                "multi-agent",
2654                "runtime-gated-generic-fallback",
2655                lifecycle(
2656                    LifecycleKind::ToolCall,
2657                    "Completed task",
2658                    Some("agent/review renderer audit"),
2659                    LifecycleStatus::Succeeded,
2660                    Vec::new(),
2661                    0,
2662                ),
2663            ),
2664        ]
2665    }
2666
2667    fn gallery(name: &'static str, readiness: &'static str, content: CellContent) -> GalleryCase {
2668        GalleryCase {
2669            name,
2670            readiness,
2671            cell: test_cell(content),
2672        }
2673    }
2674
2675    fn lifecycle(
2676        kind: LifecycleKind,
2677        action: &str,
2678        target: Option<&str>,
2679        status: LifecycleStatus,
2680        details: Vec<TimelineDetail>,
2681        tick: u64,
2682    ) -> CellContent {
2683        CellContent::Lifecycle(LifecycleCell::new(
2684            kind, action, target, status, details, true, tick,
2685        ))
2686    }
2687
2688    fn decision(
2689        action: &str,
2690        subject: &str,
2691        status: DecisionStatus,
2692        details: Vec<TimelineDetail>,
2693    ) -> CellContent {
2694        CellContent::Decision(DecisionCell::new(action, subject, status, details))
2695    }
2696
2697    fn notice(severity: NoticeSeverity, message: &str, hint: Option<&str>) -> CellContent {
2698        CellContent::Notice(NoticeCell::new(
2699            NoticeKind::General,
2700            severity,
2701            message,
2702            hint,
2703        ))
2704    }
2705
2706    fn detail(kind: TimelineDetailKind, label: Option<&str>, text: &str) -> TimelineDetail {
2707        TimelineDetail::new(kind, label, text)
2708    }
2709
2710    fn snapshot_text(text: &str) -> String {
2711        text.replace('\\', "\\\\")
2712            .replace('|', "\\|")
2713            .replace('\n', "\\n")
2714    }
2715
2716    fn style_signature(style: Style) -> String {
2717        let foreground = style
2718            .fg
2719            .map_or_else(|| "-".to_owned(), |color| format!("{color:?}"));
2720        let background = style
2721            .bg
2722            .map_or_else(|| "-".to_owned(), |color| format!("{color:?}"));
2723        format!(
2724            "{foreground}/{background}/{:?}/{:?}",
2725            style.add_modifier, style.sub_modifier
2726        )
2727    }
2728
2729    fn line_style_signature(line: &RenderedLine) -> String {
2730        let mut signature = style_signature(line.style());
2731        if !line.spans.is_empty() {
2732            let spans = line
2733                .spans
2734                .iter()
2735                .map(|span| style_signature(span.style))
2736                .collect::<Vec<_>>()
2737                .join(", ");
2738            write!(signature, " spans=[{spans}]").unwrap();
2739        }
2740        signature
2741    }
2742}