| 1 | //! In-transcript cards for sub-agent activity (issue #128). |
| 2 | //! |
| 3 | //! Two cards consume the #130 mailbox stream and render live in the chat |
| 4 | //! transcript: |
| 5 | //! |
| 6 | //! - [`DelegateCard`] — single `agent` invocation. Live tree of the |
| 7 | //! last 3 actions plus a header with status / glyph / role. |
| 8 | //! - [`FanoutCard`] — `rlm` fanout (or any future multi-child dispatch). |
| 9 | //! Dot-grid of worker slots (`●` filled, `○` pending); header owns lifecycle. |
| 10 | //! |
| 11 | //! Both cards are state machines updated by [`apply_to_delegate`] / |
| 12 | //! [`apply_to_fanout`]. The sidebar (see `tui/sidebar.rs`) defers detail |
| 13 | //! to whichever card is active in the transcript, so these are the |
| 14 | //! primary status surface. |
| 15 | |
| 16 | use std::time::Instant; |
| 17 | |
| 18 | use ratatui::style::{Color, Modifier, Style}; |
| 19 | use ratatui::text::{Line, Span}; |
| 20 | |
| 21 | use crate::tui::widgets::tool_card::{ToolFamily, family_glyph}; |
| 22 | use codewhale_agent_contract::role::public_role_label; |
| 23 | use codewhale_engine::todo_snapshot::{ |
| 24 | TodoCardProjection, card_omission_line, card_todo_projection, |
| 25 | }; |
| 26 | use codewhale_engine::tools::subagent::MailboxMessage; |
| 27 | use codewhale_engine::tools::todo::TodoListSnapshot; |
| 28 | use codewhale_palette as palette; |
| 29 | use codewhale_tui_kit::ui_text::truncate_line_to_width; |
| 30 | use unicode_width::UnicodeWidthStr; |
| 31 | |
| 32 | /// Maximum number of recent actions kept on a `DelegateCard`. Older entries |
| 33 | /// are dropped from the head; an ellipsis row signals truncation. |
| 34 | pub const DELEGATE_MAX_ACTIONS: usize = 3; |
| 35 | |
| 36 | /// Lifecycle of a delegated / fanned-out agent. |
| 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 38 | pub enum AgentLifecycle { |
| 39 | Pending, |
| 40 | Running, |
| 41 | Completed, |
| 42 | Failed, |
| 43 | Cancelled, |
| 44 | /// Interrupted with a continuable checkpoint (e.g. API timeout); not |
| 45 | /// running, but recoverable from its checkpoint. |
| 46 | Interrupted, |
| 47 | } |
| 48 | |
| 49 | impl AgentLifecycle { |
| 50 | pub(crate) fn is_terminal(self) -> bool { |
| 51 | matches!( |
| 52 | self, |
| 53 | Self::Completed | Self::Failed | Self::Cancelled | Self::Interrupted |
| 54 | ) |
| 55 | } |
| 56 | |
| 57 | #[must_use] |
| 58 | pub fn label_in( |
| 59 | self, |
| 60 | locale: codewhale_localization::Locale, |
| 61 | ) -> std::borrow::Cow<'static, str> { |
| 62 | let id = match self { |
| 63 | Self::Pending => codewhale_localization::MessageId::AgentStatusPending, |
| 64 | Self::Running => codewhale_localization::MessageId::AgentStatusRunning, |
| 65 | Self::Completed => codewhale_localization::MessageId::AgentStatusCompleted, |
| 66 | Self::Failed => codewhale_localization::MessageId::AgentStatusFailed, |
| 67 | Self::Cancelled => codewhale_localization::MessageId::AgentStatusCancelled, |
| 68 | Self::Interrupted => codewhale_localization::MessageId::AgentStatusInterrupted, |
| 69 | }; |
| 70 | codewhale_localization::tr(locale, id) |
| 71 | } |
| 72 | |
| 73 | #[must_use] |
| 74 | pub fn label(self) -> &'static str { |
| 75 | match self.label_in(codewhale_localization::Locale::En) { |
| 76 | std::borrow::Cow::Borrowed(text) => text, |
| 77 | std::borrow::Cow::Owned(_) => "", |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Semantic status color only — never the whole-card identity tint. |
| 82 | /// cyan/teal = running, amber = waiting/pending, green = done, red = failed. |
| 83 | #[must_use] |
| 84 | pub fn ink(self) -> codewhale_palette::grammar::ChromeInk { |
| 85 | match self { |
| 86 | Self::Pending => codewhale_palette::grammar::ChromeInk::Waiting, |
| 87 | Self::Running => codewhale_palette::grammar::ChromeInk::Active, |
| 88 | Self::Completed => codewhale_palette::grammar::ChromeInk::Outcome, |
| 89 | Self::Failed => codewhale_palette::grammar::ChromeInk::Failure, |
| 90 | Self::Cancelled => codewhale_palette::grammar::ChromeInk::Metadata, |
| 91 | Self::Interrupted => codewhale_palette::grammar::ChromeInk::Attention, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | #[must_use] |
| 96 | pub fn color(self, theme: &palette::UiTheme) -> Color { |
| 97 | self.ink().color(theme) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Card for a single delegated `agent` invocation. |
| 102 | /// |
| 103 | /// Stores the last [`DELEGATE_MAX_ACTIONS`] action lines; older entries are |
| 104 | /// truncated and a single ellipsis row is rendered above the visible tail. |
| 105 | #[derive(Debug, Clone)] |
| 106 | pub struct DelegateCard { |
| 107 | pub agent_id: String, |
| 108 | pub agent_type: String, |
| 109 | pub status: AgentLifecycle, |
| 110 | pub summary: Option<String>, |
| 111 | actions: Vec<String>, |
| 112 | truncated: bool, |
| 113 | pub started_at: Option<Instant>, |
| 114 | pub finished_at: Option<Instant>, |
| 115 | /// The last To-do snapshot **this** agent published for itself (#4810). |
| 116 | /// |
| 117 | /// `None` means the child has never reported Work state — the card says |
| 118 | /// nothing rather than borrowing the parent's or a sibling's list. The |
| 119 | /// snapshot is only ever written from an envelope whose `agent_id` matches |
| 120 | /// [`Self::agent_id`], which is what keeps sibling cards disjoint. |
| 121 | todo: Option<TodoListSnapshot>, |
| 122 | } |
| 123 | |
| 124 | impl DelegateCard { |
| 125 | #[must_use] |
| 126 | pub fn new(agent_id: impl Into<String>, agent_type: impl Into<String>) -> Self { |
| 127 | Self { |
| 128 | agent_id: agent_id.into(), |
| 129 | agent_type: agent_type.into(), |
| 130 | status: AgentLifecycle::Pending, |
| 131 | summary: None, |
| 132 | actions: Vec::new(), |
| 133 | truncated: false, |
| 134 | started_at: None, |
| 135 | finished_at: None, |
| 136 | todo: None, |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// Record this agent's own To-do snapshot. Returns whether the visible |
| 141 | /// projection changed (an update that renders identically is not a |
| 142 | /// redraw). Callers must only pass a snapshot published by this agent. |
| 143 | pub fn set_todo(&mut self, todo: TodoListSnapshot) -> bool { |
| 144 | let before = self.todo.as_ref().and_then(card_todo_projection); |
| 145 | let after = card_todo_projection(&todo); |
| 146 | self.todo = Some(todo); |
| 147 | before != after |
| 148 | } |
| 149 | |
| 150 | /// The child's own To-do projection, if it has reported any work. |
| 151 | #[must_use] |
| 152 | pub fn todo_projection(&self) -> Option<TodoCardProjection> { |
| 153 | self.todo.as_ref().and_then(card_todo_projection) |
| 154 | } |
| 155 | |
| 156 | /// Project this direct sub-agent card onto the shared workflow history |
| 157 | /// renderer (#4122) so collapsed/expanded concepts stay aligned. |
| 158 | #[must_use] |
| 159 | #[cfg(test)] |
| 160 | pub fn as_workflow_history_panel( |
| 161 | &self, |
| 162 | started_at_ms: u64, |
| 163 | completed_at_ms: Option<u64>, |
| 164 | ) -> crate::tui::widgets::workflow_panel::WorkflowPanel { |
| 165 | use crate::tui::widgets::workflow_panel::{WorkflowPanel, WorkflowPanelLifecycle}; |
| 166 | let lifecycle = match self.status { |
| 167 | AgentLifecycle::Pending => WorkflowPanelLifecycle::Pending, |
| 168 | AgentLifecycle::Running => WorkflowPanelLifecycle::Running, |
| 169 | AgentLifecycle::Completed => WorkflowPanelLifecycle::Succeeded, |
| 170 | AgentLifecycle::Failed => WorkflowPanelLifecycle::Failed, |
| 171 | AgentLifecycle::Cancelled => WorkflowPanelLifecycle::Cancelled, |
| 172 | AgentLifecycle::Interrupted => WorkflowPanelLifecycle::Failed, |
| 173 | }; |
| 174 | WorkflowPanel::from_direct_subagent( |
| 175 | self.agent_id.clone(), |
| 176 | public_role_label(&self.agent_type), |
| 177 | lifecycle, |
| 178 | started_at_ms, |
| 179 | completed_at_ms, |
| 180 | self.summary.clone(), |
| 181 | if matches!(self.status, AgentLifecycle::Failed) { |
| 182 | self.summary.clone() |
| 183 | } else { |
| 184 | None |
| 185 | }, |
| 186 | ) |
| 187 | } |
| 188 | |
| 189 | pub fn push_action(&mut self, action: impl Into<String>) { |
| 190 | self.actions.push(action.into()); |
| 191 | if self.actions.len() > DELEGATE_MAX_ACTIONS { |
| 192 | // Drop one head entry per overflow so steady-state is exactly |
| 193 | // DELEGATE_MAX_ACTIONS lines; the ellipsis row signals the rest. |
| 194 | self.actions.remove(0); |
| 195 | self.truncated = true; |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | #[must_use] |
| 200 | pub fn render_lines(&self, width: u16, theme: &palette::UiTheme) -> Vec<Line<'static>> { |
| 201 | let mut lines = Vec::with_capacity(self.actions.len() + 3); |
| 202 | let content_width = usize::from(width); |
| 203 | let role = public_role_label(&self.agent_type); |
| 204 | let short_id = codewhale_engine::session_manager::truncate_id(&self.agent_id).to_string(); |
| 205 | let detail = if self.status.is_terminal() { |
| 206 | String::new() |
| 207 | } else if let Some(action) = self.actions.last() { |
| 208 | truncate_action(action, 72) |
| 209 | } else { |
| 210 | short_id |
| 211 | }; |
| 212 | lines.push(delegate_header( |
| 213 | self.status, |
| 214 | &role, |
| 215 | &detail, |
| 216 | content_width, |
| 217 | theme, |
| 218 | )); |
| 219 | // The child's own Work state sits directly under its header, above the |
| 220 | // action tail: what it is working on outranks what it just did. |
| 221 | if let Some(todo) = self.todo_projection() { |
| 222 | let prefix = "\u{22EF} "; // ⋯ |
| 223 | lines.push(Line::from(vec![ |
| 224 | Span::styled(prefix, Style::default().fg(palette::TEXT_DIM)), |
| 225 | Span::styled( |
| 226 | truncate_action(&todo.header, line_detail_width(content_width, prefix)), |
| 227 | Style::default() |
| 228 | .fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 229 | ), |
| 230 | ])); |
| 231 | let item_prefix = " "; |
| 232 | for item in &todo.items { |
| 233 | lines.push(Line::from(vec![ |
| 234 | Span::raw(item_prefix), |
| 235 | Span::styled( |
| 236 | truncate_action(item, line_detail_width(content_width, item_prefix)), |
| 237 | Style::default() |
| 238 | .fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 239 | ), |
| 240 | ])); |
| 241 | } |
| 242 | if todo.omitted > 0 { |
| 243 | lines.push(Line::from(vec![ |
| 244 | Span::raw(item_prefix), |
| 245 | Span::styled( |
| 246 | truncate_action( |
| 247 | &card_omission_line(todo.omitted), |
| 248 | line_detail_width(content_width, item_prefix), |
| 249 | ), |
| 250 | Style::default() |
| 251 | .fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 252 | ), |
| 253 | ])); |
| 254 | } |
| 255 | } |
| 256 | if self.truncated { |
| 257 | lines.push(Line::from(Span::styled( |
| 258 | "\u{2026}".to_string(), // … |
| 259 | Style::default().fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 260 | ))); |
| 261 | } |
| 262 | for action in self |
| 263 | .actions |
| 264 | .iter() |
| 265 | .take(self.actions.len().saturating_sub(1)) |
| 266 | { |
| 267 | let prefix = "\u{2502} "; |
| 268 | lines.push(Line::from(vec![ |
| 269 | Span::styled( |
| 270 | prefix, |
| 271 | Style::default() |
| 272 | .fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 273 | ), |
| 274 | Span::styled( |
| 275 | truncate_action(action, line_detail_width(content_width, prefix).min(200)), |
| 276 | Style::default() |
| 277 | .fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 278 | ), |
| 279 | ])); |
| 280 | } |
| 281 | if self.status.is_terminal() { |
| 282 | let mut terminal = self.status.label().to_string(); |
| 283 | if let (Some(started), Some(finished)) = (self.started_at, self.finished_at) { |
| 284 | terminal.push_str(" · "); |
| 285 | terminal.push_str(&codewhale_command_contract::elapsed::format_elapsed_ms( |
| 286 | finished.duration_since(started).as_millis() as u64, |
| 287 | )); |
| 288 | } |
| 289 | if let Some(summary) = self |
| 290 | .summary |
| 291 | .as_deref() |
| 292 | .filter(|summary| !summary.is_empty()) |
| 293 | { |
| 294 | terminal.push_str(" · "); |
| 295 | terminal.push_str(summary); |
| 296 | } |
| 297 | let prefix = "\u{2570} "; |
| 298 | lines.push(Line::from(Span::styled( |
| 299 | format!("{prefix}{terminal}"), |
| 300 | Style::default().fg(self.status.color(theme)), |
| 301 | ))); |
| 302 | } |
| 303 | lines |
| 304 | } |
| 305 | |
| 306 | /// Number of actions held — exposed for tests; bounded at |
| 307 | /// `DELEGATE_MAX_ACTIONS`. |
| 308 | #[must_use] |
| 309 | #[cfg(test)] |
| 310 | pub fn action_count(&self) -> usize { |
| 311 | self.actions.len() |
| 312 | } |
| 313 | |
| 314 | /// Whether the head was truncated (older actions dropped). |
| 315 | #[must_use] |
| 316 | #[cfg(test)] |
| 317 | pub fn truncated(&self) -> bool { |
| 318 | self.truncated |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// One worker slot in a fanout group. |
| 323 | #[derive(Debug, Clone)] |
| 324 | pub struct WorkerSlot { |
| 325 | /// Stable logical worker key. Stays tied to the worker slot even after a |
| 326 | /// concrete sub-agent id exists. |
| 327 | pub worker_id: String, |
| 328 | is_placeholder: bool, |
| 329 | /// Concrete agent id once spawned; placeholders use the worker id. |
| 330 | pub agent_id: String, |
| 331 | pub status: AgentLifecycle, |
| 332 | } |
| 333 | |
| 334 | impl WorkerSlot { |
| 335 | #[must_use] |
| 336 | pub fn new(worker_id: impl Into<String>, status: AgentLifecycle) -> Self { |
| 337 | let worker_id = worker_id.into(); |
| 338 | Self { |
| 339 | agent_id: worker_id.clone(), |
| 340 | is_placeholder: false, |
| 341 | worker_id, |
| 342 | status, |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// Card for `rlm` (or any multi-child dispatch) fanout: dot-grid + |
| 348 | /// aggregate counts. |
| 349 | /// |
| 350 | /// Slots are added as `ChildSpawned` envelopes arrive (or pre-allocated by |
| 351 | /// the engine when the worker count is known up front); each slot |
| 352 | /// transitions independently as its `Completed` / `Failed` / `Cancelled` |
| 353 | /// envelope is observed. |
| 354 | #[derive(Debug, Clone)] |
| 355 | pub struct FanoutCard { |
| 356 | pub kind: String, |
| 357 | pub workers: Vec<WorkerSlot>, |
| 358 | } |
| 359 | |
| 360 | impl FanoutCard { |
| 361 | #[must_use] |
| 362 | pub fn new(kind: impl Into<String>) -> Self { |
| 363 | Self { |
| 364 | kind: kind.into(), |
| 365 | workers: Vec::new(), |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | /// Pre-seed worker slots when the fanout size is known up front. |
| 370 | #[cfg(test)] |
| 371 | pub fn with_workers<I, S>(mut self, ids: I) -> Self |
| 372 | where |
| 373 | I: IntoIterator<Item = S>, |
| 374 | S: Into<String>, |
| 375 | { |
| 376 | for id in ids { |
| 377 | self.workers.push(WorkerSlot { |
| 378 | is_placeholder: true, |
| 379 | ..WorkerSlot::new(id, AgentLifecycle::Pending) |
| 380 | }); |
| 381 | } |
| 382 | self |
| 383 | } |
| 384 | |
| 385 | /// Update or insert a worker by id. Returns whether the visible state |
| 386 | /// changed and the card should be redrawn. A settled worker is final: a |
| 387 | /// delayed envelope for it never reopens or re-settles the slot. |
| 388 | pub fn upsert_worker(&mut self, agent_id: &str, status: AgentLifecycle) -> bool { |
| 389 | let slot_index = self |
| 390 | .workers |
| 391 | .iter() |
| 392 | .position(|slot| slot.agent_id == agent_id) |
| 393 | .or_else(|| self.workers.iter().position(|slot| slot.is_placeholder)); |
| 394 | if let Some(index) = slot_index { |
| 395 | let slot = &mut self.workers[index]; |
| 396 | if slot.status.is_terminal() |
| 397 | || (!slot.is_placeholder |
| 398 | && (slot.status == status || status == AgentLifecycle::Pending)) |
| 399 | { |
| 400 | return false; |
| 401 | } |
| 402 | if slot.is_placeholder { |
| 403 | slot.agent_id = agent_id.to_owned(); |
| 404 | slot.is_placeholder = false; |
| 405 | } |
| 406 | slot.status = status; |
| 407 | } else { |
| 408 | self.workers.push(WorkerSlot::new(agent_id, status)); |
| 409 | } |
| 410 | true |
| 411 | } |
| 412 | |
| 413 | fn counts(&self) -> (usize, usize, usize, usize) { |
| 414 | let mut done = 0usize; |
| 415 | let mut running = 0usize; |
| 416 | let mut failed = 0usize; |
| 417 | let mut pending = 0usize; |
| 418 | for slot in &self.workers { |
| 419 | match slot.status { |
| 420 | AgentLifecycle::Completed => done += 1, |
| 421 | AgentLifecycle::Running => running += 1, |
| 422 | AgentLifecycle::Failed |
| 423 | | AgentLifecycle::Cancelled |
| 424 | | AgentLifecycle::Interrupted => failed += 1, |
| 425 | AgentLifecycle::Pending => pending += 1, |
| 426 | } |
| 427 | } |
| 428 | (done, running, failed, pending) |
| 429 | } |
| 430 | |
| 431 | #[must_use] |
| 432 | pub fn dot_grid(&self) -> String { |
| 433 | let mut s = String::with_capacity(self.workers.len()); |
| 434 | for slot in &self.workers { |
| 435 | let glyph = match slot.status { |
| 436 | AgentLifecycle::Completed => '\u{25CF}', // ● |
| 437 | AgentLifecycle::Running => '\u{25D0}', // ◐ |
| 438 | AgentLifecycle::Failed => '\u{00D7}', // × |
| 439 | AgentLifecycle::Cancelled => '\u{2298}', // ⊘ |
| 440 | AgentLifecycle::Pending => '\u{25CB}', // ○ |
| 441 | AgentLifecycle::Interrupted => '\u{25CC}', // ◌ |
| 442 | }; |
| 443 | s.push(glyph); |
| 444 | } |
| 445 | s |
| 446 | } |
| 447 | |
| 448 | /// Header plus dot grid, one glyph per worker. The grid never runs past |
| 449 | /// `width`: when it does not fit beside the header it wraps onto its own |
| 450 | /// rows, so no worker's state is clipped off the transcript edge. |
| 451 | #[must_use] |
| 452 | pub fn render_lines(&self, width: u16, theme: &palette::UiTheme) -> Vec<Line<'static>> { |
| 453 | let header_status = self.aggregate_status(); |
| 454 | let count = self.workers.len(); |
| 455 | let count_label = if count == 1 { "agent" } else { "agents" }; |
| 456 | let glyph = family_glyph(ToolFamily::Fanout); |
| 457 | let count_text = format!("{count} {count_label}"); |
| 458 | let grid_style = Style::default() |
| 459 | .fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)) |
| 460 | .add_modifier(Modifier::BOLD); |
| 461 | // Every span fits the painted width, down to zero columns (U05-m6): |
| 462 | // the glyph only when it fits, the count only with room after it. |
| 463 | let width = usize::from(width); |
| 464 | let glyph_width = UnicodeWidthStr::width(glyph); |
| 465 | let mut header = Vec::new(); |
| 466 | if width >= glyph_width { |
| 467 | header.push(Span::styled( |
| 468 | glyph, |
| 469 | Style::default() |
| 470 | .fg(header_status.color(theme)) |
| 471 | .add_modifier(Modifier::BOLD), |
| 472 | )); |
| 473 | } |
| 474 | if width > glyph_width + 1 { |
| 475 | header.push(Span::raw(" ")); |
| 476 | header.push(Span::styled( |
| 477 | truncate_action(&count_text, width - glyph_width - 1), |
| 478 | Style::default() |
| 479 | .fg(codewhale_palette::grammar::ChromeInk::Identity.color(theme)) |
| 480 | .add_modifier(Modifier::BOLD), |
| 481 | )); |
| 482 | } |
| 483 | if width == 0 { |
| 484 | return vec![Line::from(header)]; |
| 485 | } |
| 486 | let grid: Vec<char> = self.dot_grid().chars().collect(); |
| 487 | let header_width = glyph_width + 1 + count_text.width() + 1; |
| 488 | if header_width + grid.len() <= width { |
| 489 | header.push(Span::raw(" ")); |
| 490 | header.push(Span::styled(grid.iter().collect::<String>(), grid_style)); |
| 491 | return vec![Line::from(header)]; |
| 492 | } |
| 493 | let mut lines = vec![Line::from(header)]; |
| 494 | lines.extend( |
| 495 | grid.chunks(width) |
| 496 | .map(|row| Line::from(Span::styled(row.iter().collect::<String>(), grid_style))), |
| 497 | ); |
| 498 | lines |
| 499 | } |
| 500 | |
| 501 | fn aggregate_status(&self) -> AgentLifecycle { |
| 502 | self.aggregate_status_public() |
| 503 | } |
| 504 | |
| 505 | /// Public aggregate lifecycle for the activity shelf and other projectors. |
| 506 | /// |
| 507 | /// A settled fanout reports its worst outcome: one failed worker among |
| 508 | /// finished ones is a failed fanout, not a completed one; an |
| 509 | /// interrupted or cancelled worker likewise outranks the completions. |
| 510 | #[must_use] |
| 511 | pub fn aggregate_status_public(&self) -> AgentLifecycle { |
| 512 | let (done, running, _, pending) = self.counts(); |
| 513 | let any = |status: AgentLifecycle| self.workers.iter().any(|slot| slot.status == status); |
| 514 | if running > 0 { |
| 515 | AgentLifecycle::Running |
| 516 | } else if pending > 0 { |
| 517 | // Pending workers wait — amber attention, not "running" teal. |
| 518 | AgentLifecycle::Pending |
| 519 | } else if any(AgentLifecycle::Failed) { |
| 520 | AgentLifecycle::Failed |
| 521 | } else if any(AgentLifecycle::Interrupted) { |
| 522 | AgentLifecycle::Interrupted |
| 523 | } else if any(AgentLifecycle::Cancelled) { |
| 524 | AgentLifecycle::Cancelled |
| 525 | } else if done > 0 { |
| 526 | AgentLifecycle::Completed |
| 527 | } else { |
| 528 | AgentLifecycle::Pending |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | /// Worker count (slots seeded or observed via mailbox). |
| 533 | #[must_use] |
| 534 | pub fn worker_count(&self) -> usize { |
| 535 | self.workers.len() |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | fn delegate_header( |
| 540 | status: AgentLifecycle, |
| 541 | role: &str, |
| 542 | detail: &str, |
| 543 | width: usize, |
| 544 | theme: &palette::UiTheme, |
| 545 | ) -> Line<'static> { |
| 546 | let glyph = format!("{} ", family_glyph(ToolFamily::Delegate)); |
| 547 | let fixed_parts: Vec<&str> = vec![glyph.as_str(), role, " "]; |
| 548 | let fixed_width = fixed_parts |
| 549 | .iter() |
| 550 | .map(|text| UnicodeWidthStr::width(*text)) |
| 551 | .sum::<usize>(); |
| 552 | let detail = truncate_action(detail, width.saturating_sub(fixed_width)); |
| 553 | let spans = vec![ |
| 554 | Span::styled( |
| 555 | glyph, |
| 556 | Style::default() |
| 557 | .fg(status.color(theme)) |
| 558 | .add_modifier(Modifier::BOLD), |
| 559 | ), |
| 560 | Span::styled( |
| 561 | role.to_string(), |
| 562 | Style::default() |
| 563 | .fg(codewhale_palette::grammar::ChromeInk::Identity.color(theme)) |
| 564 | .add_modifier(Modifier::BOLD), |
| 565 | ), |
| 566 | Span::raw(" "), |
| 567 | Span::styled( |
| 568 | detail, |
| 569 | Style::default().fg(codewhale_palette::grammar::ChromeInk::Metadata.color(theme)), |
| 570 | ), |
| 571 | ]; |
| 572 | Line::from(spans) |
| 573 | } |
| 574 | |
| 575 | fn line_detail_width(line_width: usize, prefix: &str) -> usize { |
| 576 | line_width.saturating_sub(UnicodeWidthStr::width(prefix)) |
| 577 | } |
| 578 | |
| 579 | fn truncate_action(text: &str, max: usize) -> String { |
| 580 | truncate_line_to_width(text.trim(), max) |
| 581 | } |
| 582 | |
| 583 | /// Apply a mailbox envelope to a `DelegateCard`. Returns `true` if the |
| 584 | /// state changed (UI may want to redraw); `false` if the envelope was for |
| 585 | /// a different `agent_id`. |
| 586 | pub fn apply_to_delegate(card: &mut DelegateCard, msg: &MailboxMessage) -> bool { |
| 587 | if msg.agent_id() != card.agent_id { |
| 588 | return false; |
| 589 | } |
| 590 | let was_terminal = card.status.is_terminal(); |
| 591 | // A settled agent is final. Mailbox producers are concurrent (a tool |
| 592 | // task can outlive its agent), so a Started/Progress/tool envelope may |
| 593 | // land after the terminal one; it must not reopen the card, stretch its |
| 594 | // elapsed time, or rewrite its outcome. Only the child's own Work |
| 595 | // snapshot still applies (it keeps the terminal status), and a late |
| 596 | // `Started` may still name the role of a card that a completion-first |
| 597 | // delivery opened with the `unknown` placeholder — identity, not state. |
| 598 | if was_terminal { |
| 599 | if let MailboxMessage::Started { agent_type, .. } = msg |
| 600 | && card.agent_type == "unknown" |
| 601 | && agent_type != "unknown" |
| 602 | { |
| 603 | card.agent_type = agent_type.clone(); |
| 604 | return true; |
| 605 | } |
| 606 | if !matches!(msg, MailboxMessage::WorkState { .. }) { |
| 607 | return false; |
| 608 | } |
| 609 | } |
| 610 | if card.started_at.is_none() |
| 611 | && matches!( |
| 612 | msg, |
| 613 | MailboxMessage::Started { .. } |
| 614 | | MailboxMessage::Progress { .. } |
| 615 | | MailboxMessage::ToolCallStarted { .. } |
| 616 | | MailboxMessage::ToolCallCompleted { .. } |
| 617 | | MailboxMessage::WorkState { .. } |
| 618 | ) |
| 619 | { |
| 620 | card.started_at = Some(Instant::now()); |
| 621 | } |
| 622 | match msg { |
| 623 | MailboxMessage::Started { .. } => { |
| 624 | if card.status == AgentLifecycle::Running { |
| 625 | return false; |
| 626 | } |
| 627 | card.status = AgentLifecycle::Running; |
| 628 | } |
| 629 | MailboxMessage::Progress { status, .. } => { |
| 630 | let low_signal = is_low_signal_progress(status); |
| 631 | if low_signal && card.status == AgentLifecycle::Running { |
| 632 | return false; |
| 633 | } |
| 634 | card.status = AgentLifecycle::Running; |
| 635 | if !low_signal { |
| 636 | card.push_action(status); |
| 637 | } |
| 638 | } |
| 639 | MailboxMessage::ToolCallStarted { tool_name, .. } => { |
| 640 | card.push_action(format!("{tool_name} running")); |
| 641 | } |
| 642 | MailboxMessage::ToolCallCompleted { tool_name, ok, .. } => { |
| 643 | card.push_action(format!("{tool_name} {}", if *ok { "ok" } else { "failed" })); |
| 644 | } |
| 645 | MailboxMessage::Completed { summary, .. } => { |
| 646 | card.status = AgentLifecycle::Completed; |
| 647 | card.summary = Some(summary.clone()); |
| 648 | } |
| 649 | MailboxMessage::Failed { error, .. } => { |
| 650 | card.status = AgentLifecycle::Failed; |
| 651 | card.summary = Some(error.clone()); |
| 652 | } |
| 653 | MailboxMessage::BudgetExhausted { summary, .. } => { |
| 654 | card.status = AgentLifecycle::Failed; |
| 655 | card.summary = Some(summary.clone()); |
| 656 | } |
| 657 | MailboxMessage::Interrupted { reason, .. } => { |
| 658 | card.status = AgentLifecycle::Interrupted; |
| 659 | card.summary = Some(reason.clone()); |
| 660 | } |
| 661 | MailboxMessage::Cancelled { .. } => { |
| 662 | card.status = AgentLifecycle::Cancelled; |
| 663 | } |
| 664 | MailboxMessage::WorkState { todo, .. } => { |
| 665 | // agent_id already matched above, so this is this child's own |
| 666 | // list. Publishing live work is evidence that a pending child |
| 667 | // has started, while terminal cards keep both their terminal |
| 668 | // status and the last snapshot the child published. |
| 669 | let status_changed = if card.status == AgentLifecycle::Pending { |
| 670 | card.status = AgentLifecycle::Running; |
| 671 | true |
| 672 | } else { |
| 673 | false |
| 674 | }; |
| 675 | return card.set_todo(todo.clone()) || status_changed; |
| 676 | } |
| 677 | MailboxMessage::ChildSpawned { .. } => { |
| 678 | // Delegate cards represent a single agent; child spawns belong |
| 679 | // to a sibling fanout card, not this one. |
| 680 | return false; |
| 681 | } |
| 682 | MailboxMessage::TokenUsage { .. } | MailboxMessage::FileWrites { .. } => { |
| 683 | // Cost accumulation happens in handle_subagent_mailbox (ui.rs) |
| 684 | // before this apply function is called; TokenUsage never reaches |
| 685 | // this arm in practice. |
| 686 | return false; |
| 687 | } |
| 688 | } |
| 689 | if !was_terminal && card.status.is_terminal() { |
| 690 | card.finished_at = Some(Instant::now()); |
| 691 | } |
| 692 | true |
| 693 | } |
| 694 | |
| 695 | /// Known limitation: this still matches on message text, while the footer |
| 696 | /// path keys off the structured `routine_wait` flag (#6290). The mailbox is |
| 697 | /// a stable cross-crate (`protocol`) surface whose payloads may come from |
| 698 | /// another binary, so this arm cannot assume the flag exists — and no |
| 699 | /// in-crate producer sends routine waits here anyway (only "queued" and |
| 700 | /// "running" texts), so threading the flag would change nothing. If a future |
| 701 | /// producer sends routine waits over the mailbox, give `Progress` the flag |
| 702 | /// and match on it here instead of extending this list. |
| 703 | fn is_low_signal_progress(status: &str) -> bool { |
| 704 | let status = status.trim().to_ascii_lowercase(); |
| 705 | status.contains("requesting model response") |
| 706 | || status.starts_with("started (") |
| 707 | || (status.starts_with("step ") && status.contains(": complete")) |
| 708 | } |
| 709 | |
| 710 | /// Apply a mailbox envelope to a `FanoutCard`. Updates per-worker state |
| 711 | /// based on which child the envelope is about. Returns `true` on change. |
| 712 | pub fn apply_to_fanout(card: &mut FanoutCard, msg: &MailboxMessage) -> bool { |
| 713 | let id = msg.agent_id(); |
| 714 | match msg { |
| 715 | MailboxMessage::Started { .. } |
| 716 | | MailboxMessage::Progress { .. } |
| 717 | | MailboxMessage::ToolCallStarted { .. } => card.upsert_worker(id, AgentLifecycle::Running), |
| 718 | MailboxMessage::ToolCallCompleted { .. } => true, |
| 719 | MailboxMessage::Completed { .. } => card.upsert_worker(id, AgentLifecycle::Completed), |
| 720 | MailboxMessage::Failed { .. } | MailboxMessage::BudgetExhausted { .. } => { |
| 721 | card.upsert_worker(id, AgentLifecycle::Failed) |
| 722 | } |
| 723 | MailboxMessage::Interrupted { .. } => card.upsert_worker(id, AgentLifecycle::Interrupted), |
| 724 | MailboxMessage::Cancelled { .. } => card.upsert_worker(id, AgentLifecycle::Cancelled), |
| 725 | MailboxMessage::ChildSpawned { child_id, .. } => { |
| 726 | card.upsert_worker(child_id, AgentLifecycle::Pending) |
| 727 | } |
| 728 | // A fanout card is a dot grid of many workers with no per-worker row |
| 729 | // to hang a list on. Rather than merge N children's lists into one |
| 730 | // card — which would be exactly the cross-agent leak this surface must |
| 731 | // not have — it shows none of them. WorkState is intentionally |
| 732 | // unavailable on this fanout surface; an individually spawned child |
| 733 | // may show its own To-do when it has a separate delegate card. |
| 734 | MailboxMessage::WorkState { .. } => false, |
| 735 | MailboxMessage::TokenUsage { .. } => { |
| 736 | // Cost accumulation happens in handle_subagent_mailbox (ui.rs) |
| 737 | // before this apply function is called; TokenUsage never reaches |
| 738 | // this arm in practice. |
| 739 | true |
| 740 | } |
| 741 | MailboxMessage::FileWrites { .. } => false, |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | #[cfg(test)] |
| 746 | mod tests { |
| 747 | use super::*; |
| 748 | use unicode_width::UnicodeWidthStr; |
| 749 | |
| 750 | fn render_to_strings(lines: &[Line<'static>]) -> Vec<String> { |
| 751 | lines |
| 752 | .iter() |
| 753 | .map(|line| { |
| 754 | line.spans |
| 755 | .iter() |
| 756 | .map(|span| span.content.as_ref()) |
| 757 | .collect::<String>() |
| 758 | }) |
| 759 | .collect() |
| 760 | } |
| 761 | |
| 762 | #[test] |
| 763 | fn delegate_card_header_does_not_duplicate_verb_as_role() { |
| 764 | let card = DelegateCard::new("agent_1", "explore"); |
| 765 | let rendered = |
| 766 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 767 | assert!( |
| 768 | !rendered.contains("delegate"), |
| 769 | "delegate must not be visible in the card: {rendered:?}" |
| 770 | ); |
| 771 | assert!(!rendered.contains("[running]"), "{rendered:?}"); |
| 772 | let explore = DelegateCard::new("agent_2", "scout"); |
| 773 | let explore_rendered = |
| 774 | render_to_strings(&explore.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 775 | assert!(explore_rendered.contains("explore"), "{explore_rendered:?}"); |
| 776 | } |
| 777 | |
| 778 | #[test] |
| 779 | fn delegate_card_cjk_text_respects_render_width() { |
| 780 | let mut card = DelegateCard::new("agent_e0b2dcf1", "implementer"); |
| 781 | card.status = AgentLifecycle::Running; |
| 782 | card.summary = Some( |
| 783 | "抹香鲸 agent_e0b2dcf1 running 10+ 124838ms role: implementer git: branch codex/issue-3439-zhipu-glm-fixture @ issue-3439".into(), |
| 784 | ); |
| 785 | card.push_action("objective: QUESTION: Add Zhipu GLM as a first-class provider-scoped route for 中文输出".to_string()); |
| 786 | |
| 787 | let rendered = render_to_strings(&card.render_lines(40, &codewhale_palette::UI_THEME)); |
| 788 | |
| 789 | assert!(rendered[0].contains("implement"), "{rendered:?}"); |
| 790 | for line in rendered { |
| 791 | let width = UnicodeWidthStr::width(line.as_str()); |
| 792 | assert!(width <= 40, "line width {width} exceeds 40: {line:?}"); |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn delegate_card_truncates_to_last_three_actions_with_ellipsis() { |
| 798 | let mut card = DelegateCard::new("agent_001", "general"); |
| 799 | card.push_action("read README.md"); |
| 800 | card.push_action("grep TODO"); |
| 801 | card.push_action("edit src/lib.rs"); |
| 802 | // Up to the limit — no truncation yet. |
| 803 | assert!(!card.truncated()); |
| 804 | assert_eq!(card.action_count(), DELEGATE_MAX_ACTIONS); |
| 805 | |
| 806 | card.push_action("write tests"); |
| 807 | card.push_action("run cargo test"); |
| 808 | assert!(card.truncated(), "truncation flag flips on overflow"); |
| 809 | assert_eq!( |
| 810 | card.action_count(), |
| 811 | DELEGATE_MAX_ACTIONS, |
| 812 | "stable steady-state size" |
| 813 | ); |
| 814 | |
| 815 | let rendered = render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)); |
| 816 | assert!( |
| 817 | rendered.iter().any(|line| line.contains('\u{2026}')), |
| 818 | "ellipsis indicator must render: got {rendered:?}" |
| 819 | ); |
| 820 | // The oldest two actions ("read README.md", "grep TODO") were dropped. |
| 821 | assert!( |
| 822 | !rendered.iter().any(|line| line.contains("read README.md")), |
| 823 | "oldest action evicted: got {rendered:?}" |
| 824 | ); |
| 825 | assert!( |
| 826 | rendered.iter().any(|line| line.contains("run cargo test")), |
| 827 | "newest action retained: got {rendered:?}" |
| 828 | ); |
| 829 | assert!( |
| 830 | rendered.iter().any(|line| line.contains("write tests")), |
| 831 | "second-newest retained: got {rendered:?}" |
| 832 | ); |
| 833 | assert!( |
| 834 | rendered.iter().any(|line| line.contains("edit src/lib.rs")), |
| 835 | "third-newest retained: got {rendered:?}" |
| 836 | ); |
| 837 | } |
| 838 | |
| 839 | #[test] |
| 840 | fn delegate_card_terminal_status_renders_summary_row() { |
| 841 | let mut card = DelegateCard::new("agent_002", "explore"); |
| 842 | card.push_action("listing files"); |
| 843 | let msg = MailboxMessage::Completed { |
| 844 | agent_id: "agent_002".into(), |
| 845 | summary: "scanned 42 files, no TODOs found".into(), |
| 846 | }; |
| 847 | assert!(apply_to_delegate(&mut card, &msg)); |
| 848 | assert_eq!(card.status, AgentLifecycle::Completed); |
| 849 | let rendered = render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)); |
| 850 | assert!( |
| 851 | rendered.iter().any(|line| line.contains("╰ done")), |
| 852 | "terminal status row renders done: got {rendered:?}" |
| 853 | ); |
| 854 | assert!( |
| 855 | rendered |
| 856 | .iter() |
| 857 | .any(|line| line.contains("scanned 42 files")), |
| 858 | "summary row renders on terminal status: got {rendered:?}" |
| 859 | ); |
| 860 | } |
| 861 | |
| 862 | #[test] |
| 863 | fn delegate_card_ignores_low_signal_scheduler_progress() { |
| 864 | let mut card = DelegateCard::new("agent_003", "general"); |
| 865 | let msg = MailboxMessage::progress("agent_003", "step 1/100: requesting model response"); |
| 866 | |
| 867 | assert!(apply_to_delegate(&mut card, &msg)); |
| 868 | assert_eq!(card.status, AgentLifecycle::Running); |
| 869 | assert_eq!( |
| 870 | card.action_count(), |
| 871 | 0, |
| 872 | "scheduler progress should not become a stale transcript row" |
| 873 | ); |
| 874 | |
| 875 | let rendered = |
| 876 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 877 | assert!(!rendered.contains("step 1/100"), "{rendered}"); |
| 878 | assert!( |
| 879 | !rendered.contains("requesting model response"), |
| 880 | "{rendered}" |
| 881 | ); |
| 882 | assert!( |
| 883 | !apply_to_delegate(&mut card, &msg), |
| 884 | "repeated low-signal progress should not redraw the card" |
| 885 | ); |
| 886 | } |
| 887 | |
| 888 | #[test] |
| 889 | fn delegate_tool_rows_omit_internal_step_numbers() { |
| 890 | let mut card = DelegateCard::new("agent_004", "general"); |
| 891 | |
| 892 | assert!(apply_to_delegate( |
| 893 | &mut card, |
| 894 | &MailboxMessage::ToolCallStarted { |
| 895 | agent_id: "agent_004".into(), |
| 896 | tool_name: "read_file".into(), |
| 897 | step: 7, |
| 898 | } |
| 899 | )); |
| 900 | assert!(apply_to_delegate( |
| 901 | &mut card, |
| 902 | &MailboxMessage::ToolCallCompleted { |
| 903 | agent_id: "agent_004".into(), |
| 904 | tool_name: "read_file".into(), |
| 905 | step: 7, |
| 906 | ok: true, |
| 907 | } |
| 908 | )); |
| 909 | |
| 910 | let rendered = |
| 911 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 912 | assert!(rendered.contains("read_file"), "{rendered}"); |
| 913 | assert!( |
| 914 | !rendered.contains("[7]"), |
| 915 | "internal loop step numbers are not useful in the live card: {rendered}" |
| 916 | ); |
| 917 | } |
| 918 | |
| 919 | #[test] |
| 920 | fn delegate_card_ignores_envelopes_for_other_agents() { |
| 921 | let mut card = DelegateCard::new("agent_a", "general"); |
| 922 | let other = MailboxMessage::progress("agent_b", "noise"); |
| 923 | assert!(!apply_to_delegate(&mut card, &other)); |
| 924 | assert_eq!(card.action_count(), 0); |
| 925 | } |
| 926 | |
| 927 | #[test] |
| 928 | fn fanout_card_dot_grid_renders_stateful_worker_slots() { |
| 929 | let mut card = FanoutCard::new("fanout") |
| 930 | .with_workers(["w_1", "w_2", "w_3", "w_4", "w_5", "w_6", "w_7"]); |
| 931 | card.upsert_worker("w_1", AgentLifecycle::Completed); |
| 932 | card.upsert_worker("w_2", AgentLifecycle::Completed); |
| 933 | card.upsert_worker("w_3", AgentLifecycle::Running); |
| 934 | card.upsert_worker("w_4", AgentLifecycle::Failed); |
| 935 | // 5/6/7 stay Pending. |
| 936 | |
| 937 | // Completed fills; running and failed are distinct; pending stays open. |
| 938 | assert_eq!( |
| 939 | card.dot_grid(), |
| 940 | "\u{25CF}\u{25CF}\u{25D0}\u{00D7}\u{25CB}\u{25CB}\u{25CB}" |
| 941 | ); |
| 942 | } |
| 943 | |
| 944 | #[test] |
| 945 | fn fanout_card_header_and_dot_grid_surface_aggregate_state() { |
| 946 | let mut card = FanoutCard::new("rlm").with_workers(["w_1", "w_2", "w_3", "w_4"]); |
| 947 | card.upsert_worker("w_1", AgentLifecycle::Completed); |
| 948 | card.upsert_worker("w_2", AgentLifecycle::Completed); |
| 949 | card.upsert_worker("w_3", AgentLifecycle::Completed); |
| 950 | card.upsert_worker("w_4", AgentLifecycle::Failed); |
| 951 | let rendered = |
| 952 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 953 | assert!( |
| 954 | rendered.contains("4 agents"), |
| 955 | "header should show count: {rendered}" |
| 956 | ); |
| 957 | assert!( |
| 958 | rendered.starts_with("⋮⋮ 4 agents"), |
| 959 | "header should omit the fanout kind: {rendered}" |
| 960 | ); |
| 961 | assert!( |
| 962 | rendered.contains("\u{25CF}\u{25CF}\u{25CF}\u{00D7}"), |
| 963 | "dot grid should mirror worker states: {rendered}" |
| 964 | ); |
| 965 | assert!( |
| 966 | !rendered.contains(" pending"), |
| 967 | "redundant counts line should stay omitted: {rendered}" |
| 968 | ); |
| 969 | } |
| 970 | |
| 971 | #[test] |
| 972 | fn fanout_apply_inserts_unknown_worker_via_child_spawned() { |
| 973 | let mut card = FanoutCard::new("fanout"); |
| 974 | let msg = MailboxMessage::ChildSpawned { |
| 975 | parent_id: "root".into(), |
| 976 | child_id: "agent_late".into(), |
| 977 | }; |
| 978 | assert!(apply_to_fanout(&mut card, &msg)); |
| 979 | assert_eq!(card.worker_count(), 1); |
| 980 | assert_eq!(card.workers[0].agent_id, "agent_late"); |
| 981 | assert_eq!(card.workers[0].status, AgentLifecycle::Pending); |
| 982 | } |
| 983 | |
| 984 | #[test] |
| 985 | fn fanout_started_claims_seeded_pending_slot_without_growing_grid() { |
| 986 | let mut card = FanoutCard::new("fanout").with_workers(["task:a", "task:b"]); |
| 987 | let started = MailboxMessage::started( |
| 988 | "agent_live", |
| 989 | codewhale_agent_contract::role::FleetRole::Worker, |
| 990 | ); |
| 991 | |
| 992 | assert!(apply_to_fanout(&mut card, &started)); |
| 993 | |
| 994 | assert_eq!(card.worker_count(), 2); |
| 995 | assert_eq!(card.workers[0].agent_id, "agent_live"); |
| 996 | assert_eq!(card.workers[0].status, AgentLifecycle::Running); |
| 997 | assert_eq!(card.workers[1].agent_id, "task:b"); |
| 998 | assert_eq!(card.workers[1].status, AgentLifecycle::Pending); |
| 999 | let progress = |
| 1000 | MailboxMessage::progress("agent_live", "step 1/100: requesting model response"); |
| 1001 | assert!( |
| 1002 | !apply_to_fanout(&mut card, &progress), |
| 1003 | "repeated progress for a running worker should not redraw" |
| 1004 | ); |
| 1005 | } |
| 1006 | |
| 1007 | #[test] |
| 1008 | fn fanout_apply_transitions_worker_through_lifecycle() { |
| 1009 | let mut card = FanoutCard::new("fanout").with_workers(["w_1"]); |
| 1010 | let started = |
| 1011 | MailboxMessage::started("w_1", codewhale_agent_contract::role::FleetRole::Worker); |
| 1012 | apply_to_fanout(&mut card, &started); |
| 1013 | assert_eq!(card.workers[0].status, AgentLifecycle::Running); |
| 1014 | |
| 1015 | let done = MailboxMessage::Completed { |
| 1016 | agent_id: "w_1".into(), |
| 1017 | summary: "ok".into(), |
| 1018 | }; |
| 1019 | apply_to_fanout(&mut card, &done); |
| 1020 | assert_eq!(card.workers[0].status, AgentLifecycle::Completed); |
| 1021 | } |
| 1022 | |
| 1023 | #[test] |
| 1024 | fn fanout_dot_grid_arithmetic_for_various_n() { |
| 1025 | // Spot-check several fanout sizes with a mix of states; this is the |
| 1026 | // arithmetic snapshot the issue acceptance calls out. |
| 1027 | let cases: &[(usize, usize, &str)] = &[ |
| 1028 | (1, 0, "\u{25CB}"), |
| 1029 | (1, 1, "\u{25CF}"), |
| 1030 | (3, 2, "\u{25CF}\u{25CF}\u{25CB}"), |
| 1031 | ( |
| 1032 | 7, |
| 1033 | 3, |
| 1034 | "\u{25CF}\u{25CF}\u{25CF}\u{25CB}\u{25CB}\u{25CB}\u{25CB}", |
| 1035 | ), |
| 1036 | ]; |
| 1037 | for (total, done, expected) in cases { |
| 1038 | let ids: Vec<String> = (0..*total).map(|i| format!("w_{i}")).collect(); |
| 1039 | let mut card = FanoutCard::new("fanout").with_workers(ids.iter().cloned()); |
| 1040 | for id in ids.iter().take(*done) { |
| 1041 | card.upsert_worker(id, AgentLifecycle::Completed); |
| 1042 | } |
| 1043 | assert_eq!( |
| 1044 | card.dot_grid(), |
| 1045 | *expected, |
| 1046 | "fanout dot-grid for total={total} done={done}", |
| 1047 | ); |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | #[test] |
| 1052 | fn delegate_interrupted_leaves_running_and_renders_reason() { |
| 1053 | let mut card = DelegateCard::new("agent_int", "general"); |
| 1054 | apply_to_delegate( |
| 1055 | &mut card, |
| 1056 | &MailboxMessage::started( |
| 1057 | "agent_int", |
| 1058 | codewhale_agent_contract::role::FleetRole::Worker, |
| 1059 | ), |
| 1060 | ); |
| 1061 | assert_eq!(card.status, AgentLifecycle::Running); |
| 1062 | |
| 1063 | let msg = MailboxMessage::Interrupted { |
| 1064 | agent_id: "agent_int".into(), |
| 1065 | reason: "API call timed out after 120000ms; checkpoint preserved for continuation" |
| 1066 | .into(), |
| 1067 | }; |
| 1068 | assert!(apply_to_delegate(&mut card, &msg)); |
| 1069 | assert_eq!(card.status, AgentLifecycle::Interrupted); |
| 1070 | |
| 1071 | let rendered = |
| 1072 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 1073 | assert!(rendered.contains("╰ interrupted"), "{rendered}"); |
| 1074 | assert!(rendered.contains("API call timed out"), "{rendered}"); |
| 1075 | } |
| 1076 | |
| 1077 | #[test] |
| 1078 | fn fanout_interrupted_worker_leaves_running_counts() { |
| 1079 | let mut card = FanoutCard::new("fanout").with_workers(["w_1", "w_2"]); |
| 1080 | apply_to_fanout( |
| 1081 | &mut card, |
| 1082 | &MailboxMessage::started("w_1", codewhale_agent_contract::role::FleetRole::Worker), |
| 1083 | ); |
| 1084 | apply_to_fanout( |
| 1085 | &mut card, |
| 1086 | &MailboxMessage::started("w_2", codewhale_agent_contract::role::FleetRole::Worker), |
| 1087 | ); |
| 1088 | |
| 1089 | let msg = MailboxMessage::Interrupted { |
| 1090 | agent_id: "w_1".into(), |
| 1091 | reason: "API call timed out".into(), |
| 1092 | }; |
| 1093 | assert!(apply_to_fanout(&mut card, &msg)); |
| 1094 | assert_eq!(card.workers[0].status, AgentLifecycle::Interrupted); |
| 1095 | assert_eq!(card.workers[1].status, AgentLifecycle::Running); |
| 1096 | |
| 1097 | // Copy dedupe (Wave 5c #4): the counts line is gone — the header and |
| 1098 | // dot grid carry the aggregate state instead. |
| 1099 | let rendered = |
| 1100 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 1101 | assert!(rendered.contains("2 agents"), "{rendered}"); |
| 1102 | assert!( |
| 1103 | rendered.contains('\u{25D0}'), |
| 1104 | "dot grid should keep the running worker glyph: {rendered}" |
| 1105 | ); |
| 1106 | assert!( |
| 1107 | rendered.contains('\u{25CC}'), |
| 1108 | "dot grid should mark the interrupted worker: {rendered}" |
| 1109 | ); |
| 1110 | |
| 1111 | let msg = MailboxMessage::Interrupted { |
| 1112 | agent_id: "w_2".into(), |
| 1113 | reason: "API call timed out".into(), |
| 1114 | }; |
| 1115 | assert!(apply_to_fanout(&mut card, &msg)); |
| 1116 | let rendered = |
| 1117 | render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)).join("\n"); |
| 1118 | assert!(rendered.contains("2 agents"), "{rendered}"); |
| 1119 | } |
| 1120 | |
| 1121 | #[test] |
| 1122 | fn fanout_card_omits_redundant_counts_line_when_header_and_grid_present() { |
| 1123 | let ids: Vec<String> = (0..16).map(|i| format!("w_{i}")).collect(); |
| 1124 | let mut card = FanoutCard::new("fanout").with_workers(ids.iter().cloned()); |
| 1125 | for id in ids.iter().take(12) { |
| 1126 | card.upsert_worker(id, AgentLifecycle::Completed); |
| 1127 | } |
| 1128 | card.upsert_worker("w_12", AgentLifecycle::Running); |
| 1129 | |
| 1130 | let rendered = render_to_strings(&card.render_lines(80, &codewhale_palette::UI_THEME)); |
| 1131 | assert!( |
| 1132 | rendered.iter().any(|line| line.contains('\u{25CF}')), |
| 1133 | "dot grid should remain: {rendered:?}" |
| 1134 | ); |
| 1135 | assert!( |
| 1136 | !rendered.iter().any(|line| line.contains('·')), |
| 1137 | "counts line should be dropped: {rendered:?}" |
| 1138 | ); |
| 1139 | } |
| 1140 | |
| 1141 | // === #4810: a child's own To-do on its own card === |
| 1142 | |
| 1143 | use codewhale_engine::tools::todo::{TodoItem, TodoStatus}; |
| 1144 | |
| 1145 | fn todo(items: &[(u32, &str, TodoStatus)], in_progress_id: Option<u32>) -> TodoListSnapshot { |
| 1146 | let items: Vec<TodoItem> = items |
| 1147 | .iter() |
| 1148 | .map(|(id, content, status)| TodoItem { |
| 1149 | id: *id, |
| 1150 | content: (*content).to_string(), |
| 1151 | status: *status, |
| 1152 | }) |
| 1153 | .collect(); |
| 1154 | let settled = items.iter().filter(|item| item.status.is_settled()).count(); |
| 1155 | let completion_pct = if items.is_empty() { |
| 1156 | 0 |
| 1157 | } else { |
| 1158 | ((settled * 100) / items.len()) as u8 |
| 1159 | }; |
| 1160 | TodoListSnapshot { |
| 1161 | items, |
| 1162 | completion_pct, |
| 1163 | in_progress_id, |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | fn work_state(agent_id: &str, snapshot: TodoListSnapshot) -> MailboxMessage { |
| 1168 | MailboxMessage::WorkState { |
| 1169 | agent_id: agent_id.to_string(), |
| 1170 | todo: snapshot, |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | #[test] |
| 1175 | fn delegate_card_renders_the_childs_own_todo_under_its_row() { |
| 1176 | let mut card = DelegateCard::new("agent_child", "implementer"); |
| 1177 | apply_to_delegate( |
| 1178 | &mut card, |
| 1179 | &MailboxMessage::started( |
| 1180 | "agent_child", |
| 1181 | codewhale_agent_contract::role::FleetRole::Worker, |
| 1182 | ), |
| 1183 | ); |
| 1184 | assert!(apply_to_delegate( |
| 1185 | &mut card, |
| 1186 | &work_state( |
| 1187 | "agent_child", |
| 1188 | todo( |
| 1189 | &[ |
| 1190 | (1, "read the runtime seam", TodoStatus::Completed), |
| 1191 | (2, "write the projection", TodoStatus::InProgress), |
| 1192 | ], |
| 1193 | Some(2), |
| 1194 | ), |
| 1195 | ), |
| 1196 | )); |
| 1197 | |
| 1198 | let rendered = |
| 1199 | render_to_strings(&card.render_lines(100, &codewhale_palette::UI_THEME)).join("\n"); |
| 1200 | assert!(rendered.contains("To-do 1/2"), "{rendered}"); |
| 1201 | assert!(rendered.contains("50% settled"), "{rendered}"); |
| 1202 | assert!( |
| 1203 | rendered.contains("[~] #2 write the projection"), |
| 1204 | "{rendered}" |
| 1205 | ); |
| 1206 | assert!( |
| 1207 | rendered.contains("[x] #1 read the runtime seam"), |
| 1208 | "{rendered}" |
| 1209 | ); |
| 1210 | // Role, model-facing lifecycle label, and identity stay exactly as the |
| 1211 | // row already reported them. |
| 1212 | assert!(rendered.contains("implement"), "{rendered}"); |
| 1213 | } |
| 1214 | |
| 1215 | #[test] |
| 1216 | fn delegate_card_ignores_work_state_addressed_to_another_agent() { |
| 1217 | let mut card = DelegateCard::new("agent_a", "general"); |
| 1218 | assert!(!apply_to_delegate( |
| 1219 | &mut card, |
| 1220 | &work_state( |
| 1221 | "agent_b", |
| 1222 | todo(&[(1, "sibling only work", TodoStatus::InProgress)], Some(1)), |
| 1223 | ), |
| 1224 | )); |
| 1225 | assert!(card.todo_projection().is_none()); |
| 1226 | let rendered = |
| 1227 | render_to_strings(&card.render_lines(100, &codewhale_palette::UI_THEME)).join("\n"); |
| 1228 | assert!(!rendered.contains("sibling only work"), "{rendered}"); |
| 1229 | assert!(!rendered.contains("To-do"), "{rendered}"); |
| 1230 | } |
| 1231 | |
| 1232 | #[test] |
| 1233 | fn delegate_card_shows_a_same_turn_update_without_waiting_for_completion() { |
| 1234 | let mut card = DelegateCard::new("agent_child", "general"); |
| 1235 | apply_to_delegate( |
| 1236 | &mut card, |
| 1237 | &work_state( |
| 1238 | "agent_child", |
| 1239 | todo(&[(1, "draft the fix", TodoStatus::InProgress)], Some(1)), |
| 1240 | ), |
| 1241 | ); |
| 1242 | |
| 1243 | // Same step: the child calls work_update and immediately republishes. |
| 1244 | apply_to_delegate( |
| 1245 | &mut card, |
| 1246 | &MailboxMessage::ToolCallCompleted { |
| 1247 | agent_id: "agent_child".to_string(), |
| 1248 | tool_name: "work_update".to_string(), |
| 1249 | step: 1, |
| 1250 | ok: true, |
| 1251 | }, |
| 1252 | ); |
| 1253 | assert!( |
| 1254 | apply_to_delegate( |
| 1255 | &mut card, |
| 1256 | &work_state( |
| 1257 | "agent_child", |
| 1258 | todo( |
| 1259 | &[ |
| 1260 | (1, "draft the fix", TodoStatus::Completed), |
| 1261 | (2, "add the regression", TodoStatus::InProgress), |
| 1262 | ], |
| 1263 | Some(2), |
| 1264 | ), |
| 1265 | ), |
| 1266 | ), |
| 1267 | "a changed list must redraw the card" |
| 1268 | ); |
| 1269 | |
| 1270 | let rendered = |
| 1271 | render_to_strings(&card.render_lines(100, &codewhale_palette::UI_THEME)).join("\n"); |
| 1272 | assert_eq!(card.status, AgentLifecycle::Running, "still mid-turn"); |
| 1273 | assert!(rendered.contains("[~] #2 add the regression"), "{rendered}"); |
| 1274 | assert!(rendered.contains("[x] #1 draft the fix"), "{rendered}"); |
| 1275 | assert!(rendered.contains("To-do 1/2"), "{rendered}"); |
| 1276 | |
| 1277 | // Republishing the identical snapshot is not a visible change. |
| 1278 | assert!(!apply_to_delegate( |
| 1279 | &mut card, |
| 1280 | &work_state( |
| 1281 | "agent_child", |
| 1282 | todo( |
| 1283 | &[ |
| 1284 | (1, "draft the fix", TodoStatus::Completed), |
| 1285 | (2, "add the regression", TodoStatus::InProgress), |
| 1286 | ], |
| 1287 | Some(2), |
| 1288 | ), |
| 1289 | ), |
| 1290 | )); |
| 1291 | } |
| 1292 | |
| 1293 | #[test] |
| 1294 | fn delegate_card_empty_child_todo_renders_no_item_at_all() { |
| 1295 | let mut card = DelegateCard::new("agent_child", "general"); |
| 1296 | card.push_action("read_file ok"); |
| 1297 | apply_to_delegate( |
| 1298 | &mut card, |
| 1299 | &work_state("agent_child", TodoListSnapshot::default()), |
| 1300 | ); |
| 1301 | |
| 1302 | assert!(card.todo_projection().is_none()); |
| 1303 | let rendered = |
| 1304 | render_to_strings(&card.render_lines(100, &codewhale_palette::UI_THEME)).join("\n"); |
| 1305 | assert!( |
| 1306 | !rendered.contains("To-do"), |
| 1307 | "an empty list states nothing: {rendered}" |
| 1308 | ); |
| 1309 | assert!( |
| 1310 | !rendered.contains('#'), |
| 1311 | "no synthesized item may appear: {rendered}" |
| 1312 | ); |
| 1313 | assert!(rendered.contains("read_file ok"), "{rendered}"); |
| 1314 | } |
| 1315 | |
| 1316 | #[test] |
| 1317 | fn delegate_card_todo_is_bounded_and_marks_what_it_elided() { |
| 1318 | let items: Vec<(u32, String, TodoStatus)> = (1..=9) |
| 1319 | .map(|id| { |
| 1320 | ( |
| 1321 | id, |
| 1322 | format!("item {id} ").repeat(30), |
| 1323 | if id == 8 { |
| 1324 | TodoStatus::InProgress |
| 1325 | } else { |
| 1326 | TodoStatus::Pending |
| 1327 | }, |
| 1328 | ) |
| 1329 | }) |
| 1330 | .collect(); |
| 1331 | let refs: Vec<(u32, &str, TodoStatus)> = items |
| 1332 | .iter() |
| 1333 | .map(|(id, content, status)| (*id, content.as_str(), *status)) |
| 1334 | .collect(); |
| 1335 | let mut card = DelegateCard::new("agent_child", "general"); |
| 1336 | apply_to_delegate(&mut card, &work_state("agent_child", todo(&refs, Some(8)))); |
| 1337 | |
| 1338 | let projection = card.todo_projection().expect("projection"); |
| 1339 | assert_eq!( |
| 1340 | projection.items.len(), |
| 1341 | codewhale_engine::todo_snapshot::MAX_CARD_ITEM_LINES |
| 1342 | ); |
| 1343 | assert_eq!( |
| 1344 | projection.omitted, |
| 1345 | 9 - codewhale_engine::todo_snapshot::MAX_CARD_ITEM_LINES |
| 1346 | ); |
| 1347 | assert!( |
| 1348 | projection |
| 1349 | .items |
| 1350 | .iter() |
| 1351 | .any(|line| line.starts_with("[~] #8")), |
| 1352 | "the active item is never the one dropped: {projection:?}" |
| 1353 | ); |
| 1354 | |
| 1355 | let rendered = render_to_strings(&card.render_lines(60, &codewhale_palette::UI_THEME)); |
| 1356 | assert!( |
| 1357 | rendered.iter().any(|line| line.contains("+6 more")), |
| 1358 | "elision must be stated: {rendered:?}" |
| 1359 | ); |
| 1360 | for line in &rendered { |
| 1361 | assert!( |
| 1362 | UnicodeWidthStr::width(line.as_str()) <= 60, |
| 1363 | "line exceeds the card width: {line:?}" |
| 1364 | ); |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | #[test] |
| 1369 | fn terminal_delegate_cards_keep_the_last_child_todo() { |
| 1370 | for terminal in [ |
| 1371 | MailboxMessage::Completed { |
| 1372 | agent_id: "agent_child".to_string(), |
| 1373 | summary: "done".to_string(), |
| 1374 | }, |
| 1375 | MailboxMessage::Failed { |
| 1376 | agent_id: "agent_child".to_string(), |
| 1377 | error: "boom".to_string(), |
| 1378 | }, |
| 1379 | MailboxMessage::Cancelled { |
| 1380 | agent_id: "agent_child".to_string(), |
| 1381 | }, |
| 1382 | ] { |
| 1383 | let mut card = DelegateCard::new("agent_child", "general"); |
| 1384 | apply_to_delegate( |
| 1385 | &mut card, |
| 1386 | &work_state( |
| 1387 | "agent_child", |
| 1388 | todo( |
| 1389 | &[ |
| 1390 | (1, "land the fix", TodoStatus::Completed), |
| 1391 | (2, "run the suite", TodoStatus::InProgress), |
| 1392 | ], |
| 1393 | Some(2), |
| 1394 | ), |
| 1395 | ), |
| 1396 | ); |
| 1397 | apply_to_delegate(&mut card, &terminal); |
| 1398 | |
| 1399 | let rendered = |
| 1400 | render_to_strings(&card.render_lines(100, &codewhale_palette::UI_THEME)).join("\n"); |
| 1401 | assert!(card.status.is_terminal(), "{:?}", card.status); |
| 1402 | assert!( |
| 1403 | rendered.contains("[~] #2 run the suite"), |
| 1404 | "terminal card keeps the last truthful list ({:?}): {rendered}", |
| 1405 | card.status |
| 1406 | ); |
| 1407 | assert!(rendered.contains("To-do 1/2"), "{rendered}"); |
| 1408 | } |
| 1409 | } |
| 1410 | |
| 1411 | #[test] |
| 1412 | fn fanout_card_does_not_project_any_workers_todo() { |
| 1413 | let mut card = FanoutCard::new("fanout").with_workers(["w_1", "w_2"]); |
| 1414 | assert!(!apply_to_fanout( |
| 1415 | &mut card, |
| 1416 | &work_state( |
| 1417 | "w_1", |
| 1418 | todo(&[(1, "worker one work", TodoStatus::InProgress)], Some(1)), |
| 1419 | ), |
| 1420 | )); |
| 1421 | let rendered = |
| 1422 | render_to_strings(&card.render_lines(100, &codewhale_palette::UI_THEME)).join("\n"); |
| 1423 | assert!(!rendered.contains("worker one work"), "{rendered}"); |
| 1424 | assert!(!rendered.contains("To-do"), "{rendered}"); |
| 1425 | } |
| 1426 | |
| 1427 | #[test] |
| 1428 | fn direct_subagent_projects_onto_shared_workflow_history_card() { |
| 1429 | use crate::tui::widgets::workflow_panel::WorkflowHistoryExtras; |
| 1430 | |
| 1431 | let mut card = DelegateCard::new("agent_xyz", "explore"); |
| 1432 | card.status = AgentLifecycle::Completed; |
| 1433 | card.summary = Some("mapped 4 call sites".to_string()); |
| 1434 | let panel = card.as_workflow_history_panel(1_000, Some(5_000)); |
| 1435 | let compact = panel.render_history_card(100, false, &WorkflowHistoryExtras::default()); |
| 1436 | let joined = render_to_strings(&compact).join("\n"); |
| 1437 | assert!( |
| 1438 | joined.contains("success") || joined.contains("explore"), |
| 1439 | "shared compact lifecycle: {joined}" |
| 1440 | ); |
| 1441 | assert!( |
| 1442 | joined.contains("1/1 done"), |
| 1443 | "shared settled/total count: {joined}" |
| 1444 | ); |
| 1445 | let expanded = panel.render_history_card( |
| 1446 | 100, |
| 1447 | true, |
| 1448 | &WorkflowHistoryExtras { |
| 1449 | result_summary: Some("mapped 4 call sites".to_string()), |
| 1450 | ..WorkflowHistoryExtras::default() |
| 1451 | }, |
| 1452 | ); |
| 1453 | let joined = render_to_strings(&expanded).join("\n"); |
| 1454 | assert!(joined.contains("result:"), "{joined}"); |
| 1455 | assert!(joined.contains("mapped 4 call sites"), "{joined}"); |
| 1456 | } |
| 1457 | |
| 1458 | /// U05-04: mailbox producers are concurrent, so a Started/Progress/tool |
| 1459 | /// envelope can land after an agent's terminal one. It must not reopen |
| 1460 | /// the card or its fanout slot, and must not move a settled count. |
| 1461 | #[test] |
| 1462 | fn late_envelopes_never_reopen_a_settled_agent() { |
| 1463 | let role = || codewhale_agent_contract::role::FleetRole::Worker; |
| 1464 | let mut card = DelegateCard::new("agent_late", "general"); |
| 1465 | apply_to_delegate(&mut card, &MailboxMessage::started("agent_late", role())); |
| 1466 | assert!(apply_to_delegate( |
| 1467 | &mut card, |
| 1468 | &MailboxMessage::Completed { |
| 1469 | agent_id: "agent_late".into(), |
| 1470 | summary: "done".into(), |
| 1471 | }, |
| 1472 | )); |
| 1473 | let finished_at = card.finished_at; |
| 1474 | for late in [ |
| 1475 | MailboxMessage::started("agent_late", role()), |
| 1476 | MailboxMessage::progress("agent_late", "step 4: reading files"), |
| 1477 | MailboxMessage::ToolCallStarted { |
| 1478 | agent_id: "agent_late".into(), |
| 1479 | tool_name: "read_file".into(), |
| 1480 | step: 4, |
| 1481 | }, |
| 1482 | MailboxMessage::Failed { |
| 1483 | agent_id: "agent_late".into(), |
| 1484 | error: "late".into(), |
| 1485 | }, |
| 1486 | ] { |
| 1487 | assert!(!apply_to_delegate(&mut card, &late), "{late:?}"); |
| 1488 | } |
| 1489 | assert_eq!(card.status, AgentLifecycle::Completed); |
| 1490 | assert_eq!(card.summary.as_deref(), Some("done")); |
| 1491 | assert_eq!(card.finished_at, finished_at); |
| 1492 | |
| 1493 | // A completion-first recovery card may still learn its role from a |
| 1494 | // late `Started`, but it stays settled. |
| 1495 | let mut recovered = DelegateCard::new("agent_r", "unknown"); |
| 1496 | apply_to_delegate( |
| 1497 | &mut recovered, |
| 1498 | &MailboxMessage::Completed { |
| 1499 | agent_id: "agent_r".into(), |
| 1500 | summary: "done".into(), |
| 1501 | }, |
| 1502 | ); |
| 1503 | assert!(apply_to_delegate( |
| 1504 | &mut recovered, |
| 1505 | &MailboxMessage::started("agent_r", role()) |
| 1506 | )); |
| 1507 | assert_ne!(recovered.agent_type, "unknown"); |
| 1508 | assert_eq!(recovered.status, AgentLifecycle::Completed); |
| 1509 | |
| 1510 | let mut fanout = FanoutCard::new("rlm"); |
| 1511 | for id in ["w_1", "w_2"] { |
| 1512 | apply_to_fanout( |
| 1513 | &mut fanout, |
| 1514 | &MailboxMessage::ChildSpawned { |
| 1515 | parent_id: "root".into(), |
| 1516 | child_id: id.into(), |
| 1517 | }, |
| 1518 | ); |
| 1519 | apply_to_fanout(&mut fanout, &MailboxMessage::started(id, role())); |
| 1520 | apply_to_fanout( |
| 1521 | &mut fanout, |
| 1522 | &MailboxMessage::Completed { |
| 1523 | agent_id: id.into(), |
| 1524 | summary: "ok".into(), |
| 1525 | }, |
| 1526 | ); |
| 1527 | } |
| 1528 | assert!(!apply_to_fanout( |
| 1529 | &mut fanout, |
| 1530 | &MailboxMessage::progress("w_1", "step 9: late") |
| 1531 | )); |
| 1532 | assert!(!apply_to_fanout( |
| 1533 | &mut fanout, |
| 1534 | &MailboxMessage::started("w_2", role()) |
| 1535 | )); |
| 1536 | assert_eq!(fanout.worker_count(), 2); |
| 1537 | assert_eq!(fanout.counts(), (2, 0, 0, 0)); |
| 1538 | assert_eq!(fanout.aggregate_status_public(), AgentLifecycle::Completed); |
| 1539 | } |
| 1540 | |
| 1541 | /// U05-m2: a settled fanout headlines its worst outcome — one failure |
| 1542 | /// among completions is a failed fanout, not a completed one. |
| 1543 | #[test] |
| 1544 | fn mixed_fanout_outcomes_never_aggregate_to_completed() { |
| 1545 | let mut card = FanoutCard::new("rlm").with_workers(["w_1", "w_2", "w_3"]); |
| 1546 | card.upsert_worker("w_1", AgentLifecycle::Completed); |
| 1547 | card.upsert_worker("w_2", AgentLifecycle::Completed); |
| 1548 | card.upsert_worker("w_3", AgentLifecycle::Failed); |
| 1549 | assert_eq!(card.aggregate_status_public(), AgentLifecycle::Failed); |
| 1550 | |
| 1551 | let mut card = FanoutCard::new("rlm").with_workers(["w_1", "w_2"]); |
| 1552 | card.upsert_worker("w_1", AgentLifecycle::Completed); |
| 1553 | card.upsert_worker("w_2", AgentLifecycle::Cancelled); |
| 1554 | assert_eq!(card.aggregate_status_public(), AgentLifecycle::Cancelled); |
| 1555 | |
| 1556 | let mut card = FanoutCard::new("rlm").with_workers(["w_1"]); |
| 1557 | card.upsert_worker("w_1", AgentLifecycle::Completed); |
| 1558 | assert_eq!(card.aggregate_status_public(), AgentLifecycle::Completed); |
| 1559 | } |
| 1560 | |
| 1561 | /// U05-m6: a wide fanout wraps its dot grid instead of running past the |
| 1562 | /// transcript width, and every worker keeps its glyph. |
| 1563 | #[test] |
| 1564 | fn fanout_header_fits_zero_and_one_column_renders() { |
| 1565 | let ids: Vec<String> = (0..5).map(|i| format!("w_{i}")).collect(); |
| 1566 | let card = FanoutCard::new("rlm").with_workers(ids.iter().cloned()); |
| 1567 | // Every width from nothing up past the header, including the ones |
| 1568 | // where the count is truncated and the grid wraps. |
| 1569 | for width in 0_u16..=16 { |
| 1570 | let lines = render_to_strings(&card.render_lines(width, &codewhale_palette::UI_THEME)); |
| 1571 | assert!(!lines.is_empty(), "{width}"); |
| 1572 | for line in &lines { |
| 1573 | assert!( |
| 1574 | UnicodeWidthStr::width(line.as_str()) <= usize::from(width), |
| 1575 | "{width}: {line:?}" |
| 1576 | ); |
| 1577 | } |
| 1578 | } |
| 1579 | } |
| 1580 | |
| 1581 | #[test] |
| 1582 | fn fanout_grid_wraps_within_the_render_width() { |
| 1583 | let ids: Vec<String> = (0..40).map(|i| format!("w_{i}")).collect(); |
| 1584 | let card = FanoutCard::new("rlm").with_workers(ids.iter().cloned()); |
| 1585 | for width in [12_u16, 20, 80] { |
| 1586 | let lines = render_to_strings(&card.render_lines(width, &codewhale_palette::UI_THEME)); |
| 1587 | for line in &lines { |
| 1588 | assert!( |
| 1589 | UnicodeWidthStr::width(line.as_str()) <= usize::from(width), |
| 1590 | "{width}: {line:?}" |
| 1591 | ); |
| 1592 | } |
| 1593 | let glyphs = lines |
| 1594 | .join("") |
| 1595 | .chars() |
| 1596 | .filter(|ch| *ch == '\u{25CB}') |
| 1597 | .count(); |
| 1598 | assert_eq!(glyphs, 40, "{width}: {lines:?}"); |
| 1599 | } |
| 1600 | } |
| 1601 | } |
| 1602 |