Skip to main content

hyprstream_compositor/
chrome.rs

1//! Shell chrome state machine — pure, no I/O, WASM-safe.
2//!
3//! `ShellChrome` holds all the TUI chrome state: mode, window list, model
4//! list, background animation, and settings.  `handle_key` returns
5//! `Vec<ChromeOutput>` describing what the event loop should do — no ZMQ,
6//! no tokio, no side-effects.
7
8use std::path::PathBuf;
9
10use waxterm::input::KeyPress;
11use waxterm::widgets::{SelectList, WidgetResult};
12
13// ============================================================================
14// Toast notification types
15// ============================================================================
16
17#[derive(Clone, Copy, Debug)]
18pub enum ToastLevel {
19    Info,
20    Warn,
21    Error,
22}
23
24pub struct Toast {
25    pub message: String,
26    pub level: ToastLevel,
27    born: std::time::Instant,
28    ttl: std::time::Duration,
29}
30
31/// Bit-31 marks client-local IDs (windows/panes not on the server).
32pub const LOCAL_ID_BIT: u32 = 0x8000_0000;
33
34/// Returns true if the ID is client-local (bit 31 set).
35pub fn is_local_id(id: u32) -> bool {
36    id & LOCAL_ID_BIT != 0
37}
38
39use crate::background::{BackgroundState, BackgroundStyle, ALL_STYLES, PREVIEW_H, PREVIEW_W};
40
41// ============================================================================
42// Public types re-used by consumers
43// ============================================================================
44
45/// One row in the Service Manager modal.
46#[derive(Clone, Debug)]
47pub struct ServiceEntry {
48    pub name: String,
49    pub active: bool,
50    pub mode: ServiceMode,
51    pub pid: Option<u32>,
52}
53
54/// One row in the Images tab of the Worker Manager.
55#[derive(Clone, Debug)]
56pub struct ImageEntry {
57    pub repo_tag: String,
58    pub id: String,
59    pub size_bytes: u64,
60    pub created: String,
61}
62
63/// Tab within the Worker Manager modal.
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub enum WorkerTab {
66    Sandboxes,
67    Images,
68}
69
70/// Input dialog for text entry (pull image, create sandbox, create container).
71#[derive(Debug)]
72pub struct InputDialog {
73    pub title: &'static str,
74    pub fields: Vec<InputField>,
75    pub focused: usize,
76}
77
78/// One field in an InputDialog.
79#[derive(Debug)]
80pub struct InputField {
81    pub label: &'static str,
82    pub buf: Vec<u8>,
83    pub cursor: usize,
84    /// If Some, field cycles through these choices instead of free text.
85    pub choices: Option<Vec<String>>,
86    pub choice_idx: usize,
87    /// If true, field is a boolean toggle.
88    pub is_toggle: bool,
89    pub toggle_val: bool,
90}
91
92impl InputField {
93    pub fn text(label: &'static str) -> Self {
94        Self {
95            label,
96            buf: Vec::new(),
97            cursor: 0,
98            choices: None,
99            choice_idx: 0,
100            is_toggle: false,
101            toggle_val: false,
102        }
103    }
104    pub fn text_with_default(label: &'static str, default: &str) -> Self {
105        let buf = default.as_bytes().to_vec();
106        let cursor = buf.len();
107        Self {
108            label,
109            buf,
110            cursor,
111            choices: None,
112            choice_idx: 0,
113            is_toggle: false,
114            toggle_val: false,
115        }
116    }
117    pub fn toggle(label: &'static str) -> Self {
118        Self {
119            label,
120            buf: Vec::new(),
121            cursor: 0,
122            choices: None,
123            choice_idx: 0,
124            is_toggle: true,
125            toggle_val: false,
126        }
127    }
128    pub fn choices(label: &'static str, options: Vec<String>) -> Self {
129        Self {
130            label,
131            buf: Vec::new(),
132            cursor: 0,
133            choices: Some(options),
134            choice_idx: 0,
135            is_toggle: false,
136            toggle_val: false,
137        }
138    }
139    pub fn value(&self) -> String {
140        if self.is_toggle {
141            if self.toggle_val {
142                "true".to_owned()
143            } else {
144                "false".to_owned()
145            }
146        } else if let Some(ref opts) = self.choices {
147            opts.get(self.choice_idx).cloned().unwrap_or_default()
148        } else {
149            String::from_utf8_lossy(&self.buf).to_string()
150        }
151    }
152}
153
154impl InputDialog {
155    pub fn focused_field(&mut self) -> Option<&mut InputField> {
156        self.fields.get_mut(self.focused)
157    }
158}
159
160#[derive(Clone, Debug, PartialEq)]
161pub enum ServiceMode {
162    Systemd,
163    Daemon,
164    Both,
165    Stopped,
166}
167
168/// One sandbox row in the Worker Manager modal.
169#[derive(Clone, Debug)]
170pub struct WorkerEntry {
171    pub id: String,
172    pub full_id: String,
173    pub state: String,
174    pub backend: String,
175    pub cpu_pct: Option<u32>,
176    pub mem_mb: Option<u64>,
177    pub containers: Vec<ContainerEntry>,
178}
179
180#[derive(Clone, Debug)]
181pub struct ContainerEntry {
182    pub id: String,
183    pub full_id: String,
184    pub image: String,
185    pub state: String,
186    pub cpu_pct: Option<u32>,
187    pub mem_mb: Option<u64>,
188}
189
190/// Generation parameter defaults from the model's generation_config.json,
191/// served via the model status RPC. All fields are Option — None means
192/// "model has no opinion, use server default."
193/// Adjusting a None field via the settings UI promotes it to Some.
194#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
195pub struct GenerationDefaults {
196    pub temperature: Option<f32>,
197    pub top_p: Option<f32>,
198    pub top_k: Option<usize>,
199    pub max_tokens: Option<usize>,
200    pub context_window: Option<usize>,
201}
202
203impl GenerationDefaults {
204    /// Number of user-adjustable fields in the pre-chat settings modal.
205    /// Must match the fields array in render.rs and the match arms in apply_gen_field_delta.
206    pub const NUM_FIELDS: usize = 5;
207}
208
209#[derive(Clone, Debug)]
210pub struct ModelEntry {
211    pub model_ref: String,
212    pub path: PathBuf,
213    pub loaded: bool,
214    pub loading: bool,
215    pub gen_defaults: GenerationDefaults,
216}
217
218impl std::fmt::Display for ModelEntry {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        if self.loading {
221            write!(f, "{} [loading\u{2026}]", self.model_ref)
222        } else if self.loaded {
223            write!(f, "{} [loaded]", self.model_ref)
224        } else {
225            write!(f, "{}", self.model_ref)
226        }
227    }
228}
229
230/// Lightweight window descriptor from TuiService.
231#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
232pub struct WindowSummary {
233    pub id: u32,
234    pub name: String,
235    pub active_pane_id: u32,
236    pub panes: Vec<PaneSummary>,
237}
238
239/// Lightweight pane descriptor.
240#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
241pub struct PaneSummary {
242    pub id: u32,
243    pub cols: u16,
244    pub rows: u16,
245    pub is_private: bool,
246}
247
248// ============================================================================
249// ShellMode
250// ============================================================================
251
252/// What kind of conversation picker entry this is.
253#[derive(Clone, Debug, PartialEq, Eq)]
254pub enum ConversationKind {
255    /// Create a new private (client-owned, encrypted) conversation.
256    NewPrivate,
257    /// Create a new server-side conversation.
258    NewServer,
259    /// Resume an existing conversation by UUID.
260    Resume { uuid: String },
261}
262
263/// Entry in the conversation picker.
264#[derive(Clone, Debug)]
265pub struct ConversationPickerEntry {
266    pub kind: ConversationKind,
267    pub label: String,
268    pub last_active: u64,
269}
270
271impl std::fmt::Display for ConversationPickerEntry {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        write!(f, "{}", self.label)
274    }
275}
276
277pub enum ShellMode {
278    /// Keys forwarded to the active shell via SendInput RPC.
279    Normal,
280    /// Model-list modal is open.
281    ModelList,
282    /// Settings modal is open.
283    Settings,
284    /// Start-menu popup (Ctrl+Space).
285    StartMenu { selected: usize },
286    /// Console log overlay (F9).
287    Console,
288    /// Fullscreen — all chrome hidden, pane fills terminal.
289    Fullscreen,
290    /// Conversation picker for a specific model.
291    ConversationPicker {
292        model_ref: String,
293        list: waxterm::widgets::SelectList<ConversationPickerEntry>,
294    },
295    /// Service Manager modal (F5).
296    ServiceManager { selected: usize },
297    /// Worker / Sandbox Manager modal (F6).
298    WorkerManager {
299        sandbox_sel: usize,
300        container_sel: usize,
301        show_containers: bool,
302        tab: WorkerTab,
303        image_sel: usize,
304        input_mode: Option<InputDialog>,
305    },
306    /// Pre-chat generation settings before starting a new conversation.
307    PreChatSettings(Box<PreChatSettingsState>),
308    /// Clone flow: multi-step clone wizard.
309    CloneFlow(CloneScreen),
310    /// Git operation in progress (pull/push).
311    GitOpInProgress {
312        op_name: String,
313        model_ref: String,
314        progress_msg: String,
315    },
316}
317
318/// Clone flow screens for the model dialog.
319pub enum CloneScreen {
320    EnterUrl(waxterm::widgets::TextInput),
321    EnterName(waxterm::widgets::TextInput, String),
322    Cloning {
323        name: String,
324        progress_msg: String,
325        progress_pct: u8,
326    },
327    Done(String),
328    Failed(String),
329}
330
331/// State for the pre-chat settings modal.
332pub struct PreChatSettingsState {
333    pub model_ref: String,
334    pub defaults: GenerationDefaults,
335    pub form: waxterm::widgets::SettingsForm,
336    pub chat_type: PreChatType,
337}
338
339/// Build a SettingsForm from GenerationDefaults.
340pub fn build_settings_form(defaults: &GenerationDefaults) -> waxterm::widgets::SettingsForm {
341    use waxterm::widgets::NumericField;
342    waxterm::widgets::SettingsForm::new(vec![
343        NumericField::new("Max Tokens")
344            .integer()
345            .range(64.0, 32768.0)
346            .step(64.0)
347            .value(defaults.max_tokens.map(|v| v as f64))
348            .none_label("default"),
349        NumericField::new("Temperature")
350            .float(2)
351            .range(0.0, 2.0)
352            .step(0.05)
353            .value(defaults.temperature.map(|v| v as f64))
354            .none_label("default"),
355        NumericField::new("Top-P")
356            .float(2)
357            .range(0.05, 1.0)
358            .step(0.05)
359            .value(defaults.top_p.map(|v| v as f64))
360            .none_label("default"),
361        NumericField::new("Top-K")
362            .integer()
363            .range(1.0, 200.0)
364            .step(1.0)
365            .value(defaults.top_k.map(|v| v as f64))
366            .none_label("off"),
367        NumericField::new("Context Window")
368            .integer()
369            .range(512.0, 131072.0)
370            .step(512.0)
371            .value(defaults.context_window.map(|v| v as f64))
372            .none_label("model default"),
373    ])
374}
375
376/// Extract GenerationDefaults from a SettingsForm's current values.
377pub fn form_to_generation_defaults(form: &waxterm::widgets::SettingsForm) -> GenerationDefaults {
378    let vals = form.values();
379    GenerationDefaults {
380        max_tokens: vals.first().copied().flatten().map(|v| v as usize),
381        temperature: vals.get(1).copied().flatten().map(|v| v as f32),
382        top_p: vals.get(2).copied().flatten().map(|v| v as f32),
383        top_k: vals.get(3).copied().flatten().map(|v| v as usize),
384        context_window: vals.get(4).copied().flatten().map(|v| v as usize),
385    }
386}
387
388/// Whether the new conversation is private or server-side.
389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
390pub enum PreChatType {
391    Private,
392    Server,
393}
394
395/// Menu items: (label, chord hint shown in popup).
396#[cfg(feature = "experimental")]
397pub const MENU_ITEMS: &[(&str, &str)] = &[
398    ("New", "N"),
399    ("Close", "Q"),
400    ("Cycle", "Tab"),
401    ("Models", "M"),
402    ("Log", "L"),
403    ("Workers", "W"),
404    ("Services", "V"),
405    ("Settings", "S"),
406    ("Fullscreen", "F"),
407    ("Disconnect", "D"),
408];
409
410/// Menu items: (label, chord hint shown in popup).
411#[cfg(not(feature = "experimental"))]
412pub const MENU_ITEMS: &[(&str, &str)] = &[
413    ("New", "N"),
414    ("Close", "Q"),
415    ("Cycle", "Tab"),
416    ("Models", "M"),
417    ("Log", "L"),
418    ("Workers", "W"),
419    ("Settings", "S"),
420    ("Fullscreen", "F"),
421    ("Disconnect", "D"),
422];
423
424// ============================================================================
425// RPC requests emitted by the chrome
426// ============================================================================
427
428/// Pure typed enum — no ZMQ types, no capnp types, WASM-safe.
429#[derive(Debug, serde::Serialize)]
430#[serde(tag = "type", rename_all = "snake_case")]
431pub enum RpcRequest {
432    SendInput {
433        viewer_id: u32,
434        data: Vec<u8>,
435    },
436    CreateWindow {
437        session_id: u32,
438    },
439    CloseWindow {
440        session_id: u32,
441        window_id: u32,
442    },
443    FocusWindow {
444        session_id: u32,
445        window_id: u32,
446    },
447    SpawnShell {
448        session_id: u32,
449        pane_id: u32,
450        cwd: String,
451    },
452    LoadModel {
453        model_ref: String,
454    },
455    UnloadModel {
456        model_ref: String,
457    },
458    SpawnServerChat {
459        session_id: u32,
460        model_ref: String,
461        cols: u16,
462        rows: u16,
463        pane_id: u32,
464        gen_defaults: Option<GenerationDefaults>,
465    },
466    /// Client-local private chat — no server round-trip required.
467    /// If `resume_uuid` is Some, resumes an existing conversation.
468    LocalPrivateChat {
469        model_ref: String,
470        cols: u16,
471        rows: u16,
472        resume_uuid: Option<String>,
473        gen_defaults: Option<GenerationDefaults>,
474    },
475    /// Delete a private conversation (UUID as string).
476    DeleteConversation {
477        uuid: String,
478        model_ref: String,
479    },
480    /// Request the conversation list for a model (shell handler populates it).
481    ListConversations {
482        model_ref: String,
483    },
484    ServiceStart {
485        name: String,
486    },
487    ServiceStop {
488        name: String,
489    },
490    ServiceRestart {
491        name: String,
492    },
493    ServiceInstall,
494    ServiceStopAll,
495    ServiceStartAll,
496    WorkerDestroySandbox {
497        sandbox_id: String,
498    },
499    WorkerExecSync {
500        sandbox_id: String,
501        container_id: String,
502        cmd: Vec<String>,
503    },
504    WorkerImageList,
505    WorkerImagePull {
506        image: String,
507    },
508    WorkerImageRemove {
509        image: String,
510    },
511    WorkerCreateSandbox {
512        hostname: String,
513        backend: String,
514        gpu: bool,
515    },
516    WorkerCreateContainer {
517        sandbox_id: String,
518        image: String,
519        cmd: Vec<String>,
520        tty: bool,
521    },
522    WorkerStartContainer {
523        container_id: String,
524    },
525    WorkerStopContainer {
526        container_id: String,
527    },
528    WorkerRemoveContainer {
529        container_id: String,
530    },
531    AttachContainer {
532        sandbox_id: String,
533        container_id: String,
534        cols: u16,
535        rows: u16,
536    },
537    CloneModel {
538        url: String,
539        name: String,
540    },
541    PullModel {
542        model_ref: String,
543    },
544    PushModel {
545        model_ref: String,
546    },
547    FetchModelStatus,
548    Quit,
549}
550
551/// Output from `ShellChrome::handle_key`.
552pub enum ChromeOutput {
553    Redraw,
554    Rpc(RpcRequest),
555    /// Key bytes that should be routed to a client-owned ChatApp task.
556    RouteInput {
557        app_id: u32,
558        data: Vec<u8>,
559    },
560}
561
562// ============================================================================
563// ShellChrome
564// ============================================================================
565
566pub struct ShellChrome {
567    pub mode: ShellMode,
568    pub windows: Vec<WindowSummary>,
569    pub active_win: usize,
570    pub model_list: SelectList<ModelEntry>,
571    /// Background animation (full terminal area).
572    pub bg: BackgroundState,
573    /// Background animation for the settings preview box.
574    pub preview_bg: BackgroundState,
575    /// Settings drop-down.
576    pub settings_list: SelectList<BackgroundStyle>,
577    /// Saved background style — restored when settings is cancelled.
578    saved_style: BackgroundStyle,
579    /// pane IDs that are private (client-owned ChatApp); used for 🔒 indicator.
580    pub private_panes: std::collections::HashSet<u32>,
581    pub cols: u16,
582    pub pane_rows: u16,
583    pub session_id: u32,
584    pub viewer_id: u32,
585    /// Active toast notifications.
586    pub toasts: std::collections::VecDeque<Toast>,
587    /// Console log history (capped at 500 lines).
588    pub console_log: std::collections::VecDeque<String>,
589    /// Scroll offset for console modal.
590    pub console_scroll: usize,
591    /// Service entries for the Service Manager modal.
592    pub service_list: Vec<ServiceEntry>,
593    /// Worker/sandbox entries for the Worker Manager modal.
594    pub worker_list: Vec<WorkerEntry>,
595    /// Pool summary line for the Worker Manager modal.
596    pub worker_pool_summary: String,
597    /// Image list for the Images tab.
598    pub image_list: Vec<ImageEntry>,
599    /// Model ref waiting for load to complete before opening conversation picker.
600    pub pending_picker_model: Option<String>,
601}
602
603impl ShellChrome {
604    pub fn new(
605        cols: u16,
606        pane_rows: u16,
607        session_id: u32,
608        viewer_id: u32,
609        windows: Vec<WindowSummary>,
610        models: Vec<ModelEntry>,
611    ) -> Self {
612        let model_list = SelectList::new("Models", models);
613        let default_style = BackgroundStyle::Stars;
614        let settings_list = SelectList::new("Background", ALL_STYLES.to_vec()).with_selected(1); // Stars is index 1
615
616        let mut bg = BackgroundState::new(default_style);
617        bg.tick(cols, pane_rows);
618
619        Self {
620            mode: ShellMode::Normal,
621            windows,
622            active_win: 0,
623            model_list,
624            bg,
625            preview_bg: BackgroundState::new(default_style),
626            settings_list,
627            saved_style: default_style,
628            private_panes: std::collections::HashSet::new(),
629            cols,
630            pane_rows,
631            session_id,
632            viewer_id,
633            toasts: std::collections::VecDeque::new(),
634            console_log: std::collections::VecDeque::new(),
635            console_scroll: 0,
636            service_list: Vec::new(),
637            worker_list: Vec::new(),
638            worker_pool_summary: String::new(),
639            image_list: Vec::new(),
640            pending_picker_model: None,
641        }
642    }
643
644    /// Update model loaded status (called from background polling results).
645    /// Returns a follow-up RPC if a conversation picker was pending for this model.
646    pub fn update_model_status(&mut self, model_ref: &str, loaded: bool) -> Option<RpcRequest> {
647        let mut was_loading = false;
648        for entry in self.model_list.items_mut() {
649            if entry.model_ref == model_ref {
650                was_loading = was_loading || entry.loading;
651                entry.loaded = loaded;
652                entry.loading = false;
653            }
654        }
655        if was_loading && loaded {
656            self.push_toast(format!("Loaded {model_ref}"), ToastLevel::Info);
657        }
658        // Check if a conversation picker was waiting for this model.
659        if let Some(ref pending) = self.pending_picker_model {
660            if pending == model_ref {
661                if loaded {
662                    // Only auto-open picker if user is still in a relevant context.
663                    if matches!(self.mode, ShellMode::ModelList | ShellMode::Normal) {
664                        let mr = pending.clone();
665                        self.pending_picker_model = None;
666                        return Some(RpcRequest::ListConversations { model_ref: mr });
667                    }
668                    // User navigated to another modal — leave pending for later.
669                } else {
670                    // Load failed — clear pending.
671                    self.pending_picker_model = None;
672                }
673            }
674        }
675        None
676    }
677
678    /// Update window list (called when TuiService reports window changes).
679    /// Merges server windows with existing client-local windows (bit-31 set).
680    pub fn update_windows(&mut self, server_wins: Vec<WindowSummary>) -> bool {
681        // Preserve client-local windows (bit-31 set).
682        let local_wins: Vec<WindowSummary> = self
683            .windows
684            .drain(..)
685            .filter(|w| is_local_id(w.id))
686            .collect();
687
688        // Sync private_panes: combine server-reported + locally-tracked.
689        let mut new_private: std::collections::HashSet<u32> = server_wins
690            .iter()
691            .flat_map(|w| w.panes.iter())
692            .filter(|p| p.is_private)
693            .map(|p| p.id)
694            .collect();
695        for w in &local_wins {
696            for p in &w.panes {
697                if p.is_private {
698                    new_private.insert(p.id);
699                }
700            }
701        }
702        let private_changed = new_private != self.private_panes;
703        self.private_panes = new_private;
704
705        // Merge: server windows first, then local windows.
706        let mut merged = server_wins;
707        merged.extend(local_wins);
708
709        let changed = merged.len() != self.windows.len()
710            || merged
711                .iter()
712                .zip(&self.windows)
713                .any(|(a, b)| a.id != b.id || a.panes.len() != b.panes.len());
714        if changed || private_changed {
715            self.active_win = self.active_win.min(merged.len().saturating_sub(1));
716            self.windows = merged;
717        }
718        changed || private_changed
719    }
720
721    /// Active pane ID in the currently focused window.
722    /// Prefers a locally-owned private pane over the server-managed active pane,
723    /// since the server intentionally keeps the non-private pane as active_pane_id
724    /// to avoid publishing private content to viewers.
725    pub fn active_pane_id(&self) -> u32 {
726        let Some(win) = self.windows.get(self.active_win) else {
727            return 0;
728        };
729        if let Some(p) = win
730            .panes
731            .iter()
732            .find(|p| self.private_panes.contains(&p.id))
733        {
734            return p.id;
735        }
736        win.active_pane_id
737    }
738
739    /// Tick background animations. Returns true if animated (needs redraw).
740    pub fn tick_bg(&mut self) -> bool {
741        let show_bg = self.windows.is_empty() || matches!(self.mode, ShellMode::Settings);
742        if show_bg {
743            self.bg.tick(self.cols, self.pane_rows);
744        }
745        if matches!(self.mode, ShellMode::Settings) {
746            self.preview_bg.tick(PREVIEW_W, PREVIEW_H);
747        }
748        show_bg && self.bg.is_animated()
749    }
750
751    /// Push a toast notification. Also persists the message to console_log.
752    pub fn push_toast(&mut self, msg: impl Into<String>, level: ToastLevel) {
753        let message: String = msg.into();
754        self.log_line(message.clone());
755        let ttl = match level {
756            ToastLevel::Error => std::time::Duration::from_secs(5),
757            ToastLevel::Warn => std::time::Duration::from_secs(4),
758            ToastLevel::Info => std::time::Duration::from_secs(2),
759        };
760        self.toasts.push_back(Toast {
761            message,
762            level,
763            born: std::time::Instant::now(),
764            ttl,
765        });
766        if self.toasts.len() > 5 {
767            self.toasts.pop_front();
768        }
769    }
770
771    /// Expire stale toasts. Returns true if any expired (caller should redraw).
772    pub fn tick_toasts(&mut self) -> bool {
773        let before = self.toasts.len();
774        self.toasts.retain(|t| t.born.elapsed() < t.ttl);
775        self.toasts.len() != before
776    }
777
778    /// Append a line to the console log (capped at 500 entries).
779    pub fn log_line(&mut self, line: impl Into<String>) {
780        self.console_log.push_back(line.into());
781        if self.console_log.len() > 500 {
782            self.console_log.pop_front();
783        }
784    }
785
786    pub fn update_service_list(&mut self, entries: Vec<ServiceEntry>) {
787        self.service_list = entries;
788    }
789
790    pub fn update_worker_list(&mut self, sandboxes: Vec<WorkerEntry>, pool_summary: String) {
791        self.worker_list = sandboxes;
792        self.worker_pool_summary = pool_summary;
793    }
794
795    // =========================================================================
796    // Key dispatch
797    // =========================================================================
798
799    pub fn handle_key(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
800        match self.mode {
801            ShellMode::Normal => self.handle_normal(key),
802            ShellMode::Fullscreen => self.handle_fullscreen(key),
803            ShellMode::ModelList => self.handle_model_list(key),
804            ShellMode::Settings => self.handle_settings(key),
805            ShellMode::StartMenu { selected } => self.handle_start_menu(key, selected),
806            ShellMode::Console => self.handle_console(key),
807            ShellMode::ConversationPicker { .. } => self.handle_conversation_picker(key),
808            ShellMode::ServiceManager { selected } => self.handle_service_manager(key, selected),
809            ShellMode::WorkerManager {
810                sandbox_sel,
811                container_sel,
812                show_containers,
813                tab,
814                image_sel,
815                ref mut input_mode,
816            } => {
817                // Input dialog intercepts all keys when active.
818                if input_mode.is_some() {
819                    return self.handle_input_dialog(key);
820                }
821                self.handle_worker_manager(
822                    key,
823                    sandbox_sel,
824                    container_sel,
825                    show_containers,
826                    tab,
827                    image_sel,
828                )
829            }
830            ShellMode::PreChatSettings(_) => self.handle_pre_chat_settings(key),
831            ShellMode::CloneFlow(_) => self.handle_clone_flow(key),
832            ShellMode::GitOpInProgress { .. } => self.handle_git_op(key),
833        }
834    }
835
836    // ── Normal mode ──────────────────────────────────────────────────────────
837
838    fn handle_normal(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
839        match key {
840            KeyPress::CtrlSpace => {
841                self.mode = ShellMode::StartMenu { selected: 0 };
842                vec![ChromeOutput::Redraw]
843            }
844            KeyPress::Char(0x06) => {
845                // Ctrl-F — toggle fullscreen (hide all chrome).
846                self.mode = ShellMode::Fullscreen;
847                vec![ChromeOutput::Redraw]
848            }
849            KeyPress::Char(0x02) => {
850                // Ctrl-B — handled at event loop level; chrome does nothing.
851                vec![]
852            }
853            key => {
854                let bytes = keypress_to_bytes(key);
855                if bytes.is_empty() {
856                    vec![]
857                } else {
858                    let active = self.active_pane_id();
859                    if self.private_panes.contains(&active) {
860                        // Route to client-owned ChatApp task instead of server
861                        vec![ChromeOutput::RouteInput {
862                            app_id: active,
863                            data: bytes,
864                        }]
865                    } else {
866                        let vid = self.viewer_id;
867                        vec![ChromeOutput::Rpc(RpcRequest::SendInput {
868                            viewer_id: vid,
869                            data: bytes,
870                        })]
871                    }
872                }
873            }
874        }
875    }
876
877    // ── ModelList mode ───────────────────────────────────────────────────────
878
879    fn handle_model_list(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
880        // c — clone
881        if matches!(key, KeyPress::Char(b'c')) {
882            self.mode = ShellMode::CloneFlow(CloneScreen::EnterUrl(
883                waxterm::widgets::TextInput::new("Repository URL:"),
884            ));
885            return vec![ChromeOutput::Redraw];
886        }
887        // p — pull
888        if matches!(key, KeyPress::Char(b'p')) {
889            if let Some(model) = self.model_list.selected_item().cloned() {
890                self.mode = ShellMode::GitOpInProgress {
891                    op_name: "Pull".to_owned(),
892                    model_ref: model.model_ref.clone(),
893                    progress_msg: "Fetching…".to_owned(),
894                };
895                return vec![
896                    ChromeOutput::Rpc(RpcRequest::PullModel {
897                        model_ref: model.model_ref,
898                    }),
899                    ChromeOutput::Redraw,
900                ];
901            }
902        }
903        // P — push
904        if matches!(key, KeyPress::Char(b'P')) {
905            if let Some(model) = self.model_list.selected_item().cloned() {
906                self.mode = ShellMode::GitOpInProgress {
907                    op_name: "Push".to_owned(),
908                    model_ref: model.model_ref.clone(),
909                    progress_msg: "Pushing…".to_owned(),
910                };
911                return vec![
912                    ChromeOutput::Rpc(RpcRequest::PushModel {
913                        model_ref: model.model_ref,
914                    }),
915                    ChromeOutput::Redraw,
916                ];
917            }
918        }
919        // l — submit load request (power-user preload, no pending picker)
920        if matches!(key, KeyPress::Char(b'l' | b'L')) {
921            if let Some(model) = self.model_list.selected_item().cloned() {
922                let model_ref = model.model_ref.clone();
923                self.push_toast(format!("Loading {model_ref}\u{2026}"), ToastLevel::Info);
924                for entry in self.model_list.items_mut() {
925                    if entry.model_ref == model_ref {
926                        entry.loading = true;
927                    }
928                }
929                return vec![ChromeOutput::Rpc(RpcRequest::LoadModel { model_ref })];
930            }
931        }
932        // u — unload
933        if matches!(key, KeyPress::Char(b'u' | b'U')) {
934            if let Some(model) = self.model_list.selected_item().cloned() {
935                let model_ref = model.model_ref.clone();
936                return vec![ChromeOutput::Rpc(RpcRequest::UnloadModel { model_ref })];
937            }
938        }
939        // T — terminal in model worktree
940        if matches!(key, KeyPress::Char(b't' | b'T')) {
941            if let Some(model) = self.model_list.selected_item().cloned() {
942                let cwd = model.path.to_string_lossy().into_owned();
943                let sid = self.session_id;
944                self.mode = ShellMode::Normal;
945                return vec![ChromeOutput::Rpc(RpcRequest::SpawnShell {
946                    session_id: sid,
947                    pane_id: 0,
948                    cwd,
949                })];
950            }
951        }
952
953        match self.model_list.handle_key(&key) {
954            WidgetResult::Cancelled => {
955                self.pending_picker_model = None;
956                self.mode = ShellMode::Normal;
957                vec![ChromeOutput::Redraw]
958            }
959            WidgetResult::Confirmed(model) => self.enter_chat_for_model(&model),
960            WidgetResult::Pending => {
961                vec![ChromeOutput::Redraw]
962            }
963        }
964    }
965
966    /// Unified Enter handler: auto-load if needed, then open conversation picker.
967    fn enter_chat_for_model(&mut self, model: &ModelEntry) -> Vec<ChromeOutput> {
968        let model_ref = model.model_ref.clone();
969        if model.loaded {
970            // Model ready — open conversation picker immediately.
971            self.mode = ShellMode::Normal;
972            vec![ChromeOutput::Rpc(RpcRequest::ListConversations {
973                model_ref,
974            })]
975        } else if model.loading {
976            // Already loading — stash pending picker, stay in ModelList.
977            self.pending_picker_model = Some(model_ref.clone());
978            self.push_toast(
979                format!("Waiting for {model_ref} to load\u{2026}"),
980                ToastLevel::Info,
981            );
982            vec![ChromeOutput::Redraw]
983        } else {
984            // Not loaded — auto-load and stash pending picker.
985            self.pending_picker_model = Some(model_ref.clone());
986            self.push_toast(format!("Loading {model_ref}\u{2026}"), ToastLevel::Info);
987            for entry in self.model_list.items_mut() {
988                if entry.model_ref == model_ref {
989                    entry.loading = true;
990                }
991            }
992            vec![ChromeOutput::Rpc(RpcRequest::LoadModel { model_ref })]
993        }
994    }
995
996    // ── CloneFlow mode ────────────────────────────────────────────────────────
997
998    fn handle_clone_flow(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
999        let screen = match std::mem::replace(&mut self.mode, ShellMode::Normal) {
1000            ShellMode::CloneFlow(s) => s,
1001            other => {
1002                self.mode = other;
1003                return vec![];
1004            }
1005        };
1006        match screen {
1007            CloneScreen::EnterUrl(mut input) => {
1008                match input.handle_key(&key) {
1009                    WidgetResult::Confirmed(url) => {
1010                        self.mode = ShellMode::CloneFlow(CloneScreen::EnterName(
1011                            waxterm::widgets::TextInput::new("Local name (Enter for default):"),
1012                            url,
1013                        ));
1014                    }
1015                    WidgetResult::Cancelled => {
1016                        self.mode = ShellMode::ModelList;
1017                    }
1018                    WidgetResult::Pending => {
1019                        self.mode = ShellMode::CloneFlow(CloneScreen::EnterUrl(input));
1020                    }
1021                }
1022                vec![ChromeOutput::Redraw]
1023            }
1024            CloneScreen::EnterName(mut input, url) => match input.handle_key(&key) {
1025                WidgetResult::Confirmed(name) => {
1026                    let clone_name = if name.is_empty() {
1027                        url.rsplit('/')
1028                            .next()
1029                            .unwrap_or("model")
1030                            .trim_end_matches(".git")
1031                            .to_owned()
1032                    } else {
1033                        name
1034                    };
1035                    let display_name = clone_name.clone();
1036                    self.mode = ShellMode::CloneFlow(CloneScreen::Cloning {
1037                        name: display_name,
1038                        progress_msg: "Starting…".to_owned(),
1039                        progress_pct: 0,
1040                    });
1041                    vec![
1042                        ChromeOutput::Rpc(RpcRequest::CloneModel {
1043                            url,
1044                            name: clone_name,
1045                        }),
1046                        ChromeOutput::Redraw,
1047                    ]
1048                }
1049                WidgetResult::Cancelled => {
1050                    self.mode = ShellMode::ModelList;
1051                    vec![ChromeOutput::Redraw]
1052                }
1053                WidgetResult::Pending => {
1054                    self.mode = ShellMode::CloneFlow(CloneScreen::EnterName(input, url));
1055                    vec![ChromeOutput::Redraw]
1056                }
1057            },
1058            CloneScreen::Cloning {
1059                name,
1060                progress_msg,
1061                progress_pct,
1062            } => {
1063                // No key handling during clone — just put the screen back
1064                self.mode = ShellMode::CloneFlow(CloneScreen::Cloning {
1065                    name,
1066                    progress_msg,
1067                    progress_pct,
1068                });
1069                vec![]
1070            }
1071            CloneScreen::Done(_) | CloneScreen::Failed(_) => {
1072                if matches!(key, KeyPress::Enter | KeyPress::Escape) {
1073                    self.mode = ShellMode::ModelList;
1074                    vec![
1075                        ChromeOutput::Rpc(RpcRequest::FetchModelStatus),
1076                        ChromeOutput::Redraw,
1077                    ]
1078                } else {
1079                    self.mode = ShellMode::CloneFlow(screen);
1080                    vec![]
1081                }
1082            }
1083        }
1084    }
1085
1086    // ── GitOpInProgress mode ─────────────────────────────────────────────────
1087
1088    fn handle_git_op(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
1089        let is_terminal = match &self.mode {
1090            ShellMode::GitOpInProgress { progress_msg, .. } => {
1091                progress_msg.starts_with("Done:") || progress_msg.starts_with("Error:")
1092            }
1093            _ => false,
1094        };
1095        if is_terminal && matches!(key, KeyPress::Enter | KeyPress::Escape) {
1096            self.mode = ShellMode::ModelList;
1097            return vec![ChromeOutput::Redraw];
1098        }
1099        vec![]
1100    }
1101
1102    /// Update git operation progress from the service layer.
1103    pub fn update_git_op_progress(&mut self, msg: &str) {
1104        if let ShellMode::GitOpInProgress { progress_msg, .. } = &mut self.mode {
1105            *progress_msg = msg.to_owned();
1106        }
1107    }
1108
1109    /// Update clone progress from the service layer.
1110    pub fn update_clone_progress(&mut self, stage: &str, pct: u8) {
1111        if let ShellMode::CloneFlow(CloneScreen::Cloning {
1112            progress_msg,
1113            progress_pct,
1114            ..
1115        }) = &mut self.mode
1116        {
1117            *progress_msg = stage.to_owned();
1118            *progress_pct = pct;
1119        }
1120    }
1121
1122    /// Transition clone flow to done/failed.
1123    pub fn finish_clone(&mut self, success: bool, msg: String) {
1124        if matches!(self.mode, ShellMode::CloneFlow(CloneScreen::Cloning { .. })) {
1125            self.mode = if success {
1126                ShellMode::CloneFlow(CloneScreen::Done(msg))
1127            } else {
1128                ShellMode::CloneFlow(CloneScreen::Failed(msg))
1129            };
1130        }
1131    }
1132
1133    // ── StartMenu mode ───────────────────────────────────────────────────────
1134
1135    fn handle_start_menu(&mut self, key: KeyPress, selected: usize) -> Vec<ChromeOutput> {
1136        let n = MENU_ITEMS.len();
1137        let chord: Option<usize> = match key {
1138            KeyPress::Char(b'n' | b'N') => Some(0), // New
1139            KeyPress::Char(b'q' | b'Q') => Some(1), // Close
1140            KeyPress::Tab => Some(2),               // Cycle
1141            KeyPress::Char(b'm' | b'M') => Some(3), // Models
1142            KeyPress::Char(b'l' | b'L') => Some(4), // Log
1143            KeyPress::Char(b'w' | b'W') => Some(5), // Workers
1144            #[cfg(feature = "experimental")]
1145            KeyPress::Char(b'v' | b'V') => Some(6), // Services
1146            KeyPress::Char(b's' | b'S') => {
1147                #[cfg(feature = "experimental")]
1148                {
1149                    Some(7)
1150                }
1151                #[cfg(not(feature = "experimental"))]
1152                {
1153                    Some(6)
1154                }
1155            }
1156            KeyPress::Char(b'f' | b'F') => {
1157                #[cfg(feature = "experimental")]
1158                {
1159                    Some(8)
1160                }
1161                #[cfg(not(feature = "experimental"))]
1162                {
1163                    Some(7)
1164                }
1165            }
1166            KeyPress::Char(b'd' | b'D') => {
1167                #[cfg(feature = "experimental")]
1168                {
1169                    Some(9)
1170                }
1171                #[cfg(not(feature = "experimental"))]
1172                {
1173                    Some(8)
1174                }
1175            }
1176            _ => None,
1177        };
1178        if let Some(idx) = chord {
1179            self.mode = ShellMode::Normal;
1180            return self.execute_menu_action(idx);
1181        }
1182        match key {
1183            KeyPress::Escape | KeyPress::CtrlSpace => {
1184                self.mode = ShellMode::Normal;
1185            }
1186            KeyPress::ArrowUp => {
1187                self.mode = ShellMode::StartMenu {
1188                    selected: if selected == 0 { n - 1 } else { selected - 1 },
1189                };
1190            }
1191            KeyPress::ArrowDown => {
1192                self.mode = ShellMode::StartMenu {
1193                    selected: (selected + 1) % n,
1194                };
1195            }
1196            KeyPress::Enter => {
1197                self.mode = ShellMode::Normal;
1198                return self.execute_menu_action(selected);
1199            }
1200            _ => {}
1201        }
1202        vec![ChromeOutput::Redraw]
1203    }
1204
1205    pub(crate) fn execute_menu_action(&mut self, idx: usize) -> Vec<ChromeOutput> {
1206        let sid = self.session_id;
1207
1208        // Indices for items that shift when "Services" is present (experimental).
1209        #[cfg(feature = "experimental")]
1210        const SERVICES_IDX: usize = 6;
1211        #[cfg(feature = "experimental")]
1212        const SETTINGS_IDX: usize = 7;
1213        #[cfg(not(feature = "experimental"))]
1214        const SETTINGS_IDX: usize = 6;
1215        #[cfg(feature = "experimental")]
1216        const FULLSCREEN_IDX: usize = 8;
1217        #[cfg(not(feature = "experimental"))]
1218        const FULLSCREEN_IDX: usize = 7;
1219        #[cfg(feature = "experimental")]
1220        const DISCONNECT_IDX: usize = 9;
1221        #[cfg(not(feature = "experimental"))]
1222        const DISCONNECT_IDX: usize = 8;
1223
1224        match idx {
1225            0 => vec![ChromeOutput::Rpc(RpcRequest::CreateWindow {
1226                session_id: sid,
1227            })],
1228            1 => {
1229                if let Some(win) = self.windows.get(self.active_win) {
1230                    let wid = win.id;
1231                    vec![ChromeOutput::Rpc(RpcRequest::CloseWindow {
1232                        session_id: sid,
1233                        window_id: wid,
1234                    })]
1235                } else {
1236                    vec![]
1237                }
1238            }
1239            2 => {
1240                // Cycle windows — emit FocusWindow; active_win is updated in handle_rpc
1241                // after the RPC succeeds, so we don't diverge if the target was closed.
1242                if !self.windows.is_empty() {
1243                    let next = (self.active_win + 1) % self.windows.len();
1244                    if let Some(w) = self.windows.get(next) {
1245                        let wid = w.id;
1246                        return vec![ChromeOutput::Rpc(RpcRequest::FocusWindow {
1247                            session_id: sid,
1248                            window_id: wid,
1249                        })];
1250                    }
1251                }
1252                vec![ChromeOutput::Redraw]
1253            }
1254            3 => {
1255                self.mode = ShellMode::ModelList;
1256                vec![ChromeOutput::Redraw]
1257            }
1258            4 => {
1259                // Log (console)
1260                self.console_scroll = self.console_log.len().saturating_sub(1);
1261                self.mode = ShellMode::Console;
1262                vec![ChromeOutput::Redraw]
1263            }
1264            5 => {
1265                // Workers
1266                self.mode = ShellMode::WorkerManager {
1267                    sandbox_sel: 0,
1268                    container_sel: 0,
1269                    show_containers: false,
1270                    tab: WorkerTab::Sandboxes,
1271                    image_sel: 0,
1272                    input_mode: None,
1273                };
1274                vec![ChromeOutput::Redraw]
1275            }
1276            #[cfg(feature = "experimental")]
1277            SERVICES_IDX => {
1278                self.mode = ShellMode::ServiceManager { selected: 0 };
1279                vec![ChromeOutput::Redraw]
1280            }
1281            SETTINGS_IDX => {
1282                self.saved_style = self.bg.style;
1283                let i = ALL_STYLES
1284                    .iter()
1285                    .position(|s| *s == self.bg.style)
1286                    .unwrap_or(0);
1287                self.settings_list =
1288                    SelectList::new("Background", ALL_STYLES.to_vec()).with_selected(i);
1289                self.preview_bg.style = self.bg.style;
1290                self.mode = ShellMode::Settings;
1291                vec![ChromeOutput::Redraw]
1292            }
1293            FULLSCREEN_IDX => {
1294                self.mode = ShellMode::Fullscreen;
1295                vec![ChromeOutput::Redraw]
1296            }
1297            DISCONNECT_IDX => vec![ChromeOutput::Rpc(RpcRequest::Quit)],
1298            _ => vec![],
1299        }
1300    }
1301
1302    // ── Console mode ─────────────────────────────────────────────────────────
1303
1304    fn handle_console(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
1305        match key {
1306            KeyPress::ArrowUp => {
1307                self.console_scroll = self.console_scroll.saturating_sub(1);
1308                vec![ChromeOutput::Redraw]
1309            }
1310            KeyPress::ArrowDown => {
1311                let max = self.console_log.len().saturating_sub(1);
1312                if self.console_scroll < max {
1313                    self.console_scroll += 1;
1314                }
1315                vec![ChromeOutput::Redraw]
1316            }
1317            KeyPress::Escape => {
1318                self.mode = ShellMode::Normal;
1319                vec![ChromeOutput::Redraw]
1320            }
1321            _ => vec![],
1322        }
1323    }
1324
1325    // ── Fullscreen mode ───────────────────────────────────────────────────────
1326
1327    fn handle_fullscreen(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
1328        match key {
1329            KeyPress::Char(0x06) | KeyPress::Escape => {
1330                // Ctrl-F or Esc — exit fullscreen.
1331                self.mode = ShellMode::Normal;
1332                vec![ChromeOutput::Redraw]
1333            }
1334            key => {
1335                let bytes = keypress_to_bytes(key);
1336                if bytes.is_empty() {
1337                    vec![]
1338                } else {
1339                    let active = self.active_pane_id();
1340                    if self.private_panes.contains(&active) {
1341                        vec![ChromeOutput::RouteInput {
1342                            app_id: active,
1343                            data: bytes,
1344                        }]
1345                    } else {
1346                        let vid = self.viewer_id;
1347                        vec![ChromeOutput::Rpc(RpcRequest::SendInput {
1348                            viewer_id: vid,
1349                            data: bytes,
1350                        })]
1351                    }
1352                }
1353            }
1354        }
1355    }
1356
1357    /// Open the conversation picker with the given entries.
1358    /// Called by the shell handler after loading the manifest.
1359    pub fn open_conversation_picker(
1360        &mut self,
1361        model_ref: String,
1362        conversations: Vec<ConversationPickerEntry>,
1363    ) {
1364        let mut items = vec![
1365            ConversationPickerEntry {
1366                kind: ConversationKind::NewPrivate,
1367                label: "\u{1f512} New conversation \u{2014} private".to_owned(),
1368                last_active: u64::MAX, // sort first
1369            },
1370            ConversationPickerEntry {
1371                kind: ConversationKind::NewServer,
1372                label: "\u{1f310} New conversation \u{2014} server".to_owned(),
1373                last_active: u64::MAX - 1, // sort second
1374            },
1375        ];
1376        items.extend(conversations);
1377        let list = SelectList::new(format!("{} \u{2014} Conversations", model_ref), items);
1378        self.mode = ShellMode::ConversationPicker { model_ref, list };
1379    }
1380
1381    // ── ConversationPicker mode ────────────────────────────────────────────
1382
1383    fn handle_conversation_picker(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
1384        let (model_ref, list) = match &mut self.mode {
1385            ShellMode::ConversationPicker { model_ref, list } => (model_ref.clone(), list),
1386            _ => return vec![],
1387        };
1388
1389        // 's' — open pre-chat settings (only on new-conversation entries)
1390        if matches!(key, KeyPress::Char(b's' | b'S')) {
1391            if let Some(entry) = list.selected_item() {
1392                let chat_type = match entry.kind {
1393                    ConversationKind::NewPrivate => Some(PreChatType::Private),
1394                    ConversationKind::NewServer => Some(PreChatType::Server),
1395                    ConversationKind::Resume { .. } => None,
1396                };
1397                if let Some(chat_type) = chat_type {
1398                    let defaults = self.gen_defaults_for(&model_ref);
1399                    let form = build_settings_form(&defaults);
1400                    self.mode = ShellMode::PreChatSettings(Box::new(PreChatSettingsState {
1401                        model_ref: model_ref.clone(),
1402                        defaults,
1403                        form,
1404                        chat_type,
1405                    }));
1406                    return vec![ChromeOutput::Redraw];
1407                }
1408            }
1409        }
1410
1411        // 'd' — delete selected conversation (only on resume entries)
1412        if matches!(key, KeyPress::Char(b'd' | b'D')) {
1413            let idx = list.selected_index();
1414            if let Some(entry) = list.selected_item().cloned() {
1415                if let ConversationKind::Resume { uuid } = entry.kind {
1416                    let mr = model_ref.clone();
1417                    list.items_mut().remove(idx);
1418                    list.clamp_selected();
1419                    self.push_toast("Deleted conversation", ToastLevel::Info);
1420                    return vec![
1421                        ChromeOutput::Rpc(RpcRequest::DeleteConversation {
1422                            uuid,
1423                            model_ref: mr,
1424                        }),
1425                        ChromeOutput::Redraw,
1426                    ];
1427                }
1428            }
1429        }
1430
1431        match list.handle_key(&key) {
1432            WidgetResult::Cancelled => {
1433                self.mode = ShellMode::Normal;
1434                vec![ChromeOutput::Redraw]
1435            }
1436            WidgetResult::Confirmed(entry) => {
1437                let cols = self.cols;
1438                let rows = self.pane_rows;
1439                self.mode = ShellMode::Normal;
1440                match entry.kind {
1441                    ConversationKind::NewServer => {
1442                        let gen_defs = self.gen_defaults_for(&model_ref);
1443                        vec![ChromeOutput::Rpc(RpcRequest::SpawnServerChat {
1444                            session_id: self.session_id,
1445                            model_ref,
1446                            cols,
1447                            rows,
1448                            pane_id: 0,
1449                            gen_defaults: Some(gen_defs),
1450                        })]
1451                    }
1452                    ConversationKind::NewPrivate => {
1453                        let gen_defs = self.gen_defaults_for(&model_ref);
1454                        vec![ChromeOutput::Rpc(RpcRequest::LocalPrivateChat {
1455                            model_ref,
1456                            cols,
1457                            rows,
1458                            resume_uuid: None,
1459                            gen_defaults: Some(gen_defs),
1460                        })]
1461                    }
1462                    ConversationKind::Resume { uuid } => {
1463                        vec![ChromeOutput::Rpc(RpcRequest::LocalPrivateChat {
1464                            model_ref,
1465                            cols,
1466                            rows,
1467                            resume_uuid: Some(uuid),
1468                            gen_defaults: None,
1469                        })]
1470                    }
1471                }
1472            }
1473            WidgetResult::Pending => {
1474                if matches!(key, KeyPress::Escape) {
1475                    self.mode = ShellMode::Normal;
1476                }
1477                vec![ChromeOutput::Redraw]
1478            }
1479        }
1480    }
1481
1482    /// Look up generation defaults for a model from the model list.
1483    fn gen_defaults_for(&self, model_ref: &str) -> GenerationDefaults {
1484        self.model_list
1485            .items()
1486            .iter()
1487            .find(|e| e.model_ref == model_ref)
1488            .map(|e| e.gen_defaults.clone())
1489            .unwrap_or_default()
1490    }
1491
1492    // ── PreChatSettings mode ───────────────────────────────────────────────
1493
1494    /// Handle key input in the pre-chat generation settings modal.
1495    /// Delegates to the SettingsForm widget for field navigation and editing.
1496    /// Escape (when not editing a field) re-emits ListConversations to rebuild the picker.
1497    fn handle_pre_chat_settings(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
1498        let state = match &mut self.mode {
1499            ShellMode::PreChatSettings(s) => s,
1500            _ => return vec![],
1501        };
1502
1503        match state.form.handle_key(&key) {
1504            waxterm::widgets::WidgetResult::Confirmed(()) => {
1505                let cols = self.cols;
1506                let rows = self.pane_rows;
1507                let mr = state.model_ref.clone();
1508                let gen_defs = form_to_generation_defaults(&state.form);
1509                let chat_type = state.chat_type;
1510                self.mode = ShellMode::Normal;
1511                match chat_type {
1512                    PreChatType::Server => {
1513                        vec![ChromeOutput::Rpc(RpcRequest::SpawnServerChat {
1514                            session_id: self.session_id,
1515                            model_ref: mr,
1516                            cols,
1517                            rows,
1518                            pane_id: 0,
1519                            gen_defaults: Some(gen_defs),
1520                        })]
1521                    }
1522                    PreChatType::Private => {
1523                        vec![ChromeOutput::Rpc(RpcRequest::LocalPrivateChat {
1524                            model_ref: mr,
1525                            cols,
1526                            rows,
1527                            resume_uuid: None,
1528                            gen_defaults: Some(gen_defs),
1529                        })]
1530                    }
1531                }
1532            }
1533            waxterm::widgets::WidgetResult::Cancelled => {
1534                let mr = state.model_ref.clone();
1535                self.mode = ShellMode::Normal;
1536                vec![ChromeOutput::Rpc(RpcRequest::ListConversations {
1537                    model_ref: mr,
1538                })]
1539            }
1540            waxterm::widgets::WidgetResult::Pending => {
1541                vec![ChromeOutput::Redraw]
1542            }
1543        }
1544    }
1545
1546    // ── ServiceManager mode ────────────────────────────────────────────────
1547
1548    fn handle_service_manager(&mut self, key: KeyPress, selected: usize) -> Vec<ChromeOutput> {
1549        let n = self.service_list.len();
1550        match key {
1551            KeyPress::ArrowUp | KeyPress::Char(b'k') if n > 0 => {
1552                self.mode = ShellMode::ServiceManager {
1553                    selected: if selected == 0 { n - 1 } else { selected - 1 },
1554                };
1555                vec![ChromeOutput::Redraw]
1556            }
1557            KeyPress::ArrowDown | KeyPress::Char(b'j') if n > 0 => {
1558                self.mode = ShellMode::ServiceManager {
1559                    selected: (selected + 1) % n,
1560                };
1561                vec![ChromeOutput::Redraw]
1562            }
1563            KeyPress::Char(b's') => {
1564                if let Some(svc) = self.service_list.get(selected) {
1565                    let name = svc.name.clone();
1566                    return vec![ChromeOutput::Rpc(RpcRequest::ServiceStop { name })];
1567                }
1568                vec![]
1569            }
1570            KeyPress::Char(b't') => {
1571                if let Some(svc) = self.service_list.get(selected) {
1572                    let name = svc.name.clone();
1573                    return vec![ChromeOutput::Rpc(RpcRequest::ServiceStart { name })];
1574                }
1575                vec![]
1576            }
1577            KeyPress::Char(b'r') => {
1578                if let Some(svc) = self.service_list.get(selected) {
1579                    let name = svc.name.clone();
1580                    return vec![ChromeOutput::Rpc(RpcRequest::ServiceRestart { name })];
1581                }
1582                vec![]
1583            }
1584            KeyPress::Char(b'a') => {
1585                vec![ChromeOutput::Rpc(RpcRequest::ServiceStartAll)]
1586            }
1587            KeyPress::Char(b'S') => {
1588                vec![ChromeOutput::Rpc(RpcRequest::ServiceStopAll)]
1589            }
1590            KeyPress::Char(b'i') => {
1591                vec![ChromeOutput::Rpc(RpcRequest::ServiceInstall)]
1592            }
1593            KeyPress::Escape => {
1594                self.mode = ShellMode::Normal;
1595                vec![ChromeOutput::Redraw]
1596            }
1597            _ => vec![],
1598        }
1599    }
1600
1601    // ── WorkerManager mode ──────────────────────────────────────────────────
1602
1603    fn handle_worker_manager(
1604        &mut self,
1605        key: KeyPress,
1606        sandbox_sel: usize,
1607        container_sel: usize,
1608        show_containers: bool,
1609        tab: WorkerTab,
1610        image_sel: usize,
1611    ) -> Vec<ChromeOutput> {
1612        // Helper macro for constructing mode with current tab state.
1613        macro_rules! wm {
1614            ($ss:expr, $cs:expr, $sc:expr) => {
1615                ShellMode::WorkerManager {
1616                    sandbox_sel: $ss,
1617                    container_sel: $cs,
1618                    show_containers: $sc,
1619                    tab,
1620                    image_sel,
1621                    input_mode: None,
1622                }
1623            };
1624            ($ss:expr, $cs:expr, $sc:expr, tab: $t:expr) => {
1625                ShellMode::WorkerManager {
1626                    sandbox_sel: $ss,
1627                    container_sel: $cs,
1628                    show_containers: $sc,
1629                    tab: $t,
1630                    image_sel,
1631                    input_mode: None,
1632                }
1633            };
1634            ($ss:expr, $cs:expr, $sc:expr, tab: $t:expr, img: $is:expr) => {
1635                ShellMode::WorkerManager {
1636                    sandbox_sel: $ss,
1637                    container_sel: $cs,
1638                    show_containers: $sc,
1639                    tab: $t,
1640                    image_sel: $is,
1641                    input_mode: None,
1642                }
1643            };
1644        }
1645
1646        // Tab key toggles between Sandboxes and Images
1647        if key == KeyPress::Tab {
1648            let new_tab = match tab {
1649                WorkerTab::Sandboxes => WorkerTab::Images,
1650                WorkerTab::Images => WorkerTab::Sandboxes,
1651            };
1652            self.mode = wm!(sandbox_sel, container_sel, false, tab: new_tab);
1653            // When switching to Images tab, request image list refresh
1654            if new_tab == WorkerTab::Images {
1655                return vec![
1656                    ChromeOutput::Redraw,
1657                    ChromeOutput::Rpc(RpcRequest::WorkerImageList),
1658                ];
1659            }
1660            return vec![ChromeOutput::Redraw];
1661        }
1662
1663        // Images tab handling
1664        if tab == WorkerTab::Images {
1665            let n = self.image_list.len();
1666            return match key {
1667                KeyPress::ArrowUp | KeyPress::Char(b'k') if n > 0 => {
1668                    let new_sel = if image_sel == 0 { n - 1 } else { image_sel - 1 };
1669                    self.mode = wm!(sandbox_sel, container_sel, false, tab: WorkerTab::Images, img: new_sel);
1670                    vec![ChromeOutput::Redraw]
1671                }
1672                KeyPress::ArrowDown | KeyPress::Char(b'j') if n > 0 => {
1673                    let new_sel = (image_sel + 1) % n;
1674                    self.mode = wm!(sandbox_sel, container_sel, false, tab: WorkerTab::Images, img: new_sel);
1675                    vec![ChromeOutput::Redraw]
1676                }
1677                // Pull image
1678                KeyPress::Char(b'p') => {
1679                    self.mode = ShellMode::WorkerManager {
1680                        sandbox_sel,
1681                        container_sel,
1682                        show_containers: false,
1683                        tab: WorkerTab::Images,
1684                        image_sel,
1685                        input_mode: Some(InputDialog {
1686                            title: "Pull Image",
1687                            fields: vec![InputField::text("Image")],
1688                            focused: 0,
1689                        }),
1690                    };
1691                    vec![ChromeOutput::Redraw]
1692                }
1693                // Remove image
1694                KeyPress::Char(b'x') => {
1695                    if let Some(img) = self.image_list.get(image_sel) {
1696                        let image = img.repo_tag.clone();
1697                        return vec![ChromeOutput::Rpc(RpcRequest::WorkerImageRemove { image })];
1698                    }
1699                    vec![]
1700                }
1701                KeyPress::Escape => {
1702                    self.mode = ShellMode::Normal;
1703                    vec![ChromeOutput::Redraw]
1704                }
1705                _ => vec![],
1706            };
1707        }
1708
1709        // Sandboxes tab
1710        let n = self.worker_list.len();
1711        match key {
1712            // Sandbox navigation (when not showing containers)
1713            KeyPress::ArrowUp | KeyPress::Char(b'k') if n > 0 && !show_containers => {
1714                self.mode = wm!(
1715                    if sandbox_sel == 0 {
1716                        n - 1
1717                    } else {
1718                        sandbox_sel - 1
1719                    },
1720                    0,
1721                    false
1722                );
1723                vec![ChromeOutput::Redraw]
1724            }
1725            KeyPress::ArrowDown | KeyPress::Char(b'j') if n > 0 && !show_containers => {
1726                self.mode = wm!((sandbox_sel + 1) % n, 0, false);
1727                vec![ChromeOutput::Redraw]
1728            }
1729            // Enter container view
1730            KeyPress::Enter | KeyPress::ArrowRight if !show_containers => {
1731                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1732                    if !sb.containers.is_empty() {
1733                        self.mode = wm!(sandbox_sel, 0, true);
1734                    }
1735                }
1736                vec![ChromeOutput::Redraw]
1737            }
1738            // Exit container view
1739            KeyPress::ArrowLeft if show_containers => {
1740                self.mode = wm!(sandbox_sel, 0, false);
1741                vec![ChromeOutput::Redraw]
1742            }
1743            // Container navigation
1744            KeyPress::ArrowUp | KeyPress::Char(b'k') if show_containers => {
1745                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1746                    let cn = sb.containers.len();
1747                    let new_sel = if cn > 0 && container_sel > 0 {
1748                        container_sel - 1
1749                    } else if cn > 0 {
1750                        cn - 1
1751                    } else {
1752                        0
1753                    };
1754                    self.mode = wm!(sandbox_sel, new_sel, true);
1755                }
1756                vec![ChromeOutput::Redraw]
1757            }
1758            KeyPress::ArrowDown | KeyPress::Char(b'j') if show_containers => {
1759                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1760                    let cn = sb.containers.len();
1761                    let new_sel = if cn > 0 { (container_sel + 1) % cn } else { 0 };
1762                    self.mode = wm!(sandbox_sel, new_sel, true);
1763                }
1764                vec![ChromeOutput::Redraw]
1765            }
1766            // Create sandbox
1767            KeyPress::Char(b'n') if !show_containers => {
1768                self.mode = ShellMode::WorkerManager {
1769                    sandbox_sel,
1770                    container_sel,
1771                    show_containers: false,
1772                    tab,
1773                    image_sel,
1774                    input_mode: Some(InputDialog {
1775                        title: "Create Sandbox",
1776                        fields: vec![
1777                            InputField::text_with_default("Hostname", "sandbox"),
1778                            InputField::choices(
1779                                "Backend",
1780                                vec!["kata".to_owned(), "runc".to_owned(), "gvisor".to_owned()],
1781                            ),
1782                            InputField::toggle("GPU"),
1783                        ],
1784                        focused: 0,
1785                    }),
1786                };
1787                vec![ChromeOutput::Redraw]
1788            }
1789            // Destroy sandbox
1790            KeyPress::Char(b'x') if !show_containers => {
1791                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1792                    let sid = sb.full_id.clone();
1793                    return vec![ChromeOutput::Rpc(RpcRequest::WorkerDestroySandbox {
1794                        sandbox_id: sid,
1795                    })];
1796                }
1797                vec![]
1798            }
1799            // Create container
1800            KeyPress::Char(b'n') if show_containers => {
1801                if self.worker_list.get(sandbox_sel).is_some() {
1802                    self.mode = ShellMode::WorkerManager {
1803                        sandbox_sel,
1804                        container_sel,
1805                        show_containers: true,
1806                        tab,
1807                        image_sel,
1808                        input_mode: Some(InputDialog {
1809                            title: "Create Container",
1810                            fields: vec![
1811                                InputField::text_with_default("Image", "alpine:latest"),
1812                                InputField::text_with_default("Command", "/bin/sh"),
1813                                InputField::toggle("TTY"),
1814                            ],
1815                            focused: 0,
1816                        }),
1817                    };
1818                }
1819                vec![ChromeOutput::Redraw]
1820            }
1821            // Start container
1822            KeyPress::Char(b't') if show_containers => {
1823                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1824                    if let Some(ctr) = sb.containers.get(container_sel) {
1825                        return vec![ChromeOutput::Rpc(RpcRequest::WorkerStartContainer {
1826                            container_id: ctr.full_id.clone(),
1827                        })];
1828                    }
1829                }
1830                vec![]
1831            }
1832            // Stop container
1833            KeyPress::Char(b's') if show_containers => {
1834                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1835                    if let Some(ctr) = sb.containers.get(container_sel) {
1836                        return vec![ChromeOutput::Rpc(RpcRequest::WorkerStopContainer {
1837                            container_id: ctr.full_id.clone(),
1838                        })];
1839                    }
1840                }
1841                vec![]
1842            }
1843            // Remove container
1844            KeyPress::Char(b'x') if show_containers => {
1845                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1846                    if let Some(ctr) = sb.containers.get(container_sel) {
1847                        return vec![ChromeOutput::Rpc(RpcRequest::WorkerRemoveContainer {
1848                            container_id: ctr.full_id.clone(),
1849                        })];
1850                    }
1851                }
1852                vec![]
1853            }
1854            // Attach to container
1855            KeyPress::Char(b'a') if show_containers => {
1856                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1857                    if let Some(ctr) = sb.containers.get(container_sel) {
1858                        return vec![ChromeOutput::Rpc(RpcRequest::AttachContainer {
1859                            sandbox_id: sb.full_id.clone(),
1860                            container_id: ctr.full_id.clone(),
1861                            cols: self.cols,
1862                            rows: self.pane_rows,
1863                        })];
1864                    }
1865                }
1866                vec![]
1867            }
1868            // Exec in container
1869            KeyPress::Char(b'e') if show_containers => {
1870                if let Some(sb) = self.worker_list.get(sandbox_sel) {
1871                    if let Some(ctr) = sb.containers.get(container_sel) {
1872                        let sid = sb.full_id.clone();
1873                        let cid = ctr.full_id.clone();
1874                        return vec![ChromeOutput::Rpc(RpcRequest::WorkerExecSync {
1875                            sandbox_id: sid,
1876                            container_id: cid,
1877                            cmd: vec!["id".to_owned()],
1878                        })];
1879                    }
1880                }
1881                vec![]
1882            }
1883            KeyPress::Escape => {
1884                self.mode = ShellMode::Normal;
1885                vec![ChromeOutput::Redraw]
1886            }
1887            _ => vec![],
1888        }
1889    }
1890
1891    // ── Input dialog handling ───────────────────────────────────────────────
1892
1893    fn handle_input_dialog(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
1894        // Extract current state to determine context.
1895        let (tab, sandbox_sel, container_sel, show_containers, image_sel) = match &self.mode {
1896            ShellMode::WorkerManager {
1897                tab,
1898                sandbox_sel,
1899                container_sel,
1900                show_containers,
1901                image_sel,
1902                ..
1903            } => (
1904                *tab,
1905                *sandbox_sel,
1906                *container_sel,
1907                *show_containers,
1908                *image_sel,
1909            ),
1910            _ => return vec![],
1911        };
1912
1913        match key {
1914            KeyPress::Escape => {
1915                // Cancel dialog
1916                self.mode = ShellMode::WorkerManager {
1917                    sandbox_sel,
1918                    container_sel,
1919                    show_containers,
1920                    tab,
1921                    image_sel,
1922                    input_mode: None,
1923                };
1924                vec![ChromeOutput::Redraw]
1925            }
1926            KeyPress::Enter => {
1927                // Submit dialog
1928                let dialog = match &mut self.mode {
1929                    ShellMode::WorkerManager {
1930                        ref mut input_mode, ..
1931                    } => input_mode.take(),
1932                    _ => None,
1933                };
1934                let Some(dialog) = dialog else {
1935                    return vec![];
1936                };
1937                let rpc = match dialog.title {
1938                    "Pull Image" => {
1939                        let image = dialog.fields[0].value();
1940                        if image.is_empty() {
1941                            None
1942                        } else {
1943                            Some(RpcRequest::WorkerImagePull { image })
1944                        }
1945                    }
1946                    "Create Sandbox" => {
1947                        let hostname = dialog.fields[0].value();
1948                        let backend = dialog.fields[1].value();
1949                        let gpu = dialog.fields[2].toggle_val;
1950                        Some(RpcRequest::WorkerCreateSandbox {
1951                            hostname,
1952                            backend,
1953                            gpu,
1954                        })
1955                    }
1956                    "Create Container" => {
1957                        let sandbox_id = self
1958                            .worker_list
1959                            .get(sandbox_sel)
1960                            .map(|sb| sb.full_id.clone())
1961                            .unwrap_or_default();
1962                        let image = dialog.fields[0].value();
1963                        let cmd_str = dialog.fields[1].value();
1964                        let cmd: Vec<String> =
1965                            cmd_str.split_whitespace().map(String::from).collect();
1966                        let tty = dialog.fields[2].toggle_val;
1967                        Some(RpcRequest::WorkerCreateContainer {
1968                            sandbox_id,
1969                            image,
1970                            cmd,
1971                            tty,
1972                        })
1973                    }
1974                    _ => None,
1975                };
1976                self.mode = ShellMode::WorkerManager {
1977                    sandbox_sel,
1978                    container_sel,
1979                    show_containers,
1980                    tab,
1981                    image_sel,
1982                    input_mode: None,
1983                };
1984                if let Some(req) = rpc {
1985                    vec![ChromeOutput::Redraw, ChromeOutput::Rpc(req)]
1986                } else {
1987                    vec![ChromeOutput::Redraw]
1988                }
1989            }
1990            KeyPress::ArrowDown => {
1991                if let ShellMode::WorkerManager {
1992                    input_mode: Some(ref mut d),
1993                    ..
1994                } = self.mode
1995                {
1996                    if d.focused + 1 < d.fields.len() {
1997                        d.focused += 1;
1998                    }
1999                }
2000                vec![ChromeOutput::Redraw]
2001            }
2002            KeyPress::ArrowUp => {
2003                if let ShellMode::WorkerManager {
2004                    input_mode: Some(ref mut d),
2005                    ..
2006                } = self.mode
2007                {
2008                    if d.focused > 0 {
2009                        d.focused -= 1;
2010                    }
2011                }
2012                vec![ChromeOutput::Redraw]
2013            }
2014            KeyPress::Char(b' ') => {
2015                if let ShellMode::WorkerManager {
2016                    input_mode: Some(ref mut d),
2017                    ..
2018                } = self.mode
2019                {
2020                    if let Some(f) = d.fields.get_mut(d.focused) {
2021                        if f.is_toggle {
2022                            f.toggle_val = !f.toggle_val;
2023                        } else if let Some(ref opts) = f.choices {
2024                            if !opts.is_empty() {
2025                                f.choice_idx = (f.choice_idx + 1) % opts.len();
2026                            }
2027                        } else {
2028                            f.buf.insert(f.cursor, b' ');
2029                            f.cursor += 1;
2030                        }
2031                    }
2032                }
2033                vec![ChromeOutput::Redraw]
2034            }
2035            KeyPress::Backspace => {
2036                if let ShellMode::WorkerManager {
2037                    input_mode: Some(ref mut d),
2038                    ..
2039                } = self.mode
2040                {
2041                    if let Some(f) = d.fields.get_mut(d.focused) {
2042                        if !f.is_toggle && f.choices.is_none() && f.cursor > 0 {
2043                            f.cursor -= 1;
2044                            f.buf.remove(f.cursor);
2045                        }
2046                    }
2047                }
2048                vec![ChromeOutput::Redraw]
2049            }
2050            KeyPress::ArrowLeft => {
2051                if let ShellMode::WorkerManager {
2052                    input_mode: Some(ref mut d),
2053                    ..
2054                } = self.mode
2055                {
2056                    if let Some(f) = d.fields.get_mut(d.focused) {
2057                        if !f.is_toggle && f.choices.is_none() && f.cursor > 0 {
2058                            f.cursor -= 1;
2059                        }
2060                    }
2061                }
2062                vec![ChromeOutput::Redraw]
2063            }
2064            KeyPress::ArrowRight => {
2065                if let ShellMode::WorkerManager {
2066                    input_mode: Some(ref mut d),
2067                    ..
2068                } = self.mode
2069                {
2070                    if let Some(f) = d.fields.get_mut(d.focused) {
2071                        if !f.is_toggle && f.choices.is_none() && f.cursor < f.buf.len() {
2072                            f.cursor += 1;
2073                        }
2074                    }
2075                }
2076                vec![ChromeOutput::Redraw]
2077            }
2078            KeyPress::Char(c) => {
2079                if let ShellMode::WorkerManager {
2080                    input_mode: Some(ref mut d),
2081                    ..
2082                } = self.mode
2083                {
2084                    if let Some(f) = d.fields.get_mut(d.focused) {
2085                        if f.is_toggle {
2086                            f.toggle_val = !f.toggle_val;
2087                        } else if let Some(ref opts) = f.choices {
2088                            if !opts.is_empty() {
2089                                f.choice_idx = (f.choice_idx + 1) % opts.len();
2090                            }
2091                        } else {
2092                            f.buf.insert(f.cursor, c);
2093                            f.cursor += 1;
2094                        }
2095                    }
2096                }
2097                vec![ChromeOutput::Redraw]
2098            }
2099            _ => vec![],
2100        }
2101    }
2102
2103    // ── Settings mode ────────────────────────────────────────────────────────
2104
2105    fn handle_settings(&mut self, key: KeyPress) -> Vec<ChromeOutput> {
2106        match self.settings_list.handle_key(&key) {
2107            WidgetResult::Cancelled => {
2108                self.bg.style = self.saved_style;
2109                self.preview_bg.style = self.saved_style;
2110                self.mode = ShellMode::Normal;
2111                vec![ChromeOutput::Redraw]
2112            }
2113            WidgetResult::Confirmed(style) => {
2114                self.bg.style = style;
2115                self.preview_bg.style = style;
2116                self.mode = ShellMode::Normal;
2117                vec![ChromeOutput::Redraw]
2118            }
2119            WidgetResult::Pending => {
2120                if let Some(&style) = self.settings_list.selected_item() {
2121                    self.bg.style = style;
2122                    self.preview_bg.style = style;
2123                }
2124                vec![ChromeOutput::Redraw]
2125            }
2126        }
2127    }
2128}
2129
2130// ============================================================================
2131// KeyPress → raw bytes (for forwarding to PTY via sendInput)
2132// ============================================================================
2133
2134pub fn keypress_to_bytes(key: KeyPress) -> Vec<u8> {
2135    match key {
2136        KeyPress::Char(b) => vec![b],
2137        KeyPress::Enter => vec![b'\r'],
2138        KeyPress::Backspace => vec![0x7f],
2139        KeyPress::Tab => vec![b'\t'],
2140        KeyPress::Escape => vec![0x1b],
2141        KeyPress::ArrowUp => b"\x1b[A".to_vec(),
2142        KeyPress::ArrowDown => b"\x1b[B".to_vec(),
2143        KeyPress::ArrowRight => b"\x1b[C".to_vec(),
2144        KeyPress::ArrowLeft => b"\x1b[D".to_vec(),
2145        KeyPress::F(1) => b"\x1bOP".to_vec(),
2146        KeyPress::F(2) => b"\x1bOQ".to_vec(),
2147        KeyPress::F(3) => b"\x1bOR".to_vec(),
2148        KeyPress::F(4) => b"\x1bOS".to_vec(),
2149        KeyPress::F(5) => b"\x1b[15~".to_vec(),
2150        KeyPress::F(6) => b"\x1b[17~".to_vec(),
2151        KeyPress::F(7) => b"\x1b[18~".to_vec(),
2152        KeyPress::F(8) => b"\x1b[19~".to_vec(),
2153        KeyPress::F(9) => b"\x1b[20~".to_vec(),
2154        KeyPress::F(10) => b"\x1b[21~".to_vec(),
2155        KeyPress::F(11) => b"\x1b[23~".to_vec(),
2156        KeyPress::F(12) => b"\x1b[24~".to_vec(),
2157        KeyPress::F(_) | KeyPress::CtrlSpace | KeyPress::ScrollUp | KeyPress::ScrollDown => vec![],
2158    }
2159}
2160
2161// ============================================================================
2162// Tests
2163// ============================================================================
2164
2165#[cfg(test)]
2166#[allow(clippy::unwrap_used, clippy::expect_used)]
2167mod tests {
2168    use super::*;
2169
2170    fn make_chrome() -> ShellChrome {
2171        ShellChrome::new(120, 40, 1, 1, vec![], vec![])
2172    }
2173
2174    #[cfg(feature = "experimental")]
2175    fn sample_services() -> Vec<ServiceEntry> {
2176        vec![
2177            ServiceEntry {
2178                name: "oai".into(),
2179                active: true,
2180                mode: ServiceMode::Systemd,
2181                pid: Some(1234),
2182            },
2183            ServiceEntry {
2184                name: "registry".into(),
2185                active: false,
2186                mode: ServiceMode::Stopped,
2187                pid: None,
2188            },
2189            ServiceEntry {
2190                name: "model".into(),
2191                active: true,
2192                mode: ServiceMode::Daemon,
2193                pid: Some(5678),
2194            },
2195        ]
2196    }
2197
2198    fn sample_workers() -> Vec<WorkerEntry> {
2199        vec![
2200            WorkerEntry {
2201                id: "abc123".into(),
2202                full_id: "abc12345-6789".into(),
2203                state: "Ready".into(),
2204                backend: "kata".into(),
2205                cpu_pct: Some(25),
2206                mem_mb: Some(512),
2207                containers: vec![
2208                    ContainerEntry {
2209                        id: "ctr1".into(),
2210                        full_id: "ctr1-full".into(),
2211                        image: "hyprstream:latest".into(),
2212                        state: "Running".into(),
2213                        cpu_pct: Some(10),
2214                        mem_mb: Some(256),
2215                    },
2216                    ContainerEntry {
2217                        id: "ctr2".into(),
2218                        full_id: "ctr2-full".into(),
2219                        image: "worker:v2".into(),
2220                        state: "Stopped".into(),
2221                        cpu_pct: None,
2222                        mem_mb: None,
2223                    },
2224                ],
2225            },
2226            WorkerEntry {
2227                id: "def456".into(),
2228                full_id: "def45678-abcd".into(),
2229                state: "Starting".into(),
2230                backend: "nspawn".into(),
2231                cpu_pct: None,
2232                mem_mb: None,
2233                containers: vec![],
2234            },
2235        ]
2236    }
2237
2238    // ── F5 Service Manager ──────────────────────────────────────────────────
2239
2240    #[cfg(feature = "experimental")]
2241    #[test]
2242    fn start_menu_v_opens_service_manager() {
2243        let mut chrome = make_chrome();
2244        chrome.mode = ShellMode::StartMenu { selected: 0 };
2245        let out = chrome.handle_key(KeyPress::Char(b'v'));
2246        assert!(matches!(
2247            chrome.mode,
2248            ShellMode::ServiceManager { selected: 0 }
2249        ));
2250        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Redraw)));
2251    }
2252
2253    #[cfg(feature = "experimental")]
2254    #[test]
2255    fn service_manager_escape_returns_to_normal() {
2256        let mut chrome = make_chrome();
2257        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2258        let out = chrome.handle_key(KeyPress::Escape);
2259        assert!(matches!(chrome.mode, ShellMode::Normal));
2260        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Redraw)));
2261    }
2262
2263    #[cfg(feature = "experimental")]
2264    #[test]
2265    fn service_manager_navigate_down() {
2266        let mut chrome = make_chrome();
2267        chrome.service_list = sample_services();
2268        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2269
2270        chrome.handle_key(KeyPress::ArrowDown);
2271        assert!(matches!(
2272            chrome.mode,
2273            ShellMode::ServiceManager { selected: 1 }
2274        ));
2275
2276        chrome.handle_key(KeyPress::ArrowDown);
2277        assert!(matches!(
2278            chrome.mode,
2279            ShellMode::ServiceManager { selected: 2 }
2280        ));
2281
2282        // Wraps around
2283        chrome.handle_key(KeyPress::ArrowDown);
2284        assert!(matches!(
2285            chrome.mode,
2286            ShellMode::ServiceManager { selected: 0 }
2287        ));
2288    }
2289
2290    #[cfg(feature = "experimental")]
2291    #[test]
2292    fn service_manager_navigate_up() {
2293        let mut chrome = make_chrome();
2294        chrome.service_list = sample_services();
2295        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2296
2297        // Wraps to last
2298        chrome.handle_key(KeyPress::ArrowUp);
2299        assert!(matches!(
2300            chrome.mode,
2301            ShellMode::ServiceManager { selected: 2 }
2302        ));
2303
2304        chrome.handle_key(KeyPress::ArrowUp);
2305        assert!(matches!(
2306            chrome.mode,
2307            ShellMode::ServiceManager { selected: 1 }
2308        ));
2309    }
2310
2311    #[cfg(feature = "experimental")]
2312    #[test]
2313    fn service_manager_vim_keys() {
2314        let mut chrome = make_chrome();
2315        chrome.service_list = sample_services();
2316        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2317
2318        chrome.handle_key(KeyPress::Char(b'j'));
2319        assert!(matches!(
2320            chrome.mode,
2321            ShellMode::ServiceManager { selected: 1 }
2322        ));
2323
2324        chrome.handle_key(KeyPress::Char(b'k'));
2325        assert!(matches!(
2326            chrome.mode,
2327            ShellMode::ServiceManager { selected: 0 }
2328        ));
2329    }
2330
2331    #[cfg(feature = "experimental")]
2332    #[test]
2333    fn service_manager_start_emits_rpc() {
2334        let mut chrome = make_chrome();
2335        chrome.service_list = sample_services();
2336        chrome.mode = ShellMode::ServiceManager { selected: 1 };
2337
2338        let out = chrome.handle_key(KeyPress::Char(b't'));
2339        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::ServiceStart { ref name }) if name == "registry")));
2340    }
2341
2342    #[cfg(feature = "experimental")]
2343    #[test]
2344    fn service_manager_stop_emits_rpc() {
2345        let mut chrome = make_chrome();
2346        chrome.service_list = sample_services();
2347        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2348
2349        let out = chrome.handle_key(KeyPress::Char(b's'));
2350        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::ServiceStop { ref name }) if name == "oai")));
2351    }
2352
2353    #[cfg(feature = "experimental")]
2354    #[test]
2355    fn service_manager_restart_emits_rpc() {
2356        let mut chrome = make_chrome();
2357        chrome.service_list = sample_services();
2358        chrome.mode = ShellMode::ServiceManager { selected: 2 };
2359
2360        let out = chrome.handle_key(KeyPress::Char(b'r'));
2361        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::ServiceRestart { ref name }) if name == "model")));
2362    }
2363
2364    #[cfg(feature = "experimental")]
2365    #[test]
2366    fn service_manager_start_all() {
2367        let mut chrome = make_chrome();
2368        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2369
2370        let out = chrome.handle_key(KeyPress::Char(b'a'));
2371        assert!(out
2372            .iter()
2373            .any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::ServiceStartAll))));
2374    }
2375
2376    #[cfg(feature = "experimental")]
2377    #[test]
2378    fn service_manager_stop_all() {
2379        let mut chrome = make_chrome();
2380        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2381
2382        let out = chrome.handle_key(KeyPress::Char(b'S'));
2383        assert!(out
2384            .iter()
2385            .any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::ServiceStopAll))));
2386    }
2387
2388    #[cfg(feature = "experimental")]
2389    #[test]
2390    fn service_manager_install() {
2391        let mut chrome = make_chrome();
2392        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2393
2394        let out = chrome.handle_key(KeyPress::Char(b'i'));
2395        assert!(out
2396            .iter()
2397            .any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::ServiceInstall))));
2398    }
2399
2400    #[cfg(feature = "experimental")]
2401    #[test]
2402    fn service_manager_empty_list_no_crash() {
2403        let mut chrome = make_chrome();
2404        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2405        // Empty list — navigation should do nothing, no panic
2406        let out = chrome.handle_key(KeyPress::ArrowDown);
2407        assert!(out.is_empty());
2408        let out = chrome.handle_key(KeyPress::ArrowUp);
2409        assert!(out.is_empty());
2410    }
2411
2412    #[cfg(feature = "experimental")]
2413    #[test]
2414    fn service_manager_start_on_empty_list() {
2415        let mut chrome = make_chrome();
2416        chrome.mode = ShellMode::ServiceManager { selected: 0 };
2417        // Start on empty list — no panic, no output
2418        let out = chrome.handle_key(KeyPress::Char(b't'));
2419        assert!(out.is_empty());
2420    }
2421
2422    #[cfg(feature = "experimental")]
2423    #[test]
2424    fn update_service_list_clamps_selection() {
2425        let mut chrome = make_chrome();
2426        chrome.service_list = sample_services();
2427        chrome.mode = ShellMode::ServiceManager { selected: 2 };
2428
2429        // Shrink the list — selection should be clamped
2430        let short_list = vec![ServiceEntry {
2431            name: "oai".into(),
2432            active: true,
2433            mode: ServiceMode::Systemd,
2434            pid: None,
2435        }];
2436        chrome.update_service_list(short_list);
2437        // Selection clamping happens in Compositor::handle(ServiceList), not in chrome directly.
2438        // But verify the list was updated.
2439        assert_eq!(chrome.service_list.len(), 1);
2440    }
2441
2442    // ── Worker Manager (via Ctrl-Space → W) ─────────────────────────────────
2443
2444    #[test]
2445    fn start_menu_w_opens_worker_manager() {
2446        let mut chrome = make_chrome();
2447        chrome.mode = ShellMode::StartMenu { selected: 0 };
2448        let out = chrome.handle_key(KeyPress::Char(b'w'));
2449        assert!(matches!(
2450            chrome.mode,
2451            ShellMode::WorkerManager {
2452                sandbox_sel: 0,
2453                container_sel: 0,
2454                show_containers: false,
2455                tab: WorkerTab::Sandboxes,
2456                image_sel: 0,
2457                input_mode: None
2458            }
2459        ));
2460        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Redraw)));
2461    }
2462
2463    #[test]
2464    fn worker_manager_escape_returns_to_normal() {
2465        let mut chrome = make_chrome();
2466        chrome.mode = ShellMode::WorkerManager {
2467            sandbox_sel: 0,
2468            container_sel: 0,
2469            show_containers: false,
2470            tab: WorkerTab::Sandboxes,
2471            image_sel: 0,
2472            input_mode: None,
2473        };
2474        chrome.handle_key(KeyPress::Escape);
2475        assert!(matches!(chrome.mode, ShellMode::Normal));
2476    }
2477
2478    #[test]
2479    fn worker_manager_navigate_sandboxes() {
2480        let mut chrome = make_chrome();
2481        chrome.worker_list = sample_workers();
2482        chrome.mode = ShellMode::WorkerManager {
2483            sandbox_sel: 0,
2484            container_sel: 0,
2485            show_containers: false,
2486            tab: WorkerTab::Sandboxes,
2487            image_sel: 0,
2488            input_mode: None,
2489        };
2490
2491        chrome.handle_key(KeyPress::ArrowDown);
2492        assert!(matches!(
2493            chrome.mode,
2494            ShellMode::WorkerManager { sandbox_sel: 1, .. }
2495        ));
2496
2497        chrome.handle_key(KeyPress::ArrowDown);
2498        assert!(matches!(
2499            chrome.mode,
2500            ShellMode::WorkerManager { sandbox_sel: 0, .. }
2501        ));
2502
2503        chrome.handle_key(KeyPress::ArrowUp);
2504        assert!(matches!(
2505            chrome.mode,
2506            ShellMode::WorkerManager { sandbox_sel: 1, .. }
2507        ));
2508    }
2509
2510    #[test]
2511    fn worker_manager_enter_container_view() {
2512        let mut chrome = make_chrome();
2513        chrome.worker_list = sample_workers();
2514        chrome.mode = ShellMode::WorkerManager {
2515            sandbox_sel: 0,
2516            container_sel: 0,
2517            show_containers: false,
2518            tab: WorkerTab::Sandboxes,
2519            image_sel: 0,
2520            input_mode: None,
2521        };
2522
2523        // First sandbox has containers
2524        chrome.handle_key(KeyPress::Enter);
2525        assert!(matches!(
2526            chrome.mode,
2527            ShellMode::WorkerManager {
2528                sandbox_sel: 0,
2529                container_sel: 0,
2530                show_containers: true,
2531                tab: WorkerTab::Sandboxes,
2532                image_sel: 0,
2533                input_mode: None
2534            }
2535        ));
2536    }
2537
2538    #[test]
2539    fn worker_manager_enter_no_containers() {
2540        let mut chrome = make_chrome();
2541        chrome.worker_list = sample_workers();
2542        chrome.mode = ShellMode::WorkerManager {
2543            sandbox_sel: 1,
2544            container_sel: 0,
2545            show_containers: false,
2546            tab: WorkerTab::Sandboxes,
2547            image_sel: 0,
2548            input_mode: None,
2549        };
2550
2551        // Second sandbox has no containers — should stay in sandbox view
2552        chrome.handle_key(KeyPress::Enter);
2553        assert!(matches!(
2554            chrome.mode,
2555            ShellMode::WorkerManager {
2556                show_containers: false,
2557                ..
2558            }
2559        ));
2560    }
2561
2562    #[test]
2563    fn worker_manager_navigate_containers() {
2564        let mut chrome = make_chrome();
2565        chrome.worker_list = sample_workers();
2566        chrome.mode = ShellMode::WorkerManager {
2567            sandbox_sel: 0,
2568            container_sel: 0,
2569            show_containers: true,
2570            tab: WorkerTab::Sandboxes,
2571            image_sel: 0,
2572            input_mode: None,
2573        };
2574
2575        chrome.handle_key(KeyPress::ArrowDown);
2576        assert!(matches!(
2577            chrome.mode,
2578            ShellMode::WorkerManager {
2579                container_sel: 1,
2580                show_containers: true,
2581                ..
2582            }
2583        ));
2584
2585        // Wrap around
2586        chrome.handle_key(KeyPress::ArrowDown);
2587        assert!(matches!(
2588            chrome.mode,
2589            ShellMode::WorkerManager {
2590                container_sel: 0,
2591                show_containers: true,
2592                ..
2593            }
2594        ));
2595    }
2596
2597    #[test]
2598    fn worker_manager_back_from_containers() {
2599        let mut chrome = make_chrome();
2600        chrome.worker_list = sample_workers();
2601        chrome.mode = ShellMode::WorkerManager {
2602            sandbox_sel: 0,
2603            container_sel: 1,
2604            show_containers: true,
2605            tab: WorkerTab::Sandboxes,
2606            image_sel: 0,
2607            input_mode: None,
2608        };
2609
2610        chrome.handle_key(KeyPress::ArrowLeft);
2611        assert!(matches!(
2612            chrome.mode,
2613            ShellMode::WorkerManager {
2614                sandbox_sel: 0,
2615                container_sel: 0,
2616                show_containers: false,
2617                tab: WorkerTab::Sandboxes,
2618                image_sel: 0,
2619                input_mode: None
2620            }
2621        ));
2622    }
2623
2624    #[test]
2625    fn worker_manager_destroy_sandbox() {
2626        let mut chrome = make_chrome();
2627        chrome.worker_list = sample_workers();
2628        chrome.mode = ShellMode::WorkerManager {
2629            sandbox_sel: 0,
2630            container_sel: 0,
2631            show_containers: false,
2632            tab: WorkerTab::Sandboxes,
2633            image_sel: 0,
2634            input_mode: None,
2635        };
2636
2637        let out = chrome.handle_key(KeyPress::Char(b'x'));
2638        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::WorkerDestroySandbox { ref sandbox_id }) if sandbox_id == "abc12345-6789")));
2639    }
2640
2641    #[test]
2642    fn worker_manager_exec_in_container() {
2643        let mut chrome = make_chrome();
2644        chrome.worker_list = sample_workers();
2645        chrome.mode = ShellMode::WorkerManager {
2646            sandbox_sel: 0,
2647            container_sel: 1,
2648            show_containers: true,
2649            tab: WorkerTab::Sandboxes,
2650            image_sel: 0,
2651            input_mode: None,
2652        };
2653
2654        let out = chrome.handle_key(KeyPress::Char(b'e'));
2655        assert!(out.iter().any(|o| matches!(o,
2656            ChromeOutput::Rpc(RpcRequest::WorkerExecSync { ref sandbox_id, ref container_id, .. })
2657            if sandbox_id == "abc12345-6789" && container_id == "ctr2-full"
2658        )));
2659    }
2660
2661    #[test]
2662    fn worker_manager_empty_list_no_crash() {
2663        let mut chrome = make_chrome();
2664        chrome.mode = ShellMode::WorkerManager {
2665            sandbox_sel: 0,
2666            container_sel: 0,
2667            show_containers: false,
2668            tab: WorkerTab::Sandboxes,
2669            image_sel: 0,
2670            input_mode: None,
2671        };
2672        // Empty list — no panic
2673        chrome.handle_key(KeyPress::ArrowDown);
2674        chrome.handle_key(KeyPress::ArrowUp);
2675        chrome.handle_key(KeyPress::Enter);
2676        let out = chrome.handle_key(KeyPress::Char(b'x'));
2677        assert!(out.is_empty());
2678    }
2679
2680    // ── Compositor ServiceList/WorkerList input ─────────────────────────────
2681
2682    #[cfg(feature = "experimental")]
2683    #[test]
2684    fn compositor_service_list_clamps_selection() {
2685        let mut comp = crate::Compositor::new(120, 40, 1, 1, vec![], vec![]);
2686        comp.chrome.mode = ShellMode::ServiceManager { selected: 5 };
2687
2688        let out = comp.handle(crate::CompositorInput::ServiceList(sample_services()));
2689        assert!(out
2690            .iter()
2691            .any(|o| matches!(o, crate::CompositorOutput::Redraw)));
2692        if let ShellMode::ServiceManager { selected } = comp.chrome.mode {
2693            assert!(selected <= 2, "selection should be clamped to list len - 1");
2694        } else {
2695            panic!("mode should still be ServiceManager");
2696        }
2697    }
2698
2699    #[test]
2700    fn compositor_worker_list_clamps_selection() {
2701        let mut comp = crate::Compositor::new(120, 40, 1, 1, vec![], vec![]);
2702        comp.chrome.mode = ShellMode::WorkerManager {
2703            sandbox_sel: 10,
2704            container_sel: 5,
2705            show_containers: true,
2706            tab: WorkerTab::Sandboxes,
2707            image_sel: 0,
2708            input_mode: None,
2709        };
2710
2711        let out = comp.handle(crate::CompositorInput::WorkerList {
2712            sandboxes: sample_workers(),
2713            pool_summary: "2 sandboxes".into(),
2714        });
2715        assert!(out
2716            .iter()
2717            .any(|o| matches!(o, crate::CompositorOutput::Redraw)));
2718        if let ShellMode::WorkerManager { sandbox_sel, .. } = comp.chrome.mode {
2719            assert!(sandbox_sel <= 1, "sandbox_sel should be clamped");
2720        } else {
2721            panic!("mode should still be WorkerManager");
2722        }
2723    }
2724
2725    // ── Start menu chord tests ───────────────────────────────────────────────
2726
2727    #[test]
2728    fn start_menu_l_opens_console() {
2729        let mut chrome = make_chrome();
2730        chrome.mode = ShellMode::StartMenu { selected: 0 };
2731        let out = chrome.handle_key(KeyPress::Char(b'l'));
2732        assert!(matches!(chrome.mode, ShellMode::Console));
2733        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Redraw)));
2734    }
2735
2736    #[test]
2737    fn start_menu_f_enters_fullscreen() {
2738        let mut chrome = make_chrome();
2739        chrome.mode = ShellMode::StartMenu { selected: 0 };
2740        let out = chrome.handle_key(KeyPress::Char(b'f'));
2741        assert!(matches!(chrome.mode, ShellMode::Fullscreen));
2742        assert!(out.iter().any(|o| matches!(o, ChromeOutput::Redraw)));
2743    }
2744
2745    #[test]
2746    fn f_keys_pass_through_in_normal() {
2747        let mut chrome = make_chrome();
2748        // F9 should pass through to the active pane as escape sequence bytes.
2749        let out = chrome.handle_key(KeyPress::F(9));
2750        assert!(
2751            out.iter().any(|o| matches!(o,
2752                ChromeOutput::Rpc(RpcRequest::SendInput { data, .. })
2753                    if *data == b"\x1b[20~"
2754            )),
2755            "F9 should produce SendInput with VT escape sequence"
2756        );
2757    }
2758
2759    // ── Unified chat flow tests ──────────────────────────────────────────────
2760
2761    fn make_chrome_with_models() -> ShellChrome {
2762        let models = vec![
2763            ModelEntry {
2764                model_ref: "loaded:main".into(),
2765                path: "/tmp".into(),
2766                loaded: true,
2767                loading: false,
2768                gen_defaults: GenerationDefaults::default(),
2769            },
2770            ModelEntry {
2771                model_ref: "unloaded:main".into(),
2772                path: "/tmp".into(),
2773                loaded: false,
2774                loading: false,
2775                gen_defaults: GenerationDefaults::default(),
2776            },
2777            ModelEntry {
2778                model_ref: "loading:main".into(),
2779                path: "/tmp".into(),
2780                loaded: false,
2781                loading: true,
2782                gen_defaults: GenerationDefaults::default(),
2783            },
2784        ];
2785        ShellChrome::new(120, 40, 1, 1, vec![], models)
2786    }
2787
2788    #[test]
2789    fn model_list_enter_loaded_emits_list_conversations() {
2790        let mut chrome = make_chrome_with_models();
2791        chrome.mode = ShellMode::ModelList;
2792        // Select the first model (loaded:main) and press Enter.
2793        let out = chrome.handle_key(KeyPress::Enter);
2794        assert!(matches!(chrome.mode, ShellMode::Normal));
2795        assert!(out.iter().any(|o| matches!(o,
2796            ChromeOutput::Rpc(RpcRequest::ListConversations { ref model_ref })
2797                if model_ref == "loaded:main"
2798        )));
2799        assert!(chrome.pending_picker_model.is_none());
2800    }
2801
2802    #[test]
2803    fn model_list_enter_unloaded_emits_load_and_stashes_pending() {
2804        let mut chrome = make_chrome_with_models();
2805        chrome.mode = ShellMode::ModelList;
2806        // Navigate to unloaded:main (index 1).
2807        chrome.handle_key(KeyPress::ArrowDown);
2808        let out = chrome.handle_key(KeyPress::Enter);
2809        // Should emit LoadModel, not ListConversations.
2810        assert!(out.iter().any(|o| matches!(o,
2811            ChromeOutput::Rpc(RpcRequest::LoadModel { ref model_ref })
2812                if model_ref == "unloaded:main"
2813        )));
2814        assert_eq!(
2815            chrome.pending_picker_model.as_deref(),
2816            Some("unloaded:main")
2817        );
2818    }
2819
2820    #[test]
2821    fn model_list_enter_loading_stashes_pending_no_rpc() {
2822        let mut chrome = make_chrome_with_models();
2823        chrome.mode = ShellMode::ModelList;
2824        // Navigate to loading:main (index 2).
2825        chrome.handle_key(KeyPress::ArrowDown);
2826        chrome.handle_key(KeyPress::ArrowDown);
2827        let out = chrome.handle_key(KeyPress::Enter);
2828        // Should only redraw, no RPC.
2829        assert!(!out.iter().any(|o| matches!(o, ChromeOutput::Rpc(..))));
2830        assert_eq!(chrome.pending_picker_model.as_deref(), Some("loading:main"));
2831    }
2832
2833    #[test]
2834    fn update_model_status_opens_picker_when_pending() {
2835        let mut chrome = make_chrome_with_models();
2836        chrome.pending_picker_model = Some("unloaded:main".into());
2837        let follow_up = chrome.update_model_status("unloaded:main", true);
2838        assert!(
2839            matches!(follow_up, Some(RpcRequest::ListConversations { ref model_ref }) if model_ref == "unloaded:main")
2840        );
2841        assert!(chrome.pending_picker_model.is_none());
2842    }
2843
2844    #[test]
2845    fn update_model_status_clears_pending_on_timeout() {
2846        let mut chrome = make_chrome_with_models();
2847        chrome.pending_picker_model = Some("unloaded:main".into());
2848        let follow_up = chrome.update_model_status("unloaded:main", false);
2849        assert!(follow_up.is_none());
2850        assert!(chrome.pending_picker_model.is_none());
2851    }
2852
2853    #[test]
2854    fn model_list_escape_clears_pending() {
2855        let mut chrome = make_chrome_with_models();
2856        chrome.mode = ShellMode::ModelList;
2857        chrome.pending_picker_model = Some("unloaded:main".into());
2858        chrome.handle_key(KeyPress::Escape);
2859        assert!(matches!(chrome.mode, ShellMode::Normal));
2860        assert!(chrome.pending_picker_model.is_none());
2861    }
2862
2863    #[test]
2864    fn conversation_picker_new_server_emits_spawn_server_chat() {
2865        let mut chrome = make_chrome_with_models();
2866        chrome.open_conversation_picker("loaded:main".into(), vec![]);
2867        // Select "New conversation — server" (index 1) and confirm.
2868        chrome.handle_key(KeyPress::ArrowDown);
2869        let out = chrome.handle_key(KeyPress::Enter);
2870        assert!(matches!(chrome.mode, ShellMode::Normal));
2871        assert!(out.iter().any(|o| matches!(o,
2872            ChromeOutput::Rpc(RpcRequest::SpawnServerChat { ref model_ref, .. })
2873                if model_ref == "loaded:main"
2874        )));
2875    }
2876
2877    #[test]
2878    fn conversation_picker_new_private_emits_local_private_chat() {
2879        let mut chrome = make_chrome_with_models();
2880        chrome.open_conversation_picker("loaded:main".into(), vec![]);
2881        // First item is "New conversation — private" (index 0), press Enter.
2882        let out = chrome.handle_key(KeyPress::Enter);
2883        assert!(matches!(chrome.mode, ShellMode::Normal));
2884        assert!(out.iter().any(|o| matches!(o,
2885            ChromeOutput::Rpc(RpcRequest::LocalPrivateChat { ref model_ref, resume_uuid: None, .. })
2886                if model_ref == "loaded:main"
2887        )));
2888    }
2889
2890    #[test]
2891    fn conversation_picker_cannot_delete_sentinels() {
2892        let mut chrome = make_chrome_with_models();
2893        chrome.open_conversation_picker("loaded:main".into(), vec![]);
2894        // Try to delete first entry (sentinel).
2895        let out = chrome.handle_key(KeyPress::Char(b'd'));
2896        // Should NOT emit DeleteConversation.
2897        assert!(!out
2898            .iter()
2899            .any(|o| matches!(o, ChromeOutput::Rpc(RpcRequest::DeleteConversation { .. }))));
2900    }
2901}