返回 CodeWhale
background_indicator.rs
根目录 / crates / tui / src / tui / background_indicator.rs
1 //! Compact live "pending background work" indicator near the composer.
2 //!
3 //! When the main turn is waiting on background shells, durable tasks, or
4 //! running sub-agents, a single chip row renders directly above the composer
5 //! so the user can see — at the exact place they are looking — that the model
6 //! is blocked on background work and on what. It auto-updates as items start
7 //! and finish, and the row collapses to zero rows entirely when nothing is
8 //! pending.
9 //!
10 //! # Source of truth
11 //!
12 //! The indicator mirrors state the Work strip and the `/jobs` surface already
13 //! read — it introduces no new registry and takes no lock in the render path:
14 //!
15 //! - **Durable tasks**: `App::task_panel` entries that are not live shells.
16 //! Background shells are first-class work-strip rows (`▾ Shells N`) and
17 //! are not mirrored here.
18 //! - **Sub-agents**: the union of `App::subagent_cache` entries still in
19 //! `Running` state and `App::agent_progress` keys — the same live projection
20 //! `running_agent_count` uses, so spawn/completion events update the chip
21 //! immediately.
22 //!
23 //! # Rendering
24 //!
25 //! `ui/frame.rs` reserves one extra layout row between the pending-input
26 //! preview and the composer, carves it from the auxiliary budget (so compact
27 //! terminals shed the chip before they shed chat/composer space), and calls
28 //! [`render`] only when [`PendingWork::is_empty`] is false.
29
30 use std::collections::HashSet;
31
32 use crate::tui::app::{App, TaskPanelEntry, TaskPanelEntryKind};
33 use codewhale_localization::truncate_to_width;
34
35 /// Per-item label cap so one long command or objective cannot eat the whole
36 /// row before the whole-line truncation kicks in.
37 const ITEM_LABEL_MAX_WIDTH: usize = 20;
38
39 /// Kind of in-flight background work the main turn is waiting on.
40 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
41 pub enum PendingItemKind {
42 /// Background shell job (the `/jobs` surface).
43 Shell,
44 /// Durable task / RLM run tracked by the TaskManager.
45 Task,
46 /// Running sub-agent / fleet worker.
47 Agent,
48 }
49
50 /// Lifecycle state carried by the App's background-work projection.
51 ///
52 /// The task panel currently receives wire-status tokens, so normalize them at
53 /// the projection boundary. Renderers then consume this typed state instead
54 /// of re-interpreting status strings.
55 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
56 pub enum PendingItemState {
57 Queued,
58 Running,
59 }
60
61 impl PendingItemKind {
62 /// Singular noun used for the count summary ("1 shell", "2 agents").
63 #[must_use]
64 pub fn noun(self) -> &'static str {
65 match self {
66 Self::Shell => "shell",
67 Self::Task => "task",
68 Self::Agent => "agent",
69 }
70 }
71
72 pub(crate) fn plural_noun(self, count: usize) -> String {
73 if count == 1 {
74 self.noun().to_string()
75 } else {
76 format!("{}s", self.noun())
77 }
78 }
79 }
80
81 /// One in-flight item shown in the chip row.
82 #[derive(Debug, Clone, PartialEq, Eq)]
83 pub struct PendingItem {
84 pub kind: PendingItemKind,
85 pub state: PendingItemState,
86 /// Short human label (task id / role / name / command), pre-truncated.
87 pub label: String,
88 }
89
90 /// Snapshot of the background work the main turn is waiting on.
91 #[derive(Debug, Clone, PartialEq, Eq, Default)]
92 pub struct PendingWork {
93 /// Shells and tasks first (in `task_panel` order), then agents in stable
94 /// id order. Empty means the indicator row is hidden.
95 pub items: Vec<PendingItem>,
96 }
97
98 impl PendingWork {
99 #[must_use]
100 pub fn count(&self, kind: PendingItemKind) -> usize {
101 self.items.iter().filter(|item| item.kind == kind).count()
102 }
103
104 #[must_use]
105 #[cfg(test)]
106 pub fn count_state(&self, state: PendingItemState) -> usize {
107 self.items.iter().filter(|item| item.state == state).count()
108 }
109 }
110
111 fn truncate_label(label: &str) -> String {
112 let trimmed = label.trim();
113 if trimmed.is_empty() {
114 "…".to_string()
115 } else {
116 truncate_to_width(trimmed, ITEM_LABEL_MAX_WIDTH)
117 }
118 }
119
120 /// Build the composer pending-work snapshot from the same state the Work
121 /// strip and `/jobs` surface render. Read-only; no locks, no registries.
122 ///
123 /// Live shells deliberately remain only on the detailed Work strip, rather
124 /// than being repeated in the composer crumb.
125 #[must_use]
126 pub fn pending_work_from_app(app: &App) -> PendingWork {
127 collect_pending_work(app)
128 }
129
130 fn collect_pending_work(app: &App) -> PendingWork {
131 let mut items: Vec<PendingItem> = Vec::new();
132
133 // Background shells and durable tasks: the merged task_panel snapshot
134 // refreshed by `refresh_active_task_panel` on the event loop. Shell jobs
135 // carry a `shell: <command>` summary; durable/RLM tasks carry their own
136 // prompt summary and their task id is the stable label.
137 for entry in &app.task_panel {
138 let Some(state) = pending_item_state(entry) else {
139 continue;
140 };
141 // Live shells belong on the work strip (`▾ Shells N`), not this
142 // composer crumb. A dual surface hid the PTY behind hourglasses.
143 let is_shell = is_live_shell_entry(entry);
144 if is_shell {
145 continue;
146 }
147 let trimmed = entry.prompt_summary.trim();
148 let label = if !trimmed.is_empty() {
149 trimmed
150 } else {
151 entry.id.as_str()
152 };
153 items.push(PendingItem {
154 kind: PendingItemKind::Task,
155 state,
156 label: truncate_label(label),
157 });
158 }
159
160 // Running sub-agents: subagent_cache first (richer: nickname/role), then
161 // agent_progress-only ids, deduped by id exactly like running_agent_count.
162 let mut seen: HashSet<&str> = HashSet::new();
163 for agent in app.subagent_cache.iter().filter(|agent| {
164 matches!(
165 agent.status,
166 codewhale_engine::tools::subagent::SubAgentStatus::Running
167 )
168 }) {
169 if !seen.insert(agent.agent_id.as_str()) {
170 continue;
171 }
172 let role = agent
173 .assignment
174 .role
175 .as_deref()
176 .filter(|role| !role.trim().is_empty())
177 .unwrap_or_else(|| agent.agent_type.as_str());
178 // The name this lane was dispatched under is what the operator
179 // thinks in; the whale nickname only names an unnamed one (#5287).
180 let name = app
181 .agent_given_name(&agent.agent_id)
182 .or_else(|| {
183 agent
184 .nickname
185 .clone()
186 .filter(|name| !name.trim().is_empty() && *name != agent.agent_id)
187 })
188 .or_else(|| app.agent_label_map.get(&agent.agent_id).cloned());
189 let label = match name.as_deref() {
190 Some(name) if name != role => format!("{name}·{role}"),
191 _ => role.to_string(),
192 };
193 items.push(PendingItem {
194 kind: PendingItemKind::Agent,
195 state: PendingItemState::Running,
196 label: truncate_label(&label),
197 });
198 }
199 for id in app.agent_progress.keys() {
200 if !seen.insert(id.as_str()) {
201 continue;
202 }
203 let label = app.agent_display_label(id);
204 items.push(PendingItem {
205 kind: PendingItemKind::Agent,
206 state: PendingItemState::Running,
207 label: truncate_label(&label),
208 });
209 }
210
211 PendingWork { items }
212 }
213
214 /// Normalize the task-panel's serialized lifecycle token once at the
215 /// projection boundary. Consumers should use [`PendingItemState`] rather than
216 /// comparing these wire values in their render paths.
217 #[must_use]
218 pub(crate) fn pending_item_state(entry: &TaskPanelEntry) -> Option<PendingItemState> {
219 match entry.status.as_str() {
220 "queued" => Some(PendingItemState::Queued),
221 "running" => Some(PendingItemState::Running),
222 _ => None,
223 }
224 }
225
226 /// Whether a task-panel row is a currently live shell job. This is shared by
227 /// the detailed Work strip and compact live-status projections so a shell
228 /// cannot be omitted or classified differently between surfaces.
229 #[must_use]
230 pub(crate) fn is_live_shell_entry(entry: &TaskPanelEntry) -> bool {
231 pending_item_state(entry).is_some() && entry.kind == TaskPanelEntryKind::Shell
232 }
233
234 #[cfg(test)]
235 mod tests {
236 use super::*;
237 use unicode_width::UnicodeWidthStr;
238
239 fn shell(label: &str) -> PendingItem {
240 PendingItem {
241 kind: PendingItemKind::Shell,
242 state: PendingItemState::Running,
243 label: truncate_label(label),
244 }
245 }
246
247 fn task(label: &str) -> PendingItem {
248 PendingItem {
249 kind: PendingItemKind::Task,
250 state: PendingItemState::Running,
251 label: truncate_label(label),
252 }
253 }
254
255 fn agent(label: &str) -> PendingItem {
256 PendingItem {
257 kind: PendingItemKind::Agent,
258 state: PendingItemState::Running,
259 label: truncate_label(label),
260 }
261 }
262
263 #[test]
264 fn empty_pending_work_hides_the_indicator() {
265 let work = PendingWork::default();
266 assert!(work.items.is_empty());
267 assert_eq!(work.count(PendingItemKind::Shell), 0);
268 assert_eq!(work.count(PendingItemKind::Task), 0);
269 assert_eq!(work.count(PendingItemKind::Agent), 0);
270 }
271
272 #[test]
273 fn counts_cover_shells_tasks_and_agents_with_pluralization() {
274 let work = PendingWork {
275 items: vec![shell("cargo test"), task("run"), agent("Agent 3·scout")],
276 };
277 assert!(!work.items.is_empty());
278 assert_eq!(work.count(PendingItemKind::Shell), 1);
279 assert_eq!(work.count(PendingItemKind::Task), 1);
280 assert_eq!(work.count(PendingItemKind::Agent), 1);
281 assert_eq!(PendingItemKind::Shell.plural_noun(1), "shell");
282 assert_eq!(PendingItemKind::Task.plural_noun(1), "task");
283 assert_eq!(PendingItemKind::Agent.plural_noun(1), "agent");
284 }
285
286 #[test]
287 fn plural_counts_for_multiple_same_kind_items() {
288 let work = PendingWork {
289 items: vec![shell("one"), shell("two"), agent("A")],
290 };
291 assert_eq!(work.count(PendingItemKind::Shell), 2);
292 assert_eq!(PendingItemKind::Shell.plural_noun(2), "shells");
293 assert_eq!(work.count(PendingItemKind::Agent), 1);
294 }
295
296 #[test]
297 fn completion_clears_the_line() {
298 let mut work = PendingWork {
299 items: vec![shell("cargo test")],
300 };
301 assert!(!work.items.is_empty());
302 work.items.clear();
303 assert!(work.items.is_empty());
304 }
305
306 #[test]
307 fn long_labels_are_pre_truncated() {
308 let long = "cargo test -p codewhale-tui --lib background_indicator -- --exact this is long";
309 let work = PendingWork {
310 items: vec![shell(long)],
311 };
312 assert!(
313 work.items[0].label.contains('…'),
314 "over-long command ellipsized: got {}",
315 work.items[0].label
316 );
317 assert!(
318 work.items[0].label.width() <= ITEM_LABEL_MAX_WIDTH,
319 "label capped at {ITEM_LABEL_MAX_WIDTH}: got {}",
320 work.items[0].label
321 );
322 }
323
324 #[test]
325 fn pending_work_from_app_skips_non_background_entries() {
326 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from("."));
327 let app = crate::tui::test_support::test_app_with_options(options);
328 assert!(
329 pending_work_from_app(&app).items.is_empty(),
330 "bare app has no pending background work"
331 );
332 }
333
334 #[test]
335 fn pending_work_from_app_picks_up_shell_and_agent_entries() {
336 use crate::tui::app::TaskPanelEntry;
337 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from("."));
338 let mut app = crate::tui::test_support::test_app_with_options(options);
339 app.task_panel.push(TaskPanelEntry {
340 exit_code: None,
341 id: "shell_a1b2c3d4".to_string(),
342 status: "running".to_string(),
343 prompt_summary: "shell: cargo test -p codewhale-tui".to_string(),
344 duration_ms: Some(42_000),
345 kind: TaskPanelEntryKind::Shell,
346 stale: true,
347 elapsed_since_output_ms: Some(99_000),
348 owner_agent_id: None,
349 owner_agent_name: None,
350 current_tool: None,
351 role: None,
352 files_touched: 0,
353 });
354 app.task_panel.push(TaskPanelEntry {
355 exit_code: None,
356 id: "run".to_string(),
357 status: "running".to_string(),
358 prompt_summary: "background confirmation test".to_string(),
359 duration_ms: Some(99_000),
360 kind: TaskPanelEntryKind::Background,
361 stale: false,
362 elapsed_since_output_ms: None,
363 owner_agent_id: None,
364 owner_agent_name: None,
365 current_tool: None,
366 role: None,
367 files_touched: 0,
368 });
369 app.agent_progress
370 .insert("agent_live".to_string(), "checking the build".to_string());
371 app.agent_label_map
372 .insert("agent_live".to_string(), "Agent 1".to_string());
373
374 let work = pending_work_from_app(&app);
375 assert_eq!(
376 work.count(PendingItemKind::Shell),
377 0,
378 "shells are work-strip rows, not crumb items"
379 );
380 assert_eq!(work.count(PendingItemKind::Task), 1, "durable task counted");
381 assert_eq!(
382 work.count(PendingItemKind::Agent),
383 1,
384 "running agent counted"
385 );
386 let labels: Vec<&str> = work.items.iter().map(|item| item.label.as_str()).collect();
387 assert!(
388 !labels.iter().any(|label| label.contains("cargo test")),
389 "shell command must not occupy the counts: {labels:?}"
390 );
391 assert!(
392 labels
393 .iter()
394 .any(|label| label.starts_with("background confirma")),
395 "{labels:?}"
396 );
397 assert!(
398 labels.iter().any(|label| label.contains("Agent 1")),
399 "{labels:?}"
400 );
401
402 // Completion clears the snapshot: dropping the running entries hides
403 // the indicator entirely.
404 app.task_panel.clear();
405 app.agent_progress.clear();
406 let cleared = pending_work_from_app(&app);
407 assert!(cleared.items.is_empty(), "completion clears the indicator");
408 }
409
410 #[test]
411 fn durable_work_projection_keeps_queued_and_running_states() {
412 use crate::tui::app::TaskPanelEntry;
413 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from("."));
414 let mut app = crate::tui::test_support::test_app_with_options(options);
415 app.task_panel.extend([
416 TaskPanelEntry {
417 exit_code: None,
418 id: "durable-running".to_string(),
419 status: "running".to_string(),
420 prompt_summary: "durable work".to_string(),
421 duration_ms: Some(42_000),
422 kind: TaskPanelEntryKind::Background,
423 stale: false,
424 elapsed_since_output_ms: None,
425 owner_agent_id: None,
426 owner_agent_name: None,
427 current_tool: None,
428 role: None,
429 files_touched: 0,
430 },
431 TaskPanelEntry {
432 exit_code: None,
433 id: "durable-queued".to_string(),
434 status: "queued".to_string(),
435 prompt_summary: "durable work".to_string(),
436 duration_ms: None,
437 kind: TaskPanelEntryKind::Background,
438 stale: false,
439 elapsed_since_output_ms: None,
440 owner_agent_id: None,
441 owner_agent_name: None,
442 current_tool: None,
443 role: None,
444 files_touched: 0,
445 },
446 ]);
447
448 let work = pending_work_from_app(&app);
449 assert_eq!(work.count(PendingItemKind::Task), 2);
450 assert_eq!(work.count_state(PendingItemState::Queued), 1);
451 assert_eq!(work.count_state(PendingItemState::Running), 1);
452 assert!(
453 work.items
454 .iter()
455 .any(|item| item.label == "durable work" && item.state == PendingItemState::Running),
456 "durable running task must retain its typed state: {work:?}"
457 );
458 assert!(
459 work.items
460 .iter()
461 .any(|item| item.label == "durable work" && item.state == PendingItemState::Queued),
462 "durable queued task must retain its typed state: {work:?}"
463 );
464 }
465
466 #[test]
467 fn durable_task_prefers_trimmed_summary_and_falls_back_to_id() {
468 use crate::tui::app::TaskPanelEntry;
469 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from("."));
470 let mut app = crate::tui::test_support::test_app_with_options(options);
471 app.task_panel.extend([
472 TaskPanelEntry {
473 exit_code: None,
474 id: "task_with_summary".to_string(),
475 status: "running".to_string(),
476 prompt_summary: " audit workspace diff ".to_string(),
477 duration_ms: Some(1_000),
478 kind: TaskPanelEntryKind::Background,
479 stale: false,
480 elapsed_since_output_ms: None,
481 owner_agent_id: None,
482 owner_agent_name: None,
483 current_tool: None,
484 role: None,
485 files_touched: 0,
486 },
487 TaskPanelEntry {
488 exit_code: None,
489 id: "task_blank_summary".to_string(),
490 status: "queued".to_string(),
491 prompt_summary: " \t\n ".to_string(),
492 duration_ms: None,
493 kind: TaskPanelEntryKind::Background,
494 stale: false,
495 elapsed_since_output_ms: None,
496 owner_agent_id: None,
497 owner_agent_name: None,
498 current_tool: None,
499 role: None,
500 files_touched: 0,
501 },
502 ]);
503
504 let work = pending_work_from_app(&app);
505 let labels: Vec<&str> = work.items.iter().map(|item| item.label.as_str()).collect();
506 assert_eq!(labels, ["audit workspace diff", "task_blank_summary"]);
507 }
508
509 #[test]
510 fn pending_agents_are_labelled_by_the_name_they_were_dispatched_under() {
511 use codewhale_agent_contract::role::FleetRole;
512 use codewhale_engine::tools::subagent::{
513 SubAgentAssignment, SubAgentResult, SubAgentStatus,
514 };
515 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from("."));
516 let mut app = crate::tui::test_support::test_app_with_options(options);
517 let running = |agent_id: &str, name: &str| SubAgentResult {
518 usage: None,
519 name: name.to_string(),
520 agent_id: agent_id.to_string(),
521 context_mode: "fresh".to_string(),
522 fork_context: false,
523 workspace: None,
524 git_branch: None,
525 agent_type: FleetRole::Worker,
526 assignment: SubAgentAssignment {
527 native_preset: None,
528 objective: "sweep the lane".to_string(),
529 role: Some("builder".to_string()),
530 },
531 model: "test-model".to_string(),
532 nickname: Some(
533 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(agent_id, "en"),
534 ),
535 status: SubAgentStatus::Running,
536 worker_status: None,
537 runtime_permissions: None,
538 parent_run_id: None,
539 spawn_depth: 0,
540 child_route: None,
541 result: None,
542 steps_taken: 1,
543 checkpoint: None,
544 needs_input: None,
545 duration_ms: 100,
546 started_at: None,
547 from_prior_session: false,
548 idle_ms: None,
549 heartbeat_timeout_ms: None,
550 };
551 app.subagent_cache
552 .push(running("agent_named_lane", "triage"));
553 // An unnamed dispatch: `name` is still the agent id, so the whale
554 // nickname stays the honest label (#5287).
555 app.subagent_cache
556 .push(running("agent_plain_lane", "agent_plain_lane"));
557
558 let work = pending_work_from_app(&app);
559 let labels: Vec<&str> = work.items.iter().map(|item| item.label.as_str()).collect();
560 let whale = codewhale_engine::tools::subagent::whale_name_for_id_in_locale(
561 "agent_plain_lane",
562 "en",
563 );
564 assert_eq!(
565 labels,
566 ["triage·builder".to_string(), format!("{whale}·builder")]
567 );
568 }
569 }
570
570 lines RUST