purple-ssh 2.41.1

Open-source terminal SSH manager and SSH config editor. Search hundreds of hosts, sync from 16 clouds, transfer files, manage Docker and Podman over SSH, sign short-lived Vault SSH certs and expose an MCP server for AI agents. 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
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
//! Visual regression tests for every screen.
//!
//! Each test renders one screen into a `TestBackend` buffer using demo data,
//! serialises the buffer (characters plus per-cell style info) and compares
//! the result against a `.golden` baseline in `tests/visual_golden/`. Any
//! visual change to spacing, colors, text or borders fails the test.
//!
//! Regenerate baselines after intentional UI changes:
//!     ./scripts/update-golden.sh
//!
//! Implementation notes:
//! - Tests live in the binary crate (not in `tests/`) because they need
//!   access to private types (`App`, `ui::render`, `animation::AnimationState`).
//! - All tests pin the color mode to ANSI 16 (`init_with_mode(1)`) so output
//!   is deterministic across terminals (no truecolor RGB drift, no NO_COLOR
//!   stripping).
//! - Tests use a process-wide lock to serialise demo state mutations and
//!   theme initialisation across `cargo test` worker threads.

use std::path::PathBuf;
use std::sync::MutexGuard;

use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;
use ratatui::style::{Color, Modifier};

use crate::animation::AnimationState;
use crate::app::{App, Screen};
use crate::demo;
use crate::demo_flag;
use crate::preferences;
use crate::ui;

const TERM_WIDTH: u16 = 100;
const TERM_HEIGHT: u16 = 30;

/// RAII guard returned by `setup()`. Holds the cross-suite lock for the
/// duration of the test and resets the demo flag on drop so subsequent
/// non-visual tests do not observe a sticky `demo_flag::is_demo() == true`.
struct VisualGuard {
    _lock: MutexGuard<'static, ()>,
}

impl Drop for VisualGuard {
    fn drop(&mut self) {
        demo_flag::disable();
    }
}

/// Acquire the cross-suite test lock, pin ANSI 16 colors and return a guard
/// that releases the lock and resets the demo flag on drop.
///
/// The lock is shared with `preferences::tests::with_temp_prefs` because both
/// suites mutate process-wide state (`PATH_OVERRIDE`, `demo_flag::DEMO_MODE`)
/// that would otherwise race when `cargo test` runs them concurrently.
#[must_use]
fn setup() -> VisualGuard {
    let lock = preferences::GLOBAL_TEST_IO_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    ui::theme::init_with_mode(1);
    VisualGuard { _lock: lock }
}

fn golden_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/visual_golden")
}

fn golden_path(name: &str) -> PathBuf {
    golden_dir().join(format!("{name}.golden"))
}

fn color_name(c: Color) -> String {
    match c {
        Color::Reset => "Reset".into(),
        Color::Black => "Black".into(),
        Color::Red => "Red".into(),
        Color::Green => "Green".into(),
        Color::Yellow => "Yellow".into(),
        Color::Blue => "Blue".into(),
        Color::Magenta => "Magenta".into(),
        Color::Cyan => "Cyan".into(),
        Color::Gray => "Gray".into(),
        Color::DarkGray => "DarkGray".into(),
        Color::LightRed => "LightRed".into(),
        Color::LightGreen => "LightGreen".into(),
        Color::LightYellow => "LightYellow".into(),
        Color::LightBlue => "LightBlue".into(),
        Color::LightMagenta => "LightMagenta".into(),
        Color::LightCyan => "LightCyan".into(),
        Color::White => "White".into(),
        Color::Rgb(r, g, b) => format!("Rgb({r},{g},{b})"),
        Color::Indexed(i) => format!("Indexed({i})"),
    }
}

fn modifier_name(m: Modifier) -> String {
    if m.is_empty() {
        return "-".into();
    }
    let mut parts = Vec::new();
    if m.contains(Modifier::BOLD) {
        parts.push("BOLD");
    }
    if m.contains(Modifier::DIM) {
        parts.push("DIM");
    }
    if m.contains(Modifier::ITALIC) {
        parts.push("ITALIC");
    }
    if m.contains(Modifier::UNDERLINED) {
        parts.push("UNDERLINED");
    }
    if m.contains(Modifier::SLOW_BLINK) {
        parts.push("SLOW_BLINK");
    }
    if m.contains(Modifier::RAPID_BLINK) {
        parts.push("RAPID_BLINK");
    }
    if m.contains(Modifier::REVERSED) {
        parts.push("REVERSED");
    }
    if m.contains(Modifier::HIDDEN) {
        parts.push("HIDDEN");
    }
    if m.contains(Modifier::CROSSED_OUT) {
        parts.push("CROSSED_OUT");
    }
    parts.join("|")
}

/// Serialise a buffer to a deterministic string: a character grid followed by
/// a `---STYLES---` marker and one line per non-default cell with its style.
fn serialize_buffer(buf: &Buffer) -> String {
    let mut out = String::new();
    let area = buf.area;
    for y in 0..area.height {
        for x in 0..area.width {
            out.push_str(buf[(x, y)].symbol());
        }
        out.push('\n');
    }
    out.push_str("---STYLES---\n");
    for y in 0..area.height {
        for x in 0..area.width {
            let cell = &buf[(x, y)];
            let is_default_fg = matches!(cell.fg, Color::Reset);
            let is_default_bg = matches!(cell.bg, Color::Reset);
            let is_default_mod = cell.modifier.is_empty();
            if is_default_fg && is_default_bg && is_default_mod {
                continue;
            }
            out.push_str(&format!(
                "({x},{y}) fg={} bg={} mod={}\n",
                color_name(cell.fg),
                color_name(cell.bg),
                modifier_name(cell.modifier),
            ));
        }
    }
    out
}

/// Compare actual output to the golden file. When `UPDATE_GOLDEN=1` is set,
/// overwrite the golden file instead of asserting.
fn assert_golden(name: &str, actual: &str) {
    let path = golden_path(name);
    if std::env::var_os("UPDATE_GOLDEN").is_some() {
        std::fs::create_dir_all(golden_dir()).expect("create golden dir");
        std::fs::write(&path, actual).expect("write golden");
        return;
    }

    let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| {
        panic!(
            "failed to read golden {}: {e}. Run UPDATE_GOLDEN=1 cargo test --bin purple visual_regression to create it.",
            path.display()
        )
    });

    if expected != actual {
        // Write the actual output next to the golden so the diff is easy to inspect.
        let actual_path = path.with_extension("actual");
        let _ = std::fs::write(&actual_path, actual);
        panic!(
            "visual regression: {name} differs from baseline.\n  golden: {}\n  actual: {}\nIf the change is intentional, run ./scripts/update-golden.sh and review the diff.",
            path.display(),
            actual_path.display(),
        );
    }
}

/// Render the given screen into a buffer and return the serialised result.
fn render_screen(app: &mut App) -> String {
    let backend = TestBackend::new(TERM_WIDTH, TERM_HEIGHT);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    serialize_buffer(&buf)
}

// ---------------------------------------------------------------------------
// Tests (29 total). Each test pins ANSI-16 colors, builds a fresh demo app,
// switches to the target screen, renders it and compares against a golden.
// ---------------------------------------------------------------------------

#[test]
fn visual_host_list() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    let actual = render_screen(&mut app);
    assert_golden("host_list", &actual);
}

#[test]
fn visual_host_list_search() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.start_search_with("aws");
    let actual = render_screen(&mut app);
    assert_golden("host_list_search", &actual);
}

#[test]
fn visual_host_list_detail_panel() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Detail panel renders alongside the host list when view_mode is Detailed
    // and the terminal is wide enough (DETAIL_MIN_WIDTH).
    app.view_mode = crate::app::ViewMode::Detailed;
    let actual = render_screen(&mut app);
    assert_golden("host_list_detail_panel", &actual);
}

#[test]
fn visual_host_form_add() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::AddHost;
    let actual = render_screen(&mut app);
    assert_golden("host_form_add", &actual);
}

#[test]
fn visual_host_form_edit() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::EditHost {
        alias: "bastion-ams".to_string(),
    };
    let actual = render_screen(&mut app);
    assert_golden("host_form_edit", &actual);
}

#[test]
fn visual_host_detail() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::HostDetail { index: 0 };
    let actual = render_screen(&mut app);
    assert_golden("host_detail", &actual);
}

#[test]
fn visual_tunnel_list() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::TunnelList {
        alias: "bastion-ams".to_string(),
    };
    let actual = render_screen(&mut app);
    assert_golden("tunnel_list", &actual);
}

#[test]
fn visual_tunnel_form() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::TunnelForm {
        alias: "bastion-ams".to_string(),
        editing: None,
    };
    let actual = render_screen(&mut app);
    assert_golden("tunnel_form", &actual);
}

#[test]
fn visual_key_list() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::KeyList;
    let actual = render_screen(&mut app);
    assert_golden("key_list", &actual);
}

#[test]
fn visual_key_detail() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::KeyDetail { index: 0 };
    let actual = render_screen(&mut app);
    assert_golden("key_detail", &actual);
}

#[test]
fn visual_help() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::Help {
        return_screen: Box::new(Screen::HostList),
    };
    let actual = render_screen(&mut app);
    assert_golden("help", &actual);
}

#[test]
fn visual_confirm_delete() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ConfirmDelete {
        alias: "bastion-ams".to_string(),
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_delete", &actual);
}

#[test]
fn visual_snippet_picker() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::SnippetPicker {
        target_aliases: vec!["bastion-ams".to_string()],
    };
    let actual = render_screen(&mut app);
    assert_golden("snippet_picker", &actual);
}

#[test]
fn visual_snippet_form() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::SnippetForm {
        target_aliases: vec!["bastion-ams".to_string()],
        editing: None,
    };
    let actual = render_screen(&mut app);
    assert_golden("snippet_form", &actual);
}

#[test]
fn visual_snippet_output() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.snippet_output = Some(crate::app::SnippetOutputState {
        run_id: 1,
        results: vec![crate::app::SnippetHostOutput {
            alias: "bastion-ams".to_string(),
            stdout: "load average: 0.12 0.18 0.21\n".to_string(),
            stderr: String::new(),
            exit_code: Some(0),
        }],
        scroll_offset: 0,
        completed: 1,
        total: 1,
        all_done: true,
        cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
    });
    app.screen = Screen::SnippetOutput {
        snippet_name: "uptime".to_string(),
        target_aliases: vec!["bastion-ams".to_string()],
    };
    let actual = render_screen(&mut app);
    assert_golden("snippet_output", &actual);
}

#[test]
fn visual_snippet_param_form() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    let snippet = crate::snippet::Snippet {
        name: "uptime".to_string(),
        command: "uptime".to_string(),
        description: "Server uptime and load".to_string(),
    };
    // Param form requires state populated with the snippet's params (none here),
    // so build an empty SnippetParamFormState matching the snippet.
    let params: Vec<crate::snippet::SnippetParam> = Vec::new();
    app.snippet_param_form = Some(crate::app::SnippetParamFormState::new(&params));
    app.screen = Screen::SnippetParamForm {
        snippet,
        target_aliases: vec!["bastion-ams".to_string()],
    };
    let actual = render_screen(&mut app);
    assert_golden("snippet_param_form", &actual);
}

#[test]
fn visual_tag_picker() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::TagPicker;
    let actual = render_screen(&mut app);
    assert_golden("tag_picker", &actual);
}

#[test]
fn visual_theme_picker() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.ui.theme_picker_builtins = ui::theme::ThemeDef::builtins();
    app.ui.theme_picker_custom = Vec::new();
    app.ui.theme_picker_saved_name = "Purple".to_string();
    app.ui.theme_picker_state.select(Some(0));
    app.screen = Screen::ThemePicker;
    let actual = render_screen(&mut app);
    assert_golden("theme_picker", &actual);
}

#[test]
fn visual_containers() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Containers screen requires container_state. Populate from the demo cache.
    let alias = "bastion-ams".to_string();
    let cached = app
        .container_cache
        .get(&alias)
        .map(|c| c.containers.clone())
        .unwrap_or_default();
    app.container_state = Some(crate::app::ContainerState {
        alias: alias.clone(),
        askpass: None,
        runtime: Some(crate::containers::ContainerRuntime::Docker),
        containers: cached,
        list_state: ratatui::widgets::ListState::default(),
        loading: false,
        error: None,
        action_in_progress: None,
        confirm_action: None,
    });
    app.screen = Screen::Containers { alias };
    let actual = render_screen(&mut app);
    assert_golden("containers", &actual);
}

#[test]
fn visual_file_browser() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    let alias = "bastion-ams".to_string();
    // Use a deterministic empty browser state. remote_loading=true skips remote
    // I/O and local entries are intentionally empty so output is host-agnostic.
    app.file_browser = Some(crate::file_browser::FileBrowserState {
        alias: alias.clone(),
        askpass: None,
        active_pane: crate::file_browser::BrowserPane::Local,
        local_path: std::path::PathBuf::from("/demo"),
        local_entries: Vec::new(),
        local_list_state: ratatui::widgets::ListState::default(),
        local_selected: std::collections::HashSet::new(),
        local_error: None,
        remote_path: String::new(),
        remote_entries: Vec::new(),
        remote_list_state: ratatui::widgets::ListState::default(),
        remote_selected: std::collections::HashSet::new(),
        remote_error: None,
        remote_loading: true,
        show_hidden: false,
        sort: crate::file_browser::BrowserSort::Name,
        confirm_copy: None,
        transferring: None,
        transfer_error: None,
        connection_recorded: true,
    });
    app.screen = Screen::FileBrowser { alias };
    let actual = render_screen(&mut app);
    assert_golden("file_browser", &actual);
}

#[test]
fn visual_command_palette() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.palette = Some(crate::app::CommandPaletteState::new());
    let actual = render_screen(&mut app);
    assert_golden("command_palette", &actual);
}

#[test]
fn visual_bulk_tag_editor() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Bulk tag editor operates on multi_select. Populate it with a couple of demo hosts.
    app.multi_select.insert(0);
    app.multi_select.insert(1);
    app.screen = Screen::BulkTagEditor;
    let actual = render_screen(&mut app);
    assert_golden("bulk_tag_editor", &actual);
}

#[test]
fn visual_provider_list() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::Providers;
    let actual = render_screen(&mut app);
    assert_golden("provider_list", &actual);
}

#[test]
fn visual_provider_form() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ProviderForm {
        provider: "aws".to_string(),
    };
    let actual = render_screen(&mut app);
    assert_golden("provider_form", &actual);
}

#[test]
fn visual_confirm_host_key_reset() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ConfirmHostKeyReset {
        alias: "bastion-ams".to_string(),
        hostname: "bastion.example.com".to_string(),
        known_hosts_path: "/demo/.ssh/known_hosts".to_string(),
        askpass: None,
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_host_key_reset", &actual);
}

#[test]
fn visual_confirm_import() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ConfirmImport { count: 5 };
    let actual = render_screen(&mut app);
    assert_golden("confirm_import", &actual);
}

#[test]
fn visual_confirm_purge_stale() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ConfirmPurgeStale {
        aliases: vec!["aws-old-1".to_string(), "aws-old-2".to_string()],
        provider: Some("aws".to_string()),
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_purge_stale", &actual);
}

#[test]
fn visual_confirm_vault_sign() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ConfirmVaultSign {
        signable: Vec::new(),
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_vault_sign", &actual);
}

#[test]
fn visual_welcome() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::Welcome {
        has_backup: true,
        host_count: 22,
        known_hosts_count: 47,
    };
    let actual = render_screen(&mut app);
    assert_golden("welcome", &actual);
}