Skip to main content

limitless_cli/modules/
interactive_prompt.rs

1//! Interactive user-confirmation dialogs for auto-fixes.
2//!
3//! [`prompt_user_confirmation`] asks a yes/no question and reads a single
4//! keypress (no Enter required) with a 30 second timeout; the default is used
5//! when the user presses Enter or the prompt expires. [`prompt_fix_selection`]
6//! renders a checkbox list that is navigated with the arrow keys, toggled with
7//! space and confirmed with Enter.
8//!
9//! Both prompts are written against the [`KeyReader`] / [`PromptWriter`]
10//! abstractions so the same logic is unit-testable with [`MockKeyReader`] and
11//! [`CapturingWriter`] instead of a real terminal.
12//!
13//! ```
14//! use limitless_cli::modules::interactive_prompt::{
15//!     prompt_user_confirmation_with, CapturingWriter, Key, MockKeyReader,
16//!     CONFIRM_TIMEOUT,
17//! };
18//!
19//! let mut reader = MockKeyReader::new(vec![Key::Enter]);
20//! let mut writer = CapturingWriter::default();
21//! let confirmed = prompt_user_confirmation_with(
22//!     "Copy .env.example to .env?",
23//!     true,
24//!     CONFIRM_TIMEOUT,
25//!     &mut reader,
26//!     &mut writer,
27//! );
28//! assert!(confirmed);
29//! assert!(writer.output.contains("❓ Copy .env.example to .env? (Y/n) [y]"));
30//! ```
31
32use std::collections::VecDeque;
33use std::io::{self, Write};
34use std::time::Duration;
35
36/// How long a confirmation prompt waits for input before using its default.
37pub const CONFIRM_TIMEOUT: Duration = Duration::from_secs(30);
38
39/// How long the fix-selection list stays idle before it confirms what is
40/// currently selected (avoids the prompt hanging forever).
41const SELECT_IDLE_TIMEOUT: Duration = Duration::from_secs(600);
42
43/// Shown when the user types anything other than `y` / `n`.
44const INVALID_INPUT_MSG: &str = "Please enter y or n";
45
46/// One auto-fix candidate offered by the selection UI.
47///
48/// ```
49/// use limitless_cli::modules::interactive_prompt::Fix;
50///
51/// let fix = Fix::new("Copy .env.example to .env");
52/// assert_eq!(fix.description, "Copy .env.example to .env");
53/// ```
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub struct Fix {
56    /// Short, human-readable description shown in the checklist.
57    pub description: String,
58}
59
60impl Fix {
61    /// Creates a fix candidate from a description.
62    pub fn new(description: impl Into<String>) -> Self {
63        Self {
64            description: description.into(),
65        }
66    }
67}
68
69/// A normalized key press that the prompts understand.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Key {
72    /// A printable character, e.g. `'y'`.
73    Char(char),
74    /// Enter / return key.
75    Enter,
76    /// Up arrow.
77    Up,
78    /// Down arrow.
79    Down,
80    /// Space bar.
81    Space,
82    /// Escape key (cancels a selection).
83    Esc,
84    /// Any other key we intentionally ignore.
85    Unknown,
86}
87
88/// Abstraction over the terminal so prompts can be driven by mock input.
89///
90/// Implementors return the next normalized [`Key`], or `None` when `timeout`
91/// elapses without a key press (or at end of a mocked input queue).
92pub trait KeyReader {
93    /// Blocks up to `timeout`, returning the next key or `None` on timeout.
94    fn read_key(&mut self, timeout: Duration) -> Option<Key>;
95}
96
97/// Abstraction over the output stream so prompts can capture their text.
98pub trait PromptWriter {
99    /// Buffers `text` for display.
100    fn write(&mut self, text: &str);
101    /// Flushes buffered text to the real output.
102    fn flush(&mut self) -> io::Result<()>;
103}
104
105/// Key reader backed by a real terminal via the `crossterm` crate.
106pub struct TerminalKeyReader;
107
108impl KeyReader for TerminalKeyReader {
109    fn read_key(&mut self, timeout: Duration) -> Option<Key> {
110        // Non-key events (mouse moves, resizes) are ignored so `None` only
111        // ever means "no key was pressed within `timeout`".
112        loop {
113            if !crossterm::event::poll(timeout).unwrap_or(false) {
114                return None;
115            }
116            match crossterm::event::read() {
117                Ok(crossterm::event::Event::Key(event)) => return Some(key_from_crossterm(event)),
118                _ => continue,
119            }
120        }
121    }
122}
123
124fn key_from_crossterm(event: crossterm::event::KeyEvent) -> Key {
125    // In raw mode Ctrl-C arrives as CONTROL + `c`, never as `\u{3}`; map it
126    // back so the prompts still treat it as "bail with the default".
127    if event
128        .modifiers
129        .contains(crossterm::event::KeyModifiers::CONTROL)
130        && event.code == crossterm::event::KeyCode::Char('c')
131    {
132        return Key::Char('\u{3}');
133    }
134    match event.code {
135        crossterm::event::KeyCode::Char(' ') => Key::Space,
136        crossterm::event::KeyCode::Char(c) => Key::Char(c),
137        crossterm::event::KeyCode::Enter => Key::Enter,
138        crossterm::event::KeyCode::Up => Key::Up,
139        crossterm::event::KeyCode::Down => Key::Down,
140        crossterm::event::KeyCode::Esc => Key::Esc,
141        _ => Key::Unknown,
142    }
143}
144
145/// Writer backed by the real standard output.
146pub struct StdoutWriter;
147
148impl PromptWriter for StdoutWriter {
149    fn write(&mut self, text: &str) {
150        let _ = io::stdout().write_all(text.as_bytes());
151    }
152
153    fn flush(&mut self) -> io::Result<()> {
154        io::stdout().flush()
155    }
156}
157
158/// Restores the terminal to cooked mode when dropped, even on early returns.
159struct RawModeGuard;
160
161impl RawModeGuard {
162    fn enable() -> io::Result<Self> {
163        crossterm::terminal::enable_raw_mode()?;
164        Ok(Self)
165    }
166}
167
168impl Drop for RawModeGuard {
169    fn drop(&mut self) {
170        let _ = crossterm::terminal::disable_raw_mode();
171    }
172}
173
174/// Asks `message` as a yes/no question and returns the user's decision.
175///
176/// - `(Y/n)` / `[y]` when `default` is `true`; `(y/N)` / `[n]` otherwise.
177/// - A single `y`/`Y` (or `yes`) answers yes; `n`/`N` (or `no`) answers no.
178/// - Enter (empty input) answers with `default`.
179/// - Anything else prints `Please enter y or n` and asks again.
180/// - After [`CONFIRM_TIMEOUT`] the prompt falls back to `default`.
181///
182/// No confirmation prompt works without a terminal; use
183/// [`prompt_user_confirmation_with`] for mockable input.
184pub fn prompt_user_confirmation(message: &str, default: bool) -> bool {
185    let _guard = RawModeGuard::enable().ok();
186    let mut reader = TerminalKeyReader;
187    let mut writer = StdoutWriter;
188    prompt_user_confirmation_with(message, default, CONFIRM_TIMEOUT, &mut reader, &mut writer)
189}
190
191/// Testable core of [`prompt_user_confirmation`]; see the module docs.
192pub fn prompt_user_confirmation_with(
193    message: &str,
194    default: bool,
195    timeout: Duration,
196    reader: &mut dyn KeyReader,
197    writer: &mut dyn PromptWriter,
198) -> bool {
199    loop {
200        writer.write(&prompt_line(message, default));
201        let _ = writer.flush();
202
203        let Some(key) = reader.read_key(timeout) else {
204            writer.write(&format!(
205                "\n(timeout after {timeout:?} — using default {})",
206                if default { "yes" } else { "no" }
207            ));
208            let _ = writer.flush();
209            return default;
210        };
211
212        // Visual feedback: one star per received keypress.
213        writer.write("*");
214        let _ = writer.flush();
215
216        match parse_confirmation_key(key, default) {
217            Some(decision) => {
218                writer.write("\n");
219                let _ = writer.flush();
220                return decision;
221            }
222            None => {
223                writer.write(format!("\n{INVALID_INPUT_MSG}\n").as_str());
224                let _ = writer.flush();
225            }
226        }
227    }
228}
229
230/// Builds the `❓ … (Y/n) [y]\n>> ` prompt line for `default`.
231fn prompt_line(message: &str, default: bool) -> String {
232    let hint = if default { "(Y/n)" } else { "(y/N)" };
233    let bracket = if default { "[y]" } else { "[n]" };
234    format!("❓ {message} {hint} {bracket}\n>> ")
235}
236
237/// Maps one key press to a decision. Returns:
238/// - `Some(true|false)` — decisive, stop asking;
239/// - `Some(_)` on Enter — use the default;
240/// - `None` — invalid input, ask again.
241fn parse_confirmation_key(key: Key, default: bool) -> Option<bool> {
242    match key {
243        Key::Char(c) if c.eq_ignore_ascii_case(&'y') => Some(true),
244        Key::Char(c) if c.eq_ignore_ascii_case(&'n') => Some(false),
245        Key::Enter | Key::Char('\r') | Key::Char('\n') => Some(default),
246        Key::Char('\u{3}') => Some(default), // Ctrl-C: bail with default
247        _ => None,
248    }
249}
250
251/// Builds a fix list from `mentor_messages`-style suggestions.
252///
253/// ```
254/// use limitless_cli::modules::interactive_prompt::{Fix, fixes_from_mentors};
255/// let fixes = fixes_from_mentors(&["Fix A".into(), "Fix B".into()]);
256/// assert_eq!(fixes.len(), 2);
257/// assert_eq!(fixes[0].description, "Fix A");
258/// ```
259pub fn fixes_from_mentors(suggestions: &[String]) -> Vec<Fix> {
260    suggestions.iter().map(|s| Fix::new(s.clone())).collect()
261}
262
263/// Renders a checkbox list and returns the user-selected fixes.
264///
265/// - Up / Down arrows move the highlight.
266/// - Space toggles the highlighted entry.
267/// - Enter confirms; Escape cancels (returns `[]`).
268/// - If nothing is pressed for [`SELECT_IDLE_TIMEOUT`], the currently
269///   selected entries are returned.
270///
271/// ```
272/// use limitless_cli::modules::interactive_prompt::{
273///     CapturingWriter, Fix, Key, MockKeyReader, prompt_fix_selection_with,
274/// };
275///
276/// let fixes = vec![Fix::new("Copy .env.example"), Fix::new("Terminate ghost"),
277///                  Fix::new("Update dependencies")];
278/// let mut reader = MockKeyReader::new(vec![Key::Down, Key::Space, Key::Enter]);
279/// let mut writer = CapturingWriter::default();
280/// let chosen = prompt_fix_selection_with(&fixes, &mut reader, &mut writer);
281/// assert_eq!(chosen.len(), 1);
282/// assert_eq!(chosen[0].description, "Terminate ghost");
283/// assert!(writer.output.contains("☑ Terminate ghost"));
284/// ```
285pub fn prompt_fix_selection(fixes: &[Fix]) -> Vec<Fix> {
286    let _guard = RawModeGuard::enable().ok();
287    let mut reader = TerminalKeyReader;
288    let mut writer = StdoutWriter;
289    prompt_fix_selection_with(fixes, &mut reader, &mut writer)
290}
291
292/// Testable core of [`prompt_fix_selection`]; see the module docs.
293pub fn prompt_fix_selection_with(
294    fixes: &[Fix],
295    reader: &mut dyn KeyReader,
296    writer: &mut dyn PromptWriter,
297) -> Vec<Fix> {
298    if fixes.is_empty() {
299        return Vec::new();
300    }
301
302    let count = fixes.len();
303    let mut index = 0usize;
304    let mut toggled = vec![false; count];
305
306    render_all(writer, fixes, index, &toggled, false);
307    let _ = writer.flush();
308
309    loop {
310        match reader.read_key(SELECT_IDLE_TIMEOUT) {
311            Some(Key::Up) => {
312                index = (index + count - 1) % count;
313                redraw(writer, fixes, index, &toggled);
314            }
315            Some(Key::Down) => {
316                index = (index + 1) % count;
317                redraw(writer, fixes, index, &toggled);
318            }
319            Some(Key::Space) => {
320                toggled[index] = !toggled[index];
321                redraw(writer, fixes, index, &toggled);
322            }
323            Some(Key::Enter) | Some(Key::Char('\r')) | Some(Key::Char('\n')) => {
324                writer.write("\x1b[2K\r");
325                let _ = writer.flush();
326                return collect_selected(fixes, &toggled);
327            }
328            Some(Key::Esc) => {
329                writer.write("\n");
330                let _ = writer.flush();
331                return Vec::new();
332            }
333            None => {
334                // Idle for SELECT_IDLE_TIMEOUT: return the current selection.
335                writer.write("\n");
336                let _ = writer.flush();
337                return collect_selected(fixes, &toggled);
338            }
339            Some(Key::Unknown) => {
340                // Ignore keys we do not understand and keep waiting.
341                continue;
342            }
343            Some(_) => {
344                // Any other printable character: ignore and keep waiting.
345                continue;
346            }
347        }
348    }
349}
350
351/// Collects the fixes whose checkbox is toggled on.
352fn collect_selected(fixes: &[Fix], toggled: &[bool]) -> Vec<Fix> {
353    fixes
354        .iter()
355        .zip(toggled)
356        .filter(|(_, on)| **on)
357        .map(|(fix, _)| fix.clone())
358        .collect()
359}
360
361/// Draws the header plus one row per fix.
362///
363/// When `clear` is set every line is first erased with `\r\x1b[2K`, which lets
364/// callers refresh the list in place after a key press.
365fn render_all(
366    writer: &mut dyn PromptWriter,
367    fixes: &[Fix],
368    index: usize,
369    toggled: &[bool],
370    clear: bool,
371) {
372    let erase = if clear { "\r\x1b[2K" } else { "" };
373    let mut out = String::new();
374    out.push_str(&format!(
375        "{erase}Which issues should we fix? (arrow keys to move, space to select)\n"
376    ));
377    for (i, fix) in fixes.iter().enumerate() {
378        let marker = if toggled[i] { "☑" } else { "☐" };
379        if i == index {
380            out.push_str(&format!(
381                "{erase}\x1b[7m> {marker} {}\x1b[0m\n",
382                fix.description
383            ));
384        } else {
385            out.push_str(&format!("{erase}  {marker} {}\n", fix.description));
386        }
387    }
388    writer.write(&out);
389}
390
391/// Moves the cursor back up over the rendered list and redraws it.
392fn redraw(writer: &mut dyn PromptWriter, fixes: &[Fix], index: usize, toggled: &[bool]) {
393    let lines = 1 + fixes.len();
394    writer.write(&format!("\x1b[{lines}A"));
395    render_all(writer, fixes, index, toggled, true);
396    let _ = writer.flush();
397}
398
399/// A [`KeyReader`] that replays a canned sequence of keys for tests.
400#[derive(Debug, Clone)]
401pub struct MockKeyReader {
402    keys: VecDeque<Key>,
403    timeouts: u32,
404}
405
406impl MockKeyReader {
407    /// Creates a reader that will replay `keys` in order, then return `None`.
408    pub fn new(keys: Vec<Key>) -> Self {
409        Self {
410            keys: keys.into(),
411            timeouts: 0,
412        }
413    }
414
415    /// Prepends `timeouts` simulated `None` results (i.e. expired waits).
416    pub fn with_timeouts(mut self, timeouts: u32) -> Self {
417        self.timeouts = timeouts;
418        self
419    }
420}
421
422impl KeyReader for MockKeyReader {
423    fn read_key(&mut self, _timeout: Duration) -> Option<Key> {
424        if self.timeouts > 0 {
425            self.timeouts -= 1;
426            return None;
427        }
428        self.keys.pop_front()
429    }
430}
431
432/// A [`PromptWriter`] that records everything written for assertions.
433#[derive(Debug, Clone, Default)]
434pub struct CapturingWriter {
435    /// All text written so far, in order.
436    pub output: String,
437}
438
439impl PromptWriter for CapturingWriter {
440    fn write(&mut self, text: &str) {
441        self.output.push_str(text);
442    }
443
444    fn flush(&mut self) -> io::Result<()> {
445        Ok(())
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452
453    fn keys(values: &[char]) -> Vec<Key> {
454        values.iter().map(|c| Key::Char(*c)).collect()
455    }
456
457    fn run_confirmation(keys: Vec<Key>, default: bool, timeouts: u32) -> (bool, String) {
458        let mut reader = MockKeyReader::new(keys).with_timeouts(timeouts);
459        let mut writer = CapturingWriter::default();
460        let result = prompt_user_confirmation_with(
461            "Copy .env.example to .env?",
462            default,
463            Duration::from_secs(30),
464            &mut reader,
465            &mut writer,
466        );
467        (result, writer.output)
468    }
469
470    #[test]
471    fn lower_y_answers_yes() {
472        let (ok, out) = run_confirmation(keys(&['y']), true, 0);
473        assert!(ok);
474        assert!(out.contains("❓ Copy .env.example to .env? (Y/n) [y]"));
475        assert!(out.contains(">> "));
476        assert!(out.contains('*'), "visual feedback star expected");
477    }
478
479    #[test]
480    fn upper_y_answers_yes() {
481        let (ok, _) = run_confirmation(keys(&['Y']), false, 0);
482        assert!(ok);
483    }
484
485    #[test]
486    fn lower_n_answers_no() {
487        let (ok, _) = run_confirmation(keys(&['n']), true, 0);
488        assert!(!ok);
489    }
490
491    #[test]
492    fn upper_n_answers_no() {
493        let (ok, _) = run_confirmation(keys(&['N']), true, 0);
494        assert!(!ok);
495    }
496
497    #[test]
498    fn yes_word_first_char_decides() {
499        let (ok, _) = run_confirmation(keys(&['y', 'e', 's']), false, 0);
500        assert!(ok);
501    }
502
503    #[test]
504    fn no_word_first_char_decides() {
505        let (ok, _) = run_confirmation(keys(&['n', 'o']), true, 0);
506        assert!(!ok);
507    }
508
509    #[test]
510    fn enter_uses_default_true() {
511        let (ok, _) = run_confirmation(vec![Key::Enter], true, 0);
512        assert!(ok);
513    }
514
515    #[test]
516    fn enter_uses_default_false() {
517        let (ok, _) = run_confirmation(vec![Key::Enter], false, 0);
518        assert!(!ok);
519    }
520
521    #[test]
522    fn default_true_renders_caps_hint() {
523        let (_, out) = run_confirmation(keys(&['y']), true, 0);
524        assert!(out.contains("(Y/n) [y]"));
525    }
526
527    #[test]
528    fn default_false_renders_other_hint() {
529        let (_, out) = run_confirmation(keys(&['n']), false, 0);
530        assert!(out.contains("(y/N) [n]"));
531    }
532
533    #[test]
534    fn invalid_input_reprompts_then_accepts() {
535        let (ok, out) = run_confirmation(vec![Key::Char('x'), Key::Char('n')], true, 0);
536        assert!(!ok, "second key 'n' should answer no");
537        assert_eq!(out.matches(INVALID_INPUT_MSG).count(), 1);
538        assert_eq!(out.matches(">> ").count(), 2);
539    }
540
541    #[test]
542    fn invalid_input_until_enter_uses_default() {
543        let (ok, out) = run_confirmation(vec![Key::Char('?'), Key::Enter], true, 0);
544        assert!(ok);
545        assert_eq!(out.matches(INVALID_INPUT_MSG).count(), 1);
546    }
547
548    #[test]
549    fn timeout_uses_default() {
550        let (ok, out) = run_confirmation(vec![], true, 1);
551        assert!(ok, "timeout should fall back to default(true)");
552        assert!(out.contains("timeout"));
553        assert!(out.contains("default yes"));
554    }
555
556    #[test]
557    fn timeout_uses_default_false() {
558        let (ok, out) = run_confirmation(vec![], false, 1);
559        assert!(!ok);
560        assert!(out.contains("default no"));
561    }
562
563    #[test]
564    fn repeated_timeouts_do_not_hang() {
565        let (ok, out) = run_confirmation(vec![], true, 5);
566        assert!(ok);
567        assert_eq!(out.matches("timeout").count(), 1);
568    }
569
570    #[test]
571    fn unicode_message_preserved() {
572        let mut reader = MockKeyReader::new(vec![Key::Char('y')]);
573        let mut writer = CapturingWriter::default();
574        prompt_user_confirmation_with(
575            "Déployer 🚀 ?",
576            true,
577            Duration::from_secs(30),
578            &mut reader,
579            &mut writer,
580        );
581        assert!(writer.output.contains("Déployer 🚀 ?"));
582    }
583
584    // ------------------------------------------------------------------
585    // Fix selection
586    // ------------------------------------------------------------------
587
588    fn sample_fixes() -> Vec<Fix> {
589        vec![
590            Fix::new("Copy .env.example to .env"),
591            Fix::new("Terminate ghost process on port 3000"),
592            Fix::new("Update dependencies"),
593        ]
594    }
595
596    fn run_selection(keys: Vec<Key>) -> (Vec<Fix>, String) {
597        let mut reader = MockKeyReader::new(keys);
598        let mut writer = CapturingWriter::default();
599        let chosen = prompt_fix_selection_with(&sample_fixes(), &mut reader, &mut writer);
600        (chosen, writer.output)
601    }
602
603    #[test]
604    fn selection_toggle_with_arrows_and_space() {
605        let (chosen, out) = run_selection(vec![
606            Key::Down,  // move to 1
607            Key::Space, // toggle fix 1 on
608            Key::Down,  // move to 2
609            Key::Space, // toggle fix 2 on
610            Key::Up,    // back to 1
611            Key::Space, // toggle fix 1 off
612            Key::Enter,
613        ]);
614        assert_eq!(chosen.len(), 1);
615        assert_eq!(chosen[0].description, "Update dependencies");
616        assert!(out.contains("Which issues should we fix?"));
617        assert!(out.contains("☑") && out.contains("☐"));
618        assert!(out.contains("☑ Update dependencies"));
619    }
620
621    #[test]
622    fn selection_enter_without_toggles_returns_empty() {
623        let (chosen, _) = run_selection(vec![Key::Enter]);
624        assert!(chosen.is_empty());
625    }
626
627    #[test]
628    fn selection_escape_cancels() {
629        let (chosen, _) = run_selection(vec![Key::Down, Key::Space, Key::Esc]);
630        assert!(chosen.is_empty());
631    }
632
633    #[test]
634    fn selection_wraps_around_top_and_bottom() {
635        let (chosen, _) = run_selection(vec![
636            Key::Up,    // wraps to last (index 2)
637            Key::Space, // toggle last on
638            Key::Enter,
639        ]);
640        assert_eq!(chosen.len(), 1);
641        assert_eq!(chosen[0].description, "Update dependencies");
642    }
643
644    #[test]
645    fn selection_unknown_keys_are_ignored() {
646        let (chosen, _) = run_selection(vec![
647            Key::Unknown,
648            Key::Unknown,
649            Key::Space,
650            Key::Unknown,
651            Key::Enter,
652        ]);
653        assert_eq!(chosen.len(), 1);
654        assert_eq!(chosen[0].description, "Copy .env.example to .env");
655    }
656
657    #[test]
658    fn selection_empty_fixes_returns_empty_immediately() {
659        let mut reader = MockKeyReader::new(vec![Key::Enter]);
660        let mut writer = CapturingWriter::default();
661        let chosen = prompt_fix_selection_with(&[], &mut reader, &mut writer);
662        assert!(chosen.is_empty());
663        assert!(writer.output.is_empty());
664    }
665
666    #[test]
667    fn selection_idle_timeout_keeps_current_choice() {
668        let mut reader = MockKeyReader::new(vec![Key::Down, Key::Space]);
669        let mut writer = CapturingWriter::default();
670        let chosen = prompt_fix_selection_with(&sample_fixes(), &mut reader, &mut writer);
671        assert_eq!(chosen.len(), 1);
672        assert_eq!(
673            chosen[0].description,
674            "Terminate ghost process on port 3000"
675        );
676    }
677
678    #[test]
679    fn fixes_from_mentors_maps_descriptions() {
680        let suggestions = vec![
681            "Install npm".to_string(),
682            "Set EDITOR".to_string(),
683            "Kill ghost process".to_string(),
684        ];
685        let fixes = fixes_from_mentors(&suggestions);
686        assert_eq!(fixes.len(), 3);
687        assert_eq!(fixes[2].description, "Kill ghost process");
688    }
689}