返回 CodeWhale
subagent_routing.rs
根目录 / crates / tui / src / tui / subagent_routing.rs
1 //! Sub-agent and background-task routing helpers for the TUI loop.
2
3 use std::time::{Duration, Instant};
4
5 use crate::tui::app::{
6 AgentCurrentActivity, AgentCurrentActivityStatus, AgentProgressMeta, AgentRecentAction, App,
7 MAX_AGENT_RECENT_ACTIONS, TaskPanelEntry, TaskPanelEntryKind, bound_agent_activity_text,
8 };
9 use crate::tui::history::HistoryCell;
10 use crate::tui::history::SubAgentCell;
11 use crate::tui::pager::PagerView;
12 use crate::tui::tool_routing::refreshes_workspace_context_on_completion;
13 use crate::tui::widgets::agent_card::{
14 AgentLifecycle, DelegateCard, FanoutCard, apply_to_delegate, apply_to_fanout,
15 };
16 use crate::tui::workspace_context;
17 use codewhale_app_server::exec_agent::summarize_tool_output;
18 use codewhale_config::AppMode;
19 use codewhale_engine::agent_roster::{AgentRosterRow, RosterState, one_line, result_headline};
20 use codewhale_engine::core::events::AgentProgressEventMeta;
21 use codewhale_engine::task_manager::{TaskRecord, TaskStatus, TaskSummary};
22 use codewhale_engine::tools::subagent::{
23 AgentRunUsage, AgentWorkerStatus, MailboxMessage, SubAgentResult, SubAgentStatus,
24 subagent_progress_tool_display_name,
25 };
26
27 /// Keep settled cards visible briefly, then archive them from the compact
28 /// live projection. Their transcript card and persisted agent record remain
29 /// reachable through the Agents register.
30 const SUBAGENT_TERMINAL_CARD_TTL: Duration = Duration::from_secs(45);
31 const SUBAGENT_TERMINAL_CARD_MAX_RETAINED: usize = 24;
32
33 pub(super) fn running_agent_count(app: &App) -> usize {
34 let mut ids: std::collections::HashSet<&str> =
35 app.agent_progress.keys().map(String::as_str).collect();
36 for agent in app
37 .subagent_cache
38 .iter()
39 .filter(|agent| matches!(agent.status, SubAgentStatus::Running))
40 {
41 ids.insert(agent.agent_id.as_str());
42 }
43 ids.len()
44 }
45
46 /// Describe detached workers that deliberately survive a parent-turn stop.
47 ///
48 /// `agent` starts are detached from the turn cancellation token, so a plain
49 /// "Request cancelled" receipt is incomplete whenever live workers remain.
50 /// Use stable UI labels where available and raw ids as a lossless fallback;
51 /// sorting keeps the receipt deterministic across HashMap iteration order.
52 pub(super) fn parent_stop_status(app: &App, base: &str) -> String {
53 let mut ids = std::collections::BTreeSet::new();
54 ids.extend(app.agent_progress.keys().cloned());
55 ids.extend(
56 app.subagent_cache
57 .iter()
58 .filter(|agent| matches!(agent.status, SubAgentStatus::Running))
59 .map(|agent| agent.agent_id.clone()),
60 );
61 if ids.is_empty() {
62 return base.to_string();
63 }
64
65 let labels = ids
66 .into_iter()
67 .map(|id| {
68 app.agent_label_map
69 .get(&id)
70 .filter(|label| !label.trim().is_empty())
71 .cloned()
72 .unwrap_or(id)
73 })
74 .collect::<Vec<_>>();
75 format!(
76 "{base}; detached workers continue (none canceled): {}",
77 labels.join(", ")
78 )
79 }
80
81 pub(super) fn active_fanout_counts(app: &App) -> Option<(usize, usize)> {
82 // Read running count from the canonical slot states on the active
83 // FanoutCard, if one exists. Used by `rlm` and any future multi-child
84 // dispatch the parent agent makes via repeated `agent`.
85 if let Some(idx) = app.last_fanout_card_index
86 && let Some(HistoryCell::SubAgent(SubAgentCell::Fanout(card))) = app.history.get(idx)
87 {
88 let running = card
89 .workers
90 .iter()
91 .filter(|slot| matches!(slot.status, AgentLifecycle::Running))
92 .count();
93 return Some((running, card.worker_count()));
94 }
95 None
96 }
97
98 /// True when this child settled by being *parked* at the parent's turn end
99 /// rather than by asking anyone anything (#5906).
100 ///
101 /// The runtime parks a turn-owned child with a `needs_input` note that reads
102 /// like a question ("Resume this parked child with ..."), so every surface
103 /// that keys off `needs_input` used to render a parked husk with the same
104 /// "waiting for input" label as a child a user can actually answer. The
105 /// checkpoint records which of the two it is; this is the one place the UI
106 /// asks, so no surface has to sniff the reason string.
107 pub(crate) fn subagent_is_parked(agent: &SubAgentResult) -> bool {
108 agent
109 .checkpoint
110 .as_ref()
111 .is_some_and(|checkpoint| checkpoint.parked_at_turn_end)
112 }
113
114 /// The one-line recovery a parked row shows instead of a pending question:
115 /// nobody will answer it, so it names the two ways out that actually exist.
116 pub(crate) fn parked_recovery_detail(app: &App) -> String {
117 codewhale_localization::tr(
118 app.ui_locale,
119 codewhale_localization::MessageId::AgentStatusParkedRecovery,
120 )
121 .into_owned()
122 }
123
124 pub(super) fn reconcile_subagent_activity_state(app: &mut App) {
125 reconcile_subagent_activity_state_at(app, Instant::now());
126 }
127
128 pub(super) fn apply_subagent_terminal_projection(
129 app: &mut App,
130 agent_id: &str,
131 status: SubAgentStatus,
132 result: Option<String>,
133 ) -> bool {
134 app.agent_progress.remove(agent_id);
135
136 let worker_status = worker_status_for_terminal_projection(&status);
137 let safe_result = result.map(|result| bound_agent_activity_text(&result));
138 let meta = app
139 .agent_progress_meta
140 .entry(agent_id.to_string())
141 .or_default();
142 // A parked child projects as `Interrupted` here. Interrupted-over-Waiting
143 // and interrupted-over-Parked are both "the settled state the surface
144 // already established, restated" — do not downgrade either (#5906).
145 let sticky = meta
146 .current_activity
147 .as_ref()
148 .map(|activity| activity.status)
149 .filter(|status| {
150 matches!(
151 status,
152 AgentCurrentActivityStatus::Waiting | AgentCurrentActivityStatus::Parked
153 )
154 });
155 let activity_status = match sticky {
156 Some(status) if worker_status == AgentWorkerStatus::Interrupted => status,
157 _ => worker_status.into(),
158 };
159 let step = meta
160 .current_activity
161 .as_ref()
162 .and_then(|activity| activity.step);
163 meta.current_activity = Some(AgentCurrentActivity::bounded(
164 activity_status,
165 safe_result.clone(),
166 None,
167 step,
168 ));
169 meta.current_tool = None;
170
171 let Some(agent) = app
172 .subagent_cache
173 .iter_mut()
174 .find(|agent| agent.agent_id == agent_id)
175 else {
176 reconcile_subagent_activity_state(app);
177 return false;
178 };
179
180 agent.worker_status = Some(worker_status);
181 agent.status = status;
182 if let Some(result) = safe_result {
183 agent.result = Some(result);
184 }
185 reconcile_subagent_activity_state(app);
186 true
187 }
188
189 pub(crate) fn worker_status_for_terminal_projection(status: &SubAgentStatus) -> AgentWorkerStatus {
190 match status {
191 SubAgentStatus::Running => AgentWorkerStatus::Running,
192 SubAgentStatus::Completed => AgentWorkerStatus::Completed,
193 SubAgentStatus::Interrupted(_) => AgentWorkerStatus::Interrupted,
194 SubAgentStatus::Failed(_) | SubAgentStatus::BudgetExhausted => AgentWorkerStatus::Failed,
195 SubAgentStatus::Cancelled => AgentWorkerStatus::Cancelled,
196 }
197 }
198
199 fn ensure_roster_scope(app: &mut App, owner_session_id: &str) -> bool {
200 if owner_session_id.is_empty() || app.current_session_id.as_deref() != Some(owner_session_id) {
201 return false;
202 }
203 if app.agent_roster_session_id.as_deref() != Some(owner_session_id) {
204 app.agent_roster.clear();
205 app.agent_roster_session_id = Some(owner_session_id.to_string());
206 }
207 true
208 }
209
210 fn roster_display_name(app: &App, agent_id: &str, candidate: Option<&str>) -> String {
211 candidate
212 .map(str::trim)
213 .filter(|name| !name.is_empty() && *name != agent_id)
214 .map(str::to_string)
215 .or_else(|| {
216 app.agent_progress_meta
217 .get(agent_id)
218 .and_then(|meta| meta.display_name.as_deref())
219 .map(str::trim)
220 .filter(|name| !name.is_empty() && *name != agent_id)
221 .map(str::to_string)
222 })
223 .or_else(|| {
224 app.agent_label_map
225 .get(agent_id)
226 .filter(|label| !label.trim().is_empty() && *label != agent_id)
227 .cloned()
228 })
229 .unwrap_or_else(|| "agent".to_string())
230 }
231
232 fn sanitized_roster_model(model: &str) -> String {
233 let clean = codewhale_runtime::safe_label::sanitize_persisted_route_label(model);
234 let trimmed = clean.trim();
235 if trimmed.is_empty() {
236 String::new()
237 } else {
238 bound_agent_activity_text(trimmed)
239 }
240 }
241
242 pub(crate) fn upsert_roster_spawn(
243 app: &mut App,
244 owner_session_id: &str,
245 agent_id: &str,
246 prompt_summary: &str,
247 worker_status: Option<AgentWorkerStatus>,
248 parent_run_id: Option<&str>,
249 model: &str,
250 display_name: Option<&str>,
251 ) {
252 if !ensure_roster_scope(app, owner_session_id) {
253 return;
254 }
255 let status = worker_status.unwrap_or(AgentWorkerStatus::Running);
256 let state = RosterState::from_worker(status);
257 let name = roster_display_name(app, agent_id, display_name);
258 let model = sanitized_roster_model(model);
259 let activity = (!prompt_summary.trim().is_empty()).then(|| one_line(prompt_summary));
260 if let Some(existing) = app
261 .agent_roster
262 .iter_mut()
263 .find(|row| row.worker_id == agent_id)
264 {
265 if existing.display_name.trim().is_empty()
266 || existing.display_name == "agent"
267 || App::is_agent_counter_placeholder(&existing.display_name)
268 {
269 existing.display_name = name;
270 }
271 if !model.is_empty() {
272 existing.model = model;
273 }
274 if existing.parent_run_id.is_none() {
275 existing.parent_run_id = parent_run_id.map(str::to_string);
276 }
277 if !existing.state.is_terminal() && existing.state != RosterState::Parked {
278 existing.status = status;
279 existing.state = state;
280 if existing.activity.is_none() {
281 existing.activity = activity;
282 }
283 }
284 return;
285 }
286 app.agent_roster.push(AgentRosterRow {
287 worker_id: agent_id.to_string(),
288 display_name: name,
289 model,
290 state,
291 status,
292 activity,
293 outcome: None,
294 millis: None,
295 input_tokens: None,
296 output_tokens: None,
297 cost_microusd: None,
298 steps_taken: 0,
299 parent_run_id: parent_run_id.map(str::to_string),
300 run_id: agent_id.to_string(),
301 });
302 }
303
304 pub(crate) fn upsert_roster_progress(
305 app: &mut App,
306 owner_session_id: &str,
307 agent_id: &str,
308 display: &str,
309 activity: &AgentProgressEventMeta,
310 parent_run_id: Option<&str>,
311 ) {
312 if !ensure_roster_scope(app, owner_session_id) {
313 return;
314 }
315 let status = activity.worker_status;
316 let state = RosterState::from_worker(status);
317 let line = (!display.trim().is_empty()).then(|| one_line(display));
318 let name = roster_display_name(app, agent_id, None);
319 let model = app
320 .agent_progress_meta
321 .get(agent_id)
322 .and_then(|meta| meta.resolved_model.clone())
323 .unwrap_or_default();
324 if let Some(existing) = app
325 .agent_roster
326 .iter_mut()
327 .find(|row| row.worker_id == agent_id)
328 {
329 if existing.parent_run_id.is_none() {
330 existing.parent_run_id = parent_run_id.map(str::to_string);
331 }
332 if (existing.model.is_empty() || existing.model == "unknown") && !model.is_empty() {
333 existing.model = model;
334 }
335 if !existing.state.is_terminal() && existing.state != RosterState::Parked {
336 existing.status = status;
337 existing.state = state;
338 if line.is_some() {
339 existing.activity = line;
340 }
341 if let Some(step) = activity.step {
342 existing.steps_taken = existing.steps_taken.max(step);
343 }
344 }
345 return;
346 }
347 app.agent_roster.push(AgentRosterRow {
348 worker_id: agent_id.to_string(),
349 display_name: name,
350 model,
351 state,
352 status,
353 activity: line,
354 outcome: None,
355 millis: None,
356 input_tokens: None,
357 output_tokens: None,
358 cost_microusd: None,
359 steps_taken: activity.step.unwrap_or(0),
360 parent_run_id: parent_run_id.map(str::to_string),
361 run_id: agent_id.to_string(),
362 });
363 }
364
365 #[allow(clippy::too_many_arguments)]
366 pub(crate) fn upsert_roster_terminal(
367 app: &mut App,
368 owner_session_id: &str,
369 agent_id: &str,
370 outcome: Option<&SubAgentStatus>,
371 result: &str,
372 parent_run_id: Option<&str>,
373 usage: Option<&AgentRunUsage>,
374 display_name: Option<&str>,
375 elapsed_ms: Option<u64>,
376 ) {
377 if !ensure_roster_scope(app, owner_session_id) {
378 return;
379 }
380 let parked = app
381 .agent_progress_meta
382 .get(agent_id)
383 .and_then(|meta| meta.current_activity.as_ref())
384 .is_some_and(|activity| activity.status == AgentCurrentActivityStatus::Parked)
385 || app
386 .subagent_cache
387 .iter()
388 .find(|agent| agent.agent_id == agent_id)
389 .is_some_and(subagent_is_parked);
390 let worker_status = outcome
391 .map(worker_status_for_terminal_projection)
392 .unwrap_or(AgentWorkerStatus::Interrupted);
393 let state = if parked {
394 RosterState::Parked
395 } else {
396 RosterState::from_worker(worker_status)
397 };
398 let bounded_result = bound_agent_activity_text(result);
399 let activity = result_headline(&bounded_result)
400 .map(|headline| one_line(&headline))
401 .filter(|line| !line.is_empty());
402 let outcome_text = (!bounded_result.trim().is_empty()).then_some(bounded_result);
403 let name = roster_display_name(app, agent_id, display_name);
404 let model = app
405 .agent_progress_meta
406 .get(agent_id)
407 .and_then(|meta| meta.resolved_model.clone())
408 .or_else(|| {
409 app.subagent_cache
410 .iter()
411 .find(|agent| agent.agent_id == agent_id)
412 .map(|agent| sanitized_roster_model(&agent.model))
413 })
414 .unwrap_or_default();
415 let step = app
416 .agent_progress_meta
417 .get(agent_id)
418 .and_then(|meta| meta.current_activity.as_ref())
419 .and_then(|activity| activity.step)
420 .or_else(|| {
421 app.subagent_cache
422 .iter()
423 .find(|agent| agent.agent_id == agent_id)
424 .map(|agent| agent.steps_taken)
425 });
426 if let Some(existing) = app
427 .agent_roster
428 .iter_mut()
429 .find(|row| row.worker_id == agent_id)
430 {
431 if let Some(name) = display_name
432 .map(str::trim)
433 .filter(|name| !name.is_empty() && *name != agent_id)
434 {
435 existing.display_name = name.to_string();
436 } else if existing.display_name.trim().is_empty()
437 || existing.display_name == "agent"
438 || App::is_agent_counter_placeholder(&existing.display_name)
439 {
440 existing.display_name = name;
441 }
442 if (existing.model.is_empty() || existing.model == "unknown") && !model.is_empty() {
443 existing.model = model;
444 }
445 if existing.parent_run_id.is_none() {
446 existing.parent_run_id = parent_run_id.map(str::to_string);
447 }
448 if existing.state != RosterState::Parked
449 || matches!(
450 state,
451 RosterState::Done | RosterState::Failed | RosterState::Cancelled
452 )
453 {
454 existing.status = worker_status;
455 existing.state = state;
456 }
457 if activity.is_some() {
458 existing.activity = activity;
459 }
460 if outcome_text.is_some() {
461 existing.outcome = outcome_text;
462 }
463 if elapsed_ms.is_some() {
464 existing.millis = elapsed_ms;
465 }
466 if let Some(usage) = usage {
467 if usage.input_tokens.is_some() {
468 existing.input_tokens = usage.input_tokens;
469 }
470 if usage.output_tokens.is_some() {
471 existing.output_tokens = usage.output_tokens;
472 }
473 if usage.cost_microusd.is_some() {
474 existing.cost_microusd = usage.cost_microusd;
475 }
476 }
477 if let Some(step) = step {
478 existing.steps_taken = existing.steps_taken.max(step);
479 }
480 return;
481 }
482 app.agent_roster.push(AgentRosterRow {
483 worker_id: agent_id.to_string(),
484 display_name: name,
485 model,
486 state,
487 status: worker_status,
488 activity,
489 outcome: outcome_text,
490 millis: elapsed_ms,
491 input_tokens: usage.and_then(|u| u.input_tokens),
492 output_tokens: usage.and_then(|u| u.output_tokens),
493 cost_microusd: usage.and_then(|u| u.cost_microusd),
494 steps_taken: step.unwrap_or(0),
495 parent_run_id: parent_run_id.map(str::to_string),
496 run_id: agent_id.to_string(),
497 });
498 }
499
500 pub(crate) fn upsert_roster_from_mailbox(
501 app: &mut App,
502 owner_session_id: &str,
503 message: &MailboxMessage,
504 ) {
505 if matches!(
506 message,
507 MailboxMessage::FileWrites { .. } | MailboxMessage::WorkState { .. }
508 ) {
509 return;
510 }
511 if !ensure_roster_scope(app, owner_session_id) {
512 return;
513 }
514 let agent_id = message.agent_id();
515 match message {
516 MailboxMessage::Started { agent_type, .. } => {
517 upsert_roster_spawn(
518 app,
519 owner_session_id,
520 agent_id,
521 "",
522 Some(AgentWorkerStatus::Running),
523 None,
524 "",
525 Some(agent_type.as_str()),
526 );
527 }
528 MailboxMessage::ChildSpawned { parent_id, .. } => {
529 upsert_roster_spawn(
530 app,
531 owner_session_id,
532 agent_id,
533 "",
534 Some(AgentWorkerStatus::Starting),
535 Some(parent_id.as_str()),
536 "",
537 None,
538 );
539 }
540 MailboxMessage::TokenUsage { record, route, .. } => {
541 let route = record
542 .as_ref()
543 .filter(|record| record.settlement.is_some())
544 .map_or(route.as_ref(), |record| &record.usage.route);
545 let model = sanitized_roster_model(&route.model);
546 if !model.is_empty()
547 && let Some(existing) = app
548 .agent_roster
549 .iter_mut()
550 .find(|row| row.worker_id == agent_id)
551 && (existing.model.is_empty() || existing.model == "unknown")
552 {
553 existing.model = model;
554 }
555 }
556 MailboxMessage::ToolCallStarted {
557 tool_name, step, ..
558 } => {
559 if let Some(existing) = app
560 .agent_roster
561 .iter_mut()
562 .find(|row| row.worker_id == agent_id)
563 && !existing.state.is_terminal()
564 && existing.state != RosterState::Parked
565 {
566 let tool =
567 bound_agent_activity_text(subagent_progress_tool_display_name(tool_name));
568 existing.status = AgentWorkerStatus::RunningTool;
569 existing.state = RosterState::Running;
570 existing.activity = Some(format!("step {step} · {tool}"));
571 existing.steps_taken = existing.steps_taken.max(*step);
572 }
573 }
574 MailboxMessage::ToolCallCompleted { step, .. } => {
575 if let Some(existing) = app
576 .agent_roster
577 .iter_mut()
578 .find(|row| row.worker_id == agent_id)
579 && !existing.state.is_terminal()
580 && existing.state != RosterState::Parked
581 {
582 existing.status = AgentWorkerStatus::Running;
583 existing.state = RosterState::Running;
584 existing.steps_taken = existing.steps_taken.max(*step);
585 }
586 }
587 MailboxMessage::Progress { status, .. } => {
588 let line = one_line(&bound_agent_activity_text(status));
589 if !line.is_empty()
590 && let Some(existing) = app
591 .agent_roster
592 .iter_mut()
593 .find(|row| row.worker_id == agent_id)
594 && !existing.state.is_terminal()
595 && existing.state != RosterState::Parked
596 {
597 existing.activity = Some(line);
598 }
599 }
600 MailboxMessage::Completed { summary, .. } => {
601 let elapsed_ms = app
602 .agent_progress_meta
603 .get(agent_id)
604 .and_then(|meta| meta.started_at)
605 .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
606 upsert_roster_terminal(
607 app,
608 owner_session_id,
609 agent_id,
610 Some(&SubAgentStatus::Completed),
611 summary,
612 None,
613 None,
614 None,
615 elapsed_ms,
616 );
617 }
618 MailboxMessage::Failed { error, .. } => {
619 let elapsed_ms = app
620 .agent_progress_meta
621 .get(agent_id)
622 .and_then(|meta| meta.started_at)
623 .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
624 upsert_roster_terminal(
625 app,
626 owner_session_id,
627 agent_id,
628 Some(&SubAgentStatus::Failed(error.clone())),
629 error,
630 None,
631 None,
632 None,
633 elapsed_ms,
634 );
635 }
636 MailboxMessage::BudgetExhausted { summary, .. } => {
637 let elapsed_ms = app
638 .agent_progress_meta
639 .get(agent_id)
640 .and_then(|meta| meta.started_at)
641 .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
642 upsert_roster_terminal(
643 app,
644 owner_session_id,
645 agent_id,
646 Some(&SubAgentStatus::BudgetExhausted),
647 summary,
648 None,
649 None,
650 None,
651 elapsed_ms,
652 );
653 }
654 MailboxMessage::Interrupted { reason, .. } => {
655 let elapsed_ms = app
656 .agent_progress_meta
657 .get(agent_id)
658 .and_then(|meta| meta.started_at)
659 .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
660 let existing_settled = app
661 .agent_roster
662 .iter()
663 .find(|row| row.worker_id == agent_id)
664 .is_some_and(|row| row.state.is_terminal() || row.state == RosterState::Parked);
665 if !existing_settled {
666 upsert_roster_terminal(
667 app,
668 owner_session_id,
669 agent_id,
670 Some(&SubAgentStatus::Interrupted(reason.clone())),
671 reason,
672 None,
673 None,
674 None,
675 elapsed_ms,
676 );
677 if let Some(existing) = app
678 .agent_roster
679 .iter_mut()
680 .find(|row| row.worker_id == agent_id)
681 && existing.state != RosterState::Parked
682 {
683 existing.status = AgentWorkerStatus::WaitingForUser;
684 existing.state = RosterState::Waiting;
685 }
686 }
687 }
688 MailboxMessage::Cancelled { .. } => {
689 let elapsed_ms = app
690 .agent_progress_meta
691 .get(agent_id)
692 .and_then(|meta| meta.started_at)
693 .map(|started| u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
694 upsert_roster_terminal(
695 app,
696 owner_session_id,
697 agent_id,
698 Some(&SubAgentStatus::Cancelled),
699 "",
700 None,
701 None,
702 None,
703 elapsed_ms,
704 );
705 }
706 MailboxMessage::FileWrites { .. } | MailboxMessage::WorkState { .. } => {}
707 }
708 }
709
710 pub(super) fn reconcile_subagent_activity_state_at(app: &mut App, now: Instant) {
711 reconcile_terminal_subagent_card_retention(app, now);
712
713 let cached_agents = app.subagent_cache.clone();
714 let running_agents: Vec<(String, String)> = cached_agents
715 .iter()
716 .filter(|agent| matches!(agent.status, SubAgentStatus::Running))
717 .map(|agent| {
718 (
719 agent.agent_id.clone(),
720 summarize_tool_output(&agent.assignment.objective),
721 )
722 })
723 .collect();
724
725 let running_ids: std::collections::HashSet<String> =
726 running_agents.iter().map(|(id, _)| id.clone()).collect();
727 // Evict a progress row only when the authoritative cache actually knows
728 // the agent and reports it non-running. A progress-only entry — an agent
729 // whose AgentSpawned/AgentList delivery was dropped under channel
730 // pressure so the cache has never seen it — must survive until the cache
731 // supersedes it, or spawned agents flicker in and out of the sidebar.
732 let cached_ids: std::collections::HashSet<String> = cached_agents
733 .iter()
734 .map(|agent| agent.agent_id.clone())
735 .collect();
736 app.agent_progress
737 .retain(|id, _| running_ids.contains(id) || !cached_ids.contains(id));
738 let progress_ids: std::collections::HashSet<String> =
739 app.agent_progress.keys().cloned().collect();
740 app.agent_progress_meta
741 .retain(|id, _| cached_ids.contains(id) || progress_ids.contains(id));
742
743 for (id, objective) in &running_agents {
744 app.agent_progress
745 .entry(id.clone())
746 .or_insert_with(|| objective.clone());
747 }
748
749 let recovery_detail = parked_recovery_detail(app);
750 for agent in &cached_agents {
751 let meta = app
752 .agent_progress_meta
753 .entry(agent.agent_id.clone())
754 .or_insert_with(|| AgentProgressMeta {
755 parent_run_id: agent.parent_run_id.clone(),
756 spawn_depth: agent.spawn_depth,
757 ..AgentProgressMeta::default()
758 });
759 meta.parent_run_id = agent.parent_run_id.clone();
760 meta.spawn_depth = agent.spawn_depth;
761
762 let existing = meta.current_activity.clone();
763 let parked = subagent_is_parked(agent);
764 // Parked outranks `needs_input`: the park note *is* phrased as a
765 // question, and reading it as one is exactly the bug (#5906).
766 let mut structured_status = if parked {
767 AgentCurrentActivityStatus::Parked
768 } else if agent.needs_input.is_some() {
769 AgentCurrentActivityStatus::Waiting
770 } else if let Some(worker_status) = agent.worker_status {
771 worker_status.into()
772 } else if matches!(agent.status, SubAgentStatus::Running) {
773 existing
774 .as_ref()
775 .map(|activity| activity.status)
776 .unwrap_or(AgentCurrentActivityStatus::Running)
777 } else {
778 worker_status_for_terminal_projection(&agent.status).into()
779 };
780 if structured_status == AgentCurrentActivityStatus::Interrupted
781 && existing
782 .as_ref()
783 .is_some_and(|activity| activity.status == AgentCurrentActivityStatus::Waiting)
784 {
785 structured_status = AgentCurrentActivityStatus::Waiting;
786 }
787
788 let detail = parked
789 .then(|| recovery_detail.clone())
790 .or_else(|| {
791 agent
792 .needs_input
793 .as_ref()
794 .map(|needs_input| needs_input.question.clone())
795 })
796 .or_else(|| {
797 existing
798 .as_ref()
799 .filter(|activity| activity.status == structured_status)
800 .and_then(|activity| activity.detail.clone())
801 })
802 .or_else(|| agent.result.clone());
803 let current_tool = existing
804 .as_ref()
805 .filter(|_| structured_status == AgentCurrentActivityStatus::RunningTool)
806 .and_then(|activity| activity.current_tool.clone());
807 let step = (agent.steps_taken > 0)
808 .then_some(agent.steps_taken)
809 .or_else(|| existing.as_ref().and_then(|activity| activity.step));
810 meta.current_activity = Some(AgentCurrentActivity::bounded(
811 structured_status,
812 detail,
813 current_tool.clone(),
814 step,
815 ));
816 meta.current_tool = current_tool;
817 }
818
819 if running_ids.is_empty() {
820 app.agent_activity_started_at = None;
821 } else if app.agent_activity_started_at.is_none() {
822 app.agent_activity_started_at = Some(Instant::now());
823 }
824
825 reconcile_cards_with_snapshots(app);
826 }
827
828 fn reconcile_terminal_subagent_card_retention(app: &mut App, now: Instant) {
829 let current_ids: std::collections::HashSet<String> = app
830 .subagent_cache
831 .iter()
832 .map(|agent| agent.agent_id.clone())
833 .collect();
834 app.subagent_terminal_seen_at
835 .retain(|id, _| current_ids.contains(id));
836
837 for agent in &app.subagent_cache {
838 if matches!(agent.status, SubAgentStatus::Running) {
839 app.subagent_terminal_seen_at.remove(&agent.agent_id);
840 } else {
841 app.subagent_terminal_seen_at
842 .entry(agent.agent_id.clone())
843 .or_insert(now);
844 }
845 }
846
847 app.subagent_cache.retain(|agent| {
848 if matches!(agent.status, SubAgentStatus::Running) {
849 return true;
850 }
851 app.subagent_terminal_seen_at
852 .get(&agent.agent_id)
853 .and_then(|seen_at| now.checked_duration_since(*seen_at))
854 .is_none_or(|age| age <= SUBAGENT_TERMINAL_CARD_TTL)
855 });
856
857 let mut terminal_seen: Vec<(String, Instant)> = app
858 .subagent_cache
859 .iter()
860 .filter(|agent| !matches!(agent.status, SubAgentStatus::Running))
861 .filter_map(|agent| {
862 app.subagent_terminal_seen_at
863 .get(&agent.agent_id)
864 .map(|seen_at| (agent.agent_id.clone(), *seen_at))
865 })
866 .collect();
867 terminal_seen.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
868 let keep_terminal_ids: std::collections::HashSet<String> = terminal_seen
869 .into_iter()
870 .take(SUBAGENT_TERMINAL_CARD_MAX_RETAINED)
871 .map(|(id, _)| id)
872 .collect();
873 app.subagent_cache.retain(|agent| {
874 matches!(agent.status, SubAgentStatus::Running)
875 || keep_terminal_ids.contains(agent.agent_id.as_str())
876 });
877
878 let kept_ids: std::collections::HashSet<String> = app
879 .subagent_cache
880 .iter()
881 .map(|agent| agent.agent_id.clone())
882 .collect();
883 app.subagent_terminal_seen_at
884 .retain(|id, _| kept_ids.contains(id));
885 }
886
887 /// Sync in-transcript card slots that still render as running against the
888 /// canonical manager snapshot statuses. A card can miss its terminal mailbox
889 /// envelope (e.g. API-timeout interruption observed only via `AgentList`),
890 /// which would otherwise leave the fanout/delegate UI counting the agent as
891 /// running indefinitely.
892 fn reconcile_cards_with_snapshots(app: &mut App) {
893 let non_running: Vec<(String, AgentLifecycle)> = app
894 .subagent_cache
895 .iter()
896 .filter_map(|agent| {
897 let lifecycle = match &agent.status {
898 SubAgentStatus::Running => return None,
899 SubAgentStatus::Interrupted(_) => AgentLifecycle::Interrupted,
900 SubAgentStatus::Completed => AgentLifecycle::Completed,
901 SubAgentStatus::Failed(_) => AgentLifecycle::Failed,
902 SubAgentStatus::Cancelled => AgentLifecycle::Cancelled,
903 SubAgentStatus::BudgetExhausted => AgentLifecycle::Failed,
904 };
905 Some((agent.agent_id.clone(), lifecycle))
906 })
907 .collect();
908 for (agent_id, lifecycle) in non_running {
909 let Some(&idx) = app.subagent_card_index.get(&agent_id) else {
910 continue;
911 };
912 let updated = match app.history.get_mut(idx) {
913 Some(HistoryCell::SubAgent(SubAgentCell::Delegate(card)))
914 if card.agent_id == agent_id
915 && matches!(
916 card.status,
917 AgentLifecycle::Pending | AgentLifecycle::Running
918 ) =>
919 {
920 card.status = lifecycle;
921 true
922 }
923 Some(HistoryCell::SubAgent(SubAgentCell::Fanout(card))) => {
924 match card.workers.iter_mut().find(|slot| {
925 slot.agent_id == agent_id
926 && matches!(
927 slot.status,
928 AgentLifecycle::Pending | AgentLifecycle::Running
929 )
930 }) {
931 Some(slot) => {
932 slot.status = lifecycle;
933 true
934 }
935 None => false,
936 }
937 }
938 _ => false,
939 };
940 if updated {
941 app.bump_history_cell(idx);
942 }
943 }
944 }
945
946 fn subagent_status_rank(status: &SubAgentStatus) -> u8 {
947 match status {
948 SubAgentStatus::Running => 0,
949 SubAgentStatus::Interrupted(_) => 1,
950 SubAgentStatus::Failed(_) => 2,
951 SubAgentStatus::Completed => 3,
952 SubAgentStatus::Cancelled => 4,
953 SubAgentStatus::BudgetExhausted => 2,
954 }
955 }
956
957 pub(super) fn sort_subagents_in_place(agents: &mut [SubAgentResult]) {
958 agents.sort_by(|a, b| {
959 subagent_status_rank(&a.status)
960 .cmp(&subagent_status_rank(&b.status))
961 .then_with(|| a.agent_type.as_str().cmp(b.agent_type.as_str()))
962 .then_with(|| a.agent_id.cmp(&b.agent_id))
963 });
964 }
965
966 pub(super) fn subagent_message_refreshes_workspace_context(message: &MailboxMessage) -> bool {
967 matches!(
968 message,
969 MailboxMessage::ToolCallCompleted { tool_name, .. }
970 if refreshes_workspace_context_on_completion(tool_name)
971 )
972 }
973
974 /// Route a `MailboxMessage` envelope to the matching in-transcript card,
975 /// allocating a `DelegateCard` or `FanoutCard` on first sight (issue #128).
976 pub(super) fn handle_subagent_mailbox_for_turn(
977 app: &mut App,
978 _turn_id: &str,
979 _seq: u64,
980 message: &MailboxMessage,
981 ) -> bool {
982 if let MailboxMessage::FileWrites {
983 turn_seq, paths, ..
984 } = message
985 {
986 if let Some(session) = app.current_session_id.clone() {
987 app.delegated_writes
988 .entry((session, *turn_seq))
989 .or_default()
990 .extend(paths.iter().cloned());
991 }
992 return false;
993 }
994
995 // Accumulate sub-agent token costs for the real-time footer counter (#166).
996 if let MailboxMessage::TokenUsage { record, .. } = message {
997 if let Some(record) = record.as_ref().filter(|record| record.settlement.is_some()) {
998 let pending = codewhale_engine::cost_status::drain();
999 app.absorb_pending_background_cost(&pending);
1000 if let Err(error) = app.absorb_usage_source(record) {
1001 tracing::warn!(%error, "mailbox usage revision was not admitted");
1002 app.mark_usage_uncertain("usage_correction_unverified");
1003 }
1004 let fingerprint =
1005 codewhale_engine::cost_status::usage_source_fingerprint(&record.source_id);
1006 if app
1007 .session
1008 .accounted_usage_sources
1009 .get(&fingerprint)
1010 .is_some_and(|contribution| contribution.record == **record)
1011 {
1012 record_agent_current_activity(app, message);
1013 }
1014 return false;
1015 }
1016 let pending = codewhale_engine::cost_status::drain();
1017 app.absorb_pending_background_cost(&pending);
1018 app.mark_usage_uncertain("legacy_usage_unverified");
1019 record_agent_current_activity(app, message);
1020 return false;
1021 }
1022
1023 // Resolve (or allocate) the target cell for this envelope. ChildSpawned
1024 // is special — it always belongs to the active fanout card if one
1025 // exists; otherwise it seeds a new one.
1026 let display_message = bounded_mailbox_message(message);
1027 let agent_id = display_message.agent_id().to_string();
1028 record_agent_current_activity(app, message);
1029 if subagent_message_refreshes_workspace_context(message) {
1030 workspace_context::refresh_now(app, Instant::now());
1031 }
1032
1033 if matches!(message, MailboxMessage::ChildSpawned { .. })
1034 && let Some(idx) = app.last_fanout_card_index
1035 && let Some(HistoryCell::SubAgent(SubAgentCell::Fanout(card))) = app.history.get_mut(idx)
1036 {
1037 let updated = apply_to_fanout(card, &display_message);
1038 app.subagent_card_index.insert(agent_id, idx);
1039 if updated {
1040 app.bump_history_cell(idx);
1041 }
1042 return updated;
1043 }
1044
1045 // Existing card for this agent_id? Mutate in place.
1046 if let Some(&idx) = app.subagent_card_index.get(&agent_id) {
1047 let updated = match app.history.get_mut(idx) {
1048 Some(HistoryCell::SubAgent(SubAgentCell::Delegate(card))) => {
1049 apply_to_delegate(card, &display_message)
1050 }
1051 Some(HistoryCell::SubAgent(SubAgentCell::Fanout(card))) => {
1052 apply_to_fanout(card, &display_message)
1053 }
1054 _ => false,
1055 };
1056 if updated {
1057 // idx is already in scope from the outer
1058 // `if let Some(&idx) = app.subagent_card_index.get(&agent_id)`.
1059 app.bump_history_cell(idx);
1060 }
1061 return updated;
1062 }
1063
1064 // No existing card — only `Started` reasonably opens one. Anything else
1065 // for an unknown agent_id is dropped (likely arrived after the cell was
1066 // cleared, e.g. session-resume edge cases).
1067 let agent_type = match &display_message {
1068 MailboxMessage::Started { agent_type, .. } => agent_type.clone(),
1069 MailboxMessage::Completed { .. }
1070 | MailboxMessage::Failed { .. }
1071 | MailboxMessage::BudgetExhausted { .. }
1072 | MailboxMessage::Interrupted { .. }
1073 | MailboxMessage::Cancelled { .. } => "unknown".to_string(),
1074 _ => return false,
1075 };
1076
1077 let dispatch_kind = app.pending_subagent_dispatch.as_deref();
1078 let is_fanout = matches!(dispatch_kind, Some("rlm_open" | "rlm_eval" | "rlm"));
1079
1080 if is_fanout {
1081 // A completion-first delivery opens the slot settled, as the delegate
1082 // path does; recording it as running would leave a finished worker
1083 // counted as running with nothing left to settle it (U05-04).
1084 let first_status = match &display_message {
1085 MailboxMessage::Completed { .. } => AgentLifecycle::Completed,
1086 MailboxMessage::Failed { .. } | MailboxMessage::BudgetExhausted { .. } => {
1087 AgentLifecycle::Failed
1088 }
1089 MailboxMessage::Interrupted { .. } => AgentLifecycle::Interrupted,
1090 MailboxMessage::Cancelled { .. } => AgentLifecycle::Cancelled,
1091 _ => AgentLifecycle::Running,
1092 };
1093 // Reuse the active fanout card for sibling spawns; otherwise create
1094 // one anchored at this position so subsequent siblings join it.
1095 if let Some(idx) = app.last_fanout_card_index
1096 && let Some(HistoryCell::SubAgent(SubAgentCell::Fanout(card))) =
1097 app.history.get_mut(idx)
1098 {
1099 let updated = card.upsert_worker(&agent_id, first_status);
1100 app.subagent_card_index.insert(agent_id, idx);
1101 if updated {
1102 app.bump_history_cell(idx);
1103 }
1104 updated
1105 } else {
1106 let mut card = FanoutCard::new(dispatch_kind.unwrap_or("rlm_eval").to_string());
1107 card.upsert_worker(&agent_id, first_status);
1108 app.add_message(HistoryCell::SubAgent(SubAgentCell::Fanout(card)));
1109 let idx = app.history.len().saturating_sub(1);
1110 app.last_fanout_card_index = Some(idx);
1111 app.subagent_card_index.insert(agent_id, idx);
1112 app.bump_history_cell(idx);
1113 true
1114 }
1115 } else {
1116 let mut card = DelegateCard::new(agent_id.clone(), agent_type.clone());
1117 apply_to_delegate(&mut card, &display_message);
1118 app.add_message(HistoryCell::SubAgent(SubAgentCell::Delegate(card)));
1119 let idx = app.history.len().saturating_sub(1);
1120 app.subagent_card_index.insert(agent_id.clone(), idx);
1121 // Single delegate consumes the pending dispatch label so a follow-on
1122 // tool call doesn't accidentally inherit it.
1123 app.pending_subagent_dispatch = None;
1124 // idx was just inserted on the line above — no need to re-query.
1125 app.bump_history_cell(idx);
1126 true
1127 }
1128 }
1129
1130 #[cfg(test)]
1131 pub(super) fn handle_subagent_mailbox(app: &mut App, seq: u64, message: &MailboxMessage) -> bool {
1132 handle_subagent_mailbox_for_turn(app, "test-turn", seq, message)
1133 }
1134
1135 fn bounded_mailbox_message(message: &MailboxMessage) -> MailboxMessage {
1136 match message {
1137 MailboxMessage::Progress { agent_id, status } => MailboxMessage::Progress {
1138 agent_id: agent_id.clone(),
1139 status: bound_agent_activity_text(status),
1140 },
1141 MailboxMessage::ToolCallStarted {
1142 agent_id,
1143 tool_name,
1144 step,
1145 } => MailboxMessage::ToolCallStarted {
1146 agent_id: agent_id.clone(),
1147 tool_name: bound_agent_activity_text(subagent_progress_tool_display_name(tool_name)),
1148 step: *step,
1149 },
1150 MailboxMessage::ToolCallCompleted {
1151 agent_id,
1152 tool_name,
1153 step,
1154 ok,
1155 } => MailboxMessage::ToolCallCompleted {
1156 agent_id: agent_id.clone(),
1157 tool_name: bound_agent_activity_text(subagent_progress_tool_display_name(tool_name)),
1158 step: *step,
1159 ok: *ok,
1160 },
1161 MailboxMessage::Completed { agent_id, summary } => MailboxMessage::Completed {
1162 agent_id: agent_id.clone(),
1163 summary: bound_agent_activity_text(summary),
1164 },
1165 MailboxMessage::Failed { agent_id, error } => MailboxMessage::Failed {
1166 agent_id: agent_id.clone(),
1167 error: bound_agent_activity_text(error),
1168 },
1169 MailboxMessage::BudgetExhausted { agent_id, summary } => MailboxMessage::BudgetExhausted {
1170 agent_id: agent_id.clone(),
1171 summary: bound_agent_activity_text(summary),
1172 },
1173 MailboxMessage::Interrupted { agent_id, reason } => MailboxMessage::Interrupted {
1174 agent_id: agent_id.clone(),
1175 reason: bound_agent_activity_text(reason),
1176 },
1177 // Item text is model-authored and reaches the transcript, so it gets
1178 // the same redaction/bounding every other displayed child string gets.
1179 // Ids, statuses, and counts are preserved exactly — bounding must not
1180 // change what the ledger says.
1181 MailboxMessage::WorkState { agent_id, todo } => MailboxMessage::WorkState {
1182 agent_id: agent_id.clone(),
1183 todo: codewhale_engine::tools::todo::TodoListSnapshot {
1184 items: todo
1185 .items
1186 .iter()
1187 .map(|item| codewhale_engine::tools::todo::TodoItem {
1188 content: bound_agent_activity_text(&item.content),
1189 ..item.clone()
1190 })
1191 .collect(),
1192 ..todo.clone()
1193 },
1194 },
1195 _ => message.clone(),
1196 }
1197 }
1198
1199 fn record_agent_current_activity(app: &mut App, message: &MailboxMessage) {
1200 let agent_id = message.agent_id().to_string();
1201 let meta = app.agent_progress_meta.entry(agent_id).or_default();
1202 let now = Instant::now();
1203 meta.last_progress_at = Some(now);
1204 if matches!(
1205 message,
1206 MailboxMessage::Started { .. } | MailboxMessage::ChildSpawned { .. }
1207 ) {
1208 meta.started_at.get_or_insert(now);
1209 }
1210 if let MailboxMessage::TokenUsage {
1211 record,
1212 route,
1213 usage,
1214 source_id,
1215 ..
1216 } = message
1217 {
1218 let (route, usage) = record
1219 .as_ref()
1220 .filter(|record| record.settlement.is_some())
1221 .map_or((route.as_ref(), usage), |record| {
1222 (&record.usage.route, &record.usage.usage)
1223 });
1224 let total = u64::from(usage.input_tokens).saturating_add(u64::from(usage.output_tokens));
1225 if let Some(record) = record.as_ref().filter(|record| record.settlement.is_some()) {
1226 let key = codewhale_engine::cost_status::usage_source_fingerprint(&record.source_id);
1227 let previous = meta.received_usage_sources.insert(key, total).unwrap_or(0);
1228 meta.received_tokens = Some(
1229 meta.received_tokens
1230 .unwrap_or(0)
1231 .saturating_sub(previous)
1232 .saturating_add(total),
1233 );
1234 } else if source_id.is_empty() {
1235 meta.received_tokens = Some(meta.received_tokens.unwrap_or(0).saturating_add(total));
1236 } else {
1237 let key = codewhale_engine::cost_status::usage_source_fingerprint(source_id);
1238 if meta.received_usage_sources.insert(key, total).is_none() {
1239 meta.received_tokens =
1240 Some(meta.received_tokens.unwrap_or(0).saturating_add(total));
1241 }
1242 }
1243 meta.resolved_provider = Some(route.provider.as_str().to_string());
1244 meta.resolved_model = Some(bound_agent_activity_text(
1245 &codewhale_runtime::safe_label::sanitize_persisted_route_label(&route.model),
1246 ))
1247 .filter(|model| !model.trim().is_empty());
1248 return;
1249 }
1250 if let MailboxMessage::WorkState { todo, .. } = message {
1251 // Work state is a separate fact from what the agent is doing right
1252 // now — publishing a ledger update must not invent an activity
1253 // transition. It does update the remaining-to-do chip for the strip.
1254 if todo.is_empty() {
1255 meta.todos_remaining = None;
1256 } else {
1257 let remaining = todo
1258 .items
1259 .iter()
1260 .filter(|item| !item.status.is_settled())
1261 .count();
1262 meta.todos_remaining = Some(u32::try_from(remaining).unwrap_or(u32::MAX));
1263 }
1264 return;
1265 }
1266 if let MailboxMessage::ToolCallCompleted {
1267 tool_name,
1268 step,
1269 ok,
1270 ..
1271 } = message
1272 {
1273 if meta.recent_actions.len() == MAX_AGENT_RECENT_ACTIONS {
1274 meta.recent_actions.pop_front();
1275 }
1276 meta.recent_actions.push_back(AgentRecentAction::bounded(
1277 subagent_progress_tool_display_name(tool_name),
1278 *step,
1279 *ok,
1280 ));
1281 }
1282 let previous = meta.current_activity.clone();
1283
1284 let (status, detail, current_tool, step) = match message {
1285 MailboxMessage::Started { agent_type, .. } => (
1286 AgentCurrentActivityStatus::Running,
1287 Some(format!("started {agent_type}")),
1288 None,
1289 None,
1290 ),
1291 MailboxMessage::Progress { status, .. } => (
1292 previous
1293 .as_ref()
1294 .map(|activity| activity.status)
1295 .unwrap_or(AgentCurrentActivityStatus::Running),
1296 Some(status.clone()),
1297 previous
1298 .as_ref()
1299 .and_then(|activity| activity.current_tool.clone()),
1300 previous.as_ref().and_then(|activity| activity.step),
1301 ),
1302 MailboxMessage::ToolCallStarted {
1303 tool_name, step, ..
1304 } => (
1305 AgentCurrentActivityStatus::RunningTool,
1306 None,
1307 Some(subagent_progress_tool_display_name(tool_name).to_string()),
1308 Some(*step),
1309 ),
1310 MailboxMessage::ToolCallCompleted {
1311 tool_name,
1312 step,
1313 ok,
1314 ..
1315 } => (
1316 AgentCurrentActivityStatus::Running,
1317 Some(format!(
1318 "{} {}",
1319 subagent_progress_tool_display_name(tool_name),
1320 if *ok { "completed" } else { "failed" }
1321 )),
1322 None,
1323 Some(*step),
1324 ),
1325 MailboxMessage::ChildSpawned { parent_id, .. } => (
1326 AgentCurrentActivityStatus::Starting,
1327 Some(format!("spawned by {parent_id}")),
1328 None,
1329 None,
1330 ),
1331 MailboxMessage::Completed { summary, .. } => (
1332 AgentCurrentActivityStatus::Done,
1333 Some(summary.clone()),
1334 None,
1335 previous.as_ref().and_then(|activity| activity.step),
1336 ),
1337 MailboxMessage::Failed { error, .. } => (
1338 AgentCurrentActivityStatus::Failed,
1339 Some(error.clone()),
1340 None,
1341 previous.as_ref().and_then(|activity| activity.step),
1342 ),
1343 MailboxMessage::BudgetExhausted { summary, .. } => (
1344 AgentCurrentActivityStatus::Failed,
1345 Some(summary.clone()),
1346 None,
1347 previous.as_ref().and_then(|activity| activity.step),
1348 ),
1349 MailboxMessage::Interrupted { reason, .. } => (
1350 AgentCurrentActivityStatus::Waiting,
1351 Some(reason.clone()),
1352 None,
1353 previous.as_ref().and_then(|activity| activity.step),
1354 ),
1355 MailboxMessage::Cancelled { .. } => (
1356 AgentCurrentActivityStatus::Canceled,
1357 None,
1358 None,
1359 previous.as_ref().and_then(|activity| activity.step),
1360 ),
1361 MailboxMessage::TokenUsage { .. } => unreachable!("token usage handled above"),
1362 MailboxMessage::FileWrites { .. } => return,
1363 MailboxMessage::WorkState { .. } => unreachable!("work state handled above"),
1364 };
1365
1366 // A settled agent is final, as on its transcript card (U05-04): mailbox
1367 // producers are concurrent, so a Started/Progress/tool envelope can land
1368 // after the terminal one. It must not move the Work row back to active.
1369 // Only settlements whose continuation is a *new* agent latch; `Waiting`
1370 // (a question) resumes this same agent. The manager snapshot
1371 // (`reconcile_subagent_activity_state`) stays the authority either way.
1372 let settled = previous.as_ref().is_some_and(|activity| {
1373 matches!(
1374 activity.status,
1375 AgentCurrentActivityStatus::Done
1376 | AgentCurrentActivityStatus::Failed
1377 | AgentCurrentActivityStatus::Canceled
1378 | AgentCurrentActivityStatus::Interrupted
1379 | AgentCurrentActivityStatus::Parked
1380 )
1381 });
1382 if !settled {
1383 meta.current_activity = Some(AgentCurrentActivity::bounded(
1384 status,
1385 detail,
1386 current_tool.clone(),
1387 step,
1388 ));
1389 meta.current_tool = current_tool;
1390 }
1391 if let MailboxMessage::ToolCallCompleted {
1392 tool_name,
1393 ok: true,
1394 ..
1395 } = message
1396 && is_file_mutation_tool(tool_name)
1397 {
1398 meta.files_touched = meta.files_touched.saturating_add(1);
1399 }
1400 }
1401
1402 fn is_file_mutation_tool(name: &str) -> bool {
1403 matches!(
1404 name,
1405 "write_file" | "edit_file" | "apply_patch" | "fim_edit" | "Write" | "Edit"
1406 )
1407 }
1408
1409 pub(super) fn task_mode_label(mode: AppMode) -> &'static str {
1410 mode.as_setting()
1411 }
1412
1413 pub(super) fn task_summary_to_panel_entry(summary: TaskSummary) -> TaskPanelEntry {
1414 TaskPanelEntry {
1415 exit_code: None,
1416 id: summary.id,
1417 status: task_status_label(summary.status).to_string(),
1418 prompt_summary: summary.prompt_summary,
1419 duration_ms: summary.duration_ms,
1420 kind: TaskPanelEntryKind::Background,
1421 stale: false,
1422 elapsed_since_output_ms: None,
1423 owner_agent_id: None,
1424 owner_agent_name: None,
1425 current_tool: None,
1426 role: None,
1427 files_touched: 0,
1428 }
1429 }
1430
1431 fn task_status_label(status: TaskStatus) -> &'static str {
1432 match status {
1433 TaskStatus::Queued => "queued",
1434 TaskStatus::Running => "running",
1435 TaskStatus::Completed => "completed",
1436 TaskStatus::Failed => "failed",
1437 TaskStatus::Canceled => "canceled",
1438 }
1439 }
1440
1441 pub(super) fn format_task_list(tasks: &[TaskSummary]) -> String {
1442 if tasks.is_empty() {
1443 return "No tasks found.".to_string();
1444 }
1445
1446 let show_session = tasks.iter().any(|task| task.owner_session_id.is_some());
1447 let mut lines = vec![format!("Tasks ({})", tasks.len())];
1448 // Build headers with the same format strings as the rows so the ID
1449 // column (21-char `task_` ids) can never drift out of alignment again.
1450 if show_session {
1451 lines.push(format!(
1452 "{:<21} {:<9} {:<12} {:>8} {}",
1453 "ID", "Status", "Session", "Time", "Title"
1454 ));
1455 } else {
1456 lines.push(format!(
1457 "{:<21} {:<9} {:>8} {}",
1458 "ID", "Status", "Time", "Title"
1459 ));
1460 }
1461 lines.push("------------------------------------------------------------".to_string());
1462 for task in tasks {
1463 let duration = task
1464 .duration_ms
1465 .map(codewhale_command_contract::elapsed::format_elapsed_ms)
1466 .unwrap_or_else(|| "-".to_string());
1467 let owner_session = task.owner_session_id.as_deref().unwrap_or("-");
1468 let owner_session = if owner_session.chars().count() > 12 {
1469 format!("{}…", owner_session.chars().take(11).collect::<String>())
1470 } else {
1471 owner_session.to_string()
1472 };
1473 if show_session {
1474 lines.push(format!(
1475 "{:<21} {:<9} {:<12} {:>8} {}",
1476 task.id,
1477 task_status_label(task.status),
1478 owner_session,
1479 duration,
1480 task.prompt_summary
1481 ));
1482 } else {
1483 lines.push(format!(
1484 "{:<21} {:<9} {:>8} {}",
1485 task.id,
1486 task_status_label(task.status),
1487 duration,
1488 task.prompt_summary
1489 ));
1490 }
1491 }
1492 lines.push("Use /task show <id> for timeline details.".to_string());
1493 lines.join("\n")
1494 }
1495
1496 pub(super) fn open_task_pager(app: &mut App, task: &TaskRecord) {
1497 let width = app
1498 .viewport
1499 .last_transcript_area
1500 .map(|area| area.width)
1501 .unwrap_or(100)
1502 .saturating_sub(4);
1503 app.view_stack.push(PagerView::from_text(
1504 format!("Task {}", task.id),
1505 &format_task_detail(task),
1506 width.max(60),
1507 ));
1508 }
1509
1510 fn format_task_detail(task: &TaskRecord) -> String {
1511 let mut lines = Vec::new();
1512 lines.push(format!("Task: {}", task.id));
1513 lines.push(format!("Status: {}", task_status_label(task.status)));
1514 lines.push(format!("Mode: {}", task.mode));
1515 lines.push(format!("Model: {}", task.model));
1516 lines.push(format!(
1517 "Workspace: {}",
1518 codewhale_util::utils::display_path(&task.workspace)
1519 ));
1520 if let Some(owner_session_id) = task.owner_session_id.as_deref() {
1521 lines.push(format!("Owning Session: {owner_session_id}"));
1522 }
1523 if let Some(thread_id) = task.thread_id.as_ref() {
1524 lines.push(format!("Runtime Thread: {thread_id}"));
1525 }
1526 if let Some(turn_id) = task.turn_id.as_ref() {
1527 lines.push(format!("Runtime Turn: {turn_id}"));
1528 }
1529 if task.runtime_event_count > 0 {
1530 lines.push(format!("Runtime Events: {}", task.runtime_event_count));
1531 }
1532 lines.push(format!("Created: {}", task.created_at));
1533 if let Some(started_at) = task.started_at {
1534 lines.push(format!("Started: {started_at}"));
1535 }
1536 if let Some(ended_at) = task.ended_at {
1537 lines.push(format!("Ended: {ended_at}"));
1538 }
1539 if let Some(duration) = task.duration_ms {
1540 lines.push(format!(
1541 "Duration: {}",
1542 codewhale_command_contract::elapsed::format_elapsed_ms(duration)
1543 ));
1544 }
1545 lines.push(String::new());
1546 lines.push("Prompt:".to_string());
1547 lines.push(task.prompt.clone());
1548
1549 if let Some(summary) = task.result_summary.as_ref() {
1550 lines.push(String::new());
1551 lines.push("Result Summary:".to_string());
1552 lines.push(summary.clone());
1553 }
1554 if let Some(path) = task.result_detail_path.as_ref() {
1555 lines.push(format!("Result Artifact: {}", path.display()));
1556 }
1557 if let Some(error) = task.error.as_ref() {
1558 lines.push(String::new());
1559 lines.push(format!("Error: {error}"));
1560 }
1561
1562 lines.push(String::new());
1563 lines.push("Tool Calls:".to_string());
1564 if task.tool_calls.is_empty() {
1565 lines.push("- (none)".to_string());
1566 } else {
1567 for tool in &task.tool_calls {
1568 let status = match tool.status {
1569 codewhale_engine::task_manager::TaskToolStatus::Running => "running",
1570 codewhale_engine::task_manager::TaskToolStatus::Success => "success",
1571 codewhale_engine::task_manager::TaskToolStatus::Failed => "failed",
1572 codewhale_engine::task_manager::TaskToolStatus::Canceled => "canceled",
1573 };
1574 let mut line = format!(
1575 "- {} [{}] {}",
1576 tool.name,
1577 status,
1578 tool.output_summary.as_deref().unwrap_or("(no summary)")
1579 );
1580 if let Some(duration) = tool.duration_ms {
1581 line.push_str(&format!(" ({:.2}s)", duration as f64 / 1000.0));
1582 }
1583 lines.push(line);
1584 if let Some(path) = tool.detail_path.as_ref() {
1585 lines.push(format!(" detail: {}", path.display()));
1586 }
1587 if let Some(path) = tool.patch_ref.as_ref() {
1588 lines.push(format!(" patch: {}", path.display()));
1589 }
1590 }
1591 }
1592
1593 lines.push(String::new());
1594 lines.push("Timeline:".to_string());
1595 if task.timeline.is_empty() {
1596 lines.push("- (none)".to_string());
1597 } else {
1598 for entry in &task.timeline {
1599 lines.push(format!(
1600 "- [{}] {}: {}",
1601 entry.timestamp, entry.kind, entry.summary
1602 ));
1603 if let Some(path) = entry.detail_path.as_ref() {
1604 lines.push(format!(" detail: {}", path.display()));
1605 }
1606 }
1607 }
1608
1609 lines.join("\n")
1610 }
1611
1612 #[cfg(test)]
1613 mod tests {
1614 use super::*;
1615 use crate::tui::app::{InitialInput, TuiOptions};
1616 use crate::tui::widgets::agent_card::AgentLifecycle;
1617 use chrono::Utc;
1618 use codewhale_agent_contract::role::FleetRole;
1619 use codewhale_engine::task_manager::{TaskStatus, TaskSummary};
1620 use codewhale_engine::tools::subagent::SubAgentAssignment;
1621 use codewhale_runtime::config::Config;
1622 use std::path::PathBuf;
1623
1624 fn test_options() -> TuiOptions {
1625 TuiOptions {
1626 model: "test-model".to_string(),
1627 allow_shell: true,
1628 max_subagents: 4,
1629 start_in_agent_mode: true,
1630 initial_input: None::<InitialInput>,
1631 startup_notice: None,
1632 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
1633 }
1634 }
1635
1636 fn test_route(
1637 provider: codewhale_config::ProviderKind,
1638 model: &str,
1639 ) -> codewhale_engine::cost_status::EffectiveRouteEnvelope {
1640 codewhale_engine::cost_status::EffectiveRouteEnvelope::capture(
1641 None,
1642 provider,
1643 provider.as_str(),
1644 model,
1645 Some(provider.provider().default_base_url()),
1646 Utc::now(),
1647 )
1648 }
1649
1650 fn task_summary(id: &str, status: TaskStatus, duration_ms: Option<u64>) -> TaskSummary {
1651 TaskSummary {
1652 execution_binding_known: true,
1653 id: id.to_string(),
1654 status,
1655 prompt_summary: "Fix task list output".to_string(),
1656 name: None,
1657 model: "deepseek-v4-pro".to_string(),
1658 model_provider: None,
1659 model_provider_id: None,
1660 mode: "agent".to_string(),
1661 workspace: PathBuf::from("/tmp"),
1662 created_at: Utc::now(),
1663 started_at: None,
1664 ended_at: None,
1665 duration_ms,
1666 lifecycle_seq: 1,
1667 error: None,
1668 terminal_reason: None,
1669 thread_id: None,
1670 turn_id: None,
1671 owner_session_id: None,
1672 }
1673 }
1674
1675 fn subagent_result(id: &str, status: SubAgentStatus) -> SubAgentResult {
1676 SubAgentResult {
1677 usage: None,
1678 name: id.to_string(),
1679 agent_id: id.to_string(),
1680 context_mode: "fresh".to_string(),
1681 fork_context: false,
1682 workspace: None,
1683 git_branch: None,
1684 agent_type: FleetRole::Worker,
1685 assignment: SubAgentAssignment {
1686 native_preset: None,
1687 objective: format!("objective-{id}"),
1688 role: Some("worker".to_string()),
1689 },
1690 model: "deepseek-v4-flash".to_string(),
1691 nickname: None,
1692 status,
1693 worker_status: None,
1694 runtime_permissions: None,
1695 parent_run_id: None,
1696 spawn_depth: 0,
1697 child_route: None,
1698 result: None,
1699 steps_taken: 0,
1700 checkpoint: None,
1701 needs_input: None,
1702 duration_ms: 0,
1703 started_at: None,
1704 from_prior_session: false,
1705 idle_ms: None,
1706 heartbeat_timeout_ms: None,
1707 }
1708 }
1709
1710 #[test]
1711 fn task_list_includes_title_header_and_time_column() {
1712 let output = format_task_list(&[
1713 task_summary("task_12345678", TaskStatus::Running, None),
1714 task_summary("task_abcdef12", TaskStatus::Completed, Some(1234)),
1715 ]);
1716
1717 assert!(output.contains(&format!(
1718 "{:<21} {:<9} {:>8} {}",
1719 "ID", "Status", "Time", "Title"
1720 )));
1721 assert!(output.contains(&format!(
1722 "{:<21} {:<9} {:>8} {}",
1723 "task_12345678", "running", "-", "Fix task list output"
1724 )));
1725 assert!(output.contains(&format!(
1726 "{:<21} {:<9} {:>8} {}",
1727 "task_abcdef12", "completed", "1s", "Fix task list output"
1728 )));
1729 }
1730
1731 #[test]
1732 fn task_list_shows_owner_session_when_present() {
1733 let mut task = task_summary("task_owned", TaskStatus::Running, None);
1734 task.owner_session_id = Some("session-123456".to_string());
1735
1736 let output = format_task_list(&[task]);
1737
1738 assert!(output.contains(&format!(
1739 "{:<21} {:<9} {:<12} {:>8} {}",
1740 "ID", "Status", "Session", "Time", "Title"
1741 )));
1742 // Owner ids are truncated to 11 chars + '…' so the rendered value
1743 // stays inside the 12-wide Session column and cannot drift the
1744 // remaining columns out of alignment.
1745 assert!(output.contains("session-123…"), "{output}");
1746 }
1747
1748 #[test]
1749 fn mailbox_progress_reports_transcript_change_only_for_visible_card_updates() {
1750 let mut app = App::new(test_options(), &Config::default());
1751 let started = MailboxMessage::started("agent_live", FleetRole::Worker);
1752 assert!(
1753 handle_subagent_mailbox(&mut app, 1, &started),
1754 "first started envelope creates a visible card"
1755 );
1756
1757 let progress =
1758 MailboxMessage::progress("agent_live", "step 1/100: requesting model response");
1759 assert!(
1760 !handle_subagent_mailbox(&mut app, 2, &progress),
1761 "low-signal progress for an already-running card is a no-op"
1762 );
1763
1764 let tool = MailboxMessage::ToolCallStarted {
1765 agent_id: "agent_live".to_string(),
1766 tool_name: "read_file".to_string(),
1767 step: 1,
1768 };
1769 assert!(
1770 handle_subagent_mailbox(&mut app, 3, &tool),
1771 "tool progress still updates the visible transcript card"
1772 );
1773 assert_eq!(
1774 app.agent_progress_meta["agent_live"]
1775 .current_tool
1776 .as_deref(),
1777 Some("read_file")
1778 );
1779
1780 let completed = MailboxMessage::ToolCallCompleted {
1781 agent_id: "agent_live".to_string(),
1782 tool_name: "read_file".to_string(),
1783 step: 1,
1784 ok: true,
1785 };
1786 assert!(handle_subagent_mailbox(&mut app, 4, &completed));
1787 assert_eq!(app.agent_progress_meta["agent_live"].current_tool, None);
1788
1789 let wrote = MailboxMessage::ToolCallCompleted {
1790 agent_id: "agent_live".to_string(),
1791 tool_name: "apply_patch".to_string(),
1792 step: 2,
1793 ok: true,
1794 };
1795 assert!(handle_subagent_mailbox(&mut app, 5, &wrote));
1796 assert_eq!(app.agent_progress_meta["agent_live"].files_touched, 1);
1797 }
1798
1799 #[test]
1800 fn canonical_child_file_activity_counts_only_successful_mutations() {
1801 let mut app = App::new(test_options(), &Config::default());
1802
1803 for (step, tool_name) in ["read_file", "list_dir", "file_search", "grep_files"]
1804 .into_iter()
1805 .enumerate()
1806 {
1807 record_agent_current_activity(
1808 &mut app,
1809 &MailboxMessage::ToolCallCompleted {
1810 agent_id: "agent_files".to_string(),
1811 tool_name: tool_name.to_string(),
1812 step: step as u32,
1813 ok: true,
1814 },
1815 );
1816 }
1817 assert_eq!(app.agent_progress_meta["agent_files"].files_touched, 0);
1818
1819 for (step, tool_name) in ["write_file", "edit_file", "apply_patch"]
1820 .into_iter()
1821 .enumerate()
1822 {
1823 record_agent_current_activity(
1824 &mut app,
1825 &MailboxMessage::ToolCallCompleted {
1826 agent_id: "agent_files".to_string(),
1827 tool_name: tool_name.to_string(),
1828 step: (step + 10) as u32,
1829 ok: true,
1830 },
1831 );
1832 }
1833 assert_eq!(app.agent_progress_meta["agent_files"].files_touched, 3);
1834
1835 record_agent_current_activity(
1836 &mut app,
1837 &MailboxMessage::ToolCallCompleted {
1838 agent_id: "agent_files".to_string(),
1839 tool_name: "write_file".to_string(),
1840 step: 20,
1841 ok: false,
1842 },
1843 );
1844 assert_eq!(app.agent_progress_meta["agent_files"].files_touched, 3);
1845 }
1846
1847 #[test]
1848 fn recent_actions_are_three_bounded_structured_tool_outcomes() {
1849 let mut app = App::new(test_options(), &Config::default());
1850 let agent_id = "agent_recent";
1851 for step in 1..=5 {
1852 record_agent_current_activity(
1853 &mut app,
1854 &MailboxMessage::ToolCallCompleted {
1855 agent_id: agent_id.to_string(),
1856 tool_name: format!("\u{1b}[31mtool_{step}\u{1b}[0m"),
1857 step,
1858 ok: step != 4,
1859 },
1860 );
1861 }
1862 record_agent_current_activity(
1863 &mut app,
1864 &MailboxMessage::Progress {
1865 agent_id: agent_id.to_string(),
1866 status: "tool_99 completed".to_string(),
1867 },
1868 );
1869
1870 let actions = &app.agent_progress_meta[agent_id].recent_actions;
1871 assert_eq!(actions.len(), MAX_AGENT_RECENT_ACTIONS);
1872 assert_eq!(
1873 actions.iter().map(|action| action.step).collect::<Vec<_>>(),
1874 vec![3, 4, 5]
1875 );
1876 assert!(!actions.iter().any(|action| action.step == 99));
1877 assert!(actions.iter().all(|action| !action.tool.contains('\u{1b}')));
1878 assert!(!actions[1].ok);
1879 }
1880
1881 #[test]
1882 fn token_usage_records_only_the_effective_child_route_facts() {
1883 let mut app = App::new(test_options(), &Config::default());
1884 let changed = handle_subagent_mailbox(
1885 &mut app,
1886 91,
1887 &MailboxMessage::TokenUsage {
1888 record: None,
1889 agent_id: "agent_route".to_string(),
1890 source_id: "response-route".to_string(),
1891 route: Box::new(test_route(
1892 codewhale_config::ProviderKind::Openrouter,
1893 "vendor/model-real",
1894 )),
1895 usage: codewhale_models::Usage::default(),
1896 },
1897 );
1898
1899 assert!(!changed, "route facts do not allocate a transcript card");
1900 let meta = &app.agent_progress_meta["agent_route"];
1901 assert_eq!(meta.resolved_provider.as_deref(), Some("openrouter"));
1902 assert_eq!(meta.resolved_model.as_deref(), Some("vendor/model-real"));
1903 assert!(meta.current_activity.is_none());
1904 }
1905
1906 #[test]
1907 fn token_usage_accumulates_input_plus_output_across_child_turns() {
1908 let mut app = App::new(test_options(), &Config::default());
1909 let route = test_route(
1910 codewhale_config::ProviderKind::Deepseek,
1911 "deepseek-v4-flash",
1912 );
1913 handle_subagent_mailbox(
1914 &mut app,
1915 1,
1916 &MailboxMessage::TokenUsage {
1917 record: None,
1918 agent_id: "agent_spend".to_string(),
1919 source_id: "response-1".to_string(),
1920 route: Box::new(route.clone()),
1921 usage: codewhale_models::Usage {
1922 input_tokens: 1_000,
1923 output_tokens: 40,
1924 ..Default::default()
1925 },
1926 },
1927 );
1928 handle_subagent_mailbox(
1929 &mut app,
1930 2,
1931 &MailboxMessage::TokenUsage {
1932 record: None,
1933 agent_id: "agent_spend".to_string(),
1934 source_id: "response-2".to_string(),
1935 route: Box::new(route),
1936 usage: codewhale_models::Usage {
1937 input_tokens: 2_000,
1938 output_tokens: 60,
1939 ..Default::default()
1940 },
1941 },
1942 );
1943
1944 assert_eq!(
1945 app.agent_progress_meta["agent_spend"].received_tokens,
1946 Some(3_100),
1947 "work-bar tally must match worker budget total (input+output)"
1948 );
1949 }
1950
1951 #[test]
1952 fn typed_mailbox_lifecycle_projects_running_waiting_failed_and_done() {
1953 let mut app = App::new(test_options(), &Config::default());
1954
1955 assert!(handle_subagent_mailbox(
1956 &mut app,
1957 1,
1958 &MailboxMessage::started("agent_running", FleetRole::Worker),
1959 ));
1960 assert_eq!(
1961 app.agent_progress_meta["agent_running"]
1962 .current_activity
1963 .as_ref()
1964 .map(|activity| activity.status),
1965 Some(AgentCurrentActivityStatus::Running)
1966 );
1967
1968 assert!(handle_subagent_mailbox(
1969 &mut app,
1970 2,
1971 &MailboxMessage::ToolCallStarted {
1972 agent_id: "agent_running".to_string(),
1973 tool_name: "read_file".to_string(),
1974 step: 3,
1975 },
1976 ));
1977 let running = app.agent_progress_meta["agent_running"]
1978 .current_activity
1979 .as_ref()
1980 .expect("running tool projection");
1981 assert_eq!(running.status, AgentCurrentActivityStatus::RunningTool);
1982 assert_eq!(running.current_tool.as_deref(), Some("read_file"));
1983 assert_eq!(running.step, Some(3));
1984
1985 assert!(handle_subagent_mailbox(
1986 &mut app,
1987 3,
1988 &MailboxMessage::Interrupted {
1989 agent_id: "agent_running".to_string(),
1990 reason: "approval needed".to_string(),
1991 },
1992 ));
1993 let waiting = app.agent_progress_meta["agent_running"]
1994 .current_activity
1995 .as_ref()
1996 .expect("waiting projection");
1997 assert_eq!(waiting.status, AgentCurrentActivityStatus::Waiting);
1998 assert_eq!(waiting.detail.as_deref(), Some("approval needed"));
1999
2000 for (seq, agent_id, terminal, expected) in [
2001 (
2002 4,
2003 "agent_failed",
2004 MailboxMessage::Failed {
2005 agent_id: "agent_failed".to_string(),
2006 error: "verification failed".to_string(),
2007 },
2008 AgentCurrentActivityStatus::Failed,
2009 ),
2010 (
2011 5,
2012 "agent_done",
2013 MailboxMessage::Completed {
2014 agent_id: "agent_done".to_string(),
2015 summary: "verification complete".to_string(),
2016 },
2017 AgentCurrentActivityStatus::Done,
2018 ),
2019 ] {
2020 assert!(handle_subagent_mailbox(&mut app, seq, &terminal));
2021 assert_eq!(
2022 app.agent_progress_meta[agent_id]
2023 .current_activity
2024 .as_ref()
2025 .map(|activity| activity.status),
2026 Some(expected)
2027 );
2028 }
2029 }
2030
2031 #[test]
2032 fn reconcile_projects_typed_status_when_activity_detail_is_missing() {
2033 let mut app = App::new(test_options(), &Config::default());
2034 let mut agent = subagent_result("agent_model_wait", SubAgentStatus::Running);
2035 agent.worker_status = Some(AgentWorkerStatus::ModelWait);
2036 app.subagent_cache.push(agent);
2037
2038 reconcile_subagent_activity_state_at(&mut app, Instant::now());
2039
2040 let activity = app.agent_progress_meta["agent_model_wait"]
2041 .current_activity
2042 .as_ref()
2043 .expect("typed activity fallback");
2044 assert_eq!(activity.status, AgentCurrentActivityStatus::ModelWait);
2045 assert_eq!(activity.detail, None);
2046 }
2047
2048 #[test]
2049 fn mailbox_compact_projection_redacts_secrets_and_control_sequences() {
2050 let mut app = App::new(test_options(), &Config::default());
2051 let agent_id = "agent_safe_projection";
2052 assert!(handle_subagent_mailbox(
2053 &mut app,
2054 1,
2055 &MailboxMessage::started(agent_id, FleetRole::Worker),
2056 ));
2057 let secret = "sk-mailbox-secret-1234567890";
2058 let raw = format!(
2059 "\u{1b}[31mrunning\u{1b}[0m\napi_key={secret}\n\u{1b}]8;;https://example.invalid\u{7}details\u{1b}]8;;\u{7}\u{1}"
2060 );
2061 assert!(handle_subagent_mailbox(
2062 &mut app,
2063 2,
2064 &MailboxMessage::progress(agent_id, raw.clone()),
2065 ));
2066
2067 let activity = app.agent_progress_meta[agent_id]
2068 .current_activity
2069 .as_ref()
2070 .expect("safe activity projection");
2071 let detail = activity.detail.as_deref().expect("safe detail");
2072 assert!(detail.contains("[redacted]"), "{detail:?}");
2073 assert!(!detail.contains(secret), "{detail:?}");
2074 assert!(!detail.contains('\u{1b}'), "{detail:?}");
2075 assert!(!detail.contains("example.invalid"), "{detail:?}");
2076
2077 let card_index = app.subagent_card_index[agent_id];
2078 let HistoryCell::SubAgent(SubAgentCell::Delegate(card)) = &app.history[card_index] else {
2079 panic!("expected delegate card");
2080 };
2081 let rendered = card
2082 .render_lines(120, &codewhale_palette::UI_THEME)
2083 .into_iter()
2084 .flat_map(|line| line.spans.into_iter().map(|span| span.content.into_owned()))
2085 .collect::<String>();
2086 assert!(rendered.contains("[redacted]"), "{rendered:?}");
2087 assert!(!rendered.contains(secret), "{rendered:?}");
2088 assert!(!rendered.contains('\u{1b}'), "{rendered:?}");
2089 assert!(!rendered.contains("example.invalid"), "{rendered:?}");
2090 assert!(
2091 raw.contains(secret),
2092 "source mailbox payload stays untouched"
2093 );
2094 assert!(
2095 raw.contains('\u{1b}'),
2096 "source mailbox payload stays untouched"
2097 );
2098 }
2099
2100 #[test]
2101 fn reconcile_keeps_progress_only_rows_until_cache_knows_the_agent() {
2102 let mut app = App::new(test_options(), &Config::default());
2103
2104 // A progress-first agent: its AgentSpawned/AgentList delivery was
2105 // dropped under channel pressure, so the authoritative cache has
2106 // never seen it. Its sidebar row must survive reconciliation.
2107 app.agent_progress
2108 .insert("agent_orphan".to_string(), "step 2/10".to_string());
2109 app.agent_progress_meta.insert(
2110 "agent_orphan".to_string(),
2111 AgentProgressMeta {
2112 parent_run_id: None,
2113 spawn_depth: 0,
2114 ..AgentProgressMeta::default()
2115 },
2116 );
2117
2118 // A terminal agent the cache DOES know about: its stale progress row
2119 // must still be evicted.
2120 app.subagent_cache
2121 .push(subagent_result("agent_done", SubAgentStatus::Completed));
2122 app.agent_progress
2123 .insert("agent_done".to_string(), "step 9/10".to_string());
2124 app.agent_progress_meta.insert(
2125 "agent_done".to_string(),
2126 AgentProgressMeta {
2127 parent_run_id: None,
2128 spawn_depth: 0,
2129 ..AgentProgressMeta::default()
2130 },
2131 );
2132
2133 reconcile_subagent_activity_state_at(&mut app, Instant::now());
2134
2135 assert!(
2136 app.agent_progress.contains_key("agent_orphan"),
2137 "progress-only agent unknown to the cache must survive reconcile"
2138 );
2139 assert!(
2140 app.agent_progress_meta.contains_key("agent_orphan"),
2141 "progress-only meta unknown to the cache must survive reconcile"
2142 );
2143 assert!(
2144 !app.agent_progress.contains_key("agent_done"),
2145 "cache-known terminal agent progress must still be evicted"
2146 );
2147 assert_eq!(
2148 app.agent_progress_meta["agent_done"]
2149 .current_activity
2150 .as_ref()
2151 .map(|activity| activity.status),
2152 Some(AgentCurrentActivityStatus::Done),
2153 "cache-known terminal agents retain a bounded terminal projection"
2154 );
2155
2156 // Once the authoritative cache reports the orphan as terminal, the
2157 // normal eviction applies and the row is released.
2158 app.subagent_cache
2159 .push(subagent_result("agent_orphan", SubAgentStatus::Completed));
2160 reconcile_subagent_activity_state_at(&mut app, Instant::now());
2161 assert!(
2162 !app.agent_progress.contains_key("agent_orphan"),
2163 "cache supersedes the progress-only row once it knows the agent"
2164 );
2165 assert_eq!(
2166 app.agent_progress_meta["agent_orphan"]
2167 .current_activity
2168 .as_ref()
2169 .map(|activity| activity.status),
2170 Some(AgentCurrentActivityStatus::Done)
2171 );
2172 }
2173
2174 #[test]
2175 fn terminal_cards_archive_after_forty_five_seconds_without_losing_history() {
2176 let mut app = App::new(test_options(), &Config::default());
2177 let agent_id = "agent_archive";
2178 assert!(handle_subagent_mailbox(
2179 &mut app,
2180 1,
2181 &MailboxMessage::started(agent_id, FleetRole::Worker),
2182 ));
2183 app.subagent_cache
2184 .push(subagent_result(agent_id, SubAgentStatus::Completed));
2185
2186 let observed = Instant::now();
2187 reconcile_subagent_activity_state_at(&mut app, observed);
2188 reconcile_subagent_activity_state_at(&mut app, observed + SUBAGENT_TERMINAL_CARD_TTL);
2189 assert!(
2190 app.subagent_cache
2191 .iter()
2192 .any(|agent| agent.agent_id == agent_id),
2193 "the terminal card stays visible through its full 45-second grace period"
2194 );
2195
2196 reconcile_subagent_activity_state_at(
2197 &mut app,
2198 observed + SUBAGENT_TERMINAL_CARD_TTL + Duration::from_millis(1),
2199 );
2200 assert!(
2201 !app.subagent_cache
2202 .iter()
2203 .any(|agent| agent.agent_id == agent_id),
2204 "the compact live cache must archive the settled card after the grace period"
2205 );
2206 assert!(
2207 app.subagent_card_index.contains_key(agent_id),
2208 "archiving a compact card must not delete its transcript record"
2209 );
2210 }
2211
2212 #[test]
2213 fn apply_subagent_terminal_projection_clears_live_progress_and_card_state() {
2214 let mut app = App::new(test_options(), &Config::default());
2215 let started = MailboxMessage::started("agent_done", FleetRole::Worker);
2216 assert!(handle_subagent_mailbox(&mut app, 1, &started));
2217 let card_idx = app.subagent_card_index["agent_done"];
2218 let initial_revision = app.history_revisions[card_idx];
2219
2220 app.subagent_cache
2221 .push(subagent_result("agent_done", SubAgentStatus::Running));
2222 app.agent_progress
2223 .insert("agent_done".to_string(), "step 4/10".to_string());
2224 app.agent_progress_meta.insert(
2225 "agent_done".to_string(),
2226 AgentProgressMeta {
2227 parent_run_id: None,
2228 spawn_depth: 0,
2229 ..AgentProgressMeta::default()
2230 },
2231 );
2232
2233 assert!(apply_subagent_terminal_projection(
2234 &mut app,
2235 "agent_done",
2236 SubAgentStatus::Cancelled,
2237 Some("cancelled by user".to_string())
2238 ));
2239
2240 assert!(!app.agent_progress.contains_key("agent_done"));
2241 assert_eq!(
2242 app.agent_progress_meta["agent_done"]
2243 .current_activity
2244 .as_ref()
2245 .map(|activity| activity.status),
2246 Some(AgentCurrentActivityStatus::Canceled)
2247 );
2248 let agent = app
2249 .subagent_cache
2250 .iter()
2251 .find(|agent| agent.agent_id == "agent_done")
2252 .expect("projected agent remains cached");
2253 assert_eq!(agent.status, SubAgentStatus::Cancelled);
2254 assert_eq!(agent.worker_status, Some(AgentWorkerStatus::Cancelled));
2255 assert_eq!(agent.result.as_deref(), Some("cancelled by user"));
2256 assert_eq!(running_agent_count(&app), 0);
2257 assert_ne!(
2258 app.history_revisions[card_idx], initial_revision,
2259 "terminal projection should invalidate the stale running card"
2260 );
2261 match &app.history[card_idx] {
2262 HistoryCell::SubAgent(SubAgentCell::Delegate(card)) => {
2263 assert_eq!(card.status, AgentLifecycle::Cancelled);
2264 }
2265 cell => panic!("expected delegate card, got {cell:?}"),
2266 }
2267 }
2268
2269 #[test]
2270 fn parent_stop_status_names_only_workers_that_continue_detached() {
2271 let mut app = App::new(test_options(), &Config::default());
2272 app.subagent_cache
2273 .push(subagent_result("agent_b", SubAgentStatus::Running));
2274 app.subagent_cache
2275 .push(subagent_result("agent_done", SubAgentStatus::Completed));
2276 app.agent_progress
2277 .insert("agent_a".to_string(), "running tool".to_string());
2278 app.agent_label_map
2279 .insert("agent_a".to_string(), "Agent 1".to_string());
2280 app.agent_label_map
2281 .insert("agent_b".to_string(), "Southern Right".to_string());
2282 app.agent_label_map
2283 .insert("agent_done".to_string(), "Finished worker".to_string());
2284
2285 let status = parent_stop_status(&app, "Request cancelled");
2286 assert_eq!(
2287 status,
2288 "Request cancelled; detached workers continue (none canceled): Agent 1, Southern Right"
2289 );
2290 assert!(!status.contains("Finished worker"));
2291 }
2292
2293 #[test]
2294 fn parent_stop_status_is_unchanged_without_detached_workers() {
2295 let app = App::new(test_options(), &Config::default());
2296 assert_eq!(
2297 parent_stop_status(&app, "Request cancelled"),
2298 "Request cancelled"
2299 );
2300 }
2301
2302 #[test]
2303 fn completion_before_started_allocates_recovery_delegate_card() {
2304 let mut app = App::new(test_options(), &Config::default());
2305 let completed = MailboxMessage::Completed {
2306 agent_id: "agent_early".to_string(),
2307 summary: "recovered after early completion".to_string(),
2308 };
2309 assert!(
2310 handle_subagent_mailbox(&mut app, 1, &completed),
2311 "completion-first delivery must still open a card"
2312 );
2313 assert!(app.subagent_card_index.contains_key("agent_early"));
2314
2315 let started = MailboxMessage::started("agent_early", FleetRole::Worker);
2316 assert!(handle_subagent_mailbox(&mut app, 2, &started));
2317 match app.history.last() {
2318 Some(HistoryCell::SubAgent(SubAgentCell::Delegate(card))) => {
2319 assert_eq!(card.agent_id, "agent_early");
2320 assert_ne!(card.agent_type, "…");
2321 }
2322 other => panic!("expected delegate card, got {other:?}"),
2323 }
2324 }
2325
2326 /// #4810: each child card carries that child's own ledger — never the
2327 /// parent's, never a sibling's, and never as transcript messages.
2328 #[test]
2329 fn sibling_child_cards_render_disjoint_todo_lists() {
2330 use codewhale_engine::tools::todo::{TodoItem, TodoListSnapshot, TodoStatus};
2331
2332 fn snapshot(id: u32, content: &str) -> TodoListSnapshot {
2333 TodoListSnapshot {
2334 items: vec![TodoItem {
2335 id,
2336 content: content.to_string(),
2337 status: TodoStatus::InProgress,
2338 }],
2339 completion_pct: 0,
2340 in_progress_id: Some(id),
2341 }
2342 }
2343
2344 fn card_text(app: &App, agent_id: &str) -> String {
2345 let idx = app.subagent_card_index[agent_id];
2346 let HistoryCell::SubAgent(SubAgentCell::Delegate(card)) = &app.history[idx] else {
2347 panic!("expected a delegate card for {agent_id}");
2348 };
2349 assert_eq!(card.agent_id, agent_id);
2350 card.render_lines(120, &app.ui_theme)
2351 .into_iter()
2352 .flat_map(|line| line.spans.into_iter().map(|span| span.content.into_owned()))
2353 .collect()
2354 }
2355
2356 let mut app = App::new(test_options(), &Config::default());
2357 // The parent's own ledger exists and must never surface on a child.
2358 let parent_item = "PARENT ONLY: ship the release";
2359
2360 for (seq, id) in ["agent_left", "agent_right"].into_iter().enumerate() {
2361 assert!(handle_subagent_mailbox(
2362 &mut app,
2363 seq as u64 + 1,
2364 &MailboxMessage::started(id, FleetRole::Worker),
2365 ));
2366 }
2367 assert!(handle_subagent_mailbox(
2368 &mut app,
2369 3,
2370 &MailboxMessage::WorkState {
2371 agent_id: "agent_left".to_string(),
2372 todo: snapshot(1, "LEFT: map the call sites"),
2373 },
2374 ));
2375 assert!(handle_subagent_mailbox(
2376 &mut app,
2377 4,
2378 &MailboxMessage::WorkState {
2379 agent_id: "agent_right".to_string(),
2380 todo: snapshot(1, "RIGHT: write the migration"),
2381 },
2382 ));
2383
2384 let left = card_text(&app, "agent_left");
2385 let right = card_text(&app, "agent_right");
2386 assert!(left.contains("LEFT: map the call sites"), "{left}");
2387 assert!(!left.contains("RIGHT:"), "sibling leak: {left}");
2388 assert!(!left.contains(parent_item), "parent leak: {left}");
2389 assert!(right.contains("RIGHT: write the migration"), "{right}");
2390 assert!(!right.contains("LEFT:"), "sibling leak: {right}");
2391 assert!(!right.contains(parent_item), "parent leak: {right}");
2392
2393 // A nested child of agent_left gets its own card and its own ledger;
2394 // neither its parent's card nor its uncle's card absorbs it.
2395 assert!(handle_subagent_mailbox(
2396 &mut app,
2397 5,
2398 &MailboxMessage::started("agent_nested", FleetRole::Worker),
2399 ));
2400 assert!(handle_subagent_mailbox(
2401 &mut app,
2402 6,
2403 &MailboxMessage::WorkState {
2404 agent_id: "agent_nested".to_string(),
2405 todo: snapshot(1, "NESTED: read one file"),
2406 },
2407 ));
2408 assert!(card_text(&app, "agent_nested").contains("NESTED: read one file"));
2409 assert!(!card_text(&app, "agent_left").contains("NESTED:"));
2410 assert!(!card_text(&app, "agent_right").contains("NESTED:"));
2411
2412 // Nothing entered the transcript as an ordinary message: every To-do
2413 // row lives inside a sub-agent card.
2414 assert!(
2415 !app.history.iter().any(|cell| {
2416 !matches!(cell, HistoryCell::SubAgent(_))
2417 && format!("{cell:?}").contains("map the call sites")
2418 }),
2419 "child To-do must not become an ordinary transcript message"
2420 );
2421 }
2422
2423 /// Work state is a ledger fact, not an activity transition: it must not
2424 /// invent or overwrite what the agent is currently doing.
2425 #[test]
2426 fn work_state_updates_todos_remaining_without_rewriting_activity() {
2427 use codewhale_engine::tools::todo::{TodoItem, TodoListSnapshot, TodoStatus};
2428
2429 let mut app = App::new(test_options(), &Config::default());
2430 assert!(handle_subagent_mailbox(
2431 &mut app,
2432 1,
2433 &MailboxMessage::started("agent_todos", FleetRole::Worker),
2434 ));
2435 assert!(handle_subagent_mailbox(
2436 &mut app,
2437 2,
2438 &MailboxMessage::ToolCallStarted {
2439 agent_id: "agent_todos".to_string(),
2440 tool_name: "read_file".to_string(),
2441 step: 1,
2442 },
2443 ));
2444 assert!(handle_subagent_mailbox(
2445 &mut app,
2446 3,
2447 &MailboxMessage::WorkState {
2448 agent_id: "agent_todos".to_string(),
2449 todo: TodoListSnapshot {
2450 items: vec![
2451 TodoItem {
2452 id: 1,
2453 content: "done already".to_string(),
2454 status: TodoStatus::Completed,
2455 },
2456 TodoItem {
2457 id: 2,
2458 content: "still cooking".to_string(),
2459 status: TodoStatus::InProgress,
2460 },
2461 TodoItem {
2462 id: 3,
2463 content: "not yet".to_string(),
2464 status: TodoStatus::Pending,
2465 },
2466 ],
2467 completion_pct: 33,
2468 in_progress_id: Some(2),
2469 },
2470 },
2471 ));
2472
2473 let meta = &app.agent_progress_meta["agent_todos"];
2474 assert_eq!(meta.todos_remaining, Some(2));
2475 let activity = meta.current_activity.as_ref().expect("activity");
2476 assert_eq!(activity.status, AgentCurrentActivityStatus::RunningTool);
2477 assert_eq!(activity.current_tool.as_deref(), Some("read_file"));
2478
2479 // Empty publish clears the chip source (no list → no figure).
2480 assert!(handle_subagent_mailbox(
2481 &mut app,
2482 4,
2483 &MailboxMessage::WorkState {
2484 agent_id: "agent_todos".to_string(),
2485 todo: TodoListSnapshot::default(),
2486 },
2487 ));
2488 assert_eq!(app.agent_progress_meta["agent_todos"].todos_remaining, None);
2489 }
2490
2491 #[test]
2492 fn work_state_envelope_does_not_rewrite_current_activity() {
2493 let mut app = App::new(test_options(), &Config::default());
2494 assert!(handle_subagent_mailbox(
2495 &mut app,
2496 1,
2497 &MailboxMessage::started("agent_x", FleetRole::Worker),
2498 ));
2499 assert!(handle_subagent_mailbox(
2500 &mut app,
2501 2,
2502 &MailboxMessage::ToolCallStarted {
2503 agent_id: "agent_x".to_string(),
2504 tool_name: "read_file".to_string(),
2505 step: 2,
2506 },
2507 ));
2508 assert!(handle_subagent_mailbox(
2509 &mut app,
2510 3,
2511 &MailboxMessage::WorkState {
2512 agent_id: "agent_x".to_string(),
2513 todo: codewhale_engine::tools::todo::TodoListSnapshot {
2514 items: vec![codewhale_engine::tools::todo::TodoItem {
2515 id: 1,
2516 content: "keep reading".to_string(),
2517 status: codewhale_engine::tools::todo::TodoStatus::InProgress,
2518 }],
2519 completion_pct: 0,
2520 in_progress_id: Some(1),
2521 },
2522 },
2523 ));
2524
2525 let activity = app.agent_progress_meta["agent_x"]
2526 .current_activity
2527 .as_ref()
2528 .expect("activity");
2529 assert_eq!(activity.status, AgentCurrentActivityStatus::RunningTool);
2530 assert_eq!(activity.current_tool.as_deref(), Some("read_file"));
2531 }
2532
2533 /// Displayed child ledger text goes through the same redaction the rest of
2534 /// the child's displayed strings do.
2535 #[test]
2536 fn work_state_item_text_is_redacted_before_it_reaches_the_card() {
2537 let mut app = App::new(test_options(), &Config::default());
2538 assert!(handle_subagent_mailbox(
2539 &mut app,
2540 1,
2541 &MailboxMessage::started("agent_secret", FleetRole::Worker),
2542 ));
2543 let secret = "sk-mailbox-secret-1234567890";
2544 assert!(handle_subagent_mailbox(
2545 &mut app,
2546 2,
2547 &MailboxMessage::WorkState {
2548 agent_id: "agent_secret".to_string(),
2549 todo: codewhale_engine::tools::todo::TodoListSnapshot {
2550 items: vec![codewhale_engine::tools::todo::TodoItem {
2551 id: 4,
2552 content: format!("rotate api_key={secret}"),
2553 status: codewhale_engine::tools::todo::TodoStatus::InProgress,
2554 }],
2555 completion_pct: 0,
2556 in_progress_id: Some(4),
2557 },
2558 },
2559 ));
2560
2561 let idx = app.subagent_card_index["agent_secret"];
2562 let HistoryCell::SubAgent(SubAgentCell::Delegate(card)) = &app.history[idx] else {
2563 panic!("expected delegate card");
2564 };
2565 let rendered: String = card
2566 .render_lines(120, &codewhale_palette::UI_THEME)
2567 .into_iter()
2568 .flat_map(|line| line.spans.into_iter().map(|span| span.content.into_owned()))
2569 .collect();
2570 assert!(!rendered.contains(secret), "{rendered}");
2571 assert!(rendered.contains("[redacted]"), "{rendered}");
2572 assert!(
2573 rendered.contains("#4"),
2574 "item identity is preserved: {rendered}"
2575 );
2576 }
2577
2578 #[test]
2579 fn fanout_completion_burst_preserves_started_to_done_ordering() {
2580 let mut app = App::new(test_options(), &Config::default());
2581 app.pending_subagent_dispatch = Some("rlm_eval".to_string());
2582 for (seq, id) in ["agent_a", "agent_b"].into_iter().enumerate() {
2583 assert!(handle_subagent_mailbox(
2584 &mut app,
2585 seq as u64 + 1,
2586 &MailboxMessage::started(id, FleetRole::Scout),
2587 ));
2588 }
2589 assert!(handle_subagent_mailbox(
2590 &mut app,
2591 3,
2592 &MailboxMessage::Completed {
2593 agent_id: "agent_a".to_string(),
2594 summary: "a done".to_string(),
2595 },
2596 ));
2597 let Some(HistoryCell::SubAgent(SubAgentCell::Fanout(card))) = app.history.last() else {
2598 panic!("expected fanout card");
2599 };
2600 assert_eq!(card.workers.len(), 2);
2601 assert_eq!(card.workers[0].status, AgentLifecycle::Completed);
2602 assert_eq!(card.workers[1].status, AgentLifecycle::Running);
2603 }
2604 }
2605
2605 lines RUST