返回 CodeWhale
thinking.rs
根目录 / crates / tui / src / tui / history / thinking.rs
1 //! Rendering for reasoning/thinking transcript cells.
2
3 use ratatui::style::{Color, Modifier, Style};
4 use ratatui::text::{Line, Span};
5
6 use crate::tui::thinking_checkpoint::{Checkpoints, THINKING_STREAMING_PREVIEW_LINE_LIMIT};
7 use codewhale_localization::{Locale, MessageId, tr};
8 use codewhale_palette as palette;
9 use codewhale_tui_kit::markdown_render;
10
11 /// Reasoning header opener. Replaces the spinner glyph on thinking cells —
12 /// reasoning is a slow exhale, not a tool spin.
13 pub(super) const REASONING_OPENER: &str = "\u{2026}"; // …
14 /// Reasoning body left rail. Dashed (`╎`) instead of the solid `▏` block to
15 /// visually separate reasoning from message body and tool output.
16 pub(super) const REASONING_RAIL: &str = "\u{254E} "; // ╎ + space
17 /// Trailing-line cursor on streaming reasoning. Anchored to the live colour
18 /// so the user sees where new tokens land.
19 pub(super) const REASONING_CURSOR: &str = "\u{258E}"; // ▎
20
21 const THINKING_SUMMARY_LINE_LIMIT: usize = 4;
22 /// Non-calm completed preview; calm mode uses a header-only projection.
23 const THINKING_COMPLETED_PREVIEW_LINE_LIMIT: usize = 2;
24
25 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
26 enum ThinkingVisualState {
27 Live,
28 Done,
29 Idle,
30 }
31
32 #[cfg(test)]
33 #[must_use]
34 pub fn extract_reasoning_summary(text: &str) -> Option<String> {
35 extract_explicit_reasoning_summary(text).or_else(|| {
36 let fallback = text.trim();
37 if fallback.is_empty() {
38 None
39 } else {
40 Some(fallback.to_string())
41 }
42 })
43 }
44
45 fn extract_explicit_reasoning_summary(text: &str) -> Option<String> {
46 let mut lines = text.lines().peekable();
47 while let Some(line) = lines.next() {
48 let trimmed = line.trim();
49 if trimmed.to_lowercase().starts_with("summary") {
50 let mut summary = String::new();
51 if let Some((_, rest)) = trimmed.split_once(':')
52 && !rest.trim().is_empty()
53 {
54 summary.push_str(rest.trim());
55 summary.push('\n');
56 }
57 while let Some(next) = lines.peek() {
58 let next_trimmed = next.trim();
59 if next_trimmed.is_empty() {
60 break;
61 }
62 if next_trimmed.starts_with('#') || next_trimmed.starts_with("**") {
63 break;
64 }
65 summary.push_str(next_trimmed);
66 summary.push('\n');
67 lines.next();
68 }
69 let summary = summary.trim().to_string();
70 return if summary.is_empty() {
71 None
72 } else {
73 Some(summary)
74 };
75 }
76 }
77 None
78 }
79
80 pub(super) fn render_thinking(
81 content: &str,
82 width: u16,
83 streaming: bool,
84 duration_secs: Option<f32>,
85 collapsed: bool,
86 low_motion: bool,
87 ) -> Vec<Line<'static>> {
88 render_thinking_with_analysis(
89 content,
90 width,
91 streaming,
92 duration_secs,
93 collapsed,
94 low_motion,
95 true,
96 )
97 .0
98 }
99
100 pub(crate) fn render_thinking_with_analysis(
101 content: &str,
102 width: u16,
103 streaming: bool,
104 duration_secs: Option<f32>,
105 collapsed: bool,
106 low_motion: bool,
107 highlight: bool,
108 ) -> (Vec<Line<'static>>, bool) {
109 render_thinking_with_preview_limit(
110 content,
111 width,
112 streaming,
113 duration_secs,
114 collapsed,
115 low_motion,
116 highlight,
117 Locale::En,
118 THINKING_COMPLETED_PREVIEW_LINE_LIMIT,
119 markdown_render::detected_palette_mode(),
120 Checkpoints::default(),
121 )
122 }
123
124 #[allow(clippy::too_many_arguments)]
125 pub(crate) fn render_thinking_with_preview_limit(
126 content: &str,
127 width: u16,
128 streaming: bool,
129 duration_secs: Option<f32>,
130 collapsed: bool,
131 low_motion: bool,
132 highlight: bool,
133 locale: Locale,
134 completed_preview_lines: usize,
135 palette_mode: palette::PaletteMode,
136 checkpoints: Checkpoints,
137 ) -> (Vec<Line<'static>>, bool) {
138 let state = thinking_visual_state(streaming, duration_secs);
139 let style = thinking_style();
140 // 12% reasoning surface tint over the app ink — the only deliberately
141 // warm element in the transcript. Dropped on Ansi-16 terminals where the
142 // tint would distort the named palette.
143 let depth = cached_color_depth();
144 let body_bg = palette::reasoning_surface_tint(depth);
145 let body_style = match (highlight, body_bg) {
146 (true, Some(bg)) => style.italic().bg(bg),
147 (_, None) | (false, Some(_)) => style.italic(),
148 };
149 let mut lines = Vec::new();
150
151 let label = if streaming {
152 format!("{}…", tr(locale, MessageId::WhaleStateThinking))
153 } else if let Some(duration) = duration_secs.filter(|duration| *duration >= 1.0) {
154 tr(locale, MessageId::TranscriptThoughtFor).replace(
155 "{duration}",
156 &codewhale_command_contract::elapsed::format_elapsed_ms((duration * 1000.0) as u64),
157 )
158 } else {
159 tr(locale, MessageId::TranscriptThought).into_owned()
160 };
161 lines.push(Line::from(vec![
162 Span::styled(
163 format!("{REASONING_OPENER} "),
164 Style::default().fg(thinking_state_accent(state)),
165 ),
166 Span::styled(label, Style::default().fg(thinking_state_accent(state))),
167 ]));
168
169 let content_width = width.saturating_sub(3).max(1);
170 // #6196: compute only the projection being shown. The previous order ran
171 // the collapsed preview render first and threw it away whenever the body
172 // was expanded — a full extra body render per streaming beat.
173 let (rendered, expandable) = if collapsed
174 && streaming
175 && checkpoints.excerpts[1].is_some()
176 && let Some(tail) = content.get(checkpoints.tail..)
177 {
178 let mut rows = Vec::new();
179 for (index, excerpt) in checkpoints.excerpts.into_iter().enumerate() {
180 if let Some(excerpt) = excerpt.and_then(|(from, to)| content.get(from..to)) {
181 let ink = if index == 1 && !low_motion && checkpoints.emphasis != 0 {
182 codewhale_tui_kit::mark::lerp_color(
183 palette::TEXT_REASONING,
184 palette::ACCENT_REASONING_LIVE,
185 f32::from(checkpoints.emphasis) / 2.0,
186 )
187 } else {
188 palette::TEXT_REASONING
189 };
190 rows.push(Line::from(vec![
191 Span::styled(
192 "› ",
193 Style::default().fg(thinking_state_accent(ThinkingVisualState::Done)),
194 ),
195 Span::styled(
196 codewhale_tui_kit::ui_text::semantic_truncate(
197 excerpt,
198 usize::from(content_width.saturating_sub(2)),
199 ),
200 style.fg(ink),
201 ),
202 ]));
203 }
204 }
205 let (live, _) = collapsed_thinking_body(
206 tail,
207 width,
208 true,
209 body_style,
210 completed_preview_lines,
211 palette_mode,
212 );
213 rows.extend(live);
214 (rows, true)
215 } else if collapsed {
216 collapsed_thinking_body(
217 content,
218 width,
219 streaming,
220 body_style,
221 completed_preview_lines,
222 palette_mode,
223 )
224 } else if content.trim().is_empty() {
225 (Vec::new(), false)
226 } else {
227 let body: Vec<Line<'static>> = markdown_render::render_markdown_tagged_with_palette(
228 content,
229 content_width,
230 body_style,
231 palette_mode,
232 )
233 .into_iter()
234 .map(|line| line.line)
235 .collect();
236 // The collapse affordance mirrors the collapsed preview's "more than
237 // the preview would show" test, derived from this single render
238 // instead of rendering the preview too: streaming content outgrows
239 // the streaming preview; settled content shows more than the
240 // completed preview, or differs from its explicit summary.
241 let expandable = if streaming {
242 body.len() > THINKING_STREAMING_PREVIEW_LINE_LIMIT
243 } else {
244 extract_explicit_reasoning_summary(content).is_some_and(|summary| {
245 summary.trim() != content.trim() || body.len() > THINKING_SUMMARY_LINE_LIMIT
246 }) || body.len() > completed_preview_lines
247 };
248 (body, expandable)
249 };
250
251 let rail_style = Style::default().fg(thinking_state_accent(state));
252 let cursor_style = Style::default().fg(palette::ACCENT_REASONING_LIVE);
253
254 if rendered.is_empty() && streaming && !low_motion {
255 lines[0]
256 .spans
257 .push(Span::styled(format!(" {REASONING_CURSOR}"), cursor_style));
258 }
259
260 let last_idx = rendered.len().saturating_sub(1);
261 for (idx, line) in rendered.into_iter().enumerate() {
262 let mut spans = vec![Span::styled(REASONING_RAIL.to_string(), rail_style)];
263 spans.extend(line.spans);
264 // Mark only the live tail; styling every line would churn the block.
265 if streaming && !low_motion && idx == last_idx {
266 spans.push(Span::styled(format!(" {REASONING_CURSOR}"), cursor_style));
267 }
268 lines.push(Line::from(spans));
269 }
270
271 if collapsed && expandable {
272 // The header owns the reveal affordance: it never displaces a live
273 // tail row, and settled calm reasoning remains a single line.
274 lines[0]
275 .spans
276 .push(Span::styled(" ›", Style::default().fg(palette::TEXT_MUTED)));
277 }
278
279 (lines, expandable)
280 }
281
282 fn collapsed_thinking_body(
283 content: &str,
284 width: u16,
285 streaming: bool,
286 style: Style,
287 completed_preview_lines: usize,
288 palette_mode: palette::PaletteMode,
289 ) -> (Vec<Line<'static>>, bool) {
290 if !streaming && completed_preview_lines == 0 {
291 return (Vec::new(), !content.trim().is_empty());
292 }
293 let (body_text, without_explicit_summary): (std::borrow::Cow<'_, str>, bool) = if streaming {
294 (std::borrow::Cow::Borrowed(content), false)
295 } else {
296 match extract_explicit_reasoning_summary(content) {
297 Some(summary) => (std::borrow::Cow::Owned(summary), false),
298 None => (std::borrow::Cow::Borrowed(content), true),
299 }
300 };
301 let limit = if streaming {
302 THINKING_STREAMING_PREVIEW_LINE_LIMIT
303 } else if without_explicit_summary {
304 completed_preview_lines
305 } else {
306 THINKING_SUMMARY_LINE_LIMIT
307 };
308 // #6196: the streaming preview keeps only the newest `limit` rendered
309 // lines, so rendering the whole body every beat made streaming cost grow
310 // with message size. Render a self-contained tail of the source instead;
311 // the settled (`!streaming`) path still renders everything once per
312 // revision, which the transcript cache already amortizes.
313 let render_source: &str = if streaming {
314 streaming_preview_tail_source(&body_text, limit.saturating_add(1))
315 } else {
316 &body_text
317 };
318 // #4146/#4148 used to scrub snake_case here. That rule could not tell
319 // CodeWhale identifiers from user identifiers: paths, env vars, and
320 // module names became bare ellipses while the full body remained one
321 // keypress away. Keep the default view readable; do not revive the scrub.
322 let mut lines = if render_source.trim().is_empty() {
323 Vec::new()
324 } else {
325 markdown_render::render_markdown_tagged_with_palette(
326 render_source,
327 width.saturating_sub(3).max(1),
328 style,
329 palette_mode,
330 )
331 .into_iter()
332 .map(|line| line.line)
333 .collect()
334 };
335 let truncated = lines.len() > limit;
336 if truncated {
337 if streaming {
338 // Follow the live cursor: discard the head, not the newest lines.
339 lines.drain(0..lines.len() - limit);
340 } else {
341 lines.truncate(limit);
342 }
343 }
344 let meaningful = truncated || (!streaming && body_text.trim() != content.trim());
345 (lines, meaningful)
346 }
347
348 /// A trailing slice of the streaming reasoning body that renders
349 /// independently of the lines above it (#6196).
350 ///
351 /// The slice cannot start mid-construct: a cut inside a fenced code block
352 /// would re-classify its lines as paragraphs, and a cut inside a table group
353 /// would re-render it as a fresh table. One forward pass mirrors the parser's
354 /// own fence rule (`push_parsed_line`) to learn, per line boundary, whether
355 /// the boundary sits inside an open fence; the start is then moved back past
356 /// any construct it would split. Collecting `min_source_lines` complete
357 /// lines is enough for the caller's purposes: every source line renders to
358 /// one or more rows, so `limit + 1` source lines always yield more than
359 /// `limit` rendered rows and the "truncated" verdict survives.
360 fn streaming_preview_tail_source(body: &str, min_source_lines: usize) -> &str {
361 // (byte offset, whether the boundary above this line is inside an open
362 // fence). One entry per line; cheap next to the render it bounds.
363 let mut lines: Vec<(usize, bool)> = Vec::new();
364 let mut open_fence: Option<(char, usize)> = None;
365 let mut offset = 0usize;
366 for piece in body.split_inclusive('\n') {
367 let raw_line = piece
368 .strip_suffix('\n')
369 .map_or(piece, |line| line.strip_suffix('\r').unwrap_or(line));
370 lines.push((offset, open_fence.is_some()));
371 let trimmed = raw_line.trim_start();
372 let fence_char = if trimmed.starts_with('~') { '~' } else { '`' };
373 let fence_len = trimmed.chars().take_while(|c| *c == fence_char).count();
374 if fence_len >= 3 {
375 match open_fence {
376 Some((open_char, open_len))
377 if fence_char == open_char
378 && fence_len >= open_len
379 && trimmed[fence_len..].trim().is_empty() =>
380 {
381 open_fence = None;
382 }
383 None => open_fence = Some((fence_char, fence_len)),
384 Some(_) => {}
385 }
386 }
387 offset += piece.len();
388 }
389
390 if lines.len() <= min_source_lines {
391 // Fewer lines than the window needs: render the whole body.
392 return body;
393 }
394 // Walk the desired start back to a boundary that splits no construct:
395 // never inside an open fence (that boundary's line is code content) and
396 // never mid-table (a table group is a run of `|`-prefixed lines).
397 let mut index = lines.len() - min_source_lines;
398 while index > 0 {
399 let (line_offset, inside_before) = lines[index];
400 let line = body[line_offset..].lines().next().unwrap_or("");
401 if !inside_before && !line.trim_start().starts_with('|') {
402 break;
403 }
404 index -= 1;
405 }
406 &body[lines[index].0..]
407 }
408
409 pub(super) fn render_hidden_thinking_activity(
410 _width: u16,
411 duration_secs: Option<f32>,
412 low_motion: bool,
413 locale: Locale,
414 ) -> Vec<Line<'static>> {
415 let state = ThinkingVisualState::Live;
416 let mut header_spans = vec![
417 Span::styled(
418 format!("{REASONING_OPENER} "),
419 Style::default().fg(thinking_state_accent(state)),
420 ),
421 Span::styled(
422 format!("{}…", tr(locale, MessageId::WhaleStateThinking)),
423 thinking_title_style(),
424 ),
425 ];
426 if let Some(dur) = duration_secs {
427 header_spans.push(Span::styled(" · ", Style::default().fg(palette::TEXT_DIM)));
428 header_spans.push(Span::styled(
429 codewhale_command_contract::elapsed::format_elapsed_ms((dur * 1000.0) as u64),
430 thinking_meta_style(),
431 ));
432 }
433 if !low_motion {
434 header_spans.push(Span::styled(
435 format!(" {REASONING_CURSOR}"),
436 Style::default().fg(palette::ACCENT_REASONING_LIVE),
437 ));
438 }
439 vec![Line::from(header_spans)]
440 }
441
442 fn thinking_style() -> Style {
443 Style::default().fg(palette::TEXT_REASONING)
444 }
445
446 fn thinking_visual_state(streaming: bool, duration_secs: Option<f32>) -> ThinkingVisualState {
447 if streaming {
448 ThinkingVisualState::Live
449 } else if duration_secs.is_some() {
450 ThinkingVisualState::Done
451 } else {
452 ThinkingVisualState::Idle
453 }
454 }
455
456 fn thinking_title_style() -> Style {
457 Style::default()
458 .fg(palette::TEXT_SOFT)
459 .add_modifier(Modifier::BOLD)
460 }
461
462 fn thinking_meta_style() -> Style {
463 Style::default().fg(palette::TEXT_DIM)
464 }
465
466 fn thinking_state_accent(state: ThinkingVisualState) -> Color {
467 match state {
468 ThinkingVisualState::Live => palette::ACCENT_REASONING_LIVE,
469 ThinkingVisualState::Done => palette::TEXT_DIM,
470 ThinkingVisualState::Idle => palette::TEXT_DIM,
471 }
472 }
473
474 /// Once-initialised colour depth for the terminal session. Avoids re-reading
475 /// `COLORTERM` / `TERM` env vars on every frame.
476 static COLOR_DEPTH: std::sync::OnceLock<palette::ColorDepth> = std::sync::OnceLock::new();
477
478 pub(super) fn cached_color_depth() -> palette::ColorDepth {
479 *COLOR_DEPTH.get_or_init(palette::ColorDepth::detect)
480 }
481
482 #[cfg(test)]
483 mod tests {
484 use super::*;
485
486 fn joined_text(lines: &[Line<'static>]) -> Vec<String> {
487 lines
488 .iter()
489 .map(|line| {
490 line.spans
491 .iter()
492 .map(|span| span.content.as_ref())
493 .collect::<String>()
494 })
495 .collect()
496 }
497
498 #[test]
499 fn tail_source_extends_back_past_fences_and_tables() {
500 // Short bodies render whole.
501 assert_eq!(
502 streaming_preview_tail_source("one\ntwo\n", 12),
503 "one\ntwo\n"
504 );
505
506 let mut fenced = String::from("```rust\n");
507 for i in 0..30 {
508 fenced.push_str(&format!("let v{i} = {i};\n"));
509 }
510 fenced.push_str("```\nafter the block\n");
511 // A 2-line window would start at the closing fence (which parses as
512 // an opener when orphaned); the slice must start at the real fence
513 // opener so the code lines keep their classification.
514 let slice = streaming_preview_tail_source(&fenced, 2);
515 assert!(slice.starts_with("```rust"));
516 assert!(slice.ends_with("after the block\n"));
517
518 // A table group must not be split either.
519 let table = "intro\n| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n";
520 assert_eq!(streaming_preview_tail_source(table, 2), table);
521
522 // An unterminated fence owns everything after its opener; the slice
523 // must extend back to the opener, not cut inside the block.
524 let open = "```\ncode a\ncode b\ncode c\n";
525 let slice = streaming_preview_tail_source(open, 2);
526 assert!(slice.starts_with("```\ncode a"));
527 }
528
529 #[test]
530 fn collapsed_streaming_preview_renders_only_the_newest_lines() {
531 let mut body = String::new();
532 for i in 0..40 {
533 body.push_str(&format!("head marker {i}\n"));
534 }
535 for i in 0..20 {
536 body.push_str(&format!("tail marker {i}\n"));
537 }
538 let (lines, expandable) = render_thinking_with_preview_limit(
539 &body,
540 100,
541 true,
542 None,
543 true,
544 false,
545 false,
546 Locale::En,
547 THINKING_COMPLETED_PREVIEW_LINE_LIMIT,
548 palette::PaletteMode::Dark,
549 Checkpoints::default(),
550 );
551 assert!(expandable, "a long streaming body must offer expand");
552 // header (including the affordance) + three preview rows
553 assert_eq!(lines.len(), 1 + THINKING_STREAMING_PREVIEW_LINE_LIMIT);
554 let text = joined_text(&lines);
555 assert!(text.iter().any(|t| t.contains("tail marker 19")));
556 assert!(text.iter().any(|t| t.contains("tail marker 17")));
557 assert!(
558 !text.iter().any(|t| t.contains("tail marker 16")),
559 "the window must drop the head: {text:?}"
560 );
561 assert!(!text.iter().any(|t| t.contains("head marker 39")));
562 }
563
564 #[test]
565 fn collapsed_streaming_preview_keeps_open_fence_classification() {
566 let mut body = String::from("```\n");
567 for i in 0..40 {
568 body.push_str(&format!("code line {i}\n"));
569 }
570 let (lines, _) = render_thinking_with_preview_limit(
571 &body,
572 100,
573 true,
574 None,
575 true,
576 false,
577 false,
578 Locale::En,
579 THINKING_COMPLETED_PREVIEW_LINE_LIMIT,
580 palette::PaletteMode::Dark,
581 Checkpoints::default(),
582 );
583 // Code rows carry the two-space code prefix after the rail; if the
584 // tail slice started inside the open fence they would render as
585 // paragraphs and lose it.
586 let text = joined_text(&lines);
587 let code_prefix = format!("{REASONING_RAIL} ");
588 assert!(
589 text.iter().any(|t| t.starts_with(&code_prefix)),
590 "visible code rows must keep the code prefix: {text:?}"
591 );
592 }
593
594 #[test]
595 fn expanded_streaming_thinking_parses_the_body_once() {
596 // #6196: the expanded path used to run the collapsed preview render
597 // first and throw it away — two full body renders per beat.
598 let mut body = String::from("```\n");
599 for i in 0..40 {
600 body.push_str(&format!("expanded line {i}\n"));
601 }
602 markdown_render::reset_parse_invocation_count();
603 let (lines, expandable) = render_thinking_with_preview_limit(
604 &body,
605 100,
606 true,
607 None,
608 false,
609 false,
610 false,
611 Locale::En,
612 THINKING_COMPLETED_PREVIEW_LINE_LIMIT,
613 palette::PaletteMode::Dark,
614 Checkpoints::default(),
615 );
616 assert_eq!(
617 markdown_render::parse_invocation_count(),
618 1,
619 "the expanded view must render the body exactly once"
620 );
621 assert!(expandable);
622 assert!(lines.len() > THINKING_STREAMING_PREVIEW_LINE_LIMIT);
623 }
624 }
625
625 lines RUST