rskit-cli 0.2.0-alpha.2

CLI framework: progress bars, structured output, signal handling
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! The [`Prompter`]: a terminal-agnostic driver for every prompt kind.
//!
//! A `Prompter` binds three things — a [`Terminal`], a resolved [`PromptMode`],
//! and a rendering [`Style`] — and exposes one method per question type. The
//! prompt-kind logic lives in [`super::kinds`]; the prompter only wires the
//! shared state through to it, so the same call works over cooked stdio, a
//! raw-mode TTY, or a scripted test double.
//!
//! Build one from the environment with [`Prompter::from_env`] — which auto-selects
//! a rich raw-mode terminal when one is available and the `interactive` feature
//! is compiled, else a line terminal — or from explicit parts with
//! [`Prompter::new`] for deterministic tests.

use std::io::IsTerminal;

use rskit_errors::AppResult;

use super::choice::{Choice, ChoiceId};
use super::kinds;
use super::mode::PromptMode;
use super::render::Style;
use super::terminal::{LineTerminal, Terminal};
use super::validate::Validator;
use crate::theme::{ColorChoice, Glyphs, Palette};

/// A terminal-agnostic prompt driver.
///
/// Generic over its [`Terminal`] so tests can bind a
/// [`ScriptedTerminal`](super::terminal::ScriptedTerminal) directly while
/// [`Prompter::from_env`] erases the concrete terminal behind a `Box<dyn Terminal>`.
pub struct Prompter<T> {
    terminal: T,
    mode: PromptMode,
    style: Style,
}

impl Prompter<Box<dyn Terminal>> {
    /// Build a prompter bound to the process environment.
    ///
    /// The [`PromptMode`] follows whether both stdin and stderr are terminals,
    /// and the [`Palette`] follows `color` against stderr, so interactivity and
    /// styling both honour redirection and `NO_COLOR`. Prompts render to stderr,
    /// so a redirected stderr (e.g. `cmd 2>log`) forces [`PromptMode::NonInteractive`]
    /// rather than blocking on input behind an invisible prompt. When the
    /// `interactive` feature is compiled and both streams are terminals, a rich
    /// raw-mode terminal is selected for arrow-key navigation; otherwise a line
    /// terminal is used.
    #[must_use]
    pub fn from_env(color: ColorChoice) -> Self {
        let stderr = std::io::stderr();
        let mode = PromptMode::from_stdio(std::io::stdin().is_terminal(), stderr.is_terminal());
        let palette = Palette::for_stream(color, &stderr);
        let glyphs = Glyphs::from_env();
        let terminal = resolve_terminal(mode.is_interactive());
        Self {
            terminal,
            mode,
            style: Style::new(palette, glyphs),
        }
    }
}

impl<T: Terminal> Prompter<T> {
    /// Build a prompter from an explicit terminal, mode, and palette.
    ///
    /// Glyphs default to the ASCII fallback for byte-clean, deterministic tests;
    /// override with [`Prompter::with_glyphs`].
    #[must_use]
    pub const fn new(terminal: T, mode: PromptMode, palette: Palette) -> Self {
        Self {
            terminal,
            mode,
            style: Style::new(palette, Glyphs::new(false)),
        }
    }

    /// Override the glyph set (Unicode symbols vs ASCII fallback).
    #[must_use]
    pub const fn with_glyphs(mut self, glyphs: Glyphs) -> Self {
        self.style = Style::new(self.style.palette(), glyphs);
        self
    }

    /// The resolved interaction mode.
    #[must_use]
    pub const fn mode(&self) -> PromptMode {
        self.mode
    }

    /// The bound terminal, for inspecting captured output in tests.
    #[must_use]
    pub const fn terminal(&self) -> &T {
        &self.terminal
    }

    /// Ask for exactly one choice.
    ///
    /// In [`PromptMode::NonInteractive`] this resolves to the recommended choice;
    /// with none it is a typed error. A key-driven terminal shows an arrow-key
    /// radio list; a line-driven terminal shows a numbered list.
    ///
    /// # Errors
    ///
    /// Returns an error when `choices` is empty, when a non-interactive prompt has
    /// no recommended default, when the user cancels, or when input closes early.
    pub fn select(&mut self, prompt: &str, choices: &[Choice]) -> AppResult<ChoiceId> {
        kinds::select::run(&mut self.terminal, self.style, self.mode, prompt, choices)
    }

    /// Ask for zero or more choices.
    ///
    /// The default answer is the set of recommended choices, which may be empty.
    /// A key-driven terminal shows an arrow-key checkbox list; a line-driven
    /// terminal accepts a comma-separated list of numbers.
    ///
    /// # Errors
    ///
    /// Returns an error when `choices` is empty, when the user cancels, or when
    /// input closes early.
    pub fn multi_select(&mut self, prompt: &str, choices: &[Choice]) -> AppResult<Vec<ChoiceId>> {
        kinds::multi_select::run(&mut self.terminal, self.style, self.mode, prompt, choices)
    }

    /// Ask a yes/no question with an explicit default.
    ///
    /// # Errors
    ///
    /// Returns an error when the user cancels or when input closes early.
    pub fn confirm(&mut self, prompt: &str, default: bool) -> AppResult<bool> {
        kinds::confirm::run(&mut self.terminal, self.style, self.mode, prompt, default)
    }

    /// Ask for freeform text with an optional default.
    ///
    /// In [`PromptMode::NonInteractive`] this resolves to `default`; with none it
    /// is a typed error.
    ///
    /// # Errors
    ///
    /// Returns an error when a non-interactive prompt has no default, when the
    /// user cancels, or when input closes early.
    pub fn text(&mut self, prompt: &str, default: Option<&str>) -> AppResult<String> {
        kinds::text::run(
            &mut self.terminal,
            self.style,
            self.mode,
            prompt,
            default,
            None,
        )
    }

    /// Ask for freeform text validated by `validator`, re-asking on rejection.
    ///
    /// In [`PromptMode::NonInteractive`] a rejected default is a typed error
    /// rather than a silent bad value.
    ///
    /// # Errors
    ///
    /// Returns an error when a non-interactive prompt has no default or a rejected
    /// default, when the user cancels, or when input closes early.
    pub fn text_with(
        &mut self,
        prompt: &str,
        default: Option<&str>,
        validator: &dyn Validator,
    ) -> AppResult<String> {
        kinds::text::run(
            &mut self.terminal,
            self.style,
            self.mode,
            prompt,
            default,
            Some(validator),
        )
    }
}

/// Select the concrete terminal for [`Prompter::from_env`]: rich when a TTY is
/// present and the `interactive` feature is compiled, else line.
fn resolve_terminal(is_tty: bool) -> Box<dyn Terminal> {
    #[cfg(feature = "interactive")]
    {
        if is_tty && let Ok(terminal) = super::terminal::RichTerminal::stderr() {
            return Box::new(terminal);
        }
    }
    #[cfg(not(feature = "interactive"))]
    let _ = is_tty;
    Box::new(LineTerminal::stdio())
}

#[cfg(test)]
mod tests {
    use super::{Choice, ChoiceId, Palette, PromptMode, Prompter};
    use crate::prompt::key::Key;
    use crate::prompt::terminal::ScriptedTerminal;
    use crate::prompt::validate::non_empty;
    use crate::theme::{ColorChoice, Glyphs};

    fn plain_choices() -> Vec<Choice> {
        vec![
            Choice::new("go", "Go"),
            Choice::new("rust", "Rust").recommended(),
            Choice::new("node", "Node.js"),
        ]
    }

    fn no_default_choices() -> Vec<Choice> {
        vec![Choice::new("go", "Go"), Choice::new("rust", "Rust")]
    }

    fn line_prompter(
        terminal: ScriptedTerminal,
        mode: PromptMode,
        color: bool,
    ) -> Prompter<ScriptedTerminal> {
        Prompter::new(terminal, mode, Palette::new(color))
    }

    // ── Non-interactive resolution ──────────────────────────────────────

    #[test]
    fn non_interactive_select_resolves_to_recommended() {
        let choice = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect("recommended default resolves");
        assert_eq!(choice, ChoiceId::new("rust"));
    }

    #[test]
    fn non_interactive_select_without_default_errors() {
        let choices = vec![Choice::new("go", "Go"), Choice::new("rust", "Rust")];
        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .select("Ecosystem?", &choices)
        .expect_err("no recommended default must error");
        assert!(err.message().contains("non-interactive"));
    }

    #[test]
    fn non_interactive_multi_select_returns_recommended_set() {
        let selected = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .multi_select("Tasks?", &plain_choices())
        .expect("recommended set resolves");
        assert_eq!(selected, vec![ChoiceId::new("rust")]);
    }

    #[test]
    fn non_interactive_multi_select_allows_empty_default() {
        let choices = vec![Choice::new("a", "A"), Choice::new("b", "B")];
        let selected = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .multi_select("Tasks?", &choices)
        .expect("empty selection is valid");
        assert!(selected.is_empty());
    }

    #[test]
    fn non_interactive_confirm_returns_default() {
        let value = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .confirm("Proceed?", true)
        .expect("confirm resolves to default");
        assert!(value);
    }

    #[test]
    fn non_interactive_text_uses_default_and_errors_without_one() {
        let value = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .text("Name?", Some("toven"))
        .expect("text resolves to default");
        assert_eq!(value, "toven");

        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .text("Name?", None)
        .expect_err("no default must error");
        assert!(err.message().contains("non-interactive"));
    }

    #[test]
    fn non_interactive_text_with_rejects_invalid_default() {
        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .text_with("Name?", Some("  "), &non_empty("required"))
        .expect_err("invalid default must error");
        assert!(err.message().contains("invalid"));
    }

    // ── Line-driven interaction ─────────────────────────────────────────

    #[test]
    fn line_select_reads_a_numbered_answer() {
        let choice = line_prompter(
            ScriptedTerminal::line_driven().with_line("1"),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect("first choice selected");
        assert_eq!(choice, ChoiceId::new("go"));
    }

    #[test]
    fn line_select_empty_line_accepts_recommended() {
        let choice = line_prompter(
            ScriptedTerminal::line_driven().with_line(""),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect("blank accepts recommended");
        assert_eq!(choice, ChoiceId::new("rust"));
    }

    #[test]
    fn line_select_reprompts_on_invalid_then_succeeds() {
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_lines(["9", "x", "3"]),
            PromptMode::Interactive,
            false,
        );
        let choice = prompter
            .select("Ecosystem?", &plain_choices())
            .expect("valid choice after retries");
        assert_eq!(choice, ChoiceId::new("node"));
        assert!(prompter.terminal().output().contains("between 1 and 3"));
    }

    #[test]
    fn line_select_errors_when_input_closes() {
        let choices = vec![Choice::new("go", "Go"), Choice::new("rust", "Rust")];
        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &choices)
        .expect_err("closed input must error, not hang");
        assert!(err.message().contains("input closed"));
    }

    #[test]
    fn line_multi_select_parses_and_dedupes() {
        let selected = line_prompter(
            ScriptedTerminal::line_driven().with_line("3, 1, 1"),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &plain_choices())
        .expect("comma list parses");
        assert_eq!(selected, vec![ChoiceId::new("node"), ChoiceId::new("go")]);
    }

    #[test]
    fn line_multi_select_empty_line_uses_defaults() {
        let selected = line_prompter(
            ScriptedTerminal::line_driven().with_line(""),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &plain_choices())
        .expect("blank uses recommended defaults");
        assert_eq!(selected, vec![ChoiceId::new("rust")]);
    }

    #[test]
    fn line_confirm_parses_yes_no_and_default() {
        assert!(
            line_prompter(
                ScriptedTerminal::line_driven().with_line("y"),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", false)
            .expect("yes")
        );
        assert!(
            !line_prompter(
                ScriptedTerminal::line_driven().with_line("no"),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", true)
            .expect("no")
        );
        assert!(
            line_prompter(
                ScriptedTerminal::line_driven().with_line(""),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", true)
            .expect("blank uses default")
        );
    }

    #[test]
    fn line_text_reads_value_and_falls_back_to_default() {
        let value = line_prompter(
            ScriptedTerminal::line_driven().with_line("custom"),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", Some("toven"))
        .expect("typed value");
        assert_eq!(value, "custom");

        let value = line_prompter(
            ScriptedTerminal::line_driven().with_line(""),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", Some("toven"))
        .expect("blank uses default");
        assert_eq!(value, "toven");
    }

    #[test]
    fn line_text_with_reasks_until_valid() {
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_lines(["  ", "ok"]),
            PromptMode::Interactive,
            false,
        );
        let value = prompter
            .text_with("Name?", None, &non_empty("required"))
            .expect("valid after retry");
        assert_eq!(value, "ok");
        assert!(prompter.terminal().output().contains("required"));
    }

    // ── Key-driven interaction ──────────────────────────────────────────

    #[test]
    fn key_select_navigates_and_confirms() {
        let choice = line_prompter(
            ScriptedTerminal::key_driven().with_keys([Key::Down, Key::Enter]),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect("arrow navigation selects");
        assert_eq!(choice, ChoiceId::new("node"));
    }

    #[test]
    fn key_select_starts_on_recommended_default() {
        let choice = line_prompter(
            ScriptedTerminal::key_driven().with_key(Key::Enter),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect("enter accepts default");
        assert_eq!(choice, ChoiceId::new("rust"));
    }

    #[test]
    fn key_select_escape_cancels() {
        let err = line_prompter(
            ScriptedTerminal::key_driven().with_key(Key::Escape),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect_err("escape cancels");
        assert!(err.message().contains("cancelled"));
    }

    #[test]
    fn key_multi_select_toggles_selection() {
        // Recommended (Rust, index 1) starts selected; toggle Go on, Rust off,
        // Node on, to exercise toggling in both directions.
        let selected = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::Space, // Go on
                Key::Down,
                Key::Space, // Rust off
                Key::Down,
                Key::Space, // Node on
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &plain_choices())
        .expect("space toggles");
        assert_eq!(selected, vec![ChoiceId::new("go"), ChoiceId::new("node")]);
    }

    #[test]
    fn key_confirm_reads_letter() {
        assert!(
            line_prompter(
                ScriptedTerminal::key_driven().with_key(Key::Char('y')),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", false)
            .expect("y confirms")
        );
    }

    #[test]
    fn key_text_edits_with_backspace() {
        let value = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::Char('h'),
                Key::Char('i'),
                Key::Char('x'),
                Key::Backspace,
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", None)
        .expect("typed value");
        assert_eq!(value, "hi");
    }

    #[test]
    fn key_text_inserts_literal_space() {
        // The space bar decodes to Key::Space (not Key::Char(' ')), so text entry
        // must treat it as a literal space — otherwise multi-word answers are
        // impossible on a real rich terminal.
        let value = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::Char('h'),
                Key::Char('i'),
                Key::Space,
                Key::Char('t'),
                Key::Char('h'),
                Key::Char('e'),
                Key::Char('r'),
                Key::Char('e'),
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", None)
        .expect("typed value");
        assert_eq!(value, "hi there");
    }

    #[test]
    fn key_select_runs_in_raw_mode_and_restores() {
        let mut prompter = line_prompter(
            ScriptedTerminal::key_driven().with_key(Key::Enter),
            PromptMode::Interactive,
            false,
        );
        let _ = prompter
            .select("Ecosystem?", &plain_choices())
            .expect("select");
        assert!(!prompter.terminal().is_interactive(), "raw mode restored");
    }

    // ── Rendering & metadata ────────────────────────────────────────────

    #[test]
    fn choice_metadata_round_trips_into_rendered_output() {
        let choices = vec![
            Choice::new("rust", "Rust")
                .with_annotation("detected in dev-deps")
                .recommended(),
            Choice::new("go", "Go"),
        ];
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_line("1"),
            PromptMode::Interactive,
            false,
        );
        let _ = prompter.select("Ecosystem?", &choices).expect("select");
        let rendered = prompter.terminal().output();
        assert!(rendered.contains("Rust"));
        assert!(rendered.contains("detected in dev-deps"));
        assert!(rendered.contains("(recommended)"));
    }

    #[test]
    fn disabled_palette_renders_without_ansi_escapes() {
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_line("1"),
            PromptMode::Interactive,
            false,
        );
        let _ = prompter
            .select("Ecosystem?", &plain_choices())
            .expect("select");
        assert!(
            !prompter.terminal().output().contains('\u{1b}'),
            "no color must be byte-clean"
        );
    }

    #[test]
    fn enabled_palette_emits_ansi_escapes() {
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_line("1"),
            PromptMode::Interactive,
            true,
        );
        let _ = prompter
            .select("Ecosystem?", &plain_choices())
            .expect("select");
        assert!(
            prompter.terminal().output().contains('\u{1b}'),
            "color must emit SGR escapes"
        );
    }

    #[test]
    fn empty_choice_set_is_rejected() {
        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &[])
        .expect_err("empty choices rejected");
        assert!(err.message().contains("at least one choice"));
    }

    #[test]
    fn multi_select_empty_choice_set_is_rejected() {
        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &[])
        .expect_err("empty choices rejected");
        assert!(err.message().contains("at least one choice"));
    }

    // ── Confirm: key- and line-driven branches ──────────────────────────

    #[test]
    fn key_confirm_enter_default_letter_no_and_escape() {
        // Enter accepts the default.
        assert!(
            line_prompter(
                ScriptedTerminal::key_driven().with_key(Key::Enter),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", true)
            .expect("enter accepts default")
        );
        // 'n' declines.
        assert!(
            !line_prompter(
                ScriptedTerminal::key_driven().with_key(Key::Char('n')),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", true)
            .expect("n declines")
        );
        // An unrelated key is ignored before 'Y' confirms.
        assert!(
            line_prompter(
                ScriptedTerminal::key_driven().with_keys([Key::Left, Key::Char('Y')]),
                PromptMode::Interactive,
                false
            )
            .confirm("Proceed?", false)
            .expect("Y confirms after an ignored key")
        );
        // Escape cancels.
        let err = line_prompter(
            ScriptedTerminal::key_driven().with_key(Key::Escape),
            PromptMode::Interactive,
            false,
        )
        .confirm("Proceed?", true)
        .expect_err("escape cancels");
        assert!(err.message().contains("cancelled"));
    }

    #[test]
    fn line_confirm_reprompts_on_invalid_and_errors_on_close() {
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_lines(["maybe", "yes"]),
            PromptMode::Interactive,
            false,
        );
        assert!(
            prompter
                .confirm("Proceed?", false)
                .expect("yes after retry")
        );
        assert!(prompter.terminal().output().contains("'y' or 'n'"));

        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::Interactive,
            false,
        )
        .confirm("Proceed?", true)
        .expect_err("closed input must error");
        assert!(err.message().contains("input closed"));
    }

    // ── Select: extra key navigation and line branches ──────────────────

    #[test]
    fn key_select_home_end_and_up_navigate_and_ignore_unrelated_keys() {
        // Start on the recommended default (Rust, index 1): End→node(2),
        // Home→go(0), Down→rust(1), Up→go(0), Tab→rust(1), Left is ignored,
        // Enter confirms Rust.
        let choice = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::End,
                Key::Home,
                Key::Down,
                Key::Up,
                Key::Tab,
                Key::Left,
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        )
        .select("Ecosystem?", &plain_choices())
        .expect("navigation resolves");
        assert_eq!(choice, ChoiceId::new("rust"));
    }

    #[test]
    fn line_select_empty_without_default_requires_a_choice() {
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_lines(["", "2"]),
            PromptMode::Interactive,
            false,
        );
        let choice = prompter
            .select("Ecosystem?", &no_default_choices())
            .expect("valid choice after the required notice");
        assert_eq!(choice, ChoiceId::new("rust"));
        assert!(
            prompter
                .terminal()
                .output()
                .contains("a choice is required")
        );
    }

    // ── Multi-select: extra key navigation and line branches ────────────

    #[test]
    fn key_multi_select_escape_cancels_and_navigation_wraps() {
        let err = line_prompter(
            ScriptedTerminal::key_driven().with_key(Key::Escape),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &plain_choices())
        .expect_err("escape cancels");
        assert!(err.message().contains("cancelled"));

        // End→2, Home→0, Up→2, Tab→0, Left ignored, Space toggles Go on, Enter.
        let selected = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::End,
                Key::Home,
                Key::Up,
                Key::Tab,
                Key::Left,
                Key::Space,
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &plain_choices())
        .expect("navigation and toggle resolve");
        assert_eq!(selected, vec![ChoiceId::new("go"), ChoiceId::new("rust")]);
    }

    #[test]
    fn line_multi_select_notice_none_hint_and_close() {
        // No recommended choice → the default hint reads `[none]`; an invalid
        // answer shows a notice before a valid comma list is accepted.
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_lines(["x", "1,2"]),
            PromptMode::Interactive,
            false,
        );
        let selected = prompter
            .multi_select("Tasks?", &no_default_choices())
            .expect("valid list after the notice");
        assert_eq!(selected, vec![ChoiceId::new("go"), ChoiceId::new("rust")]);
        let out = prompter.terminal().output();
        assert!(out.contains("[none]"));
        assert!(out.contains("comma-separated"));

        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::Interactive,
            false,
        )
        .multi_select("Tasks?", &no_default_choices())
        .expect_err("closed input must error");
        assert!(err.message().contains("input closed"));
    }

    // ── Text: required, validator-reason, and cancellation branches ─────

    #[test]
    fn key_text_required_then_validator_reason_then_value() {
        let reject_short = |value: &str| {
            if value.len() >= 2 {
                Ok(())
            } else {
                Err("too short".to_string())
            }
        };

        // Enter on an empty buffer with no default surfaces the required notice,
        // then a typed value is accepted.
        let value = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::Enter,
                Key::Char('h'),
                Key::Char('i'),
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", None)
        .expect("value after the required notice");
        assert_eq!(value, "hi");

        // A rejected value shows the validator reason, then a valid value passes.
        let mut prompter = line_prompter(
            ScriptedTerminal::key_driven().with_keys([
                Key::Char('a'),
                Key::Enter,
                Key::Char('b'),
                Key::Enter,
            ]),
            PromptMode::Interactive,
            false,
        );
        let value = prompter
            .text_with("Name?", None, &reject_short)
            .expect("valid after the reason");
        assert_eq!(value, "ab");
        assert!(prompter.terminal().output().contains("too short"));
    }

    #[test]
    fn key_text_ignores_unrelated_keys_and_escape_cancels() {
        let err = line_prompter(
            ScriptedTerminal::key_driven().with_keys([Key::Left, Key::Escape]),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", None)
        .expect_err("escape cancels");
        assert!(err.message().contains("cancelled"));
    }

    #[test]
    fn line_text_errors_when_input_closes() {
        let err = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::Interactive,
            false,
        )
        .text("Name?", None)
        .expect_err("closed input must error");
        assert!(err.message().contains("input closed"));
    }

    #[test]
    fn line_text_with_shows_validator_reason_before_accepting() {
        let reject_short = |value: &str| {
            if value.len() >= 2 {
                Ok(())
            } else {
                Err("too short".to_string())
            }
        };
        let mut prompter = line_prompter(
            ScriptedTerminal::line_driven().with_lines(["a", "ok"]),
            PromptMode::Interactive,
            false,
        );
        let value = prompter
            .text_with("Name?", None, &reject_short)
            .expect("valid after the reason");
        assert_eq!(value, "ok");
        assert!(prompter.terminal().output().contains("too short"));
    }

    // ── Construction & metadata accessors ───────────────────────────────

    #[test]
    fn from_env_builds_a_prompter_and_reports_its_mode() {
        // Under a test harness neither stream is a TTY, so the environment
        // prompter is non-interactive; building it also exercises terminal
        // selection over the process streams.
        let prompter = Prompter::from_env(ColorChoice::Never);
        assert_eq!(prompter.mode(), PromptMode::NonInteractive);
    }

    #[test]
    fn with_glyphs_overrides_symbols_and_preserves_mode() {
        let prompter = line_prompter(
            ScriptedTerminal::line_driven(),
            PromptMode::NonInteractive,
            false,
        )
        .with_glyphs(Glyphs::new(true));
        assert_eq!(prompter.mode(), PromptMode::NonInteractive);
    }
}