返回 CodeWhale
data_display.rs
根目录 / crates / tui / src / tui / history / data_display.rs
1 //! Transcript cell for `show_data`: the kit's `DataDisplay`, painted fully
2 //! drawn. Known limits: no draw-in motion in the transcript, and the chart is
3 //! painted with the dark truecolor role theme that the backend then adapts,
4 //! like the other kit adapters here, so ASCII-only terminals get the
5 //! Unicode glyphs.
6
7 use codewhale_localization::{Locale, MessageId, tr};
8 use codewhale_palette as palette;
9 use codewhale_ratatui::color::ColorDepth;
10 use codewhale_ratatui::detect::Appearance;
11 use codewhale_ratatui::{Caps, DataDisplay, DataWords, Paint, Theme};
12 use ratatui::buffer::Buffer;
13 use ratatui::layout::Rect;
14 use ratatui::style::Style;
15 use ratatui::text::{Line, Span};
16
17 use super::{ToolStatus, render_compact_kv, render_tool_header_with_summary};
18
19 const INDENT: &str = " ";
20
21 #[derive(Debug, Clone)]
22 pub struct DataDisplayCell {
23 pub display: Result<DataDisplay, String>,
24 pub status: ToolStatus,
25 }
26
27 impl DataDisplayCell {
28 #[must_use]
29 pub fn from_input(input: &serde_json::Value, status: ToolStatus) -> Self {
30 let display = codewhale_engine::tools::show_data::parse_data_display(input)
31 .map_err(|error| error.to_string());
32 let status = if display.is_err() {
33 ToolStatus::Failed
34 } else {
35 status
36 };
37 Self { display, status }
38 }
39
40 pub fn from_history(
41 call: &codewhale_models::ContentBlock,
42 input: &serde_json::Value,
43 messages: &[codewhale_models::Message],
44 ) -> Self {
45 use codewhale_models::ContentBlock;
46 let mut cell = Self::from_input(input, ToolStatus::Stopped);
47 let Some(key) = call
48 .tool_call_key()
49 .filter(|key| !key.as_str().trim().is_empty())
50 else {
51 return cell;
52 };
53 let matching: Vec<_> = messages
54 .iter()
55 .flat_map(|message| &message.content)
56 .filter(|block| block.tool_call_key().as_ref() == Some(&key))
57 .collect();
58 if matching
59 .iter()
60 .filter(|block| matches!(block, ContentBlock::ToolUse { .. }))
61 .count()
62 != 1
63 {
64 return cell;
65 }
66 let results: Vec<_> = matching
67 .into_iter()
68 .filter_map(|block| match block {
69 ContentBlock::ToolResult {
70 tool_use_id,
71 content,
72 is_error,
73 ..
74 } => Some((tool_use_id, content, is_error)),
75 _ => None,
76 })
77 .collect();
78 if let [(tool_use_id, content, is_error)] = results.as_slice() {
79 let ContentBlock::ToolUse { id, .. } = call else {
80 return cell;
81 };
82 if *tool_use_id != id {
83 return cell;
84 }
85 if **is_error == Some(true) {
86 cell.status = ToolStatus::Failed;
87 cell.display = Err((*content).clone());
88 } else if cell.display.is_ok() {
89 cell.status = ToolStatus::Success;
90 }
91 }
92 cell
93 }
94
95 pub fn lines_with_motion_and_locale(
96 &self,
97 width: u16,
98 low_motion: bool,
99 locale: Locale,
100 ) -> Vec<Line<'static>> {
101 let label = self
102 .display
103 .as_ref()
104 .ok()
105 .map(|display| codewhale_ratatui::text::display_safe(display.label()));
106 let mut lines = vec![render_tool_header_with_summary(
107 "show_data",
108 label.as_deref().filter(|label| !label.trim().is_empty()),
109 None,
110 self.status,
111 None,
112 low_motion,
113 locale,
114 )];
115 match &self.display {
116 Ok(display) if self.status != ToolStatus::Stopped => {
117 lines.extend(chart_lines(display, width, locale))
118 }
119 Ok(_) => {}
120 Err(error) => lines.extend(render_compact_kv(
121 &tr(locale, MessageId::ToolReceiptFailed),
122 &codewhale_ratatui::text::display_safe(error),
123 Style::default().fg(palette::STATUS_ERROR),
124 width,
125 )),
126 }
127 lines
128 }
129 }
130
131 fn chart_lines(display: &DataDisplay, width: u16, locale: Locale) -> Vec<Line<'static>> {
132 let inner = width.saturating_sub(INDENT.len() as u16).max(1);
133 let theme = Theme::new(Caps {
134 depth: ColorDepth::TrueColor,
135 ascii: false,
136 appearance: Appearance::Dark,
137 });
138 let words = DataWords {
139 now: tr(locale, MessageId::DataChartNow),
140 min: tr(locale, MessageId::DataChartMin),
141 max: tr(locale, MessageId::DataChartMax),
142 empty: tr(locale, MessageId::DataChartEmpty),
143 points: tr(locale, MessageId::DataChartPoints),
144 };
145 let view = display.view().with_words(&words).area_fill(true);
146 let height = view.height(inner, &theme).max(1);
147 let area = Rect::new(0, 0, inner, height);
148 let mut buf = Buffer::empty(area);
149 view.paint(area, &mut buf, &theme);
150
151 (0..height)
152 .map(|y| {
153 let mut spans = vec![Span::raw(INDENT)];
154 let mut run = String::new();
155 let mut run_style = Style::default();
156 let mut x = 0;
157 while x < inner {
158 let cell = &buf[(x, y)];
159 let style = cell.style();
160 if style != run_style && !run.is_empty() {
161 spans.push(Span::styled(std::mem::take(&mut run), run_style));
162 }
163 run_style = style;
164 run.push_str(cell.symbol());
165 x += u16::try_from(codewhale_ratatui::text::width(cell.symbol()).max(1))
166 .unwrap_or(1);
167 }
168 let trimmed = run.trim_end();
169 if !trimmed.is_empty() || run_style != Style::default() {
170 let keep = if run_style == Style::default() {
171 trimmed.to_string()
172 } else {
173 run
174 };
175 spans.push(Span::styled(keep, run_style));
176 }
177 Line::from(spans)
178 })
179 .collect()
180 }
181
182 #[cfg(test)]
183 mod tests {
184 use super::*;
185 use serde_json::json;
186
187 fn text(lines: &[Line<'_>]) -> String {
188 lines
189 .iter()
190 .map(|line| {
191 line.spans
192 .iter()
193 .map(|span| span.content.as_ref())
194 .collect::<String>()
195 })
196 .collect::<Vec<_>>()
197 .join("\n")
198 }
199
200 #[test]
201 fn show_data_input_paints_a_chart_or_names_the_refusal() {
202 let bars = DataDisplayCell::from_input(
203 &json!({
204 "kind": "bars",
205 "label": "Tokens by model",
206 "unit": "tokens",
207 "items": [
208 { "label": "opus", "value": 400.0 },
209 { "label": "haiku", "value": 100.0 }
210 ]
211 }),
212 ToolStatus::Success,
213 );
214 assert_eq!(bars.status, ToolStatus::Success);
215 let rendered = text(&bars.lines_with_motion_and_locale(60, true, Locale::En));
216 assert!(rendered.contains("Tokens by model"), "{rendered}");
217 assert!(rendered.contains("opus"), "{rendered}");
218 assert!(rendered.contains("haiku"), "{rendered}");
219 assert!(rendered.contains('\u{2588}'), "{rendered}");
220
221 let refused = DataDisplayCell::from_input(
222 &json!({ "kind": "trend", "label": "x", "values": [1.0], "rows": 40 }),
223 ToolStatus::Running,
224 );
225 assert_eq!(refused.status, ToolStatus::Failed);
226 let rendered = text(&refused.lines_with_motion_and_locale(60, true, Locale::En));
227 assert!(rendered.contains("40 rows"), "{rendered}");
228 }
229 #[test]
230 fn show_data_wide_labels_fit_and_survive_session_restore() {
231 use crate::tui::history::{HistoryCell, ToolCell, history_cells_from_message_with_results};
232 use codewhale_engine::session_manager::{SessionManager, create_saved_session};
233 use codewhale_models::{ContentBlock, Message, Role};
234
235 let input = json!({
236 "kind": "bars", "label": "Tokens",
237 "items": [{ "label": "模型", "value": 42 }]
238 });
239 let message = Message {
240 role: Role::Assistant,
241 content: vec![ContentBlock::ToolUse {
242 execution_id: None,
243 id: "chart-1".into(),
244 name: "show_data".into(),
245 input: input.clone(),
246 caller: None,
247 thought_signature: None,
248 }],
249 };
250 let tmp = tempfile::tempdir().unwrap();
251 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
252 let result = Message {
253 role: Role::User,
254 content: vec![ContentBlock::ToolResult {
255 execution_id: None,
256 tool_use_id: "chart-1".into(),
257 content: "Shown".into(),
258 is_error: None,
259 content_blocks: None,
260 }],
261 };
262 let session = create_saved_session(&[message, result], "test-model", tmp.path(), 0, None);
263 manager.save_session(&session).unwrap();
264 let loaded = manager.load_session(&session.metadata.id).unwrap();
265 let cells = history_cells_from_message_with_results(&loaded.messages[0], &loaded.messages);
266 let [HistoryCell::Tool(ToolCell::DataDisplay(restored))] = cells.as_slice() else {
267 panic!("expected restored chart");
268 };
269 let call = &loaded.messages[0].content[0];
270 let unfinished = DataDisplayCell::from_history(call, &input, &loaded.messages[..1]);
271 assert_eq!(unfinished.status, ToolStatus::Stopped);
272 assert!(
273 !text(&unfinished.lines_with_motion_and_locale(60, true, Locale::En)).contains("模型")
274 );
275 let mut failed_messages = loaded.messages.clone();
276 if let ContentBlock::ToolResult {
277 is_error, content, ..
278 } = &mut failed_messages[1].content[0]
279 {
280 *is_error = Some(true);
281 *content = "Denied by policy".into();
282 }
283 let failed = DataDisplayCell::from_history(call, &input, &failed_messages);
284 assert_eq!(failed.status, ToolStatus::Failed);
285 assert!(
286 text(&failed.lines_with_motion_and_locale(60, true, Locale::En))
287 .contains("Denied by policy")
288 );
289 let mut ambiguous = loaded.messages.clone();
290 ambiguous.push(loaded.messages[0].clone());
291 assert_eq!(
292 DataDisplayCell::from_history(call, &input, &ambiguous).status,
293 ToolStatus::Stopped
294 );
295 let live = DataDisplayCell::from_input(&input, ToolStatus::Success);
296 for width in [20, 40, 60, 100] {
297 let lines = chart_lines(restored.display.as_ref().unwrap(), width, Locale::En);
298 assert!(text(&lines).contains("模型"));
299 assert!(lines.iter().all(|line| line.width() <= usize::from(width)));
300 assert_eq!(
301 restored.lines_with_motion_and_locale(width, true, Locale::En),
302 live.lines_with_motion_and_locale(width, true, Locale::En)
303 );
304 }
305 }
306 }
307
307 lines RUST