Skip to main content

trusty_code/
progress.rs

1//! Real-time phase progress streaming to the terminal (#149).
2//!
3//! Why: Workflow runs take 20–70 minutes and previously emitted nothing on
4//! stdout/stderr until the `observe` phase completed. Users had no signal that
5//! the harness was alive, which is terrible UX. Streaming a one-line summary
6//! per phase (and per code-wave) to stderr — colorized when stderr is a TTY —
7//! gives operators live progress without polluting stdout (which is reserved
8//! for the structured `--json` envelope).
9//!
10//! What: `ProgressReporter` is a tiny stderr-printer with three lifecycle
11//! hooks (`phase_start`, `phase_done`, `phase_failed`) plus a `wave_start` /
12//! `wave_done` pair for the code phase's per-wave loop and a final
13//! `workflow_done` summary. Output is pure stderr `eprintln!` — no logging
14//! framework, no allocations on the hot path beyond the formatted line.
15//!
16//! Test: see unit tests at the bottom of this file:
17//! - `progress_reporter_formats_phase_start`
18//! - `progress_reporter_formats_phase_done_no_color`
19
20use std::io::IsTerminal;
21use std::time::{Duration, Instant};
22
23/// ANSI color helpers used when stderr is a TTY. Plain strings otherwise.
24///
25/// Why: Colorizing only when the output is interactive avoids dumping escape
26/// codes into log files / CI captures while still giving humans a readable
27/// stream when running locally.
28/// What: `wrap` returns either `\x1b[<code>m{}\x1b[0m` or the original string
29/// based on `use_color`.
30fn wrap(use_color: bool, code: &str, s: &str) -> String {
31    if use_color {
32        format!("\x1b[{code}m{s}\x1b[0m")
33    } else {
34        s.to_string()
35    }
36}
37
38const COLOR_BOLD: &str = "1";
39const COLOR_DIM: &str = "2";
40const COLOR_GREEN: &str = "32";
41const COLOR_RED: &str = "31";
42const COLOR_CYAN: &str = "36";
43
44/// Streams human-readable progress lines to stderr while a workflow runs.
45///
46/// Why: A purpose-built reporter (vs. ad-hoc `eprintln!`s sprinkled in the
47/// engine) keeps the formatting in one place so the terminal output stays
48/// consistent across phases, waves, and failure paths.
49/// What: Stores the workflow start `Instant` so `workflow_done` can compute a
50/// total elapsed, plus a `use_color` flag captured once at construction.
51/// Test: `progress_reporter_formats_phase_start`,
52/// `progress_reporter_formats_phase_done_no_color`.
53pub struct ProgressReporter {
54    #[allow(dead_code)]
55    start: Instant,
56    use_color: bool,
57}
58
59impl Default for ProgressReporter {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl ProgressReporter {
66    /// Construct a reporter, detecting whether stderr is a TTY for color.
67    ///
68    /// Why: Avoid emitting ANSI codes when stderr is piped/captured.
69    /// What: Captures `Instant::now()` and `std::io::stderr().is_terminal()`.
70    /// Test: Indirect via formatting tests (force-disable color via `with_color`).
71    pub fn new() -> Self {
72        Self {
73            start: Instant::now(),
74            use_color: std::io::stderr().is_terminal(),
75        }
76    }
77
78    /// Force-set the color flag (used by tests for deterministic output).
79    #[allow(dead_code)]
80    pub fn with_color(mut self, use_color: bool) -> Self {
81        self.use_color = use_color;
82        self
83    }
84
85    /// Format a phase-start line. Public for testing; production paths call
86    /// `phase_start` which prints to stderr.
87    pub fn format_phase_start(&self, phase: &str) -> String {
88        let arrow = wrap(self.use_color, COLOR_CYAN, "▶");
89        let arrow = wrap(self.use_color, COLOR_DIM, &arrow);
90        let name = wrap(self.use_color, COLOR_BOLD, &format!("{phase:<10}"));
91        format!("[tcode] {arrow} {name} starting…")
92    }
93
94    /// Print "phase starting" to stderr.
95    pub fn phase_start(&self, phase: &str) {
96        eprintln!("\r{}", self.format_phase_start(phase));
97    }
98
99    /// Format a phase-done line.
100    pub fn format_phase_done(
101        &self,
102        phase: &str,
103        elapsed: Duration,
104        cost: f32,
105        note: Option<&str>,
106    ) -> String {
107        let check = wrap(self.use_color, COLOR_GREEN, "✓");
108        let name = wrap(self.use_color, COLOR_BOLD, &format!("{phase:<10}"));
109        let stats = format!("({}, ~${:.2})", format_duration(elapsed), cost);
110        let stats = wrap(self.use_color, COLOR_DIM, &stats);
111        match note {
112            Some(n) if !n.is_empty() => {
113                format!("[tcode] {check} {name} done  {stats} — {n}")
114            }
115            _ => format!("[tcode] {check} {name} done  {stats}"),
116        }
117    }
118
119    /// Print "phase done" to stderr, with elapsed time and cost.
120    pub fn phase_done(&self, phase: &str, elapsed: Duration, cost: f32, note: Option<&str>) {
121        eprintln!("\r{}", self.format_phase_done(phase, elapsed, cost, note));
122    }
123
124    /// Print "phase failed" to stderr with elapsed time and a short error.
125    pub fn phase_failed(&self, phase: &str, elapsed: Duration, error: &str) {
126        let cross = wrap(self.use_color, COLOR_RED, "✗");
127        let name = wrap(self.use_color, COLOR_BOLD, &format!("{phase:<10}"));
128        let stats = wrap(
129            self.use_color,
130            COLOR_DIM,
131            &format!("({})", format_duration(elapsed)),
132        );
133        // Truncate long errors to keep the line readable.
134        let short = error.lines().next().unwrap_or(error);
135        let short: String = short.chars().take(120).collect();
136        eprintln!("\r[tcode] {cross} {name} failed {stats} — {short}");
137    }
138
139    /// Print a "code wave starting" line for the wave-loop branch of the code
140    /// phase. The wave loop runs sequentially across multiple files; surfacing
141    /// per-wave progress prevents the code phase from looking stuck.
142    pub fn wave_start(&self, wave_index: usize, wave_total: usize, file_count: usize) {
143        let arrow = wrap(self.use_color, COLOR_DIM, "▶");
144        let name = wrap(self.use_color, COLOR_BOLD, "code      ");
145        eprintln!(
146            "\r[tcode] {arrow} {name} wave {wave_index}/{wave_total}  ({file_count} file{plural})",
147            plural = if file_count == 1 { "" } else { "s" },
148        );
149    }
150
151    /// Print a "code wave done" line. Symmetric counterpart to `wave_start`.
152    pub fn wave_done(&self, wave_index: usize, wave_total: usize, elapsed: Duration) {
153        let check = wrap(self.use_color, COLOR_GREEN, "✓");
154        let name = wrap(self.use_color, COLOR_BOLD, "code      ");
155        let stats = wrap(
156            self.use_color,
157            COLOR_DIM,
158            &format!("({})", format_duration(elapsed)),
159        );
160        eprintln!("\r[tcode] {check} {name} wave {wave_index}/{wave_total} done {stats}");
161    }
162
163    /// Print the final workflow-complete summary line.
164    pub fn workflow_done(&self, total_elapsed: Duration, total_cost: f32) {
165        let check = wrap(self.use_color, COLOR_GREEN, "✓");
166        let name = wrap(self.use_color, COLOR_BOLD, "workflow  ");
167        let stats = wrap(
168            self.use_color,
169            COLOR_DIM,
170            &format!(
171                "({}, ${:.2} total)",
172                format_duration(total_elapsed),
173                total_cost
174            ),
175        );
176        eprintln!("\r[tcode] {check} {name} complete  {stats}");
177    }
178
179    /// Workflow-level start time accessor (used by callers that want to show
180    /// the wall-clock elapsed alongside per-phase numbers).
181    #[allow(dead_code)]
182    pub fn workflow_started(&self) -> Instant {
183        self.start
184    }
185}
186
187/// Format a `Duration` as `MmSSs` for short runs and `Hh MmSSs` for long ones.
188///
189/// Why: Operators care about seconds for sub-minute phases and want to see
190/// minutes/seconds for long ones. Strict `secs.millis` is not friendly when a
191/// phase runs for several minutes.
192/// What: `42s`, `3m12s`, `1h05m12s`.
193/// Test: `format_duration_renders_human_friendly`.
194pub fn format_duration(d: Duration) -> String {
195    let total = d.as_secs();
196    let h = total / 3600;
197    let m = (total % 3600) / 60;
198    let s = total % 60;
199    if h > 0 {
200        format!("{h}h{m:02}m{s:02}s")
201    } else if m > 0 {
202        format!("{m}m{s:02}s")
203    } else {
204        format!("{s}s")
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn progress_reporter_formats_phase_start() {
214        let r = ProgressReporter::new().with_color(false);
215        let s = r.format_phase_start("research");
216        assert!(s.contains("research"), "got: {s}");
217        assert!(s.contains("starting"), "got: {s}");
218        assert!(s.starts_with("[tcode]"), "got: {s}");
219        // No ANSI when color disabled.
220        assert!(!s.contains("\x1b["), "expected no ANSI in: {s}");
221    }
222
223    #[test]
224    fn progress_reporter_formats_phase_done_no_color() {
225        let r = ProgressReporter::new().with_color(false);
226        let s = r.format_phase_done("plan", Duration::from_secs(18), 0.04, None);
227        assert!(s.contains("plan"), "got: {s}");
228        assert!(s.contains("done"), "got: {s}");
229        assert!(s.contains("18s"), "got: {s}");
230        assert!(s.contains("$0.04"), "got: {s}");
231        assert!(!s.contains("\x1b["), "expected no ANSI in: {s}");
232    }
233
234    #[test]
235    fn progress_reporter_phase_done_includes_note() {
236        let r = ProgressReporter::new().with_color(false);
237        let s = r.format_phase_done("qa", Duration::from_secs(28), 0.09, Some("35/35 passed"));
238        assert!(s.contains("35/35 passed"), "got: {s}");
239    }
240
241    #[test]
242    fn progress_reporter_uses_color_when_enabled() {
243        let r = ProgressReporter::new().with_color(true);
244        let s = r.format_phase_start("research");
245        assert!(s.contains("\x1b["), "expected ANSI in: {s}");
246    }
247
248    #[test]
249    fn format_duration_renders_human_friendly() {
250        assert_eq!(format_duration(Duration::from_secs(42)), "42s");
251        assert_eq!(format_duration(Duration::from_secs(192)), "3m12s");
252        assert_eq!(format_duration(Duration::from_secs(3912)), "1h05m12s");
253        assert_eq!(format_duration(Duration::from_secs(0)), "0s");
254    }
255}