返回 CodeWhale
tool_routing.rs
根目录 / crates / tui / src / tui / tool_routing.rs
1 //! Active tool-card routing helpers for the TUI loop.
2
3 use std::path::PathBuf;
4 use std::time::Instant;
5
6 use crate::tui::active_cell::ActiveCell;
7 use crate::tui::app::{App, ToolDetailRecord, ToolEvidence};
8 use crate::tui::history::DataDisplayCell;
9 use crate::tui::history::ExecCell;
10 use crate::tui::history::ExecSource;
11 use crate::tui::history::ExecWait;
12 use crate::tui::history::ExploringCell;
13 use crate::tui::history::ExploringEntry;
14 use crate::tui::history::GenericToolCell;
15 use crate::tui::history::HistoryCell;
16 use crate::tui::history::McpToolCell;
17 use crate::tui::history::PatchSummaryCell;
18 use crate::tui::history::PlanUpdateCell;
19 use crate::tui::history::ReviewCell;
20 use crate::tui::history::ToolCell;
21 use crate::tui::history::ToolStatus;
22 use crate::tui::history::ViewImageCell;
23 use crate::tui::history::WebSearchCell;
24 use crate::tui::history::output_looks_like_diff;
25 use crate::tui::history::summarize_mcp_output;
26 use crate::tui::workspace_context;
27 use codewhale_app_server::exec_agent::summarize_tool_args;
28 use codewhale_app_server::exec_agent::summarize_tool_output;
29 use codewhale_config::hooks::HookEvent;
30 use codewhale_engine::tools::ReviewOutput;
31 use codewhale_engine::tools::plan::PlanSnapshot;
32 use codewhale_engine::tools::spec::{ToolError, ToolResult};
33 use codewhale_execpolicy::canonical_action::canonical_action_alias;
34 use codewhale_localization::{Locale, MessageId, tr};
35 use codewhale_tools::patch_preflight::{NormalizedApplyPatchInput, normalize_apply_patch_input};
36
37 #[allow(clippy::too_many_lines)]
38 pub(super) fn handle_tool_call_started(
39 app: &mut App,
40 id: &str,
41 name: &str,
42 input: &serde_json::Value,
43 ) {
44 // #2511: ToolCallBefore gate moved to turn-loop planning loop
45 // (Engine::run_turn). Removing observer-only firing
46 // here to avoid double-firing hooks for each tool call.
47 // Hooks that need observation can configure ToolCallBefore on
48 // the turn-loop gate — it processes the denial (exit code 2).
49
50 let id = id.to_string();
51 let semantic_name = canonical_action_alias(name, input);
52
53 // All in-flight tool work for the current turn lives in `app.active_cell`
54 // until the turn completes. This mirrors Codex's contract: ONE active cell
55 // mutates in place; finalized history isn't touched until flush. This
56 // keeps the transcript stable while parallel completions arrive in any
57 // order.
58 if app.active_cell.is_none() {
59 app.active_cell = Some(ActiveCell::new());
60 }
61
62 if is_exploring_tool(semantic_name) {
63 let label = exploring_label(semantic_name, input, &app.workspace, app.ui_locale);
64 push_active_tool_cell(
65 app,
66 &id,
67 name,
68 input,
69 HistoryCell::Tool(ToolCell::Exploring(ExploringCell {
70 entries: vec![ExploringEntry {
71 label,
72 search: semantic_name == "grep_files",
73 status: ToolStatus::Queued,
74 error: None,
75 }],
76 })),
77 );
78 let virtual_index = app.tool_cells[&id];
79 app.exploring_entries.insert(id, (virtual_index, 0));
80 return;
81 }
82
83 if semantic_name == "task_shell_wait"
84 && let Some(task_id) = plain_shell_poll_task_id(input)
85 && has_shell_origin_row(app, task_id)
86 {
87 app.ignored_tool_calls.insert(id, input.clone());
88 return;
89 }
90
91 if is_exec_tool(semantic_name) {
92 let command = exec_target_from_input(input);
93 let source = exec_source_from_input(input);
94 let interaction = exec_interaction_summary(semantic_name, input);
95 let mut is_wait = false;
96
97 if let Some((summary, wait)) = interaction.as_ref() {
98 is_wait = *wait;
99 if is_wait
100 && app
101 .last_exec_wait_command
102 .as_ref()
103 .is_some_and(|last| last == &command)
104 {
105 app.ignored_tool_calls.insert(id, input.clone());
106 return;
107 }
108 if is_wait {
109 app.last_exec_wait_command = Some(command.clone());
110 }
111
112 push_active_tool_cell(
113 app,
114 &id,
115 name,
116 input,
117 HistoryCell::Tool(ToolCell::Exec(ExecCell {
118 command,
119 status: ToolStatus::Queued,
120 output: None,
121 live_output: None,
122 shell_task_id: None,
123 owner_agent_id: None,
124 owner_agent_name: None,
125 started_at: None,
126 duration_ms: None,
127 stale_elapsed_since_output_ms: None,
128 waiting: None,
129 source,
130 description: None,
131 interaction: Some(summary.clone()),
132 output_summary: None,
133 })),
134 );
135 return;
136 }
137
138 if exec_is_background(input)
139 && app
140 .last_exec_wait_command
141 .as_ref()
142 .is_some_and(|last| last == &command)
143 {
144 app.ignored_tool_calls.insert(id, input.clone());
145 return;
146 }
147 if exec_is_background(input) && !is_wait {
148 app.last_exec_wait_command = Some(command.clone());
149 }
150
151 push_active_tool_cell(
152 app,
153 &id,
154 name,
155 input,
156 HistoryCell::Tool(ToolCell::Exec(ExecCell {
157 command,
158 status: ToolStatus::Queued,
159 output: None,
160 live_output: None,
161 shell_task_id: None,
162 owner_agent_id: None,
163 owner_agent_name: None,
164 started_at: None,
165 duration_ms: None,
166 stale_elapsed_since_output_ms: None,
167 waiting: None,
168 source,
169 description: input
170 .get("description")
171 .and_then(serde_json::Value::as_str)
172 .map(str::to_string),
173 interaction: None,
174 output_summary: None,
175 })),
176 );
177 return;
178 }
179
180 if semantic_name == "show_data" {
181 push_active_tool_cell(
182 app,
183 &id,
184 name,
185 input,
186 HistoryCell::Tool(ToolCell::DataDisplay(DataDisplayCell::from_input(
187 input,
188 ToolStatus::Queued,
189 ))),
190 );
191 return;
192 }
193
194 if semantic_name == "update_plan" {
195 let snapshot = parse_plan_input(input);
196 push_active_tool_cell(
197 app,
198 &id,
199 name,
200 input,
201 HistoryCell::Tool(ToolCell::PlanUpdate(PlanUpdateCell {
202 snapshot,
203 status: ToolStatus::Queued,
204 })),
205 );
206 return;
207 }
208
209 if matches!(semantic_name, "write_file" | "edit_file" | "apply_patch") {
210 let (path, summary) = parse_file_mutation_summary(semantic_name, input);
211 push_active_tool_cell(
212 app,
213 &id,
214 name,
215 input,
216 HistoryCell::Tool(ToolCell::PatchSummary(PatchSummaryCell {
217 path,
218 summary,
219 status: ToolStatus::Queued,
220 error: None,
221 receipt: None,
222 })),
223 );
224 return;
225 }
226
227 if semantic_name == "review" {
228 let target = review_target_label(input);
229 push_active_tool_cell(
230 app,
231 &id,
232 name,
233 input,
234 HistoryCell::Tool(ToolCell::Review(ReviewCell {
235 target,
236 status: ToolStatus::Queued,
237 output: None,
238 error: None,
239 })),
240 );
241 return;
242 }
243
244 if is_mcp_tool(semantic_name) {
245 push_active_tool_cell(
246 app,
247 &id,
248 name,
249 input,
250 HistoryCell::Tool(ToolCell::Mcp(McpToolCell {
251 tool: name.to_string(),
252 status: ToolStatus::Queued,
253 content: None,
254 is_image: false,
255 })),
256 );
257 return;
258 }
259
260 if is_view_image_tool(semantic_name) {
261 if let Some(path) = input.get("path").and_then(|v| v.as_str()) {
262 let raw_path = PathBuf::from(path);
263 let display_path = raw_path
264 .strip_prefix(&app.workspace)
265 .unwrap_or(&raw_path)
266 .to_path_buf();
267 push_active_tool_cell(
268 app,
269 &id,
270 name,
271 input,
272 HistoryCell::Tool(ToolCell::ViewImage(ViewImageCell { path: display_path })),
273 );
274 }
275 return;
276 }
277
278 if is_web_search_tool(semantic_name) {
279 let query = web_search_query(input);
280 push_active_tool_cell(
281 app,
282 &id,
283 name,
284 input,
285 HistoryCell::Tool(ToolCell::WebSearch(WebSearchCell {
286 query,
287 status: ToolStatus::Queued,
288 summary: None,
289 source: None,
290 degraded: None,
291 ref_count: 0,
292 })),
293 );
294 return;
295 }
296
297 let mut input_summary = summarize_tool_args(input);
298 // Lead the `agent` args summary with the non-default action so renderers
299 // can tell inspections (peek/status/wait) apart from spawns without a
300 // schema change — a peek must not draw the same "delegate done" line as
301 // a launch (#4112, dogfood A5).
302 if name == "agent"
303 && let Some(action) = input.get("action").and_then(serde_json::Value::as_str)
304 {
305 let action = action.trim().to_ascii_lowercase();
306 let already_leads = input_summary
307 .as_deref()
308 .is_some_and(|summary| summary.starts_with("action:"));
309 if !action.is_empty()
310 && !already_leads
311 && action != "start"
312 && action != "spawn"
313 && action != "run"
314 {
315 input_summary = Some(match input_summary {
316 Some(rest) => format!("action: {action} {rest}"),
317 None => format!("action: {action}"),
318 });
319 }
320 }
321 push_active_tool_cell(
322 app,
323 &id,
324 name,
325 input,
326 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
327 name: semantic_name.to_string(),
328 status: ToolStatus::Queued,
329 input_summary,
330 output: None,
331 prompts: None,
332 spillover_path: None,
333 output_summary: None,
334 is_diff: false,
335 })),
336 );
337 }
338
339 /// Push a tool cell as a new entry in `active_cell`, register the tool id,
340 /// and write a stub detail record so the pager / Ctrl+O can find it.
341 fn push_active_tool_cell(
342 app: &mut App,
343 tool_id: &str,
344 tool_name: &str,
345 input: &serde_json::Value,
346 cell: HistoryCell,
347 ) {
348 if app.active_cell.is_none() {
349 app.active_cell = Some(ActiveCell::new());
350 }
351 let active = app.active_cell.as_mut().expect("active_cell just ensured");
352 let entry_idx = active.push_tool(tool_id.to_string(), cell);
353 app.active_tool_entry_completed_at.remove(&entry_idx);
354 let virtual_index = app.history.len() + entry_idx;
355 register_tool_cell(app, tool_id, tool_name, input, virtual_index);
356 app.mark_history_updated();
357 }
358
359 pub(crate) fn hold_exec_cards_for_approval(app: &mut App, tool_id: &str) {
360 if let Some(&index) = app.tool_cells.get(tool_id) {
361 set_exec_card_waiting(app, index, Some(ExecWait::Approval));
362 }
363 }
364
365 pub(crate) fn clear_exec_card_approval_hold(app: &mut App, tool_id: &str) {
366 if let Some(&index) = app.tool_cells.get(tool_id) {
367 set_exec_card_waiting(app, index, None);
368 }
369 }
370
371 pub(crate) fn record_execute_tools_nested_call(app: &mut App, call_id: &str, action_id: &str) {
372 let action_id = action_id.trim();
373 if action_id.is_empty() || action_id == "execute_tools" {
374 return;
375 }
376 let Some((parent_id, seq)) = call_id.rsplit_once('.') else {
377 return;
378 };
379 if seq.is_empty() || !seq.chars().all(|c| c.is_ascii_digit()) {
380 return;
381 }
382 let Some(&index) = app.tool_cells.get(parent_id) else {
383 return;
384 };
385 let updated = if let Some(HistoryCell::Tool(ToolCell::Generic(generic))) =
386 app.cell_at_virtual_index_mut(index)
387 {
388 if generic.name == "execute_tools" && generic.status == ToolStatus::Running {
389 let prev_count = generic
390 .input_summary
391 .as_deref()
392 .and_then(|summary| summary.split_once(" · "))
393 .and_then(|(prefix, _)| {
394 prefix
395 .strip_suffix(" calls")
396 .or_else(|| prefix.strip_suffix(" call"))
397 })
398 .and_then(|num| num.parse::<usize>().ok())
399 .unwrap_or(0);
400 let next_count = prev_count.saturating_add(1);
401 let call_word = if next_count == 1 { "call" } else { "calls" };
402 generic.input_summary = Some(format!("{next_count} {call_word} · {action_id}"));
403 true
404 } else {
405 false
406 }
407 } else {
408 false
409 };
410 if updated {
411 app.bump_active_cell_revision();
412 app.needs_redraw = true;
413 }
414 }
415
416 pub(crate) fn handle_tool_execution_started(app: &mut App, tool_id: &str) {
417 if let Some(&(virtual_index, entry_idx)) = app.exploring_entries.get(tool_id) {
418 let changed = if let Some(HistoryCell::Tool(ToolCell::Exploring(explore))) =
419 app.cell_at_virtual_index_mut(virtual_index)
420 && let Some(entry) = explore.entries.get_mut(entry_idx)
421 && entry.status == ToolStatus::Queued
422 {
423 entry.status = ToolStatus::Running;
424 true
425 } else {
426 false
427 };
428 if changed {
429 app.bump_active_cell_revision();
430 app.needs_redraw = true;
431 }
432 return;
433 }
434
435 let Some(&index) = app.tool_cells.get(tool_id) else {
436 return;
437 };
438 let changed = if let Some(HistoryCell::Tool(tool)) = app.cell_at_virtual_index_mut(index) {
439 match tool {
440 ToolCell::Exec(exec)
441 if exec.status.is_active()
442 && (exec.status != ToolStatus::Running
443 || exec.waiting.is_some()
444 || exec.started_at.is_none()) =>
445 {
446 exec.status = ToolStatus::Running;
447 exec.waiting = None;
448 exec.started_at.get_or_insert_with(Instant::now);
449 true
450 }
451 ToolCell::PlanUpdate(plan) if plan.status == ToolStatus::Queued => {
452 plan.status = ToolStatus::Running;
453 true
454 }
455 ToolCell::PatchSummary(patch) if patch.status == ToolStatus::Queued => {
456 patch.status = ToolStatus::Running;
457 true
458 }
459 ToolCell::Review(review) if review.status == ToolStatus::Queued => {
460 review.status = ToolStatus::Running;
461 true
462 }
463 ToolCell::Mcp(mcp) if mcp.status == ToolStatus::Queued => {
464 mcp.status = ToolStatus::Running;
465 true
466 }
467 ToolCell::WebSearch(search) if search.status == ToolStatus::Queued => {
468 search.status = ToolStatus::Running;
469 true
470 }
471 ToolCell::DataDisplay(data) if data.status == ToolStatus::Queued => {
472 data.status = ToolStatus::Running;
473 true
474 }
475 ToolCell::Generic(generic) if generic.status == ToolStatus::Queued => {
476 generic.status = ToolStatus::Running;
477 true
478 }
479 _ => false,
480 }
481 } else {
482 false
483 };
484 if changed {
485 app.bump_active_cell_revision();
486 app.needs_redraw = true;
487 }
488 }
489
490 fn set_exec_card_waiting(app: &mut App, index: usize, waiting: Option<ExecWait>) {
491 let is_change = matches!(
492 app.cell_at_virtual_index(index),
493 Some(HistoryCell::Tool(ToolCell::Exec(exec)))
494 if exec.status.is_active() && exec.waiting != waiting
495 );
496 if !is_change {
497 return;
498 }
499 if let Some(HistoryCell::Tool(ToolCell::Exec(exec))) = app.cell_at_virtual_index_mut(index) {
500 exec.waiting = waiting;
501 if waiting.is_none() && exec.started_at.is_none() {
502 exec.status = ToolStatus::Queued;
503 }
504 app.bump_active_cell_revision();
505 app.needs_redraw = true;
506 }
507 }
508
509 fn register_tool_cell(
510 app: &mut App,
511 tool_id: &str,
512 tool_name: &str,
513 input: &serde_json::Value,
514 cell_index: usize,
515 ) {
516 app.tool_cells.insert(tool_id.to_string(), cell_index);
517 let record = ToolDetailRecord {
518 tool_id: tool_id.to_string(),
519 tool_name: tool_name.to_string(),
520 input: input.clone(),
521 output: None,
522 };
523 if cell_index < app.history.len() {
524 app.tool_details_by_cell.insert(cell_index, record);
525 } else {
526 // Active-cell entry: keep the detail record in `active_tool_details`
527 // until the active cell flushes. `flush_active_cell` migrates these
528 // records into `tool_details_by_cell` keyed by the eventual real
529 // cell index.
530 app.active_tool_details.insert(tool_id.to_string(), record);
531 }
532 }
533
534 /// Per-record ceiling on a retained tool output (#5472 finding 3).
535 ///
536 /// These strings are kept for the transcript's expand-tool-output view, which
537 /// shows an excerpt — nothing reads the whole thing. `Bash` already arrives
538 /// truncated at 30 KB, but tools with no such contract (`rlm`, large file
539 /// reads, MCP responses) previously stored whatever they returned, for every
540 /// call, until the 5,000-cell history fold.
541 const TOOL_DETAIL_OUTPUT_MAX_BYTES: usize = 64 * 1024;
542
543 /// Ceiling on retained tool outputs across the whole transcript.
544 ///
545 /// The history cap is counted in *cells*, so 5,000 cells each holding a large
546 /// output was bounded only in principle. Past this budget the oldest cells'
547 /// outputs are released — oldest first, because both other consumers of this
548 /// map (`context_inspector`, `file_picker_relevance`) already read only the
549 /// most recent records, and the expand view degrades to "not retained" rather
550 /// than lying about the content.
551 const TOOL_DETAIL_TOTAL_BUDGET_BYTES: usize = 8 * 1024 * 1024;
552
553 /// Truncate to a whole-character boundary, naming what was dropped.
554 fn bounded_tool_detail_output(mut text: String) -> String {
555 if text.len() <= TOOL_DETAIL_OUTPUT_MAX_BYTES {
556 return text;
557 }
558 let original = text.len();
559 let mut end = TOOL_DETAIL_OUTPUT_MAX_BYTES;
560 while end > 0 && !text.is_char_boundary(end) {
561 end -= 1;
562 }
563 text.truncate(end);
564 text.push_str(&format!(
565 "\n\n[Tool output retained up to {TOOL_DETAIL_OUTPUT_MAX_BYTES} bytes of {original}; \
566 the transcript keeps an excerpt, not the whole result.]"
567 ));
568 text
569 }
570
571 fn store_tool_detail_output(
572 app: &mut App,
573 tool_id: &str,
574 cell_index: usize,
575 result: &Result<ToolResult, ToolError>,
576 ) {
577 let payload = bounded_tool_detail_output(match result {
578 Ok(tool_result) => tool_result.content.clone(),
579 Err(err) => err.to_string(),
580 });
581 if cell_index < app.history.len()
582 && let Some(detail) = app.tool_details_by_cell.get_mut(&cell_index)
583 {
584 detail.output = Some(payload.clone());
585 }
586 // Also write to the active table while the entry might still live there;
587 // some callsites pre-rewrite cell_index but the active_tool_details map is
588 // the canonical source for in-flight outputs.
589 if let Some(detail) = app.active_tool_details.get_mut(tool_id) {
590 detail.output = Some(payload);
591 }
592 release_oldest_tool_detail_outputs(app);
593 }
594
595 /// Hold the retained-output total under [`TOOL_DETAIL_TOTAL_BUDGET_BYTES`] by
596 /// dropping the oldest cells' outputs. The records themselves stay, so the
597 /// inspector still lists the call and its input.
598 pub(super) fn release_oldest_tool_detail_outputs(app: &mut App) {
599 let mut total = 0usize;
600 for detail in app.tool_details_by_cell.values() {
601 total = total.saturating_add(detail.output.as_ref().map_or(0, String::len));
602 }
603 if total <= TOOL_DETAIL_TOTAL_BUDGET_BYTES {
604 return;
605 }
606 let mut oldest_first: Vec<usize> = app
607 .tool_details_by_cell
608 .iter()
609 .filter(|(_, detail)| detail.output.is_some())
610 .map(|(index, _)| *index)
611 .collect();
612 oldest_first.sort_unstable();
613 for index in oldest_first {
614 if total <= TOOL_DETAIL_TOTAL_BUDGET_BYTES {
615 break;
616 }
617 if let Some(detail) = app.tool_details_by_cell.get_mut(&index) {
618 let freed = detail.output.as_ref().map_or(0, String::len);
619 detail.output = None;
620 total = total.saturating_sub(freed);
621 }
622 }
623 }
624
625 #[allow(clippy::too_many_lines)]
626 /// Inspect a tool's success metadata for the `child_*` token-usage
627 /// fields that tools spawning their own LLM calls populate (e.g.
628 /// `rlm`). Roll any reported child-token cost into the session's
629 /// running sub-agent cost counter so the footer total reflects all
630 /// tokens the user is actually billed for, not just the parent turn's
631 /// tokens.
632 ///
633 /// Without this hook, an RLM-heavy session shows a fraction of the
634 /// real spend because the parent turn's `Usage` only counts the
635 /// orchestrator's tokens, not the dozens of `deepseek-v4-flash` child
636 /// rounds RLM fans out under the hood (#524).
637 fn accrue_child_token_cost_if_any(app: &mut App, result: &Result<ToolResult, ToolError>) {
638 let Ok(tool_result) = result else { return };
639 let Some(metadata) = tool_result.metadata.as_ref() else {
640 return;
641 };
642 if let Some(batch) = codewhale_engine::cost_status::child_usage_records_from_metadata(metadata)
643 {
644 let pending = codewhale_engine::cost_status::drain();
645 app.absorb_pending_background_cost(&pending);
646 for record in &batch.records {
647 if record.settlement.is_some() {
648 if let Err(error) = app.absorb_usage_source(record) {
649 tracing::warn!(%error, "tool usage revision was not admitted");
650 }
651 } else {
652 app.mark_usage_uncertain("legacy_usage_unverified");
653 }
654 }
655 for record in &batch.drop_records {
656 let pending = codewhale_engine::cost_status::background_cost_for_runtime_drop(record);
657 app.absorb_pending_background_cost(&pending);
658 }
659 let residual_dropped_records = batch
660 .dropped_records
661 .saturating_sub(u64::try_from(batch.drop_records.len()).unwrap_or(u64::MAX));
662 if residual_dropped_records > 0 {
663 let dropped = u32::try_from(residual_dropped_records).unwrap_or(u32::MAX);
664 app.session.cost_unpriced_turns =
665 app.session.cost_unpriced_turns.saturating_add(dropped);
666 app.session.cost_cny_unpriced_turns =
667 app.session.cost_cny_unpriced_turns.saturating_add(dropped);
668 app.session
669 .cost_unpriced_reasons
670 .insert("routed_usage_receipt_missing".to_string());
671 app.session
672 .cost_cny_unpriced_reasons
673 .insert("routed_usage_receipt_missing".to_string());
674 }
675 return;
676 }
677 if codewhale_engine::cost_status::child_route_envelope_from_metadata(metadata).is_some()
678 && codewhale_engine::cost_status::child_usage_from_metadata(metadata).is_some()
679 {
680 app.mark_usage_uncertain("legacy_usage_unverified");
681 }
682 }
683
684 fn record_spillover_artifact_if_any(
685 app: &mut App,
686 id: &str,
687 name: &str,
688 result: &Result<ToolResult, ToolError>,
689 ) {
690 let Ok(tool_result) = result else { return };
691 let Some(path) = tool_result
692 .metadata
693 .as_ref()
694 .and_then(|metadata| metadata.get("spillover_path"))
695 .and_then(serde_json::Value::as_str)
696 .map(PathBuf::from)
697 else {
698 return;
699 };
700 let metadata = tool_result.metadata.as_ref();
701 let session_id = metadata
702 .and_then(|metadata| metadata.get("artifact_session_id"))
703 .and_then(serde_json::Value::as_str)
704 .or(app.current_session_id.as_deref())
705 .unwrap_or("");
706 let storage_path = metadata
707 .and_then(|metadata| metadata.get("artifact_relative_path"))
708 .and_then(serde_json::Value::as_str)
709 .map(PathBuf::from)
710 .unwrap_or_else(|| path.clone());
711 let content_for_preview = metadata
712 .and_then(|metadata| metadata.get("artifact_preview"))
713 .and_then(serde_json::Value::as_str)
714 .unwrap_or(&tool_result.content);
715 let byte_size = metadata
716 .and_then(|metadata| metadata.get("artifact_byte_size"))
717 .and_then(serde_json::Value::as_u64)
718 .unwrap_or_else(|| {
719 std::fs::metadata(&storage_path)
720 .map(|metadata| metadata.len())
721 .unwrap_or(tool_result.content.len() as u64)
722 });
723 if app
724 .session_artifacts
725 .iter()
726 .any(|artifact| artifact.tool_call_id == id && artifact.storage_path == storage_path)
727 {
728 return;
729 }
730 app.session_artifacts.push(
731 codewhale_runtime::artifacts::record_tool_output_artifact_with_size(
732 session_id,
733 id,
734 name,
735 storage_path,
736 byte_size,
737 content_for_preview,
738 ),
739 );
740 }
741
742 pub(super) fn evidence_completion_should_be_ignored(
743 app: &App,
744 id: &str,
745 result: &Result<ToolResult, ToolError>,
746 ) -> bool {
747 evidence_completion_identity_should_be_ignored(
748 app.current_session_id.as_deref(),
749 app.session_artifacts
750 .iter()
751 .map(|artifact| (artifact.id.as_str(), artifact.tool_call_id.as_str())),
752 id,
753 result,
754 )
755 }
756
757 fn evidence_completion_identity_should_be_ignored<'a>(
758 current_session: Option<&str>,
759 known_artifacts: impl IntoIterator<Item = (&'a str, &'a str)>,
760 id: &str,
761 result: &Result<ToolResult, ToolError>,
762 ) -> bool {
763 let Some(metadata) = result
764 .as_ref()
765 .ok()
766 .and_then(|result| result.metadata.as_ref())
767 else {
768 return false;
769 };
770 let origin = metadata
771 .get("artifact_session_id")
772 .and_then(serde_json::Value::as_str);
773 if let (Some(origin), Some(current)) = (origin, current_session)
774 && origin != current
775 {
776 return true;
777 }
778 metadata
779 .get("artifact_id")
780 .and_then(serde_json::Value::as_str)
781 .is_some_and(|artifact_id| {
782 known_artifacts
783 .into_iter()
784 .any(|(known_id, known_call)| known_id == artifact_id && known_call == id)
785 })
786 }
787
788 /// #3031: shell/tasks tools embed the literal `"(no output)"` into successful
789 /// `ToolResult` content (the model-facing transcript needs a non-empty tool
790 /// result). Treat it as no output on the TUI side so the compact-mode
791 /// suppression gate in `history.rs` actually fires; the raw content remains
792 /// available through the tool-detail store.
793 fn visible_tool_output(content: &str) -> Option<String> {
794 if content.trim() == "(no output)" {
795 None
796 } else {
797 Some(content.to_string())
798 }
799 }
800
801 /// Fire `tool_call_after` for every settled tool call, plus `on_error` when
802 /// the call failed.
803 ///
804 /// `on_error` is documented as covering tool failures, not just transport and
805 /// auth failures, so the tool path has to raise it too — the engine-error path
806 /// in `apply_engine_error_to_app` never sees a tool that returned
807 /// `success: false`.
808 ///
809 /// Both are observer events: their stdout is ignored and neither can change
810 /// the result that goes back to the model. That is a statement about
811 /// Codewhale's control flow only — the commands themselves are arbitrary
812 /// shells and may have any external side effect.
813 fn fire_tool_completion_hooks(
814 app: &mut App,
815 id: &str,
816 name: &str,
817 result: &Result<ToolResult, ToolError>,
818 ignored_input: Option<&serde_json::Value>,
819 ) {
820 let wants_after = app.hooks.has_hooks_for_event(HookEvent::ToolCallAfter);
821 let wants_error = app
822 .hooks
823 .has_hooks_for_event(codewhale_config::hooks::HookEvent::OnError);
824 if !wants_after && !wants_error {
825 // Fast path: skip the result clone and HookContext allocation when
826 // the user has configured neither event.
827 return;
828 }
829
830 let input = ignored_input.cloned().or_else(|| {
831 app.active_tool_details
832 .get(id)
833 .or_else(|| {
834 app.tool_cells
835 .get(id)
836 .and_then(|index| app.tool_details_by_cell.get(index))
837 })
838 .map(|detail| detail.input.clone())
839 });
840 let context = app
841 .base_hook_context()
842 .with_tool_name(name)
843 .with_tool_call_id(id)
844 .with_tool_outcome(result);
845 let context = input.as_ref().map_or_else(
846 || context.clone(),
847 |input| context.clone().with_tool_args(input),
848 );
849 let failed = context.tool_success == Some(false);
850 let error_context = (wants_error && failed).then(|| {
851 let text = context.tool_result.as_deref().unwrap_or_default();
852 let message = format!("tool `{name}` failed: {text}");
853 context.clone().with_error(&message)
854 });
855
856 if wants_after && let Err(error) = app.submit_hooks(HookEvent::ToolCallAfter, context) {
857 app.surface_observer_hook_submission_failure(error);
858 }
859
860 if let Some(context) = error_context
861 && let Err(error) = app.submit_hooks(codewhale_config::hooks::HookEvent::OnError, context)
862 {
863 app.surface_observer_hook_submission_failure(error);
864 }
865 }
866
867 pub(super) fn handle_tool_call_complete(
868 app: &mut App,
869 id: &str,
870 name: &str,
871 result: &Result<ToolResult, ToolError>,
872 ) {
873 let ignored_input = app.ignored_tool_calls.remove(id);
874 if let Some(input) = ignored_input.as_ref()
875 && tool_status_from_result(result) != ToolStatus::Failed
876 {
877 // "Ignored" is a *presentation* decision: these are real settled
878 // results — repeated `wait` polls, background-shell status reads —
879 // that the transcript deliberately does not redraw. Observers still
880 // have to see them, or `tool_call_after` silently skips a whole class
881 // of completions while claiming to fire after each tool call. Fired
882 // here and returned immediately, so each id emits exactly once. A
883 // failed ignored call falls through and is drawn as an orphan.
884 record_spillover_artifact_if_any(app, id, name, result);
885 fire_tool_completion_hooks(app, id, name, result, Some(input));
886 if tool_status_from_result(result) != ToolStatus::Running
887 && refreshes_workspace_context_on_completion(canonical_action_alias(name, input))
888 {
889 workspace_context::refresh_now(app, Instant::now());
890 }
891 return;
892 }
893 // Preserve the execution/audit name while recovering the action-qualified
894 // semantic name from the registered call input. Active entries and
895 // already-flushed history use separate detail stores.
896 let detail = app.active_tool_details.get(id).or_else(|| {
897 app.tool_cells
898 .get(id)
899 .and_then(|cell_index| app.tool_details_by_cell.get(cell_index))
900 });
901 let semantic_name = detail
902 .map_or(name, |detail| canonical_action_alias(name, &detail.input))
903 .to_string();
904 let explicit_background = detail.is_some_and(|detail| {
905 exec_is_background(&detail.input)
906 || detail.input.get("tty").and_then(serde_json::Value::as_bool) == Some(true)
907 });
908
909 // Roll any child-LLM token usage the tool reports into the
910 // session-cost counter. Runs unconditionally so future tools that
911 // spawn their own LLM calls (RLM, summarizers, retrieval helpers)
912 // get accrued without needing a per-tool hook (#524).
913 accrue_child_token_cost_if_any(app, result);
914 record_spillover_artifact_if_any(app, id, name, result);
915
916 // #455: fire `tool_call_after` (and `on_error` for failures) here, before
917 // any of the presentation early-returns below. Firing it further down meant
918 // exploring-tool completions and orphaned completions never emitted the
919 // event at all, so "fires after each tool call" was not true.
920 fire_tool_completion_hooks(app, id, name, result, ignored_input.as_ref());
921
922 // Results recorded by earlier engines begin with a note for the model
923 // ("[approval] This tool call required approval…"). Repeating it as the
924 // first line of the output reads as an internal log (#6566). The engine's
925 // approval stamp decides what is a note, never the text alone.
926 let displayed;
927 let result = match result {
928 Ok(tool_result) => {
929 let shown_content =
930 codewhale_engine::core::engine::content_without_approval_note(tool_result);
931 if shown_content.len() == tool_result.content.len() {
932 result
933 } else {
934 let mut shown = tool_result.clone();
935 shown.content = shown_content.to_string();
936 displayed = Ok(shown);
937 &displayed
938 }
939 }
940 Err(_) => result,
941 };
942
943 // Exploring entries land in the per-tool map regardless of whether they
944 // live in the active cell or in finalized history; the path is the same.
945 if let Some((cell_index, entry_index)) = app.exploring_entries.remove(id) {
946 app.tool_cells.remove(id);
947 store_tool_detail_output(app, id, cell_index, result);
948 if let Some(HistoryCell::Tool(ToolCell::Exploring(cell))) =
949 app.cell_at_virtual_index_mut(cell_index)
950 && let Some(entry) = cell.entries.get_mut(entry_index)
951 {
952 entry.status = tool_status_from_result(result);
953 entry.error = if entry.status == ToolStatus::Failed {
954 match result {
955 Ok(tool_result) => visible_tool_output(&tool_result.content),
956 Err(err) => Some(err.to_string()),
957 }
958 } else {
959 None
960 };
961 app.mark_history_updated();
962 // Mutating the in-flight exploring cell needs an active-cell
963 // revision bump so the transcript cache invalidates the synthetic
964 // tail row.
965 if cell_index >= app.history.len() {
966 app.active_cell_revision = app.active_cell_revision.wrapping_add(1);
967 if let Some(active) = app.active_cell.as_mut() {
968 active.bump_revision();
969 }
970 }
971 }
972 refresh_active_tool_completion_timestamp(app, cell_index);
973 return;
974 }
975
976 // Look up the cell by tool id. If the id isn't registered, that's an
977 // orphan completion (race condition where the started event was lost or
978 // a tool result arrived after the active cell was already flushed). Build
979 // a finalized standalone cell from the result so the user can still see
980 // the output, but DO NOT touch the active cell.
981 let Some(cell_index) = app.tool_cells.remove(id) else {
982 push_orphan_tool_completion(app, id, name, result);
983 return;
984 };
985
986 store_tool_detail_output(app, id, cell_index, result);
987 let in_active = cell_index >= app.history.len();
988
989 let status = tool_status_from_result(result);
990 let mutation_receipt = matches!(
991 semantic_name.as_str(),
992 "write_file" | "edit_file" | "apply_patch"
993 )
994 .then(|| {
995 result.as_ref().ok().and_then(|tool_result| {
996 crate::tui::history::FileMutationReceipt::from_success(&app.workspace, tool_result)
997 })
998 })
999 .flatten();
1000 let mut workflow_panel_output: Option<String> = None;
1001 let mut moved_to_jobs = false;
1002
1003 if let Some(cell) = app.cell_at_virtual_index_mut(cell_index) {
1004 match cell {
1005 HistoryCell::Tool(ToolCell::Exec(exec)) => {
1006 exec.status = status;
1007 if let Ok(tool_result) = result.as_ref() {
1008 let shell_task_id = tool_result
1009 .metadata
1010 .as_ref()
1011 .and_then(|m| m.get("task_id"))
1012 .and_then(serde_json::Value::as_str)
1013 .filter(|task_id| !task_id.trim().is_empty())
1014 .map(str::to_string);
1015 if shell_task_id.is_some() {
1016 exec.shell_task_id = shell_task_id;
1017 }
1018 exec.owner_agent_id = tool_result
1019 .metadata
1020 .as_ref()
1021 .and_then(|m| m.get("owner_agent_id"))
1022 .and_then(serde_json::Value::as_str)
1023 .filter(|agent_id| !agent_id.trim().is_empty())
1024 .map(str::to_string);
1025 exec.owner_agent_name = tool_result
1026 .metadata
1027 .as_ref()
1028 .and_then(|m| m.get("owner_agent_name"))
1029 .and_then(serde_json::Value::as_str)
1030 .filter(|agent_name| !agent_name.trim().is_empty())
1031 .map(str::to_string);
1032 if let Some(meta_command) = tool_result
1033 .metadata
1034 .as_ref()
1035 .and_then(|m| m.get("command"))
1036 .and_then(serde_json::Value::as_str)
1037 && !meta_command.trim().is_empty()
1038 && (exec.command == "command" || exec.command.starts_with("command "))
1039 {
1040 exec.command = meta_command.to_string();
1041 if exec.interaction.as_deref().is_some_and(|interaction| {
1042 interaction.starts_with("Waiting for command")
1043 }) {
1044 let task_suffix = tool_result
1045 .metadata
1046 .as_ref()
1047 .and_then(|m| m.get("task_id"))
1048 .and_then(serde_json::Value::as_str)
1049 .map(|task_id| format!(" ({task_id})"))
1050 .unwrap_or_default();
1051 exec.interaction =
1052 Some(format!("Waiting for \"{meta_command}\"{task_suffix}"));
1053 }
1054 }
1055 exec.duration_ms = tool_result
1056 .metadata
1057 .as_ref()
1058 .and_then(|m| m.get("duration_ms"))
1059 .and_then(serde_json::Value::as_u64);
1060 if status != ToolStatus::Running && exec.interaction.is_none() {
1061 exec.output = visible_tool_output(&tool_result.content);
1062 exec.output_summary = exec
1063 .output
1064 .as_deref()
1065 .map(codewhale_app_server::exec_agent::summarize_tool_output);
1066 exec.live_output = None;
1067 } else if status == ToolStatus::Running && exec.interaction.is_none() {
1068 moved_to_jobs = !explicit_background;
1069 }
1070 } else if let Err(err) = result.as_ref()
1071 && exec.interaction.is_none()
1072 {
1073 exec.output = Some(err.to_string());
1074 exec.output_summary = Some(
1075 codewhale_app_server::exec_agent::summarize_tool_output(&err.to_string()),
1076 );
1077 }
1078 app.mark_history_updated();
1079 }
1080 HistoryCell::Tool(ToolCell::PlanUpdate(plan)) => {
1081 plan.status = status;
1082 app.mark_history_updated();
1083 }
1084 HistoryCell::Tool(ToolCell::PatchSummary(patch)) => {
1085 patch.status = status;
1086 patch.receipt = mutation_receipt;
1087 match result.as_ref() {
1088 Ok(tool_result) if tool_result.success => {
1089 if let Ok(json) =
1090 serde_json::from_str::<serde_json::Value>(&tool_result.content)
1091 && let Some(message) = json.get("message").and_then(|v| v.as_str())
1092 {
1093 patch.summary = message.to_string();
1094 }
1095 }
1096 Ok(tool_result) => {
1097 patch.error = Some(tool_result.content.clone());
1098 }
1099 Err(err) => {
1100 patch.error = Some(err.to_string());
1101 }
1102 }
1103 app.mark_history_updated();
1104 }
1105 HistoryCell::Tool(ToolCell::Review(review)) => {
1106 review.status = status;
1107 match result.as_ref() {
1108 Ok(tool_result) => {
1109 if tool_result.success {
1110 review.output = Some(ReviewOutput::parse(&tool_result.content));
1111 } else {
1112 review.error = Some(tool_result.content.clone());
1113 }
1114 }
1115 Err(err) => {
1116 review.error = Some(err.to_string());
1117 }
1118 }
1119 app.mark_history_updated();
1120 }
1121 HistoryCell::Tool(ToolCell::Mcp(mcp)) => {
1122 match result.as_ref() {
1123 Ok(tool_result) => {
1124 let summary = summarize_mcp_output(&tool_result.content);
1125 if status == ToolStatus::Hydrated {
1126 mcp.status = status;
1127 } else if summary.is_error == Some(true) {
1128 mcp.status = ToolStatus::Failed;
1129 } else {
1130 mcp.status = status;
1131 }
1132 mcp.is_image = summary.is_image;
1133 mcp.content = summary.content;
1134 }
1135 Err(err) => {
1136 mcp.status = status;
1137 mcp.content = Some(err.to_string());
1138 }
1139 }
1140 app.mark_history_updated();
1141 }
1142 HistoryCell::Tool(ToolCell::DataDisplay(data)) => {
1143 data.status = status;
1144 match result.as_ref() {
1145 Ok(tool_result) if !tool_result.success => {
1146 data.display = Err(tool_result.content.clone());
1147 }
1148 Err(err) => data.display = Err(err.to_string()),
1149 Ok(_) => {}
1150 }
1151 if data.display.is_err() {
1152 data.status = ToolStatus::Failed;
1153 }
1154 app.mark_history_updated();
1155 }
1156 HistoryCell::Tool(ToolCell::WebSearch(search)) => {
1157 search.status = status;
1158 match result.as_ref() {
1159 Ok(tool_result) => {
1160 search.summary = Some(summarize_tool_output(&tool_result.content));
1161 let presentation = web_search_presentation(&tool_result.content);
1162 search.source = presentation.source;
1163 search.degraded = presentation.degraded;
1164 search.ref_count = presentation.ref_count;
1165 }
1166 Err(err) => {
1167 search.summary = Some(err.to_string());
1168 }
1169 }
1170 app.mark_history_updated();
1171 }
1172 HistoryCell::Tool(ToolCell::Generic(generic)) => {
1173 generic.status = status;
1174 match result.as_ref() {
1175 Ok(tool_result) => {
1176 generic.output = visible_tool_output(&tool_result.content);
1177 generic.output_summary =
1178 generic.output.as_deref().map(summarize_tool_output);
1179 generic.is_diff = output_looks_like_diff(&tool_result.content);
1180 }
1181 Err(err) => {
1182 generic.output = Some(err.to_string());
1183 generic.output_summary = Some(summarize_tool_output(&err.to_string()));
1184 generic.is_diff = false;
1185 }
1186 }
1187 // #4121: capture workflow JSON before releasing the cell borrow
1188 // so we can hydrate the panel without overlapping borrows.
1189 if generic.name == "workflow" {
1190 workflow_panel_output = generic.output.clone();
1191 }
1192 app.mark_history_updated();
1193 }
1194 _ => {}
1195 }
1196 }
1197
1198 // #4121 / #4122: feed typed workflow events into the panel *and* keep the
1199 // history card snapshot in sync. Live streaming also arrives via
1200 // `Event::WorkflowUi`; this path covers tool-complete hydration.
1201 if let Some(output) = workflow_panel_output.as_deref() {
1202 apply_workflow_output_to_panel(app, output);
1203 }
1204 if moved_to_jobs {
1205 let notice = app
1206 .tr(codewhale_localization::MessageId::ShellWaitReleased)
1207 .replace("{jobs}", "/jobs");
1208 app.push_status_toast(notice, crate::tui::app::StatusToastLevel::Info, Some(6_000));
1209 }
1210
1211 // If the mutated cell lived inside the active group, bump the active-cell
1212 // revision so the transcript cache re-renders the synthetic tail row.
1213 if in_active {
1214 app.active_cell_revision = app.active_cell_revision.wrapping_add(1);
1215 if let Some(active) = app.active_cell.as_mut() {
1216 active.bump_revision();
1217 }
1218 refresh_active_tool_completion_timestamp(app, cell_index);
1219 }
1220
1221 if refreshes_workspace_context_on_completion(&semantic_name) && status != ToolStatus::Running {
1222 workspace_context::refresh_now(app, Instant::now());
1223 }
1224
1225 // Collect evidence for the post-turn receipt.
1226 let evidence_summary = match result.as_ref() {
1227 Ok(tool_result) => {
1228 if tool_result.success {
1229 summarize_tool_output(&tool_result.content)
1230 } else {
1231 format!("failed: {}", summarize_tool_output(&tool_result.content))
1232 }
1233 }
1234 Err(err) => format!("error: {err}"),
1235 };
1236 app.tool_evidence.push(ToolEvidence {
1237 tool_name: name.to_string(),
1238 summary: evidence_summary,
1239 });
1240 }
1241
1242 #[derive(Debug, Default, PartialEq, Eq)]
1243 struct WebSearchPresentation {
1244 source: Option<String>,
1245 degraded: Option<String>,
1246 ref_count: usize,
1247 }
1248
1249 fn web_search_presentation(content: &str) -> WebSearchPresentation {
1250 let Ok(value) = serde_json::from_str::<serde_json::Value>(content) else {
1251 return WebSearchPresentation::default();
1252 };
1253 let surfaces = if value.get("receipt").is_some() {
1254 vec![&value]
1255 } else {
1256 value
1257 .get("search_query")
1258 .and_then(serde_json::Value::as_array)
1259 .map(|items| items.iter().collect())
1260 .unwrap_or_default()
1261 };
1262 let source = surfaces
1263 .iter()
1264 .filter_map(|surface| surface.get("source").and_then(serde_json::Value::as_str))
1265 .map(str::to_string)
1266 .next();
1267 let mut degraded = Vec::new();
1268 let mut ref_count = 0usize;
1269 for surface in surfaces {
1270 if let Some(results) = surface.get("results").and_then(serde_json::Value::as_array) {
1271 ref_count = ref_count.saturating_add(
1272 results
1273 .iter()
1274 .filter(|result| {
1275 result
1276 .get("ref_id")
1277 .and_then(serde_json::Value::as_str)
1278 .is_some_and(|ref_id| !ref_id.is_empty())
1279 })
1280 .count(),
1281 );
1282 }
1283 if let Some(reasons) = surface
1284 .pointer("/receipt/degraded")
1285 .and_then(serde_json::Value::as_array)
1286 {
1287 for reason in reasons {
1288 if let Some(label) = degraded_reason_label(reason)
1289 && !degraded.contains(&label)
1290 {
1291 degraded.push(label);
1292 }
1293 }
1294 }
1295 }
1296 WebSearchPresentation {
1297 source,
1298 degraded: (!degraded.is_empty()).then(|| degraded.join("; ")),
1299 ref_count,
1300 }
1301 }
1302
1303 fn degraded_reason_label(reason: &serde_json::Value) -> Option<String> {
1304 let kind = reason.get("kind")?.as_str()?;
1305 let backend = |field: &str| {
1306 reason
1307 .get(field)
1308 .and_then(serde_json::Value::as_str)
1309 .unwrap_or("unknown")
1310 };
1311 Some(match kind {
1312 "backend_unavailable" => format!("{} unavailable", backend("backend")),
1313 "no_usable_results" => format!("{} returned no usable results", backend("backend")),
1314 "backend_fallback" => format!("{} -> {}", backend("from"), backend("to")),
1315 "challenge_detected" => format!("{} challenge", backend("backend")),
1316 "scrape_fallback" => format!("{} -> {} scrape", backend("from"), backend("to")),
1317 "knob_ignored" => format!(
1318 "{} ignored",
1319 reason
1320 .get("knob")
1321 .and_then(serde_json::Value::as_str)
1322 .unwrap_or("filter")
1323 ),
1324 "post_filtered" => format!(
1325 "{} post-filtered",
1326 reason
1327 .get("knob")
1328 .and_then(serde_json::Value::as_str)
1329 .unwrap_or("results")
1330 ),
1331 "synthesized_results" => "synthesized results".to_string(),
1332 other => other.replace('_', " "),
1333 })
1334 }
1335
1336 /// Hydrate or advance a workflow run from a workflow tool JSON payload: a
1337 /// run record (with its retained `events` tail) or a status envelope. A
1338 /// status envelope only refreshes runs this view already holds — polling an
1339 /// old run must not bring it back, or its finish line would be written twice.
1340 fn apply_workflow_output_to_panel(app: &mut App, output: &str) {
1341 let Ok(value) = serde_json::from_str::<serde_json::Value>(output) else {
1342 return;
1343 };
1344 if value.get("action").and_then(|v| v.as_str()) == Some("status") {
1345 if let Some(runs) = value.get("runs").and_then(|r| r.as_array()) {
1346 for run in runs {
1347 apply_workflow_run_record(app, run, false);
1348 }
1349 }
1350 } else {
1351 apply_workflow_run_record(app, &value, true);
1352 }
1353 app.announce_settled_workflows();
1354 }
1355
1356 fn apply_workflow_run_record(app: &mut App, value: &serde_json::Value, may_create: bool) {
1357 let Some(run_id) = value
1358 .get("run_id")
1359 .and_then(|v| v.as_str())
1360 .filter(|run_id| !run_id.trim().is_empty())
1361 .map(str::to_string)
1362 .or_else(|| {
1363 value
1364 .get("events")
1365 .and_then(|events| events.as_array())
1366 .and_then(|events| {
1367 events.iter().find_map(|event| {
1368 event
1369 .get("run_id")
1370 .and_then(|v| v.as_str())
1371 .filter(|run_id| !run_id.trim().is_empty())
1372 .map(str::to_string)
1373 })
1374 })
1375 })
1376 else {
1377 return;
1378 };
1379 if app.workflow_run(&run_id).is_none() && !may_create {
1380 return;
1381 }
1382 let label = value
1383 .get("workflow_goal")
1384 .and_then(|v| v.as_str())
1385 .or_else(|| value.get("workflow_id").and_then(|v| v.as_str()))
1386 .unwrap_or(&run_id)
1387 .to_string();
1388 let at_ms = value
1389 .get("started_at_ms")
1390 .and_then(|v| v.as_u64())
1391 .unwrap_or(0);
1392
1393 // Prefer the typed event stream when present.
1394 if let Some(events) = value.get("events").and_then(|e| e.as_array()) {
1395 if app.workflow_run(&run_id).is_none() {
1396 let mut panel = crate::tui::widgets::workflow_panel::WorkflowPanel::new(
1397 run_id.clone(),
1398 label,
1399 at_ms,
1400 );
1401 panel.locale = app.ui_locale;
1402 app.push_workflow_run(panel);
1403 }
1404 let Some(panel) = app.workflow_run_mut(&run_id) else {
1405 return;
1406 };
1407 let injected: Vec<serde_json::Value> = events
1408 .iter()
1409 .map(|event| {
1410 let mut event = event.clone();
1411 if let Some(obj) = event.as_object_mut() {
1412 // The top-level run record is authoritative. Do not let a
1413 // stale/malformed embedded id retarget one replay event.
1414 obj.insert(
1415 "run_id".to_string(),
1416 serde_json::Value::String(run_id.clone()),
1417 );
1418 }
1419 event
1420 })
1421 .collect();
1422 // A replayed tail can repeat this run's `run_started`, which resets
1423 // its state; whether the finish line was written survives that.
1424 let announced = panel.finish_announced;
1425 panel.apply_json_events(&injected);
1426 panel.finish_announced = announced || panel.finish_announced;
1427 // Completion/status payloads replay a retained event tail. Merge
1428 // the authoritative exact count + bounded structured ledger after
1429 // replay so live dispatch failures are neither duplicated nor
1430 // lost when older events have fallen out of the tail (#5528).
1431 panel.merge_dispatch_failures_from_run_json(value);
1432 if let Some(summary) = value
1433 .get("result")
1434 .and_then(codewhale_engine::tools::workflow::workflow_result_preview)
1435 {
1436 panel.result_summary = Some(summary);
1437 }
1438 if let Some(path) = value.get("source_path").and_then(|v| v.as_str()) {
1439 panel.source_path = Some(PathBuf::from(path));
1440 }
1441 app.needs_redraw = true;
1442 sync_workflow_history_card(app, &run_id);
1443 return;
1444 }
1445
1446 // A summary/phases snapshot hydrates the whole run.
1447 if let Some(mut panel) =
1448 crate::tui::widgets::workflow_panel::WorkflowPanel::from_run_json(value)
1449 {
1450 panel.locale = app.ui_locale;
1451 match app.workflow_run_mut(&run_id) {
1452 Some(existing) => {
1453 panel.finish_announced = existing.finish_announced;
1454 *existing = panel;
1455 }
1456 None => app.push_workflow_run(panel),
1457 }
1458 app.needs_redraw = true;
1459 sync_workflow_history_card(app, &run_id);
1460 return;
1461 }
1462
1463 // Fallback: bare run record without events — at least surface its state.
1464 use crate::tui::widgets::workflow_panel::{WorkflowPanelEvent, WorkflowPanelLifecycle};
1465 let status = value
1466 .get("status")
1467 .and_then(|v| v.as_str())
1468 .unwrap_or("running");
1469 if app.workflow_run(&run_id).is_none() {
1470 app.apply_workflow_panel_event(
1471 &run_id,
1472 WorkflowPanelEvent::RunStarted {
1473 run_id: run_id.clone(),
1474 workflow_id: value
1475 .get("workflow_id")
1476 .and_then(|v| v.as_str())
1477 .map(str::to_string),
1478 workflow_goal: Some(label),
1479 source_path: value
1480 .get("source_path")
1481 .and_then(|v| v.as_str())
1482 .map(PathBuf::from),
1483 at_ms,
1484 },
1485 );
1486 }
1487 let life = match status {
1488 "completed" | "succeeded" => WorkflowPanelLifecycle::Succeeded,
1489 "degraded" => WorkflowPanelLifecycle::Degraded,
1490 "failed" => WorkflowPanelLifecycle::Failed,
1491 "cancelled" | "canceled" => WorkflowPanelLifecycle::Cancelled,
1492 _ => WorkflowPanelLifecycle::Running,
1493 };
1494 if life != WorkflowPanelLifecycle::Running
1495 && app
1496 .workflow_run(&run_id)
1497 .is_some_and(|run| !run.lifecycle.is_terminal())
1498 {
1499 app.apply_workflow_panel_event(
1500 &run_id,
1501 WorkflowPanelEvent::RunCompleted {
1502 status: life,
1503 error: value
1504 .get("error")
1505 .and_then(|v| v.as_str())
1506 .map(str::to_string),
1507 at_ms: value
1508 .get("completed_at_ms")
1509 .and_then(|v| v.as_u64())
1510 .unwrap_or(at_ms),
1511 },
1512 );
1513 }
1514 sync_workflow_history_card(app, &run_id);
1515 }
1516
1517 /// Apply one live `WorkflowUi` engine event to its run.
1518 ///
1519 /// Progress is applied to state at once but costs nothing else: only a run's
1520 /// start and end touch the transcript, so a 75-agent fan-out's stream of
1521 /// task and budget events never rescans history or reserializes a card.
1522 pub(super) fn apply_workflow_ui_event(app: &mut App, run_id: &str, event: &serde_json::Value) {
1523 use crate::tui::widgets::workflow_panel::WorkflowPanelEvent;
1524
1525 let mut event = event.clone();
1526 if let Some(obj) = event.as_object_mut() {
1527 // The engine envelope owns route identity. An embedded stale id must
1528 // not move this event onto another run's state.
1529 obj.insert(
1530 "run_id".to_string(),
1531 serde_json::Value::String(run_id.to_string()),
1532 );
1533 }
1534 let event_type = event
1535 .get("type")
1536 .and_then(|v| v.as_str())
1537 .unwrap_or_default()
1538 .to_string();
1539 // The engine names what the run returned; keep it for the finish line.
1540 // Set before the event applies, so the line written on this very event
1541 // already carries it.
1542 if event_type == "run_completed"
1543 && let Some(preview) = event
1544 .get("result_preview")
1545 .and_then(|v| v.as_str())
1546 .map(str::to_string)
1547 && let Some(run) = app.workflow_run_mut(run_id)
1548 {
1549 run.result_summary = Some(preview);
1550 }
1551 let Some(panel_event) = WorkflowPanelEvent::from_json_value(&event) else {
1552 return;
1553 };
1554 if !app.apply_workflow_panel_event(run_id, panel_event) {
1555 return;
1556 }
1557 if event_type == "run_started" {
1558 sync_workflow_history_card(app, run_id);
1559 }
1560 }
1561
1562 /// Apply a live workflow event only when its immutable owner is the active
1563 /// conversation. This check deliberately sits in the mutation helper so every
1564 /// caller fails closed before touching the run or transcript history.
1565 pub(super) fn apply_owned_workflow_ui_event(
1566 app: &mut App,
1567 owner_session_id: &str,
1568 run_id: &str,
1569 event: &serde_json::Value,
1570 ) -> bool {
1571 if app.current_session_id.as_deref() != Some(owner_session_id) {
1572 return false;
1573 }
1574 apply_workflow_ui_event(app, run_id, event);
1575 true
1576 }
1577
1578 /// A foreground `run` card has no output until the tool returns, but its
1579 /// start line names the run. Give the newest still-running `workflow` card —
1580 /// the one this run belongs to, or one that has no run yet — the run's
1581 /// snapshot. A card whose tool has returned keeps its own output.
1582 fn sync_workflow_history_card(app: &mut App, run_id: &str) {
1583 let Some(snapshot) = app
1584 .workflow_run(run_id)
1585 .map(|panel| panel.to_run_json().to_string())
1586 else {
1587 return;
1588 };
1589 let history_len = app.history.len();
1590 let total = history_len
1591 + app
1592 .active_cell
1593 .as_ref()
1594 .map(|a| a.entries().len())
1595 .unwrap_or(0);
1596 let mut target = None;
1597 for idx in (0..total).rev() {
1598 let Some(HistoryCell::Tool(ToolCell::Generic(generic))) = app.cell_at_virtual_index(idx)
1599 else {
1600 continue;
1601 };
1602 if generic.name != "workflow" || !generic.status.is_active() {
1603 continue;
1604 }
1605 let card_run = generic
1606 .output
1607 .as_deref()
1608 .and_then(|out| serde_json::from_str::<serde_json::Value>(out).ok())
1609 .and_then(|v| {
1610 v.get("run_id")
1611 .and_then(|id| id.as_str())
1612 .map(str::to_string)
1613 });
1614 match card_run.as_deref() {
1615 Some(id) if id == run_id => {
1616 target = Some(idx);
1617 break;
1618 }
1619 None if target.is_none() => target = Some(idx),
1620 _ => {}
1621 }
1622 }
1623 let Some(idx) = target else {
1624 return;
1625 };
1626 if let Some(HistoryCell::Tool(ToolCell::Generic(generic))) = app.cell_at_virtual_index_mut(idx)
1627 {
1628 generic.output = Some(snapshot);
1629 generic.output_summary = Some(format!("workflow {run_id}"));
1630 app.mark_history_updated();
1631 }
1632 }
1633
1634 fn refresh_active_tool_completion_timestamp(app: &mut App, cell_index: usize) {
1635 if cell_index < app.history.len() {
1636 return;
1637 }
1638 let entry_idx = cell_index - app.history.len();
1639 let Some(cell) = app.cell_at_virtual_index(cell_index) else {
1640 app.active_tool_entry_completed_at.remove(&entry_idx);
1641 return;
1642 };
1643
1644 if history_cell_has_running_tool(cell) {
1645 app.active_tool_entry_completed_at.remove(&entry_idx);
1646 } else {
1647 app.active_tool_entry_completed_at
1648 .entry(entry_idx)
1649 .or_insert_with(Instant::now);
1650 }
1651 }
1652
1653 fn history_cell_has_running_tool(cell: &HistoryCell) -> bool {
1654 let HistoryCell::Tool(tool) = cell else {
1655 return false;
1656 };
1657 match tool {
1658 ToolCell::Exec(exec) => exec.status.is_active(),
1659 ToolCell::Exploring(explore) => {
1660 explore.entries.iter().any(|entry| entry.status.is_active())
1661 }
1662 ToolCell::PlanUpdate(plan) => plan.status.is_active(),
1663 ToolCell::PatchSummary(patch) => patch.status.is_active(),
1664 ToolCell::Review(review) => review.status.is_active(),
1665 ToolCell::Mcp(mcp) => mcp.status.is_active(),
1666 ToolCell::ViewImage(_) => false,
1667 ToolCell::WebSearch(search) => search.status.is_active(),
1668 ToolCell::DataDisplay(data) => data.status.is_active(),
1669 ToolCell::Generic(generic) => generic.status.is_active(),
1670 }
1671 }
1672
1673 /// Build a finalized standalone history cell for a tool completion whose
1674 /// start was never registered (orphan). This preserves the contract that
1675 /// every tool result is visible somewhere; the alternative (silently
1676 /// dropping it) hides errors and breaks debuggability.
1677 ///
1678 /// Choice of cell type: success-only mutation metadata is sufficient to
1679 /// reconstruct a structured File receipt; other orphans stay generic because
1680 /// no input payload remains. The pager remains usable in both cases because
1681 /// `tool_details_by_cell` is populated with the result text.
1682 ///
1683 /// ## Index drift
1684 ///
1685 /// If an active cell is in flight when the orphan arrives, pushing the
1686 /// orphan into `app.history` shifts every active-cell virtual index forward
1687 /// by 1. We must rewrite `tool_cells` / `exploring_entries` accordingly so
1688 /// later completion lookups still find the right entries.
1689 fn push_orphan_tool_completion(
1690 app: &mut App,
1691 tool_id: &str,
1692 name: &str,
1693 result: &Result<ToolResult, ToolError>,
1694 ) {
1695 let status = tool_status_from_result(result);
1696 let output = match result.as_ref() {
1697 Ok(tool_result) => Some(summarize_tool_output(&tool_result.content)),
1698 Err(err) => Some(err.to_string()),
1699 };
1700 let spillover_path = result
1701 .as_ref()
1702 .ok()
1703 .and_then(|r| r.metadata.as_ref())
1704 .and_then(|m| m.get("spillover_path"))
1705 .and_then(serde_json::Value::as_str)
1706 .map(std::path::PathBuf::from);
1707 let output_summary = output.as_deref().map(summarize_tool_output);
1708 let is_diff = output.as_deref().is_some_and(output_looks_like_diff);
1709 let mutation_receipt = result.as_ref().ok().and_then(|tool_result| {
1710 crate::tui::history::FileMutationReceipt::from_success(&app.workspace, tool_result)
1711 });
1712 let cell = if let Some(receipt) = mutation_receipt {
1713 let path = receipt
1714 .files
1715 .first()
1716 .map_or_else(|| "<file>".to_string(), |file| file.path.clone());
1717 let summary = receipt.semantic_summary(app.ui_locale);
1718 HistoryCell::Tool(ToolCell::PatchSummary(PatchSummaryCell {
1719 path,
1720 summary,
1721 status,
1722 error: None,
1723 receipt: Some(receipt),
1724 }))
1725 } else {
1726 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
1727 name: name.to_string(),
1728 status,
1729 input_summary: None,
1730 output,
1731 prompts: None,
1732 spillover_path,
1733 output_summary,
1734 is_diff,
1735 }))
1736 };
1737 app.add_message(cell);
1738 let cell_index = app.history.len().saturating_sub(1);
1739 app.tool_details_by_cell.insert(
1740 cell_index,
1741 ToolDetailRecord {
1742 tool_id: tool_id.to_string(),
1743 tool_name: name.to_string(),
1744 input: serde_json::Value::Null,
1745 output: match result.as_ref() {
1746 Ok(tool_result) => Some(tool_result.content.clone()),
1747 Err(err) => Some(err.to_string()),
1748 },
1749 },
1750 );
1751
1752 // The virtual-index rebase this path used to do inline now lives in
1753 // `App::add_message`, so every mid-turn history insert gets it — not just
1754 // orphan completions. That gap was #5478: `/rename`'s note shifted the
1755 // indices with nothing to re-base them.
1756 }
1757
1758 fn tool_status_from_result(result: &Result<ToolResult, ToolError>) -> ToolStatus {
1759 match result.as_ref() {
1760 Ok(tool_result) if is_deferred_schema_hydration(tool_result) => ToolStatus::Hydrated,
1761 Ok(tool_result) => match metadata_status(tool_result.metadata.as_ref()) {
1762 Some("Running") => ToolStatus::Running,
1763 Some("Killed") => ToolStatus::Stopped,
1764 _ if tool_result.success => ToolStatus::Success,
1765 _ if tool_result
1766 .metadata
1767 .as_ref()
1768 .and_then(|meta| meta.get("cancelled"))
1769 .and_then(serde_json::Value::as_bool)
1770 == Some(true) =>
1771 {
1772 ToolStatus::Stopped
1773 }
1774 _ => ToolStatus::Failed,
1775 },
1776 Err(err) => match metadata_status(err.metadata()) {
1777 Some("Killed") => ToolStatus::Stopped,
1778 _ => ToolStatus::Failed,
1779 },
1780 }
1781 }
1782
1783 fn metadata_status(metadata: Option<&serde_json::Value>) -> Option<&str> {
1784 metadata
1785 .and_then(|meta| meta.get("status"))
1786 .and_then(serde_json::Value::as_str)
1787 }
1788
1789 fn is_deferred_schema_hydration(tool_result: &ToolResult) -> bool {
1790 let Some(metadata) = tool_result.metadata.as_ref() else {
1791 return false;
1792 };
1793 metadata
1794 .get("event")
1795 .and_then(serde_json::Value::as_str)
1796 .is_some_and(|event| event == "tool.schema_hydrated")
1797 && metadata
1798 .get("executed")
1799 .and_then(serde_json::Value::as_bool)
1800 .is_some_and(|executed| !executed)
1801 && metadata
1802 .get("deferred_tool_loaded")
1803 .and_then(serde_json::Value::as_bool)
1804 .unwrap_or(false)
1805 }
1806
1807 fn is_exploring_tool(name: &str) -> bool {
1808 matches!(name, "read_file" | "list_dir" | "grep_files" | "list_files")
1809 }
1810
1811 fn is_exec_tool(name: &str) -> bool {
1812 matches!(
1813 name,
1814 "exec_shell"
1815 | "exec_shell_wait"
1816 | "exec_shell_interact"
1817 | "exec_shell_cancel"
1818 | "exec_wait"
1819 | "exec_interact"
1820 | "task_shell_wait"
1821 )
1822 }
1823
1824 fn plain_shell_poll_task_id(input: &serde_json::Value) -> Option<&str> {
1825 if input.get("task_ids").is_some()
1826 || input.get("gate").is_some_and(|gate| !gate.is_null())
1827 || codewhale_engine::tools::tasks::task_shell_wait_requests_cancel(input)
1828 {
1829 return None;
1830 }
1831 input
1832 .get("task_id")
1833 .and_then(serde_json::Value::as_str)
1834 .filter(|task_id| !task_id.trim().is_empty())
1835 }
1836
1837 fn has_shell_origin_row(app: &App, task_id: &str) -> bool {
1838 (0..app.virtual_cell_count()).any(|index| {
1839 matches!(
1840 app.cell_at_virtual_index(index),
1841 Some(HistoryCell::Tool(ToolCell::Exec(exec)))
1842 if exec.interaction.is_none() && exec.shell_task_id.as_deref() == Some(task_id)
1843 )
1844 })
1845 }
1846
1847 pub(super) fn refreshes_workspace_context_on_completion(name: &str) -> bool {
1848 matches!(
1849 name,
1850 "exec_shell"
1851 | "exec_shell_wait"
1852 | "exec_shell_interact"
1853 | "exec_shell_cancel"
1854 | "exec_wait"
1855 | "exec_interact"
1856 | "task_shell_start"
1857 | "task_shell_wait"
1858 | "write_file"
1859 | "edit_file"
1860 | "apply_patch"
1861 )
1862 }
1863
1864 pub(super) fn exploring_label(
1865 name: &str,
1866 input: &serde_json::Value,
1867 workspace: &std::path::Path,
1868 locale: Locale,
1869 ) -> String {
1870 let fallback = format!("{name} tool");
1871 let obj = input.as_object();
1872 let path = || {
1873 obj.and_then(|o| o.get("path"))
1874 .and_then(|v| v.as_str())
1875 .map(|path| codewhale_util::utils::workspace_relative(path, workspace))
1876 };
1877 match name {
1878 "read_file" => path().map_or(fallback, |path| {
1879 tr(locale, MessageId::ToolExploringReading).replace("{path}", &path)
1880 }),
1881 "list_dir" => path().map_or_else(
1882 || tr(locale, MessageId::ToolExploringListingDirectory).into_owned(),
1883 |path| tr(locale, MessageId::ToolExploringListing).replace("{path}", &path),
1884 ),
1885 "grep_files" => {
1886 let pattern = obj
1887 .and_then(|o| o.get("pattern"))
1888 .and_then(|v| v.as_str())
1889 .unwrap_or("pattern");
1890 tr(locale, MessageId::ToolExploringSearching).replace("{pattern}", pattern)
1891 }
1892 "list_files" => tr(locale, MessageId::ToolExploringListingFiles).into_owned(),
1893 _ => fallback,
1894 }
1895 }
1896
1897 fn is_mcp_tool(name: &str) -> bool {
1898 name.starts_with("mcp_")
1899 }
1900
1901 fn is_view_image_tool(name: &str) -> bool {
1902 matches!(name, "view_image" | "view_image_file" | "view_image_tool")
1903 }
1904
1905 fn is_web_search_tool(name: &str) -> bool {
1906 matches!(name, "web_search" | "search_web" | "search" | "web.run")
1907 || name.ends_with("_web_search")
1908 }
1909
1910 fn web_search_query(input: &serde_json::Value) -> String {
1911 if let Some(searches) = input.get("search_query").and_then(|v| v.as_array())
1912 && let Some(first) = searches.first()
1913 && let Some(q) = first.get("q").and_then(|v| v.as_str())
1914 {
1915 return q.to_string();
1916 }
1917
1918 input
1919 .get("query")
1920 .or_else(|| input.get("q"))
1921 .or_else(|| input.get("search"))
1922 .and_then(|v| v.as_str())
1923 .unwrap_or("Web search")
1924 .to_string()
1925 }
1926
1927 fn review_target_label(input: &serde_json::Value) -> String {
1928 let target = input
1929 .get("target")
1930 .and_then(|v| v.as_str())
1931 .unwrap_or("review")
1932 .trim();
1933 let kind = input
1934 .get("kind")
1935 .and_then(|v| v.as_str())
1936 .unwrap_or("")
1937 .trim()
1938 .to_ascii_lowercase();
1939 let staged = input
1940 .get("staged")
1941 .and_then(|v| v.as_bool())
1942 .unwrap_or(false);
1943 let target_lower = target.to_ascii_lowercase();
1944
1945 if kind == "diff"
1946 || target_lower == "diff"
1947 || target_lower == "git diff"
1948 || target_lower == "staged"
1949 || target_lower == "cached"
1950 {
1951 if staged || target_lower == "staged" || target_lower == "cached" {
1952 return "git diff --cached".to_string();
1953 }
1954 return "git diff".to_string();
1955 }
1956
1957 target.to_string()
1958 }
1959
1960 fn parse_plan_input(input: &serde_json::Value) -> PlanSnapshot {
1961 PlanSnapshot::from_tool_input(input)
1962 }
1963
1964 fn parse_file_mutation_summary(semantic_name: &str, input: &serde_json::Value) -> (String, String) {
1965 if semantic_name != "apply_patch" {
1966 let path = input
1967 .get("path")
1968 .and_then(serde_json::Value::as_str)
1969 .filter(|path| !path.trim().is_empty())
1970 .unwrap_or("<file>")
1971 .to_string();
1972 let summary = match semantic_name {
1973 "write_file" => "Writing file",
1974 "edit_file" => "Editing file",
1975 _ => "Changing file",
1976 }
1977 .to_string();
1978 return (path, summary);
1979 }
1980 let patch_text = match normalize_apply_patch_input(input) {
1981 Ok(NormalizedApplyPatchInput::Replacement {
1982 entries: changes, ..
1983 }) => {
1984 let count = changes.len();
1985 let path = changes
1986 .first()
1987 .and_then(|c| c.get("path"))
1988 .and_then(|v| v.as_str())
1989 .map(str::to_string)
1990 .unwrap_or_else(|| "<file>".to_string());
1991 let label = if count <= 1 {
1992 path
1993 } else {
1994 format!("{count} files")
1995 };
1996 let summary = format!("Changes: {count} file(s)");
1997 return (label, summary);
1998 }
1999 Ok(NormalizedApplyPatchInput::Patch(patch)) => patch,
2000 Err(_) => "",
2001 };
2002 let paths = extract_patch_paths(patch_text);
2003 let path = input
2004 .get("path")
2005 .and_then(|v| v.as_str())
2006 .map(str::to_string)
2007 .or_else(|| {
2008 if paths.len() == 1 {
2009 paths.first().cloned()
2010 } else if paths.is_empty() {
2011 None
2012 } else {
2013 Some(format!("{} files", paths.len()))
2014 }
2015 })
2016 .unwrap_or_else(|| "<file>".to_string());
2017
2018 let (adds, removes) = count_patch_changes(patch_text);
2019 let summary = if adds == 0 && removes == 0 {
2020 "Patch applied".to_string()
2021 } else {
2022 format!("Changes: +{adds} / -{removes}")
2023 };
2024 (path, summary)
2025 }
2026
2027 fn extract_patch_paths(patch: &str) -> Vec<String> {
2028 let mut paths = Vec::new();
2029 for line in patch.lines() {
2030 if let Some(rest) = line.strip_prefix("+++ ") {
2031 let raw = rest.trim();
2032 if raw == "/dev/null" || raw == "dev/null" {
2033 continue;
2034 }
2035 let raw = raw.strip_prefix("b/").unwrap_or(raw);
2036 if !paths.contains(&raw.to_string()) {
2037 paths.push(raw.to_string());
2038 }
2039 } else if let Some(rest) = line.strip_prefix("diff --git ") {
2040 let parts: Vec<&str> = rest.split_whitespace().collect();
2041 if let Some(path) = parts.get(1).or_else(|| parts.first()) {
2042 let raw = path.trim();
2043 let raw = raw
2044 .strip_prefix("b/")
2045 .or_else(|| raw.strip_prefix("a/"))
2046 .unwrap_or(raw);
2047 if !paths.contains(&raw.to_string()) {
2048 paths.push(raw.to_string());
2049 }
2050 }
2051 }
2052 }
2053 paths
2054 }
2055
2056 fn count_patch_changes(patch: &str) -> (usize, usize) {
2057 let mut adds = 0;
2058 let mut removes = 0;
2059 for line in patch.lines() {
2060 if line.starts_with("+++") || line.starts_with("---") {
2061 continue;
2062 }
2063 if line.starts_with('+') {
2064 adds += 1;
2065 } else if line.starts_with('-') {
2066 removes += 1;
2067 }
2068 }
2069 (adds, removes)
2070 }
2071
2072 fn exec_command_from_input(input: &serde_json::Value) -> Option<String> {
2073 input
2074 .get("command")
2075 .and_then(|v| v.as_str())
2076 .map(std::string::ToString::to_string)
2077 }
2078
2079 fn exec_target_from_input(input: &serde_json::Value) -> String {
2080 exec_command_from_input(input).unwrap_or_else(|| {
2081 input
2082 .get("task_id")
2083 .or_else(|| input.get("id"))
2084 .and_then(|v| v.as_str())
2085 .map(|task_id| format!("command {task_id}"))
2086 .or_else(|| {
2087 let task_ids = input
2088 .get("task_ids")
2089 .and_then(serde_json::Value::as_array)?
2090 .iter()
2091 .filter_map(serde_json::Value::as_str)
2092 .collect::<Vec<_>>();
2093 (!task_ids.is_empty()).then(|| format!("commands {}", task_ids.join(", ")))
2094 })
2095 .unwrap_or_else(|| "command".to_string())
2096 })
2097 }
2098
2099 fn exec_source_from_input(input: &serde_json::Value) -> ExecSource {
2100 match input.get("source").and_then(|v| v.as_str()) {
2101 Some(source) if source.eq_ignore_ascii_case("user") => ExecSource::User,
2102 _ => ExecSource::Assistant,
2103 }
2104 }
2105
2106 fn exec_interaction_summary(name: &str, input: &serde_json::Value) -> Option<(String, bool)> {
2107 let command = exec_target_from_input(input);
2108 let command_display = format!("\"{command}\"");
2109 let interaction_input = input
2110 .get("input")
2111 .or_else(|| input.get("stdin"))
2112 .or_else(|| input.get("data"))
2113 .and_then(|v| v.as_str());
2114
2115 let cancels_task_shell = name == "task_shell_wait"
2116 && codewhale_engine::tools::tasks::task_shell_wait_requests_cancel(input);
2117 let polls_task_shell =
2118 name == "task_shell_wait" && input.get("gate").is_none_or(serde_json::Value::is_null);
2119 let is_wait_tool = matches!(name, "exec_shell_wait" | "exec_wait") || polls_task_shell;
2120 let is_interact_tool = matches!(name, "exec_shell_interact" | "exec_interact");
2121 let is_cancel_tool = name == "exec_shell_cancel" || cancels_task_shell;
2122
2123 if is_cancel_tool {
2124 let summary = if input.get("all").and_then(serde_json::Value::as_bool) == Some(true) {
2125 "Cancelled all background commands".to_string()
2126 } else if let Some(task_id) = input
2127 .get("task_id")
2128 .or_else(|| input.get("id"))
2129 .and_then(serde_json::Value::as_str)
2130 {
2131 format!("Cancelled command {task_id}")
2132 } else {
2133 "Cancelled background command".to_string()
2134 };
2135 return Some((summary, false));
2136 }
2137
2138 if is_interact_tool || interaction_input.is_some() {
2139 let preview = interaction_input.map(summarize_interaction_input);
2140 let summary = if let Some(preview) = preview {
2141 format!("Interacted with {command_display}, sent {preview}")
2142 } else {
2143 format!("Interacted with {command_display}")
2144 };
2145 return Some((summary, false));
2146 }
2147
2148 if is_wait_tool || input.get("wait").and_then(serde_json::Value::as_bool) == Some(true) {
2149 if exec_command_from_input(input).is_none() && command != "command" {
2150 return Some((format!("Waiting for {command}"), true));
2151 }
2152 return Some((format!("Waited for {command_display}"), true));
2153 }
2154
2155 None
2156 }
2157
2158 fn summarize_interaction_input(input: &str) -> String {
2159 let mut single_line = input.replace('\r', "");
2160 single_line = single_line.replace('\n', "\\n");
2161 single_line = single_line.replace('\"', "'");
2162 let max_len = 80;
2163 if single_line.chars().count() <= max_len {
2164 return format!("\"{single_line}\"");
2165 }
2166 let mut out = String::new();
2167 for ch in single_line.chars().take(max_len.saturating_sub(3)) {
2168 out.push(ch);
2169 }
2170 out.push_str("...");
2171 format!("\"{out}\"")
2172 }
2173
2174 fn exec_is_background(input: &serde_json::Value) -> bool {
2175 input
2176 .get("background")
2177 .and_then(serde_json::Value::as_bool)
2178 .unwrap_or(false)
2179 }
2180
2181 #[cfg(test)]
2182 mod tests {
2183 use super::*;
2184 use codewhale_engine::tools::plan::StepStatus;
2185 use serde_json::json;
2186
2187 #[test]
2188 fn concurrent_runs_keep_their_own_events() {
2189 let mut app = crate::tui::test_support::test_app_with_options(
2190 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2191 );
2192 apply_workflow_ui_event(
2193 &mut app,
2194 "run-a",
2195 &json!({
2196 "type": "run_started",
2197 "workflow_goal": "first run",
2198 "at_ms": 1_000,
2199 }),
2200 );
2201 apply_workflow_ui_event(
2202 &mut app,
2203 "run-b",
2204 &json!({
2205 "type": "run_started",
2206 "workflow_goal": "second run",
2207 "at_ms": 2_000,
2208 }),
2209 );
2210 apply_workflow_ui_event(
2211 &mut app,
2212 "run-b",
2213 &json!({"type": "phase_started", "title": "Build", "at_ms": 2_100}),
2214 );
2215 let before = app.workflow_run("run-b").expect("run B").to_run_json();
2216
2217 // Both runs are rows of their own; a delayed start for A touches A.
2218 apply_workflow_ui_event(
2219 &mut app,
2220 "run-a",
2221 &json!({
2222 "type": "run_started",
2223 "workflow_goal": "delayed first run",
2224 "at_ms": 1_500,
2225 }),
2226 );
2227 // The immutable envelope says A even if a malformed embedded field
2228 // claims B. Neither this failure nor A's terminal event belongs to B.
2229 apply_workflow_ui_event(
2230 &mut app,
2231 "run-a",
2232 &json!({
2233 "type": "task_dispatch_failed",
2234 "run_id": "run-b",
2235 "label": "late task",
2236 "message": "late A failure",
2237 "at_ms": 2_200,
2238 }),
2239 );
2240 apply_workflow_ui_event(
2241 &mut app,
2242 "run-a",
2243 &json!({
2244 "type": "run_completed",
2245 "status": "failed",
2246 "error": "late A completion",
2247 "at_ms": 2_300,
2248 }),
2249 );
2250
2251 assert_eq!(app.workflow_runs.len(), 2, "two runs, two rows");
2252 assert_eq!(
2253 app.workflow_run("run-b").expect("run B").to_run_json(),
2254 before
2255 );
2256 let run_a = app.workflow_run("run-a").expect("run A");
2257 assert_eq!(
2258 run_a.lifecycle,
2259 crate::tui::widgets::workflow_panel::WorkflowPanelLifecycle::Failed
2260 );
2261 assert_eq!(run_a.dispatch_failure_count, 1);
2262 }
2263
2264 #[test]
2265 fn a_completion_replay_for_another_run_never_touches_this_one() {
2266 let mut app = crate::tui::test_support::test_app_with_options(
2267 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2268 );
2269 apply_workflow_ui_event(
2270 &mut app,
2271 "run-b",
2272 &json!({
2273 "type": "run_started",
2274 "workflow_goal": "active run",
2275 "at_ms": 2_000,
2276 }),
2277 );
2278 apply_workflow_ui_event(
2279 &mut app,
2280 "run-b",
2281 &json!({"type": "phase_started", "title": "Verify", "at_ms": 2_100}),
2282 );
2283 let before = app.workflow_run("run-b").expect("run B").to_run_json();
2284
2285 // A retained completion tail can contain run_started. The top-level
2286 // run identity keeps the whole replay on run A.
2287 apply_workflow_output_to_panel(
2288 &mut app,
2289 &json!({
2290 "run_id": "run-a",
2291 "workflow_goal": "prior run",
2292 "started_at_ms": 1_000,
2293 "completed_at_ms": 2_200,
2294 "status": "failed",
2295 "events": [
2296 {
2297 "type": "run_started",
2298 "run_id": "run-a",
2299 "workflow_goal": "prior run",
2300 "at_ms": 1_000,
2301 },
2302 {
2303 "type": "task_dispatch_failed",
2304 "run_id": "run-a",
2305 "message": "prior failure",
2306 "at_ms": 1_100,
2307 },
2308 {
2309 "type": "run_completed",
2310 "run_id": "run-a",
2311 "status": "failed",
2312 "at_ms": 2_200,
2313 }
2314 ],
2315 "dispatch_failure_count": 1,
2316 "dispatch_failures": [{
2317 "message": "prior failure",
2318 "at_ms": 1_100,
2319 }],
2320 })
2321 .to_string(),
2322 );
2323
2324 assert_eq!(
2325 app.workflow_run("run-b").expect("run B").to_run_json(),
2326 before
2327 );
2328 assert!(app.workflow_run("run-a").is_some());
2329 }
2330
2331 #[test]
2332 fn workflow_completion_replay_uses_authoritative_dispatch_failure_ledger() {
2333 let mut app = crate::tui::test_support::test_app_with_options(
2334 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2335 );
2336 let failure = json!({
2337 "type": "task_dispatch_failed",
2338 "label": "review docs",
2339 "phase": "Analyze",
2340 "message": "profile unavailable",
2341 "at_ms": 1_250,
2342 });
2343 apply_workflow_ui_event(
2344 &mut app,
2345 "run-1",
2346 &json!({
2347 "type": "run_started",
2348 "workflow_goal": "audit",
2349 "at_ms": 1_000,
2350 }),
2351 );
2352 apply_workflow_ui_event(&mut app, "run-1", &failure);
2353 assert_eq!(
2354 app.workflow_run("run-1")
2355 .expect("live run")
2356 .dispatch_failure_count,
2357 1
2358 );
2359
2360 // A long run's retained tail may no longer include run_started, so
2361 // this event is a replay of the live failure rather than a new slot.
2362 apply_workflow_output_to_panel(
2363 &mut app,
2364 &json!({
2365 "run_id": "run-1",
2366 "workflow_goal": "audit",
2367 "started_at_ms": 1_000,
2368 "events": [failure],
2369 "dispatch_failure_count": 1,
2370 "dispatch_failures": [{
2371 "label": "review docs",
2372 "phase": "Analyze",
2373 "message": "profile unavailable",
2374 "at_ms": 1_250,
2375 }],
2376 })
2377 .to_string(),
2378 );
2379
2380 let panel = app.workflow_run("run-1").expect("completed run");
2381 assert_eq!(panel.dispatch_failure_count, 1);
2382 assert_eq!(panel.dispatch_failures.len(), 1);
2383 assert_eq!(panel.failure_cancel_counts(), (1, 0));
2384 }
2385
2386 #[test]
2387 fn degraded_run_writes_one_warning_finish_line_after_its_start_card() {
2388 let mut app = crate::tui::test_support::test_app_with_options(
2389 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2390 );
2391 app.history
2392 .push(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
2393 name: "workflow".to_string(),
2394 status: ToolStatus::Running,
2395 input_summary: Some("action: run".to_string()),
2396 output: None,
2397 prompts: None,
2398 spillover_path: None,
2399 output_summary: None,
2400 is_diff: false,
2401 })));
2402
2403 apply_workflow_output_to_panel(
2404 &mut app,
2405 &json!({
2406 "run_id": "run-partial",
2407 "workflow_goal": "audit",
2408 "status": "degraded",
2409 "started_at_ms": 1_000,
2410 "completed_at_ms": 2_000,
2411 "dispatch_failure_count": 1,
2412 "dispatch_failures": [{
2413 "label": "review docs",
2414 "message": "profile unavailable",
2415 "at_ms": 1_500,
2416 }],
2417 })
2418 .to_string(),
2419 );
2420
2421 let HistoryCell::Tool(ToolCell::Generic(receipt)) = app.history.last().expect("receipt")
2422 else {
2423 panic!("the finish line is a workflow card")
2424 };
2425 assert_eq!(receipt.status, ToolStatus::Warning);
2426 let output: serde_json::Value =
2427 serde_json::from_str(receipt.output.as_deref().expect("snapshot")).expect("json");
2428 assert_eq!(output["transcript_line"], "finished");
2429 assert_eq!(output["run_id"], "run-partial");
2430 assert!(!history_cell_has_running_tool(
2431 app.history.last().expect("receipt")
2432 ));
2433
2434 // The live stream delivering the same terminal event later does not
2435 // write the line again.
2436 let cells = app.history.len();
2437 apply_workflow_ui_event(
2438 &mut app,
2439 "run-partial",
2440 &json!({"type": "run_completed", "status": "degraded", "at_ms": 2_000}),
2441 );
2442 assert_eq!(app.history.len(), cells);
2443 }
2444
2445 #[test]
2446 fn a_foreground_run_card_carries_its_own_finish_line() {
2447 let mut app = crate::tui::test_support::test_app_with_options(
2448 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2449 );
2450 let mut active = crate::tui::active_cell::ActiveCell::new();
2451 active.push_untracked(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
2452 name: "workflow".to_string(),
2453 status: ToolStatus::Running,
2454 input_summary: None,
2455 output: None,
2456 prompts: None,
2457 spillover_path: None,
2458 output_summary: None,
2459 is_diff: false,
2460 })));
2461 app.active_cell = Some(active);
2462 apply_workflow_ui_event(
2463 &mut app,
2464 "run-fg",
2465 &json!({"type": "run_started", "workflow_goal": "survey", "at_ms": 1_000}),
2466 );
2467 apply_workflow_ui_event(
2468 &mut app,
2469 "run-fg",
2470 &json!({"type": "run_completed", "status": "completed", "result_preview": "3 findings", "at_ms": 5_000}),
2471 );
2472 // The tool returns the settled record into its own card.
2473 if let Some(HistoryCell::Tool(ToolCell::Generic(card))) = app
2474 .active_cell
2475 .as_mut()
2476 .and_then(|active| active.entry_mut(0))
2477 {
2478 card.status = ToolStatus::Success;
2479 card.output = Some(
2480 json!({
2481 "run_id": "run-fg",
2482 "workflow_goal": "survey",
2483 "status": "completed",
2484 "started_at_ms": 1_000,
2485 "completed_at_ms": 5_000,
2486 "result": {"summary": "3 findings"},
2487 })
2488 .to_string(),
2489 );
2490 }
2491 app.flush_active_cell();
2492 assert_eq!(
2493 app.history.len(),
2494 1,
2495 "the card owns the finish; no second line"
2496 );
2497 let rendered = app.history[0]
2498 .lines(100)
2499 .iter()
2500 .map(|line| {
2501 line.spans
2502 .iter()
2503 .map(|s| s.content.as_ref())
2504 .collect::<String>()
2505 })
2506 .collect::<Vec<_>>()
2507 .join("\n");
2508 // The settled record replaces `started`: one row for the run.
2509 assert!(!rendered.contains("started"), "{rendered}");
2510 assert!(rendered.contains("finished"), "{rendered}");
2511 assert!(rendered.contains("3 findings"), "{rendered}");
2512 }
2513
2514 #[test]
2515 fn a_detached_finish_waits_for_its_start_card_to_leave_the_active_group() {
2516 let mut app = crate::tui::test_support::test_app_with_options(
2517 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2518 );
2519 let start_card = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
2520 name: "workflow".to_string(),
2521 status: ToolStatus::Success,
2522 input_summary: None,
2523 output: Some(
2524 json!({"run_id": "run-fast", "workflow_goal": "quick", "status": "running"})
2525 .to_string(),
2526 ),
2527 prompts: None,
2528 spillover_path: None,
2529 output_summary: None,
2530 is_diff: false,
2531 }));
2532 let mut active = crate::tui::active_cell::ActiveCell::new();
2533 active.push_untracked(start_card);
2534 app.active_cell = Some(active);
2535 for event in [
2536 json!({"type": "run_started", "workflow_goal": "quick", "at_ms": 1_000}),
2537 json!({"type": "run_completed", "status": "failed", "error": "script error, line 3", "at_ms": 1_400}),
2538 ] {
2539 apply_workflow_ui_event(&mut app, "run-fast", &event);
2540 }
2541 assert!(
2542 app.history.is_empty(),
2543 "the finish line must not jump above its start"
2544 );
2545
2546 app.flush_active_cell();
2547 // One row per run: the start card becomes the finish, in place.
2548 assert_eq!(app.history.len(), 1, "the start card is the finish line");
2549 let HistoryCell::Tool(ToolCell::Generic(finish)) = &app.history[0] else {
2550 panic!("finish line is a workflow card");
2551 };
2552 assert_eq!(finish.status, ToolStatus::Failed);
2553 let rendered = app.history[0]
2554 .lines(100)
2555 .iter()
2556 .map(|line| {
2557 line.spans
2558 .iter()
2559 .map(|s| s.content.as_ref())
2560 .collect::<String>()
2561 })
2562 .collect::<Vec<_>>()
2563 .join("\n");
2564 assert!(rendered.contains("failed"), "{rendered}");
2565 assert!(rendered.contains("quick"), "{rendered}");
2566 assert!(rendered.contains("script error, line 3"), "{rendered}");
2567 assert!(!rendered.contains("started"), "{rendered}");
2568
2569 // The live stream repeating the terminal event writes nothing more.
2570 apply_workflow_ui_event(
2571 &mut app,
2572 "run-fast",
2573 &json!({"type": "run_completed", "status": "failed", "error": "script error, line 3", "at_ms": 1_400}),
2574 );
2575 assert_eq!(app.history.len(), 1);
2576 }
2577
2578 fn workflow_card(record: serde_json::Value) -> HistoryCell {
2579 HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
2580 name: "workflow".to_string(),
2581 status: ToolStatus::Success,
2582 input_summary: None,
2583 output: Some(record.to_string()),
2584 prompts: None,
2585 spillover_path: None,
2586 output_summary: None,
2587 is_diff: false,
2588 }))
2589 }
2590
2591 fn is_finish_card(cell: &HistoryCell) -> bool {
2592 let HistoryCell::Tool(ToolCell::Generic(tool)) = cell else {
2593 return false;
2594 };
2595 tool.output
2596 .as_deref()
2597 .and_then(|out| serde_json::from_str::<serde_json::Value>(out).ok())
2598 .is_some_and(|value| value.get("transcript_line").is_some())
2599 }
2600
2601 fn settle_run(app: &mut App, run_id: &str) {
2602 for event in [
2603 json!({"type": "run_started", "workflow_goal": "quick", "at_ms": 1_000}),
2604 json!({"type": "run_completed", "status": "failed", "error": "script error", "at_ms": 1_355}),
2605 ] {
2606 apply_workflow_ui_event(app, run_id, &event);
2607 }
2608 }
2609
2610 #[test]
2611 fn a_status_poll_that_returned_the_settled_record_is_the_only_finish() {
2612 let mut app = crate::tui::test_support::test_app_with_options(
2613 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2614 );
2615 let mut active = crate::tui::active_cell::ActiveCell::new();
2616 active.push_untracked(workflow_card(
2617 json!({"run_id": "run-x", "workflow_goal": "quick", "status": "running"}),
2618 ));
2619 active.push_untracked(workflow_card(
2620 json!({"run_id": "run-x", "workflow_goal": "quick", "status": "failed"}),
2621 ));
2622 app.active_cell = Some(active);
2623 settle_run(&mut app, "run-x");
2624 app.flush_active_cell();
2625
2626 assert_eq!(app.history.len(), 2, "no extra finish appended");
2627 assert!(
2628 !app.history.iter().any(is_finish_card),
2629 "the poll already shows the finish; the start card must not repeat it"
2630 );
2631 }
2632
2633 #[test]
2634 fn the_finish_rewrites_the_start_card_not_a_later_status_poll() {
2635 let mut app = crate::tui::test_support::test_app_with_options(
2636 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2637 );
2638 let running = json!({"run_id": "run-x", "workflow_goal": "quick", "status": "running"});
2639 app.add_message(workflow_card(running.clone()));
2640 app.add_message(workflow_card(running));
2641 settle_run(&mut app, "run-x");
2642
2643 assert_eq!(app.history.len(), 2);
2644 assert!(is_finish_card(&app.history[0]), "the start card settles");
2645 assert!(!is_finish_card(&app.history[1]), "the poll is left alone");
2646 }
2647
2648 #[test]
2649 fn a_run_that_settles_after_the_conversation_moved_on_finishes_at_the_tail() {
2650 let mut app = crate::tui::test_support::test_app_with_options(
2651 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
2652 );
2653 app.add_message(workflow_card(
2654 json!({"run_id": "run-x", "workflow_goal": "quick", "status": "running"}),
2655 ));
2656 app.add_message(HistoryCell::User {
2657 content: "meanwhile, something else".to_string(),
2658 });
2659 settle_run(&mut app, "run-x");
2660
2661 assert_eq!(app.history.len(), 3, "the finish is appended");
2662 assert!(!is_finish_card(&app.history[0]));
2663 assert!(
2664 is_finish_card(&app.history[2]),
2665 "the finish sits at the tail"
2666 );
2667 }
2668
2669 #[cfg(unix)]
2670 fn hook_log_lines_eventually(path: &std::path::Path, expected: usize) -> Vec<String> {
2671 for _ in 0..100 {
2672 let lines = std::fs::read_to_string(path)
2673 .unwrap_or_default()
2674 .lines()
2675 .map(str::to_string)
2676 .collect::<Vec<_>>();
2677 if lines.len() >= expected {
2678 return lines;
2679 }
2680 std::thread::sleep(std::time::Duration::from_millis(10));
2681 }
2682 std::fs::read_to_string(path)
2683 .unwrap_or_default()
2684 .lines()
2685 .map(str::to_string)
2686 .collect()
2687 }
2688
2689 /// A UI-ignored completion is still a completion. `tool_call_after` and
2690 /// `on_error` must fire for it — exactly once — or the documented "fires
2691 /// after each tool call" silently excludes repeated `wait` and background
2692 /// results, which is the class of call an observer most wants to record.
2693 #[cfg(unix)]
2694 #[test]
2695 fn ignored_tool_calls_still_fire_after_and_error_hooks_once() {
2696 use codewhale_config::hooks::{Hook, HookEvent, HooksConfig};
2697 use codewhale_engine::hooks::HookExecutor;
2698
2699 let dir = tempfile::tempdir().expect("tempdir");
2700 let after_log = dir.path().join("after.log");
2701 let error_log = dir.path().join("error.log");
2702 let script = |path: &std::path::Path| {
2703 format!(
2704 "printf '%s\\n' \"$DEEPSEEK_TOOL_CALL_ID\" >> {}",
2705 path.display()
2706 )
2707 };
2708
2709 let mut app = crate::tui::test_support::test_app_with_options(
2710 crate::tui::test_support::test_tui_options(dir.path()),
2711 );
2712 app.workspace = dir.path().to_path_buf();
2713 app.hooks = HookExecutor::new(
2714 HooksConfig {
2715 enabled: true,
2716 hooks: vec![
2717 Hook::new(HookEvent::ToolCallAfter, &script(&after_log)).with_name("after"),
2718 Hook::new(HookEvent::OnError, &script(&error_log)).with_name("error"),
2719 ],
2720 ..HooksConfig::default()
2721 },
2722 dir.path().to_path_buf(),
2723 );
2724
2725 let id = "call_ignored_1";
2726 app.ignored_tool_calls
2727 .insert(id.to_string(), serde_json::Value::Null);
2728 let failed: Result<ToolResult, ToolError> = Ok(ToolResult::error("boom"));
2729
2730 handle_tool_call_complete(&mut app, id, "exec_shell", &failed);
2731
2732 // The presentation state still consumed the id...
2733 assert!(!app.ignored_tool_calls.contains_key(id));
2734 // ...and both observers saw the call, once each.
2735 let after = hook_log_lines_eventually(&after_log, 1);
2736 let errors = hook_log_lines_eventually(&error_log, 1);
2737 assert_eq!(after, vec![id]);
2738 assert_eq!(errors, vec![id]);
2739
2740 // A successful ignored completion fires `tool_call_after` only.
2741 let second = "call_ignored_2";
2742 app.ignored_tool_calls
2743 .insert(second.to_string(), serde_json::Value::Null);
2744 handle_tool_call_complete(
2745 &mut app,
2746 second,
2747 "exec_shell",
2748 &Ok(ToolResult::success("ok")),
2749 );
2750 let after = hook_log_lines_eventually(&after_log, 2);
2751 let errors = hook_log_lines_eventually(&error_log, 1);
2752 assert_eq!(after, vec![id, second]);
2753 assert_eq!(errors, vec![id]);
2754 }
2755
2756 /// #6582: hooks see a `bash` command's real exit code and status, for a
2757 /// failing command as well as a passing one. A nonzero exit is a
2758 /// `ToolError`. A foreground wait that expires is not: the command moves
2759 /// to the background and stays running, so `on_error` does not fire for it.
2760 #[cfg(unix)]
2761 #[test]
2762 fn bash_completion_hooks_get_exit_code_and_status_for_failures() {
2763 use codewhale_config::hooks::{Hook, HookEvent, HooksConfig};
2764 use codewhale_engine::hooks::HookExecutor;
2765 use codewhale_engine::tools::spec::{ToolContext, ToolSpec};
2766
2767 let dir = tempfile::tempdir().expect("tempdir");
2768 let after_log = dir.path().join("after.log");
2769 let error_log = dir.path().join("error.log");
2770 let script = |path: &std::path::Path| {
2771 format!(
2772 "printf '%s %s %s %s\\n' \"$DEEPSEEK_TOOL_CALL_ID\" \"${{DEEPSEEK_TOOL_EXIT_CODE-unset}}\" \"${{DEEPSEEK_TOOL_STATUS-unset}}\" \"$DEEPSEEK_TOOL_SUCCESS\" >> {}",
2773 path.display()
2774 )
2775 };
2776 let mut app = crate::tui::test_support::test_app_with_options(
2777 crate::tui::test_support::test_tui_options(dir.path()),
2778 );
2779 app.workspace = dir.path().to_path_buf();
2780 app.hooks = HookExecutor::new(
2781 HooksConfig {
2782 enabled: true,
2783 hooks: vec![
2784 Hook::new(HookEvent::ToolCallAfter, &script(&after_log)),
2785 Hook::new(HookEvent::OnError, &script(&error_log)),
2786 ],
2787 ..HooksConfig::default()
2788 },
2789 dir.path().to_path_buf(),
2790 );
2791
2792 let runtime = tokio::runtime::Runtime::new().expect("runtime");
2793 let context = ToolContext::new(dir.path());
2794 let cases = [
2795 ("call-exit-0", json!({"command": "exit 0"})),
2796 ("call-exit-1", json!({"command": "exit 1"})),
2797 (
2798 "call-exit-127",
2799 json!({"command": "codewhale-no-such-command-6582"}),
2800 ),
2801 (
2802 "call-timeout",
2803 json!({"command": "sleep 5", "timeout": 0.2}),
2804 ),
2805 ];
2806 for (id, input) in cases {
2807 let result = runtime.block_on(
2808 codewhale_engine::tools::shell::LowercaseBashTool.execute(input, &context),
2809 );
2810 handle_tool_call_complete(&mut app, id, "bash", &result);
2811 }
2812
2813 let mut after = hook_log_lines_eventually(&after_log, 4);
2814 let mut errors = hook_log_lines_eventually(&error_log, 2);
2815 after.sort();
2816 errors.sort();
2817 assert_eq!(
2818 after,
2819 vec![
2820 "call-exit-0 0 completed true",
2821 "call-exit-1 1 failed false",
2822 "call-exit-127 127 failed false",
2823 "call-timeout unset running true",
2824 ]
2825 );
2826 assert_eq!(
2827 errors,
2828 vec![
2829 "call-exit-1 1 failed false",
2830 "call-exit-127 127 failed false",
2831 ]
2832 );
2833 }
2834
2835 #[test]
2836 fn adaptive_evidence_late_foreign_and_duplicate_completions_are_ignored() {
2837 let result = Ok(ToolResult::success("bounded").with_metadata(json!({
2838 "artifact_session_id": "session-a",
2839 "artifact_id": "art_call-a"
2840 })));
2841 assert!(evidence_completion_identity_should_be_ignored(
2842 Some("session-b"),
2843 std::iter::empty(),
2844 "call-a",
2845 &result,
2846 ));
2847 assert!(evidence_completion_identity_should_be_ignored(
2848 Some("session-a"),
2849 [("art_call-a", "call-a")],
2850 "call-a",
2851 &result,
2852 ));
2853 assert!(!evidence_completion_identity_should_be_ignored(
2854 Some("session-a"),
2855 std::iter::empty(),
2856 "call-a",
2857 &result,
2858 ));
2859 }
2860
2861 #[test]
2862 fn web_search_presentation_reads_source_degradation_and_citation_count() {
2863 let presentation = web_search_presentation(
2864 &json!({
2865 "source": "provider-native/xai/grok-4.5",
2866 "results": [
2867 {"ref_id": "web_a", "url": "https://example.com/a"},
2868 {"ref_id": "web_b", "url": "https://example.com/b"}
2869 ],
2870 "receipt": {
2871 "degraded": [
2872 {"kind": "backend_unavailable", "backend": "provider_native"},
2873 {"kind": "backend_fallback", "from": "provider_native", "to": "tavily"}
2874 ]
2875 }
2876 })
2877 .to_string(),
2878 );
2879
2880 assert_eq!(
2881 presentation.source.as_deref(),
2882 Some("provider-native/xai/grok-4.5")
2883 );
2884 assert_eq!(
2885 presentation.degraded.as_deref(),
2886 Some("provider_native unavailable; provider_native -> tavily")
2887 );
2888 assert_eq!(presentation.ref_count, 2);
2889 }
2890
2891 #[test]
2892 fn web_run_presentation_reads_nested_search_receipts() {
2893 let presentation = web_search_presentation(
2894 &json!({
2895 "search_query": [{
2896 "source": "duckduckgo",
2897 "results": [{"ref_id": "web_a"}],
2898 "receipt": {
2899 "degraded": [{"kind": "knob_ignored", "knob": "recency"}]
2900 }
2901 }]
2902 })
2903 .to_string(),
2904 );
2905
2906 assert_eq!(presentation.source.as_deref(), Some("duckduckgo"));
2907 assert_eq!(presentation.degraded.as_deref(), Some("recency ignored"));
2908 assert_eq!(presentation.ref_count, 1);
2909 }
2910
2911 #[test]
2912 fn parse_plan_input_accepts_legacy_payload() {
2913 let snapshot = parse_plan_input(&json!({
2914 "explanation": "Legacy explanation",
2915 "plan": [
2916 { "step": "inspect", "status": "completed" },
2917 { "step": "patch", "status": "in_progress" }
2918 ]
2919 }));
2920
2921 assert_eq!(snapshot.explanation.as_deref(), Some("Legacy explanation"));
2922 assert_eq!(snapshot.items.len(), 2);
2923 assert_eq!(snapshot.items[0].status, StepStatus::Completed);
2924 assert_eq!(snapshot.items[1].status, StepStatus::InProgress);
2925 }
2926
2927 #[test]
2928 fn parse_plan_input_extracts_rich_artifact_fields() {
2929 let snapshot = parse_plan_input(&json!({
2930 "title": " PlanArtifact ",
2931 "objective": "Make Plan mode reviewable",
2932 "context_summary": "Grounded in issue #2691",
2933 "sources_used": [" gh issue view 2691 ", ""],
2934 "critical_files": ["crates/engine/src/tools/plan.rs"],
2935 "constraints": ["No secrets"],
2936 "recommended_approach": "Enrich update_plan",
2937 "verification_plan": "Run focused tests",
2938 "risks_and_unknowns": "Replay may drift",
2939 "handoff_packet": "Continue with session replay",
2940 "plan": [
2941 { "step": " ", "status": "completed" },
2942 { "step": "render all fields", "status": "weird" }
2943 ]
2944 }));
2945
2946 assert_eq!(snapshot.title.as_deref(), Some("PlanArtifact"));
2947 assert_eq!(snapshot.sources_used, vec!["gh issue view 2691"]);
2948 assert_eq!(
2949 snapshot.critical_files,
2950 vec!["crates/engine/src/tools/plan.rs"]
2951 );
2952 assert_eq!(snapshot.constraints, vec!["No secrets"]);
2953 assert_eq!(
2954 snapshot.verification_plan.as_deref(),
2955 Some("Run focused tests")
2956 );
2957 assert_eq!(snapshot.items.len(), 1);
2958 assert_eq!(snapshot.items[0].step, "render all fields");
2959 assert_eq!(snapshot.items[0].status, StepStatus::Pending);
2960 }
2961
2962 #[test]
2963 fn parse_patch_summary_treats_replace_and_legacy_changes_equally() {
2964 let replacements = json!([{
2965 "path": "src/lib.rs",
2966 "content": "fn replacement() {}\n"
2967 }]);
2968
2969 let canonical =
2970 parse_file_mutation_summary("apply_patch", &json!({"replace": replacements.clone()}));
2971 let legacy = parse_file_mutation_summary("apply_patch", &json!({"changes": replacements}));
2972
2973 assert_eq!(canonical, legacy);
2974 }
2975
2976 // ── #3031: "(no output)" placeholder must not defeat compact rendering ─
2977
2978 #[test]
2979 fn visible_tool_output_maps_no_output_placeholder_to_none() {
2980 assert_eq!(visible_tool_output("(no output)"), None);
2981 assert_eq!(visible_tool_output(" (no output)\n"), None);
2982 }
2983
2984 #[test]
2985 fn visible_tool_output_preserves_real_content() {
2986 assert_eq!(
2987 visible_tool_output("compiled 3 crates").as_deref(),
2988 Some("compiled 3 crates")
2989 );
2990 // Output that merely CONTAINS the placeholder is real output.
2991 assert_eq!(
2992 visible_tool_output("step 1: (no output) — continuing").as_deref(),
2993 Some("step 1: (no output) — continuing")
2994 );
2995 assert_eq!(visible_tool_output("").as_deref(), Some(""));
2996 }
2997
2998 #[test]
2999 fn exec_cell_without_output_suppresses_placeholder_in_live_mode() {
3000 use crate::tui::history::{ExecCell, ExecSource, ToolCell, ToolStatus};
3001
3002 let cell = ToolCell::Exec(ExecCell {
3003 command: "true".to_string(),
3004 status: ToolStatus::Success,
3005 output: None,
3006 live_output: None,
3007 shell_task_id: None,
3008 owner_agent_id: None,
3009 owner_agent_name: None,
3010 started_at: None,
3011 duration_ms: Some(120),
3012 stale_elapsed_since_output_ms: None,
3013 waiting: None,
3014 source: ExecSource::Assistant,
3015 description: None,
3016 interaction: None,
3017 output_summary: None,
3018 });
3019
3020 let live: String = cell
3021 .lines(80)
3022 .iter()
3023 .flat_map(|line| line.spans.iter().map(|s| s.content.to_string()))
3024 .collect();
3025 assert!(
3026 !live.contains("(no output)"),
3027 "Live mode must suppress the placeholder: {live:?}"
3028 );
3029
3030 let transcript: String = cell
3031 .transcript_lines(80)
3032 .iter()
3033 .flat_map(|line| line.spans.iter().map(|s| s.content.to_string()))
3034 .collect();
3035 assert!(
3036 transcript.contains("(no output)"),
3037 "Transcript mode still records the placeholder: {transcript:?}"
3038 );
3039 }
3040
3041 // === #5472 finding 3: retained tool outputs are bounded ===
3042
3043 #[test]
3044 fn tool_detail_output_is_capped_and_says_what_it_dropped() {
3045 let small = "short output".to_string();
3046 assert_eq!(super::bounded_tool_detail_output(small.clone()), small);
3047
3048 let huge = "x".repeat(super::TOOL_DETAIL_OUTPUT_MAX_BYTES * 3);
3049 let bounded = super::bounded_tool_detail_output(huge);
3050 assert!(
3051 bounded.len() < super::TOOL_DETAIL_OUTPUT_MAX_BYTES + 200,
3052 "retained {} bytes",
3053 bounded.len()
3054 );
3055 assert!(bounded.contains("the transcript keeps an excerpt"));
3056 }
3057
3058 #[test]
3059 fn tool_detail_cap_never_splits_a_character() {
3060 // Every char is 3 bytes, so a byte-exact cut lands mid-character.
3061 let wide = "宽".repeat(super::TOOL_DETAIL_OUTPUT_MAX_BYTES);
3062 let bounded = super::bounded_tool_detail_output(wide);
3063 assert!(bounded.starts_with('宽'));
3064 assert!(bounded.contains("excerpt"));
3065 }
3066
3067 #[test]
3068 fn oldest_tool_outputs_are_released_once_the_budget_is_exceeded() {
3069 let mut app = crate::tui::app::App::new(
3070 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
3071 &codewhale_runtime::config::Config::default(),
3072 );
3073 // 200 records x 64 KiB = 12.8 MiB, well past the 8 MiB budget.
3074 let record_count = 200usize;
3075 for index in 0..record_count {
3076 let tool_id = format!("tool-{index}");
3077 super::handle_tool_call_started(
3078 &mut app,
3079 &tool_id,
3080 "read_file",
3081 &serde_json::json!({ "path": format!("file-{index}.txt") }),
3082 );
3083 app.active_tool_details.insert(
3084 tool_id.clone(),
3085 ToolDetailRecord {
3086 tool_id,
3087 tool_name: "read_file".to_string(),
3088 input: serde_json::Value::Null,
3089 output: Some("y".repeat(super::TOOL_DETAIL_OUTPUT_MAX_BYTES)),
3090 },
3091 );
3092 }
3093 app.flush_active_cell();
3094
3095 let retained: usize = app
3096 .tool_details_by_cell
3097 .values()
3098 .map(|detail| detail.output.as_ref().map_or(0, String::len))
3099 .sum();
3100 assert!(
3101 retained <= super::TOOL_DETAIL_TOTAL_BUDGET_BYTES,
3102 "retained {retained} bytes over the {} budget",
3103 super::TOOL_DETAIL_TOTAL_BUDGET_BYTES
3104 );
3105 assert_eq!(
3106 app.tool_details_by_cell.len(),
3107 record_count,
3108 "records stay listed; only their outputs are released"
3109 );
3110 assert!(
3111 app.tool_details_by_cell[&(record_count - 1)]
3112 .output
3113 .is_some(),
3114 "the newest output must survive — it is the one the user can still expand"
3115 );
3116 assert!(
3117 app.tool_details_by_cell[&0].output.is_none(),
3118 "the oldest output is the first to go"
3119 );
3120 }
3121
3122 #[test]
3123 fn execute_tools_nested_span_updates_running_card_and_bumps_revision() {
3124 let mut app = crate::tui::app::App::new(
3125 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
3126 &codewhale_runtime::config::Config::default(),
3127 );
3128 super::handle_tool_call_started(
3129 &mut app,
3130 "cm-1",
3131 "execute_tools",
3132 &serde_json::json!({ "code": "await tools.call('grep_files', {})" }),
3133 );
3134 super::handle_tool_execution_started(&mut app, "cm-1");
3135 let rev0 = app.active_cell_revision;
3136 super::record_execute_tools_nested_call(&mut app, "cm-1", "execute_tools");
3137 assert_eq!(app.active_cell_revision, rev0);
3138
3139 super::record_execute_tools_nested_call(&mut app, "cm-1.1", "grep_files");
3140 assert_ne!(app.active_cell_revision, rev0);
3141 let idx = app.tool_cells["cm-1"];
3142 let Some(HistoryCell::Tool(ToolCell::Generic(cell))) = app.cell_at_virtual_index(idx)
3143 else {
3144 panic!("expected GenericToolCell for execute_tools");
3145 };
3146 assert_eq!(cell.input_summary.as_deref(), Some("1 call · grep_files"));
3147
3148 let rev1 = app.active_cell_revision;
3149 super::record_execute_tools_nested_call(&mut app, "cm-1.2", "linear.list_issues");
3150 assert_ne!(app.active_cell_revision, rev1);
3151 let Some(HistoryCell::Tool(ToolCell::Generic(cell))) = app.cell_at_virtual_index(idx)
3152 else {
3153 panic!("expected GenericToolCell for execute_tools");
3154 };
3155 assert_eq!(
3156 cell.input_summary.as_deref(),
3157 Some("2 calls · linear.list_issues")
3158 );
3159
3160 super::handle_tool_call_complete(
3161 &mut app,
3162 "cm-1",
3163 "execute_tools",
3164 &Ok(ToolResult::success("{}")),
3165 );
3166 let rev2 = app.active_cell_revision;
3167 super::record_execute_tools_nested_call(&mut app, "cm-1.3", "late_call");
3168 assert_eq!(app.active_cell_revision, rev2);
3169 }
3170
3171 #[test]
3172 fn announced_tools_start_queued_and_flip_to_running_on_execution_started() {
3173 let mut app = crate::tui::app::App::new(
3174 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
3175 &codewhale_runtime::config::Config::default(),
3176 );
3177 super::handle_tool_call_started(
3178 &mut app,
3179 "sh-1",
3180 "exec_shell",
3181 &serde_json::json!({ "command": "echo first" }),
3182 );
3183 super::handle_tool_call_started(
3184 &mut app,
3185 "sh-2",
3186 "exec_shell",
3187 &serde_json::json!({ "command": "echo second" }),
3188 );
3189 super::handle_tool_call_started(
3190 &mut app,
3191 "rd-1",
3192 "read_file",
3193 &serde_json::json!({ "path": "Cargo.toml" }),
3194 );
3195 super::handle_tool_call_started(
3196 &mut app,
3197 "gn-1",
3198 "custom_tool",
3199 &serde_json::json!({ "k": "v" }),
3200 );
3201
3202 let sh1_idx = app.tool_cells["sh-1"];
3203 let sh2_idx = app.tool_cells["sh-2"];
3204 let gn1_idx = app.tool_cells["gn-1"];
3205 let (rd1_idx, rd1_entry) = app.exploring_entries["rd-1"];
3206
3207 let Some(HistoryCell::Tool(ToolCell::Exec(exec1))) = app.cell_at_virtual_index(sh1_idx)
3208 else {
3209 panic!("expected ExecCell");
3210 };
3211 assert_eq!(exec1.status, ToolStatus::Queued);
3212 assert_eq!(exec1.waiting, None);
3213 assert!(exec1.started_at.is_none());
3214
3215 super::hold_exec_cards_for_approval(&mut app, "sh-1");
3216 let Some(HistoryCell::Tool(ToolCell::Exec(exec1))) = app.cell_at_virtual_index(sh1_idx)
3217 else {
3218 panic!("expected ExecCell");
3219 };
3220 assert_eq!(exec1.waiting, Some(ExecWait::Approval));
3221 assert_eq!(exec1.status, ToolStatus::Queued);
3222 assert!(exec1.started_at.is_none());
3223
3224 let Some(HistoryCell::Tool(ToolCell::Exec(exec2))) = app.cell_at_virtual_index(sh2_idx)
3225 else {
3226 panic!("expected ExecCell");
3227 };
3228 assert_eq!(exec2.waiting, None);
3229 assert_eq!(exec2.status, ToolStatus::Queued);
3230
3231 super::clear_exec_card_approval_hold(&mut app, "sh-1");
3232 let Some(HistoryCell::Tool(ToolCell::Exec(exec1))) = app.cell_at_virtual_index(sh1_idx)
3233 else {
3234 panic!("expected ExecCell");
3235 };
3236 assert_eq!(exec1.waiting, None);
3237 assert_eq!(exec1.status, ToolStatus::Queued);
3238 assert!(exec1.started_at.is_none());
3239
3240 super::handle_tool_execution_started(&mut app, "sh-1");
3241 super::handle_tool_execution_started(&mut app, "rd-1");
3242 super::handle_tool_execution_started(&mut app, "gn-1");
3243
3244 let Some(HistoryCell::Tool(ToolCell::Exec(exec1))) = app.cell_at_virtual_index(sh1_idx)
3245 else {
3246 panic!("expected ExecCell");
3247 };
3248 assert_eq!(exec1.status, ToolStatus::Running);
3249 assert_eq!(exec1.waiting, None);
3250 assert!(exec1.started_at.is_some());
3251
3252 let Some(HistoryCell::Tool(ToolCell::Exploring(explore))) =
3253 app.cell_at_virtual_index(rd1_idx)
3254 else {
3255 panic!("expected ExploringCell");
3256 };
3257 assert_eq!(explore.entries[rd1_entry].status, ToolStatus::Running);
3258
3259 let Some(HistoryCell::Tool(ToolCell::Generic(generic))) =
3260 app.cell_at_virtual_index(gn1_idx)
3261 else {
3262 panic!("expected GenericToolCell");
3263 };
3264 assert_eq!(generic.status, ToolStatus::Running);
3265 }
3266 }
3267
3267 lines RUST