gpuviewer-tui 0.2.2

gpuviewer — the GPU flight recorder (terminal UI + --json streaming)
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
//! Dashboard rendering: device tabs · charts · gauges · process table · the story feed.
//! Two modes share the layout: Live draws the RAM ring + latest tick, Replay draws the
//! cached rollup window around the cursor (see `app.rs`) — same panes, different source,
//! and every replay surface says so ("REPLAY") so recorded data is never mistaken for live.
//! The third mode, the timeline overview, swaps the panes for hour-scale strips with an
//! event lane (labeled "TIMELINE" with the same insistence).

use std::sync::atomic::Ordering;

use chrono::{Local, TimeZone};
use gpuviewer_core::{fmt_bytes, Confidence, Event, Severity, StaticInfo, Vendor};
use gpuviewer_history::{SampleRollup, Tier};
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols;
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Axis, Block, Borders, Chart, Dataset, Gauge, GraphType, List, ListItem, Row, Table, Tabs,
};
use ratatui::Frame;

use crate::app::{
    App, ChartStyle, Mode, ReplayBlock, ReplayWindow, TimelineWindow, TIMELINE_ZOOMS,
};
use crate::collector::Shared;

const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
/// Seconds of history shown in live charts.
const CHART_WINDOW_S: f64 = 300.0;
/// Seconds either side of the cursor shown in replay charts (matches the queried window).
const REPLAY_WINDOW_S: f64 = 300.0;

fn vendor_color(v: Vendor) -> Color {
    match v {
        Vendor::Nvidia => Color::Green,
        Vendor::Amd => Color::Red,
        Vendor::Intel => Color::Blue,
        Vendor::Apple => Color::White,
        Vendor::Unknown => Color::Gray,
    }
}

pub fn render(f: &mut Frame, app: &App, shared: &Shared) {
    // The timeline overview replaces the whole dashboard below the tabs; like
    // `replay_window()`, the accessor is `Some` only in its own mode.
    if let Some(w) = app.timeline_window() {
        render_timeline(f, app, shared, w);
        return;
    }

    let [tabs_a, main_a, story_a, footer_a] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(12),
        Constraint::Length(9),
        Constraint::Length(1),
    ])
    .areas(f.area());

    render_tabs(f, tabs_a, app, shared);

    let [charts_a, procs_a] =
        Layout::horizontal([Constraint::Percentage(62), Constraint::Percentage(38)]).areas(main_a);

    // `replay_window()` is `Some` only in replay mode, so a stale cache can never shadow
    // the live panes.
    let replay = app.replay_window();
    if let Some(info) = shared.infos.get(app.selected) {
        match replay {
            Some(w) => {
                render_charts_replay(f, charts_a, app, w, info);
                render_processes_replay(f, procs_a, app, w, info);
            }
            None => {
                render_charts(f, charts_a, app, shared, info);
                render_processes(f, procs_a, app, shared, info);
            }
        }
    }

    match replay {
        Some(w) => render_story_replay(f, story_a, app, w),
        None => render_story(f, story_a, app, shared),
    }
    render_footer(f, footer_a, app, shared);
}

fn render_tabs(f: &mut Frame, area: Rect, app: &App, shared: &Shared) {
    let titles: Vec<Line> = shared
        .infos
        .iter()
        .enumerate()
        .map(|(i, info)| {
            let mut spans = vec![
                Span::styled(
                    format!(" {} ", i),
                    Style::default()
                        .fg(Color::Black)
                        .bg(vendor_color(info.vendor)),
                ),
                Span::raw(format!(" {} ", info.name)),
            ];
            // A lost device is flagged in the strip itself so the dead tab is visible
            // while ANOTHER device is selected — per-device loss must never hide behind
            // tab selection (the footer stays quiet: the other devices are still live).
            if shared.lost.get(i).copied().flatten().is_some() {
                spans.push(Span::styled(
                    "LOST ",
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ));
            }
            Line::from(spans)
        })
        .collect();
    let tabs = Tabs::new(titles)
        .select(app.selected)
        .highlight_style(Style::default().add_modifier(Modifier::BOLD | Modifier::UNDERLINED));
    f.render_widget(tabs, area);
}

fn render_charts(f: &mut Frame, area: Rect, app: &App, shared: &Shared, info: &StaticInfo) {
    let [util_a, vram_a, gauges_a] = Layout::vertical([
        Constraint::Percentage(45),
        Constraint::Percentage(40),
        Constraint::Length(3),
    ])
    .areas(area);

    let now_ms = gpuviewer_core::now_ms() as f64;
    let hist = shared.history.device(&info.id);

    // Once the collector is dead — or THIS device stopped answering (device_lost) —
    // these headlines describe a frozen snapshot, not the present — tag them the way
    // replay tags its panes, so the values cannot read as current (the audit's
    // tick-panic frozen-UI hole, rendering half; same shape per-device).
    let device_lost = shared.lost.get(app.selected).copied().flatten().is_some();
    let stale_tag = if shared.stopped.is_some() || device_lost {
        " STALE"
    } else {
        ""
    };

    // Utilization chart.
    let util_pts: Vec<(f64, f64)> = hist
        .map(|h| {
            h.iter()
                .filter_map(|s| {
                    s.util_pct
                        .map(|u| ((s.ts_ms as f64 - now_ms) / 1000.0, u as f64))
                })
                .filter(|(x, _)| *x >= -CHART_WINDOW_S)
                .collect()
        })
        .unwrap_or_default();
    let latest_util = shared.latest[app.selected]
        .as_ref()
        .and_then(|s| s.util_pct)
        .map(|u| format!("{u:.0}%"))
        .unwrap_or_else(|| "—".into());
    // When the source's utilization is an engine headline (WDDM busiest engine), the
    // engine's name rides with the number — "Copy 97%" reads differently from "3D 97%".
    let engine_tag = shared.latest[app.selected]
        .as_ref()
        .and_then(|s| s.util_engine.as_deref())
        .map(|e| format!(" ({e})"))
        .unwrap_or_default();
    let util_segs = wave_segments(&util_pts, 1.0, app.chart_style);
    let ds = style_datasets(&util_segs, app.chart_style, Color::Cyan);
    let chart = Chart::new(ds)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" util {latest_util}{engine_tag}{stale_tag} "))
                .title_bottom(duty_cycle_caveat()),
        )
        .x_axis(Axis::default().bounds([-CHART_WINDOW_S, 0.0]))
        .y_axis(
            Axis::default()
                .bounds([0.0, 100.0])
                .labels(["0", "50", "100"]),
        );
    f.render_widget(chart, util_a);

    // VRAM chart.
    let vram_pts: Vec<(f64, f64)> = hist
        .map(|h| {
            h.iter()
                .filter_map(|s| {
                    s.mem_used_bytes
                        .map(|m| ((s.ts_ms as f64 - now_ms) / 1000.0, m as f64 / GIB))
                })
                .filter(|(x, _)| *x >= -CHART_WINDOW_S)
                .collect()
        })
        .unwrap_or_default();
    let latest_mem = shared.latest[app.selected]
        .as_ref()
        .and_then(|s| s.mem_used_bytes)
        .map(fmt_bytes)
        .unwrap_or_else(|| "—".into());
    render_vram_chart(
        f,
        vram_a,
        info,
        &vram_pts,
        &VramChartCtx {
            headline: &latest_mem,
            x_bounds: [-CHART_WINDOW_S, 0.0],
            title_tag: stale_tag,
            sample_w_s: 1.0,
            style: app.chart_style,
        },
    );

    // Gauge row reads the latest tick's sample.
    let latest = shared.latest[app.selected].as_ref();
    render_gauges(
        f,
        gauges_a,
        &GaugeValues {
            power_mw: latest.and_then(|s| s.power_mw),
            // The limit the driver enforces NOW (it can change mid-run); the startup
            // value only when this tick could not read it.
            power_limit_mw: latest
                .and_then(|s| s.power_limit_mw)
                .or(info.power_limit_mw),
            temp_c: latest.and_then(|s| s.temp_c),
            temp_slowdown_c: info.temp_slowdown_c,
            // None = this source cannot observe throttling (§5.4) — rendered as an
            // explicit "throttle n/a", never as an implied "not throttling".
            throttling: latest.and_then(|s| s.throttle).map(|t| t.any()),
            fan_pct: latest.and_then(|s| s.fan_pct),
            sm_clock_mhz: latest.and_then(|s| s.sm_clock_mhz),
            pcie: latest.and_then(|s| s.pcie_gen.zip(s.pcie_width)),
        },
    );
}

/// Replay charts: the 10s rollup window, x-axis in seconds relative to the cursor. The
/// chart titles carry the cursor bucket's value plus " REPLAY" so recorded data is never
/// mistaken for live.
fn render_charts_replay(f: &mut Frame, area: Rect, app: &App, w: &ReplayWindow, info: &StaticInfo) {
    let [util_a, vram_a, gauges_a] = Layout::vertical([
        Constraint::Percentage(45),
        Constraint::Percentage(40),
        Constraint::Length(3),
    ])
    .areas(area);

    let cursor = app.cursor_ms as f64;
    let samples: &[SampleRollup] = w
        .samples
        .get(app.selected)
        .map(Vec::as_slice)
        .unwrap_or(&[]);
    let at = bucket_at(samples, app.cursor_ms);

    // Utilization (bucket averages) across the window.
    let util_pts: Vec<(f64, f64)> = samples
        .iter()
        .filter_map(|r| {
            r.util_avg
                .map(|u| ((r.bucket_ms as f64 - cursor) / 1000.0, u as f64))
        })
        .collect();
    let cursor_util = at
        .and_then(|r| r.util_avg)
        .map(|u| format!("{u:.0}%"))
        .unwrap_or_else(|| "—".into());
    let bucket_w_s = Tier::TenSec.width_ms() as f64 / 1000.0;
    let util_segs = wave_segments(&util_pts, bucket_w_s, app.chart_style);
    let ds = style_datasets(&util_segs, app.chart_style, Color::Cyan);
    let chart = Chart::new(ds)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" util {cursor_util} REPLAY "))
                .title_bottom(duty_cycle_caveat()),
        )
        .x_axis(
            Axis::default()
                .bounds([-REPLAY_WINDOW_S, REPLAY_WINDOW_S])
                .labels(["-5m", "cursor", "+5m"]),
        )
        .y_axis(
            Axis::default()
                .bounds([0.0, 100.0])
                .labels(["0", "50", "100"]),
        );
    f.render_widget(chart, util_a);

    // VRAM (bucket averages).
    let vram_pts: Vec<(f64, f64)> = samples
        .iter()
        .filter_map(|r| {
            r.mem_avg
                .map(|m| ((r.bucket_ms as f64 - cursor) / 1000.0, m as f64 / GIB))
        })
        .collect();
    let cursor_mem = at
        .and_then(|r| r.mem_avg)
        .map(fmt_bytes)
        .unwrap_or_else(|| "—".into());
    render_vram_chart(
        f,
        vram_a,
        info,
        &vram_pts,
        &VramChartCtx {
            headline: &cursor_mem,
            x_bounds: [-REPLAY_WINDOW_S, REPLAY_WINDOW_S],
            title_tag: " REPLAY",
            sample_w_s: bucket_w_s,
            style: app.chart_style,
        },
    );

    // Gauge row reads the bucket at the cursor. Three states, not two: `throttle_n > 0`
    // is an observed throttle (fact); zero WITH observations is an observed all-clear;
    // zero with NO observations is a blind spot, and must render "n/a" exactly as live
    // does — flagging on `throttle_n > 0` alone reported every unobservable source as
    // quiet, which is the one thing replay must never do.
    render_gauges(
        f,
        gauges_a,
        &GaugeValues {
            power_mw: at.and_then(|r| r.power_avg_mw),
            power_limit_mw: info.power_limit_mw,
            temp_c: at.and_then(|r| r.temp_max_c),
            temp_slowdown_c: info.temp_slowdown_c,
            throttling: at.and_then(|r| bucket_throttling(r.throttle_n, r.throttle_observed_n)),
            fan_pct: at.and_then(|r| r.fan_max_pct),
            sm_clock_mhz: at.and_then(|r| r.sm_clock_avg),
            // Not in the rollups: a link width is a state, not a quantity to average.
            pcie: None,
        },
    );
}

/// The temp gauge's fill, or `None` when there is nothing to be a fraction OF.
///
/// A gauge's fill is a claim about proportion — "this far toward the limit". When the
/// driver never reported a slowdown threshold there is no limit to be a proportion of,
/// and filling toward an assumed one (this used to default to 95 °C) puts a number on
/// screen that no source ever produced. `None` means the caller draws an empty bar and
/// says why; a two-thirds-full bar against an invented ceiling says something false.
fn temp_gauge_ratio(temp_c: f32, slowdown_c: Option<f32>) -> Option<f64> {
    slowdown_c
        .filter(|s| *s > 0.0)
        .map(|s| (temp_c as f64 / s as f64).clamp(0.0, 1.0))
}

/// Replay's throttle reading for one recorded bucket — three states, not two.
///
/// `throttle_n` alone cannot answer this: zero means both "observed, and it was not
/// throttling" and "nothing here could ever see the bitmask" (wddm and apple by design,
/// NVML on a per-metric NOT_SUPPORTED, and every row written before schema v3). Reading
/// `throttle_n > 0` as the whole answer reported every blind bucket as an observed
/// all-clear — the live gauge has always distinguished the two, and replay must match it,
/// because replay is the mode this product is FOR.
fn bucket_throttling(throttle_n: u32, throttle_observed_n: u32) -> Option<bool> {
    match (throttle_n, throttle_observed_n) {
        // An observed-active frame is a fact regardless of the observed count, so a v2
        // row that recorded throttling still reads as throttling after migration.
        (n, _) if n > 0 => Some(true),
        (_, 0) => None,
        _ => Some(false),
    }
}

/// Consecutive points farther apart than this are not bridged: the trace breaks and the
/// blank stays, because a hole in the recording must look like a hole. Covers both the
/// 10s rollup spacing and the live cadence at its maximum idle-backoff stretch (10s).
const GAP_BRIDGE_S: f64 = 15.0;

/// Square-wave outline from sampled points: each value holds flat until the next sample,
/// then steps vertically — no diagonal interpolation smearing a 0→95 transition. Points
/// farther apart than [`GAP_BRIDGE_S`] start a new segment (rendered as separate
/// datasets), and each segment's last value is held for `trail_s`, the sample's real
/// width, so the newest bucket is drawn as wide as it actually is.
fn step_segments(pts: &[(f64, f64)], trail_s: f64) -> Vec<Vec<(f64, f64)>> {
    let mut segs: Vec<Vec<(f64, f64)>> = Vec::new();
    let mut cur: Vec<(f64, f64)> = Vec::new();
    for &(x, y) in pts {
        match cur.last().copied() {
            Some((px, py)) if x - px <= GAP_BRIDGE_S => {
                cur.push((x, py)); // hold the previous value to here…
                cur.push((x, y)); // …then step vertically
            }
            Some((px, py)) => {
                cur.push((px + trail_s, py));
                segs.push(std::mem::take(&mut cur));
                cur.push((x, y));
            }
            None => cur.push((x, y)),
        }
    }
    if let Some(&(px, py)) = cur.last() {
        cur.push((px + trail_s, py));
        segs.push(cur);
    }
    segs
}

/// Sub-point spacing when densifying a square wave for Bar paint, in x-units (seconds).
const SOLID_STEP_S: f64 = 2.0;

/// The square wave for `pts` in the active style. [`step_segments`] builds the
/// hold-then-step wave with its gap breaks for both styles; Solid additionally expands
/// each segment's horizontal holds into sub-points every [`SOLID_STEP_S`], because Bar
/// paints each point as an isolated column and without them the fill would show phantom
/// blank columns between samples that read as recording gaps. Sub-points never cross a
/// segment boundary, so real gaps stay exactly as blank as the outline draws them — the
/// two styles differ only in paint, never in values or gap semantics.
fn wave_segments(pts: &[(f64, f64)], trail_s: f64, style: ChartStyle) -> Vec<Vec<(f64, f64)>> {
    let segs = step_segments(pts, trail_s);
    match style {
        ChartStyle::Braille => segs,
        ChartStyle::Solid => segs
            .iter()
            .map(|seg| {
                let mut out: Vec<(f64, f64)> = Vec::with_capacity(seg.len() * 2);
                for pair in seg.windows(2) {
                    let ((x0, y0), (x1, _)) = (pair[0], pair[1]);
                    out.push((x0, y0));
                    // Fill the horizontal run; vertical steps (x1 == x0) add nothing.
                    let mut x = x0 + SOLID_STEP_S;
                    while x < x1 {
                        out.push((x, y0));
                        x += SOLID_STEP_S;
                    }
                }
                if let Some(&last) = seg.last() {
                    out.push(last);
                }
                out
            })
            .collect(),
    }
}

/// One dataset per gap-separated segment, painted per the chosen style: the braille step
/// outline, or commit 5352249's filled half-block columns.
fn style_datasets<'a>(
    segs: &'a [Vec<(f64, f64)>],
    style: ChartStyle,
    color: Color,
) -> Vec<Dataset<'a>> {
    let (marker, graph_type) = match style {
        ChartStyle::Braille => (symbols::Marker::Braille, GraphType::Line),
        ChartStyle::Solid => (symbols::Marker::HalfBlock, GraphType::Bar),
    };
    segs.iter()
        .map(|seg| {
            Dataset::default()
                .marker(marker)
                .graph_type(graph_type)
                .style(Style::default().fg(color))
                .data(seg)
        })
        .collect()
}

/// The 10s rollup covering `cursor_ms`, if recorded. Exact-bucket only: a cursor sitting
/// in a gap shows "—" on every gauge rather than a neighboring bucket's values.
fn bucket_at(samples: &[SampleRollup], cursor_ms: u64) -> Option<&SampleRollup> {
    let key = cursor_ms - cursor_ms % Tier::TenSec.width_ms();
    samples.iter().find(|r| r.bucket_ms == key)
}

/// Per-mode inputs to the shared VRAM chart: live and replay differ only in these.
struct VramChartCtx<'a> {
    headline: &'a str,
    x_bounds: [f64; 2],
    title_tag: &'a str,
    sample_w_s: f64,
    style: ChartStyle,
}

/// The VRAM chart, shared by live (raw ring samples) and replay (bucket averages): only
/// the points and the per-mode context differ.
/// The mandatory duty-cycle qualifier for the util chart.
///
/// Every vendor's "utilization" here means *the fraction of time at least one kernel was
/// resident* — not how much of the GPU's capacity was used. A device sitting at "100%"
/// can be nowhere near compute- or bandwidth-bound. The number is honest; presenting it
/// bare as "util" is what misleads, so the qualifier renders with the chart rather than
/// living only in the README.
fn duty_cycle_caveat() -> Line<'static> {
    Line::styled(
        " duty-cycle: time ≥1 kernel resident, not saturation ",
        Style::default().fg(Color::DarkGray).italic(),
    )
}

fn render_vram_chart(
    f: &mut Frame,
    area: Rect,
    info: &StaticInfo,
    pts: &[(f64, f64)],
    ctx: &VramChartCtx,
) {
    let total_gib = info.mem_total_bytes.map(|b| b as f64 / GIB).unwrap_or(0.0);
    let total_label = info
        .mem_total_bytes
        .map(fmt_bytes)
        .unwrap_or_else(|| "?".into());
    let segs = wave_segments(pts, ctx.sample_w_s, ctx.style);
    let ds = style_datasets(&segs, ctx.style, Color::Magenta);
    let y_max = if total_gib > 0.0 { total_gib } else { 1.0 };
    let y_max_label = format!("{y_max:.0}G");
    let mut block = Block::default().borders(Borders::ALL).title(format!(
        " vram {} / {total_label}{} ",
        ctx.headline, ctx.title_tag
    ));
    // The §5.4 mandatory honesty label, rendered exactly where the qualified number is:
    // on Apple the "total" is a unified-memory working-set budget, on WDDM the headline
    // util is a busiest-engine duty-cycle — without this line the chart would mislabel.
    if let Some(caveat) = &info.source_caveat {
        block = block.title_bottom(Line::styled(
            format!(" {caveat} "),
            Style::default().fg(Color::DarkGray).italic(),
        ));
    }
    let chart = Chart::new(ds)
        .block(block)
        .x_axis(Axis::default().bounds(ctx.x_bounds))
        .y_axis(
            Axis::default()
                .bounds([0.0, y_max])
                .labels(["0", y_max_label.as_str()]),
        );
    f.render_widget(chart, area);
}

/// Columns the timeline strips span at `frame_width`: the frame minus the strips' side
/// borders. The event loop calls this too (see `App::timeline_cols`), so a cursor step is
/// exactly one rendered column.
pub(crate) fn timeline_strip_cols(frame_width: u16) -> usize {
    frame_width.saturating_sub(2).max(1) as usize
}

/// Fold tier buckets into per-column peaks for the timeline strips. Column `c` owns the
/// time range `[from + c·span/n, from + (c+1)·span/n)`; every bucket overlapping that
/// range contributes, and the column takes the MAX — forensics wants the peaks, a mean
/// would iron out the very spikes worth scrolling back for. `None` means the column's
/// whole range holds nothing recorded — rendered blank, because unrecorded time must look
/// like a hole, never like zero (a bucket whose metric is absent also paints nothing:
/// "unavailable" is not zero either).
///
/// Mapping buckets→columns by range overlap (not nearest-column rounding) is what kills
/// the quantization trap: with N buckets across M columns, a naive x-mapping leaves
/// periodic one-column blanks indistinguishable from real recording gaps.
pub(crate) fn timeline_columns(
    samples: &[SampleRollup],
    from_ms: u64,
    to_ms: u64,
    bucket_w_ms: u64,
    ncols: usize,
    metric: impl Fn(&SampleRollup) -> Option<f64>,
) -> Vec<Option<f64>> {
    let mut cols: Vec<Option<f64>> = vec![None; ncols];
    let span = to_ms.saturating_sub(from_ms);
    if span == 0 || ncols == 0 {
        return cols;
    }
    for r in samples {
        // The slice of the bucket `[bucket_ms, bucket_ms + width)` inside the window.
        let b0 = r.bucket_ms.max(from_ms);
        let b1 = r.bucket_ms.saturating_add(bucket_w_ms).min(to_ms);
        if b1 <= b0 {
            continue;
        }
        let Some(v) = metric(r) else { continue };
        // First and last column whose range the slice overlaps (floor mapping, end
        // exclusive — hence b1 - 1).
        let c0 = ((b0 - from_ms) * ncols as u64 / span) as usize;
        let c1 = (((b1 - 1) - from_ms) * ncols as u64 / span) as usize;
        for col in cols.iter_mut().take(c1.min(ncols - 1) + 1).skip(c0) {
            *col = Some(col.map_or(v, |prev| prev.max(v)));
        }
    }
    cols
}

/// The column owning timestamp `ts_ms`, under the same floor mapping as
/// [`timeline_columns`], clamped into range. `ncols` must be ≥ 1.
fn timeline_col_of(ts_ms: u64, from_ms: u64, span_ms: u64, ncols: usize) -> usize {
    ((ts_ms.saturating_sub(from_ms) * ncols as u64 / span_ms.max(1)) as usize).min(ncols - 1)
}

/// The timeline overview: hours of recorded history per screen — the altitude above
/// replay. For the selected device, a solid util strip stacked on a solid VRAM strip
/// (always solid regardless of the chart-style toggle: at minutes per column, fill reads
/// as shape and an outline reads as noise), then a one-row event lane and a cursor
/// readout. Columns with nothing recorded stay blank — a hole, never a zero.
fn render_timeline(f: &mut Frame, app: &App, shared: &Shared, w: &TimelineWindow) {
    let [tabs_a, util_a, vram_a, lane_a, status_a, footer_a] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Fill(1),
        Constraint::Fill(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
    ])
    .areas(f.area());

    render_tabs(f, tabs_a, app, shared);

    let ncols = timeline_strip_cols(f.area().width);
    let span_ms = w.to_ms.saturating_sub(w.from_ms).max(1);
    let col_label = fmt_span((span_ms / ncols as u64).max(1));
    let bucket_w_ms = w.tier.width_ms();
    let samples: &[SampleRollup] = w
        .samples
        .get(app.selected)
        .map(Vec::as_slice)
        .unwrap_or(&[]);
    let cursor_col = timeline_col_of(app.timeline_cursor_ms, w.from_ms, span_ms, ncols);

    // util strip: per-column peak of each bucket's recorded max.
    let util_cols = timeline_columns(samples, w.from_ms, w.to_ms, bucket_w_ms, ncols, |r| {
        r.util_max.map(f64::from)
    });
    let util_top = util_cols.iter().flatten().copied().fold(100.0, f64::max);
    render_timeline_strip(
        f,
        util_a,
        &util_cols,
        util_top,
        Color::Cyan,
        format!(" util % — peak per col, 1 col ≈ {col_label} — TIMELINE "),
        None,
    );

    // VRAM strip, scaled to the device total — but never below the observed peak: a
    // value painted off the top of the chart would vanish, and a vanished column reads
    // as a recording gap.
    let info = shared.infos.get(app.selected);
    let total_label = info
        .and_then(|i| i.mem_total_bytes)
        .map(fmt_bytes)
        .unwrap_or_else(|| "?".into());
    let total_gib = info
        .and_then(|i| i.mem_total_bytes)
        .map(|b| b as f64 / GIB)
        .unwrap_or(0.0);
    let vram_cols = timeline_columns(samples, w.from_ms, w.to_ms, bucket_w_ms, ncols, |r| {
        r.mem_max.map(|m| m as f64 / GIB)
    });
    let vram_top = vram_cols
        .iter()
        .flatten()
        .copied()
        .fold(total_gib.max(1.0), f64::max);
    render_timeline_strip(
        f,
        vram_a,
        &vram_cols,
        vram_top,
        Color::Magenta,
        format!(" vram / {total_label} — peak per col, 1 col ≈ {col_label} — TIMELINE "),
        // Same §5.4 label as the live/replay chart — the qualified number is the same.
        info.and_then(|i| i.source_caveat.as_deref()),
    );

    render_timeline_lane(f, lane_a, w, ncols, cursor_col);
    render_timeline_status(f, status_a, app, w, &util_cols, &vram_cols, cursor_col);
    render_footer(f, footer_a, app, shared);
}

/// One solid strip: each rendered column is an independent half-block bar (commit
/// 5352249's filled technique), so a blank column means exactly one thing — nothing was
/// recorded in the time it owns. `x_bounds [0, ncols-1]` with one point per column index
/// maps data columns 1:1 onto terminal columns (the painter scales by resolution − 1),
/// so no quantization can fake a gap or paper over one; the axes carry no labels because
/// a label gutter would shrink the paint area and break that mapping. A recorded zero
/// still paints the bottom half-block — visibly different from a hole.
fn render_timeline_strip(
    f: &mut Frame,
    area: Rect,
    cols: &[Option<f64>],
    y_max: f64,
    color: Color,
    title: String,
    caveat: Option<&str>,
) {
    let pts: Vec<(f64, f64)> = cols
        .iter()
        .enumerate()
        .filter_map(|(c, v)| v.map(|v| (c as f64, v)))
        .collect();
    let ds = vec![Dataset::default()
        .marker(symbols::Marker::HalfBlock)
        .graph_type(GraphType::Bar)
        .style(Style::default().fg(color))
        .data(&pts)];
    let mut block = Block::default().borders(Borders::ALL).title(title);
    if let Some(caveat) = caveat {
        block = block.title_bottom(Line::styled(
            format!(" {caveat} "),
            Style::default().fg(Color::DarkGray).italic(),
        ));
    }
    let chart = Chart::new(ds)
        .block(block)
        .x_axis(Axis::default().bounds([0.0, (cols.len().max(2) - 1) as f64]))
        .y_axis(Axis::default().bounds([0.0, y_max.max(1.0)]));
    f.render_widget(chart, area);
}

/// The event lane: one marker cell per strip column. Facts keep their story-feed
/// severity icon; "likely" inferences show an italic '?' — the one-cell echo of the
/// feed's italic "likely" tag. Columns holding several events merge into a count ('+'
/// past 9) in the most severe member's color. The cursor cell is REVERSED, like every
/// other selection in the UI (cyan when it sits on empty time).
fn render_timeline_lane(
    f: &mut Frame,
    area: Rect,
    w: &TimelineWindow,
    ncols: usize,
    cursor_col: usize,
) {
    let span_ms = w.to_ms.saturating_sub(w.from_ms).max(1);
    let mut cells: Vec<Vec<&Event>> = vec![Vec::new(); ncols];
    for e in &w.events {
        if e.ts_ms < w.from_ms || e.ts_ms > w.to_ms {
            continue;
        }
        cells[timeline_col_of(e.ts_ms, w.from_ms, span_ms, ncols)].push(e);
    }
    // One left-margin space keeps lane cell `i` under strip column `i` (the strips sit
    // inside a one-cell border).
    let mut spans: Vec<Span> = Vec::with_capacity(ncols + 1);
    spans.push(Span::raw(" "));
    for (c, evs) in cells.iter().enumerate() {
        let (label, mut style) = match evs.as_slice() {
            [] => (" ".to_string(), Style::default()),
            [e] => lane_marker(e),
            many => {
                let sev = many
                    .iter()
                    .map(|e| e.severity)
                    .max_by_key(|s| severity_rank(*s))
                    .unwrap_or(Severity::Info);
                let label = if many.len() <= 9 {
                    many.len().to_string()
                } else {
                    "+".to_string()
                };
                let (_, color) = severity_marker(sev);
                (
                    label,
                    Style::default().fg(color).add_modifier(Modifier::BOLD),
                )
            }
        };
        if c == cursor_col {
            if evs.is_empty() {
                style = style.fg(Color::Cyan);
            }
            style = style.add_modifier(Modifier::REVERSED);
        }
        spans.push(Span::styled(label, style));
    }
    f.render_widget(Line::from(spans), area);
}

/// A single event's lane cell.
fn lane_marker(e: &Event) -> (String, Style) {
    let (icon, color) = severity_marker(e.severity);
    if e.confidence == Confidence::Likely {
        ("?".to_string(), Style::default().fg(color).italic())
    } else {
        (icon.to_string(), Style::default().fg(color))
    }
}

/// Cursor readout under the lane: wall-clock, the strips' values at the cursor column
/// ("—" when the column is blank — a gap stays a gap even in text), and the window's
/// nearest event rendered with its story-feed styling (so "likely" stays labeled).
fn render_timeline_status(
    f: &mut Frame,
    area: Rect,
    app: &App,
    w: &TimelineWindow,
    util_cols: &[Option<f64>],
    vram_cols: &[Option<f64>],
    cursor_col: usize,
) {
    let util = util_cols
        .get(cursor_col)
        .copied()
        .flatten()
        .map(|v| format!("{v:.0}%"))
        .unwrap_or_else(|| "—".into());
    let vram = vram_cols
        .get(cursor_col)
        .copied()
        .flatten()
        .map(|v| format!("{v:.1} GiB"))
        .unwrap_or_else(|| "—".into());
    let mut spans = vec![
        Span::styled(
            format!(" cursor {} ", fmt_clock(app.timeline_cursor_ms)),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(format!("· util {util} · vram {vram} ")),
    ];
    let nearest = w
        .events
        .iter()
        .min_by_key(|e| e.ts_ms.abs_diff(app.timeline_cursor_ms));
    if let Some(e) = nearest {
        spans.push(Span::styled(
            "· nearest ",
            Style::default().fg(Color::DarkGray),
        ));
        spans.extend(event_line(e).spans);
    }
    f.render_widget(Line::from(spans), area);
}

/// Compact duration label: "45s", "2m", "1h30m", "7d". Sub-second spans (a very narrow
/// column at a very short window) say "<1s" rather than rounding up to a lie.
fn fmt_span(ms: u64) -> String {
    if ms < 1000 {
        return "<1s".into();
    }
    let s = ms / 1000;
    let (d, h, m, rs) = (s / 86_400, s % 86_400 / 3_600, s % 3_600 / 60, s % 60);
    if d > 0 {
        if h > 0 {
            format!("{d}d{h}h")
        } else {
            format!("{d}d")
        }
    } else if h > 0 {
        if m > 0 {
            format!("{h}h{m:02}m")
        } else {
            format!("{h}h")
        }
    } else if m > 0 {
        if rs > 0 {
            format!("{m}m{rs:02}s")
        } else {
            format!("{m}m")
        }
    } else {
        format!("{s}s")
    }
}

/// The gauge row's inputs, shared by live (latest sample) and replay (bucket at cursor).
/// Every field is `Option`: an absent metric renders "—", never a fake zero.
struct GaugeValues {
    power_mw: Option<u32>,
    power_limit_mw: Option<u32>,
    temp_c: Option<f32>,
    temp_slowdown_c: Option<f32>,
    /// Whether the temp gauge flags throttling. `Some(true)`: observed active (live:
    /// current bits; replay: ≥1 observed-active frame in the cursor's bucket).
    /// `Some(false)`: observed quiet. `None`: unobservable on this source (§5.4) — the
    /// gauge says "throttle n/a" instead of implying quiet.
    throttling: Option<bool>,
    fan_pct: Option<f32>,
    sm_clock_mhz: Option<u32>,
    /// Current PCIe link (generation, width) — live only; the rollups do not carry it.
    pcie: Option<(u32, u32)>,
}

/// Gauge row: power · temp · fan/clock.
fn render_gauges(f: &mut Frame, area: Rect, v: &GaugeValues) {
    let [pw_a, tp_a, fc_a] = Layout::horizontal([
        Constraint::Ratio(1, 3),
        Constraint::Ratio(1, 3),
        Constraint::Ratio(1, 3),
    ])
    .areas(area);

    let (p_ratio, p_label) = match (v.power_mw, v.power_limit_mw) {
        (Some(p), Some(lim)) if lim > 0 => (
            (p as f64 / lim as f64).clamp(0.0, 1.0),
            format!("{:.0}W / {:.0}W", p as f64 / 1000.0, lim as f64 / 1000.0),
        ),
        (Some(p), _) => (0.0, format!("{:.0}W", p as f64 / 1000.0)),
        _ => (0.0, "—".into()),
    };
    f.render_widget(
        Gauge::default()
            .block(Block::default().borders(Borders::ALL).title(" power "))
            .ratio(p_ratio)
            .gauge_style(Style::default().fg(Color::Yellow))
            .label(p_label),
        pw_a,
    );

    let (t_ratio, t_label, t_color) = match v.temp_c {
        Some(t) => {
            // A gauge's FILL is a claim about proportion: "this far toward the limit".
            // Making one up when the limit is unknown (this was `unwrap_or(95.0)`) puts a
            // number on screen that no source ever reported — a bar reading two-thirds
            // full against a slowdown point the driver never gave us. When the threshold
            // is absent the bar makes no proportional claim at all and the label says why,
            // so an empty bar reads as "no scale" rather than "cold".
            let scale = temp_gauge_ratio(t, v.temp_slowdown_c);
            let throttle_note = match v.throttling {
                Some(true) => " ⚠ THROTTLING",
                Some(false) => "",
                // Unobservable ≠ quiet: say so where the flag would appear.
                None => " · throttle n/a",
            };
            let label = match scale {
                Some(_) => format!("{t:.0}°C{throttle_note}"),
                None => format!("{t:.0}°C{throttle_note} · scale n/a"),
            };
            (
                scale.unwrap_or(0.0),
                label,
                if v.throttling == Some(true) {
                    Color::Red
                } else {
                    Color::Green
                },
            )
        }
        None => (0.0, "—".into(), Color::Green),
    };
    f.render_widget(
        Gauge::default()
            .block(Block::default().borders(Borders::ALL).title(" temp "))
            .ratio(t_ratio)
            .gauge_style(Style::default().fg(t_color))
            .label(t_label),
        tp_a,
    );

    let fan = v
        .fan_pct
        .map(|p| format!("fan {p:.0}%"))
        .unwrap_or_else(|| "fan —".into());
    let clk = v
        .sm_clock_mhz
        .map(|c| format!("{c} MHz"))
        .unwrap_or_else(|| "— MHz".into());
    let fan_ratio = v
        .fan_pct
        .map(|p| (p as f64 / 100.0).clamp(0.0, 1.0))
        .unwrap_or(0.0);
    // The link only shows where a source reports it (NVML); elsewhere it is omitted
    // rather than printed as "—" — the gauge row has no room for a column of dashes.
    let link = v
        .pcie
        .map(|(g, w)| format!(" · Gen{g} x{w}"))
        .unwrap_or_default();
    f.render_widget(
        Gauge::default()
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(" fan · clock "),
            )
            .ratio(fan_ratio)
            .gauge_style(Style::default().fg(Color::Blue))
            .label(format!("{fan} · {clk}{link}")),
        fc_a,
    );
}

/// Process table column widths (shared by live and replay).
const PROC_WIDTHS: [Constraint; 6] = [
    Constraint::Length(7),
    Constraint::Min(10),
    Constraint::Length(4),
    Constraint::Length(9),
    Constraint::Length(6),
    Constraint::Length(6),
];

fn proc_header() -> Row<'static> {
    Row::new(vec!["pid", "name", "type", "mem", "util", "cpu"]).style(
        Style::default()
            .add_modifier(Modifier::BOLD)
            .fg(Color::DarkGray),
    )
}

/// "python train.py --cfg big [docker:3f2a9c1b]" — the command line (when captured)
/// tells three `python` processes apart, and the container identity rides with it so a
/// containerized workload is recognizable at a glance. Without a captured command line
/// the process name stands alone.
fn proc_display_name(name: &str, cmdline: Option<&str>, container: Option<&str>) -> String {
    let base = cmdline.unwrap_or(name);
    match container {
        Some(c) => format!("{base} [{c}]"),
        None => base.to_string(),
    }
}

fn fmt_opt_pct(v: Option<f32>) -> String {
    v.map(|p| format!("{p:.0}%")).unwrap_or_else(|| "—".into())
}

/// The process pane's block, with the `process_hint` (WSL2 driver limitation, privilege
/// wall) surfaced right where the user is looking for the missing rows. The hint applies
/// in replay too: the recording only ever held what the collector could see.
fn proc_block(info: &StaticInfo) -> Block<'static> {
    let mut block = Block::default().borders(Borders::ALL).title(" processes ");
    if let Some(hint) = &info.process_hint {
        block = block.title_bottom(Line::styled(
            format!(" {hint} "),
            Style::default().fg(Color::DarkGray).italic(),
        ));
    }
    block
}

fn render_processes(f: &mut Frame, area: Rect, app: &App, shared: &Shared, info: &StaticInfo) {
    let mut procs = shared.processes[app.selected].clone();
    procs.sort_by_key(|p| std::cmp::Reverse(p.mem_bytes.unwrap_or(0)));

    let rows: Vec<Row> = procs
        .iter()
        .map(|p| {
            Row::new(vec![
                p.pid.to_string(),
                proc_display_name(&p.name, p.cmdline.as_deref(), p.container.as_deref()),
                p.kind.label().to_string(),
                p.mem_bytes.map(fmt_bytes).unwrap_or_else(|| "—".into()),
                fmt_opt_pct(p.util_pct),
                fmt_opt_pct(p.cpu_pct),
            ])
        })
        .collect();

    let mut block = proc_block(info);
    if shared.stopped.is_some() {
        // The list is the last one collected, not the present process set — say so where
        // the user is looking, like the charts' STALE tag.
        block = block.title_bottom(Line::styled(
            " stale — collection stopped ",
            Style::default().fg(Color::Red).italic(),
        ));
    } else if let Some(at) = shared.lost.get(app.selected).copied().flatten() {
        // The per-device flavor of the same affordance: this device stopped answering,
        // so its list (and the charts' frozen tails) are the last data it gave. The age
        // is measured from the last good SAMPLE, not the loss declaration — the data
        // went quiet before the verdict did.
        let age = shared.latest[app.selected]
            .as_ref()
            .map(|s| {
                format!(
                    "last data {} ago",
                    fmt_span(gpuviewer_core::now_ms().saturating_sub(s.ts_ms))
                )
            })
            .unwrap_or_else(|| "no data this session".into());
        block = block.title_bottom(Line::styled(
            format!(" stale — device lost {}, {age} ", fmt_clock(at)),
            Style::default().fg(Color::Red).italic(),
        ));
    }
    let table = Table::new(rows, PROC_WIDTHS)
        .header(proc_header())
        .block(block);
    f.render_widget(table, area);
}

/// Replay process table: the 10s rollup bucket at the cursor (`processes_at`), with the
/// bucket's peak memory and mean util/cpu per process.
fn render_processes_replay(
    f: &mut Frame,
    area: Rect,
    app: &App,
    w: &ReplayWindow,
    info: &StaticInfo,
) {
    let mut procs = w.processes.get(app.selected).cloned().unwrap_or_default();
    procs.sort_by_key(|p| std::cmp::Reverse(p.mem_max.unwrap_or(0)));

    let rows: Vec<Row> = procs
        .iter()
        .map(|p| {
            Row::new(vec![
                p.pid.to_string(),
                proc_display_name(&p.name, p.cmdline.as_deref(), p.container.as_deref()),
                p.kind.label().to_string(),
                p.mem_max.map(fmt_bytes).unwrap_or_else(|| "—".into()),
                fmt_opt_pct(p.util_avg),
                fmt_opt_pct(p.cpu_avg),
            ])
        })
        .collect();

    let table = Table::new(rows, PROC_WIDTHS)
        .header(proc_header())
        .block(proc_block(info));
    f.render_widget(table, area);
}

fn render_story(f: &mut Frame, area: Rect, app: &App, shared: &Shared) {
    let cap = area.height.saturating_sub(2) as usize;
    let sel = app.story_selected;
    // Newest first; skip just enough of the newest rows to keep the selection visible.
    let skip = sel.map_or(0, |s| s.saturating_sub(cap.saturating_sub(1)));
    let items: Vec<ListItem> = shared
        .history
        .events()
        .iter()
        .rev()
        .filter(|e| app.story_filter.admits(e))
        .enumerate()
        .skip(skip)
        .take(cap)
        .map(|(i, e)| {
            let mut line = event_line(e);
            if Some(i) == sel {
                line = line.style(Style::default().add_modifier(Modifier::REVERSED));
            }
            ListItem::new(line)
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .title(match app.story_filter.label() {
                Some(l) => format!(" story — what changed and why [{l}] "),
                None => " story — what changed and why ".to_string(),
            })
            .title_style(Style::default().add_modifier(Modifier::BOLD)),
    );
    f.render_widget(list, area);
}

/// Replay story feed: the window's events in chronological order, with a marker row
/// anchoring the cursor's own place in time among them.
fn render_story_replay(f: &mut Frame, area: Rect, app: &App, w: &ReplayWindow) {
    let cap = area.height.saturating_sub(2) as usize;
    let marker_at = w
        .events
        .iter()
        .take_while(|e| e.ts_ms <= app.cursor_ms)
        .count();
    let mut rows: Vec<(Option<usize>, Line)> = Vec::with_capacity(w.events.len() + 1);
    let mut marker_row = None;
    for (i, e) in w.events.iter().enumerate() {
        if i == marker_at {
            marker_row = Some(rows.len());
            rows.push((None, cursor_line(app.cursor_ms)));
        }
        if app.story_filter.admits(e) {
            rows.push((Some(i), event_line(e)));
        }
    }
    if marker_at == w.events.len() {
        marker_row = Some(rows.len());
        rows.push((None, cursor_line(app.cursor_ms)));
    }

    // Keep the selected row (or, with nothing selected, the cursor marker) visible.
    let marker_row = marker_row.unwrap_or(0);
    let focus = app
        .story_selected
        .and_then(|s| rows.iter().position(|(idx, _)| *idx == Some(s)))
        .unwrap_or(marker_row);
    let skip = focus.saturating_sub(cap.saturating_sub(1));
    let items: Vec<ListItem> = rows
        .into_iter()
        .skip(skip)
        .take(cap)
        .map(|(idx, line)| {
            let line = if idx.is_some() && idx == app.story_selected {
                line.style(Style::default().add_modifier(Modifier::REVERSED))
            } else {
                line
            };
            ListItem::new(line)
        })
        .collect();

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .title(format!(
                " story — events {}–{}{} ",
                fmt_clock(w.from_ms),
                fmt_clock(w.to_ms),
                app.story_filter
                    .label()
                    .map(|l| format!(" [{l}]"))
                    .unwrap_or_default()
            ))
            .title_style(Style::default().add_modifier(Modifier::BOLD)),
    );
    f.render_widget(list, area);
}

/// The cursor's own row in the replay story feed — "you are here" among the events.
fn cursor_line(cursor_ms: u64) -> Line<'static> {
    Line::styled(
        format!("── cursor {} ──", fmt_clock(cursor_ms)),
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )
}

/// Story-feed severity → (icon, color); shared by the feed rows and the timeline lane.
fn severity_marker(s: Severity) -> (&'static str, Color) {
    match s {
        Severity::Critical => ("✖", Color::Red),
        Severity::Warning => ("⚠", Color::Yellow),
        Severity::Info => ("·", Color::DarkGray),
    }
}

/// Severity ordering for merged lane markers (the enum is wire-ordered, not `Ord`).
fn severity_rank(s: Severity) -> u8 {
    match s {
        Severity::Info => 0,
        Severity::Warning => 1,
        Severity::Critical => 2,
    }
}

fn event_line(e: &Event) -> Line<'static> {
    let ts = fmt_clock(e.ts_ms);
    let (icon, color) = severity_marker(e.severity);

    let mut spans = vec![
        Span::styled(format!("{ts} "), Style::default().fg(Color::DarkGray)),
        Span::styled(format!("{icon} "), Style::default().fg(color)),
    ];
    if e.confidence == Confidence::Likely {
        spans.push(Span::styled(
            "likely ".to_string(),
            Style::default().fg(Color::DarkGray).italic(),
        ));
    }
    spans.push(Span::styled(e.title.clone(), Style::default().fg(color)));
    Line::from(spans)
}

/// Wall HH:MM:SS for event rows and the replay cursor.
fn fmt_clock(ms: u64) -> String {
    Local
        .timestamp_millis_opt(ms as i64)
        .single()
        .map(|t| t.format("%H:%M:%S").to_string())
        .unwrap_or_else(|| "--:--:--".into())
}

fn render_footer(f: &mut Frame, area: Rect, app: &App, shared: &Shared) {
    // "(mock data)" must appear exactly when the data IS mock: a footer that calls
    // live NVML data mock (or vice versa) is the confidently-wrong labeling this
    // product exists to avoid. The rule holds in replay too — a mock run records to
    // the mock database, so its replay is also mock data.
    let mock_tag = if shared.mock { " (mock data)" } else { "" };
    // A dead collector outranks every hint: in the live mode the panes are frozen at the
    // stop, so the footer becomes the stop banner — when, why, and what the panes now
    // mean. (Replay and the timeline already label their data as recorded history; the
    // live view is the one place stale data could masquerade as current.)
    if app.mode == Mode::Live {
        if let Some(stop) = &shared.stopped {
            let line = Line::from(format!(
                " ✖ COLLECTION STOPPED {} — collector panicked: {} — panes show the last \
                 data before the stop · q quit{mock_tag}",
                fmt_clock(stop.at_ms),
                stop.reason
            ))
            .style(Style::default().fg(Color::Red).add_modifier(Modifier::BOLD))
            .alignment(Alignment::Left);
            f.render_widget(line, area);
            return;
        }
    }
    let text = match app.mode {
        // The file viewer has no live mode behind the recording, so the "esc live" hint
        // would be a dead key dressed as a feature — the file's name and the read-only
        // promise take its place. Provenance is unstated, so no mock/live claim either.
        // Key hints name the letter aliases, not pgup/pgdn/home/end: the letters exist
        // on every keyboard (Mac laptops have none of those four keys), the legacy keys
        // still work, and the README documents the full matrix.
        Mode::Replay => match app.view_file() {
            Some(file) => format!(
                " REPLAY {}  viewing {file} (read-only) · q quit · enter jump to event · \
                 ←→/ad scrub 10s · A/D 5m · g/G ends · t timeline · c style · f filter",
                fmt_clock(app.cursor_ms)
            ),
            None => format!(
                " REPLAY {}  esc live · enter jump to event · ←→/ad scrub 10s · A/D 5m · \
                 g/G ends · t timeline · c style · f filter  (10s rollups, 48h retention){mock_tag}",
                fmt_clock(app.cursor_ms)
            ),
        },
        Mode::Timeline => {
            // Esc backs out to where 't' was pressed from — except in the file viewer,
            // which is pinned to replay (no live view exists behind a recording).
            let back = if app.view_file().is_some() {
                "replay"
            } else {
                "live"
            };
            let viewing = app
                .view_file()
                .map(|file| format!("  viewing {file} (read-only)"))
                .unwrap_or_default();
            let zoom = TIMELINE_ZOOMS[app.timeline_zoom].label;
            // A recording younger than the zoom window: say what is actually on screen.
            let span_note = app
                .timeline_window()
                .filter(|w| w.clamped)
                .map(|w| {
                    format!(
                        " ({} recorded)",
                        fmt_span(w.to_ms.saturating_sub(w.from_ms))
                    )
                })
                .unwrap_or_default();
            format!(
                " TIMELINE {zoom}{span_note}{viewing}  t/esc {back} · +/- zoom · ←→/ad cursor · \
                 A/D jump · g/G ends · enter drill to replay · q quit{mock_tag}"
            )
        }
        Mode::Live => {
            let paused = if app.paused() { " · PAUSED" } else { "" };
            // Surface the stretched cadence whenever low-power backoff is active, so a
            // sparser chart is explained rather than mistaken for missing data.
            let eff = shared.effective_interval_ms.load(Ordering::Relaxed);
            let cadence = if eff > shared.interval_ms {
                if eff.is_multiple_of(1000) {
                    format!(" · low-power cadence {}s", eff / 1000)
                } else {
                    format!(" · low-power cadence {:.1}s", eff as f64 / 1000.0)
                }
            } else {
                String::new()
            };
            // Name the actual cause. Printing "--no-persist is set" for an unreadable
            // database would assert a flag the user never passed.
            let hint = match app.replay_hint {
                Some(ReplayBlock::NoPersistence) => {
                    " · replay needs persistence (--no-persist is set)"
                }
                Some(ReplayBlock::Unreadable) => " · replay unavailable (history db unreadable)",
                None => "",
            };
            format!(
                " q quit · ←→/ad/tab device · p pause{paused} · ↑↓/ws story · enter/r replay · \
                 t timeline · c style · f filter{cadence}{hint}  —  gpuviewer{mock_tag}"
            )
        }
    };
    let line = Line::from(text)
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Left);
    f.render_widget(line, area);
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::Ordering;
    use std::sync::Arc;
    use std::time::Duration;

    use gpuviewer_core::{DeviceId, DynamicSample, ProcessKind, ProcessSample, ThrottleReasons};
    use gpuviewer_history::SampleRollup;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    use super::{fmt_span, timeline_columns};
    use crate::app::App;
    use crate::collector::{test_collector, Collector, CollectorStop, Engine, EngineConfig};

    /// A rollup row carrying only a bucket key and a util peak — everything else absent,
    /// the way a sparse recording looks.
    fn bucket(bucket_ms: u64, util_max: Option<f32>) -> SampleRollup {
        SampleRollup {
            device_id: DeviceId("test".into()),
            bucket_ms,
            n: 1,
            util_min: None,
            util_avg: None,
            util_max,
            mem_avg: None,
            mem_max: None,
            power_avg_mw: None,
            power_max_mw: None,
            temp_avg_c: None,
            temp_max_c: None,
            fan_max_pct: None,
            sm_clock_min: None,
            sm_clock_avg: None,
            sm_clock_max: None,
            throttle_n: 0,
            throttle_observed_n: 0,
            throttle_thermal_n: 0,
            throttle_power_n: 0,
            throttle_hw_n: 0,
        }
    }

    fn util(r: &SampleRollup) -> Option<f64> {
        r.util_max.map(f64::from)
    }

    /// Several buckets landing in one column aggregate by MAX — the timeline shows
    /// peaks, not means — and columns whose whole range is unrecorded stay `None`.
    #[test]
    fn timeline_columns_take_max_and_leave_gaps_blank() {
        // Window 0..100s, 10s buckets, 5 columns: each column owns two bucket slots.
        let samples = [
            bucket(0, Some(10.0)),
            bucket(10_000, Some(90.0)),
            bucket(20_000, Some(50.0)), // 30s slot missing — column still has data
        ];
        let cols = timeline_columns(&samples, 0, 100_000, 10_000, 5, util);
        assert_eq!(cols[0], Some(90.0), "two buckets fold to their max");
        assert_eq!(cols[1], Some(50.0), "a half-empty column keeps its bucket");
        assert_eq!(
            &cols[2..],
            &[None, None, None],
            "unrecorded columns stay blank — never zero"
        );
    }

    /// The quantization trap: N buckets across M columns with naive x-mapping leaves
    /// periodic one-column blanks that read as recording gaps. Range-overlap ownership
    /// must keep a CONTINUOUS recording continuous at any cols:buckets ratio — and keep
    /// a REAL gap exactly where it is.
    #[test]
    fn timeline_columns_no_phantom_gaps_at_awkward_ratios() {
        // 10 contiguous buckets over 100s.
        let full: Vec<SampleRollup> = (0..10).map(|i| bucket(i * 10_000, Some(50.0))).collect();
        for ncols in [3, 7, 10, 33, 64] {
            let cols = timeline_columns(&full, 0, 100_000, 10_000, ncols, util);
            assert!(
                cols.iter().all(Option::is_some),
                "continuous recording must paint every one of {ncols} columns"
            );
        }

        // Same recording with the 50–60s bucket missing: only columns owned entirely
        // by that hole go blank.
        let gappy: Vec<SampleRollup> = (0..10)
            .filter(|i| *i != 5)
            .map(|i| bucket(i * 10_000, Some(50.0)))
            .collect();
        let cols = timeline_columns(&gappy, 0, 100_000, 10_000, 33, util);
        let blanks: Vec<usize> = (0..33).filter(|&c| cols[c].is_none()).collect();
        assert_eq!(
            blanks,
            vec![17, 18],
            "exactly the columns inside the real gap are blank"
        );
    }

    /// More buckets than columns: every bucket lands somewhere, each column is the max
    /// of all buckets overlapping its range.
    #[test]
    fn timeline_columns_fold_many_buckets_per_column() {
        let samples: Vec<SampleRollup> = (0..40)
            .map(|i| bucket(i * 10_000, Some(i as f32)))
            .collect();
        let cols = timeline_columns(&samples, 0, 400_000, 10_000, 4, util);
        assert_eq!(
            cols,
            vec![Some(9.0), Some(19.0), Some(29.0), Some(39.0)],
            "each column is the peak of its ten buckets"
        );
    }

    /// A recorded bucket whose metric is absent paints nothing: "unavailable" is not
    /// zero. And a bucket straddling a column boundary feeds both columns.
    #[test]
    fn timeline_columns_absent_metric_and_straddling_bucket() {
        let cols = timeline_columns(&[bucket(0, None)], 0, 20_000, 10_000, 2, util);
        assert_eq!(cols, vec![None, None], "absent metric stays blank");

        // Bucket [5s, 15s) overlaps both columns of a 2-column 20s window.
        let cols = timeline_columns(&[bucket(5_000, Some(42.0))], 0, 20_000, 10_000, 2, util);
        assert_eq!(cols, vec![Some(42.0), Some(42.0)]);

        // A bucket entirely outside the window contributes nowhere.
        let cols = timeline_columns(&[bucket(30_000, Some(99.0))], 0, 20_000, 10_000, 2, util);
        assert_eq!(cols, vec![None, None]);
    }

    #[test]
    fn fmt_span_is_compact_and_honest_below_a_second() {
        assert_eq!(fmt_span(500), "<1s");
        assert_eq!(fmt_span(45_000), "45s");
        assert_eq!(fmt_span(120_000), "2m");
        assert_eq!(fmt_span(130_000), "2m10s");
        assert_eq!(fmt_span(5_400_000), "1h30m");
        assert_eq!(fmt_span(48 * 3_600_000), "2d");
        assert_eq!(fmt_span(7 * 24 * 3_600_000), "7d");
    }

    /// A mock engine that does not persist (tests never touch the on-disk store here).
    fn mock_engine() -> Engine {
        Engine::new(EngineConfig {
            force_mock: true,
            ..Default::default()
        })
    }

    /// The processes pane must surface `StaticInfo::process_hint` (the WSL2 / privilege
    /// wall explanation) when present, and render unchanged when it is `None` — the mock
    /// sets `None`, so only this test exercises the `Some` branch.
    #[test]
    fn process_hint_renders_in_processes_pane() {
        // Long interval: the collector thread stays quiet while we drive draws by hand.
        let collector = Collector::start(mock_engine(), Duration::from_secs(3600), false);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);
        let mut terminal = Terminal::new(TestBackend::new(200, 40)).unwrap();

        // Baseline: no hint (mock default) renders without it.
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, &app, &sh)).unwrap();
        }
        let screen = terminal.backend().to_string();
        assert!(screen.contains("processes"));
        assert!(!screen.contains("your processes only"));

        // With a hint on the selected device, the pane shows it.
        shared.lock().unwrap().infos[0].process_hint = Some("your processes only".into());
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, &app, &sh)).unwrap();
        }
        let screen = terminal.backend().to_string();
        assert!(
            screen.contains("your processes only"),
            "process_hint missing from processes pane:\n{screen}"
        );
    }

    /// `StaticInfo::source_caveat` (§5.4 — the Apple working-set-budget label, the WDDM
    /// duty-cycle wording) must render on the VRAM chart, right where the qualified
    /// number is; the mock sets `None`, so only this test exercises the `Some` branch.
    #[test]
    fn source_caveat_renders_on_the_vram_chart() {
        let collector = Collector::start(mock_engine(), Duration::from_secs(3600), false);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);
        let mut terminal = Terminal::new(TestBackend::new(200, 40)).unwrap();

        // Baseline: no caveat (mock default) renders without it.
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, &app, &sh)).unwrap();
        }
        let screen = terminal.backend().to_string();
        assert!(!screen.contains("working-set budget"));

        shared.lock().unwrap().infos[0].source_caveat =
            Some("unified-memory working-set budget".into());
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, &app, &sh)).unwrap();
        }
        let screen = terminal.backend().to_string();
        assert!(
            screen.contains("unified-memory working-set budget"),
            "source_caveat missing from the chart area:\n{screen}"
        );
    }

    /// A source that cannot observe throttling (`throttle: None`, §5.4) must read
    /// "throttle n/a" on the temp gauge — an explicit blind spot, never an implied
    /// "not throttling".
    /// Replay must read a recorded bucket in the same three states the live gauge does.
    /// Before `throttle_observed_n` existed, replay flagged on `throttle_n > 0` alone, so
    /// every bucket from a source that cannot see the bitmask — and every row written by
    /// an older build — rendered as an observed all-clear. That is the None-as-Some(false)
    /// conflation the model forbids, arriving through the store.
    #[test]
    fn replay_bucket_throttle_has_three_states() {
        assert_eq!(
            super::bucket_throttling(0, 0),
            None,
            "no observations = unknown, NOT an all-clear"
        );
        assert_eq!(
            super::bucket_throttling(0, 6),
            Some(false),
            "six frames looked and none was throttling = a real all-clear"
        );
        assert_eq!(
            super::bucket_throttling(2, 6),
            Some(true),
            "an observed-active frame is throttling"
        );
        assert_eq!(
            super::bucket_throttling(2, 0),
            Some(true),
            "a v2 row that recorded throttling stays a fact after migration, even though \
             it never recorded an observed count"
        );
    }

    /// A gauge's fill is a claim about proportion. With no reported slowdown threshold
    /// there is nothing to be a proportion of, so the bar must make no claim at all — it
    /// used to fill toward a hardcoded 95 °C, putting a ratio on screen no source gave.
    #[test]
    fn temp_gauge_makes_no_proportional_claim_without_a_threshold() {
        assert_eq!(
            super::temp_gauge_ratio(70.0, None),
            None,
            "no threshold reported = no proportional claim"
        );
        assert_eq!(
            super::temp_gauge_ratio(42.0, Some(84.0)),
            Some(0.5),
            "a real threshold gives a real fraction"
        );
        assert_eq!(
            super::temp_gauge_ratio(99.0, Some(84.0)),
            Some(1.0),
            "over the threshold clamps rather than overflowing the bar"
        );
        assert_eq!(
            super::temp_gauge_ratio(70.0, Some(0.0)),
            None,
            "a zero threshold is not a scale — dividing by it would read as infinitely hot"
        );
    }

    /// CLAUDE.md's standing rule: utilization is duty-cycle, never presented as capacity.
    /// The qualifier belongs on the chart, not only in the README.
    #[test]
    fn util_chart_carries_the_duty_cycle_qualifier() {
        let collector = test_collector(None);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);
        let screen = draw(&app, &shared);
        assert!(
            screen.contains("duty-cycle"),
            "the util chart must label what the number actually measures:\n{screen}"
        );
    }

    #[test]
    fn unobservable_throttle_reads_na_not_quiet() {
        // Stationary collector: no tick thread to overwrite the injected sample.
        let collector = test_collector(None);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);

        // A sample with a temperature but no throttle observability (the wddm shape —
        // synthetic here because the mock always observes).
        shared.lock().unwrap().latest[0] = Some(DynamicSample {
            ts_ms: gpuviewer_core::now_ms(),
            util_pct: Some(50.0),
            util_engine: None,
            mem_used_bytes: Some(1 << 30),
            power_mw: None,
            temp_c: Some(60.0),
            fan_pct: None,
            sm_clock_mhz: None,
            mem_clock_mhz: None,
            encoder_pct: None,
            decoder_pct: None,
            throttle: None,
            power_limit_mw: None,
            pcie_gen: None,
            pcie_width: None,
            ecc_uncorrected: None,
        });
        let screen = draw(&app, &shared);
        assert!(
            screen.contains("throttle n/a"),
            "unobservable throttle must be labeled n/a:\n{screen}"
        );
        assert!(!screen.contains("THROTTLING"));

        // Observed-quiet: no n/a label, no flag — the plain reading.
        shared.lock().unwrap().latest[0].as_mut().unwrap().throttle =
            Some(ThrottleReasons::default());
        let screen = draw(&app, &shared);
        assert!(!screen.contains("throttle n/a"));
        assert!(!screen.contains("THROTTLING"));
    }

    /// The footer's "(mock data)" tag must track the actual data source — it was once
    /// hardcoded, calling live NVML data mock. The mock engine asserts the tag; then
    /// flipping `Shared::mock` (what a real backend produces) asserts its absence.
    #[test]
    fn footer_mock_tag_tracks_data_source() {
        let collector = Collector::start(mock_engine(), Duration::from_secs(3600), false);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);
        let mut terminal = Terminal::new(TestBackend::new(200, 40)).unwrap();

        // Mock engine: the footer says so.
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, &app, &sh)).unwrap();
        }
        let screen = terminal.backend().to_string();
        assert!(
            screen.contains("(mock data)"),
            "mock data must be labeled mock:\n{screen}"
        );

        // Live data must never carry the mock tag.
        shared.lock().unwrap().mock = false;
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, &app, &sh)).unwrap();
        }
        let screen = terminal.backend().to_string();
        assert!(
            !screen.contains("(mock data)"),
            "live data must not be labeled mock:\n{screen}"
        );
        assert!(screen.contains("gpuviewer"), "footer brand text missing");
    }

    fn draw(app: &App, shared: &Arc<std::sync::Mutex<crate::collector::Shared>>) -> String {
        let mut terminal = Terminal::new(TestBackend::new(200, 40)).unwrap();
        {
            let sh = shared.lock().unwrap();
            terminal.draw(|f| super::render(f, app, &sh)).unwrap();
        }
        terminal.backend().to_string()
    }

    /// The LIVE process table carries the cpu column and shows the container after the
    /// name ("ollama [docker:3f2a9c1b]") — the same shape replay renders from rollups.
    #[test]
    fn live_process_table_shows_cpu_and_container() {
        let collector = test_collector(None);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);

        shared.lock().unwrap().processes[0] = vec![ProcessSample {
            pid: 7,
            name: "ollama".into(),
            kind: ProcessKind::Compute,
            mem_bytes: Some(3 << 30),
            util_pct: Some(80.0),
            cpu_pct: Some(42.0),
            container: Some("docker:3f2a9c1b".into()),
            cmdline: None,
        }];
        let screen = draw(&app, &shared);
        assert!(
            screen.contains("cpu"),
            "cpu column header missing:\n{screen}"
        );
        assert!(
            screen.contains("ollama [docker:3f2a9c1b]"),
            "container must follow the process name:\n{screen}"
        );
        assert!(screen.contains("42%"), "cpu_pct value missing:\n{screen}");
    }

    /// The footer announces the stretched cadence while low-power backoff is active, and
    /// stays quiet at the configured interval — a sparser chart must be explained, never
    /// left to read as missing data.
    #[test]
    fn footer_shows_low_power_cadence_when_backed_off() {
        let collector = test_collector(None);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);

        // At the configured cadence: no label.
        let screen = draw(&app, &shared);
        assert!(!screen.contains("low-power cadence"));

        // Backed off to 5s: the footer says so.
        shared
            .lock()
            .unwrap()
            .effective_interval_ms
            .store(5000, Ordering::Relaxed);
        let screen = draw(&app, &shared);
        assert!(
            screen.contains("low-power cadence 5s"),
            "active backoff must be announced:\n{screen}"
        );
    }

    /// The rendering half of the tick-panic frozen-UI fix: once `Shared::stopped` is set,
    /// the footer must state COLLECTION STOPPED with the time and the panic summary, and
    /// the live panes must read stale — charts tagged like replay tags its panes, the
    /// process table flagged — never as current data.
    #[test]
    fn stopped_collector_banner_and_stale_tags() {
        let collector = test_collector(None);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);

        // Alive: no banner, no stale tags anywhere.
        let screen = draw(&app, &shared);
        assert!(!screen.contains("COLLECTION STOPPED"));
        assert!(!screen.contains("STALE"));

        shared.lock().unwrap().stopped = Some(CollectorStop {
            at_ms: 1_000_000_000_000,
            reason: "attempt to multiply with overflow".into(),
        });
        let screen = draw(&app, &shared);
        assert!(
            screen.contains("COLLECTION STOPPED"),
            "the footer must state the stop:\n{screen}"
        );
        assert!(
            screen.contains("attempt to multiply with overflow"),
            "the panic summary must be on screen:\n{screen}"
        );
        assert!(
            screen.contains("STALE"),
            "chart headlines must read stale, not current:\n{screen}"
        );
        assert!(
            screen.contains("stale — collection stopped"),
            "the process pane must flag its list as stale:\n{screen}"
        );
    }

    /// The per-device flavor of the staleness affordances: a LOST device's panes read
    /// stale (chart STALE tags, a process-pane flag carrying the loss time and the data
    /// age, a tab-strip marker) while the footer does NOT claim collection stopped — the
    /// other devices are still live. Recovery clears every marker.
    #[test]
    fn lost_device_panes_read_stale_without_stop_banner() {
        let collector = test_collector(None);
        let shared = Arc::clone(&collector.shared);
        let app = App::new(collector);

        // Give the selected device a last good sample so "last data … ago" has an age.
        shared.lock().unwrap().latest[0] = Some(DynamicSample {
            ts_ms: gpuviewer_core::now_ms().saturating_sub(34_000),
            util_pct: Some(72.0),
            util_engine: None,
            mem_used_bytes: Some(4 << 30),
            power_mw: None,
            temp_c: None,
            fan_pct: None,
            sm_clock_mhz: None,
            mem_clock_mhz: None,
            encoder_pct: None,
            decoder_pct: None,
            throttle: Some(ThrottleReasons::default()),
            power_limit_mw: None,
            pcie_gen: None,
            pcie_width: None,
            ecc_uncorrected: None,
        });

        // Alive: no stale affordances anywhere.
        let screen = draw(&app, &shared);
        assert!(!screen.contains("STALE"));
        assert!(!screen.contains("LOST"));
        assert!(!screen.contains("device lost"));

        shared.lock().unwrap().lost[0] = Some(1_000_000_000_000);
        let screen = draw(&app, &shared);
        assert!(
            screen.contains("STALE"),
            "a lost device's chart headlines must read stale, not current:\n{screen}"
        );
        assert!(
            screen.contains("LOST"),
            "the tab strip must flag the lost device:\n{screen}"
        );
        assert!(
            screen.contains("stale — device lost"),
            "the process pane must carry the loss flag:\n{screen}"
        );
        assert!(
            screen.contains("last data"),
            "the affordance must carry the age of the last good data:\n{screen}"
        );
        assert!(
            !screen.contains("COLLECTION STOPPED"),
            "one lost device is not a collector stop — other devices are live:\n{screen}"
        );

        // Recovery clears every marker.
        shared.lock().unwrap().lost[0] = None;
        let screen = draw(&app, &shared);
        assert!(!screen.contains("STALE"));
        assert!(!screen.contains("LOST"));
        assert!(!screen.contains("device lost"));
    }
}