返回 CodeWhale
sidebar.rs
根目录 / crates / tui / src / tui / sidebar.rs
1 //! Sub-agent row projection shared by the agent details view and the
2 //! roster: display name, typed status word, and child progress per worker.
3 //!
4 //! This is what is left of the classic sidebar (Pinned / Activity / Agents /
5 //! Context line panels). Those panels were retired when every dock view moved
6 //! onto the work surface's row pipeline (2026-09-02); the projection below is
7 //! the part other surfaces still read.
8
9 use codewhale_engine::tools::subagent::{
10 AgentWorkerStatus, SubAgentStatus, localized_whale_display_names,
11 };
12
13 use super::app::{AgentCurrentActivityStatus, App};
14
15 #[derive(Debug, Clone, Default)]
16 pub struct SidebarAgentRow {
17 pub id: String,
18 pub parent_run_id: Option<String>,
19 pub name: String,
20 pub model: Option<String>,
21 pub status: String,
22 pub steps_taken: u32,
23 pub duration_ms: Option<u64>,
24 /// `(settled, total)` over this row's direct children, when it has any
25 /// (#5479). A fan-out parent's own status says nothing about whether the
26 /// work it launched is finished; this is the "5/6 agents done" fact the
27 /// rail otherwise makes you count by eye. `None` for a leaf.
28 pub children_settled: Option<(usize, usize)>,
29 }
30
31 pub(crate) fn sidebar_agent_rows(app: &App) -> Vec<SidebarAgentRow> {
32 let cached_ids: std::collections::HashSet<&str> = app
33 .subagent_cache
34 .iter()
35 .map(|agent| agent.agent_id.as_str())
36 .collect();
37 let display_names = localized_whale_display_names(
38 app.subagent_cache
39 .iter()
40 .map(|agent| (agent.agent_id.as_str(), agent.nickname.as_deref())),
41 app.ui_locale.tag(),
42 );
43 let mut rows: Vec<SidebarAgentRow> = app
44 .subagent_cache
45 .iter()
46 .map(|agent| {
47 let current_activity = app
48 .agent_progress_meta
49 .get(&agent.agent_id)
50 .and_then(|meta| meta.current_activity.as_ref());
51 // The dispatch name leads (#5287). Generated whales name the
52 // agents that have none, locale-derived from the neutral agent
53 // id; never replay a persisted label from another language.
54 let display_name = app
55 .agent_given_name(&agent.agent_id)
56 .or_else(|| {
57 agent
58 .child_route
59 .as_ref()
60 .and_then(|route| route.resolved_profile_id.as_deref())
61 .map(str::trim)
62 .filter(|profile| !profile.is_empty())
63 .map(str::to_string)
64 })
65 .or_else(|| display_names.get(&agent.agent_id).cloned())
66 .or_else(|| app.agent_label_map.get(&agent.agent_id).cloned())
67 .unwrap_or_else(|| agent.name.clone());
68 SidebarAgentRow {
69 id: agent.agent_id.clone(),
70 parent_run_id: agent.parent_run_id.clone(),
71 name: display_name,
72 model: Some(agent.model.clone()).filter(|model| !model.trim().is_empty()),
73 status: current_activity
74 .map(|activity| {
75 sidebar_current_activity_status_text(activity.status, app.ui_locale)
76 })
77 .or_else(|| {
78 agent.worker_status.map(|status| {
79 std::borrow::Cow::Borrowed(sidebar_worker_status_text(status))
80 })
81 })
82 .unwrap_or_else(|| {
83 std::borrow::Cow::Borrowed(subagent_status_text(&agent.status))
84 })
85 .into_owned(),
86 steps_taken: agent.steps_taken,
87 duration_ms: Some(agent.duration_ms),
88 // Filled in by `annotate_child_progress` once every row exists.
89 children_settled: None,
90 }
91 })
92 .collect();
93
94 rows.extend(
95 app.agent_progress
96 .iter()
97 .filter(|(id, _)| !cached_ids.contains(id.as_str()))
98 .map(|(id, _progress)| {
99 // Progress-only rows do not carry a generated whale name yet;
100 // keep their existing stable Agent-N placeholder until the
101 // manager snapshot arrives.
102 let display_name = app
103 .agent_label_map
104 .get(id.as_str())
105 .cloned()
106 .unwrap_or_else(|| id.clone());
107 let meta = app.agent_progress_meta.get(id.as_str());
108 let current_activity = meta.and_then(|meta| meta.current_activity.as_ref());
109 SidebarAgentRow {
110 id: id.clone(),
111 parent_run_id: meta.and_then(|meta| meta.parent_run_id.clone()),
112 name: display_name,
113 model: meta.and_then(|meta| meta.resolved_model.clone()),
114 status: current_activity
115 .map(|activity| {
116 sidebar_current_activity_status_text(activity.status, app.ui_locale)
117 })
118 .unwrap_or(std::borrow::Cow::Borrowed(sidebar_worker_status_text(
119 AgentWorkerStatus::Running,
120 )))
121 .into_owned(),
122 steps_taken: 0,
123 duration_ms: None,
124 children_settled: None,
125 }
126 }),
127 );
128
129 let mut rows = sort_sidebar_agent_rows_as_tree(rows);
130 annotate_child_progress(&mut rows);
131 rows
132 }
133
134 /// Fill in each row's `children_settled` from its direct children.
135 ///
136 /// Counted over the rows actually present: a child whose record has aged out of
137 /// the ledger cannot be counted, and inventing a denominator that included it
138 /// would misreport progress as worse than it is.
139 fn annotate_child_progress(rows: &mut [SidebarAgentRow]) {
140 let mut totals: std::collections::HashMap<String, (usize, usize)> =
141 std::collections::HashMap::new();
142 for row in rows.iter() {
143 let Some(parent) = row.parent_run_id.as_deref() else {
144 continue;
145 };
146 let entry = totals.entry(parent.to_string()).or_insert((0, 0));
147 entry.1 += 1;
148 if sidebar_agent_status_is_terminal(row.status.as_str()) {
149 entry.0 += 1;
150 }
151 }
152 for row in rows.iter_mut() {
153 row.children_settled = totals.get(&row.id).copied();
154 }
155 }
156
157 fn sort_sidebar_agent_rows_as_tree(rows: Vec<SidebarAgentRow>) -> Vec<SidebarAgentRow> {
158 let known_ids: std::collections::HashSet<String> =
159 rows.iter().map(|row| row.id.clone()).collect();
160 let mut children: std::collections::HashMap<String, Vec<usize>> =
161 std::collections::HashMap::new();
162 let mut roots = Vec::new();
163
164 for (idx, row) in rows.iter().enumerate() {
165 if let Some(parent) = row.parent_run_id.as_deref()
166 && known_ids.contains(parent)
167 {
168 children.entry(parent.to_string()).or_default().push(idx);
169 continue;
170 }
171 roots.push(idx);
172 }
173
174 fn push_tree(
175 idx: usize,
176 rows: &[SidebarAgentRow],
177 children: &std::collections::HashMap<String, Vec<usize>>,
178 seen: &mut std::collections::HashSet<usize>,
179 order: &mut Vec<usize>,
180 ) {
181 if !seen.insert(idx) {
182 return;
183 }
184 order.push(idx);
185 if let Some(child_indices) = children.get(&rows[idx].id) {
186 for child_idx in child_indices {
187 push_tree(*child_idx, rows, children, seen, order);
188 }
189 }
190 }
191
192 let mut order = Vec::with_capacity(rows.len());
193 let mut seen = std::collections::HashSet::new();
194 for idx in roots {
195 push_tree(idx, &rows, &children, &mut seen, &mut order);
196 }
197 for idx in 0..rows.len() {
198 push_tree(idx, &rows, &children, &mut seen, &mut order);
199 }
200
201 // Materialize by move instead of cloning each row a second time (#3898):
202 // `seen` guarantees every index lands in `order` exactly once, so each
203 // slot is taken exactly once and no row is dropped.
204 let mut slots: Vec<Option<SidebarAgentRow>> = rows.into_iter().map(Some).collect();
205 order
206 .into_iter()
207 .map(|idx| slots[idx].take().expect("each row emitted exactly once"))
208 .collect()
209 }
210
211 fn subagent_status_text(status: &SubAgentStatus) -> &'static str {
212 match status {
213 SubAgentStatus::Running => "running",
214 SubAgentStatus::Completed => "done",
215 SubAgentStatus::Interrupted(_) => "interrupted",
216 SubAgentStatus::Failed(_) => "failed",
217 SubAgentStatus::Cancelled => "canceled",
218 SubAgentStatus::BudgetExhausted => "budget",
219 }
220 }
221
222 fn sidebar_worker_status_text(status: AgentWorkerStatus) -> &'static str {
223 match status {
224 AgentWorkerStatus::Queued => "queued",
225 AgentWorkerStatus::Starting => "starting",
226 AgentWorkerStatus::Running => "running",
227 AgentWorkerStatus::WaitingForUser => "waiting",
228 AgentWorkerStatus::ModelWait => "model wait",
229 AgentWorkerStatus::RunningTool => "tool",
230 AgentWorkerStatus::Completed => "done",
231 AgentWorkerStatus::Failed => "failed",
232 AgentWorkerStatus::Cancelled => "canceled",
233 AgentWorkerStatus::Interrupted => "interrupted",
234 }
235 }
236
237 fn sidebar_current_activity_status_text(
238 status: AgentCurrentActivityStatus,
239 locale: codewhale_localization::Locale,
240 ) -> std::borrow::Cow<'static, str> {
241 // A parked husk gets its own word, translated (#5906) — "waiting" here
242 // would be the same lie the work surface used to tell.
243 if status == AgentCurrentActivityStatus::Parked {
244 return codewhale_localization::tr(
245 locale,
246 codewhale_localization::MessageId::AgentStatusParked,
247 );
248 }
249 std::borrow::Cow::Borrowed(match status {
250 AgentCurrentActivityStatus::Queued => "queued",
251 AgentCurrentActivityStatus::Starting => "starting",
252 AgentCurrentActivityStatus::Running => "running",
253 AgentCurrentActivityStatus::ModelWait => "model wait",
254 AgentCurrentActivityStatus::RunningTool => "tool",
255 AgentCurrentActivityStatus::Waiting => "waiting",
256 AgentCurrentActivityStatus::Done => "done",
257 AgentCurrentActivityStatus::Failed => "failed",
258 AgentCurrentActivityStatus::Canceled => "canceled",
259 AgentCurrentActivityStatus::Interrupted => "interrupted",
260 AgentCurrentActivityStatus::Parked => unreachable!("handled above"),
261 })
262 }
263
264 fn sidebar_agent_status_is_terminal(status: &str) -> bool {
265 matches!(
266 status,
267 "done" | "canceled" | "failed" | "interrupted" | "budget"
268 )
269 }
270
271 #[cfg(test)]
272 mod tests {
273 use super::sidebar_agent_rows;
274 use crate::tui::app::{
275 AgentCurrentActivity, AgentCurrentActivityStatus, AgentProgressMeta, App,
276 SidebarHoverSection, SidebarHoverState, TuiOptions,
277 };
278 use codewhale_localization::Locale;
279 use codewhale_runtime::config::Config;
280 use std::path::PathBuf;
281
282 fn create_test_app() -> App {
283 let options = TuiOptions {
284 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
285 };
286 let mut app = App::new(options, &Config::default());
287 // Legacy strip geometry (see ui.rs); Bottom default has its own tests.
288 app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Top;
289 app
290 }
291
292 // ---- Sidebar hover tooltip tests ----
293
294 #[test]
295 fn sidebar_hover_state_default_is_empty() {
296 let state = SidebarHoverState::default();
297 assert!(state.sections.is_empty());
298 }
299
300 #[test]
301 fn sidebar_hover_section_stores_lines() {
302 use ratatui::layout::Rect;
303 let section = SidebarHoverSection {
304 content_area: Rect::new(1, 1, 38, 8),
305 lines: vec!["line 1".to_string(), "line 2".to_string()],
306 rows: vec![],
307 };
308 assert_eq!(section.lines.len(), 2);
309 assert_eq!(section.lines[0], "line 1");
310 assert!(section.content_area.x > 0);
311 }
312
313 #[test]
314 fn hover_line_matching_respects_content_area_offset() {
315 use ratatui::layout::Rect;
316 let section = SidebarHoverSection {
317 content_area: Rect::new(62, 2, 36, 6),
318 lines: vec![
319 "first".to_string(),
320 "second".to_string(),
321 "third".to_string(),
322 ],
323 rows: vec![],
324 };
325
326 // Mouse within content area, first line
327 let line_idx = (2u16.saturating_sub(section.content_area.y)) as usize;
328 assert_eq!(section.lines[line_idx], "first");
329
330 // Mouse within content area, second line
331 let line_idx = (3u16.saturating_sub(section.content_area.y)) as usize;
332 assert_eq!(section.lines[line_idx], "second");
333
334 // Mouse outside content area (above) — row < content_area.y
335 assert!((1u16) < section.content_area.y);
336 }
337
338 // ── #3030: stable labels instead of raw internal ids ───────────────────
339
340 #[test]
341 fn ensure_agent_label_assigns_stable_sequential_labels() {
342 let mut app = create_test_app();
343 assert_eq!(app.ensure_agent_label("agent_aaa111"), "Agent 1");
344 assert_eq!(app.ensure_agent_label("agent_bbb222"), "Agent 2");
345 // Re-seeing a known agent keeps its original label.
346 assert_eq!(app.ensure_agent_label("agent_aaa111"), "Agent 1");
347 assert_eq!(app.agent_counter, 2);
348 // Read-only lookup falls back to the raw id for unknown agents.
349 assert_eq!(app.agent_display_label("agent_bbb222"), "Agent 2");
350 assert_eq!(app.agent_display_label("agent_zzz999"), "agent_zzz999");
351 }
352
353 #[test]
354 fn ensure_agent_label_prefers_identity_over_the_counter() {
355 let mut app = create_test_app();
356 let route = |profile: Option<&str>, role: &str| {
357 Some(codewhale_engine::tools::subagent::ChildRouteReceipt {
358 requested_type: "custom".to_string(),
359 requested_profile: profile.map(str::to_string),
360 resolved_profile_id: None,
361 profile_origin: None,
362 canonical_role: role.to_string(),
363 provider_id: "deepseek".to_string(),
364 model_id: "deepseek-v4-pro".to_string(),
365 route_source: "roster".to_string(),
366 fallback_note: None,
367 requested_reasoning: "inherit".to_string(),
368 effective_reasoning: None,
369 runtime_version: "test".to_string(),
370 runtime_build_sha: "unknown".to_string(),
371 })
372 };
373
374 let mut named = cached_agent("agent_named", None);
375 named.name = "branch-triage".to_string();
376 app.subagent_cache.push(named);
377
378 let mut role = cached_agent("agent_role", None);
379 role.assignment.role = Some("reviewer".to_string());
380 app.subagent_cache.push(role);
381
382 let mut profile = cached_agent("agent_profile", None);
383 profile.assignment.role = None;
384 profile.child_route = route(Some("release-lead"), "custom");
385 app.subagent_cache.push(profile);
386
387 let mut canonical = cached_agent("agent_canonical", None);
388 canonical.assignment.role = None;
389 canonical.child_route = route(None, "planner");
390 app.subagent_cache.push(canonical);
391
392 let mut typed = cached_agent("agent_typed", None);
393 typed.assignment.role = None;
394 typed.agent_type = codewhale_agent_contract::role::FleetRole::Builder;
395 app.subagent_cache.push(typed);
396
397 // The dispatch name leads, annotated with the role when the role is
398 // not already part of the name.
399 assert_eq!(
400 app.ensure_agent_label("agent_named"),
401 "branch-triage · general"
402 );
403 // Unnamed children go by their role (#6565: the engine's one name);
404 // a suffix appears only when another agent already shows that name.
405 assert_eq!(app.ensure_agent_label("agent_role"), "reviewer");
406 assert_eq!(app.ensure_agent_label("agent_profile"), "release-lead");
407 assert_eq!(app.ensure_agent_label("agent_canonical"), "planner");
408 assert_eq!(app.ensure_agent_label("agent_typed"), "implement");
409
410 // A progress-only agent first seen before its metadata arrives gets a
411 // counter placeholder, then upgrades once the identity is observed.
412 assert_eq!(app.ensure_agent_label("agent_late"), "Agent 1");
413 let mut late = cached_agent("agent_late", None);
414 late.assignment.role = Some("verifier".to_string());
415 app.subagent_cache.push(late);
416 assert_eq!(app.ensure_agent_label("agent_late"), "test");
417 }
418
419 #[test]
420 fn ensure_agent_label_disambiguates_concurrent_same_role_children() {
421 let mut app = create_test_app();
422
423 let mut first = cached_agent("agent_builder_a", None);
424 first.assignment.role = None;
425 first.agent_type = codewhale_agent_contract::role::FleetRole::Builder;
426 app.subagent_cache.push(first);
427
428 let mut second = cached_agent("agent_builder_b", None);
429 second.assignment.role = None;
430 second.agent_type = codewhale_agent_contract::role::FleetRole::Builder;
431 app.subagent_cache.push(second);
432
433 assert_eq!(app.ensure_agent_label("agent_builder_a"), "implement");
434 assert_eq!(app.ensure_agent_label("agent_builder_b"), "implement · 2");
435 // Stability: re-seeing a known builder keeps its assigned label.
436 assert_eq!(app.ensure_agent_label("agent_builder_a"), "implement");
437 assert_eq!(app.ensure_agent_label("agent_builder_b"), "implement · 2");
438
439 // A different role needs no suffix.
440 let mut reviewer = cached_agent("agent_reviewer_a", None);
441 reviewer.assignment.role = Some("reviewer".to_string());
442 app.subagent_cache.push(reviewer);
443 assert_eq!(app.ensure_agent_label("agent_reviewer_a"), "reviewer");
444 }
445
446 #[test]
447 fn ensure_agent_label_named_child_skips_role_suffix_when_present() {
448 let mut app = create_test_app();
449
450 let mut named = cached_agent("agent_named", None);
451 named.name = "release-lead".to_string();
452 named.assignment.role = None;
453 named.child_route = Some(codewhale_engine::tools::subagent::ChildRouteReceipt {
454 requested_type: "custom".to_string(),
455 requested_profile: Some("release-lead".to_string()),
456 resolved_profile_id: None,
457 profile_origin: None,
458 canonical_role: "release-lead".to_string(),
459 provider_id: "deepseek".to_string(),
460 model_id: "deepseek-v4-pro".to_string(),
461 route_source: "roster".to_string(),
462 fallback_note: None,
463 requested_reasoning: "inherit".to_string(),
464 effective_reasoning: None,
465 runtime_version: "test".to_string(),
466 runtime_build_sha: "unknown".to_string(),
467 });
468 app.subagent_cache.push(named);
469
470 // The role is already part of the name, so no duplicate suffix.
471 assert_eq!(app.ensure_agent_label("agent_named"), "release-lead");
472 }
473
474 fn cached_agent(
475 agent_id: &str,
476 nickname: Option<&str>,
477 ) -> codewhale_engine::tools::subagent::SubAgentResult {
478 codewhale_engine::tools::subagent::SubAgentResult {
479 usage: None,
480 // An unnamed dispatch: the manager seeds `name` with the agent id
481 // and only replaces it when the caller supplied one.
482 name: agent_id.to_string(),
483 agent_id: agent_id.to_string(),
484 context_mode: "fresh".to_string(),
485 fork_context: false,
486 workspace: None,
487 git_branch: None,
488 agent_type: codewhale_agent_contract::role::FleetRole::Worker,
489 assignment: codewhale_engine::tools::subagent::SubAgentAssignment {
490 native_preset: None,
491 objective: "task".to_string(),
492 role: Some("worker".to_string()),
493 },
494 model: String::new(),
495 nickname: nickname.map(str::to_string),
496 status: codewhale_engine::tools::subagent::SubAgentStatus::Running,
497 worker_status: None,
498 runtime_permissions: None,
499 parent_run_id: None,
500 spawn_depth: 0,
501 child_route: None,
502 result: None,
503 steps_taken: 1,
504 checkpoint: None,
505 needs_input: None,
506 duration_ms: 100,
507 started_at: None,
508 from_prior_session: false,
509 idle_ms: None,
510 heartbeat_timeout_ms: None,
511 }
512 }
513
514 // === #5479: a fan-out parent shows how much of its fan-out is done ===
515
516 #[test]
517 fn a_fanout_parent_row_reports_how_many_children_have_settled() {
518 let mut app = create_test_app();
519 let parent = cached_agent("workflow_parent", None);
520 for index in 0..6 {
521 let mut child = cached_agent(&format!("child_{index}"), None);
522 child.parent_run_id = Some("workflow_parent".to_string());
523 child.spawn_depth = 1;
524 if index < 5 {
525 child.status = codewhale_engine::tools::subagent::SubAgentStatus::Completed;
526 child.worker_status =
527 Some(codewhale_engine::tools::subagent::AgentWorkerStatus::Completed);
528 }
529 app.subagent_cache.push(child);
530 }
531 app.subagent_cache.push(parent);
532
533 let rows = sidebar_agent_rows(&app);
534 let parent_row = rows
535 .iter()
536 .find(|row| row.id == "workflow_parent")
537 .expect("parent row");
538 assert_eq!(
539 parent_row.children_settled,
540 Some((5, 6)),
541 "the parent's own status says nothing about its fan-out"
542 );
543 for row in rows.iter().filter(|row| row.id != "workflow_parent") {
544 assert_eq!(
545 row.children_settled, None,
546 "a leaf must not claim a fan-out it does not have"
547 );
548 }
549 }
550
551 #[test]
552 fn a_parent_whose_children_aged_out_reports_no_progress_rather_than_zero() {
553 // A denominator that counted rows no longer in the ledger would report
554 // progress as worse than it is.
555 let mut app = create_test_app();
556 app.subagent_cache.push(cached_agent("lonely_parent", None));
557 let rows = sidebar_agent_rows(&app);
558 assert_eq!(rows[0].children_settled, None);
559 }
560
561 #[test]
562 fn sidebar_agent_rows_use_worker_status_from_cached_agents() {
563 let mut app = create_test_app();
564 let mut agent = cached_agent("agent_model_wait", Some("Blue"));
565 agent.worker_status = Some(codewhale_engine::tools::subagent::AgentWorkerStatus::ModelWait);
566 app.subagent_cache.push(agent);
567
568 let rows = sidebar_agent_rows(&app);
569
570 assert_eq!(rows.len(), 1);
571 assert_eq!(rows[0].status, "model wait");
572 }
573
574 #[test]
575 fn sidebar_agent_rows_project_typed_lifecycle_fixtures() {
576 let mut app = create_test_app();
577 let fixtures = [
578 (
579 "agent_running",
580 "Running",
581 codewhale_engine::tools::subagent::SubAgentStatus::Running,
582 codewhale_engine::tools::subagent::AgentWorkerStatus::RunningTool,
583 AgentCurrentActivityStatus::RunningTool,
584 "tool",
585 ),
586 (
587 "agent_waiting",
588 "Waiting",
589 codewhale_engine::tools::subagent::SubAgentStatus::Interrupted(
590 "approval".to_string(),
591 ),
592 codewhale_engine::tools::subagent::AgentWorkerStatus::WaitingForUser,
593 AgentCurrentActivityStatus::Waiting,
594 "waiting",
595 ),
596 (
597 "agent_failed",
598 "Failed",
599 codewhale_engine::tools::subagent::SubAgentStatus::Failed(
600 "verification".to_string(),
601 ),
602 codewhale_engine::tools::subagent::AgentWorkerStatus::Failed,
603 AgentCurrentActivityStatus::Failed,
604 "failed",
605 ),
606 (
607 "agent_done",
608 "Done",
609 codewhale_engine::tools::subagent::SubAgentStatus::Completed,
610 codewhale_engine::tools::subagent::AgentWorkerStatus::Completed,
611 AgentCurrentActivityStatus::Done,
612 "done",
613 ),
614 ];
615 for (id, nickname, status, worker_status, activity_status, _) in &fixtures {
616 let mut agent = cached_agent(id, Some(nickname));
617 agent.status = status.clone();
618 agent.worker_status = Some(*worker_status);
619 app.subagent_cache.push(agent);
620 app.agent_progress_meta.insert(
621 (*id).to_string(),
622 AgentProgressMeta {
623 current_activity: Some(AgentCurrentActivity::bounded(
624 *activity_status,
625 (*id == "agent_waiting").then_some("approval required".to_string()),
626 (*id == "agent_running").then_some("read_file".to_string()),
627 Some(2),
628 )),
629 ..AgentProgressMeta::default()
630 },
631 );
632 }
633
634 let rows = sidebar_agent_rows(&app);
635 for (id, _, _, _, _, expected_status) in fixtures {
636 let row = rows
637 .iter()
638 .find(|row| row.id == id)
639 .expect("typed lifecycle row");
640 assert_eq!(row.status, expected_status);
641 }
642 }
643
644 #[test]
645 fn sidebar_progress_only_rows_never_infer_status_from_display_text() {
646 let mut app = create_test_app();
647 app.ensure_agent_label("agent_queued");
648 app.agent_progress.insert(
649 "agent_queued".to_string(),
650 "queued waiting failed completed".to_string(),
651 );
652
653 let rows = sidebar_agent_rows(&app);
654
655 assert_eq!(rows.len(), 1);
656 assert_eq!(rows[0].name, "Agent 1");
657 assert_eq!(rows[0].status, "running");
658
659 app.agent_progress_meta.insert(
660 "agent_queued".to_string(),
661 AgentProgressMeta {
662 current_activity: Some(AgentCurrentActivity::bounded(
663 AgentCurrentActivityStatus::Queued,
664 Some("waiting for launch permit".to_string()),
665 None,
666 None,
667 )),
668 ..AgentProgressMeta::default()
669 },
670 );
671 crate::tui::ui::record_agent_spawned_route(&mut app, "agent_queued", "deepseek-v4-pro");
672 let rows = sidebar_agent_rows(&app);
673 assert_eq!(rows[0].status, "queued");
674 assert_eq!(rows[0].model.as_deref(), Some("deepseek-v4-pro"));
675 }
676
677 #[test]
678 fn sidebar_agent_rows_preserve_explicit_names_and_derive_whales_from_locale() {
679 let mut app = create_test_app();
680 let agent_id = "agent_cafe0123";
681 app.ensure_agent_label(agent_id);
682 app.subagent_cache
683 .push(cached_agent(agent_id, Some("doc-fixer")));
684
685 let rows = super::sidebar_agent_rows(&app);
686 assert_eq!(
687 rows[0].name, "doc-fixer",
688 "an explicit custom nickname remains user-owned"
689 );
690
691 // Without an explicit nickname, display is derived from the neutral id
692 // in the active UI locale rather than from the old Agent-N label.
693 app.subagent_cache[0].nickname = None;
694 let rows = super::sidebar_agent_rows(&app);
695 assert_eq!(
696 rows[0].name,
697 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(agent_id, "en")
698 );
699 }
700
701 #[test]
702 fn sidebar_agent_rows_lead_with_the_dispatch_name() {
703 // #5287: operators dispatch by name and think by name, so the session
704 // name outranks both the generated whale and the Agent-N label.
705 let mut app = create_test_app();
706 let agent_id = "agent_cafe0123";
707 app.ensure_agent_label(agent_id);
708 let whale = codewhale_engine::tools::subagent::whale_name_for_id_in_locale(agent_id, "en");
709 let mut agent = cached_agent(agent_id, Some(&whale));
710 agent.name = "branch-triage".to_string();
711 app.subagent_cache.push(agent);
712
713 let rows = super::sidebar_agent_rows(&app);
714 assert_eq!(rows[0].name, "branch-triage");
715 }
716
717 #[test]
718 fn sidebar_agent_rows_prefer_resolved_profile_over_generated_whale() {
719 let mut app = create_test_app();
720 let agent_id = "agent_cafe0123";
721 app.ensure_agent_label(agent_id);
722 let whale = codewhale_engine::tools::subagent::whale_name_for_id_in_locale(agent_id, "en");
723 let mut agent = cached_agent(agent_id, Some(&whale));
724 agent.child_route = Some(codewhale_engine::tools::subagent::ChildRouteReceipt {
725 requested_type: "custom".to_string(),
726 requested_profile: Some("DeepSeek V4 Flash".to_string()),
727 resolved_profile_id: Some("flash-scout".to_string()),
728 profile_origin: Some("fleet:release".to_string()),
729 canonical_role: "scout".to_string(),
730 provider_id: "deepseek".to_string(),
731 model_id: "deepseek-v4-flash-vision-exp".to_string(),
732 route_source: "fleet".to_string(),
733 fallback_note: None,
734 requested_reasoning: "inherit".to_string(),
735 effective_reasoning: None,
736 runtime_version: "test".to_string(),
737 runtime_build_sha: "unknown".to_string(),
738 });
739 app.subagent_cache.push(agent);
740
741 let rows = super::sidebar_agent_rows(&app);
742 assert_eq!(rows[0].name, "flash-scout");
743 }
744
745 #[test]
746 fn english_sidebar_relocalizes_mixed_persisted_whale_names() {
747 let mut app = create_test_app();
748 app.ui_locale = Locale::En;
749 for (agent_id, legacy_locale) in [
750 ("agent_locale_a", "zh-Hans"),
751 ("agent_locale_b", "ja"),
752 ("agent_locale_c", "vi"),
753 ] {
754 let legacy_name = codewhale_engine::tools::subagent::whale_name_for_id_in_locale(
755 agent_id,
756 legacy_locale,
757 );
758 app.subagent_cache
759 .push(cached_agent(agent_id, Some(&legacy_name)));
760 }
761
762 let rows = super::sidebar_agent_rows(&app);
763 assert_eq!(rows.len(), 3);
764 for row in rows {
765 assert!(
766 row.name.is_ascii(),
767 "English Fleet display leaked a prior-locale whale: {}",
768 row.name
769 );
770 assert_eq!(
771 row.name,
772 codewhale_engine::tools::subagent::whale_name_for_id_in_locale(&row.id, "en")
773 );
774 }
775 }
776
777 // === #5906: parked husks vs. children that actually asked ============
778
779 /// A child parked at the parent's turn end is handed a `needs_input` note
780 /// phrased as a question ("Resume this parked child with ..."), which is
781 /// why every surface used to label it `waiting`. Build one exactly the way
782 /// the runtime does and assert the row names the state instead.
783 fn parked_agent(agent_id: &str) -> codewhale_engine::tools::subagent::SubAgentResult {
784 let mut agent = cached_agent(agent_id, None);
785 agent.status = codewhale_engine::tools::subagent::SubAgentStatus::Interrupted(
786 "Parent turn ended before this turn-owned child settled.".to_string(),
787 );
788 agent.worker_status =
789 Some(codewhale_engine::tools::subagent::AgentWorkerStatus::WaitingForUser);
790 agent.needs_input = Some(codewhale_engine::tools::subagent::SubAgentNeedsInput {
791 question: format!(
792 "Resume this parked child with agent(action=\"start\", resume_from=\"{agent_id}\")."
793 ),
794 });
795 agent.checkpoint = Some(codewhale_engine::tools::subagent::SubAgentCheckpoint {
796 limit_kind: None,
797 checkpoint_id: format!("{agent_id}:step:2"),
798 agent_id: agent_id.to_string(),
799 continuation_handle: format!("agent:{agent_id}:checkpoint"),
800 reason: "Parent turn ended before this turn-owned child settled.".to_string(),
801 continuable: true,
802 steps_taken: 2,
803 message_count: 4,
804 created_at_ms: 1_000,
805 messages: Vec::new(),
806 omitted_messages: 0,
807 parked_at_turn_end: true,
808 });
809 agent
810 }
811
812 fn asking_agent(agent_id: &str) -> codewhale_engine::tools::subagent::SubAgentResult {
813 let mut agent = cached_agent(agent_id, None);
814 agent.worker_status =
815 Some(codewhale_engine::tools::subagent::AgentWorkerStatus::WaitingForUser);
816 agent.needs_input = Some(codewhale_engine::tools::subagent::SubAgentNeedsInput {
817 question: "Which path should I use?".to_string(),
818 });
819 agent
820 }
821
822 #[test]
823 fn a_parked_row_says_parked_and_a_real_question_still_says_waiting() {
824 let mut app = create_test_app();
825 app.subagent_cache.push(parked_agent("agent_parked"));
826 app.subagent_cache.push(asking_agent("agent_asking"));
827 crate::tui::subagent_routing::reconcile_subagent_activity_state(&mut app);
828
829 let rows = sidebar_agent_rows(&app);
830 let parked = rows
831 .iter()
832 .find(|row| row.id == "agent_parked")
833 .expect("parked row");
834 let asking = rows
835 .iter()
836 .find(|row| row.id == "agent_asking")
837 .expect("asking row");
838
839 assert_eq!(parked.status, "parked");
840 assert_ne!(
841 parked.status, "waiting",
842 "a parked husk must not wear the label a child a user can answer wears"
843 );
844 assert_eq!(asking.status, "waiting");
845 }
846
847 /// The status word is registry copy, not a hardcoded English literal.
848 #[test]
849 fn the_parked_status_word_follows_the_ui_locale() {
850 let mut app = create_test_app();
851 app.ui_locale = Locale::De;
852 app.subagent_cache.push(parked_agent("agent_parked_de"));
853 crate::tui::subagent_routing::reconcile_subagent_activity_state(&mut app);
854
855 let rows = sidebar_agent_rows(&app);
856 assert_eq!(
857 rows[0].status,
858 codewhale_localization::tr(
859 Locale::De,
860 codewhale_localization::MessageId::AgentStatusParked
861 )
862 );
863 }
864
865 // --- Unicode / CJK / terminal-width QA (issue #3488) -------------------
866 // The sub-agent overlay renders CJK display names next to ASCII ids,
867 // numeric columns (step count, elapsed), status verbs, and branch lines.
868 // These guard that a CJK name never shifts the status columns, corrupts the
869 // panel border, or hides the running/completed state (#3488 dogfood case:
870 // a worker named 抹香鲸).
871 }
872
872 lines RUST