返回 CodeWhale
tool_run.rs
根目录 / crates / tui / src / tui / history / tool_run.rs
1 //! Tool-run grouping for transcript collapse.
2
3 use super::{HistoryCell, ToolCell};
4 use codewhale_localization::{Locale, MessageId, tr};
5
6 #[derive(Debug, Clone, PartialEq, Eq)]
7 pub struct ToolRun {
8 /// Original index of the first tool cell in `App::history`.
9 pub start: usize,
10 /// Number of collapsed cells in the run.
11 pub count: usize,
12 /// Dominant tool names, deduplicated and capped for summary rendering.
13 pub tool_families: Vec<String>,
14 /// Human-facing activity buckets for Cursor-style metadata rows.
15 pub activity: ToolRunActivitySummary,
16 }
17
18 #[derive(Debug, Default, Clone, PartialEq, Eq)]
19 pub struct ToolRunActivitySummary {
20 pub files: usize,
21 pub searches: usize,
22 pub commands: usize,
23 pub edits: usize,
24 pub delegates: usize,
25 pub metadata: usize,
26 pub other: usize,
27 }
28
29 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
30 enum ToolRunActivity {
31 File,
32 Search,
33 Command,
34 Edit,
35 Delegate,
36 Metadata,
37 Other,
38 }
39
40 impl ToolRunActivitySummary {
41 fn record(&mut self, tool: &ToolCell) {
42 match classify_tool_run_activity(tool) {
43 ToolRunActivity::File => self.files += 1,
44 ToolRunActivity::Search => self.searches += 1,
45 ToolRunActivity::Command => self.commands += 1,
46 ToolRunActivity::Edit => self.edits += 1,
47 ToolRunActivity::Delegate => self.delegates += 1,
48 ToolRunActivity::Metadata => self.metadata += 1,
49 ToolRunActivity::Other => self.other += 1,
50 }
51 }
52 }
53
54 /// Detect contiguous runs of successful, low-risk tool cells.
55 ///
56 /// Failed, running, command, MCP, patch, review, diff, and plan-update cells
57 /// split runs so important state never disappears into a summary row
58 /// (`ToolCell::is_collapsible_guard`); `v` / expansion keeps the grouped
59 /// cells' raw details available.
60 #[cfg(test)]
61 pub fn detect_tool_runs(history: &[HistoryCell], min_size: usize) -> Vec<ToolRun> {
62 detect_tool_runs_from_slices(history, &[], min_size)
63 }
64
65 /// Detect contiguous runs across committed history plus the active in-flight
66 /// tail. `ToolRun::start` is always the virtual transcript index:
67 /// `history.len() + active_offset` for active entries.
68 pub fn detect_tool_runs_from_slices(
69 history: &[HistoryCell],
70 active_entries: &[HistoryCell],
71 min_size: usize,
72 ) -> Vec<ToolRun> {
73 if min_size == 0 {
74 return Vec::new();
75 }
76
77 let mut runs = Vec::new();
78 let mut index = 0;
79 let total_len = history.len().saturating_add(active_entries.len());
80 while index < total_len {
81 if !cell_at_virtual_index(history, active_entries, index)
82 .is_some_and(is_collapsible_tool_cell)
83 {
84 index += 1;
85 continue;
86 }
87
88 let start = index;
89 let mut names: Vec<String> = Vec::new();
90 let mut activity = ToolRunActivitySummary::default();
91 while index < total_len
92 && cell_at_virtual_index(history, active_entries, index)
93 .is_some_and(is_collapsible_tool_cell)
94 {
95 if let Some(HistoryCell::Tool(tool)) =
96 cell_at_virtual_index(history, active_entries, index)
97 {
98 let name = tool_display_name(tool);
99 if !names.iter().any(|existing| existing == name) {
100 names.push(name.to_string());
101 }
102 activity.record(tool);
103 }
104 index += 1;
105 }
106
107 let count = index - start;
108 if count >= min_size {
109 names.truncate(3);
110 runs.push(ToolRun {
111 start,
112 count,
113 tool_families: names,
114 activity,
115 });
116 }
117 }
118
119 runs
120 }
121
122 fn cell_at_virtual_index<'a>(
123 history: &'a [HistoryCell],
124 active_entries: &'a [HistoryCell],
125 index: usize,
126 ) -> Option<&'a HistoryCell> {
127 history
128 .get(index)
129 .or_else(|| active_entries.get(index.checked_sub(history.len())?))
130 }
131
132 fn is_collapsible_tool_cell(cell: &HistoryCell) -> bool {
133 matches!(cell, HistoryCell::Tool(tool) if tool.is_success() && !tool.is_collapsible_guard())
134 }
135
136 pub(super) fn generic_tool_name_is_collapse_guard(name: &str) -> bool {
137 let normalized = name.trim().to_ascii_lowercase();
138 if is_metadata_tool_name(&normalized) {
139 return false;
140 }
141
142 normalized.contains("patch")
143 || normalized.contains("write")
144 || normalized.contains("edit")
145 || normalized.contains("delete")
146 || normalized.contains("remove")
147 || normalized.contains("commit")
148 || normalized.contains("push")
149 || normalized.contains("review")
150 }
151
152 fn is_metadata_tool_name(name: &str) -> bool {
153 matches!(
154 name,
155 "update_plan"
156 | "work_update"
157 | "todo_write"
158 | "todo_add"
159 | "todo_update"
160 | "checklist_write"
161 | "checklist_add"
162 | "checklist_update"
163 | "checklist_list"
164 )
165 }
166
167 fn tool_display_name(tool: &ToolCell) -> &str {
168 match tool {
169 ToolCell::Generic(cell) => cell.name.as_str(),
170 ToolCell::Mcp(cell) => cell.tool.as_str(),
171 ToolCell::WebSearch(_) => "web_search",
172 ToolCell::ViewImage(_) => "view_image",
173 ToolCell::DataDisplay(_) => "show_data",
174 ToolCell::Exploring(_) => "explore",
175 ToolCell::Exec(_) => "shell",
176 ToolCell::PlanUpdate(_) => "update_plan",
177 ToolCell::PatchSummary(_) => "apply_patch",
178 ToolCell::Review(_) => "review",
179 }
180 }
181
182 fn classify_tool_run_activity(tool: &ToolCell) -> ToolRunActivity {
183 let name = tool_display_name(tool);
184 classify_tool_name_activity(name)
185 }
186
187 fn classify_tool_name_activity(name: &str) -> ToolRunActivity {
188 let normalized = name.trim().to_ascii_lowercase();
189 match normalized.as_str() {
190 "read_file" | "list_dir" | "view_image" | "explore" | "git_status" | "git_diff"
191 | "git_log" | "git_show" | "git_blame" | "git_commit_plan" => ToolRunActivity::File,
192 "grep_files" | "file_search" | "web_search" | "fetch_url" | "registry_sync" => {
193 ToolRunActivity::Search
194 }
195 "shell"
196 | "exec_shell"
197 | "exec_shell_wait"
198 | "exec_shell_interact"
199 | "exec_shell_cancel"
200 | "task_shell_start"
201 | "task_shell_wait"
202 | "start_registry_mcp_server"
203 | "run_tests"
204 | "run_verifiers"
205 | "wait_for_dev_server"
206 | "task_gate_run"
207 | "validate_data" => ToolRunActivity::Command,
208 "edit_file" | "apply_patch" | "write_file" | "diff" => ToolRunActivity::Edit,
209 "agent" | "rlm_open" | "rlm_eval" | "rlm_configure" | "rlm_close" | "rlm" => {
210 ToolRunActivity::Delegate
211 }
212 _ if is_metadata_tool_name(&normalized) => ToolRunActivity::Metadata,
213 _ if normalized.contains("search")
214 || normalized.contains("grep")
215 || normalized.contains("find") =>
216 {
217 ToolRunActivity::Search
218 }
219 _ if normalized.contains("read")
220 || normalized.contains("list")
221 || normalized.contains("view")
222 || normalized.contains("open") =>
223 {
224 ToolRunActivity::File
225 }
226 _ if normalized.contains("patch")
227 || normalized.contains("write")
228 || normalized.contains("edit")
229 || normalized.contains("diff") =>
230 {
231 ToolRunActivity::Edit
232 }
233 _ if normalized.contains("run")
234 || normalized.contains("exec")
235 || normalized.contains("shell")
236 || normalized.contains("test")
237 || normalized.contains("check") =>
238 {
239 ToolRunActivity::Command
240 }
241 _ if normalized.contains("agent")
242 || normalized.contains("delegate")
243 || normalized.contains("fanout")
244 || normalized.contains("rlm") =>
245 {
246 ToolRunActivity::Delegate
247 }
248 _ if normalized.contains("metadata")
249 || normalized.contains("session")
250 || normalized.contains("context")
251 || normalized.contains("plan")
252 || normalized.contains("todo") =>
253 {
254 ToolRunActivity::Metadata
255 }
256 _ => ToolRunActivity::Other,
257 }
258 }
259
260 #[must_use]
261 pub fn tool_run_summary(run: &ToolRun, locale: Locale) -> String {
262 let activity = &run.activity;
263 let mut parts = Vec::new();
264 if activity.files > 0 {
265 parts.push(counted(
266 activity.files,
267 locale,
268 MessageId::ActivityFileOne,
269 MessageId::ActivityFileMany,
270 ));
271 }
272 if activity.searches > 0 {
273 parts.push(counted(
274 activity.searches,
275 locale,
276 MessageId::ActivitySearchOne,
277 MessageId::ActivitySearchMany,
278 ));
279 }
280
281 let mut clauses = Vec::new();
282 if !parts.is_empty() {
283 let clause = tr(locale, MessageId::ActivityExplored).replace(
284 "{items}",
285 &parts.join(&tr(locale, MessageId::ListSeparator)),
286 );
287 clauses.push(with_activity_families(
288 clause,
289 run,
290 &[ToolRunActivity::File, ToolRunActivity::Search],
291 locale,
292 ));
293 }
294 if activity.commands > 0 {
295 let count = counted(
296 activity.commands,
297 locale,
298 MessageId::ActivityCommandOne,
299 MessageId::ActivityCommandMany,
300 );
301 let clause = tr(locale, MessageId::ActivityRan).replace("{items}", &count);
302 clauses.push(with_activity_families(
303 clause,
304 run,
305 &[ToolRunActivity::Command],
306 locale,
307 ));
308 }
309 if activity.edits > 0 {
310 let count = counted(
311 activity.edits,
312 locale,
313 MessageId::ActivityFileOne,
314 MessageId::ActivityFileMany,
315 );
316 clauses.push(tr(locale, MessageId::ActivityEdited).replace("{items}", &count));
317 }
318 if activity.delegates > 0 {
319 let count = counted(
320 activity.delegates,
321 locale,
322 MessageId::ActivityTaskOne,
323 MessageId::ActivityTaskMany,
324 );
325 clauses.push(tr(locale, MessageId::ActivityDelegated).replace("{items}", &count));
326 }
327 if activity.metadata > 0 || activity.other > 0 || clauses.is_empty() {
328 clauses.push(tr(locale, MessageId::ActivityUpdatedMetadata).into_owned());
329 }
330 sentence_case_activity(clauses.join(&tr(locale, MessageId::ActivityClauseSeparator)))
331 }
332
333 fn with_activity_families(
334 clause: String,
335 run: &ToolRun,
336 activities: &[ToolRunActivity],
337 locale: Locale,
338 ) -> String {
339 let mut families: Vec<String> = Vec::new();
340 for family in &run.tool_families {
341 let label = family.replace('_', " ");
342 if activities.contains(&classify_tool_name_activity(family)) && !families.contains(&label) {
343 families.push(label);
344 }
345 }
346
347 if families.is_empty() {
348 return clause;
349 }
350 tr(locale, MessageId::ActivityFamilies)
351 .replace("{clause}", &clause)
352 .replace(
353 "{families}",
354 &families.join(&tr(locale, MessageId::ListSeparator)),
355 )
356 }
357
358 pub(super) fn counted(
359 count: usize,
360 locale: Locale,
361 singular: MessageId,
362 plural: MessageId,
363 ) -> String {
364 tr(locale, if count == 1 { singular } else { plural }).replace("{count}", &count.to_string())
365 }
366
367 pub(super) fn sentence_case_activity(text: String) -> String {
368 let mut chars = text.chars();
369 let Some(first) = chars.next() else {
370 return text;
371 };
372 let mut out = String::new();
373 out.extend(first.to_uppercase());
374 out.push_str(chars.as_str());
375 out
376 }
377
378 #[cfg(test)]
379 mod tests {
380 use super::*;
381 use codewhale_execpolicy::canonical_action::canonical_action_alias;
382 use serde_json::json;
383
384 #[test]
385 fn canonical_file_mutations_never_collapse_behind_summary_rows() {
386 for action in ["write", "edit", "patch"] {
387 let input = json!({"action": action});
388 let semantic_name = canonical_action_alias("File", &input);
389 assert!(
390 generic_tool_name_is_collapse_guard(semantic_name),
391 "File.{action}"
392 );
393 }
394
395 for action in ["read", "list", "search_name", "search_content"] {
396 let input = json!({"action": action});
397 let semantic_name = canonical_action_alias("File", &input);
398 assert!(
399 !generic_tool_name_is_collapse_guard(semantic_name),
400 "File.{action}"
401 );
402 }
403 }
404
405 #[test]
406 fn normalized_git_and_run_actions_keep_truthful_activity_buckets() {
407 for action in ["status", "diff", "log", "show", "blame", "commit_plan"] {
408 let input = json!({"action": action});
409 assert_eq!(
410 classify_tool_name_activity(canonical_action_alias("Git", &input)),
411 ToolRunActivity::File,
412 "Git.{action}"
413 );
414 }
415 for action in ["tests", "verifiers"] {
416 let input = json!({"action": action});
417 assert_eq!(
418 classify_tool_name_activity(canonical_action_alias("Run", &input)),
419 ToolRunActivity::Command,
420 "Run.{action}"
421 );
422 }
423 }
424 }
425
425 lines RUST