Skip to main content

hyprstream_tui/
shell_app.rs

1//! ShellApp — TUI shell with model list modal, settings, and background.
2//!
3//! Each "window" is a PTY-backed shell process. Output is VTE-parsed by
4//! `avt::Vt`. The model list modal (F10) lets users open shells scoped to a
5//! model worktree directory. The settings modal (F11) lets users choose a
6//! background style. When no windows are open the animated background fills
7//! the pane area.
8
9#![cfg(not(target_os = "wasi"))]
10
11use std::path::PathBuf;
12
13use waxterm::app::TerminalApp;
14use waxterm::input::KeyPress;
15use waxterm::widgets::{SelectList, TextInput, WidgetResult};
16
17use crate::background::{BackgroundState, BackgroundStyle, ALL_STYLES, PREVIEW_H, PREVIEW_W};
18use crate::shell::{kill_shell, spawn_shell, ShellInput};
19use crate::vt_pane::VtPane;
20
21type LoadFn = Box<dyn Fn(&str, ModelStatusSender) + Send>;
22
23// ============================================================================
24// Git operation types
25// ============================================================================
26
27/// Progress update from a background git operation.
28#[derive(Debug, Clone)]
29pub enum GitOpProgress {
30    CloneProgress {
31        stage: String,
32        pct: u8,
33    },
34    Status(String),
35    Done {
36        message: String,
37        new_model: Option<ModelEntry>,
38    },
39    Failed(String),
40    /// Authoritative model list from a background registry re-scan (refresh_fn).
41    ModelList(Vec<ModelEntry>),
42}
43
44pub type GitProgressSender = std::sync::mpsc::Sender<GitOpProgress>;
45pub type CloneFn = Box<dyn Fn(String, Option<String>, Option<String>, GitProgressSender) + Send>;
46pub type PullFn = Box<dyn Fn(String, GitProgressSender) + Send>;
47pub type PushFn = Box<dyn Fn(String, GitProgressSender) + Send>;
48pub type FetchStatusFn =
49    Box<dyn Fn(Vec<String>, std::sync::mpsc::Sender<(String, u32, u32, bool)>) + Send>;
50/// Re-query the registry for the current model set; results return via
51/// `GitOpProgress::ModelList` on the shared git-progress channel.
52pub type RefreshFn = Box<dyn Fn(GitProgressSender) + Send>;
53
54/// Bundled git operation callbacks injected by the service layer.
55pub struct GitOps {
56    pub clone_fn: CloneFn,
57    pub pull_fn: PullFn,
58    pub push_fn: PushFn,
59    pub fetch_status_fn: FetchStatusFn,
60    pub refresh_fn: RefreshFn,
61}
62
63// ============================================================================
64// Model discovery
65// ============================================================================
66
67/// A model repo discovered in the registry directory.
68#[derive(Clone, Debug)]
69pub struct ModelEntry {
70    pub model_ref: String, // "name:branch"
71    pub path: PathBuf,
72    pub loaded: bool,
73    pub ahead: u32,
74    pub behind: u32,
75    pub is_dirty: bool,
76}
77
78impl std::fmt::Display for ModelEntry {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "{}", self.model_ref)?;
81        if self.loaded {
82            write!(f, " [loaded]")?;
83        }
84        if self.ahead > 0 || self.behind > 0 {
85            write!(f, " [+{}/-{}]", self.ahead, self.behind)?;
86        }
87        if self.is_dirty {
88            write!(f, " [dirty]")?;
89        }
90        Ok(())
91    }
92}
93
94/// Scan `registry` for git repos (directories containing `.git` or `HEAD`).
95pub fn discover_models(registry: &std::path::Path) -> Vec<ModelEntry> {
96    let Ok(entries) = std::fs::read_dir(registry) else {
97        return vec![];
98    };
99    let mut models: Vec<ModelEntry> = entries
100        .filter_map(|e| e.ok())
101        .filter(|e| e.path().join(".git").exists() || e.path().join("HEAD").exists())
102        .map(|e| ModelEntry {
103            model_ref: e.file_name().to_string_lossy().into_owned(),
104            path: e.path(),
105            loaded: false,
106            ahead: 0,
107            behind: 0,
108            is_dirty: false,
109        })
110        .collect();
111    models.sort_by(|a, b| a.model_ref.cmp(&b.model_ref));
112    models
113}
114
115/// Merge an authoritative `incoming` model list against the `existing` entries,
116/// carrying over each existing entry's git status (ahead/behind/dirty — fetched
117/// out-of-band) and returning the index that keeps `selected_ref` selected
118/// (falling back to 0). The authoritative list defines membership, so models
119/// removed upstream drop out and newly-cloned models appear.
120fn merge_models(
121    existing: &[ModelEntry],
122    incoming: Vec<ModelEntry>,
123    selected_ref: Option<&str>,
124) -> (Vec<ModelEntry>, usize) {
125    let prev: std::collections::HashMap<&str, &ModelEntry> =
126        existing.iter().map(|e| (e.model_ref.as_str(), e)).collect();
127    let merged: Vec<ModelEntry> = incoming
128        .into_iter()
129        .map(|mut m| {
130            if let Some(p) = prev.get(m.model_ref.as_str()) {
131                m.ahead = p.ahead;
132                m.behind = p.behind;
133                m.is_dirty = p.is_dirty;
134            }
135            m
136        })
137        .collect();
138    let new_index = selected_ref
139        .and_then(|r| merged.iter().position(|e| e.model_ref == r))
140        .unwrap_or(0);
141    (merged, new_index)
142}
143
144// ============================================================================
145// Pane window
146// ============================================================================
147
148/// A running shell attached to an avt virtual terminal via `VtPane`.
149pub struct PaneWindow {
150    pub title: String,
151    /// VT state + stdout channel.
152    pub pane: VtPane,
153    /// OS PID for SIGTERM on Drop.
154    shell_pid: u32,
155    /// Send input bytes or control signals to the shell.
156    input_tx: std::sync::mpsc::SyncSender<ShellInput>,
157}
158
159impl PaneWindow {
160    pub fn new(title: String, cwd: Option<PathBuf>, cols: u16, rows: u16) -> std::io::Result<Self> {
161        let shell = spawn_shell(cwd, cols, rows)?;
162        let pane = VtPane::new(cols, rows, shell.stdout_rx, None);
163        Ok(Self {
164            title,
165            pane,
166            shell_pid: shell.pid,
167            input_tx: shell.input_tx,
168        })
169    }
170
171    /// Drain stdout_rx into the VTE parser.
172    ///
173    /// Returns `(got_data, is_dead)`:
174    /// - `got_data` — true if any bytes arrived (caller should redraw)
175    /// - `is_dead`  — true if the channel disconnected (PTY process exited)
176    pub fn drain(&mut self) -> (bool, bool) {
177        self.pane.drain()
178    }
179
180    /// Send raw bytes to the shell stdin.
181    pub fn send_bytes(&self, data: Vec<u8>) {
182        let _ = self.input_tx.send(ShellInput::Bytes(data));
183    }
184
185    /// Resize the PTY and VT.
186    pub fn resize(&mut self, cols: u16, rows: u16) {
187        // Shell-specific xterm escape to inform the VT of new dimensions.
188        self.pane.vt.feed_str(&format!("\x1b[8;{rows};{cols}t"));
189        self.pane.resize_vt(cols, rows);
190        let _ = self.input_tx.send(ShellInput::Resize { cols, rows });
191    }
192}
193
194impl Drop for PaneWindow {
195    fn drop(&mut self) {
196        kill_shell(self.shell_pid);
197    }
198}
199
200// ============================================================================
201// App mode
202// ============================================================================
203
204/// Clone flow sub-screens.
205pub enum CloneScreen {
206    /// Prompting for the repository URL.
207    EnterUrl(TextInput),
208    /// Prompting for an optional local name (URL stored from previous step).
209    EnterName(TextInput, String),
210    /// Clone in progress — progress updates driven by tick().
211    Cloning {
212        url: String,
213        name: String,
214        progress_msg: String,
215        progress_pct: u8,
216    },
217    /// Clone completed successfully.
218    Done(String),
219    /// Clone failed.
220    Failed(String),
221}
222
223pub enum ShellMode {
224    /// Keys forwarded directly to the active shell.
225    Normal,
226    /// Model list modal is open.
227    ModelList,
228    /// Settings modal is open.
229    Settings,
230    /// Start-menu popup (Ctrl+Space).
231    StartMenu { selected: usize },
232    /// Multi-step clone flow.
233    CloneFlow(CloneScreen),
234    /// Pull/push in progress.
235    GitOpInProgress {
236        op_name: String,
237        model_ref: String,
238        progress_msg: String,
239    },
240}
241
242/// Menu items: (label, chord hint shown in popup).
243pub const MENU_ITEMS: &[(&str, &str)] = &[
244    ("New", "N"),
245    ("Close", "Q"),
246    ("Cycle", "Tab"),
247    ("Models", "M"),
248    ("Settings", "S"),
249    ("Disconnect", "D"),
250];
251
252// ============================================================================
253// Command
254// ============================================================================
255
256pub enum ShellCmd {
257    Key(KeyPress),
258}
259
260impl From<KeyPress> for ShellCmd {
261    fn from(k: KeyPress) -> Self {
262        ShellCmd::Key(k)
263    }
264}
265
266// ============================================================================
267// ShellApp
268// ============================================================================
269
270/// Sender half for model status updates from background load-polling threads.
271pub type ModelStatusSender = std::sync::mpsc::Sender<(String, bool)>;
272
273pub struct ShellApp {
274    pub mode: ShellMode,
275    pub windows: Vec<PaneWindow>,
276    pub active: usize,
277    pub model_list: SelectList<ModelEntry>,
278    /// Background animation state (full terminal area).
279    pub bg: BackgroundState,
280    /// Background animation state for the settings preview box.
281    pub preview_bg: BackgroundState,
282    /// Settings drop-down (one entry per BackgroundStyle).
283    pub settings_list: SelectList<BackgroundStyle>,
284    /// Background style saved when settings opens — restored on cancel.
285    saved_style: BackgroundStyle,
286    /// Shown in status bar while a model is loading.
287    pub load_status: Option<String>,
288    /// Receives `(model_ref, loaded)` updates from background load-polling threads.
289    status_rx: std::sync::mpsc::Receiver<(String, bool)>,
290    /// Cloned and passed into `load_fn` on each call.
291    status_tx: ModelStatusSender,
292    pub cols: u16,
293    pub rows: u16,
294    quit: bool,
295    /// Ctrl-B prefix was pressed; next key selects action.
296    ctrl_b_pending: bool,
297    /// Submit a load request.  Receives a `ModelStatusSender` to push the final
298    /// `(model_ref, true/false)` result once the model is actually loaded.
299    load_fn: LoadFn,
300    unload_fn: Box<dyn Fn(&str) -> bool + Send>,
301    /// Git operation callbacks (clone, pull, push, status fetch).
302    git_ops: Option<GitOps>,
303    /// Receives progress updates from background git operations.
304    git_progress_rx: std::sync::mpsc::Receiver<GitOpProgress>,
305    /// Sender cloned into git operation callbacks.
306    git_progress_tx: GitProgressSender,
307    /// Receives per-model status updates (model_ref, ahead, behind, dirty).
308    git_status_rx: std::sync::mpsc::Receiver<(String, u32, u32, bool)>,
309    git_status_tx: std::sync::mpsc::Sender<(String, u32, u32, bool)>,
310    /// Registry dir the model list was discovered from; re-scanned when the
311    /// ModelList view opens so models cloned out-of-band (CLI, another window)
312    /// appear without restarting the TUI.
313    registry_dir: Option<PathBuf>,
314}
315
316impl ShellApp {
317    pub fn new(
318        models: Vec<ModelEntry>,
319        cols: u16,
320        rows: u16,
321        load_fn: LoadFn,
322        unload_fn: Box<dyn Fn(&str) -> bool + Send>,
323        git_ops: Option<GitOps>,
324        registry_dir: Option<PathBuf>,
325    ) -> Self {
326        let pane_rows = rows.saturating_sub(2);
327        let initial = PaneWindow::new("shell".to_owned(), None, cols, pane_rows)
328            .unwrap_or_else(|e| panic!("Failed to spawn shell: {e}"));
329
330        let model_list = SelectList::new("Models", models);
331
332        let default_style = BackgroundStyle::Stars;
333        let settings_list = SelectList::new("Background", ALL_STYLES.to_vec()).with_selected(1); // Stars is index 1
334
335        let (status_tx, status_rx) = std::sync::mpsc::channel();
336        let (git_progress_tx, git_progress_rx) = std::sync::mpsc::channel();
337        let (git_status_tx, git_status_rx) = std::sync::mpsc::channel();
338
339        Self {
340            mode: ShellMode::Normal,
341            windows: vec![initial],
342            active: 0,
343            model_list,
344            bg: BackgroundState::new(default_style),
345            preview_bg: BackgroundState::new(default_style),
346            settings_list,
347            saved_style: default_style,
348            load_status: None,
349            status_rx,
350            status_tx,
351            cols,
352            rows,
353            quit: false,
354            ctrl_b_pending: false,
355            load_fn,
356            unload_fn,
357            git_ops,
358            git_progress_rx,
359            git_progress_tx,
360            git_status_rx,
361            git_status_tx,
362            registry_dir,
363        }
364    }
365
366    /// Refresh the model list so a model cloned out-of-band (CLI, another
367    /// window) shows up without restarting the TUI. Called when the ModelList
368    /// view opens. Service-backed: re-query the registry via `refresh_fn`
369    /// (authoritative `name:branch` refs); results arrive asynchronously as
370    /// `GitOpProgress::ModelList` and are merged in `tick`. Standalone (no git
371    /// ops): re-scan the registry dir synchronously.
372    fn refresh_model_list(&mut self) {
373        if let Some(ref git_ops) = self.git_ops {
374            (git_ops.refresh_fn)(self.git_progress_tx.clone());
375            return;
376        }
377        let Some(ref dir) = self.registry_dir else {
378            return;
379        };
380        let discovered = discover_models(dir);
381        self.merge_model_list(discovered);
382    }
383
384    /// Merge an authoritative model list into `model_list`, preserving the
385    /// per-entry git status (ahead/behind/dirty) the status thread populated and
386    /// keeping the current selection on the same model where possible.
387    fn merge_model_list(&mut self, incoming: Vec<ModelEntry>) {
388        if incoming.is_empty() {
389            return;
390        }
391        let selected_ref = self.model_list.selected_item().map(|e| e.model_ref.clone());
392        let (merged, new_index) =
393            merge_models(self.model_list.items(), incoming, selected_ref.as_deref());
394        self.model_list = SelectList::new("Models", merged).with_selected(new_index);
395    }
396
397    pub fn pane_rows(&self) -> u16 {
398        self.rows.saturating_sub(2)
399    }
400
401    fn open_terminal(&mut self, cwd: Option<PathBuf>, title: String) {
402        let rows = self.pane_rows();
403        match PaneWindow::new(title, cwd, self.cols, rows) {
404            Ok(win) => {
405                self.windows.push(win);
406                self.active = self.windows.len() - 1;
407            }
408            Err(e) => {
409                eprintln!("hyprstream-tui: open_terminal failed: {e}");
410            }
411        }
412    }
413
414    fn close_active(&mut self) {
415        if self.windows.is_empty() {
416            return;
417        }
418        self.windows.remove(self.active);
419        if !self.windows.is_empty() {
420            self.active = self.active.min(self.windows.len() - 1);
421        }
422    }
423
424    fn cycle_window(&mut self) {
425        if !self.windows.is_empty() {
426            self.active = (self.active + 1) % self.windows.len();
427        }
428    }
429
430    fn handle_normal(&mut self, key: KeyPress) -> bool {
431        // Ctrl-B prefix: next key selects action.
432        if self.ctrl_b_pending {
433            self.ctrl_b_pending = false;
434            match key {
435                KeyPress::Char(b'q') | KeyPress::Char(b'd') => {
436                    self.quit = true;
437                    return true;
438                }
439                _ => {
440                    // Not a multiplexer key — forward Ctrl-B + this key to PTY.
441                    if let Some(win) = self.windows.get(self.active) {
442                        win.send_bytes(vec![0x02]);
443                        let bytes = keypress_to_bytes(key);
444                        if !bytes.is_empty() {
445                            win.send_bytes(bytes);
446                        }
447                    }
448                    return false;
449                }
450            }
451        }
452        match key {
453            KeyPress::CtrlSpace => {
454                self.mode = ShellMode::StartMenu { selected: 0 };
455                true
456            }
457            KeyPress::Char(0x02) => {
458                // Ctrl-B prefix — wait for next key.
459                self.ctrl_b_pending = true;
460                true
461            }
462            key => {
463                let bytes = keypress_to_bytes(key);
464                if let Some(win) = self.windows.get(self.active) {
465                    if !bytes.is_empty() {
466                        win.send_bytes(bytes);
467                    }
468                }
469                false
470            }
471        }
472    }
473
474    fn handle_model_list(&mut self, key: KeyPress) -> bool {
475        // Clone — opens the clone flow (no model selection needed).
476        if matches!(key, KeyPress::Char(b'c')) && self.git_ops.is_some() {
477            self.mode =
478                ShellMode::CloneFlow(CloneScreen::EnterUrl(TextInput::new("Repository URL:")));
479            return true;
480        }
481
482        // Pull — fetch+merge for the selected model.
483        if matches!(key, KeyPress::Char(b'p')) {
484            if let (Some(git_ops), Some(model)) =
485                (&self.git_ops, self.model_list.selected_item().cloned())
486            {
487                (git_ops.pull_fn)(model.model_ref.clone(), self.git_progress_tx.clone());
488                self.mode = ShellMode::GitOpInProgress {
489                    op_name: "Pull".to_owned(),
490                    model_ref: model.model_ref,
491                    progress_msg: "Fetching…".to_owned(),
492                };
493                return true;
494            }
495        }
496
497        // Push — push commits for the selected model.
498        if matches!(key, KeyPress::Char(b'P')) {
499            if let (Some(git_ops), Some(model)) =
500                (&self.git_ops, self.model_list.selected_item().cloned())
501            {
502                (git_ops.push_fn)(model.model_ref.clone(), self.git_progress_tx.clone());
503                self.mode = ShellMode::GitOpInProgress {
504                    op_name: "Push".to_owned(),
505                    model_ref: model.model_ref,
506                    progress_msg: "Pushing…".to_owned(),
507                };
508                return true;
509            }
510        }
511
512        if matches!(key, KeyPress::Char(b'l' | b'L')) {
513            if let Some(model) = self.model_list.selected_item().cloned() {
514                (self.load_fn)(&model.model_ref, self.status_tx.clone());
515                self.load_status = Some(format!("Loading {}…", model.model_ref));
516                return true;
517            }
518        }
519        if matches!(key, KeyPress::Char(b'u' | b'U')) {
520            if let Some(model) = self.model_list.selected_item().cloned() {
521                let ok = (self.unload_fn)(&model.model_ref);
522                if ok {
523                    let idx = self.model_list.selected_index();
524                    if let Some(entry) = self.model_list.items_mut().get_mut(idx) {
525                        entry.loaded = false;
526                    }
527                }
528                return true;
529            }
530        }
531
532        #[cfg(any(target_os = "linux", target_os = "openbsd"))]
533        if matches!(key, KeyPress::Char(b't' | b'T') | KeyPress::Enter) {
534            if let Some(model) = self.model_list.selected_item().cloned() {
535                self.open_terminal(Some(model.path), format!("{} shell", model.model_ref));
536                self.mode = ShellMode::Normal;
537                return true;
538            }
539        }
540
541        match self.model_list.handle_key(&key) {
542            WidgetResult::Cancelled => {
543                self.mode = ShellMode::Normal;
544                true
545            }
546            WidgetResult::Confirmed(model) => {
547                #[cfg(any(target_os = "linux", target_os = "openbsd"))]
548                self.open_terminal(Some(model.path), format!("{} shell", model.model_ref));
549                #[cfg(not(any(target_os = "linux", target_os = "openbsd")))]
550                let _ = model;
551                self.mode = ShellMode::Normal;
552                true
553            }
554            WidgetResult::Pending => true,
555        }
556    }
557
558    fn handle_clone_flow(&mut self, key: KeyPress) -> bool {
559        let screen = std::mem::replace(
560            &mut self.mode,
561            ShellMode::Normal, // temporary placeholder
562        );
563        let ShellMode::CloneFlow(screen) = screen else {
564            self.mode = screen;
565            return false;
566        };
567
568        match screen {
569            CloneScreen::EnterUrl(mut input) => match input.handle_key(&key) {
570                WidgetResult::Confirmed(url) => {
571                    if url.trim().is_empty() {
572                        self.mode = ShellMode::ModelList;
573                    } else {
574                        self.mode = ShellMode::CloneFlow(CloneScreen::EnterName(
575                            TextInput::new("Local name (Enter for default):"),
576                            url,
577                        ));
578                    }
579                }
580                WidgetResult::Cancelled => {
581                    self.mode = ShellMode::ModelList;
582                }
583                WidgetResult::Pending => {
584                    self.mode = ShellMode::CloneFlow(CloneScreen::EnterUrl(input));
585                }
586            },
587            CloneScreen::EnterName(mut input, url) => match input.handle_key(&key) {
588                WidgetResult::Confirmed(name) => {
589                    let name_opt = if name.trim().is_empty() {
590                        None
591                    } else {
592                        Some(name)
593                    };
594                    let display_name = name_opt.clone().unwrap_or_else(|| url.clone());
595                    if let Some(ref git_ops) = self.git_ops {
596                        (git_ops.clone_fn)(
597                            url.clone(),
598                            name_opt,
599                            None,
600                            self.git_progress_tx.clone(),
601                        );
602                    }
603                    self.mode = ShellMode::CloneFlow(CloneScreen::Cloning {
604                        url,
605                        name: display_name,
606                        progress_msg: "Starting…".to_owned(),
607                        progress_pct: 0,
608                    });
609                }
610                WidgetResult::Cancelled => {
611                    self.mode = ShellMode::ModelList;
612                }
613                WidgetResult::Pending => {
614                    self.mode = ShellMode::CloneFlow(CloneScreen::EnterName(input, url));
615                }
616            },
617            CloneScreen::Cloning {
618                url,
619                name,
620                progress_msg,
621                progress_pct,
622            } => {
623                // No key handling during clone — progress driven by tick().
624                self.mode = ShellMode::CloneFlow(CloneScreen::Cloning {
625                    url,
626                    name,
627                    progress_msg,
628                    progress_pct,
629                });
630            }
631            CloneScreen::Done(_) | CloneScreen::Failed(_) => {
632                if matches!(key, KeyPress::Enter | KeyPress::Escape) {
633                    self.mode = ShellMode::ModelList;
634                } else {
635                    self.mode = ShellMode::CloneFlow(screen);
636                }
637            }
638        }
639        true
640    }
641
642    fn handle_git_op_progress(&mut self, key: KeyPress) -> bool {
643        // Allow Esc/Enter to dismiss after completion (detected by "Done:" or "Error:" prefix).
644        if let ShellMode::GitOpInProgress {
645            ref progress_msg, ..
646        } = self.mode
647        {
648            if (progress_msg.starts_with("Done:") || progress_msg.starts_with("Error:"))
649                && matches!(key, KeyPress::Enter | KeyPress::Escape)
650            {
651                self.mode = ShellMode::ModelList;
652            }
653        }
654        true
655    }
656
657    fn handle_start_menu(&mut self, key: KeyPress, selected: usize) -> bool {
658        let n = MENU_ITEMS.len();
659        // Chord shortcuts execute immediately, closing the menu.
660        let chord_action: Option<usize> = match key {
661            KeyPress::Char(b'n' | b'N') => Some(0),
662            KeyPress::Char(b'q' | b'Q') => Some(1),
663            KeyPress::Tab => Some(2),
664            KeyPress::Char(b'm' | b'M') => Some(3),
665            KeyPress::Char(b's' | b'S') => Some(4),
666            KeyPress::Char(b'd' | b'D') => Some(5),
667            _ => None,
668        };
669        if let Some(idx) = chord_action {
670            self.mode = ShellMode::Normal;
671            return self.execute_menu_action(idx);
672        }
673        match key {
674            KeyPress::Escape | KeyPress::CtrlSpace => {
675                self.mode = ShellMode::Normal;
676            }
677            KeyPress::ArrowUp => {
678                self.mode = ShellMode::StartMenu {
679                    selected: if selected == 0 { n - 1 } else { selected - 1 },
680                };
681            }
682            KeyPress::ArrowDown => {
683                self.mode = ShellMode::StartMenu {
684                    selected: (selected + 1) % n,
685                };
686            }
687            KeyPress::Enter => {
688                self.mode = ShellMode::Normal;
689                return self.execute_menu_action(selected);
690            }
691            _ => {}
692        }
693        true
694    }
695
696    fn execute_menu_action(&mut self, idx: usize) -> bool {
697        match idx {
698            0 => self.open_terminal(None, "shell".to_owned()),
699            1 => self.close_active(),
700            2 => self.cycle_window(),
701            3 => {
702                self.refresh_model_list();
703                self.mode = ShellMode::ModelList;
704                self.fetch_git_status();
705            }
706            4 => {
707                self.saved_style = self.bg.style;
708                let i = ALL_STYLES
709                    .iter()
710                    .position(|s| *s == self.bg.style)
711                    .unwrap_or(0);
712                self.settings_list =
713                    SelectList::new("Background", ALL_STYLES.to_vec()).with_selected(i);
714                self.preview_bg.style = self.bg.style;
715                self.mode = ShellMode::Settings;
716            }
717            5 => {
718                self.quit = true;
719            }
720            _ => {}
721        }
722        true
723    }
724
725    fn fetch_git_status(&self) {
726        if let Some(ref git_ops) = self.git_ops {
727            let refs: Vec<String> = self
728                .model_list
729                .items()
730                .iter()
731                .map(|e| e.model_ref.clone())
732                .collect();
733            if !refs.is_empty() {
734                (git_ops.fetch_status_fn)(refs, self.git_status_tx.clone());
735            }
736        }
737    }
738
739    fn handle_settings(&mut self, key: KeyPress) -> bool {
740        match self.settings_list.handle_key(&key) {
741            WidgetResult::Cancelled => {
742                // Restore saved style on Esc.
743                self.bg.style = self.saved_style;
744                self.preview_bg.style = self.saved_style;
745                self.mode = ShellMode::Normal;
746                true
747            }
748            WidgetResult::Confirmed(style) => {
749                self.bg.style = style;
750                self.preview_bg.style = style;
751                self.mode = ShellMode::Normal;
752                true
753            }
754            WidgetResult::Pending => {
755                // Live-preview: sync bg style to the highlighted list entry.
756                if let Some(&style) = self.settings_list.selected_item() {
757                    self.bg.style = style;
758                    self.preview_bg.style = style;
759                }
760                true
761            }
762        }
763    }
764}
765
766impl TerminalApp for ShellApp {
767    type Command = ShellCmd;
768
769    fn render(&self, frame: &mut ratatui::Frame) {
770        crate::shell_ui::draw(frame, self);
771    }
772
773    fn handle_input(&mut self, cmd: ShellCmd) -> bool {
774        let ShellCmd::Key(key) = cmd;
775        match self.mode {
776            ShellMode::Normal => self.handle_normal(key),
777            ShellMode::ModelList => self.handle_model_list(key),
778            ShellMode::Settings => self.handle_settings(key),
779            ShellMode::StartMenu { selected } => self.handle_start_menu(key, selected),
780            ShellMode::CloneFlow(_) => self.handle_clone_flow(key),
781            ShellMode::GitOpInProgress { .. } => self.handle_git_op_progress(key),
782        }
783    }
784
785    fn tick(&mut self, _delta_ms: u64) -> bool {
786        let mut redraw = false;
787        let mut dead: Vec<usize> = Vec::new();
788        for (i, win) in self.windows.iter_mut().enumerate() {
789            let (got_data, is_dead) = win.drain();
790            if got_data && i == self.active {
791                redraw = true;
792            }
793            if is_dead {
794                dead.push(i);
795            }
796        }
797        // Remove dead windows in reverse order so earlier indices stay valid.
798        for i in dead.into_iter().rev() {
799            self.windows.remove(i);
800            if !self.windows.is_empty() && self.active >= self.windows.len() {
801                self.active = self.windows.len() - 1;
802            }
803            redraw = true;
804        }
805
806        // Drain model status updates from background load-polling threads.
807        while let Ok((model_ref, loaded)) = self.status_rx.try_recv() {
808            for entry in self.model_list.items_mut() {
809                if entry.model_ref == model_ref {
810                    entry.loaded = loaded;
811                }
812            }
813            if self
814                .load_status
815                .as_ref()
816                .is_some_and(|s| s.contains(&model_ref))
817            {
818                self.load_status = None;
819            }
820            redraw = true;
821        }
822
823        // Drain git operation progress updates.
824        while let Ok(progress) = self.git_progress_rx.try_recv() {
825            match progress {
826                GitOpProgress::CloneProgress { stage, pct } => {
827                    if let ShellMode::CloneFlow(CloneScreen::Cloning {
828                        ref mut progress_msg,
829                        ref mut progress_pct,
830                        ..
831                    }) = self.mode
832                    {
833                        *progress_msg = stage;
834                        *progress_pct = pct;
835                    }
836                }
837                GitOpProgress::Status(msg) => {
838                    if let ShellMode::GitOpInProgress {
839                        ref mut progress_msg,
840                        ..
841                    } = self.mode
842                    {
843                        *progress_msg = msg;
844                    }
845                }
846                GitOpProgress::Done { message, new_model } => {
847                    if let Some(entry) = new_model {
848                        self.model_list.items_mut().push(entry);
849                        self.model_list
850                            .items_mut()
851                            .sort_by(|a, b| a.model_ref.cmp(&b.model_ref));
852                    }
853                    match self.mode {
854                        ShellMode::CloneFlow(_) => {
855                            self.mode = ShellMode::CloneFlow(CloneScreen::Done(message));
856                        }
857                        ShellMode::GitOpInProgress { .. } => {
858                            self.mode = ShellMode::GitOpInProgress {
859                                op_name: String::new(),
860                                model_ref: String::new(),
861                                progress_msg: format!("Done: {message}"),
862                            };
863                        }
864                        _ => {}
865                    }
866                }
867                GitOpProgress::Failed(msg) => match self.mode {
868                    ShellMode::CloneFlow(_) => {
869                        self.mode = ShellMode::CloneFlow(CloneScreen::Failed(msg));
870                    }
871                    ShellMode::GitOpInProgress { .. } => {
872                        self.mode = ShellMode::GitOpInProgress {
873                            op_name: String::new(),
874                            model_ref: String::new(),
875                            progress_msg: format!("Error: {msg}"),
876                        };
877                    }
878                    _ => {}
879                },
880                GitOpProgress::ModelList(models) => {
881                    self.merge_model_list(models);
882                    // Refresh git status for any newly-appeared models.
883                    self.fetch_git_status();
884                }
885            }
886            redraw = true;
887        }
888
889        // Drain git status fetch results.
890        while let Ok((model_ref, ahead, behind, dirty)) = self.git_status_rx.try_recv() {
891            for entry in self.model_list.items_mut() {
892                if entry.model_ref == model_ref {
893                    entry.ahead = ahead;
894                    entry.behind = behind;
895                    entry.is_dirty = dirty;
896                }
897            }
898            redraw = true;
899        }
900
901        // Tick background animation when it is visible.
902        let show_bg = self.windows.is_empty() || matches!(self.mode, ShellMode::Settings);
903        if show_bg {
904            self.bg.tick(self.cols, self.pane_rows());
905            if self.bg.is_animated() {
906                redraw = true;
907            }
908            // Also tick the settings preview at its fixed small dimensions.
909            if matches!(self.mode, ShellMode::Settings) {
910                self.preview_bg.tick(PREVIEW_W, PREVIEW_H);
911            }
912        }
913
914        redraw
915    }
916
917    fn should_quit(&self) -> bool {
918        self.quit
919    }
920}
921
922// Re-export from compositor (canonical implementation).
923pub use hyprstream_compositor::keypress_to_bytes;
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928
929    fn entry(model_ref: &str, loaded: bool, ahead: u32, behind: u32, dirty: bool) -> ModelEntry {
930        ModelEntry {
931            model_ref: model_ref.to_owned(),
932            path: PathBuf::from("/tmp").join(model_ref),
933            loaded,
934            ahead,
935            behind,
936            is_dirty: dirty,
937        }
938    }
939
940    #[test]
941    fn merge_adds_new_models_and_preserves_git_status() {
942        // Existing entry carries out-of-band git status (ahead/behind/dirty).
943        let existing = vec![entry("a:main", true, 2, 1, true)];
944        // Authoritative refresh: same model (loaded flipped) plus a freshly-cloned one.
945        let incoming = vec![
946            entry("a:main", false, 0, 0, false),
947            entry("b:main", false, 0, 0, false),
948        ];
949        let (merged, idx) = merge_models(&existing, incoming, Some("a:main"));
950
951        assert_eq!(merged.len(), 2, "newly-cloned b:main appears");
952        let a = &merged[0];
953        assert_eq!(a.model_ref, "a:main");
954        // loaded comes from the authoritative list...
955        assert!(!a.loaded);
956        // ...but git status is carried over from the existing entry.
957        assert_eq!((a.ahead, a.behind, a.is_dirty), (2, 1, true));
958        // new model has no carried-over status.
959        assert_eq!(
960            (merged[1].ahead, merged[1].behind, merged[1].is_dirty),
961            (0, 0, false)
962        );
963        // selection stays on a:main.
964        assert_eq!(idx, 0);
965    }
966
967    #[test]
968    fn merge_drops_removed_models_and_keeps_selection() {
969        let existing = vec![
970            entry("a:main", false, 0, 0, false),
971            entry("b:main", false, 0, 0, false),
972        ];
973        // b was removed upstream; only a remains. Selection was on b.
974        let incoming = vec![entry("a:main", false, 0, 0, false)];
975        let (merged, idx) = merge_models(&existing, incoming, Some("b:main"));
976        assert_eq!(merged.len(), 1);
977        assert_eq!(merged[0].model_ref, "a:main");
978        // selection target gone → fall back to 0.
979        assert_eq!(idx, 0);
980    }
981
982    #[test]
983    fn merge_keeps_selection_on_moved_index() {
984        let existing = vec![entry("b:main", false, 0, 0, false)];
985        // Refresh returns sorted list; previously-selected b is now at index 1.
986        let incoming = vec![
987            entry("a:main", false, 0, 0, false),
988            entry("b:main", false, 0, 0, false),
989        ];
990        let (merged, idx) = merge_models(&existing, incoming, Some("b:main"));
991        assert_eq!(idx, 1, "selection follows the model to its new index");
992        assert_eq!(merged[idx].model_ref, "b:main");
993    }
994}