Skip to main content

hyprstream_tui/wizard/
mod.rs

1//! Setup wizard TUI application.
2//!
3//! Implements `waxterm::TerminalApp` to drive the wizard through 6 phases:
4//! Install, Bootstrap, Policy Templates, Users & Roles, API Tokens, Services.
5
6pub mod backend;
7pub mod phases;
8
9use ratatui::layout::{Constraint, Layout, Rect};
10use ratatui::style::{Color, Modifier, Style};
11use ratatui::text::{Line, Span};
12use ratatui::widgets::Paragraph;
13use ratatui::Frame;
14
15use waxterm::input::KeyPress;
16use waxterm::widgets::{ConfirmDialog, MultiSelectList, SelectList, TextInput, WidgetResult};
17
18use backend::{
19    BootstrapPoll, InstallAction, InstallPoll, LibtorchVariant, OpStatus, RunMode, WizardBackend,
20};
21use phases::*;
22
23/// Wizard command type — just wraps KeyPress.
24pub enum WizardCommand {
25    Key(KeyPress),
26}
27
28impl From<KeyPress> for WizardCommand {
29    fn from(k: KeyPress) -> Self {
30        WizardCommand::Key(k)
31    }
32}
33
34/// Predefined role definitions.
35const ROLE_OPTIONS: &[(&str, &str)] = &[
36    ("admin", "Full access to everything"),
37    ("operator", "Infer + query + load/unload models"),
38    ("viewer", "Read-only queries"),
39    ("trainer", "Inference + training"),
40    ("custom", "Define custom permissions"),
41];
42
43/// Action options for custom roles.
44const ACTION_OPTIONS: &[&str] = &["infer", "train", "query", "write", "serve", "manage"];
45
46/// Expiration options for tokens.
47const EXPIRY_OPTIONS: &[&str] = &["90 days (recommended)", "30 days", "1 year", "never"];
48
49/// The wizard TUI application.
50pub struct WizardApp<B: WizardBackend> {
51    backend: B,
52    phase: WizardPhase,
53    quit: bool,
54    // Accumulated state across phases
55    install_summary: Option<String>,
56    templates_applied: Vec<String>,
57    users_created: Vec<UserRecord>,
58    tokens_generated: Vec<TokenRecord>,
59    services_started: bool,
60    // Transient state for user creation flow
61    pending_username: String,
62    pending_role: String,
63    pending_resource: String,
64    // Token generation queue
65    token_queue: Vec<String>,
66    token_queue_idx: usize,
67    // Install phase transient state
68    install_variant: Option<LibtorchVariant>,
69}
70
71impl<B: WizardBackend> WizardApp<B> {
72    pub fn new(backend: B) -> Self {
73        Self {
74            backend,
75            phase: WizardPhase::Install(InstallScreen::Detecting),
76            quit: false,
77            install_summary: None,
78            templates_applied: Vec::new(),
79            users_created: Vec::new(),
80            tokens_generated: Vec::new(),
81            services_started: false,
82            pending_username: String::new(),
83            pending_role: String::new(),
84            pending_resource: String::new(),
85            token_queue: Vec::new(),
86            token_queue_idx: 0,
87            install_variant: None,
88        }
89    }
90
91    fn phase_number(&self) -> u8 {
92        match &self.phase {
93            WizardPhase::Install(_) => 1,
94            WizardPhase::Bootstrap(_) => 2,
95            WizardPhase::PolicyTemplate(_) => 3,
96            WizardPhase::Users(_) => 4,
97            WizardPhase::Tokens(_) => 5,
98            WizardPhase::Services(_) => 6,
99            WizardPhase::Summary(_) => 7,
100        }
101    }
102
103    fn phase_name(&self) -> &str {
104        match &self.phase {
105            WizardPhase::Install(_) => "Install / Update",
106            WizardPhase::Bootstrap(_) => "Environment Bootstrap",
107            WizardPhase::PolicyTemplate(_) => "Policy Template",
108            WizardPhase::Users(_) => "Users & Roles",
109            WizardPhase::Tokens(_) => "API Tokens",
110            WizardPhase::Services(_) => "Services",
111            WizardPhase::Summary(_) => "Setup Complete",
112        }
113    }
114
115    fn advance_to_bootstrap(&mut self) {
116        self.phase = WizardPhase::Bootstrap(BootstrapScreen::new());
117    }
118
119    fn advance_to_policy(&mut self) {
120        let templates = self.backend.templates();
121        if self.backend.has_existing_policy() {
122            self.phase = WizardPhase::PolicyTemplate(PolicyScreen::ConfirmReplace(
123                ConfirmDialog::new("Existing policy found. Replace with a template?")
124                    .with_default(false),
125            ));
126        } else {
127            self.phase = WizardPhase::PolicyTemplate(PolicyScreen::select_from(&templates));
128        }
129    }
130
131    fn advance_to_users(&mut self) {
132        self.phase = WizardPhase::Users(UserScreen::AskAdd(
133            ConfirmDialog::new("Add a user?").with_default(false),
134        ));
135    }
136
137    fn advance_to_tokens(&mut self) {
138        // Build queue of users to generate tokens for
139        self.token_queue = self
140            .users_created
141            .iter()
142            .map(|u| u.username.clone())
143            .collect();
144
145        if self.token_queue.is_empty() {
146            self.advance_to_services();
147            return;
148        }
149
150        self.token_queue_idx = 0;
151        self.advance_token_for_next_user();
152    }
153
154    fn advance_token_for_next_user(&mut self) {
155        if self.token_queue_idx < self.token_queue.len() {
156            let username = self.token_queue[self.token_queue_idx].clone();
157            self.phase = WizardPhase::Tokens(TokenScreen::AskGenerate(
158                ConfirmDialog::new(format!("Generate API token for '{username}'?")),
159                username,
160            ));
161        } else {
162            self.advance_to_services();
163        }
164    }
165
166    fn advance_to_services(&mut self) {
167        self.phase = WizardPhase::Services(ServiceScreen::AskStart(
168            ConfirmDialog::new("Start services now?").with_default(true),
169        ));
170    }
171
172    fn advance_to_summary(&mut self) {
173        self.phase = WizardPhase::Summary(SummaryScreen {
174            install_result: self.install_summary.clone(),
175            templates_applied: self.templates_applied.clone(),
176            users_created: self.users_created.clone(),
177            tokens_generated: self.tokens_generated.clone(),
178            services_started: self.services_started,
179        });
180    }
181
182    fn make_variant_select() -> SelectList<String> {
183        let options: Vec<String> = LibtorchVariant::all()
184            .iter()
185            .map(|v| format!("{} ({})", v.label(), v.id()))
186            .collect();
187        SelectList::new("Select variant:", options)
188    }
189
190    fn variant_from_selection(selection: &str) -> LibtorchVariant {
191        if selection.contains("cuda128") {
192            LibtorchVariant::Cuda128
193        } else if selection.contains("cuda130") {
194            LibtorchVariant::Cuda130
195        } else if selection.contains("rocm71") {
196            LibtorchVariant::Rocm71
197        } else {
198            LibtorchVariant::Cpu
199        }
200    }
201
202    fn make_role_select() -> SelectList<String> {
203        let options: Vec<String> = ROLE_OPTIONS
204            .iter()
205            .map(|(name, desc)| format!("{name} — {desc}"))
206            .collect();
207        SelectList::new("Role:", options).with_selected(1)
208    }
209
210    fn make_expiry_select() -> SelectList<String> {
211        let options: Vec<String> = EXPIRY_OPTIONS.iter().map(|s| (*s).to_string()).collect();
212        SelectList::new("Token expiration:", options)
213    }
214
215    fn make_action_multiselect() -> MultiSelectList<String> {
216        let options: Vec<String> = ACTION_OPTIONS.iter().map(|s| (*s).to_string()).collect();
217        MultiSelectList::new("Actions to allow:", options)
218    }
219
220    fn expiry_to_duration(selection: &str) -> &str {
221        if selection.starts_with("30") {
222            "30d"
223        } else if selection.starts_with("1 year") {
224            "1y"
225        } else if selection.starts_with("never") {
226            "never"
227        } else {
228            "90d"
229        }
230    }
231}
232
233impl<B: WizardBackend> waxterm::TerminalApp for WizardApp<B> {
234    type Command = WizardCommand;
235
236    fn render(&self, frame: &mut Frame) {
237        let area = frame.area();
238        let chunks = Layout::vertical([
239            Constraint::Length(3), // header
240            Constraint::Length(1), // phase indicator
241            Constraint::Length(1), // separator
242            Constraint::Min(10),   // content
243            Constraint::Length(2), // footer
244        ])
245        .split(area);
246
247        render_header(frame, chunks[0]);
248        render_phase_indicator(frame, chunks[1], self.phase_number(), self.phase_name());
249        render_separator(frame, chunks[2]);
250        self.render_content(frame, chunks[3]);
251        render_footer(frame, chunks[4], &self.phase);
252    }
253
254    fn handle_input(&mut self, cmd: WizardCommand) -> bool {
255        let WizardCommand::Key(key) = cmd;
256
257        // Global quit on 'q' at summary, or Ctrl-C (Char(3))
258        if let KeyPress::Char(b'q') = key {
259            if matches!(&self.phase, WizardPhase::Summary(_)) {
260                self.quit = true;
261                return true;
262            }
263        }
264        if let KeyPress::Char(3) = key {
265            self.quit = true;
266            return true;
267        }
268
269        // Dispatch based on current phase. We check discriminant without borrowing
270        // to avoid double-mutable-borrow in the handler methods (which use mem::replace).
271        let phase_num = self.phase_number();
272        match phase_num {
273            1 => self.handle_install_input(&key),
274            2 => {
275                // Bootstrap is tick-driven, no input needed
276                false
277            }
278            3 => self.handle_policy_input(&key),
279            4 => self.handle_users_input(&key),
280            5 => self.handle_tokens_input(&key),
281            6 => self.handle_services_input(&key),
282            7 => {
283                // Summary screen: Enter exits the wizard. ('q' is also
284                // handled via the global quit shortcut above, line 264.)
285                if key == KeyPress::Enter {
286                    self.quit = true;
287                }
288                true
289            }
290            _ => false,
291        }
292    }
293
294    fn tick(&mut self, _delta_ms: u64) -> bool {
295        match &mut self.phase {
296            WizardPhase::Install(screen) => match screen {
297                InstallScreen::Detecting => {
298                    let env = self.backend.detect_environment();
299                    let action = self.backend.recommend_action(&env);
300                    // Auto-skip for AppImage and Development modes
301                    match &action {
302                        InstallAction::Skip { .. } => {
303                            self.phase = WizardPhase::Install(InstallScreen::Skipped);
304                            self.advance_to_bootstrap();
305                            return true;
306                        }
307                        InstallAction::AlreadyCurrent => {
308                            self.install_summary = Some(format!(
309                                "Already running optimal variant ({})",
310                                env.current_variant
311                            ));
312                            self.phase = WizardPhase::Install(InstallScreen::Done(format!(
313                                "Already running {} — no changes needed",
314                                env.current_variant
315                            )));
316                            // Don't auto-advance; let user press Enter
317                        }
318                        InstallAction::UpgradeVariant(_) => {}
319                    }
320                    if !matches!(self.phase, WizardPhase::Install(InstallScreen::Done(_))) {
321                        self.phase =
322                            WizardPhase::Install(InstallScreen::ShowFindings { env, action });
323                    }
324                    true
325                }
326                InstallScreen::Installing {
327                    variant,
328                    progress_pct,
329                    status_msg,
330                } => match self.backend.poll_install() {
331                    InstallPoll::Downloading { item, pct } => {
332                        *progress_pct = pct;
333                        *status_msg = format!("Downloading {item}...");
334                        true
335                    }
336                    InstallPoll::Extracting { item } => {
337                        *status_msg = format!("Extracting {item}...");
338                        true
339                    }
340                    InstallPoll::Configuring { step } => {
341                        *status_msg = step;
342                        *progress_pct = 100;
343                        true
344                    }
345                    InstallPoll::Done { summary } => {
346                        self.install_summary = Some(summary.clone());
347                        let v = variant.clone();
348                        self.phase = WizardPhase::Install(InstallScreen::Done(format!(
349                            "{} variant installed — {summary}",
350                            v.label()
351                        )));
352                        true
353                    }
354                    InstallPoll::Failed(msg) => {
355                        self.phase = WizardPhase::Install(InstallScreen::Failed(msg));
356                        true
357                    }
358                    InstallPoll::Detecting => true,
359                },
360                _ => false,
361            },
362            WizardPhase::Bootstrap(screen) => {
363                if !screen.started {
364                    screen.started = true;
365                    self.backend.start_bootstrap();
366                }
367                if screen.done {
368                    return false;
369                }
370                match self.backend.poll_bootstrap() {
371                    BootstrapPoll::InProgress(msg) => {
372                        screen.current_step = msg;
373                        true
374                    }
375                    BootstrapPoll::Done(steps) => {
376                        screen.completed_steps = steps;
377                        screen.current_step.clear();
378                        screen.done = true;
379                        // Auto-advance after bootstrap
380                        self.advance_to_policy();
381                        true
382                    }
383                    BootstrapPoll::Failed(msg) => {
384                        screen.failed = Some(msg);
385                        screen.done = true;
386                        true
387                    }
388                }
389            }
390            WizardPhase::Services(ServiceScreen::Starting) => {
391                match self.backend.poll_pending() {
392                    OpStatus::InProgress => true,
393                    OpStatus::Done => {
394                        self.services_started = true;
395                        self.phase = WizardPhase::Services(ServiceScreen::Done(true));
396                        // Auto-advance to summary
397                        self.advance_to_summary();
398                        true
399                    }
400                    OpStatus::Failed(_msg) => {
401                        self.phase = WizardPhase::Services(ServiceScreen::Done(false));
402                        self.advance_to_summary();
403                        true
404                    }
405                }
406            }
407            _ => false,
408        }
409    }
410
411    fn should_quit(&self) -> bool {
412        self.quit
413    }
414}
415
416// ─────────────────────────────────────────────────────────────────────────────
417// Input handling (split out to work around borrow checker)
418// ─────────────────────────────────────────────────────────────────────────────
419
420// These methods take &mut self but need separate borrowing for phase mutation.
421// We use a pattern of taking the phase enum, matching, then reassigning.
422
423impl<B: WizardBackend> WizardApp<B> {
424    fn handle_install_input(&mut self, key: &KeyPress) -> bool {
425        let phase = std::mem::replace(
426            &mut self.phase,
427            WizardPhase::Install(InstallScreen::Skipped),
428        );
429
430        let WizardPhase::Install(screen) = phase else {
431            return false;
432        };
433
434        match screen {
435            InstallScreen::Detecting => {
436                // Tick-driven, no input needed
437                self.phase = WizardPhase::Install(InstallScreen::Detecting);
438                false
439            }
440            InstallScreen::ShowFindings { env, action } => {
441                match key {
442                    KeyPress::Enter => {
443                        // Accept recommendation
444                        if let InstallAction::UpgradeVariant(ref variant) = action {
445                            let v = variant.clone();
446                            self.install_variant = Some(v.clone());
447                            self.backend.start_install(&v);
448                            self.phase = WizardPhase::Install(InstallScreen::Installing {
449                                variant: v,
450                                progress_pct: 0,
451                                status_msg: "Starting download...".to_string(),
452                            });
453                        } else {
454                            // Skip/AlreadyCurrent — advance
455                            self.advance_to_bootstrap();
456                        }
457                    }
458                    KeyPress::Char(b's') => {
459                        // Skip
460                        self.phase = WizardPhase::Install(InstallScreen::Skipped);
461                        self.advance_to_bootstrap();
462                    }
463                    KeyPress::Char(b'v') => {
464                        // Choose variant manually
465                        self.phase = WizardPhase::Install(InstallScreen::SelectVariant(
466                            Self::make_variant_select(),
467                        ));
468                    }
469                    _ => {
470                        // Put it back
471                        self.phase =
472                            WizardPhase::Install(InstallScreen::ShowFindings { env, action });
473                        return false;
474                    }
475                }
476                true
477            }
478            InstallScreen::SelectVariant(mut list) => {
479                match list.handle_key(key) {
480                    WidgetResult::Confirmed(selection) => {
481                        let variant = Self::variant_from_selection(&selection);
482                        self.install_variant = Some(variant.clone());
483                        self.backend.start_install(&variant);
484                        self.phase = WizardPhase::Install(InstallScreen::Installing {
485                            variant,
486                            progress_pct: 0,
487                            status_msg: "Starting download...".to_string(),
488                        });
489                    }
490                    WidgetResult::Cancelled => {
491                        self.phase = WizardPhase::Install(InstallScreen::Skipped);
492                        self.advance_to_bootstrap();
493                    }
494                    WidgetResult::Pending => {
495                        self.phase = WizardPhase::Install(InstallScreen::SelectVariant(list));
496                    }
497                }
498                true
499            }
500            InstallScreen::Installing {
501                variant,
502                progress_pct,
503                status_msg,
504            } => {
505                // Tick-driven, no user input
506                self.phase = WizardPhase::Install(InstallScreen::Installing {
507                    variant,
508                    progress_pct,
509                    status_msg,
510                });
511                false
512            }
513            InstallScreen::Done(_msg) => {
514                if *key == KeyPress::Enter {
515                    self.advance_to_bootstrap();
516                    true
517                } else {
518                    self.phase = WizardPhase::Install(InstallScreen::Done(_msg));
519                    false
520                }
521            }
522            InstallScreen::Skipped => {
523                self.advance_to_bootstrap();
524                true
525            }
526            InstallScreen::Failed(msg) => {
527                match key {
528                    KeyPress::Char(b'r') => {
529                        // Retry
530                        if let Some(ref variant) = self.install_variant {
531                            let v = variant.clone();
532                            self.backend.start_install(&v);
533                            self.phase = WizardPhase::Install(InstallScreen::Installing {
534                                variant: v,
535                                progress_pct: 0,
536                                status_msg: "Retrying download...".to_string(),
537                            });
538                        } else {
539                            self.phase = WizardPhase::Install(InstallScreen::Detecting);
540                        }
541                    }
542                    KeyPress::Char(b's') => {
543                        self.phase = WizardPhase::Install(InstallScreen::Skipped);
544                        self.advance_to_bootstrap();
545                    }
546                    KeyPress::Char(b'q') => {
547                        self.quit = true;
548                    }
549                    _ => {
550                        self.phase = WizardPhase::Install(InstallScreen::Failed(msg));
551                        return false;
552                    }
553                }
554                true
555            }
556        }
557    }
558
559    fn handle_policy_input(&mut self, key: &KeyPress) -> bool {
560        // Take the phase to work around the borrow
561        let phase = std::mem::replace(
562            &mut self.phase,
563            WizardPhase::PolicyTemplate(PolicyScreen::Skipped),
564        );
565
566        let WizardPhase::PolicyTemplate(screen) = phase else {
567            return false;
568        };
569
570        match screen {
571            PolicyScreen::ConfirmReplace(mut dialog) => match dialog.handle_key(key) {
572                WidgetResult::Confirmed(true) => {
573                    let templates = self.backend.templates();
574                    self.phase = WizardPhase::PolicyTemplate(PolicyScreen::select_from(&templates));
575                }
576                WidgetResult::Confirmed(false) | WidgetResult::Cancelled => {
577                    self.phase = WizardPhase::PolicyTemplate(PolicyScreen::Skipped);
578                    self.advance_to_users();
579                }
580                WidgetResult::Pending => {
581                    self.phase = WizardPhase::PolicyTemplate(PolicyScreen::ConfirmReplace(dialog));
582                }
583            },
584            PolicyScreen::SelectTemplate(mut list) => {
585                match list.handle_key(key) {
586                    WidgetResult::Confirmed(selection) => {
587                        if selection.starts_with("None") {
588                            self.phase = WizardPhase::PolicyTemplate(PolicyScreen::Skipped);
589                            self.advance_to_users();
590                        } else {
591                            let name = selection
592                                .split(" —")
593                                .next()
594                                .unwrap_or("")
595                                .trim()
596                                .to_string();
597                            self.backend.apply_template(&name);
598                            self.templates_applied.push(name.clone());
599                            self.phase = WizardPhase::PolicyTemplate(PolicyScreen::Applied(name));
600                            // Auto-advance after applying template
601                            self.advance_to_users();
602                        }
603                    }
604                    WidgetResult::Cancelled => {
605                        self.advance_to_users();
606                    }
607                    WidgetResult::Pending => {
608                        self.phase =
609                            WizardPhase::PolicyTemplate(PolicyScreen::SelectTemplate(list));
610                    }
611                }
612            }
613            PolicyScreen::Applied(_) | PolicyScreen::Skipped => {
614                self.advance_to_users();
615            }
616        }
617        true
618    }
619
620    fn handle_users_input(&mut self, key: &KeyPress) -> bool {
621        let phase = std::mem::replace(&mut self.phase, WizardPhase::Users(UserScreen::Done));
622
623        let WizardPhase::Users(screen) = phase else {
624            return false;
625        };
626
627        match screen {
628            UserScreen::AskAdd(mut dialog) => match dialog.handle_key(key) {
629                WidgetResult::Confirmed(true) => {
630                    self.phase =
631                        WizardPhase::Users(UserScreen::EnterName(TextInput::new("Username:")));
632                }
633                WidgetResult::Confirmed(false) | WidgetResult::Cancelled => {
634                    self.phase = WizardPhase::Users(UserScreen::Done);
635                    self.advance_to_tokens();
636                }
637                WidgetResult::Pending => {
638                    self.phase = WizardPhase::Users(UserScreen::AskAdd(dialog));
639                }
640            },
641            UserScreen::EnterName(mut input) => {
642                match input.handle_key(key) {
643                    WidgetResult::Confirmed(name) => {
644                        if name.trim().is_empty() {
645                            // Re-prompt
646                            self.phase = WizardPhase::Users(UserScreen::EnterName(TextInput::new(
647                                "Username:",
648                            )));
649                        } else {
650                            self.pending_username = name.trim().to_string();
651                            self.phase = WizardPhase::Users(UserScreen::SelectRole(
652                                Self::make_role_select(),
653                            ));
654                        }
655                    }
656                    WidgetResult::Cancelled => {
657                        self.phase = WizardPhase::Users(UserScreen::Done);
658                        self.advance_to_tokens();
659                    }
660                    WidgetResult::Pending => {
661                        self.phase = WizardPhase::Users(UserScreen::EnterName(input));
662                    }
663                }
664            }
665            UserScreen::SelectRole(mut list) => match list.handle_key(key) {
666                WidgetResult::Confirmed(selection) => {
667                    let role_name = selection
668                        .split(" —")
669                        .next()
670                        .unwrap_or("")
671                        .trim()
672                        .to_string();
673
674                    if role_name == "custom" {
675                        self.pending_role = "custom".to_string();
676                        self.phase = WizardPhase::Users(UserScreen::CustomResource(
677                            TextInput::new("Resource pattern (e.g., model:*, *):")
678                                .with_default("*"),
679                        ));
680                    } else {
681                        self.backend.add_user(&self.pending_username, &role_name);
682                        self.users_created.push(UserRecord {
683                            username: self.pending_username.clone(),
684                            role: role_name,
685                        });
686                        self.phase = WizardPhase::Users(UserScreen::AskAnother(
687                            ConfirmDialog::new("Add another user?").with_default(false),
688                        ));
689                    }
690                }
691                WidgetResult::Cancelled => {
692                    self.phase = WizardPhase::Users(UserScreen::AskAnother(
693                        ConfirmDialog::new("Add another user?").with_default(false),
694                    ));
695                }
696                WidgetResult::Pending => {
697                    self.phase = WizardPhase::Users(UserScreen::SelectRole(list));
698                }
699            },
700            UserScreen::CustomResource(mut input) => match input.handle_key(key) {
701                WidgetResult::Confirmed(resource) => {
702                    self.pending_resource = resource;
703                    self.phase = WizardPhase::Users(UserScreen::CustomActions(
704                        Self::make_action_multiselect(),
705                    ));
706                }
707                WidgetResult::Cancelled => {
708                    self.phase = WizardPhase::Users(UserScreen::AskAnother(
709                        ConfirmDialog::new("Add another user?").with_default(false),
710                    ));
711                }
712                WidgetResult::Pending => {
713                    self.phase = WizardPhase::Users(UserScreen::CustomResource(input));
714                }
715            },
716            UserScreen::CustomActions(mut list) => match list.handle_key(key) {
717                WidgetResult::Confirmed(actions) => {
718                    self.backend.add_user_custom(
719                        &self.pending_username,
720                        &self.pending_resource,
721                        &actions,
722                    );
723                    let actions_str = actions.join(",");
724                    self.users_created.push(UserRecord {
725                        username: self.pending_username.clone(),
726                        role: format!("custom({actions_str})"),
727                    });
728                    self.phase = WizardPhase::Users(UserScreen::AskAnother(
729                        ConfirmDialog::new("Add another user?").with_default(false),
730                    ));
731                }
732                WidgetResult::Cancelled => {
733                    self.phase = WizardPhase::Users(UserScreen::AskAnother(
734                        ConfirmDialog::new("Add another user?").with_default(false),
735                    ));
736                }
737                WidgetResult::Pending => {
738                    self.phase = WizardPhase::Users(UserScreen::CustomActions(list));
739                }
740            },
741            UserScreen::AskAnother(mut dialog) => match dialog.handle_key(key) {
742                WidgetResult::Confirmed(true) => {
743                    self.phase =
744                        WizardPhase::Users(UserScreen::EnterName(TextInput::new("Username:")));
745                }
746                WidgetResult::Confirmed(false) | WidgetResult::Cancelled => {
747                    self.backend.save_policies();
748                    self.phase = WizardPhase::Users(UserScreen::Done);
749                    self.advance_to_tokens();
750                }
751                WidgetResult::Pending => {
752                    self.phase = WizardPhase::Users(UserScreen::AskAnother(dialog));
753                }
754            },
755            UserScreen::Done => {
756                self.advance_to_tokens();
757            }
758        }
759        true
760    }
761
762    fn handle_tokens_input(&mut self, key: &KeyPress) -> bool {
763        let phase = std::mem::replace(&mut self.phase, WizardPhase::Tokens(TokenScreen::Done));
764
765        let WizardPhase::Tokens(screen) = phase else {
766            return false;
767        };
768
769        match screen {
770            TokenScreen::AskGenerate(mut dialog, username) => match dialog.handle_key(key) {
771                WidgetResult::Confirmed(true) => {
772                    self.phase = WizardPhase::Tokens(TokenScreen::SelectExpiry(
773                        Self::make_expiry_select(),
774                        username,
775                    ));
776                }
777                WidgetResult::Confirmed(false) | WidgetResult::Cancelled => {
778                    self.token_queue_idx += 1;
779                    self.advance_token_for_next_user();
780                }
781                WidgetResult::Pending => {
782                    self.phase = WizardPhase::Tokens(TokenScreen::AskGenerate(dialog, username));
783                }
784            },
785            TokenScreen::SelectExpiry(mut list, username) => match list.handle_key(key) {
786                WidgetResult::Confirmed(selection) => {
787                    let duration = Self::expiry_to_duration(&selection);
788                    let result = self.backend.generate_token(&username, duration);
789                    let record = TokenRecord {
790                        username: username.clone(),
791                        token: result.token,
792                        expires: result.expires,
793                    };
794                    self.tokens_generated.push(record.clone());
795                    self.phase = WizardPhase::Tokens(TokenScreen::ShowToken(record));
796                }
797                WidgetResult::Cancelled => {
798                    self.token_queue_idx += 1;
799                    self.advance_token_for_next_user();
800                }
801                WidgetResult::Pending => {
802                    self.phase = WizardPhase::Tokens(TokenScreen::SelectExpiry(list, username));
803                }
804            },
805            TokenScreen::ShowToken(_record) => {
806                // Any key advances
807                self.token_queue_idx += 1;
808                self.advance_token_for_next_user();
809            }
810            TokenScreen::NextUser | TokenScreen::Done => {
811                self.advance_to_services();
812            }
813        }
814        true
815    }
816
817    fn handle_services_input(&mut self, key: &KeyPress) -> bool {
818        let phase = std::mem::replace(
819            &mut self.phase,
820            WizardPhase::Services(ServiceScreen::Done(false)),
821        );
822
823        let WizardPhase::Services(screen) = phase else {
824            return false;
825        };
826
827        match screen {
828            ServiceScreen::AskStart(mut dialog) => match dialog.handle_key(key) {
829                WidgetResult::Confirmed(true) => {
830                    self.backend.start_services();
831                    self.phase = WizardPhase::Services(ServiceScreen::Starting);
832                }
833                WidgetResult::Confirmed(false) | WidgetResult::Cancelled => {
834                    self.advance_to_summary();
835                }
836                WidgetResult::Pending => {
837                    self.phase = WizardPhase::Services(ServiceScreen::AskStart(dialog));
838                }
839            },
840            ServiceScreen::Starting => {
841                // tick-driven
842                self.phase = WizardPhase::Services(ServiceScreen::Starting);
843            }
844            ServiceScreen::Done(_) => {
845                self.advance_to_summary();
846            }
847        }
848        true
849    }
850}
851
852// ─────────────────────────────────────────────────────────────────────────────
853// Rendering
854// ─────────────────────────────────────────────────────────────────────────────
855
856fn render_header(frame: &mut Frame, area: Rect) {
857    let lines = vec![
858        Line::from(""),
859        Line::from(Span::styled(
860            "  Hyprstream Setup Wizard",
861            Style::default()
862                .fg(Color::Cyan)
863                .add_modifier(Modifier::BOLD),
864        )),
865        Line::from(Span::styled(
866            format!("  {}", "=".repeat(40)),
867            Style::default().fg(Color::DarkGray),
868        )),
869    ];
870    frame.render_widget(Paragraph::new(lines), area);
871}
872
873fn render_phase_indicator(frame: &mut Frame, area: Rect, current: u8, name: &str) {
874    let phases = [
875        "Install",
876        "Bootstrap",
877        "Policy",
878        "Users",
879        "Tokens",
880        "Services",
881    ];
882    let mut spans = vec![Span::raw("  ")];
883    for (i, label) in phases.iter().enumerate() {
884        let num = (i + 1) as u8;
885        let style = if num < current {
886            Style::default().fg(Color::Green)
887        } else if num == current {
888            Style::default()
889                .fg(Color::Yellow)
890                .add_modifier(Modifier::BOLD)
891        } else {
892            Style::default().fg(Color::DarkGray)
893        };
894        let marker = if num < current {
895            "v"
896        } else if num == current {
897            ">"
898        } else {
899            " "
900        };
901        spans.push(Span::styled(format!("{marker}{num}.{label}"), style));
902        if i < phases.len() - 1 {
903            spans.push(Span::raw(" "));
904        }
905    }
906    spans.push(Span::raw(format!("  — {name}")));
907    frame.render_widget(Paragraph::new(Line::from(spans)), area);
908}
909
910fn render_separator(frame: &mut Frame, area: Rect) {
911    frame.render_widget(
912        Paragraph::new(Line::from(Span::styled(
913            format!("  {}", "-".repeat(40)),
914            Style::default().fg(Color::DarkGray),
915        ))),
916        area,
917    );
918}
919
920fn render_footer(frame: &mut Frame, area: Rect, phase: &WizardPhase) {
921    let hint = match phase {
922        WizardPhase::Install(screen) => match screen {
923            InstallScreen::Detecting => "  Detecting environment...",
924            InstallScreen::ShowFindings { action, .. } => match action {
925                InstallAction::UpgradeVariant(_) => {
926                    "  [Enter] Install  [s] Skip  [v] Choose variant"
927                }
928                _ => "  [Enter] Continue",
929            },
930            InstallScreen::SelectVariant(_) => {
931                "  Arrow keys to navigate, Enter to select, Esc to skip"
932            }
933            InstallScreen::Installing { .. } => "  Downloading and installing...",
934            InstallScreen::Done(_) => "  [Enter] Continue",
935            InstallScreen::Skipped => "  Skipping...",
936            InstallScreen::Failed(_) => "  [r] Retry  [s] Skip  [q] Quit",
937        },
938        WizardPhase::Bootstrap(_) => "  Bootstrapping environment...",
939        WizardPhase::PolicyTemplate(_) => "  Arrow keys to navigate, Enter to select, Esc to skip",
940        WizardPhase::Users(_) => "  Arrow keys to navigate, Enter to confirm, Esc to skip",
941        WizardPhase::Tokens(_) => "  Arrow keys to navigate, Enter to confirm",
942        WizardPhase::Services(_) => "  y/n or arrow keys, Enter to confirm",
943        WizardPhase::Summary(_) => "  Press Enter or q to exit",
944    };
945    let lines = vec![
946        Line::from(""),
947        Line::from(Span::styled(hint, Style::default().fg(Color::DarkGray))),
948    ];
949    frame.render_widget(Paragraph::new(lines), area);
950}
951
952impl<B: WizardBackend> WizardApp<B> {
953    fn render_content(&self, frame: &mut Frame, area: Rect) {
954        // Indent content area
955        let content_area = Rect {
956            x: area.x + 2,
957            width: area.width.saturating_sub(4),
958            ..area
959        };
960
961        match &self.phase {
962            WizardPhase::Install(screen) => {
963                render_install(frame, content_area, screen);
964            }
965            WizardPhase::Bootstrap(screen) => {
966                render_bootstrap(frame, content_area, screen);
967            }
968            WizardPhase::PolicyTemplate(screen) => {
969                render_policy(frame, content_area, screen);
970            }
971            WizardPhase::Users(screen) => {
972                render_users(frame, content_area, screen, &self.users_created);
973            }
974            WizardPhase::Tokens(screen) => {
975                render_tokens(frame, content_area, screen);
976            }
977            WizardPhase::Services(screen) => {
978                render_services(frame, content_area, screen);
979            }
980            WizardPhase::Summary(screen) => {
981                render_summary(frame, content_area, screen);
982            }
983        }
984    }
985}
986
987fn render_install(frame: &mut Frame, area: Rect, screen: &InstallScreen) {
988    use backend::{GpuKind, LIBTORCH_VERSION};
989
990    match screen {
991        InstallScreen::Detecting => {
992            let lines = vec![Line::from(vec![
993                Span::styled("  > ", Style::default().fg(Color::Yellow)),
994                Span::styled(
995                    "Detecting environment...",
996                    Style::default().fg(Color::Yellow),
997                ),
998            ])];
999            frame.render_widget(Paragraph::new(lines), area);
1000        }
1001        InstallScreen::ShowFindings { env, action } => {
1002            let mut lines = vec![
1003                Line::from(Span::styled(
1004                    "Environment Detection",
1005                    Style::default().add_modifier(Modifier::BOLD),
1006                )),
1007                Line::from(Span::styled(
1008                    "-".repeat(30),
1009                    Style::default().fg(Color::DarkGray),
1010                )),
1011            ];
1012
1013            let run_mode_str = match &env.run_mode {
1014                RunMode::AppImage => "AppImage",
1015                RunMode::BareBinary => "cargo install (bare binary)",
1016                RunMode::Development => "development (cargo)",
1017            };
1018            lines.push(Line::from(format!("Run mode:    {run_mode_str}")));
1019
1020            let gpu_str = match &env.gpu {
1021                GpuKind::Nvidia {
1022                    driver_version,
1023                    cuda_compat,
1024                } => format!("NVIDIA (driver {driver_version}) -> {cuda_compat}"),
1025                GpuKind::Amd { rocm_version } => {
1026                    if let Some(ver) = rocm_version {
1027                        format!("AMD (ROCm {ver})")
1028                    } else {
1029                        "AMD (no ROCm)".to_string()
1030                    }
1031                }
1032                GpuKind::None => "None".to_string(),
1033            };
1034            lines.push(Line::from(format!("GPU:         {gpu_str}")));
1035            lines.push(Line::from(format!(
1036                "libtorch:    {LIBTORCH_VERSION}+{} (compiled)",
1037                env.current_variant.id()
1038            )));
1039
1040            if let Some(ref installed) = env.installed_variant {
1041                lines.push(Line::from(format!("Installed:   {}", installed.label())));
1042            } else {
1043                lines.push(Line::from("Installed:   (none)"));
1044            }
1045
1046            lines.push(Line::from(""));
1047
1048            match action {
1049                InstallAction::UpgradeVariant(variant) => {
1050                    lines.push(Line::from(Span::styled(
1051                        "Recommendation",
1052                        Style::default().add_modifier(Modifier::BOLD),
1053                    )));
1054                    lines.push(Line::from(Span::styled(
1055                        "-".repeat(30),
1056                        Style::default().fg(Color::DarkGray),
1057                    )));
1058                    lines.push(Line::from(format!(
1059                        "Download GPU binary + libtorch ({}) (~2.5 GB)",
1060                        variant.label()
1061                    )));
1062                    lines.push(Line::from("Enables GPU-accelerated inference."));
1063                }
1064                InstallAction::AlreadyCurrent => {
1065                    lines.push(Line::from(Span::styled(
1066                        "Already running the optimal variant.",
1067                        Style::default().fg(Color::Green),
1068                    )));
1069                }
1070                InstallAction::Skip { reason } => {
1071                    lines.push(Line::from(Span::styled(
1072                        format!("Skipping: {reason}"),
1073                        Style::default().fg(Color::DarkGray),
1074                    )));
1075                }
1076            }
1077
1078            frame.render_widget(Paragraph::new(lines), area);
1079        }
1080        InstallScreen::SelectVariant(list) => {
1081            list.render(frame, area);
1082        }
1083        InstallScreen::Installing {
1084            progress_pct,
1085            status_msg,
1086            ..
1087        } => {
1088            let bar_width = 40usize;
1089            let filled = ((*progress_pct as usize) * bar_width) / 100;
1090            let empty = bar_width - filled;
1091            let bar = format!(
1092                "[{}{}] {:>3}%",
1093                "#".repeat(filled),
1094                " ".repeat(empty),
1095                progress_pct,
1096            );
1097
1098            let lines = vec![
1099                Line::from(Span::raw(format!("  {status_msg}"))),
1100                Line::from(Span::styled(
1101                    format!("  {bar}"),
1102                    Style::default().fg(Color::Cyan),
1103                )),
1104            ];
1105            frame.render_widget(Paragraph::new(lines), area);
1106        }
1107        InstallScreen::Done(msg) => {
1108            let lines = vec![
1109                Line::from(vec![
1110                    Span::styled("  v ", Style::default().fg(Color::Green)),
1111                    Span::raw(msg.as_str()),
1112                ]),
1113                Line::from(""),
1114                Line::from(Span::styled(
1115                    "  Press Enter to continue...",
1116                    Style::default().fg(Color::DarkGray),
1117                )),
1118            ];
1119            frame.render_widget(Paragraph::new(lines), area);
1120        }
1121        InstallScreen::Skipped => {
1122            let line = Line::from(Span::styled(
1123                "  Skipped",
1124                Style::default().fg(Color::DarkGray),
1125            ));
1126            frame.render_widget(Paragraph::new(line), area);
1127        }
1128        InstallScreen::Failed(msg) => {
1129            let lines = vec![
1130                Line::from(vec![
1131                    Span::styled("  x ", Style::default().fg(Color::Red)),
1132                    Span::styled(msg.as_str(), Style::default().fg(Color::Red)),
1133                ]),
1134                Line::from(""),
1135                Line::from(Span::styled(
1136                    "  [r] Retry  [s] Skip  [q] Quit",
1137                    Style::default().fg(Color::DarkGray),
1138                )),
1139            ];
1140            frame.render_widget(Paragraph::new(lines), area);
1141        }
1142    }
1143}
1144
1145fn render_bootstrap(frame: &mut Frame, area: Rect, screen: &BootstrapScreen) {
1146    let mut lines: Vec<Line> = Vec::new();
1147
1148    for step in &screen.completed_steps {
1149        lines.push(Line::from(vec![
1150            Span::styled("  v ", Style::default().fg(Color::Green)),
1151            Span::raw(step),
1152        ]));
1153    }
1154
1155    if let Some(ref msg) = screen.failed {
1156        lines.push(Line::from(vec![
1157            Span::styled("  x ", Style::default().fg(Color::Red)),
1158            Span::styled(msg, Style::default().fg(Color::Red)),
1159        ]));
1160    } else if !screen.done {
1161        lines.push(Line::from(vec![
1162            Span::styled("  > ", Style::default().fg(Color::Yellow)),
1163            Span::styled(&screen.current_step, Style::default().fg(Color::Yellow)),
1164        ]));
1165    }
1166
1167    frame.render_widget(Paragraph::new(lines), area);
1168}
1169
1170fn render_policy(frame: &mut Frame, area: Rect, screen: &PolicyScreen) {
1171    match screen {
1172        PolicyScreen::ConfirmReplace(dialog) => dialog.render(frame, area),
1173        PolicyScreen::SelectTemplate(list) => list.render(frame, area),
1174        PolicyScreen::Applied(name) => {
1175            let line = Line::from(vec![
1176                Span::styled("  v ", Style::default().fg(Color::Green)),
1177                Span::raw(format!("Applied template '{name}'")),
1178            ]);
1179            frame.render_widget(Paragraph::new(line), area);
1180        }
1181        PolicyScreen::Skipped => {
1182            let line = Line::from(Span::styled(
1183                "  Skipped",
1184                Style::default().fg(Color::DarkGray),
1185            ));
1186            frame.render_widget(Paragraph::new(line), area);
1187        }
1188    }
1189}
1190
1191fn render_users(frame: &mut Frame, area: Rect, screen: &UserScreen, created: &[UserRecord]) {
1192    let mut lines: Vec<Line> = Vec::new();
1193
1194    // Show already-created users
1195    for user in created {
1196        lines.push(Line::from(vec![
1197            Span::styled("  v ", Style::default().fg(Color::Green)),
1198            Span::raw(format!("{} ({})", user.username, user.role)),
1199        ]));
1200    }
1201
1202    if !created.is_empty() {
1203        lines.push(Line::from(""));
1204    }
1205
1206    // The remaining area for the active widget
1207    let used_rows = lines.len() as u16;
1208    let widget_area = Rect {
1209        y: area.y + used_rows,
1210        height: area.height.saturating_sub(used_rows),
1211        ..area
1212    };
1213
1214    frame.render_widget(Paragraph::new(lines), area);
1215
1216    match screen {
1217        UserScreen::AskAdd(dialog) => dialog.render(frame, widget_area),
1218        UserScreen::EnterName(input) => input.render(frame, widget_area),
1219        UserScreen::SelectRole(list) => list.render(frame, widget_area),
1220        UserScreen::CustomResource(input) => input.render(frame, widget_area),
1221        UserScreen::CustomActions(list) => list.render(frame, widget_area),
1222        UserScreen::AskAnother(dialog) => dialog.render(frame, widget_area),
1223        UserScreen::Done => {}
1224    }
1225}
1226
1227fn render_tokens(frame: &mut Frame, area: Rect, screen: &TokenScreen) {
1228    match screen {
1229        TokenScreen::AskGenerate(dialog, _) => dialog.render(frame, area),
1230        TokenScreen::SelectExpiry(list, username) => {
1231            let header = Line::from(Span::raw(format!("  Token for '{username}':")));
1232            let header_area = Rect { height: 1, ..area };
1233            frame.render_widget(Paragraph::new(header), header_area);
1234            let list_area = Rect {
1235                y: area.y + 2,
1236                height: area.height.saturating_sub(2),
1237                ..area
1238            };
1239            list.render(frame, list_area);
1240        }
1241        TokenScreen::ShowToken(record) => {
1242            let lines = vec![
1243                Line::from(vec![
1244                    Span::styled("  v ", Style::default().fg(Color::Green)),
1245                    Span::raw(format!("Token for '{}':", record.username)),
1246                ]),
1247                Line::from(""),
1248                Line::from(Span::styled(
1249                    format!("  {}", record.token),
1250                    Style::default().fg(Color::Yellow),
1251                )),
1252                Line::from(""),
1253                Line::from(Span::raw(format!("  Expires: {}", record.expires))),
1254                Line::from(""),
1255                Line::from(Span::styled(
1256                    "  Save this token now — it cannot be retrieved again.",
1257                    Style::default().fg(Color::Yellow),
1258                )),
1259                Line::from(""),
1260                Line::from(Span::styled(
1261                    "  Press any key to continue...",
1262                    Style::default().fg(Color::DarkGray),
1263                )),
1264            ];
1265            frame.render_widget(Paragraph::new(lines), area);
1266        }
1267        TokenScreen::NextUser | TokenScreen::Done => {}
1268    }
1269}
1270
1271fn render_services(frame: &mut Frame, area: Rect, screen: &ServiceScreen) {
1272    match screen {
1273        ServiceScreen::AskStart(dialog) => dialog.render(frame, area),
1274        ServiceScreen::Starting => {
1275            let line = Line::from(vec![
1276                Span::styled("  > ", Style::default().fg(Color::Yellow)),
1277                Span::raw("Starting services..."),
1278            ]);
1279            frame.render_widget(Paragraph::new(line), area);
1280        }
1281        ServiceScreen::Done(success) => {
1282            let (marker, msg, color) = if *success {
1283                ("v", "Services started", Color::Green)
1284            } else {
1285                ("x", "Service startup failed", Color::Red)
1286            };
1287            let line = Line::from(vec![
1288                Span::styled(format!("  {marker} "), Style::default().fg(color)),
1289                Span::raw(msg),
1290            ]);
1291            frame.render_widget(Paragraph::new(line), area);
1292        }
1293    }
1294}
1295
1296fn render_summary(frame: &mut Frame, area: Rect, screen: &SummaryScreen) {
1297    let mut lines = vec![
1298        Line::from(Span::styled(
1299            "Setup Complete",
1300            Style::default()
1301                .fg(Color::Green)
1302                .add_modifier(Modifier::BOLD),
1303        )),
1304        Line::from(""),
1305    ];
1306
1307    if let Some(ref install) = screen.install_result {
1308        lines.push(Line::from(format!("Install: {install}")));
1309    }
1310
1311    if !screen.templates_applied.is_empty() {
1312        lines.push(Line::from(format!(
1313            "Templates: {}",
1314            screen.templates_applied.join(", ")
1315        )));
1316    }
1317
1318    if !screen.users_created.is_empty() {
1319        lines.push(Line::from("Users:"));
1320        for user in &screen.users_created {
1321            lines.push(Line::from(format!("  {} ({})", user.username, user.role)));
1322        }
1323    }
1324
1325    if !screen.tokens_generated.is_empty() {
1326        lines.push(Line::from("Tokens generated:"));
1327        for token in &screen.tokens_generated {
1328            let preview = if token.token.len() > 20 {
1329                format!("{}...", &token.token[..20])
1330            } else {
1331                token.token.clone()
1332            };
1333            lines.push(Line::from(format!(
1334                "  {} — {} (expires {})",
1335                token.username, preview, token.expires
1336            )));
1337        }
1338    }
1339
1340    if screen.services_started {
1341        lines.push(Line::from(Span::styled(
1342            "Services: running",
1343            Style::default().fg(Color::Green),
1344        )));
1345    }
1346
1347    lines.push(Line::from(""));
1348    lines.push(Line::from("Next steps:"));
1349    lines.push(Line::from("  hyprstream service start"));
1350    lines.push(Line::from("  hyprstream quick list"));
1351    lines.push(Line::from("  hyprstream quick clone <model>"));
1352    lines.push(Line::from("  hyprstream quick infer <model>"));
1353
1354    frame.render_widget(Paragraph::new(lines), area);
1355}
1356
1357#[cfg(test)]
1358mod tests {
1359    use super::*;
1360    use backend::{GpuKind, MockWizardBackend, RunMode};
1361    use waxterm::TerminalApp;
1362
1363    fn make_app() -> WizardApp<MockWizardBackend> {
1364        WizardApp::new(MockWizardBackend::new())
1365    }
1366
1367    /// Advance past install phase (tick once to detect, then skip).
1368    fn skip_install(app: &mut WizardApp<MockWizardBackend>) {
1369        // First tick triggers detection → ShowFindings
1370        app.tick(33);
1371        assert_eq!(
1372            app.phase_number(),
1373            1,
1374            "Should still be at Install after detection"
1375        );
1376        // Press 's' to skip
1377        app.handle_input(WizardCommand::Key(KeyPress::Char(b's')));
1378        assert_eq!(app.phase_number(), 2, "Should be at Bootstrap after skip");
1379    }
1380
1381    /// Advance past bootstrap phase (tick until done).
1382    fn complete_bootstrap(app: &mut WizardApp<MockWizardBackend>) {
1383        for _ in 0..100 {
1384            app.tick(33);
1385            if app.phase_number() > 2 {
1386                break;
1387            }
1388        }
1389        assert!(
1390            app.phase_number() >= 3,
1391            "Should have advanced past bootstrap"
1392        );
1393    }
1394
1395    // ─── Install phase tests ─────────────────────────────────────────────
1396
1397    #[test]
1398    fn test_initial_phase_is_install() {
1399        let app = make_app();
1400        assert_eq!(app.phase_number(), 1);
1401        assert!(matches!(
1402            app.phase,
1403            WizardPhase::Install(InstallScreen::Detecting)
1404        ));
1405        assert!(!app.should_quit());
1406    }
1407
1408    #[test]
1409    fn test_install_detect_advances() {
1410        let mut app = make_app();
1411        // Tick triggers detection
1412        app.tick(33);
1413        assert!(matches!(
1414            app.phase,
1415            WizardPhase::Install(InstallScreen::ShowFindings { .. })
1416        ));
1417    }
1418
1419    #[test]
1420    fn test_install_skip() {
1421        let mut app = make_app();
1422        app.tick(33); // detect
1423                      // Press 's' to skip
1424        app.handle_input(WizardCommand::Key(KeyPress::Char(b's')));
1425        assert_eq!(app.phase_number(), 2, "Should advance to Bootstrap");
1426    }
1427
1428    #[test]
1429    fn test_install_confirm() {
1430        let mut app = make_app();
1431        app.tick(33); // detect → ShowFindings with UpgradeVariant(Cuda130)
1432
1433        // Press Enter to install
1434        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1435        assert!(
1436            matches!(
1437                app.phase,
1438                WizardPhase::Install(InstallScreen::Installing { .. })
1439            ),
1440            "Should be installing"
1441        );
1442
1443        // Tick until done
1444        for _ in 0..50 {
1445            app.tick(33);
1446            if matches!(app.phase, WizardPhase::Install(InstallScreen::Done(_))) {
1447                break;
1448            }
1449        }
1450        assert!(matches!(
1451            app.phase,
1452            WizardPhase::Install(InstallScreen::Done(_))
1453        ));
1454
1455        // Press Enter to advance
1456        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1457        assert_eq!(app.phase_number(), 2, "Should advance to Bootstrap");
1458        assert!(app.install_summary.is_some());
1459    }
1460
1461    #[test]
1462    fn test_install_select_variant() {
1463        let mut app = make_app();
1464        app.tick(33); // detect
1465
1466        // Press 'v' to pick variant
1467        app.handle_input(WizardCommand::Key(KeyPress::Char(b'v')));
1468        assert!(matches!(
1469            app.phase,
1470            WizardPhase::Install(InstallScreen::SelectVariant(_))
1471        ));
1472
1473        // Select first option (CPU)
1474        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1475        assert!(matches!(
1476            app.phase,
1477            WizardPhase::Install(InstallScreen::Installing { .. })
1478        ));
1479    }
1480
1481    #[test]
1482    fn test_install_appimage_auto_skip() {
1483        let backend = MockWizardBackend::new().with_run_mode(RunMode::AppImage);
1484        let mut app = WizardApp::new(backend);
1485
1486        // Tick triggers detection → auto-skip for AppImage
1487        app.tick(33);
1488        assert_eq!(
1489            app.phase_number(),
1490            2,
1491            "AppImage should auto-skip to Bootstrap"
1492        );
1493    }
1494
1495    #[test]
1496    fn test_install_already_current() {
1497        // No GPU → recommends CPU, compiled variant is CPU → AlreadyCurrent
1498        let backend = MockWizardBackend::new().with_gpu(GpuKind::None);
1499        let mut app = WizardApp::new(backend);
1500
1501        app.tick(33); // detect → AlreadyCurrent → Done
1502        assert!(
1503            matches!(app.phase, WizardPhase::Install(InstallScreen::Done(_))),
1504            "Should show Done for already-current"
1505        );
1506
1507        // Enter to continue
1508        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1509        assert_eq!(app.phase_number(), 2);
1510    }
1511
1512    #[test]
1513    fn test_install_development_auto_skip() {
1514        let backend = MockWizardBackend::new().with_run_mode(RunMode::Development);
1515        let mut app = WizardApp::new(backend);
1516
1517        app.tick(33);
1518        assert_eq!(
1519            app.phase_number(),
1520            2,
1521            "Development mode should auto-skip to Bootstrap"
1522        );
1523    }
1524
1525    // ─── Existing tests updated for new phase numbering ──────────────────
1526
1527    #[test]
1528    fn test_bootstrap_auto_advances() {
1529        let mut app = make_app();
1530        skip_install(&mut app);
1531        complete_bootstrap(&mut app);
1532        assert!(
1533            app.phase_number() >= 3,
1534            "Should have advanced past bootstrap"
1535        );
1536    }
1537
1538    #[test]
1539    fn test_full_flow_skip_everything() {
1540        let mut app = make_app();
1541
1542        // Install: skip
1543        skip_install(&mut app);
1544
1545        // Bootstrap
1546        complete_bootstrap(&mut app);
1547        assert_eq!(app.phase_number(), 3);
1548
1549        // Policy: navigate to "None — skip template" (always the last
1550        // option regardless of how many templates the backend reports).
1551        // SelectList clamps at the bottom, so pressing Down more times
1552        // than there are items still lands on the last entry.
1553        for _ in 0..10 {
1554            app.handle_input(WizardCommand::Key(KeyPress::ArrowDown));
1555        }
1556        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1557        assert_eq!(app.phase_number(), 4, "Should be at Users phase");
1558
1559        // Users: decline to add user (press 'n'). The token-queue
1560        // auto-skips when no users were created (advance_to_tokens →
1561        // advance_to_services), so we land on Services directly, NOT
1562        // Tokens.
1563        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n')));
1564        assert_eq!(
1565            app.phase_number(),
1566            6,
1567            "Should be at Services phase (Tokens auto-skipped)"
1568        );
1569
1570        // Services: decline to start (press 'n')
1571        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n')));
1572
1573        // Should be at summary
1574        assert!(matches!(app.phase, WizardPhase::Summary(_)));
1575
1576        // Exit
1577        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1578        assert!(app.should_quit());
1579    }
1580
1581    #[test]
1582    fn test_full_flow_with_install() {
1583        let mut app = make_app();
1584
1585        // Install: detect → confirm → tick through → done → advance
1586        app.tick(33);
1587        app.handle_input(WizardCommand::Key(KeyPress::Enter)); // install
1588        for _ in 0..50 {
1589            app.tick(33);
1590            if matches!(app.phase, WizardPhase::Install(InstallScreen::Done(_))) {
1591                break;
1592            }
1593        }
1594        app.handle_input(WizardCommand::Key(KeyPress::Enter)); // continue
1595        assert_eq!(app.phase_number(), 2);
1596
1597        // Bootstrap
1598        complete_bootstrap(&mut app);
1599
1600        // Skip remaining phases
1601        app.handle_input(WizardCommand::Key(KeyPress::Escape)); // policy
1602        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n'))); // users
1603        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n'))); // tokens
1604        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n'))); // services
1605
1606        assert!(matches!(app.phase, WizardPhase::Summary(_)));
1607        if let WizardPhase::Summary(ref s) = app.phase {
1608            assert!(s.install_result.is_some());
1609        }
1610    }
1611
1612    #[test]
1613    fn test_select_template() {
1614        let mut app = make_app();
1615        skip_install(&mut app);
1616        complete_bootstrap(&mut app);
1617
1618        // Select first template (local)
1619        app.handle_input(WizardCommand::Key(KeyPress::Enter));
1620
1621        // Should have applied template and advanced
1622        assert!(!app.templates_applied.is_empty());
1623        assert_eq!(app.templates_applied[0], "local");
1624    }
1625
1626    #[test]
1627    fn test_quit_at_summary() {
1628        let mut app = make_app();
1629        skip_install(&mut app);
1630        complete_bootstrap(&mut app);
1631
1632        // Skip all phases
1633        app.handle_input(WizardCommand::Key(KeyPress::Escape)); // policy
1634        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n'))); // users
1635        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n'))); // tokens
1636        app.handle_input(WizardCommand::Key(KeyPress::Char(b'n'))); // services
1637
1638        assert!(matches!(app.phase, WizardPhase::Summary(_)));
1639        app.handle_input(WizardCommand::Key(KeyPress::Char(b'q')));
1640        assert!(app.should_quit());
1641    }
1642}