ltop 0.2.5

btop-styled TUI monitoring only local network, LAN neighbours and disk I/O
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
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
//! ltop: btop-styled TUI monitor (net / lan / disk io / conns / procs)

pub mod app;
pub mod collect;
pub mod config;
pub mod log;
pub mod replay;
pub mod report;
pub mod snapshot;
pub mod theme;
pub mod theme_data;
pub mod ui;
pub mod watch;

use std::io::{self, stdout, Write};
use std::time::{Duration, Instant};

use anyhow::Result;
use crossterm::{
    event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
        KeyboardEnhancementFlags, MouseEventKind, PopKeyboardEnhancementFlags,
        PushKeyboardEnhancementFlags,
    },
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};

use app::{App, MenuState};

type Tui = Terminal<CrosstermBackend<io::Stdout>>;

/// `--help`/`-h`、`--version`/`-V` 在任何副作用(目录迁移/主题初始化/开终端)之前短路
fn early_exit(args: &[String]) -> Option<Result<()>> {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        // argv[0] 的文件名即调用名(官方只发 ltop;用户自建软链别名同效),
        // 取不到回落 ltop
        let prog = args
            .first()
            .and_then(|a| std::path::Path::new(a).file_name())
            .and_then(|n| n.to_str())
            .unwrap_or("ltop");
        println!("{}", usage_text(prog));
        return Some(Ok(()));
    }
    if args.iter().any(|a| a == "--version" || a == "-V") {
        println!("ltop {}", env!("CARGO_PKG_VERSION"));
        return Some(Ok(()));
    }
    // 未知旗标明确报错:静默忽略会让 typo 直接落进 TUI(--json 打错时
    // 用户以为拿到了 JSON)
    let known = [
        "--json",
        "--schema",
        "--dump",
        "--log",
        "--log-interval",
        "--follow-theme",
        "--replay",
        "--top",
        "--csv",
        "--help",
        "-h",
        "--version",
        "-V",
    ];
    if let Some(bad) = args
        .iter()
        .skip(1)
        .find(|a| a.starts_with("--") && !known.contains(&a.as_str()))
    {
        eprintln!("ltop: unknown option {bad} (try --help)");
        return Some(Err(anyhow::anyhow!("unknown option")));
    }
    None
}

/// 与 `--dump`/`--replay`/`--log` 的实际处理一一对应;改参数先改这里。
/// USAGE 行按调用名显示:用户可自建软链别名(`ln -s ltop <名>`),
/// 软链指向同一程序,-h 自然跟随调用名
fn usage_text(prog: &str) -> String {
    format!(
        "ltop v{} — btop-styled TUI monitoring for local network, LAN neighbours and disk I/O

USAGE:
    {prog} [OPTIONS]

    (no options)            run the TUI
    watch [OPTIONS]         headless capture to a schema-v1 JSONL file
    report <FILE> [OPTIONS] window summary of a watch/monlog JSONL (--json for AI)
    --json                  AI-friendly structured snapshot (JSON, schema v1)
    --schema                field reference for --json (machine-readable)
    --dump                  one-shot diagnostic dump to stdout, then exit
    --log                   start the TUI with the monitoring log enabled
    --log-interval <MS>     monitoring log interval in ms (with --log; default from settings)
    --follow-theme          live-follow Omarchy theme changes while running (default off)
    --replay [FILE]         replay/analyse the latest session log (or a given JSONL file)
    --top <N>               replay: report the top N processes (default 15)
    --csv <OUT>             replay: also export per-process deltas as CSV
    -h, --help              print this help
    -V, --version           print version

eBPF per-process/per-connection accounting needs the privileged helper:
    sudo systemctl enable --now ltop-bpf
Data scopes differ by design (PROCS = payload, NET box = NIC bytes) — see in-app help (m → help).",
        env!("CARGO_PKG_VERSION")
    )
}

/// 本发行版仅支持 x86_64:eBPF 探针的 PT_REGS 寄存器映射与各数据源都按
/// 探针寄存器映射覆盖 x86_64 与 aarch64;其他架构启动即明确报错,
/// 而不是静默产出错账
pub fn arch_guard() -> Result<()> {
    let ok = match std::env::consts::OS {
        "linux" => matches!(std::env::consts::ARCH, "x86_64" | "aarch64"),
        "macos" => matches!(std::env::consts::ARCH, "x86_64" | "aarch64"),
        _ => false,
    };
    if !ok {
        anyhow::bail!(
            "ltop v{} supports Linux and macOS on x86_64/aarch64 (running on {} {}); \
             see README",
            env!("CARGO_PKG_VERSION"),
            std::env::consts::OS,
            std::env::consts::ARCH
        );
    }
    Ok(())
}

/// entry point used by the `ltop` binary (and any symlink alias to it)
pub fn cli_main() -> Result<()> {
    // `ltop --dump | head` 这类管道截断:恢复 SIGPIPE 默认行为,静默退出
    // 而非 println! 在 EPIPE 上 panic
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
    let args: Vec<String> = std::env::args().collect();
    // 子命令最先分派:各自的 --help/参数校验在各自模块(help/version
    // 通用短路在下方,只管 TUI 路径的旗标)
    match args.get(1).map(String::as_str) {
        Some("watch") => return watch::run(&args[2..]),
        Some("report") => return report::run(&args[2..]),
        // 子命令打错字不能掉进 TUI(此前 repor 会静默开界面);
        // 旗标(含 --json 等)照旧走原路径
        Some(cmd) if !cmd.starts_with('-') => {
            eprintln!("ltop: unknown command {cmd:?} (subcommands: watch, report; try --help)");
            return Err(anyhow::anyhow!("unknown command"));
        }
        _ => {}
    }
    // help/version 最先短路:不依赖 tty,也不受 arch 限制(arm64 上也要能看帮助)
    if let Some(res) = early_exit(&args) {
        return res;
    }
    arch_guard()?;
    config::Config::migrate_legacy_dirs();
    if args.iter().any(|a| a == "--replay") {
        return replay::run_replay(&args);
    }
    let theme_src = theme::init();
    // 恢复上次选定的内嵌主题(非 omarchy 跟随)
    let boot_cfg = config::Config::load();
    if boot_cfg.theme != "omarchy" {
        let _ = theme::apply_by_name(&boot_cfg.theme);
    }
    if args.iter().any(|a| a == "--json") {
        return json_snapshot();
    }
    if args.iter().any(|a| a == "--schema") {
        return print_schema();
    }
    if args.iter().any(|a| a == "--dump") {
        return dump(&theme_src);
    }
    let auto_log = args.iter().any(|a| a == "--log");
    // 实时跟随:CLI 旗标或配置开启;默认关(非 omarchy 系统无意义,省每 tick 一次 stat)
    let follow_theme = args.iter().any(|a| a == "--follow-theme") || boot_cfg.theme_live_follow;
    let log_interval: Option<Duration> = args
        .iter()
        .position(|a| a == "--log-interval")
        .and_then(|i| args.get(i + 1))
        .and_then(|v| v.parse::<u64>().ok())
        .map(Duration::from_millis);

    let mut terminal = setup()?;
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = restore();
        default_hook(info);
    }));
    let res = run(&mut terminal, log_interval, auto_log, follow_theme);
    restore()?;
    res
}

fn setup() -> Result<Tui> {
    enable_raw_mode()?;
    // DISAMBIGUATE_ESCAPE_CODES:esc 编码为完整 CSI 序列,消除裸 0x1B 与
    // 鼠标 SGR 序列的歧义——ssh 分包下 esc 曾被逐字节降级,鼠标事件被
    // 拆成数字字符误触盒子 hide(取证实测)。不支持的终端忽略此请求。
    execute!(
        stdout(),
        EnterAlternateScreen,
        EnableMouseCapture,
        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
    )?;
    Ok(Terminal::new(CrosstermBackend::new(stdout()))?)
}

fn restore() -> Result<()> {
    disable_raw_mode()?;
    execute!(
        stdout(),
        PopKeyboardEnhancementFlags,
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    Ok(())
}

fn run(
    terminal: &mut Tui,
    log_interval: Option<Duration>,
    auto_log: bool,
    follow_theme: bool,
) -> Result<()> {
    let mut app = App::new(log_interval);
    // CLI --follow-theme 在配置之上再开一档(配置默认关)
    app.theme_live_follow = app.theme_live_follow || follow_theme;
    if auto_log {
        app.log.toggle();
    }
    // two warm-up samples so the first frame already has rates
    app.update();
    std::thread::sleep(Duration::from_millis(350));
    app.update();
    let mut last_tick = Instant::now();

    while !app.quit {
        terminal.draw(|f| ui::draw(f, &app))?;

        let timeout = app.tick.saturating_sub(last_tick.elapsed());
        if event::poll(timeout)? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    handle_key(&mut app, key.code, key.modifiers);
                }
                Event::Mouse(m) => handle_mouse(&mut app, &m),
                _ => {}
            }
        }

        if last_tick.elapsed() >= app.tick {
            // omarchy 跟随模式(--follow-theme / theme_live_follow):主题文件
            // 被重写(omarchy-theme-set)即热重载,下一帧 draw 拿到新调色板
            if app.theme_live_follow {
                theme::poll_omarchy_follow();
            }
            app.update();
            last_tick = Instant::now();
        }
    }
    app.log.finalize();
    Ok(())
}

/// OSC 52:把文本写入终端本地剪贴板(base64;零依赖,ssh 场景直达本地)
fn osc52_copy(text: &str) {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut b64 = String::new();
    for chunk in text.as_bytes().chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        b64.push(T[(n >> 18) as usize & 63] as char);
        b64.push(T[(n >> 12) as usize & 63] as char);
        b64.push(if chunk.len() > 1 {
            T[(n >> 6) as usize & 63] as char
        } else {
            '='
        });
        b64.push(if chunk.len() > 2 {
            T[n as usize & 63] as char
        } else {
            '='
        });
    }
    let _ = write!(stdout(), "\x1b]52;c;{b64}\x07");
    let _ = stdout().flush();
}

/// Settings 菜单:循环改第 sel 项的值(forward=下一个值/反向=上一个值;
/// 布尔项两向同效)。返回是否发生变更(需存盘)。
fn cycle_setting(app: &mut App, sel: usize, forward: bool) -> bool {
    const ROWS: usize = 12;
    const TICKS: [u64; 5] = [250, 500, 1000, 2000, 5000];
    const LOGS: [u64; 5] = [10_000, 30_000, 60_000, 300_000, 600_000];
    const RETENTION: [u32; 3] = [7, 30, 0];
    const SWEEPS: [u64; 4] = [30, 60, 120, 300];
    const TOMBS: [u64; 4] = [0, 3000, 5000, 8000];
    fn step_in(list: &[u64], cur: u64, forward: bool) -> u64 {
        let i = list.iter().position(|&v| v == cur).unwrap_or(0);
        let n = list.len();
        list[if forward {
            (i + 1) % n
        } else {
            (i + n - 1) % n
        }]
    }
    fn step_u32(list: &[u32], cur: u32, forward: bool) -> u32 {
        let i = list.iter().position(|&v| v == cur).unwrap_or(0);
        let n = list.len();
        list[if forward {
            (i + 1) % n
        } else {
            (i + n - 1) % n
        }]
    }
    let _ = ROWS;
    match sel {
        0 => {
            app.lang = app.lang.next();
            true
        }
        1 => {
            let ms = step_in(&TICKS, app.tick.as_millis() as u64, forward);
            app.tick = Duration::from_millis(ms);
            true
        }
        2 => {
            app.layout = if forward {
                app.layout.next()
            } else {
                app.layout.prev()
            };
            true
        }
        3 => {
            app.graph_net = if forward {
                app.graph_net.next_with_block()
            } else {
                app.graph_net.prev_with_block()
            };
            true
        }
        4 => {
            app.graph_disk = if forward {
                app.graph_disk.next_with_block()
            } else {
                app.graph_disk.prev_with_block()
            };
            true
        }
        5 => {
            let ms = step_in(&LOGS, app.log.interval.as_millis() as u64, forward);
            app.log.interval = Duration::from_millis(ms);
            true
        }
        6 => {
            let d = step_u32(&RETENTION, app.log.retention_days, forward);
            app.log.retention_days = d;
            let _ = app.log.purge_old();
            true
        }
        7 => {
            let s = step_in(&SWEEPS, app.lan.sweep_interval.as_secs(), forward);
            app.lan.sweep_interval = Duration::from_secs(s);
            true
        }
        8 => {
            app.lan.sweep_enabled = !app.lan.sweep_enabled;
            true
        }
        9 => {
            app.log_tracked_only = !app.log_tracked_only;
            true
        }
        10 => {
            app.allow_global_kill = !app.allow_global_kill;
            true
        }
        11 => {
            let cur = app.conn.tombstone_ttl.as_millis() as u64;
            let i = TOMBS.iter().position(|&v| v == cur).map_or(0, |i| {
                if forward {
                    (i + 1) % TOMBS.len()
                } else {
                    (i + TOMBS.len() - 1) % TOMBS.len()
                }
            });
            app.conn.tombstone_ttl = std::time::Duration::from_millis(TOMBS[i]);
            true
        }
        12 => {
            app.proc_expand_default = !app.proc_expand_default;
            true
        }
        _ => false,
    }
}

fn handle_key(app: &mut App, code: KeyCode, modifiers: KeyModifiers) {
    // 诊断开关:LTOP_KEY_LOG=<文件> 追加记录每个按键事件(排查 ssh 下的
    // 按键序列串扰,如 esc 触发盒子 hide)
    if let Ok(path) = std::env::var("LTOP_KEY_LOG") {
        use std::io::Write;
        if let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
        {
            let _ = writeln!(f, "{code:?} {modifiers:?}");
        }
    }
    if modifiers.contains(KeyModifiers::CONTROL) && code == KeyCode::Char('c') {
        app.quit = true;
        return;
    }
    match app.menu {
        MenuState::None => match code {
            KeyCode::Char('q') => app.quit = true,
            // z:焦点盒(LAN/CONNS/PROCS)全屏 zoom;再按退出。esc 在 zoom
            // 中也只退出 zoom(不触发清 focus/选中)
            KeyCode::Char('z') => {
                if app.zoom.is_some() {
                    app.zoom = None;
                } else if matches!(
                    app.last_focus,
                    crate::app::BOX_LAN | crate::app::BOX_CONNS | crate::app::BOX_PROCS
                ) && app.visible[app.last_focus]
                {
                    app.zoom = Some(app.last_focus);
                }
            }
            KeyCode::Esc if app.zoom.is_some() => app.zoom = None,
            KeyCode::Char(' ') => app.paused = !app.paused,
            KeyCode::Char('/') => {
                // 打开时载入当前过滤,可直接编辑;清空后 enter 即重置
                app.search_buf = app.search.clone();
                app.menu = MenuState::Search;
            }
            // Esc backs out of everything (focus + selection); only m opens
            // the menu — reaching for Esc to close a popup must never land
            // you in another popup one press later
            KeyCode::Esc => {
                app.conn.peer_filter = None; // 解除 LAN 联动的对端过滤
                for f in app.focus.iter_mut() {
                    *f = false;
                }
                for s in app.sel.iter_mut() {
                    *s = None;
                }
            }
            KeyCode::Char('m') => app.menu = MenuState::Main(0),
            // ssh 下 esc 序列可能被解析成带 ALT 修饰的幽灵字符键;盒子的
            // hide/show 只响应无修饰的数字
            KeyCode::Char(c @ '1'..='6')
                if !modifiers.intersects(KeyModifiers::ALT | KeyModifiers::CONTROL) =>
            {
                let idx = (c as usize - '1' as usize).min(app::BOX_COUNT - 1);
                let shown = app.visible.iter().filter(|&&v| v).count();
                if !(app.visible[idx] && shown <= 1) {
                    app.visible[idx] = !app.visible[idx];
                }
            }
            KeyCode::Tab => app.layout = app.layout.next(),
            KeyCode::Char('n') => {
                app.net.cycle_selected();
                app.last_focus = app::BOX_NET;
            }
            KeyCode::Char('p') => {
                // 单焦点:点亮一个盒即熄灭其余
                let on = !app.focus[app::BOX_PROCS];
                app.focus[app::BOX_PROCS] = on;
                app.focus[app::BOX_CONNS] = false;
                app.focus[app::BOX_LAN] = false;
                app.last_focus = app::BOX_PROCS;
            }
            KeyCode::Char('c') => {
                let on = !app.focus[app::BOX_CONNS];
                app.focus[app::BOX_CONNS] = on;
                app.focus[app::BOX_PROCS] = false;
                app.focus[app::BOX_LAN] = false;
                app.last_focus = app::BOX_CONNS;
            }
            KeyCode::Char('l') => {
                // 单焦点:点亮 lan 即熄灭 procs/conns
                let on = !app.focus[app::BOX_LAN];
                app.focus[app::BOX_LAN] = on;
                app.focus[app::BOX_PROCS] = false;
                app.focus[app::BOX_CONNS] = false;
                app.last_focus = app::BOX_LAN;
            }
            KeyCode::Char('e') => app.lan.sort = app.lan.sort.next(),
            KeyCode::Char('i') => {
                app.io_graph = app.io_graph.next();
                app.last_focus = app::BOX_DISKIO;
            }
            KeyCode::Char('r') => app.proc.sort = app.proc.sort.next(),
            // `d` matches the [d]isks title letter; `e` now belongs to the
            // lan box (order cycle)
            KeyCode::Char('d') => {
                app.disks_expanded = !app.disks_expanded;
            }
            KeyCode::Char('f') => {
                app.conn.filter = app.conn.filter.next();
                app.conn.peer_filter = None; // 手动切过滤即解除对端联动
            }
            KeyCode::Char('o') => app.conn.sort = app.conn.sort.next(),
            KeyCode::Left | KeyCode::Right => {
                // 聚合父行上:← 折叠、→ 展开;其余场景不占用
                let b = app.last_focus;
                if b == app::BOX_CONNS && app.focus[b] && ui::selected_is_agg(app, b) {
                    if let Some(key) = ui::selected_agg_key(app, b) {
                        // ← 折叠、→ 展开(相对设置中的默认态取反亦可)
                        let open = code == KeyCode::Right;
                        ui::set_group_open(app, &key, open);
                    }
                }
            }
            KeyCode::Char('k') => {
                let b = app.last_focus;
                if app.focus[b] {
                    if let Some(pid) = ui::selected_pid(app, b) {
                        kill_pid(pid);
                    }
                }
            }
            KeyCode::Char('L') => {
                app.log.toggle();
            }
            KeyCode::Enter => {
                let b = app.last_focus;
                if app.focus[b] {
                    // lan 行上的 enter = 置顶(仅一个)+ 联动 conns 只看该对端;
                    // 再按取消置顶并解除联动
                    if b == app::BOX_LAN {
                        if let Some(id) = ui::selected_id(app, b) {
                            let ip = std::net::Ipv4Addr::from(id as u32);
                            if app.lan.tracked.contains(&ip) {
                                app.lan.tracked.remove(&ip);
                                app.conn.peer_filter = None;
                            } else {
                                app.lan.tracked.clear();
                                app.lan.tracked.insert(ip);
                                // 焦点留在 lan:再按 enter 即取消;
                                // conns 盒的联动过滤结果实时可见
                                app.conn.peer_filter = Some(ip);
                            }
                            ui::reselect(app, app::BOX_LAN, id);
                        }
                    } else if b == app::BOX_CONNS && ui::selected_is_agg(app, b) {
                        if let Some(key) = ui::selected_agg_key(app, b) {
                            ui::toggle_group(app, &key);
                        }
                    } else if let Some(id) = ui::selected_id(app, b) {
                        app.detail_sel = 0;
                        app.menu = MenuState::Detail(b, id);
                    }
                }
            }
            KeyCode::Up => {
                let b = app.last_focus;
                if app.focus[b] {
                    ui::move_selection(app, b, -1);
                } else {
                    app.scroll[b] = app.scroll[b].saturating_sub(3);
                }
            }
            // Home/End/g/G:跳顶/跳底(聚焦盒移动选中,未聚焦盒跳滚动;
            // ssh 幽灵序列防御同数字键——排除 ALT/CTRL)
            KeyCode::Home | KeyCode::Char('g')
                if !modifiers.intersects(KeyModifiers::ALT | KeyModifiers::CONTROL) =>
            {
                let b = app.last_focus;
                if app.focus[b] {
                    ui::jump_selection(app, b, true);
                } else {
                    app.scroll[b] = 0;
                }
            }
            KeyCode::End | KeyCode::Char('G')
                if !modifiers.intersects(KeyModifiers::ALT | KeyModifiers::CONTROL) =>
            {
                let b = app.last_focus;
                if app.focus[b] {
                    ui::jump_selection(app, b, false);
                } else {
                    app.scroll[b] = usize::MAX;
                }
            }
            KeyCode::Down => {
                let b = app.last_focus;
                if app.focus[b] {
                    ui::move_selection(app, b, 1);
                } else {
                    app.scroll[b] = app.scroll[b].saturating_add(3);
                }
            }
            KeyCode::PageUp => {
                app.scroll[app.last_focus] = app.scroll[app.last_focus].saturating_sub(3);
            }
            KeyCode::PageDown => {
                app.scroll[app.last_focus] = app.scroll[app.last_focus].saturating_add(3);
            }
            KeyCode::Char('s') => {
                app.lan.sweep_enabled = !app.lan.sweep_enabled;
                if app.lan.sweep_enabled {
                    app.lan.sweep_now();
                }
            }
            KeyCode::Char('+') | KeyCode::Char('=') => {
                app.tick = (app.tick + Duration::from_millis(250)).min(Duration::from_secs(5));
            }
            KeyCode::Char('-') => {
                app.tick = app
                    .tick
                    .saturating_sub(Duration::from_millis(250))
                    .max(Duration::from_millis(250));
            }
            _ => {}
        },
        MenuState::Main(sel) => {
            const BUTTONS: usize = 7;
            match code {
                KeyCode::Left | KeyCode::Char('h') => {
                    app.menu = MenuState::Main((sel + BUTTONS - 1) % BUTTONS)
                }
                KeyCode::Right | KeyCode::Char('l') => {
                    app.menu = MenuState::Main((sel + 1) % BUTTONS)
                }
                KeyCode::Enter => match sel {
                    0 => app.menu = MenuState::Theme(0, 0),
                    1 => app.menu = MenuState::Settings(0),
                    2 => app.menu = MenuState::Reset(0),
                    3 => app.menu = MenuState::Graphs(0),
                    4 => app.menu = MenuState::Help,
                    5 => app.quit = true,
                    _ => app.menu = MenuState::None,
                },
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('m') => {
                    app.menu = MenuState::None
                }
                _ => {}
            }
        }
        MenuState::Settings(sel) => {
            const ROWS: usize = 13;
            let changed = match code {
                KeyCode::Up | KeyCode::Char('k') => {
                    app.menu = MenuState::Settings(sel.saturating_sub(1));
                    false
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    app.menu = MenuState::Settings((sel + 1).min(ROWS - 1));
                    false
                }
                KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => {
                    cycle_setting(app, sel, true)
                }
                KeyCode::Left | KeyCode::Char('h') => cycle_setting(app, sel, false),
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('m') => {
                    app.menu = MenuState::None;
                    false
                }
                _ => false,
            };
            if changed {
                app.save_config();
            }
        }
        MenuState::Theme(sel, scroll) => match code {
            KeyCode::Up | KeyCode::Char('k') => {
                if sel > 0 {
                    let scroll = if sel - 1 < scroll { scroll - 1 } else { scroll };
                    app.menu = MenuState::Theme(sel - 1, scroll);
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                let count = theme::builtin_count() + 1;
                if sel + 1 < count {
                    let scroll = if sel + 1 >= scroll + ui::THEME_VISIBLE {
                        scroll + 1
                    } else {
                        scroll
                    };
                    app.menu = MenuState::Theme(sel + 1, scroll);
                }
            }
            KeyCode::Enter => {
                let ok = if sel == 0 {
                    theme::apply_omarchy()
                } else {
                    theme::apply_builtin(sel - 1)
                };
                if ok {
                    // 主题选择持久化(omarchy 跟随记为 "omarchy")
                    app.save_config();
                }
            }
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('m') => app.menu = MenuState::None,
            _ => {}
        },
        MenuState::Reset(sel) => match code {
            KeyCode::Up | KeyCode::Char('k') => app.menu = MenuState::Reset(sel.saturating_sub(1)),
            KeyCode::Down | KeyCode::Char('j') => app.menu = MenuState::Reset((sel + 1).min(2)),
            KeyCode::Enter => {
                match sel {
                    0 => app.reset_net(),
                    1 => app.reset_disk(),
                    _ => app.reset_all(),
                }
                app.menu = MenuState::None;
            }
            KeyCode::Char('n') => {
                app.reset_net();
                app.menu = MenuState::None;
            }
            KeyCode::Char('d') => {
                app.reset_disk();
                app.menu = MenuState::None;
            }
            KeyCode::Char('a') => {
                app.reset_all();
                app.menu = MenuState::None;
            }
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('m') => app.menu = MenuState::None,
            _ => {}
        },
        MenuState::Graphs(sel) => match code {
            KeyCode::Up | KeyCode::Char('k') => app.menu = MenuState::Graphs(sel.saturating_sub(1)),
            KeyCode::Down | KeyCode::Char('j') => app.menu = MenuState::Graphs((sel + 1).min(2)),
            // 行改值:Right/l=下一模式,Left/h=上一模式(Block 仅在此可达)
            KeyCode::Right | KeyCode::Char('l') => match sel {
                0 => app.graph_net = app.graph_net.next_with_block(),
                1 => app.graph_disk = app.graph_disk.next_with_block(),
                _ => {
                    let s = app.graph_net.next_with_block();
                    app.graph_net = s;
                    app.graph_disk = s;
                }
            },
            KeyCode::Left | KeyCode::Char('h') => match sel {
                0 => app.graph_net = app.graph_net.prev_with_block(),
                1 => app.graph_disk = app.graph_disk.prev_with_block(),
                _ => {
                    let s = app.graph_net.prev_with_block();
                    app.graph_net = s;
                    app.graph_disk = s;
                }
            },
            KeyCode::Enter => match sel {
                0 => app.graph_net = app.graph_net.next_with_block(),
                1 => app.graph_disk = app.graph_disk.next_with_block(),
                _ => {
                    let s = app.graph_net.next_with_block();
                    app.graph_net = s;
                    app.graph_disk = s;
                }
            },
            // n/d/a 直达键保留(下一模式)
            KeyCode::Char('n') => app.graph_net = app.graph_net.next_with_block(),
            KeyCode::Char('d') => app.graph_disk = app.graph_disk.next_with_block(),
            KeyCode::Char('a') => {
                let s = app.graph_net.next_with_block();
                app.graph_net = s;
                app.graph_disk = s;
            }
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('m') => app.menu = MenuState::None,
            _ => {}
        },
        MenuState::Search => match code {
            KeyCode::Tab => {
                app.search_box = if app.search_box == app::BOX_CONNS {
                    app::BOX_PROCS
                } else {
                    app::BOX_CONNS
                };
            }
            KeyCode::Char(c) => app.search_buf.push(c),
            KeyCode::Backspace => {
                app.search_buf.pop();
            }
            KeyCode::Enter => {
                app.search = std::mem::take(&mut app.search_buf);
                app.menu = MenuState::None;
            }
            KeyCode::Esc => {
                // esc = 重置:清除已应用的过滤与缓冲
                app.search.clear();
                app.search_buf.clear();
                app.menu = MenuState::None;
            }
            _ => {}
        },
        MenuState::Help => app.menu = MenuState::None,
        MenuState::Detail(b, id) => match code {
            KeyCode::Up => {
                if app.detail_sel > 0 {
                    app.detail_sel -= 1;
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if app.detail_sel + 1 < ui::detail_field_count(app, b, id) {
                    app.detail_sel += 1;
                }
            }
            KeyCode::Char('y') => {
                if let Some(text) = ui::detail_selected_value(app, b, id) {
                    osc52_copy(&text);
                }
            }
            KeyCode::Char(' ') | KeyCode::Char('t') => ui::toggle_track(app, b, id),
            KeyCode::Char('s') => {
                // exited process: start it right away; a running one goes
                // through the restart confirmation (SIGTERM + relaunch)
                if b == app::BOX_PROCS {
                    if let Some(p) = app.proc.procs.iter().find(|p| p.pid as u64 == id) {
                        if let Some(cmd) = &p.cmdline {
                            if p.alive {
                                app.menu = MenuState::ConfirmRestart(p.pid);
                            } else {
                                let _ = start_cmd(cmd);
                            }
                        }
                    }
                }
            }
            KeyCode::Char('k') => {
                let pid = match b {
                    app::BOX_PROCS => Some(id as u32),
                    app::BOX_CONNS => app
                        .conn
                        .conns
                        .iter()
                        .find(|c| c.inode == id)
                        .and_then(|c| c.pid),
                    _ => None,
                };
                if let Some(pid) = pid {
                    app.menu = MenuState::ConfirmKill(pid);
                }
            }
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('m') => app.menu = MenuState::None,
            _ => {}
        },
        MenuState::ConfirmKill(pid) => match code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                kill_pid(pid);
                app.menu = MenuState::None;
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc | KeyCode::Char('q') => {
                app.menu = MenuState::None;
            }
            _ => {}
        },
        MenuState::ConfirmRestart(pid) => match code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
                let cmd = app
                    .proc
                    .procs
                    .iter()
                    .find(|p| p.pid == pid)
                    .and_then(|p| p.cmdline.clone());
                if let Some(cmd) = cmd {
                    kill_pid(pid);
                    // relaunch from a worker thread: the old instance may take
                    // a moment to exit (releasing ports/singleton locks), and
                    // the TUI must not freeze while waiting for it
                    std::thread::spawn(move || {
                        for _ in 0..40 {
                            // kill(0) 探活(EPERM = 活着但没权限发信号)——
                            // 跨平台,Linux /proc 探测的同义替换
                            let alive = unsafe { libc::kill(pid as libc::pid_t, 0) } == 0
                                || std::io::Error::last_os_error().raw_os_error()
                                    == Some(libc::EPERM);
                            if !alive {
                                break;
                            }
                            std::thread::sleep(std::time::Duration::from_millis(50));
                        }
                        let _ = start_cmd(&cmd);
                    });
                }
                app.menu = MenuState::None;
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc | KeyCode::Char('q') => {
                app.menu = MenuState::None;
            }
            _ => {}
        },
    }
}

fn handle_mouse(app: &mut App, m: &crossterm::event::MouseEvent) {
    use crossterm::event::MouseButton;
    match m.kind {
        MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
            if let Some(idx) = ui::hit_box(m.column, m.row) {
                if m.kind == MouseEventKind::ScrollUp {
                    app.scroll[idx] = app.scroll[idx].saturating_sub(3);
                } else {
                    app.scroll[idx] = app.scroll[idx].saturating_add(3);
                }
            }
        }
        MouseEventKind::Down(MouseButton::Left) => {
            // 双击(同格 400ms 内两次):直接打开该行 detail(procs/conns)
            if let Some((t0, c0, r0)) = app.last_click {
                if t0.elapsed() < std::time::Duration::from_millis(400)
                    && c0 == m.column
                    && r0 == m.row
                {
                    app.last_click = None;
                    let idx = ui::hit_box(m.column, m.row);
                    if let Some(b) = idx {
                        if let Some(id) = ui::selected_id(app, b) {
                            app.menu = crate::app::MenuState::Detail(b, id);
                        }
                    }
                    return;
                }
            }
            app.last_click = Some((std::time::Instant::now(), m.column, m.row));
            // clicking a procs/conns data row selects (and focuses) it;
            // clicking anywhere else cancels every focus
            let hit = ui::hit_box(m.column, m.row)
                .filter(|&idx| matches!(idx, app::BOX_PROCS | app::BOX_CONNS | app::BOX_LAN))
                .and_then(|idx| ui::box_rect(idx).map(|r| (idx, r)));
            let mut on_row = false;
            if let Some((idx, rect)) = hit {
                let row = m.row as i32 - (rect.y as i32 + 2); // border + header
                if row >= 0 {
                    // 与绘制同源:off 以可见行数封顶(旧版用未封顶的 scroll,
                    // 滚到底后点击错位)
                    let visible = (rect.height as usize).saturating_sub(3).max(1);
                    let abs = ui::clamped_offset(app, idx, visible) + row as usize;
                    if abs < ui::list_len(app, idx) {
                        app.sel[idx] = Some(abs);
                        // 单焦点:点亮一个盒即熄灭其余(与 p/c/l 键同语义)
                        for (b, f) in app.focus.iter_mut().enumerate() {
                            *f = b == idx;
                        }
                        app.last_focus = idx;
                        on_row = true;
                        // 点击聚合父行:选中同时切换展开/折叠
                        if idx == app::BOX_CONNS && ui::selected_is_agg(app, idx) {
                            if let Some(key) = ui::selected_agg_key(app, idx) {
                                ui::toggle_group(app, &key);
                            }
                        }
                    }
                }
            }
            if !on_row {
                // clicked an empty row or outside any list: cancel all focus
                for f in app.focus.iter_mut() {
                    *f = false;
                }
                for s in app.sel.iter_mut() {
                    *s = None;
                }
            }
        }
        _ => {}
    }
}

/// SIGTERM, the polite request; the process can still clean up and exit.
pub(crate) fn kill_pid(pid: u32) {
    unsafe {
        libc::kill(pid as i32, libc::SIGTERM);
    }
}

/// Launch a captured command line detached from the terminal: own session
/// (survives the TUI), null stdio. Used to start/restart a process from its
/// detail panel.
pub(crate) fn start_cmd(cmd: &[String]) -> std::io::Result<u32> {
    use std::os::unix::process::CommandExt;
    use std::process::{Command, Stdio};
    let (prog, args) = cmd
        .split_first()
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "empty command"))?;
    // SAFETY: pre_exec runs in the forked child before exec; setsid() takes no
    // arguments, and the closure touches nothing else
    unsafe {
        Command::new(prog)
            .args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .pre_exec(|| {
                libc::setsid();
                Ok(())
            })
            .spawn()
            .map(|child| child.id())
    }
}

/// AI-friendly structured snapshot: two sampling rounds (rates), JSON out
pub fn json_snapshot() -> Result<()> {
    let mut app = App::new(None);
    app.update();
    std::thread::sleep(Duration::from_millis(1200));
    app.update();
    let snap = snapshot::from_app(&app);
    println!("{}", serde_json::to_string_pretty(&snap)?);
    Ok(())
}

/// field reference for `--json` consumers (machine-parseable, versioned)
pub fn print_schema() -> Result<()> {
    let fields: &[(&str, &str, &str)] = &[
        (
            "schema",
            "u32",
            "snapshot schema version (additive-only within a version)",
        ),
        ("meta.hostname", "string", "host name"),
        ("meta.ts", "u64", "unix timestamp (seconds)"),
        ("meta.version", "string", "ltop version"),
        ("meta.os / meta.arch", "string", "platform"),
        (
            "meta.udp_helper",
            "bool",
            "eBPF helper snapshot fresh (Linux only)",
        ),
        ("net.selected", "string", "interface shown in the TUI"),
        (
            "net.interfaces[].name/operstate/mac",
            "string",
            "interface identity",
        ),
        (
            "net.interfaces[].speed_mbps",
            "u64?",
            "link speed (None on Wi-Fi)",
        ),
        ("net.interfaces[].addresses[]", "string", "CIDR addresses"),
        (
            "net.interfaces[].rx_bps/tx_bps",
            "f64",
            "instantaneous bytes/s",
        ),
        (
            "net.interfaces[].session_rx/session_tx",
            "u64",
            "bytes since ltop start",
        ),
        (
            "net.interfaces[].alive_rx/alive_tx",
            "u64",
            "bytes since interface up",
        ),
        ("lan.subnets[]", "string", "observed subnets (CIDR)"),
        ("lan.gateways[]", "string", "default gateways"),
        (
            "lan.neighbours[].ip/mac/hostname/iface",
            "string",
            "neighbour identity; mac is null on macOS (system sanitizes)",
        ),
        (
            "lan.neighbours[].is_gateway/is_self/tracked",
            "bool",
            "role flags",
        ),
        (
            "disk.devices[].name/mounts[]/fstype",
            "string",
            "device identity",
        ),
        ("disk.devices[].total/used", "u64", "capacity (bytes)"),
        (
            "disk.devices[].read_bps/write_bps/iops",
            "f64",
            "throughput",
        ),
        (
            "disk.session_read/session_write",
            "u64",
            "bytes since ltop start",
        ),
        (
            "conns[].proto/local/remote/state",
            "string",
            "connection identity (state: LISTEN/ESTAB/UDP)",
        ),
        (
            "conns[].process/pid/user",
            "string|u32|null",
            "owner (null when not owned by you)",
        ),
        ("conns[].inode", "u64", "stable row key"),
        (
            "conns[].bytes_recv/bytes_sent",
            "u64",
            "cumulative per-socket bytes",
        ),
        ("conns[].bps_recv/bps_sent", "f64", "instantaneous bytes/s"),
        (
            "procs[].pid/name/alive",
            "u32|string|bool",
            "process identity",
        ),
        (
            "procs[].net_recv/net_sent/udp_recv/udp_sent",
            "u64",
            "session Σ bytes",
        ),
        (
            "procs[].net_bps_recv/net_bps_sent",
            "f64",
            "network bytes/s",
        ),
        (
            "procs[].disk_read/disk_written/disk_bps_read/disk_bps_written",
            "u64|f64",
            "disk I/O (own-uid processes)",
        ),
    ];
    let out = serde_json::json!({
        "schema": snapshot::SCHEMA,
        "command": "ltop --json",
        "fields": fields.iter().map(|(p, t, d)| serde_json::json!({
            "path": p, "type": t, "description": d,
        })).collect::<Vec<_>>(),
    });
    println!("{}", serde_json::to_string_pretty(&out)?);
    Ok(())
}

/// headless dump of one sampled round (debug aid)
pub fn dump(theme_src: &str) -> Result<()> {
    let mut app = App::new(None);
    app.update();
    // long enough for the hostname workers (mDNS + NetBIOS) to finish
    std::thread::sleep(Duration::from_millis(2600));
    app.update();

    println!("== THEME ==\n{theme_src}");
    println!("== NET ==");
    println!("selected: {:?}", app.net.selected);
    for (name, info) in &app.net.ifaces {
        let (rx, tx) = match app.net.rates.get(name) {
            Some(r) => (format!("{:.0} B/s", r.rx), format!("{:.0} B/s", r.tx)),
            None => ("-".into(), "-".into()),
        };
        println!(
            "{:<12} {:<8} speed {:<8} mac {:<18} rx {:<12} tx {:<12} addrs {:?}",
            name,
            info.operstate,
            info.speed_mbps.unwrap_or(0),
            info.mac,
            rx,
            tx,
            info.addrs
        );
    }

    println!("== LAN ==");
    println!(
        "subnets: {:?}  gateways: {:?}  sweep: {}",
        app.lan.subnets, app.lan.gateways, app.lan.sweeping
    );
    for n in app.lan.sorted_neighbors() {
        println!(
            "{:<16} {:<18} {:<10} host {:<24} {}{}",
            n.ip.to_string(),
            n.mac.clone().unwrap_or_default(),
            n.iface,
            n.hostname.clone().unwrap_or_default(),
            if n.is_gateway { "gw " } else { "" },
            if n.is_self { "self" } else { "" },
        );
    }

    println!("== CONNS == total {}", app.conn.conns.len());
    for c in app.conn.conns.iter().take(12) {
        let proc_str = match (&c.proc, c.pid) {
            (Some(n), Some(p)) => format!("{n}({p})"),
            _ => app.conn.user_name(c.uid),
        };
        println!(
            "{:<20} {:<24} -> {:<24} {} r {:.0} w {:.0}",
            proc_str,
            collect::conn::sock_str(&c.local),
            collect::conn::sock_str(&c.remote),
            if c.is_listen() {
                "LISTEN"
            } else if c.is_tcp() {
                "EST"
            } else {
                "UDP"
            },
            c.rate_recv,
            c.rate_sent
        );
    }

    println!("== PROCS ==");
    for p in app.proc.procs.iter().take(12) {
        println!(
            "{:<20} net SUM={}/{} r {}/{} disk SUM={}/{} r {}/{}",
            format!("{}({})", p.name, p.pid),
            fmt_human(p.net_recv as f64),
            fmt_human(p.net_sent as f64),
            fmt_human(p.net_rr),
            fmt_human(p.net_sr),
            fmt_human(p.disk_r as f64),
            fmt_human(p.disk_w as f64),
            fmt_human(p.disk_rr),
            fmt_human(p.disk_wr),
        );
    }

    println!("== UDP (eBPF) ==");
    println!(
        "snapshot {}  fresh {}  pids {}  sockets {}",
        app.udp.path.display(),
        app.udp.fresh,
        app.udp.pids_seen,
        app.udp.sks_seen
    );
    for d in app.udp.last_inodes.iter().take(8) {
        let conn = app
            .conn
            .conns
            .iter()
            .find(|c| c.inode == d.inode)
            .map(|c| {
                format!(
                    "{} -> {}",
                    collect::conn::sock_str(&c.local),
                    collect::conn::sock_str(&c.remote)
                )
            })
            .unwrap_or_else(|| "(socket 已关闭)".into());
        println!(
            "  inode {:<8} {}  delta r {}/ w {}",
            d.inode,
            conn,
            fmt_human(d.recv as f64),
            fmt_human(d.sent as f64),
        );
    }
    for p in app
        .proc
        .procs
        .iter()
        .filter(|p| p.udp_recv + p.udp_sent > 0)
        .take(12)
    {
        println!(
            "{:<20} udp SUM={}/{} r {}/{}",
            format!("{}({})", p.name, p.pid),
            fmt_human(p.udp_recv as f64),
            fmt_human(p.udp_sent as f64),
            fmt_human(p.udp_rr),
            fmt_human(p.udp_sr),
        );
    }

    println!("== DISK ==");
    let mut tree_lines: Vec<String> = Vec::new();
    fn emit(
        nodes: &[collect::disk::TreeNode],
        prefix: String,
        depth: usize,
        out: &mut Vec<String>,
    ) {
        let n = nodes.len();
        for (i, node) in nodes.iter().enumerate() {
            let last = i + 1 == n;
            let glyph = if depth == 0 {
                String::new()
            } else if last {
                "+- ".into()
            } else {
                "|- ".into()
            };
            let child_prefix = if depth == 0 {
                String::new()
            } else {
                format!("{prefix}{}", if last { "  " } else { "| " })
            };
            out.push(format!("{prefix}{glyph}{}", node.name));
            emit(&node.children, child_prefix, depth + 1, out);
        }
    }
    emit(&app.disk.tree, String::new(), 0, &mut tree_lines);
    for l in &tree_lines {
        println!("  {l}");
    }
    for d in &app.disk.devices {
        println!(
            "{:<14} {:<6} mounts {:?} used {}/{} r {:.0} w {:.0}",
            d.name,
            d.fstype,
            d.mounts,
            fmt_human(d.used as f64),
            fmt_human(d.total as f64),
            d.rate_r,
            d.rate_w
        );
    }
    Ok(())
}

pub(crate) fn fmt_human(v: f64) -> String {
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
    let mut v = v;
    let mut u = 0;
    while v >= 1024.0 && u < 4 {
        v /= 1024.0;
        u += 1;
    }
    format!("{v:.1}{}", UNITS[u])
}

/// CLI 消息语言:默认英文,config.conf 的 lang=zh 切中文(headless 路径
/// 不建 App,轻量直读配置;cfg(test) 下按测试隔离约定返回默认 En)
pub fn cli_lang_zh() -> bool {
    matches!(config::Config::load().lang, config::Lang::Zh)
}

/// EN/ZH 字面量二选一(配合 cli_lang_zh 使用;返回 String 规避闭包寿命)
pub fn pick<'a>(zh: bool, en: &'a str, c: &'a str) -> &'a str {
    if zh {
        c
    } else {
        en
    }
}

pub fn pick_s(zh: bool, en: &str, c: &str) -> String {
    pick(zh, en, c).to_string()
}

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

    /// the build-time eBPF object must parse and carry all four probes plus
    /// the LRU map, so a broken clang output fails tests instead of at runtime
    /// (aya_obj 依赖仅 Linux;mac 构建跳过本测试)
    #[cfg(target_os = "linux")]
    #[test]
    fn bpf_object_parses_with_probes_and_map() {
        let path = std::path::Path::new(env!("OUT_DIR")).join("ltop_udp_bpf.o");
        let Ok(bytes) = std::fs::read(&path) else {
            eprintln!("skipped: 没有 eBPF 对象(构建机缺 clang)");
            return;
        };
        let obj = aya_obj::Object::parse(&bytes).expect("parse eBPF object");
        for name in [
            "udp_send",
            "udp_recv_entry",
            "udp_recv",
            "udp6_send",
            "udp6_recv_entry",
            "udp6_recv",
            "tcp_send_entry",
            "tcp_send",
            "tcp_recv_entry",
            "tcp_recv",
        ] {
            assert!(obj.programs.contains_key(name), "缺程序 {name}");
        }
        for (name, ksize) in [("net_bytes", 4u32), ("udp_bytes", 4)] {
            let m = obj.maps.get(name).expect("缺 pid 账本 map");
            let aya_obj::maps::Map::Legacy(m) = m else {
                panic!("{name} 应是 legacy map 定义");
            };
            assert_eq!(m.def.map_type, 9, "BPF_MAP_TYPE_LRU_HASH");
            assert_eq!(m.def.key_size, ksize);
            assert_eq!(m.def.value_size, 16);
            assert_eq!(m.def.max_entries, 16384);
        }
        let sk = obj.maps.get("udp_sk").expect("缺 udp_sk map");
        let aya_obj::maps::Map::Legacy(sk) = sk else {
            panic!("udp_sk 应是 legacy map 定义");
        };
        assert_eq!(sk.def.map_type, 9);
        assert_eq!(sk.def.key_size, 8); // struct sock 指针为键
        assert_eq!(sk.def.value_size, 16);
        let stash = obj.maps.get("recv_sk").expect("缺 recv_sk map");
        let aya_obj::maps::Map::Legacy(stash) = stash else {
            panic!("recv_sk 应是 legacy map 定义");
        };
        assert_eq!(stash.def.key_size, 8); // 完整 pid_tgid
        assert_eq!(stash.def.value_size, 8); // 暂存的 sk
        let cache = obj.maps.get("sk_ino").expect("缺 sk_ino map");
        let aya_obj::maps::Map::Legacy(cache) = cache else {
            panic!("sk_ino 应是 legacy map 定义");
        };
        assert_eq!(cache.def.key_size, 8); // sk
        assert_eq!(cache.def.value_size, 8); // inode
    }

    #[test]
    fn enter_on_aggregate_toggles_collapse() {
        use crossterm::event::{KeyCode, KeyModifiers};
        let mut app = App::new(None);
        app.conn.sort = crate::collect::conn::ConnSort::Proc;
        let mk = |inode: u64| crate::collect::conn::Conn {
            proto: crate::collect::conn::IPPROTO_TCP,
            local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
            remote: ("127.0.0.1".parse().unwrap(), 443),
            state: 1,
            uid: 0,
            inode,
            bytes_recv: 100,
            bytes_sent: 0,
            rate_recv: 0.0,
            rate_sent: 0.0,
            pid: Some(1000 + inode as u32),
            proc: Some("web".into()),
            dead: false,
            first_seen: None,
            dead_at: None,
        };
        app.conn.conns = vec![mk(1), mk(2)];
        app.sel[app::BOX_CONNS] = Some(0); // 聚合父行
        app.focus[app::BOX_CONNS] = true;
        handle_key(&mut app, KeyCode::Enter, KeyModifiers::empty());
        assert!(app.expanded.contains("web"), "聚合行 enter 应展开组");
        handle_key(&mut app, KeyCode::Enter, KeyModifiers::empty());
        assert!(!app.expanded.contains("web"), "再按应折叠");
        // ← 折叠 / → 展开
        app.expanded.insert("web".into());
        handle_key(&mut app, KeyCode::Left, KeyModifiers::empty());
        assert!(!app.expanded.contains("web"));
        handle_key(&mut app, KeyCode::Right, KeyModifiers::empty());
        assert!(app.expanded.contains("web"));
    }

    #[test]
    fn enter_on_lan_pins_single_and_filters_conns() {
        use crossterm::event::{KeyCode, KeyModifiers};
        use std::net::Ipv4Addr;
        let mut app = App::new(None);
        for k in 1..=3u32 {
            let ip = Ipv4Addr::new(10, 0, 0, k as u8);
            app.lan.neighbors.insert(
                ip,
                crate::collect::lan::Neighbor {
                    ip,
                    mac: None,
                    mac_hidden: false,
                    iface: "eth0".into(),
                    complete: true,
                    hostname: None,
                    is_gateway: false,
                    is_self: false,
                    last_seen: std::time::Instant::now(),
                },
            );
        }
        // 选中第 2 台(排序后位置 1),聚焦 lan
        app.conn.sort = crate::collect::conn::ConnSort::Name;
        app.focus[app::BOX_LAN] = true;
        app.last_focus = app::BOX_LAN;
        app.sel[app::BOX_LAN] = Some(1);
        let ip2 = Ipv4Addr::new(10, 0, 0, 2);

        handle_key(&mut app, KeyCode::Enter, KeyModifiers::empty());
        assert!(app.lan.tracked.contains(&ip2), "enter 应置顶");
        assert_eq!(app.lan.tracked.len(), 1, "置顶应只有一个");
        assert_eq!(app.conn.peer_filter, Some(ip2), "应联动 conns 对端过滤");
        // 置顶组提前:选中的邻居现在在位置 0
        assert_eq!(app.lan.sorted_neighbors()[0].ip, ip2, "置顶后应排第一");

        // 再按:取消置顶 + 解除联动
        handle_key(&mut app, KeyCode::Enter, KeyModifiers::empty());
        assert!(app.lan.tracked.is_empty(), "再按应取消置顶");
        assert!(app.conn.peer_filter.is_none(), "联动应解除");
    }

    #[test]
    fn lan_focus_excludes_other_boxes() {
        use crossterm::event::{KeyCode, KeyModifiers};
        let mut app = App::new(None);
        handle_key(&mut app, KeyCode::Char('p'), KeyModifiers::empty());
        handle_key(&mut app, KeyCode::Char('l'), KeyModifiers::empty());
        assert!(app.focus[app::BOX_LAN] && !app.focus[app::BOX_PROCS]);
        handle_key(&mut app, KeyCode::Char('c'), KeyModifiers::empty());
        assert!(app.focus[app::BOX_CONNS] && !app.focus[app::BOX_LAN]);
    }

    #[test]
    fn e_key_cycles_lan_sort() {
        use crossterm::event::{KeyCode, KeyModifiers};
        let mut app = App::new(None);
        let s0 = app.lan.sort;
        handle_key(&mut app, KeyCode::Char('e'), KeyModifiers::empty());
        assert_ne!(app.lan.sort, s0, "e 应循环 lan 排序");
    }

    #[test]
    fn esc_resets_the_applied_search() {
        use crossterm::event::{KeyCode, KeyModifiers};
        let mut app = App::new(None);
        app.search = "fire".into();
        app.search_buf = "fire".into();
        app.menu = MenuState::Search;
        handle_key(&mut app, KeyCode::Char('x'), KeyModifiers::NONE);
        assert_eq!(app.search_buf, "firex");
        assert_eq!(app.search, "fire", "输入中不影响已应用过滤");
        handle_key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
        assert_eq!(app.search, "firex", "enter 应用");
        assert!(app.menu == MenuState::None);
        // 再次进入搜索会载入现有过滤;esc 一键重置
        handle_key(&mut app, KeyCode::Char('/'), KeyModifiers::NONE);
        assert_eq!(app.search_buf, "firex");
        handle_key(&mut app, KeyCode::Esc, KeyModifiers::NONE);
        assert!(app.search.is_empty(), "esc 应清除已应用过滤");
        assert!(app.search_buf.is_empty());
        assert!(app.menu == MenuState::None);
    }

    #[test]
    fn kill_pid_terminates_the_process() {
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .expect("spawn sleep");
        let pid = child.id();
        kill_pid(pid);
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert!(
            child.try_wait().expect("wait").is_some(),
            "child {pid} survived SIGTERM"
        );
    }

    /// 当前系统全部 pid(Linux 走 /proc,mac 走 sysctl KERN_PROC_ALL)
    fn all_pids() -> Vec<u32> {
        #[cfg(target_os = "linux")]
        {
            std::fs::read_dir("/proc")
                .expect("read /proc")
                .flatten()
                .filter_map(|e| e.file_name().to_string_lossy().parse::<u32>().ok())
                .collect()
        }
        #[cfg(target_os = "macos")]
        {
            crate::collect::macproc::list_pids()
                .into_iter()
                .map(|m| m.pid)
                .collect()
        }
    }

    /// pid 是否存活且 comm 为 name(comm 在 Linux/mac 都是 15 字符截断名)
    fn pid_runs(pid: u32, name: &str) -> bool {
        #[cfg(target_os = "linux")]
        {
            std::fs::read_to_string(format!("/proc/{pid}/comm"))
                .map(|c| c.trim() == name)
                .unwrap_or(false)
        }
        #[cfg(target_os = "macos")]
        {
            crate::collect::macproc::list_pids()
                .iter()
                .any(|m| m.pid == pid && m.comm == name)
        }
    }

    /// 找一个 comm == name 且非 exclude 的存活 pid
    fn find_running(name: &str, exclude: u32) -> Option<u32> {
        all_pids()
            .into_iter()
            .find(|&p| p != exclude && pid_runs(p, name))
    }

    #[test]
    fn start_cmd_launches_detached() {
        let before = all_pids();
        let new_pid =
            start_cmd(&["sleep".to_string(), "30".to_string()]).expect("spawn detached sleep");
        std::thread::sleep(std::time::Duration::from_millis(150));
        assert!(
            pid_runs(new_pid, "sleep"),
            "detached child must be alive and running sleep"
        );
        kill_pid(new_pid);
        std::thread::sleep(std::time::Duration::from_millis(300));
        // detached child is reaped by init; its pid must not have existed before
        assert!(!before.contains(&new_pid));
    }

    /// p/c focus: first press focuses, second press unfocuses — and unfocusing
    /// must also stop the two-line selection overlay from rendering (that
    /// lingering overlay read as "focus didn't cancel")
    #[test]
    fn p_and_c_second_press_cancels_focus() {
        use crossterm::event::KeyCode;
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = App::new(None);
        app.update();
        for (key, idx, other) in [
            (KeyCode::Char('p'), app::BOX_PROCS, app::BOX_CONNS),
            (KeyCode::Char('c'), app::BOX_CONNS, app::BOX_PROCS),
        ] {
            assert!(!app.focus[idx], "starts unfocused");
            handle_key(&mut app, key, KeyModifiers::empty());
            assert!(app.focus[idx], "first press focuses");
            assert!(!app.focus[other], "单焦点:另一盒熄灭");
            handle_key(&mut app, key, KeyModifiers::empty());
            assert!(!app.focus[idx], "second press cancels focus");
        }
        // p 后再 c:唯一焦点切换到 conns
        handle_key(&mut app, KeyCode::Char('p'), KeyModifiers::empty());
        handle_key(&mut app, KeyCode::Char('c'), KeyModifiers::empty());
        assert!(app.focus[app::BOX_CONNS] && !app.focus[app::BOX_PROCS]);
        // with a selection set, the two-line overlay (its "(pid N)" detail
        // line) renders while focused and disappears when focus is cancelled
        handle_key(&mut app, KeyCode::Char('p'), KeyModifiers::empty());
        app.proc.procs.push(crate::collect::proc::ProcRow {
            pid: 4242,
            name: "probe".into(),
            net_recv: 10,
            net_sent: 0,
            net_rr: 0.0,
            net_sr: 0.0,
            udp_recv: 0,
            udp_sent: 0,
            udp_rr: 0.0,
            udp_sr: 0.0,
            disk_r: 0,
            disk_w: 0,
            disk_rr: 0.0,
            disk_wr: 0.0,
            uptime_s: None,
            alive: true,
            cmdline: None,
        });
        app.proc.procs.shrink_to_fit();
        app.sel[app::BOX_PROCS] = Some(0);
        let buf_text = |term: &Terminal<TestBackend>| {
            let buf = term.backend().buffer();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect::<String>()
        };
        app.focus[app::BOX_PROCS] = true;
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| ui::draw(f, &app)).unwrap();
        assert!(
            buf_text(&term).contains("(pid "),
            "overlay renders while focused"
        );
        app.focus[app::BOX_PROCS] = false;
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| ui::draw(f, &app)).unwrap();
        assert!(
            !buf_text(&term).contains("(pid "),
            "overlay gone after unfocus"
        );
    }

    /// Esc on the main page clears all focus/selection; it must NOT open the
    /// menu — closing a popup with Esc must never land in another popup one
    /// press later. `m` keeps opening the menu.
    #[test]
    fn esc_clears_focus_and_m_opens_menu() {
        use crossterm::event::KeyCode;

        let mut app = App::new(None);
        app.focus[app::BOX_PROCS] = true;
        app.focus[app::BOX_CONNS] = true;
        app.sel[app::BOX_PROCS] = Some(2);
        handle_key(&mut app, KeyCode::Esc, KeyModifiers::empty());
        assert!(app.focus.iter().all(|&f| !f), "esc clears all focus");
        assert!(app.sel.iter().all(|&s| s.is_none()), "esc clears selection");
        assert!(app.menu == MenuState::None, "esc does not open the menu");
        handle_key(&mut app, KeyCode::Char('m'), KeyModifiers::empty());
        assert!(matches!(app.menu, MenuState::Main(_)), "m opens the menu");
    }

    /// 点击行点亮一个盒时必须熄灭其余:旧版点击只置位不清除,p 后点
    /// LAN 行会出现双焦点,绕过 p/c/l 键的单焦点不变量
    #[test]
    fn mouse_click_enforces_single_focus() {
        use crate::collect::proc::ProcRow;
        use crossterm::event::{KeyCode, MouseButton, MouseEvent, MouseEventKind};
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut app = App::new(None);
        // 注入合成进程,不依赖测试机的真实采样
        app.proc.procs.push(ProcRow {
            pid: 4242,
            name: "probe".into(),
            net_recv: 10,
            net_sent: 0,
            net_rr: 0.0,
            net_sr: 0.0,
            udp_recv: 0,
            udp_sent: 0,
            udp_rr: 0.0,
            udp_sr: 0.0,
            disk_r: 0,
            disk_w: 0,
            disk_rr: 0.0,
            disk_wr: 0.0,
            uptime_s: None,
            alive: true,
            cmdline: None,
        });
        // 先画一帧,再从 buffer 定位 PROCS 标题上标(⁶)拿点击坐标——
        // 不读 BOX_AREAS(全局态,并行测试互踩,见 layout 测试注释)
        let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
        term.draw(|f| ui::draw(f, &app)).unwrap();
        handle_key(&mut app, KeyCode::Char('l'), KeyModifiers::empty());
        assert!(app.focus[app::BOX_LAN], "l 点亮 lan");
        let buf = term.backend().buffer();
        let procs_title = (0..buf.area().height)
            .flat_map(|y| (0..buf.area().width).map(move |x| (x, y)))
            .find(|(x, y)| buf[(*x, *y)].symbol() == "\u{2076}")
            .expect("⁶procs 标题");
        // 点击标题行下两行 = 首个数据行(跳过边框+表头)。hit_box 内部读
        // BOX_AREAS 全局态,并行测试可能恰好清掉它,重绘重试消除竞态
        let m = MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: procs_title.0 + 2,
            row: procs_title.1 + 2,
            modifiers: KeyModifiers::empty(),
        };
        for _ in 0..20 {
            term.draw(|f| ui::draw(f, &app)).unwrap();
            handle_mouse(&mut app, &m);
            if app.focus[app::BOX_PROCS] {
                break;
            }
        }
        assert!(app.focus[app::BOX_PROCS], "点击 procs 行点亮 procs");
        assert!(!app.focus[app::BOX_LAN], "单焦点:lan 熄灭");
        assert!(!app.focus[app::BOX_CONNS], "单焦点:conns 熄灭");
    }

    /// 本发行版仅 x86_64:钉住 arch_guard 的通过路径(测试进程即 x86_64;
    /// 非 x86_64 分支是纯字符串比较,无法在测试内模拟)
    #[test]
    fn arch_guard_passes_on_x86_64() {
        assert!(arch_guard().is_ok());
    }

    /// 非 omarchy 跟随档(固定内嵌主题)时 poll 必须是 no-op:
    /// 固定主题就是用户显式选的,不能被外部文件改写
    #[test]
    fn poll_is_noop_when_not_following() {
        assert!(!theme::poll_omarchy_follow());
    }

    /// --help 文本必须覆盖全部入口参数与助手提示:改参数先改 usage_text,
    /// 这里防的是"加了参数忘了写帮助"。USAGE 行跟随调用名(自建软链别名同效)
    #[test]
    fn usage_covers_all_flags() {
        let u = usage_text("ltop");
        for flag in [
            "--dump",
            "--log",
            "--log-interval",
            "--follow-theme",
            "--replay",
            "--top",
            "--csv",
            "-h, --help",
            "-V, --version",
            "ltop-bpf",
            "watch",
            "report",
        ] {
            assert!(u.contains(flag), "usage 缺 {flag}");
        }
        assert!(u.contains("ltop [OPTIONS]"), "USAGE 用调用名");
        assert!(
            usage_text("myalias").contains("myalias [OPTIONS]"),
            "自建软链别名同版帮助(调用名跟随机制保留)"
        );
    }

    /// update() 必须把 LAN 选中纳入每 tick 锚定:数据驱动的重排只发生
    /// 在 sample() 阶段(捕获在前、采样在后),旧版 sel_anchor[LAN] 永远
    /// 为 None,主机名解析到达等重排会让选中漂移到别的对端
    #[test]
    fn update_anchors_lan_selection() {
        use crate::collect::lan::{LanSort, Neighbor};
        use std::net::Ipv4Addr;
        use std::time::Instant;

        let mut app = App::new(None);
        let mk = |ip: Ipv4Addr, host: &str| Neighbor {
            ip,
            mac: None,
            mac_hidden: false,
            iface: "eth0".into(),
            complete: true,
            hostname: Some(host.into()),
            is_gateway: false,
            is_self: false,
            last_seen: Instant::now(),
        };
        let a = Ipv4Addr::new(10, 0, 0, 2);
        let b = Ipv4Addr::new(10, 0, 0, 3);
        app.lan.neighbors.insert(a, mk(a, "zzz"));
        app.lan.neighbors.insert(b, mk(b, "aaa"));
        app.lan.sort = LanSort::Ip;
        app.sel[app::BOX_LAN] = Some(0);
        assert_eq!(
            ui::selected_id(&app, app::BOX_LAN),
            Some(u32::from(a) as u64)
        );
        app.update();
        assert_eq!(
            app.sel_anchor[app::BOX_LAN],
            Some(u32::from(a) as u64),
            "update 锚定 LAN 选中(旧版恒为 None)"
        );
        assert_eq!(
            ui::selected_id(&app, app::BOX_LAN),
            Some(u32::from(a) as u64),
            "采样后仍是同一主机"
        );
    }

    #[test]
    fn s_restarts_a_running_process_after_confirmation() {
        use crate::collect::proc::ProcRow;
        use crossterm::event::KeyCode;

        let mut child = std::process::Command::new("sleep")
            .arg("31")
            .spawn()
            .expect("spawn sleep 31");
        let pid = child.id();
        let mut app = App::new(None);
        app.proc.procs.push(ProcRow {
            pid,
            name: "sleep".into(),
            net_recv: 0,
            net_sent: 0,
            net_rr: 0.0,
            net_sr: 0.0,
            udp_recv: 0,
            udp_sent: 0,
            udp_rr: 0.0,
            udp_sr: 0.0,
            disk_r: 0,
            disk_w: 0,
            disk_rr: 0.0,
            disk_wr: 0.0,
            uptime_s: None,
            alive: true,
            cmdline: Some(vec!["sleep".into(), "31".into()]),
        });
        app.menu = MenuState::Detail(app::BOX_PROCS, u64::from(pid));
        handle_key(&mut app, KeyCode::Char('s'), KeyModifiers::empty());
        assert!(
            matches!(app.menu, MenuState::ConfirmRestart(_)),
            "s on a running process asks for confirmation"
        );
        // refusing changes nothing
        handle_key(&mut app, KeyCode::Char('n'), KeyModifiers::empty());
        assert!(app.menu == MenuState::None);
        std::thread::sleep(std::time::Duration::from_millis(150));
        assert!(child.try_wait().expect("poll").is_none(), "n must not kill");

        // confirming: SIGTERM the old instance, then relaunch in the worker
        app.menu = MenuState::Detail(app::BOX_PROCS, u64::from(pid));
        handle_key(&mut app, KeyCode::Char('s'), KeyModifiers::empty());
        handle_key(&mut app, KeyCode::Char('y'), KeyModifiers::empty());
        assert!(app.menu == MenuState::None);
        // reap the old instance promptly (the worker waits for the pid to
        // vanish via kill(0); a zombie lingers until the parent reaps it)
        let _ = child.wait();
        // give the worker time to notice and spawn the new one
        std::thread::sleep(std::time::Duration::from_millis(500));
        assert!(
            child.try_wait().expect("poll").is_some(),
            "old instance terminated"
        );
        let new_pid = find_running("sleep", pid).expect("relaunched sleep must be running");
        kill_pid(new_pid);
    }
}