Skip to main content

limitless_cli/modules/
message_formatter.rs

1//! Renders [`MentorMessage`]s as friendly, color-coded advice boxes.
2//!
3//! Every message is drawn inside a Unicode box (`┌─┐│└┘`) whose accent
4//! color and emoji reflect the [`Severity`] of the underlying issue:
5//!
6//! | Severity | Emoji | Accent                | ANSI code |
7//! |----------|-------|-----------------------|-----------|
8//! | Info     | 💡    | soft light blue       | `\x1b[94m` |
9//! | Warning  | ⚠️    | amber / yellow        | `\x1b[33m` |
10//! | Critical | 🚨    | bright red            | `\x1b[91m` |
11//!
12//! The box is a fixed width ([`BOX_WIDTH`]) and all body text is word-wrapped
13//! to keep every line exactly one terminal column wide.
14//!
15//! ```
16//! use limitless_cli::models::{MentorMessage, Severity};
17//! use limitless_cli::modules::message_formatter::{format_mentor_message, BOX_WIDTH};
18//!
19//! let msg = MentorMessage {
20//!     severity: Severity::Critical,
21//!     plain_english: "Port 3000 is already in use.".into(),
22//!     technical_detail: "Another process listens on 0.0.0.0:3000.".into(),
23//!     suggested_action: "Run `lsof -i :3000` and stop that process.".into(),
24//! };
25//! let rendered = format_mentor_message(&msg);
26//! assert!(rendered.contains("🚨 MENTOR NOTE:"));
27//! assert!(rendered.contains("URGENT ACTION REQUIRED:"));
28//!
29//! // Pure text (no ANSI) is handy for logging and tests:
30//! use limitless_cli::modules::message_formatter::format_mentor_message_plain;
31//! let plain = format_mentor_message_plain(&msg);
32//! assert!(!plain.contains('\x1b'));
33//! for line in plain.lines() {
34//!     assert_eq!(line.chars().count(), BOX_WIDTH);
35//! }
36//! ```
37
38use crate::models::{MentorMessage, Severity};
39
40/// Overall box width measured in terminal columns / string characters.
41///
42/// Every frame line — border, heading or body — is exactly this wide.
43pub const BOX_WIDTH: usize = 60;
44
45/// Inner text width between the two vertical bars.
46const INNER_WIDTH: usize = BOX_WIDTH - 4;
47
48/// Leading spaces used for the indented "why / action" body text.
49const BODY_INDENT: usize = 4;
50
51/// Regular box corners used for the top border.
52const TOP_LEFT: char = '┌';
53const TOP_RIGHT: char = '┐';
54
55/// Regular box corners used for the bottom border.
56const BOTTOM_LEFT: char = '└';
57const BOTTOM_RIGHT: char = '┘';
58
59/// Horizontal / vertical frame characters.
60const HORIZONTAL: char = '─';
61const VERTICAL: char = '│';
62
63/// The muted ANSI color palette backing the three severity levels.
64///
65/// | Severity | Code        |
66/// |----------|-------------|
67/// | Info     | `\x1b[94m`  |
68/// | Warning  | `\x1b[33m`  |
69/// | Critical | `\x1b[91m`  |
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct Palette {
72    /// Soft light blue — `\x1b[94m`
73    pub info: &'static str,
74    /// Amber / yellow — `\x1b[33m`
75    pub warning: &'static str,
76    /// Bright red — `\x1b[91m`
77    pub critical: &'static str,
78    /// ANSI reset — `\x1b[0m`
79    pub reset: &'static str,
80}
81
82/// The muted ANSI color scheme used everywhere in this module.
83pub const PALETTE: Palette = Palette {
84    info: "\x1b[94m",
85    warning: "\x1b[33m",
86    critical: "\x1b[91m",
87    reset: "\x1b[0m",
88};
89
90/// Accent color configured for one severity level.
91///
92/// ```
93/// use limitless_cli::modules::message_formatter::{PALETTE, accent_for};
94/// use limitless_cli::models::Severity;
95///
96/// assert_eq!(accent_for(Severity::Info), PALETTE.info);
97/// assert_eq!(accent_for(Severity::Warning), PALETTE.warning);
98/// assert_eq!(accent_for(Severity::Critical), PALETTE.critical);
99/// ```
100pub fn accent_for(severity: Severity) -> &'static str {
101    match severity {
102        Severity::Info => PALETTE.info,
103        Severity::Warning => PALETTE.warning,
104        Severity::Critical => PALETTE.critical,
105    }
106}
107
108/// Emoji + label pairing for the note header.
109///
110/// ```
111/// use limitless_cli::modules::message_formatter::note_emoji;
112/// use limitless_cli::models::Severity;
113///
114/// assert_eq!(note_emoji(Severity::Info), "💡");
115/// assert_eq!(note_emoji(Severity::Critical), "🚨");
116/// ```
117pub fn note_emoji(severity: Severity) -> &'static str {
118    match severity {
119        Severity::Info => "💡",
120        Severity::Warning => "⚠️",
121        Severity::Critical => "🚨",
122    }
123}
124
125/// Emoji used next to the suggested-action heading.
126///
127/// ```
128/// use limitless_cli::modules::message_formatter::action_emoji;
129/// use limitless_cli::models::Severity;
130///
131/// assert_eq!(action_emoji(Severity::Info), "✅");
132/// assert_eq!(action_emoji(Severity::Warning), "⚡");
133/// assert_eq!(action_emoji(Severity::Critical), "🚨");
134/// ```
135pub fn action_emoji(severity: Severity) -> &'static str {
136    match severity {
137        Severity::Info => "✅",
138        Severity::Warning => "⚡",
139        Severity::Critical => "🚨",
140    }
141}
142
143/// Heading shown above the suggested action.
144///
145/// Critical messages signal urgency; warnings ask for a quick action.
146///
147/// ```
148/// use limitless_cli::modules::message_formatter::action_label;
149/// use limitless_cli::models::Severity;
150///
151/// assert_eq!(action_label(Severity::Info), "Next step:");
152/// assert_eq!(action_label(Severity::Warning), "Quick action:");
153/// assert_eq!(action_label(Severity::Critical), "URGENT ACTION REQUIRED:");
154/// ```
155pub fn action_label(severity: Severity) -> &'static str {
156    match severity {
157        Severity::Info => "Next step:",
158        Severity::Warning => "Quick action:",
159        Severity::Critical => "URGENT ACTION REQUIRED:",
160    }
161}
162
163/// Render `msg` as a colorized advice box (ANSI escape codes included).
164///
165/// The accent color, note emoji and action heading all follow [`msg.severity`]
166/// (see [`Severity`] / [`PALETTE`]).
167pub fn format_mentor_message(msg: &MentorMessage) -> String {
168    render_box(msg, true)
169}
170
171/// Render `msg` as a plain advice box with zero ANSI escape codes.
172///
173/// Useful for logging verbatim or for exact-output tests.
174pub fn format_mentor_message_plain(msg: &MentorMessage) -> String {
175    render_box(msg, false)
176}
177
178/// Which frame lines get tinted with the severity accent.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180enum RowKind {
181    Border,
182    Heading,
183    Body,
184}
185
186fn render_box(msg: &MentorMessage, colored: bool) -> String {
187    let severity = msg.severity;
188    let accent = accent_for(severity);
189
190    let header_lines = wrap(
191        &format!(
192            "{} MENTOR NOTE: {}",
193            note_emoji(severity),
194            msg.plain_english
195        ),
196        INNER_WIDTH,
197    );
198
199    let mut rows: Vec<(RowKind, String)> = Vec::new();
200    rows.push((RowKind::Border, border_line(TOP_LEFT, TOP_RIGHT)));
201    for line in header_lines {
202        rows.push((RowKind::Heading, content_line(&line)));
203    }
204    rows.push((RowKind::Body, content_line("")));
205    rows.push((RowKind::Heading, content_line("📋 Why this matters:")));
206    for line in wrap_indented(&msg.technical_detail) {
207        rows.push((RowKind::Body, content_line(&line)));
208    }
209    rows.push((RowKind::Body, content_line("")));
210    rows.push((
211        RowKind::Heading,
212        content_line(&format!(
213            "{} {}",
214            action_emoji(severity),
215            action_label(severity)
216        )),
217    ));
218    for line in wrap_indented(&msg.suggested_action) {
219        rows.push((RowKind::Body, content_line(&line)));
220    }
221    rows.push((RowKind::Border, border_line(BOTTOM_LEFT, BOTTOM_RIGHT)));
222
223    let mut out = String::new();
224    for (kind, line) in rows {
225        let rendered = if colored && kind != RowKind::Body {
226            format!("{accent}{line}{}", PALETTE.reset)
227        } else {
228            line
229        };
230        out.push_str(&rendered);
231        out.push('\n');
232    }
233    out
234}
235
236/// Produces a horizontal frame line, e.g. `┌─────┐` or `└─────┘`.
237fn border_line(left: char, right: char) -> String {
238    let mut line = String::new();
239    line.push(left);
240    for _ in 0..(BOX_WIDTH - 2) {
241        line.push(HORIZONTAL);
242    }
243    line.push(right);
244    line
245}
246
247/// Produces a vertical frame row holding `content` padded to `INNER_WIDTH`.
248fn content_line(content: &str) -> String {
249    format!("{VERTICAL} {content:<INNER_WIDTH$} {VERTICAL}")
250}
251
252/// Body text wrapped at the box's text width and indented by `BODY_INDENT`.
253fn wrap_indented(text: &str) -> Vec<String> {
254    let width = INNER_WIDTH - BODY_INDENT;
255    wrap(text, width)
256        .into_iter()
257        .map(|line| format!("{}{line}", " ".repeat(BODY_INDENT)))
258        .collect()
259}
260
261/// Word-wraps `text` so every line is at most `width` characters long.
262///
263/// Words longer than `width` are hard-split across lines. Multiple
264/// consecutive spaces are collapsed into a single gap.
265fn wrap(text: &str, width: usize) -> Vec<String> {
266    if text.is_empty() || width == 0 {
267        return vec![String::new()];
268    }
269
270    let mut lines = Vec::new();
271    let mut current = String::new();
272
273    for word in text.split(' ') {
274        let word_len = word.chars().count();
275        if word_len == 0 {
276            continue;
277        }
278        if word_len > width {
279            if !current.is_empty() {
280                lines.push(std::mem::take(&mut current));
281            }
282            let mut chunk = String::new();
283            for ch in word.chars() {
284                if chunk.chars().count() == width {
285                    lines.push(std::mem::take(&mut chunk));
286                }
287                chunk.push(ch);
288            }
289            current = chunk;
290        } else if current.is_empty() {
291            current.push_str(word);
292        } else if current.chars().count() + 1 + word_len <= width {
293            current.push(' ');
294            current.push_str(word);
295        } else {
296            lines.push(std::mem::take(&mut current));
297            current.push_str(word);
298        }
299    }
300
301    if !current.is_empty() {
302        lines.push(current);
303    }
304    if lines.is_empty() {
305        lines.push(String::new());
306    }
307    lines
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    fn msg(severity: Severity) -> MentorMessage {
315        MentorMessage {
316            severity,
317            plain_english: "Node is ready.".into(),
318            technical_detail: "Runtime v22.9.0 detected.".into(),
319            suggested_action: "None.".into(),
320        }
321    }
322
323    #[test]
324    fn info_box_renders_exact_plain_output() {
325        let pad = |content: &str| {
326            format!(
327                "{content}{}",
328                " ".repeat(INNER_WIDTH - content.chars().count())
329            )
330        };
331        let row = |content: String| format!("│ {content} │");
332        let border =
333            |left: char, right: char| format!("{left}{}{right}", "─".repeat(BOX_WIDTH - 2));
334
335        let expected = format!(
336            "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n",
337            border(TOP_LEFT, TOP_RIGHT),
338            row(pad("💡 MENTOR NOTE: Node is ready.")),
339            row(pad("")),
340            row(pad("📋 Why this matters:")),
341            row(pad("    Runtime v22.9.0 detected.")),
342            row(pad("")),
343            row(pad("✅ Next step:")),
344            row(pad("    None.")),
345            border(BOTTOM_LEFT, BOTTOM_RIGHT),
346        );
347        assert_eq!(format_mentor_message_plain(&msg(Severity::Info)), expected);
348    }
349
350    #[test]
351    fn warning_box_uses_quick_action_label() {
352        let out = format_mentor_message_plain(&msg(Severity::Warning));
353        assert!(out.contains("⚠️ MENTOR NOTE:"));
354        assert!(out.contains("⚡ Quick action:"));
355        assert!(!out.contains("URGENT ACTION REQUIRED:"));
356    }
357
358    #[test]
359    fn critical_box_marks_action_as_urgent() {
360        let out = format_mentor_message_plain(&msg(Severity::Critical));
361        assert!(out.contains("🚨 MENTOR NOTE:"));
362        assert!(out.contains("🚨 URGENT ACTION REQUIRED:"));
363    }
364
365    #[test]
366    fn every_plain_line_is_exactly_box_width() {
367        for severity in [Severity::Info, Severity::Warning, Severity::Critical] {
368            let out = format_mentor_message_plain(&msg(severity));
369            for line in out.lines() {
370                assert_eq!(line.chars().count(), BOX_WIDTH);
371            }
372            assert!(!out.contains('\x1b'));
373        }
374    }
375
376    #[test]
377    fn colored_output_uses_muted_ansi_palette() {
378        let info = format_mentor_message(&msg(Severity::Info));
379        assert!(info.contains(accent_for(Severity::Info)));
380        assert!(info.contains(PALETTE.reset));
381
382        let warning = format_mentor_message(&msg(Severity::Warning));
383        assert!(warning.contains(accent_for(Severity::Warning)));
384        assert!(warning.contains(PALETTE.reset));
385
386        let critical = format_mentor_message(&msg(Severity::Critical));
387        assert!(critical.contains(accent_for(Severity::Critical)));
388        assert!(critical.contains(PALETTE.reset));
389    }
390
391    #[test]
392    fn long_messages_wrap_within_box() {
393        let long = MentorMessage {
394            severity: Severity::Info,
395            plain_english: "The npm package manager was not found on your PATH, which means the install command cannot resolve it.".into(),
396            technical_detail: "Neither `npm` nor `npx` resolve to an executable under any of the configured PATH entries.".into(),
397            suggested_action: "Run `npm install -g node` or reinstall Node and then restart your terminal before trying again.".into(),
398        };
399        let plain = format_mentor_message_plain(&long);
400        assert!(plain.lines().count() > 9, "wrapping should add rows");
401        for line in plain.lines() {
402            assert_eq!(line.chars().count(), BOX_WIDTH);
403        }
404        assert!(plain.contains("📋 Why this matters:"));
405        assert!(plain.contains("Next step:"));
406    }
407
408    #[test]
409    fn wrap_respects_width() {
410        let text = "one two three four five";
411        assert_eq!(
412            wrap(text, 10),
413            vec![
414                "one two".to_string(),
415                "three four".to_string(),
416                "five".to_string(),
417            ]
418        );
419    }
420
421    #[test]
422    fn wrap_hard_splits_overlong_words() {
423        assert_eq!(
424            wrap("abcdefghijk", 4),
425            vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string(),]
426        );
427    }
428
429    #[test]
430    fn wrap_collapses_multiple_spaces() {
431        assert_eq!(wrap("a   b", 10), vec!["a b".to_string()]);
432    }
433
434    #[test]
435    fn wrap_empty_and_width_zero() {
436        assert_eq!(wrap("", 10), vec![String::new()]);
437        assert_eq!(wrap("abc", 0), vec![String::new()]);
438    }
439
440    #[test]
441    fn indented_body_stays_within_inner_width() {
442        let lines = wrap_indented("Short body.");
443        assert_eq!(lines[0], "    Short body.");
444        assert!(lines.iter().all(|l| l.chars().count() <= INNER_WIDTH));
445    }
446
447    #[test]
448    fn palette_values_are_exact_ansi_codes() {
449        assert_eq!(PALETTE.info, "\x1b[94m");
450        assert_eq!(PALETTE.warning, "\x1b[33m");
451        assert_eq!(PALETTE.critical, "\x1b[91m");
452        assert_eq!(PALETTE.reset, "\x1b[0m");
453    }
454
455    #[test]
456    fn test_mentor_message_formatting() {
457        let msg = MentorMessage {
458            severity: Severity::Warning,
459            plain_english: "Port 3000 is jammed.".to_string(),
460            technical_detail: "EADDRINUSE".to_string(),
461            suggested_action: "Free the port, then retry".to_string(),
462        };
463
464        let plain = format_mentor_message_plain(&msg);
465        assert!(!plain.contains("\x1b["), "plain output must have no ANSI");
466        assert!(plain.contains("Port 3000 is jammed."));
467        assert!(plain.contains("EADDRINUSE"));
468        assert!(plain.contains("Free the port, then retry"));
469        assert!(plain.contains("MENTOR NOTE:"), "severity label should be rendered");
470
471        let colored = format_mentor_message(&msg);
472        assert!(colored.contains("\x1b["), "colored output must use ANSI");
473        assert!(colored.contains("Port 3000 is jammed."));
474    }
475}