use colored::{ColoredString, Colorize};
use crate::models::{CheckStatus, DiagnosticResult, EnvironmentState, HealthScore, HealthStatus};
pub const DASHBOARD_WIDTH: usize = 76;
const INNER_WIDTH: usize = DASHBOARD_WIDTH - 4;
pub const HEALTH_BAR_CELLS: usize = 20;
pub const VERSION_BANNER: &str = concat!(
"🚀 LIMITLESS v",
env!("CARGO_PKG_VERSION"),
" — SYSTEM ENVIRONMENT PRE-FLIGHT"
);
pub fn render_dashboard(state: &EnvironmentState) -> String {
render_dashboard_inner(state, true)
}
pub fn render_dashboard_plain(state: &EnvironmentState) -> String {
render_dashboard_inner(state, false)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowStyle {
Plain,
Green,
Red,
Yellow,
Cyan,
Dimmed,
CyanBold,
BoldGreen,
BoldYellow,
Status(HealthStatus),
}
fn apply_style(s: &str, style: RowStyle) -> ColoredString {
match style {
RowStyle::Plain => s.normal(),
RowStyle::Green => s.green(),
RowStyle::Red => s.red(),
RowStyle::Yellow => s.yellow(),
RowStyle::Cyan => s.cyan(),
RowStyle::Dimmed => s.dimmed(),
RowStyle::CyanBold => s.cyan().bold(),
RowStyle::BoldGreen => s.green().bold(),
RowStyle::BoldYellow => s.yellow().bold(),
RowStyle::Status(HealthStatus::Healthy) => s.green().bold(),
RowStyle::Status(HealthStatus::Caution) => s.yellow().bold(),
RowStyle::Status(HealthStatus::Critical) => s.red().bold(),
}
}
fn effective_health(state: &EnvironmentState) -> HealthScore {
if state.diagnostics.is_empty() {
state.health_score
} else {
HealthScore::from_results(&state.diagnostics)
}
}
fn status_label(status: HealthStatus) -> &'static str {
match status {
HealthStatus::Healthy => "HEALTHY",
HealthStatus::Caution => "CAUTION",
HealthStatus::Critical => "CRITICAL",
}
}
fn health_bar_parts(percentage: u32) -> (String, String) {
let filled = ((percentage as f64 * HEALTH_BAR_CELLS as f64) / 100.0).round() as usize;
let filled = filled.min(HEALTH_BAR_CELLS);
("█".repeat(filled), "░".repeat(HEALTH_BAR_CELLS - filled))
}
fn border_line(top: bool) -> String {
let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
format!("{left}{}{right}", "─".repeat(DASHBOARD_WIDTH - 2))
}
fn styled_row(segments: &[(String, RowStyle)], colored: bool) -> String {
let plain: Vec<&str> = segments.iter().map(|(s, _)| s.as_str()).collect();
let plain_len: usize = plain.iter().map(|s| s.chars().count()).sum();
let pad = INNER_WIDTH.saturating_sub(plain_len);
let mut line = String::from("│ ");
for (text, style) in segments {
if colored {
line.push_str(&apply_style(text, *style).to_string());
} else {
line.push_str(text);
}
}
line.push_str(&" ".repeat(pad));
line.push_str(" │");
line
}
fn wrap(text: &str, width: usize) -> Vec<String> {
if text.is_empty() || width == 0 {
return vec![String::new()];
}
let mut lines = Vec::new();
let mut current = String::new();
for word in text.split(' ') {
let word_len = word.chars().count();
if word_len == 0 {
continue;
}
if word_len > width {
if !current.is_empty() {
lines.push(std::mem::take(&mut current));
}
let mut chunk = String::new();
for ch in word.chars() {
if chunk.chars().count() == width {
lines.push(std::mem::take(&mut chunk));
}
chunk.push(ch);
}
current = chunk;
} else if current.is_empty() {
current.push_str(word);
} else if current.chars().count() + 1 + word_len <= width {
current.push(' ');
current.push_str(word);
} else {
lines.push(std::mem::take(&mut current));
current.push_str(word);
}
}
if !current.is_empty() {
lines.push(current);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
fn wrap_indented(text: &str) -> Vec<String> {
let width = INNER_WIDTH - 4;
wrap(text, width)
.into_iter()
.map(|line| format!("{}{line}", " ".repeat(4)))
.collect()
}
fn diagnostic_rows(result: &DiagnosticResult, colored: bool) -> Vec<String> {
let (icon, style) = match result.status {
CheckStatus::Pass => ("✓", RowStyle::Green),
CheckStatus::Warn => ("⚠", RowStyle::Yellow),
CheckStatus::Fail => ("✖", RowStyle::Red),
};
let body = format!("{}: {}", result.check_name, result.message);
let body_width = INNER_WIDTH - 4;
let wrapped = wrap(&body, body_width);
let mut rows = Vec::new();
for (index, line) in wrapped.iter().enumerate() {
if index == 0 {
let icon_token = format!("[{icon}] ");
rows.push(styled_row(
&[(icon_token, style), (line.clone(), RowStyle::Plain)],
colored,
));
} else {
rows.push(styled_row(
&[(format!(" {line}"), RowStyle::Plain)],
colored,
));
}
}
rows
}
fn fix_row(number: usize, action: &str, colored: bool) -> Vec<String> {
const PROMPT: &str = " (Y/n) [y]";
let body_width = INNER_WIDTH - 4;
let mut lines = wrap(&format!("{number}. {action}"), body_width);
let last = lines.last_mut().expect("wrap always emits one line");
if last.chars().count() + PROMPT.chars().count() <= body_width {
last.push_str(PROMPT);
} else {
lines.push(PROMPT.to_string());
}
lines
.into_iter()
.map(|line| styled_row(&[(format!(" {line}"), RowStyle::Plain)], colored))
.collect()
}
fn render_dashboard_inner(state: &EnvironmentState, colored: bool) -> String {
let health = effective_health(state);
let mentors = crate::modules::diagnostics::mentor_messages(&state.diagnostics);
let has_fixes = !mentors.is_empty();
let (bar_fill, bar_empty) = health_bar_parts(health.percentage);
let mut out = String::new();
out.push_str(&border_line(true));
out.push('\n');
out.push_str(&styled_row(
&[(VERSION_BANNER.to_string(), RowStyle::CyanBold)],
colored,
));
out.push('\n');
out.push_str(&styled_row(
&[("─".repeat(INNER_WIDTH), RowStyle::Dimmed)],
colored,
));
out.push('\n');
if !state.diagnostics.is_empty() {
out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
out.push('\n');
for result in &state.diagnostics {
for row in diagnostic_rows(result, colored) {
out.push_str(&row);
out.push('\n');
}
}
out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
out.push('\n');
} else {
out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
out.push('\n');
out.push_str(&styled_row(
&[("No checks recorded yet.".to_string(), RowStyle::Dimmed)],
colored,
));
out.push('\n');
}
out.push_str(&styled_row(
&[
("Health Score: ".to_string(), RowStyle::Plain),
(format!("{}% ", health.percentage), RowStyle::Plain),
("[".to_string(), RowStyle::Plain),
(bar_fill, RowStyle::Green),
(bar_empty, RowStyle::Dimmed),
("]".to_string(), RowStyle::Plain),
],
colored,
));
out.push('\n');
out.push_str(&styled_row(
&[
("Status: ".to_string(), RowStyle::Plain),
(
status_label(health.overall_status).to_string(),
RowStyle::Status(health.overall_status),
),
],
colored,
));
out.push('\n');
if let Some(mentor) = mentors.first() {
out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
out.push('\n');
out.push_str(&styled_row(
&[("💡 MENTOR NOTE:".to_string(), RowStyle::Cyan)],
colored,
));
out.push('\n');
for line in wrap_indented(&mentor.plain_english) {
out.push_str(&styled_row(&[(line, RowStyle::Plain)], colored));
out.push('\n');
}
}
if has_fixes {
out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
out.push('\n');
out.push_str(&styled_row(
&[("✅ RECOMMENDED FIXES:".to_string(), RowStyle::BoldGreen)],
colored,
));
out.push('\n');
for (index, mentor) in mentors.iter().enumerate() {
for row in fix_row(index + 1, &mentor.suggested_action, colored) {
out.push_str(&row);
out.push('\n');
}
}
out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
out.push('\n');
out.push_str(&styled_row(
&[(
"> Executing auto-fixes... ✨".to_string(),
RowStyle::BoldYellow,
)],
colored,
));
out.push('\n');
}
out.push_str(&border_line(false));
out.push('\n');
out
}
pub async fn run_orbit() {
let state = crate::modules::diagnostics::build_snapshot(".");
print!("{}", render_dashboard(&state));
if state.ready_for_dev() {
println!(
"{}",
" Dashboard complete — environment is ready to develop."
.green()
.bold()
);
} else {
println!(
"{}",
" Dashboard complete — review the notes above before continuing."
.yellow()
.bold()
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{HealthScore, ProjectStack};
fn state_from(diagnostics: Vec<DiagnosticResult>) -> EnvironmentState {
EnvironmentState {
detected_stack: ProjectStack::Node {
version: "18.12.0".into(),
package_manager: "npm".into(),
},
runtime_version: Some("v18.12.0".into()),
env_file_exists: false,
env_example_exists: true,
dependencies_healthy: true,
blocked_ports: vec![(3000, 9921)],
diagnostics: diagnostics.clone(),
health_score: HealthScore::from_results(&diagnostics),
}
}
fn demo_diagnostics() -> Vec<DiagnosticResult> {
vec![
DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node v18.12.0 found"),
DiagnosticResult::new("Env Audit", CheckStatus::Fail, ".env file missing"),
DiagnosticResult::new(
"Port Scan",
CheckStatus::Fail,
"Port 3000 occupied by PID 9921",
),
DiagnosticResult::new("Dependencies", CheckStatus::Pass, "node_modules present"),
]
}
#[test]
fn dashboard_render_renders_all_status_icons() {
let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
assert_eq!(dashboard.matches("[✓]").count(), 2);
assert_eq!(dashboard.matches("[✖]").count(), 2);
assert!(!dashboard.contains("[⚠]"));
assert!(dashboard.contains("Runtime Check: Node v18.12.0 found"));
assert!(dashboard.contains("Env Audit: .env file missing"));
}
#[test]
fn warn_check_uses_amber_icon() {
let diagnostics = vec![
DiagnosticResult::new("Runtime Check", CheckStatus::Warn, "Node is outdated"),
DiagnosticResult::new("Port Scan", CheckStatus::Fail, "Port 5432 busy"),
];
let dashboard = render_dashboard_plain(&state_from(diagnostics));
assert_eq!(dashboard.matches("[⚠]").count(), 1);
assert_eq!(dashboard.matches("[✖]").count(), 1);
}
#[test]
fn header_shows_version_banner_and_borders() {
let dashboard = render_dashboard_plain(&EnvironmentState::default());
assert!(dashboard.starts_with("┌"));
assert!(dashboard.ends_with("┘\n"));
assert!(dashboard.contains(VERSION_BANNER));
}
#[test]
fn every_line_is_exactly_dashboard_width() {
for diagnostics in [
demo_diagnostics(),
vec![DiagnosticResult::new(
"A",
CheckStatus::Fail,
"long message ".repeat(30),
)],
vec![],
] {
let dashboard = render_dashboard_plain(&state_from(diagnostics));
for line in dashboard.lines() {
let observed = line.chars().count();
assert!(
observed <= DASHBOARD_WIDTH,
"line too wide ({observed} > {DASHBOARD_WIDTH}): {line:?}"
);
}
}
}
#[test]
fn health_bar_is_accurate_for_percentages() {
let cases = [
(0, 0, 20),
(25, 5, 15),
(50, 10, 10),
(75, 15, 5),
(100, 20, 0),
];
for (pct, filled, empty) in cases {
assert_eq!(health_bar_parts(pct).0, "█".repeat(filled));
assert_eq!(health_bar_parts(pct).1, "░".repeat(empty));
}
let diagnostics = vec![
DiagnosticResult::new("1", CheckStatus::Pass, "ok"),
DiagnosticResult::new("2", CheckStatus::Fail, "bad"),
];
let dashboard = render_dashboard_plain(&state_from(diagnostics));
assert!(dashboard.contains("Health Score: 50% [██████████░░░░░░░░░░]"));
}
#[test]
fn status_badge_matches_health() {
let pass = DiagnosticResult::new("A", CheckStatus::Pass, "ok");
let fail = DiagnosticResult::new("B", CheckStatus::Fail, "bad");
let caution =
render_dashboard_plain(&state_from(vec![pass.clone(), pass.clone(), fail.clone()]));
assert!(caution.contains("Status: CAUTION"));
let healthy = render_dashboard_plain(&state_from(vec![pass.clone(), pass.clone()]));
assert!(healthy.contains("Status: HEALTHY"));
let critical = render_dashboard_plain(&state_from(vec![fail.clone(), fail.clone()]));
assert!(critical.contains("Status: CRITICAL"));
}
#[test]
fn mentor_note_section_appears_for_failing_checks() {
let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
assert!(dashboard.contains("💡 MENTOR NOTE:"));
}
#[test]
fn recommended_fixes_are_numbered_with_prompt() {
let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
assert!(dashboard.contains("✅ RECOMMENDED FIXES:"));
assert!(dashboard.contains(" (Y/n) [y]"));
let fix_lines: Vec<&str> = dashboard
.lines()
.filter(|l| l.contains("(Y/n) [y]"))
.collect();
assert_eq!(fix_lines.len(), 2, "one fix per failing check");
assert!(dashboard.contains("> Executing auto-fixes... ✨"));
}
#[test]
fn all_pass_dashboard_skips_mentor_and_fixes() {
let diagnostics = vec![
DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node v22.9.0 found"),
DiagnosticResult::new("Dependencies", CheckStatus::Pass, "node_modules present"),
];
let dashboard = render_dashboard_plain(&state_from(diagnostics));
assert!(!dashboard.contains("💡 MENTOR NOTE:"));
assert!(!dashboard.contains("RECOMMENDED FIXES:"));
assert!(!dashboard.contains("(Y/n) [y]"));
assert!(!dashboard.contains("Executing auto-fixes"));
assert!(dashboard.contains("Status: HEALTHY"));
assert!(dashboard.contains("Health Score: 100% ["));
}
#[test]
fn dashboard_uses_terminal_colors() {
colored::control::set_override(true);
let dashboard = render_dashboard(&state_from(demo_diagnostics()));
assert!(dashboard.contains("\x1b["));
assert!(dashboard.contains("\x1b[0m"));
colored::control::unset_override();
}
#[test]
fn wrap_helper_respects_width() {
assert_eq!(
wrap("one two three four", 8),
vec![
"one two".to_string(),
"three".to_string(),
"four".to_string()
]
);
assert_eq!(
wrap("abcdefghijk", 4),
vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string()]
);
assert_eq!(wrap("", 10), vec![String::new()]);
}
#[test]
fn long_diagnostics_wrap_with_indentation() {
let diagnostics = vec![DiagnosticResult::new(
"Tools Check",
CheckStatus::Warn,
"very long tool check output that should definitely be wrapped across multiple rows without overflowing the frame".to_string(),
)];
let dashboard = render_dashboard_plain(&state_from(diagnostics));
assert_eq!(dashboard.matches("[⚠]").count(), 1);
for line in dashboard.lines() {
assert_eq!(line.chars().count(), DASHBOARD_WIDTH);
}
}
#[test]
fn empty_diagnostics_show_placeholder() {
let dashboard = render_dashboard_plain(&EnvironmentState::default());
assert!(dashboard.contains("No checks recorded yet."));
assert!(!dashboard.contains("RECOMMENDED FIXES:"));
}
#[test]
fn test_dashboard_rendering() {
let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
assert!(dashboard.contains(VERSION_BANNER));
assert!(dashboard.contains("Runtime Check: Node v18.12.0 found"));
assert!(dashboard.contains("Env Audit: .env file missing"));
assert!(dashboard.contains("Health Score: 50% ["));
assert!(dashboard.contains("Status: CRITICAL"));
assert!(dashboard.contains("💡 MENTOR NOTE:"));
}
#[test]
fn test_color_codes_valid() {
colored::control::set_override(true);
let colored = render_dashboard(&state_from(demo_diagnostics()));
assert!(colored.contains("\x1b["), "colored dashboard needs ANSI");
assert!(colored.contains("\x1b[0m"), "colored dashboard must reset");
assert!(!colored.contains("\x1b[0m\x1b[0m"), "no double resets");
colored::control::set_override(false);
let plain = render_dashboard_plain(&state_from(demo_diagnostics()));
assert!(
!plain.contains("\x1b["),
"plain dashboard must not contain ANSI escapes"
);
colored::control::unset_override();
}
#[test]
fn test_box_drawing_characters() {
let dashboard = render_dashboard_plain(&EnvironmentState::default());
assert!(dashboard.contains('┌'), "top-left corner missing");
assert!(dashboard.contains('┐'), "top-right corner missing");
assert!(dashboard.contains('└'), "bottom-left corner missing");
assert!(dashboard.contains('┘'), "bottom-right corner missing");
assert!(dashboard.contains('│'), "vertical border missing");
assert!(dashboard.contains('─'), "horizontal border missing");
for line in dashboard.lines() {
assert_eq!(line.chars().count(), DASHBOARD_WIDTH);
}
}
}