返回 CodeWhale
tool_output.rs
根目录 / crates / tui / src / tui / history / tool_output.rs
1 //! Preserved tool-output rendering and line selection.
2
3 use codewhale_app_server::exec_agent::summarize_tool_output;
4 use ratatui::style::Style;
5 use ratatui::text::{Line, Span};
6 use serde_json::Value;
7 use unicode_segmentation::UnicodeSegmentation;
8 use unicode_width::UnicodeWidthStr;
9
10 use codewhale_localization::{Locale, MessageId, tr};
11 use codewhale_palette as palette;
12
13 use super::constants::{TOOL_OUTPUT_HEAD_LINES, TOOL_OUTPUT_TAIL_LINES, TRANSCRIPT_RAIL};
14 use super::{
15 RenderMode, details_affordance_line, looks_like_file_path, render_card_detail_line_single,
16 render_card_detail_line_single_styled, tool_value_style, truncate_text,
17 };
18
19 /// Columns the first output row gives up to its label: `result: ` or
20 /// `output: `. Both labels are the same width, which is what lets one cached
21 /// set of rows serve either card.
22 const FIRST_ROW_LABEL_COLUMNS: usize = "result: ".len();
23
24 pub(super) fn render_tool_output_mode(
25 output: &str,
26 width: u16,
27 line_limit: usize,
28 mode: RenderMode,
29 locale: Locale,
30 ) -> Vec<Line<'static>> {
31 render_preserved_output_mode(output, width, line_limit, mode, Some("result"), locale)
32 }
33
34 pub(super) fn render_exec_output_mode(
35 output: &str,
36 width: u16,
37 line_limit: usize,
38 mode: RenderMode,
39 locale: Locale,
40 labeled: bool,
41 ) -> Vec<Line<'static>> {
42 render_preserved_output_mode(
43 output,
44 width,
45 line_limit,
46 mode,
47 labeled.then_some("output"),
48 locale,
49 )
50 }
51
52 #[derive(Debug, Clone, PartialEq, Eq)]
53 pub struct OutputRow {
54 pub text: String,
55 pub intact: bool,
56 /// SGR-styled segments of `text` when the source line carried colour
57 /// (`cargo`, `git`, `gh` with colour forced on, anything run through a
58 /// PTY). Concatenated they equal `text`; `None` for plain rows so the
59 /// common path allocates nothing extra.
60 pub styled: Option<Vec<StyledSegment>>,
61 }
62
63 const OUTPUT_DISPLAY_ROWS: usize = 512;
64 const MAX_SELECTED_ROWS: usize = (OUTPUT_DISPLAY_ROWS - 1) / 2;
65 const MAX_ROW_BYTES: usize = 4 * 1024;
66 const MAX_STYLE_RUNS: usize = 64;
67 const MAX_STYLED_LINE_BYTES: usize = 32 * 1024;
68
69 #[derive(Debug, Clone, Default, PartialEq, Eq)]
70 pub struct OutputProjection {
71 pub rows: Vec<OutputRow>,
72 pub omitted_before: Vec<usize>,
73 pub omitted_after: usize,
74 pub total_rows: usize,
75 pub total_nonblank: usize,
76 pub shortened: bool,
77 }
78
79 impl OutputProjection {
80 pub fn allocated_bytes(&self) -> usize {
81 let mut bytes = std::mem::size_of::<Self>()
82 .saturating_add(
83 self.rows
84 .capacity()
85 .saturating_mul(std::mem::size_of::<OutputRow>()),
86 )
87 .saturating_add(
88 self.omitted_before
89 .capacity()
90 .saturating_mul(std::mem::size_of::<usize>()),
91 );
92 for row in &self.rows {
93 bytes = bytes.saturating_add(row.text.capacity());
94 if let Some(segments) = &row.styled {
95 bytes = bytes.saturating_add(
96 segments
97 .capacity()
98 .saturating_mul(std::mem::size_of::<StyledSegment>()),
99 );
100 for (text, _) in segments {
101 bytes = bytes.saturating_add(text.capacity());
102 }
103 }
104 }
105 bytes
106 }
107 }
108
109 /// One run of `OutputRow::text` with the style the tool's own SGR codes
110 /// asked for. Only the painted preview uses these segments; source copying
111 /// retains the stored tool output independently.
112 pub type StyledSegment = (String, Style);
113
114 /// Heuristic: does the output look like a unified diff? Returns true when
115 /// the output contains at least one hunk header (`@@`) or a `diff --git`
116 /// line, which are reliable markers of unified diff content (#380).
117 pub(crate) fn output_looks_like_diff(output: &str) -> bool {
118 let mut lines = output.lines();
119 // Check first 5 lines for diff markers
120 for _ in 0..5 {
121 let Some(line) = lines.next() else { break };
122 let trimmed = line.trim();
123 if trimmed.starts_with("@@") || trimmed.starts_with("diff --git") {
124 return true;
125 }
126 }
127 false
128 }
129
130 /// Summary information extracted from an MCP tool output payload.
131 pub struct McpOutputSummary {
132 pub content: Option<String>,
133 pub is_image: bool,
134 pub is_error: Option<bool>,
135 }
136
137 /// Summarize raw MCP output into UI-friendly content.
138 #[must_use]
139 pub fn summarize_mcp_output(output: &str) -> McpOutputSummary {
140 if let Ok(json) = serde_json::from_str::<Value>(output) {
141 let is_error = json
142 .get("isError")
143 .and_then(serde_json::Value::as_bool)
144 .or_else(|| json.get("is_error").and_then(serde_json::Value::as_bool));
145
146 if let Some(blocks) = json.get("content").and_then(|v| v.as_array()) {
147 let mut lines = Vec::new();
148 let mut is_image = false;
149
150 for block in blocks {
151 let block_type = block
152 .get("type")
153 .and_then(|v| v.as_str())
154 .unwrap_or("unknown");
155 match block_type {
156 "text" => {
157 let text = block.get("text").and_then(|v| v.as_str()).unwrap_or("");
158 if !text.is_empty() {
159 lines.push(format!("- text: {}", truncate_text(text, 200)));
160 }
161 }
162 "image" | "image_url" => {
163 is_image = true;
164 let url = block
165 .get("url")
166 .or_else(|| block.get("image_url"))
167 .and_then(|v| v.as_str());
168 if let Some(url) = url {
169 lines.push(format!("- image: {}", truncate_text(url, 200)));
170 } else {
171 lines.push("- image".to_string());
172 }
173 }
174 "resource" | "resource_link" => {
175 let uri = block
176 .get("uri")
177 .or_else(|| block.get("url"))
178 .and_then(|v| v.as_str())
179 .unwrap_or("<resource>");
180 lines.push(format!("- resource: {}", truncate_text(uri, 200)));
181 }
182 other => {
183 lines.push(format!("- {other} content"));
184 }
185 }
186 }
187
188 return McpOutputSummary {
189 content: if lines.is_empty() {
190 None
191 } else {
192 Some(lines.join("\n"))
193 },
194 is_image,
195 is_error,
196 };
197 }
198 }
199
200 McpOutputSummary {
201 content: Some(summarize_tool_output(output)),
202 is_image: output_is_image(output),
203 is_error: None,
204 }
205 }
206
207 #[must_use]
208 pub fn output_is_image(output: &str) -> bool {
209 // Sniff the extensions case-insensitively over the raw bytes. Lowercasing
210 // the whole output first copied every byte of a payload that can run to
211 // hundreds of kilobytes, once per MCP completion, to answer a question
212 // about eight ASCII suffixes.
213 const IMAGE_EXTENSIONS: [&str; 8] = [
214 ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".ppm",
215 ];
216
217 let bytes = output.as_bytes();
218 IMAGE_EXTENSIONS.iter().any(|ext| {
219 let needle = ext.as_bytes();
220 bytes
221 .windows(needle.len())
222 .any(|window| window.eq_ignore_ascii_case(needle))
223 })
224 }
225
226 fn render_preserved_output_mode(
227 output: &str,
228 width: u16,
229 line_limit: usize,
230 mode: RenderMode,
231 first_label: Option<&str>,
232 locale: Locale,
233 ) -> Vec<Line<'static>> {
234 if let Some(label) = first_label {
235 debug_assert_eq!(label.len() + 2, FIRST_ROW_LABEL_COLUMNS);
236 }
237 let mut lines = Vec::new();
238 if mode == RenderMode::Source {
239 lines.push(render_card_detail_line_single(
240 first_label,
241 output,
242 tool_value_style(),
243 ));
244 return lines;
245 }
246 if output.trim().is_empty() {
247 // #3031: In compact/Live mode, suppress "(no output)" — the tool
248 // header already carries the success/failure status.
249 if mode == RenderMode::Transcript {
250 lines.push(Line::from(Span::styled(
251 " (no output)",
252 Style::default().fg(palette::TEXT_MUTED).italic(),
253 )));
254 }
255 return lines;
256 }
257
258 let transcript = mode == RenderMode::Transcript;
259 let limit = if transcript || line_limit == 0 {
260 MAX_SELECTED_ROWS
261 } else {
262 line_limit.clamp(1, MAX_SELECTED_ROWS)
263 };
264 let content_hash = crate::tui::output_rows_cache::hash_output(output);
265 let projection = crate::tui::output_rows_cache::get_or_compute_rows_with_hash(
266 content_hash,
267 width,
268 limit,
269 transcript,
270 || output_projection(output, width, limit),
271 );
272 let emit_gap = |lines: &mut Vec<Line<'static>>, omitted: usize| {
273 if omitted > 0 {
274 lines.push(details_affordance_line(
275 &format!(
276 "{} · {}",
277 tr(locale, MessageId::ApprovalMoreLines)
278 .replace("{count}", &omitted.to_string())
279 .trim_start(),
280 crate::tui::key_shortcuts::tool_details_shortcut_action_hint(&tr(
281 locale,
282 MessageId::FooterHintOutput
283 ),)
284 ),
285 Style::default().fg(palette::TEXT_MUTED),
286 ));
287 }
288 };
289 for (index, row) in projection.rows.iter().enumerate() {
290 emit_gap(&mut lines, projection.omitted_before[index]);
291 render_output_row(
292 &mut lines,
293 if index == 0 { first_label } else { None },
294 row,
295 width,
296 );
297 }
298 emit_gap(&mut lines, projection.omitted_after);
299 if projection.shortened {
300 lines.push(super::render_spillover_annotation(width, locale));
301 }
302 lines
303 }
304
305 fn output_projection(output: &str, width: u16, limit: usize) -> OutputProjection {
306 use std::collections::{BTreeSet, BinaryHeap, VecDeque};
307 let mut total = 0usize;
308 let mut nonblank = 0usize;
309 let mut first = Vec::with_capacity(limit);
310 let mut fill = Vec::with_capacity(limit);
311 let mut tail = VecDeque::with_capacity(TOOL_OUTPUT_TAIL_LINES);
312 let mut important = BinaryHeap::with_capacity(limit + TOOL_OUTPUT_TAIL_LINES);
313 let head = TOOL_OUTPUT_HEAD_LINES.min(limit / 2).max(1);
314 let mut shortened = false;
315 for_each_output_row(output, width, |row, clipped| {
316 let index = total;
317 total = total.saturating_add(1);
318 shortened |= clipped;
319 if first.len() < limit {
320 first.push(index);
321 }
322 if is_blank_row(&row) {
323 return;
324 }
325 nonblank = nonblank.saturating_add(1);
326 if fill.len() < limit {
327 fill.push(index);
328 }
329 if nonblank <= head {
330 return;
331 }
332 if tail.len() == TOOL_OUTPUT_TAIL_LINES {
333 tail.pop_front();
334 }
335 tail.push_back((index, states_outcome(&row.text)));
336 if let Some(rank) = output_importance_rank(&row.text) {
337 important.push((rank, index));
338 if important.len() > limit + TOOL_OUTPUT_TAIL_LINES {
339 important.pop();
340 }
341 }
342 });
343 let selected: BTreeSet<usize> = if total <= limit {
344 first.into_iter().collect()
345 } else if nonblank <= limit {
346 fill.into_iter().collect()
347 } else {
348 let tail_budget = TOOL_OUTPUT_TAIL_LINES.min(limit.saturating_sub(head));
349 let mut selected: BTreeSet<usize> = fill.iter().take(head).copied().collect();
350 let mut picked = Vec::with_capacity(tail_budget);
351 for &(index, outcome) in tail.iter().rev() {
352 if outcome && picked.len() < tail_budget {
353 picked.push(index);
354 }
355 }
356 for &(index, _) in tail.iter().rev() {
357 if picked.len() >= tail_budget {
358 break;
359 }
360 if !picked.contains(&index) {
361 picked.push(index);
362 }
363 }
364 selected.extend(picked);
365 let mut ranked = important.into_vec();
366 ranked.sort_unstable();
367 for (_, index) in ranked {
368 if selected.len() >= limit {
369 break;
370 }
371 selected.insert(index);
372 }
373 for index in fill {
374 if selected.len() >= limit {
375 break;
376 }
377 selected.insert(index);
378 }
379 selected
380 };
381 let mut projection = OutputProjection {
382 rows: Vec::with_capacity(limit.saturating_mul(2).saturating_add(1)),
383 omitted_before: Vec::with_capacity(limit.saturating_mul(2).saturating_add(1)),
384 total_rows: total,
385 total_nonblank: nonblank,
386 shortened,
387 ..Default::default()
388 };
389 let mut index = 0usize;
390 let mut hidden = 0usize;
391 let mut only = None;
392 for_each_output_row(output, width, |row, _| {
393 if selected.contains(&index) {
394 if hidden == 1 {
395 projection
396 .rows
397 .push(only.take().expect("one hidden row was retained"));
398 projection.omitted_before.push(0);
399 hidden = 0;
400 }
401 only = None;
402 projection.rows.push(row);
403 projection.omitted_before.push(hidden);
404 hidden = 0;
405 } else if !is_blank_row(&row) {
406 hidden = hidden.saturating_add(1);
407 if hidden == 1 {
408 only = Some(row);
409 } else {
410 only = None;
411 }
412 }
413 index = index.saturating_add(1);
414 });
415 if hidden == 1 {
416 projection
417 .rows
418 .push(only.expect("one hidden row was retained"));
419 projection.omitted_before.push(0);
420 } else {
421 projection.omitted_after = hidden;
422 }
423 projection
424 }
425
426 struct OutputRowStream {
427 text: String,
428 styled: Vec<StyledSegment>,
429 source_styled: bool,
430 width: usize,
431 first_width: usize,
432 current_width: usize,
433 intact: bool,
434 clipped: bool,
435 style_clipped: bool,
436 emitted: bool,
437 label_pending: bool,
438 }
439
440 impl OutputRowStream {
441 fn new(first_width: usize, width: usize, intact: bool, source_styled: bool) -> Self {
442 Self {
443 text: String::new(),
444 styled: Vec::new(),
445 source_styled,
446 width,
447 first_width,
448 current_width: 0,
449 intact,
450 clipped: false,
451 style_clipped: false,
452 emitted: false,
453 label_pending: true,
454 }
455 }
456
457 fn emit(&mut self, emit: &mut impl FnMut(OutputRow, bool)) {
458 if !self.text.trim().is_empty() {
459 self.label_pending = false;
460 }
461 let styled = std::mem::take(&mut self.styled);
462 let has_style = self.source_styled && !styled.is_empty();
463 emit(
464 OutputRow {
465 text: std::mem::take(&mut self.text),
466 intact: self.intact && !self.clipped,
467 styled: (has_style && !self.style_clipped).then_some(styled),
468 },
469 self.clipped || self.style_clipped,
470 );
471 self.current_width = 0;
472 self.emitted = true;
473 self.clipped = false;
474 self.style_clipped = false;
475 }
476
477 fn push(
478 &mut self,
479 grapheme: codewhale_tui_kit::ui_text::DisplayGrapheme<'_>,
480 styles: &[Style],
481 emit: &mut impl FnMut(OutputRow, bool),
482 ) {
483 if self.intact && self.clipped {
484 return;
485 }
486 if self.intact && grapheme.clipped_bytes > 0 {
487 self.text.clear();
488 self.text.push('…');
489 self.styled.clear();
490 self.clipped = true;
491 return;
492 }
493 if self.intact && self.text.len().saturating_add(grapheme.text.len()) > MAX_ROW_BYTES {
494 self.text.clear();
495 self.text.push('…');
496 self.styled.clear();
497 self.clipped = true;
498 return;
499 }
500 if grapheme.text.len() > MAX_ROW_BYTES {
501 if !self.text.is_empty() {
502 self.emit(emit);
503 }
504 self.text.push('…');
505 self.clipped = true;
506 self.emit(emit);
507 return;
508 }
509 let limit = if self.label_pending {
510 self.first_width
511 } else {
512 self.width
513 };
514 let byte_limit = self.text.len().saturating_add(grapheme.text.len()) > MAX_ROW_BYTES;
515 if !self.intact
516 && !self.text.is_empty()
517 && (byte_limit || self.current_width.saturating_add(grapheme.width) > limit)
518 {
519 let start = (!byte_limit)
520 .then(|| last_word_start(&self.text, grapheme.text, limit))
521 .flatten();
522 let carry = start.map(|at| self.text.split_off(at)).unwrap_or_default();
523 let carry_style = if !self.style_clipped && !self.styled.is_empty() {
524 let parts = [self.text.clone(), carry.clone()];
525 let mut split = split_segments(&self.styled, &parts);
526 self.styled = std::mem::take(&mut split[0]);
527 std::mem::take(&mut split[1])
528 } else {
529 Vec::new()
530 };
531 let carry_clipped = self.style_clipped && !carry.is_empty();
532 self.emit(emit);
533 self.current_width = UnicodeWidthStr::width(carry.as_str());
534 self.text = carry;
535 self.styled = carry_style;
536 self.style_clipped = carry_clipped;
537 }
538 self.text.push_str(grapheme.text);
539 self.current_width = self.current_width.saturating_add(grapheme.width);
540 self.clipped |= grapheme.clipped_bytes > 0;
541 if !self.style_clipped {
542 for &(ch, tag) in grapheme.cells {
543 let style = styles.get(tag).copied().unwrap_or_default();
544 if let Some((text, previous)) = self.styled.last_mut()
545 && *previous == style
546 {
547 text.push(ch);
548 } else if self.styled.len() < MAX_STYLE_RUNS {
549 self.styled.push((ch.to_string(), style));
550 } else {
551 self.styled.clear();
552 self.style_clipped = true;
553 break;
554 }
555 }
556 }
557 }
558
559 fn finish(mut self, emit: &mut impl FnMut(OutputRow, bool)) {
560 if !self.text.is_empty() || !self.emitted {
561 self.emit(emit);
562 }
563 }
564 }
565
566 #[derive(Default)]
567 struct PathLike {
568 prefix: [char; 5],
569 prefix_chars: usize,
570 previous: [char; 2],
571 url: bool,
572 separator: bool,
573 extension: bool,
574 suffix: Option<usize>,
575 bytes: usize,
576 }
577
578 impl PathLike {
579 fn push(&mut self, text: &str) {
580 self.bytes = self.bytes.saturating_add(text.len());
581 for ch in text.chars() {
582 if self.prefix_chars < 5 && (self.prefix_chars > 0 || !ch.is_whitespace()) {
583 self.prefix[self.prefix_chars] = ch;
584 self.prefix_chars += 1;
585 }
586 self.url |= self.previous == [':', '/'] && ch == '/';
587 self.previous = [self.previous[1], ch];
588 self.separator |= matches!(ch, '/' | '\\');
589 if ch.is_whitespace() {
590 self.extension |= self.suffix.is_some_and(|bytes| bytes <= 8);
591 self.suffix = None;
592 } else if ch == '.' {
593 self.suffix = Some(0);
594 } else if let Some(bytes) = self.suffix.as_mut() {
595 *bytes = bytes.saturating_add(ch.len_utf8());
596 }
597 }
598 }
599
600 fn finish(self) -> bool {
601 self.url
602 || self.prefix == ['f', 'i', 'l', 'e', ':']
603 || self.separator
604 && (self.bytes > MAX_ROW_BYTES
605 || self.extension
606 || self.suffix.is_some_and(|bytes| bytes <= 8))
607 }
608 }
609
610 fn for_each_output_row(output: &str, width: u16, mut emit: impl FnMut(OutputRow, bool)) {
611 use codewhale_tui_kit::ui_text::DisplayNormalizer;
612 let wrap_width = width.saturating_sub(4).max(1) as usize;
613 let first_width = usize::from(width)
614 .saturating_sub(UnicodeWidthStr::width(TRANSCRIPT_RAIL) + FIRST_ROW_LABEL_COLUMNS)
615 .clamp(1, wrap_width);
616 let mut first = true;
617 let mut emitted = false;
618 for line in output.lines() {
619 let requires_strip = line
620 .bytes()
621 .any(|byte| byte == 0x1b || byte < 0x20 && !matches!(byte, b'\r' | b'\t'));
622 let mut path = PathLike::default();
623 let plain = if requires_strip {
624 let mut plain = String::with_capacity(line.len().min(MAX_STYLED_LINE_BYTES));
625 let mut bounded = true;
626 codewhale_sanitize::sanitize::visit_ansi_text(line, |part| {
627 path.push(part);
628 if bounded && plain.len().saturating_add(part.len()) <= MAX_STYLED_LINE_BYTES {
629 plain.push_str(part);
630 } else {
631 bounded = false;
632 plain.clear();
633 }
634 });
635 bounded.then_some(std::borrow::Cow::Owned(plain))
636 } else {
637 path.push(line);
638 (line.len() <= MAX_STYLED_LINE_BYTES).then_some(std::borrow::Cow::Borrowed(line))
639 };
640 let styled = plain
641 .as_deref()
642 .filter(|_| line.len() <= MAX_STYLED_LINE_BYTES)
643 .and_then(|plain| styled_segments(line, plain));
644 let styles: Vec<Style> = styled
645 .as_ref()
646 .map(|segments| segments.iter().map(|(_, style)| *style).collect())
647 .unwrap_or_default();
648 let mut stream = OutputRowStream::new(
649 if first { first_width } else { wrap_width },
650 wrap_width,
651 path.finish(),
652 !styles.is_empty(),
653 );
654 stream.style_clipped =
655 styled.is_none() && line.len() > MAX_STYLED_LINE_BYTES && line.contains('\x1b');
656 let mut normalizer = DisplayNormalizer::new(0);
657 let mut emit_row = |row: OutputRow, clipped| {
658 if !row.text.trim().is_empty() {
659 first = false;
660 }
661 emitted = true;
662 emit(row, clipped);
663 };
664 {
665 let mut emit_grapheme = |grapheme: codewhale_tui_kit::ui_text::DisplayGrapheme<'_>| {
666 if grapheme.clipped_bytes == 0 {
667 stream.push(grapheme, &styles, &mut emit_row);
668 } else {
669 let mut offset = 0usize;
670 for part in grapheme.text.graphemes(true) {
671 let count = part.chars().count();
672 stream.push(
673 codewhale_tui_kit::ui_text::DisplayGrapheme {
674 text: part,
675 cells: &grapheme.cells[offset..offset + count],
676 width: UnicodeWidthStr::width(part),
677 clipped_bytes: grapheme.clipped_bytes,
678 escaped: grapheme.escaped,
679 },
680 &styles,
681 &mut emit_row,
682 );
683 offset += count;
684 }
685 }
686 };
687 if let Some(segments) = &styled {
688 for (tag, (text, _)) in segments.iter().enumerate() {
689 normalizer.push(text, tag, &mut emit_grapheme);
690 }
691 } else if let Some(plain) = &plain {
692 normalizer.push(plain, 0, &mut emit_grapheme);
693 } else if requires_strip {
694 codewhale_sanitize::sanitize::visit_ansi_text(line, |part| {
695 normalizer.push(part, 0, &mut emit_grapheme)
696 });
697 } else {
698 normalizer.push(line, 0, &mut emit_grapheme);
699 }
700 normalizer.finish(&mut emit_grapheme);
701 }
702 stream.finish(&mut emit_row);
703 }
704 if !emitted {
705 emit(
706 OutputRow {
707 text: String::new(),
708 intact: false,
709 styled: None,
710 },
711 false,
712 );
713 }
714 }
715
716 #[cfg(test)]
717 fn output_rows(output: &str, width: u16) -> Vec<OutputRow> {
718 let mut rows = Vec::new();
719 for_each_output_row(output, width, |row, _| rows.push(row));
720 rows
721 }
722
723 /// Parse the SGR codes in `line` into styled segments whose text
724 /// concatenates to `plain` (the fully stripped line). Returns `None` when the
725 /// line carries no escape at all, when nothing in it sets a style, or when
726 /// the parse disagrees with the plain strip — the plain path is then the
727 /// truth, exactly as before.
728 fn styled_segments(line: &str, plain: &str) -> Option<Vec<StyledSegment>> {
729 use ansi_to_tui::IntoText;
730
731 if !line.contains('\x1b') {
732 return None;
733 }
734 let mut kept = String::with_capacity(line.len());
735 codewhale_sanitize::sanitize::strip_ansi_keep_sgr_into(line, &mut kept);
736 let text = kept.into_text().ok()?;
737 let mut segments: Vec<StyledSegment> = Vec::new();
738 for parsed in text.lines {
739 for span in parsed.spans {
740 if span.content.is_empty() {
741 continue;
742 }
743 let style = tool_style(span.style);
744 match segments.last_mut() {
745 Some((last, last_style)) if *last_style == style => {
746 last.push_str(&span.content);
747 }
748 _ => segments.push((span.content.into_owned(), style)),
749 }
750 }
751 }
752 let round_trip: String = segments.iter().map(|(text, _)| text.as_str()).collect();
753 if round_trip != plain || segments.iter().all(|(_, style)| *style == Style::default()) {
754 return None;
755 }
756 Some(segments)
757 }
758
759 /// What the tool asked for, expressed relative to the cell's own ink. A
760 /// tool's *reset* (`ESC[0m`, or `Color::Reset`) means "back to the
761 /// terminal default", and in the transcript that default is the value style
762 /// the cell already paints — so resets become "nothing set" instead of a
763 /// `Style::reset()` that would wipe the cell's dim/state colour when
764 /// patched over it. Only positive requests (a colour, bold, underline)
765 /// survive.
766 fn tool_style(style: Style) -> Style {
767 let keep = |colour: Option<ratatui::style::Color>| {
768 colour.filter(|c| *c != ratatui::style::Color::Reset)
769 };
770 let mut out = Style::default().add_modifier(style.add_modifier);
771 if let Some(fg) = keep(style.fg) {
772 out = out.fg(fg);
773 }
774 if let Some(bg) = keep(style.bg) {
775 out = out.bg(bg);
776 }
777 out
778 }
779
780 /// Re-split styled segments along the boundaries `wrap_text` chose, so each
781 /// wrapped part keeps the colours of the characters it holds. `parts` must
782 /// concatenate to the segments' text (which is how `wrap_text` splits).
783 pub(super) fn split_segments(
784 segments: &[StyledSegment],
785 parts: &[String],
786 ) -> Vec<Vec<StyledSegment>> {
787 let mut chars = segments
788 .iter()
789 .flat_map(|(text, style)| text.chars().map(move |ch| (ch, *style)));
790 parts
791 .iter()
792 .map(|part| {
793 let mut out: Vec<StyledSegment> = Vec::new();
794 for (ch, style) in chars.by_ref().take(part.chars().count()) {
795 match out.last_mut() {
796 Some((last, last_style)) if *last_style == style => last.push(ch),
797 _ => out.push((ch.to_string(), style)),
798 }
799 }
800 out
801 })
802 .collect()
803 }
804
805 fn is_blank_row(row: &OutputRow) -> bool {
806 row.text.trim().is_empty()
807 }
808
809 /// Does the row say that something passed or failed? Plain words only, the
810 /// same way `output_importance_rank` spots errors — no tool's format is parsed.
811 fn states_outcome(line: &str) -> bool {
812 const OUTCOME_WORDS: [&str; 10] = [
813 "pass", "passed", "passes", "passing", "fail", "failed", "fails", "failing", "failure",
814 "failures",
815 ];
816 line.split(|ch: char| !ch.is_ascii_alphabetic())
817 .any(|word| {
818 OUTCOME_WORDS
819 .iter()
820 .any(|outcome| word.eq_ignore_ascii_case(outcome))
821 })
822 }
823
824 fn output_importance_rank(line: &str) -> Option<usize> {
825 let contains = |needle: &str| {
826 line.as_bytes()
827 .windows(needle.len())
828 .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
829 };
830 if [
831 "error",
832 "failed",
833 "failure",
834 "fatal",
835 "panic",
836 "exception",
837 "traceback",
838 "denied",
839 "not found",
840 "no such file",
841 "cannot",
842 "can't",
843 ]
844 .iter()
845 .any(|needle| contains(needle))
846 {
847 return Some(0);
848 }
849 if contains("warning") || contains("warn") {
850 return Some(1);
851 }
852 is_path_or_url_like(line).then_some(2)
853 }
854
855 fn is_path_or_url_like(line: &str) -> bool {
856 let mut path = PathLike::default();
857 path.push(line);
858 path.finish()
859 }
860
861 /// Detect whether a line contains a `path:line` pattern that could be
862 /// opened by `first_file_line_reference`. Returns a distinctive style
863 /// (underline + blue) when the pattern matches, or `None` otherwise.
864 /// The style is applied over the existing value style so the line
865 /// remains readable.
866 fn file_line_style(text: &str) -> Option<Style> {
867 let trimmed = text.trim();
868 if let Some((before, after)) = trimmed.rsplit_once(':')
869 && !before.is_empty()
870 && after.chars().all(|c| c.is_ascii_digit())
871 && looks_like_file_path(before)
872 {
873 Some(
874 Style::default()
875 .fg(palette::WHALE_ACTION)
876 .add_modifier(ratatui::style::Modifier::UNDERLINED),
877 )
878 } else {
879 None
880 }
881 }
882
883 /// Apply inline diff highlighting to a single text line.
884 ///
885 /// Returns the appropriate style for the line based on its prefix:
886 /// - Lines starting with `+` (after trimming) => `palette::DIFF_ADDED` (green)
887 /// - Lines starting with `-` (after trimming) => `palette::STATUS_ERROR` (red)
888 /// - Lines starting with `@@` => `palette::WHALE_ACTION` (cyan/blue)
889 /// - All other lines => None (use default style)
890 fn diff_line_style(text: &str) -> Option<Style> {
891 let trimmed = text.trim_start();
892 if trimmed.starts_with("@@") {
893 Some(Style::default().fg(palette::WHALE_ACTION))
894 } else if trimmed.starts_with('+') && !trimmed.starts_with("+++") {
895 Some(Style::default().fg(palette::DIFF_ADDED))
896 } else if trimmed.starts_with('-') && !trimmed.starts_with("---") {
897 Some(Style::default().fg(palette::STATUS_ERROR))
898 } else {
899 None
900 }
901 }
902
903 fn render_output_row(
904 lines: &mut Vec<Line<'static>>,
905 label: Option<&str>,
906 row: &OutputRow,
907 _width: u16,
908 ) {
909 // #374: apply file:line highlighting when the row text contains
910 // a `path:line` pattern. Diff style takes precedence (colored
911 // prefix lines should stay colored), but if no diff style matched,
912 // check for a file:line pattern and highlight it distinctively.
913 let diff_style = diff_line_style(&row.text);
914 let file_style = file_line_style(&row.text);
915 let value_style = diff_style.or(file_style).unwrap_or_else(tool_value_style);
916 if let Some(segments) = &row.styled {
917 lines.push(render_card_detail_line_single_styled(
918 label,
919 segments,
920 value_style,
921 ));
922 } else {
923 lines.push(render_card_detail_line_single(
924 label,
925 &row.text,
926 value_style,
927 ));
928 }
929 }
930
931 pub(super) fn wrap_plain_line(line: &str, style: Style, width: u16) -> Vec<Line<'static>> {
932 let mut lines = Vec::new();
933 for part in wrap_text(line, width.max(1) as usize) {
934 lines.push(Line::from(Span::styled(part, style)));
935 }
936 lines
937 }
938
939 /// Wrap `text` to `width` columns, ending each row between words when it
940 /// can. A word longer than a row is still split between graphemes.
941 ///
942 /// Nothing is dropped or added: the rows concatenate back to `text`, with
943 /// the whitespace a row was broken at left on the end of that row. Tool
944 /// output keeps its column alignment, and `split_segments` can lay the
945 /// colours back over the rows by counting characters.
946 pub(super) fn wrap_text(text: &str, width: usize) -> Vec<String> {
947 let mut lines = Vec::new();
948 for_each_wrapped_text(text, width, |part| lines.push(part.to_string()));
949 lines
950 }
951
952 pub(super) fn for_each_wrapped_text(text: &str, width: usize, mut emit: impl FnMut(&str)) {
953 if width == 0 || text.is_empty() {
954 emit(text);
955 return;
956 }
957 let mut start = 0usize;
958 for (index, grapheme) in text.grapheme_indices(true) {
959 let end = index + grapheme.len();
960 if start < index && UnicodeWidthStr::width(&text[start..end]) > width {
961 let split = last_word_start(&text[start..index], grapheme, width)
962 .map_or(index, |at| start + at);
963 emit(&text[start..split]);
964 start = split;
965 }
966 }
967 emit(&text[start..]);
968 }
969
970 /// Where the last word of a full `row` starts, when that word should move
971 /// down to the next row together with `next`, the grapheme that did not fit.
972 ///
973 /// `None` means break right where the row ends: it already ends between
974 /// words, it is one unbroken word, everything before the word is
975 /// indentation, or the word would not fit on the next row either.
976 fn last_word_start(row: &str, next: &str, width: usize) -> Option<usize> {
977 let is_space = |text: &str| text.chars().all(char::is_whitespace);
978 let words = row.trim_end();
979 if words.len() < row.len() && !is_space(next) {
980 return None;
981 }
982 let (space, gap) = words
983 .grapheme_indices(true)
984 .rev()
985 .find(|(_, grapheme)| is_space(grapheme))?;
986 let start = space + gap.len();
987 let fits = UnicodeWidthStr::width(&row[start..]) + UnicodeWidthStr::width(next) <= width;
988 (fits && !row[..space].trim().is_empty()).then_some(start)
989 }
990
991 #[cfg(test)]
992 mod ansi_colour_tests {
993 use super::*;
994 use ratatui::style::{Color, Modifier};
995
996 fn styled_text(rows: &[OutputRow]) -> Vec<String> {
997 rows.iter()
998 .map(|row| {
999 row.styled
1000 .as_ref()
1001 .map(|segments| segments.iter().map(|(t, _)| t.as_str()).collect())
1002 .unwrap_or_default()
1003 })
1004 .collect()
1005 }
1006
1007 #[test]
1008 fn plain_line_carries_no_styled_segments() {
1009 let rows = output_rows(" Compiling codewhale v0.9.12", 80);
1010 assert_eq!(rows.len(), 1);
1011 assert_eq!(rows[0].text, " Compiling codewhale v0.9.12");
1012 assert!(rows[0].styled.is_none());
1013 }
1014
1015 #[test]
1016 fn cargo_style_line_keeps_its_green_bold_verb() {
1017 let line = "\x1b[1m\x1b[32m Compiling\x1b[0m codewhale v0.9.12";
1018 let rows = output_rows(line, 80);
1019 assert_eq!(rows.len(), 1);
1020 assert_eq!(rows[0].text, " Compiling codewhale v0.9.12");
1021 let segments = rows[0]
1022 .styled
1023 .as_ref()
1024 .expect("coloured line keeps segments");
1025 assert_eq!(segments[0].0, " Compiling");
1026 assert_eq!(segments[0].1.fg, Some(Color::Green));
1027 assert!(segments[0].1.add_modifier.contains(Modifier::BOLD));
1028 assert_eq!(segments[1].0, " codewhale v0.9.12");
1029 assert_eq!(segments[1].1, Style::default());
1030 assert_eq!(styled_text(&rows), vec![rows[0].text.clone()]);
1031 }
1032
1033 #[test]
1034 fn osc8_link_is_stripped_while_its_sgr_colour_survives() {
1035 let line =
1036 "see \x1b]8;;https://example.com/x\x1b\\\x1b[31mthe docs\x1b[0m\x1b]8;;\x1b\\ now";
1037 let rows = output_rows(line, 80);
1038 assert_eq!(rows.len(), 1);
1039 assert_eq!(rows[0].text, "see the docs now");
1040 let segments = rows[0]
1041 .styled
1042 .as_ref()
1043 .expect("SGR inside an OSC 8 wrapper");
1044 assert_eq!(segments[0], ("see ".to_string(), Style::default()));
1045 assert_eq!(segments[1].0, "the docs");
1046 assert_eq!(segments[1].1.fg, Some(Color::Red));
1047 assert_eq!(segments[2], (" now".to_string(), Style::default()));
1048 }
1049
1050 #[test]
1051 fn wrapped_rows_split_the_colour_along_wrap_boundaries() {
1052 let line = format!("\x1b[33m{}\x1b[0m{}", "y".repeat(12), "p".repeat(8));
1053 // width 12 → the labelled first row holds 2 characters and the rows
1054 // under it 8: rows of 2/8/8/2.
1055 let rows = output_rows(&line, 12);
1056 assert_eq!(rows.len(), 4);
1057 assert_eq!(
1058 styled_text(&rows),
1059 rows.iter().map(|r| r.text.clone()).collect::<Vec<_>>()
1060 );
1061 let third = rows[2].styled.as_ref().unwrap();
1062 assert_eq!(
1063 third[0],
1064 ("yy".to_string(), Style::default().fg(Color::Yellow))
1065 );
1066 assert_eq!(third[1], ("pppppp".to_string(), Style::default()));
1067 }
1068
1069 #[test]
1070 fn painted_span_patches_tool_colour_over_the_cell_style() {
1071 let rows = output_rows("\x1b[31merror\x1b[0m: boom", 80);
1072 let mut lines = Vec::new();
1073 render_output_row(&mut lines, Some("output"), &rows[0], 80);
1074 assert_eq!(lines.len(), 1);
1075 let spans = &lines[0].spans;
1076 // rail, label, gap, "error", ": boom"
1077 assert_eq!(spans[3].content, "error");
1078 assert_eq!(spans[3].style.fg, Some(Color::Red));
1079 assert_eq!(spans[4].content, ": boom");
1080 assert_eq!(spans[4].style, tool_value_style());
1081 let plain: String = spans[3..].iter().map(|s| s.content.as_ref()).collect();
1082 assert_eq!(plain, "error: boom");
1083 }
1084
1085 #[test]
1086 fn coloured_intact_path_stays_on_one_line_with_the_plain_hitbox() {
1087 let path = "crates/tui/src/tui/history/tool_output.rs:812";
1088 let coloured = format!("\x1b[35m{path}\x1b[0m");
1089 let plain_rows = output_rows(path, 20);
1090 let styled_rows = output_rows(&coloured, 20);
1091 assert_eq!(plain_rows.len(), 1);
1092 assert_eq!(styled_rows.len(), 1);
1093 assert!(plain_rows[0].intact && styled_rows[0].intact);
1094 assert!(styled_rows[0].styled.is_some());
1095
1096 let mut plain = Vec::new();
1097 render_output_row(&mut plain, Some("output"), &plain_rows[0], 20);
1098 let mut styled = Vec::new();
1099 render_output_row(&mut styled, Some("output"), &styled_rows[0], 20);
1100 assert_eq!(plain.len(), 1, "plain intact row is one line");
1101 assert_eq!(styled.len(), 1, "coloured intact row is one line too");
1102 let text = |line: &Line<'static>| {
1103 line.spans
1104 .iter()
1105 .map(|s| s.content.as_ref())
1106 .collect::<String>()
1107 };
1108 assert_eq!(text(&styled[0]), text(&plain[0]));
1109 // Same prefix (rail + label + gap), so the click region is identical.
1110 assert_eq!(
1111 styled[0].spans[..3]
1112 .iter()
1113 .map(|s| s.content.as_ref())
1114 .collect::<Vec<_>>(),
1115 plain[0].spans[..3]
1116 .iter()
1117 .map(|s| s.content.as_ref())
1118 .collect::<Vec<_>>()
1119 );
1120 assert_eq!(styled[0].spans[3].style.fg, Some(Color::Magenta));
1121 }
1122
1123 #[test]
1124 fn a_line_that_only_resets_stays_on_the_plain_path() {
1125 let rows = output_rows("done\x1b[0m", 80);
1126 assert_eq!(rows[0].text, "done");
1127 assert!(rows[0].styled.is_none());
1128 }
1129
1130 #[test]
1131 fn image_sniffing_is_case_insensitive_over_the_raw_bytes() {
1132 assert!(output_is_image("saved to /tmp/Chart.PNG"));
1133 assert!(output_is_image("shot.jpeg"));
1134 assert!(output_is_image(".WEBP"));
1135 assert!(!output_is_image("no image here"));
1136 // The historical `contains` contract is preserved: a name that merely
1137 // embeds an extension still counts.
1138 assert!(output_is_image("weird.pngx"));
1139 // A byte-window scan must not panic on multi-byte text.
1140 assert!(!output_is_image("日本語のテキストのみ"));
1141 assert!(!output_is_image(""));
1142 }
1143
1144 #[test]
1145 fn wrap_text_breaks_between_graphemes() {
1146 // An emoji-presentation heart and a keycap are one two-column
1147 // grapheme each, the way Ratatui counts cells.
1148 for text in ["ab\u{2764}\u{fe0f}cd", "ab1\u{fe0f}\u{20e3}cd"] {
1149 for width in 2..=6 {
1150 let lines = wrap_text(text, width);
1151 let rejoined: Vec<&str> =
1152 lines.iter().flat_map(|line| line.graphemes(true)).collect();
1153 assert_eq!(
1154 rejoined,
1155 text.graphemes(true).collect::<Vec<_>>(),
1156 "width {width} split a grapheme: {lines:?}"
1157 );
1158 for line in &lines {
1159 assert!(line.width() <= width, "line {line:?} exceeds width {width}");
1160 }
1161 }
1162 }
1163 }
1164
1165 #[test]
1166 fn wrap_text_ends_rows_between_words() {
1167 assert_eq!(
1168 wrap_text("Bring a refillable water bottle.", 22),
1169 ["Bring a refillable ", "water bottle."]
1170 );
1171 // A row that is exactly full still ends on a whole word.
1172 assert_eq!(wrap_text("aaa bbb ccc", 7), ["aaa ", "bbb ccc"]);
1173 // Only a word longer than the row is split, and indentation is not
1174 // mistaken for a place to break.
1175 assert_eq!(
1176 wrap_text(" averyverylongtoken tail", 10),
1177 [" averyv", "erylongtok", "en tail"]
1178 );
1179 assert_eq!(
1180 wrap_text(&"y".repeat(20), 8),
1181 ["y".repeat(8), "y".repeat(8), "y".repeat(4)]
1182 );
1183 }
1184
1185 #[test]
1186 fn wrap_text_keeps_every_character_and_stays_within_the_width() {
1187 for text in [
1188 "name size modified",
1189 "aaa bbb",
1190 "word x",
1191 " ",
1192 "日本語のテキスト と english mixed 語語語語語語",
1193 "a \u{301}b c d e f",
1194 "tab\tseparated\tvalues",
1195 ] {
1196 for width in 1..=14 {
1197 let lines = wrap_text(text, width);
1198 assert_eq!(lines.concat(), text, "width {width} changed the text");
1199 for line in &lines {
1200 assert!(
1201 line.width() <= width || line.graphemes(true).count() == 1,
1202 "line {line:?} exceeds width {width}"
1203 );
1204 assert_eq!(
1205 wrap_text(line, width),
1206 std::slice::from_ref(line),
1207 "a wrapped row must not wrap again at width {width}"
1208 );
1209 }
1210 }
1211 }
1212 }
1213
1214 /// The tutorial frame that showed `refillable wate / r bott / le.`: one
1215 /// long MCP result line, wrapped once for the card and once more behind
1216 /// the `result:` label.
1217 #[test]
1218 fn long_result_line_wraps_between_words_and_only_once() {
1219 let output = "- text: Next shoreline cleanup: Saturday at 09:00, North Pier. \
1220 Bring gloves and a refillable water bottle. (Demo data.)";
1221 for width in [60, 100, 110] {
1222 let lines = render_tool_output_mode(output, width, 20, RenderMode::Live, Locale::En);
1223 let rows: Vec<String> = lines
1224 .iter()
1225 .map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
1226 .collect();
1227 assert_eq!(
1228 rows.len(),
1229 output_rows(output, width).len(),
1230 "painting wrapped a row a second time at width {width}: {rows:#?}"
1231 );
1232 let words: Vec<&str> = rows
1233 .iter()
1234 .flat_map(|row| row.split_whitespace())
1235 .filter(|word| *word != TRANSCRIPT_RAIL.trim() && *word != "result:")
1236 .collect();
1237 assert_eq!(
1238 words,
1239 output.split_whitespace().collect::<Vec<_>>(),
1240 "a word was split at width {width}: {rows:#?}"
1241 );
1242 for row in &rows {
1243 assert!(row.width() <= usize::from(width), "{row:?} exceeds {width}");
1244 }
1245 }
1246 }
1247 }
1248
1248 lines RUST