返回 CodeWhale
checklist.rs
根目录 / crates / tui / src / tui / history / checklist.rs
1 //! Checklist and todo transcript rendering helpers.
2
3 use ratatui::style::{Color, Style};
4 use ratatui::text::{Line, Span};
5 use serde_json::Value;
6 use unicode_width::UnicodeWidthStr;
7
8 use codewhale_localization::{Locale, MessageId, tr};
9 use codewhale_palette as palette;
10
11 use super::{
12 RenderMode, TRANSCRIPT_RAIL, ToolStatus, render_card_detail_line_single,
13 render_tool_header_with_family_and_summary, tool_value_style, truncate_text, wrap_text,
14 };
15
16 pub(crate) fn is_checklist_tool_name(name: &str) -> bool {
17 matches!(
18 name,
19 "work_update"
20 | "checklist_write"
21 | "checklist_add"
22 | "checklist_update"
23 | "todo_write"
24 | "todo_add"
25 | "todo_update"
26 )
27 }
28
29 #[derive(Debug, Clone)]
30 pub(super) struct ChecklistItemSnapshot {
31 pub(super) content: String,
32 pub(super) status: String,
33 }
34
35 #[derive(Debug, Clone, Default)]
36 pub(super) struct ChecklistSnapshot {
37 pub(super) items: Vec<ChecklistItemSnapshot>,
38 pub(super) completion_pct: u8,
39 pub(super) completed: usize,
40 pub(super) total: usize,
41 }
42
43 /// Pull a structured checklist snapshot out of the tool's text output.
44 /// The tool emits a leading human-readable line followed by JSON, so we
45 /// scan for the first `{` and parse from there. Returns `None` if the
46 /// payload is missing the expected `items` array.
47 pub(super) fn parse_checklist_snapshot(output: &str) -> Option<ChecklistSnapshot> {
48 let json_start = output.find('{')?;
49 let parsed: Value = serde_json::from_str(&output[json_start..]).ok()?;
50 let items_value = parsed.get("items")?.as_array()?;
51
52 let items: Vec<ChecklistItemSnapshot> = items_value
53 .iter()
54 .map(|item| ChecklistItemSnapshot {
55 content: item
56 .get("content")
57 .and_then(Value::as_str)
58 .unwrap_or("")
59 .to_string(),
60 status: item
61 .get("status")
62 .and_then(Value::as_str)
63 .unwrap_or("pending")
64 .to_string(),
65 })
66 .collect();
67
68 if items.is_empty() {
69 return None;
70 }
71
72 let completed = items
73 .iter()
74 .filter(|item| item.status.eq_ignore_ascii_case("completed"))
75 .count();
76 let total = items.len();
77 let completion_pct = parsed
78 .get("completion_pct")
79 .and_then(Value::as_u64)
80 .map(|pct| u8::try_from(pct.min(100)).unwrap_or(100))
81 .unwrap_or_else(|| {
82 (completed * 100)
83 .checked_div(total)
84 .and_then(|pct| u8::try_from(pct).ok())
85 .unwrap_or(0)
86 });
87
88 Some(ChecklistSnapshot {
89 items,
90 completion_pct,
91 completed,
92 total,
93 })
94 }
95
96 /// One parsed "Updated todo #N to STATUS" prefix line emitted by
97 /// `todo_update` / `checklist_update`. Used by [`render_checklist_change_card`]
98 /// to show a compact state-change line instead of the full item list.
99 #[derive(Debug, Clone, PartialEq, Eq)]
100 pub(super) struct ChecklistChange {
101 pub(super) id: u32,
102 pub(super) status: String,
103 }
104
105 /// Parse the leading line of a checklist-update tool output. Returns
106 /// `None` for non-update outputs (e.g. `todo_write` snapshots, errors,
107 /// or an unexpected format) so the caller falls back to the full-list
108 /// renderer.
109 pub(super) fn parse_update_prefix(output: &str) -> Option<ChecklistChange> {
110 // The tool output shape is `Updated todo #3 to in_progress\n{ ... }`.
111 // We tolerate `checklist` or `todo` as the noun and any reasonable
112 // status word (the snapshot lookup in the renderer is the source of
113 // truth for the title — we just need the id+status pair).
114 let first = output.lines().next()?.trim();
115 let rest = first
116 .strip_prefix("Updated todo #")
117 .or_else(|| first.strip_prefix("Updated checklist #"))?;
118 let (id_str, after) = rest.split_once(' ')?;
119 let id: u32 = id_str.parse().ok()?;
120 let status = after.strip_prefix("to ")?.trim().to_string();
121 if status.is_empty() {
122 return None;
123 }
124 Some(ChecklistChange { id, status })
125 }
126
127 /// Render a compact one-line state-change card for `todo_update` /
128 /// `checklist_update` calls (#403). Shows the changed item's marker,
129 /// title, and old -> new status, with a `M/N · pct%` progress summary
130 /// in the header. The full list is still available through the tool
131 /// detail record.
132 pub(super) fn render_checklist_change_card(
133 name: &str,
134 status: ToolStatus,
135 snapshot: &ChecklistSnapshot,
136 change: &ChecklistChange,
137 width: u16,
138 low_motion: bool,
139 locale: Locale,
140 ) -> Vec<Line<'static>> {
141 let mut lines = Vec::new();
142 let header_summary = format!(
143 "{}/{} \u{00B7} {}%",
144 snapshot.completed, snapshot.total, snapshot.completion_pct
145 );
146 let family = crate::tui::widgets::tool_card::tool_family_for_name(name);
147 lines.push(render_tool_header_with_family_and_summary(
148 family,
149 Some(&header_summary),
150 None,
151 status,
152 None,
153 low_motion,
154 locale,
155 ));
156
157 // Look up the title from the snapshot. `id` in tool input is
158 // 1-indexed; `items` is 0-indexed.
159 let item = (change.id as usize)
160 .checked_sub(1)
161 .and_then(|idx| snapshot.items.get(idx));
162 let title = item
163 .map(|i| i.content.trim().to_string())
164 .filter(|s| !s.is_empty())
165 .unwrap_or_else(|| "(missing title)".to_string());
166
167 let (marker, marker_color) = checklist_status_marker(&change.status);
168 let prefix = format!("{marker} ");
169 let prefix_width =
170 UnicodeWidthStr::width(TRANSCRIPT_RAIL) + UnicodeWidthStr::width(prefix.as_str());
171 let id_label = format!("Todo #{}", change.id);
172 let arrow = " \u{2192} ";
173 let status_label = checklist_status_label(&change.status, locale);
174 let title_budget = usize::from(width)
175 .saturating_sub(prefix_width)
176 .saturating_sub(UnicodeWidthStr::width(id_label.as_str()))
177 .saturating_sub(UnicodeWidthStr::width(arrow))
178 .saturating_sub(UnicodeWidthStr::width(status_label.as_str()))
179 .saturating_sub(2)
180 .max(8);
181 let title_truncated = truncate_text(title.as_str(), title_budget);
182
183 let spans = vec![
184 Span::styled(
185 "\u{258F} ".to_string(),
186 Style::default().fg(palette::TEXT_DIM),
187 ),
188 Span::styled(prefix, Style::default().fg(marker_color)),
189 Span::styled(id_label, Style::default().fg(palette::TEXT_DIM)),
190 Span::styled(": ".to_string(), Style::default().fg(palette::TEXT_DIM)),
191 Span::styled(title_truncated, tool_value_style()),
192 Span::styled(arrow.to_string(), Style::default().fg(palette::TEXT_DIM)),
193 Span::styled(status_label, Style::default().fg(marker_color)),
194 ];
195 lines.push(Line::from(spans));
196
197 // Tease that the full list is still available without leaving the
198 // transcript. Mirrors the same affordance used by other tool cells.
199 lines.push(render_card_detail_line_single(
200 None,
201 &format!(
202 "{} item{} \u{00B7} {}",
203 snapshot.total,
204 if snapshot.total == 1 { "" } else { "s" },
205 crate::tui::key_shortcuts::tool_details_shortcut_action_hint("list")
206 ),
207 Style::default().fg(palette::TEXT_MUTED),
208 ));
209 lines
210 }
211
212 fn checklist_status_label(status: &str, locale: Locale) -> String {
213 use codewhale_engine::tools::todo::TodoStatus;
214 let id = match TodoStatus::parse(status) {
215 Some(TodoStatus::Pending) => MessageId::TodoStatusPending,
216 Some(TodoStatus::InProgress) => MessageId::TodoStatusInProgress,
217 Some(TodoStatus::Completed) => MessageId::TodoStatusCompleted,
218 Some(TodoStatus::Cancelled) => MessageId::TodoStatusCancelled,
219 None => return status.to_string(),
220 };
221 tr(locale, id).into_owned()
222 }
223
224 fn checklist_status_marker(status: &str) -> (&'static str, Color) {
225 match status.to_ascii_lowercase().as_str() {
226 "completed" | "done" => ("\u{2611}", palette::STATUS_SUCCESS), // ☑
227 "in_progress" | "inprogress" | "running" => ("\u{25D0}", palette::WHALE_ACTION), // ◐
228 "blocked" | "failed" => ("\u{2717}", palette::STATUS_ERROR), // ✗
229 "cancelled" | "canceled" | "skipped" => ("\u{2298}", palette::TEXT_MUTED), // ⊘
230 _ => ("\u{2610}", palette::TEXT_MUTED), // ☐ pending
231 }
232 }
233
234 const CHECKLIST_LIVE_ITEM_LIMIT: usize = 8;
235
236 pub(super) fn render_checklist_card(
237 name: &str,
238 status: ToolStatus,
239 snapshot: &ChecklistSnapshot,
240 width: u16,
241 low_motion: bool,
242 mode: RenderMode,
243 locale: Locale,
244 ) -> Vec<Line<'static>> {
245 let mut lines = Vec::new();
246 let header_summary = format!(
247 "{}/{} \u{00B7} {}%",
248 snapshot.completed, snapshot.total, snapshot.completion_pct
249 );
250 let family = crate::tui::widgets::tool_card::tool_family_for_name(name);
251 lines.push(render_tool_header_with_family_and_summary(
252 family,
253 Some(&header_summary),
254 None,
255 status,
256 None,
257 low_motion,
258 locale,
259 ));
260
261 let cap = match mode {
262 RenderMode::Live => CHECKLIST_LIVE_ITEM_LIMIT,
263 RenderMode::Transcript | RenderMode::Source => snapshot.items.len(),
264 };
265 let visible: Vec<&ChecklistItemSnapshot> = snapshot.items.iter().take(cap).collect();
266 let omitted = snapshot.items.len().saturating_sub(visible.len());
267
268 for item in visible {
269 let (marker, color) = checklist_status_marker(&item.status);
270 let prefix = format!("{marker} ");
271 // Reserve room for the rail + marker prefix when wrapping content.
272 let prefix_width =
273 UnicodeWidthStr::width(TRANSCRIPT_RAIL) + UnicodeWidthStr::width(prefix.as_str());
274 let content_width = usize::from(width).saturating_sub(prefix_width).max(1);
275 for (idx, part) in wrap_text(item.content.trim(), content_width)
276 .into_iter()
277 .enumerate()
278 {
279 let mut spans = vec![Span::styled(
280 "\u{258F} ".to_string(),
281 Style::default().fg(palette::TEXT_DIM),
282 )];
283 if idx == 0 {
284 spans.push(Span::styled(prefix.clone(), Style::default().fg(color)));
285 } else {
286 spans.push(Span::raw(
287 " ".repeat(UnicodeWidthStr::width(prefix.as_str())),
288 ));
289 }
290 spans.push(Span::styled(part, tool_value_style()));
291 lines.push(Line::from(spans));
292 }
293 }
294
295 if omitted > 0 {
296 lines.push(render_card_detail_line_single(
297 None,
298 &format!(
299 "+{omitted} more \u{00B7} {}",
300 crate::tui::key_shortcuts::tool_details_shortcut_action_hint("list")
301 ),
302 Style::default().fg(palette::TEXT_DIM),
303 ));
304 }
305
306 lines
307 }
308
308 lines RUST