返回 CodeWhale
message.rs
根目录 / crates / tui / src / tui / history / message.rs
1 //! User, assistant, and system message transcript rendering.
2
3 use ratatui::style::{Modifier, Style};
4 use ratatui::text::{Line, Span};
5 use unicode_width::UnicodeWidthStr;
6
7 use codewhale_palette as palette;
8 use codewhale_tui_kit::markdown_render;
9 use codewhale_tui_kit::ui_text::CopyLineSeparator;
10
11 use super::{ASSISTANT_GLYPH, USER_GLYPH};
12
13 pub(crate) struct RenderedTranscriptLine {
14 pub line: Line<'static>,
15 pub links: Vec<codewhale_tui_kit::osc8::LineLink>,
16 pub copy_prefix_width: usize,
17 pub copy_separator_after: CopyLineSeparator,
18 }
19
20 pub(super) fn render_message(
21 prefix: &str,
22 label_style: Style,
23 body_style: Style,
24 content: &str,
25 width: u16,
26 ) -> Vec<Line<'static>> {
27 render_message_with_copy_metadata(prefix, label_style, body_style, content, width)
28 .into_iter()
29 .map(|rendered| rendered.line)
30 .collect()
31 }
32
33 pub(super) fn render_message_with_copy_metadata(
34 prefix: &str,
35 label_style: Style,
36 body_style: Style,
37 content: &str,
38 width: u16,
39 ) -> Vec<RenderedTranscriptLine> {
40 render_message_with_copy_metadata_for_palette(
41 prefix,
42 label_style,
43 body_style,
44 content,
45 width,
46 markdown_render::detected_palette_mode(),
47 )
48 }
49
50 pub(super) fn render_message_with_copy_metadata_for_palette(
51 prefix: &str,
52 label_style: Style,
53 body_style: Style,
54 content: &str,
55 width: u16,
56 palette_mode: palette::PaletteMode,
57 ) -> Vec<RenderedTranscriptLine> {
58 render_message_with_copy_metadata_for_palette_and_links(
59 prefix,
60 label_style,
61 body_style,
62 content,
63 width,
64 palette_mode,
65 None,
66 )
67 }
68
69 pub(super) fn render_message_with_copy_metadata_for_palette_and_links(
70 prefix: &str,
71 label_style: Style,
72 body_style: Style,
73 content: &str,
74 width: u16,
75 palette_mode: palette::PaletteMode,
76 link_resolver: Option<&mut markdown_render::WorkspaceLinkResolver<'_>>,
77 ) -> Vec<RenderedTranscriptLine> {
78 // An assistant cell whose content is entirely whitespace (e.g. a stray
79 // newline streamed between reasoning and a tool call) would otherwise
80 // render as a bare, orphaned role glyph floating on its own line — the
81 // "blue dots with nothing after them" artifact. Render nothing so the
82 // transcript doesn't accumulate empty markers. Real prose, including
83 // messages that merely start with blank lines, still renders normally.
84 if prefix == ASSISTANT_GLYPH && content.trim().is_empty() {
85 return Vec::new();
86 }
87 let prefix_width = UnicodeWidthStr::width(prefix);
88 let prefix_width_u16 = u16::try_from(prefix_width.saturating_add(2)).unwrap_or(u16::MAX);
89 let content_width = usize::from(width.saturating_sub(prefix_width_u16).max(1));
90 let mut lines = Vec::new();
91 // Pre-process $...$ and $$...$$ LaTeX math expressions into Unicode
92 let content_rendered = super::latex_render::render_latex_in_text(content);
93 let rendered = markdown_render::render_markdown_tagged_with_palette_and_links(
94 &content_rendered,
95 content_width as u16,
96 body_style,
97 palette_mode,
98 link_resolver,
99 );
100 for (idx, rendered_line) in rendered.into_iter().enumerate() {
101 lines.push(decorate_markdown_line(
102 prefix,
103 prefix_width,
104 label_style,
105 idx,
106 rendered_line,
107 ));
108 }
109 if lines.is_empty() {
110 lines.push(RenderedTranscriptLine {
111 line: Line::from(""),
112 links: Vec::new(),
113 copy_prefix_width: 0,
114 copy_separator_after: CopyLineSeparator::Newline,
115 });
116 }
117 lines
118 }
119
120 #[allow(clippy::too_many_arguments)]
121 pub(crate) fn update_streaming_message_render(
122 cache: &mut markdown_render::IncrementalMarkdownRenderCache,
123 content: &str,
124 width: u16,
125 label_style: Style,
126 body_style: Style,
127 palette_mode: palette::PaletteMode,
128 verified_append: bool,
129 lines: &mut Vec<Line<'static>>,
130 links: &mut Vec<Vec<codewhale_tui_kit::osc8::LineLink>>,
131 copy_separators: &mut Vec<CopyLineSeparator>,
132 copy_prefix_widths: &mut Vec<usize>,
133 ) -> usize {
134 let prefix = ASSISTANT_GLYPH;
135 let prefix_width = UnicodeWidthStr::width(prefix);
136 let prefix_width_u16 = u16::try_from(prefix_width.saturating_add(2)).unwrap_or(u16::MAX);
137 let content_width = width.saturating_sub(prefix_width_u16).max(1);
138 // Pre-process $...$ and $$...$$ LaTeX math expressions into Unicode
139 let content = super::latex_render::render_latex_in_text(content);
140 let delta = cache.update(
141 &content,
142 content_width,
143 body_style,
144 palette_mode,
145 verified_append,
146 );
147
148 let replace_from = delta.replace_from;
149 lines.truncate(replace_from);
150 links.truncate(replace_from);
151 copy_separators.truncate(replace_from);
152 copy_prefix_widths.truncate(replace_from);
153
154 for rendered_line in delta.lines {
155 let index = lines.len();
156 let rendered =
157 decorate_markdown_line(prefix, prefix_width, label_style, index, rendered_line);
158 lines.push(rendered.line);
159 links.push(rendered.links);
160 copy_separators.push(rendered.copy_separator_after);
161 copy_prefix_widths.push(rendered.copy_prefix_width);
162 }
163 replace_from
164 }
165
166 fn decorate_markdown_line(
167 prefix: &str,
168 prefix_width: usize,
169 label_style: Style,
170 index: usize,
171 rendered_line: markdown_render::RenderedMarkdownLine,
172 ) -> RenderedTranscriptLine {
173 let display_prefix_width = if prefix.is_empty() {
174 0
175 } else {
176 prefix_width + 1
177 };
178 let links = rendered_line
179 .links
180 .iter()
181 .map(|link| link.shifted(display_prefix_width))
182 .collect();
183 let line = if index == 0 {
184 let mut spans = Vec::new();
185 if !prefix.is_empty() {
186 spans.push(Span::styled(
187 prefix.to_string(),
188 label_style.add_modifier(Modifier::BOLD),
189 ));
190 spans.push(Span::raw(" "));
191 }
192 spans.extend(rendered_line.line.spans);
193 Line::from(spans)
194 } else {
195 let indent = if prefix.is_empty() {
196 String::new()
197 } else if rendered_line.is_code {
198 " ".repeat(prefix_width + 1)
199 } else {
200 let mut s = String::with_capacity(prefix_width + 1);
201 s.push('\u{258F}');
202 s.extend(std::iter::repeat_n(' ', prefix_width));
203 s
204 };
205 let rail_style = Style::default().fg(palette::TEXT_DIM);
206 let mut spans = vec![Span::styled(indent, rail_style)];
207 spans.extend(rendered_line.line.spans);
208 Line::from(spans)
209 };
210 RenderedTranscriptLine {
211 line,
212 links,
213 copy_prefix_width: rendered_line.copy_prefix_width
214 + history_copy_prefix_width(prefix, prefix_width, rendered_line.is_code, index),
215 copy_separator_after: rendered_line.copy_separator_after,
216 }
217 }
218
219 fn history_copy_prefix_width(
220 prefix: &str,
221 prefix_width: usize,
222 is_code: bool,
223 line_index: usize,
224 ) -> usize {
225 if line_index > 0 && is_code && !prefix.is_empty() {
226 prefix_width + 1
227 } else {
228 0
229 }
230 }
231
232 pub(super) fn hard_break_copy_lines(lines: Vec<Line<'static>>) -> Vec<RenderedTranscriptLine> {
233 lines
234 .into_iter()
235 .map(|line| RenderedTranscriptLine {
236 line,
237 links: Vec::new(),
238 copy_prefix_width: 0,
239 copy_separator_after: CopyLineSeparator::Newline,
240 })
241 .collect()
242 }
243
244 /// Render a plain-text user message: split on newlines, word-wrap each line,
245 /// preserve leading whitespace. No markdown interpretation (headings, lists,
246 /// code blocks, etc. are rendered as literal text).
247 pub(super) fn render_plain_message(
248 prefix: &str,
249 label_style: Style,
250 body_style: Style,
251 content: &str,
252 width: u16,
253 ) -> Vec<Line<'static>> {
254 let prefix_width = UnicodeWidthStr::width(prefix);
255 let prefix_width_u16 = u16::try_from(prefix_width.saturating_add(2)).unwrap_or(u16::MAX);
256 let content_width = width.saturating_sub(prefix_width_u16).max(1);
257 // Pre-process $...$ and $$...$$ LaTeX math expressions into Unicode
258 let content_rendered = super::latex_render::render_latex_in_text(content);
259 let rendered = markdown_render::render_plain_text(&content_rendered, content_width, body_style);
260 let mut lines = Vec::with_capacity(rendered.len());
261
262 for (idx, line) in rendered.into_iter().enumerate() {
263 if idx == 0 {
264 let mut spans = Vec::new();
265 if !prefix.is_empty() {
266 spans.push(Span::styled(
267 prefix.to_string(),
268 label_style.add_modifier(Modifier::BOLD),
269 ));
270 spans.push(Span::raw(" "));
271 }
272 spans.extend(line.spans);
273 lines.push(Line::from(spans));
274 } else {
275 let indent = if prefix.is_empty() {
276 String::new()
277 } else {
278 let mut s = String::with_capacity(prefix_width + 1);
279 s.push('\u{258F}');
280 s.extend(std::iter::repeat_n(' ', prefix_width));
281 s
282 };
283 let rail_style = Style::default().fg(palette::TEXT_DIM);
284 let mut spans = vec![Span::styled(indent, rail_style)];
285 spans.extend(line.spans);
286 lines.push(Line::from(spans));
287 }
288 }
289
290 if lines.is_empty() {
291 lines.push(Line::from(""));
292 }
293 lines
294 }
295
296 /// A user turn is marked by its `▎` rail and the adaptive `USER_BODY` ink.
297 /// Only the newest one also carries the elevated-surface background, so the
298 /// eye lands on the turn in play; every older prompt renders on the bare
299 /// ground. (A fill behind *every* user row read as striping on every theme,
300 /// which is why the block is newest-only rather than per-role.)
301 pub(super) fn render_user_message(
302 content: &str,
303 width: u16,
304 highlight: bool,
305 ) -> Vec<Line<'static>> {
306 let lines = render_plain_message(
307 USER_GLYPH,
308 user_label_style(),
309 user_body_style(),
310 content,
311 width,
312 );
313 if !highlight {
314 return lines;
315 }
316 let bg = palette::SURFACE_ELEVATED;
317 lines
318 .into_iter()
319 .map(|mut line| {
320 line.style = line.style.bg(bg);
321 let target_width = usize::from(width);
322 let line_width = line.width();
323 if line_width < target_width {
324 line.spans.push(Span::styled(
325 " ".repeat(target_width - line_width),
326 Style::default().bg(bg),
327 ));
328 }
329 line
330 })
331 .collect()
332 }
333
334 pub(super) fn user_label_style() -> Style {
335 Style::default().fg(palette::USER_BODY)
336 }
337
338 pub(super) fn user_body_style() -> Style {
339 Style::default().fg(palette::USER_BODY)
340 }
341
342 /// Style for the assistant glyph (`●`). When the cell is streaming and
343 /// motion is allowed, the foreground pulses on a 2s cycle between 30% and
344 /// 100% brightness — the only deliberately animated element in a calm
345 /// transcript. When idle (or low_motion is on) it sits at the full DeepSeek
346 /// sky color so finished turns read as solid rather than dim.
347 pub(super) fn assistant_label_style_for(streaming: bool, low_motion: bool) -> Style {
348 let color = if streaming && !low_motion {
349 let now_ms = std::time::SystemTime::now()
350 .duration_since(std::time::UNIX_EPOCH)
351 .map(|d| d.as_millis() as u64)
352 .unwrap_or(0);
353 palette::pulse_brightness(palette::WHALE_ACTION, now_ms)
354 } else {
355 palette::WHALE_ACTION
356 };
357 Style::default().fg(color)
358 }
359
360 pub(super) fn system_label_style() -> Style {
361 Style::default().fg(palette::TEXT_ACCENT)
362 }
363
364 pub(super) fn message_body_style() -> Style {
365 Style::default().fg(palette::TEXT_PRIMARY)
366 }
367
368 pub(super) fn system_body_style() -> Style {
369 Style::default().fg(palette::TEXT_SOFT)
370 }
371
372 /// Double the bare backslashes in a machine-generated note.
373 ///
374 /// A note names paths, and a Windows path is littered with `\`. The markdown
375 /// renderer honours CommonMark §2.4, where a backslash before ASCII punctuation
376 /// is an escape: `\.` yields `.`, so `C:\Users\asus\.codewhale` rendered as
377 /// `C:\Users\asus.codewhale` and the note pointed at a directory that does not
378 /// exist. The renderer is right — a producer that wants a literal backslash
379 /// escapes it — so plain note prose is escaped here, at the one place every note
380 /// passes through.
381 ///
382 /// Doubling is the whole fix: `\\` renders as `\`.
383 ///
384 /// Three regions are left exactly as written, because the renderer already
385 /// copies them verbatim and doubling inside one would *print* the extra
386 /// backslash:
387 ///
388 /// - a fenced block, closed only by a run at least as long as its opener;
389 /// - a line carrying inline code (`` ` ``), a shape a note's third-party text
390 /// (MCP guidance, extension prompts) brings with it;
391 /// - a table row.
392 ///
393 /// A line that is both prose and delimited keeps today's behavior rather than
394 /// trading one wrong backslash for another.
395 pub(super) fn escape_note_backslashes(content: &str) -> std::borrow::Cow<'_, str> {
396 if !content.contains('\\') {
397 return std::borrow::Cow::Borrowed(content);
398 }
399 let mut out = String::with_capacity(content.len() + 8);
400 let mut fence_len: Option<usize> = None;
401 for (index, line) in content.split('\n').enumerate() {
402 if index > 0 {
403 out.push('\n');
404 }
405 let trimmed = line.trim_start();
406 let run = trimmed.chars().take_while(|ch| *ch == '`').count();
407 if let Some(open) = fence_len {
408 // The renderer closes a fence only on a closing run at least as
409 // long as the opener, so a shorter run inside one is code content.
410 if run >= open && trimmed[run..].trim().is_empty() {
411 fence_len = None;
412 }
413 out.push_str(line);
414 continue;
415 }
416 if run >= 3 {
417 fence_len = Some(run);
418 out.push_str(line);
419 continue;
420 }
421 if carries_verbatim_inline_markdown(line) {
422 out.push_str(line);
423 continue;
424 }
425 for ch in line.chars() {
426 if ch == '\\' {
427 out.push('\\');
428 }
429 out.push(ch);
430 }
431 }
432 std::borrow::Cow::Owned(out)
433 }
434
435 /// Whether the renderer will copy this line's inline markup verbatim, so a
436 /// doubled backslash would reach the screen doubled.
437 fn carries_verbatim_inline_markdown(line: &str) -> bool {
438 let trimmed = line.trim();
439 if trimmed.starts_with('|') && trimmed.ends_with('|') && trimmed.len() > 1 {
440 return true;
441 }
442 line.contains('`')
443 }
444
444 lines RUST