purple-ssh 3.15.11

Open-source terminal SSH manager that keeps ~/.ssh/config in sync with your cloud infra. Spin up a VM on AWS, GCP, Azure, Hetzner or 12 other cloud providers and it appears in your host list. Destroy it and the entry dims. Search hundreds of hosts, transfer files, manage Docker and Podman over SSH, sign Vault SSH certs. Rust TUI, MIT licensed.
Documentation
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
use std::collections::{HashMap, HashSet};

use ratatui::text::Span;

use crate::app::ping::PingStatus;
use crate::ssh_config::model::{ConfigElement, HostEntry, PatternEntry, SshConfigFile};
use crate::ui::theme;

/// Host, group, sort and view state grouped off the `App` god-struct. Holds
/// the parsed `~/.ssh/config`, the resolved host + pattern entries, the
/// display list built from them, the render cache, the undo stack for
/// deletions, the multi-select set for bulk snippet runs and all sort /
/// group / view UI-state. Pure state container.
pub struct HostState {
    pub ssh_config: SshConfigFile,
    pub list: Vec<HostEntry>,
    pub patterns: Vec<PatternEntry>,
    pub display_list: Vec<HostListItem>,
    pub render_cache: HostListRenderCache,
    pub undo_stack: Vec<DeletedHost>,
    /// Host indices selected for multi-host snippet execution (space to toggle).
    pub multi_select: HashSet<usize>,
    pub sort_mode: SortMode,
    pub group_by: GroupBy,
    pub view_mode: ViewMode,
    /// Currently active group filter. None = show all groups.
    pub group_filter: Option<String>,
    /// Ordered list of group names from the current display list.
    pub group_tab_order: Vec<String>,
    /// Host/pattern counts per group (computed before group filtering).
    pub group_host_counts: HashMap<String, usize>,
}

impl HostState {
    /// Construct from a loaded config and pre-resolved host/pattern lists.
    pub fn from_config(
        ssh_config: SshConfigFile,
        hosts: Vec<HostEntry>,
        patterns: Vec<PatternEntry>,
        display_list: Vec<HostListItem>,
    ) -> Self {
        Self {
            ssh_config,
            list: hosts,
            patterns,
            display_list,
            render_cache: HostListRenderCache::default(),
            undo_stack: Vec::new(),
            multi_select: HashSet::new(),
            sort_mode: SortMode::Original,
            group_by: GroupBy::None,
            view_mode: ViewMode::Compact,
            group_filter: None,
            group_tab_order: Vec::new(),
            group_host_counts: HashMap::new(),
        }
    }

    /// Change the group-by mode and reset any active group filter in
    /// lockstep. Callers that change `group_by` directly would leave a
    /// stale `group_filter` referring to a group that no longer exists.
    pub fn set_group_by(&mut self, by: GroupBy) {
        self.group_by = by;
        self.group_filter = None;
    }

    /// Flip the host list between Compact and Detailed view.
    pub fn toggle_view_mode(&mut self) {
        self.view_mode = match self.view_mode {
            ViewMode::Compact => ViewMode::Detailed,
            ViewMode::Detailed => ViewMode::Compact,
        };
    }

    /// Toggle multi-select membership for the host at `idx`. Returns
    /// `true` when `idx` is now selected (was inserted) and `false` when
    /// it is now unselected (was removed) so the caller can react
    /// without re-reading the set.
    pub fn toggle_multi_select(&mut self, idx: usize) -> bool {
        let inserted = !self.multi_select.contains(&idx);
        if inserted {
            self.multi_select.insert(idx);
        } else {
            self.multi_select.remove(&idx);
        }
        inserted
    }
}

#[cfg(test)]
impl Default for HostState {
    fn default() -> Self {
        Self {
            ssh_config: SshConfigFile {
                elements: Vec::new(),
                path: std::path::PathBuf::new(),
                crlf: false,
                bom: false,
            },
            list: Vec::new(),
            patterns: Vec::new(),
            display_list: Vec::new(),
            render_cache: HostListRenderCache::default(),
            undo_stack: Vec::new(),
            multi_select: HashSet::new(),
            sort_mode: SortMode::Original,
            group_by: GroupBy::None,
            view_mode: ViewMode::Compact,
            group_filter: None,
            group_tab_order: Vec::new(),
            group_host_counts: HashMap::new(),
        }
    }
}

/// An item in the display list (hosts + group headers).
#[derive(Debug, Clone)]
pub enum HostListItem {
    GroupHeader(String),
    Host { index: usize },
    Pattern { index: usize },
}

/// View mode for the host list.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ViewMode {
    Compact,
    Detailed,
}

/// Sort mode for the host list.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SortMode {
    Original,
    AlphaAlias,
    AlphaHostname,
    Frecency,
    MostRecent,
    Status,
}

impl SortMode {
    pub fn next(self) -> Self {
        match self {
            SortMode::Original => SortMode::AlphaAlias,
            SortMode::AlphaAlias => SortMode::AlphaHostname,
            SortMode::AlphaHostname => SortMode::Frecency,
            SortMode::Frecency => SortMode::MostRecent,
            SortMode::MostRecent => SortMode::Status,
            SortMode::Status => SortMode::Original,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            SortMode::Original => "config order",
            SortMode::AlphaAlias => "A-Z alias",
            SortMode::AlphaHostname => "A-Z hostname",
            SortMode::Frecency => "most used",
            SortMode::MostRecent => "most recent",
            SortMode::Status => "down first",
        }
    }

    pub fn to_key(self) -> &'static str {
        match self {
            SortMode::Original => "original",
            SortMode::AlphaAlias => "alpha_alias",
            SortMode::AlphaHostname => "alpha_hostname",
            SortMode::Frecency => "frecency",
            SortMode::MostRecent => "most_recent",
            SortMode::Status => "status",
        }
    }

    pub fn from_key(s: &str) -> Self {
        match s {
            "original" => SortMode::Original,
            "alpha_alias" => SortMode::AlphaAlias,
            "alpha_hostname" => SortMode::AlphaHostname,
            "frecency" => SortMode::Frecency,
            "most_recent" => SortMode::MostRecent,
            "status" => SortMode::Status,
            _ => SortMode::MostRecent,
        }
    }
}

/// Build health summary spans: ●23 ▲2 ✖1 ○1
/// Only includes states with count > 0. Returns empty vec if no pings.
pub fn health_summary_spans(
    ping_status: &HashMap<String, PingStatus>,
    hosts: &[HostEntry],
) -> Vec<Span<'static>> {
    health_summary_spans_for(ping_status, hosts.iter().map(|h| h.alias.as_str()))
}

/// Build health summary spans for a subset of host aliases.
/// Only includes states with count > 0. Returns empty vec if no pings.
pub fn health_summary_spans_for<'a>(
    ping_status: &HashMap<String, PingStatus>,
    aliases: impl Iterator<Item = &'a str>,
) -> Vec<Span<'static>> {
    if ping_status.is_empty() {
        return vec![];
    }
    let mut online = 0u32;
    let mut slow = 0u32;
    let mut down = 0u32;
    let mut unchecked = 0u32;
    for alias in aliases {
        match ping_status.get(alias) {
            Some(PingStatus::Reachable { .. }) => online += 1,
            Some(PingStatus::Slow { .. }) => slow += 1,
            Some(PingStatus::Unreachable) => down += 1,
            Some(PingStatus::Checking) | None => unchecked += 1,
            Some(PingStatus::Skipped) => {} // ProxyJump, excluded
        }
    }
    let mut spans = Vec::new();
    if online > 0 {
        spans.push(Span::styled(
            format!("\u{25CF}{online}"),
            theme::online_dot(),
        ));
    }
    if slow > 0 {
        if !spans.is_empty() {
            spans.push(Span::raw(" "));
        }
        spans.push(Span::styled(format!("\u{25B2}{slow}"), theme::warning()));
    }
    if down > 0 {
        if !spans.is_empty() {
            spans.push(Span::raw(" "));
        }
        spans.push(Span::styled(format!("\u{2716}{down}"), theme::error()));
    }
    if unchecked > 0 {
        if !spans.is_empty() {
            spans.push(Span::raw(" "));
        }
        spans.push(Span::styled(format!("\u{25CB}{unchecked}"), theme::muted()));
    }
    spans
}

/// Group mode for the host list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GroupBy {
    None,
    Provider,
    Tag(String),
}

impl GroupBy {
    pub fn to_key(&self) -> String {
        match self {
            GroupBy::None => "none".to_string(),
            GroupBy::Provider => "provider".to_string(),
            GroupBy::Tag(tag) => format!("tag:{}", tag),
        }
    }

    pub fn from_key(s: &str) -> Self {
        match s {
            "none" => GroupBy::None,
            "provider" => GroupBy::Provider,
            s if s.starts_with("tag:") => match s.strip_prefix("tag:") {
                Some(tag) => GroupBy::Tag(tag.to_string()),
                _ => GroupBy::None,
            },
            _ => GroupBy::None,
        }
    }

    pub fn label(&self) -> String {
        match self {
            GroupBy::None => "ungrouped".to_string(),
            GroupBy::Provider => "provider".to_string(),
            GroupBy::Tag(tag) => format!("tag: {}", tag),
        }
    }
}

/// Stores a deleted host for undo.
#[derive(Debug, Clone)]
pub struct DeletedHost {
    pub element: ConfigElement,
    pub position: usize,
}

/// Item in the ProxyJump picker list. Scored hosts (used elsewhere as
/// ProxyJump, matching a jump-host name pattern, or sharing the editing
/// host's domain suffix) are promoted above a visual separator so the
/// likely pick is at the top and the rest stays alphabetical below.
/// `SectionLabel` renders a non-selectable heading (e.g. "Suggestions")
/// above the scored section. Navigation skips both `SectionLabel` and
/// `Separator`.
#[derive(Debug, Clone, PartialEq)]
pub enum ProxyJumpCandidate {
    Host {
        alias: String,
        hostname: String,
        suggested: bool,
    },
    SectionLabel(&'static str),
    Separator,
}

/// Lazily-computed derived state that feeds the host-list renderer.
///
/// The renderer runs on every keystroke and every animation tick. Rebuilding
/// these from `hosts`/`display_list`/`history` per frame allocates thousands
/// of short-lived `String`s on hosts lists in the 500+ range. Fields are
/// `None` when dirty; the renderer populates them on first use after an
/// invalidation and subsequent frames reuse the values until the next
/// mutation calls `invalidate()`.
#[derive(Default)]
pub struct HostListRenderCache {
    /// Max width of formatted "last connected" strings across all hosts.
    /// Caches the `format_time_ago` allocations.
    pub history_width: Option<usize>,
    /// Group-header text -> host aliases in that group. Built from
    /// `display_list`, so invalidates on every sort/filter/reload.
    pub group_alias_map: Option<HashMap<String, Vec<String>>>,
}

impl HostListRenderCache {
    pub fn invalidate(&mut self) {
        self.history_width = None;
        self.group_alias_map = None;
    }
}

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

    #[test]
    fn default_is_empty() {
        let s = HostState::default();
        assert!(s.list.is_empty());
        assert!(s.patterns.is_empty());
        assert!(s.display_list.is_empty());
        assert!(s.undo_stack.is_empty());
        assert!(s.multi_select.is_empty());
        assert!(s.group_filter.is_none());
        assert!(s.group_tab_order.is_empty());
        assert!(s.group_host_counts.is_empty());
    }

    #[test]
    fn set_group_by_provider_clears_filter() {
        let mut s = HostState {
            group_filter: Some("acme".to_string()),
            ..Default::default()
        };
        s.set_group_by(GroupBy::Provider);
        assert!(matches!(s.group_by, GroupBy::Provider));
        assert!(s.group_filter.is_none());
    }

    #[test]
    fn set_group_by_none_clears_filter() {
        let mut s = HostState {
            group_by: GroupBy::Provider,
            group_filter: Some("acme".to_string()),
            ..Default::default()
        };
        s.set_group_by(GroupBy::None);
        assert!(matches!(s.group_by, GroupBy::None));
        assert!(s.group_filter.is_none());
    }

    #[test]
    fn set_group_by_tag_clears_filter() {
        let mut s = HostState {
            group_filter: Some("prod".to_string()),
            ..Default::default()
        };
        s.set_group_by(GroupBy::Tag("staging".to_string()));
        match &s.group_by {
            GroupBy::Tag(t) => assert_eq!(t, "staging"),
            _ => panic!("expected Tag, got {:?}", s.group_by),
        }
        assert!(s.group_filter.is_none());
    }

    #[test]
    fn set_group_by_overwrites_existing() {
        let mut s = HostState {
            group_by: GroupBy::Provider,
            ..Default::default()
        };
        s.set_group_by(GroupBy::None);
        assert!(matches!(s.group_by, GroupBy::None));
    }

    #[test]
    fn toggle_view_mode_compact_to_detailed() {
        let mut s = HostState::default();
        assert_eq!(s.view_mode, ViewMode::Compact);
        s.toggle_view_mode();
        assert_eq!(s.view_mode, ViewMode::Detailed);
    }

    #[test]
    fn toggle_view_mode_detailed_to_compact() {
        let mut s = HostState {
            view_mode: ViewMode::Detailed,
            ..Default::default()
        };
        s.toggle_view_mode();
        assert_eq!(s.view_mode, ViewMode::Compact);
    }

    #[test]
    fn toggle_multi_select_inserts_when_absent_and_returns_true() {
        let mut s = HostState::default();
        let now_selected = s.toggle_multi_select(3);
        assert!(now_selected);
        assert!(s.multi_select.contains(&3));
    }

    #[test]
    fn toggle_multi_select_removes_when_present_and_returns_false() {
        let mut s = HostState::default();
        s.multi_select.insert(3);
        let now_selected = s.toggle_multi_select(3);
        assert!(!now_selected);
        assert!(!s.multi_select.contains(&3));
    }

    #[test]
    fn toggle_multi_select_does_not_touch_other_indices() {
        let mut s = HostState::default();
        s.multi_select.insert(1);
        s.multi_select.insert(2);
        s.toggle_multi_select(3);
        assert!(s.multi_select.contains(&1));
        assert!(s.multi_select.contains(&2));
        assert!(s.multi_select.contains(&3));
    }
}