omnyssh 1.0.3

TUI SSH dashboard & server manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
//! Host list state: add/edit form, list view, popups, and the `App` methods
//! that create, update, delete, and connect to hosts.

use std::io::Stdout;
use std::time::Duration;

use ratatui::{backend::CrosstermBackend, Terminal};

use super::*;
use crate::ssh::client::HostSource;

// ---------------------------------------------------------------------------
// Host form (used in Add / Edit popups)
// ---------------------------------------------------------------------------

/// Labels for every field in the host add/edit form.
pub const FORM_FIELD_LABELS: &[&str] = &[
    "Name",
    "Hostname / IP",
    "User",
    "Port",
    "Identity File",
    "Password (optional)",
    "Tags (comma-sep)",
    "Notes",
];

/// A single editable text field in the host form.
#[derive(Debug, Clone, Default)]
pub struct FormField {
    pub value: String,
    /// Cursor position (byte offset) within `value`.
    pub cursor: usize,
}

impl FormField {
    pub fn with_value(s: impl Into<String>) -> Self {
        let value = s.into();
        let cursor = value.len();
        Self { value, cursor }
    }

    /// Insert a character at the current cursor position.
    pub fn insert_char(&mut self, c: char) {
        self.value.insert(self.cursor, c);
        self.cursor += c.len_utf8();
    }

    /// Delete the character immediately before the cursor (backspace).
    pub fn backspace(&mut self) {
        if self.cursor == 0 {
            return;
        }
        // Find the previous char boundary.
        let prev = self.value[..self.cursor]
            .char_indices()
            .next_back()
            .map(|(i, _)| i)
            .unwrap_or(0);
        self.value.drain(prev..self.cursor);
        self.cursor = prev;
    }
}

/// The host add/edit form, containing all editable fields.
#[derive(Debug, Clone)]
pub struct HostForm {
    /// Parallel to `FORM_FIELD_LABELS`.
    pub fields: Vec<FormField>,
    /// Index of the currently focused field.
    pub focused_field: usize,
}

impl HostForm {
    /// Creates an empty form for adding a new host.
    pub fn empty() -> Self {
        Self {
            fields: FORM_FIELD_LABELS
                .iter()
                .map(|_| FormField::default())
                .collect(),
            focused_field: 0,
        }
    }

    /// Creates a form pre-filled from an existing host (for editing).
    pub fn from_host(host: &Host) -> Self {
        let mut form = Self::empty();
        form.fields[0] = FormField::with_value(&host.name);
        form.fields[1] = FormField::with_value(&host.hostname);
        form.fields[2] = FormField::with_value(&host.user);
        form.fields[3] = FormField::with_value(host.port.to_string());
        form.fields[4] = FormField::with_value(host.identity_file.as_deref().unwrap_or(""));
        form.fields[5] = FormField::with_value(host.password.as_deref().unwrap_or(""));
        form.fields[6] = FormField::with_value(host.tags.join(", "));
        form.fields[7] = FormField::with_value(host.notes.as_deref().unwrap_or(""));
        form
    }

    /// Validates the form and converts it into a [`Host`].
    ///
    /// # Errors
    /// Returns a human-readable error string if validation fails.
    pub fn to_host(&self, source: HostSource) -> Result<Host, String> {
        let name = self.fields[0].value.trim().to_string();
        if name.is_empty() {
            return Err("Name cannot be empty".to_string());
        }

        let hostname = self.fields[1].value.trim().to_string();
        if hostname.is_empty() {
            return Err("Hostname / IP cannot be empty".to_string());
        }

        let user = {
            let v = self.fields[2].value.trim();
            if v.is_empty() {
                "root".to_string()
            } else {
                v.to_string()
            }
        };

        let port = {
            let v = self.fields[3].value.trim();
            if v.is_empty() {
                22u16
            } else {
                v.parse::<u16>().ok().filter(|&p| p != 0).ok_or_else(|| {
                    format!("Port must be a number between 1 and 65535, got '{v}'")
                })?
            }
        };

        let identity_file = {
            let v = self.fields[4].value.trim();
            if v.is_empty() {
                None
            } else {
                Some(v.to_string())
            }
        };

        let password = {
            let v = self.fields[5].value.trim();
            if v.is_empty() {
                None
            } else {
                Some(v.to_string())
            }
        };

        let tags: Vec<String> = self.fields[6]
            .value
            .split(',')
            .map(|t| t.trim().to_string())
            .filter(|t| !t.is_empty())
            .collect();

        let notes = {
            let v = self.fields[7].value.trim();
            if v.is_empty() {
                None
            } else {
                Some(v.to_string())
            }
        };

        Ok(Host {
            name,
            hostname,
            user,
            port,
            identity_file,
            password,
            proxy_jump: None,
            tags,
            notes,
            source,
            original_ssh_host: None,
            key_setup_date: None,
            password_auth_disabled: None,
        })
    }

    /// Move focus to the next field (wraps around).
    pub fn focus_next(&mut self) {
        self.focused_field = (self.focused_field + 1) % self.fields.len();
    }

    /// Move focus to the previous field (wraps around).
    pub fn focus_prev(&mut self) {
        if self.focused_field == 0 {
            self.focused_field = self.fields.len() - 1;
        } else {
            self.focused_field -= 1;
        }
    }
}

// ---------------------------------------------------------------------------
// Host list popup variants
// ---------------------------------------------------------------------------

/// Which popup is currently visible over the host list.
#[derive(Debug, Clone)]
pub enum HostPopup {
    /// Adding a new host.
    Add(HostForm),
    /// Editing an existing host (`host_idx` is the index in `AppState.hosts`).
    Edit { host_idx: usize, form: HostForm },
    /// Asking for confirmation before deleting (`host_idx`).
    DeleteConfirm(usize),
    /// Asking for confirmation to set up SSH key authentication.
    KeySetupConfirm(usize),
    /// Showing key setup progress.
    KeySetupProgress {
        host_idx: usize,
        host_name: String,
        current_step: Option<crate::ssh::key_setup::KeySetupStep>,
    },
}

// ---------------------------------------------------------------------------
// Host-list view state (UI-only, not shared with SSH tasks)
// ---------------------------------------------------------------------------

/// UI state specific to the host list / Dashboard screen.
#[derive(Debug, Default)]
pub struct HostListView {
    /// Selected row index within `filtered_indices`.
    pub selected: usize,
    /// True when the user is actively typing a search query.
    pub search_mode: bool,
    /// Current fuzzy-search query.
    pub search_query: String,
    /// Indices into `AppState.hosts` that match the current query, sorted and
    /// tag-filtered according to `sort_order` / `tag_filter`.
    pub filtered_indices: Vec<usize>,
    /// Currently visible popup (if any).
    pub popup: Option<HostPopup>,
    /// Host waiting to be connected (handled before the next render).
    pub pending_connect: Option<Host>,
    // Dashboard additions -----------
    /// Active sort order for the dashboard grid.
    pub sort_order: SortOrder,
    /// Active tag filter. `None` = show all hosts.
    pub tag_filter: Option<String>,
    /// Whether the tag-filter popup is open.
    pub tag_popup_open: bool,
    /// Selected index within the tag picker popup.
    pub tag_popup_selected: usize,
    /// All unique tags across all hosts (used by the tag picker popup).
    pub available_tags: Vec<String>,
}

impl HostListView {
    /// Returns the index into `AppState.hosts` for the selected filtered row.
    pub fn selected_host_idx(&self) -> Option<usize> {
        self.filtered_indices.get(self.selected).copied()
    }

    /// Rebuilds `filtered_indices` applying text search, tag filter, and
    /// sort order.
    ///
    /// Accepts `metrics` so CPU/RAM sorts can compare live values. Pass an
    /// empty map if metrics are not yet available.
    pub fn rebuild_filter(
        &mut self,
        hosts: &[Host],
        metrics: &HashMap<String, Metrics>,
        statuses: &HashMap<String, ConnectionStatus>,
    ) {
        use std::cmp::Ordering;

        // 1. Text filter.
        let mut indices = filter_hosts(hosts, &self.search_query);

        // Guard: drop any stale indices that fell out of bounds due to a host
        // removal that happened before rebuild_filter was called.
        indices.retain(|&i| i < hosts.len());

        // 2. Tag filter.
        if let Some(tag) = &self.tag_filter {
            let tag = tag.clone();
            indices.retain(|&i| hosts[i].tags.contains(&tag));
        }

        // 3. Sort.
        match self.sort_order {
            SortOrder::Name => {
                indices.sort_by(|&a, &b| hosts[a].name.cmp(&hosts[b].name));
            }
            SortOrder::Cpu => {
                indices.sort_by(|&a, &b| {
                    let ca = metrics
                        .get(&hosts[a].name)
                        .and_then(|m| m.cpu_percent)
                        .unwrap_or(-1.0);
                    let cb = metrics
                        .get(&hosts[b].name)
                        .and_then(|m| m.cpu_percent)
                        .unwrap_or(-1.0);
                    cb.partial_cmp(&ca).unwrap_or(Ordering::Equal)
                });
            }
            SortOrder::Ram => {
                indices.sort_by(|&a, &b| {
                    let ra = metrics
                        .get(&hosts[a].name)
                        .and_then(|m| m.ram_percent)
                        .unwrap_or(-1.0);
                    let rb = metrics
                        .get(&hosts[b].name)
                        .and_then(|m| m.ram_percent)
                        .unwrap_or(-1.0);
                    rb.partial_cmp(&ra).unwrap_or(Ordering::Equal)
                });
            }
            SortOrder::Status => {
                indices.sort_by(|&a, &b| {
                    let sa = status_priority(statuses.get(&hosts[a].name));
                    let sb = status_priority(statuses.get(&hosts[b].name));
                    sa.cmp(&sb)
                });
            }
        }

        self.filtered_indices = indices;
        // Clamp selection to the new range.
        if self.filtered_indices.is_empty() {
            self.selected = 0;
        } else if self.selected >= self.filtered_indices.len() {
            self.selected = self.filtered_indices.len() - 1;
        }
    }

    /// Scroll down by one row.
    pub fn select_next(&mut self) {
        if self.filtered_indices.is_empty() {
            return;
        }
        self.selected = (self.selected + 1).min(self.filtered_indices.len() - 1);
    }

    /// Scroll up by one row.
    pub fn select_prev(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// Rebuild the `available_tags` list from the full host list.
    pub fn rebuild_tags(&mut self, hosts: &[Host]) {
        let mut tags: Vec<String> = hosts.iter().flat_map(|h| h.tags.iter().cloned()).collect();
        tags.sort();
        tags.dedup();
        self.available_tags = tags;
    }
}

/// Lower number = higher priority for status sort.
fn status_priority(status: Option<&ConnectionStatus>) -> u8 {
    match status {
        Some(ConnectionStatus::Connected) => 0,
        Some(ConnectionStatus::Connecting) => 1,
        Some(ConnectionStatus::Unknown) | None => 2,
        Some(ConnectionStatus::Failed(_)) => 3,
    }
}

/// Simple case-insensitive substring filter over name / hostname / tags / notes.
///
/// Returns the matching indices into `hosts`. When `query` is empty every
/// host matches.
pub fn filter_hosts(hosts: &[Host], query: &str) -> Vec<usize> {
    if query.is_empty() {
        return (0..hosts.len()).collect();
    }
    let q = query.to_lowercase();
    hosts
        .iter()
        .enumerate()
        .filter(|(_, h)| {
            h.name.to_lowercase().contains(&q)
                || h.hostname.to_lowercase().contains(&q)
                || h.tags.iter().any(|t| t.to_lowercase().contains(&q))
                || h.notes
                    .as_deref()
                    .map(|n| n.to_lowercase().contains(&q))
                    .unwrap_or(false)
        })
        .map(|(i, _)| i)
        .collect()
}

impl App {
    /// Handles the user confirming the Add or Edit host form.
    pub(crate) async fn handle_confirm_form(&mut self) {
        match self.view.host_list.popup.take() {
            Some(HostPopup::Add(form)) => {
                match form.to_host(HostSource::Manual) {
                    Ok(host) => {
                        let has_password = host.password.is_some();
                        let host_name = host.name.clone();

                        {
                            let mut state = self.state.write().await;
                            state.hosts.push(host);
                        }
                        self.save_manual_hosts().await;

                        // Restart poll_manager to include the new host
                        {
                            let state = self.state.read().await;
                            if let Some(old) = self.poll_manager.take() {
                                old.shutdown();
                            }
                            self.poll_manager = Some(PollManager::start(
                                state.hosts.clone(),
                                self.event_tx.clone(),
                                Duration::from_secs(30),
                            ));
                        }

                        let state = self.state.read().await;
                        self.view.host_list.rebuild_filter(
                            &state.hosts,
                            &state.metrics,
                            &state.connection_statuses,
                        );
                        self.view.host_list.rebuild_tags(&state.hosts);

                        // Suggest SSH key setup if host was added with password
                        if has_password {
                            self.view.status_message = Some(format!(
                                "Host '{}' added. Press 'Shift+K' to set up SSH key authentication (recommended).",
                                host_name
                            ));
                        } else {
                            self.view.status_message = Some("Host added.".to_string());
                        }
                    }
                    Err(e) => {
                        // Restore popup so the user can correct the input.
                        self.view.host_list.popup = Some(HostPopup::Add(form));
                        self.view.status_message = Some(format!("Error: {e}"));
                    }
                }
            }

            Some(HostPopup::Edit { host_idx, form }) => match form.to_host(HostSource::Manual) {
                Ok(mut host) => {
                    let (old_name, _was_ssh_config) = {
                        let mut state = self.state.write().await;
                        let old_host = state.hosts.get(host_idx);
                        let old_name = old_host.map(|h| h.name.clone());
                        let was_ssh_config = old_host
                            .map(|h| h.source == HostSource::SshConfig)
                            .unwrap_or(false);

                        // If editing a SSH config host, preserve original name for duplicate prevention
                        if was_ssh_config && old_name.is_some() {
                            host.original_ssh_host = old_name.clone();
                        }

                        if let Some(slot) = state.hosts.get_mut(host_idx) {
                            *slot = host.clone();
                        }
                        (old_name, was_ssh_config)
                    };

                    // If the host name changed, migrate all associated data
                    if let Some(old_name) = old_name {
                        if old_name != host.name {
                            let mut state = self.state.write().await;

                            // Migrate metrics
                            if let Some(metrics) = state.metrics.remove(&old_name) {
                                state.metrics.insert(host.name.clone(), metrics);
                            }

                            // Migrate connection status
                            if let Some(status) = state.connection_statuses.remove(&old_name) {
                                state.connection_statuses.insert(host.name.clone(), status);
                            }

                            // Migrate services
                            if let Some(services) = state.services.remove(&old_name) {
                                state.services.insert(host.name.clone(), services);
                            }

                            // Migrate alerts
                            if let Some(alerts) = state.alerts.remove(&old_name) {
                                state.alerts.insert(host.name.clone(), alerts);
                            }

                            // Migrate discovery status
                            if let Some(discovery) = state.discovery_status.remove(&old_name) {
                                state.discovery_status.insert(host.name.clone(), discovery);
                            }
                        }
                    }

                    self.save_manual_hosts().await;
                    let state = self.state.read().await;
                    self.view.host_list.rebuild_filter(
                        &state.hosts,
                        &state.metrics,
                        &state.connection_statuses,
                    );
                    self.view.host_list.rebuild_tags(&state.hosts);
                    self.view.status_message = Some("Host updated.".to_string());
                }
                Err(e) => {
                    self.view.host_list.popup = Some(HostPopup::Edit { host_idx, form });
                    self.view.status_message = Some(format!("Error: {e}"));
                }
            },

            other => {
                // Wrong popup type — put it back unchanged.
                self.view.host_list.popup = other;
            }
        }
    }

    /// Handles the user confirming deletion.
    pub(crate) async fn handle_confirm_delete(&mut self) {
        if let Some(HostPopup::DeleteConfirm(idx)) = self.view.host_list.popup.take() {
            {
                let mut state = self.state.write().await;
                if idx < state.hosts.len() {
                    let removed = state.hosts.remove(idx);
                    self.view.status_message = Some(format!("Deleted '{}'.", removed.name));
                }
            }
            self.save_manual_hosts().await;
            let state = self.state.read().await;
            self.view.host_list.rebuild_filter(
                &state.hosts,
                &state.metrics,
                &state.connection_statuses,
            );
            self.view.host_list.rebuild_tags(&state.hosts);
        }
    }

    /// Saves the manually-added hosts to `hosts.toml`.
    pub(crate) async fn save_manual_hosts(&mut self) {
        let hosts = self.state.read().await.hosts.clone();
        if let Err(e) = config::save_hosts(&hosts) {
            self.view.status_message = Some(format!("Save failed: {e}"));
        }
    }

    /// Temporarily restores the terminal, runs the system SSH binary for the
    /// given host, then re-initialises the TUI.
    pub(crate) async fn connect_system_ssh(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
        host: &Host,
    ) -> anyhow::Result<()> {
        // 1. Leave TUI mode.
        leave_tui()?;

        // 2. Build SSH command (ConnectTimeout=10).
        let mut cmd = tokio::process::Command::new("ssh");
        cmd.args(["-o", "ConnectTimeout=10"]);
        if host.port != 22 {
            cmd.args(["-p", &host.port.to_string()]);
        }
        if let Some(ref key) = host.identity_file {
            cmd.args(["-i", key]);
        }
        if let Some(ref jump) = host.proxy_jump {
            cmd.args(["-J", jump]);
        }
        cmd.arg(format!("{}@{}", host.user, host.hostname));

        // 3. Hand off terminal control to SSH. A spawn/wait failure (e.g. no
        //    `ssh` binary on PATH) must not abort the app — the TUI is still
        //    restored below and the error is shown in the status bar.
        tracing::info!("Connecting to {} via system SSH", host.name);
        let outcome = match cmd.spawn() {
            Ok(mut child) => child.wait().await,
            Err(e) => Err(e),
        };

        // 4. Re-enter TUI mode. Bracketed paste is re-enabled here because the
        // remote shell may have left it disabled when the SSH session ended.
        enter_tui()?;
        terminal.clear()?;

        // 5. Show connection result.
        self.view.status_message = Some(match outcome {
            Ok(status) if status.success() => format!("Disconnected from '{}'.", host.name),
            Ok(status) => format!(
                "SSH to '{}' exited with code {:?}.",
                host.name,
                status.code()
            ),
            Err(e) => format!("Failed to launch ssh for '{}': {e}", host.name),
        });

        Ok(())
    }
}

/// Leaves the omnyssh TUI so a child process can own the terminal.
fn leave_tui() -> anyhow::Result<()> {
    crossterm::terminal::disable_raw_mode()?;
    crossterm::execute!(
        std::io::stdout(),
        crossterm::terminal::LeaveAlternateScreen,
        crate::utils::mouse::DisableMinimalMouseCapture,
        crossterm::event::DisableBracketedPaste,
    )?;
    Ok(())
}

/// Re-enters the omnyssh TUI after a child process has exited.
fn enter_tui() -> anyhow::Result<()> {
    crossterm::terminal::enable_raw_mode()?;
    crossterm::execute!(
        std::io::stdout(),
        crossterm::terminal::EnterAlternateScreen,
        crate::utils::mouse::EnableMinimalMouseCapture,
        crossterm::event::EnableBracketedPaste,
    )?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Builds a host form from the 8 field values, in `FORM_FIELD_LABELS` order.
    fn host_form(values: [&str; 8]) -> HostForm {
        let mut form = HostForm::empty();
        for (i, v) in values.iter().enumerate() {
            form.fields[i] = FormField::with_value(*v);
        }
        form
    }

    // --- HostForm::to_host (P0.2) -----------------------------------------

    #[test]
    fn to_host_empty_name_errs() {
        let form = host_form(["", "h", "u", "22", "", "", "", ""]);
        assert!(form.to_host(HostSource::Manual).is_err());
    }

    #[test]
    fn to_host_whitespace_name_errs() {
        let form = host_form(["   ", "h", "u", "22", "", "", "", ""]);
        assert!(form.to_host(HostSource::Manual).is_err());
    }

    #[test]
    fn to_host_empty_hostname_errs() {
        let form = host_form(["n", "", "u", "22", "", "", "", ""]);
        assert!(form.to_host(HostSource::Manual).is_err());
    }

    #[test]
    fn to_host_empty_user_defaults_root() {
        let host = host_form(["n", "h", "", "22", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert_eq!(host.user, "root");
    }

    #[test]
    fn to_host_whitespace_user_defaults_root() {
        let host = host_form(["n", "h", "  ", "22", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert_eq!(host.user, "root");
    }

    #[test]
    fn to_host_empty_port_defaults_22() {
        let host = host_form(["n", "h", "u", "", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert_eq!(host.port, 22);
    }

    #[test]
    fn to_host_valid_port_parsed() {
        let host = host_form(["n", "h", "u", "2222", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert_eq!(host.port, 2222);
    }

    #[test]
    fn to_host_port_max_accepted() {
        let host = host_form(["n", "h", "u", "65535", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert_eq!(host.port, 65535);
    }

    #[test]
    fn to_host_port_zero_errs() {
        // Port 0 is invalid for SSH; the form rejects it.
        assert!(host_form(["n", "h", "u", "0", "", "", "", ""])
            .to_host(HostSource::Manual)
            .is_err());
    }

    #[test]
    fn to_host_port_overflow_errs() {
        let err = host_form(["n", "h", "u", "65536", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap_err();
        assert!(err.contains("between 1 and 65535"));
    }

    #[test]
    fn to_host_port_non_numeric_errs() {
        assert!(host_form(["n", "h", "u", "abc", "", "", "", ""])
            .to_host(HostSource::Manual)
            .is_err());
    }

    #[test]
    fn to_host_port_negative_errs() {
        assert!(host_form(["n", "h", "u", "-1", "", "", "", ""])
            .to_host(HostSource::Manual)
            .is_err());
    }

    #[test]
    fn to_host_optional_fields_none_when_empty() {
        let host = host_form(["n", "h", "u", "22", "", "", "", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert!(host.identity_file.is_none());
        assert!(host.password.is_none());
        assert!(host.notes.is_none());
        assert!(host.tags.is_empty());
    }

    #[test]
    fn to_host_tags_split_and_trimmed() {
        let host = host_form(["n", "h", "u", "22", "", "", "a, b ,c,,", ""])
            .to_host(HostSource::Manual)
            .unwrap();
        assert_eq!(host.tags, vec!["a", "b", "c"]);
    }

    #[test]
    fn to_host_source_and_metadata_propagated() {
        let host = host_form(["n", "h", "u", "22", "", "", "", ""])
            .to_host(HostSource::SshConfig)
            .unwrap();
        assert_eq!(host.source, HostSource::SshConfig);
        assert!(host.original_ssh_host.is_none());
        assert!(host.key_setup_date.is_none());
        assert!(host.password_auth_disabled.is_none());
    }

    // --- FormField insert/backspace, UTF-8 safety (P1.1) ------------------

    #[test]
    fn formfield_insert_ascii() {
        let mut f = FormField::default();
        f.insert_char('a');
        assert_eq!(f.value, "a");
        assert_eq!(f.cursor, 1);
    }

    #[test]
    fn formfield_insert_multibyte_advances_cursor_by_byte_len() {
        let mut f = FormField::default();
        f.insert_char('é');
        assert_eq!(f.value, "é");
        assert_eq!(f.cursor, 2);
    }

    #[test]
    fn formfield_insert_emoji_advances_cursor_by_four() {
        let mut f = FormField::default();
        f.insert_char('😀');
        assert_eq!(f.cursor, 4);
    }

    #[test]
    fn formfield_insert_at_start() {
        let mut f = FormField::with_value("bc");
        f.cursor = 0;
        f.insert_char('a');
        assert_eq!(f.value, "abc");
        assert_eq!(f.cursor, 1);
    }

    #[test]
    fn formfield_insert_on_multibyte_boundary_stays_valid() {
        // Cursor sits between 'a' and 'é' — a valid char boundary.
        let mut f = FormField::with_value("aé");
        f.cursor = 1;
        f.insert_char('X');
        assert_eq!(f.value, "aXé");
    }

    #[test]
    fn formfield_backspace_ascii() {
        let mut f = FormField::with_value("ab");
        f.backspace();
        assert_eq!(f.value, "a");
        assert_eq!(f.cursor, 1);
    }

    #[test]
    fn formfield_backspace_removes_whole_multibyte_char() {
        let mut f = FormField::with_value("é");
        f.backspace();
        assert_eq!(f.value, "");
        assert_eq!(f.cursor, 0);
    }

    #[test]
    fn formfield_backspace_at_zero_is_noop() {
        let mut f = FormField::default();
        f.backspace();
        assert_eq!(f.value, "");
        assert_eq!(f.cursor, 0);
    }

    #[test]
    fn formfield_with_value_cursor_at_byte_len() {
        let f = FormField::with_value("héllo");
        assert_eq!(f.cursor, 6);
    }

    // --- filter_hosts (P1.3) ----------------------------------------------

    fn host(name: &str, hostname: &str, tags: &[&str], notes: Option<&str>) -> Host {
        Host {
            name: name.to_string(),
            hostname: hostname.to_string(),
            tags: tags.iter().map(|t| t.to_string()).collect(),
            notes: notes.map(|n| n.to_string()),
            ..Host::default()
        }
    }

    #[test]
    fn filter_hosts_empty_query_returns_all() {
        let hosts = [host("a", "1", &[], None), host("b", "2", &[], None)];
        assert_eq!(filter_hosts(&hosts, ""), vec![0, 1]);
    }

    #[test]
    fn filter_hosts_matches_name() {
        let hosts = [host("web-prod", "1", &[], None), host("db", "2", &[], None)];
        assert_eq!(filter_hosts(&hosts, "web"), vec![0]);
    }

    #[test]
    fn filter_hosts_matches_hostname() {
        let hosts = [
            host("a", "10.0.0.1", &[], None),
            host("b", "10.0.0.2", &[], None),
        ];
        assert_eq!(filter_hosts(&hosts, "0.0.1"), vec![0]);
    }

    #[test]
    fn filter_hosts_matches_tag() {
        let hosts = [
            host("a", "1", &["prod"], None),
            host("b", "2", &["dev"], None),
        ];
        assert_eq!(filter_hosts(&hosts, "prod"), vec![0]);
    }

    #[test]
    fn filter_hosts_matches_notes() {
        let hosts = [
            host("a", "1", &[], Some("bastion host")),
            host("b", "2", &[], None),
        ];
        assert_eq!(filter_hosts(&hosts, "bastion"), vec![0]);
    }

    #[test]
    fn filter_hosts_case_insensitive() {
        let hosts = [host("Web-Prod", "1", &[], None)];
        assert_eq!(filter_hosts(&hosts, "WEB"), vec![0]);
    }

    #[test]
    fn filter_hosts_no_match_returns_empty() {
        let hosts = [host("a", "1", &[], None)];
        assert!(filter_hosts(&hosts, "zzz").is_empty());
    }

    // --- HostListView::rebuild_filter and selection (P1.4) ----------------

    fn filtered_names<'a>(view: &HostListView, hosts: &'a [Host]) -> Vec<&'a str> {
        view.filtered_indices
            .iter()
            .map(|&i| hosts[i].name.as_str())
            .collect()
    }

    fn metrics_cpu(value: f64) -> Metrics {
        Metrics {
            cpu_percent: Some(value),
            ..Metrics::default()
        }
    }

    fn metrics_ram(value: f64) -> Metrics {
        Metrics {
            ram_percent: Some(value),
            ..Metrics::default()
        }
    }

    #[test]
    fn rebuild_sort_name_alphabetical() {
        let hosts = [
            host("c", "1", &[], None),
            host("a", "2", &[], None),
            host("b", "3", &[], None),
        ];
        let mut view = HostListView::default();
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(filtered_names(&view, &hosts), ["a", "b", "c"]);
    }

    #[test]
    fn rebuild_sort_cpu_descending_missing_metrics_last() {
        let hosts = [
            host("a", "1", &[], None),
            host("b", "2", &[], None),
            host("c", "3", &[], None),
        ];
        let metrics = HashMap::from([
            ("a".to_string(), metrics_cpu(90.0)),
            ("b".to_string(), metrics_cpu(10.0)),
        ]);
        let mut view = HostListView {
            sort_order: SortOrder::Cpu,
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &metrics, &HashMap::new());
        assert_eq!(filtered_names(&view, &hosts), ["a", "b", "c"]);
    }

    #[test]
    fn rebuild_sort_ram_descending() {
        let hosts = [host("a", "1", &[], None), host("b", "2", &[], None)];
        let metrics = HashMap::from([
            ("a".to_string(), metrics_ram(20.0)),
            ("b".to_string(), metrics_ram(80.0)),
        ]);
        let mut view = HostListView {
            sort_order: SortOrder::Ram,
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &metrics, &HashMap::new());
        assert_eq!(filtered_names(&view, &hosts), ["b", "a"]);
    }

    #[test]
    fn rebuild_sort_status_priority() {
        let hosts = [
            host("a", "1", &[], None),
            host("b", "2", &[], None),
            host("c", "3", &[], None),
            host("d", "4", &[], None),
        ];
        let statuses = HashMap::from([
            ("a".to_string(), ConnectionStatus::Failed("x".to_string())),
            ("b".to_string(), ConnectionStatus::Connected),
            ("c".to_string(), ConnectionStatus::Connecting),
        ]);
        let mut view = HostListView {
            sort_order: SortOrder::Status,
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &statuses);
        // Connected, Connecting, Unknown/None, Failed.
        assert_eq!(filtered_names(&view, &hosts), ["b", "c", "d", "a"]);
    }

    #[test]
    fn rebuild_tag_filter_includes_only_matching() {
        let hosts = [
            host("a", "1", &["prod"], None),
            host("b", "2", &["dev"], None),
        ];
        let mut view = HostListView {
            tag_filter: Some("prod".to_string()),
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(filtered_names(&view, &hosts), ["a"]);
    }

    #[test]
    fn rebuild_tag_filter_none_shows_all() {
        let hosts = [
            host("a", "1", &["prod"], None),
            host("b", "2", &["dev"], None),
        ];
        let mut view = HostListView::default();
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(view.filtered_indices.len(), 2);
    }

    #[test]
    fn rebuild_combines_text_tag_and_sort() {
        let hosts = [
            host("web1", "1", &["prod"], None),
            host("web2", "2", &["dev"], None),
            host("db1", "3", &["prod"], None),
        ];
        let mut view = HostListView {
            search_query: "web".to_string(),
            tag_filter: Some("prod".to_string()),
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(filtered_names(&view, &hosts), ["web1"]);
    }

    #[test]
    fn rebuild_clamps_selection_when_list_shrinks() {
        let hosts = [host("a", "1", &[], None), host("b", "2", &[], None)];
        let mut view = HostListView {
            selected: 5,
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(view.selected, 1);
    }

    #[test]
    fn rebuild_resets_selection_to_zero_when_empty() {
        let hosts = [host("a", "1", &[], None)];
        let mut view = HostListView {
            selected: 3,
            search_query: "zzz".to_string(),
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(view.selected, 0);
    }

    #[test]
    fn rebuild_preserves_selection_in_range() {
        let hosts = [
            host("a", "1", &[], None),
            host("b", "2", &[], None),
            host("c", "3", &[], None),
        ];
        let mut view = HostListView {
            selected: 1,
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(view.selected, 1);
    }

    #[test]
    fn rebuild_handles_shrunk_host_list_without_panic() {
        let many = [
            host("a", "1", &[], None),
            host("b", "2", &[], None),
            host("c", "3", &[], None),
        ];
        let mut view = HostListView::default();
        view.rebuild_filter(&many, &HashMap::new(), &HashMap::new());
        let few = [host("a", "1", &[], None)];
        view.rebuild_filter(&few, &HashMap::new(), &HashMap::new());
        assert!(view.filtered_indices.iter().all(|&i| i < few.len()));
    }

    #[test]
    fn rebuild_cpu_sort_with_empty_metrics_does_not_panic() {
        let hosts = [host("a", "1", &[], None), host("b", "2", &[], None)];
        let mut view = HostListView {
            sort_order: SortOrder::Cpu,
            ..Default::default()
        };
        view.rebuild_filter(&hosts, &HashMap::new(), &HashMap::new());
        assert_eq!(view.filtered_indices.len(), 2);
    }

    #[test]
    fn host_select_next_clamps_at_last() {
        let mut view = HostListView {
            filtered_indices: vec![0, 1],
            ..Default::default()
        };
        view.select_next();
        view.select_next();
        view.select_next();
        assert_eq!(view.selected, 1);
    }

    #[test]
    fn host_select_prev_saturates_at_zero() {
        let mut view = HostListView {
            filtered_indices: vec![0, 1],
            ..Default::default()
        };
        view.select_prev();
        assert_eq!(view.selected, 0);
    }

    #[test]
    fn host_select_next_noop_when_empty() {
        let mut view = HostListView::default();
        view.select_next();
        assert_eq!(view.selected, 0);
    }
}