返回 CodeWhale
model.rs
根目录 / crates / tui / src / tui / work_surface / model.rs
1 use std::collections::HashSet;
2 use std::fmt::Write as _;
3 use std::path::{Component, Path};
4 use std::time::Instant;
5
6 use codewhale_localization::{Locale, MessageId, tr};
7 use ratatui::layout::Rect;
8
9 use crate::tui::app::{
10 AgentCurrentActivityStatus, AgentProgressMeta, App, SidebarRowAction, TaskPanelEntry,
11 TaskPanelEntryKind,
12 };
13 use crate::tui::background_indicator::is_live_shell_entry;
14 use crate::tui::history::{
15 FileActivityKind, FileActivitySummary, FileMutationReceipt, HistoryCell, SubAgentCell, ToolCell,
16 };
17 use crate::tui::widgets::agent_card::AgentLifecycle;
18 use codewhale_engine::tools::subagent::{AgentWorkerStatus, SubAgentResult, SubAgentStatus};
19 use codewhale_engine::work_graph::{
20 AcceptanceRequirement, EdgeKind, EvidenceKind, EvidenceKindTag, NodeKind, NodeState,
21 OperationBinding, OwnerState, Provenance, WorkGraphSnapshot, WorkNode,
22 };
23 use codewhale_execpolicy::canonical_action::canonical_action_alias;
24 use codewhale_runtime::settings::InlineDiffMode;
25 use codewhale_tui_kit::menu_style::{StatusKind, status_mark};
26
27 /// Persisted Ocean work-surface placement. Bottom is deliberately absent: the
28 /// composer and phase footer own the shell's lower edge. `Off` hides the rail
29 /// outright (rail unification, 0.9.4).
30 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
31 pub enum WorkSurfacePlacement {
32 /// Under the composer — the default (round 3, 2026-09-01: the bar's
33 /// information lives below the composer, so scrolling up reads as
34 /// intentional history).
35 #[default]
36 Bottom,
37 Top,
38 Left,
39 Right,
40 Off,
41 }
42
43 impl WorkSurfacePlacement {
44 /// Strip placements render as a horizontal band; side placements as a
45 /// rail. Bottom shares Top's auto-fit height math — only its position
46 /// in the frame differs.
47 #[must_use]
48 pub const fn is_strip(self) -> bool {
49 matches!(self, Self::Top | Self::Bottom)
50 }
51 }
52
53 /// Which view the bottom dock shows. Orthogonal to placement: the user picks
54 /// *where* the dock sits and *what* it shows.
55 ///
56 /// One bottom view, cycled in this order (founder redirect, 2026-09-02):
57 /// agents → tasks → background → files → notepad → context → git → price.
58 /// `Pinned` folded into `Tasks` (the goal heading rides the tasks view on
59 /// side placements); `pinned` stays accepted as a setting word.
60 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
61 pub enum RailPanel {
62 /// The agent roster: one row per sub-agent, retained after completion.
63 Agents,
64 /// The to-do list: plan-step rows from the work graph.
65 #[default]
66 Tasks,
67 /// Background shells and durable tasks. Scheduled work has its own manager.
68 Background,
69 /// Live workspace PTYs shared with the model, with explicit input focus.
70 Terminal,
71 /// Files edited this session (`+/−`) and files read into context.
72 Files,
73 /// Per-workspace plain-text notes (`.codewhale/notes.md`).
74 Notepad,
75 /// The context budget: used/limit, compaction threshold, breakdown.
76 Context,
77 /// Branch, ahead/behind, dirty count, last commits.
78 Git,
79 /// Session cost, per-agent cost, cache hit %, model rate.
80 Price,
81 }
82
83 impl RailPanel {
84 /// Cycle order — also the tab order in the dock strip.
85 pub const ORDER: [RailPanel; 9] = [
86 Self::Tasks,
87 Self::Agents,
88 Self::Background,
89 Self::Terminal,
90 Self::Files,
91 Self::Notepad,
92 Self::Context,
93 Self::Git,
94 Self::Price,
95 ];
96
97 /// Views the dock opens on its own when they have content and the user
98 /// has not picked one: the to-do list first, then live agents, then
99 /// background work (founder, 2026-09-03: "To-do and Agents as the first
100 /// two, opening on To-do"). The others open only when cycled to.
101 pub const AUTO_ORDER: [RailPanel; 3] = [Self::Tasks, Self::Agents, Self::Background];
102
103 #[must_use]
104 pub fn next(self) -> Self {
105 let index = Self::ORDER.iter().position(|p| *p == self).unwrap_or(0);
106 Self::ORDER[(index + 1) % Self::ORDER.len()]
107 }
108
109 #[must_use]
110 pub fn prev(self) -> Self {
111 let index = Self::ORDER.iter().position(|p| *p == self).unwrap_or(0);
112 Self::ORDER[(index + Self::ORDER.len() - 1) % Self::ORDER.len()]
113 }
114 }
115
116 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
117 pub(super) enum DockTabTarget {
118 Panel(RailPanel),
119 Close,
120 }
121
122 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
123 pub(super) struct DockTabHitbox {
124 pub(super) target: DockTabTarget,
125 pub(super) area: Rect,
126 }
127
128 impl RailPanel {
129 #[must_use]
130 pub fn parse(value: &str) -> Self {
131 match value.trim().to_ascii_lowercase().as_str() {
132 "agents" | "subagents" | "sub-agents" => Self::Agents,
133 "tasks" | "todo" | "todos" => Self::Tasks,
134 "background" | "shells" | "jobs" => Self::Background,
135 "terminal" | "terminals" => Self::Terminal,
136 "files" | "changes" => Self::Files,
137 "notepad" | "notes" => Self::Notepad,
138 "context" | "session" => Self::Context,
139 "git" | "branch" => Self::Git,
140 "price" | "cost" => Self::Price,
141 _ => Self::Tasks,
142 }
143 }
144
145 #[must_use]
146 pub const fn as_setting(self) -> &'static str {
147 match self {
148 Self::Agents => "agents",
149 Self::Tasks => "tasks",
150 Self::Background => "background",
151 Self::Terminal => "terminal",
152 Self::Files => "files",
153 Self::Notepad => "notepad",
154 Self::Context => "context",
155 Self::Git => "git",
156 Self::Price => "price",
157 }
158 }
159
160 /// Tab label. CAPS on purpose (founder ruling 2026-09-03): the tabs are
161 /// the dock's primary navigation and lowercase nouns read as status
162 /// text beside them. The plan-step list reads TODO, not TASKS — the
163 /// Background panel already holds running tasks, so TASKS collides
164 /// with it. `as_setting()` stays lowercase — it is the persisted
165 /// value, never a label.
166 #[must_use]
167 pub const fn title(self) -> &'static str {
168 match self {
169 Self::Agents => "AGENTS",
170 Self::Tasks => "TODO",
171 Self::Background => "BACKGROUND",
172 Self::Terminal => "TERMINAL",
173 Self::Files => "FILES",
174 Self::Notepad => "NOTEPAD",
175 Self::Context => "CONTEXT",
176 Self::Git => "GIT",
177 Self::Price => "PRICE",
178 }
179 }
180 }
181
182 impl WorkSurfacePlacement {
183 #[must_use]
184 pub fn parse(value: &str) -> Self {
185 match value.trim().to_ascii_lowercase().as_str() {
186 "top" => Self::Top,
187 "left" => Self::Left,
188 "right" => Self::Right,
189 "off" => Self::Off,
190 _ => Self::Bottom,
191 }
192 }
193
194 #[must_use]
195 pub const fn as_setting(self) -> &'static str {
196 match self {
197 Self::Bottom => "bottom",
198 Self::Top => "top",
199 Self::Left => "left",
200 Self::Right => "right",
201 Self::Off => "off",
202 }
203 }
204 }
205
206 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
207 pub struct WorkRowId(pub String);
208
209 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
210 pub(super) enum WorkTone {
211 Heading,
212 Live,
213 /// Consequential and waiting on someone — Cognition, not Failure. A to-do
214 /// blocked on your answer has not failed.
215 Attention,
216 /// Something actually failed. The only tone that spends Failure red.
217 Failure,
218 Success,
219 Muted,
220 }
221
222 #[derive(Debug, Clone)]
223 pub(super) struct WorkRow {
224 pub id: WorkRowId,
225 pub mark: &'static str,
226 pub label: String,
227 pub detail: String,
228 pub tone: WorkTone,
229 pub selectable: bool,
230 pub primary_action: Option<SidebarRowAction>,
231 /// Present only on sub-agent rows. Carries the fields the fleet row paints
232 /// beyond `label`, so the renderer can drop them one at a time as the
233 /// surface narrows instead of truncating one pre-joined string.
234 pub agent: Option<AgentRowFacts>,
235 }
236
237 /// The parts of a sub-agent row that are laid out as their own columns.
238 ///
239 /// `label` already carries the preferred identity column (nesting indent,
240 /// nickname when the agent has one, `(+N)` child count). This carries the
241 /// rest: the role-only spelling of that same column, what the agent is doing,
242 /// and the right-aligned receipt.
243 #[derive(Debug, Clone, Default, PartialEq, Eq)]
244 pub(super) struct AgentRowFacts {
245 /// The identity column spelled with the fleet role instead of the
246 /// nickname. Equal to `label` when the agent has no nickname. The
247 /// renderer falls back to this when a nickname is too wide for the
248 /// identity column — a name is shown whole or not at all.
249 pub role_label: String,
250 /// The status word (`running`, `completed`, `failed`, …) painted as its
251 /// own column. The glyph carries the same fact for scanning; the word is
252 /// what makes the row legible without memorizing glyph vocabulary
253 /// (owner regression report, 2026-08-04).
254 pub status: String,
255 /// What the agent was sent to do.
256 pub objective: String,
257 /// Wall-clock seconds, frozen once the agent is observed terminal so a
258 /// finished agent stops ticking. `None` when no duration is known.
259 pub elapsed_secs: Option<u64>,
260 /// Model from the child's frozen spawn route or a later effective-route
261 /// usage envelope; never inferred from the parent session's model.
262 pub model: Option<String>,
263 /// Tokens used by the child. `None` means *genuinely unknown* —
264 /// the row then renders no token figure rather than claiming zero.
265 pub tokens: Option<u64>,
266 /// Unsettled items on this child's to-do list. `None` when no list has
267 /// been published; `Some(0)` means the list exists and is fully settled
268 /// (the strip still hides a zero chip — see `agent_receipt`).
269 pub todos_remaining: Option<u32>,
270 /// Whether this row on its own keeps the work dock open
271 /// ([`live_agent_row_count`]). Running, queued and answerable work does;
272 /// a finished agent does not.
273 ///
274 /// Typed at every construction site, never sniffed back out of `status` —
275 /// a renderer must not infer lifecycle from an English word
276 /// (`crates/tui/AGENTS.md`). The derivation deliberately differs by
277 /// source because the sources carry different facts: a card in the
278 /// 45-second live cache is *news*, so a fresh failure re-opens the dock
279 /// long enough to be seen, while the same worker's retained receipt stays
280 /// readable for an hour (`COMPLETED_AGENT_RETENTION`) and must not pin the
281 /// dock open for the rest of the session.
282 pub holds_dock_open: bool,
283 }
284
285 #[derive(Debug, Clone)]
286 pub(super) struct WorkHitbox {
287 pub id: WorkRowId,
288 pub row_y: u16,
289 }
290
291 #[derive(Debug, Clone)]
292 enum WorkSourceState {
293 Error(String),
294 Disconnected,
295 }
296
297 impl WorkSourceState {
298 const fn label(&self) -> &'static str {
299 match self {
300 Self::Error(_) => "error",
301 Self::Disconnected => "disconnected",
302 }
303 }
304
305 fn detail(&self) -> &str {
306 match self {
307 Self::Error(error) => error,
308 Self::Disconnected => "Work Graph runtime is not attached",
309 }
310 }
311 }
312
313 /// Live Work summary recent-only presentation lifetime (#4688).
314 pub(super) const RECENT_ONLY_TTL_MS: u64 = 4_000;
315 /// Settled file/search/write receipt lifetime in the live strip (#4690).
316 pub(super) const ACTIVITY_RECEIPT_TTL_MS: u64 = 3_000;
317 pub(super) const TOP_HEIGHT_MIN: u16 = codewhale_runtime::settings::WORK_SURFACE_TOP_HEIGHT_MIN;
318 pub(super) const TOP_HEIGHT_MAX: u16 = codewhale_runtime::settings::WORK_SURFACE_TOP_HEIGHT_MAX;
319 pub(super) const SIDE_WIDTH_MIN: u16 = 26;
320 pub(super) const SIDE_WIDTH_MAX: u16 = 80;
321
322 /// Which restored work rows belong to a prior session instance (#4416).
323 ///
324 /// Decided once per session id and cached: this instance's own later
325 /// autosaves restamp the persisted record, and re-probing after that would
326 /// re-badge restored rows as live work.
327 #[derive(Debug, Clone)]
328 pub(crate) struct SessionInstanceScope {
329 pub(super) session_id: String,
330 pub(super) from_prior_instance: bool,
331 /// Node ids present in the graph supplied at session restore time: the
332 /// restored persisted rows, as opposed to work this instance creates
333 /// afterwards.
334 pub(super) restored_nodes: HashSet<String>,
335 }
336
337 #[derive(Debug, Clone)]
338 pub struct WorkSurfaceState {
339 #[cfg(all(unix, not(target_env = "ohos")))]
340 pub(super) terminal: super::terminal::TerminalDock,
341 pub placement: WorkSurfacePlacement,
342 pub(super) effective_placement: WorkSurfacePlacement,
343 /// Panel selection — orthogonal to placement.
344 pub panel: RailPanel,
345 /// The user picked `panel` (cycle key, tab click, `/workbar <view>`), so
346 /// the auto rule leaves it alone and an empty view still paints. Esc
347 /// clears it and the dock goes back to showing whichever work view has
348 /// content.
349 pub explicit_view: bool,
350 /// The settled file activity `project()` computed this frame for the
351 /// TASKS view. The FILES view and its tab badge read it, so the history
352 /// is scanned once per frame, not once per view (#6565).
353 pub(super) file_activity: SettledFileActivity,
354 pub top_height: u16,
355 pub side_width: u16,
356 pub(super) resizing: bool,
357 pub(super) divider_hovered: bool,
358 pub(super) resize_anchor_column: u16,
359 pub(super) resize_anchor_row: u16,
360 pub(super) resize_anchor_size: u16,
361 /// Focus owner axis — distinct from selection and detail-open.
362 pub focused: bool,
363 /// Keyboard/mouse selection highlight.
364 pub selected: Option<WorkRowId>,
365 /// Which row currently owns an open detail (pager / agent card).
366 pub opened: Option<WorkRowId>,
367 pub scroll_offset: usize,
368 pub last_area: Option<Rect>,
369 pub visible_rows: usize,
370 pub total_rows: usize,
371 pub(super) dock_tabs: Vec<DockTabHitbox>,
372 pub(super) pressed_tab: Option<DockTabTarget>,
373 pub(super) hovered_tab: Option<DockTabTarget>,
374 pub dismissed: bool,
375 pub dismissed_at_rows: usize,
376 /// The auto view measured at dismissal: the dock re-opens when that
377 /// view grows or when the auto rule picks a different one (a worker
378 /// starting while the to-do list was closed is new work).
379 pub(super) dismissed_view: RailPanel,
380 pub(super) hovered: Option<WorkRowId>,
381 pub(super) hitboxes: Vec<WorkHitbox>,
382 pub(super) cached_graph: Option<WorkGraphSnapshot>,
383 pub(super) latest_rows: Vec<WorkRow>,
384 /// Full ranked catalog retained for inspector/history after live chrome expires.
385 pub(super) catalog_rows: Vec<WorkRow>,
386 /// Monotonic origin for presentation lifetimes (not wall-clock epoch).
387 presentation_origin: Instant,
388 /// Optional injected clock (ms since origin) for deterministic tests.
389 presentation_now_ms: Option<u64>,
390 /// When the projection last became recent-only (ms since origin).
391 recent_only_since_ms: Option<u64>,
392 /// Fingerprint of the recent-only set so a new completion can re-surface once.
393 recent_only_fingerprint: u64,
394 /// After TTL or user-turn, keep the live summary collapsed until new actionable work.
395 recent_only_suppressed: bool,
396 /// When the current activity receipt fingerprint first became live.
397 activity_since_ms: Option<u64>,
398 activity_fingerprint: u64,
399 activity_suppressed: bool,
400 /// Bumped on accepted user turns / newly started operations.
401 user_turn_epoch: u64,
402 last_handled_user_turn_epoch: u64,
403 /// Elapsed wall-clock, in ms, captured the first frame each sub-agent was
404 /// observed in a terminal state. The manager's `duration_ms` is
405 /// `started_at.elapsed()` recomputed per snapshot, so it keeps growing
406 /// after an agent finishes; latching the first terminal reading is what
407 /// makes a completed row stop ticking.
408 pub(super) frozen_agent_elapsed_ms: std::collections::HashMap<String, u64>,
409 /// Session-instance ownership of the restored session record (#4416).
410 pub(crate) session_instance: Option<SessionInstanceScope>,
411 /// Test override for the sessions directory the ownership probe reads;
412 /// production resolves the default location lazily.
413 pub(crate) session_owner_probe_dir: Option<std::path::PathBuf>,
414 }
415
416 impl Default for WorkSurfaceState {
417 fn default() -> Self {
418 Self::with_placement(WorkSurfacePlacement::Bottom)
419 }
420 }
421
422 impl WorkSurfaceState {
423 #[must_use]
424 pub(crate) fn is_resizing(&self) -> bool {
425 self.resizing
426 }
427
428 /// The placement actually rendered this frame (after the narrow-terminal
429 /// fallback), for truthful status readouts.
430 #[must_use]
431 pub fn effective_placement(&self) -> WorkSurfacePlacement {
432 self.effective_placement
433 }
434
435 #[must_use]
436 pub fn with_placement(placement: WorkSurfacePlacement) -> Self {
437 Self::with_layout(placement, 3, 30)
438 }
439
440 #[must_use]
441 pub fn with_layout(placement: WorkSurfacePlacement, top_height: u16, side_width: u16) -> Self {
442 Self {
443 placement,
444 effective_placement: placement,
445 panel: RailPanel::default(),
446 #[cfg(all(unix, not(target_env = "ohos")))]
447 terminal: super::terminal::TerminalDock::default(),
448 explicit_view: false,
449 file_activity: SettledFileActivity::default(),
450 top_height: top_height.clamp(TOP_HEIGHT_MIN, TOP_HEIGHT_MAX),
451 side_width: side_width.clamp(SIDE_WIDTH_MIN, SIDE_WIDTH_MAX),
452 resizing: false,
453 divider_hovered: false,
454 resize_anchor_column: 0,
455 resize_anchor_row: 0,
456 resize_anchor_size: 0,
457 focused: false,
458 selected: None,
459 opened: None,
460 scroll_offset: 0,
461 last_area: None,
462 visible_rows: 0,
463 total_rows: 0,
464 dock_tabs: Vec::new(),
465 pressed_tab: None,
466 hovered_tab: None,
467 dismissed: false,
468 dismissed_at_rows: 0,
469 dismissed_view: RailPanel::default(),
470 hovered: None,
471 hitboxes: Vec::new(),
472 cached_graph: None,
473 latest_rows: Vec::new(),
474 catalog_rows: Vec::new(),
475 presentation_origin: Instant::now(),
476 presentation_now_ms: None,
477 recent_only_since_ms: None,
478 recent_only_fingerprint: 0,
479 recent_only_suppressed: false,
480 activity_since_ms: None,
481 activity_fingerprint: 0,
482 activity_suppressed: false,
483 user_turn_epoch: 0,
484 last_handled_user_turn_epoch: 0,
485 frozen_agent_elapsed_ms: std::collections::HashMap::new(),
486 session_instance: None,
487 session_owner_probe_dir: None,
488 }
489 }
490
491 /// Inject a monotonic clock for presentation-lifetime tests.
492 #[cfg(test)]
493 pub(super) fn set_presentation_now_ms(&mut self, now_ms: u64) {
494 self.presentation_now_ms = Some(now_ms);
495 }
496
497 /// Signal that the user accepted a turn or a new operation started.
498 /// Recent-only live chrome collapses immediately (#4688).
499 pub fn note_user_turn_or_new_operation(&mut self) {
500 self.user_turn_epoch = self.user_turn_epoch.wrapping_add(1);
501 }
502
503 #[must_use]
504 pub(crate) fn frozen_agent_elapsed_ms(&self, agent_id: &str) -> Option<u64> {
505 self.frozen_agent_elapsed_ms.get(agent_id).copied()
506 }
507
508 pub(crate) fn reset_session_state(&mut self, next_session_id: Option<&str>) {
509 self.cached_graph = None;
510 self.latest_rows.clear();
511 self.catalog_rows.clear();
512 self.file_activity = SettledFileActivity::default();
513 self.frozen_agent_elapsed_ms.clear();
514 self.selected = None;
515 self.opened = None;
516 self.hovered = None;
517 self.scroll_offset = 0;
518 self.dismissed = false;
519 self.dismissed_at_rows = 0;
520 self.recent_only_since_ms = None;
521 self.recent_only_fingerprint = 0;
522 self.recent_only_suppressed = false;
523 self.activity_since_ms = None;
524 self.activity_fingerprint = 0;
525 self.activity_suppressed = false;
526 if self
527 .session_instance
528 .as_ref()
529 .is_some_and(|scope| next_session_id != Some(scope.session_id.as_str()))
530 {
531 self.session_instance = None;
532 }
533 }
534
535 /// Record the exact graph restored from persisted session state. This
536 /// must happen at the restore boundary: the first later runtime capture
537 /// may already contain work created by this process.
538 pub(crate) fn record_restored_session(
539 &mut self,
540 session_id: &str,
541 graph: Option<&WorkGraphSnapshot>,
542 ) {
543 let from_prior_instance = session_record_from_prior_instance(self, session_id);
544 let restored_nodes = if from_prior_instance {
545 graph
546 .into_iter()
547 .flat_map(|graph| graph.nodes.iter())
548 .map(|node| node.id.as_str().to_string())
549 .collect()
550 } else {
551 HashSet::new()
552 };
553 self.session_instance = Some(SessionInstanceScope {
554 session_id: session_id.to_string(),
555 from_prior_instance,
556 restored_nodes,
557 });
558 }
559
560 /// A restored graph row owned by a prior session instance whose terminal
561 /// failure or staleness must not render as this session's live work
562 /// (#4416). Plan steps stay: the resumed to-do list is the point of
563 /// restoring; failed/stale operations and blockers are the leak.
564 pub(super) fn is_prior_instance_residue(&self, node: &WorkNode) -> bool {
565 let Some(scope) = self.session_instance.as_ref() else {
566 return false;
567 };
568 scope.from_prior_instance
569 && scope.restored_nodes.contains(node.id.as_str())
570 && node.kind != NodeKind::PlanStep
571 && matches!(node.state, NodeState::Failed | NodeState::Stale)
572 }
573
574 fn now_ms(&self) -> u64 {
575 self.presentation_now_ms.unwrap_or_else(|| {
576 u64::try_from(self.presentation_origin.elapsed().as_millis()).unwrap_or(u64::MAX)
577 })
578 }
579
580 pub(super) fn selected_index(&self, rows: &[WorkRow]) -> Option<usize> {
581 self.selected
582 .as_ref()
583 .and_then(|selected| rows.iter().position(|row| &row.id == selected))
584 }
585
586 /// Keep row identity and the viewport offset valid without moving the
587 /// viewport to the remembered keyboard selection. Mouse-wheel scrolling
588 /// is allowed to leave that selection off-screen until keyboard
589 /// navigation resumes.
590 pub(super) fn clamp_viewport(&mut self, rows: &[WorkRow]) {
591 let selectable = rows.iter().filter(|row| row.selectable).collect::<Vec<_>>();
592 if selectable.is_empty() {
593 self.selected = None;
594 // An explicitly opened empty panel still owns its tabs and Esc.
595 // Preserve that focus; ordinary typing can still release it.
596 self.focused &= self.explicit_view;
597 self.scroll_offset = 0;
598 return;
599 }
600 let established_selection = selectable
601 .iter()
602 .any(|row| Some(&row.id) == self.selected.as_ref());
603 if !established_selection {
604 let preferred = selectable
605 .iter()
606 // Both halves of the old `Attention` tone: splitting Failure out
607 // of it changed what red means, not what deserves focus first.
608 .find(|row| matches!(row.tone, WorkTone::Attention | WorkTone::Failure))
609 .or_else(|| selectable.iter().find(|row| row.tone == WorkTone::Live))
610 .copied()
611 .unwrap_or(selectable[0]);
612 self.selected = Some(preferred.id.clone());
613 // Establishing a new selection should reveal the current or
614 // needs-input item without reordering the canonical list. Later
615 // redraws keep mouse-wheel ownership and do not chase selection.
616 if let Some(selected) = rows.iter().position(|row| row.id == preferred.id) {
617 if selected < self.scroll_offset {
618 self.scroll_offset = selected;
619 } else if self.visible_rows > 0
620 && selected >= self.scroll_offset.saturating_add(self.visible_rows)
621 {
622 self.scroll_offset = selected.saturating_add(1) - self.visible_rows;
623 }
624 }
625 }
626 self.scroll_offset = self
627 .scroll_offset
628 .min(rows.len().saturating_sub(self.visible_rows.max(1)));
629 }
630
631 /// Reveal the remembered selection after keyboard navigation. Rendering
632 /// alone must use `clamp_viewport`; otherwise every redraw undoes a mouse
633 /// wheel offset when the selection is above the viewport.
634 pub(super) fn clamp_selection(&mut self, rows: &[WorkRow]) {
635 self.clamp_viewport(rows);
636 let Some(selected) = self.selected_index(rows) else {
637 return;
638 };
639 if selected < self.scroll_offset {
640 self.scroll_offset = selected;
641 } else if self.visible_rows > 0
642 && selected >= self.scroll_offset.saturating_add(self.visible_rows)
643 {
644 self.scroll_offset = selected.saturating_add(1).saturating_sub(self.visible_rows);
645 }
646 self.scroll_offset = self
647 .scroll_offset
648 .min(rows.len().saturating_sub(self.visible_rows.max(1)));
649 }
650 }
651
652 pub(super) fn project(app: &mut App) -> Vec<WorkRow> {
653 let active_session = app.current_session_id.is_some();
654 freeze_terminal_agent_elapsed(app);
655 let agents = agent_rows(app);
656 let coordination = coordination_row(app);
657 let activity = settled_file_activity(app);
658 app.work_surface.file_activity = activity.clone();
659 let capture = app.runtime_services.work.as_ref().map(|work| {
660 work.try_capture(app.current_session_id.as_deref())
661 .map(|snapshot| snapshot.map(|snapshot| snapshot.graph))
662 });
663
664 let (graph, source_state) = match capture {
665 Some(Ok(Some(graph))) => {
666 app.work_surface.cached_graph = Some(graph.clone());
667 (Some(graph), None)
668 }
669 Some(Ok(None)) => {
670 app.work_surface.cached_graph = None;
671 (None, None)
672 }
673 Some(Err(error)) => (
674 app.work_surface.cached_graph.clone(),
675 active_session.then_some(WorkSourceState::Error(error)),
676 ),
677 None => (
678 app.work_surface.cached_graph.clone(),
679 active_session.then_some(WorkSourceState::Disconnected),
680 ),
681 };
682
683 update_session_instance_scope(app);
684
685 let mut rows = match graph {
686 Some(graph) => graph_rows(
687 &mut app.work_surface,
688 &graph,
689 source_state.as_ref(),
690 agents,
691 coordination,
692 activity,
693 ),
694 None if !agents.is_empty() || coordination.is_some() || !activity.is_empty() => {
695 ordered_rows(
696 &mut app.work_surface,
697 None,
698 source_state.as_ref(),
699 agents,
700 coordination,
701 activity,
702 )
703 }
704 None => source_state.map_or_else(Vec::new, |state| {
705 vec![section_heading(
706 "work",
707 &format!("Work · {}", state.label()),
708 state.detail(),
709 )]
710 }),
711 };
712 rows = with_live_shell_rows(app, rows);
713 app.work_surface.latest_rows = rows.clone();
714 if let Some(opened) = app.work_surface.opened.as_ref()
715 && !rows.iter().any(|row| &row.id == opened)
716 && !app
717 .work_surface
718 .catalog_rows
719 .iter()
720 .any(|row| &row.id == opened)
721 {
722 app.work_surface.opened = None;
723 }
724 rows
725 }
726
727 /// The tasks view: plan-step to-dos. On strips the list is literal to-dos
728 /// only; side rails keep the rest of the graph projection (operations,
729 /// blockers, receipts) under them. Sub-agents and shells have their own
730 /// views now, so nothing here competes with a running worker for rows — the
731 /// dock opens on the agents view while one runs.
732 pub(super) fn project_visible(app: &mut App) -> Vec<WorkRow> {
733 let rows = project(app);
734 let todo_ids = plan_step_row_ids(app);
735 let strip = app.work_surface.effective_placement.is_strip();
736 let mut out: Vec<WorkRow> = rows
737 .into_iter()
738 .filter(|row| {
739 !row.id.0.starts_with("worker:")
740 && !row.id.0.starts_with("shell:")
741 && row.id.0 != "section:shells"
742 && row.id.0 != "section:agents"
743 && (!strip || todo_ids.contains(&row.id.0))
744 })
745 .collect();
746 // On Top the goal is already the strip title; a side column repeats it
747 // as its first row so the durable goal home survives in every placement.
748 if !strip && let Some(label) = goal_row_label(app) {
749 out.insert(0, section_heading("goal", &label, ""));
750 }
751 app.work_surface.latest_rows = out.clone();
752 out
753 }
754
755 fn goal_row_label(app: &App) -> Option<String> {
756 let (objective, paused) = crate::tui::footer_ui::active_goal_chip_state(app)?;
757 let flat = objective.trim().replace(['\n', '\r'], " ");
758 if flat.is_empty() {
759 return None;
760 }
761 Some(if paused {
762 format!("Goal (paused): {flat}")
763 } else {
764 format!("Goal: {flat}")
765 })
766 }
767
768 /// The agents view: the roster. Every worker row, live or settled, under the
769 /// `▾ Subagents N` group door, oldest-first as the runtime reports them.
770 ///
771 /// ## Order and nesting
772 ///
773 /// This list is **roster-ordered** — creation order with parked husks sunk
774 /// last (`build_agent_roster`) — not tree-ordered. The `↳ ` indent and the
775 /// `(+N)` child count that `order_agent_seeds` stamps are therefore a fact
776 /// about the *live* projection carried through this merge, never a claim that
777 /// the row directly above an indented row is its parent.
778 ///
779 /// Rows built from a retained receipt stay flat, and that is deliberate.
780 /// `AgentRosterRow` does carry `parent_run_id`, but deriving depth from it
781 /// here would put a second depth authority on one list and, because the list
782 /// is not tree-ordered, would draw exactly the dangling indent
783 /// `order_agent_seeds` refuses to draw. Nesting instead degrades to flat, and
784 /// it degrades symmetrically: once either half of a pair has outlived its
785 /// live card, the surviving half loses its `↳ ` or its `(+N)` with it,
786 /// because `order_agent_seeds` only ever sees cache seeds. A pair is nested
787 /// or it is flat; one half is never marked without the other. Pinned by
788 /// `a_retained_child_renders_flat_under_a_retained_parent` and
789 /// `a_live_child_flattens_once_its_parent_has_expired_to_a_receipt`.
790 fn agents_view_rows(app: &mut App) -> Vec<WorkRow> {
791 let rows = project(app);
792 let mut agents: Vec<WorkRow> = rows
793 .into_iter()
794 .filter(|row| row.id.0.starts_with("worker:"))
795 .collect();
796 // The compact cache expires settled cards after 45 seconds. The explicit
797 // register is session history: retain its receipt rows, preserving fresh
798 // cache/progress projections by worker ID when both sources know a worker.
799 let mut retained = Vec::new();
800 let mut seen = HashSet::new();
801 for receipt in app.current_agent_roster() {
802 let id = WorkRowId(format!("worker:{}", receipt.worker_id));
803 if !seen.insert(id.clone()) {
804 continue;
805 }
806 if let Some(index) = agents.iter().position(|row| row.id == id) {
807 retained.push(agents.remove(index));
808 continue;
809 }
810 let parked = receipt.state == codewhale_engine::agent_roster::RosterState::Parked;
811 let status = if parked {
812 current_activity_status_label(AgentCurrentActivityStatus::Parked, app.ui_locale)
813 } else {
814 std::borrow::Cow::Borrowed(worker_status_label(receipt.status))
815 };
816 let activity = receipt.activity.clone().unwrap_or_default();
817 let name = app
818 .agent_label_map
819 .get(&receipt.worker_id)
820 .filter(|label| !App::is_agent_counter_placeholder(label))
821 .cloned()
822 .or_else(|| {
823 let candidate = receipt.display_name.trim();
824 (!candidate.is_empty() && candidate != receipt.worker_id)
825 .then(|| candidate.to_string())
826 })
827 .or_else(|| app.agent_label_map.get(&receipt.worker_id).cloned())
828 .unwrap_or_else(|| receipt.display_name.clone());
829 let bucket = if parked {
830 WorkBucket::Ready
831 } else {
832 worker_status_bucket(receipt.status)
833 };
834 let tokens = match (receipt.input_tokens, receipt.output_tokens) {
835 (Some(input), Some(output)) => Some(input.saturating_add(output)),
836 (Some(input), None) => Some(input),
837 (None, Some(output)) => Some(output),
838 (None, None) => None,
839 };
840 retained.push(WorkRow {
841 id,
842 mark: receipt.state.glyph(),
843 label: name.clone(),
844 detail: if activity.is_empty() {
845 status.to_string()
846 } else {
847 format!("{status} · {activity}")
848 },
849 tone: agent_tone(bucket, receipt.status == AgentWorkerStatus::Failed),
850 selectable: true,
851 primary_action: Some(SidebarRowAction::OpenAgentTranscript {
852 agent_id: receipt.worker_id.clone(),
853 }),
854 agent: Some(AgentRowFacts {
855 role_label: name,
856 status: status.to_string(),
857 objective: activity,
858 elapsed_secs: receipt.millis.map(|millis| millis / 1_000),
859 model: (!receipt.model.is_empty() && receipt.model != "unknown")
860 .then(|| receipt.model.clone()),
861 tokens,
862 todos_remaining: None,
863 // History, not news: a settled receipt has nothing running,
864 // and a parked husk asked nobody anything (#5906). Only a
865 // worker still running or still answerable holds the dock.
866 holds_dock_open: !parked && !receipt.state.is_terminal(),
867 }),
868 });
869 }
870 for row in agents {
871 if seen.insert(row.id.clone()) {
872 retained.push(row);
873 }
874 }
875 for cell in &app.history {
876 match cell {
877 HistoryCell::SubAgent(SubAgentCell::Delegate(card)) => {
878 let id = WorkRowId(format!("worker:{}", card.agent_id));
879 if seen.insert(id.clone()) {
880 retained.push(transcript_agent_row(
881 app,
882 id,
883 &card.agent_id,
884 &card.agent_type,
885 card.status,
886 card.summary.as_deref(),
887 ));
888 }
889 }
890 HistoryCell::SubAgent(SubAgentCell::Fanout(card)) => {
891 for worker in &card.workers {
892 let id = WorkRowId(format!("worker:{}", worker.agent_id));
893 if seen.insert(id.clone()) {
894 let summary = format!("{} · {}", card.kind, worker.worker_id);
895 retained.push(transcript_agent_row(
896 app,
897 id,
898 &worker.agent_id,
899 "worker",
900 worker.status,
901 Some(&summary),
902 ));
903 }
904 }
905 }
906 _ => {}
907 }
908 }
909 let agents = retained;
910 let mut out = Vec::with_capacity(agents.len() + 1);
911 if !agents.is_empty() {
912 out.push(agents_section_heading(&format!(
913 "Subagents {}",
914 agents.len()
915 )));
916 out.extend(agents);
917 }
918 app.work_surface.latest_rows = out.clone();
919 out
920 }
921
922 fn transcript_agent_row(
923 app: &App,
924 id: WorkRowId,
925 agent_id: &str,
926 agent_type: &str,
927 lifecycle: AgentLifecycle,
928 summary: Option<&str>,
929 ) -> WorkRow {
930 let (worker_status, state) = match lifecycle {
931 AgentLifecycle::Pending => (
932 AgentWorkerStatus::Queued,
933 codewhale_engine::agent_roster::RosterState::Running,
934 ),
935 AgentLifecycle::Running => (
936 AgentWorkerStatus::Running,
937 codewhale_engine::agent_roster::RosterState::Running,
938 ),
939 AgentLifecycle::Completed => (
940 AgentWorkerStatus::Completed,
941 codewhale_engine::agent_roster::RosterState::Done,
942 ),
943 AgentLifecycle::Failed => (
944 AgentWorkerStatus::Failed,
945 codewhale_engine::agent_roster::RosterState::Failed,
946 ),
947 AgentLifecycle::Cancelled => (
948 AgentWorkerStatus::Cancelled,
949 codewhale_engine::agent_roster::RosterState::Cancelled,
950 ),
951 AgentLifecycle::Interrupted => (
952 AgentWorkerStatus::Interrupted,
953 codewhale_engine::agent_roster::RosterState::Cancelled,
954 ),
955 };
956 let status = worker_status_label(worker_status);
957 let bucket = worker_status_bucket(worker_status);
958 let name = app
959 .agent_label_map
960 .get(agent_id)
961 .filter(|label| !App::is_agent_counter_placeholder(label))
962 .cloned()
963 .or_else(|| {
964 let trimmed = agent_type.trim();
965 (!trimmed.is_empty() && trimmed != "unknown" && trimmed != agent_id)
966 .then(|| trimmed.to_string())
967 })
968 .or_else(|| app.agent_label_map.get(agent_id).cloned())
969 .unwrap_or_else(|| "agent".to_string());
970 let objective = summary
971 .map(codewhale_engine::agent_roster::one_line)
972 .filter(|text| !text.is_empty())
973 .unwrap_or_default();
974 WorkRow {
975 id,
976 mark: state.glyph(),
977 label: name.clone(),
978 detail: if objective.is_empty() {
979 status.to_string()
980 } else {
981 format!("{status} · {objective}")
982 },
983 tone: agent_tone(bucket, worker_status == AgentWorkerStatus::Failed),
984 selectable: true,
985 primary_action: Some(SidebarRowAction::OpenAgentTranscript {
986 agent_id: agent_id.to_string(),
987 }),
988 agent: Some(AgentRowFacts {
989 role_label: name,
990 status: status.to_string(),
991 objective,
992 elapsed_secs: None,
993 model: None,
994 tokens: None,
995 todos_remaining: None,
996 holds_dock_open: matches!(lifecycle, AgentLifecycle::Pending | AgentLifecycle::Running),
997 }),
998 }
999 }
1000
1001 /// Pick the view for this frame when the user has not picked one.
1002 ///
1003 /// The dock is one bottom view. Cycling, a tab click, or `/workbar <view>`
1004 /// makes the choice explicit and it sticks until Esc; otherwise the first of
1005 /// [`RailPanel::AUTO_ORDER`] with content wins — agents while a sub-agent
1006 /// runs, then the to-do list, then background work — and the persisted
1007 /// `rail_panel` preference is what shows when none of them has anything.
1008 pub(crate) fn resolve_view(app: &mut App) {
1009 if app.work_surface.explicit_view {
1010 return;
1011 }
1012 for panel in RailPanel::AUTO_ORDER {
1013 if !view_has_work(app, panel) {
1014 continue;
1015 }
1016 if app.work_surface.panel != panel {
1017 app.work_surface.panel = panel;
1018 app.work_surface.scroll_offset = 0;
1019 app.work_surface.selected = None;
1020 }
1021 return;
1022 }
1023 }
1024
1025 /// How much work the auto-opening views hold between them: live agents,
1026 /// to-dos, and running background work. The dismissed dock re-opens when
1027 /// this grows, whichever view the new work lands in.
1028 pub(crate) fn auto_work_rows(app: &mut App) -> usize {
1029 let agents = live_agent_row_count(app);
1030 let tasks = visible_rows_for(app, RailPanel::Tasks)
1031 .iter()
1032 .filter(|row| row.id.0.starts_with("graph:"))
1033 .count();
1034 let background = if background_has_live_work(app) {
1035 visible_rows_for(app, RailPanel::Background).len()
1036 } else {
1037 0
1038 };
1039 agents + tasks + background
1040 }
1041
1042 fn view_has_work(app: &mut App, panel: RailPanel) -> bool {
1043 match panel {
1044 RailPanel::Agents => live_agent_row_count(app) > 0,
1045 // To-dos are the plan steps. A side rail also folds a summary of
1046 // running work into this view; that summary is not a reason to
1047 // open on TODO when the workers themselves live one tab over.
1048 RailPanel::Tasks => visible_rows_for(app, panel)
1049 .iter()
1050 .any(|row| row.id.0.starts_with("graph:")),
1051 // Scheduled automations that are not running are a fact about the
1052 // account, not work in this session: they must not open the dock
1053 // before the first prompt (0.9.12 defect #10). Live shells, durable
1054 // tasks are work. Scheduled automation configuration belongs in /automation.
1055 RailPanel::Background => background_has_live_work(app),
1056 RailPanel::Files
1057 | RailPanel::Terminal
1058 | RailPanel::Notepad
1059 | RailPanel::Context
1060 | RailPanel::Git
1061 | RailPanel::Price => false,
1062 }
1063 }
1064
1065 /// Live worker rows: the ones that make the agents view open on its own.
1066 ///
1067 /// Counted over [`agents_view_rows`] — the same merged projection the register
1068 /// renders — not over the 45-second `subagent_cache` alone. A child that is
1069 /// blocked on a person survives in the retained roster after its live card
1070 /// expires, and across a session restore, where `subagent_cache` keeps only
1071 /// this instance's workers; the dock has to open for it either way.
1072 pub(super) fn live_agent_row_count(app: &mut App) -> usize {
1073 agents_view_rows(app)
1074 .iter()
1075 .filter(|row| {
1076 row.id.0.starts_with("worker:")
1077 && row
1078 .agent
1079 .as_ref()
1080 .is_some_and(|facts| facts.holds_dock_open)
1081 })
1082 .count()
1083 }
1084
1085 /// Whether the background view holds anything actually running: a live
1086 /// shell or a queued or running durable task. Finished work stays listed but
1087 /// never opens the dock or counts as live (#6565).
1088 pub(super) fn background_has_live_work(app: &mut App) -> bool {
1089 !shell_work_rows(app).is_empty() || !durable_task_rows(app).is_empty()
1090 }
1091
1092 /// The background view: live shells, live durable tasks, then a muted
1093 /// `Finished N` group with the shells and tasks that ended, and how.
1094 fn background_view_rows(app: &mut App) -> Vec<WorkRow> {
1095 let mut out = Vec::new();
1096 push_shell_group(&mut out, shell_work_rows(app));
1097 out.extend(durable_task_rows(app));
1098 let finished = finished_background_rows(app);
1099 if !finished.is_empty() {
1100 out.push(section_heading(
1101 "finished",
1102 &tr(app.ui_locale, MessageId::BackgroundFinishedHeading)
1103 .replace("{count}", &finished.len().to_string()),
1104 &tr(app.ui_locale, MessageId::BackgroundFinishedHint),
1105 ));
1106 out.extend(finished);
1107 }
1108 app.work_surface.latest_rows = out.clone();
1109 out
1110 }
1111
1112 /// A background shell row, live or finished.
1113 fn is_shell_entry(entry: &TaskPanelEntry) -> bool {
1114 entry.kind == TaskPanelEntryKind::Shell
1115 }
1116
1117 /// Queued or running. A stale running task still needs a look, so it stays.
1118 fn is_live_task_status(status: &str) -> bool {
1119 matches!(status, "queued" | "running")
1120 }
1121
1122 /// Live durable tasks (queued or running).
1123 fn durable_task_rows(app: &App) -> Vec<WorkRow> {
1124 app.task_panel
1125 .iter()
1126 .filter(|entry| !is_shell_entry(entry) && is_live_task_status(&entry.status))
1127 .map(|entry| {
1128 let status = if entry.stale {
1129 "stale"
1130 } else {
1131 entry.status.as_str()
1132 };
1133 let bucket = if entry.stale {
1134 WorkBucket::Attention
1135 } else if entry.status == "queued" {
1136 WorkBucket::Ready
1137 } else {
1138 WorkBucket::Active
1139 };
1140 WorkRow {
1141 id: WorkRowId(format!("task:{}", entry.id)),
1142 mark: agent_mark(bucket),
1143 label: entry.prompt_summary.clone(),
1144 detail: format!("{status} · {}", entry.id),
1145 tone: bucket_tone(bucket),
1146 selectable: true,
1147 primary_action: task_show_action(entry),
1148 agent: None,
1149 }
1150 })
1151 .collect()
1152 }
1153
1154 fn task_show_action(entry: &TaskPanelEntry) -> Option<SidebarRowAction> {
1155 (!entry.id.starts_with("rlm-"))
1156 .then(|| SidebarRowAction::Command(format!("/task show {}", entry.id)))
1157 }
1158
1159 fn shell_show_action(entry: &TaskPanelEntry) -> Option<SidebarRowAction> {
1160 Some(SidebarRowAction::Command(format!(
1161 "/jobs show {}",
1162 entry.id
1163 )))
1164 }
1165
1166 /// Finished shells and durable tasks, muted, each saying how it ended:
1167 /// `exit 0 · 12s`, `failed · exit 2`, `killed`, `timed out`. The shell
1168 /// leads with its command; its id is only in the detail and inspector.
1169 fn finished_background_rows(app: &App) -> Vec<WorkRow> {
1170 app.task_panel
1171 .iter()
1172 .filter(|entry| !is_live_task_status(&entry.status))
1173 .map(|entry| {
1174 let failed = matches!(entry.status.as_str(), "failed" | "timed_out");
1175 let tone = if failed {
1176 WorkTone::Failure
1177 } else {
1178 WorkTone::Muted
1179 };
1180 let mark = match entry.status.as_str() {
1181 "completed" => codewhale_tui_kit::glyphs::DONE,
1182 _ if failed => codewhale_tui_kit::glyphs::ATTENTION,
1183 _ => codewhale_tui_kit::glyphs::NEUTRAL,
1184 };
1185 if is_shell_entry(entry) {
1186 let command = shell_command(entry);
1187 let outcome = finished_shell_outcome(app.ui_locale, entry);
1188 WorkRow {
1189 id: WorkRowId(format!("shell:{}", entry.id)),
1190 mark,
1191 label: command.clone(),
1192 detail: format!("{outcome} · {}", entry.id),
1193 tone,
1194 selectable: true,
1195 primary_action: shell_show_action(entry),
1196 agent: Some(AgentRowFacts {
1197 role_label: "shell".to_string(),
1198 status: outcome,
1199 objective: command,
1200 elapsed_secs: entry.duration_ms.map(|ms| ms / 1_000),
1201 model: None,
1202 tokens: None,
1203 todos_remaining: None,
1204 holds_dock_open: false,
1205 }),
1206 }
1207 } else {
1208 let took = entry
1209 .duration_ms
1210 .map(|ms| format!(" · {}", codewhale_engine::agent_roster::format_duration(ms)))
1211 .unwrap_or_default();
1212 WorkRow {
1213 id: WorkRowId(format!("task:{}", entry.id)),
1214 mark,
1215 label: entry.prompt_summary.clone(),
1216 detail: format!(
1217 "{}{took} · {}",
1218 tr(
1219 app.ui_locale,
1220 match entry.status.as_str() {
1221 "completed" => MessageId::BackgroundOutcomeDone,
1222 "failed" => MessageId::BackgroundOutcomeFailed,
1223 _ => MessageId::BackgroundOutcomeCancelled,
1224 }
1225 ),
1226 entry.id
1227 ),
1228 tone,
1229 selectable: true,
1230 primary_action: task_show_action(entry),
1231 agent: None,
1232 }
1233 }
1234 })
1235 .collect()
1236 }
1237
1238 /// A shell entry's command, without the `shell: ` prefix; its id when the
1239 /// command is empty.
1240 fn shell_command(entry: &TaskPanelEntry) -> String {
1241 let command = entry
1242 .prompt_summary
1243 .strip_prefix("shell: ")
1244 .unwrap_or(entry.prompt_summary.as_str())
1245 .trim();
1246 if command.is_empty() {
1247 entry.id.clone()
1248 } else {
1249 codewhale_app_server::exec_agent::summarize_tool_output(command).replace(['\n', '\r'], " ")
1250 }
1251 }
1252
1253 /// How a finished shell ended, the same words its notice uses.
1254 fn finished_shell_outcome(locale: Locale, entry: &TaskPanelEntry) -> String {
1255 let exit = entry
1256 .exit_code
1257 .map(|code| tr(locale, MessageId::BackgroundExitCode).replace("{code}", &code.to_string()));
1258 match entry.status.as_str() {
1259 "completed" => {
1260 let took = entry
1261 .duration_ms
1262 .map(|ms| format!(" · {}", codewhale_engine::agent_roster::format_duration(ms)))
1263 .unwrap_or_default();
1264 format!(
1265 "{}{took}",
1266 exit.unwrap_or_else(|| tr(locale, MessageId::BackgroundOutcomeDone).into_owned())
1267 )
1268 }
1269 "failed" => {
1270 let failed = tr(locale, MessageId::BackgroundOutcomeFailed);
1271 exit.map_or_else(|| failed.to_string(), |exit| format!("{failed} · {exit}"))
1272 }
1273 "killed" => tr(locale, MessageId::BackgroundOutcomeKilled).into_owned(),
1274 "timed_out" => tr(locale, MessageId::BackgroundOutcomeTimedOut).into_owned(),
1275 other => other.to_string(),
1276 }
1277 }
1278
1279 /// Row ids of the plan-step (to-do) nodes in the cached graph.
1280 pub(super) fn plan_step_row_ids(app: &App) -> HashSet<String> {
1281 app.work_surface
1282 .cached_graph
1283 .as_ref()
1284 .map(|snapshot| {
1285 snapshot
1286 .nodes
1287 .iter()
1288 .filter(|node| node.kind == NodeKind::PlanStep)
1289 .map(|node| format!("graph:{}", node.id.as_str()))
1290 .collect::<HashSet<_>>()
1291 })
1292 .unwrap_or_default()
1293 }
1294
1295 /// Rows for the selected rail panel, routed through the same row/hitbox
1296 /// machinery regardless of panel: every work row a user can see is a door
1297 /// (`crates/tui/AGENTS.md`, "rows are objects"), whichever panel it appears
1298 /// in.
1299 ///
1300 /// - `Tasks` — the full live projection ([`project_visible`]).
1301 /// - `Agents` — the full sub-agent register under the `▾ Subagents N` header,
1302 /// then live shells, then the durable to-do checklist: opening the register
1303 /// never hides the list.
1304 /// - `Pinned` — the goal, the sub-agent group, then the plan-step to-dos.
1305 /// - `Context` — empty: session facts are a line list, not work rows, and
1306 /// render outside the row machinery.
1307 ///
1308 /// **No panel choice may hide a running sub-agent.** `Pinned` used to filter
1309 /// the projection down to plan steps, which meant the owner's own
1310 /// `rail_panel = "pinned"` made a live worker unreachable: with no to-dos and
1311 /// no goal the projection was empty, the strip collapsed to zero rows, and
1312 /// the top bar was header chrome only — the 2026-08-04 "I spawned a sub agent
1313 /// and the top bar showed nothing" report, pinned by
1314 /// `tests/work_bar_subagents_pty.rs`. There is no header chip or phase-strip
1315 /// fallback for sub-agents, so this strip is the *only* persistent surface
1316 /// they have; a panel preference about which durable work to foreground is
1317 /// not consent to lose the running fleet. Sub-agent rows are durable in the
1318 /// same sense the panel's name means (they survive completion — see the row
1319 /// lifetime rule in the module docs), so they belong here on their own terms.
1320 pub(super) fn visible_rows_for_panel(app: &mut App) -> Vec<WorkRow> {
1321 let panel = app.work_surface.panel;
1322 visible_rows_for(app, panel)
1323 }
1324
1325 pub(super) fn visible_rows_for(app: &mut App, panel: RailPanel) -> Vec<WorkRow> {
1326 match panel {
1327 RailPanel::Agents => agents_view_rows(app),
1328 RailPanel::Tasks => project_visible(app),
1329 RailPanel::Background => background_view_rows(app),
1330 RailPanel::Terminal => Vec::new(),
1331 RailPanel::Files => super::views::files_rows(app),
1332 RailPanel::Notepad => super::views::notepad_rows(app),
1333 RailPanel::Context => super::views::context_rows(app),
1334 RailPanel::Git => super::views::git_rows(app),
1335 RailPanel::Price => super::views::price_rows(app),
1336 }
1337 }
1338
1339 /// Classify the current session against this process's session-instance
1340 /// boot id (#4416), mirroring the `SubAgentManager` prior-session pattern
1341 /// (#405). The probe runs once per session id. Persisted row identity is
1342 /// recorded separately at the actual session restore boundary.
1343 fn update_session_instance_scope(app: &mut App) {
1344 let Some(session_id) = app.current_session_id.clone() else {
1345 app.work_surface.session_instance = None;
1346 return;
1347 };
1348 let classified = app
1349 .work_surface
1350 .session_instance
1351 .as_ref()
1352 .is_some_and(|scope| scope.session_id == session_id);
1353 if !classified {
1354 let from_prior_instance =
1355 session_record_from_prior_instance(&app.work_surface, &session_id);
1356 app.work_surface.session_instance = Some(SessionInstanceScope {
1357 session_id,
1358 from_prior_instance,
1359 restored_nodes: HashSet::new(),
1360 });
1361 }
1362 }
1363
1364 fn session_record_from_prior_instance(surface: &WorkSurfaceState, session_id: &str) -> bool {
1365 let manager = match surface.session_owner_probe_dir.as_ref() {
1366 Some(dir) => codewhale_engine::session_manager::SessionManager::new(dir.clone()),
1367 None => codewhale_engine::session_manager::SessionManager::default_location(),
1368 };
1369 manager.is_ok_and(|manager| manager.session_from_prior_instance(session_id))
1370 }
1371
1372 fn graph_rows(
1373 surface: &mut WorkSurfaceState,
1374 snapshot: &WorkGraphSnapshot,
1375 source_state: Option<&WorkSourceState>,
1376 agents: Vec<RankedWorkRow>,
1377 coordination: Option<RankedWorkRow>,
1378 activity: SettledFileActivity,
1379 ) -> Vec<WorkRow> {
1380 ordered_rows(
1381 surface,
1382 Some(snapshot),
1383 source_state,
1384 agents,
1385 coordination,
1386 activity,
1387 )
1388 }
1389
1390 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1391 enum WorkBucket {
1392 Active,
1393 Attention,
1394 Ready,
1395 Recent,
1396 }
1397
1398 impl WorkBucket {
1399 /// Presentation priority: needs-input outranks running work (#4689).
1400 const fn rank(self) -> u8 {
1401 match self {
1402 Self::Attention => 0,
1403 Self::Active => 1,
1404 Self::Ready => 2,
1405 Self::Recent => 3,
1406 }
1407 }
1408
1409 const fn is_actionable(self) -> bool {
1410 !matches!(self, Self::Recent)
1411 }
1412 }
1413
1414 #[derive(Clone)]
1415 struct RankedWorkRow {
1416 bucket: WorkBucket,
1417 order: usize,
1418 is_plan_step: bool,
1419 row: WorkRow,
1420 }
1421
1422 /// Complete unique targets; only the aggregate summary presentation is capped.
1423 #[derive(Clone)]
1424 pub(super) struct SettledFileActivity {
1425 pub(super) locale: Locale,
1426 pub(super) summary: FileActivitySummary,
1427 pub(super) read: Vec<String>,
1428 list: Vec<String>,
1429 search: Vec<String>,
1430 pub(super) write: Vec<String>,
1431 pub(super) mutations: Vec<FileMutationReceipt>,
1432 pub(super) inline_diff_mode: InlineDiffMode,
1433 }
1434
1435 impl Default for SettledFileActivity {
1436 fn default() -> Self {
1437 Self {
1438 locale: Locale::En,
1439 summary: FileActivitySummary::default(),
1440 read: Vec::new(),
1441 list: Vec::new(),
1442 search: Vec::new(),
1443 write: Vec::new(),
1444 mutations: Vec::new(),
1445 inline_diff_mode: InlineDiffMode::default(),
1446 }
1447 }
1448 }
1449
1450 impl std::fmt::Debug for SettledFileActivity {
1451 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1452 f.debug_struct("SettledFileActivity")
1453 .field("read", &self.read.len())
1454 .field("write", &self.write.len())
1455 .field("mutations", &self.mutations.len())
1456 .finish_non_exhaustive()
1457 }
1458 }
1459
1460 impl SettledFileActivity {
1461 fn is_empty(&self) -> bool {
1462 self.summary.is_empty()
1463 }
1464 }
1465
1466 fn ordered_rows(
1467 surface: &mut WorkSurfaceState,
1468 snapshot: Option<&WorkGraphSnapshot>,
1469 source_state: Option<&WorkSourceState>,
1470 mut ranked: Vec<RankedWorkRow>,
1471 coordination: Option<RankedWorkRow>,
1472 activity: SettledFileActivity,
1473 ) -> Vec<WorkRow> {
1474 ranked.extend(coordination);
1475 if let Some(snapshot) = snapshot {
1476 ranked.extend(
1477 snapshot
1478 .nodes
1479 .iter()
1480 .filter(|node| {
1481 matches!(
1482 node.kind,
1483 NodeKind::PlanStep | NodeKind::Operation | NodeKind::Blocker
1484 )
1485 })
1486 .filter(|node| !is_settled_transient_operation(node))
1487 .filter(|node| !surface.is_prior_instance_residue(node))
1488 // A plan step dropped from the Plan/To-do list (e.g. the model
1489 // cleared it with an empty `todo_write`) stays in the graph
1490 // but must leave the rail (#6546).
1491 .filter(|node| {
1492 node.kind != NodeKind::PlanStep || snapshot.compat.projects(&node.id)
1493 })
1494 .enumerate()
1495 .map(|(order, node)| RankedWorkRow {
1496 bucket: node_bucket(node),
1497 order: 10_000usize.saturating_add(order),
1498 is_plan_step: node.kind == NodeKind::PlanStep,
1499 row: graph_node_row(snapshot, node),
1500 }),
1501 );
1502 }
1503
1504 // Activity is projected separately so we can apply a single aggregated
1505 // transient receipt instead of one live row per tool kind (#4690).
1506 let activity_row = aggregate_activity_row(&activity);
1507 if let Some(row) = activity_row.clone() {
1508 ranked.push(row);
1509 }
1510
1511 ranked.sort_by(|a, b| match (a.is_plan_step, b.is_plan_step) {
1512 // To-do (plan step) rows keep canonical order: a completed step must
1513 // not sink below a later pending step and lose its identity. Agent and
1514 // operation rows still sort by status bucket (#4689).
1515 (true, true) => a.order.cmp(&b.order),
1516 (true, false) => std::cmp::Ordering::Less,
1517 (false, true) => std::cmp::Ordering::Greater,
1518 (false, false) => a
1519 .bucket
1520 .rank()
1521 .cmp(&b.bucket.rank())
1522 .then_with(|| a.order.cmp(&b.order)),
1523 });
1524
1525 let active = ranked
1526 .iter()
1527 .filter(|item| item.bucket == WorkBucket::Active)
1528 .count();
1529 let attention = ranked
1530 .iter()
1531 .filter(|item| item.bucket == WorkBucket::Attention)
1532 .count();
1533 let ready = ranked
1534 .iter()
1535 .filter(|item| item.bucket == WorkBucket::Ready)
1536 .count();
1537 let recent = ranked
1538 .iter()
1539 .filter(|item| item.bucket == WorkBucket::Recent)
1540 .count();
1541 let actionable = attention + active + ready;
1542 let source = source_state
1543 .map(|state| format!(" · {}", state.label()))
1544 .unwrap_or_default();
1545 let detail = match (snapshot, source_state) {
1546 (Some(snapshot), Some(state)) => {
1547 format!("graph revision {} · {}", snapshot.revision, state.detail())
1548 }
1549 (Some(snapshot), None) => format!("graph revision {}", snapshot.revision),
1550 (None, Some(state)) => state.detail().to_string(),
1551 (None, None) => "Current session activity".to_string(),
1552 };
1553
1554 let now = surface.now_ms();
1555 let user_turn_force_hide = surface.user_turn_epoch != surface.last_handled_user_turn_epoch;
1556 if user_turn_force_hide {
1557 surface.last_handled_user_turn_epoch = surface.user_turn_epoch;
1558 if actionable == 0 {
1559 surface.recent_only_suppressed = true;
1560 }
1561 surface.activity_suppressed = true;
1562 }
1563
1564 // Recent-only lifecycle (#4688): show a brief completion, then collapse.
1565 let recent_fp = fingerprint_rows(
1566 ranked
1567 .iter()
1568 .filter(|item| item.bucket == WorkBucket::Recent)
1569 .map(|item| item.row.id.0.as_str()),
1570 );
1571 if actionable > 0 {
1572 surface.recent_only_since_ms = None;
1573 surface.recent_only_suppressed = false;
1574 surface.recent_only_fingerprint = recent_fp;
1575 } else if recent > 0 {
1576 if surface.recent_only_fingerprint != recent_fp {
1577 // A new completion after expiry may surface once.
1578 surface.recent_only_fingerprint = recent_fp;
1579 surface.recent_only_since_ms = Some(now);
1580 surface.recent_only_suppressed = false;
1581 } else if surface.recent_only_since_ms.is_none() && !surface.recent_only_suppressed {
1582 surface.recent_only_since_ms = Some(now);
1583 }
1584 if let Some(since) = surface.recent_only_since_ms
1585 && now.saturating_sub(since) >= RECENT_ONLY_TTL_MS
1586 {
1587 surface.recent_only_suppressed = true;
1588 }
1589 } else {
1590 surface.recent_only_since_ms = None;
1591 surface.recent_only_suppressed = false;
1592 surface.recent_only_fingerprint = 0;
1593 }
1594
1595 // Activity receipt lifetime (#4690): one aggregated row, 3s, no raw payloads.
1596 let activity_fp = activity_row
1597 .as_ref()
1598 .map(|row| fingerprint_rows(std::iter::once(row.row.label.as_str())))
1599 .unwrap_or(0);
1600 let show_activity = if activity_row.is_none() {
1601 surface.activity_since_ms = None;
1602 surface.activity_fingerprint = 0;
1603 surface.activity_suppressed = false;
1604 false
1605 } else {
1606 if surface.activity_fingerprint != activity_fp {
1607 surface.activity_fingerprint = activity_fp;
1608 surface.activity_since_ms = Some(now);
1609 surface.activity_suppressed = false;
1610 } else if surface.activity_since_ms.is_none() && !surface.activity_suppressed {
1611 surface.activity_since_ms = Some(now);
1612 }
1613 if let Some(since) = surface.activity_since_ms
1614 && now.saturating_sub(since) >= ACTIVITY_RECEIPT_TTL_MS
1615 {
1616 surface.activity_suppressed = true;
1617 }
1618 !surface.activity_suppressed
1619 };
1620
1621 let subject = ranked
1622 .iter()
1623 .find(|item| item.bucket.is_actionable())
1624 .map(|item| (item.bucket, sanitize_summary_title(&item.row.label)));
1625 let heading_label = match (actionable > 0, subject.as_ref()) {
1626 (true, Some((WorkBucket::Attention, title))) => {
1627 format!("Work · Needs input: {title} · {attention} blocked{source}")
1628 }
1629 (true, Some((WorkBucket::Active, title))) => {
1630 format!("Work · Running: {title} · {active} active{source}")
1631 }
1632 (true, Some((WorkBucket::Ready, title))) => {
1633 format!("Work · Ready: {title} · {ready} ready{source}")
1634 }
1635 (true, _) => format!(
1636 "Work · {active} active · {attention} needs input · {ready} ready · {recent} recent{source}"
1637 ),
1638 (false, _) => format!(
1639 "Work · {active} active · {attention} needs input · {ready} ready · {recent} recent{source}"
1640 ),
1641 };
1642
1643 // Full catalog for inspector/history even when live chrome collapses.
1644 let mut catalog = vec![section_heading("work", &heading_label, &detail)];
1645 catalog.extend(ranked.iter().map(|item| item.row.clone()));
1646 // Prior-instance terminal residue stays reachable through the explicit
1647 // catalog, labeled historical, but never as this session's live work
1648 // (#4416).
1649 if let Some(snapshot) = snapshot {
1650 catalog.extend(
1651 snapshot
1652 .nodes
1653 .iter()
1654 .filter(|node| surface.is_prior_instance_residue(node))
1655 .map(|node| {
1656 let mut row = graph_node_row(snapshot, node);
1657 row.detail = format!("prior session · {}", row.detail);
1658 row.tone = WorkTone::Muted;
1659 row
1660 }),
1661 );
1662 }
1663 surface.catalog_rows = catalog.clone();
1664
1665 // Live chrome policy (Tasks/side projections — Top uses `project_visible`):
1666 // - actionable: heading + (optional) single activity receipt
1667 // - recent-only: transient receipts collapse after the TTL / next user
1668 // turn (#4688); settled to-dos stay as durable rows. Settled sub-agents
1669 // on Top collapse into the Subagents header (see `project_visible`) and
1670 // remain reachable via the Agents panel / catalog.
1671 // - empty: no heading
1672 let is_durable =
1673 |item: &RankedWorkRow| item.is_plan_step || item.row.id.0.starts_with("worker:");
1674 let has_durable = ranked.iter().any(is_durable);
1675 if ranked.is_empty() && source_state.is_none() {
1676 return Vec::new();
1677 }
1678 if actionable == 0 && recent == 0 {
1679 // Source-only error/disconnected heading is still useful.
1680 return if source_state.is_some() {
1681 vec![section_heading("work", &heading_label, &detail)]
1682 } else {
1683 Vec::new()
1684 };
1685 }
1686 let suppress_transient_recent = actionable == 0 && surface.recent_only_suppressed;
1687 if suppress_transient_recent && !has_durable {
1688 return Vec::new();
1689 }
1690
1691 // The live heading must count the rows the live list actually shows.
1692 // Once transient recent rows are suppressed, quoting the unfiltered
1693 // `recent` total would claim receipts the reader cannot see — the
1694 // catalog heading keeps the full count because the catalog keeps the
1695 // full rows.
1696 let live_heading = if suppress_transient_recent {
1697 let live_recent = ranked
1698 .iter()
1699 .filter(|item| item.bucket == WorkBucket::Recent && is_durable(item))
1700 .count();
1701 format!(
1702 "Work · {active} active · {attention} needs input · {ready} ready · {live_recent} recent{source}"
1703 )
1704 } else {
1705 heading_label.clone()
1706 };
1707
1708 // Full ordered children remain in the projection for side rails, inspector
1709 // selection, and durable recent visibility. Live Top height is capped in
1710 // render (#4690). Recent-only *summary* lifetime is handled above (#4688).
1711 let mut live = vec![section_heading("work", &live_heading, &detail)];
1712 for item in ranked {
1713 if item.row.id.0 == "activity:aggregate" && !show_activity {
1714 continue;
1715 }
1716 if suppress_transient_recent && !is_durable(&item) {
1717 continue;
1718 }
1719 live.push(item.row);
1720 }
1721 live
1722 }
1723
1724 fn fingerprint_rows<'a>(ids: impl Iterator<Item = &'a str>) -> u64 {
1725 use std::hash::{Hash, Hasher};
1726 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1727 for id in ids {
1728 id.hash(&mut hasher);
1729 }
1730 hasher.finish()
1731 }
1732
1733 fn sanitize_summary_title(raw: &str) -> String {
1734 let single_line = raw
1735 .chars()
1736 .map(|ch| {
1737 if ch.is_control() || ch == '\n' || ch == '\r' || ch == '\t' {
1738 ' '
1739 } else {
1740 ch
1741 }
1742 })
1743 .collect::<String>();
1744 let collapsed = single_line.split_whitespace().collect::<Vec<_>>().join(" ");
1745 let trimmed = collapsed.trim();
1746 if trimmed.is_empty() {
1747 return "work item".to_string();
1748 }
1749 let mut chars = trimmed.chars();
1750 let prefix = chars.by_ref().take(72).collect::<String>();
1751 if chars.next().is_some() {
1752 format!("{prefix}…")
1753 } else {
1754 prefix
1755 }
1756 }
1757
1758 fn coordination_row(app: &App) -> Option<RankedWorkRow> {
1759 let projection = app.coordination_detail.as_ref()?;
1760 let has_context_receipt = projection.context_projections.iter().any(|receipt| {
1761 !receipt.decision_ids.is_empty()
1762 || receipt.projected_bytes > 0
1763 || receipt.deduplicated > 0
1764 || receipt.omitted > 0
1765 });
1766 let has_metrics = !projection.metrics.hottest_paths.is_empty()
1767 || projection.metrics.package_or_module_growth.is_some()
1768 || projection.metrics.route_or_cost.is_some();
1769 if projection.decisions.is_empty()
1770 && projection.write_claims.is_empty()
1771 && projection.reconciliations.is_empty()
1772 && projection.contentions.is_empty()
1773 && !has_context_receipt
1774 && !has_metrics
1775 {
1776 return None;
1777 }
1778 let attention = crate::tui::coordination_detail::needs_attention(projection);
1779 let bucket = if attention {
1780 WorkBucket::Attention
1781 } else {
1782 WorkBucket::Recent
1783 };
1784 let title = app
1785 .tr(codewhale_localization::MessageId::CoordinationWorkTitle)
1786 .into_owned();
1787 Some(RankedWorkRow {
1788 bucket,
1789 // Coordination is a session-wide receipt, before individual workers
1790 // within the same bucket but after live/attention priority sorting.
1791 order: 100,
1792 is_plan_step: false,
1793 row: WorkRow {
1794 id: WorkRowId("coordination".to_string()),
1795 mark: if attention {
1796 codewhale_tui_kit::glyphs::ATTENTION
1797 } else {
1798 codewhale_tui_kit::glyphs::DONE
1799 },
1800 label: title.clone(),
1801 detail: crate::tui::coordination_detail::summary(app.ui_locale, projection),
1802 tone: bucket_tone(bucket),
1803 selectable: true,
1804 primary_action: Some(SidebarRowAction::InspectWork {
1805 title,
1806 body: crate::tui::coordination_detail::format(app.ui_locale, projection),
1807 stop_action: None,
1808 }),
1809 agent: None,
1810 },
1811 })
1812 }
1813
1814 fn node_bucket(node: &WorkNode) -> WorkBucket {
1815 match node.state {
1816 NodeState::Initializing | NodeState::Active => WorkBucket::Active,
1817 NodeState::Failed if is_transient_failed_operation(node) => WorkBucket::Recent,
1818 NodeState::Waiting | NodeState::Blocked | NodeState::Stale | NodeState::Failed => {
1819 WorkBucket::Attention
1820 }
1821 NodeState::Completed if !node.acceptance.is_empty() => WorkBucket::Attention,
1822 NodeState::Ready => WorkBucket::Ready,
1823 NodeState::Completed
1824 | NodeState::Verified
1825 | NodeState::Superseded
1826 | NodeState::Cancelled => WorkBucket::Recent,
1827 }
1828 }
1829
1830 fn is_transient_failed_operation(node: &WorkNode) -> bool {
1831 node.kind == NodeKind::Operation
1832 && node
1833 .binding
1834 .as_ref()
1835 .is_some_and(|binding| !binding.durable)
1836 && node.acceptance.is_empty()
1837 && node.state == NodeState::Failed
1838 }
1839
1840 /// One worker row before display ordering: the rendered row plus the parent
1841 /// link and fleet identity the strip uses to number, order, and indent
1842 /// nested spawns (#36).
1843 struct AgentRowSeed {
1844 agent_id: String,
1845 parent_run_id: Option<String>,
1846 role: String,
1847 /// A real nickname or stable label, never the raw agent id (#36).
1848 name: Option<String>,
1849 ranked: RankedWorkRow,
1850 }
1851
1852 /// Indent marker for a nested spawn: nothing at the top level (no permanent
1853 /// chrome for the common flat fan-out), `↳` once nesting is actually
1854 /// present, with two extra spaces per additional level (#36).
1855 fn agent_nesting_indent(depth: usize) -> String {
1856 match depth {
1857 0 => String::new(),
1858 level => format!("{}↳ ", " ".repeat(level.saturating_sub(1))),
1859 }
1860 }
1861
1862 /// Compose the sub-agent identity column: nesting indent, who the agent is,
1863 /// and `(+N)` when that agent has spawned children of its own.
1864 ///
1865 /// `who` is the agent's nickname when it has one and its fleet role when it
1866 /// does not. A nickname is identity that CodeWhale actually has, so it leads;
1867 /// the role is the honest fallback. The raw agent-id hash is never a name and
1868 /// is never rendered (#36).
1869 fn agent_strip_label(indent: &str, who: &str, children: usize) -> String {
1870 if children == 0 {
1871 format!("{indent}{who}")
1872 } else {
1873 format!("{indent}{who} (+{children})")
1874 }
1875 }
1876
1877 /// Order worker rows so nested spawns sit directly under their parent, then
1878 /// stamp each label with its display depth and a sequential number. Rows
1879 /// whose parent is not visible (e.g. the parent finished and left the cache)
1880 /// stay at the top level — honest flat rendering beats a dangling indent.
1881 fn order_agent_seeds(seeds: Vec<AgentRowSeed>) -> Vec<RankedWorkRow> {
1882 let known_ids: HashSet<&str> = seeds.iter().map(|seed| seed.agent_id.as_str()).collect();
1883 let mut children: std::collections::HashMap<&str, Vec<usize>> =
1884 std::collections::HashMap::new();
1885 let mut roots = Vec::new();
1886 for (idx, seed) in seeds.iter().enumerate() {
1887 if let Some(parent) = seed.parent_run_id.as_deref()
1888 && known_ids.contains(parent)
1889 {
1890 children.entry(parent).or_default().push(idx);
1891 continue;
1892 }
1893 roots.push(idx);
1894 }
1895
1896 fn push_tree(
1897 idx: usize,
1898 depth: usize,
1899 seeds: &[AgentRowSeed],
1900 children: &std::collections::HashMap<&str, Vec<usize>>,
1901 seen: &mut HashSet<usize>,
1902 order: &mut Vec<(usize, usize)>,
1903 ) {
1904 if !seen.insert(idx) {
1905 return;
1906 }
1907 order.push((idx, depth));
1908 if let Some(child_indices) = children.get(seeds[idx].agent_id.as_str()) {
1909 for child_idx in child_indices {
1910 push_tree(*child_idx, depth + 1, seeds, children, seen, order);
1911 }
1912 }
1913 }
1914
1915 let mut order = Vec::with_capacity(seeds.len());
1916 let mut seen = HashSet::new();
1917 for idx in roots {
1918 push_tree(idx, 0, &seeds, &children, &mut seen, &mut order);
1919 }
1920 // Cycle/orphan backstop: emit anything the walk missed at the top level.
1921 for idx in 0..seeds.len() {
1922 push_tree(idx, 0, &seeds, &children, &mut seen, &mut order);
1923 }
1924
1925 // `(+N)` counts children that are actually on this surface: the same map
1926 // the tree walk used, so the badge can never promise a child the list does
1927 // not show. Snapshot it before `seeds` is consumed — `children` borrows it.
1928 let child_counts: Vec<usize> = seeds
1929 .iter()
1930 .map(|seed| {
1931 children
1932 .get(seed.agent_id.as_str())
1933 .map_or(0, |indices| indices.len())
1934 })
1935 .collect();
1936
1937 let mut slots: Vec<Option<AgentRowSeed>> = seeds.into_iter().map(Some).collect();
1938 order
1939 .into_iter()
1940 .enumerate()
1941 .map(|(position, (idx, depth))| {
1942 let seed = slots[idx].take().expect("each row emitted exactly once");
1943 let mut ranked = seed.ranked;
1944 let indent = agent_nesting_indent(depth.min(3));
1945 let role_label = agent_strip_label(&indent, &seed.role, child_counts[idx]);
1946 ranked.row.label = match seed.name.as_deref() {
1947 Some(name) => agent_strip_label(&indent, name, child_counts[idx]),
1948 None => role_label.clone(),
1949 };
1950 if let Some(facts) = ranked.row.agent.as_mut() {
1951 facts.role_label = role_label;
1952 }
1953 // `ordered_rows` re-sorts within status buckets by `order`; stamp
1954 // the tree position so a child sorts directly under its parent
1955 // whenever they share a bucket.
1956 ranked.order = position;
1957 ranked
1958 })
1959 .collect()
1960 }
1961
1962 fn agent_rows(app: &App) -> Vec<RankedWorkRow> {
1963 let cached_ids = app
1964 .subagent_cache
1965 .iter()
1966 .filter(|agent| !agent.from_prior_session)
1967 .map(|agent| agent.agent_id.as_str())
1968 .collect::<HashSet<_>>();
1969 let mut seeds = app
1970 .subagent_cache
1971 .iter()
1972 .filter(|agent| !agent.from_prior_session)
1973 .enumerate()
1974 .map(|(order, agent)| {
1975 let meta = app.agent_progress_meta.get(&agent.agent_id);
1976 let current_activity = meta.and_then(|meta| meta.current_activity.as_ref());
1977 let status = current_activity
1978 .map(|activity| current_activity_status_label(activity.status, app.ui_locale))
1979 .or_else(|| {
1980 agent
1981 .worker_status
1982 .map(|status| std::borrow::Cow::Borrowed(worker_status_label(status)))
1983 })
1984 .unwrap_or_else(|| {
1985 std::borrow::Cow::Borrowed(subagent_status_label(&agent.status))
1986 });
1987 let bucket = current_activity
1988 .map(|activity| current_activity_status_bucket(activity.status))
1989 .or_else(|| agent.worker_status.map(worker_status_bucket))
1990 .unwrap_or_else(|| subagent_status_bucket(&agent.status));
1991 // Read failure from the same source the bucket came from, so the
1992 // tone can never disagree with the row it is painting.
1993 let failed = current_activity.map_or_else(
1994 || {
1995 agent.worker_status.map_or_else(
1996 || matches!(agent.status, SubAgentStatus::Failed(_)),
1997 |status| matches!(status, AgentWorkerStatus::Failed),
1998 )
1999 },
2000 |activity| matches!(activity.status, AgentCurrentActivityStatus::Failed),
2001 );
2002 let resolved_profile = agent
2003 .child_route
2004 .as_ref()
2005 .and_then(|route| route.resolved_profile_id.as_deref())
2006 .map(str::trim)
2007 .filter(|profile| !profile.is_empty());
2008 let role = resolved_profile
2009 .or(agent
2010 .assignment
2011 .role
2012 .as_deref()
2013 .filter(|role| !role.trim().is_empty()))
2014 .unwrap_or_else(|| agent.agent_type.as_str())
2015 .to_string();
2016 // The dispatch name leads (#5287); a nickname or stable label
2017 // names the agents dispatched without one. Never the bare agent
2018 // id (#36) — absent rather than fabricated, so the identity
2019 // column falls back to the role.
2020 let name = app
2021 .agent_given_name(&agent.agent_id)
2022 .or_else(|| resolved_profile.map(str::to_string))
2023 .or_else(|| {
2024 agent
2025 .nickname
2026 .clone()
2027 .filter(|name| !name.trim().is_empty() && name != &agent.agent_id)
2028 })
2029 .or_else(|| app.agent_label_map.get(&agent.agent_id).cloned());
2030 let terminal = agent_is_terminal(agent, meta);
2031 // A finished agent's row says what it produced, not what it was
2032 // asked (#6565): the headline of its result, or why it stopped.
2033 // Enter opens the full text.
2034 let objective = terminal
2035 .then(|| crate::tui::agent_focus::settled_headline(app, &agent.agent_id))
2036 .flatten()
2037 .unwrap_or_else(|| summarize_assignment(&agent.assignment.objective));
2038 let mut facts = vec![status.to_string(), objective.clone()];
2039 // Quiet completion (#36): in-flight metadata (current tool, step
2040 // counters) is working state, not a receipt, and must not linger
2041 // after the run ends. What it changed is the receipt, so a
2042 // finished row keeps its file count.
2043 if terminal {
2044 if let Some(files) = meta
2045 .map(|meta| meta.files_touched)
2046 .filter(|count| *count > 0)
2047 {
2048 facts.push(
2049 tr(app.ui_locale, MessageId::BackgroundFilesChanged)
2050 .replace("{count}", &files.to_string()),
2051 );
2052 }
2053 } else {
2054 facts.extend(live_activity_facts(app, &agent.agent_id));
2055 facts.extend(quiet_fact(app, agent, meta));
2056 }
2057 AgentRowSeed {
2058 agent_id: agent.agent_id.clone(),
2059 parent_run_id: agent.parent_run_id.clone(),
2060 role,
2061 name,
2062 ranked: RankedWorkRow {
2063 bucket,
2064 order,
2065 is_plan_step: false,
2066 row: WorkRow {
2067 id: WorkRowId(format!("worker:{}", agent.agent_id)),
2068 mark: agent_mark(bucket),
2069 // Stamped by `order_agent_seeds` once the display
2070 // depth (and therefore the indent) is known.
2071 label: String::new(),
2072 detail: facts.join(" · "),
2073 tone: agent_tone(bucket, failed),
2074 selectable: true,
2075 // One agent, one destination (v0.9.7): activation
2076 // opens the agent's transcript directly; Agent
2077 // Details is the secondary action from there.
2078 primary_action: Some(SidebarRowAction::OpenAgentTranscript {
2079 agent_id: agent.agent_id.clone(),
2080 }),
2081 agent: Some(AgentRowFacts {
2082 // Stamped by `order_agent_seeds`, which is where
2083 // the indent and child count become known.
2084 role_label: String::new(),
2085 status: status.to_string(),
2086 objective,
2087 elapsed_secs: Some(agent_elapsed_ms(app, agent) / 1_000),
2088 model: meta.and_then(|meta| meta.resolved_model.clone()),
2089 tokens: meta.and_then(|meta| meta.received_tokens),
2090 todos_remaining: meta.and_then(|meta| meta.todos_remaining),
2091 holds_dock_open: bucket.is_actionable(),
2092 }),
2093 },
2094 },
2095 }
2096 })
2097 .collect::<Vec<_>>();
2098
2099 let mut progress_only = app
2100 .agent_progress
2101 .iter()
2102 .filter(|(id, _)| !cached_ids.contains(id.as_str()))
2103 .collect::<Vec<_>>();
2104 progress_only.sort_by_key(|(id, _)| (*id).clone());
2105 seeds.extend(
2106 progress_only
2107 .into_iter()
2108 .enumerate()
2109 .map(|(order, (id, _progress))| {
2110 let meta = app.agent_progress_meta.get(id);
2111 let current_activity = meta.and_then(|meta| meta.current_activity.as_ref());
2112 let status = current_activity
2113 .map(|activity| current_activity_status_label(activity.status, app.ui_locale))
2114 .unwrap_or(std::borrow::Cow::Borrowed("running"));
2115 let bucket = current_activity
2116 .map(|activity| current_activity_status_bucket(activity.status))
2117 .unwrap_or(WorkBucket::Active);
2118 let failed = current_activity
2119 .is_some_and(|a| matches!(a.status, AgentCurrentActivityStatus::Failed));
2120 let name = app.agent_label_map.get(id).cloned();
2121 let mut facts = vec![status.to_string()];
2122 facts.extend(live_activity_facts(app, id));
2123 AgentRowSeed {
2124 agent_id: id.clone(),
2125 parent_run_id: meta.and_then(|meta| meta.parent_run_id.clone()),
2126 // Role is unknown until the manager snapshot arrives;
2127 // "agent" is the honest fallback, not a fabrication.
2128 role: "agent".to_string(),
2129 name,
2130 ranked: RankedWorkRow {
2131 bucket,
2132 order: 5_000usize.saturating_add(order),
2133 is_plan_step: false,
2134 row: WorkRow {
2135 id: WorkRowId(format!("worker:{id}")),
2136 mark: agent_mark(bucket),
2137 label: String::new(),
2138 detail: facts.join(" · "),
2139 tone: agent_tone(bucket, failed),
2140 selectable: true,
2141 // Same destination as the cached-seed rows above.
2142 primary_action: Some(SidebarRowAction::OpenAgentTranscript {
2143 agent_id: id.clone(),
2144 }),
2145 agent: Some(AgentRowFacts {
2146 role_label: String::new(),
2147 status: status.to_string(),
2148 // No manager snapshot yet, so there is no
2149 // assignment to quote: the live activity line
2150 // is the honest answer to "what is it doing".
2151 // The status word itself is the status
2152 // column's job, so it is not repeated here.
2153 objective: facts[1..].join(" · "),
2154 // Neither a duration nor a usage envelope has
2155 // been seen for this id. Both render as
2156 // nothing rather than as `0s` / `0 tokens`.
2157 elapsed_secs: None,
2158 model: meta.and_then(|meta| meta.resolved_model.clone()),
2159 tokens: meta.and_then(|meta| meta.received_tokens),
2160 todos_remaining: meta.and_then(|meta| meta.todos_remaining),
2161 holds_dock_open: bucket.is_actionable(),
2162 }),
2163 },
2164 },
2165 }
2166 }),
2167 );
2168 order_agent_seeds(seeds)
2169 }
2170
2171 fn summarize_assignment(value: &str) -> String {
2172 // Flatten newlines the way the goal-title path does: a multi-line
2173 // objective must not break the one-line work-bar row (2026-08-04 review).
2174 let summary = codewhale_app_server::exec_agent::summarize_tool_output(value);
2175 if summary.contains(['\n', '\r']) {
2176 summary.replace(['\n', '\r'], " ")
2177 } else {
2178 summary
2179 }
2180 }
2181
2182 /// A running agent's live facts for its dock row, each said once (#6565).
2183 /// The activity detail usually already names the step and the tool ("step 6:
2184 /// finished tool 'read_file'"); repeating them as `using read_file · step 6`
2185 /// made every row say the same thing twice.
2186 fn live_activity_facts(app: &App, agent_id: &str) -> Vec<String> {
2187 let meta = app.agent_progress_meta.get(agent_id);
2188 let activity = meta.and_then(|meta| meta.current_activity.as_ref());
2189 let detail = activity.and_then(|activity| activity.detail.as_deref());
2190 let mut facts = Vec::new();
2191 if let Some(detail) = detail {
2192 facts.push(detail.to_string());
2193 }
2194 let said = |fact: &str| detail.is_some_and(|detail| names_whole(detail, fact));
2195 if let Some(tool) = activity.and_then(|activity| activity.current_tool.as_deref())
2196 && !said(tool)
2197 {
2198 facts.push(tr(app.ui_locale, MessageId::BackgroundUsingTool).replace("{tool}", tool));
2199 }
2200 if let Some(step) = activity.and_then(|activity| activity.step)
2201 && !said(&format!("step {step}"))
2202 {
2203 facts.push(
2204 tr(app.ui_locale, MessageId::BackgroundStep).replace("{step}", &step.to_string()),
2205 );
2206 }
2207 if let Some(files) = meta
2208 .map(|meta| meta.files_touched)
2209 .filter(|count| *count > 0)
2210 {
2211 facts.push(
2212 tr(app.ui_locale, MessageId::BackgroundFilesChanged)
2213 .replace("{count}", &files.to_string()),
2214 );
2215 }
2216 facts
2217 }
2218
2219 /// A running agent quiet this long says so on its row.
2220 const QUIET_AFTER_MS: u64 = 60_000;
2221
2222 /// `quiet 2m · auto-stop at 5m` for a running agent that has shown the manager
2223 /// no progress for a minute and has no tool in flight (#6565).
2224 ///
2225 /// This reads the engine's own clock (`idle_ms`, the one its heartbeat reads)
2226 /// and the bound that heartbeat enforces, capped by the last envelope the TUI
2227 /// saw from the child, because `AgentList` snapshots are not refreshed by
2228 /// ordinary progress. A tool in flight is never quiet: a long tool is expected, and the
2229 /// heartbeat bound sits above the tool timeout. When the engine does stop the
2230 /// agent, the row's result says so ("Auto-cancelled after 300s without
2231 /// sub-agent progress"), and Stop on the row ends it sooner.
2232 fn quiet_fact(
2233 app: &App,
2234 agent: &SubAgentResult,
2235 meta: Option<&AgentProgressMeta>,
2236 ) -> Option<String> {
2237 if agent.worker_status == Some(AgentWorkerStatus::RunningTool)
2238 || meta.and_then(|meta| meta.current_tool.as_ref()).is_some()
2239 {
2240 return None;
2241 }
2242 let since_snapshot = app.subagent_cache_received_at.map_or(0, |at| {
2243 u64::try_from(at.elapsed().as_millis()).unwrap_or(u64::MAX)
2244 });
2245 let mut idle = agent.idle_ms?.saturating_add(since_snapshot);
2246 // The snapshot is not refreshed by ordinary progress, so an agent that
2247 // kept working after it would otherwise read as quiet. Any envelope the
2248 // TUI saw from the child since then caps the estimate.
2249 if let Some(at) = meta.and_then(|meta| meta.last_progress_at) {
2250 idle = idle.min(u64::try_from(at.elapsed().as_millis()).unwrap_or(u64::MAX));
2251 }
2252 if idle < QUIET_AFTER_MS {
2253 return None;
2254 }
2255 let bound = agent.heartbeat_timeout_ms?;
2256 let coarse = |millis: u64| {
2257 let seconds = millis / 1_000;
2258 if seconds < 60 {
2259 format!("{seconds}s")
2260 } else {
2261 format!("{}m", seconds / 60)
2262 }
2263 };
2264 Some(
2265 tr(app.ui_locale, MessageId::BackgroundQuiet)
2266 .replace("{idle}", &coarse(idle.min(bound)))
2267 .replace("{bound}", &coarse(bound)),
2268 )
2269 }
2270
2271 /// Whether `text` names `fact` as a whole token: "step 1" is not said by
2272 /// "step 10", nor a tool `read` by "read_file".
2273 fn names_whole(text: &str, fact: &str) -> bool {
2274 let is_word = |c: char| c.is_alphanumeric() || c == '_';
2275 !fact.is_empty()
2276 && text.match_indices(fact).any(|(at, _)| {
2277 let before = text[..at].chars().next_back();
2278 let after = text[at + fact.len()..].chars().next();
2279 !before.is_some_and(is_word) && !after.is_some_and(is_word)
2280 })
2281 }
2282
2283 /// Has this agent stopped working? Typed live activity wins over the worker
2284 /// status, which in turn wins over the coarse manager status — the same
2285 /// precedence the row's status label and bucket already use.
2286 fn agent_is_terminal(agent: &SubAgentResult, meta: Option<&AgentProgressMeta>) -> bool {
2287 meta.and_then(|meta| meta.current_activity.as_ref())
2288 .map(|activity| {
2289 matches!(
2290 activity.status,
2291 AgentCurrentActivityStatus::Done
2292 | AgentCurrentActivityStatus::Canceled
2293 | AgentCurrentActivityStatus::Failed
2294 | AgentCurrentActivityStatus::Interrupted
2295 )
2296 })
2297 .or_else(|| {
2298 agent.worker_status.map(|worker_status| {
2299 matches!(
2300 worker_status,
2301 AgentWorkerStatus::Completed
2302 | AgentWorkerStatus::Cancelled
2303 | AgentWorkerStatus::Failed
2304 | AgentWorkerStatus::Interrupted
2305 )
2306 })
2307 })
2308 .unwrap_or(matches!(
2309 agent.status,
2310 SubAgentStatus::Completed
2311 | SubAgentStatus::Cancelled
2312 | SubAgentStatus::Failed(_)
2313 | SubAgentStatus::Interrupted(_)
2314 | SubAgentStatus::BudgetExhausted
2315 ))
2316 }
2317
2318 /// Latch each finished agent's elapsed time the first frame it is observed
2319 /// terminal, and forget agents that have left the cache.
2320 ///
2321 /// The manager recomputes `SubAgentResult::duration_ms` as
2322 /// `started_at.elapsed()` on every snapshot, so a completed agent's duration
2323 /// keeps growing for as long as it stays listed. Without this pass a finished
2324 /// row would tick forever, which is exactly the thing a receipt must not do.
2325 fn freeze_terminal_agent_elapsed(app: &mut App) {
2326 let live: HashSet<&str> = app
2327 .subagent_cache
2328 .iter()
2329 .map(|agent| agent.agent_id.as_str())
2330 .collect();
2331 app.work_surface
2332 .frozen_agent_elapsed_ms
2333 .retain(|id, _| live.contains(id.as_str()));
2334
2335 for agent in &app.subagent_cache {
2336 if !agent_is_terminal(agent, app.agent_progress_meta.get(&agent.agent_id)) {
2337 continue;
2338 }
2339 app.work_surface
2340 .frozen_agent_elapsed_ms
2341 .entry(agent.agent_id.clone())
2342 .or_insert(agent.duration_ms);
2343 }
2344 }
2345
2346 /// Frozen elapsed for a finished agent, live elapsed for a running one.
2347 fn agent_elapsed_ms(app: &App, agent: &codewhale_engine::tools::subagent::SubAgentResult) -> u64 {
2348 // Live ticking (4b): derive from start timestamp at render when running,
2349 // otherwise use frozen snapshot. The redraw already happens; stale cached
2350 // duration is the bug.
2351 if matches!(
2352 agent.status,
2353 codewhale_engine::tools::subagent::SubAgentStatus::Running
2354 ) && let Some(started_at) = agent.started_at
2355 {
2356 return u64::try_from(started_at.elapsed().as_millis()).unwrap_or(agent.duration_ms);
2357 }
2358 app.work_surface
2359 .frozen_agent_elapsed_ms
2360 .get(&agent.agent_id)
2361 .copied()
2362 .unwrap_or(agent.duration_ms)
2363 }
2364
2365 fn current_activity_status_bucket(status: AgentCurrentActivityStatus) -> WorkBucket {
2366 match status {
2367 AgentCurrentActivityStatus::Waiting
2368 | AgentCurrentActivityStatus::Interrupted
2369 | AgentCurrentActivityStatus::Failed => WorkBucket::Attention,
2370 // Not Attention (#5906): a parked husk asked nobody anything, so it
2371 // must not sort above live work nor be counted in the `needs input`
2372 // chip. Ready ranks below Attention and Active and stays actionable,
2373 // which is what it is — resumable, or dismissable.
2374 AgentCurrentActivityStatus::Parked | AgentCurrentActivityStatus::Queued => {
2375 WorkBucket::Ready
2376 }
2377 AgentCurrentActivityStatus::Done | AgentCurrentActivityStatus::Canceled => {
2378 WorkBucket::Recent
2379 }
2380 AgentCurrentActivityStatus::Starting
2381 | AgentCurrentActivityStatus::Running
2382 | AgentCurrentActivityStatus::ModelWait
2383 | AgentCurrentActivityStatus::RunningTool => WorkBucket::Active,
2384 }
2385 }
2386
2387 fn current_activity_status_label(
2388 status: AgentCurrentActivityStatus,
2389 locale: codewhale_localization::Locale,
2390 ) -> std::borrow::Cow<'static, str> {
2391 // `parked` is the one word here that has to be translated: it is new
2392 // vocabulary a reader has never seen on this row, and the whole point is
2393 // that it does not read as "waiting for input" (#5906).
2394 if status == AgentCurrentActivityStatus::Parked {
2395 return codewhale_localization::tr(
2396 locale,
2397 codewhale_localization::MessageId::AgentStatusParked,
2398 );
2399 }
2400 std::borrow::Cow::Borrowed(match status {
2401 AgentCurrentActivityStatus::Queued => "queued",
2402 AgentCurrentActivityStatus::Starting => "starting",
2403 AgentCurrentActivityStatus::Running => "running",
2404 AgentCurrentActivityStatus::ModelWait => "waiting for model",
2405 AgentCurrentActivityStatus::RunningTool => "running tool",
2406 AgentCurrentActivityStatus::Waiting => "waiting for input",
2407 AgentCurrentActivityStatus::Done => "completed",
2408 AgentCurrentActivityStatus::Failed => "failed",
2409 AgentCurrentActivityStatus::Canceled => "cancelled",
2410 AgentCurrentActivityStatus::Interrupted => "interrupted",
2411 AgentCurrentActivityStatus::Parked => unreachable!("handled above"),
2412 })
2413 }
2414
2415 fn worker_status_bucket(status: AgentWorkerStatus) -> WorkBucket {
2416 match status {
2417 AgentWorkerStatus::WaitingForUser
2418 | AgentWorkerStatus::Interrupted
2419 | AgentWorkerStatus::Failed => WorkBucket::Attention,
2420 AgentWorkerStatus::Queued => WorkBucket::Ready,
2421 AgentWorkerStatus::Completed | AgentWorkerStatus::Cancelled => WorkBucket::Recent,
2422 AgentWorkerStatus::Starting
2423 | AgentWorkerStatus::Running
2424 | AgentWorkerStatus::ModelWait
2425 | AgentWorkerStatus::RunningTool => WorkBucket::Active,
2426 }
2427 }
2428
2429 fn worker_status_label(status: AgentWorkerStatus) -> &'static str {
2430 match status {
2431 AgentWorkerStatus::Queued => "queued",
2432 AgentWorkerStatus::Starting => "starting",
2433 AgentWorkerStatus::Running => "running",
2434 AgentWorkerStatus::WaitingForUser => "waiting for input",
2435 AgentWorkerStatus::ModelWait => "waiting for model",
2436 AgentWorkerStatus::RunningTool => "running tool",
2437 AgentWorkerStatus::Completed => "completed",
2438 AgentWorkerStatus::Failed => "failed",
2439 AgentWorkerStatus::Cancelled => "cancelled",
2440 AgentWorkerStatus::Interrupted => "interrupted",
2441 }
2442 }
2443
2444 fn subagent_status_bucket(status: &SubAgentStatus) -> WorkBucket {
2445 match status {
2446 SubAgentStatus::Running => WorkBucket::Active,
2447 SubAgentStatus::Interrupted(_)
2448 | SubAgentStatus::Failed(_)
2449 | SubAgentStatus::BudgetExhausted => WorkBucket::Attention,
2450 SubAgentStatus::Completed | SubAgentStatus::Cancelled => WorkBucket::Recent,
2451 }
2452 }
2453
2454 fn subagent_status_label(status: &SubAgentStatus) -> &'static str {
2455 match status {
2456 SubAgentStatus::Running => "running",
2457 SubAgentStatus::Completed => "completed",
2458 SubAgentStatus::Interrupted(_) => "interrupted",
2459 SubAgentStatus::Failed(_) => "failed",
2460 SubAgentStatus::Cancelled => "cancelled",
2461 SubAgentStatus::BudgetExhausted => "budget exhausted",
2462 }
2463 }
2464
2465 /// `WorkBucket::Attention` deliberately groups a wait with a failure so they
2466 /// sort together — both need you. Tone must not follow it that far: only an
2467 /// actual failure spends Failure red.
2468 const fn agent_tone(bucket: WorkBucket, failed: bool) -> WorkTone {
2469 match bucket {
2470 WorkBucket::Attention if failed => WorkTone::Failure,
2471 other => bucket_tone(other),
2472 }
2473 }
2474
2475 const fn bucket_tone(bucket: WorkBucket) -> WorkTone {
2476 match bucket {
2477 WorkBucket::Active => WorkTone::Live,
2478 WorkBucket::Attention => WorkTone::Attention,
2479 WorkBucket::Ready => WorkTone::Muted,
2480 WorkBucket::Recent => WorkTone::Success,
2481 }
2482 }
2483
2484 const fn agent_mark(bucket: WorkBucket) -> &'static str {
2485 match bucket {
2486 WorkBucket::Active => codewhale_tui_kit::glyphs::SELECTION,
2487 WorkBucket::Attention => codewhale_tui_kit::glyphs::ATTENTION,
2488 WorkBucket::Ready => codewhale_tui_kit::glyphs::READY,
2489 WorkBucket::Recent => codewhale_tui_kit::glyphs::DONE,
2490 }
2491 }
2492
2493 pub(super) fn settled_file_activity(app: &App) -> SettledFileActivity {
2494 let mut activity = SettledFileActivity {
2495 locale: app.ui_locale,
2496 inline_diff_mode: app.inline_diff_mode,
2497 ..SettledFileActivity::default()
2498 };
2499 let mut seen = HashSet::new();
2500 for index in 0..app.virtual_cell_count() {
2501 let Some(HistoryCell::Tool(cell)) = app.cell_at_virtual_index(index) else {
2502 continue;
2503 };
2504 if !cell.is_success() {
2505 continue;
2506 }
2507 let Some(detail) = app.tool_detail_record_for_cell(index) else {
2508 continue;
2509 };
2510 let activity_tool_name = canonical_action_alias(&detail.tool_name, &detail.input);
2511 let kind = if matches!(cell, ToolCell::PatchSummary(_)) {
2512 Some(FileActivityKind::Write)
2513 } else {
2514 FileActivitySummary::from_tool_name(activity_tool_name)
2515 };
2516 let Some(kind) = kind else {
2517 continue;
2518 };
2519 if !seen.insert(detail.tool_id.as_str()) {
2520 continue;
2521 }
2522 activity.summary.record(kind);
2523 if kind == FileActivityKind::Write
2524 && let ToolCell::PatchSummary(mutation) = cell
2525 && let Some(receipt) = mutation.receipt.as_ref()
2526 {
2527 let additional_files =
2528 u32::try_from(receipt.files.len().saturating_sub(1)).unwrap_or(u32::MAX);
2529 activity.summary.files_written = activity
2530 .summary
2531 .files_written
2532 .saturating_add(additional_files);
2533 activity.mutations.push(receipt.clone());
2534 }
2535 let target = activity_target(&app.workspace, activity_tool_name, &detail.input, kind);
2536 let details = match kind {
2537 FileActivityKind::Read => &mut activity.read,
2538 FileActivityKind::List => &mut activity.list,
2539 FileActivityKind::Search => &mut activity.search,
2540 FileActivityKind::Write => &mut activity.write,
2541 };
2542 if let Some(target) = target
2543 && !details.contains(&target)
2544 {
2545 details.push(target);
2546 }
2547 }
2548 if let Some(session_id) = app.current_session_id.as_deref() {
2549 for ((owner, _), paths) in &app.delegated_writes {
2550 if owner != session_id {
2551 continue;
2552 }
2553 for raw_path in paths {
2554 if let Some(target) = privacy_safe_path(&app.workspace, raw_path)
2555 && !activity.write.contains(&target)
2556 {
2557 activity.summary.record(FileActivityKind::Write);
2558 activity.write.push(target);
2559 }
2560 }
2561 }
2562 }
2563 activity
2564 }
2565
2566 fn aggregate_activity_row(activity: &SettledFileActivity) -> Option<RankedWorkRow> {
2567 if activity.is_empty() {
2568 return None;
2569 }
2570 let locale = activity.locale;
2571 let summaries = activity.summary.compact_display(locale);
2572 if summaries.is_empty() {
2573 return None;
2574 }
2575 // Single aggregated live receipt; never inline raw patterns/commands (#4690).
2576 let label = if summaries.len() == 1 {
2577 summaries[0].clone()
2578 } else {
2579 summaries.join(" · ")
2580 };
2581 let mutation_detail = activity.mutations.last().map(|receipt| {
2582 if activity.inline_diff_mode == InlineDiffMode::Off {
2583 receipt.outcome_label(locale)
2584 } else {
2585 receipt.semantic_summary(locale)
2586 }
2587 });
2588 let mutation_body =
2589 settled_mutation_body(&activity.mutations, activity.inline_diff_mode, locale);
2590 let mut body_parts = Vec::new();
2591 if !mutation_body.is_empty() {
2592 body_parts.push(mutation_body);
2593 }
2594 for (kind, details) in [
2595 (tr(locale, MessageId::FileActivityReadLabel), &activity.read),
2596 (tr(locale, MessageId::FileActivityListLabel), &activity.list),
2597 (
2598 tr(locale, MessageId::FileActivitySearchLabel),
2599 &activity.search,
2600 ),
2601 (
2602 tr(locale, MessageId::FileActivityWriteLabel),
2603 &activity.write,
2604 ),
2605 ] {
2606 if details.is_empty() {
2607 continue;
2608 }
2609 body_parts.push(format!(
2610 "{kind}:\n{}",
2611 details[..details.len().min(12)].join("\n")
2612 ));
2613 }
2614 if body_parts.is_empty() {
2615 body_parts.push(tr(locale, MessageId::FileActivityNoDetail).into_owned());
2616 }
2617 let detail = mutation_detail
2618 .or_else(|| {
2619 activity
2620 .write
2621 .first()
2622 .cloned()
2623 .or_else(|| activity.read.first().cloned())
2624 .or_else(|| {
2625 activity
2626 .search
2627 .first()
2628 .map(|_| tr(locale, MessageId::FileActivityPatterns).into_owned())
2629 })
2630 .or_else(|| activity.list.first().cloned())
2631 })
2632 .unwrap_or_else(|| tr(locale, MessageId::FileActivitySettled).into_owned());
2633 let detail = sanitize_summary_title(&detail);
2634 Some(RankedWorkRow {
2635 bucket: WorkBucket::Recent,
2636 order: 20_000,
2637 is_plan_step: false,
2638 row: WorkRow {
2639 id: WorkRowId("activity:aggregate".to_string()),
2640 mark: codewhale_tui_kit::glyphs::DONE,
2641 label,
2642 detail,
2643 tone: WorkTone::Success,
2644 selectable: true,
2645 primary_action: Some(SidebarRowAction::InspectWork {
2646 title: tr(locale, MessageId::FileActivityDetailTitle).into_owned(),
2647 body: body_parts.join("\n\n"),
2648 stop_action: None,
2649 }),
2650 agent: None,
2651 },
2652 })
2653 }
2654
2655 #[cfg(test)]
2656 fn activity_rows(activity: SettledFileActivity) -> Vec<RankedWorkRow> {
2657 aggregate_activity_row(&activity).into_iter().collect()
2658 }
2659
2660 pub(super) fn settled_mutation_body(
2661 receipts: &[FileMutationReceipt],
2662 mode: InlineDiffMode,
2663 locale: Locale,
2664 ) -> String {
2665 let Some(receipt) = receipts.last() else {
2666 return String::new();
2667 };
2668 let details = crate::tui::key_shortcuts::tool_details_shortcut_action_hint(
2669 tr(locale, MessageId::FileMutationExactEvidence).as_ref(),
2670 );
2671 let hint = tr(locale, MessageId::FileMutationSelectReceipt).replace("{hint}", &details);
2672 match mode {
2673 InlineDiffMode::Off => format!("{}\n\n{hint}", receipt.outcome_label(locale)),
2674 InlineDiffMode::Summary => format!("{}\n\n{hint}", receipt.semantic_summary(locale)),
2675 InlineDiffMode::Full => {
2676 let diff = receipt
2677 .display_diff
2678 .lines()
2679 .take(40)
2680 .collect::<Vec<_>>()
2681 .join("\n");
2682 if diff.trim().is_empty() {
2683 format!("{}\n\n{hint}", receipt.semantic_summary(locale))
2684 } else {
2685 format!("{}\n\n{diff}\n\n{hint}", receipt.semantic_summary(locale))
2686 }
2687 }
2688 }
2689 }
2690
2691 fn activity_target(
2692 workspace: &Path,
2693 tool_name: &str,
2694 input: &serde_json::Value,
2695 kind: FileActivityKind,
2696 ) -> Option<String> {
2697 if tool_name == "apply_patch"
2698 && let Ok(preflight) = codewhale_tools::patch_preflight::preflight_apply_patch(input)
2699 {
2700 let targets = preflight
2701 .touched_files
2702 .iter()
2703 .filter_map(|path| privacy_safe_path(workspace, path))
2704 .take(4)
2705 .collect::<Vec<_>>();
2706 if !targets.is_empty() {
2707 return Some(targets.join(", "));
2708 }
2709 }
2710 let keys: &[&str] = match kind {
2711 FileActivityKind::Search => &["pattern", "query", "path"],
2712 _ => &["path", "file_path"],
2713 };
2714 keys.iter().find_map(|key| {
2715 let value = input.get(*key)?.as_str()?.trim();
2716 if value.is_empty() {
2717 return None;
2718 }
2719 if kind == FileActivityKind::Search && *key != "path" {
2720 return Some(safe_pattern(value));
2721 }
2722 privacy_safe_path(workspace, value)
2723 })
2724 }
2725
2726 fn privacy_safe_path(workspace: &Path, raw: &str) -> Option<String> {
2727 let path = Path::new(raw);
2728 let normalized_raw = raw.replace('\\', "/");
2729 let normalized_workspace = workspace.to_string_lossy().replace('\\', "/");
2730 let relative = if path.is_absolute() || normalized_raw.starts_with('/') {
2731 let workspace_prefix = normalized_workspace.trim_end_matches('/');
2732 if normalized_raw == workspace_prefix {
2733 ""
2734 } else {
2735 normalized_raw.strip_prefix(&format!("{workspace_prefix}/"))?
2736 }
2737 } else {
2738 normalized_raw.as_str()
2739 };
2740 let relative = Path::new(relative);
2741 if relative.components().any(|component| {
2742 matches!(
2743 component,
2744 Component::ParentDir | Component::RootDir | Component::Prefix(_)
2745 )
2746 }) {
2747 return None;
2748 }
2749 let display = relative.to_string_lossy().replace('\\', "/");
2750 (!display.is_empty()).then_some(display)
2751 }
2752
2753 fn safe_pattern(raw: &str) -> String {
2754 let single_line = raw.replace(['\n', '\r', '\t'], " ");
2755 let mut chars = single_line.chars();
2756 let prefix = chars.by_ref().take(80).collect::<String>();
2757 if chars.next().is_some() {
2758 format!("{prefix}…")
2759 } else {
2760 prefix
2761 }
2762 }
2763
2764 fn is_settled_transient_operation(node: &WorkNode) -> bool {
2765 node.kind == NodeKind::Operation
2766 && node
2767 .binding
2768 .as_ref()
2769 .is_some_and(|binding| !binding.durable)
2770 && match node.state {
2771 NodeState::Completed => node.acceptance.is_empty(),
2772 NodeState::Verified | NodeState::Superseded | NodeState::Cancelled => true,
2773 _ => false,
2774 }
2775 }
2776
2777 fn section_heading(id: &str, label: &str, detail: &str) -> WorkRow {
2778 WorkRow {
2779 id: WorkRowId(format!("section:{id}")),
2780 mark: "▾",
2781 label: label.to_string(),
2782 detail: detail.to_string(),
2783 tone: WorkTone::Heading,
2784 selectable: false,
2785 primary_action: None,
2786 agent: None,
2787 }
2788 }
2789
2790 /// The sub-agent heading is a real group door: selecting it reveals the full
2791 /// Agents panel, including settled workers whose exact transcripts remain
2792 /// available after the compact strip archives them.
2793 fn agents_section_heading(label: &str) -> WorkRow {
2794 WorkRow {
2795 id: WorkRowId("section:agents".to_string()),
2796 mark: "▾",
2797 label: label.to_string(),
2798 detail: "Open the full subagent register".to_string(),
2799 tone: WorkTone::Heading,
2800 selectable: true,
2801 primary_action: Some(SidebarRowAction::ShowSubagentsPanel),
2802 agent: None,
2803 }
2804 }
2805
2806 fn with_live_shell_rows(app: &App, mut rows: Vec<WorkRow>) -> Vec<WorkRow> {
2807 rows.retain(|row| !row.id.0.starts_with("shell:") && row.id.0 != "section:shells");
2808 let shells = shell_work_rows(app);
2809 if shells.is_empty() {
2810 return rows;
2811 }
2812 let mut out = Vec::with_capacity(rows.len() + shells.len() + 1);
2813 push_shell_group(&mut out, shells);
2814 out.extend(rows);
2815 out
2816 }
2817
2818 fn push_shell_group(out: &mut Vec<WorkRow>, shells: Vec<WorkRow>) {
2819 if shells.is_empty() {
2820 return;
2821 }
2822 out.push(shells_section_heading(&shells));
2823 out.extend(shells);
2824 }
2825
2826 fn shell_work_rows(app: &App) -> Vec<WorkRow> {
2827 app.task_panel
2828 .iter()
2829 .filter(|entry| is_live_shell_entry(entry))
2830 .map(|entry| {
2831 let command = shell_command(entry);
2832 let command = command.as_str();
2833 let status = if entry.stale {
2834 "stale"
2835 } else {
2836 entry.status.as_str()
2837 };
2838 let elapsed_secs = entry.duration_ms.map(|ms| ms / 1_000);
2839 let objective = command.to_string();
2840 WorkRow {
2841 id: WorkRowId(format!("shell:{}", entry.id)),
2842 mark: agent_mark(WorkBucket::Active),
2843 // The command is what a person recognises; the id stays in
2844 // the detail and the inspector (#6565).
2845 label: objective.clone(),
2846 detail: format!("{status} · {}", entry.id),
2847 tone: WorkTone::Live,
2848 selectable: true,
2849 primary_action: shell_show_action(entry),
2850 agent: Some(AgentRowFacts {
2851 role_label: "shell".to_string(),
2852 status: status.to_string(),
2853 objective,
2854 elapsed_secs,
2855 model: None,
2856 tokens: None,
2857 todos_remaining: None,
2858 // Only live shells reach this list; the agents counter
2859 // never sees a `shell:` row either way.
2860 holds_dock_open: true,
2861 }),
2862 }
2863 })
2864 .collect()
2865 }
2866
2867 fn shells_section_heading(shells: &[WorkRow]) -> WorkRow {
2868 let ids: Vec<&str> = shells
2869 .iter()
2870 .filter_map(|row| row.id.0.strip_prefix("shell:"))
2871 .collect();
2872 let listing = if ids.is_empty() {
2873 String::new()
2874 } else {
2875 format!(
2876 "{}\n\n",
2877 ids.iter()
2878 .map(|id| format!("- {id}"))
2879 .collect::<Vec<_>>()
2880 .join("\n")
2881 )
2882 };
2883 WorkRow {
2884 id: WorkRowId("section:shells".to_string()),
2885 mark: "▾",
2886 label: format!("Shells {}", shells.len()),
2887 detail: "Watch live output · cancel by the id on the row".to_string(),
2888 tone: WorkTone::Heading,
2889 selectable: true,
2890 primary_action: Some(SidebarRowAction::InspectWork {
2891 title: format!("Shells {}", shells.len()),
2892 body: format!(
2893 "Running shells ({})\n\n{listing}Open a row to watch output. Cancel with /jobs cancel <id> or /jobs cancel all.",
2894 shells.len()
2895 ),
2896 stop_action: Some(Box::new(SidebarRowAction::Command(
2897 "/jobs cancel all".to_string(),
2898 ))),
2899 }),
2900 agent: None,
2901 }
2902 }
2903
2904 fn graph_node_row(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> WorkRow {
2905 let (mark, tone) = match node.state {
2906 NodeState::Ready => (codewhale_tui_kit::glyphs::READY, WorkTone::Muted),
2907 NodeState::Initializing => (codewhale_tui_kit::glyphs::SELECTION, WorkTone::Live),
2908 NodeState::Active => (codewhale_tui_kit::glyphs::SELECTION, WorkTone::Live),
2909 NodeState::Waiting => (codewhale_tui_kit::glyphs::ATTENTION, WorkTone::Attention),
2910 NodeState::Blocked => (
2911 status_mark(StatusKind::Attention).glyph,
2912 WorkTone::Attention,
2913 ),
2914 NodeState::Completed if node.acceptance.is_empty() => {
2915 (status_mark(StatusKind::Done).glyph, WorkTone::Success)
2916 }
2917 NodeState::Completed => (
2918 status_mark(StatusKind::Attention).glyph,
2919 WorkTone::Attention,
2920 ),
2921 NodeState::Verified => (status_mark(StatusKind::Done).glyph, WorkTone::Success),
2922 NodeState::Stale => ("?", WorkTone::Attention),
2923 NodeState::Superseded | NodeState::Cancelled => ("−", WorkTone::Muted),
2924 NodeState::Failed => (codewhale_tui_kit::glyphs::FAILED, WorkTone::Failure),
2925 };
2926 let state = state_label(node);
2927 let kind = kind_label(node.kind);
2928 // A to-do row always carries its status word in the detail column, using
2929 // the same vocabulary as `/task digest` (pending / in progress /
2930 // completed / cancelled). Only the redundant `· plan step` KIND suffix is
2931 // dropped — the strip's checkbox marks already say the row is a plan
2932 // step, but they do not say its state in words, and dropping the state
2933 // itself was the 0.9.4 regression (a pending to-do rendered no label at
2934 // all). Non-step nodes keep the state · kind pair.
2935 let detail = if node.kind == NodeKind::PlanStep {
2936 todo_state_label(node).to_string()
2937 } else {
2938 format!("{state} · {kind}")
2939 };
2940 let stop_action = node
2941 .state
2942 .is_live()
2943 .then(|| stop_action(node.binding.as_ref()))
2944 .flatten();
2945 WorkRow {
2946 id: WorkRowId(format!("graph:{}", node.id.as_str())),
2947 mark,
2948 label: node.title.clone(),
2949 detail,
2950 tone,
2951 selectable: true,
2952 primary_action: Some(SidebarRowAction::InspectWork {
2953 title: format!("Work · {}", node.title),
2954 body: inspector_text(snapshot, node),
2955 stop_action: stop_action.map(Box::new),
2956 }),
2957 agent: None,
2958 }
2959 }
2960
2961 /// Status word for a plan-step (to-do) row, aligned with the four-state
2962 /// To-do vocabulary the `/task digest` text surface uses. Graph-only states
2963 /// keep their graph names.
2964 fn todo_state_label(node: &WorkNode) -> &'static str {
2965 match node.state {
2966 NodeState::Ready => "pending",
2967 NodeState::Initializing | NodeState::Active => "in progress",
2968 _ => state_label(node),
2969 }
2970 }
2971
2972 fn state_label(node: &WorkNode) -> &'static str {
2973 match node.state {
2974 NodeState::Ready => "ready",
2975 NodeState::Initializing => "initializing",
2976 NodeState::Active => "running",
2977 NodeState::Waiting => "waiting",
2978 NodeState::Blocked => "blocked",
2979 NodeState::Completed if node.acceptance.is_empty() => "completed",
2980 NodeState::Completed => "completed · evidence pending",
2981 NodeState::Verified => "verified",
2982 NodeState::Stale => "stale",
2983 NodeState::Superseded => "superseded",
2984 NodeState::Cancelled => "cancelled",
2985 NodeState::Failed => "failed",
2986 }
2987 }
2988
2989 const fn kind_label(kind: NodeKind) -> &'static str {
2990 match kind {
2991 NodeKind::Objective => "objective",
2992 NodeKind::PlanStep => "plan step",
2993 NodeKind::Operation => "operation",
2994 NodeKind::Evidence => "evidence",
2995 NodeKind::Blocker => "blocker",
2996 NodeKind::Approval => "approval",
2997 NodeKind::RuntimeRef => "runtime",
2998 NodeKind::LaneRef => "lane",
2999 }
3000 }
3001
3002 fn stop_action(binding: Option<&OperationBinding>) -> Option<SidebarRowAction> {
3003 let binding = binding?;
3004 if let Some(id) = binding.external.strip_prefix("task:") {
3005 Some(SidebarRowAction::Command(format!("/task cancel {id}")))
3006 } else if let Some(id) = binding.external.strip_prefix("shell:") {
3007 Some(SidebarRowAction::Command(format!("/jobs cancel {id}")))
3008 } else if let Some(id) = binding.external.strip_prefix("worker:") {
3009 Some(SidebarRowAction::CancelAgent {
3010 agent_id: id.to_string(),
3011 })
3012 } else {
3013 binding
3014 .external
3015 .strip_prefix("workflow:")
3016 .map(|id| SidebarRowAction::Command(format!("/workflow cancel {id}")))
3017 }
3018 }
3019
3020 fn inspector_text(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
3021 let mut out = String::new();
3022 section_text(
3023 &mut out,
3024 "Objective",
3025 objective_for(snapshot, node)
3026 .as_deref()
3027 .unwrap_or("Not connected"),
3028 );
3029 section_list(
3030 &mut out,
3031 "Prerequisites",
3032 related_nodes(snapshot, node, EdgeKind::DependsOn, true),
3033 );
3034 section_text(
3035 &mut out,
3036 "Current",
3037 &format!("{} · {}", state_label(node), kind_label(node.kind)),
3038 );
3039 section_list(
3040 &mut out,
3041 "Downstream impact",
3042 related_nodes(snapshot, node, EdgeKind::DependsOn, false),
3043 );
3044 section_text(&mut out, "Binding + lifecycle owner", &binding_text(node));
3045 section_text(
3046 &mut out,
3047 "Evidence vs acceptance",
3048 &evidence_text(snapshot, node),
3049 );
3050 section_text(
3051 &mut out,
3052 "Blockers / approvals",
3053 &blockers_approvals_text(snapshot, node),
3054 );
3055 section_text(&mut out, "Why next", &why_next(snapshot, node));
3056 section_text(
3057 &mut out,
3058 "Provenance + last reconcile",
3059 &provenance_text(node),
3060 );
3061 if node.state == NodeState::Stale {
3062 section_text(
3063 &mut out,
3064 "Last bounded output",
3065 last_output_ref(snapshot, node)
3066 .as_deref()
3067 .unwrap_or("No output receipt"),
3068 );
3069 }
3070 out.trim_end().to_string()
3071 }
3072
3073 fn objective_for(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> Option<String> {
3074 if node.kind == NodeKind::Objective {
3075 return Some(node.title.clone());
3076 }
3077 let mut current = node.id.clone();
3078 let mut seen = HashSet::new();
3079 while seen.insert(current.clone()) {
3080 let Some(parent) = snapshot.edges.iter().find_map(|edge| {
3081 (edge.kind == EdgeKind::Contains && edge.to == current).then(|| edge.from.clone())
3082 }) else {
3083 break;
3084 };
3085 let Some(parent_node) = snapshot.node(&parent) else {
3086 break;
3087 };
3088 if parent_node.kind == NodeKind::Objective {
3089 return Some(parent_node.title.clone());
3090 }
3091 current = parent;
3092 }
3093 snapshot.compat.plan.objective.clone()
3094 }
3095
3096 fn related_nodes(
3097 snapshot: &WorkGraphSnapshot,
3098 node: &WorkNode,
3099 kind: EdgeKind,
3100 outgoing: bool,
3101 ) -> Vec<String> {
3102 snapshot
3103 .edges
3104 .iter()
3105 .filter(|edge| edge.kind == kind)
3106 .filter_map(|edge| {
3107 let related = if outgoing && edge.from == node.id {
3108 Some(&edge.to)
3109 } else if !outgoing && edge.to == node.id {
3110 Some(&edge.from)
3111 } else {
3112 None
3113 }?;
3114 snapshot
3115 .node(related)
3116 .map(|related| format!("{} · {}", related.title, state_label(related)))
3117 })
3118 .collect()
3119 }
3120
3121 fn binding_text(node: &WorkNode) -> String {
3122 let Some(binding) = node.binding.as_ref() else {
3123 return "Not bound".to_string();
3124 };
3125 let mut text = format!(
3126 "Owner: {}\nDurable: {}",
3127 binding.external,
3128 if binding.durable { "yes" } else { "no" }
3129 );
3130 if let Some(observation) = binding.last_observation.as_ref() {
3131 let owner_state = match observation.owner_state {
3132 OwnerState::Initializing => "initializing",
3133 OwnerState::Running => "running",
3134 OwnerState::Waiting => "waiting",
3135 OwnerState::Completed => "completed",
3136 OwnerState::Degraded => "degraded (finished with dropped slots)",
3137 OwnerState::Failed => "failed",
3138 OwnerState::Cancelled => "cancelled",
3139 };
3140 let _ = write!(
3141 text,
3142 "\nLast owner state: {owner_state}\nLast reconcile: {} ms UTC · sequence {}",
3143 observation.observed_at, observation.seq
3144 );
3145 } else {
3146 text.push_str("\nLast reconcile: never");
3147 }
3148 text
3149 }
3150
3151 fn evidence_text(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
3152 let acceptance = if node.acceptance.is_empty() {
3153 vec!["- No evidence requirement".to_string()]
3154 } else {
3155 node.acceptance
3156 .iter()
3157 .map(|requirement| format!("- {}", acceptance_label(requirement)))
3158 .collect()
3159 };
3160 let evidence = evidence_for(snapshot, node);
3161 let evidence = if evidence.is_empty() {
3162 vec!["- None attached".to_string()]
3163 } else {
3164 evidence
3165 .into_iter()
3166 .map(|evidence| {
3167 let reference = evidence
3168 .evidence
3169 .as_ref()
3170 .map(|item| item.reference())
3171 .unwrap_or("invalid evidence node");
3172 format!("- {reference} · {}", state_label(evidence))
3173 })
3174 .collect()
3175 };
3176 format!(
3177 "Acceptance:\n{}\nEvidence:\n{}",
3178 acceptance.join("\n"),
3179 evidence.join("\n")
3180 )
3181 }
3182
3183 fn acceptance_label(requirement: &AcceptanceRequirement) -> String {
3184 match requirement {
3185 AcceptanceRequirement::EvidenceOfKind { kind } => {
3186 let kind = match kind {
3187 EvidenceKindTag::ToolRun => "tool run",
3188 EvidenceKindTag::Artifact => "artifact",
3189 EvidenceKindTag::TestSummary => "test summary",
3190 EvidenceKindTag::Receipt => "receipt",
3191 EvidenceKindTag::Approval => "approval",
3192 EvidenceKindTag::Route => "route",
3193 EvidenceKindTag::WebCitation => "web citation",
3194 };
3195 format!("evidence of kind {kind}")
3196 }
3197 }
3198 }
3199
3200 fn evidence_for<'a>(snapshot: &'a WorkGraphSnapshot, node: &WorkNode) -> Vec<&'a WorkNode> {
3201 snapshot
3202 .edges
3203 .iter()
3204 .filter(|edge| edge.kind == EdgeKind::Verifies && edge.to == node.id)
3205 .filter_map(|edge| snapshot.node(&edge.from))
3206 .collect()
3207 }
3208
3209 fn blockers_approvals_text(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
3210 let mut lines = Vec::new();
3211 lines.extend(
3212 related_nodes(snapshot, node, EdgeKind::Blocks, false)
3213 .into_iter()
3214 .map(|item| format!("- Blocked by {item}")),
3215 );
3216 lines.extend(
3217 related_nodes(snapshot, node, EdgeKind::RequiresApproval, true)
3218 .into_iter()
3219 .map(|item| format!("- Approval {item}")),
3220 );
3221 if node.kind == NodeKind::PlanStep {
3222 lines.extend(
3223 snapshot
3224 .nodes
3225 .iter()
3226 .filter(|candidate| candidate.kind == NodeKind::Approval)
3227 .map(|approval| format!("- {} · {}", approval.title, state_label(approval))),
3228 );
3229 }
3230 if lines.is_empty() {
3231 "None".to_string()
3232 } else {
3233 lines.join("\n")
3234 }
3235 }
3236
3237 fn why_next(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
3238 match node.state {
3239 NodeState::Ready => {
3240 let pending = related_nodes(snapshot, node, EdgeKind::DependsOn, true);
3241 if pending.is_empty() {
3242 "Ready with no recorded prerequisite".to_string()
3243 } else {
3244 format!("Ready after: {}", pending.join(", "))
3245 }
3246 }
3247 NodeState::Initializing => "Spawn intent is registered; awaiting owner handle".to_string(),
3248 NodeState::Active => "Lifecycle owner reports active work".to_string(),
3249 NodeState::Waiting => "Waiting on an owner or approval".to_string(),
3250 NodeState::Blocked => "Blocked; resolve the causes above".to_string(),
3251 NodeState::Completed if !node.acceptance.is_empty() => {
3252 "Execution ended, but acceptance evidence is still missing".to_string()
3253 }
3254 NodeState::Stale => "Owner cannot confirm liveness after reconciliation".to_string(),
3255 NodeState::Verified => "Acceptance evidence is satisfied".to_string(),
3256 NodeState::Completed => "Completed with no evidence requirement".to_string(),
3257 NodeState::Superseded => "A replacement node owns this work".to_string(),
3258 NodeState::Cancelled => "Cancelled by lifecycle owner".to_string(),
3259 NodeState::Failed => "Failed; inspect owner output before retrying".to_string(),
3260 }
3261 }
3262
3263 fn provenance_text(node: &WorkNode) -> String {
3264 let provenance = match &node.provenance {
3265 Provenance::Import { ordinal, .. } => ordinal
3266 .map(|ordinal| format!("legacy import · ordinal {ordinal}"))
3267 .unwrap_or_else(|| "legacy import".to_string()),
3268 Provenance::ToolUpdate { tool, call_id } => {
3269 format!("tool {tool} · call {call_id}")
3270 }
3271 Provenance::RuntimeReconcile {
3272 source,
3273 observed_at,
3274 } => format!("runtime {source} · {observed_at} ms UTC"),
3275 Provenance::UserEdit { proposal_id } => format!("user-approved diff {proposal_id}"),
3276 };
3277 let reconcile = node
3278 .binding
3279 .as_ref()
3280 .and_then(|binding| binding.last_observation.as_ref())
3281 .map(|observation| format!("{} ms UTC", observation.observed_at))
3282 .unwrap_or_else(|| "never".to_string());
3283 format!("Source: {provenance}\nLast reconcile: {reconcile}")
3284 }
3285
3286 fn last_output_ref(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> Option<String> {
3287 node.binding
3288 .as_ref()
3289 .and_then(|binding| binding.last_observation.as_ref())
3290 .and_then(|observation| observation.output.as_ref())
3291 .map(format_evidence_ref)
3292 .or_else(|| {
3293 evidence_for(snapshot, node)
3294 .into_iter()
3295 .max_by_key(|evidence| evidence.updated_at)
3296 .and_then(|evidence| evidence.evidence.as_ref())
3297 .map(format_evidence_ref)
3298 })
3299 }
3300
3301 fn format_evidence_ref(evidence: &codewhale_engine::work_graph::EvidenceRef) -> String {
3302 let kind = match evidence.kind() {
3303 EvidenceKind::ToolRun => "tool run".to_string(),
3304 EvidenceKind::Artifact { .. } => "artifact".to_string(),
3305 EvidenceKind::TestSummary => "test summary".to_string(),
3306 EvidenceKind::Receipt { .. } => "receipt".to_string(),
3307 EvidenceKind::Approval => "approval".to_string(),
3308 EvidenceKind::Route => "route".to_string(),
3309 EvidenceKind::WebCitation {
3310 url, retrieved_at, ..
3311 } => format!("web citation · {url} · retrieved {retrieved_at}"),
3312 };
3313 let bytes = evidence
3314 .raw_bytes()
3315 .map(|bytes| format!(" · {bytes} raw bytes"))
3316 .unwrap_or_default();
3317 let truncation = if evidence.truncated() {
3318 " · truncated"
3319 } else {
3320 ""
3321 };
3322 format!("{} · {kind}{bytes}{truncation}", evidence.reference())
3323 }
3324
3325 fn section_text(out: &mut String, title: &str, body: &str) {
3326 let _ = writeln!(out, "{title}\n{body}\n");
3327 }
3328
3329 fn section_list(out: &mut String, title: &str, items: Vec<String>) {
3330 if items.is_empty() {
3331 section_text(out, title, "None");
3332 } else {
3333 section_text(
3334 out,
3335 title,
3336 &items
3337 .into_iter()
3338 .map(|item| format!("- {item}"))
3339 .collect::<Vec<_>>()
3340 .join("\n"),
3341 );
3342 }
3343 }
3344
3345 #[cfg(test)]
3346 mod tests {
3347 use super::*;
3348 use codewhale_engine::tools::spec::ToolResult;
3349 use codewhale_runtime::config::Config;
3350
3351 /// #6565: a fact is dropped from a dock row only when the detail names
3352 /// that exact fact, never a longer one that contains it.
3353 #[test]
3354 fn a_fact_is_said_only_by_its_whole_name() {
3355 assert!(names_whole("step 6: finished tool 'read_file'", "step 6"));
3356 assert!(names_whole(
3357 "step 6: finished tool 'read_file'",
3358 "read_file"
3359 ));
3360 assert!(!names_whole("step 10: finished tool 'read_file'", "step 1"));
3361 assert!(!names_whole("finished tool 'read_file'", "read"));
3362 assert!(names_whole("read then step 1", "step 1"));
3363 assert!(!names_whole("anything", ""));
3364 }
3365 use crate::tui::app::TuiOptions;
3366 use crate::tui::tool_routing::{handle_tool_call_complete, handle_tool_call_started};
3367 use codewhale_engine::work_graph::{CompatTodoBinding, OperationBinding, WorkNodeId};
3368
3369 fn test_app() -> App {
3370 App::new(
3371 TuiOptions {
3372 model: "deepseek-v4-flash".to_string(),
3373 start_in_agent_mode: true,
3374 ..crate::tui::test_support::test_tui_options(std::path::PathBuf::from(
3375 "/workspace/project",
3376 ))
3377 },
3378 &Config::default(),
3379 )
3380 }
3381
3382 fn surface() -> WorkSurfaceState {
3383 WorkSurfaceState::default()
3384 }
3385
3386 fn operation(state: NodeState, suffix: &str) -> WorkNode {
3387 WorkNode {
3388 id: WorkNodeId::derive("work-surface-test", suffix),
3389 kind: NodeKind::Operation,
3390 title: format!("operation {suffix}"),
3391 state,
3392 acceptance: Vec::new(),
3393 binding: Some(OperationBinding {
3394 external: format!("shell:{suffix}"),
3395 durable: false,
3396 last_observation: None,
3397 }),
3398 evidence: None,
3399 provenance: Provenance::ToolUpdate {
3400 tool: "test".to_string(),
3401 call_id: suffix.to_string(),
3402 },
3403 created_at: 1,
3404 updated_at: 1,
3405 }
3406 }
3407
3408 fn running_agent(agent_id: &str) -> SubAgentResult {
3409 SubAgentResult {
3410 usage: None,
3411 name: agent_id.to_string(),
3412 agent_id: agent_id.to_string(),
3413 context_mode: "fresh".to_string(),
3414 fork_context: false,
3415 workspace: None,
3416 git_branch: None,
3417 agent_type: codewhale_agent_contract::role::FleetRole::Worker,
3418 assignment: codewhale_engine::tools::subagent::SubAgentAssignment {
3419 native_preset: None,
3420 objective: "sweep the lane".to_string(),
3421 role: Some("builder".to_string()),
3422 },
3423 model: "test-model".to_string(),
3424 nickname: Some(
3425 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(agent_id, "en"),
3426 ),
3427 status: SubAgentStatus::Running,
3428 worker_status: None,
3429 runtime_permissions: None,
3430 parent_run_id: None,
3431 spawn_depth: 0,
3432 child_route: None,
3433 result: None,
3434 steps_taken: 1,
3435 checkpoint: None,
3436 needs_input: None,
3437 duration_ms: 100,
3438 started_at: None,
3439 from_prior_session: false,
3440 idle_ms: None,
3441 heartbeat_timeout_ms: None,
3442 }
3443 }
3444
3445 fn retained_agent_receipt(
3446 id: &str,
3447 status: AgentWorkerStatus,
3448 state: codewhale_engine::agent_roster::RosterState,
3449 ) -> codewhale_engine::agent_roster::AgentRosterRow {
3450 codewhale_engine::agent_roster::AgentRosterRow {
3451 worker_id: id.to_string(),
3452 display_name: format!("retained {id}"),
3453 model: "test-model".to_string(),
3454 state,
3455 status,
3456 activity: None,
3457 outcome: None,
3458 millis: Some(3_000),
3459 input_tokens: None,
3460 output_tokens: None,
3461 cost_microusd: None,
3462 steps_taken: 3,
3463 parent_run_id: None,
3464 run_id: id.to_string(),
3465 }
3466 }
3467
3468 /// The register merges the retained roster with the live cache; the
3469 /// counter that opens the dock has to read the same merged view, or a
3470 /// child blocked on a person goes unseen the moment its 45-second card
3471 /// expires (or a session restore filters it out of `subagent_cache`).
3472 #[test]
3473 fn a_roster_only_waiting_worker_opens_the_dock() {
3474 use codewhale_engine::agent_roster::RosterState;
3475
3476 let mut app = test_app();
3477 app.current_session_id = Some("roster-owner".to_string());
3478 app.agent_roster_session_id = app.current_session_id.clone();
3479 assert!(app.subagent_cache.is_empty());
3480 app.agent_roster = vec![retained_agent_receipt(
3481 "blocked",
3482 AgentWorkerStatus::WaitingForUser,
3483 RosterState::Waiting,
3484 )];
3485
3486 assert_eq!(live_agent_row_count(&mut app), 1);
3487 assert!(view_has_work(&mut app, RailPanel::Agents));
3488 }
3489
3490 /// The other half of reading the roster: it is retained for an hour, so a
3491 /// settled receipt must not pin the dock open for the rest of the session.
3492 /// A parked husk counts as settled too — nothing will answer it (#5906).
3493 #[test]
3494 fn retained_settled_receipts_do_not_hold_the_dock_open() {
3495 use codewhale_engine::agent_roster::RosterState;
3496
3497 let mut app = test_app();
3498 app.current_session_id = Some("roster-owner".to_string());
3499 app.agent_roster_session_id = app.current_session_id.clone();
3500 app.agent_roster = vec![
3501 retained_agent_receipt("done", AgentWorkerStatus::Completed, RosterState::Done),
3502 retained_agent_receipt("failed", AgentWorkerStatus::Failed, RosterState::Failed),
3503 retained_agent_receipt(
3504 "cancelled",
3505 AgentWorkerStatus::Cancelled,
3506 RosterState::Cancelled,
3507 ),
3508 retained_agent_receipt(
3509 "parked",
3510 AgentWorkerStatus::WaitingForUser,
3511 RosterState::Parked,
3512 ),
3513 ];
3514
3515 // Every receipt is still readable in the register...
3516 assert_eq!(
3517 agents_view_rows(&mut app)
3518 .iter()
3519 .filter(|row| row.agent.is_some())
3520 .count(),
3521 4
3522 );
3523 // ...and none of them re-opens the dock.
3524 assert_eq!(live_agent_row_count(&mut app), 0);
3525 assert!(!view_has_work(&mut app, RailPanel::Agents));
3526 }
3527
3528 /// #36 nesting is a fact about the *live* projection: `order_agent_seeds`
3529 /// indents a child only when its parent is on the same surface, and
3530 /// `(+N)` counts only children the list actually shows.
3531 #[test]
3532 fn nesting_survives_while_both_rows_are_live() {
3533 let mut app = test_app();
3534 app.current_session_id = Some("roster-owner".to_string());
3535 app.agent_roster_session_id = app.current_session_id.clone();
3536 let mut child = running_agent("child");
3537 child.parent_run_id = Some("parent".to_string());
3538 app.subagent_cache = vec![running_agent("parent"), child];
3539
3540 let rows = agents_view_rows(&mut app);
3541 let label = |id: &str| {
3542 rows.iter()
3543 .find(|row| row.id.0 == format!("worker:{id}"))
3544 .unwrap_or_else(|| panic!("{id} row: {rows:?}"))
3545 .label
3546 .clone()
3547 };
3548 assert!(label("child").starts_with("↳ "), "{:?}", label("child"));
3549 assert!(label("parent").contains("(+1)"), "{:?}", label("parent"));
3550 }
3551
3552 /// Deliberate, and asserted so it is not "fixed" into a lie: a receipt
3553 /// that has outlived its live card renders FLAT, with no `↳ ` and no
3554 /// `(+N)`, even when the roster still knows its `parent_run_id`.
3555 ///
3556 /// The register is ordered by the roster (creation order, parked last),
3557 /// not by the tree, so an indent here would be an adjacency claim the
3558 /// list cannot keep — exactly the dangling indent `order_agent_seeds`
3559 /// refuses to draw. Deriving depth here instead would also put a second
3560 /// depth authority on the same list. Nesting degrades to flat, and it
3561 /// degrades symmetrically: see the sibling test below.
3562 #[test]
3563 fn a_retained_child_renders_flat_under_a_retained_parent() {
3564 use codewhale_engine::agent_roster::RosterState;
3565
3566 let mut app = test_app();
3567 app.current_session_id = Some("roster-owner".to_string());
3568 app.agent_roster_session_id = app.current_session_id.clone();
3569 let mut child =
3570 retained_agent_receipt("child", AgentWorkerStatus::Completed, RosterState::Done);
3571 child.parent_run_id = Some("parent".to_string());
3572 app.agent_roster = vec![
3573 retained_agent_receipt("parent", AgentWorkerStatus::Completed, RosterState::Done),
3574 child,
3575 ];
3576
3577 let rows = agents_view_rows(&mut app);
3578 for id in ["parent", "child"] {
3579 let label = rows
3580 .iter()
3581 .find(|row| row.id.0 == format!("worker:{id}"))
3582 .unwrap_or_else(|| panic!("{id} row: {rows:?}"))
3583 .label
3584 .clone();
3585 assert!(!label.contains('↳'), "{id}: {label:?}");
3586 assert!(!label.contains("(+"), "{id}: {label:?}");
3587 }
3588 }
3589
3590 /// The other direction, which is what makes the flattening honest rather
3591 /// than half-applied: when the PARENT has expired to a receipt and only
3592 /// the child is still live, the live child flattens too — its parent is
3593 /// not among the cache seeds, so `order_agent_seeds` leaves it at the top
3594 /// level. Nesting is present for a pair or absent for a pair; it is never
3595 /// stamped on one half of one.
3596 #[test]
3597 fn a_live_child_flattens_once_its_parent_has_expired_to_a_receipt() {
3598 use codewhale_engine::agent_roster::RosterState;
3599
3600 let mut app = test_app();
3601 app.current_session_id = Some("roster-owner".to_string());
3602 app.agent_roster_session_id = app.current_session_id.clone();
3603 let mut child = running_agent("child");
3604 child.parent_run_id = Some("parent".to_string());
3605 app.subagent_cache = vec![child];
3606 let mut retained_child =
3607 retained_agent_receipt("child", AgentWorkerStatus::Running, RosterState::Running);
3608 retained_child.parent_run_id = Some("parent".to_string());
3609 app.agent_roster = vec![
3610 retained_agent_receipt("parent", AgentWorkerStatus::Completed, RosterState::Done),
3611 retained_child,
3612 ];
3613
3614 let rows = agents_view_rows(&mut app);
3615 let child_label = rows
3616 .iter()
3617 .find(|row| row.id.0 == "worker:child")
3618 .unwrap_or_else(|| panic!("child row: {rows:?}"))
3619 .label
3620 .clone();
3621 assert!(!child_label.contains('↳'), "{child_label:?}");
3622 let parent_label = rows
3623 .iter()
3624 .find(|row| row.id.0 == "worker:parent")
3625 .unwrap_or_else(|| panic!("parent row: {rows:?}"))
3626 .label
3627 .clone();
3628 assert!(!parent_label.contains("(+"), "{parent_label:?}");
3629 }
3630
3631 #[test]
3632 fn agents_register_retains_expired_receipts_alongside_fresh_live_rows() {
3633 use crate::tui::subagent_routing::reconcile_subagent_activity_state_at;
3634 use codewhale_engine::agent_roster::RosterState;
3635 use std::time::Duration;
3636
3637 let mut app = test_app();
3638 app.current_session_id = Some("roster-owner".to_string());
3639 app.agent_roster_session_id = app.current_session_id.clone();
3640 let mut done = running_agent("done");
3641 done.status = SubAgentStatus::Completed;
3642 app.subagent_cache = vec![done, running_agent("live")];
3643 let receipt =
3644 retained_agent_receipt("done", AgentWorkerStatus::Completed, RosterState::Done);
3645 app.agent_roster = vec![
3646 receipt.clone(),
3647 receipt,
3648 // A newer live cache row must win over an older retained receipt.
3649 retained_agent_receipt("live", AgentWorkerStatus::Completed, RosterState::Done),
3650 ];
3651 app.agent_progress
3652 .insert("done".to_string(), "old progress".to_string());
3653 let observed = Instant::now();
3654 reconcile_subagent_activity_state_at(&mut app, observed);
3655 reconcile_subagent_activity_state_at(&mut app, observed + Duration::from_secs(46));
3656 assert!(
3657 !app.subagent_cache
3658 .iter()
3659 .any(|agent| agent.agent_id == "done")
3660 );
3661 assert!(!app.agent_progress.contains_key("done"));
3662
3663 let rows = agents_view_rows(&mut app);
3664 let workers: Vec<_> = rows.iter().filter(|row| row.agent.is_some()).collect();
3665 assert_eq!(workers.len(), 2, "one row per retained/live worker ID");
3666 let done = workers
3667 .iter()
3668 .find(|row| row.id.0 == "worker:done")
3669 .unwrap();
3670 assert_eq!(done.agent.as_ref().unwrap().status, "completed");
3671 assert_eq!(done.agent.as_ref().unwrap().elapsed_secs, Some(3));
3672 assert_eq!(done.agent.as_ref().unwrap().tokens, None);
3673 let live = workers
3674 .iter()
3675 .find(|row| row.id.0 == "worker:live")
3676 .unwrap();
3677 assert_eq!(live.agent.as_ref().unwrap().status, "running");
3678
3679 app.subagent_cache[0].status = SubAgentStatus::Completed;
3680 reconcile_subagent_activity_state_at(&mut app, observed + Duration::from_secs(47));
3681 reconcile_subagent_activity_state_at(&mut app, observed + Duration::from_secs(93));
3682 assert!(app.subagent_cache.is_empty());
3683 assert!(app.agent_progress.is_empty());
3684 let rows = agents_view_rows(&mut app);
3685 assert_eq!(rows.iter().filter(|row| row.agent.is_some()).count(), 2);
3686 }
3687
3688 #[test]
3689 fn retained_agents_register_is_bound_to_the_exact_parent_session() {
3690 use codewhale_engine::agent_roster::RosterState;
3691
3692 let mut app = test_app();
3693 app.agent_roster_session_id = Some("original-session".to_string());
3694 app.agent_roster = vec![retained_agent_receipt(
3695 "private-worker",
3696 AgentWorkerStatus::Completed,
3697 RosterState::Done,
3698 )];
3699 app.agent_roster[0].cost_microusd = Some(1_000);
3700 for owner in [None, Some(""), Some("other-session")] {
3701 app.current_session_id = owner.map(str::to_string);
3702 assert!(app.current_agent_roster().is_empty());
3703 assert!(
3704 !agents_view_rows(&mut app)
3705 .iter()
3706 .any(|row| row.agent.is_some())
3707 );
3708 assert!(
3709 !super::super::views::price_rows(&mut app)
3710 .iter()
3711 .any(|row| row.id.0.starts_with("price:agent:"))
3712 );
3713 }
3714 app.current_session_id = Some("original-session".to_string());
3715 assert_eq!(app.current_agent_roster().len(), 1);
3716 assert_eq!(
3717 agents_view_rows(&mut app)
3718 .iter()
3719 .filter(|row| row.agent.is_some())
3720 .count(),
3721 1
3722 );
3723 }
3724
3725 #[test]
3726 fn retained_agents_register_distinguishes_parked_from_waiting_for_input() {
3727 use codewhale_engine::agent_roster::RosterState;
3728
3729 let mut app = test_app();
3730 app.current_session_id = Some("roster-owner".to_string());
3731 app.agent_roster_session_id = app.current_session_id.clone();
3732 app.agent_roster = vec![
3733 retained_agent_receipt(
3734 "parked",
3735 AgentWorkerStatus::WaitingForUser,
3736 RosterState::Parked,
3737 ),
3738 retained_agent_receipt(
3739 "asked",
3740 AgentWorkerStatus::WaitingForUser,
3741 RosterState::Waiting,
3742 ),
3743 ];
3744 let rows = agents_view_rows(&mut app);
3745 let parked = rows.iter().find(|row| row.id.0 == "worker:parked").unwrap();
3746 let asked = rows.iter().find(|row| row.id.0 == "worker:asked").unwrap();
3747 assert_eq!(parked.mark, RosterState::Parked.glyph());
3748 assert_eq!(parked.tone, WorkTone::Muted);
3749 assert_ne!(parked.agent.as_ref().unwrap().status, "waiting for input");
3750 assert_eq!(asked.agent.as_ref().unwrap().status, "waiting for input");
3751 assert_eq!(asked.tone, WorkTone::Attention);
3752 assert!(
3753 matches!(&parked.primary_action, Some(SidebarRowAction::OpenAgentTranscript { agent_id }) if agent_id == "parked")
3754 );
3755 }
3756
3757 /// #5287: the identity column leads with the name the lane was dispatched
3758 /// under; the whale only names an agent that was dispatched without one.
3759 #[test]
3760 fn agent_identity_column_leads_with_the_dispatch_name() {
3761 let mut app = test_app();
3762 let mut named = running_agent("agent_named_lane");
3763 named.name = "branch-triage".to_string();
3764 app.subagent_cache.push(named);
3765 app.subagent_cache.push(running_agent("agent_plain_lane"));
3766
3767 let rows = agent_rows(&app);
3768 let label = |id: &str| {
3769 rows.iter()
3770 .find(|ranked| ranked.row.id.0 == format!("worker:{id}"))
3771 .unwrap_or_else(|| panic!("row for {id}"))
3772 .row
3773 .label
3774 .clone()
3775 };
3776 assert_eq!(label("agent_named_lane"), "branch-triage");
3777 assert_eq!(
3778 label("agent_plain_lane"),
3779 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(
3780 "agent_plain_lane",
3781 "en"
3782 )
3783 );
3784 }
3785
3786 #[test]
3787 fn agent_identity_column_prefers_resolved_profile_over_generated_whale() {
3788 let mut app = test_app();
3789 let mut agent = running_agent("agent_flash_lane");
3790 agent.child_route = Some(codewhale_engine::tools::subagent::ChildRouteReceipt {
3791 requested_type: "custom".to_string(),
3792 requested_profile: Some("DeepSeek V4 Flash".to_string()),
3793 resolved_profile_id: Some("flash-scout".to_string()),
3794 profile_origin: Some("fleet:release".to_string()),
3795 canonical_role: "scout".to_string(),
3796 provider_id: "deepseek".to_string(),
3797 model_id: "deepseek-v4-flash-vision-exp".to_string(),
3798 route_source: "fleet".to_string(),
3799 fallback_note: None,
3800 requested_reasoning: "inherit".to_string(),
3801 effective_reasoning: None,
3802 runtime_version: "test".to_string(),
3803 runtime_build_sha: "unknown".to_string(),
3804 });
3805 app.subagent_cache.push(agent);
3806
3807 let row = agent_rows(&app)
3808 .into_iter()
3809 .find(|ranked| ranked.row.id.0 == "worker:agent_flash_lane")
3810 .expect("resolved Fleet row")
3811 .row;
3812 assert_eq!(row.label, "flash-scout");
3813 assert_eq!(
3814 row.agent.as_ref().map(|facts| facts.role_label.as_str()),
3815 Some("flash-scout")
3816 );
3817 }
3818
3819 /// After the recent-only TTL suppresses transient receipts, the live
3820 /// heading must count only the recent rows the live list still shows —
3821 /// quoting the unfiltered total would claim receipts the reader cannot
3822 /// see (2026-08-04 adversarial review of the durable-row exemption).
3823 #[test]
3824 fn suppressed_transients_leave_the_live_heading_count_honest() {
3825 let mut plan_step = operation(NodeState::Completed, "shipped-step");
3826 plan_step.kind = NodeKind::PlanStep;
3827 plan_step.binding = None;
3828 let mut transient = operation(NodeState::Completed, "settled-op");
3829 transient.binding.as_mut().expect("binding").durable = true;
3830 let mut snapshot = WorkGraphSnapshot::new();
3831 snapshot.compat.todos.push(CompatTodoBinding {
3832 legacy_id: 1,
3833 node: plan_step.id.clone(),
3834 plan_index: None,
3835 });
3836 snapshot.nodes = vec![plan_step, transient];
3837
3838 let mut surface = surface();
3839 surface.set_presentation_now_ms(0);
3840 let _ = graph_rows(
3841 &mut surface,
3842 &snapshot,
3843 None,
3844 Vec::new(),
3845 None,
3846 SettledFileActivity::default(),
3847 );
3848 surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS + 1);
3849 let rows = graph_rows(
3850 &mut surface,
3851 &snapshot,
3852 None,
3853 Vec::new(),
3854 None,
3855 SettledFileActivity::default(),
3856 );
3857 let heading = &rows[0];
3858 assert!(
3859 heading.label.contains("1 recent"),
3860 "live heading counts only the surviving durable row: {}",
3861 heading.label
3862 );
3863 assert!(
3864 rows.iter().any(|row| row.label.contains("shipped-step")),
3865 "durable to-do row survives: {rows:?}"
3866 );
3867 assert!(
3868 !rows.iter().any(|row| row.label.contains("settled-op")),
3869 "transient receipt is suppressed: {rows:?}"
3870 );
3871 // The catalog keeps the full rows, so it keeps the full count.
3872 assert!(
3873 surface
3874 .catalog_rows
3875 .first()
3876 .is_some_and(|row| row.label.contains("2 recent")),
3877 "catalog heading keeps the unfiltered count: {:?}",
3878 surface.catalog_rows.first()
3879 );
3880 }
3881
3882 #[test]
3883 fn heading_counts_initializing_and_active_operations_as_running() {
3884 let mut snapshot = WorkGraphSnapshot::new();
3885 snapshot.nodes = vec![
3886 operation(NodeState::Initializing, "initializing"),
3887 operation(NodeState::Active, "active"),
3888 operation(NodeState::Ready, "ready"),
3889 ];
3890
3891 let rows = graph_rows(
3892 &mut surface(),
3893 &snapshot,
3894 None,
3895 Vec::new(),
3896 None,
3897 SettledFileActivity::default(),
3898 );
3899
3900 assert_eq!(
3901 rows.first().map(|row| row.label.as_str()),
3902 Some("Work · Running: operation initializing · 2 active")
3903 );
3904 }
3905
3906 #[test]
3907 fn live_projection_hides_clean_transient_receipts_without_duplicate_todo_group() {
3908 let todo_id = WorkNodeId::derive("work-surface-test", "todo:1");
3909 let todo = WorkNode {
3910 id: todo_id.clone(),
3911 kind: NodeKind::PlanStep,
3912 title: "Keep the durable checklist visible".to_string(),
3913 state: NodeState::Ready,
3914 acceptance: Vec::new(),
3915 binding: None,
3916 evidence: None,
3917 provenance: Provenance::ToolUpdate {
3918 tool: "work_update".to_string(),
3919 call_id: "todo-1".to_string(),
3920 },
3921 created_at: 1,
3922 updated_at: 1,
3923 };
3924 let mut snapshot = WorkGraphSnapshot::new();
3925 snapshot.nodes = vec![
3926 operation(NodeState::Completed, "settled"),
3927 operation(NodeState::Active, "running"),
3928 todo,
3929 ];
3930 snapshot.compat.todos.push(CompatTodoBinding {
3931 legacy_id: 1,
3932 node: todo_id,
3933 plan_index: None,
3934 });
3935
3936 let rows = graph_rows(
3937 &mut surface(),
3938 &snapshot,
3939 None,
3940 Vec::new(),
3941 None,
3942 SettledFileActivity::default(),
3943 );
3944 let labels = rows
3945 .iter()
3946 .map(|row| row.label.as_str())
3947 .collect::<Vec<_>>();
3948
3949 assert!(labels.contains(&"operation running"), "{labels:?}");
3950 assert!(!labels.contains(&"operation settled"), "{labels:?}");
3951 assert_eq!(
3952 labels
3953 .iter()
3954 .filter(|label| **label == "Keep the durable checklist visible")
3955 .count(),
3956 1,
3957 "one plan node must produce one Work row: {labels:?}"
3958 );
3959 assert!(
3960 !labels.iter().any(|label| label.starts_with("To-do")),
3961 "the ordered Work projection must not add a duplicate To-do heading: {labels:?}"
3962 );
3963 assert!(
3964 labels.contains(&"Keep the durable checklist visible"),
3965 "{labels:?}"
3966 );
3967 assert!(
3968 snapshot
3969 .nodes
3970 .iter()
3971 .any(|node| node.title == "operation settled"),
3972 "projection filtering must retain the historical graph receipt"
3973 );
3974 }
3975
3976 /// #6546: clearing the To-do list (an empty `todo_write`) drops the
3977 /// compat bindings but keeps the old plan-step nodes in the graph. The
3978 /// rail must follow the projection, not every plan step ever written.
3979 #[tokio::test]
3980 async fn cleared_todo_list_leaves_no_plan_step_rows() {
3981 use codewhale_engine::tools::todo::{TodoList, TodoStatus};
3982
3983 let todos = codewhale_engine::tools::todo::new_shared_todo_list();
3984 let plan = codewhale_engine::tools::plan::new_shared_plan_state();
3985 let work = codewhale_engine::work_graph::new_shared_work_runtime(todos.clone(), plan);
3986 let mut written = TodoList::new();
3987 written.add("stale finished item".to_string(), TodoStatus::Completed);
3988 work.apply_todo_update("session-6546", "todo_write", &written.snapshot())
3989 .await
3990 .expect("write todo");
3991 work.publish_pending().await.expect("publish write");
3992 let rows_for = |graph: &WorkGraphSnapshot| {
3993 graph_rows(
3994 &mut surface(),
3995 graph,
3996 None,
3997 Vec::new(),
3998 None,
3999 SettledFileActivity::default(),
4000 )
4001 .into_iter()
4002 .map(|row| row.label)
4003 .collect::<Vec<_>>()
4004 };
4005 let before = work
4006 .capture(Some("session-6546"))
4007 .expect("capture")
4008 .expect("graph");
4009 assert!(
4010 rows_for(&before.graph)
4011 .iter()
4012 .any(|label| label.contains("stale finished item")),
4013 "precondition: the written item renders"
4014 );
4015
4016 work.apply_todo_update("session-6546", "todo_write", &TodoList::new().snapshot())
4017 .await
4018 .expect("clear todos");
4019 work.publish_pending().await.expect("publish clear");
4020 let after = work
4021 .capture(Some("session-6546"))
4022 .expect("capture")
4023 .expect("graph keeps its history");
4024 assert!(after.todos.is_empty());
4025 assert!(
4026 after
4027 .graph
4028 .nodes
4029 .iter()
4030 .any(|node| node.title == "stale finished item"),
4031 "precondition: the retired node is still in the graph"
4032 );
4033 let labels = rows_for(&after.graph);
4034 assert!(
4035 !labels
4036 .iter()
4037 .any(|label| label.contains("stale finished item")),
4038 "cleared To-do item must leave the rail: {labels:?}"
4039 );
4040 }
4041
4042 #[test]
4043 fn projection_keeps_durable_and_evidence_gated_terminal_operations() {
4044 let mut durable = operation(NodeState::Completed, "durable");
4045 durable.binding.as_mut().expect("binding").durable = true;
4046 let mut failed = operation(NodeState::Failed, "failed");
4047 failed.binding.as_mut().expect("binding").durable = true;
4048 let mut evidence_pending = operation(NodeState::Completed, "evidence-pending");
4049 evidence_pending.acceptance = vec![AcceptanceRequirement::EvidenceOfKind {
4050 kind: EvidenceKindTag::ToolRun,
4051 }];
4052 let mut snapshot = WorkGraphSnapshot::new();
4053 snapshot.nodes = vec![durable, failed, evidence_pending];
4054
4055 let rows = graph_rows(
4056 &mut surface(),
4057 &snapshot,
4058 None,
4059 Vec::new(),
4060 None,
4061 SettledFileActivity::default(),
4062 );
4063 let labels = rows
4064 .iter()
4065 .map(|row| row.label.as_str())
4066 .collect::<Vec<_>>();
4067
4068 for expected in [
4069 "operation durable",
4070 "operation failed",
4071 "operation evidence-pending",
4072 ] {
4073 assert!(labels.contains(&expected), "missing {expected}: {labels:?}");
4074 }
4075 }
4076
4077 #[test]
4078 fn transient_failed_operation_is_recent_while_durable_failure_needs_input() {
4079 let transient = operation(NodeState::Failed, "shell transient");
4080 let mut durable = operation(NodeState::Failed, "durable");
4081 durable.binding.as_mut().expect("binding").durable = true;
4082
4083 assert_eq!(node_bucket(&transient), WorkBucket::Recent);
4084 assert_eq!(node_bucket(&durable), WorkBucket::Attention);
4085 }
4086
4087 #[test]
4088 fn projection_orders_attention_before_ready_and_recent() {
4089 let mut recent = operation(NodeState::Completed, "recent");
4090 recent.binding.as_mut().expect("binding").durable = true;
4091 let mut snapshot = WorkGraphSnapshot::new();
4092 snapshot.nodes = vec![
4093 recent,
4094 operation(NodeState::Ready, "ready"),
4095 operation(NodeState::Blocked, "blocked"),
4096 operation(NodeState::Active, "active"),
4097 ];
4098
4099 let labels = graph_rows(
4100 &mut surface(),
4101 &snapshot,
4102 None,
4103 Vec::new(),
4104 None,
4105 SettledFileActivity::default(),
4106 )
4107 .into_iter()
4108 .map(|row| row.label)
4109 .collect::<Vec<_>>();
4110
4111 assert_eq!(
4112 labels,
4113 [
4114 "Work · Needs input: operation blocked · 1 blocked",
4115 "operation blocked",
4116 "operation active",
4117 "operation ready",
4118 "operation recent",
4119 ]
4120 );
4121 }
4122
4123 #[test]
4124 fn activity_targets_keep_workspace_relative_paths_and_hide_external_paths() {
4125 let workspace = Path::new("/workspace/project");
4126 assert_eq!(
4127 privacy_safe_path(workspace, "/workspace/project/src/lib.rs").as_deref(),
4128 Some("src/lib.rs")
4129 );
4130 assert_eq!(
4131 privacy_safe_path(workspace, "/Users/alice/private.txt"),
4132 None
4133 );
4134 assert_eq!(privacy_safe_path(workspace, "../private.txt"), None);
4135 assert_eq!(safe_pattern("needle\nsecret"), "needle secret");
4136 }
4137
4138 #[test]
4139 fn settled_canonical_file_actions_keep_aggregates_and_safe_targets() {
4140 let mut app = test_app();
4141 let calls = [
4142 ("read", serde_json::json!({"path": "src/read.rs"})),
4143 ("list", serde_json::json!({"path": "src"})),
4144 ("search_name", serde_json::json!({"query": "lib.rs"})),
4145 (
4146 "search_content",
4147 serde_json::json!({"pattern": "needle\nprivate", "path": "src"}),
4148 ),
4149 (
4150 "write",
4151 serde_json::json!({"path": "src/new.rs", "content": "new\n"}),
4152 ),
4153 (
4154 "edit",
4155 serde_json::json!({
4156 "path": "src/edit.rs",
4157 "search": "old",
4158 "replace": "new"
4159 }),
4160 ),
4161 (
4162 "patch",
4163 serde_json::json!({
4164 "patch": "diff --git a/src/patch.rs b/src/patch.rs\n--- a/src/patch.rs\n+++ b/src/patch.rs\n@@ -1 +1 @@\n-old\n+new\n"
4165 }),
4166 ),
4167 ];
4168
4169 for (action, payload) in calls {
4170 let id = format!("file-{action}");
4171 let mut input = payload;
4172 input["action"] = serde_json::json!(action);
4173 handle_tool_call_started(&mut app, &id, "File", &input);
4174 handle_tool_call_complete(&mut app, &id, "File", &Ok(ToolResult::success("ok")));
4175 app.flush_active_cell();
4176 }
4177
4178 let activity = settled_file_activity(&app);
4179 assert_eq!(
4180 activity.summary,
4181 FileActivitySummary {
4182 files_read: 1,
4183 dirs_listed: 1,
4184 patterns_searched: 2,
4185 files_written: 3,
4186 }
4187 );
4188 assert_eq!(activity.read, ["src/read.rs"]);
4189 assert_eq!(activity.list, ["src"]);
4190 assert_eq!(activity.search, ["lib.rs", "needle private"]);
4191 assert_eq!(
4192 activity.write,
4193 ["src/new.rs", "src/edit.rs", "src/patch.rs"]
4194 );
4195 }
4196
4197 #[test]
4198 fn multifile_receipt_counts_semantic_file_outcomes_in_work_label() {
4199 let mut app = test_app();
4200 let input = serde_json::json!({
4201 "action": "patch",
4202 "patch": "--- a/update.rs\n+++ b/update.rs\n@@ -1 +1 @@\n-old\n+new\n"
4203 });
4204 handle_tool_call_started(&mut app, "file-multi", "File", &input);
4205 let result = ToolResult::success("ok").with_metadata(serde_json::json!({
4206 "mutation": {
4207 "diff": "diff --git a/old.rs b/new.rs\nrename from old.rs\nrename to new.rs\n--- a/update.rs\n+++ b/update.rs\n@@ -1 +1 @@\n-old\n+new\n--- /dev/null\n+++ b/create.rs\n@@ -0,0 +1 @@\n+created\n--- a/delete.rs\n+++ /dev/null\n@@ -1 +0,0 @@\n-deleted\n",
4208 "files": [
4209 { "path": "update.rs", "outcome": "updated" },
4210 { "path": "create.rs", "outcome": "created" },
4211 { "path": "delete.rs", "outcome": "deleted" }
4212 ],
4213 "renames": [{ "from": "old.rs", "to": "new.rs" }]
4214 }
4215 }));
4216 handle_tool_call_complete(&mut app, "file-multi", "File", &Ok(result));
4217 app.flush_active_cell();
4218
4219 let activity = settled_file_activity(&app);
4220 assert_eq!(activity.summary.files_written, 4);
4221 let write_row = activity_rows(activity)
4222 .into_iter()
4223 .find(|row| row.row.label.starts_with("Wrote"))
4224 .expect("write row");
4225 assert_eq!(write_row.row.label, "Wrote 4 files");
4226 assert_eq!(
4227 write_row.row.detail,
4228 "4 files · 1 created · 1 updated · 1 deleted · 1 renamed · +2 -2"
4229 );
4230 }
4231
4232 fn mutation_activity(mode: InlineDiffMode) -> SettledFileActivity {
4233 let result = ToolResult::success("ok").with_metadata(serde_json::json!({
4234 "mutation": {
4235 "diff": "--- /Users/alice/private.rs\n+++ /Users/alice/private.rs\n@@ -1 +1 @@\n-old\n+new\n",
4236 "files": [{
4237 "path": "/Users/alice/private.rs",
4238 "outcome": "updated"
4239 }],
4240 "renames": []
4241 }
4242 }));
4243 let receipt = FileMutationReceipt::from_success(Path::new("/workspace/project"), &result)
4244 .expect("receipt");
4245 SettledFileActivity {
4246 summary: FileActivitySummary {
4247 files_written: 1,
4248 ..FileActivitySummary::default()
4249 },
4250 write: vec!["src/public.rs".to_string()],
4251 mutations: vec![receipt],
4252 inline_diff_mode: mode,
4253 ..SettledFileActivity::default()
4254 }
4255 }
4256
4257 fn mutation_activity_body(mode: InlineDiffMode) -> (String, String, String) {
4258 let row = activity_rows(mutation_activity(mode))
4259 .into_iter()
4260 .next()
4261 .expect("activity row")
4262 .row;
4263 let SidebarRowAction::InspectWork { body, .. } =
4264 row.primary_action.expect("inspect action")
4265 else {
4266 panic!("write row must open Work inspection")
4267 };
4268 (row.label, row.detail, body)
4269 }
4270
4271 #[test]
4272 fn work_mutation_rows_keep_labels_privacy_and_all_inline_modes() {
4273 let (label, detail, full) = mutation_activity_body(InlineDiffMode::Full);
4274 assert_eq!(label, "Wrote 1 file");
4275 assert_eq!(detail, "Updated <external file> · +1 -1");
4276 assert!(full.contains("-old"), "{full}");
4277 assert!(full.contains("+new"), "{full}");
4278 assert!(!full.contains("alice"), "{full}");
4279 assert!(full.contains("exact change evidence"), "{full}");
4280
4281 let (_, _, summary) = mutation_activity_body(InlineDiffMode::Summary);
4282 assert!(
4283 summary.contains("Updated <external file> · +1 -1"),
4284 "{summary}"
4285 );
4286 assert!(!summary.contains("-old"), "{summary}");
4287 assert!(!summary.contains("+new"), "{summary}");
4288 assert!(!summary.contains("alice"), "{summary}");
4289
4290 let (_, detail, off) = mutation_activity_body(InlineDiffMode::Off);
4291 assert_eq!(detail, "Updated <external file>");
4292 assert!(off.contains("Updated <external file>"), "{off}");
4293 assert!(!off.contains("+1 -1"), "{off}");
4294 assert!(!off.contains("-old"), "{off}");
4295 assert!(!off.contains("alice"), "{off}");
4296 assert!(off.contains("exact change evidence"), "{off}");
4297 }
4298
4299 #[test]
4300 fn recent_only_summary_expires_after_ttl_and_user_turn() {
4301 let mut recent = operation(NodeState::Completed, "recent");
4302 recent.binding.as_mut().expect("binding").durable = true;
4303 let mut snapshot = WorkGraphSnapshot::new();
4304 snapshot.nodes = vec![recent];
4305
4306 let mut surface = surface();
4307 surface.set_presentation_now_ms(0);
4308 let rows = graph_rows(
4309 &mut surface,
4310 &snapshot,
4311 None,
4312 Vec::new(),
4313 None,
4314 SettledFileActivity::default(),
4315 );
4316 assert!(
4317 rows.iter().any(|row| row.id.0.starts_with("section:")),
4318 "recent-only should surface briefly: {rows:?}"
4319 );
4320
4321 surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS);
4322 let expired = graph_rows(
4323 &mut surface,
4324 &snapshot,
4325 None,
4326 Vec::new(),
4327 None,
4328 SettledFileActivity::default(),
4329 );
4330 assert!(
4331 expired.is_empty(),
4332 "recent-only must collapse after TTL: {expired:?}"
4333 );
4334 // Catalog retains durable history for inspector/history.
4335 assert!(
4336 surface
4337 .catalog_rows
4338 .iter()
4339 .any(|row| row.label == "operation recent"),
4340 "catalog must keep recent work after live expiry"
4341 );
4342
4343 // New completion fingerprint re-surfaces once.
4344 let mut newer = operation(NodeState::Completed, "newer");
4345 newer.binding.as_mut().expect("binding").durable = true;
4346 snapshot.nodes.push(newer);
4347 surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS + 10);
4348 let resurfaced = graph_rows(
4349 &mut surface,
4350 &snapshot,
4351 None,
4352 Vec::new(),
4353 None,
4354 SettledFileActivity::default(),
4355 );
4356 assert!(
4357 !resurfaced.is_empty(),
4358 "a new completion may surface once after expiry"
4359 );
4360
4361 // User turn hides immediately while still recent-only.
4362 surface.note_user_turn_or_new_operation();
4363 surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS + 11);
4364 let after_turn = graph_rows(
4365 &mut surface,
4366 &snapshot,
4367 None,
4368 Vec::new(),
4369 None,
4370 SettledFileActivity::default(),
4371 );
4372 assert!(
4373 after_turn.is_empty(),
4374 "user turn must hide recent-only immediately: {after_turn:?}"
4375 );
4376 }
4377
4378 #[test]
4379 fn needs_input_and_ready_never_expire_with_clock() {
4380 let mut snapshot = WorkGraphSnapshot::new();
4381 snapshot.nodes = vec![
4382 operation(NodeState::Blocked, "blocked"),
4383 operation(NodeState::Ready, "ready"),
4384 ];
4385 let mut surface = surface();
4386 surface.set_presentation_now_ms(0);
4387 let _ = graph_rows(
4388 &mut surface,
4389 &snapshot,
4390 None,
4391 Vec::new(),
4392 None,
4393 SettledFileActivity::default(),
4394 );
4395 surface.set_presentation_now_ms(60_000);
4396 let rows = graph_rows(
4397 &mut surface,
4398 &snapshot,
4399 None,
4400 Vec::new(),
4401 None,
4402 SettledFileActivity::default(),
4403 );
4404 assert!(
4405 rows[0].label.starts_with("Work · Needs input:"),
4406 "{}",
4407 rows[0].label
4408 );
4409 assert!(rows.iter().any(|row| row.label == "operation blocked"));
4410 assert!(rows.iter().any(|row| row.label == "operation ready"));
4411 }
4412
4413 #[test]
4414 fn files_keep_all_unique_paths_while_activity_summary_is_capped() {
4415 use super::super::views::{files_rows, files_touched_count};
4416 let mut app = test_app();
4417 for action in ["read", "write"] {
4418 // Repeat the thirteenth path under a new call ID to check uniqueness.
4419 for index in 0..14 {
4420 let id = format!("{action}-{index}");
4421 let path = format!("{action}-{:02}.rs", index.min(12));
4422 let input = serde_json::json!({"action": action, "path": path, "content": "new"});
4423 handle_tool_call_started(&mut app, &id, "File", &input);
4424 handle_tool_call_complete(&mut app, &id, "File", &Ok(ToolResult::success("ok")));
4425 app.flush_active_cell();
4426 }
4427 }
4428 app.work_surface.file_activity = settled_file_activity(&app);
4429 assert!(app.work_surface.file_activity.mutations.is_empty());
4430 assert_eq!(files_touched_count(&mut app), 26);
4431 let rows = files_rows(&mut app);
4432 assert!(rows.iter().any(|row| row.label == "Read 13"));
4433 assert!(rows.iter().any(|row| row.label == "Edited 13"));
4434 for action in ["read", "write"] {
4435 for index in 0..13 {
4436 let path = format!("{action}-{index:02}.rs");
4437 assert_eq!(
4438 rows.iter().filter(|row| row.label == path).count(),
4439 1,
4440 "{path}"
4441 );
4442 }
4443 }
4444 let summary = aggregate_activity_row(&app.work_surface.file_activity).unwrap();
4445 let Some(SidebarRowAction::InspectWork { body, .. }) = summary.row.primary_action else {
4446 panic!("activity summary opens its preview");
4447 };
4448 for action in ["read", "write"] {
4449 assert!(body.contains(&format!("{action}-11.rs")));
4450 assert!(!body.contains(&format!("{action}-12.rs")));
4451 }
4452 app.ui_locale = Locale::ZhHans;
4453 app.work_surface.file_activity = settled_file_activity(&app);
4454 let rows = files_rows(&mut app);
4455 assert!(rows.iter().any(|row| row.label == "读取 13"));
4456 assert!(rows.iter().any(|row| row.label == "已编辑 13"));
4457 let summary = aggregate_activity_row(&app.work_surface.file_activity).unwrap();
4458 assert!(
4459 summary.row.label.contains("读取了14个文件"),
4460 "{}",
4461 summary.row.label
4462 );
4463 }
4464
4465 #[test]
4466 fn activity_receipts_aggregate_and_expire_without_raw_payloads() {
4467 let activity = SettledFileActivity {
4468 summary: FileActivitySummary {
4469 files_read: 1,
4470 patterns_searched: 2,
4471 files_written: 1,
4472 ..FileActivitySummary::default()
4473 },
4474 read: vec!["src/lib.rs".to_string()],
4475 search: vec!["(?i)super_secret_pattern_xyz".to_string()],
4476 write: vec!["src/main.rs".to_string()],
4477 ..SettledFileActivity::default()
4478 };
4479 let mut surface = surface();
4480 surface.set_presentation_now_ms(0);
4481 let rows = ordered_rows(&mut surface, None, None, Vec::new(), None, activity.clone());
4482 let activity_row = rows
4483 .iter()
4484 .find(|row| row.id.0 == "activity:aggregate")
4485 .expect("aggregate activity");
4486 assert!(activity_row.label.contains("Read 1 file ·"));
4487 assert!(activity_row.label.contains("Searched 2 patterns"));
4488 assert!(!activity_row.label.contains("super_secret_pattern_xyz"));
4489 assert!(!activity_row.detail.contains("super_secret_pattern_xyz"));
4490
4491 surface.set_presentation_now_ms(ACTIVITY_RECEIPT_TTL_MS);
4492 let expired = ordered_rows(&mut surface, None, None, Vec::new(), None, activity);
4493 assert!(
4494 expired.iter().all(|row| row.id.0 != "activity:aggregate"),
4495 "activity receipt must expire after TTL: {expired:?}"
4496 );
4497 }
4498
4499 #[test]
4500 fn summary_subject_prefers_attention_over_active_and_ready() {
4501 let mut snapshot = WorkGraphSnapshot::new();
4502 snapshot.nodes = vec![
4503 operation(NodeState::Active, "running"),
4504 operation(NodeState::Blocked, "choose a release target"),
4505 operation(NodeState::Ready, "review rebuilt binary"),
4506 ];
4507 let rows = graph_rows(
4508 &mut surface(),
4509 &snapshot,
4510 None,
4511 Vec::new(),
4512 None,
4513 SettledFileActivity::default(),
4514 );
4515 assert_eq!(
4516 rows[0].label,
4517 "Work · Needs input: operation choose a release target · 1 blocked"
4518 );
4519 }
4520
4521 fn running_shell_entry(id: &str, command: &str) -> crate::tui::app::TaskPanelEntry {
4522 crate::tui::app::TaskPanelEntry {
4523 exit_code: None,
4524 id: id.to_string(),
4525 status: "running".to_string(),
4526 prompt_summary: format!("shell: {command}"),
4527 duration_ms: Some(42_000),
4528 kind: crate::tui::app::TaskPanelEntryKind::Shell,
4529 stale: false,
4530 elapsed_since_output_ms: None,
4531 owner_agent_id: None,
4532 owner_agent_name: None,
4533 current_tool: None,
4534 role: None,
4535 files_touched: 0,
4536 }
4537 }
4538
4539 #[test]
4540 fn live_shells_are_first_class_background_rows() {
4541 let mut app = test_app();
4542 app.work_surface.placement = WorkSurfacePlacement::Top;
4543 app.work_surface.effective_placement = WorkSurfacePlacement::Top;
4544 app.task_panel.push(running_shell_entry(
4545 "shell_a1b2c3d4",
4546 "cd /workspace/example-project",
4547 ));
4548 app.subagent_cache
4549 .push(running_agent("doc-scout-spec-arch"));
4550
4551 // Shells never crowd the agents or tasks views; they are the
4552 // background view, and the dock badges them there.
4553 let agents = visible_rows_for(&mut app, RailPanel::Agents);
4554 assert!(
4555 agents
4556 .iter()
4557 .any(|row| row.id.0 == "section:agents" && row.label.contains("Subagents")),
4558 "subagent visibility must not regress: {agents:?}"
4559 );
4560 assert!(!agents.iter().any(|row| row.id.0.starts_with("shell:")));
4561 let rows = visible_rows_for(&mut app, RailPanel::Background);
4562 let heading = rows
4563 .iter()
4564 .find(|row| row.id.0 == "section:shells")
4565 .expect("Shells group heading");
4566 assert_eq!(heading.label, "Shells 1");
4567 assert!(heading.selectable);
4568 let shell = rows
4569 .iter()
4570 .find(|row| row.id.0 == "shell:shell_a1b2c3d4")
4571 .expect("navigable shell row");
4572 // #6565: the command leads; the id stays in the detail.
4573 assert_eq!(shell.label, "cd /workspace/example-project");
4574 assert!(shell.detail.contains("shell_a1b2c3d4"), "{}", shell.detail);
4575 assert!(
4576 matches!(
4577 shell.primary_action.as_ref(),
4578 Some(SidebarRowAction::Command(command)) if command == "/jobs show shell_a1b2c3d4"
4579 ),
4580 "shell row must open the live inspector, got {:?}",
4581 shell.primary_action
4582 );
4583 let facts = shell
4584 .agent
4585 .as_ref()
4586 .expect("shell uses the same row columns");
4587 assert_eq!(facts.role_label, "shell");
4588 assert_eq!(facts.status, "running");
4589 assert!(
4590 facts.objective.contains("example-project"),
4591 "{}",
4592 facts.objective
4593 );
4594 }
4595
4596 #[test]
4597 fn durable_tasks_are_not_promoted_as_shell_rows() {
4598 let mut app = test_app();
4599 app.work_surface.placement = WorkSurfacePlacement::Top;
4600 app.work_surface.effective_placement = WorkSurfacePlacement::Top;
4601 app.task_panel.push(crate::tui::app::TaskPanelEntry {
4602 exit_code: None,
4603 id: "run".to_string(),
4604 status: "running".to_string(),
4605 prompt_summary: "background confirmation test".to_string(),
4606 duration_ms: Some(99_000),
4607 kind: crate::tui::app::TaskPanelEntryKind::Background,
4608 stale: false,
4609 elapsed_since_output_ms: None,
4610 owner_agent_id: None,
4611 owner_agent_name: None,
4612 current_tool: None,
4613 role: None,
4614 files_touched: 0,
4615 });
4616 let rows = project_visible(&mut app);
4617 assert!(
4618 rows.iter()
4619 .all(|row| !row.id.0.starts_with("shell:") && row.id.0 != "section:shells"),
4620 "non-shell task_panel entries must not become Shells rows: {rows:?}"
4621 );
4622 }
4623
4624 fn finished_entry(
4625 id: &str,
4626 summary: &str,
4627 status: &str,
4628 exit_code: Option<i64>,
4629 ) -> crate::tui::app::TaskPanelEntry {
4630 crate::tui::app::TaskPanelEntry {
4631 exit_code,
4632 status: status.to_string(),
4633 prompt_summary: summary.to_string(),
4634 duration_ms: Some(12_000),
4635 ..running_shell_entry(id, "unused")
4636 }
4637 }
4638
4639 #[test]
4640 fn finished_shells_and_tasks_sit_muted_under_finished_and_never_count_as_live() {
4641 // #6565: a finished task looked live and reopened the dock; a
4642 // finished shell vanished with no trace of how it ended.
4643 let mut app = test_app();
4644 app.task_panel
4645 .push(running_shell_entry("shell_dev", "npm run dev"));
4646 app.task_panel.push(finished_entry(
4647 "shell_ok",
4648 "shell: cargo build",
4649 "completed",
4650 Some(0),
4651 ));
4652 app.task_panel.push(finished_entry(
4653 "shell_bad",
4654 "shell: npm test",
4655 "failed",
4656 Some(2),
4657 ));
4658 app.task_panel.push(finished_entry(
4659 "shell_kill",
4660 "shell: sleep 99",
4661 "killed",
4662 None,
4663 ));
4664 app.task_panel.push(finished_entry(
4665 "shell_slow",
4666 "shell: make e2e",
4667 "timed_out",
4668 None,
4669 ));
4670 app.task_panel.push(TaskPanelEntry {
4671 kind: TaskPanelEntryKind::Background,
4672 ..finished_entry("task_done", "summarize the logs", "completed", None)
4673 });
4674 let rows = visible_rows_for(&mut app, RailPanel::Background);
4675 let ids = rows.iter().map(|row| row.id.0.as_str()).collect::<Vec<_>>();
4676 assert_eq!(
4677 ids,
4678 [
4679 "section:shells",
4680 "shell:shell_dev",
4681 "section:finished",
4682 "shell:shell_ok",
4683 "shell:shell_bad",
4684 "shell:shell_kill",
4685 "shell:shell_slow",
4686 "task:task_done",
4687 ]
4688 );
4689 let row = |id: &str| rows.iter().find(|row| row.id.0 == id).unwrap();
4690 assert_eq!(row("section:finished").label, "Finished 5");
4691 assert_eq!(row("shell:shell_ok").label, "cargo build");
4692 assert_eq!(row("shell:shell_ok").detail, "exit 0 · 12s · shell_ok");
4693 assert_eq!(row("shell:shell_ok").tone, WorkTone::Muted);
4694 assert_eq!(row("shell:shell_bad").detail, "failed · exit 2 · shell_bad");
4695 assert_eq!(row("shell:shell_bad").tone, WorkTone::Failure);
4696 assert_eq!(row("shell:shell_kill").detail, "killed · shell_kill");
4697 assert_eq!(row("shell:shell_slow").detail, "timed out · shell_slow");
4698 assert_eq!(row("task:task_done").tone, WorkTone::Muted);
4699 assert!(
4700 row("shell:shell_ok")
4701 .agent
4702 .as_ref()
4703 .is_some_and(|facts| !facts.holds_dock_open && facts.role_label == "shell")
4704 );
4705
4706 // The running dev server is the only live work.
4707 assert!(background_has_live_work(&mut app));
4708 app.task_panel.remove(0);
4709 assert!(!background_has_live_work(&mut app));
4710 assert_eq!(auto_work_rows(&mut app), 0);
4711 }
4712
4713 #[test]
4714 fn a_quiet_running_agent_shows_the_engines_idle_clock_and_bound() {
4715 let mut app = test_app();
4716 let mut agent = running_agent("agent_quiet");
4717 agent.idle_ms = Some(125_000);
4718 agent.heartbeat_timeout_ms = Some(300_000);
4719 app.subagent_cache.push(agent);
4720 let detail = |app: &App| {
4721 agent_rows(app)
4722 .into_iter()
4723 .find(|ranked| ranked.row.id.0 == "worker:agent_quiet")
4724 .expect("row")
4725 .row
4726 .detail
4727 };
4728 assert!(
4729 detail(&app).ends_with("quiet 2m · auto-stop at 5m"),
4730 "{}",
4731 detail(&app)
4732 );
4733 // A tool in flight is never quiet.
4734 app.agent_progress_meta
4735 .entry("agent_quiet".to_string())
4736 .or_default()
4737 .current_tool = Some("exec_shell".to_string());
4738 assert!(!detail(&app).contains("quiet"), "{}", detail(&app));
4739 // Under a minute says nothing.
4740 app.agent_progress_meta.clear();
4741 app.subagent_cache[0].idle_ms = Some(20_000);
4742 assert!(!detail(&app).contains("quiet"), "{}", detail(&app));
4743 }
4744
4745 #[test]
4746 fn progress_after_an_old_snapshot_keeps_a_working_agent_from_reading_quiet() {
4747 let mut app = test_app();
4748 let mut agent = running_agent("agent_busy");
4749 // The snapshot is ten minutes old; its idle clock would read quiet.
4750 agent.idle_ms = Some(0);
4751 agent.heartbeat_timeout_ms = Some(300_000);
4752 app.subagent_cache.push(agent);
4753 app.subagent_cache_received_at =
4754 std::time::Instant::now().checked_sub(std::time::Duration::from_secs(600));
4755 let detail = |app: &App| {
4756 agent_rows(app)
4757 .into_iter()
4758 .find(|ranked| ranked.row.id.0 == "worker:agent_busy")
4759 .expect("row")
4760 .row
4761 .detail
4762 };
4763 assert!(detail(&app).contains("quiet 5m"), "{}", detail(&app));
4764 // A progress envelope since then, with no tool in flight between
4765 // read-only tools, means the agent is working.
4766 app.agent_progress_meta
4767 .entry("agent_busy".to_string())
4768 .or_default()
4769 .last_progress_at = Some(std::time::Instant::now());
4770 assert!(!detail(&app).contains("quiet"), "{}", detail(&app));
4771 // The TUI's clock only caps the engine's, never extends it: a child
4772 // quiet since its last envelope two minutes ago reads 2m.
4773 app.agent_progress_meta
4774 .get_mut("agent_busy")
4775 .expect("meta")
4776 .last_progress_at =
4777 std::time::Instant::now().checked_sub(std::time::Duration::from_secs(125));
4778 assert!(detail(&app).contains("quiet 2m"), "{}", detail(&app));
4779 }
4780
4781 #[test]
4782 fn background_review_shell_prefixed_tasks_keep_task_actions() {
4783 let mut app = test_app();
4784 for (id, summary) in [
4785 ("task_real", "shell: explain this command"),
4786 ("shell_legacy", "ordinary task"),
4787 ] {
4788 app.task_panel.push(TaskPanelEntry {
4789 kind: TaskPanelEntryKind::Background,
4790 prompt_summary: summary.into(),
4791 ..running_shell_entry(id, "unused")
4792 });
4793 }
4794 assert!(
4795 app.task_panel
4796 .iter()
4797 .all(|entry| !is_live_shell_entry(entry))
4798 );
4799 assert_eq!(
4800 crate::tui::background_indicator::pending_work_from_app(&app)
4801 .count(crate::tui::background_indicator::PendingItemKind::Task),
4802 2
4803 );
4804 for status in ["running", "completed"] {
4805 for entry in &mut app.task_panel {
4806 entry.status = status.into();
4807 }
4808 let rows = visible_rows_for(&mut app, RailPanel::Background);
4809 for id in ["task_real", "shell_legacy"] {
4810 let row = rows
4811 .iter()
4812 .find(|row| row.id.0 == format!("task:{id}"))
4813 .expect("task row");
4814 assert!(
4815 matches!(&row.primary_action, Some(SidebarRowAction::Command(command)) if command == &format!("/task show {id}"))
4816 );
4817 }
4818 }
4819 }
4820
4821 #[test]
4822 fn background_review_snapshot_tool_is_never_quiet_without_progress_metadata() {
4823 let app = test_app();
4824 let mut agent = running_agent("agent_tool");
4825 agent.idle_ms = Some(125_000);
4826 agent.heartbeat_timeout_ms = Some(300_000);
4827 agent.worker_status = Some(AgentWorkerStatus::RunningTool);
4828 assert_eq!(quiet_fact(&app, &agent, None), None);
4829 assert_eq!(
4830 quiet_fact(&app, &agent, Some(&AgentProgressMeta::default())),
4831 None
4832 );
4833 agent.worker_status = None;
4834 assert!(quiet_fact(&app, &agent, None).is_some());
4835 }
4836
4837 #[test]
4838 fn background_review_finished_rows_and_quiet_copy_use_the_selected_locale() {
4839 let mut app = test_app();
4840 app.ui_locale = Locale::Fr;
4841 app.task_panel.push(finished_entry(
4842 "shell_kill",
4843 "shell: sleep 99",
4844 "killed",
4845 None,
4846 ));
4847 let rows = visible_rows_for(&mut app, RailPanel::Background);
4848 assert_eq!(rows[0].label, "Terminés 1");
4849 assert_eq!(rows[0].detail, "Ouvrez une ligne pour voir sa sortie");
4850 assert!(rows[1].detail.starts_with("arrêté de force"));
4851 for (status, expected) in [
4852 ("completed", "code de sortie 0"),
4853 ("failed", "échec"),
4854 ("timed_out", "délai dépassé"),
4855 ] {
4856 let entry = finished_entry("shell", "shell: command", status, Some(0));
4857 assert!(finished_shell_outcome(Locale::Fr, &entry).contains(expected));
4858 }
4859 for (status, expected) in [("failed", "échec"), ("canceled", "annulation")] {
4860 app.task_panel = vec![TaskPanelEntry {
4861 kind: TaskPanelEntryKind::Background,
4862 ..finished_entry("task", "vérifier", status, None)
4863 }];
4864 let rows = finished_background_rows(&app);
4865 assert_eq!(rows[0].detail, format!("{expected} · 12s · task"));
4866 }
4867 let mut agent = running_agent("agent_quiet");
4868 agent.idle_ms = Some(125_000);
4869 agent.heartbeat_timeout_ms = Some(300_000);
4870 assert_eq!(
4871 quiet_fact(&app, &agent, None).as_deref(),
4872 Some("sans progrès depuis 2m · arrêt automatique à 5m")
4873 );
4874 }
4875
4876 #[test]
4877 fn turn_one_fleet_retains_spawned_and_completed_agents_without_agent_list_and_past_ttl() {
4878 use crate::tui::subagent_routing::{
4879 apply_subagent_terminal_projection, reconcile_subagent_activity_state_at,
4880 upsert_roster_progress, upsert_roster_spawn, upsert_roster_terminal,
4881 };
4882 use codewhale_engine::core::events::AgentProgressEventMeta;
4883 use codewhale_engine::tools::subagent::AgentRunUsage;
4884 use std::time::Duration;
4885
4886 let mut app = test_app();
4887 app.set_current_session_id(Some("turn-1-session".to_string()));
4888 app.work_surface.panel = RailPanel::Tasks;
4889 app.work_surface.explicit_view = false;
4890
4891 app.agent_progress.insert(
4892 "agent_51275578".to_string(),
4893 "starting: Inspect turn_loop.rs".to_string(),
4894 );
4895 upsert_roster_spawn(
4896 &mut app,
4897 "turn-1-session",
4898 "agent_51275578",
4899 "Inspect turn_loop.rs",
4900 Some(AgentWorkerStatus::Running),
4901 None,
4902 "gemini-4-hydrogen",
4903 Some("scout"),
4904 );
4905 resolve_view(&mut app);
4906 assert_eq!(app.work_surface.panel, RailPanel::Agents);
4907 assert_eq!(live_agent_row_count(&mut app), 1);
4908
4909 let progress_meta = AgentProgressEventMeta {
4910 worker_status: AgentWorkerStatus::RunningTool,
4911 tool_name: Some("read_file".to_string()),
4912 step: Some(3),
4913 routine_wait: false,
4914 approval_id: None,
4915 };
4916 upsert_roster_progress(
4917 &mut app,
4918 "turn-1-session",
4919 "agent_51275578",
4920 "step 3 · read_file",
4921 &progress_meta,
4922 None,
4923 );
4924
4925 let usage = AgentRunUsage {
4926 status: "recorded".to_string(),
4927 input_tokens: Some(12_000),
4928 output_tokens: Some(450),
4929 total_tokens: Some(12_450),
4930 cost_microusd: Some(2_500),
4931 note: String::new(),
4932 };
4933 upsert_roster_terminal(
4934 &mut app,
4935 "turn-1-session",
4936 "agent_51275578",
4937 Some(&SubAgentStatus::Cancelled),
4938 "Cancelled by parent",
4939 None,
4940 Some(&usage),
4941 Some("scout"),
4942 Some(14_000),
4943 );
4944 apply_subagent_terminal_projection(
4945 &mut app,
4946 "agent_51275578",
4947 SubAgentStatus::Cancelled,
4948 Some("Cancelled by parent".to_string()),
4949 );
4950
4951 upsert_roster_spawn(
4952 &mut app,
4953 "turn-1-session",
4954 "agent_failed",
4955 "Run verification",
4956 Some(AgentWorkerStatus::Running),
4957 None,
4958 "gemini-4-hydrogen",
4959 Some("verifier"),
4960 );
4961 upsert_roster_terminal(
4962 &mut app,
4963 "turn-1-session",
4964 "agent_failed",
4965 Some(&SubAgentStatus::Failed("tests failed".to_string())),
4966 "tests failed",
4967 None,
4968 None,
4969 Some("verifier"),
4970 Some(9_000),
4971 );
4972 apply_subagent_terminal_projection(
4973 &mut app,
4974 "agent_failed",
4975 SubAgentStatus::Failed("tests failed".to_string()),
4976 Some("tests failed".to_string()),
4977 );
4978
4979 let now = Instant::now();
4980 reconcile_subagent_activity_state_at(&mut app, now);
4981 reconcile_subagent_activity_state_at(&mut app, now + Duration::from_secs(60));
4982 assert!(app.subagent_cache.is_empty());
4983 assert!(app.agent_progress.is_empty());
4984
4985 resolve_view(&mut app);
4986 assert_eq!(app.work_surface.panel, RailPanel::Agents);
4987 assert_eq!(live_agent_row_count(&mut app), 0);
4988
4989 let rows = agents_view_rows(&mut app);
4990 let workers: Vec<_> = rows.iter().filter(|row| row.agent.is_some()).collect();
4991 assert_eq!(workers.len(), 2);
4992
4993 let cancelled = workers
4994 .iter()
4995 .find(|row| row.id.0 == "worker:agent_51275578")
4996 .expect("cancelled worker retained");
4997 assert_eq!(cancelled.label, "scout");
4998 let cancelled_facts = cancelled.agent.as_ref().unwrap();
4999 assert_eq!(cancelled_facts.status, "cancelled");
5000 assert_eq!(cancelled_facts.elapsed_secs, Some(14));
5001 assert_eq!(cancelled_facts.tokens, Some(12_450));
5002 assert_eq!(cancelled_facts.model.as_deref(), Some("gemini-4-hydrogen"));
5003
5004 let failed = workers
5005 .iter()
5006 .find(|row| row.id.0 == "worker:agent_failed")
5007 .expect("failed worker retained");
5008 assert_eq!(failed.tone, WorkTone::Failure);
5009 assert_eq!(failed.agent.as_ref().unwrap().status, "failed");
5010
5011 let price = super::super::views::price_rows(&mut app);
5012 assert!(
5013 price
5014 .iter()
5015 .any(|row| row.id.0 == "price:agent:agent_51275578"),
5016 "cost view must show live priced subagents before AgentList arrives"
5017 );
5018 }
5019
5020 #[test]
5021 fn session_switch_via_set_current_session_id_isolates_fleet_and_workbar() {
5022 use crate::tui::subagent_routing::upsert_roster_spawn;
5023
5024 let mut app = test_app();
5025 app.set_current_session_id(Some("session-a".to_string()));
5026 app.subagent_cache.push(running_agent("worker_a"));
5027 app.agent_progress
5028 .insert("worker_a".to_string(), "working".to_string());
5029 upsert_roster_spawn(
5030 &mut app,
5031 "session-a",
5032 "worker_a",
5033 "work in session a",
5034 Some(AgentWorkerStatus::Running),
5035 None,
5036 "gemini-4-hydrogen",
5037 Some("scout-a"),
5038 );
5039 app.work_surface.dismissed = true;
5040 assert_eq!(
5041 agents_view_rows(&mut app)
5042 .iter()
5043 .filter(|row| row.agent.is_some())
5044 .count(),
5045 1
5046 );
5047
5048 app.set_current_session_id(Some("session-b".to_string()));
5049 assert!(app.subagent_cache.is_empty());
5050 assert!(app.agent_progress.is_empty());
5051 assert!(app.current_agent_roster().is_empty());
5052 assert!(!app.work_surface.dismissed);
5053 assert!(agents_view_rows(&mut app).is_empty());
5054 }
5055
5056 #[test]
5057 fn delegated_writes_appear_in_files_view_for_owning_session_only() {
5058 let mut app = test_app();
5059 app.workspace = std::path::PathBuf::from("/repo");
5060 app.set_current_session_id(Some("session-files".to_string()));
5061 app.delegated_writes.insert(
5062 ("session-files".to_string(), 1),
5063 std::collections::BTreeSet::from([
5064 "/repo/crates/tui/src/lib.rs".to_string(),
5065 "../outside.rs".to_string(),
5066 ]),
5067 );
5068 app.delegated_writes.insert(
5069 ("other-session".to_string(), 1),
5070 std::collections::BTreeSet::from(["/repo/crates/tui/src/other.rs".to_string()]),
5071 );
5072
5073 assert_eq!(super::super::views::files_touched_count(&mut app), 1);
5074 let rows = super::super::views::files_rows(&mut app);
5075 assert!(rows.iter().any(|row| row.label == "crates/tui/src/lib.rs"));
5076 assert!(!rows.iter().any(|row| row.label.contains("outside.rs")));
5077 assert!(!rows.iter().any(|row| row.label.contains("other.rs")));
5078 }
5079 }
5080
5080 lines RUST