返回 CodeWhale
workflow_panel.rs
根目录 / crates / tui / src / tui / widgets / workflow_panel.rs
1 //! WorkflowPanel — one workflow run's state, reduced from its event stream.
2 //!
3 //! Issue #4121 (CODEWHALE_0_8_68 §2.4). Progress lives off the transcript: the
4 //! workbar under the composer (`workbar.rs`) paints one row per run from this
5 //! state, and `/workflows` holds the detail. Events are applied through
6 //! [`WorkflowPanelEvent`].
7 //!
8 //! Issue #4122 routes the same event stream into a compact history card that
9 //! reuses this state machine: collapsed summarizes lifecycle/children/phases/
10 //! failures/elapsed; expanded adds phase/child summaries, artifact links,
11 //! final result, and failure details. Direct sub-agent cards share helpers
12 //! from this module where practical.
13
14 use std::path::PathBuf;
15 use std::time::{SystemTime, UNIX_EPOCH};
16
17 #[cfg(test)]
18 use ratatui::style::Modifier;
19 use ratatui::style::Style;
20 use ratatui::text::{Line, Span};
21 use serde_json::{Value, json};
22 use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
23
24 use codewhale_localization::{Locale, MessageId, tr};
25 use codewhale_palette as palette;
26 use codewhale_tui_kit::ui_text::{pad_to_display_width, truncate_line_to_width};
27
28 /// Maximum phase summary chips shown in the expanded body.
29 const MAX_PHASE_SUMMARY: usize = 6;
30 const MAX_SUMMARY_CHILD_ROWS: usize = 64;
31 /// Newest rejected dispatches retained by the panel. The workflow journal is
32 /// the durable, unbounded source of truth; this is only a compact UI tail.
33 const MAX_DISPATCH_FAILURES_RETAINED: usize = 12;
34 /// Rejected dispatches shown at once in the live panel/history body.
35 const MAX_VISIBLE_DISPATCH_FAILURES: usize = 3;
36 /// Columns the transcript card header gives its summary
37 /// (`history::constants::TOOL_HEADER_SUMMARY_LIMIT`); the finish line's facts
38 /// are fitted to it so the header never cuts the counts.
39 const FINISH_FACTS_COLS: usize = 72;
40 /// The title keeps at least this much of itself on the finish line.
41 const MIN_FINISH_TITLE_COLS: usize = 16;
42
43 /// Lifecycle of the active (or most recently completed) workflow run.
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 pub enum WorkflowPanelLifecycle {
46 Pending,
47 Running,
48 Succeeded,
49 /// The workflow returned usable output but one or more task slots failed.
50 Degraded,
51 Failed,
52 Cancelled,
53 }
54
55 impl WorkflowPanelLifecycle {
56 #[must_use]
57 pub fn is_running(self) -> bool {
58 matches!(self, Self::Running | Self::Pending)
59 }
60
61 #[must_use]
62 pub fn is_terminal(self) -> bool {
63 matches!(
64 self,
65 Self::Succeeded | Self::Degraded | Self::Failed | Self::Cancelled
66 )
67 }
68
69 #[cfg(test)]
70 #[must_use]
71 pub fn label(self) -> &'static str {
72 match self {
73 Self::Pending => "pending",
74 Self::Running => "running",
75 Self::Succeeded => "success",
76 Self::Degraded => "degraded",
77 Self::Failed => "failed",
78 Self::Cancelled => "cancelled",
79 }
80 }
81
82 #[cfg(test)]
83 fn display_label(self, locale: Locale) -> std::borrow::Cow<'static, str> {
84 match self {
85 Self::Degraded => tr(locale, MessageId::WorkflowStatusDegraded),
86 other => std::borrow::Cow::Borrowed(other.label()),
87 }
88 }
89
90 #[cfg(test)]
91 fn color(self) -> ratatui::style::Color {
92 match self {
93 Self::Pending => palette::TEXT_MUTED,
94 // A healthy run is accent, not attention: warning/error colours
95 // are reserved for states that need the user (#6503).
96 Self::Running => palette::WHALE_ACTION,
97 Self::Succeeded => palette::STATUS_SUCCESS,
98 Self::Degraded => palette::STATUS_WARNING,
99 Self::Failed => palette::STATUS_ERROR,
100 Self::Cancelled => palette::TEXT_MUTED,
101 }
102 }
103 }
104
105 /// Per-task / per-worker row status.
106 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
107 pub enum WorkflowRowStatus {
108 Unknown,
109 Pending,
110 Running,
111 Waiting,
112 Succeeded,
113 Failed,
114 Cancelled,
115 SchemaFailed,
116 }
117
118 impl WorkflowRowStatus {
119 #[must_use]
120 pub fn label(self) -> &'static str {
121 match self {
122 Self::Unknown => "unknown",
123 Self::Pending => "pending",
124 Self::Running => "running",
125 Self::Waiting => "waiting",
126 Self::Succeeded => "done",
127 Self::Failed => "failed",
128 Self::Cancelled => "cancelled",
129 Self::SchemaFailed => "schema",
130 }
131 }
132
133 /// Localized display variant of [`Self::label`]. `label()` stays
134 /// English because it doubles as the machine-readable `status` token in
135 /// [`WorkflowPanel::to_run_json`]; this method is for rendered rows only.
136 #[must_use]
137 pub fn display_label(self, locale: Locale) -> std::borrow::Cow<'static, str> {
138 match self {
139 Self::Unknown => tr(locale, MessageId::WorkflowReceiptUnknown),
140 Self::Waiting => tr(locale, MessageId::WorkflowStatusWaiting),
141 other => std::borrow::Cow::Borrowed(other.label()),
142 }
143 }
144
145 #[must_use]
146 pub fn is_running(self) -> bool {
147 matches!(self, Self::Pending | Self::Running | Self::Waiting)
148 }
149
150 #[must_use]
151 pub fn is_failure(self) -> bool {
152 matches!(self, Self::Failed | Self::SchemaFailed)
153 }
154
155 #[must_use]
156 pub fn is_cancel(self) -> bool {
157 matches!(self, Self::Cancelled)
158 }
159
160 fn color(self) -> ratatui::style::Color {
161 match self {
162 Self::Unknown | Self::Pending => palette::TEXT_MUTED,
163 // Running is the normal state of a live row, so it reads neutral
164 // (#6503). Waiting covers `needs_user` / `blocked`, which do want
165 // attention; failure red stays reserved for actual failure.
166 Self::Running => palette::TEXT_TOOL_OUTPUT,
167 Self::Waiting => palette::STATUS_WARNING,
168 Self::Succeeded => palette::STATUS_SUCCESS,
169 Self::Failed | Self::SchemaFailed => palette::STATUS_ERROR,
170 Self::Cancelled => palette::TEXT_MUTED,
171 }
172 }
173
174 fn from_ir_status(status: &str) -> Self {
175 match status {
176 "unknown" => Self::Unknown,
177 "succeeded" | "completed" | "success" | "done" => Self::Succeeded,
178 "failed" | "error" => Self::Failed,
179 "cancelled" | "canceled" => Self::Cancelled,
180 "budget_exceeded" => Self::Failed,
181 "running" => Self::Running,
182 "waiting" | "blocked" | "needs_user" => Self::Waiting,
183 "pending" => Self::Pending,
184 other if other.contains("schema") => Self::SchemaFailed,
185 _ => Self::Failed,
186 }
187 }
188 }
189
190 /// Closed route-source vocabulary minted by the spawn resolver. Persisted
191 /// journals are untrusted input: an unrecognized value stays unknown rather
192 /// than becoming UI copy (#4039).
193 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
194 pub enum WorkflowRouteSource {
195 TaskModel,
196 TaskModelStrength,
197 AgentProfileModel,
198 AgentProfileLoadout,
199 RoleDefault,
200 RunModel,
201 }
202
203 impl WorkflowRouteSource {
204 fn parse(value: &str) -> Option<Self> {
205 match value.trim() {
206 "task.model" => Some(Self::TaskModel),
207 "task.model_strength" => Some(Self::TaskModelStrength),
208 "agent_profile.model" => Some(Self::AgentProfileModel),
209 "agent_profile.loadout" => Some(Self::AgentProfileLoadout),
210 "role.default" => Some(Self::RoleDefault),
211 "run.model" => Some(Self::RunModel),
212 _ => None,
213 }
214 }
215
216 const fn as_str(self) -> &'static str {
217 match self {
218 Self::TaskModel => "task.model",
219 Self::TaskModelStrength => "task.model_strength",
220 Self::AgentProfileModel => "agent_profile.model",
221 Self::AgentProfileLoadout => "agent_profile.loadout",
222 Self::RoleDefault => "role.default",
223 Self::RunModel => "run.model",
224 }
225 }
226 }
227
228 /// Closed token provenance carried by a terminal usage receipt.
229 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
230 pub enum WorkflowTokenSource {
231 ProviderReported,
232 Estimated,
233 }
234
235 impl WorkflowTokenSource {
236 fn parse(value: &str) -> Option<Self> {
237 match value.trim() {
238 "provider_reported" => Some(Self::ProviderReported),
239 "estimated" => Some(Self::Estimated),
240 _ => None,
241 }
242 }
243
244 const fn as_str(self) -> &'static str {
245 match self {
246 Self::ProviderReported => "provider_reported",
247 Self::Estimated => "estimated",
248 }
249 }
250 }
251
252 /// Immutable route captured by the task-started event (#4039, #5305).
253 #[derive(Debug, Clone, Default, PartialEq, Eq)]
254 pub struct WorkflowRowRoute {
255 pub child_route: Option<codewhale_engine::tools::subagent::ChildRouteReceipt>,
256 pub role: Option<String>,
257 pub provider: Option<String>,
258 pub model: Option<String>,
259 pub requested_reasoning: Option<String>,
260 pub effective_reasoning: Option<String>,
261 pub route_source: Option<WorkflowRouteSource>,
262 }
263
264 impl WorkflowRowRoute {
265 fn from_json(value: &Value) -> Self {
266 let child_route: Option<codewhale_engine::tools::subagent::ChildRouteReceipt> = value
267 .get("child_route")
268 .cloned()
269 .and_then(|value| serde_json::from_value(value).ok());
270 let receipt = child_route.as_ref();
271 Self {
272 role: receipt
273 .map(|receipt| receipt.canonical_role.clone())
274 .or_else(|| opt_str(value, "resolved_role"))
275 .or_else(|| opt_str(value, "role")),
276 provider: receipt
277 .map(|receipt| receipt.provider_id.clone())
278 .or_else(|| opt_str(value, "resolved_provider"))
279 .or_else(|| opt_str(value, "provider")),
280 model: receipt
281 .map(|receipt| receipt.model_id.clone())
282 .or_else(|| opt_str(value, "resolved_model")),
283 requested_reasoning: receipt
284 .map(|receipt| receipt.requested_reasoning.clone())
285 .or_else(|| opt_str(value, "requested_reasoning"))
286 .or_else(|| opt_str(value, "thinking")),
287 effective_reasoning: receipt
288 .and_then(|receipt| receipt.effective_reasoning.clone())
289 .or_else(|| opt_str(value, "effective_reasoning")),
290 route_source: receipt
291 .and_then(|receipt| WorkflowRouteSource::parse(&receipt.route_source))
292 .or_else(|| {
293 opt_str(value, "route_source")
294 .as_deref()
295 .and_then(WorkflowRouteSource::parse)
296 }),
297 child_route,
298 }
299 }
300
301 fn field(value: Option<&String>, locale: Locale) -> String {
302 value
303 .map(String::as_str)
304 .map(crate::tui::app::bound_agent_activity_text)
305 .map(|value| {
306 value
307 .chars()
308 .map(|ch| if ch.is_control() { ' ' } else { ch })
309 .collect::<String>()
310 .split_whitespace()
311 .collect::<Vec<_>>()
312 .join(" ")
313 })
314 .filter(|value| !value.is_empty())
315 .unwrap_or_else(|| tr(locale, MessageId::WorkflowReceiptUnknown).into_owned())
316 }
317 }
318
319 /// Optional terminal usage receipt from `task_completed` (#4039).
320 #[derive(Debug, Clone, Default, PartialEq, Eq)]
321 pub struct WorkflowRowUsage {
322 pub input_tokens: Option<u64>,
323 pub output_tokens: Option<u64>,
324 pub total_tokens: Option<u64>,
325 pub tool_calls: Option<u32>,
326 pub duration_ms: Option<u64>,
327 pub token_source: Option<WorkflowTokenSource>,
328 }
329
330 impl WorkflowRowUsage {
331 fn token_total(&self) -> Option<u64> {
332 self.total_tokens
333 .or_else(|| match (self.input_tokens, self.output_tokens) {
334 (Some(input), Some(output)) => Some(input.saturating_add(output)),
335 _ => None,
336 })
337 }
338
339 fn token_source_label(&self, locale: Locale) -> String {
340 match self.token_source {
341 Some(WorkflowTokenSource::ProviderReported) => {
342 tr(locale, MessageId::WorkflowReceiptProviderReported).into_owned()
343 }
344 Some(WorkflowTokenSource::Estimated) => {
345 tr(locale, MessageId::WorkflowReceiptEstimated).into_owned()
346 }
347 None => tr(locale, MessageId::WorkflowReceiptUnknown).into_owned(),
348 }
349 }
350 }
351
352 /// One worker/task row under a phase.
353 #[derive(Debug, Clone, PartialEq, Eq)]
354 pub struct WorkflowPanelRow {
355 pub task_id: String,
356 pub label: String,
357 pub profile: Option<String>,
358 pub model: Option<String>,
359 pub strength: Option<String>,
360 pub worktree: bool,
361 pub workspace: Option<PathBuf>,
362 pub status: WorkflowRowStatus,
363 pub started_at_ms: u64,
364 pub completed_at_ms: Option<u64>,
365 pub error: Option<String>,
366 pub schema_error: Option<String>,
367 pub route: WorkflowRowRoute,
368 pub usage: Option<WorkflowRowUsage>,
369 }
370
371 /// One lane gate status line surfaced by the Workflow runtime (#4179).
372 #[derive(Debug, Clone, PartialEq, Eq)]
373 pub struct WorkflowPanelGateLine {
374 pub gate_id: String,
375 pub role: Option<String>,
376 pub gate: Option<String>,
377 pub state: String,
378 pub blocked_role: Option<String>,
379 pub blocked_reason: Option<String>,
380 }
381
382 /// One ordered phase group.
383 #[derive(Debug, Clone, PartialEq, Eq)]
384 pub struct WorkflowPanelPhase {
385 pub title: String,
386 pub rows: Vec<WorkflowPanelRow>,
387 pub omitted_child_count: u64,
388 }
389
390 /// One workflow task dispatch rejected before a child agent existed.
391 ///
392 /// This deliberately does not reuse [`WorkflowPanelRow`]: counting a rejected
393 /// launch as a child would make the panel's child/receipt totals dishonest.
394 #[derive(Debug, Clone, PartialEq, Eq)]
395 pub struct WorkflowPanelDispatchFailure {
396 pub label: Option<String>,
397 pub phase: Option<String>,
398 pub message: String,
399 pub at_ms: u64,
400 }
401
402 impl WorkflowPanelDispatchFailure {
403 fn bounded(label: Option<String>, phase: Option<String>, message: String, at_ms: u64) -> Self {
404 let bounded = |value: String| {
405 crate::tui::app::bound_agent_activity_text(&value)
406 .chars()
407 .map(|ch| if ch.is_control() { ' ' } else { ch })
408 .collect::<String>()
409 .split_whitespace()
410 .collect::<Vec<_>>()
411 .join(" ")
412 };
413 let label = label.map(bounded).filter(|value| !value.is_empty());
414 let phase = phase.map(bounded).filter(|value| !value.is_empty());
415 let message = bounded(message);
416 Self {
417 label,
418 phase,
419 message,
420 at_ms,
421 }
422 }
423 }
424
425 impl WorkflowPanelPhase {
426 fn new(title: impl Into<String>) -> Self {
427 Self {
428 title: title.into(),
429 rows: Vec::new(),
430 omitted_child_count: 0,
431 }
432 }
433
434 fn counts(&self) -> (usize, usize, usize, usize) {
435 let mut done = 0usize;
436 let mut running = 0usize;
437 let mut failed = 0usize;
438 let mut cancelled = 0usize;
439 for row in &self.rows {
440 match row.status {
441 WorkflowRowStatus::Unknown => {}
442 WorkflowRowStatus::Succeeded => done += 1,
443 WorkflowRowStatus::Running
444 | WorkflowRowStatus::Pending
445 | WorkflowRowStatus::Waiting => running += 1,
446 WorkflowRowStatus::Failed | WorkflowRowStatus::SchemaFailed => failed += 1,
447 WorkflowRowStatus::Cancelled => cancelled += 1,
448 }
449 }
450 (done, running, failed, cancelled)
451 }
452
453 /// Labelled non-zero counts, e.g. `4 running · 1 done` (#6503). Replaces
454 /// the unlabelled `[0✓ 5… 0! 0⊘]` glyph counters.
455 fn counts_text(&self, locale: Locale, separator: &str) -> String {
456 let (done, running, failed, cancelled) = self.counts();
457 let mut counts = [
458 (running, MessageId::WorkflowCountRunning),
459 (done, MessageId::WorkflowCountDone),
460 (failed, MessageId::WorkflowCountFailed),
461 (cancelled, MessageId::WorkflowCountCancelled),
462 ]
463 .into_iter()
464 .filter(|(count, _)| *count > 0)
465 .map(|(count, id)| count_text(locale, id, count))
466 .collect::<Vec<_>>();
467 let unknown = self
468 .rows
469 .iter()
470 .filter(|row| row.status == WorkflowRowStatus::Unknown)
471 .count() as u64;
472 let unknown = unknown.saturating_add(self.omitted_child_count);
473 if unknown > 0 {
474 counts.push(format!(
475 "{unknown} {}",
476 tr(locale, MessageId::WorkflowReceiptUnknown)
477 ));
478 }
479 if counts.is_empty() {
480 tr(locale, MessageId::WorkflowNoTasksYet).into_owned()
481 } else {
482 counts.join(separator)
483 }
484 }
485 }
486
487 /// Events the panel understands. Mirrors the tool-side `WorkflowUiEvent`
488 /// shape so #4122 can forward JSON without re-encoding.
489 #[derive(Debug, Clone, PartialEq, Eq)]
490 pub enum WorkflowPanelEvent {
491 RunStarted {
492 run_id: String,
493 workflow_id: Option<String>,
494 workflow_goal: Option<String>,
495 source_path: Option<PathBuf>,
496 at_ms: u64,
497 },
498 RunCompleted {
499 status: WorkflowPanelLifecycle,
500 error: Option<String>,
501 at_ms: u64,
502 },
503 RunCancelled {
504 reason: String,
505 at_ms: u64,
506 },
507 PhaseStarted {
508 title: String,
509 at_ms: u64,
510 },
511 TaskStarted {
512 task_id: String,
513 label: Option<String>,
514 profile: Option<String>,
515 model: Option<String>,
516 strength: Option<String>,
517 resolved_model: Option<String>,
518 worktree: bool,
519 workspace: Option<PathBuf>,
520 /// Launch receipt carried by this event (#4039).
521 route: Box<WorkflowRowRoute>,
522 at_ms: u64,
523 },
524 TaskCompleted {
525 task_id: String,
526 status: WorkflowRowStatus,
527 /// Terminal usage receipt carried by this event, if any (#4039).
528 usage: Option<WorkflowRowUsage>,
529 /// Why a failed or cancelled task ended (`reason` on the wire). The
530 /// run's own error is often an aggregate ("all 2 task(s) failed"); the
531 /// task's reason is the cause a person can act on.
532 reason: Option<String>,
533 at_ms: u64,
534 },
535 GateUpdated {
536 gate_id: String,
537 role: Option<String>,
538 gate: Option<String>,
539 state: String,
540 blocked_role: Option<String>,
541 blocked_reason: Option<String>,
542 at_ms: u64,
543 },
544 TaskSchemaValidationFailed {
545 task_id: String,
546 message: String,
547 at_ms: u64,
548 },
549 TaskDispatchFailed {
550 label: Option<String>,
551 phase: Option<String>,
552 message: String,
553 at_ms: u64,
554 },
555 }
556
557 impl WorkflowPanelEvent {
558 /// Parse one flattened tool UI event (`{"type":"…", …}`).
559 pub fn from_json_value(value: &Value) -> Option<Self> {
560 let event_type = value.get("type")?.as_str()?;
561 let at_ms = value
562 .get("at_ms")
563 .and_then(Value::as_u64)
564 .unwrap_or_else(now_ms);
565 match event_type {
566 "run_started" => Some(Self::RunStarted {
567 run_id: value
568 .get("run_id")
569 .and_then(Value::as_str)
570 .unwrap_or("workflow")
571 .to_string(),
572 workflow_id: opt_str(value, "workflow_id"),
573 workflow_goal: opt_str(value, "workflow_goal"),
574 source_path: opt_str(value, "source_path").map(PathBuf::from),
575 at_ms,
576 }),
577 "run_completed" => {
578 // A terminal receipt without a readable status is not
579 // evidence of success; it fails closed like an unknown one.
580 let status = value
581 .get("status")
582 .and_then(Value::as_str)
583 .map(lifecycle_from_status)
584 .unwrap_or(WorkflowPanelLifecycle::Failed);
585 Some(Self::RunCompleted {
586 status,
587 error: opt_str(value, "error"),
588 at_ms,
589 })
590 }
591 "run_cancelled" => Some(Self::RunCancelled {
592 reason: opt_str(value, "reason").unwrap_or_else(|| "cancelled".to_string()),
593 at_ms,
594 }),
595 "phase_started" => Some(Self::PhaseStarted {
596 title: opt_str(value, "title").unwrap_or_else(|| "Phase".to_string()),
597 at_ms,
598 }),
599 "task_started" => Some(Self::TaskStarted {
600 task_id: opt_str(value, "task_id")?,
601 // Prefer typed workflow metadata over generic label so rows
602 // never fall back to prompt parsing (#4119).
603 label: opt_str(value, "workflow_task_label").or_else(|| opt_str(value, "label")),
604 profile: opt_str(value, "profile"),
605 model: opt_str(value, "model").or_else(|| opt_str(value, "resolved_model")),
606 strength: opt_str(value, "strength"),
607 resolved_model: opt_str(value, "resolved_model"),
608 worktree: value
609 .get("worktree")
610 .and_then(Value::as_bool)
611 .unwrap_or(false),
612 workspace: opt_str(value, "workspace").map(PathBuf::from),
613 route: Box::new(WorkflowRowRoute::from_json(value)),
614 at_ms,
615 }),
616 "task_completed" => {
617 // Like `run_completed`: a missing status, or a completion
618 // receipt that still says running/pending, is contradictory
619 // and fails closed rather than leaving a live-looking row.
620 let status = value
621 .get("status")
622 .and_then(Value::as_str)
623 .map(WorkflowRowStatus::from_ir_status)
624 .filter(|status| {
625 !matches!(
626 status,
627 WorkflowRowStatus::Running
628 | WorkflowRowStatus::Pending
629 | WorkflowRowStatus::Unknown
630 )
631 })
632 .unwrap_or(WorkflowRowStatus::Failed);
633 Some(Self::TaskCompleted {
634 task_id: opt_str(value, "task_id")?,
635 status,
636 usage: value.get("usage").and_then(usage_from_json),
637 reason: opt_str(value, "reason").or_else(|| opt_str(value, "error")),
638 at_ms,
639 })
640 }
641 "gate_updated" => Some(Self::GateUpdated {
642 gate_id: opt_str(value, "gate_id")?,
643 role: opt_str(value, "role"),
644 gate: opt_str(value, "gate"),
645 state: opt_str(value, "state").unwrap_or_else(|| "pending".to_string()),
646 blocked_role: opt_str(value, "blocked_role"),
647 blocked_reason: opt_str(value, "blocked_reason"),
648 at_ms,
649 }),
650 "task_schema_validation_failed" => Some(Self::TaskSchemaValidationFailed {
651 task_id: opt_str(value, "task_id")?,
652 message: opt_str(value, "message").unwrap_or_else(|| "schema failed".to_string()),
653 at_ms,
654 }),
655 "task_dispatch_failed" => Some(Self::TaskDispatchFailed {
656 label: opt_str(value, "label"),
657 phase: opt_str(value, "phase"),
658 message: opt_str(value, "message").unwrap_or_default(),
659 at_ms,
660 }),
661 // Logs are intentionally not surfaced in the panel body — they
662 // would re-flood the surface the panel exists to protect.
663 "log" | "budget_updated" => None,
664 _ => None,
665 }
666 }
667 }
668
669 /// Collapsible workflow activity panel.
670 #[derive(Debug, Clone)]
671 pub struct WorkflowPanel {
672 pub run_id: String,
673 pub label: String,
674 pub lifecycle: WorkflowPanelLifecycle,
675 pub phases: Vec<WorkflowPanelPhase>,
676 pub selected_phase: usize,
677 pub gates: Vec<WorkflowPanelGateLine>,
678 /// Newest rejected launches. These are run failures, not child rows.
679 pub dispatch_failures: Vec<WorkflowPanelDispatchFailure>,
680 /// Monotonic count, including failures older than the retained UI tail.
681 pub dispatch_failure_count: usize,
682 pub started_at_ms: u64,
683 pub completed_at_ms: Option<u64>,
684 pub error: Option<String>,
685 /// Optional final result / verification summary for the history card.
686 pub result_summary: Option<String>,
687 /// Source script path or other durable artifact pointer.
688 pub source_path: Option<PathBuf>,
689 /// Spillover / full-output path when the tool result was large.
690 pub spillover_path: Option<PathBuf>,
691 /// UI locale for rendered copy. Defaults to English; hosts with app
692 /// access set it after construction (#4057 wave 2).
693 pub locale: Locale,
694 /// Whether the transcript already carries this run's finish line. The live
695 /// stream and the tool-complete hydration can both deliver the terminal
696 /// event; the line is written once.
697 pub finish_announced: bool,
698 /// Direct-agent cards reuse the Workflow history layout but do not carry a
699 /// Workflow launch receipt. Keep that distinction explicit so the shared
700 /// renderer never invents unknown Workflow provenance for them (#4039).
701 show_workflow_receipts: bool,
702 }
703
704 /// Extra fields the history card can show that are not part of the live panel
705 /// progress surface (artifact links, final result text).
706 #[derive(Debug, Clone, Default)]
707 pub struct WorkflowHistoryExtras {
708 pub result_summary: Option<String>,
709 pub source_path: Option<PathBuf>,
710 pub spillover_path: Option<PathBuf>,
711 pub verification_summary: Option<String>,
712 }
713
714 impl WorkflowPanel {
715 #[must_use]
716 pub fn new(run_id: impl Into<String>, label: impl Into<String>, at_ms: u64) -> Self {
717 Self {
718 run_id: run_id.into(),
719 label: label.into(),
720 lifecycle: WorkflowPanelLifecycle::Running,
721 phases: Vec::new(),
722 selected_phase: 0,
723 gates: Vec::new(),
724 dispatch_failures: Vec::new(),
725 dispatch_failure_count: 0,
726 started_at_ms: at_ms,
727 completed_at_ms: None,
728 error: None,
729 result_summary: None,
730 source_path: None,
731 spillover_path: None,
732 locale: Locale::En,
733 finish_announced: false,
734 show_workflow_receipts: true,
735 }
736 }
737
738 /// Hydrate panel state from a workflow tool JSON payload (run record or a
739 /// snapshot produced by [`Self::to_run_json`]). Prefers the typed `events`
740 /// array when present; falls back to summary + phase fields.
741 #[must_use]
742 pub fn from_run_json(value: &Value) -> Option<Self> {
743 if value.get("action").and_then(Value::as_str) == Some("status") {
744 return None;
745 }
746 let run_id = value
747 .get("run_id")
748 .and_then(Value::as_str)
749 .filter(|s| !s.is_empty())?
750 .to_string();
751 let label = value
752 .get("workflow_goal")
753 .and_then(Value::as_str)
754 .or_else(|| value.get("workflow_id").and_then(Value::as_str))
755 .filter(|s| !s.trim().is_empty())
756 .unwrap_or(&run_id)
757 .to_string();
758 let at_ms = value
759 .get("started_at_ms")
760 .and_then(Value::as_u64)
761 .unwrap_or(0);
762 let mut panel = Self::new(run_id.clone(), label.clone(), at_ms);
763
764 if let Some(events) = value.get("events").and_then(Value::as_array) {
765 for event in events {
766 let mut event = event.clone();
767 if let Some(obj) = event.as_object_mut() {
768 obj.insert("run_id".to_string(), Value::String(run_id.clone()));
769 }
770 panel.apply_json_event(&event);
771 }
772 } else if let Some(phases) = value.get("phases").and_then(Value::as_array) {
773 for phase_val in phases {
774 let title = phase_val
775 .get("title")
776 .and_then(Value::as_str)
777 .unwrap_or("Work");
778 panel.phases.push(WorkflowPanelPhase::new(title));
779 let phase_idx = panel.phases.len() - 1;
780 panel.phases[phase_idx].omitted_child_count = phase_val
781 .get("omitted_child_count")
782 .and_then(Value::as_u64)
783 .unwrap_or(0);
784 if let Some(rows) = phase_val.get("rows").and_then(Value::as_array) {
785 for row in rows {
786 let task_id = row
787 .get("task_id")
788 .and_then(Value::as_str)
789 .unwrap_or("task")
790 .to_string();
791 let status = row
792 .get("status")
793 .and_then(Value::as_str)
794 .map(WorkflowRowStatus::from_ir_status)
795 .unwrap_or(WorkflowRowStatus::Pending);
796 panel.phases[phase_idx].rows.push(WorkflowPanelRow {
797 task_id: task_id.clone(),
798 label: row
799 .get("label")
800 .and_then(Value::as_str)
801 .unwrap_or(&task_id)
802 .to_string(),
803 profile: opt_str(row, "profile"),
804 model: opt_str(row, "model"),
805 strength: opt_str(row, "strength"),
806 worktree: row
807 .get("worktree")
808 .and_then(Value::as_bool)
809 .unwrap_or(false),
810 workspace: opt_str(row, "workspace").map(PathBuf::from),
811 status,
812 started_at_ms: row
813 .get("started_at_ms")
814 .and_then(Value::as_u64)
815 .unwrap_or(at_ms),
816 completed_at_ms: row.get("completed_at_ms").and_then(Value::as_u64),
817 error: opt_str(row, "error"),
818 schema_error: opt_str(row, "schema_error"),
819 route: WorkflowRowRoute::from_json(row),
820 usage: row.get("usage").and_then(usage_from_json),
821 });
822 }
823 }
824 }
825 if !panel.phases.is_empty() {
826 panel.selected_phase = panel.phases.len() - 1;
827 }
828 } else if let Some(child_count) =
829 value
830 .get("child_count")
831 .and_then(Value::as_u64)
832 .or_else(|| {
833 value
834 .get("child_ids")
835 .and_then(Value::as_array)
836 .map(|a| a.len() as u64)
837 })
838 {
839 // Bare summary without events: synthesize a Work phase so child
840 // count still surfaces on the history card.
841 if child_count > 0 {
842 let mut phase = WorkflowPanelPhase::new("Work");
843 let shown = child_count.min(MAX_SUMMARY_CHILD_ROWS as u64) as usize;
844 phase.omitted_child_count = child_count.saturating_sub(shown as u64);
845 for i in 0..shown {
846 let id = value
847 .get("child_ids")
848 .and_then(Value::as_array)
849 .and_then(|ids| ids.get(i))
850 .and_then(Value::as_str)
851 .map(str::to_string)
852 .unwrap_or_else(|| format!("child-{i}"));
853 phase.rows.push(WorkflowPanelRow {
854 task_id: id.clone(),
855 label: id,
856 profile: None,
857 model: None,
858 strength: None,
859 worktree: false,
860 workspace: None,
861 status: WorkflowRowStatus::Unknown,
862 started_at_ms: at_ms,
863 completed_at_ms: value.get("completed_at_ms").and_then(Value::as_u64),
864 error: None,
865 schema_error: None,
866 // A bare child-count summary carries no receipt at all;
867 // the row must show that rather than infer one (#4039).
868 route: WorkflowRowRoute::default(),
869 usage: None,
870 });
871 }
872 panel.phases.push(phase);
873 }
874 }
875
876 panel.merge_dispatch_failures_from_run_json(value);
877
878 if let Some(gates) = value
879 .get("gate_status")
880 .or_else(|| value.get("gates"))
881 .and_then(Value::as_array)
882 {
883 for gate in gates {
884 if let Some(gate_id) = opt_str(gate, "gate_id") {
885 panel.upsert_gate(WorkflowPanelGateLine {
886 gate_id,
887 role: opt_str(gate, "role"),
888 gate: opt_str(gate, "gate"),
889 state: opt_str(gate, "state").unwrap_or_else(|| "pending".to_string()),
890 blocked_role: opt_str(gate, "blocked_role"),
891 blocked_reason: opt_str(gate, "blocked_reason"),
892 });
893 }
894 }
895 }
896
897 if let Some(status) = value.get("status").and_then(Value::as_str) {
898 let life = lifecycle_from_status(status);
899 if life.is_terminal() {
900 panel.lifecycle = life;
901 panel.completed_at_ms = value
902 .get("completed_at_ms")
903 .and_then(Value::as_u64)
904 .or(panel.completed_at_ms);
905 } else if panel.lifecycle.is_running() {
906 panel.lifecycle = life;
907 }
908 }
909 if let Some(error) = opt_str(value, "error") {
910 panel.error = Some(error);
911 }
912 // Apply extras after events so RunStarted reset does not wipe them.
913 if panel.source_path.is_none() {
914 panel.source_path = opt_str(value, "source_path").map(PathBuf::from);
915 }
916 if panel.result_summary.is_none() {
917 panel.result_summary = value
918 .get("result")
919 .and_then(summarize_result_value)
920 .or_else(|| opt_str(value, "result_summary"));
921 }
922 if let Some(verification) = value.get("verification")
923 && let Some(summary) = verification.get("summary").and_then(Value::as_str)
924 {
925 let trimmed = summary.trim();
926 if !trimmed.is_empty() {
927 panel.result_summary = Some(match panel.result_summary.take() {
928 Some(existing) => format!("{existing} · verify: {trimmed}"),
929 None => format!("verify: {trimmed}"),
930 });
931 }
932 }
933 // Prefer the goal label from the payload when events used a fallback.
934 if !label.is_empty() && panel.label == run_id {
935 panel.label = label;
936 }
937 Some(panel)
938 }
939
940 /// Snapshot panel state into a JSON blob suitable for the history cell
941 /// (and re-hydration via [`Self::from_run_json`]).
942 #[must_use]
943 pub fn to_run_json(&self) -> Value {
944 let status = match self.lifecycle {
945 WorkflowPanelLifecycle::Pending => "pending",
946 WorkflowPanelLifecycle::Running => "running",
947 WorkflowPanelLifecycle::Succeeded => "completed",
948 WorkflowPanelLifecycle::Degraded => "degraded",
949 WorkflowPanelLifecycle::Failed => "failed",
950 WorkflowPanelLifecycle::Cancelled => "cancelled",
951 };
952 let (done, total) = self.done_total();
953 let (failed, cancelled) = self.failure_cancel_counts();
954 json!({
955 "run_id": self.run_id,
956 "status": status,
957 "workflow_goal": self.label,
958 "started_at_ms": self.started_at_ms,
959 "completed_at_ms": self.completed_at_ms,
960 "child_count": total,
961 "done_count": done,
962 "phase_count": self.phase_count(),
963 "failure_count": failed,
964 "cancel_count": cancelled,
965 "error": self.error,
966 "result_summary": self.result_summary,
967 "source_path": self.source_path.as_ref().map(|p| p.display().to_string()),
968 "spillover_path": self.spillover_path.as_ref().map(|p| p.display().to_string()),
969 "dispatch_failure_count": self.dispatch_failure_count,
970 "dispatch_failures": self.dispatch_failures.iter().map(|failure| {
971 json!({
972 "label": failure.label.as_deref(),
973 "phase": failure.phase.as_deref(),
974 "message": failure.message.as_str(),
975 "at_ms": failure.at_ms,
976 })
977 }).collect::<Vec<_>>(),
978 "gates": self.gates.iter().map(|gate| {
979 json!({
980 "gate_id": gate.gate_id.as_str(),
981 "role": gate.role.as_deref(),
982 "gate": gate.gate.as_deref(),
983 "state": gate.state.as_str(),
984 "blocked_role": gate.blocked_role.as_deref(),
985 "blocked_reason": gate.blocked_reason.as_deref(),
986 })
987 }).collect::<Vec<_>>(),
988 "phases": self.phases.iter().map(workflow_phase_run_json).collect::<Vec<_>>(),
989 })
990 }
991
992 /// Compact one-line history-card summary: lifecycle, settled/total
993 /// children, phases, failures (only when there are any), elapsed (#4122,
994 /// #6503). The free-text goal lives on the expanded body so the fixed
995 /// header summary budget (≈56 cols) never drops counts.
996 #[cfg(test)]
997 #[must_use]
998 pub fn compact_summary_text(&self, width: usize) -> String {
999 let raw = format!(
1000 "workflow {life} · {counts}",
1001 life = self.lifecycle.display_label(self.locale),
1002 counts = self.summary_counts_text(),
1003 );
1004 truncate_line_to_width(&raw, width.max(1))
1005 }
1006
1007 /// `N/M done · P phases[ · F failed][ · C cancelled] · elapsed`. The
1008 /// settled count is left out until a child exists.
1009 #[cfg(test)]
1010 fn summary_counts_text(&self) -> String {
1011 let (_, total) = self.done_total();
1012 let phases = self.phase_count();
1013 let phase_id = if phases == 1 {
1014 MessageId::WorkflowPhaseCountOne
1015 } else {
1016 MessageId::WorkflowPhaseCountMany
1017 };
1018 let settled = if total > 0 {
1019 format!("{} · ", self.settled_text())
1020 } else {
1021 String::new()
1022 };
1023 format!(
1024 "{settled}{phases}{problems} · {elapsed}",
1025 phases = count_text(self.locale, phase_id, phases),
1026 problems = self.problem_counts_suffix(),
1027 elapsed = self.elapsed_label(),
1028 )
1029 }
1030
1031 /// `N/M done`, localized.
1032 #[cfg(test)]
1033 fn settled_text(&self) -> String {
1034 let (done, total) = self.done_total();
1035 tr(self.locale, MessageId::WorkflowSettledOfTotal)
1036 .replace("{done}", &done.to_string())
1037 .replace("{total}", &total.to_string())
1038 }
1039
1040 /// ` · N failed · N cancelled`, each only when non-zero (#6503): a
1041 /// healthy run does not spend header columns announcing `0 fail`.
1042 #[cfg(test)]
1043 fn problem_counts_suffix(&self) -> String {
1044 let (failed, cancelled) = self.failure_cancel_counts();
1045 let mut out = String::new();
1046 if failed > 0 {
1047 out.push_str(" · ");
1048 out.push_str(&count_text(
1049 self.locale,
1050 MessageId::WorkflowCountFailed,
1051 failed,
1052 ));
1053 }
1054 if cancelled > 0 {
1055 out.push_str(" · ");
1056 out.push_str(&count_text(
1057 self.locale,
1058 MessageId::WorkflowCountCancelled,
1059 cancelled,
1060 ));
1061 }
1062 out
1063 }
1064
1065 /// Elapsed label shared with direct sub-agent cards.
1066 #[must_use]
1067 pub fn elapsed_label(&self) -> String {
1068 // Guard against epoch-zero starts (bare status payloads without
1069 // timestamps) which would otherwise render multi-year elapsed times.
1070 if self.started_at_ms == 0 {
1071 if let Some(completed) = self.completed_at_ms {
1072 return codewhale_command_contract::elapsed::format_elapsed_ms(completed);
1073 }
1074 return "0s".to_string();
1075 }
1076 let end = self.completed_at_ms.unwrap_or_else(now_ms);
1077 codewhale_command_contract::elapsed::format_elapsed_ms(
1078 end.saturating_sub(self.started_at_ms),
1079 )
1080 }
1081
1082 /// Expanded history-card body lines (phase/child summaries, links,
1083 /// result, failures). Empty when the card should stay compact.
1084 #[must_use]
1085 pub fn history_expanded_lines(
1086 &self,
1087 width: u16,
1088 extras: &WorkflowHistoryExtras,
1089 ) -> Vec<Line<'static>> {
1090 let content_width = usize::from(width).max(1);
1091 let mut lines = Vec::new();
1092
1093 if !self.label.trim().is_empty() {
1094 lines.push(Line::from(Span::styled(
1095 truncate_line_to_width(
1096 &format!("goal: {}", short_label(self.label.trim(), 160)),
1097 content_width,
1098 ),
1099 Style::default().fg(palette::TEXT_TOOL_OUTPUT),
1100 )));
1101 }
1102
1103 // Phase summary strip (same chips as the panel body).
1104 if !self.phases.is_empty() {
1105 let mut chips = Vec::new();
1106 for (idx, phase) in self.phases.iter().take(MAX_PHASE_SUMMARY).enumerate() {
1107 let marker =
1108 codewhale_tui_kit::glyphs::selection_marker(idx == self.selected_phase);
1109 chips.push(format!(
1110 "{marker}{title} ({counts})",
1111 title = short_label(&phase.title, 24),
1112 counts = phase.counts_text(self.locale, ", "),
1113 ));
1114 }
1115 if self.phases.len() > MAX_PHASE_SUMMARY {
1116 chips.push(format!("+{}", self.phases.len() - MAX_PHASE_SUMMARY));
1117 }
1118 lines.push(Line::from(Span::styled(
1119 truncate_line_to_width(&format!("phases: {}", chips.join(" ")), content_width),
1120 Style::default().fg(palette::TEXT_MUTED),
1121 )));
1122 }
1123
1124 if !self.gates.is_empty() {
1125 lines.push(Line::from(Span::styled(
1126 truncate_line_to_width(&format!("gates: {}", self.gates_summary()), content_width),
1127 Style::default().fg(palette::TEXT_MUTED),
1128 )));
1129 }
1130
1131 // Child summary across all phases.
1132 let children: Vec<String> = self
1133 .phases
1134 .iter()
1135 .flat_map(|p| p.rows.iter())
1136 .take(8)
1137 .map(|row| {
1138 format!(
1139 "{mark} {label} ({status})",
1140 mark = role_mark(row.profile.as_deref()),
1141 label = short_label(&row.label, 16),
1142 status = row.status.display_label(self.locale)
1143 )
1144 })
1145 .collect();
1146 if !children.is_empty() {
1147 let more = self.done_total().1.saturating_sub(children.len() as u64);
1148 let mut body = children.join(" · ");
1149 if more > 0 {
1150 body = format!("+{more} more · {body}");
1151 }
1152 lines.push(Line::from(Span::styled(
1153 truncate_line_to_width(&format!("children: {body}"), content_width),
1154 Style::default().fg(palette::TEXT_TOOL_OUTPUT),
1155 )));
1156 }
1157
1158 // The history variant uses the same real-data lane vocabulary as the
1159 // live panel. Durations are proportional within the run; gates remain
1160 // a separate named line because runtime events do not yet timestamp
1161 // them precisely enough to place them on a synthetic timeline.
1162 let rows = self.phases.iter().flat_map(|phase| phase.rows.iter());
1163 let max_elapsed = rows
1164 .clone()
1165 .map(|row| row_elapsed_ms(row, now_ms()))
1166 .max()
1167 .unwrap_or(0);
1168 for row in rows.take(8) {
1169 lines.push(Line::from(Span::styled(
1170 truncate_line_to_width(
1171 &format!(
1172 "lane {mark} {label} {track} {elapsed} {status}",
1173 mark = role_mark(row.profile.as_deref()),
1174 label = pad_to_display_width(&short_label(&row.label, 14), 14),
1175 track = lane_track(row, max_elapsed, 16, now_ms()),
1176 elapsed = if row.status == WorkflowRowStatus::Unknown {
1177 tr(self.locale, MessageId::WorkflowReceiptUnknown).into_owned()
1178 } else {
1179 codewhale_command_contract::elapsed::format_elapsed_ms(row_elapsed_ms(
1180 row,
1181 now_ms(),
1182 ))
1183 },
1184 status = row.status.display_label(self.locale),
1185 ),
1186 content_width,
1187 ),
1188 Style::default().fg(row.status.color()),
1189 )));
1190 // #4039: the history card shows the same immutable receipt as the
1191 // live panel, so a finished run stays auditable after the fact.
1192 if self.show_workflow_receipts {
1193 lines.extend(
1194 receipt_line_strings(row, self.locale, content_width, 2)
1195 .into_iter()
1196 .map(|text| {
1197 Line::from(Span::styled(text, Style::default().fg(palette::TEXT_MUTED)))
1198 }),
1199 );
1200 }
1201 }
1202
1203 // Rejected launches are run-level failures rather than child lanes.
1204 // Keep their newest bounded details visible in the completed card.
1205 lines.extend(self.render_dispatch_failure_lines(content_width));
1206
1207 if self.lifecycle.is_terminal() {
1208 let (done, total) = self.done_total();
1209 let (failed, cancelled) = self.failure_cancel_counts();
1210 lines.push(Line::from(Span::styled(
1211 truncate_line_to_width(
1212 &tr(self.locale, MessageId::WorkflowDebrief)
1213 .replace("{done}", &done.to_string())
1214 .replace("{total}", &total.to_string())
1215 .replace("{failed}", &failed.to_string())
1216 .replace("{cancelled}", &cancelled.to_string())
1217 .replace("{elapsed}", &self.elapsed_label()),
1218 content_width,
1219 ),
1220 Style::default().fg(palette::TEXT_MUTED),
1221 )));
1222 }
1223
1224 let result = extras
1225 .result_summary
1226 .as_deref()
1227 .or(self.result_summary.as_deref())
1228 .or(extras.verification_summary.as_deref());
1229 if let Some(result) = result.filter(|s| !s.trim().is_empty()) {
1230 lines.push(Line::from(Span::styled(
1231 truncate_line_to_width(
1232 &format!("result: {}", short_label(result.trim(), 160)),
1233 content_width,
1234 ),
1235 Style::default().fg(palette::TEXT_TOOL_OUTPUT),
1236 )));
1237 }
1238
1239 let source = extras
1240 .source_path
1241 .as_ref()
1242 .or(self.source_path.as_ref())
1243 .map(|p| p.display().to_string());
1244 if let Some(path) = source.filter(|s| !s.is_empty()) {
1245 lines.push(Line::from(Span::styled(
1246 truncate_line_to_width(&format!("source: {path}"), content_width),
1247 Style::default().fg(palette::TEXT_MUTED),
1248 )));
1249 }
1250 let spill = extras
1251 .spillover_path
1252 .as_ref()
1253 .or(self.spillover_path.as_ref())
1254 .map(|p| p.display().to_string());
1255 if let Some(path) = spill.filter(|s| !s.is_empty()) {
1256 lines.push(Line::from(Span::styled(
1257 truncate_line_to_width(&format!("artifact: {path}"), content_width),
1258 Style::default().fg(palette::TEXT_MUTED),
1259 )));
1260 } else if self.lifecycle.is_terminal() {
1261 let details = crate::tui::shell_key_routing::tool_details_chord();
1262 let transcript_hint = tr(self.locale, MessageId::WorkflowTranscriptDetails)
1263 .replace("{details}", details.as_ref());
1264 lines.push(Line::from(Span::styled(
1265 truncate_line_to_width(&transcript_hint, content_width),
1266 Style::default().fg(palette::TEXT_MUTED),
1267 )));
1268 }
1269
1270 if let Some(error) = self.error.as_deref().filter(|s| !s.trim().is_empty()) {
1271 lines.push(Line::from(Span::styled(
1272 truncate_line_to_width(
1273 &format!("error: {}", short_label(error, 160)),
1274 content_width,
1275 ),
1276 Style::default().fg(palette::STATUS_ERROR),
1277 )));
1278 }
1279 for row in self.phases.iter().flat_map(|p| p.rows.iter()) {
1280 if let Some(schema) = row.schema_error.as_deref() {
1281 lines.push(Line::from(Span::styled(
1282 truncate_line_to_width(
1283 &format!(
1284 "schema {}: {}",
1285 short_label(&row.task_id, 12),
1286 short_label(schema, 120)
1287 ),
1288 content_width,
1289 ),
1290 Style::default().fg(palette::STATUS_ERROR),
1291 )));
1292 } else if row.status.is_failure()
1293 && let Some(err) = row.error.as_deref()
1294 {
1295 lines.push(Line::from(Span::styled(
1296 truncate_line_to_width(
1297 &format!(
1298 "fail {}: {}",
1299 short_label(&row.label, 14),
1300 short_label(err, 120)
1301 ),
1302 content_width,
1303 ),
1304 Style::default().fg(palette::STATUS_ERROR),
1305 )));
1306 }
1307 }
1308
1309 lines
1310 }
1311
1312 /// Full history-card lines including a simple self-contained header so
1313 /// unit tests (and direct sub-agent cards) can render without history.rs.
1314 ///
1315 /// Public convergence API for #4122 — also exercised by unit tests and
1316 /// `DelegateCard::as_workflow_history_panel`.
1317 #[must_use]
1318 #[cfg(test)]
1319 pub fn render_history_card(
1320 &self,
1321 width: u16,
1322 expanded: bool,
1323 extras: &WorkflowHistoryExtras,
1324 ) -> Vec<Line<'static>> {
1325 let content_width = usize::from(width).max(1);
1326 let mut lines = Vec::new();
1327 let glyph = if expanded { '▼' } else { '▶' };
1328 let summary = self.compact_summary_text(content_width.saturating_sub(2));
1329 lines.push(Line::from(Span::styled(
1330 truncate_line_to_width(&format!("{glyph} {summary}"), content_width),
1331 Style::default()
1332 .fg(self.lifecycle.color())
1333 .add_modifier(Modifier::BOLD),
1334 )));
1335 if expanded {
1336 lines.extend(self.history_expanded_lines(width, extras));
1337 }
1338 lines
1339 }
1340
1341 /// Single-agent "mini workflow" view for direct sub-agent cards so they
1342 /// share the same lifecycle/elapsed/result concepts as workflow runs.
1343 #[must_use]
1344 #[cfg(test)]
1345 pub fn from_direct_subagent(
1346 agent_id: impl Into<String>,
1347 role: impl Into<String>,
1348 lifecycle: WorkflowPanelLifecycle,
1349 started_at_ms: u64,
1350 completed_at_ms: Option<u64>,
1351 summary: Option<String>,
1352 error: Option<String>,
1353 ) -> Self {
1354 let agent_id = agent_id.into();
1355 let role = role.into();
1356 let mut panel = Self::new(agent_id.clone(), role.clone(), started_at_ms);
1357 panel.lifecycle = lifecycle;
1358 panel.completed_at_ms = completed_at_ms;
1359 panel.show_workflow_receipts = false;
1360 panel.result_summary = summary.clone();
1361 panel.error = error.clone();
1362 let status = match lifecycle {
1363 WorkflowPanelLifecycle::Pending => WorkflowRowStatus::Pending,
1364 WorkflowPanelLifecycle::Running => WorkflowRowStatus::Running,
1365 WorkflowPanelLifecycle::Succeeded => WorkflowRowStatus::Succeeded,
1366 WorkflowPanelLifecycle::Degraded => WorkflowRowStatus::Failed,
1367 WorkflowPanelLifecycle::Failed => WorkflowRowStatus::Failed,
1368 WorkflowPanelLifecycle::Cancelled => WorkflowRowStatus::Cancelled,
1369 };
1370 let mut phase = WorkflowPanelPhase::new("Agent");
1371 phase.rows.push(WorkflowPanelRow {
1372 task_id: agent_id,
1373 label: role,
1374 profile: None,
1375 model: None,
1376 strength: None,
1377 worktree: false,
1378 workspace: None,
1379 status,
1380 started_at_ms,
1381 completed_at_ms,
1382 error,
1383 schema_error: None,
1384 // A direct sub-agent card projects a single agent, not a Workflow
1385 // task, so it carries no Workflow launch/usage receipt (#4039).
1386 route: WorkflowRowRoute::default(),
1387 usage: completed_at_ms.map(|_| WorkflowRowUsage::default()),
1388 });
1389 panel.phases.push(phase);
1390 panel
1391 }
1392
1393 /// Apply a stream of events. `RunStarted` replaces any prior completed run.
1394 pub fn apply_event(&mut self, event: WorkflowPanelEvent) {
1395 match event {
1396 WorkflowPanelEvent::RunStarted {
1397 run_id,
1398 workflow_id,
1399 workflow_goal,
1400 source_path,
1401 at_ms,
1402 } => {
1403 // A repeated or replayed start of this same run never resets
1404 // it: rebuilding would erase settled rows and a terminal
1405 // outcome (U05-01). It names the run (its goal is fixed for
1406 // the run) and fills only what the panel still lacks, such as
1407 // the start time of a placeholder opened by a late event.
1408 if run_id == self.run_id {
1409 if let Some(label) = workflow_goal.or(workflow_id) {
1410 self.label = label;
1411 }
1412 if self.started_at_ms == 0 {
1413 self.started_at_ms = at_ms;
1414 }
1415 if self.source_path.is_none() {
1416 self.source_path = source_path;
1417 }
1418 return;
1419 }
1420 // New run replaces preserved completed state.
1421 let locale = self.locale;
1422 *self = Self::new(
1423 run_id,
1424 workflow_goal
1425 .or(workflow_id)
1426 .unwrap_or_else(|| "workflow".to_string()),
1427 at_ms,
1428 );
1429 self.locale = locale;
1430 self.source_path = source_path;
1431 }
1432 WorkflowPanelEvent::RunCompleted {
1433 status,
1434 error,
1435 at_ms,
1436 } => {
1437 // A cancel is final. Under backpressure the VM's own
1438 // `run_completed` can land after `run_cancelled`; it must not
1439 // repaint a stopped run as finished or drop the cancel reason.
1440 if self.lifecycle == WorkflowPanelLifecycle::Cancelled {
1441 return;
1442 }
1443 // A completion receipt that still says running/pending is
1444 // contradictory, not a success.
1445 self.lifecycle = if status.is_running() {
1446 WorkflowPanelLifecycle::Failed
1447 } else {
1448 status
1449 };
1450 self.error = error;
1451 self.completed_at_ms = Some(at_ms);
1452 }
1453 WorkflowPanelEvent::RunCancelled { reason, at_ms } => {
1454 self.finalize_running_rows(WorkflowRowStatus::Cancelled, at_ms);
1455 self.lifecycle = WorkflowPanelLifecycle::Cancelled;
1456 self.error = Some(reason);
1457 self.completed_at_ms = Some(at_ms);
1458 }
1459 WorkflowPanelEvent::PhaseStarted { title, at_ms: _ } => {
1460 if self.phases.last().is_some_and(|phase| phase.title == title) {
1461 return;
1462 }
1463 self.phases.push(WorkflowPanelPhase::new(title));
1464 self.selected_phase = self.phases.len().saturating_sub(1);
1465 }
1466 WorkflowPanelEvent::TaskStarted {
1467 task_id,
1468 label,
1469 profile,
1470 model,
1471 strength,
1472 resolved_model,
1473 worktree,
1474 workspace,
1475 route,
1476 at_ms,
1477 } => {
1478 // A settled run is final. A child launch that raced the
1479 // cancel (or any late same-run start) is recorded, but it
1480 // never reopens the run or resets a row that already settled.
1481 let settled = self.lifecycle.is_terminal();
1482 if settled && self.find_row_mut(&task_id).is_some() {
1483 return;
1484 }
1485 if self.phases.is_empty() {
1486 self.phases.push(WorkflowPanelPhase::new("Work"));
1487 self.selected_phase = 0;
1488 }
1489 // Tasks join the runtime's newest phase. `selected_phase` is
1490 // the render cursor and never routes an arriving task.
1491 let phase_idx = self.phases.len().saturating_sub(1);
1492 let display_model = resolved_model.or(model);
1493 let mut row = WorkflowPanelRow {
1494 task_id: task_id.clone(),
1495 label: label
1496 .filter(|s| !s.trim().is_empty())
1497 .unwrap_or_else(|| task_id.clone()),
1498 profile,
1499 model: display_model,
1500 strength,
1501 worktree,
1502 workspace,
1503 status: WorkflowRowStatus::Running,
1504 started_at_ms: at_ms,
1505 completed_at_ms: None,
1506 error: None,
1507 schema_error: None,
1508 route: *route,
1509 usage: None,
1510 };
1511 if self.lifecycle == WorkflowPanelLifecycle::Cancelled {
1512 // Same finalization the cancel applied to running rows.
1513 row.status = WorkflowRowStatus::Cancelled;
1514 row.completed_at_ms = Some(at_ms);
1515 row.usage = Some(WorkflowRowUsage::default());
1516 }
1517 if let Some(existing) = self.find_row_mut(&task_id) {
1518 *existing = row;
1519 } else if let Some(phase) = self.phases.get_mut(phase_idx) {
1520 phase.rows.push(row);
1521 }
1522 if !settled {
1523 self.lifecycle = WorkflowPanelLifecycle::Running;
1524 }
1525 }
1526 WorkflowPanelEvent::TaskCompleted {
1527 task_id,
1528 status,
1529 usage,
1530 reason,
1531 at_ms,
1532 } => {
1533 if let Some(row) = self.find_row_mut(&task_id) {
1534 row.status = status;
1535 row.completed_at_ms = Some(at_ms);
1536 if (status.is_failure() || status.is_cancel())
1537 && let Some(reason) = reason.filter(|text| !text.trim().is_empty())
1538 {
1539 row.error = Some(reason);
1540 }
1541 // A completed row always carries a usage receipt, even when
1542 // every counter in it is unknown (#4039).
1543 row.usage = Some(usage.unwrap_or_default());
1544 }
1545 }
1546 WorkflowPanelEvent::GateUpdated {
1547 gate_id,
1548 role,
1549 gate,
1550 state,
1551 blocked_role,
1552 blocked_reason,
1553 at_ms: _,
1554 } => {
1555 self.upsert_gate(WorkflowPanelGateLine {
1556 gate_id,
1557 role,
1558 gate,
1559 state,
1560 blocked_role,
1561 blocked_reason,
1562 });
1563 }
1564 WorkflowPanelEvent::TaskSchemaValidationFailed {
1565 task_id,
1566 message,
1567 at_ms,
1568 } => {
1569 if let Some(row) = self.find_row_mut(&task_id) {
1570 row.status = WorkflowRowStatus::SchemaFailed;
1571 row.schema_error = Some(message);
1572 row.completed_at_ms = Some(at_ms);
1573 } else {
1574 // Schema can fire before/without a started task.
1575 if self.phases.is_empty() {
1576 self.phases.push(WorkflowPanelPhase::new("Work"));
1577 }
1578 let phase_idx = self.phases.len().saturating_sub(1);
1579 if let Some(phase) = self.phases.get_mut(phase_idx) {
1580 phase.rows.push(WorkflowPanelRow {
1581 task_id,
1582 label: "schema".to_string(),
1583 profile: None,
1584 model: None,
1585 strength: None,
1586 worktree: false,
1587 workspace: None,
1588 status: WorkflowRowStatus::SchemaFailed,
1589 started_at_ms: at_ms,
1590 completed_at_ms: Some(at_ms),
1591 error: None,
1592 schema_error: Some(message),
1593 // Schema failure without a task_started: nothing was
1594 // received about the route, so nothing is claimed.
1595 route: WorkflowRowRoute::default(),
1596 usage: Some(WorkflowRowUsage::default()),
1597 });
1598 }
1599 }
1600 }
1601 WorkflowPanelEvent::TaskDispatchFailed {
1602 label,
1603 phase,
1604 message,
1605 at_ms,
1606 } => {
1607 self.record_dispatch_failure(label, phase, message, at_ms);
1608 // A failed launch can be only one slot in a parallel phase;
1609 // keep the run live so surviving siblings can still finish.
1610 if self.lifecycle.is_running() {
1611 self.lifecycle = WorkflowPanelLifecycle::Running;
1612 }
1613 }
1614 }
1615 }
1616
1617 /// Apply one event only when its explicit route identity belongs to this
1618 /// panel. A strictly newer `run_started` is the sole event allowed to
1619 /// select a different run; legacy direct callers without an id remain
1620 /// accepted.
1621 pub fn apply_json_event(&mut self, value: &Value) -> bool {
1622 let event_type = value.get("type").and_then(Value::as_str);
1623 let event_run_id = value
1624 .get("run_id")
1625 .or_else(|| value.get("workflow_run_id"))
1626 .and_then(Value::as_str)
1627 .filter(|run_id| !run_id.trim().is_empty());
1628 if event_type == Some("run_started")
1629 && event_run_id.is_some_and(|run_id| run_id != self.run_id)
1630 && value
1631 .get("at_ms")
1632 .and_then(Value::as_u64)
1633 .is_none_or(|at_ms| at_ms <= self.started_at_ms)
1634 {
1635 return false;
1636 }
1637 if event_type != Some("run_started")
1638 && event_run_id.is_some_and(|run_id| run_id != self.run_id)
1639 {
1640 return false;
1641 }
1642 if let Some(event) = WorkflowPanelEvent::from_json_value(value) {
1643 self.apply_event(event);
1644 return true;
1645 }
1646 false
1647 }
1648
1649 pub fn apply_json_events(&mut self, values: &[Value]) {
1650 for value in values {
1651 self.apply_json_event(value);
1652 }
1653 }
1654
1655 /// Merge the authoritative structured failure ledger carried by a run
1656 /// result after its retained event tail has been applied. The tail can
1657 /// replay events already seen live; the exact top-level count and newest
1658 /// bounded ledger therefore replace, rather than add to, panel state.
1659 pub(crate) fn merge_dispatch_failures_from_run_json(&mut self, value: &Value) {
1660 let fallback_at_ms = value
1661 .get("started_at_ms")
1662 .and_then(Value::as_u64)
1663 .unwrap_or(self.started_at_ms);
1664 let ledger = value
1665 .get("dispatch_failures")
1666 .and_then(Value::as_array)
1667 .map(|failures| {
1668 let start = failures
1669 .len()
1670 .saturating_sub(MAX_DISPATCH_FAILURES_RETAINED);
1671 failures[start..]
1672 .iter()
1673 .map(|failure| {
1674 WorkflowPanelDispatchFailure::bounded(
1675 opt_str(failure, "label"),
1676 opt_str(failure, "phase"),
1677 opt_str(failure, "message").unwrap_or_default(),
1678 failure
1679 .get("at_ms")
1680 .and_then(Value::as_u64)
1681 .unwrap_or(fallback_at_ms),
1682 )
1683 })
1684 .collect::<Vec<_>>()
1685 });
1686 let declared_count = value
1687 .get("dispatch_failure_count")
1688 .and_then(Value::as_u64)
1689 .map(|count| usize::try_from(count).unwrap_or(usize::MAX));
1690
1691 if let Some(ledger) = ledger {
1692 let returned = ledger.len();
1693 self.dispatch_failures = ledger;
1694 self.dispatch_failure_count = declared_count
1695 .map(|count| count.max(returned))
1696 .unwrap_or_else(|| self.dispatch_failure_count.max(returned));
1697 } else if let Some(count) = declared_count {
1698 self.dispatch_failure_count = count;
1699 }
1700 }
1701
1702 /// Tokens the run has used so far from finished agents' receipts.
1703 /// `None` until something is reported — never a made-up zero.
1704 #[must_use]
1705 pub fn tokens_so_far(&self) -> Option<u64> {
1706 let receipts: u64 = self
1707 .phases
1708 .iter()
1709 .flat_map(|phase| phase.rows.iter())
1710 .filter_map(|row| row.usage.as_ref().and_then(WorkflowRowUsage::token_total))
1711 .sum();
1712 (receipts > 0).then_some(receipts)
1713 }
1714
1715 /// The transcript's finish line for a settled run: the state word, the
1716 /// facts (`name · 1/3 done · 2 failed · 2m 14s · ↓1.2M`), and the result
1717 /// or the one reason it fell short. The name is the goal's first sentence
1718 /// and the reason is a first sentence too; the full goal, every agent's
1719 /// error and the run's own error stay on the expanded card. `None` while
1720 /// the run is live.
1721 #[must_use]
1722 pub fn finish_line(&self) -> Option<(String, String, Option<String>)> {
1723 let state = match self.lifecycle {
1724 WorkflowPanelLifecycle::Pending | WorkflowPanelLifecycle::Running => return None,
1725 WorkflowPanelLifecycle::Succeeded => MessageId::WorkflowLineFinished,
1726 WorkflowPanelLifecycle::Degraded => MessageId::WorkflowLineFinishedWithGaps,
1727 WorkflowPanelLifecycle::Failed => MessageId::WorkflowLineFailed,
1728 WorkflowPanelLifecycle::Cancelled => MessageId::WorkflowLineStopped,
1729 };
1730 let (_, _, _, total) = self.row_outcomes();
1731 let mut rest = Vec::new();
1732 if total > 0 || self.dispatch_failure_count > 0 {
1733 rest.push(self.outcome_counts_text());
1734 }
1735 rest.push(self.elapsed_label());
1736 if let Some(tokens) = self.tokens_so_far() {
1737 rest.push(format!(
1738 "↓{}",
1739 crate::tui::footer_ui::format_token_count_compact(tokens)
1740 ));
1741 }
1742 // The title gives way, at a word boundary, so the counts and elapsed
1743 // are never the part the card header cuts off.
1744 let rest = rest.join(" · ");
1745 let title_cols = FINISH_FACTS_COLS
1746 .saturating_sub(rest.width() + 3)
1747 .max(MIN_FINISH_TITLE_COLS);
1748 let facts = [
1749 codewhale_tui_kit::ui_text::semantic_truncate(&self.short_title(), title_cols),
1750 rest,
1751 ];
1752 let detail = match self.lifecycle {
1753 WorkflowPanelLifecycle::Succeeded | WorkflowPanelLifecycle::Degraded => self
1754 .result_summary
1755 .clone()
1756 .map(|text| text.split_whitespace().collect::<Vec<_>>().join(" "))
1757 .or_else(|| self.outcome_reason())
1758 .or_else(|| self.error.as_deref().map(first_sentence)),
1759 _ => self
1760 .outcome_reason()
1761 .or_else(|| self.result_summary.as_deref().map(first_sentence)),
1762 }
1763 .filter(|text| !text.is_empty());
1764 Some((
1765 tr(self.locale, state).into_owned(),
1766 facts.join(" · "),
1767 detail,
1768 ))
1769 }
1770
1771 #[must_use]
1772 pub fn done_total(&self) -> (usize, u64) {
1773 let mut done = 0usize;
1774 let mut total = 0u64;
1775 for phase in &self.phases {
1776 for row in &phase.rows {
1777 total = total.saturating_add(1);
1778 if !row.status.is_running() && row.status != WorkflowRowStatus::Unknown {
1779 done = done.saturating_add(1);
1780 }
1781 }
1782 total = total.saturating_add(phase.omitted_child_count);
1783 }
1784 (done, total)
1785 }
1786
1787 #[must_use]
1788 pub fn phase_count(&self) -> usize {
1789 self.phases.len()
1790 }
1791
1792 #[must_use]
1793 pub fn failure_cancel_counts(&self) -> (usize, usize) {
1794 let mut failed = self.dispatch_failure_count;
1795 let mut cancelled = 0usize;
1796 for phase in &self.phases {
1797 for row in &phase.rows {
1798 if row.status.is_failure() {
1799 failed = failed.saturating_add(1);
1800 } else if row.status.is_cancel() {
1801 cancelled = cancelled.saturating_add(1);
1802 }
1803 }
1804 }
1805 (failed, cancelled)
1806 }
1807
1808 /// Known row outcomes and total children, including omitted summaries.
1809 /// Rejected dispatches are not children and stay outside these counts.
1810 #[must_use]
1811 pub fn row_outcomes(&self) -> (usize, usize, usize, u64) {
1812 self.phases
1813 .iter()
1814 .fold((0usize, 0usize, 0usize, 0u64), |acc, phase| {
1815 let (done, _, failed, cancelled) = phase.counts();
1816 (
1817 acc.0.saturating_add(done),
1818 acc.1.saturating_add(failed),
1819 acc.2.saturating_add(cancelled),
1820 acc.3
1821 .saturating_add(phase.rows.len() as u64)
1822 .saturating_add(phase.omitted_child_count),
1823 )
1824 })
1825 }
1826
1827 /// The run's name on one-line surfaces: the goal's first sentence. The
1828 /// full goal stays on the expanded card, so a paragraph-long goal is not
1829 /// the title of every row that names the run.
1830 #[must_use]
1831 pub fn short_title(&self) -> String {
1832 let title = first_sentence(&self.label);
1833 if title.is_empty() {
1834 "workflow".to_string()
1835 } else {
1836 title
1837 }
1838 }
1839
1840 /// `k/n done · m failed · c cancelled`: what finished, and what did not.
1841 /// Only the done count is always there; a failed or cancelled count shows
1842 /// only when it is not zero. Settled-but-failed agents never count as done.
1843 #[must_use]
1844 pub fn outcome_counts_text(&self) -> String {
1845 let (succeeded, _, _, total) = self.row_outcomes();
1846 let (failed, cancelled) = self.failure_cancel_counts();
1847 let mut parts = Vec::new();
1848 if total > 0 {
1849 parts.push(
1850 tr(self.locale, MessageId::WorkflowSettledOfTotal)
1851 .replace("{done}", &succeeded.to_string())
1852 .replace("{total}", &total.to_string()),
1853 );
1854 } else if failed == 0 {
1855 parts.push(tr(self.locale, MessageId::WorkflowNoTasksYet).into_owned());
1856 }
1857 if failed > 0 {
1858 parts.push(count_text(
1859 self.locale,
1860 MessageId::WorkflowCountFailed,
1861 failed,
1862 ));
1863 }
1864 if cancelled > 0 {
1865 parts.push(count_text(
1866 self.locale,
1867 MessageId::WorkflowCountCancelled,
1868 cancelled,
1869 ));
1870 }
1871 parts.join(" · ")
1872 }
1873
1874 /// The one reason worth showing for a run that settled short of success,
1875 /// as its first sentence. When nothing succeeded, a failed agent's own
1876 /// reason ("Authorization failed: …") beats the run's aggregate ("no task
1877 /// produced a result: all 2 task(s) failed …"): it is the cause a person
1878 /// can act on. `None` for a live or fully successful run.
1879 #[must_use]
1880 pub fn outcome_reason(&self) -> Option<String> {
1881 let row_reason = || {
1882 self.phases
1883 .iter()
1884 .flat_map(|phase| phase.rows.iter())
1885 .filter(|row| row.status.is_failure())
1886 .find_map(|row| row.error.as_deref().or(row.schema_error.as_deref()))
1887 .map(str::to_string)
1888 .or_else(|| {
1889 self.dispatch_failures
1890 .first()
1891 .map(|failure| failure.message.clone())
1892 })
1893 };
1894 let run_error = || self.error.clone();
1895 let reason = match self.lifecycle {
1896 WorkflowPanelLifecycle::Pending
1897 | WorkflowPanelLifecycle::Running
1898 | WorkflowPanelLifecycle::Succeeded => return None,
1899 WorkflowPanelLifecycle::Cancelled => run_error(),
1900 WorkflowPanelLifecycle::Degraded => row_reason().or_else(run_error),
1901 WorkflowPanelLifecycle::Failed => {
1902 let (succeeded, _, _, _) = self.row_outcomes();
1903 if succeeded == 0 {
1904 row_reason().or_else(run_error)
1905 } else {
1906 run_error().or_else(row_reason)
1907 }
1908 }
1909 };
1910 reason
1911 .map(|text| first_sentence(strip_error_tag(&text)))
1912 .filter(|text| !text.is_empty())
1913 }
1914
1915 fn record_dispatch_failure(
1916 &mut self,
1917 label: Option<String>,
1918 phase: Option<String>,
1919 message: String,
1920 at_ms: u64,
1921 ) {
1922 let failure = WorkflowPanelDispatchFailure::bounded(label, phase, message, at_ms);
1923 self.dispatch_failure_count = self.dispatch_failure_count.saturating_add(1);
1924 self.dispatch_failures.push(failure);
1925 if self.dispatch_failures.len() > MAX_DISPATCH_FAILURES_RETAINED {
1926 let overflow = self.dispatch_failures.len() - MAX_DISPATCH_FAILURES_RETAINED;
1927 self.dispatch_failures.drain(..overflow);
1928 }
1929 }
1930
1931 fn render_dispatch_failure_lines(&self, width: usize) -> Vec<Line<'static>> {
1932 let shown = self
1933 .dispatch_failures
1934 .len()
1935 .min(MAX_VISIBLE_DISPATCH_FAILURES);
1936 let start = self.dispatch_failures.len().saturating_sub(shown);
1937 let mut lines = Vec::with_capacity(shown.saturating_add(1));
1938 for failure in &self.dispatch_failures[start..] {
1939 let slot = match (failure.label.as_deref(), failure.phase.as_deref()) {
1940 (Some(label), Some(phase)) if label != phase => {
1941 format!("{} [{}]", short_label(label, 28), short_label(phase, 20))
1942 }
1943 (Some(label), _) => short_label(label, 28),
1944 (None, Some(phase)) => short_label(phase, 28),
1945 (None, None) => {
1946 tr(self.locale, MessageId::WorkflowDispatchFallbackTask).into_owned()
1947 }
1948 };
1949 let message = if failure.message.is_empty() {
1950 tr(self.locale, MessageId::SetupStatusFailed).into_owned()
1951 } else {
1952 short_label(&failure.message, 160)
1953 };
1954 let text = tr(self.locale, MessageId::WorkflowDispatchFailureLine)
1955 .replace("{slot}", &slot)
1956 .replace("{message}", &message);
1957 lines.push(Line::from(Span::styled(
1958 truncate_line_to_width(&text, width.max(1)),
1959 Style::default().fg(palette::STATUS_ERROR),
1960 )));
1961 }
1962 let omitted = self.dispatch_failure_count.saturating_sub(shown);
1963 if omitted > 0 {
1964 let text = tr(self.locale, MessageId::WorkflowDispatchFailuresOmitted)
1965 .replace("{count}", &omitted.to_string());
1966 lines.push(Line::from(Span::styled(
1967 truncate_line_to_width(&text, width.max(1)),
1968 Style::default().fg(palette::TEXT_MUTED),
1969 )));
1970 }
1971 lines
1972 }
1973
1974 fn find_row_mut(&mut self, task_id: &str) -> Option<&mut WorkflowPanelRow> {
1975 for phase in &mut self.phases {
1976 if let Some(row) = phase.rows.iter_mut().find(|r| r.task_id == task_id) {
1977 return Some(row);
1978 }
1979 }
1980 None
1981 }
1982
1983 fn gates_summary(&self) -> String {
1984 self.gates
1985 .iter()
1986 .take(6)
1987 .map(|gate| {
1988 let target = gate
1989 .blocked_role
1990 .as_deref()
1991 .or(gate.role.as_deref())
1992 .unwrap_or("-");
1993 if let Some(reason) = gate.blocked_reason.as_deref() {
1994 format!(
1995 "{}:{}->{} ({})",
1996 short_label(&gate.gate_id, 18),
1997 gate.state,
1998 target,
1999 short_label(reason, 40)
2000 )
2001 } else {
2002 format!(
2003 "{}:{}->{}",
2004 short_label(&gate.gate_id, 18),
2005 gate.state,
2006 target
2007 )
2008 }
2009 })
2010 .collect::<Vec<_>>()
2011 .join(" ")
2012 }
2013
2014 fn upsert_gate(&mut self, gate: WorkflowPanelGateLine) {
2015 if let Some(existing) = self
2016 .gates
2017 .iter_mut()
2018 .find(|existing| existing.gate_id == gate.gate_id)
2019 {
2020 *existing = gate;
2021 } else {
2022 self.gates.push(gate);
2023 }
2024 }
2025
2026 fn finalize_running_rows(&mut self, status: WorkflowRowStatus, at_ms: u64) {
2027 for phase in &mut self.phases {
2028 for row in &mut phase.rows {
2029 if row.status.is_running() {
2030 row.status = status;
2031 row.completed_at_ms = Some(at_ms);
2032 // A terminal Workflow row must keep the receipt shape even
2033 // when cancellation arrived before provider telemetry.
2034 // Unknown counters remain unknown; they never disappear or
2035 // become fabricated zeros (#4039).
2036 row.usage.get_or_insert_with(WorkflowRowUsage::default);
2037 }
2038 }
2039 }
2040 }
2041 }
2042
2043 fn workflow_phase_run_json(phase: &WorkflowPanelPhase) -> Value {
2044 json!({
2045 "title": phase.title,
2046 "rows": phase.rows.iter().map(workflow_row_run_json).collect::<Vec<_>>(),
2047 "omitted_child_count": phase.omitted_child_count,
2048 })
2049 }
2050
2051 fn workflow_row_run_json(row: &WorkflowPanelRow) -> Value {
2052 let usage = row.usage.as_ref().map(|usage| {
2053 json!({
2054 "input_tokens": usage.input_tokens,
2055 "output_tokens": usage.output_tokens,
2056 "total_tokens": usage.total_tokens,
2057 "tool_calls": usage.tool_calls,
2058 "duration_ms": usage.duration_ms,
2059 "token_source": usage.token_source.map(WorkflowTokenSource::as_str),
2060 })
2061 });
2062 json!({
2063 "task_id": row.task_id,
2064 "label": row.label,
2065 "profile": row.profile,
2066 "model": row.model,
2067 "strength": row.strength,
2068 "worktree": row.worktree,
2069 "workspace": row.workspace.as_ref().map(|p| p.display().to_string()),
2070 "status": row.status.label(),
2071 "started_at_ms": row.started_at_ms,
2072 "completed_at_ms": row.completed_at_ms,
2073 "error": row.error,
2074 "schema_error": row.schema_error,
2075 "role": row.route.role,
2076 "provider": row.route.provider,
2077 "resolved_model": row.route.model,
2078 "requested_reasoning": row.route.requested_reasoning,
2079 "effective_reasoning": row.route.effective_reasoning,
2080 "route_source": row.route.route_source.map(WorkflowRouteSource::as_str),
2081 "child_route": row.route.child_route,
2082 "usage": usage,
2083 })
2084 }
2085
2086 fn lifecycle_from_status(status: &str) -> WorkflowPanelLifecycle {
2087 match status {
2088 "running" => WorkflowPanelLifecycle::Running,
2089 "completed" | "succeeded" | "success" => WorkflowPanelLifecycle::Succeeded,
2090 "degraded" => WorkflowPanelLifecycle::Degraded,
2091 "failed" | "error" => WorkflowPanelLifecycle::Failed,
2092 "cancelled" | "canceled" => WorkflowPanelLifecycle::Cancelled,
2093 "pending" => WorkflowPanelLifecycle::Pending,
2094 _ => WorkflowPanelLifecycle::Failed,
2095 }
2096 }
2097
2098 /// Drop a leading error-taxonomy tag (`[auth] `, `[rate_limit] `): the
2099 /// sentence after it already says what kind of failure it was, and a one-row
2100 /// surface has no columns to spare. The full error keeps its tag.
2101 fn strip_error_tag(text: &str) -> &str {
2102 let trimmed = text.trim_start();
2103 trimmed
2104 .strip_prefix('[')
2105 .and_then(|rest| rest.split_once("] "))
2106 .filter(|(tag, _)| {
2107 !tag.is_empty()
2108 && tag.len() <= 24
2109 && tag
2110 .chars()
2111 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
2112 })
2113 .map_or(trimmed, |(_, rest)| rest)
2114 }
2115
2116 /// The first sentence of `text`, whitespace-flattened, without its closing
2117 /// full stop. A sentence ends at `.`, `!` or `?` followed by whitespace, or at
2118 /// `;` — so `v0.10.1.` inside a sentence and `a.rs` never split it. Nothing is
2119 /// cut mid-word: the caller truncates, at a word boundary, only what does not
2120 /// fit.
2121 pub(crate) fn first_sentence(text: &str) -> String {
2122 let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
2123 let mut end = flat.len();
2124 let mut chars = flat.char_indices().peekable();
2125 while let Some((index, ch)) = chars.next() {
2126 let next_is_space = chars.peek().is_some_and(|(_, next)| *next == ' ');
2127 if ch == ';' || (matches!(ch, '.' | '!' | '?') && next_is_space) {
2128 end = if ch == '.' || ch == ';' {
2129 index
2130 } else {
2131 index + ch.len_utf8()
2132 };
2133 break;
2134 }
2135 }
2136 flat[..end].trim_end_matches(['.', ' ']).trim().to_string()
2137 }
2138
2139 /// `{count} running`-style labelled count.
2140 fn count_text(locale: Locale, id: MessageId, count: usize) -> String {
2141 tr(locale, id).replace("{count}", &count.to_string())
2142 }
2143
2144 fn localized_field(locale: Locale, id: MessageId, value: &str) -> String {
2145 tr(locale, id).replace("{value}", value)
2146 }
2147
2148 /// Launch route only: role, provider/model, requested→effective reasoning,
2149 /// route source (#4039).
2150 fn route_receipt_parts(row: &WorkflowPanelRow, locale: Locale) -> Vec<String> {
2151 let unknown = tr(locale, MessageId::WorkflowReceiptUnknown).into_owned();
2152 let role = WorkflowRowRoute::field(row.route.role.as_ref(), locale);
2153 let provider = WorkflowRowRoute::field(row.route.provider.as_ref(), locale);
2154 let model = WorkflowRowRoute::field(row.route.model.as_ref(), locale);
2155 let requested = WorkflowRowRoute::field(row.route.requested_reasoning.as_ref(), locale);
2156 let effective = WorkflowRowRoute::field(row.route.effective_reasoning.as_ref(), locale);
2157 let source = row
2158 .route
2159 .route_source
2160 .map(WorkflowRouteSource::as_str)
2161 .unwrap_or(unknown.as_str());
2162 vec![
2163 localized_field(locale, MessageId::WorkflowReceiptRole, &role),
2164 format!("{provider}/{model}"),
2165 localized_field(
2166 locale,
2167 MessageId::WorkflowReceiptReasoning,
2168 &format!("{requested}→{effective}"),
2169 ),
2170 localized_field(locale, MessageId::WorkflowReceiptVia, source),
2171 ]
2172 }
2173
2174 /// Full receipt: launch route plus, for a settled row, what it cost.
2175 fn receipt_parts(row: &WorkflowPanelRow, locale: Locale) -> Vec<String> {
2176 let unknown = tr(locale, MessageId::WorkflowReceiptUnknown).into_owned();
2177 let mut parts = route_receipt_parts(row, locale);
2178 if let Some(usage) = row.usage.as_ref() {
2179 let tokens = usage.token_total().map_or_else(
2180 || unknown.clone(),
2181 |total| format!("{total} ({})", usage.token_source_label(locale)),
2182 );
2183 let tools = usage
2184 .tool_calls
2185 .map_or_else(|| unknown.clone(), |calls| calls.to_string());
2186 let duration = usage.duration_ms.map_or_else(
2187 || unknown.clone(),
2188 codewhale_command_contract::elapsed::format_elapsed_ms,
2189 );
2190 parts.extend([
2191 localized_field(locale, MessageId::WorkflowReceiptTokens, &tokens),
2192 localized_field(locale, MessageId::WorkflowReceiptTools, &tools),
2193 localized_field(locale, MessageId::WorkflowReceiptDuration, &duration),
2194 ]);
2195 }
2196 parts
2197 }
2198
2199 /// Full English receipt retained for history serialization tests and text
2200 /// exports. Renderers use [`receipt_line_strings`] so narrow terminals wrap
2201 /// fields instead of dropping them.
2202 #[must_use]
2203 #[cfg(test)]
2204 pub fn row_receipt_text(row: &WorkflowPanelRow) -> String {
2205 receipt_parts(row, Locale::En).join(" · ")
2206 }
2207
2208 fn receipt_line_strings(
2209 row: &WorkflowPanelRow,
2210 locale: Locale,
2211 width: usize,
2212 requested_indent: usize,
2213 ) -> Vec<String> {
2214 pack_receipt_lines(receipt_parts(row, locale), width, requested_indent)
2215 }
2216
2217 /// Pack receipt fields into indented lines that fit `width`, wrapping whole
2218 /// fields first and hard-wrapping only a field wider than the line.
2219 fn pack_receipt_lines(parts: Vec<String>, width: usize, requested_indent: usize) -> Vec<String> {
2220 let indent = requested_indent.min(width.saturating_sub(1));
2221 let prefix = " ".repeat(indent);
2222 let available = width.saturating_sub(indent).max(1);
2223 let mut packed = Vec::new();
2224 let mut current = String::new();
2225
2226 for part in parts {
2227 if UnicodeWidthStr::width(part.as_str()) > available {
2228 if !current.is_empty() {
2229 packed.push(std::mem::take(&mut current));
2230 }
2231 packed.extend(hard_wrap_display(&part, available));
2232 continue;
2233 }
2234 let combined_width = if current.is_empty() {
2235 UnicodeWidthStr::width(part.as_str())
2236 } else {
2237 UnicodeWidthStr::width(current.as_str()) + 3 + UnicodeWidthStr::width(part.as_str())
2238 };
2239 if !current.is_empty() && combined_width > available {
2240 packed.push(std::mem::take(&mut current));
2241 }
2242 if current.is_empty() {
2243 current = part;
2244 } else {
2245 current.push_str(" · ");
2246 current.push_str(&part);
2247 }
2248 }
2249 if !current.is_empty() {
2250 packed.push(current);
2251 }
2252 packed
2253 .into_iter()
2254 .map(|line| format!("{prefix}{line}"))
2255 .collect()
2256 }
2257
2258 fn hard_wrap_display(text: &str, width: usize) -> Vec<String> {
2259 let width = width.max(1);
2260 let mut lines = Vec::new();
2261 let mut line = String::new();
2262 let mut used = 0usize;
2263 for ch in text.chars() {
2264 let ch_width = ch.width().unwrap_or(0);
2265 if !line.is_empty() && used + ch_width > width {
2266 lines.push(std::mem::take(&mut line));
2267 used = 0;
2268 }
2269 line.push(ch);
2270 used += ch_width;
2271 }
2272 if !line.is_empty() {
2273 lines.push(line);
2274 }
2275 if lines.is_empty() {
2276 lines.push(String::new());
2277 }
2278 lines
2279 }
2280
2281 /// Read a terminal usage receipt out of a `task_completed` payload (#4039).
2282 ///
2283 /// Absent counters stay `None`. An object that carries no counter at all still
2284 /// produces a receipt so the row can say `unknown` in every column instead of
2285 /// silently omitting the line.
2286 fn usage_from_json(value: &Value) -> Option<WorkflowRowUsage> {
2287 let object = value.as_object()?;
2288 let number = |key: &str| object.get(key).and_then(Value::as_u64);
2289 Some(WorkflowRowUsage {
2290 input_tokens: number("input_tokens"),
2291 output_tokens: number("output_tokens"),
2292 total_tokens: number("total_tokens"),
2293 tool_calls: number("tool_calls").and_then(|calls| u32::try_from(calls).ok()),
2294 duration_ms: number("duration_ms"),
2295 token_source: opt_str(value, "token_source")
2296 .as_deref()
2297 .and_then(WorkflowTokenSource::parse),
2298 })
2299 }
2300
2301 fn opt_str(value: &Value, key: &str) -> Option<String> {
2302 value
2303 .get(key)
2304 .and_then(Value::as_str)
2305 .map(str::trim)
2306 .filter(|s| !s.is_empty())
2307 .map(str::to_string)
2308 }
2309
2310 fn short_label(text: &str, max: usize) -> String {
2311 let trimmed = text.trim();
2312 if trimmed.width() <= max {
2313 return trimmed.to_string();
2314 }
2315 truncate_line_to_width(trimmed, max)
2316 }
2317
2318 /// Terminal-safe role grammar from the underwater design contract. Labels
2319 /// remain authoritative; the marks make siblings scan as the same work kind.
2320 fn role_mark(profile: Option<&str>) -> &'static str {
2321 let role = profile.unwrap_or_default().trim().to_ascii_lowercase();
2322 if role.contains("operator") {
2323 "@"
2324 } else if role.contains("manager") || role.contains("lead") || role.contains("coordinator") {
2325 "/\\"
2326 } else if role.contains("scout") || role.contains("research") || role.contains("explor") {
2327 "<>"
2328 } else if role.contains("build") || role.contains("implement") || role.contains("engineer") {
2329 "[]"
2330 } else if role.contains("verif") || role.contains("test") || role.contains("qa") {
2331 "()"
2332 } else if role.contains("review") || role.contains("critic") {
2333 "**"
2334 } else {
2335 "--"
2336 }
2337 }
2338
2339 fn row_elapsed_ms(row: &WorkflowPanelRow, now_ms: u64) -> u64 {
2340 if row.status == WorkflowRowStatus::Unknown {
2341 return 0;
2342 }
2343 row.completed_at_ms
2344 .unwrap_or(now_ms)
2345 .saturating_sub(row.started_at_ms)
2346 }
2347
2348 fn lane_track(row: &WorkflowPanelRow, max_elapsed_ms: u64, width: usize, now_ms: u64) -> String {
2349 let width = width.max(4);
2350 let elapsed = row_elapsed_ms(row, now_ms);
2351 let filled = if max_elapsed_ms == 0 {
2352 1
2353 } else {
2354 ((elapsed as u128 * width as u128) / max_elapsed_ms as u128).clamp(1, width as u128)
2355 as usize
2356 };
2357 let end = match row.status {
2358 WorkflowRowStatus::Unknown => "? ",
2359 WorkflowRowStatus::Succeeded => "OK",
2360 WorkflowRowStatus::Failed | WorkflowRowStatus::SchemaFailed => "!!",
2361 WorkflowRowStatus::Cancelled => "XX",
2362 WorkflowRowStatus::Waiting => "? ",
2363 WorkflowRowStatus::Pending => ". ",
2364 WorkflowRowStatus::Running => "> ",
2365 };
2366 let body_width = width.saturating_sub(2);
2367 let active = filled.saturating_sub(2).min(body_width);
2368 format!(
2369 "{}{}{}",
2370 "=".repeat(active),
2371 end,
2372 "-".repeat(body_width.saturating_sub(active))
2373 )
2374 }
2375
2376 fn now_ms() -> u64 {
2377 SystemTime::now()
2378 .duration_since(UNIX_EPOCH)
2379 .map(|d| d.as_millis() as u64)
2380 .unwrap_or(0)
2381 }
2382
2383 /// The run's result as one readable line — the same wording the engine puts
2384 /// on `run_completed.result_preview`, so the transcript and the parent receipt
2385 /// never describe one result two ways.
2386 fn summarize_result_value(value: &Value) -> Option<String> {
2387 codewhale_engine::tools::workflow::workflow_result_preview(value)
2388 }
2389
2390 #[cfg(test)]
2391 mod tests {
2392 use super::*;
2393 use serde_json::json;
2394
2395 /// Exactly the flattened `task_started` payload the Workflow runtime emits
2396 /// (`WorkflowTaskStartedEvent` + `run_id`), so the projection is tested on
2397 /// the production wire shape rather than a hand-shaped struct.
2398 fn task_started_json(task_id: &str, provider: &str, model: &str) -> Value {
2399 json!({
2400 "type": "task_started",
2401 "at_ms": 1_200,
2402 "run_id": "workflow_abc",
2403 "task_id": task_id,
2404 "label": task_id,
2405 "role": "implementer",
2406 "profile": "impl-1",
2407 "model": "flash",
2408 "strength": "same",
2409 "thinking": "high",
2410 "requested_reasoning": "high",
2411 "effective_reasoning": "max",
2412 "resolved_role": "verifier",
2413 "resolved_profile": "verify-1",
2414 "resolved_provider": provider,
2415 "resolved_model": model,
2416 "route_source": "agent_profile.model",
2417 "worktree": false,
2418 "depth": 1,
2419 "workflow_run_id": "workflow_abc",
2420 "workflow_task_label": task_id,
2421 })
2422 }
2423
2424 /// Detail view: the history card's expanded body, which carries every
2425 /// row's full receipt (#4039) now that live rows are one line (#6503).
2426 fn detail(panel: &WorkflowPanel, width: u16) -> String {
2427 panel
2428 .history_expanded_lines(width, &WorkflowHistoryExtras::default())
2429 .iter()
2430 .map(|line| {
2431 line.spans
2432 .iter()
2433 .map(|span| span.content.as_ref())
2434 .collect::<String>()
2435 })
2436 .collect::<Vec<_>>()
2437 .join("\n")
2438 }
2439
2440 /// #4039: a row's receipt states the exact role, provider, model,
2441 /// requested → effective reasoning, and route source the runtime reported
2442 /// — and keeps stating them after the session routes somewhere else.
2443 #[test]
2444 fn row_route_receipt_is_exact_and_survives_a_later_model_switch() {
2445 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2446 panel.apply_json_event(&task_started_json("t1", "deepseek", "deepseek-v4-flash"));
2447 let before = detail(&panel, 200);
2448 assert!(before.contains("role verifier"), "{before}");
2449 assert!(before.contains("deepseek/deepseek-v4-flash"), "{before}");
2450 assert!(before.contains("reasoning high→max"), "{before}");
2451 assert!(before.contains("via agent_profile.model"), "{before}");
2452 // A running row claims no totals at all.
2453 assert!(!before.contains("tokens"), "{before}");
2454
2455 // The session now routes elsewhere: a later task lands on another
2456 // provider/model. The already-launched row must not follow it.
2457 panel.apply_json_event(&task_started_json("t2", "moonshot", "kimi-k3"));
2458 let after = detail(&panel, 200);
2459 assert!(after.contains("deepseek/deepseek-v4-flash"), "{after}");
2460 assert!(after.contains("moonshot/kimi-k3"), "{after}");
2461 let t1 = panel
2462 .phases
2463 .iter()
2464 .flat_map(|phase| phase.rows.iter())
2465 .find(|row| row.task_id == "t1")
2466 .expect("t1 row");
2467 assert_eq!(t1.route.provider.as_deref(), Some("deepseek"));
2468 assert_eq!(t1.route.model.as_deref(), Some("deepseek-v4-flash"));
2469 assert_eq!(t1.route.requested_reasoning.as_deref(), Some("high"));
2470 assert_eq!(t1.route.effective_reasoning.as_deref(), Some("max"));
2471 assert_eq!(
2472 t1.route.route_source,
2473 Some(WorkflowRouteSource::AgentProfileModel)
2474 );
2475 }
2476
2477 #[test]
2478 fn history_lane_columns_pad_by_display_width() {
2479 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2480 panel.apply_json_event(&task_started_json("plain", "deepseek", "deepseek-v4-flash"));
2481 panel.apply_json_event(&task_started_json(
2482 "审查代码",
2483 "deepseek",
2484 "deepseek-v4-flash",
2485 ));
2486 let text = detail(&panel, 200);
2487 let track_column = |label: &str| {
2488 let line = text
2489 .lines()
2490 .find(|line| line.starts_with("lane ") && line.contains(label))
2491 .expect("lane row renders");
2492 let end = line.find(label).expect("label") + label.len();
2493 let gap = line[end..].len() - line[end..].trim_start().len();
2494 codewhale_tui_kit::ui_text::text_display_width(&line[..end]) + gap
2495 };
2496 assert_eq!(track_column("plain"), track_column("审查代码"));
2497 }
2498
2499 /// #4039: completed rows show provider-reported totals with their
2500 /// provenance, and unreported telemetry stays `unknown` — never `0`.
2501 #[test]
2502 fn completed_row_usage_is_reported_or_unknown_but_never_a_fabricated_zero() {
2503 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2504 panel.apply_json_event(&task_started_json("t1", "deepseek", "deepseek-v4-flash"));
2505 panel.apply_json_event(&task_started_json("t2", "deepseek", "deepseek-v4-flash"));
2506 panel.apply_json_event(&json!({
2507 "type": "task_completed",
2508 "at_ms": 3_200,
2509 "task_id": "t1",
2510 "status": "succeeded",
2511 "usage": {
2512 "input_tokens": 128,
2513 "output_tokens": 32,
2514 "total_tokens": 160,
2515 "tool_calls": 3,
2516 "duration_ms": 2_000,
2517 "token_source": "provider_reported",
2518 },
2519 }));
2520 // A provider that reported nothing: the runtime omits `usage`.
2521 panel.apply_json_event(&json!({
2522 "type": "task_completed",
2523 "at_ms": 3_400,
2524 "task_id": "t2",
2525 "status": "succeeded",
2526 }));
2527
2528 let text = detail(&panel, 200);
2529 assert!(text.contains("tokens 160 (provider-reported)"), "{text}");
2530 assert!(text.contains("tools 3"), "{text}");
2531 assert!(text.contains("tokens unknown · tools unknown"), "{text}");
2532 let t2 = panel
2533 .phases
2534 .iter()
2535 .flat_map(|phase| phase.rows.iter())
2536 .find(|row| row.task_id == "t2")
2537 .expect("t2 row");
2538 let usage = t2.usage.as_ref().expect("completed rows carry a receipt");
2539 assert_eq!(usage.total_tokens, None);
2540 assert_eq!(usage.tool_calls, None);
2541 }
2542
2543 /// #4039: the projection is built once from the events already applied —
2544 /// the history round trip must carry the receipts rather than force a
2545 /// re-scan of the durable journal.
2546 #[test]
2547 fn row_receipts_survive_the_history_round_trip() {
2548 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2549 panel.apply_json_event(&task_started_json("t1", "deepseek", "deepseek-v4-flash"));
2550 panel.apply_json_event(&json!({
2551 "type": "task_completed",
2552 "at_ms": 3_200,
2553 "task_id": "t1",
2554 "status": "succeeded",
2555 "usage": {
2556 "total_tokens": 160,
2557 "tool_calls": 3,
2558 "duration_ms": 2_000,
2559 "token_source": "provider_reported",
2560 },
2561 }));
2562 let original = panel
2563 .phases
2564 .iter()
2565 .flat_map(|phase| phase.rows.iter())
2566 .map(row_receipt_text)
2567 .collect::<Vec<_>>();
2568
2569 let rehydrated = WorkflowPanel::from_run_json(&panel.to_run_json()).expect("rehydrate");
2570 let round_tripped = rehydrated
2571 .phases
2572 .iter()
2573 .flat_map(|phase| phase.rows.iter())
2574 .map(row_receipt_text)
2575 .collect::<Vec<_>>();
2576 assert_eq!(original, round_tripped);
2577
2578 {
2579 let child_id = "persisted-child";
2580 let mut started = task_started_json(child_id, "deepseek", "deepseek-v4-flash");
2581 started["requested_reasoning"] = json!("low");
2582 started["effective_reasoning"] = json!("low");
2583 started["route_source"] = json!("task.model");
2584 let persisted_json = json!({
2585 "run_id":"workflow_abc", "workflow_goal":"audit", "started_at_ms":1_000,
2586 "events":[
2587 {"type":"run_started", "run_id":"workflow_abc", "workflow_goal":"audit", "at_ms":1_000},
2588 started,
2589 {"type":"task_completed", "task_id":child_id, "status":"succeeded", "at_ms":3_200}
2590 ]
2591 });
2592 let mut panel = WorkflowPanel::from_run_json(&persisted_json)
2593 .expect("journal should hydrate workflow panel");
2594 let original_receipt = panel
2595 .phases
2596 .iter()
2597 .flat_map(|phase| phase.rows.iter())
2598 .find(|row| row.task_id == child_id)
2599 .map(row_receipt_text)
2600 .expect("spawned child receipt");
2601 assert!(original_receipt.contains("deepseek/deepseek-v4-flash"));
2602 assert!(original_receipt.contains("reasoning low→"));
2603 assert!(original_receipt.contains("via task.model"));
2604
2605 panel.apply_json_event(&json!({
2606 "type": "task_started",
2607 "at_ms": 9_000,
2608 "task_id": "later-route",
2609 "label": "later-route",
2610 "resolved_role": "consultant",
2611 "resolved_provider": "moonshot",
2612 "resolved_model": "kimi-k3",
2613 "requested_reasoning": "auto",
2614 "effective_reasoning": "medium",
2615 "route_source": "agent_profile.model",
2616 "worktree": false,
2617 }));
2618 panel.apply_json_event(&json!({
2619 "type": "task_completed",
2620 "at_ms": 9_100,
2621 "task_id": "later-route",
2622 "status": "succeeded"
2623 }));
2624 let unchanged = panel
2625 .phases
2626 .iter()
2627 .flat_map(|phase| phase.rows.iter())
2628 .find(|row| row.task_id == child_id)
2629 .map(row_receipt_text)
2630 .expect("original child after later route");
2631 assert_eq!(unchanged, original_receipt);
2632
2633 let history = WorkflowPanel::from_run_json(&panel.to_run_json())
2634 .expect("history receipt round trip");
2635 let later_receipt = history
2636 .phases
2637 .iter()
2638 .flat_map(|phase| phase.rows.iter())
2639 .find(|row| row.task_id == "later-route")
2640 .map(row_receipt_text)
2641 .expect("later route history receipt");
2642 assert!(later_receipt.contains("moonshot/kimi-k3"));
2643 assert!(later_receipt.contains("reasoning auto→medium"));
2644 assert!(later_receipt.contains("tokens unknown"));
2645 assert!(!later_receipt.contains("tokens 0"));
2646 }
2647 }
2648
2649 /// #4039 compatibility: journals written before the receipt fields existed
2650 /// still project, and every missing field reads `unknown`.
2651 #[test]
2652 fn legacy_task_events_project_as_unknown_not_as_defaults() {
2653 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2654 panel.apply_json_event(&json!({
2655 "type": "task_started",
2656 "at_ms": 1_200,
2657 "task_id": "t1",
2658 "label": "legacy",
2659 "worktree": false,
2660 }));
2661 panel.apply_json_event(&json!({
2662 "type": "task_completed",
2663 "at_ms": 1_900,
2664 "task_id": "t1",
2665 "status": "succeeded",
2666 }));
2667 let text = detail(&panel, 200);
2668 let unknown_route = "role unknown · unknown/unknown · reasoning unknown→unknown";
2669 assert!(text.contains(unknown_route), "{text}");
2670 assert!(text.contains("via unknown"), "{text}");
2671 assert!(
2672 text.contains("tokens unknown · tools unknown · duration unknown"),
2673 "{text}"
2674 );
2675 }
2676
2677 #[test]
2678 fn requested_model_and_foreign_provenance_never_become_effective_receipts() {
2679 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2680 panel.apply_json_event(&json!({
2681 "type": "task_started",
2682 "at_ms": 1_200,
2683 "task_id": "legacy",
2684 "model": "requested-only",
2685 "thinking": "high",
2686 "route_source": "foreign.source",
2687 "worktree": false,
2688 }));
2689 let row = panel
2690 .phases
2691 .iter()
2692 .flat_map(|phase| phase.rows.iter())
2693 .find(|row| row.task_id == "legacy")
2694 .expect("legacy row");
2695 assert_eq!(row.model.as_deref(), Some("requested-only"));
2696 assert_eq!(row.route.model, None);
2697 assert_eq!(row.route.route_source, None);
2698 let receipt = row_receipt_text(row);
2699 assert!(receipt.contains("unknown/unknown"), "{receipt}");
2700 assert!(receipt.contains("reasoning high→unknown"), "{receipt}");
2701 assert!(receipt.contains("via unknown"), "{receipt}");
2702 }
2703
2704 #[test]
2705 fn receipt_provenance_is_closed_and_a_reported_zero_stays_zero() {
2706 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2707 panel.apply_json_event(&task_started_json("t1", "deepseek", "deepseek-v4-flash"));
2708 panel.apply_json_event(&json!({
2709 "type": "task_completed",
2710 "at_ms": 1_300,
2711 "task_id": "t1",
2712 "status": "succeeded",
2713 "usage": {
2714 "input_tokens": 0,
2715 "output_tokens": 0,
2716 "total_tokens": 0,
2717 "tool_calls": 0,
2718 "duration_ms": 0,
2719 "token_source": "foreign-source",
2720 },
2721 }));
2722 let text = detail(&panel, 200);
2723 assert!(text.contains("tokens 0 (unknown)"), "{text}");
2724 assert!(!text.contains("foreign-source"), "{text}");
2725 }
2726
2727 #[test]
2728 fn required_receipt_fields_survive_release_terminal_sizes() {
2729 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2730 panel.apply_json_event(&task_started_json("t1", "deepseek", "deepseek-v4-flash"));
2731 panel.apply_json_event(&json!({
2732 "type": "task_completed",
2733 "at_ms": 3_200,
2734 "task_id": "t1",
2735 "status": "succeeded",
2736 "usage": {
2737 "total_tokens": 160,
2738 "tool_calls": 3,
2739 "duration_ms": 2_000,
2740 "token_source": "provider_reported",
2741 },
2742 }));
2743
2744 for width in [40_u16, 60, 80] {
2745 let lines = panel.history_expanded_lines(width, &WorkflowHistoryExtras::default());
2746 let text = lines
2747 .iter()
2748 .map(|line| {
2749 line.spans
2750 .iter()
2751 .map(|span| span.content.as_ref())
2752 .collect::<String>()
2753 })
2754 .collect::<Vec<_>>()
2755 .join("\n");
2756 for required in [
2757 "role verifier",
2758 "deepseek/deepseek-v4-flash",
2759 "reasoning high→max",
2760 "via agent_profile.model",
2761 "tokens 160 (provider-reported)",
2762 "tools 3",
2763 "duration 2s",
2764 ] {
2765 assert!(text.contains(required), "{width} lost {required}: {text}");
2766 }
2767 assert!(lines.iter().all(|line| line.width() <= usize::from(width)));
2768 }
2769 }
2770
2771 #[test]
2772 fn receipt_fields_flatten_controls_strip_ansi_and_redact_secrets() {
2773 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
2774 panel.apply_json_event(&json!({
2775 "type": "task_started",
2776 "at_ms": 1_200,
2777 "task_id": "hostile",
2778 "resolved_role": "verifier\r\nFORGED ROLE",
2779 "resolved_provider": "\u{1b}[31mdeepseek\u{1b}[0m\tFORGED PROVIDER",
2780 "resolved_model": "model\napi_key=sk-receipt-secret-1234567890",
2781 "requested_reasoning": "high\rFORGED REASONING",
2782 "effective_reasoning": "max\tFORGED EFFECTIVE",
2783 "route_source": "task.model",
2784 "worktree": false,
2785 }));
2786 let row = panel
2787 .phases
2788 .iter()
2789 .flat_map(|phase| phase.rows.iter())
2790 .find(|row| row.task_id == "hostile")
2791 .expect("hostile row");
2792 let receipt = row_receipt_text(row);
2793
2794 assert!(receipt.contains("verifier FORGED ROLE"), "{receipt:?}");
2795 assert!(receipt.contains("deepseek FORGED PROVIDER"), "{receipt:?}");
2796 assert!(receipt.contains("api_key=[redacted]"), "{receipt:?}");
2797 assert!(!receipt.contains("sk-receipt-secret"), "{receipt:?}");
2798 assert!(!receipt.chars().any(char::is_control), "{receipt:?}");
2799 for line in receipt_line_strings(row, Locale::En, 18, 2) {
2800 assert!(!line.chars().any(char::is_control), "{line:?}");
2801 assert!(line.width() <= 18, "{line:?}");
2802 }
2803 }
2804
2805 fn started_panel() -> WorkflowPanel {
2806 let mut panel = WorkflowPanel::new("workflow_abc", "ship v0.8.68", 1_000);
2807 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
2808 title: "Analyze".to_string(),
2809 at_ms: 1_100,
2810 });
2811 panel.apply_event(WorkflowPanelEvent::TaskStarted {
2812 task_id: "t1".to_string(),
2813 label: Some("scout crates".to_string()),
2814 profile: Some("explore".to_string()),
2815 model: Some("flash".to_string()),
2816 strength: Some("low".to_string()),
2817 resolved_model: Some("deepseek-v4-flash".to_string()),
2818 worktree: true,
2819 workspace: Some(PathBuf::from("/tmp/wt-1")),
2820 route: Box::default(),
2821 at_ms: 1_200,
2822 });
2823 panel
2824 }
2825
2826 #[test]
2827 fn late_run_completed_keeps_a_cancelled_run_cancelled() {
2828 let mut panel = started_panel();
2829 panel.apply_event(WorkflowPanelEvent::RunCancelled {
2830 reason: "stopped by you".to_string(),
2831 at_ms: 2_000,
2832 });
2833 panel.apply_event(WorkflowPanelEvent::RunCompleted {
2834 status: WorkflowPanelLifecycle::Succeeded,
2835 error: None,
2836 at_ms: 2_100,
2837 });
2838 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Cancelled);
2839 assert_eq!(panel.error.as_deref(), Some("stopped by you"));
2840 assert_eq!(panel.completed_at_ms, Some(2_000));
2841 assert_eq!(
2842 panel.find_row_mut("t1").expect("row").status,
2843 WorkflowRowStatus::Cancelled
2844 );
2845 }
2846
2847 /// U05-01: a child launch that raced the cancel (or any late same-run
2848 /// `task_started`) lands after the run settled. It is recorded, but it
2849 /// never reopens the run, and a settled row is never reset to running.
2850 #[test]
2851 fn late_task_started_never_reopens_a_settled_run() {
2852 let mut panel = started_panel();
2853 panel.apply_json_event(&json!({
2854 "type": "run_cancelled", "run_id": "workflow_abc",
2855 "reason": "stopped by you", "at_ms": 2_000,
2856 }));
2857 panel.apply_json_event(&task_started_json("t2", "deepseek", "flash"));
2858 panel.apply_json_event(&task_started_json("t1", "deepseek", "flash"));
2859 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Cancelled);
2860 assert_eq!(
2861 panel.find_row_mut("t1").expect("t1").status,
2862 WorkflowRowStatus::Cancelled
2863 );
2864 assert_eq!(
2865 panel
2866 .find_row_mut("t2")
2867 .expect("late t2 is recorded")
2868 .status,
2869 WorkflowRowStatus::Cancelled
2870 );
2871
2872 let mut panel = started_panel();
2873 panel.apply_json_event(&json!({
2874 "type": "task_completed", "run_id": "workflow_abc",
2875 "task_id": "t1", "status": "succeeded", "at_ms": 1_500,
2876 }));
2877 panel.apply_json_event(&json!({
2878 "type": "run_completed", "run_id": "workflow_abc",
2879 "status": "completed", "at_ms": 1_600,
2880 }));
2881 panel.apply_json_event(&task_started_json("t1", "deepseek", "flash"));
2882 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Succeeded);
2883 assert_eq!(
2884 panel.find_row_mut("t1").expect("t1").status,
2885 WorkflowRowStatus::Succeeded
2886 );
2887 }
2888
2889 /// U05-m1: an arriving task joins the runtime's newest phase, never the
2890 /// phase the user's cursor happens to rest on.
2891 #[test]
2892 fn arriving_task_joins_the_newest_phase_not_the_selected_one() {
2893 let mut panel = started_panel();
2894 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
2895 title: "Verify".to_string(),
2896 at_ms: 1_300,
2897 });
2898 panel.selected_phase = 0;
2899 panel.apply_json_event(&task_started_json("t2", "deepseek", "flash"));
2900 let ids = |phase: &WorkflowPanelPhase| {
2901 phase
2902 .rows
2903 .iter()
2904 .map(|row| row.task_id.clone())
2905 .collect::<Vec<_>>()
2906 };
2907 assert_eq!(ids(&panel.phases[0]), ["t1"]);
2908 assert_eq!(ids(&panel.phases[1]), ["t2"]);
2909 }
2910
2911 /// U05-02: a terminal receipt with a missing or contradictory status is
2912 /// not evidence of success; it fails closed like an unknown status.
2913 #[test]
2914 fn malformed_completion_status_never_reads_as_success() {
2915 for status in [None, Some("running"), Some("pending")] {
2916 let mut panel = started_panel();
2917 let mut completed = json!({
2918 "type": "run_completed", "run_id": "workflow_abc", "at_ms": 2_000,
2919 });
2920 let mut task_completed = json!({
2921 "type": "task_completed", "run_id": "workflow_abc",
2922 "task_id": "t1", "at_ms": 1_900,
2923 });
2924 if let Some(status) = status {
2925 completed["status"] = json!(status);
2926 task_completed["status"] = json!(status);
2927 }
2928 panel.apply_json_event(&task_completed);
2929 panel.apply_json_event(&completed);
2930 assert_eq!(
2931 panel.lifecycle,
2932 WorkflowPanelLifecycle::Failed,
2933 "{status:?}"
2934 );
2935 assert_eq!(
2936 panel.find_row_mut("t1").expect("row").status,
2937 WorkflowRowStatus::Failed
2938 );
2939 }
2940 }
2941
2942 /// #4208: every decorative glyph the run map emits — expand marks, role
2943 /// marks, lane glyphs, gates, status marks across running, waiting,
2944 /// failed, cancelled, and completed members — must narrow to an
2945 /// ASCII-safe alternative.
2946 #[test]
2947 fn workflow_panel_glyphs_all_have_ascii_alternatives() {
2948 let mut panel = started_panel();
2949 for (task_id, status) in [
2950 ("t1", WorkflowRowStatus::Succeeded),
2951 ("t2", WorkflowRowStatus::Failed),
2952 ("t3", WorkflowRowStatus::Cancelled),
2953 ("t4", WorkflowRowStatus::Waiting),
2954 ] {
2955 if task_id != "t1" {
2956 panel.apply_event(WorkflowPanelEvent::TaskStarted {
2957 task_id: task_id.to_string(),
2958 label: Some(format!("lane {task_id}")),
2959 profile: Some("implementer".to_string()),
2960 model: None,
2961 strength: None,
2962 resolved_model: None,
2963 worktree: false,
2964 workspace: None,
2965 route: Box::default(),
2966 at_ms: 1_400,
2967 });
2968 }
2969 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
2970 task_id: task_id.to_string(),
2971 status,
2972 usage: None,
2973 reason: None,
2974 at_ms: 2_500,
2975 });
2976 }
2977 panel.apply_event(WorkflowPanelEvent::GateUpdated {
2978 gate_id: "gate-1".to_string(),
2979 role: Some("verifier".to_string()),
2980 gate: Some("tests-green".to_string()),
2981 state: "blocked".to_string(),
2982 blocked_role: Some("implementer".to_string()),
2983 blocked_reason: Some("waiting on tests".to_string()),
2984 at_ms: 2_600,
2985 });
2986
2987 let mut glyphs: Vec<char> = panel.compact_summary_text(120).chars().collect();
2988 for line in panel.render_history_card(100, true, &WorkflowHistoryExtras::default()) {
2989 for span in &line.spans {
2990 glyphs.extend(span.content.chars());
2991 }
2992 }
2993 for ch in glyphs.into_iter().filter(|ch| !ch.is_ascii()) {
2994 let mut cell = ratatui::buffer::Cell::default();
2995 cell.set_symbol(&ch.to_string());
2996 crate::tui::color_compat::adapt_cell_symbol_for_ascii(&mut cell);
2997 assert!(
2998 cell.symbol().is_ascii(),
2999 "workflow glyph {ch:?} (U+{:04X}) lacks an ASCII-safe alternative",
3000 ch as u32
3001 );
3002 }
3003 }
3004
3005 #[test]
3006 fn a_repeated_start_of_the_same_run_keeps_settled_rows_and_outcome() {
3007 let mut panel = started_panel();
3008 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3009 task_id: "t1".to_string(),
3010 status: WorkflowRowStatus::Succeeded,
3011 usage: None,
3012 reason: None,
3013 at_ms: 1_400,
3014 });
3015 panel.apply_event(WorkflowPanelEvent::RunCompleted {
3016 status: WorkflowPanelLifecycle::Succeeded,
3017 error: None,
3018 at_ms: 1_500,
3019 });
3020 let rows = |panel: &WorkflowPanel| panel.phases.iter().map(|p| p.rows.len()).sum::<usize>();
3021 let settled_rows = rows(&panel);
3022 assert!(settled_rows > 0);
3023 assert!(panel.apply_json_event(&json!({
3024 "type": "run_started",
3025 "run_id": "workflow_abc",
3026 "at_ms": 1_600,
3027 "workflow_goal": "ship v0.8.68",
3028 "source_path": "workflows/ship.workflow.js",
3029 "token_budget": 9_000
3030 })));
3031 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Succeeded);
3032 assert_eq!(rows(&panel), settled_rows);
3033 assert_eq!(
3034 panel.source_path,
3035 Some(PathBuf::from("workflows/ship.workflow.js")),
3036 "missing metadata is filled"
3037 );
3038 }
3039
3040 #[test]
3041 fn json_events_round_trip_without_log_flood() {
3042 let mut panel = WorkflowPanel::new("w1", "goal", 0);
3043 let events = vec![
3044 json!({
3045 "type": "run_started",
3046 "at_ms": 10,
3047 "run_id": "w1",
3048 "workflow_goal": "demo",
3049 "token_budget": 5000
3050 }),
3051 json!({"type": "log", "at_ms": 11, "message": "should not appear"}),
3052 json!({"type": "phase_started", "at_ms": 12, "title": "Analyze"}),
3053 json!({
3054 "type": "task_started",
3055 "at_ms": 13,
3056 "task_id": "a",
3057 "label": "scout",
3058 "profile": "explore",
3059 "resolved_model": "flash",
3060 "worktree": true
3061 }),
3062 json!({
3063 "type": "budget_updated",
3064 "at_ms": 14,
3065 "total": 5000,
3066 "spent": 100,
3067 "remaining": 4900
3068 }),
3069 json!({
3070 "type": "task_completed",
3071 "at_ms": 15,
3072 "task_id": "a",
3073 "status": "succeeded"
3074 }),
3075 json!({
3076 "type": "gate_updated",
3077 "at_ms": 15,
3078 "gate_id": "reviewer-diff",
3079 "role": "reviewer",
3080 "gate": "review",
3081 "state": "blocked",
3082 "blocked_role": "verifier",
3083 "blocked_reason": "review found regression"
3084 }),
3085 json!({
3086 "type": "run_completed",
3087 "at_ms": 16,
3088 "status": "completed"
3089 }),
3090 ];
3091 panel.apply_json_events(&events);
3092 assert_eq!(panel.label, "demo");
3093 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Succeeded);
3094 let joined: String = panel
3095 .render_history_card(100, true, &WorkflowHistoryExtras::default())
3096 .iter()
3097 .map(|l| {
3098 l.spans
3099 .iter()
3100 .map(|s| s.content.as_ref())
3101 .collect::<String>()
3102 })
3103 .collect::<Vec<_>>()
3104 .join("\n");
3105 assert!(!joined.contains("should not appear"), "{joined}");
3106 assert!(joined.contains("scout"), "{joined}");
3107 assert!(joined.contains("done"), "{joined}");
3108 assert!(joined.contains("reviewer-diff"), "{joined}");
3109 assert!(joined.contains("review found regression"), "{joined}");
3110 }
3111
3112 #[test]
3113 fn failure_and_cancel_counts_roll_up_in_header() {
3114 let mut panel = started_panel();
3115 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3116 task_id: "t2".to_string(),
3117 label: Some("b".to_string()),
3118 profile: None,
3119 model: None,
3120 strength: None,
3121 resolved_model: None,
3122 worktree: false,
3123 workspace: None,
3124 route: Box::default(),
3125 at_ms: 1_300,
3126 });
3127 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3128 task_id: "t1".to_string(),
3129 status: WorkflowRowStatus::Failed,
3130 usage: None,
3131 reason: None,
3132 at_ms: 1_400,
3133 });
3134 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3135 task_id: "t2".to_string(),
3136 status: WorkflowRowStatus::Cancelled,
3137 usage: None,
3138 reason: None,
3139 at_ms: 1_500,
3140 });
3141 let (failed, cancelled) = panel.failure_cancel_counts();
3142 assert_eq!(failed, 1);
3143 assert_eq!(cancelled, 1);
3144 let header = panel.compact_summary_text(100);
3145 assert!(header.contains("1 fail"), "{header}");
3146 assert!(header.contains("1 cancel"), "{header}");
3147 assert!(header.contains("2/2"), "{header}");
3148 }
3149
3150 #[test]
3151 fn task_started_json_prefers_workflow_task_label_over_generic_label() {
3152 // #4119: panel rows use typed workflow metadata, not prompt text.
3153 let event = WorkflowPanelEvent::from_json_value(&json!({
3154 "type": "task_started",
3155 "task_id": "child-1",
3156 "label": "fallback-label",
3157 "workflow_task_label": "typed-label",
3158 "workflow_run_id": "run-xyz",
3159 "workflow_phase_id": "dispatch",
3160 "workflow_child_index": 2,
3161 "at_ms": 42,
3162 }))
3163 .expect("task_started parses");
3164 match event {
3165 WorkflowPanelEvent::TaskStarted { label, .. } => {
3166 assert_eq!(label.as_deref(), Some("typed-label"));
3167 }
3168 other => panic!("expected TaskStarted, got {other:?}"),
3169 }
3170
3171 let mut panel = WorkflowPanel::new("run-xyz", "goal", 1);
3172 panel.apply_json_event(&json!({
3173 "type": "task_started",
3174 "task_id": "child-1",
3175 "label": "fallback-label",
3176 "workflow_task_label": "typed-label",
3177 "at_ms": 42,
3178 }));
3179 let row = panel
3180 .phases
3181 .iter()
3182 .flat_map(|phase| phase.rows.iter())
3183 .find(|row| row.task_id == "child-1")
3184 .expect("row recorded");
3185 assert_eq!(row.label, "typed-label");
3186 }
3187
3188 #[test]
3189 fn explicit_event_run_id_cannot_cross_panel_run() {
3190 let mut panel = WorkflowPanel::new("run-b", "active run", 2_000);
3191
3192 assert!(!panel.apply_json_event(&json!({
3193 "type": "run_started",
3194 "run_id": "run-a",
3195 "workflow_goal": "late prior run",
3196 "at_ms": 1_500,
3197 })));
3198 assert!(!panel.apply_json_event(&json!({
3199 "type": "phase_started",
3200 "run_id": "run-a",
3201 "title": "Late A phase",
3202 "at_ms": 2_100,
3203 })));
3204 assert!(panel.phases.is_empty());
3205 assert_eq!(panel.run_id, "run-b");
3206
3207 assert!(panel.apply_json_event(&json!({
3208 "type": "phase_started",
3209 "run_id": "run-b",
3210 "title": "B phase",
3211 "at_ms": 2_200,
3212 })));
3213 assert_eq!(panel.phases.len(), 1);
3214 assert_eq!(panel.phases[0].title, "B phase");
3215 }
3216
3217 #[test]
3218 fn dispatch_failure_event_surfaces_without_inventing_a_child() {
3219 let mut panel = started_panel();
3220 panel.apply_json_event(&json!({
3221 "type": "task_dispatch_failed",
3222 "label": "review docs",
3223 "phase": "Analyze",
3224 "message": "unknown agent profile reviewer",
3225 "at_ms": 1_250,
3226 }));
3227
3228 assert_eq!(panel.done_total(), (0, 1), "rejected launch is not a child");
3229 assert_eq!(panel.failure_cancel_counts(), (1, 0));
3230 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Running);
3231 assert!(panel.compact_summary_text(120).contains("1 fail"));
3232
3233 let live = panel
3234 .render_history_card(120, true, &WorkflowHistoryExtras::default())
3235 .iter()
3236 .map(|line| {
3237 line.spans
3238 .iter()
3239 .map(|span| span.content.as_ref())
3240 .collect::<String>()
3241 })
3242 .collect::<Vec<_>>()
3243 .join("\n");
3244 for expected in [
3245 "dispatch failed",
3246 "review docs",
3247 "Analyze",
3248 "unknown agent profile reviewer",
3249 ] {
3250 assert!(live.contains(expected), "missing {expected}: {live}");
3251 }
3252
3253 let snapshot = panel.to_run_json();
3254 assert_eq!(snapshot["dispatch_failure_count"], 1);
3255 assert_eq!(
3256 snapshot["dispatch_failures"].as_array().map(Vec::len),
3257 Some(1)
3258 );
3259 let restored = WorkflowPanel::from_run_json(&snapshot).expect("panel rehydrates");
3260 assert_eq!(restored.done_total(), (0, 1));
3261 assert_eq!(restored.failure_cancel_counts(), (1, 0));
3262 let history = restored
3263 .render_history_card(120, true, &WorkflowHistoryExtras::default())
3264 .iter()
3265 .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
3266 .collect::<String>();
3267 assert!(history.contains("dispatch failed"), "{history}");
3268 assert!(
3269 history.contains("unknown agent profile reviewer"),
3270 "{history}"
3271 );
3272
3273 let mut japanese = restored.clone();
3274 japanese.locale = Locale::Ja;
3275 let localized = japanese
3276 .render_history_card(120, true, &WorkflowHistoryExtras::default())
3277 .iter()
3278 .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
3279 .collect::<String>();
3280 assert!(localized.contains("ディスパッチ失敗"), "{localized}");
3281 assert!(!localized.contains("dispatch failed"), "{localized}");
3282 }
3283
3284 #[test]
3285 fn degraded_run_preserves_partial_success_as_a_distinct_terminal_state() {
3286 let mut panel = started_panel();
3287 panel.apply_json_event(&json!({
3288 "type": "task_completed",
3289 "task_id": "t1",
3290 "status": "succeeded",
3291 "at_ms": 1_300,
3292 }));
3293 panel.apply_json_event(&json!({
3294 "type": "task_dispatch_failed",
3295 "label": "review docs",
3296 "message": "profile unavailable",
3297 "at_ms": 1_350,
3298 }));
3299 panel.apply_json_event(&json!({
3300 "type": "run_completed",
3301 "status": "degraded",
3302 "error": "completed with dropped slots",
3303 "at_ms": 1_400,
3304 }));
3305
3306 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Degraded);
3307 assert!(panel.lifecycle.is_terminal());
3308 assert_eq!(panel.done_total(), (1, 1));
3309 assert_eq!(panel.failure_cancel_counts(), (1, 0));
3310 assert!(panel.compact_summary_text(120).contains("degraded"));
3311
3312 panel.locale = Locale::Ja;
3313 assert!(panel.compact_summary_text(120).contains("一部失敗"));
3314 }
3315
3316 #[test]
3317 fn dispatch_failure_tail_is_bounded_and_redacted() {
3318 let mut panel = WorkflowPanel::new("workflow_abc", "audit", 1_000);
3319 for index in 0..20 {
3320 panel.apply_json_event(&json!({
3321 "type": "task_dispatch_failed",
3322 "label": format!("job-{index}"),
3323 "message": if index == 19 {
3324 "\u{1b}[31mapi_key=sk-dispatch-secret-1234567890\u{1b}[0m\nfailed"
3325 } else {
3326 "profile unavailable"
3327 },
3328 "at_ms": 1_100 + index,
3329 }));
3330 }
3331
3332 assert_eq!(panel.dispatch_failure_count, 20);
3333 assert_eq!(
3334 panel.dispatch_failures.len(),
3335 MAX_DISPATCH_FAILURES_RETAINED
3336 );
3337 assert_eq!(
3338 panel
3339 .dispatch_failures
3340 .first()
3341 .and_then(|failure| failure.label.as_deref()),
3342 Some("job-8")
3343 );
3344 let latest = panel.dispatch_failures.last().expect("latest failure");
3345 assert!(!latest.message.contains("sk-dispatch-secret"));
3346 assert!(!latest.message.chars().any(char::is_control));
3347 let rendered = panel
3348 .render_history_card(120, true, &WorkflowHistoryExtras::default())
3349 .iter()
3350 .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
3351 .collect::<String>();
3352 assert!(rendered.contains("17 earlier not shown"), "{rendered}");
3353 assert!(!rendered.contains("sk-dispatch-secret"), "{rendered}");
3354 }
3355
3356 #[test]
3357 fn run_json_overlap_does_not_double_count_dispatch_failure_ledger() {
3358 let failure = json!({
3359 "type": "task_dispatch_failed",
3360 "label": "review docs",
3361 "phase": "Analyze",
3362 "message": "profile unavailable",
3363 "at_ms": 1_250,
3364 });
3365 let panel = WorkflowPanel::from_run_json(&json!({
3366 "run_id": "workflow_abc",
3367 "workflow_goal": "audit",
3368 "started_at_ms": 1_000,
3369 "events": [
3370 {
3371 "type": "run_started",
3372 "run_id": "workflow_abc",
3373 "workflow_goal": "audit",
3374 "at_ms": 1_000,
3375 },
3376 failure.clone(),
3377 ],
3378 "dispatch_failure_count": 1,
3379 "dispatch_failures": [{
3380 "label": "review docs",
3381 "phase": "Analyze",
3382 "message": "profile unavailable",
3383 "at_ms": 1_250,
3384 }],
3385 }))
3386 .expect("panel rehydrates");
3387
3388 assert_eq!(panel.dispatch_failure_count, 1);
3389 assert_eq!(panel.dispatch_failures.len(), 1);
3390 assert_eq!(panel.failure_cancel_counts(), (1, 0));
3391
3392 let mut live = WorkflowPanel::new("workflow_abc", "audit", 1_000);
3393 live.apply_json_event(&failure);
3394 live.apply_json_events(std::slice::from_ref(&failure));
3395 live.merge_dispatch_failures_from_run_json(&json!({
3396 "dispatch_failure_count": 1,
3397 "dispatch_failures": [{
3398 "label": "review docs",
3399 "phase": "Analyze",
3400 "message": "profile unavailable",
3401 "at_ms": 1_250,
3402 }],
3403 }));
3404 assert_eq!(
3405 live.dispatch_failure_count, 1,
3406 "authoritative completion ledger must absorb retained replay"
3407 );
3408 live.apply_json_events(&[failure.clone(), failure]);
3409 live.merge_dispatch_failures_from_run_json(&json!({
3410 "dispatch_failure_count": 2,
3411 "dispatch_failures": [
3412 {
3413 "label": "review docs",
3414 "phase": "Analyze",
3415 "message": "profile unavailable",
3416 "at_ms": 1_250,
3417 },
3418 {
3419 "label": "review docs",
3420 "phase": "Analyze",
3421 "message": "profile unavailable",
3422 "at_ms": 1_250,
3423 },
3424 ],
3425 }));
3426 assert_eq!(
3427 live.dispatch_failure_count, 2,
3428 "authoritative count must preserve two genuinely identical slots"
3429 );
3430 }
3431
3432 #[test]
3433 fn imported_max_dispatch_count_cannot_overflow_failed_child_rollup() {
3434 let mut panel = started_panel();
3435 panel.dispatch_failure_count = usize::MAX;
3436 panel.find_row_mut("t1").expect("row").status = WorkflowRowStatus::Failed;
3437 assert_eq!(panel.failure_cancel_counts(), (usize::MAX, 0));
3438 }
3439
3440 #[test]
3441 fn compact_history_card_summarizes_lifecycle_children_phases_failures_elapsed() {
3442 let mut panel = started_panel();
3443 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3444 task_id: "t1".to_string(),
3445 status: WorkflowRowStatus::Failed,
3446 usage: None,
3447 reason: None,
3448 at_ms: 2_000,
3449 });
3450 panel.apply_event(WorkflowPanelEvent::RunCompleted {
3451 status: WorkflowPanelLifecycle::Failed,
3452 error: Some("scout failed".to_string()),
3453 at_ms: 2_100,
3454 });
3455 let lines = panel.render_history_card(120, false, &WorkflowHistoryExtras::default());
3456 assert_eq!(lines.len(), 1, "compact is a single summary line");
3457 let joined: String = lines
3458 .iter()
3459 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3460 .collect();
3461 assert!(joined.contains('▶'), "collapsed glyph: {joined}");
3462 assert!(
3463 joined.contains("failed") || joined.contains("fail"),
3464 "{joined}"
3465 );
3466 assert!(joined.contains("1/1 done"), "{joined}");
3467 assert!(joined.contains("1 phase"), "{joined}");
3468 assert!(joined.contains("1 fail"), "{joined}");
3469 // elapsed is present (0s or more depending on timestamps)
3470 assert!(
3471 joined.contains('s') || joined.contains('m'),
3472 "elapsed time expected: {joined}"
3473 );
3474 // Goal is reserved for the expanded body so compact stays under the
3475 // tool-header summary budget.
3476 assert!(
3477 !joined.contains("ship v0.8.68"),
3478 "compact must not spend budget on free-text goal: {joined}"
3479 );
3480 }
3481
3482 #[test]
3483 fn expanded_history_card_shows_phase_child_result_links_and_failures() {
3484 let mut panel = started_panel();
3485 panel.source_path = Some(PathBuf::from("workflows/demo.workflow.js"));
3486 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3487 task_id: "t1".to_string(),
3488 status: WorkflowRowStatus::Failed,
3489 usage: None,
3490 reason: None,
3491 at_ms: 2_000,
3492 });
3493 if let Some(row) = panel.find_row_mut("t1") {
3494 row.error = Some("timeout waiting for model".to_string());
3495 }
3496 panel.apply_event(WorkflowPanelEvent::RunCompleted {
3497 status: WorkflowPanelLifecycle::Failed,
3498 error: Some("phase Analyze failed".to_string()),
3499 at_ms: 2_100,
3500 });
3501 let extras = WorkflowHistoryExtras {
3502 result_summary: Some("no ship blockers found".to_string()),
3503 source_path: None,
3504 spillover_path: Some(PathBuf::from("/tmp/workflow-out.json")),
3505 verification_summary: None,
3506 };
3507 let lines = panel.render_history_card(120, true, &extras);
3508 let joined: String = lines
3509 .iter()
3510 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3511 .collect::<Vec<_>>()
3512 .join("\n");
3513 assert!(joined.contains('▼'), "expanded glyph: {joined}");
3514 assert!(joined.contains("goal:"), "{joined}");
3515 assert!(joined.contains("ship v0.8.68"), "{joined}");
3516 assert!(joined.contains("phases:"), "{joined}");
3517 assert!(joined.contains("Analyze"), "{joined}");
3518 assert!(joined.contains("children:"), "{joined}");
3519 assert!(joined.contains("scout crates"), "{joined}");
3520 assert!(joined.contains("result:"), "{joined}");
3521 assert!(joined.contains("no ship blockers"), "{joined}");
3522 assert!(
3523 joined.contains("source:") || joined.contains("demo.workflow"),
3524 "{joined}"
3525 );
3526 assert!(joined.contains("artifact:"), "{joined}");
3527 assert!(joined.contains("error:"), "{joined}");
3528 assert!(joined.contains("phase Analyze failed"), "{joined}");
3529 assert!(
3530 joined.contains("fail") || joined.contains("timeout"),
3531 "{joined}"
3532 );
3533 }
3534
3535 #[test]
3536 fn direct_subagent_card_reuses_history_renderer() {
3537 let panel = WorkflowPanel::from_direct_subagent(
3538 "agent_abc",
3539 "explore",
3540 WorkflowPanelLifecycle::Succeeded,
3541 1_000,
3542 Some(4_500),
3543 Some("found 3 call sites".to_string()),
3544 None,
3545 );
3546 let compact = panel.render_history_card(100, false, &WorkflowHistoryExtras::default());
3547 let joined: String = compact
3548 .iter()
3549 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3550 .collect();
3551 assert!(
3552 joined.contains("success") || joined.contains("explore"),
3553 "{joined}"
3554 );
3555 assert!(joined.contains("1/1 done"), "{joined}");
3556 assert!(joined.contains("3s") || joined.contains("s"), "{joined}");
3557
3558 let expanded = panel.render_history_card(
3559 100,
3560 true,
3561 &WorkflowHistoryExtras {
3562 result_summary: Some("found 3 call sites".to_string()),
3563 ..WorkflowHistoryExtras::default()
3564 },
3565 );
3566 let joined: String = expanded
3567 .iter()
3568 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3569 .collect::<Vec<_>>()
3570 .join("\n");
3571 assert!(joined.contains("children:"), "{joined}");
3572 assert!(joined.contains("result:"), "{joined}");
3573 assert!(joined.contains("found 3 call sites"), "{joined}");
3574 assert!(!joined.contains("reasoning unknown"), "{joined}");
3575 assert!(!joined.contains("via unknown"), "{joined}");
3576 assert!(!joined.contains("tokens unknown"), "{joined}");
3577 assert!(
3578 joined.contains(crate::tui::shell_key_routing::tool_details_chord().as_ref()),
3579 "history details hint must use the platform chord: {joined}"
3580 );
3581 assert!(!joined.contains("details (v)"), "{joined}");
3582 }
3583
3584 #[test]
3585 fn from_run_json_round_trips_events_into_history_card() {
3586 let value = json!({
3587 "run_id": "workflow_demo",
3588 "status": "completed",
3589 "workflow_goal": "ship it",
3590 "started_at_ms": 1000,
3591 "completed_at_ms": 5000,
3592 "events": [
3593 {
3594 "type": "run_started",
3595 "at_ms": 1000,
3596 "run_id": "workflow_demo",
3597 "workflow_goal": "ship it"
3598 },
3599 {"type": "phase_started", "at_ms": 1100, "title": "Build"},
3600 {
3601 "type": "task_started",
3602 "at_ms": 1200,
3603 "task_id": "t1",
3604 "label": "compile",
3605 "profile": "implementer"
3606 },
3607 {
3608 "type": "task_completed",
3609 "at_ms": 4000,
3610 "task_id": "t1",
3611 "status": "succeeded"
3612 },
3613 {"type": "run_completed", "at_ms": 5000, "status": "completed"}
3614 ]
3615 });
3616 let panel = WorkflowPanel::from_run_json(&value).expect("hydrate");
3617 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Succeeded);
3618 let compact = panel.compact_summary_text(120);
3619 assert!(compact.contains("1/1 done"), "{compact}");
3620 assert!(compact.contains("success"), "{compact}");
3621 let expanded = panel.history_expanded_lines(120, &WorkflowHistoryExtras::default());
3622 let joined: String = expanded
3623 .iter()
3624 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3625 .collect::<Vec<_>>()
3626 .join("\n");
3627 assert!(joined.contains("goal:"), "{joined}");
3628 assert!(joined.contains("ship it"), "{joined}");
3629 assert!(joined.contains("Build"), "{joined}");
3630 assert!(joined.contains("compile"), "{joined}");
3631 }
3632
3633 // ── #4131 dogfood scenario projections ──────────────────────────────────
3634
3635 /// WF-A1: read-only repo audit — scout phase on main workspace, labeled
3636 /// children, no worktree marker, synthesizer phase present.
3637 #[test]
3638 fn dogfood_read_only_repo_audit_panel() {
3639 let mut panel = WorkflowPanel::new("wf_a1", "read-only repo audit", 1_000);
3640 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3641 title: "Scout".to_string(),
3642 at_ms: 1_100,
3643 });
3644 for (id, label, role) in [
3645 ("t1", "map crates", "explore"),
3646 ("t2", "scan unsafe", "explore"),
3647 ("t3", "scan unwrap", "explore"),
3648 ] {
3649 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3650 task_id: id.to_string(),
3651 label: Some(label.to_string()),
3652 profile: Some(role.to_string()),
3653 model: Some("flash".to_string()),
3654 strength: Some("low".to_string()),
3655 resolved_model: Some("deepseek-v4-flash".to_string()),
3656 worktree: false,
3657 workspace: None,
3658 route: Box::default(),
3659 at_ms: 1_200,
3660 });
3661 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3662 task_id: id.to_string(),
3663 status: WorkflowRowStatus::Succeeded,
3664 usage: None,
3665 reason: None,
3666 at_ms: 1_500,
3667 });
3668 }
3669 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3670 title: "Synthesize".to_string(),
3671 at_ms: 1_600,
3672 });
3673 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3674 task_id: "t4".to_string(),
3675 label: Some("audit summary".to_string()),
3676 profile: Some("general".to_string()),
3677 model: None,
3678 strength: None,
3679 resolved_model: None,
3680 worktree: false,
3681 workspace: None,
3682 route: Box::default(),
3683 at_ms: 1_700,
3684 });
3685 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3686 task_id: "t4".to_string(),
3687 status: WorkflowRowStatus::Succeeded,
3688 usage: None,
3689 reason: None,
3690 at_ms: 2_000,
3691 });
3692 panel.apply_event(WorkflowPanelEvent::RunCompleted {
3693 status: WorkflowPanelLifecycle::Succeeded,
3694 error: None,
3695 at_ms: 2_100,
3696 });
3697
3698 let header = panel.compact_summary_text(140);
3699 assert!(
3700 header.contains("success") || header.contains("completed"),
3701 "{header}"
3702 );
3703 assert!(!header.contains("fail"), "{header}");
3704 assert!(
3705 header.contains("4/") || header.contains("4 child") || header.contains("0/"),
3706 "{header}"
3707 );
3708
3709 // Selected phase is Synthesize; scout labels live in earlier phases.
3710 panel.selected_phase = 0;
3711 let scout_body = panel.render_history_card(120, true, &WorkflowHistoryExtras::default());
3712 let scout_joined: String = scout_body
3713 .iter()
3714 .map(|l| {
3715 l.spans
3716 .iter()
3717 .map(|s| s.content.as_ref())
3718 .collect::<String>()
3719 })
3720 .collect::<Vec<_>>()
3721 .join("\n");
3722 assert!(scout_joined.contains("map crates"), "{scout_joined}");
3723 assert!(
3724 !scout_joined.contains(" wt "),
3725 "read-only scouts stay on main: {scout_joined}"
3726 );
3727
3728 let card = panel.render_history_card(
3729 120,
3730 true,
3731 &WorkflowHistoryExtras {
3732 result_summary: Some("no critical issues".to_string()),
3733 ..WorkflowHistoryExtras::default()
3734 },
3735 );
3736 let card_text: String = card
3737 .iter()
3738 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3739 .collect::<Vec<_>>()
3740 .join("\n");
3741 assert!(
3742 card_text.contains("Scout") || card_text.contains("Synthesize"),
3743 "{card_text}"
3744 );
3745 assert!(card_text.contains("no critical issues"), "{card_text}");
3746 assert!(
3747 !card_text.to_ascii_lowercase().contains("unknown child"),
3748 "{card_text}"
3749 );
3750 }
3751
3752 /// WF-A2: staged bugfix — implementer worktree + verifier on main.
3753 #[test]
3754 fn dogfood_staged_worktree_implementer_verifier() {
3755 let mut panel = WorkflowPanel::new("wf_a2", "staged docs fix", 1_000);
3756 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3757 title: "Implement".to_string(),
3758 at_ms: 1_100,
3759 });
3760 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3761 task_id: "impl".to_string(),
3762 label: Some("implementer".to_string()),
3763 profile: Some("implementer".to_string()),
3764 model: Some("pro".to_string()),
3765 strength: None,
3766 resolved_model: Some("deepseek-v4-pro".to_string()),
3767 worktree: true,
3768 workspace: Some(PathBuf::from("/tmp/wt-impl")),
3769 route: Box::default(),
3770 at_ms: 1_200,
3771 });
3772 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3773 task_id: "impl".to_string(),
3774 status: WorkflowRowStatus::Succeeded,
3775 usage: None,
3776 reason: None,
3777 at_ms: 2_000,
3778 });
3779 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3780 title: "Verify".to_string(),
3781 at_ms: 2_100,
3782 });
3783 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3784 task_id: "ver".to_string(),
3785 label: Some("verifier".to_string()),
3786 profile: Some("verifier".to_string()),
3787 model: Some("flash".to_string()),
3788 strength: None,
3789 resolved_model: None,
3790 worktree: false,
3791 workspace: None,
3792 route: Box::default(),
3793 at_ms: 2_200,
3794 });
3795 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3796 task_id: "ver".to_string(),
3797 status: WorkflowRowStatus::Succeeded,
3798 usage: None,
3799 reason: None,
3800 at_ms: 3_000,
3801 });
3802 panel.apply_event(WorkflowPanelEvent::RunCompleted {
3803 status: WorkflowPanelLifecycle::Succeeded,
3804 error: None,
3805 at_ms: 3_100,
3806 });
3807
3808 assert_eq!(panel.phases.len(), 2);
3809 assert_eq!(panel.phases[0].title, "Implement");
3810 assert_eq!(panel.phases[1].title, "Verify");
3811
3812 panel.selected_phase = 0;
3813 let implement_body =
3814 panel.render_history_card(140, true, &WorkflowHistoryExtras::default());
3815 let impl_text: String = implement_body
3816 .iter()
3817 .map(|l| {
3818 l.spans
3819 .iter()
3820 .map(|s| s.content.as_ref())
3821 .collect::<String>()
3822 })
3823 .collect::<Vec<_>>()
3824 .join("\n");
3825 assert!(impl_text.contains("implementer"), "{impl_text}");
3826
3827 panel.selected_phase = 1;
3828 let verify_body = panel.render_history_card(140, true, &WorkflowHistoryExtras::default());
3829 let ver_text: String = verify_body
3830 .iter()
3831 .map(|l| {
3832 l.spans
3833 .iter()
3834 .map(|s| s.content.as_ref())
3835 .collect::<String>()
3836 })
3837 .collect::<Vec<_>>()
3838 .join("\n");
3839 assert!(ver_text.contains("verifier"), "{ver_text}");
3840 assert!(
3841 !ver_text.contains(" wt"),
3842 "verifier stays on main: {ver_text}"
3843 );
3844 }
3845
3846 /// WF-A3: partial failure + synthesis — fail count visible, summary card.
3847 #[test]
3848 fn dogfood_partial_failure_and_synthesis() {
3849 let mut panel = WorkflowPanel::new("wf_a3", "partial failure synthesis", 1_000);
3850 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3851 title: "Parallel scouts".to_string(),
3852 at_ms: 1_100,
3853 });
3854 for (id, label, status) in [
3855 ("a", "scout-a", WorkflowRowStatus::Succeeded),
3856 ("b", "scout-b-fail", WorkflowRowStatus::Failed),
3857 ("c", "scout-c", WorkflowRowStatus::Succeeded),
3858 ] {
3859 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3860 task_id: id.to_string(),
3861 label: Some(label.to_string()),
3862 profile: Some("explore".to_string()),
3863 model: None,
3864 strength: None,
3865 resolved_model: None,
3866 worktree: false,
3867 workspace: None,
3868 route: Box::default(),
3869 at_ms: 1_200,
3870 });
3871 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3872 task_id: id.to_string(),
3873 status,
3874 usage: None,
3875 reason: None,
3876 at_ms: 1_500,
3877 });
3878 }
3879 if let Some(row) = panel.find_row_mut("b") {
3880 row.error = Some("scout refused to produce summary".to_string());
3881 }
3882 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3883 title: "Synthesize".to_string(),
3884 at_ms: 1_600,
3885 });
3886 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3887 task_id: "syn".to_string(),
3888 label: Some("synthesizer".to_string()),
3889 profile: Some("general".to_string()),
3890 model: None,
3891 strength: None,
3892 resolved_model: None,
3893 worktree: false,
3894 workspace: None,
3895 route: Box::default(),
3896 at_ms: 1_700,
3897 });
3898 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3899 task_id: "syn".to_string(),
3900 status: WorkflowRowStatus::Succeeded,
3901 usage: None,
3902 reason: None,
3903 at_ms: 2_000,
3904 });
3905 // Partial success at run level: completed with surviving synthesis.
3906 panel.apply_event(WorkflowPanelEvent::RunCompleted {
3907 status: WorkflowPanelLifecycle::Succeeded,
3908 error: None,
3909 at_ms: 2_100,
3910 });
3911
3912 let (failed, cancelled) = panel.failure_cancel_counts();
3913 assert_eq!(failed, 1, "exactly one parallel slot failed");
3914 assert_eq!(cancelled, 0);
3915 let header = panel.compact_summary_text(140);
3916 assert!(header.contains("1 fail"), "{header}");
3917
3918 let card = panel.render_history_card(
3919 140,
3920 true,
3921 &WorkflowHistoryExtras {
3922 result_summary: Some("2/3 scouts ok; scout-b failed".to_string()),
3923 ..WorkflowHistoryExtras::default()
3924 },
3925 );
3926 let joined: String = card
3927 .iter()
3928 .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
3929 .collect::<Vec<_>>()
3930 .join("\n");
3931 assert!(
3932 joined.contains("scout-b-fail") || joined.contains("fail"),
3933 "{joined}"
3934 );
3935 assert!(joined.contains("2/3 scouts ok"), "{joined}");
3936 }
3937
3938 /// WF-A4: cancellation mid-run — running children cancelled, done preserved.
3939 #[test]
3940 fn dogfood_cancellation_mid_run() {
3941 let mut panel = WorkflowPanel::new("wf_a4", "cancel mid-run", 1_000);
3942 panel.apply_event(WorkflowPanelEvent::PhaseStarted {
3943 title: "Long work".to_string(),
3944 at_ms: 1_100,
3945 });
3946 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3947 task_id: "slow-1".to_string(),
3948 label: Some("slow-1".to_string()),
3949 profile: Some("explore".to_string()),
3950 model: None,
3951 strength: None,
3952 resolved_model: None,
3953 worktree: false,
3954 workspace: None,
3955 route: Box::default(),
3956 at_ms: 1_200,
3957 });
3958 panel.apply_event(WorkflowPanelEvent::TaskStarted {
3959 task_id: "slow-2".to_string(),
3960 label: Some("slow-2".to_string()),
3961 profile: Some("explore".to_string()),
3962 model: None,
3963 strength: None,
3964 resolved_model: None,
3965 worktree: false,
3966 workspace: None,
3967 route: Box::default(),
3968 at_ms: 1_210,
3969 });
3970 panel.apply_event(WorkflowPanelEvent::TaskCompleted {
3971 task_id: "slow-1".to_string(),
3972 status: WorkflowRowStatus::Succeeded,
3973 usage: None,
3974 reason: None,
3975 at_ms: 1_500,
3976 });
3977
3978 // A confirmed host interrupt finalizes remaining runners. The widget
3979 // itself never claims cancellation before that runtime event.
3980 panel.apply_event(WorkflowPanelEvent::RunCancelled {
3981 reason: "interrupted".to_string(),
3982 at_ms: now_ms(),
3983 });
3984 assert_eq!(panel.lifecycle, WorkflowPanelLifecycle::Cancelled);
3985
3986 let slow1 = panel
3987 .phases
3988 .iter()
3989 .flat_map(|p| p.rows.iter())
3990 .find(|r| r.task_id == "slow-1")
3991 .expect("slow-1");
3992 let slow2 = panel
3993 .phases
3994 .iter()
3995 .flat_map(|p| p.rows.iter())
3996 .find(|r| r.task_id == "slow-2")
3997 .expect("slow-2");
3998 assert_eq!(slow1.status, WorkflowRowStatus::Succeeded);
3999 assert_eq!(slow2.status, WorkflowRowStatus::Cancelled);
4000
4001 let (failed, cancelled) = panel.failure_cancel_counts();
4002 assert_eq!(failed, 0);
4003 assert_eq!(cancelled, 1);
4004 let header = panel.compact_summary_text(120);
4005 assert!(
4006 header.contains("cancel") || header.contains("cancelled"),
4007 "{header}"
4008 );
4009 }
4010 }
4011
4011 lines RUST