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#[derive(Debug, Clone)]
25pub struct ImageClickTarget {
26 pub message_index: usize,
28 pub image_index: usize,
30}
31
32#[derive(Debug, Clone)]
34pub struct ChatState {
35 scroll_offset: u16,
37 is_user_scrolling: bool,
39 pub image_click_map: Vec<(u16, ImageClickTarget)>,
41 pub last_scroll_position: u16,
43 pub last_chat_area: Option<(u16, u16, u16, u16)>, selection: Option<((usize, usize), (usize, usize))>,
48 last_rendered_rows: Vec<String>,
52}
53
54impl ChatState {
55 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 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 let capped_offset = self.scroll_offset.min(max_scroll);
76 max_scroll.saturating_sub(capped_offset)
77 } else {
78 max_scroll
80 }
81 }
82
83 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 self.selection = None;
90 }
91
92 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 self.is_user_scrolling = false;
99 }
100 self.selection = None;
101 }
102
103 pub fn resume_auto_scroll(&mut self) {
105 self.is_user_scrolling = false;
106 self.scroll_offset = 0;
107 }
108
109 pub fn is_manually_scrolling(&self) -> bool {
111 self.is_user_scrolling
112 }
113
114 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 if screen_row < area_y || screen_row >= area_y + area_height {
121 return None;
122 }
123
124 let viewport_row = screen_row - area_y;
126 let content_line = viewport_row + self.last_scroll_position;
127
128 self.image_click_map
130 .iter()
131 .find(|(line, _)| *line == content_line)
132 .map(|(_, target)| target)
133 }
134
135 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 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 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 pub fn clear_selection(&mut self) {
168 self.selection = None;
169 }
170
171 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 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
213const SELECT_MARGIN_CELLS: usize = 2;
217
218fn 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 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
271fn 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
288fn 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
295fn 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
310fn 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
325fn line_plain_text(line: &Line) -> String {
327 line.spans.iter().map(|s| s.content.as_ref()).collect()
328}
329
330fn 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); 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
368pub struct ChatWidget<'a> {
370 pub messages: &'a [ChatMessage],
371 pub theme: &'a Theme,
372 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 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 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 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 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 if let Some(ref thinking) = msg.thinking {
434 let thinking_trimmed = thinking.trim();
436 if thinking_trimmed.is_empty()
437 || thinking_trimmed == "None"
438 || thinking_trimmed == "none"
439 {
440 } else if self.show_reasoning {
442 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 let wrapped = wrap_text_with_indent(
456 thinking,
457 content_width as usize,
458 2, 2, );
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 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 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 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 let preformatted = parsed_line.style.bg == Some(code_bg);
531 let base_style = parsed_line.style;
532
533 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 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 if !msg.actions.is_empty() {
556 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 let formatted_timestamp = format_relative_timestamp(msg.timestamp);
565 let timestamp_width = formatted_timestamp.width();
569 let min_gap = 3; let cleaned_content = &msg.content;
573
574 let role_prefix_width = role_prefix.width() + 1; let first_line_reserved = role_prefix_width + min_gap + timestamp_width;
578
579 let wrapped = wrap_text_with_indent(
581 cleaned_content,
582 content_width as usize,
583 first_line_reserved, 2, );
586
587 for (line_idx, wrapped_line) in wrapped.iter().enumerate() {
588 if line_idx == 0 {
589 let text_content = wrapped_line.trim_start(); 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 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 lines.push(Line::from(wrapped_line.clone()));
620 }
621 }
622 }
623
624 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 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 state.last_rendered_rows = lines.iter().map(line_plain_text).collect();
668
669 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 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 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
832fn 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 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 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 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 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 let diff_line = expand_tabs(diff_line);
981 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
1063fn 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 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 current_line.push_str(word);
1115 current_length = word_width;
1116 } else if current_length + 1 + word_width <= available_width {
1117 current_line.push(' ');
1120 current_line.push_str(word);
1121 current_length += 1 + word_width;
1122 } else {
1123 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 if !current_line.trim().is_empty() {
1134 wrapped_lines.push(current_line);
1135 }
1136 }
1137
1138 wrapped_lines
1139}
1140
1141fn wrap_styled_line(
1144 line: Line<'static>,
1145 width: usize,
1146 continuation_indent: usize,
1147) -> Vec<Line<'static>> {
1148 let total_width: usize = line.spans.iter().map(|s| s.content.width()).sum();
1153
1154 if total_width <= width {
1156 return vec![line];
1157 }
1158
1159 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 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 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 current_line_spans.push(Span::styled(word_with_space, span_style));
1188 current_line_width += word_width;
1189 } else {
1190 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 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 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 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); assert_eq!(byte_at_cell("你好", 0), 0);
1286 assert_eq!(byte_at_cell("你好", 2), 3); 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 assert_eq!(pad_to_cells("你好", 6), "你好 ");
1303 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 assert_eq!(user_timestamp_padding(4, 5, 8, 3, 40), 23);
1312 let pad = user_timestamp_padding(4, 10, 8, 3, 40);
1315 assert_eq!(4 + 10 + pad + 8, 40);
1316 assert_eq!(user_timestamp_padding(4, 100, 8, 3, 40), 3);
1318 }
1319
1320 #[test]
1321 fn wrap_preformatted_hard_wraps_preserving_spaces() {
1322 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 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 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 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 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 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 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 #[test]
1510 fn wrap_styled_line_uses_display_width_for_cjk() {
1511 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 #[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 #[test]
1545 fn wrap_text_with_indent_uses_display_width_for_cjk() {
1546 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 #[test]
1562 fn wrap_text_with_indent_wraps_cjk_at_visual_edge() {
1563 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}