Skip to main content

limitless_cli/modules/
tui.rs

1//! Interactive orbital dashboard (`limit orbit`) rendering.
2//!
3//! [`render_dashboard`] draws the full environment pre-flight as a single
4//! Unicode box: a version banner, one status line per diagnostic, a live
5//! health bar, a status badge, a beginner-friendly mentor note and a numbered
6//! list of auto-fixes.
7//!
8//! The full width is capped at [`DASHBOARD_WIDTH`] so the dashboard fits an
9//! 80-column terminal.
10//!
11//! ```
12//! use limitless_cli::models::{EnvironmentState, HealthScore};
13//! use limitless_cli::modules::tui::{render_dashboard, render_dashboard_plain,
14//!                                   DASHBOARD_WIDTH};
15//!
16//! let state = EnvironmentState::default();
17//! let dashboard = render_dashboard(&state);
18//! assert!(dashboard.contains(concat!("LIMITLESS v", env!("CARGO_PKG_VERSION"))));
19//!
20//! let plain = render_dashboard_plain(&state);
21//! for line in plain.lines() {
22//!     assert!(line.chars().count() <= DASHBOARD_WIDTH);
23//! }
24//! # let _ = HealthScore::default();
25//! ```
26
27use colored::{ColoredString, Colorize};
28
29use crate::models::{CheckStatus, DiagnosticResult, EnvironmentState, HealthScore, HealthStatus};
30
31/// Total width of the dashboard frame. Kept ≤ 80 so it fits any terminal.
32///
33/// ```
34/// use limitless_cli::modules::tui::DASHBOARD_WIDTH;
35/// assert!(DASHBOARD_WIDTH <= 80);
36/// ```
37pub const DASHBOARD_WIDTH: usize = 76;
38
39/// Inner content width between the two vertical frame bars.
40const INNER_WIDTH: usize = DASHBOARD_WIDTH - 4;
41
42/// Number of cells in the health bar.
43pub const HEALTH_BAR_CELLS: usize = 20;
44
45/// Version banner printed on the first row.
46/// The title banner shown at the top of every dashboard.
47///
48/// The version always matches the crate version in `Cargo.toml`.
49pub const VERSION_BANNER: &str = concat!(
50    "🚀 LIMITLESS v",
51    env!("CARGO_PKG_VERSION"),
52    " — SYSTEM ENVIRONMENT PRE-FLIGHT"
53);
54
55/// Renders the full diagnostic dashboard for `limit orbit`.
56///
57/// Colors each status icon, the health bar and the status badge using a muted
58/// ANSI palette; the returned string is therefore intended for a terminal.
59pub fn render_dashboard(state: &EnvironmentState) -> String {
60    render_dashboard_inner(state, true)
61}
62
63/// Same layout as [`render_dashboard`] but with all ANSI sequences stripped.
64///
65/// Useful for logging verbatim or for exact-output tests.
66pub fn render_dashboard_plain(state: &EnvironmentState) -> String {
67    render_dashboard_inner(state, false)
68}
69
70/// Per-segment styling used while assembling a row.
71///
72/// Plain rows are used for body text; the remaining variants map 1:1 to
73/// `colored` styles so the same layout works with colors enabled or off.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75enum RowStyle {
76    Plain,
77    Green,
78    Red,
79    Yellow,
80    Cyan,
81    Dimmed,
82    CyanBold,
83    BoldGreen,
84    BoldYellow,
85    Status(HealthStatus),
86}
87
88/// Applies a [`RowStyle`] to `s` via the `colored` crate.
89fn apply_style(s: &str, style: RowStyle) -> ColoredString {
90    match style {
91        RowStyle::Plain => s.normal(),
92        RowStyle::Green => s.green(),
93        RowStyle::Red => s.red(),
94        RowStyle::Yellow => s.yellow(),
95        RowStyle::Cyan => s.cyan(),
96        RowStyle::Dimmed => s.dimmed(),
97        RowStyle::CyanBold => s.cyan().bold(),
98        RowStyle::BoldGreen => s.green().bold(),
99        RowStyle::BoldYellow => s.yellow().bold(),
100        RowStyle::Status(HealthStatus::Healthy) => s.green().bold(),
101        RowStyle::Status(HealthStatus::Caution) => s.yellow().bold(),
102        RowStyle::Status(HealthStatus::Critical) => s.red().bold(),
103    }
104}
105
106/// Uses the live `diagnostics` to recompute health when present, falling back
107/// to the stored score (e.g. for a freshly-built empty state).
108fn effective_health(state: &EnvironmentState) -> HealthScore {
109    if state.diagnostics.is_empty() {
110        state.health_score
111    } else {
112        HealthScore::from_results(&state.diagnostics)
113    }
114}
115
116/// Uppercase status badge text, e.g. `"CAUTION"`.
117fn status_label(status: HealthStatus) -> &'static str {
118    match status {
119        HealthStatus::Healthy => "HEALTHY",
120        HealthStatus::Caution => "CAUTION",
121        HealthStatus::Critical => "CRITICAL",
122    }
123}
124
125/// Splits a percentage into (filled, empty) health-bar block strings.
126fn health_bar_parts(percentage: u32) -> (String, String) {
127    let filled = ((percentage as f64 * HEALTH_BAR_CELLS as f64) / 100.0).round() as usize;
128    let filled = filled.min(HEALTH_BAR_CELLS);
129    ("█".repeat(filled), "░".repeat(HEALTH_BAR_CELLS - filled))
130}
131
132/// A top (`┌…┐`) or bottom (`└…┘`) frame line.
133fn border_line(top: bool) -> String {
134    let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
135    format!("{left}{}{right}", "─".repeat(DASHBOARD_WIDTH - 2))
136}
137
138/// A single `│ content-padded │` row assembled from styled segments.
139///
140/// Padding is computed against the *plain* text length so ANSI escape codes
141/// never disturb the frame alignment.
142fn styled_row(segments: &[(String, RowStyle)], colored: bool) -> String {
143    let plain: Vec<&str> = segments.iter().map(|(s, _)| s.as_str()).collect();
144    let plain_len: usize = plain.iter().map(|s| s.chars().count()).sum();
145    let pad = INNER_WIDTH.saturating_sub(plain_len);
146
147    let mut line = String::from("│ ");
148    for (text, style) in segments {
149        if colored {
150            line.push_str(&apply_style(text, *style).to_string());
151        } else {
152            line.push_str(text);
153        }
154    }
155    line.push_str(&" ".repeat(pad));
156    line.push_str(" │");
157    line
158}
159
160/// Word-wraps `text` so every line is at most `width` characters long.
161///
162/// Words longer than `width` are hard-split across lines; runs of spaces are
163/// collapsed into a single gap.
164fn wrap(text: &str, width: usize) -> Vec<String> {
165    if text.is_empty() || width == 0 {
166        return vec![String::new()];
167    }
168
169    let mut lines = Vec::new();
170    let mut current = String::new();
171
172    for word in text.split(' ') {
173        let word_len = word.chars().count();
174        if word_len == 0 {
175            continue;
176        }
177        if word_len > width {
178            if !current.is_empty() {
179                lines.push(std::mem::take(&mut current));
180            }
181            let mut chunk = String::new();
182            for ch in word.chars() {
183                if chunk.chars().count() == width {
184                    lines.push(std::mem::take(&mut chunk));
185                }
186                chunk.push(ch);
187            }
188            current = chunk;
189        } else if current.is_empty() {
190            current.push_str(word);
191        } else if current.chars().count() + 1 + word_len <= width {
192            current.push(' ');
193            current.push_str(word);
194        } else {
195            lines.push(std::mem::take(&mut current));
196            current.push_str(word);
197        }
198    }
199
200    if !current.is_empty() {
201        lines.push(current);
202    }
203    if lines.is_empty() {
204        lines.push(String::new());
205    }
206    lines
207}
208
209/// Wraps `text` for the 4-space indented body area of the dashboard.
210fn wrap_indented(text: &str) -> Vec<String> {
211    let width = INNER_WIDTH - 4;
212    wrap(text, width)
213        .into_iter()
214        .map(|line| format!("{}{line}", " ".repeat(4)))
215        .collect()
216}
217
218/// Renders the status rows for one diagnostic: a colored icon, the check name
219/// and a wrapped description, with continuations indented.
220fn diagnostic_rows(result: &DiagnosticResult, colored: bool) -> Vec<String> {
221    let (icon, style) = match result.status {
222        CheckStatus::Pass => ("✓", RowStyle::Green),
223        CheckStatus::Warn => ("⚠", RowStyle::Yellow),
224        CheckStatus::Fail => ("✖", RowStyle::Red),
225    };
226
227    let body = format!("{}: {}", result.check_name, result.message);
228    let body_width = INNER_WIDTH - 4;
229    let wrapped = wrap(&body, body_width);
230
231    let mut rows = Vec::new();
232    for (index, line) in wrapped.iter().enumerate() {
233        if index == 0 {
234            let icon_token = format!("[{icon}] ");
235            rows.push(styled_row(
236                &[(icon_token, style), (line.clone(), RowStyle::Plain)],
237                colored,
238            ));
239        } else {
240            rows.push(styled_row(
241                &[(format!("    {line}"), RowStyle::Plain)],
242                colored,
243            ));
244        }
245    }
246    rows
247}
248
249/// Renders one numbered fix line: `    1. <action> (Y/n) [y]`.
250///
251/// The `(Y/n) [y]` prompt marker is never split across wrapped lines: it is
252/// appended to the last wrapped line, or moved to its own trailing line when
253/// it would overflow the frame.
254fn fix_row(number: usize, action: &str, colored: bool) -> Vec<String> {
255    const PROMPT: &str = " (Y/n) [y]";
256    let body_width = INNER_WIDTH - 4;
257    let mut lines = wrap(&format!("{number}. {action}"), body_width);
258    let last = lines.last_mut().expect("wrap always emits one line");
259    if last.chars().count() + PROMPT.chars().count() <= body_width {
260        last.push_str(PROMPT);
261    } else {
262        lines.push(PROMPT.to_string());
263    }
264    lines
265        .into_iter()
266        .map(|line| styled_row(&[(format!("    {line}"), RowStyle::Plain)], colored))
267        .collect()
268}
269
270fn render_dashboard_inner(state: &EnvironmentState, colored: bool) -> String {
271    let health = effective_health(state);
272    let mentors = crate::modules::diagnostics::mentor_messages(&state.diagnostics);
273    let has_fixes = !mentors.is_empty();
274    let (bar_fill, bar_empty) = health_bar_parts(health.percentage);
275
276    let mut out = String::new();
277
278    out.push_str(&border_line(true));
279    out.push('\n');
280    out.push_str(&styled_row(
281        &[(VERSION_BANNER.to_string(), RowStyle::CyanBold)],
282        colored,
283    ));
284    out.push('\n');
285    out.push_str(&styled_row(
286        &[("─".repeat(INNER_WIDTH), RowStyle::Dimmed)],
287        colored,
288    ));
289    out.push('\n');
290
291    if !state.diagnostics.is_empty() {
292        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
293        out.push('\n');
294        for result in &state.diagnostics {
295            for row in diagnostic_rows(result, colored) {
296                out.push_str(&row);
297                out.push('\n');
298            }
299        }
300        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
301        out.push('\n');
302    } else {
303        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
304        out.push('\n');
305        out.push_str(&styled_row(
306            &[("No checks recorded yet.".to_string(), RowStyle::Dimmed)],
307            colored,
308        ));
309        out.push('\n');
310    }
311
312    out.push_str(&styled_row(
313        &[
314            ("Health Score: ".to_string(), RowStyle::Plain),
315            (format!("{}% ", health.percentage), RowStyle::Plain),
316            ("[".to_string(), RowStyle::Plain),
317            (bar_fill, RowStyle::Green),
318            (bar_empty, RowStyle::Dimmed),
319            ("]".to_string(), RowStyle::Plain),
320        ],
321        colored,
322    ));
323    out.push('\n');
324    out.push_str(&styled_row(
325        &[
326            ("Status: ".to_string(), RowStyle::Plain),
327            (
328                status_label(health.overall_status).to_string(),
329                RowStyle::Status(health.overall_status),
330            ),
331        ],
332        colored,
333    ));
334    out.push('\n');
335
336    if let Some(mentor) = mentors.first() {
337        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
338        out.push('\n');
339        out.push_str(&styled_row(
340            &[("💡 MENTOR NOTE:".to_string(), RowStyle::Cyan)],
341            colored,
342        ));
343        out.push('\n');
344        for line in wrap_indented(&mentor.plain_english) {
345            out.push_str(&styled_row(&[(line, RowStyle::Plain)], colored));
346            out.push('\n');
347        }
348    }
349
350    if has_fixes {
351        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
352        out.push('\n');
353        out.push_str(&styled_row(
354            &[("✅ RECOMMENDED FIXES:".to_string(), RowStyle::BoldGreen)],
355            colored,
356        ));
357        out.push('\n');
358        for (index, mentor) in mentors.iter().enumerate() {
359            for row in fix_row(index + 1, &mentor.suggested_action, colored) {
360                out.push_str(&row);
361                out.push('\n');
362            }
363        }
364        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
365        out.push('\n');
366        out.push_str(&styled_row(
367            &[(
368                "> Executing auto-fixes... ✨".to_string(),
369                RowStyle::BoldYellow,
370            )],
371            colored,
372        ));
373        out.push('\n');
374    }
375
376    out.push_str(&border_line(false));
377    out.push('\n');
378    out
379}
380
381/// Runs `limit orbit`: builds a fresh snapshot and renders the dashboard.
382pub async fn run_orbit() {
383    let state = crate::modules::diagnostics::build_snapshot(".");
384    print!("{}", render_dashboard(&state));
385    if state.ready_for_dev() {
386        println!(
387            "{}",
388            "  Dashboard complete — environment is ready to develop."
389                .green()
390                .bold()
391        );
392    } else {
393        println!(
394            "{}",
395            "  Dashboard complete — review the notes above before continuing."
396                .yellow()
397                .bold()
398        );
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use crate::models::{HealthScore, ProjectStack};
406
407    fn state_from(diagnostics: Vec<DiagnosticResult>) -> EnvironmentState {
408        EnvironmentState {
409            detected_stack: ProjectStack::Node {
410                version: "18.12.0".into(),
411                package_manager: "npm".into(),
412            },
413            runtime_version: Some("v18.12.0".into()),
414            env_file_exists: false,
415            env_example_exists: true,
416            dependencies_healthy: true,
417            blocked_ports: vec![(3000, 9921)],
418            diagnostics: diagnostics.clone(),
419            health_score: HealthScore::from_results(&diagnostics),
420        }
421    }
422
423    fn demo_diagnostics() -> Vec<DiagnosticResult> {
424        vec![
425            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node v18.12.0 found"),
426            DiagnosticResult::new("Env Audit", CheckStatus::Fail, ".env file missing"),
427            DiagnosticResult::new(
428                "Port Scan",
429                CheckStatus::Fail,
430                "Port 3000 occupied by PID 9921",
431            ),
432            DiagnosticResult::new("Dependencies", CheckStatus::Pass, "node_modules present"),
433        ]
434    }
435
436    #[test]
437    fn dashboard_render_renders_all_status_icons() {
438        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
439        assert_eq!(dashboard.matches("[✓]").count(), 2);
440        assert_eq!(dashboard.matches("[✖]").count(), 2);
441        assert!(!dashboard.contains("[⚠]"));
442        assert!(dashboard.contains("Runtime Check: Node v18.12.0 found"));
443        assert!(dashboard.contains("Env Audit: .env file missing"));
444    }
445
446    #[test]
447    fn warn_check_uses_amber_icon() {
448        let diagnostics = vec![
449            DiagnosticResult::new("Runtime Check", CheckStatus::Warn, "Node is outdated"),
450            DiagnosticResult::new("Port Scan", CheckStatus::Fail, "Port 5432 busy"),
451        ];
452        let dashboard = render_dashboard_plain(&state_from(diagnostics));
453        assert_eq!(dashboard.matches("[⚠]").count(), 1);
454        assert_eq!(dashboard.matches("[✖]").count(), 1);
455    }
456
457    #[test]
458    fn header_shows_version_banner_and_borders() {
459        let dashboard = render_dashboard_plain(&EnvironmentState::default());
460        assert!(dashboard.starts_with("┌"));
461        assert!(dashboard.ends_with("┘\n"));
462        assert!(dashboard.contains(VERSION_BANNER));
463    }
464
465    #[test]
466    fn every_line_is_exactly_dashboard_width() {
467        for diagnostics in [
468            demo_diagnostics(),
469            vec![DiagnosticResult::new(
470                "A",
471                CheckStatus::Fail,
472                "long message ".repeat(30),
473            )],
474            vec![],
475        ] {
476            let dashboard = render_dashboard_plain(&state_from(diagnostics));
477            for line in dashboard.lines() {
478                let observed = line.chars().count();
479                assert!(
480                    observed <= DASHBOARD_WIDTH,
481                    "line too wide ({observed} > {DASHBOARD_WIDTH}): {line:?}"
482                );
483            }
484        }
485    }
486
487    #[test]
488    fn health_bar_is_accurate_for_percentages() {
489        let cases = [
490            (0, 0, 20),
491            (25, 5, 15),
492            (50, 10, 10),
493            (75, 15, 5),
494            (100, 20, 0),
495        ];
496        for (pct, filled, empty) in cases {
497            assert_eq!(health_bar_parts(pct).0, "█".repeat(filled));
498            assert_eq!(health_bar_parts(pct).1, "░".repeat(empty));
499        }
500
501        let diagnostics = vec![
502            DiagnosticResult::new("1", CheckStatus::Pass, "ok"),
503            DiagnosticResult::new("2", CheckStatus::Fail, "bad"),
504        ];
505        let dashboard = render_dashboard_plain(&state_from(diagnostics));
506        assert!(dashboard.contains("Health Score: 50% [██████████░░░░░░░░░░]"));
507    }
508
509    #[test]
510    fn status_badge_matches_health() {
511        let pass = DiagnosticResult::new("A", CheckStatus::Pass, "ok");
512        let fail = DiagnosticResult::new("B", CheckStatus::Fail, "bad");
513
514        let caution =
515            render_dashboard_plain(&state_from(vec![pass.clone(), pass.clone(), fail.clone()]));
516        assert!(caution.contains("Status: CAUTION"));
517
518        let healthy = render_dashboard_plain(&state_from(vec![pass.clone(), pass.clone()]));
519        assert!(healthy.contains("Status: HEALTHY"));
520
521        let critical = render_dashboard_plain(&state_from(vec![fail.clone(), fail.clone()]));
522        assert!(critical.contains("Status: CRITICAL"));
523    }
524
525    #[test]
526    fn mentor_note_section_appears_for_failing_checks() {
527        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
528        assert!(dashboard.contains("💡 MENTOR NOTE:"));
529    }
530
531    #[test]
532    fn recommended_fixes_are_numbered_with_prompt() {
533        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
534        assert!(dashboard.contains("✅ RECOMMENDED FIXES:"));
535        assert!(dashboard.contains(" (Y/n) [y]"));
536        let fix_lines: Vec<&str> = dashboard
537            .lines()
538            .filter(|l| l.contains("(Y/n) [y]"))
539            .collect();
540        assert_eq!(fix_lines.len(), 2, "one fix per failing check");
541        assert!(dashboard.contains("> Executing auto-fixes... ✨"));
542    }
543
544    #[test]
545    fn all_pass_dashboard_skips_mentor_and_fixes() {
546        let diagnostics = vec![
547            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node v22.9.0 found"),
548            DiagnosticResult::new("Dependencies", CheckStatus::Pass, "node_modules present"),
549        ];
550        let dashboard = render_dashboard_plain(&state_from(diagnostics));
551        assert!(!dashboard.contains("💡 MENTOR NOTE:"));
552        assert!(!dashboard.contains("RECOMMENDED FIXES:"));
553        assert!(!dashboard.contains("(Y/n) [y]"));
554        assert!(!dashboard.contains("Executing auto-fixes"));
555        assert!(dashboard.contains("Status: HEALTHY"));
556        assert!(dashboard.contains("Health Score: 100% ["));
557    }
558
559    #[test]
560    fn dashboard_uses_terminal_colors() {
561        colored::control::set_override(true);
562        let dashboard = render_dashboard(&state_from(demo_diagnostics()));
563        assert!(dashboard.contains("\x1b["));
564        assert!(dashboard.contains("\x1b[0m"));
565        colored::control::unset_override();
566    }
567
568    #[test]
569    fn wrap_helper_respects_width() {
570        assert_eq!(
571            wrap("one two three four", 8),
572            vec![
573                "one two".to_string(),
574                "three".to_string(),
575                "four".to_string()
576            ]
577        );
578        assert_eq!(
579            wrap("abcdefghijk", 4),
580            vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string()]
581        );
582        assert_eq!(wrap("", 10), vec![String::new()]);
583    }
584
585    #[test]
586    fn long_diagnostics_wrap_with_indentation() {
587        let diagnostics = vec![DiagnosticResult::new(
588            "Tools Check",
589            CheckStatus::Warn,
590            "very long tool check output that should definitely be wrapped across multiple rows without overflowing the frame".to_string(),
591        )];
592        let dashboard = render_dashboard_plain(&state_from(diagnostics));
593        assert_eq!(dashboard.matches("[⚠]").count(), 1);
594        for line in dashboard.lines() {
595            assert_eq!(line.chars().count(), DASHBOARD_WIDTH);
596        }
597    }
598
599    #[test]
600    fn empty_diagnostics_show_placeholder() {
601        let dashboard = render_dashboard_plain(&EnvironmentState::default());
602        assert!(dashboard.contains("No checks recorded yet."));
603        assert!(!dashboard.contains("RECOMMENDED FIXES:"));
604    }
605
606    // --- Named coverage tests ----------------------------------------------
607
608    #[test]
609    fn test_dashboard_rendering() {
610        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
611        assert!(dashboard.contains(VERSION_BANNER));
612        assert!(dashboard.contains("Runtime Check: Node v18.12.0 found"));
613        assert!(dashboard.contains("Env Audit: .env file missing"));
614        assert!(dashboard.contains("Health Score: 50% ["));
615        assert!(dashboard.contains("Status: CRITICAL"));
616        assert!(dashboard.contains("💡 MENTOR NOTE:"));
617    }
618
619    #[test]
620    fn test_color_codes_valid() {
621        colored::control::set_override(true);
622        let colored = render_dashboard(&state_from(demo_diagnostics()));
623        assert!(colored.contains("\x1b["), "colored dashboard needs ANSI");
624        assert!(colored.contains("\x1b[0m"), "colored dashboard must reset");
625        assert!(!colored.contains("\x1b[0m\x1b[0m"), "no double resets");
626
627        colored::control::set_override(false);
628        let plain = render_dashboard_plain(&state_from(demo_diagnostics()));
629        assert!(
630            !plain.contains("\x1b["),
631            "plain dashboard must not contain ANSI escapes"
632        );
633        colored::control::unset_override();
634    }
635
636    #[test]
637    fn test_box_drawing_characters() {
638        let dashboard = render_dashboard_plain(&EnvironmentState::default());
639        assert!(dashboard.contains('┌'), "top-left corner missing");
640        assert!(dashboard.contains('┐'), "top-right corner missing");
641        assert!(dashboard.contains('└'), "bottom-left corner missing");
642        assert!(dashboard.contains('┘'), "bottom-right corner missing");
643        assert!(dashboard.contains('│'), "vertical border missing");
644        assert!(dashboard.contains('─'), "horizontal border missing");
645        for line in dashboard.lines() {
646            assert_eq!(line.chars().count(), DASHBOARD_WIDTH);
647        }
648    }
649}