limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Animated progress indicators for Limitless CLI.
//!
//! [`show_progress`] drives either an indeterminate **spinner** (unknown
//! total) or a determinate **progress bar** measured in steps. The animation
//! runs on a background Tokio task so the caller can keep working without
//! blocking; every frame replaces the previous line in place with ANSI
//! cursor/erase escapes, which keeps the UI flicker-free.
//!
//! # Usage
//!
//! Spinner for indeterminate work (e.g. stack detection):
//!
//! ```
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! use limitless_cli::modules::progress::show_progress;
//!
//! let progress = show_progress("Detecting stack...", 0);
//! // ... do the work ...
//! progress.finish("Stack detected: Node.js v18.12.0").await;
//! # });
//! ```
//!
//! Progress bar for step-by-step work (e.g. diagnostics with a known count):
//!
//! ```
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! use limitless_cli::modules::progress::show_progress;
//!
//! let progress = show_progress("Running diagnostics...", 4);
//! for _ in 0..4 {
//!     progress.advance();
//! }
//! progress.finish("Diagnostics complete").await;
//! # });
//! ```
//!
//! [`show_progress`] requires an active Tokio runtime (the CLI runs inside
//! `#[tokio::main]`). Dropping an unfinished handle aborts the animation and
//! clears its line.

use colored::Colorize;
use std::io::Write;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::watch;
use tokio::task::JoinHandle;

/// Shared output target for the animator task and the handle's `Drop`, so the
/// progress line can always be cleaned up by whoever finishes the animation.
type SharedWriter = Arc<Mutex<Box<dyn Write + Send>>>;

/// How long each animation frame stays on screen (braille spinner + bar).
pub const ANIMATION_INTERVAL: Duration = Duration::from_millis(200);

/// Braille spinner frames, rotated in order every [`ANIMATION_INTERVAL`].
pub const SPINNER_FRAMES: [char; 4] = ['⠋', '⠙', '⠹', '⠸'];

/// Number of cells in the progress bar between the brackets.
pub const BAR_WIDTH: usize = 20;

/// What kind of animation [`show_progress`] should drive.
#[derive(Debug, Clone, Copy)]
enum Mode {
    /// Indeterminate; renders rotating spinner frames.
    Spinner,
    /// Determinate; renders a bar across `total` steps.
    Bar { total: u32 },
}

/// Message sent between a [`Progress`] handle and its animator task.
#[derive(Debug, Clone)]
enum Status {
    /// Animation is running.
    Running,
    /// Finished successfully; contains the checkmark text.
    Complete(String),
    /// Cancelled by the caller.
    Aborted,
}

/// Renders one spinner line for `frame_index`, erasing the line first.
///
/// ```
/// use limitless_cli::modules::progress::{SPINNER_FRAMES, spinner_line};
///
/// assert_eq!(SPINNER_FRAMES.len(), 4);
/// assert!(spinner_line("Detecting stack...", 0).ends_with("⠋"));
/// assert!(spinner_line("Detecting stack...", 1).ends_with("⠙"));
/// assert!(spinner_line("Detecting stack...", 4).ends_with("⠋")); // wraps
/// ```
pub fn spinner_line(message: &str, frame_index: usize) -> String {
    let frame = SPINNER_FRAMES[frame_index % SPINNER_FRAMES.len()];
    format!("\r\x1b[2K{message} {frame}")
}

/// Renders one determinate progress-bar line for `step` of `total`.
///
/// `step` and `total` are clamped so the bar always stays within `[0, 100]%`.
///
/// ```
/// use limitless_cli::modules::progress::{BAR_WIDTH, bar_line};
///
/// let line = bar_line("Running diagnostics...", 8, 20);
/// assert!(line.ends_with("] 40%"));
/// let filled = line.matches('█').count();
/// assert_eq!(filled, 8);
/// assert_eq!(filled + line.matches('░').count(), BAR_WIDTH);
/// assert!(bar_line("Running diagnostics...", 99, 20).ends_with("100%"));
/// ```
pub fn bar_line(message: &str, step: u32, total: u32) -> String {
    let total = total.max(1);
    let step = step.min(total);
    let percent = step * 100 / total;
    let filled = (step as usize * BAR_WIDTH / total as usize).min(BAR_WIDTH);
    let empty = BAR_WIDTH - filled;
    let bar = format!("{}{}", "█".repeat(filled), "░".repeat(empty));
    format!("\r\x1b[2K{message} [{bar}] {percent}%")
}

/// Starts an animated progress indicator on a background Tokio task.
///
/// - `total_steps == 0` → spinner mode (indeterminate).
/// - `total_steps > 0`  → progress-bar mode, split across that many steps.
///
/// The caller performs its work while the animation runs and then calls
/// [`Progress::finish`] to stop animating and print a `✓` completion line.
/// `finish` (or an explicit [`Progress::abort`]) clears the progress line and
/// restores the cursor, so nothing is left behind on screen.
pub fn show_progress(message: &str, total_steps: u32) -> Progress {
    show_progress_with(
        message,
        total_steps,
        ANIMATION_INTERVAL,
        Box::new(std::io::stdout()),
    )
}

/// Internal constructor: lets tests supply a short interval and a capturing
/// writer instead of the real terminal.
fn show_progress_with(
    message: &str,
    total_steps: u32,
    interval: Duration,
    writer: Box<dyn Write + Send>,
) -> Progress {
    let (status_tx, status_rx) = watch::channel(Status::Running);
    let step = Arc::new(AtomicU32::new(0));
    let mode = if total_steps == 0 {
        Mode::Spinner
    } else {
        Mode::Bar { total: total_steps }
    };
    let writer: SharedWriter = Arc::new(Mutex::new(writer));
    let task = tokio::spawn(animator(
        message.to_string(),
        mode,
        interval,
        status_rx,
        Arc::clone(&step),
        Arc::clone(&writer),
    ));
    Progress {
        task: Some(task),
        status: status_tx,
        step,
        writer,
        finished: false,
    }
}

/// Handle returned by [`show_progress`].
pub struct Progress {
    task: Option<JoinHandle<()>>,
    status: watch::Sender<Status>,
    step: Arc<AtomicU32>,
    writer: SharedWriter,
    finished: bool,
}

impl Progress {
    /// Advances a determinate bar by one step and returns the new step count.
    pub fn advance(&self) -> u32 {
        self.step.fetch_add(1, Ordering::Relaxed) + 1
    }

    /// Sets a determinate bar to an exact step count.
    pub fn step_to(&self, step: u32) {
        self.step.store(step, Ordering::Relaxed);
    }

    /// Stops the animation, clears its line and prints a `✓` completion line.
    ///
    /// The animator task renders the checkmark itself, so the progress line
    /// and the completion can never interleave.
    pub async fn finish(mut self, completion: impl Into<String>) {
        self.finished = true;
        let _ = self.status.send(Status::Complete(completion.into()));
        if let Some(task) = self.task.take() {
            let _ = task.await;
        }
    }

    /// Stops the animation and clears its line without printing a completion.
    pub async fn abort(mut self) {
        self.finished = true;
        let _ = self.status.send(Status::Aborted);
        if let Some(task) = self.task.take() {
            let _ = task.await;
        }
    }
}

impl Drop for Progress {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        let _ = self.status.send(Status::Aborted);
        if let Some(task) = self.task.take() {
            task.abort();
        }
        // Ensure the line is always left clean even if the task was mid-sleep.
        if let Ok(mut writer) = self.writer.lock() {
            let _ = writer.write_all(b"\r\x1b[2K\x1b[?25h");
        }
    }
}

/// The background animation loop.
///
/// It is the *only* writer of the progress line: it hides the cursor once,
/// redraws the line in place every `interval`, and on completion erases the
/// line (and prints the checkmark) before showing the cursor again.
async fn animator(
    message: String,
    mode: Mode,
    interval: Duration,
    mut status: watch::Receiver<Status>,
    step: Arc<AtomicU32>,
    writer: SharedWriter,
) {
    let _ = writer.lock().unwrap().write_all(b"\x1b[?25l");
    let mut frame = 0usize;
    loop {
        tokio::select! {
            _ = status.changed() => break,
            _ = tokio::time::sleep(interval) => {
                let line = match &mode {
                    Mode::Spinner => spinner_line(&message, frame),
                    Mode::Bar { total } => bar_line(
                        &message,
                        step.load(Ordering::Relaxed).min(*total),
                        *total,
                    ),
                };
                let mut out = writer.lock().unwrap();
                let _ = out.write_all(line.as_bytes());
                let _ = out.flush();
                frame += 1;
            }
        }
    }
    {
        let mut out = writer.lock().unwrap();
        let _ = out.write_all(b"\r\x1b[2K");
        if let Status::Complete(completion) = status.borrow().clone() {
            let _ = writeln!(out, "{} {completion}", "✓".green());
        }
        let _ = out.write_all(b"\x1b[?25h");
        let _ = out.flush();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    /// Short interval so animation tests run in a few tens of milliseconds.
    const TICK: Duration = Duration::from_millis(5);

    /// A [`Write`] target that records bytes for later inspection.
    #[derive(Debug, Default, Clone)]
    struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

    impl SharedBuffer {
        fn text(&self) -> String {
            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
        }
    }

    impl Write for SharedBuffer {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    // ------------------------------------------------------------------
    // Pure rendering
    // ------------------------------------------------------------------

    #[test]
    fn spinner_frames_rotate_through_the_braille_cycle() {
        assert_eq!(SPINNER_FRAMES, ['⠋', '⠙', '⠹', '⠸']);
    }

    #[test]
    fn spinner_line_erases_and_cycles_per_frame() {
        assert_eq!(
            spinner_line("Detecting stack...", 0),
            "\r\x1b[2KDetecting stack... ⠋"
        );
        assert_eq!(
            spinner_line("Detecting stack...", 1),
            "\r\x1b[2KDetecting stack... ⠙"
        );
        assert_eq!(
            spinner_line("Detecting stack...", 4),
            "\r\x1b[2KDetecting stack... ⠋"
        );
    }

    #[test]
    fn bar_line_renders_exact_width_and_percent() {
        let line = bar_line("Running diagnostics...", 8, 20);
        assert!(line.starts_with("\r\x1b[2KRunning diagnostics... "));
        assert!(line.ends_with("] 40%"), "8/20 must read 40%, got: {line}");

        // The leading `\r\x1b[2K` also contains a `[` (escape sequence), so
        // resolve the bar as everything between the *last* `[` and first `]`.
        let open = line.rfind('[').unwrap();
        let close = line.find(']').unwrap();
        let bar = &line[open + 1..close];
        assert_eq!(
            bar.chars().count(),
            BAR_WIDTH,
            "bar must fill {BAR_WIDTH} cells"
        );
        assert_eq!(
            bar.chars().filter(|&c| c == '█').count(),
            8,
            "8 of 20 cells filled at 40%"
        );
        assert_eq!(
            bar.chars().filter(|&c| c == '░').count(),
            BAR_WIDTH - 8,
            "the rest of the bar stays empty"
        );
    }

    #[test]
    fn bar_line_clamps_step_to_100_percent() {
        let line = bar_line("Running diagnostics...", 99, 20);
        assert!(line.ends_with("100%"));
        assert!(line.contains(&"█".repeat(BAR_WIDTH)));
        assert!(!line.contains('░'));
    }

    #[test]
    fn bar_line_zero_step_is_empty_and_guards_zero_total() {
        assert!(bar_line("Running diagnostics...", 0, 20).contains(&"░".repeat(BAR_WIDTH)));
        assert!(bar_line("Running diagnostics...", 0, 0).ends_with("0%"));
    }

    // ------------------------------------------------------------------
    // Async animation lifecycle
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn spinner_rotates_and_finish_prints_checkmark_with_cleanup() {
        let buf = SharedBuffer::default();
        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
        tokio::time::sleep(Duration::from_millis(120)).await;
        progress.finish("Stack detected: Node.js v18.12.0").await;

        let out = buf.text();
        // Cursor hidden at the start...
        assert!(out.starts_with("\x1b[?25l"));
        // ...several distinct frames rotated...
        let seen: Vec<char> = SPINNER_FRAMES
            .iter()
            .copied()
            .filter(|f| out.contains(*f))
            .collect();
        assert!(
            seen.len() >= 2,
            "expected several rotation frames, saw {seen:?}"
        );
        // ...and the line was erased before the checkmark, cursor restored.
        assert!(out.contains("\r\x1b[2K✓ Stack detected: Node.js v18.12.0"));
        assert!(out.ends_with("\x1b[?25h"), "cursor must be restored");
    }

    #[tokio::test]
    async fn bar_advances_step_by_step_towards_completion() {
        let buf = SharedBuffer::default();
        let progress = show_progress_with("Running diagnostics...", 4, TICK, Box::new(buf.clone()));
        tokio::time::sleep(Duration::from_millis(20)).await;
        progress.advance(); // 1/4 → 25%
        tokio::time::sleep(Duration::from_millis(20)).await;
        progress.advance(); // 2/4 → 50%
        tokio::time::sleep(Duration::from_millis(20)).await;
        progress.finish("Diagnostics complete").await;

        let out = buf.text();
        assert!(out.contains("25%"), "second frame should show 25%");
        assert!(out.contains("50%"), "later frames should show 50%");
        assert!(!out.contains("100%"));
        assert!(out.contains("\r\x1b[2K✓ Diagnostics complete"));
        assert!(out.ends_with("\x1b[?25h"));
    }

    #[tokio::test]
    async fn abort_cleans_up_without_printing_checkmark() {
        let buf = SharedBuffer::default();
        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
        tokio::time::sleep(Duration::from_millis(15)).await;
        progress.abort().await;

        let out = buf.text();
        assert!(!out.contains('✓'));
        assert!(out.ends_with("\x1b[?25h"));
        assert!(out.contains("\x1b[2K"));
    }

    #[tokio::test]
    async fn dropping_unfinished_handle_aborts_and_cleans_line() {
        let buf = SharedBuffer::default();
        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
        tokio::time::sleep(Duration::from_millis(15)).await;
        drop(progress);

        let out = buf.text();
        assert!(
            out.ends_with("\r\x1b[2K\x1b[?25h"),
            "drop must clear the line"
        );
    }

    #[tokio::test]
    async fn finish_before_first_frame_still_prints_clean_completion() {
        let buf = SharedBuffer::default();
        let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
        progress.finish("Stack detected: Rust v1.98.0").await;

        let out = buf.text();
        assert!(out.contains("\r\x1b[2K✓ Stack detected: Rust v1.98.0"));
        assert!(out.ends_with("\x1b[?25h"));
    }

    #[test]
    fn test_progress_bar_accuracy() {
        let line = bar_line("Scanning", 5, 10);
        assert!(line.starts_with("\r\x1b[2K"), "got: {line}");
        assert!(line.contains("Scanning ["));
        let filled = line.matches('█').count();
        let empty = line.matches('░').count();
        assert_eq!(filled + empty, BAR_WIDTH, "bar must fill BAR_WIDTH");
        assert_eq!(filled, BAR_WIDTH / 2, "5/10 must fill half the bar");
        assert!(line.ends_with("50%"));

        assert_eq!(bar_line("Scanning", 0, 10).matches('█').count(), 0);
        assert_eq!(
            bar_line("Scanning", 0, 10).matches('░').count(),
            BAR_WIDTH
        );
        assert!(bar_line("Scanning", 10, 10).ends_with("100%"));
        assert_eq!(bar_line("Scanning", 10, 10).matches('█').count(), BAR_WIDTH);

        // Steps above the total clamp to 100%.
        assert!(bar_line("Scanning", 99, 20).ends_with("100%"));

        // Degenerate totals never panic.
        assert!(bar_line("Scanning", 1, 0).ends_with("100%"));
    }
}