Skip to main content

mermaid_cli/render/widgets/
chat.rs

1use std::hash::{Hash, Hasher};
2
3use ratatui::{
4    buffer::Buffer,
5    layout::Rect,
6    style::{Modifier, Style},
7    text::{Line, Span},
8    widgets::{
9        Block, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Widget,
10    },
11};
12use rustc_hash::FxHashMap;
13use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
14
15use crate::domain::{ActionDetails, ActionDisplay, ActionResult, format_compact_count};
16use crate::models::ChatMessageKind;
17use crate::models::{ChatMessage, MessageRole};
18use crate::render::diff::{DiffLineKind, parse_diff_line};
19use crate::render::markdown::parse_markdown;
20use crate::render::theme::Theme;
21use crate::utils::format_relative_timestamp;
22
23/// Entry in the click map: maps a content line to an image in chat history
24#[derive(Debug, Clone)]
25pub struct ImageClickTarget {
26    /// Index into session_state.messages
27    pub message_index: usize,
28    /// Index into that message's images vec
29    pub image_index: usize,
30}
31
32/// State for the chat widget
33#[derive(Debug, Clone)]
34pub struct ChatState {
35    /// Manual scroll offset (only used when is_user_scrolling = true)
36    scroll_offset: u16,
37    /// Whether user is manually scrolling (not following bottom)
38    is_user_scrolling: bool,
39    /// Click map: content line number → image target (rebuilt every render)
40    pub image_click_map: Vec<(u16, ImageClickTarget)>,
41    /// Scroll position used in last render (for coordinate mapping)
42    pub last_scroll_position: u16,
43    /// Chat area rect from last render
44    pub last_chat_area: Option<(u16, u16, u16, u16)>, // (x, y, width, height)
45    /// Active drag-selection in CONTENT coordinates: `(anchor, cursor)` where
46    /// each is `(content_line, col_cells)`. Highlight + copy derive from it.
47    selection: Option<((usize, usize), (usize, usize))>,
48    /// Plain text of each rendered content row, captured every frame so the
49    /// selection can be extracted by display-cell range. Indexed by content
50    /// line (the same index the selection uses).
51    last_rendered_rows: Vec<String>,
52}
53
54impl ChatState {
55    /// Create a new chat state (starts in auto-follow mode)
56    pub fn new() -> Self {
57        Self {
58            scroll_offset: 0,
59            is_user_scrolling: false,
60            image_click_map: Vec::new(),
61            last_scroll_position: 0,
62            last_chat_area: None,
63            selection: None,
64            last_rendered_rows: Vec::new(),
65        }
66    }
67
68    /// Get the scroll position for rendering
69    /// scroll_offset represents distance from bottom, convert to ratatui scroll position
70    pub fn get_scroll_position(&self, content_height: u16, viewport_height: u16) -> u16 {
71        let max_scroll = content_height.saturating_sub(viewport_height);
72        if self.is_user_scrolling {
73            // Manual scroll: convert "distance from bottom" to scroll position
74            // scroll_offset=0 → show bottom (max_scroll), scroll_offset=max → show top (0)
75            let capped_offset = self.scroll_offset.min(max_scroll);
76            max_scroll.saturating_sub(capped_offset)
77        } else {
78            // Auto-scroll: show bottom of content
79            max_scroll
80        }
81    }
82
83    /// Scroll viewport up (shows older messages further from bottom)
84    pub fn scroll_up(&mut self, amount: u16) {
85        self.is_user_scrolling = true;
86        self.scroll_offset = self.scroll_offset.saturating_add(amount);
87        // A selection's content-line anchors don't track scrolling; drop it
88        // rather than leave a highlight stranded on the wrong rows.
89        self.selection = None;
90    }
91
92    /// Scroll viewport down (shows newer messages closer to bottom)
93    /// Automatically resumes auto-scroll when reaching the bottom
94    pub fn scroll_down(&mut self, amount: u16) {
95        self.scroll_offset = self.scroll_offset.saturating_sub(amount);
96        if self.scroll_offset == 0 {
97            // Reached bottom — resume auto-follow mode
98            self.is_user_scrolling = false;
99        }
100        self.selection = None;
101    }
102
103    /// Force resume auto-scroll mode (jump to bottom)
104    pub fn resume_auto_scroll(&mut self) {
105        self.is_user_scrolling = false;
106        self.scroll_offset = 0;
107    }
108
109    /// Check if user is manually scrolling (not following bottom)
110    pub fn is_manually_scrolling(&self) -> bool {
111        self.is_user_scrolling
112    }
113
114    /// Find an image click target at the given screen coordinates.
115    /// Returns Some((message_index, image_index)) if an image indicator was clicked.
116    pub fn find_image_at_screen_pos(&self, screen_row: u16) -> Option<&ImageClickTarget> {
117        let (_, area_y, _, area_height) = self.last_chat_area?;
118
119        // Check if click is within chat area
120        if screen_row < area_y || screen_row >= area_y + area_height {
121            return None;
122        }
123
124        // Convert screen row to content line
125        let viewport_row = screen_row - area_y;
126        let content_line = viewport_row + self.last_scroll_position;
127
128        // Look up in click map
129        self.image_click_map
130            .iter()
131            .find(|(line, _)| *line == content_line)
132            .map(|(_, target)| target)
133    }
134
135    /// Map a screen `(row, col)` to content `(line, col_cells)`, or `None`
136    /// when the point is outside the chat area. `col` is clamped to the chat
137    /// area's left edge so a drag past the gutter still maps to column 0.
138    fn screen_to_content(&self, screen_row: u16, screen_col: u16) -> Option<(usize, usize)> {
139        let (area_x, area_y, _, area_height) = self.last_chat_area?;
140        if screen_row < area_y || screen_row >= area_y + area_height {
141            return None;
142        }
143        let content_line = (screen_row - area_y) as usize + self.last_scroll_position as usize;
144        let col = screen_col.saturating_sub(area_x) as usize;
145        Some((content_line, col))
146    }
147
148    /// Begin a drag selection at the given screen position (mouse-down).
149    /// Anchors and cursor both start here; a plain click with no drag selects
150    /// nothing.
151    pub fn begin_selection(&mut self, screen_row: u16, screen_col: u16) {
152        self.selection = self
153            .screen_to_content(screen_row, screen_col)
154            .map(|p| (p, p));
155    }
156
157    /// Extend the in-progress selection to the given screen position (drag).
158    pub fn update_selection(&mut self, screen_row: u16, screen_col: u16) {
159        if let Some((anchor, _)) = self.selection
160            && let Some(cursor) = self.screen_to_content(screen_row, screen_col)
161        {
162            self.selection = Some((anchor, cursor));
163        }
164    }
165
166    /// Drop any active selection (and its highlight).
167    pub fn clear_selection(&mut self) {
168        self.selection = None;
169    }
170
171    /// Extract the currently-selected text from the last rendered frame, or
172    /// `None` if there's no selection or it's empty (e.g. a plain click).
173    /// Walks the retained per-row text and slices each row by display cells so
174    /// CJK / wide glyphs are never split mid-cell.
175    pub fn selected_text(&self) -> Option<String> {
176        let (a, b) = self.selection?;
177        let (start, end) = if a <= b { (a, b) } else { (b, a) };
178        if self.last_rendered_rows.is_empty() {
179            return None;
180        }
181        let last = self.last_rendered_rows.len() - 1;
182        let (start_line, start_col) = (start.0.min(last), start.1);
183        let (end_line, end_col) = (end.0.min(last), end.1);
184
185        let mut out = String::new();
186        for line in start_line..=end_line {
187            let row = &self.last_rendered_rows[line];
188            let c0 = if line == start_line { start_col } else { 0 };
189            let c1 = if line == end_line {
190                end_col
191            } else {
192                usize::MAX
193            };
194            let mut piece = slice_by_cells(row, c0, c1).to_string();
195            // Drop the rendered left margin (the "● "/"  " role/continuation
196            // prefix — up to SELECT_MARGIN_CELLS cells of spaces) so copied
197            // text is clean. Only spaces inside the margin zone [c0, MARGIN)
198            // are removed, so a code line's own indentation is preserved.
199            let mut margin = SELECT_MARGIN_CELLS.saturating_sub(c0);
200            while margin > 0 && piece.starts_with(' ') {
201                piece.remove(0);
202                margin -= 1;
203            }
204            out.push_str(piece.trim_end());
205            if line != end_line {
206                out.push('\n');
207            }
208        }
209        if out.is_empty() { None } else { Some(out) }
210    }
211}
212
213/// Display-cell width of the role/continuation left margin ("● " or "  ")
214/// that the renderer prepends to chat content lines. Stripped from copied
215/// selections so the clipboard gets clean text.
216const SELECT_MARGIN_CELLS: usize = 2;
217
218/// Hard-wrap a pre-formatted (code) line at `width` display cells, preserving
219/// every glyph (including whitespace) and each span's style. Continuation rows
220/// get a `indent`-space hanging indent. Unlike `wrap_styled_line` this never
221/// collapses runs of spaces, so code indentation and alignment survive.
222fn wrap_preformatted(line: Line<'static>, width: usize, indent: usize) -> Vec<Line<'static>> {
223    if width == 0 {
224        return vec![line];
225    }
226    let total: usize = line.spans.iter().map(|s| s.content.width()).sum();
227    if total <= width {
228        return vec![line];
229    }
230
231    let base = line.style;
232    let mut out: Vec<Line<'static>> = Vec::new();
233    let mut cur: Vec<Span<'static>> = Vec::new();
234    let mut cur_w = 0usize;
235    let mut on_first = true;
236
237    for span in line.spans {
238        let style = span.style;
239        let mut buf = String::new();
240        for ch in span.content.chars() {
241            let cw = ch.width().unwrap_or(0);
242            // Break before this char if it would overflow and the current row
243            // already holds real content (beyond the continuation indent).
244            let floor = if on_first { 0 } else { indent };
245            if cur_w + cw > width && cur_w > floor {
246                if !buf.is_empty() {
247                    cur.push(Span::styled(std::mem::take(&mut buf), style));
248                }
249                out.push(Line::from(std::mem::take(&mut cur)).style(base));
250                on_first = false;
251                cur.push(Span::styled(" ".repeat(indent), base));
252                cur_w = indent;
253            }
254            buf.push(ch);
255            cur_w += cw;
256        }
257        if !buf.is_empty() {
258            cur.push(Span::styled(buf, style));
259        }
260    }
261    if !cur.is_empty() {
262        out.push(Line::from(cur).style(base));
263    }
264    if out.is_empty() {
265        vec![Line::from("").style(base)]
266    } else {
267        out
268    }
269}
270
271/// Byte offset in `s` at the start of display-cell `target` (clamped to
272/// `s.len()`). A wide glyph straddling `target` is kept whole on the right
273/// side, so slicing never lands mid-character.
274fn byte_at_cell(s: &str, target: usize) -> usize {
275    if target == 0 {
276        return 0;
277    }
278    let mut width = 0usize;
279    for (idx, ch) in s.char_indices() {
280        if width >= target {
281            return idx;
282        }
283        width += ch.width().unwrap_or(0);
284    }
285    s.len()
286}
287
288/// Slice `s` to the display-cell range `[c0, c1)`.
289fn slice_by_cells(s: &str, c0: usize, c1: usize) -> &str {
290    let start = byte_at_cell(s, c0);
291    let end = byte_at_cell(s, c1).max(start);
292    &s[start..end]
293}
294
295/// Pad `s` on the right with spaces until it spans `cells` display columns,
296/// measured with `UnicodeWidthStr::width` (not chars/bytes) so a CJK/emoji row's
297/// background bar fills to the true visual edge instead of falling short (#101).
298/// Never truncates — an already-too-wide `s` is returned unchanged.
299fn pad_to_cells(s: &str, cells: usize) -> String {
300    let w = s.width();
301    if w >= cells {
302        return s.to_string();
303    }
304    let mut out = String::with_capacity(s.len() + (cells - w));
305    out.push_str(s);
306    out.push_str(&" ".repeat(cells - w));
307    out
308}
309
310/// First-line spacing for a user message: the run of spaces before the
311/// right-aligned timestamp. All inputs are display-cell widths so CJK/emoji
312/// align correctly (#104). Returns `min_gap` plus whatever slack remains to
313/// push the timestamp to `content_width`'s right edge.
314fn user_timestamp_padding(
315    role_prefix_width: usize,
316    text_width: usize,
317    timestamp_width: usize,
318    min_gap: usize,
319    content_width: usize,
320) -> usize {
321    let total_used = role_prefix_width + text_width + min_gap + timestamp_width;
322    min_gap + content_width.saturating_sub(total_used)
323}
324
325/// The plain text of a rendered line (spans concatenated, styles dropped).
326fn line_plain_text(line: &Line) -> String {
327    line.spans.iter().map(|s| s.content.as_ref()).collect()
328}
329
330/// Apply `hl` (merged onto each span's existing style) to display cells
331/// `[c0, c1)` of `line`, splitting spans at the selection boundaries so the
332/// highlight lands on exactly the selected glyphs.
333fn highlight_line_cells(line: &mut Line<'static>, c0: usize, c1: usize, hl: Style) {
334    let mut new_spans: Vec<Span<'static>> = Vec::with_capacity(line.spans.len() + 2);
335    let mut width = 0usize;
336    for span in line.spans.drain(..) {
337        let span_w = span.content.width();
338        let (span_start, span_end) = (width, width + span_w);
339        width = span_end;
340
341        let ov0 = c0.max(span_start);
342        let ov1 = c1.min(span_end);
343        if ov1 <= ov0 {
344            new_spans.push(span); // no overlap with the selection
345            continue;
346        }
347
348        let s = span.content.as_ref();
349        let b0 = byte_at_cell(s, ov0 - span_start);
350        let b1 = byte_at_cell(s, ov1 - span_start);
351        if b0 > 0 {
352            new_spans.push(Span::styled(s[..b0].to_string(), span.style));
353        }
354        new_spans.push(Span::styled(s[b0..b1].to_string(), span.style.patch(hl)));
355        if b1 < s.len() {
356            new_spans.push(Span::styled(s[b1..].to_string(), span.style));
357        }
358    }
359    line.spans = new_spans;
360}
361
362impl Default for ChatState {
363    fn default() -> Self {
364        Self::new()
365    }
366}
367
368/// Props for ChatWidget
369pub struct ChatWidget<'a> {
370    pub messages: &'a [ChatMessage],
371    pub theme: &'a Theme,
372    /// Shared markdown parse cache: content hash → parsed lines.
373    pub markdown_cache: &'a mut FxHashMap<u64, Vec<Line<'static>>>,
374    pub show_reasoning: bool,
375}
376
377impl<'a> StatefulWidget for ChatWidget<'a> {
378    type State = ChatState;
379
380    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
381        let mut lines: Vec<Line<'static>> = Vec::new();
382
383        // Code-block lines are tagged with this background; computed once so
384        // the per-message render loop and the markdown cache key can use it.
385        let code_bg = self.theme.colors.code_background.to_color();
386        let theme_seed = {
387            let mut h = rustc_hash::FxHasher::default();
388            self.theme.colors.foreground.to_color().hash(&mut h);
389            code_bg.hash(&mut h);
390            self.theme.colors.header.to_color().hash(&mut h);
391            h.finish()
392        };
393
394        // Reserve the rightmost column as a scrollbar gutter so the bar never
395        // paints over text. All content wrapping/rendering uses `content_area`.
396        let gutter: u16 = if area.width > 4 { 1 } else { 0 };
397        let content_width = area.width.saturating_sub(gutter);
398        let content_area = Rect {
399            width: content_width,
400            ..area
401        };
402
403        // Clear click map for this render pass
404        state.image_click_map.clear();
405        state.last_chat_area = Some((area.x, area.y, area.width, area.height));
406
407        let mut hidden_reasoning_notice_shown = false;
408
409        for (idx, msg) in self.messages.iter().enumerate() {
410            // Skip Tool messages - they're internal to the agent loop and their
411            // content is already displayed inline in the assistant's action blocks
412            if matches!(msg.role, MessageRole::Tool) {
413                continue;
414            }
415
416            if matches!(msg.kind, ChatMessageKind::ContextCheckpoint) {
417                if let Some(event_lines) = render_context_checkpoint_event(msg, self.theme) {
418                    lines.extend(event_lines);
419                    lines.push(Line::from(""));
420                }
421                continue;
422            }
423
424            let (role_prefix, role_color) = match msg.role {
425                MessageRole::User => (">", ratatui::style::Color::White),
426                MessageRole::Assistant => ("●", ratatui::style::Color::White),
427                MessageRole::System => ("●", self.theme.colors.system_message.to_color()),
428                MessageRole::Tool => unreachable!("Tool messages filtered above"),
429            };
430
431            if matches!(msg.role, MessageRole::Assistant) {
432                // Render thinking block if present
433                if let Some(ref thinking) = msg.thinking {
434                    // Skip rendering if thinking content is empty or literal "None"
435                    let thinking_trimmed = thinking.trim();
436                    if thinking_trimmed.is_empty()
437                        || thinking_trimmed == "None"
438                        || thinking_trimmed == "none"
439                    {
440                        // Don't render empty/null thinking blocks
441                    } else if self.show_reasoning {
442                        // Add "Thinking..." header in italic and dimmed with grayed white dot
443                        lines.push(Line::from(vec![
444                            Span::styled("● ", Style::new().fg(ratatui::style::Color::DarkGray)),
445                            Span::styled(
446                                "Thinking...",
447                                Style::new()
448                                    .fg(self.theme.colors.text_secondary.to_color())
449                                    .italic()
450                                    .dim(),
451                            ),
452                        ]));
453
454                        // Render thinking content with proper wrapping (2-space hanging indent)
455                        let wrapped = wrap_text_with_indent(
456                            thinking,
457                            content_width as usize,
458                            2, // first line indent (2 spaces)
459                            2, // continuation indent (2 spaces)
460                        );
461                        for wrapped_line in wrapped {
462                            lines.push(Line::from(Span::styled(
463                                wrapped_line,
464                                Style::new()
465                                    .fg(self.theme.colors.text_secondary.to_color())
466                                    .italic()
467                                    .dim(),
468                            )));
469                        }
470
471                        // Add blank line after thinking block
472                        lines.push(Line::from(""));
473                    } else if !hidden_reasoning_notice_shown {
474                        hidden_reasoning_notice_shown = true;
475                        let marker = if msg.content.trim().is_empty() && msg.actions.is_empty() {
476                            "Reasoning-only response hidden (/visible-reasoning on to show)"
477                        } else {
478                            "Reasoning hidden (/visible-reasoning on to show)"
479                        };
480                        lines.push(Line::from(vec![
481                            Span::styled("● ", Style::new().fg(ratatui::style::Color::DarkGray)),
482                            Span::styled(
483                                marker,
484                                Style::new()
485                                    .fg(self.theme.colors.text_secondary.to_color())
486                                    .italic()
487                                    .dim(),
488                            ),
489                        ]));
490                        // Always separate the placeholder from whatever follows
491                        // (tool actions or the visible answer) with one blank
492                        // line — the same gap every other block gets. Without
493                        // this, a "thought, then called a tool" turn (empty
494                        // content + actions) rendered the placeholder flush
495                        // against the first "● Bash(…)" line.
496                        lines.push(Line::from(""));
497                        if msg.content.trim().is_empty() && msg.actions.is_empty() {
498                            continue;
499                        }
500                    } else if msg.content.trim().is_empty() && msg.actions.is_empty() {
501                        continue;
502                    }
503                }
504
505                // With tool calling, message content is just text (no embedded action blocks)
506                // Use cached parsed markdown when available (avoids re-parsing
507                // every frame). The theme is folded into the key so a theme
508                // switch can't serve stale-colored cached lines.
509                let mut hasher = rustc_hash::FxHasher::default();
510                msg.content.hash(&mut hasher);
511                theme_seed.hash(&mut hasher);
512                let cache_key = hasher.finish();
513                let parsed_lines = if let Some(cached) = self.markdown_cache.get(&cache_key) {
514                    cached.clone()
515                } else {
516                    let parsed = parse_markdown(&msg.content, self.theme);
517                    self.markdown_cache.insert(cache_key, parsed.clone());
518                    if self.markdown_cache.len() > crate::constants::MARKDOWN_CACHE_MAX_ENTRIES {
519                        self.markdown_cache.clear();
520                        self.markdown_cache.insert(cache_key, parsed.clone());
521                    }
522                    parsed
523                };
524
525                for (line_idx, parsed_line) in parsed_lines.into_iter().enumerate() {
526                    // Code-block lines are tagged with the code background on
527                    // their base style (see markdown::parse_markdown). They're
528                    // pre-formatted: don't word-wrap (that collapses
529                    // indentation) — let the Paragraph clip overflow instead.
530                    let preformatted = parsed_line.style.bg == Some(code_bg);
531                    let base_style = parsed_line.style;
532
533                    // Add role indicator to first line or 2-space margin to others.
534                    let mut spans = if line_idx == 0 {
535                        vec![Span::styled(
536                            format!("{} ", role_prefix),
537                            Style::new().fg(role_color).bold(),
538                        )]
539                    } else {
540                        vec![Span::raw("  ")]
541                    };
542                    spans.extend(parsed_line.spans);
543                    let new_line = Line::from(spans).style(base_style);
544
545                    if preformatted {
546                        // Code: hard-wrap preserving indentation (don't
547                        // word-collapse) so wide lines stay readable.
548                        lines.extend(wrap_preformatted(new_line, content_width as usize, 2));
549                    } else {
550                        lines.extend(wrap_styled_line(new_line, content_width as usize, 2));
551                    }
552                }
553
554                // Render all actions at the end of the message
555                if !msg.actions.is_empty() {
556                    // Add blank line between text content and actions
557                    if !msg.content.trim().is_empty() {
558                        lines.push(Line::from(""));
559                    }
560                    render_actions(&msg.actions, &mut lines, self.theme, content_width as usize);
561                }
562            } else {
563                // For User messages: format timestamp and display on right edge
564                let formatted_timestamp = format_relative_timestamp(msg.timestamp);
565                // Display cells, not bytes — a CJK/emoji timestamp (or message)
566                // would otherwise mis-reserve space and push the right-aligned
567                // timestamp off its column (#104).
568                let timestamp_width = formatted_timestamp.width();
569                let min_gap = 3; // minimum spaces between text and timestamp
570
571                // Content is clean — timestamps are injected at API call time only
572                let cleaned_content = &msg.content;
573
574                // Reserve space on the first line for role prefix + gap + timestamp
575                // so text wraps early enough to not overlap the timestamp
576                let role_prefix_width = role_prefix.width() + 1; // "You " = prefix + space
577                let first_line_reserved = role_prefix_width + min_gap + timestamp_width;
578
579                // Manually wrap the user message with hanging indent (2 spaces)
580                let wrapped = wrap_text_with_indent(
581                    cleaned_content,
582                    content_width as usize,
583                    first_line_reserved, // reserve space for prefix + gap + timestamp on first line
584                    2,                   // continuation indent
585                );
586
587                for (line_idx, wrapped_line) in wrapped.iter().enumerate() {
588                    if line_idx == 0 {
589                        // First line: add role prefix and timestamp on right
590                        let text_content = wrapped_line.trim_start(); // Remove the indent we added
591                        let text_width = text_content.width();
592
593                        let mut spans = vec![
594                            Span::styled(
595                                format!("{} ", role_prefix),
596                                Style::new().fg(role_color).bold(),
597                            ),
598                            Span::raw(text_content.to_string()),
599                        ];
600
601                        // Always add at least min_gap spaces, plus any extra from word-boundary slack.
602                        // Align the timestamp to the content right edge (before the scrollbar gutter).
603                        let pad = user_timestamp_padding(
604                            role_prefix_width,
605                            text_width,
606                            timestamp_width,
607                            min_gap,
608                            content_width as usize,
609                        );
610                        spans.push(Span::raw(" ".repeat(pad)));
611                        spans.push(Span::styled(
612                            formatted_timestamp.clone(),
613                            Style::new().fg(ratatui::style::Color::Rgb(136, 136, 136)),
614                        ));
615
616                        lines.push(Line::from(spans));
617                    } else {
618                        // Continuation lines: already have 2-space margin from wrap_text_with_indent
619                        lines.push(Line::from(wrapped_line.clone()));
620                    }
621                }
622            }
623
624            // Show image indicators under user and assistant messages.
625            // User images come from clipboard paste (`Attachment`); assistant
626            // images come from tool executions that emitted `ProgressEvent::
627            // Artifact` during their run — screenshot captures, inline
628            // previews from computer-use, etc. Both land in `msg.images` as
629            // base64 strings and render the same way.
630            if matches!(msg.role, MessageRole::User | MessageRole::Assistant)
631                && let Some(ref images) = msg.images
632                && !images.is_empty()
633            {
634                for (i, _) in images.iter().enumerate() {
635                    // Record this line in the click map before pushing
636                    let content_line = lines.len() as u16;
637                    state.image_click_map.push((
638                        content_line,
639                        ImageClickTarget {
640                            message_index: idx,
641                            image_index: i,
642                        },
643                    ));
644                    lines.push(Line::from(vec![
645                        Span::styled("  ⎿ ", Style::new().fg(self.theme.colors.info.to_color())),
646                        Span::styled(
647                            format!("[Image #{}]", i + 1),
648                            Style::new().fg(self.theme.colors.info.to_color()).italic(),
649                        ),
650                    ]));
651                }
652            }
653
654            lines.push(Line::from(""));
655        }
656
657        // NOTE: The response buffer is NOT rendered during streaming (buffering mode).
658        // The response is buffered invisibly and only shown when generation is complete.
659        // This provides a Claude Code-like experience where the complete response
660        // appears instantly instead of streaming character-by-character.
661        //
662        // The status line shows progress: "↑ Sending..." → "↓ Streaming..." with timer
663
664        // Capture the plain text of each rendered row for selection
665        // extraction. Done before the highlight pass, which only changes
666        // styling, not text.
667        state.last_rendered_rows = lines.iter().map(line_plain_text).collect();
668
669        // Paint the active drag selection (reverse video over the selected
670        // cells). Selection lines are content indices, matching `lines`.
671        if let Some((a, b)) = state.selection
672            && !lines.is_empty()
673        {
674            let (start, end) = if a <= b { (a, b) } else { (b, a) };
675            let sel_style = Style::new().add_modifier(Modifier::REVERSED);
676            let last_line = lines.len() - 1;
677            for (line_idx, line) in lines
678                .iter_mut()
679                .enumerate()
680                .take(end.0.min(last_line) + 1)
681                .skip(start.0)
682            {
683                let c0 = if line_idx == start.0 { start.1 } else { 0 };
684                let c1 = if line_idx == end.0 { end.1 } else { usize::MAX };
685                if c1 > c0 {
686                    highlight_line_cells(line, c0, c1, sel_style);
687                }
688            }
689        }
690
691        // NOTE: Wrapping is disabled because we handle it manually with hanging indents
692        // Calculate content height and viewport for proper scroll clamping
693        let content_height = lines.len() as u16;
694        let viewport_height = area.height;
695
696        let scroll_pos = state.get_scroll_position(content_height, viewport_height);
697        state.last_scroll_position = scroll_pos;
698
699        let paragraph = Paragraph::new(lines)
700            .block(Block::default())
701            .scroll((scroll_pos, 0));
702
703        paragraph.render(content_area, buf);
704
705        // Scrollbar in the reserved gutter — only when the transcript actually
706        // overflows the viewport. Uses ratatui's 0.30 Scrollbar widget.
707        if gutter == 1 && content_height > viewport_height {
708            let mut sb_state = ScrollbarState::new(content_height as usize)
709                .viewport_content_length(viewport_height as usize)
710                .position(scroll_pos as usize);
711            Scrollbar::new(ScrollbarOrientation::VerticalRight)
712                .begin_symbol(None)
713                .end_symbol(None)
714                .thumb_style(Style::new().fg(self.theme.colors.border.to_color()))
715                .track_style(Style::new().fg(self.theme.colors.text_disabled.to_color()))
716                .render(area, buf, &mut sb_state);
717        }
718    }
719}
720
721fn render_context_checkpoint_event(msg: &ChatMessage, theme: &Theme) -> Option<Vec<Line<'static>>> {
722    if !matches!(msg.role, MessageRole::User) {
723        return None;
724    }
725
726    let metadata = msg.metadata.as_ref();
727    let trigger = metadata
728        .and_then(|value| value.get("trigger"))
729        .and_then(|value| value.as_str())
730        .unwrap_or("manual");
731    let before_tokens = metadata.and_then(|value| metadata_usize(value, "before_tokens"));
732    let after_tokens = metadata.and_then(|value| metadata_usize(value, "after_tokens"));
733    let archived_messages =
734        metadata.and_then(|value| metadata_usize(value, "archived_message_count"));
735    let preserved_messages =
736        metadata.and_then(|value| metadata_usize(value, "preserved_message_count"));
737    let duration_secs = metadata
738        .and_then(|value| value.get("duration_secs"))
739        .and_then(|value| value.as_f64());
740    let verified = metadata
741        .and_then(|value| value.get("verified"))
742        .and_then(|value| value.as_bool());
743    let verification_error = metadata
744        .and_then(|value| value.get("verification_error"))
745        .and_then(|value| value.as_str());
746
747    let action_color = theme.colors.info.to_color();
748    let mut result = match (before_tokens, after_tokens) {
749        (Some(before), Some(after)) => {
750            format!(
751                "Success, {} -> {} tokens",
752                format_compact_count(before),
753                format_compact_count(after)
754            )
755        },
756        _ => "Success".to_string(),
757    };
758
759    if let Some(count) = archived_messages {
760        result.push_str(&format!(
761            ", archived {} {}",
762            count,
763            if count == 1 { "message" } else { "messages" }
764        ));
765    }
766    if let Some(count) = preserved_messages {
767        result.push_str(&format!(
768            ", preserved {} {}",
769            count,
770            if count == 1 { "message" } else { "messages" }
771        ));
772    }
773    if let Some(verified) = verified {
774        if verified {
775            result.push_str(", verified");
776        } else {
777            result.push_str(", draft fallback");
778        }
779    }
780    result = append_action_duration(result, duration_secs);
781
782    let mut lines = vec![
783        Line::from(vec![
784            Span::styled("● ", Style::new().fg(action_color).bold()),
785            Span::styled("Compact(", Style::new().fg(action_color).bold()),
786            Span::styled(
787                trigger.to_string(),
788                Style::new().fg(theme.colors.text_secondary.to_color()),
789            ),
790            Span::styled(")", Style::new().fg(action_color).bold()),
791        ]),
792        Line::from(vec![
793            Span::styled("  ⎿ ", Style::new().fg(action_color)),
794            Span::styled(
795                result,
796                Style::new().fg(theme.colors.text_secondary.to_color()),
797            ),
798        ]),
799    ];
800
801    if let Some(error) = verification_error.filter(|error| !error.trim().is_empty()) {
802        lines.push(Line::from(vec![
803            Span::styled("    ", Style::new().fg(action_color)),
804            Span::styled(
805                format!("verification: {}", compact_inline_error(error, 180)),
806                Style::new().fg(theme.colors.warning.to_color()),
807            ),
808        ]));
809    }
810
811    Some(lines)
812}
813
814fn metadata_usize(value: &serde_json::Value, key: &str) -> Option<usize> {
815    value
816        .get(key)?
817        .as_u64()
818        .and_then(|value| usize::try_from(value).ok())
819}
820
821fn compact_inline_error(text: &str, max_chars: usize) -> String {
822    let text = text.trim();
823    if text.chars().count() <= max_chars {
824        return text.to_string();
825    }
826    let keep = max_chars.saturating_sub(3);
827    let mut out: String = text.chars().take(keep).collect();
828    out.push_str("...");
829    out
830}
831
832/// Render actions in Claude Code style
833/// Expand tab characters to spaces on 4-column tab stops.
834///
835/// Tabs paint as zero cells in the terminal buffer, so a line containing them
836/// has a char count larger than its painted width. Any width math done by char
837/// count (e.g. padding a diff line so its background bar spans the row) would
838/// then come up short by one column per tab. Expanding here keeps indentation
839/// visible and makes char count match painted width.
840fn expand_tabs(s: &str) -> String {
841    const TAB_WIDTH: usize = 4;
842    if !s.contains('\t') {
843        return s.to_string();
844    }
845    let mut out = String::with_capacity(s.len() + TAB_WIDTH);
846    let mut col = 0usize;
847    for ch in s.chars() {
848        if ch == '\t' {
849            let n = TAB_WIDTH - (col % TAB_WIDTH);
850            for _ in 0..n {
851                out.push(' ');
852            }
853            col += n;
854        } else {
855            out.push(ch);
856            col += UnicodeWidthChar::width(ch).unwrap_or(0);
857        }
858    }
859    out
860}
861
862fn render_actions(
863    actions: &[ActionDisplay],
864    lines: &mut Vec<Line>,
865    theme: &Theme,
866    viewport_width: usize,
867) {
868    for (action_idx, action) in actions.iter().enumerate() {
869        if action_idx > 0 {
870            lines.push(Line::from(""));
871        }
872        let action_color = match action.action_type.as_str() {
873            "Write" | "Edit" => theme.colors.success.to_color(),
874            "Delete" => theme.colors.warning.to_color(),
875            _ => theme.colors.info.to_color(),
876        };
877
878        // Header: ● Type(target)
879        lines.push(Line::from(vec![
880            Span::styled("● ", Style::new().fg(action_color).bold()),
881            Span::styled(
882                format!("{}(", action.action_type),
883                Style::new().fg(action_color).bold(),
884            ),
885            Span::styled(
886                action.target.clone(),
887                Style::new().fg(theme.colors.text_secondary.to_color()),
888            ),
889            Span::styled(")", Style::new().fg(action_color).bold()),
890        ]));
891
892        match &action.result {
893            ActionResult::Success { .. } => {
894                // Result summary from details enum
895                let result_msg = match &action.details {
896                    ActionDetails::FileContent { line_count, .. } => {
897                        let base = format!(
898                            "Success, {} {} written",
899                            line_count,
900                            if *line_count == 1 { "line" } else { "lines" }
901                        );
902                        append_action_duration(base, action.duration_seconds)
903                    },
904                    ActionDetails::Diff { summary, .. } => summary.clone(),
905                    ActionDetails::Preview { text, .. } => text.clone(),
906                    ActionDetails::Simple => match action.action_type.as_str() {
907                        "Delete" => append_action_duration(
908                            format!("Success, deleted {}", action.target),
909                            action.duration_seconds,
910                        ),
911                        _ => append_action_duration("Success".to_string(), action.duration_seconds),
912                    },
913                };
914
915                for (idx, line) in result_msg.lines().enumerate() {
916                    let prefix = if idx == 0 { "  ⎿ " } else { "    " };
917                    lines.push(Line::from(vec![
918                        Span::styled(prefix, Style::new().fg(action_color)),
919                        Span::styled(
920                            line.to_string(),
921                            Style::new().fg(theme.colors.text_secondary.to_color()),
922                        ),
923                    ]));
924                }
925
926                // Write: syntax-highlighted file preview
927                if let ActionDetails::FileContent {
928                    content,
929                    line_count,
930                } = &action.details
931                {
932                    let preview_lines: Vec<&str> = content.lines().take(10).collect();
933                    if !preview_lines.is_empty() {
934                        lines.push(Line::from(vec![Span::styled(
935                            "    ",
936                            Style::new().fg(action_color),
937                        )]));
938
939                        let preview_content = preview_lines.join("\n");
940                        let mut parsed =
941                            parse_markdown(&format!("```\n{}\n```", preview_content), theme);
942                        for parsed_line in parsed.iter_mut() {
943                            let mut new_spans =
944                                vec![Span::styled("    ", Style::new().fg(action_color))];
945                            new_spans.append(&mut parsed_line.spans);
946                            parsed_line.spans = new_spans;
947                        }
948                        lines.extend(parsed);
949
950                        if *line_count > 10 {
951                            lines.push(Line::from(vec![
952                                Span::styled("    ", Style::new().fg(action_color)),
953                                Span::styled(
954                                    format!("... ({} more lines)", line_count - 10),
955                                    Style::new()
956                                        .fg(theme.colors.text_disabled.to_color())
957                                        .italic(),
958                                ),
959                            ]));
960                        }
961                    }
962                }
963
964                // Edit: color-coded diff
965                if let ActionDetails::Diff { diff, .. } = &action.details {
966                    let diff_lines: Vec<&str> = diff.lines().collect();
967                    let display_lines: Vec<&str> = diff_lines.iter().take(80).copied().collect();
968
969                    if !display_lines.is_empty() {
970                        let removed_bg = ratatui::style::Color::Rgb(60, 20, 20);
971                        let added_bg = ratatui::style::Color::Rgb(20, 50, 20);
972
973                        for diff_line in &display_lines {
974                            // Expand tabs first: the TUI paints a tab as zero
975                            // cells, so a tab-bearing line's char count exceeds
976                            // its painted width and the char-count pad below
977                            // would leave the background bar short — a ragged
978                            // "staircase" down the right edge. Expanding also
979                            // makes tab indentation actually visible.
980                            let diff_line = expand_tabs(diff_line);
981                            // Delegate the producer-format awareness to
982                            // `parse_diff_line`, which lives next to the
983                            // marker constants and stays in lockstep with
984                            // any future format change.
985                            match parse_diff_line(&diff_line) {
986                                DiffLineKind::Removed => {
987                                    let text = format!("    {}", diff_line);
988                                    let padded = pad_to_cells(&text, viewport_width);
989                                    lines.push(Line::from(vec![Span::styled(
990                                        padded,
991                                        Style::new()
992                                            .fg(theme.colors.error.to_color())
993                                            .bg(removed_bg),
994                                    )]));
995                                },
996                                DiffLineKind::Added => {
997                                    let text = format!("    {}", diff_line);
998                                    let padded = pad_to_cells(&text, viewport_width);
999                                    lines.push(Line::from(vec![Span::styled(
1000                                        padded,
1001                                        Style::new()
1002                                            .fg(theme.colors.success.to_color())
1003                                            .bg(added_bg),
1004                                    )]));
1005                                },
1006                                DiffLineKind::Context => {
1007                                    lines.push(Line::from(vec![
1008                                        Span::styled("    ", Style::new().fg(action_color)),
1009                                        Span::styled(
1010                                            diff_line,
1011                                            Style::new().fg(theme.colors.text_secondary.to_color()),
1012                                        ),
1013                                    ]));
1014                                },
1015                            }
1016                        }
1017
1018                        let remaining = diff_lines.len().saturating_sub(display_lines.len());
1019                        if remaining > 0 {
1020                            lines.push(Line::from(vec![
1021                                Span::styled("    ", Style::new().fg(action_color)),
1022                                Span::styled(
1023                                    format!("... ({} more lines)", remaining),
1024                                    Style::new()
1025                                        .fg(theme.colors.text_disabled.to_color())
1026                                        .italic(),
1027                                ),
1028                            ]));
1029                        }
1030                    }
1031                }
1032            },
1033            ActionResult::Error { error } => {
1034                let error =
1035                    append_action_duration(format!("Error: {}", error), action.duration_seconds);
1036                lines.push(Line::from(vec![
1037                    Span::styled("  ⎿ ", Style::new().fg(theme.colors.error.to_color())),
1038                    Span::styled(error, Style::new().fg(theme.colors.error.to_color())),
1039                ]));
1040            },
1041        }
1042    }
1043}
1044
1045fn append_action_duration(mut text: String, duration_seconds: Option<f64>) -> String {
1046    if let Some(seconds) = duration_seconds {
1047        text.push_str(", took ");
1048        text.push_str(&format_action_duration(seconds));
1049    }
1050    text
1051}
1052
1053fn format_action_duration(seconds: f64) -> String {
1054    if seconds < 1.0 {
1055        format!("{}ms", (seconds * 1000.0).round().max(1.0) as u64)
1056    } else if seconds < 10.0 {
1057        format!("{:.1}s", seconds)
1058    } else {
1059        format!("{}s", seconds.round() as u64)
1060    }
1061}
1062
1063/// Wrap text with hanging indent support.
1064///
1065/// `width`, `first_line_indent`, and `continuation_indent` are all measured
1066/// in **display cells**, not bytes. Word lengths are also measured in cells
1067/// via `UnicodeWidthStr::width` so CJK / emoji wrap at the visual edge —
1068/// previously a CJK paragraph would wrap after ~1/3 of the line because
1069/// `word.len()` (bytes) is roughly 3× `word.width()` (cells) for 3-byte
1070/// codepoints.
1071fn wrap_text_with_indent(
1072    text: &str,
1073    width: usize,
1074    first_line_indent: usize,
1075    continuation_indent: usize,
1076) -> Vec<String> {
1077    let mut wrapped_lines = Vec::new();
1078
1079    for (line_idx, line) in text.lines().enumerate() {
1080        if line.is_empty() {
1081            wrapped_lines.push(String::new());
1082            continue;
1083        }
1084
1085        let current_indent = if line_idx == 0 {
1086            first_line_indent
1087        } else {
1088            continuation_indent
1089        };
1090        let available_width = width.saturating_sub(current_indent);
1091
1092        if available_width == 0 {
1093            wrapped_lines.push(" ".repeat(current_indent));
1094            continue;
1095        }
1096
1097        let words: Vec<&str> = line.split_whitespace().collect();
1098        if words.is_empty() {
1099            wrapped_lines.push(" ".repeat(current_indent));
1100            continue;
1101        }
1102
1103        let mut current_line = String::with_capacity(width);
1104        current_line.push_str(&" ".repeat(current_indent));
1105        // Display-cell widths: indent is ASCII spaces (1 cell each), so
1106        // start fresh and let words contribute their own cell widths.
1107        let mut current_length = 0;
1108
1109        for (word_idx, word) in words.iter().enumerate() {
1110            let word_width = word.width();
1111
1112            if word_idx == 0 {
1113                // First word always fits on the line
1114                current_line.push_str(word);
1115                current_length = word_width;
1116            } else if current_length + 1 + word_width <= available_width {
1117                // Word fits on current line (the +1 accounts for the
1118                // separator space, which is 1 cell)
1119                current_line.push(' ');
1120                current_line.push_str(word);
1121                current_length += 1 + word_width;
1122            } else {
1123                // Word doesn't fit, start a new line
1124                wrapped_lines.push(current_line);
1125                current_line = String::with_capacity(width);
1126                current_line.push_str(&" ".repeat(continuation_indent));
1127                current_line.push_str(word);
1128                current_length = word_width;
1129            }
1130        }
1131
1132        // Add the last line
1133        if !current_line.trim().is_empty() {
1134            wrapped_lines.push(current_line);
1135        }
1136    }
1137
1138    wrapped_lines
1139}
1140
1141/// Wrap a styled Line with hanging indent, preserving all span styles
1142/// Returns multiple Line objects with proper indentation
1143fn wrap_styled_line(
1144    line: Line<'static>,
1145    width: usize,
1146    continuation_indent: usize,
1147) -> Vec<Line<'static>> {
1148    // Widths are counted in display cells (via `UnicodeWidthStr`), not
1149    // bytes. This makes CJK double-width chars and emoji wrap at the
1150    // correct visual column, and avoids over-wrapping multi-byte ASCII-
1151    // looking glyphs.
1152    let total_width: usize = line.spans.iter().map(|s| s.content.width()).sum();
1153
1154    // If the line fits within width, return as-is
1155    if total_width <= width {
1156        return vec![line];
1157    }
1158
1159    // Line needs wrapping - extract all text and styles
1160    let mut result_lines = Vec::new();
1161    let mut current_line_spans = Vec::new();
1162    let mut current_line_width = 0usize;
1163    let available_width = width.saturating_sub(continuation_indent);
1164
1165    for span in line.spans.clone() {
1166        let span_text = span.content.to_string();
1167        let span_style = span.style;
1168
1169        // Split span text by words
1170        let words: Vec<&str> = span_text.split_whitespace().collect();
1171
1172        for (word_idx, word) in words.iter().enumerate() {
1173            let word_with_space = if word_idx > 0 || current_line_width > 0 {
1174                format!(" {}", word)
1175            } else {
1176                word.to_string()
1177            };
1178
1179            let word_width = word_with_space.width();
1180
1181            if current_line_width == 0 && result_lines.is_empty() {
1182                // First word of first line - no indent
1183                current_line_spans.push(Span::styled(word_with_space, span_style));
1184                current_line_width += word_width;
1185            } else if current_line_width + word_width <= available_width {
1186                // Word fits on current line
1187                current_line_spans.push(Span::styled(word_with_space, span_style));
1188                current_line_width += word_width;
1189            } else {
1190                // Word doesn't fit - finish current line and start new one
1191                result_lines.push(Line::from(current_line_spans));
1192                current_line_spans = vec![Span::raw(" ".repeat(continuation_indent))];
1193                current_line_spans.push(Span::styled(word.to_string(), span_style));
1194                current_line_width = word.width();
1195            }
1196        }
1197    }
1198
1199    // Add the last line if it has content
1200    if !current_line_spans.is_empty() {
1201        result_lines.push(Line::from(current_line_spans));
1202    }
1203
1204    if result_lines.is_empty() {
1205        vec![line]
1206    } else {
1207        result_lines
1208    }
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213    use super::*;
1214
1215    #[test]
1216    fn diff_background_fills_full_width_with_tabs() {
1217        // Regression: tab characters paint as zero cells, so char-count padding
1218        // left the red/green diff bar short by one column per tab — a ragged
1219        // "staircase" down the right edge. After expand_tabs, every column of a
1220        // diff row must carry the background.
1221        use crate::render::diff::{DIFF_ADDED_MARKER, DIFF_REMOVED_MARKER};
1222        use ratatui::Terminal;
1223        use ratatui::backend::TestBackend;
1224
1225        let theme = Theme::dark();
1226        let added_bg = ratatui::style::Color::Rgb(20, 50, 20);
1227        let removed_bg = ratatui::style::Color::Rgb(60, 20, 20);
1228        // Lines at increasing tab depth — the exact shape that staircased.
1229        let diff = format!(
1230            "  62{m}\tconst out = [];\n  63{p}\t\tlet fixed = false;\n  64{p}\t\t\tdeeplyNested();",
1231            m = DIFF_REMOVED_MARKER,
1232            p = DIFF_ADDED_MARKER
1233        );
1234        let action = ActionDisplay {
1235            action_type: "Edit".to_string(),
1236            target: "engine.ts".to_string(),
1237            result: ActionResult::Success {
1238                output: String::new(),
1239                images: None,
1240            },
1241            details: ActionDetails::Diff {
1242                summary: "ok".to_string(),
1243                diff,
1244            },
1245            duration_seconds: Some(0.3),
1246            metadata: None,
1247        };
1248
1249        let width: u16 = 60;
1250        let mut lines: Vec<Line> = Vec::new();
1251        render_actions(&[action], &mut lines, &theme, width as usize);
1252        let h = lines.len() as u16;
1253        let backend = TestBackend::new(width, h);
1254        let mut term = Terminal::new(backend).unwrap();
1255        term.draw(|f| {
1256            Paragraph::new(lines).render(Rect::new(0, 0, width, h), f.buffer_mut());
1257        })
1258        .unwrap();
1259        let buf = term.backend().buffer();
1260
1261        for y in 0..h {
1262            let is_diff_row = (0..width).any(|x| {
1263                let bg = buf[(x, y)].bg;
1264                bg == added_bg || bg == removed_bg
1265            });
1266            if !is_diff_row {
1267                continue;
1268            }
1269            for x in 0..width {
1270                let bg = buf[(x, y)].bg;
1271                assert!(
1272                    bg == added_bg || bg == removed_bg,
1273                    "diff background must fill the whole row, but column {x} of row {y} is unfilled (staircase)"
1274                );
1275            }
1276        }
1277    }
1278
1279    #[test]
1280    fn byte_at_cell_clamps_and_respects_cjk() {
1281        assert_eq!(byte_at_cell("hello", 0), 0);
1282        assert_eq!(byte_at_cell("hello", 3), 3);
1283        assert_eq!(byte_at_cell("hello", 99), 5); // clamp past end
1284        // "你好" = 2 chars, 3 bytes each, 2 cells each.
1285        assert_eq!(byte_at_cell("你好", 0), 0);
1286        assert_eq!(byte_at_cell("你好", 2), 3); // after first wide char
1287        // A cell index that lands mid-glyph keeps the glyph whole (rounds up).
1288        assert_eq!(byte_at_cell("你好", 1), 3);
1289    }
1290
1291    #[test]
1292    fn slice_by_cells_extracts_display_range() {
1293        assert_eq!(slice_by_cells("hello world", 0, 5), "hello");
1294        assert_eq!(slice_by_cells("hello world", 6, 11), "world");
1295        assert_eq!(slice_by_cells("你好world", 2, 7), "好wor");
1296    }
1297
1298    #[test]
1299    fn pad_to_cells_fills_to_display_width() {
1300        assert_eq!(pad_to_cells("ab", 5), "ab   ");
1301        // "你好" = 4 display cells; pad to 6 → exactly 2 trailing spaces (#101).
1302        assert_eq!(pad_to_cells("你好", 6), "你好  ");
1303        // Already wide enough → unchanged (never truncates).
1304        assert_eq!(pad_to_cells("你好", 3), "你好");
1305        assert_eq!(pad_to_cells("", 0), "");
1306    }
1307
1308    #[test]
1309    fn user_timestamp_padding_aligns_on_display_cells() {
1310        // ASCII: prefix(4) + text(5) + gap(3) + ts(8) = 20 used; content 40.
1311        assert_eq!(user_timestamp_padding(4, 5, 8, 3, 40), 23);
1312        // A wider (CJK) message shrinks the gap but the timestamp still lands at
1313        // the content right edge: role + text + pad + ts == content_width (#104).
1314        let pad = user_timestamp_padding(4, 10, 8, 3, 40);
1315        assert_eq!(4 + 10 + pad + 8, 40);
1316        // Overflow (text wider than the line) clamps to min_gap, never underflows.
1317        assert_eq!(user_timestamp_padding(4, 100, 8, 3, 40), 3);
1318    }
1319
1320    #[test]
1321    fn wrap_preformatted_hard_wraps_preserving_spaces() {
1322        // 18 cells, wraps at 10. Spaces are preserved (not collapsed) and the
1323        // leading indentation survives on the first row.
1324        let line = Line::from(vec![Span::raw("    aaaa bbbb cccc")]);
1325        let wrapped = wrap_preformatted(line, 10, 2);
1326        assert!(wrapped.len() >= 2, "wide line should wrap to multiple rows");
1327        let first: String = wrapped[0]
1328            .spans
1329            .iter()
1330            .map(|s| s.content.as_ref())
1331            .collect();
1332        assert!(
1333            first.starts_with("    aaaa"),
1334            "indentation must be preserved, got {first:?}"
1335        );
1336        let second: String = wrapped[1]
1337            .spans
1338            .iter()
1339            .map(|s| s.content.as_ref())
1340            .collect();
1341        assert!(
1342            second.starts_with("  "),
1343            "continuation should get the hanging indent, got {second:?}"
1344        );
1345    }
1346
1347    #[test]
1348    fn wrap_preformatted_short_line_unchanged() {
1349        let line = Line::from(vec![Span::raw("    short")]);
1350        let wrapped = wrap_preformatted(line, 40, 2);
1351        assert_eq!(wrapped.len(), 1);
1352        let text: String = wrapped[0]
1353            .spans
1354            .iter()
1355            .map(|s| s.content.as_ref())
1356            .collect();
1357        assert_eq!(text, "    short");
1358    }
1359
1360    /// Build a ChatState whose last frame rendered `rows`, with a selection
1361    /// already mapped to content coords, so `selected_text` can be tested
1362    /// without a real terminal.
1363    fn state_with_rows(rows: &[&str], sel: ((usize, usize), (usize, usize))) -> ChatState {
1364        let mut st = ChatState::new();
1365        st.last_rendered_rows = rows.iter().map(|r| r.to_string()).collect();
1366        st.selection = Some(sel);
1367        st
1368    }
1369
1370    #[test]
1371    fn selected_text_single_line() {
1372        let st = state_with_rows(&["> hello world"], ((0, 2), (0, 7)));
1373        assert_eq!(st.selected_text().as_deref(), Some("hello"));
1374    }
1375
1376    #[test]
1377    fn selected_text_spans_multiple_rows() {
1378        let st = state_with_rows(&["> first line", "  second line"], ((0, 2), (1, 8)));
1379        // The continuation row's "  " margin is stripped so copied text is
1380        // clean (the start row was sliced from the click column past "> ").
1381        assert_eq!(st.selected_text().as_deref(), Some("first line\nsecond"));
1382    }
1383
1384    #[test]
1385    fn selected_text_strips_margin_but_keeps_code_indentation() {
1386        // Rendered rows: 2-cell margin + the code's own indentation. Selecting
1387        // from column 0 must drop only the 2-cell margin, not the code indent.
1388        let st = state_with_rows(
1389            &["  fn main() {", "      let x = 1;", "  }"],
1390            ((0, 0), (2, 3)),
1391        );
1392        assert_eq!(
1393            st.selected_text().as_deref(),
1394            Some("fn main() {\n    let x = 1;\n}")
1395        );
1396    }
1397
1398    #[test]
1399    fn selected_text_normalizes_reversed_drag() {
1400        // Dragging bottom-up / right-to-left yields the same text.
1401        let st = state_with_rows(&["> hello world"], ((0, 7), (0, 2)));
1402        assert_eq!(st.selected_text().as_deref(), Some("hello"));
1403    }
1404
1405    #[test]
1406    fn selected_text_empty_selection_is_none() {
1407        // A plain click (anchor == cursor) selects nothing.
1408        let st = state_with_rows(&["> hello"], ((0, 3), (0, 3)));
1409        assert_eq!(st.selected_text(), None);
1410    }
1411
1412    #[test]
1413    fn highlight_line_cells_splits_spans_on_selection() {
1414        let mut line = Line::from(vec![Span::raw("abcdef")]);
1415        highlight_line_cells(
1416            &mut line,
1417            2,
1418            4,
1419            Style::new().add_modifier(Modifier::REVERSED),
1420        );
1421        // Split into "ab" | "cd"(reversed) | "ef".
1422        let texts: Vec<String> = line.spans.iter().map(|s| s.content.to_string()).collect();
1423        assert_eq!(texts, vec!["ab", "cd", "ef"]);
1424        assert!(
1425            line.spans[1]
1426                .style
1427                .add_modifier
1428                .contains(Modifier::REVERSED)
1429        );
1430        assert!(
1431            !line.spans[0]
1432                .style
1433                .add_modifier
1434                .contains(Modifier::REVERSED)
1435        );
1436    }
1437
1438    #[test]
1439    fn context_checkpoint_renders_as_compact_event() {
1440        let mut msg = ChatMessage::user("full checkpoint summary hidden from the chat log");
1441        msg.kind = ChatMessageKind::ContextCheckpoint;
1442        msg.metadata = Some(serde_json::json!({
1443            "trigger": "manual",
1444            "before_tokens": 43_800,
1445            "after_tokens": 9_200,
1446            "archived_message_count": 18,
1447            "preserved_message_count": 4,
1448            "duration_secs": 2.4,
1449            "verified": true,
1450        }));
1451
1452        let lines = render_context_checkpoint_event(&msg, &Theme::dark()).expect("event lines");
1453        let rendered = lines
1454            .iter()
1455            .map(|line| {
1456                line.spans
1457                    .iter()
1458                    .map(|span| span.content.as_ref())
1459                    .collect::<String>()
1460            })
1461            .collect::<Vec<_>>()
1462            .join("\n");
1463
1464        assert!(rendered.contains("Compact(manual)"));
1465        assert!(rendered.contains("43.8k -> 9.2k tokens"));
1466        assert!(rendered.contains("archived 18 messages"));
1467        assert!(rendered.contains("preserved 4 messages"));
1468        assert!(rendered.contains("verified"));
1469        assert!(!rendered.contains("full checkpoint summary"));
1470    }
1471
1472    #[test]
1473    fn context_checkpoint_renders_verification_fallback() {
1474        let mut msg = ChatMessage::user("full checkpoint summary hidden from the chat log");
1475        msg.kind = ChatMessageKind::ContextCheckpoint;
1476        msg.metadata = Some(serde_json::json!({
1477            "trigger": "auto_threshold",
1478            "before_tokens": 43_800,
1479            "after_tokens": 9_200,
1480            "archived_message_count": 18,
1481            "preserved_message_count": 4,
1482            "duration_secs": 2.4,
1483            "verified": false,
1484            "verification_error": "provider overloaded",
1485        }));
1486
1487        let lines = render_context_checkpoint_event(&msg, &Theme::dark()).expect("event lines");
1488        let rendered = lines
1489            .iter()
1490            .map(|line| {
1491                line.spans
1492                    .iter()
1493                    .map(|span| span.content.as_ref())
1494                    .collect::<String>()
1495            })
1496            .collect::<Vec<_>>()
1497            .join("\n");
1498
1499        assert!(rendered.contains("Compact(auto_threshold)"));
1500        assert!(rendered.contains("draft fallback"));
1501        assert!(rendered.contains("verification: provider overloaded"));
1502    }
1503
1504    /// CJK characters are 3 bytes but 2 display cells each. The
1505    /// byte-length version of `wrap_styled_line` would incorrectly
1506    /// over-wrap such input. This test asserts the display-width
1507    /// version keeps CJK-only input on a single line when the display
1508    /// width fits, even when the byte length exceeds the width.
1509    #[test]
1510    fn wrap_styled_line_uses_display_width_for_cjk() {
1511        // "你好世界" is 4 CJK chars × 3 bytes = 12 bytes, × 2 display cells = 8 cells.
1512        // Target width of 10: byte-length would see 12 > 10 and wrap;
1513        // display-width sees 8 <= 10 and keeps it on one line.
1514        let line = Line::from(Span::raw("你好世界".to_string()));
1515        let wrapped = wrap_styled_line(line, 10, 2);
1516        assert_eq!(
1517            wrapped.len(),
1518            1,
1519            "CJK input fitting in display-width should NOT be wrapped; got {} lines",
1520            wrapped.len()
1521        );
1522    }
1523
1524    /// Sanity: ASCII wrapping still works and produces >= 2 lines when
1525    /// the input exceeds the width.
1526    #[test]
1527    fn wrap_styled_line_ascii_wraps_when_too_long() {
1528        let line = Line::from(Span::raw(
1529            "the quick brown fox jumps over the lazy dog".to_string(),
1530        ));
1531        let wrapped = wrap_styled_line(line, 15, 2);
1532        assert!(
1533            wrapped.len() >= 2,
1534            "long ASCII input should wrap to multiple lines; got {}",
1535            wrapped.len()
1536        );
1537    }
1538
1539    /// Counterpart to `wrap_styled_line_uses_display_width_for_cjk` for
1540    /// the plain-string wrapper used by user messages and thinking blocks.
1541    /// The byte-based version would wrap a 4-CJK paragraph after the second
1542    /// char (12 bytes > 10) even though it fits in 8 cells. Display-width
1543    /// version keeps it on one line.
1544    #[test]
1545    fn wrap_text_with_indent_uses_display_width_for_cjk() {
1546        // "你好世界" = 4 chars, 12 bytes, 8 display cells. Width 12 cells
1547        // with 0 indent: should fit on one line.
1548        let wrapped = wrap_text_with_indent("你好世界", 12, 0, 0);
1549        assert_eq!(
1550            wrapped.len(),
1551            1,
1552            "CJK paragraph fitting in display width should not wrap; got {} lines: {:?}",
1553            wrapped.len(),
1554            wrapped
1555        );
1556        assert_eq!(wrapped[0].trim_start(), "你好世界");
1557    }
1558
1559    /// Mixed content: CJK + ASCII should still wrap correctly when the
1560    /// total exceeds available cells.
1561    #[test]
1562    fn wrap_text_with_indent_wraps_cjk_at_visual_edge() {
1563        // "你好 world 世界" = 2 + 1 + 5 + 1 + 2 = 11 cells without spaces,
1564        // with separators: 2 + 1 + 5 + 1 + 4 = 13 cells. Width 8 cells should
1565        // produce ≥ 2 lines.
1566        let wrapped = wrap_text_with_indent("你好 world 世界", 8, 0, 0);
1567        assert!(
1568            wrapped.len() >= 2,
1569            "mixed CJK+ASCII exceeding width should wrap; got {} lines: {:?}",
1570            wrapped.len(),
1571            wrapped
1572        );
1573    }
1574}