Skip to main content

limitless_cli/modules/
progress.rs

1//! Animated progress indicators for Limitless CLI.
2//!
3//! [`show_progress`] drives either an indeterminate **spinner** (unknown
4//! total) or a determinate **progress bar** measured in steps. The animation
5//! runs on a background Tokio task so the caller can keep working without
6//! blocking; every frame replaces the previous line in place with ANSI
7//! cursor/erase escapes, which keeps the UI flicker-free.
8//!
9//! # Usage
10//!
11//! Spinner for indeterminate work (e.g. stack detection):
12//!
13//! ```
14//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
15//! use limitless_cli::modules::progress::show_progress;
16//!
17//! let progress = show_progress("Detecting stack...", 0);
18//! // ... do the work ...
19//! progress.finish("Stack detected: Node.js v18.12.0").await;
20//! # });
21//! ```
22//!
23//! Progress bar for step-by-step work (e.g. diagnostics with a known count):
24//!
25//! ```
26//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
27//! use limitless_cli::modules::progress::show_progress;
28//!
29//! let progress = show_progress("Running diagnostics...", 4);
30//! for _ in 0..4 {
31//!     progress.advance();
32//! }
33//! progress.finish("Diagnostics complete").await;
34//! # });
35//! ```
36//!
37//! [`show_progress`] requires an active Tokio runtime (the CLI runs inside
38//! `#[tokio::main]`). Dropping an unfinished handle aborts the animation and
39//! clears its line.
40
41use colored::Colorize;
42use std::io::Write;
43use std::sync::atomic::{AtomicU32, Ordering};
44use std::sync::{Arc, Mutex};
45use std::time::Duration;
46use tokio::sync::watch;
47use tokio::task::JoinHandle;
48
49/// Shared output target for the animator task and the handle's `Drop`, so the
50/// progress line can always be cleaned up by whoever finishes the animation.
51type SharedWriter = Arc<Mutex<Box<dyn Write + Send>>>;
52
53/// How long each animation frame stays on screen (braille spinner + bar).
54pub const ANIMATION_INTERVAL: Duration = Duration::from_millis(200);
55
56/// Braille spinner frames, rotated in order every [`ANIMATION_INTERVAL`].
57pub const SPINNER_FRAMES: [char; 4] = ['⠋', '⠙', '⠹', '⠸'];
58
59/// Number of cells in the progress bar between the brackets.
60pub const BAR_WIDTH: usize = 20;
61
62/// What kind of animation [`show_progress`] should drive.
63#[derive(Debug, Clone, Copy)]
64enum Mode {
65    /// Indeterminate; renders rotating spinner frames.
66    Spinner,
67    /// Determinate; renders a bar across `total` steps.
68    Bar { total: u32 },
69}
70
71/// Message sent between a [`Progress`] handle and its animator task.
72#[derive(Debug, Clone)]
73enum Status {
74    /// Animation is running.
75    Running,
76    /// Finished successfully; contains the checkmark text.
77    Complete(String),
78    /// Cancelled by the caller.
79    Aborted,
80}
81
82/// Renders one spinner line for `frame_index`, erasing the line first.
83///
84/// ```
85/// use limitless_cli::modules::progress::{SPINNER_FRAMES, spinner_line};
86///
87/// assert_eq!(SPINNER_FRAMES.len(), 4);
88/// assert!(spinner_line("Detecting stack...", 0).ends_with("⠋"));
89/// assert!(spinner_line("Detecting stack...", 1).ends_with("⠙"));
90/// assert!(spinner_line("Detecting stack...", 4).ends_with("⠋")); // wraps
91/// ```
92pub fn spinner_line(message: &str, frame_index: usize) -> String {
93    let frame = SPINNER_FRAMES[frame_index % SPINNER_FRAMES.len()];
94    format!("\r\x1b[2K{message} {frame}")
95}
96
97/// Renders one determinate progress-bar line for `step` of `total`.
98///
99/// `step` and `total` are clamped so the bar always stays within `[0, 100]%`.
100///
101/// ```
102/// use limitless_cli::modules::progress::{BAR_WIDTH, bar_line};
103///
104/// let line = bar_line("Running diagnostics...", 8, 20);
105/// assert!(line.ends_with("] 40%"));
106/// let filled = line.matches('█').count();
107/// assert_eq!(filled, 8);
108/// assert_eq!(filled + line.matches('░').count(), BAR_WIDTH);
109/// assert!(bar_line("Running diagnostics...", 99, 20).ends_with("100%"));
110/// ```
111pub fn bar_line(message: &str, step: u32, total: u32) -> String {
112    let total = total.max(1);
113    let step = step.min(total);
114    let percent = step * 100 / total;
115    let filled = (step as usize * BAR_WIDTH / total as usize).min(BAR_WIDTH);
116    let empty = BAR_WIDTH - filled;
117    let bar = format!("{}{}", "█".repeat(filled), "░".repeat(empty));
118    format!("\r\x1b[2K{message} [{bar}] {percent}%")
119}
120
121/// Starts an animated progress indicator on a background Tokio task.
122///
123/// - `total_steps == 0` → spinner mode (indeterminate).
124/// - `total_steps > 0`  → progress-bar mode, split across that many steps.
125///
126/// The caller performs its work while the animation runs and then calls
127/// [`Progress::finish`] to stop animating and print a `✓` completion line.
128/// `finish` (or an explicit [`Progress::abort`]) clears the progress line and
129/// restores the cursor, so nothing is left behind on screen.
130pub fn show_progress(message: &str, total_steps: u32) -> Progress {
131    show_progress_with(
132        message,
133        total_steps,
134        ANIMATION_INTERVAL,
135        Box::new(std::io::stdout()),
136    )
137}
138
139/// Internal constructor: lets tests supply a short interval and a capturing
140/// writer instead of the real terminal.
141fn show_progress_with(
142    message: &str,
143    total_steps: u32,
144    interval: Duration,
145    writer: Box<dyn Write + Send>,
146) -> Progress {
147    let (status_tx, status_rx) = watch::channel(Status::Running);
148    let step = Arc::new(AtomicU32::new(0));
149    let mode = if total_steps == 0 {
150        Mode::Spinner
151    } else {
152        Mode::Bar { total: total_steps }
153    };
154    let writer: SharedWriter = Arc::new(Mutex::new(writer));
155    let task = tokio::spawn(animator(
156        message.to_string(),
157        mode,
158        interval,
159        status_rx,
160        Arc::clone(&step),
161        Arc::clone(&writer),
162    ));
163    Progress {
164        task: Some(task),
165        status: status_tx,
166        step,
167        writer,
168        finished: false,
169    }
170}
171
172/// Handle returned by [`show_progress`].
173pub struct Progress {
174    task: Option<JoinHandle<()>>,
175    status: watch::Sender<Status>,
176    step: Arc<AtomicU32>,
177    writer: SharedWriter,
178    finished: bool,
179}
180
181impl Progress {
182    /// Advances a determinate bar by one step and returns the new step count.
183    pub fn advance(&self) -> u32 {
184        self.step.fetch_add(1, Ordering::Relaxed) + 1
185    }
186
187    /// Sets a determinate bar to an exact step count.
188    pub fn step_to(&self, step: u32) {
189        self.step.store(step, Ordering::Relaxed);
190    }
191
192    /// Stops the animation, clears its line and prints a `✓` completion line.
193    ///
194    /// The animator task renders the checkmark itself, so the progress line
195    /// and the completion can never interleave.
196    pub async fn finish(mut self, completion: impl Into<String>) {
197        self.finished = true;
198        let _ = self.status.send(Status::Complete(completion.into()));
199        if let Some(task) = self.task.take() {
200            let _ = task.await;
201        }
202    }
203
204    /// Stops the animation and clears its line without printing a completion.
205    pub async fn abort(mut self) {
206        self.finished = true;
207        let _ = self.status.send(Status::Aborted);
208        if let Some(task) = self.task.take() {
209            let _ = task.await;
210        }
211    }
212}
213
214impl Drop for Progress {
215    fn drop(&mut self) {
216        if self.finished {
217            return;
218        }
219        let _ = self.status.send(Status::Aborted);
220        if let Some(task) = self.task.take() {
221            task.abort();
222        }
223        // Ensure the line is always left clean even if the task was mid-sleep.
224        if let Ok(mut writer) = self.writer.lock() {
225            let _ = writer.write_all(b"\r\x1b[2K\x1b[?25h");
226        }
227    }
228}
229
230/// The background animation loop.
231///
232/// It is the *only* writer of the progress line: it hides the cursor once,
233/// redraws the line in place every `interval`, and on completion erases the
234/// line (and prints the checkmark) before showing the cursor again.
235async fn animator(
236    message: String,
237    mode: Mode,
238    interval: Duration,
239    mut status: watch::Receiver<Status>,
240    step: Arc<AtomicU32>,
241    writer: SharedWriter,
242) {
243    let _ = writer.lock().unwrap().write_all(b"\x1b[?25l");
244    let mut frame = 0usize;
245    loop {
246        tokio::select! {
247            _ = status.changed() => break,
248            _ = tokio::time::sleep(interval) => {
249                let line = match &mode {
250                    Mode::Spinner => spinner_line(&message, frame),
251                    Mode::Bar { total } => bar_line(
252                        &message,
253                        step.load(Ordering::Relaxed).min(*total),
254                        *total,
255                    ),
256                };
257                let mut out = writer.lock().unwrap();
258                let _ = out.write_all(line.as_bytes());
259                let _ = out.flush();
260                frame += 1;
261            }
262        }
263    }
264    {
265        let mut out = writer.lock().unwrap();
266        let _ = out.write_all(b"\r\x1b[2K");
267        if let Status::Complete(completion) = status.borrow().clone() {
268            let _ = writeln!(out, "{} {completion}", "✓".green());
269        }
270        let _ = out.write_all(b"\x1b[?25h");
271        let _ = out.flush();
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use std::io;
279
280    /// Short interval so animation tests run in a few tens of milliseconds.
281    const TICK: Duration = Duration::from_millis(5);
282
283    /// A [`Write`] target that records bytes for later inspection.
284    #[derive(Debug, Default, Clone)]
285    struct SharedBuffer(Arc<Mutex<Vec<u8>>>);
286
287    impl SharedBuffer {
288        fn text(&self) -> String {
289            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
290        }
291    }
292
293    impl Write for SharedBuffer {
294        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
295            self.0.lock().unwrap().extend_from_slice(buf);
296            Ok(buf.len())
297        }
298
299        fn flush(&mut self) -> io::Result<()> {
300            Ok(())
301        }
302    }
303
304    // ------------------------------------------------------------------
305    // Pure rendering
306    // ------------------------------------------------------------------
307
308    #[test]
309    fn spinner_frames_rotate_through_the_braille_cycle() {
310        assert_eq!(SPINNER_FRAMES, ['⠋', '⠙', '⠹', '⠸']);
311    }
312
313    #[test]
314    fn spinner_line_erases_and_cycles_per_frame() {
315        assert_eq!(
316            spinner_line("Detecting stack...", 0),
317            "\r\x1b[2KDetecting stack... ⠋"
318        );
319        assert_eq!(
320            spinner_line("Detecting stack...", 1),
321            "\r\x1b[2KDetecting stack... ⠙"
322        );
323        assert_eq!(
324            spinner_line("Detecting stack...", 4),
325            "\r\x1b[2KDetecting stack... ⠋"
326        );
327    }
328
329    #[test]
330    fn bar_line_renders_exact_width_and_percent() {
331        let line = bar_line("Running diagnostics...", 8, 20);
332        assert!(line.starts_with("\r\x1b[2KRunning diagnostics... "));
333        assert!(line.ends_with("] 40%"), "8/20 must read 40%, got: {line}");
334
335        // The leading `\r\x1b[2K` also contains a `[` (escape sequence), so
336        // resolve the bar as everything between the *last* `[` and first `]`.
337        let open = line.rfind('[').unwrap();
338        let close = line.find(']').unwrap();
339        let bar = &line[open + 1..close];
340        assert_eq!(
341            bar.chars().count(),
342            BAR_WIDTH,
343            "bar must fill {BAR_WIDTH} cells"
344        );
345        assert_eq!(
346            bar.chars().filter(|&c| c == '█').count(),
347            8,
348            "8 of 20 cells filled at 40%"
349        );
350        assert_eq!(
351            bar.chars().filter(|&c| c == '░').count(),
352            BAR_WIDTH - 8,
353            "the rest of the bar stays empty"
354        );
355    }
356
357    #[test]
358    fn bar_line_clamps_step_to_100_percent() {
359        let line = bar_line("Running diagnostics...", 99, 20);
360        assert!(line.ends_with("100%"));
361        assert!(line.contains(&"█".repeat(BAR_WIDTH)));
362        assert!(!line.contains('░'));
363    }
364
365    #[test]
366    fn bar_line_zero_step_is_empty_and_guards_zero_total() {
367        assert!(bar_line("Running diagnostics...", 0, 20).contains(&"░".repeat(BAR_WIDTH)));
368        assert!(bar_line("Running diagnostics...", 0, 0).ends_with("0%"));
369    }
370
371    // ------------------------------------------------------------------
372    // Async animation lifecycle
373    // ------------------------------------------------------------------
374
375    #[tokio::test]
376    async fn spinner_rotates_and_finish_prints_checkmark_with_cleanup() {
377        let buf = SharedBuffer::default();
378        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
379        tokio::time::sleep(Duration::from_millis(120)).await;
380        progress.finish("Stack detected: Node.js v18.12.0").await;
381
382        let out = buf.text();
383        // Cursor hidden at the start...
384        assert!(out.starts_with("\x1b[?25l"));
385        // ...several distinct frames rotated...
386        let seen: Vec<char> = SPINNER_FRAMES
387            .iter()
388            .copied()
389            .filter(|f| out.contains(*f))
390            .collect();
391        assert!(
392            seen.len() >= 2,
393            "expected several rotation frames, saw {seen:?}"
394        );
395        // ...and the line was erased before the checkmark, cursor restored.
396        assert!(out.contains("\r\x1b[2K✓ Stack detected: Node.js v18.12.0"));
397        assert!(out.ends_with("\x1b[?25h"), "cursor must be restored");
398    }
399
400    #[tokio::test]
401    async fn bar_advances_step_by_step_towards_completion() {
402        let buf = SharedBuffer::default();
403        let progress = show_progress_with("Running diagnostics...", 4, TICK, Box::new(buf.clone()));
404        tokio::time::sleep(Duration::from_millis(20)).await;
405        progress.advance(); // 1/4 → 25%
406        tokio::time::sleep(Duration::from_millis(20)).await;
407        progress.advance(); // 2/4 → 50%
408        tokio::time::sleep(Duration::from_millis(20)).await;
409        progress.finish("Diagnostics complete").await;
410
411        let out = buf.text();
412        assert!(out.contains("25%"), "second frame should show 25%");
413        assert!(out.contains("50%"), "later frames should show 50%");
414        assert!(!out.contains("100%"));
415        assert!(out.contains("\r\x1b[2K✓ Diagnostics complete"));
416        assert!(out.ends_with("\x1b[?25h"));
417    }
418
419    #[tokio::test]
420    async fn abort_cleans_up_without_printing_checkmark() {
421        let buf = SharedBuffer::default();
422        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
423        tokio::time::sleep(Duration::from_millis(15)).await;
424        progress.abort().await;
425
426        let out = buf.text();
427        assert!(!out.contains('✓'));
428        assert!(out.ends_with("\x1b[?25h"));
429        assert!(out.contains("\x1b[2K"));
430    }
431
432    #[tokio::test]
433    async fn dropping_unfinished_handle_aborts_and_cleans_line() {
434        let buf = SharedBuffer::default();
435        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
436        tokio::time::sleep(Duration::from_millis(15)).await;
437        drop(progress);
438
439        let out = buf.text();
440        assert!(
441            out.ends_with("\r\x1b[2K\x1b[?25h"),
442            "drop must clear the line"
443        );
444    }
445
446    #[tokio::test]
447    async fn finish_before_first_frame_still_prints_clean_completion() {
448        let buf = SharedBuffer::default();
449        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
450        progress.finish("Stack detected: Rust v1.98.0").await;
451
452        let out = buf.text();
453        assert!(out.contains("\r\x1b[2K✓ Stack detected: Rust v1.98.0"));
454        assert!(out.ends_with("\x1b[?25h"));
455    }
456
457    #[test]
458    fn test_progress_bar_accuracy() {
459        let line = bar_line("Scanning", 5, 10);
460        assert!(line.starts_with("\r\x1b[2K"), "got: {line}");
461        assert!(line.contains("Scanning ["));
462        let filled = line.matches('█').count();
463        let empty = line.matches('░').count();
464        assert_eq!(filled + empty, BAR_WIDTH, "bar must fill BAR_WIDTH");
465        assert_eq!(filled, BAR_WIDTH / 2, "5/10 must fill half the bar");
466        assert!(line.ends_with("50%"));
467
468        assert_eq!(bar_line("Scanning", 0, 10).matches('█').count(), 0);
469        assert_eq!(
470            bar_line("Scanning", 0, 10).matches('░').count(),
471            BAR_WIDTH
472        );
473        assert!(bar_line("Scanning", 10, 10).ends_with("100%"));
474        assert_eq!(bar_line("Scanning", 10, 10).matches('█').count(), BAR_WIDTH);
475
476        // Steps above the total clamp to 100%.
477        assert!(bar_line("Scanning", 99, 20).ends_with("100%"));
478
479        // Degenerate totals never panic.
480        assert!(bar_line("Scanning", 1, 0).ends_with("100%"));
481    }
482}