purple-ssh 3.15.18

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
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
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
//! 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, resets the demo flag on drop so subsequent
/// non-visual tests do not observe a sticky `demo_flag::is_demo() == true`,
/// and clears the preferences path override so later tests do not inherit
/// a stale thread-local pointer.
struct VisualGuard {
    _lock: MutexGuard<'static, ()>,
}

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

/// Acquire the cross-suite test lock, pin ANSI 16 colors, point the
/// preferences path at a non-existent file so reads (e.g. last_seen_version
/// consumed by the What's New overlay) return `None` regardless of the host
/// environment, 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.
///
/// Env-sensitivity audit: visual tests must be byte-identical on any host.
/// The consumed state is:
/// - `ui::theme` — pinned via `init_with_mode(1)`, ignores NO_COLOR/COLORTERM
/// - `preferences` — path_override below, so ~/.purple/preferences is ignored
/// - `CHANGELOG.md` — embedded via `include_str!` at compile time
/// - `CARGO_PKG_VERSION` / `PURPLE_BUILD_DATE` — compile-time env vars
///   (build date drifts by calendar day; accepted as known limitation)
#[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);
    // Point at a path that does not exist so load_* returns None. We
    // intentionally do NOT create the file — individual tests may override
    // this if they need canned preference values.
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let sentinel = std::env::temp_dir().join(format!(
        "purple_vistest_nonexistent_{}_{}",
        std::process::id(),
        nanos,
    ));
    preferences::set_path_override(sentinel);
    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. 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.hosts_state
        .set_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_tunnels_overview() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    let actual = render_screen(&mut app);
    assert_golden("tunnels_overview", &actual);
}

#[test]
fn visual_tunnels_overview_active() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    // Seed a deterministic live snapshot for the host the cursor lands
    // on after `build_demo_app` (sorted alphabetically the first row is
    // bastion-ams). The detail panel reads from `demo_live_snapshots`
    // so the LIVE/CLIENTS/EVENTS cards render byte-stably.
    demo::seed_tunnel_live_snapshots(&mut app);
    app.ui.tunnels_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("tunnels_overview_active", &actual);
}

#[test]
fn visual_tunnels_overview_active_tall() {
    // Verifies the adaptive layout: on a tall terminal the detail
    // panel grows the sparkline (up to 6 rows) and surfaces more
    // CLIENTS / EVENTS rows instead of leaving empty padding at the
    // bottom of the panel.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    demo::seed_tunnel_live_snapshots(&mut app);
    app.ui.tunnels_overview_state_mut().select(Some(0));
    let backend = TestBackend::new(120, 50);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    let actual = serialize_buffer(&buf);
    assert_golden("tunnels_overview_active_tall", &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_tunnel_host_picker() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    app.screen = Screen::TunnelHostPicker;
    app.ui.tunnel_host_picker_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("tunnel_host_picker", &actual);
}

#[test]
fn visual_tunnel_host_picker_filtered() {
    // Picker with an active fuzzy query — title should switch to the
    // "X of Y" form and the list should shrink to matching hosts.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    app.screen = Screen::TunnelHostPicker;
    app.ui.set_tunnel_host_picker_query("db".to_string());
    app.ui.tunnel_host_picker_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("tunnel_host_picker_filtered", &actual);
}

#[test]
fn visual_container_host_picker() {
    // Picker shown after pressing `a` on the Containers tab. Mirrors the
    // tunnel-host-picker geometry but draws over the containers base
    // page instead of the tunnels base page.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ContainerHostPicker;
    app.ui.container_host_picker_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("container_host_picker", &actual);
}

/// Keys tab default layout: master list + Vault SSH TTL strip on top.
/// The demo config has at least one host with a `purple:vault-ssh` role
/// and a populated `vault.cert_cache` so the strip renders with several
/// gauge rows in distinct color tiers.
#[test]
fn visual_keys_overview() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("keys_overview", &actual);
}

/// Keys tab with the cursor on a hardware-bound `sk-ed25519` key. The
/// detail pane exercises the hardware-token Drunken Bishop variant and
/// the `sk-ed` algorithm badge styling.
#[test]
fn visual_keys_overview_hardware_key() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    // Demo key #1 is yubikey_work (sk-ED25519).
    app.keys.list_state_mut().select(Some(1));
    let actual = render_screen(&mut app);
    assert_golden("keys_overview_hardware", &actual);
}

/// Keys tab without any configured Vault SSH role. The strip stays hidden
/// and the master pane takes the full vertical space minus the top bar
/// and footer. Built by clearing the demo host list's `vault_ssh` field.
#[test]
fn visual_keys_overview_no_vault() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    for host in app.hosts_state.list_mut() {
        host.vault_ssh = None;
    }
    app.vault.clear_cert_cache();
    let actual = render_screen(&mut app);
    assert_golden("keys_overview_no_vault", &actual);
}

/// Keys tab on a wide + tall terminal (200x40). At this size the hero
/// renders three side-by-side cards (Keys list / Randomart / Info) and
/// the Linked Hosts grid below. Pins the layout under visual regression
/// so a future refactor cannot silently regress it.
#[test]
fn visual_keys_overview_two_cards() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    let backend = TestBackend::new(200, 40);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    assert_golden("keys_overview_two_cards", &serialize_buffer(&buf));
}

/// Keys tab on a wide terminal with 31 synthetic linked hosts so the
/// Linked Hosts card distributes across three balanced columns and the
/// Drunken Bishop card renders at its large 25×13 size. Uses a real
/// 32-byte SHA256 fingerprint so the bishop walk fills the larger grid
/// with the same density as the canonical 17×9 OpenSSH art.
#[test]
fn visual_keys_overview_many_linked_hosts() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    app.keys.list_mut()[0].fingerprint =
        "SHA256:1LayGj+CVIvJfOnQqADAT52DoJHhSa30feF/23wbRuE".to_string();
    let synthetic: Vec<String> = (1..=31).map(|i| format!("host-{:02}", i)).collect();
    app.keys.list_mut()[0].linked_hosts = synthetic.clone();
    for alias in &synthetic {
        app.hosts_state
            .list_mut()
            .push(crate::ssh_config::model::HostEntry {
                alias: alias.clone(),
                hostname: format!("10.0.{}.{}", alias.len(), alias.len() * 3 % 250),
                ..Default::default()
            });
    }
    let backend = TestBackend::new(200, 40);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    assert_golden("keys_overview_many_linked_hosts", &serialize_buffer(&buf));
}

/// Keys tab on a narrow terminal (80 cols, below `HERO_MIN_WIDTH = 60`
/// after the Keys list eats its share). The hero falls back to a single
/// stacked card. Confirms the responsive collapse path renders without
/// the side-by-side info card.
#[test]
fn visual_keys_overview_narrow() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    let backend = TestBackend::new(80, 30);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    assert_golden("keys_overview_narrow", &serialize_buffer(&buf));
}

/// Keys tab in search mode with a query that matches a subset of keys.
/// Confirms the search bar renders above the column header, the master
/// pane title shows `<query> (N/M)` with the filtered count, and the
/// list contains only matching rows.
#[test]
fn visual_keys_overview_search() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.search.set_query(Some("rsa".to_string()));
    app.keys.list_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("keys_overview_search", &actual);
}

/// Keys tab in search mode with a query that matches nothing. Confirms
/// the master pane renders an empty list with the search bar's
/// filtered count showing 0.
#[test]
fn visual_keys_overview_search_no_match() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.search.set_query(Some("xyzzy".to_string()));
    app.keys.list_state_mut().select(None);
    let actual = render_screen(&mut app);
    assert_golden("keys_overview_search_no_match", &actual);
}

/// Push-host picker freshly opened: no hosts selected yet. Vault-ssh
/// hosts render with `[-]` and a `(vault)` tag. Confirms the checkbox
/// column, vault-disabled style and overlay title.
#[test]
fn visual_keys_push_picker() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    app.screen = Screen::KeyPushPicker { key_index: 0 };
    app.keys.push_mut().list_state.select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("keys_push_picker", &actual);
}

/// Push-host picker with two hosts toggled on. Confirms the `[x]` mark
/// renders for selected non-vault hosts and the title shows the
/// "<N> selected of <total>" tally.
#[test]
fn visual_keys_push_picker_selected() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Lock the demo host count so the picker title `2 selected of 31
    // (N eligible)` is stable under demo-data drift. If a new host is
    // added or removed from the demo this assertion fails with a clear
    // message instead of an opaque golden diff.
    assert_eq!(
        app.hosts_state.list().len(),
        31,
        "demo host count drifted; update this assertion and regenerate the golden"
    );
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_state_mut().select(Some(0));
    app.screen = Screen::KeyPushPicker { key_index: 0 };
    app.keys.push_mut().list_state.select(Some(0));
    // Pick two non-vault hosts so the selected glyph renders.
    let to_select: Vec<String> = app
        .hosts_state
        .list()
        .iter()
        .filter(|h| h.vault_ssh.is_none())
        .take(2)
        .map(|h| h.alias.clone())
        .collect();
    for a in to_select {
        app.keys.push_mut().selected.insert(a);
    }
    let actual = render_screen(&mut app);
    assert_golden("keys_push_picker_selected", &actual);
}

/// Push confirm dialog with the selected aliases listed. Footer uses
/// the destructive action-verb pair `push` / `keep` via
/// `design::confirm_footer_destructive`.
#[test]
fn visual_keys_push_confirm() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    let aliases: Vec<String> = app
        .hosts_state
        .list()
        .iter()
        .filter(|h| h.vault_ssh.is_none())
        .take(3)
        .map(|h| h.alias.clone())
        .collect();
    app.keys.push_mut().committed = aliases;
    app.screen = Screen::ConfirmKeyPush { key_index: 0 };
    let actual = render_screen(&mut app);
    assert_golden("keys_push_confirm", &actual);
}

/// Keys tab with zero keys discovered. Shows the empty-state hint inside
/// the master pane. Confirms the empty path renders the hint message and
/// not the table header.
#[test]
fn visual_keys_overview_empty() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Keys;
    app.keys.list_mut().clear();
    app.keys.list_state_mut().select(None);
    let actual = render_screen(&mut app);
    assert_golden("keys_overview_empty", &actual);
}

#[test]
fn visual_host_list_empty() {
    // Fresh install: no hosts in ~/.ssh/config. The Hosts tab must
    // render ONE centred TabEmpty card naming `a add` and `S sync`
    // as the next actions; the detail panel stays a quiet bordered
    // placeholder (no "Select a host to see details." floating top-right).
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.hosts_state.list_mut().clear();
    app.hosts_state.patterns_mut().clear();
    app.hosts_state.display_list_mut().clear();
    app.hosts_state.ssh_config_mut().elements = Vec::new();
    app.tunnels.clear_active();
    app.tunnels.demo_live_snapshots_mut().clear();
    let actual = render_screen(&mut app);
    assert_golden("host_list_empty", &actual);
}

#[test]
fn visual_containers_overview_empty() {
    // Fresh-install state: no container_cache entries. The Containers
    // tab must render ONE centred TabEmpty card (no duplicate "No
    // containers cached yet." in the detail panel).
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.container_state.clear_cache();
    let actual = render_screen(&mut app);
    assert_golden("containers_overview_empty", &actual);
}

#[test]
fn visual_tunnels_overview_empty() {
    // No tunnel rules configured anywhere. The Tunnels tab must render
    // one centred TabEmpty card explaining how to add one. Easiest way
    // to force "no rules" without restructuring the demo SSH config is
    // to swap in a config that has no Host blocks at all.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    app.hosts_state.ssh_config_mut().elements = Vec::new();
    app.hosts_state.list_mut().clear();
    app.tunnels.clear_active();
    app.tunnels.demo_live_snapshots_mut().clear();
    let actual = render_screen(&mut app);
    assert_golden("tunnels_overview_empty", &actual);
}

#[test]
fn visual_containers_overview() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.ui.containers_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("containers_overview", &actual);
}

/// AlphaContainer sort mode: flat list, no host headers, HOST
/// column visible per-row. Specifically pins the regression where
/// `host_count` was being read from header items (zero in this mode)
/// and the stats title rendered "0 hosts".
#[test]
fn visual_containers_overview_alpha_container_mode() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.containers_overview.sort_mode = crate::app::ContainersSortMode::AlphaContainer;
    app.ui.containers_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("containers_overview_alpha_container", &actual);
}

/// At 200 cols the detail panel renders alongside the list. The panel
/// is 96 cols wide (twice the host-detail width) and the list takes the
/// remainder. Cursor placed on the first Container row of the first
/// non-folded host so the panel exercises the container branch rather
/// than the host-summary branch (covered separately by
/// `visual_containers_overview_host_detail`). Height set to 40 so the
/// LOGS card has visible inner rows beyond just open/close borders.
#[test]
fn visual_containers_overview_with_detail() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    let items = crate::ui::containers_overview::visible_items(&app);
    let first_container = items
        .iter()
        .position(|i| i.as_container().is_some())
        .expect("demo cache has at least one container");
    app.ui
        .containers_overview_state_mut()
        .select(Some(first_container));
    let backend = TestBackend::new(200, 60);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    let actual = serialize_buffer(&buf);
    assert_golden("containers_overview_with_detail", &actual);
}

/// Podman snapshot. Cursor parked on the podman-edge group so the
/// detail panel shows the host summary for the only podman host in
/// the demo. Pins the empty-Status rendering and the inspect-driven
/// state-glyph fallback (loki exited with code 137 via inspect cache
/// only, since podman emits no Status string).
#[test]
fn visual_containers_overview_podman_host_detail() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    let items = crate::ui::containers_overview::visible_items(&app);
    let podman_header = items
        .iter()
        .position(|i| match i {
            crate::ui::containers_overview::ContainerListItem::HostHeader { alias, .. } => {
                alias == "podman-edge"
            }
            _ => false,
        })
        .expect("podman-edge header in demo");
    app.ui
        .containers_overview_state_mut()
        .select(Some(podman_header));
    let backend = TestBackend::new(200, 60);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    let actual = serialize_buffer(&buf);
    assert_golden("containers_overview_podman_host_detail", &actual);
}

/// Sibling of the host-header variant: cursor parked on a running
/// podman container row so the detail panel shows the per-container
/// card with the docker.io/library/ image and empty docker-style
/// Status synthesized into the lower-case state label.
#[test]
fn visual_containers_overview_podman_container_detail() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    let items = crate::ui::containers_overview::visible_items(&app);
    let caddy_row = items
        .iter()
        .position(|i| match i.as_container() {
            Some(row) => row.alias == "podman-edge" && row.name == "caddy",
            None => false,
        })
        .expect("podman-edge/caddy in demo");
    app.ui
        .containers_overview_state_mut()
        .select(Some(caddy_row));
    let backend = TestBackend::new(200, 60);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    let actual = serialize_buffer(&buf);
    assert_golden("containers_overview_podman_container_detail", &actual);
}

/// Sibling of `visual_containers_overview_with_detail`: cursor parked
/// on the first host-divider row so the detail panel renders the
/// per-host summary (running/exited/total, runtime, last sync, fold
/// state, key reminder). Pins the header-detail render path against
/// drift now that dividers are first-class selection targets.
#[test]
fn visual_containers_overview_host_detail() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    let items = crate::ui::containers_overview::visible_items(&app);
    let first_header = items
        .iter()
        .position(|i| i.is_header())
        .expect("AlphaHost mode emits a header before the first container");
    app.ui
        .containers_overview_state_mut()
        .select(Some(first_header));
    let backend = TestBackend::new(200, 60);
    let mut terminal = Terminal::new(backend).expect("create terminal");
    let mut anim = AnimationState::default();
    terminal
        .draw(|frame| ui::render(frame, &mut app, &mut anim))
        .expect("render frame");
    let buf = terminal.backend().buffer().clone();
    let actual = serialize_buffer(&buf);
    assert_golden("containers_overview_host_detail", &actual);
}

#[test]
fn visual_container_logs() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ContainerLogs {
        alias: "aws-api-staging".to_string(),
        container_id: "f9a0b1c2d3e4".to_string(),
        container_name: "api".to_string(),
        body: vec![
            "2026-05-09 19:41:58  10.0.0.42  GET /api/v1/health 200 17ms".to_string(),
            "2026-05-09 19:42:01  198.51.100.7  POST /webhooks/github 202 41ms".to_string(),
            "2026-05-09 19:42:05  upstream timed out (110: Operation timed out)".to_string(),
            "2026-05-09 19:42:11  10.0.0.42  GET /api/v1/health 200 16ms".to_string(),
        ],
        fetched_at: crate::demo_flag::now_secs() - 3,
        error: None,
        scroll: 0,
        last_render_height: 0,
        search: None,
    };
    let actual = render_screen(&mut app);
    assert_golden("container_logs", &actual);
}

#[test]
fn visual_container_logs_search_active() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    let body = vec![
        "2026-05-09 19:41:58  10.0.0.42  GET /api/v1/health 200 17ms".to_string(),
        "2026-05-09 19:42:01  198.51.100.7  POST /webhooks/github 202 41ms".to_string(),
        "2026-05-09 19:42:05  upstream timed out (110: Operation timed out)".to_string(),
        "2026-05-09 19:42:11  10.0.0.42  GET /api/v1/health 200 16ms".to_string(),
    ];
    // Hand-built post-Enter state: query confirmed, three hits across
    // /api/v1/health and the GET lines, cursor parked on the first.
    let matches: Vec<usize> = body
        .iter()
        .enumerate()
        .filter_map(|(idx, line)| {
            if crate::handler::container_logs::matches_line(line, "api") {
                Some(idx)
            } else {
                None
            }
        })
        .collect();
    app.screen = Screen::ContainerLogs {
        alias: "aws-api-staging".to_string(),
        container_id: "f9a0b1c2d3e4".to_string(),
        container_name: "api".to_string(),
        body,
        fetched_at: crate::demo_flag::now_secs() - 3,
        error: None,
        scroll: 0,
        last_render_height: 0,
        search: Some(crate::app::ContainerLogsSearch {
            query: "api".to_string(),
            matches,
            current: 0,
            cursor_pos: 3,
        }),
    };
    let actual = render_screen(&mut app);
    assert_golden("container_logs_search_active", &actual);
}

#[test]
fn visual_confirm_container_restart() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ConfirmContainerRestart {
        alias: "aws-api-staging".to_string(),
        container_id: "f9a0b1c2d3e4".to_string(),
        container_name: "api".to_string(),
        project: Some("aws-api-staging".to_string()),
        uptime: Some("2d".to_string()),
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_container_restart", &actual);
}

#[test]
fn visual_confirm_container_stop() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ConfirmContainerStop {
        alias: "aws-api-staging".to_string(),
        container_id: "f9a0b1c2d3e4".to_string(),
        container_name: "api".to_string(),
        project: Some("aws-api-staging".to_string()),
        uptime: Some("2d".to_string()),
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_container_stop", &actual);
}

#[test]
fn visual_confirm_stack_restart() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ConfirmStackRestart {
        alias: "aws-api-staging".to_string(),
        project: "aws-api-staging".to_string(),
        members: vec![
            crate::app::StackMember {
                container_id: "f9a0b1c2d3e4".to_string(),
                container_name: "api".to_string(),
                uptime: Some("2d".to_string()),
            },
            crate::app::StackMember {
                container_id: "a1b2c3d4e5f6".to_string(),
                container_name: "datadog-agent".to_string(),
                uptime: Some("2d".to_string()),
            },
            crate::app::StackMember {
                container_id: "11223344aabb".to_string(),
                container_name: "nginx".to_string(),
                uptime: Some("2d".to_string()),
            },
        ],
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_stack_restart", &actual);
}

#[test]
fn visual_confirm_host_restart_all() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ConfirmHostRestartAll {
        alias: "aws-api-staging".to_string(),
        members: vec![
            crate::app::StackMember {
                container_id: "f9a0b1c2d3e4".to_string(),
                container_name: "api".to_string(),
                uptime: Some("2d".to_string()),
            },
            crate::app::StackMember {
                container_id: "a1b2c3d4e5f6".to_string(),
                container_name: "datadog-agent".to_string(),
                uptime: Some("2d".to_string()),
            },
            crate::app::StackMember {
                container_id: "11223344aabb".to_string(),
                container_name: "nginx".to_string(),
                uptime: Some("2d".to_string()),
            },
        ],
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_host_restart_all", &actual);
}

#[test]
fn visual_confirm_host_stop_all() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ConfirmHostStopAll {
        alias: "aws-api-staging".to_string(),
        members: vec![
            crate::app::StackMember {
                container_id: "f9a0b1c2d3e4".to_string(),
                container_name: "api".to_string(),
                uptime: Some("2d".to_string()),
            },
            crate::app::StackMember {
                container_id: "a1b2c3d4e5f6".to_string(),
                container_name: "datadog-agent".to_string(),
                uptime: Some("2d".to_string()),
            },
        ],
    };
    let actual = render_screen(&mut app);
    assert_golden("confirm_host_stop_all", &actual);
}

/// Containers overview after the user pressed `v` to fold the detail
/// panel. Verifies the list takes the full body width and the footer
/// flips to `v detail`.
#[test]
fn visual_containers_overview_compact() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.containers_overview.view_mode = crate::app::ViewMode::Compact;
    app.ui.containers_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("containers_overview_compact", &actual);
}

/// Containers overview with one host group folded via Space. The
/// folded host's containers vanish from the list and the divider's
/// suffix flips to `(N hidden)`.
#[test]
fn visual_containers_overview_collapsed_group() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.containers_overview
        .collapsed_hosts
        .insert("aws-api-staging".to_string());
    app.ui.containers_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("containers_overview_collapsed_group", &actual);
}

/// Container in `paused` state. Exercises the warning-tier glyph
/// (`ICON_PAUSED`) and colour path for transitional container states.
/// Counterpart of the existing running/exited goldens which cover the
/// online and stopped tiers.
#[test]
fn visual_containers_overview_paused() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    if let Some(entry) = app.container_state.cache_entry_mut("bastion-ams") {
        if let Some(first) = entry.containers.first_mut() {
            first.state = "paused".to_string();
            first.status = "Paused".to_string();
        }
    }
    app.ui.containers_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("containers_overview_paused", &actual);
}

/// Container in `restarting` state. Exercises the warning-tier glyph
/// for the transitional restart path, distinct from `paused`.
#[test]
fn visual_containers_overview_restarting() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    if let Some(entry) = app.container_state.cache_entry_mut("db-primary") {
        if let Some(first) = entry.containers.first_mut() {
            first.state = "restarting".to_string();
            first.status = "Restarting (1) 2 seconds ago".to_string();
        }
    }
    app.ui.containers_overview_state_mut().select(Some(0));
    let actual = render_screen(&mut app);
    assert_golden("containers_overview_restarting", &actual);
}

#[test]
fn visual_container_exec_prompt() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.screen = Screen::ContainerExecPrompt {
        alias: "aws-api-staging".to_string(),
        container_id: "f9a0b1c2d3e4".to_string(),
        container_name: "api".to_string(),
        query: "tail -n 50 /var/log/app.log".to_string(),
    };
    let actual = render_screen(&mut app);
    assert_golden("container_exec_prompt", &actual);
}

#[test]
fn visual_tunnels_overview_delete_confirm() {
    // Pending-delete confirmation footer rendered over the overview.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    app.ui.tunnels_overview_state_mut().select(Some(0));
    app.tunnels.request_delete(0);
    let actual = render_screen(&mut app);
    assert_golden("tunnels_overview_delete_confirm", &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.snippets
        .set_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.snippets
        .set_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_mut().builtins = ui::theme::ThemeDef::builtins();
    app.ui.theme_picker_mut().custom = Vec::new();
    app.ui.theme_picker_mut().saved_name = "Purple".to_string();
    app.ui.theme_picker_mut().list.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_state
        .cache_entry(&alias)
        .map(|c| c.containers.clone())
        .unwrap_or_default();
    app.container_session = Some(crate::app::ContainerSession {
        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_session = Some(crate::file_browser::FileBrowserSession {
        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_jump() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.jump = Some(crate::app::JumpState::default());
    app.recompute_jump_hits();
    let actual = render_screen(&mut app);
    assert_golden("jump", &actual);
}

#[test]
fn visual_jump_query() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.jump = Some(crate::app::JumpState::default());
    if let Some(p) = app.jump.as_mut() {
        for c in "files".chars() {
            p.push_query(c);
        }
    }
    app.recompute_jump_hits();
    let actual = render_screen(&mut app);
    assert_golden("jump_query", &actual);
}

#[test]
fn visual_jump_no_results() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.jump = Some(crate::app::JumpState::default());
    if let Some(p) = app.jump.as_mut() {
        for c in "zzzqqq".chars() {
            p.push_query(c);
        }
    }
    app.recompute_jump_hits();
    let actual = render_screen(&mut app);
    assert_golden("jump_no_results", &actual);
}

#[test]
fn visual_jump_with_recents() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    let mut state = crate::app::JumpState::default();
    // Seed two recents: one host, one action. Exercises the
    // RECENT-section render path that visual_jump cannot.
    let n_action = crate::app::JumpAction::all()
        .iter()
        .find(|a| a.key == 'n')
        .copied()
        .expect("'n' (What's new) action present");
    state.set_recents(vec![
        crate::app::JumpHit::Host(crate::app::HostHit {
            alias: "bastion-ams".into(),
            hostname: "bastion.ams.example".into(),
            tags: vec![],
            provider: None,
            user: String::new(),
            identity_file: String::new(),
            proxy_jump: String::new(),
            vault_ssh: None,
        }),
        crate::app::JumpHit::Action(n_action),
    ]);
    app.jump = Some(state);
    app.recompute_jump_hits();
    let actual = render_screen(&mut app);
    assert_golden("jump_with_recents", &actual);
}

#[test]
fn visual_jump_over_tunnels() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Tunnels;
    app.jump = Some(crate::app::JumpState::for_mode(
        crate::app::JumpMode::Tunnels,
    ));
    app.recompute_jump_hits();
    let actual = render_screen(&mut app);
    assert_golden("jump_over_tunnels", &actual);
}

#[test]
fn visual_jump_over_containers() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.top_page = crate::app::TopPage::Containers;
    app.jump = Some(crate::app::JumpState::for_mode(
        crate::app::JumpMode::Containers,
    ));
    app.recompute_jump_hits();
    let actual = render_screen(&mut app);
    assert_golden("jump_over_containers", &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.hosts_state.multi_select_mut().insert(0);
    app.hosts_state.multi_select_mut().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 {
        id: crate::providers::config::ProviderConfigId::bare("aws"),
    };
    let actual = render_screen(&mut app);
    assert_golden("provider_form", &actual);
}

#[test]
fn visual_provider_form_label_entry() {
    // Issue #51: when the user adds an N-th labeled config (with at least one
    // labeled section already present), the form opens with a `Label` input
    // prepended. The golden locks in the visual placement so a future field
    // reshuffle or omission of the prepend in visible_fields is caught.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::ProviderForm {
        id: crate::providers::config::ProviderConfigId::labeled("aws", ""),
    };
    // Replicate what open_add_config_flow's `_ =>` branch would do, without
    // depending on demo data layout. Label is the focused field; the form
    // sits in collapsed mode like a freshly opened add flow.
    *app.providers.form_mut() = crate::app::ProviderFormFields {
        label: String::new(),
        label_entry: true,
        url: String::new(),
        token: String::new(),
        profile: String::new(),
        project: String::new(),
        compartment: String::new(),
        regions: String::new(),
        alias_prefix: "aws".to_string(),
        user: "root".to_string(),
        identity_file: String::new(),
        verify_tls: true,
        auto_sync: true,
        vault_role: String::new(),
        vault_addr: String::new(),
        focused_field: crate::app::ProviderFormField::Label,
        cursor_pos: 0,
        expanded: false,
    };
    let actual = render_screen(&mut app);
    assert_golden("provider_form_label_entry", &actual);
}

#[test]
fn visual_provider_label_migration() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Seed pending state as if the user just hit `a` on a single-bare-config
    // provider; the screen prompts for both labels with focus on the new one.
    app.providers
        .set_pending_label_migration(Some(crate::app::PendingLabelMigration {
            provider: "hetzner".to_string(),
            existing_label: "default".to_string(),
            new_label: String::new(),
            focused: crate::app::LabelMigrationField::Existing,
            cursor_pos: "default".chars().count(),
        }));
    app.screen = Screen::ProviderLabelMigration {
        provider: "hetzner".to_string(),
    };
    let actual = render_screen(&mut app);
    assert_golden("provider_label_migration", &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);
}

#[test]
fn visual_whats_new() {
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.screen = Screen::WhatsNew(crate::app::WhatsNewState::default());
    let fixture = std::fs::read_to_string("tests/fixtures/changelog/simple.md").unwrap();
    crate::changelog::set_test_override(fixture);
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let actual = render_screen(&mut app);
        assert_golden("whats_new", &actual);
    }));
    crate::changelog::clear_test_override();
    if let Err(e) = result {
        std::panic::resume_unwind(e);
    }
}

// ---------------------------------------------------------------------------
// Detail-panel branch coverage tests. Each test targets a sub-section of
// detail_panel::render that is not exercised by the existing
// host_list_detail_panel golden.
// ---------------------------------------------------------------------------

/// Select a host by alias in the main list so detail_panel renders it.
fn select_host_by_alias(app: &mut App, alias: &str) {
    use crate::app::HostListItem;
    let pos = app.hosts_state.display_list().iter().position(|item| {
        if let HostListItem::Host { index } = item {
            app.hosts_state
                .list()
                .get(*index)
                .map(|h| h.alias == alias)
                .unwrap_or(false)
        } else {
            false
        }
    });
    app.ui.list_state_mut().select(pos);
}

#[test]
fn visual_host_detail_vault_expired() {
    // Exercises the VAULT SSH section with CertStatus::Expired:
    // shows "Expired" in error style and "(press V to sign)" affordance.
    // gateway-vpn has a direct vault-ssh role (not inherited) and no provider
    // so the role line takes the non-inherited path.
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.vault.insert_cert(
        "gateway-vpn".to_string(),
        (
            std::time::Instant::now(),
            crate::vault_ssh::CertStatus::Expired,
            None,
        ),
    );
    select_host_by_alias(&mut app, "gateway-vpn");
    app.hosts_state
        .set_view_mode(crate::app::ViewMode::Detailed);
    let actual = render_screen(&mut app);
    assert_golden("host_detail_vault_expired", &actual);
}

#[test]
fn visual_host_detail_long_proxy_chain() {
    // Exercises the ROUTE section with a 3-hop ProxyJump chain.
    // customer-db-1 already jumps via customer-jump. We extend its
    // proxy_jump to include two additional known hosts so the route
    // visualisation renders three intermediate hop lines.
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Inject a 3-hop chain: customer-jump, bastion-ams, gateway-vpn
    // All three are in the demo host list, so they render as known hops.
    if let Some(h) = app
        .hosts_state
        .list_mut()
        .iter_mut()
        .find(|h| h.alias == "customer-db-1")
    {
        h.proxy_jump = "customer-jump,bastion-ams,gateway-vpn".to_string();
    }
    select_host_by_alias(&mut app, "customer-db-1");
    app.hosts_state
        .set_view_mode(crate::app::ViewMode::Detailed);
    let actual = render_screen(&mut app);
    assert_golden("host_detail_long_proxy_chain", &actual);
}

#[test]
fn visual_host_detail_no_provider_tag() {
    // Exercises the detail panel for a host with no provider, no provider
    // metadata and no vault role. The Tags section still renders (user tags
    // present) but the Provider metadata and Vault SSH sections are absent.
    // prod-eu2 has user tags, vault-ssh, no provider. We clear the vault
    // cert cache for it so the status falls back to "Not signed".
    let _g = setup();
    let mut app = demo::build_demo_app();
    app.vault.remove_cert("prod-eu2");
    select_host_by_alias(&mut app, "prod-eu2");
    app.hosts_state
        .set_view_mode(crate::app::ViewMode::Detailed);
    let actual = render_screen(&mut app);
    assert_golden("host_detail_no_provider_tag", &actual);
}

#[test]
fn visual_host_detail_no_containers() {
    // Exercises the detail panel for a host that has no entry in the
    // container_state cache. The CONTAINERS section must be absent.
    // prod-eu1 has user tags, vault-ssh (with an inherited provider role
    // absent since there is no provider), yubikey identity. The demo
    // container cache has no entry for it.
    let _g = setup();
    let mut app = demo::build_demo_app();
    // Ensure there is definitely no container cache entry.
    app.container_state.remove_cache_entry("prod-eu1");
    select_host_by_alias(&mut app, "prod-eu1");
    app.hosts_state
        .set_view_mode(crate::app::ViewMode::Detailed);
    let actual = render_screen(&mut app);
    assert_golden("host_detail_no_containers", &actual);
}

#[test]
fn visual_host_detail_with_tags() {
    // Exercises the Tags section together with the Provider metadata section.
    // aws-api-prod carries user tags, provider tags (via provider comment),
    // provider metadata (region, instance, os, status) and an inherited
    // vault role from the aws provider config. This is the densest path
    // through the lower half of detail_panel::render.
    let _g = setup();
    let mut app = demo::build_demo_app();
    select_host_by_alias(&mut app, "aws-api-prod");
    app.hosts_state
        .set_view_mode(crate::app::ViewMode::Detailed);
    let actual = render_screen(&mut app);
    assert_golden("host_detail_with_tags", &actual);
}