Skip to main content

hyprstream_tui/wizard/
backend.rs

1//! WizardBackend trait and MockWizardBackend for WASI/testing.
2
3// Build-time libtorch metadata (emitted by build.rs).
4pub const LIBTORCH_VERSION: &str = env!("LIBTORCH_VERSION");
5pub const LIBTORCH_ABI: &str = env!("LIBTORCH_ABI");
6pub const LIBTORCH_VARIANT: &str = env!("LIBTORCH_VARIANT");
7
8/// GPU hardware detected on the host.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum GpuKind {
11    /// NVIDIA GPU with driver version and compatible CUDA version.
12    Nvidia {
13        driver_version: String,
14        cuda_compat: String,
15    },
16    /// AMD GPU with optional ROCm version.
17    Amd { rocm_version: Option<String> },
18    /// No GPU detected.
19    None,
20}
21
22/// libtorch variant identifier.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum LibtorchVariant {
25    Cpu,
26    Cuda128,
27    Cuda130,
28    Rocm71,
29}
30
31impl LibtorchVariant {
32    /// Human-readable label for display.
33    pub fn label(&self) -> &str {
34        match self {
35            Self::Cpu => "CPU",
36            Self::Cuda128 => "CUDA 12.8",
37            Self::Cuda130 => "CUDA 13.0",
38            Self::Rocm71 => "ROCm 7.1",
39        }
40    }
41
42    /// Short identifier used in paths and config.
43    pub fn id(&self) -> &str {
44        match self {
45            Self::Cpu => "cpu",
46            Self::Cuda128 => "cuda128",
47            Self::Cuda130 => "cuda130",
48            Self::Rocm71 => "rocm71",
49        }
50    }
51
52    /// All available variants.
53    pub fn all() -> &'static [LibtorchVariant] {
54        &[Self::Cpu, Self::Cuda128, Self::Cuda130, Self::Rocm71]
55    }
56
57    /// Parse from the compile-time variant string.
58    pub fn from_compiled() -> Self {
59        match LIBTORCH_VARIANT {
60            "cuda128" => Self::Cuda128,
61            "cuda130" => Self::Cuda130,
62            "rocm71" => Self::Rocm71,
63            _ => Self::Cpu,
64        }
65    }
66
67    /// Parse from a variant ID string.
68    pub fn from_id(id: &str) -> Option<Self> {
69        match id {
70            "cpu" => Some(Self::Cpu),
71            "cuda128" => Some(Self::Cuda128),
72            "cuda130" => Some(Self::Cuda130),
73            "rocm71" => Some(Self::Rocm71),
74            _ => None,
75        }
76    }
77}
78
79impl core::fmt::Display for LibtorchVariant {
80    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81        f.write_str(self.label())
82    }
83}
84
85/// How hyprstream is currently running.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum RunMode {
88    /// Running from AppImage (self-contained, may manage its own backends).
89    AppImage,
90    /// Standalone binary (cargo install, manual install, etc.).
91    BareBinary,
92    /// Running from cargo in dev (LIBTORCH set, skip install).
93    Development,
94}
95
96/// Snapshot of the runtime environment.
97#[derive(Debug, Clone)]
98pub struct EnvironmentInfo {
99    pub run_mode: RunMode,
100    pub gpu: GpuKind,
101    pub libtorch_path: Option<String>,
102    pub current_variant: LibtorchVariant,
103    pub recommended_variant: LibtorchVariant,
104    pub installed_variant: Option<LibtorchVariant>,
105}
106
107/// Action the wizard recommends.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum InstallAction {
110    /// Nothing to do — skip. Reason displayed to user.
111    Skip { reason: String },
112    /// Download GPU binary + libtorch variant.
113    UpgradeVariant(LibtorchVariant),
114    /// Already running the optimal variant.
115    AlreadyCurrent,
116}
117
118/// Progress during install/download.
119#[derive(Debug, Clone)]
120pub enum InstallPoll {
121    Detecting,
122    Downloading { item: String, pct: u8 },
123    Extracting { item: String },
124    Configuring { step: String },
125    Done { summary: String },
126    Failed(String),
127}
128
129/// Status of an async bootstrap step.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum BootstrapPoll {
132    /// Bootstrap still running. Message describes current step.
133    InProgress(String),
134    /// Bootstrap finished successfully. Steps completed.
135    Done(Vec<String>),
136    /// Bootstrap failed.
137    Failed(String),
138}
139
140/// Result of generating a token.
141#[derive(Debug, Clone)]
142pub struct TokenResult {
143    pub token: String,
144    pub expires: String,
145}
146
147/// Information about a policy template.
148#[derive(Debug, Clone)]
149pub struct TemplateInfo {
150    pub name: String,
151    pub description: String,
152}
153
154/// Status for polling async operations.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum OpStatus {
157    InProgress,
158    Done,
159    Failed(String),
160}
161
162/// Backend trait abstracting real hyprstream operations from the TUI.
163///
164/// `MockWizardBackend` provides canned responses for WASI/browser and testing.
165/// The native `BootstrapManager` (in hyprstream) bridges to the real runtime.
166pub trait WizardBackend {
167    // Install phase
168    fn detect_environment(&mut self) -> EnvironmentInfo;
169    fn recommend_action(&self, env: &EnvironmentInfo) -> InstallAction;
170    fn start_install(&mut self, variant: &LibtorchVariant);
171    fn poll_install(&mut self) -> InstallPoll;
172
173    // Bootstrap phase
174    fn start_bootstrap(&mut self);
175    fn poll_bootstrap(&mut self) -> BootstrapPoll;
176    fn has_existing_policy(&self) -> bool;
177    fn apply_template(&mut self, name: &str);
178    fn add_user(&mut self, username: &str, role: &str);
179    fn add_user_custom(&mut self, username: &str, resource: &str, actions: &[String]);
180    fn save_policies(&mut self);
181    fn generate_token(&mut self, username: &str, duration: &str) -> TokenResult;
182    fn start_services(&mut self);
183    fn poll_pending(&mut self) -> OpStatus;
184    fn local_username(&self) -> String;
185    fn templates(&self) -> Vec<TemplateInfo>;
186}
187
188/// Mock backend with canned responses for WASI/browser and testing.
189pub struct MockWizardBackend {
190    bootstrap_tick: u32,
191    bootstrap_started: bool,
192    service_tick: u32,
193    service_started: bool,
194    install_tick: u32,
195    install_started: bool,
196    detect_tick: u32,
197    detect_started: bool,
198    mock_run_mode: RunMode,
199    mock_gpu: GpuKind,
200}
201
202impl MockWizardBackend {
203    pub fn new() -> Self {
204        Self {
205            bootstrap_tick: 0,
206            bootstrap_started: false,
207            service_tick: 0,
208            service_started: false,
209            install_tick: 0,
210            install_started: false,
211            detect_tick: 0,
212            detect_started: false,
213            mock_run_mode: RunMode::BareBinary,
214            mock_gpu: GpuKind::Nvidia {
215                driver_version: "555.42".to_string(),
216                cuda_compat: "cuda130".to_string(),
217            },
218        }
219    }
220
221    /// Create a mock with AppImage run mode (auto-skips install).
222    pub fn with_run_mode(mut self, mode: RunMode) -> Self {
223        self.mock_run_mode = mode;
224        self
225    }
226
227    /// Override the mock GPU detection.
228    pub fn with_gpu(mut self, gpu: GpuKind) -> Self {
229        self.mock_gpu = gpu;
230        self
231    }
232}
233
234impl Default for MockWizardBackend {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240const BOOTSTRAP_STEPS: &[&str] = &[
241    "Checking directories...",
242    "Verifying registry...",
243    "Loading signing key...",
244    "Validating environment...",
245];
246
247impl WizardBackend for MockWizardBackend {
248    fn detect_environment(&mut self) -> EnvironmentInfo {
249        self.detect_started = true;
250        self.detect_tick = 0;
251        let recommended = match &self.mock_gpu {
252            GpuKind::Nvidia { cuda_compat, .. } => match cuda_compat.as_str() {
253                "cuda128" => LibtorchVariant::Cuda128,
254                "cuda130" => LibtorchVariant::Cuda130,
255                _ => LibtorchVariant::Cpu,
256            },
257            GpuKind::Amd { rocm_version } => {
258                if rocm_version.is_some() {
259                    LibtorchVariant::Rocm71
260                } else {
261                    LibtorchVariant::Cpu
262                }
263            }
264            GpuKind::None => LibtorchVariant::Cpu,
265        };
266        EnvironmentInfo {
267            run_mode: self.mock_run_mode.clone(),
268            gpu: self.mock_gpu.clone(),
269            libtorch_path: None,
270            // Use Cpu so the mock always recommends an upgrade (UpgradeVariant)
271            // rather than AlreadyCurrent, which depends on the build environment.
272            current_variant: LibtorchVariant::Cpu,
273            recommended_variant: recommended,
274            installed_variant: None,
275        }
276    }
277
278    fn recommend_action(&self, env: &EnvironmentInfo) -> InstallAction {
279        if env.run_mode == RunMode::Development {
280            return InstallAction::Skip {
281                reason: "Development mode — LIBTORCH already configured".to_string(),
282            };
283        }
284        if env.run_mode == RunMode::AppImage {
285            return InstallAction::Skip {
286                reason: "AppImage manages its own backends".to_string(),
287            };
288        }
289        if env.current_variant == env.recommended_variant {
290            return InstallAction::AlreadyCurrent;
291        }
292        if let Some(ref installed) = env.installed_variant {
293            if *installed == env.recommended_variant {
294                return InstallAction::AlreadyCurrent;
295            }
296        }
297        InstallAction::UpgradeVariant(env.recommended_variant.clone())
298    }
299
300    fn start_install(&mut self, _variant: &LibtorchVariant) {
301        self.install_started = true;
302        self.install_tick = 0;
303    }
304
305    fn poll_install(&mut self) -> InstallPoll {
306        if !self.install_started {
307            return InstallPoll::Failed("Install not started".to_string());
308        }
309        self.install_tick += 1;
310        match self.install_tick {
311            1..=20 => InstallPoll::Downloading {
312                item: "libtorch".to_string(),
313                pct: ((self.install_tick as u16) * 5).min(100) as u8,
314            },
315            21 => InstallPoll::Extracting {
316                item: "libtorch".to_string(),
317            },
318            22..=32 => InstallPoll::Downloading {
319                item: "hyprstream".to_string(),
320                pct: (((self.install_tick - 22) as u16) * 10).min(100) as u8,
321            },
322            33 => InstallPoll::Configuring {
323                step: "Setting up LD_LIBRARY_PATH".to_string(),
324            },
325            _ => {
326                self.install_started = false;
327                InstallPoll::Done {
328                    summary: "GPU backend installed successfully".to_string(),
329                }
330            }
331        }
332    }
333
334    fn start_bootstrap(&mut self) {
335        self.bootstrap_started = true;
336        self.bootstrap_tick = 0;
337    }
338
339    fn poll_bootstrap(&mut self) -> BootstrapPoll {
340        if !self.bootstrap_started {
341            return BootstrapPoll::InProgress("Not started".to_string());
342        }
343        self.bootstrap_tick += 1;
344        let step_idx = (self.bootstrap_tick / 8) as usize; // ~8 ticks per step at 30fps
345        if step_idx >= BOOTSTRAP_STEPS.len() {
346            BootstrapPoll::Done(vec![
347                "Directories OK".to_string(),
348                "Registry OK".to_string(),
349                "Signing key OK".to_string(),
350                "Environment OK".to_string(),
351            ])
352        } else {
353            BootstrapPoll::InProgress(BOOTSTRAP_STEPS[step_idx].to_string())
354        }
355    }
356
357    fn has_existing_policy(&self) -> bool {
358        false
359    }
360
361    fn apply_template(&mut self, _name: &str) {
362        // Mock: instant success
363    }
364
365    fn add_user(&mut self, _username: &str, _role: &str) {
366        // Mock: instant success
367    }
368
369    fn add_user_custom(&mut self, _username: &str, _resource: &str, _actions: &[String]) {
370        // Mock: instant success
371    }
372
373    fn save_policies(&mut self) {
374        // Mock: instant success
375    }
376
377    fn generate_token(&mut self, username: &str, duration: &str) -> TokenResult {
378        TokenResult {
379            token: format!("hypr_{username}_mock_token_xxxxxxxxxxxx"),
380            expires: match duration {
381                "30d" => "2026-04-01".to_string(),
382                "1y" => "2027-03-02".to_string(),
383                "never" => "never".to_string(),
384                _ => "2026-06-01".to_string(),
385            },
386        }
387    }
388
389    fn start_services(&mut self) {
390        self.service_started = true;
391        self.service_tick = 0;
392    }
393
394    fn poll_pending(&mut self) -> OpStatus {
395        if !self.service_started {
396            return OpStatus::Done;
397        }
398        self.service_tick += 1;
399        if self.service_tick > 15 {
400            self.service_started = false;
401            OpStatus::Done
402        } else {
403            OpStatus::InProgress
404        }
405    }
406
407    fn local_username(&self) -> String {
408        "localuser".to_string()
409    }
410
411    fn templates(&self) -> Vec<TemplateInfo> {
412        vec![
413            TemplateInfo {
414                name: "local".to_string(),
415                description: "Full access for local user (recommended)".to_string(),
416            },
417            TemplateInfo {
418                name: "team".to_string(),
419                description: "Multi-user with admin, operator, viewer roles".to_string(),
420            },
421            TemplateInfo {
422                name: "production".to_string(),
423                description: "Locked-down production environment".to_string(),
424            },
425        ]
426    }
427}