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
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
//! TUI event loop and app state: the live dashboard, the scroll-back replay mode —
//! the product's headline feature ("scroll back to 02:14 — it'll tell you why") — and
//! the timeline overview, the zoomed-out altitude above replay (hours per screen,
//! Enter drills back down).

use std::sync::atomic::Ordering;
use std::time::Duration;

use anyhow::Result;
use gpuviewer_core::{now_ms, Event};
use gpuviewer_history::{ProcessRollup, SampleRollup, SqliteStore, Tier};
use ratatui::crossterm::event::{self, Event as TermEvent, KeyCode, KeyEventKind, KeyModifiers};
use ratatui::layout::Rect;
use ratatui::{TerminalOptions, Viewport};

use crate::collector::Collector;

/// Viewport assumed when the terminal reports a 0×0 size (bare ptys: `script`, some CI).
const FALLBACK_SIZE: (u16, u16) = (80, 24);

/// Half-width of the replay window queried around the cursor: ±5 min of 10s rollups.
const REPLAY_HALF_WINDOW_MS: u64 = 300_000;
/// Left/Right scrub step in replay.
const SCRUB_STEP_MS: u64 = 10_000;
/// PgUp/PgDn scrub step in replay.
const SCRUB_PAGE_MS: u64 = 300_000;
/// PgUp/PgDn jump for the timeline cursor, in rendered columns.
const TIMELINE_PAGE_COLS: u64 = 10;

const HOUR_MS: u64 = 60 * 60 * 1000;

/// One rung of the timeline zoom ladder: the window it spans and the rollup tier that
/// feeds it. The 1h rung reads the 10s tier; everything wider reads the 1m tier (a 3h
/// window already holds more 10s buckets than any terminal has columns).
pub struct TimelineZoom {
    pub label: &'static str,
    pub span_ms: u64,
    pub tier: Tier,
}

/// '-' walks down this ladder (wider window), '+' climbs back up (narrower).
pub const TIMELINE_ZOOMS: [TimelineZoom; 7] = [
    TimelineZoom {
        label: "1h",
        span_ms: HOUR_MS,
        tier: Tier::TenSec,
    },
    TimelineZoom {
        label: "3h",
        span_ms: 3 * HOUR_MS,
        tier: Tier::OneMin,
    },
    TimelineZoom {
        label: "6h",
        span_ms: 6 * HOUR_MS,
        tier: Tier::OneMin,
    },
    TimelineZoom {
        label: "12h",
        span_ms: 12 * HOUR_MS,
        tier: Tier::OneMin,
    },
    TimelineZoom {
        label: "24h",
        span_ms: 24 * HOUR_MS,
        tier: Tier::OneMin,
    },
    TimelineZoom {
        label: "48h",
        span_ms: 48 * HOUR_MS,
        tier: Tier::OneMin,
    },
    TimelineZoom {
        label: "7d",
        span_ms: 7 * 24 * HOUR_MS,
        tier: Tier::OneMin,
    },
];

/// The rung the timeline opens at: 6h — wide enough to frame "the run stalled hours
/// ago", narrow enough that one column is still a couple of minutes.
pub const TIMELINE_DEFAULT_ZOOM: usize = 2;

/// Which timeline the dashboard shows: the live tick stream, a recorded window scrolled
/// back to [`App::cursor_ms`], or the zoomed-out timeline overview above both.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    Live,
    Replay,
    /// Hours of recorded history per screen, with a column cursor that Enter drills
    /// back down into replay — the core loop is overview → drill → replay → live.
    Timeline,
}

/// Why a replay/timeline key did nothing. The footer prints a different sentence per
/// variant: "replay needs persistence" is only true when recording is actually off, and
/// asserting it for an unreadable database would tell the user a flag was set that they
/// never passed — the confidently-wrong narration the trust thesis rules out.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplayBlock {
    /// No database path at all — `--no-persist`, or a session that never had one.
    NoPersistence,
    /// A database path exists but would not open read-only (corrupt, quarantined,
    /// permissions). Recording itself may be running perfectly.
    Unreadable,
}

/// How the live/replay charts paint the square wave: a braille step outline (the
/// shipped default) or the filled half-block silhouette. Both walk the same
/// hold-then-step points with the same gap-breaking — strictly a paint choice, cycled
/// with 's'. The timeline overview ignores it: its strips are always solid.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChartStyle {
    Braille,
    Solid,
}

impl ChartStyle {
    /// The other style — 's' cycles between the two.
    pub fn toggled(self) -> Self {
        match self {
            ChartStyle::Braille => ChartStyle::Solid,
            ChartStyle::Solid => ChartStyle::Braille,
        }
    }
}

/// Which events the story feed shows; `f` cycles it in live and replay. Filtering is
/// presentation only — every event is still recorded, streamed, and on the timeline lane.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StoryFilter {
    All,
    /// Warning and Critical only — the "what went wrong overnight" view.
    Warnings,
    /// Observed facts only: the inferences ("likely …") are hidden.
    Facts,
}

impl StoryFilter {
    pub fn next(self) -> Self {
        match self {
            StoryFilter::All => StoryFilter::Warnings,
            StoryFilter::Warnings => StoryFilter::Facts,
            StoryFilter::Facts => StoryFilter::All,
        }
    }

    pub fn admits(self, e: &Event) -> bool {
        match self {
            StoryFilter::All => true,
            StoryFilter::Warnings => e.severity != gpuviewer_core::Severity::Info,
            StoryFilter::Facts => e.confidence == gpuviewer_core::Confidence::Fact,
        }
    }

    /// Shown in the story pane's title while a filter is active.
    pub fn label(self) -> Option<&'static str> {
        match self {
            StoryFilter::All => None,
            StoryFilter::Warnings => Some("warnings+"),
            StoryFilter::Facts => Some("facts only"),
        }
    }
}

/// One queried replay window, cached between seeks so rendering never touches SQLite.
/// `samples`/`processes` are indexed like `Shared::infos`, so the device tabs keep working
/// unchanged in replay.
pub struct ReplayWindow {
    pub from_ms: u64,
    pub to_ms: u64,
    /// 10s-tier rollups per device across `[from_ms, to_ms]`, oldest first.
    pub samples: Vec<Vec<SampleRollup>>,
    /// Per-device process rollups for the bucket at the cursor.
    pub processes: Vec<Vec<ProcessRollup>>,
    /// Events in the window, oldest first (the store's order).
    pub events: Vec<Event>,
}

/// One queried timeline-overview window, cached like [`ReplayWindow`] so rendering never
/// touches SQLite. Holds the raw rollup rows: bucket→column aggregation happens at render
/// time because it depends on the terminal width.
pub struct TimelineWindow {
    pub from_ms: u64,
    pub to_ms: u64,
    /// The rollup tier the window was queried at (10s for the 1h zoom, else 1m).
    pub tier: Tier,
    /// True when `from_ms` was pulled in to the start of recorded history — the requested
    /// zoom is wider than the recording, and the UI must show the actual span.
    pub clamped: bool,
    /// Rollups per device across `[from_ms, to_ms]`, oldest first; indexed like
    /// `Shared::infos`.
    pub samples: Vec<Vec<SampleRollup>>,
    /// Events in the window, oldest first — all devices, like the story feed (event
    /// titles name their GPU).
    pub events: Vec<Event>,
}

/// What a key press asks the event loop to do. Returned instead of acted on inline so the
/// whole key dispatch — including "q quits from both modes, Esc only from live" — is
/// unit-testable without a terminal.
#[derive(Debug, PartialEq, Eq)]
pub enum KeyOutcome {
    Quit,
    Continue,
}

pub struct App {
    pub selected: usize,
    pub mode: Mode,
    /// Replay cursor in unix millis; meaningful only in `Mode::Replay`.
    pub cursor_ms: u64,
    /// The selected story-feed row, shared by both modes: in Live it indexes the
    /// newest-first feed, in Replay the window's chronological event list.
    pub story_selected: Option<usize>,
    /// Set after a replay/timeline key was pressed with no usable history store — the
    /// footer explains why nothing happened instead of silently swallowing the key.
    /// Carries the CAUSE, because the two causes need different sentences: blaming
    /// `--no-persist` when the user never passed it is exactly the confidently-wrong
    /// narration the honesty contract forbids.
    pub replay_hint: Option<ReplayBlock>,
    /// How the live/replay charts are painted; 'c' cycles it.
    pub chart_style: ChartStyle,
    /// Which events the story feed lists; 'f' cycles it. In Live, `story_selected`
    /// indexes the FILTERED newest-first feed; in Replay it stays an index into the
    /// window's full event list (selection just skips hidden rows).
    pub story_filter: StoryFilter,
    /// Timeline cursor in unix millis; meaningful only in `Mode::Timeline`.
    pub timeline_cursor_ms: u64,
    /// Current rung on [`TIMELINE_ZOOMS`].
    pub timeline_zoom: usize,
    /// Columns the timeline strips spanned at the last draw — written by the event loop
    /// before each draw so the cursor keys step exactly one rendered column.
    pub timeline_cols: usize,
    /// The recording file this session is pinned to (`gpuviewer view`); `Some` means there
    /// is no live source behind the UI, so the app never leaves replay.
    view_file: Option<String>,
    /// Cached replay window, re-queried on every seek.
    replay: Option<ReplayWindow>,
    /// Cached timeline window, re-queried on entry, zoom changes, and — in a live
    /// session — every collector tick (see [`Self::timeline_tick`]).
    timeline: Option<TimelineWindow>,
    /// `Shared::tick_seq` at the moment the cached timeline window was built. The event
    /// loop re-queries the window once the collector has folded a newer frame, so a live
    /// overview's right edge keeps tracking "now" instead of silently freezing at the
    /// instant 't' was pressed.
    timeline_built_seq: u64,
    /// Second, read-only store connection (WAL lets it read while the collector's writer
    /// keeps appending). Opened lazily on the first replay entry; stays `None` when
    /// persistence is off or the store cannot be opened.
    store: Option<SqliteStore>,
    collector: Collector,
}

/// Ctrl-C in raw mode: quit, in every mode — including the file viewer and timeline,
/// where a bare 'c' means something else (or nothing).
pub fn is_ctrl_c(code: KeyCode, modifiers: KeyModifiers) -> bool {
    modifiers.contains(KeyModifiers::CONTROL) && matches!(code, KeyCode::Char('c' | 'C'))
}

impl App {
    pub fn new(collector: Collector) -> Self {
        Self {
            selected: 0,
            mode: Mode::Live,
            cursor_ms: 0,
            story_selected: None,
            replay_hint: None,
            chart_style: ChartStyle::Braille,
            story_filter: StoryFilter::All,
            timeline_cursor_ms: 0,
            timeline_zoom: TIMELINE_DEFAULT_ZOOM,
            timeline_cols: (FALLBACK_SIZE.0 - 2) as usize,
            view_file: None,
            replay: None,
            timeline: None,
            timeline_built_seq: 0,
            store: None,
            collector,
        }
    }

    /// An app pinned to a recording file (`gpuviewer view FILE.gpvr`): starts in replay at
    /// the file's newest event (or its newest bucket when it holds none) and never drops to
    /// Live — there is no collector ticking and no live source, only the file. Esc/'r' are
    /// inert; 'q' quits. Pair with [`Collector::stationary`].
    pub fn viewer(collector: Collector, store: SqliteStore, file: String) -> Self {
        let mut app = Self::new(collector);
        let anchor = store.latest_event_ms(None).ok().flatten();
        app.store = Some(store);
        app.view_file = Some(file);
        app.enter_replay(anchor);
        app
    }

    /// The pinned recording's display name (`gpuviewer view`), `None` in a live session.
    pub fn view_file(&self) -> Option<&str> {
        self.view_file.as_deref()
    }

    pub fn paused(&self) -> bool {
        self.collector.paused.load(Ordering::Relaxed)
    }

    /// The cached replay window when in replay mode. Rendering reads through here so a
    /// stale cache can never leak into the live view.
    pub fn replay_window(&self) -> Option<&ReplayWindow> {
        match self.mode {
            Mode::Replay => self.replay.as_ref(),
            Mode::Live | Mode::Timeline => None,
        }
    }

    /// The cached timeline window when in timeline mode — the same staleness guard as
    /// [`Self::replay_window`].
    pub fn timeline_window(&self) -> Option<&TimelineWindow> {
        match self.mode {
            Mode::Timeline => self.timeline.as_ref(),
            Mode::Live | Mode::Replay => None,
        }
    }

    pub fn run(mut self) -> Result<()> {
        // A bare pty (e.g. `script` captures) reports a 0×0 size; the fullscreen viewport
        // would autoresize to an empty buffer and draw nothing. Pin a fixed 80×24 viewport
        // instead — `Viewport::Fixed` is never autoresized, and a pty that can't report a
        // size won't deliver meaningful resize events either. Real terminals report a
        // nonzero size and keep the normal resize-tracking fullscreen path.
        let zero_sized = ratatui::crossterm::terminal::size()
            .map(|(w, h)| w == 0 || h == 0)
            .unwrap_or(false);
        let mut terminal = if zero_sized {
            let (w, h) = FALLBACK_SIZE;
            ratatui::init_with_options(TerminalOptions {
                viewport: Viewport::Fixed(Rect::new(0, 0, w, h)),
            })
        } else {
            ratatui::init()
        };
        let res = self.event_loop(&mut terminal);
        ratatui::restore();
        // A detached collector thread would be killed mid-recording when main returns —
        // losing the partial rollup tail AND the session's `recording_stopped` mark, so
        // every TUI quit would read as a crash to the next session. Stop it cooperatively
        // (bounded — see `Collector::shutdown`) after the terminal is restored, so the
        // screen is back even if the wait runs its full grace.
        self.collector.shutdown();
        res
    }

    fn event_loop(&mut self, terminal: &mut ratatui::DefaultTerminal) -> Result<()> {
        loop {
            // Re-query the timeline overview if the collector ticked since it was built
            // — a stale window presented as "ending now" would be a quiet lie.
            self.timeline_tick();
            let width = {
                let shared = self.collector.shared.lock().unwrap();
                let n = shared.infos.len();
                if n > 0 && self.selected >= n {
                    self.selected = n - 1;
                }
                terminal
                    .draw(|f| crate::ui::render(f, self, &shared))?
                    .area
                    .width
            };
            // The timeline cursor steps by one rendered column, so the key handler needs
            // the width the strips were actually drawn at.
            self.timeline_cols = crate::ui::timeline_strip_cols(width);

            // SIGTERM/SIGHUP (a dropped SSH session, `kill`): leave through the same door
            // as `q`, so `run` restores the terminal and the collector writes its stop
            // mark and flushes the recording tail.
            if crate::signals::requested() {
                return Ok(());
            }
            if event::poll(Duration::from_millis(250))? {
                if let TermEvent::Key(key) = event::read()? {
                    if key.kind != KeyEventKind::Press {
                        continue;
                    }
                    // Raw mode turns Ctrl-C into a key event instead of SIGINT. Without
                    // this arm it fell through to the bare 'c' binding and toggled the
                    // chart style — the universal "quit" key did something else entirely.
                    if is_ctrl_c(key.code, key.modifiers) {
                        return Ok(());
                    }
                    if self.handle_key(key.code) == KeyOutcome::Quit {
                        return Ok(());
                    }
                }
            }
        }
    }

    /// Dispatch one key press according to the current mode.
    ///
    /// Ctrl-C never reaches here: the event loop quits on it first ([`is_ctrl_c`]).
    ///
    /// Every navigation key has a letter alias, because Mac laptops have no
    /// PgUp/PgDn/Home/End keys and terminal emulators routinely swallow the Fn+arrow
    /// substitutes (scrolling their own buffer instead of sending the key). The rule is
    /// uniform across modes so it can be learned once: `w`/`a`/`s`/`d` mirror the
    /// arrows, shifted `A`/`D` mirror PgUp/PgDn (a bigger step of the same motion), and
    /// `g`/`G` mirror Home/End. Chart style lives on `c` — `s` is wasd-down.
    pub fn handle_key(&mut self, code: KeyCode) -> KeyOutcome {
        match self.mode {
            Mode::Live => self.handle_key_live(code),
            Mode::Replay => self.handle_key_replay(code),
            Mode::Timeline => self.handle_key_timeline(code),
        }
    }

    fn handle_key_live(&mut self, code: KeyCode) -> KeyOutcome {
        let n = self.collector.shared.lock().unwrap().infos.len().max(1);
        match code {
            KeyCode::Char('q') | KeyCode::Esc => return KeyOutcome::Quit,
            KeyCode::Tab | KeyCode::Right | KeyCode::Char('d') => {
                self.selected = (self.selected + 1) % n
            }
            KeyCode::Left | KeyCode::BackTab | KeyCode::Char('a') => {
                self.selected = (self.selected + n - 1) % n
            }
            KeyCode::Char('p') => {
                let p = &self.collector.paused;
                p.store(!p.load(Ordering::Relaxed), Ordering::Relaxed);
            }
            KeyCode::Up | KeyCode::Char('w') => self.move_story_selection(-1),
            KeyCode::Down | KeyCode::Char('s') => self.move_story_selection(1),
            KeyCode::Enter => {
                // Enter on a selected event scrolls back to it. The feed displays
                // newest-first, so the visual index maps back from the end of the log.
                let filter = self.story_filter;
                let ts = self.story_selected.and_then(|i| {
                    let sh = self.collector.shared.lock().unwrap();
                    sh.history
                        .events()
                        .iter()
                        .rev()
                        .filter(|e| filter.admits(e))
                        .nth(i)
                        .map(|e| e.ts_ms)
                });
                if let Some(ts) = ts {
                    self.enter_replay(Some(ts));
                }
            }
            KeyCode::Char('r') => self.enter_replay(None),
            KeyCode::Char('t') => self.enter_timeline(),
            KeyCode::Char('c') => self.chart_style = self.chart_style.toggled(),
            KeyCode::Char('f') => self.cycle_story_filter(),
            _ => {}
        }
        KeyOutcome::Continue
    }

    fn handle_key_replay(&mut self, code: KeyCode) -> KeyOutcome {
        let n = self.collector.shared.lock().unwrap().infos.len().max(1);
        match code {
            // q always quits; Esc must NOT — in replay it returns to the live view.
            KeyCode::Char('q') => return KeyOutcome::Quit,
            KeyCode::Esc | KeyCode::Char('r') => {
                // Inert in the file viewer: there is no live view behind a recording to
                // return to, and swapping in an empty "live" pane would be a lie.
                if self.view_file.is_none() {
                    self.mode = Mode::Live;
                    self.story_selected = None;
                }
            }
            KeyCode::Left | KeyCode::Char('a') => self.scrub(-(SCRUB_STEP_MS as i64)),
            KeyCode::Right | KeyCode::Char('d') => self.scrub(SCRUB_STEP_MS as i64),
            KeyCode::PageUp | KeyCode::Char('A') => self.scrub(-(SCRUB_PAGE_MS as i64)),
            KeyCode::PageDown | KeyCode::Char('D') => self.scrub(SCRUB_PAGE_MS as i64),
            KeyCode::Home | KeyCode::Char('g') => {
                if let Some((earliest, _)) = self.recorded_range() {
                    self.seek(earliest);
                }
            }
            KeyCode::End | KeyCode::Char('G') => {
                if let Some((_, latest)) = self.recorded_range() {
                    self.seek(latest);
                }
            }
            KeyCode::Tab => self.selected = (self.selected + 1) % n,
            KeyCode::BackTab => self.selected = (self.selected + n - 1) % n,
            KeyCode::Up | KeyCode::Char('w') => self.move_story_selection(-1),
            KeyCode::Down | KeyCode::Char('s') => self.move_story_selection(1),
            KeyCode::Enter => {
                // Re-anchor the cursor to the selected event, then keep the selection
                // pointing at that same event inside the re-centered window.
                let ts = self
                    .story_selected
                    .zip(self.replay.as_ref())
                    .and_then(|(i, w)| w.events.get(i).map(|e| e.ts_ms));
                if let Some(ts) = ts {
                    self.seek(ts);
                    self.story_selected = self
                        .replay
                        .as_ref()
                        .and_then(|w| w.events.iter().position(|e| e.ts_ms == ts));
                }
            }
            KeyCode::Char('t') => self.enter_timeline(),
            KeyCode::Char('c') => self.chart_style = self.chart_style.toggled(),
            KeyCode::Char('f') => self.cycle_story_filter(),
            _ => {}
        }
        KeyOutcome::Continue
    }

    /// Timeline keys: the zoom ladder on '+'/'-', a column cursor on the arrows, Enter to
    /// drill down into replay at the cursor — overview → drill → replay → live.
    fn handle_key_timeline(&mut self, code: KeyCode) -> KeyOutcome {
        let n = self.collector.shared.lock().unwrap().infos.len().max(1);
        match code {
            // q always quits; Esc/'t' climb back down the altitude ladder — to the pinned
            // replay in the file viewer (there is no live view behind a recording), to
            // the live view otherwise.
            KeyCode::Char('q') => return KeyOutcome::Quit,
            KeyCode::Char('t') | KeyCode::Esc => {
                self.mode = if self.view_file.is_some() {
                    Mode::Replay
                } else {
                    Mode::Live
                };
            }
            // '=' is unshifted '+' on common layouts; accept both.
            KeyCode::Char('+') | KeyCode::Char('=') => self.timeline_rezoom(-1),
            KeyCode::Char('-') => self.timeline_rezoom(1),
            KeyCode::Left | KeyCode::Char('a') => self.timeline_step(-1),
            KeyCode::Right | KeyCode::Char('d') => self.timeline_step(1),
            KeyCode::PageUp | KeyCode::Char('A') => {
                self.timeline_step(-(TIMELINE_PAGE_COLS as i64))
            }
            KeyCode::PageDown | KeyCode::Char('D') => self.timeline_step(TIMELINE_PAGE_COLS as i64),
            KeyCode::Home | KeyCode::Char('g') => {
                if let Some(w) = &self.timeline {
                    self.timeline_cursor_ms = w.from_ms;
                }
            }
            KeyCode::End | KeyCode::Char('G') => {
                if let Some(w) = &self.timeline {
                    self.timeline_cursor_ms = w.to_ms;
                }
            }
            KeyCode::Tab => self.selected = (self.selected + 1) % n,
            KeyCode::BackTab => self.selected = (self.selected + n - 1) % n,
            KeyCode::Enter => self.enter_replay(Some(self.timeline_cursor_ms)),
            _ => {}
        }
        KeyOutcome::Continue
    }

    /// Enter replay at `cursor` (an event's ts), or at the newest recorded bucket when
    /// `None` ('r'). Public because `gpuviewer demo` opens the session already scrolled
    /// back to the last throttle onset — the user's first sight is the answer to "why did
    /// it slow down", not a live gauge. With no store available (persistence disabled, or
    /// the database unreadable) this sets the footer hint and stays live — a replay view
    /// with no recording behind it would be an empty lie.
    pub fn enter_replay(&mut self, cursor: Option<u64>) {
        if !self.ensure_store() {
            return;
        }
        // An empty store still enters replay (anchored at "now"): blank charts plus a
        // cursor time read more honestly than a key that silently does nothing.
        let anchor = cursor
            .or_else(|| self.recorded_range().map(|(_, latest)| latest))
            .unwrap_or_else(now_ms);
        self.mode = Mode::Replay;
        self.replay_hint = None;
        self.story_selected = None;
        self.seek(anchor);
        // When entering on an event, keep the selection anchored to it in the new window.
        if let Some(ts) = cursor {
            self.story_selected = self
                .replay
                .as_ref()
                .and_then(|w| w.events.iter().position(|e| e.ts_ms == ts));
        }
    }

    /// Enter the timeline overview ('t') from live or replay. Coming from replay the
    /// cursor carries over, so the overview frames where you already were; from live it
    /// starts at the window's newest edge. Needs the same store replay does — without one
    /// the footer hint explains the dead key.
    pub fn enter_timeline(&mut self) {
        if !self.ensure_store() {
            return;
        }
        let anchor = (self.mode == Mode::Replay).then_some(self.cursor_ms);
        self.mode = Mode::Timeline;
        self.replay_hint = None;
        self.story_selected = None;
        self.timeline_refresh(anchor);
    }

    /// Open the lazy read-only store connection on first use. `false` (with the footer
    /// hint set) when persistence is off or the database is unreadable — the two are
    /// recorded separately so the footer can name the real cause.
    fn ensure_store(&mut self) -> bool {
        if self.store.is_some() {
            return true;
        }
        let db_path = self.collector.shared.lock().unwrap().db_path.clone();
        let Some(path) = db_path else {
            // No path at all: recording is genuinely off.
            self.replay_hint = Some(ReplayBlock::NoPersistence);
            return false;
        };
        match SqliteStore::open_readonly(path) {
            Ok(s) => {
                self.store = Some(s);
                true
            }
            // A path exists but will not open — corrupt, mid-quarantine, or unreadable.
            // Recording may be perfectly enabled, so the footer must not blame a flag.
            Err(_) => {
                self.replay_hint = Some(ReplayBlock::Unreadable);
                false
            }
        }
    }

    /// (Re)query the timeline window at the current zoom. The window ends at "now" in a
    /// live session but at the end of recorded coverage in the file viewer
    /// ([`Self::recorded_end`]) — a recording has no "now", and hours of empty future
    /// would squeeze the data into the left margin. The start clamps to the oldest
    /// recorded bucket so a recording younger than the zoom shows its actual span
    /// (flagged via `clamped`), then aligns down to the tier width so the inclusive
    /// bucket query and the column mapping agree on the window's first bucket. `cursor`
    /// keeps an existing cursor where the new window still contains it; `None` lands on
    /// the newest edge.
    fn timeline_refresh(&mut self, cursor: Option<u64>) {
        let zoom = &TIMELINE_ZOOMS[self.timeline_zoom];
        let to_ms = match (self.view_file.is_some(), self.recorded_end()) {
            (true, Some(end)) => end,
            _ => now_ms(),
        };
        let mut from_ms = to_ms.saturating_sub(zoom.span_ms);
        let mut clamped = false;
        if let Some((earliest, _)) = self.recorded_range() {
            if earliest > from_ms {
                from_ms = earliest;
                clamped = true;
            }
        }
        from_ms -= from_ms % zoom.tier.width_ms();

        let (ids, seq) = {
            let sh = self.collector.shared.lock().unwrap();
            let ids: Vec<_> = sh.infos.iter().map(|i| i.id.clone()).collect();
            (ids, sh.tick_seq)
        };
        let Some(store) = &self.store else { return };
        let samples = ids
            .iter()
            .map(|id| {
                store
                    .samples_between(id, from_ms, to_ms, zoom.tier)
                    .unwrap_or_default()
            })
            .collect();
        let events = store.events_between(from_ms, to_ms).unwrap_or_default();
        self.timeline_cursor_ms = cursor.unwrap_or(to_ms).clamp(from_ms, to_ms);
        self.timeline_built_seq = seq;
        self.timeline = Some(TimelineWindow {
            from_ms,
            to_ms,
            tier: zoom.tier,
            clamped,
            samples,
            events,
        });
    }

    /// Re-query the cached timeline window when the collector has folded a new frame
    /// since it was built, so the live overview's right edge keeps tracking "now" and
    /// rollups recorded after entry keep arriving on screen. Called once per event-loop
    /// pass — a u64 compare unless a tick actually landed, so rendering stays off
    /// SQLite. The file viewer never refreshes: a recording does not grow. A cursor
    /// sitting on the newest edge rides it; anywhere else it keeps its wall-clock
    /// position (clamped, like every refresh).
    fn timeline_tick(&mut self) {
        if self.mode != Mode::Timeline || self.view_file.is_some() {
            return;
        }
        let seq = self.collector.shared.lock().unwrap().tick_seq;
        if seq == self.timeline_built_seq {
            return;
        }
        let cursor = self
            .timeline
            .as_ref()
            .filter(|w| self.timeline_cursor_ms < w.to_ms)
            .map(|_| self.timeline_cursor_ms);
        self.timeline_refresh(cursor);
    }

    /// Step the zoom ladder by `delta` rungs ('+' narrower, '-' wider) and re-query; the
    /// cursor keeps its wall-clock position wherever the new window still contains it.
    fn timeline_rezoom(&mut self, delta: isize) {
        self.timeline_zoom = self
            .timeline_zoom
            .saturating_add_signed(delta)
            .min(TIMELINE_ZOOMS.len() - 1);
        self.timeline_refresh(Some(self.timeline_cursor_ms));
    }

    /// Move the timeline cursor by `cols` rendered columns (the event loop records the
    /// strip width before each draw), clamped to the window.
    fn timeline_step(&mut self, cols: i64) {
        let Some(w) = &self.timeline else { return };
        let span = w.to_ms.saturating_sub(w.from_ms).max(1);
        let col_ms = (span / self.timeline_cols.max(1) as u64).max(1);
        let delta = col_ms.saturating_mul(cols.unsigned_abs());
        let target = if cols < 0 {
            self.timeline_cursor_ms.saturating_sub(delta)
        } else {
            self.timeline_cursor_ms.saturating_add(delta)
        };
        self.timeline_cursor_ms = target.clamp(w.from_ms, w.to_ms);
    }

    /// Move the cursor and re-query the cached window (cursor ± 5 min). The queries are
    /// cheap indexed range reads, so a re-query per keypress is fine; a failed query leaves
    /// the affected slice empty rather than crashing the UI.
    fn seek(&mut self, cursor_ms: u64) {
        self.cursor_ms = cursor_ms;
        let from_ms = cursor_ms.saturating_sub(REPLAY_HALF_WINDOW_MS);
        let to_ms = cursor_ms.saturating_add(REPLAY_HALF_WINDOW_MS);
        let ids: Vec<_> = {
            let sh = self.collector.shared.lock().unwrap();
            sh.infos.iter().map(|i| i.id.clone()).collect()
        };
        let Some(store) = &self.store else { return };
        let samples = ids
            .iter()
            .map(|id| {
                store
                    .samples_between(id, from_ms, to_ms, Tier::TenSec)
                    .unwrap_or_default()
            })
            .collect();
        let processes = ids
            .iter()
            .map(|id| store.processes_at(id, cursor_ms).unwrap_or_default())
            .collect();
        let events = store.events_between(from_ms, to_ms).unwrap_or_default();
        self.replay = Some(ReplayWindow {
            from_ms,
            to_ms,
            samples,
            processes,
            events,
        });
    }

    /// Scrub by `delta_ms`, clamped to the recorded range so the cursor cannot wander into
    /// the void past either end of the recording. (Seeking to an event's exact ts is NOT
    /// clamped — events can sit just past the last flushed bucket.)
    fn scrub(&mut self, delta_ms: i64) {
        let target = if delta_ms < 0 {
            self.cursor_ms.saturating_sub(delta_ms.unsigned_abs())
        } else {
            self.cursor_ms.saturating_add(delta_ms as u64)
        };
        let clamped = match self.recorded_range() {
            Some((earliest, latest)) => target.clamp(earliest, latest),
            None => target,
        };
        self.seek(clamped);
    }

    /// `(earliest, latest)` recorded bucket across both tiers, when the store holds any.
    fn recorded_range(&self) -> Option<(u64, u64)> {
        let store = self.store.as_ref()?;
        let earliest = store.earliest_bucket_ms().ok().flatten()?;
        let latest = store.latest_bucket_ms().ok().flatten()?;
        Some((earliest, latest))
    }

    /// End of recorded coverage: the newest bucket's key PLUS its width.
    /// `latest_bucket_ms` is a bucket START, and a window ending exactly on it would
    /// clip the recording's final bucket to a zero-width slice that renders as a blank
    /// column — recorded data shown as a recording gap, the exact lie the strips
    /// promise never to tell. The recorder folds every frame into both tiers, so the
    /// newest key across tiers is always a 10s key and +10s is the coverage end.
    /// Events are inserted the moment they happen while their bucket may never be
    /// flushed (the recording can end first), so the newest event can sit past the
    /// last bucket and extends the end too.
    fn recorded_end(&self) -> Option<u64> {
        let store = self.store.as_ref()?;
        let bucket_end = store
            .latest_bucket_ms()
            .ok()
            .flatten()
            .map(|key| key + Tier::TenSec.width_ms());
        let event_ts = store.latest_event_ms(None).ok().flatten();
        match (bucket_end, event_ts) {
            (Some(b), Some(e)) => Some(b.max(e)),
            (b, e) => b.or(e),
        }
    }

    /// Move the story selection by `delta` within the active feed (live ring or replay
    /// window). A first press selects the top row; the index clamps at both ends.
    fn cycle_story_filter(&mut self) {
        self.story_filter = self.story_filter.next();
        // The old index points into a different list now.
        self.story_selected = None;
    }

    /// Indices into the replay window's events that the current filter shows.
    pub fn replay_visible(&self) -> Vec<usize> {
        self.replay
            .as_ref()
            .map(|w| {
                w.events
                    .iter()
                    .enumerate()
                    .filter(|(_, e)| self.story_filter.admits(e))
                    .map(|(i, _)| i)
                    .collect()
            })
            .unwrap_or_default()
    }

    fn move_story_selection(&mut self, delta: i64) {
        match self.mode {
            Mode::Live => {
                let filter = self.story_filter;
                let count = self
                    .collector
                    .shared
                    .lock()
                    .unwrap()
                    .history
                    .events()
                    .iter()
                    .filter(|e| filter.admits(e))
                    .count();
                if count == 0 {
                    self.story_selected = None;
                    return;
                }
                self.story_selected = Some(match self.story_selected {
                    None => 0,
                    Some(i) => i.saturating_add_signed(delta as isize).min(count - 1),
                });
            }
            Mode::Replay => {
                // Step through the VISIBLE rows; the stored index stays a real index into
                // the window's events so Enter and the renderer need no remapping.
                let visible = self.replay_visible();
                if visible.is_empty() {
                    self.story_selected = None;
                    return;
                }
                let pos = match self
                    .story_selected
                    .and_then(|s| visible.iter().position(|&v| v == s))
                {
                    None => 0,
                    Some(p) => p
                        .saturating_add_signed(delta as isize)
                        .min(visible.len() - 1),
                };
                self.story_selected = Some(visible[pos]);
            }
            // The timeline has no story pane; its event lane is cursor-driven.
            Mode::Timeline => self.story_selected = None,
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn ctrl_c_quits_but_bare_c_still_toggles_the_chart() {
        use ratatui::crossterm::event::KeyModifiers;
        assert!(super::is_ctrl_c(KeyCode::Char('c'), KeyModifiers::CONTROL));
        assert!(super::is_ctrl_c(
            KeyCode::Char('C'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT
        ));
        assert!(!super::is_ctrl_c(KeyCode::Char('c'), KeyModifiers::NONE));
        assert!(!super::is_ctrl_c(KeyCode::Char('x'), KeyModifiers::CONTROL));
    }

    use std::path::PathBuf;
    use std::sync::atomic::Ordering;

    use gpuviewer_core::{
        Confidence, DeviceId, DynamicSample, Event, EventKind, ProcessKind, ProcessSample,
        Severity, ThrottleReasons, Vendor,
    };
    use gpuviewer_history::{Recorder, SqliteStore, Tier};
    use ratatui::backend::TestBackend;
    use ratatui::crossterm::event::KeyCode;
    use ratatui::Terminal;

    use super::{App, ChartStyle, KeyOutcome, Mode, ReplayBlock, TIMELINE_ZOOMS};
    use crate::collector::test_collector;

    /// Base timestamp of the seeded recording: aligned to BOTH the 10s and 1m buckets so
    /// earliest/latest are exact, and fixed so the tests are deterministic.
    const BASE: u64 = 1_000_000_080_000;

    fn scratch_path() -> PathBuf {
        use std::sync::atomic::AtomicU64;
        static SEQ: AtomicU64 = AtomicU64::new(0);
        let n = SEQ.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!(
            "gpuviewer-replay-test-{}-{n}.db",
            std::process::id()
        ))
    }

    fn cleanup(path: &PathBuf) {
        let _ = std::fs::remove_file(path);
        for ext in ["-wal", "-shm"] {
            let mut p = path.as_os_str().to_os_string();
            p.push(ext);
            let _ = std::fs::remove_file(p);
        }
    }

    fn full_sample(ts_ms: u64, util: f32) -> DynamicSample {
        DynamicSample {
            ts_ms,
            util_pct: Some(util),
            util_engine: None,
            mem_used_bytes: Some(2 << 30),
            power_mw: Some(150_000),
            temp_c: Some(65.0),
            fan_pct: Some(45.0),
            sm_clock_mhz: Some(1600),
            mem_clock_mhz: Some(8000),
            encoder_pct: None,
            decoder_pct: None,
            throttle: Some(ThrottleReasons::default()),
            power_limit_mw: None,
            pcie_gen: None,
            pcie_width: None,
            ecc_uncorrected: None,
        }
    }

    /// A process that exists ONLY in the seeded history — the live mock never produces a
    /// "ghost-train", so seeing it on screen proves replay reads the store, not the live
    /// process list.
    fn ghost_proc() -> ProcessSample {
        ProcessSample {
            pid: 4242,
            name: "ghost-train".into(),
            kind: ProcessKind::Compute,
            mem_bytes: Some(2 << 30),
            util_pct: Some(35.0),
            cpu_pct: Some(150.0),
            container: Some("docker:3f2a9c1b".into()),
            cmdline: None,
        }
    }

    fn throttle_event(ts_ms: u64, dev: &DeviceId) -> Event {
        Event {
            ts_ms,
            device: dev.clone(),
            kind: EventKind::ThrottleStart,
            severity: Severity::Warning,
            confidence: Confidence::Fact,
            title: "GPU0 began throttling (thermal)".into(),
            evidence: "throttle bits: [thermal]; 84C".into(),
        }
    }

    fn likely_event(ts_ms: u64, dev: &DeviceId) -> Event {
        Event {
            ts_ms,
            device: dev.clone(),
            kind: EventKind::IdleGap,
            severity: Severity::Info,
            confidence: Confidence::Likely,
            title: "GPU0 sat idle 14s — likely a dataloader stall".into(),
            evidence: "util 92% -> mean 2% over 14s".into(),
        }
    }

    /// Seed a recording for `dev`: three 10s buckets (BASE util_avg 50, BASE+10s util 20,
    /// BASE+20s util 80), the ghost-train process in every bucket, and two events at
    /// BASE+5s (fact) and BASE+15s (inference).
    fn seed_store(path: &PathBuf, dev: &DeviceId) {
        let (store, _) = SqliteStore::open(path).unwrap();
        let mut rec = Recorder::new(store);
        rec.store_mut()
            .register_device(dev, "Seeded GPU", Vendor::Unknown, Some(24 << 30))
            .unwrap();
        rec.observe(dev, &full_sample(BASE + 1_000, 40.0), &[ghost_proc()]);
        rec.observe(dev, &full_sample(BASE + 3_000, 60.0), &[ghost_proc()]);
        rec.observe(dev, &full_sample(BASE + 11_000, 20.0), &[ghost_proc()]);
        rec.observe(dev, &full_sample(BASE + 21_000, 80.0), &[ghost_proc()]);
        rec.record_events(&[
            throttle_event(BASE + 5_000, dev),
            likely_event(BASE + 15_000, dev),
        ]);
        rec.flush();
    }

    /// An app over a seeded store: returns it plus the scratch path for cleanup.
    fn seeded_app() -> (App, PathBuf) {
        let path = scratch_path();
        let collector = test_collector(Some(path.clone()));
        let dev = collector.shared.lock().unwrap().infos[0].id.clone();
        seed_store(&path, &dev);
        (App::new(collector), path)
    }

    /// An app pinned to the recording at `path` (`gpuviewer view incident.gpvr`),
    /// with `dev` as its one device. Split from [`seeded_viewer`] so tests can seed a
    /// custom store first.
    fn viewer_over(path: &PathBuf, dev: &DeviceId) -> App {
        let store = SqliteStore::open_readonly(path).unwrap();
        let infos = vec![gpuviewer_core::StaticInfo {
            id: dev.clone(),
            vendor: Vendor::Unknown,
            name: "Seeded GPU".into(),
            backend: "file".into(),
            mem_total_bytes: Some(24 << 30),
            power_limit_mw: None,
            max_sm_clock_mhz: None,
            temp_slowdown_c: None,
            driver_version: None,
            process_hint: None,
            source_caveat: None,
            pcie_max_gen: None,
            pcie_max_width: None,
        }];
        let collector = crate::collector::Collector::stationary(infos, Some(path.clone()));
        App::viewer(collector, store, "incident.gpvr".into())
    }

    /// A viewer over the standard [`seed_store`] recording, plus the scratch path for
    /// cleanup and the device the file records.
    fn seeded_viewer() -> (App, PathBuf, DeviceId) {
        let path = scratch_path();
        let dev = DeviceId("0000:09:00.0".into());
        seed_store(&path, &dev);
        (viewer_over(&path, &dev), path, dev)
    }

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

    /// 'r' enters replay anchored at the newest recorded bucket, and everything on screen
    /// comes from the store: chart title shows the cursor bucket's util_avg, the process
    /// table shows a process that exists only in history (with cpu column and container
    /// after the name), and the story feed lists the window's events.
    #[test]
    fn replay_enters_at_latest_and_renders_from_store() {
        let (mut app, path) = seeded_app();

        assert_eq!(app.handle_key(KeyCode::Char('r')), KeyOutcome::Continue);
        assert_eq!(app.mode, Mode::Replay);
        assert_eq!(
            app.cursor_ms,
            BASE + 20_000,
            "r anchors at the newest recorded bucket"
        );

        let screen = draw(&app);
        assert!(screen.contains("REPLAY"), "must say REPLAY:\n{screen}");
        assert!(
            screen.contains("util 80% REPLAY"),
            "chart must show the cursor bucket's util_avg from the store:\n{screen}"
        );
        assert!(
            screen.contains("ghost-train"),
            "process present only in history must render:\n{screen}"
        );
        assert!(
            screen.contains("[docker:3f2a9c1b]"),
            "container shown after the process name:\n{screen}"
        );
        assert!(
            screen.contains("150%"),
            "cpu column from cpu_avg:\n{screen}"
        );
        assert!(
            screen.contains("began throttling"),
            "window events must reach the story feed:\n{screen}"
        );
        cleanup(&path);
    }

    /// Left/Right scrub ±10s and PgUp/PgDn ±5min, all clamped to the recorded range;
    /// Home jumps to the earliest bucket; Tab still switches devices.
    #[test]
    fn replay_scrub_clamps_to_recorded_range() {
        let (mut app, path) = seeded_app();
        app.handle_key(KeyCode::Char('r'));
        assert_eq!(app.cursor_ms, BASE + 20_000);

        app.handle_key(KeyCode::Left);
        assert_eq!(app.cursor_ms, BASE + 10_000, "left scrubs back 10s");
        app.handle_key(KeyCode::Right);
        app.handle_key(KeyCode::Right);
        assert_eq!(
            app.cursor_ms,
            BASE + 20_000,
            "right scrub clamps at the newest bucket"
        );
        app.handle_key(KeyCode::PageUp);
        assert_eq!(app.cursor_ms, BASE, "PgUp clamps at the earliest bucket");
        app.handle_key(KeyCode::PageDown);
        assert_eq!(app.cursor_ms, BASE + 20_000, "PgDn clamps at the newest");
        app.handle_key(KeyCode::Home);
        assert_eq!(app.cursor_ms, BASE, "Home jumps to the earliest bucket");

        app.handle_key(KeyCode::Tab);
        assert_eq!(app.selected, 1, "tab still switches devices in replay");
        cleanup(&path);
    }

    /// Up/Down select events within the replay window and Enter re-anchors the cursor to
    /// the selected event's ts (the selection follows the event into the new window).
    #[test]
    fn replay_enter_anchors_cursor_to_selected_event() {
        let (mut app, path) = seeded_app();
        app.handle_key(KeyCode::Char('r'));

        app.handle_key(KeyCode::Down); // first press selects the oldest window event
        assert_eq!(app.story_selected, Some(0));
        app.handle_key(KeyCode::Enter);
        assert_eq!(
            app.cursor_ms,
            BASE + 5_000,
            "Enter re-anchors the cursor to the event ts"
        );
        assert_eq!(
            app.story_selected,
            Some(0),
            "selection follows the event into the re-centered window"
        );

        app.handle_key(KeyCode::Down);
        app.handle_key(KeyCode::Enter);
        assert_eq!(app.cursor_ms, BASE + 15_000);
        cleanup(&path);
    }

    /// From live: Up selects the newest story row and Enter enters replay anchored at
    /// that event's ts.
    #[test]
    fn live_enter_on_selected_event_enters_replay() {
        let (mut app, path) = seeded_app();
        {
            let mut sh = app.collector.shared.lock().unwrap();
            let dev = sh.infos[0].id.clone();
            sh.history.push_events([throttle_event(BASE + 5_000, &dev)]);
        }
        app.handle_key(KeyCode::Up);
        assert_eq!(
            app.story_selected,
            Some(0),
            "first press selects the top row"
        );
        app.handle_key(KeyCode::Enter);
        assert_eq!(app.mode, Mode::Replay);
        assert_eq!(
            app.cursor_ms,
            BASE + 5_000,
            "cursor anchors at the selected event's ts"
        );
        cleanup(&path);
    }

    /// Live filter: with "facts only", the newest row is the fact even though a newer
    /// inference exists, and Enter jumps to THAT fact — selection indexes the filtered feed.
    #[test]
    fn live_story_filter_hides_inferences_and_enter_follows_the_filtered_row() {
        let (mut app, path) = seeded_app();
        {
            let mut sh = app.collector.shared.lock().unwrap();
            let dev = sh.infos[0].id.clone();
            sh.history.push_events([
                throttle_event(BASE + 5_000, &dev),
                likely_event(BASE + 15_000, &dev),
            ]);
        }
        app.handle_key(KeyCode::Char('f')); // warnings+
        assert_eq!(app.story_filter, super::StoryFilter::Warnings);
        app.handle_key(KeyCode::Char('f')); // facts only
        assert_eq!(app.story_filter, super::StoryFilter::Facts);
        app.handle_key(KeyCode::Up);
        app.handle_key(KeyCode::Down); // only one visible row: stays on it
        assert_eq!(app.story_selected, Some(0));
        app.handle_key(KeyCode::Enter);
        assert_eq!(app.mode, Mode::Replay);
        assert_eq!(
            app.cursor_ms,
            BASE + 5_000,
            "the fact, not the newer inference"
        );
        app.handle_key(KeyCode::Char('f')); // back to all
        assert_eq!(app.story_filter, super::StoryFilter::All);
        assert_eq!(
            app.story_selected, None,
            "a filter change drops the stale index"
        );
        cleanup(&path);
    }

    /// Replay filter: selection steps over hidden rows, and the stored index is still
    /// the real window index (Enter seeks to the right event).
    #[test]
    fn replay_story_filter_skips_hidden_rows() {
        let (mut app, path) = seeded_app();
        app.enter_replay(Some(BASE + 10_000));
        app.handle_key(KeyCode::Char('f'));
        app.handle_key(KeyCode::Char('f')); // facts only: the BASE+15s inference is hidden
        app.handle_key(KeyCode::Down);
        app.handle_key(KeyCode::Down);
        let w = app.replay_window().expect("replay window");
        let sel = app.story_selected.expect("a row is selected");
        assert_eq!(
            w.events[sel].ts_ms,
            BASE + 5_000,
            "only the fact is selectable"
        );
        cleanup(&path);
    }

    /// q quits from BOTH modes; Esc quits only from live — in replay it returns to live
    /// (and 'r' toggles back out too).
    #[test]
    fn quit_and_escape_semantics_per_mode() {
        let (mut app, path) = seeded_app();

        assert_eq!(app.handle_key(KeyCode::Char('q')), KeyOutcome::Quit);
        assert_eq!(
            app.handle_key(KeyCode::Esc),
            KeyOutcome::Quit,
            "Esc quits live"
        );

        app.handle_key(KeyCode::Char('r'));
        assert_eq!(app.mode, Mode::Replay);
        assert_eq!(
            app.handle_key(KeyCode::Esc),
            KeyOutcome::Continue,
            "Esc must NOT quit while in replay"
        );
        assert_eq!(app.mode, Mode::Live, "Esc returns to live");

        app.handle_key(KeyCode::Char('r'));
        assert_eq!(app.mode, Mode::Replay);
        assert_eq!(
            app.handle_key(KeyCode::Char('q')),
            KeyOutcome::Quit,
            "q still quits from replay"
        );
        assert_eq!(app.handle_key(KeyCode::Char('r')), KeyOutcome::Continue);
        assert_eq!(app.mode, Mode::Live, "'r' in replay returns to live");

        // Esc back in live quits again, and the footer no longer says REPLAY.
        assert_eq!(app.handle_key(KeyCode::Esc), KeyOutcome::Quit);
        let screen = draw(&app);
        assert!(
            !screen.contains("REPLAY"),
            "live view must not be labeled REPLAY:\n{screen}"
        );
        cleanup(&path);
    }

    /// `gpuviewer view`: the app opens pinned to the file — replay from the first frame,
    /// anchored at the newest event — and Esc/'r' must NOT drop to Live (there is no live
    /// behind a recording); 'q' still quits; the footer names the file as read-only.
    #[test]
    fn viewer_pins_replay_and_never_drops_to_live() {
        let (mut app, path, _dev) = seeded_viewer();

        assert_eq!(app.mode, Mode::Replay, "the viewer starts in replay");
        assert_eq!(
            app.cursor_ms,
            BASE + 15_000,
            "cursor anchors at the file's newest event"
        );

        assert_eq!(app.handle_key(KeyCode::Esc), KeyOutcome::Continue);
        assert_eq!(
            app.mode,
            Mode::Replay,
            "Esc must not drop to Live — there is no live behind the file"
        );
        assert_eq!(app.handle_key(KeyCode::Char('r')), KeyOutcome::Continue);
        assert_eq!(app.mode, Mode::Replay, "'r' is inert in the viewer too");

        let screen = draw(&app);
        assert!(
            screen.contains("viewing incident.gpvr (read-only)"),
            "footer must name the file and promise read-only:\n{screen}"
        );
        assert!(
            screen.contains("REPLAY"),
            "viewer is labeled REPLAY:\n{screen}"
        );
        assert!(
            screen.contains("ghost-train"),
            "the file's recorded processes must render:\n{screen}"
        );

        assert_eq!(
            app.handle_key(KeyCode::Char('q')),
            KeyOutcome::Quit,
            "q quits the viewer"
        );
        cleanup(&path);
    }

    /// Replay keys with no store (persistence disabled) stay live and surface the footer
    /// hint instead of doing nothing silently.
    #[test]
    fn replay_without_store_shows_footer_hint() {
        let mut app = App::new(test_collector(None));
        app.handle_key(KeyCode::Char('r'));
        assert_eq!(app.mode, Mode::Live, "no store: replay must not engage");
        assert_eq!(app.replay_hint, Some(ReplayBlock::NoPersistence));
        let screen = draw(&app);
        assert!(
            screen.contains("replay needs persistence"),
            "footer must explain the dead key:\n{screen}"
        );
    }

    /// 't' opens the timeline overview at the 6h rung with the window ending at "now"
    /// and the cursor on the newest edge; '+'/'-' walk the zoom ladder and clamp at both
    /// ends; the cursor steps by rendered column, jumps by page, and pins to the window
    /// edges; Enter drills down into replay anchored exactly at the cursor; 't' from
    /// replay climbs back up with the cursor carried over; Esc drops to live.
    #[test]
    fn timeline_zooms_steps_and_drills_into_replay() {
        let (mut app, path) = seeded_app();

        app.handle_key(KeyCode::Char('t'));
        assert_eq!(app.mode, Mode::Timeline);
        let w = app.timeline_window().expect("entering builds a window");
        let (from, to) = (w.from_ms, w.to_ms);
        let span = TIMELINE_ZOOMS[2].span_ms;
        assert!(
            to - from >= span && to - from < span + 60_000,
            "default window spans the 6h rung (start aligned down to the 1m tier)"
        );
        assert_eq!(w.tier, Tier::OneMin, "6h reads the 1m tier");
        assert_eq!(
            app.timeline_cursor_ms, to,
            "cursor starts at the newest edge"
        );

        // Zoom ladder: '+' narrows and clamps at 1h, '-' widens and clamps at 7d.
        app.handle_key(KeyCode::Char('+'));
        app.handle_key(KeyCode::Char('+'));
        assert_eq!(app.timeline_zoom, 0);
        assert_eq!(
            app.timeline_window().unwrap().tier,
            Tier::TenSec,
            "the 1h rung reads the 10s tier"
        );
        app.handle_key(KeyCode::Char('+'));
        assert_eq!(app.timeline_zoom, 0, "'+' clamps at the narrowest rung");
        for _ in 0..10 {
            app.handle_key(KeyCode::Char('-'));
        }
        assert_eq!(
            app.timeline_zoom,
            TIMELINE_ZOOMS.len() - 1,
            "'-' clamps at 7d"
        );

        // Cursor: Home/End pin to the edges, arrows step one rendered column, PgDn
        // jumps ten, and steps clamp at the window edges.
        app.timeline_cols = 100;
        app.handle_key(KeyCode::Home);
        let w = app.timeline_window().unwrap();
        let (from, to) = (w.from_ms, w.to_ms);
        let col_ms = ((to - from).max(1) / 100).max(1);
        assert_eq!(
            app.timeline_cursor_ms, from,
            "Home pins to the window start"
        );
        app.handle_key(KeyCode::Left);
        assert_eq!(app.timeline_cursor_ms, from, "Left clamps at the start");
        app.handle_key(KeyCode::Right);
        assert_eq!(
            app.timeline_cursor_ms,
            from + col_ms,
            "Right steps exactly one rendered column"
        );
        app.handle_key(KeyCode::PageDown);
        assert_eq!(app.timeline_cursor_ms, from + 11 * col_ms, "PgDn jumps ten");
        app.handle_key(KeyCode::End);
        assert_eq!(app.timeline_cursor_ms, to, "End pins to the window end");
        app.handle_key(KeyCode::PageUp);
        assert_eq!(app.timeline_cursor_ms, to - 10 * col_ms);

        // Enter drills down; 't' climbs back up with the cursor carried over.
        let cursor = app.timeline_cursor_ms;
        app.handle_key(KeyCode::Enter);
        assert_eq!(app.mode, Mode::Replay);
        assert_eq!(
            app.cursor_ms, cursor,
            "Enter drills into replay at the timeline cursor"
        );
        app.handle_key(KeyCode::Char('t'));
        assert_eq!(app.mode, Mode::Timeline);
        assert_eq!(
            app.timeline_cursor_ms, cursor,
            "re-entering from replay keeps the cursor"
        );
        assert_eq!(app.handle_key(KeyCode::Esc), KeyOutcome::Continue);
        assert_eq!(app.mode, Mode::Live, "Esc drops from the overview to live");

        // Tab still switches devices in the overview.
        app.handle_key(KeyCode::Char('t'));
        app.handle_key(KeyCode::Tab);
        assert_eq!(app.selected, 1);
        assert_eq!(
            app.handle_key(KeyCode::Char('q')),
            KeyOutcome::Quit,
            "q quits from the timeline too"
        );
        cleanup(&path);
    }

    /// A db path that exists but will not open is NOT the same as persistence being off.
    /// The old footer asserted "--no-persist is set" for both, telling the user a flag was
    /// set that they never passed — the exact confidently-wrong narration the honesty
    /// contract rules out. Each cause gets its own sentence.
    #[test]
    fn unreadable_db_blames_the_db_not_the_flag() {
        // A path that is not there — the file was deleted or quarantined out from under a
        // running session. A read-only open refuses to create it, so this is the real
        // Err branch. (Junk CONTENT would not do: SQLite parses lazily and opens fine.)
        let path = scratch_path();
        cleanup(&path);

        let mut app = App::new(test_collector(Some(path.clone())));
        app.handle_key(KeyCode::Char('r'));

        assert_eq!(
            app.mode,
            Mode::Live,
            "unreadable store: replay must not engage"
        );
        assert_eq!(app.replay_hint, Some(ReplayBlock::Unreadable));

        let screen = draw(&app);
        assert!(
            screen.contains("history db unreadable"),
            "footer must name the real cause:\n{screen}"
        );
        assert!(
            !screen.contains("--no-persist"),
            "footer must not assert a flag the user never passed:\n{screen}"
        );
        cleanup(&path);
    }

    /// 't' with no store behaves like 'r': stays live and surfaces the footer hint.
    #[test]
    fn timeline_without_store_shows_footer_hint() {
        let mut app = App::new(test_collector(None));
        app.handle_key(KeyCode::Char('t'));
        assert_eq!(
            app.mode,
            Mode::Live,
            "no store: the overview must not engage"
        );
        assert_eq!(app.replay_hint, Some(ReplayBlock::NoPersistence));
    }

    /// In the file viewer the timeline window ends at the END of the file's newest
    /// bucket — its key plus the 10s width, never the key itself, which would clip the
    /// final recorded bucket to a zero-width slice rendered as a gap (a recording has
    /// no "now" either way). The start clamps to the recorded span, the replay cursor
    /// carries over, the screen labels itself TIMELINE with solid strips and lane
    /// markers, and Esc returns to the pinned replay — never to a live view that does
    /// not exist.
    #[test]
    fn viewer_timeline_clamps_to_file_span_and_returns_to_replay() {
        let (mut app, path, _dev) = seeded_viewer();

        app.handle_key(KeyCode::Char('t'));
        assert_eq!(app.mode, Mode::Timeline);
        let w = app.timeline_window().expect("viewer builds a window");
        assert_eq!(
            w.to_ms,
            BASE + 30_000,
            "the viewer window ends at the END of the file's newest bucket (key + 10s)"
        );
        assert_eq!(
            w.from_ms, BASE,
            "the start clamps to the file's oldest bucket"
        );
        assert!(w.clamped, "a 20s file inside a 6h zoom is clamped");
        assert_eq!(
            app.timeline_cursor_ms,
            BASE + 15_000,
            "the replay cursor (the file's newest event) carries over"
        );

        let screen = draw(&app);
        assert!(
            screen.contains("TIMELINE") && screen.contains("peak per col"),
            "the overview labels itself and its aggregation:\n{screen}"
        );
        assert!(
            screen.contains('█'),
            "strips paint solid filled columns:\n{screen}"
        );
        assert!(
            screen.contains('⚠'),
            "the lane marks the throttle fact with its severity icon:\n{screen}"
        );
        assert!(
            screen.contains('?'),
            "the lane marks the inference as '?' — not a fact icon:\n{screen}"
        );
        assert!(
            screen.contains("viewing incident.gpvr (read-only)"),
            "the viewer keeps naming the file:\n{screen}"
        );
        assert!(
            screen.contains("(30s recorded)"),
            "a clamped window must state the actual recorded span — three full 10s \
             buckets, not one bucket short:\n{screen}"
        );

        assert_eq!(app.handle_key(KeyCode::Esc), KeyOutcome::Continue);
        assert_eq!(
            app.mode,
            Mode::Replay,
            "the viewer's overview exits to the pinned replay, not to live"
        );
        cleanup(&path);
    }

    /// Window-end defect guard at the 1h/TenSec rung, where the newest 10s bucket's KEY
    /// always equals the old (buggy) window end: the window must extend to the bucket's
    /// END, so the file's final recorded bucket paints and the End-cursor readout shows
    /// its values — never "util — · vram —" over recorded data.
    #[test]
    fn viewer_timeline_tensec_rung_covers_the_final_bucket() {
        let (mut app, path, _dev) = seeded_viewer();

        app.handle_key(KeyCode::Char('t'));
        app.handle_key(KeyCode::Char('+'));
        app.handle_key(KeyCode::Char('+'));
        let w = app.timeline_window().expect("viewer builds a window");
        assert_eq!(w.tier, Tier::TenSec, "the 1h rung reads the 10s tier");
        assert_eq!(
            w.to_ms,
            BASE + 30_000,
            "the window ends at the newest 10s bucket's END — ending on its key clips \
             the final bucket to a zero-width slice that renders as a gap"
        );

        app.handle_key(KeyCode::End);
        assert_eq!(app.timeline_cursor_ms, BASE + 30_000);
        let screen = draw(&app);
        assert!(
            screen.contains("util 80%"),
            "the End cursor sits over the final recorded bucket, not a phantom gap:\n{screen}"
        );
        assert!(
            screen.contains("vram 2.0 GiB"),
            "vram at the End cursor comes from the final bucket too:\n{screen}"
        );
        cleanup(&path);
    }

    /// The OneMin-rung variant of the window-end defect: when a recording's final frame
    /// lands in the first 10s slot of a minute (the newest 10s key equals the 1m key —
    /// about one in six recordings), a window ending on the bucket KEY clips the entire
    /// final minute to nothing. The recorded minute must render.
    #[test]
    fn viewer_timeline_keeps_final_minute_when_file_ends_at_minute_start() {
        let path = scratch_path();
        let dev = DeviceId("0000:09:00.0".into());
        {
            let (store, _) = SqliteStore::open(&path).unwrap();
            let mut rec = Recorder::new(store);
            rec.store_mut()
                .register_device(&dev, "Seeded GPU", Vendor::Unknown, Some(24 << 30))
                .unwrap();
            rec.observe(&dev, &full_sample(BASE + 1_000, 40.0), &[]);
            // The final frame sits just past a minute boundary: 10s key == 1m key.
            rec.observe(&dev, &full_sample(BASE + 61_000, 70.0), &[]);
            rec.flush();
        }
        let mut app = viewer_over(&path, &dev);

        app.handle_key(KeyCode::Char('t'));
        let w = app.timeline_window().expect("viewer builds a window");
        assert_eq!(
            w.tier,
            Tier::OneMin,
            "the default 6h rung reads the 1m tier"
        );
        assert_eq!(
            w.to_ms,
            BASE + 70_000,
            "the window ends at the newest 10s bucket's END (BASE+60s key + 10s)"
        );

        app.handle_key(KeyCode::End);
        let screen = draw(&app);
        assert!(
            screen.contains("util 70%"),
            "the file's final minute must render under the End cursor, not vanish:\n{screen}"
        );
        assert!(
            screen.contains("(1m10s recorded)"),
            "the clamped span states the full recorded coverage:\n{screen}"
        );
        cleanup(&path);
    }

    /// Events land in the store the moment they happen, while their bucket may never be
    /// flushed (the recording can end first) — an event past the last flushed bucket
    /// must stretch the viewer's window so it still appears in the event lane.
    #[test]
    fn viewer_timeline_stretches_to_an_event_past_the_last_bucket() {
        let (mut app, path, dev) = seeded_viewer();
        {
            let (mut store, _) = SqliteStore::open(&path).unwrap();
            store
                .insert_events(&[throttle_event(BASE + 45_000, &dev)])
                .unwrap();
        }

        app.handle_key(KeyCode::Char('t'));
        let w = app.timeline_window().expect("viewer builds a window");
        assert_eq!(
            w.to_ms,
            BASE + 45_000,
            "the window end stretches to the newest event past the last bucket"
        );
        assert!(
            w.events.iter().any(|e| e.ts_ms == BASE + 45_000),
            "the late event must be inside the window, not silently dropped"
        );
        cleanup(&path);
    }

    /// Tick-invalidation defect guard: a live overview must not freeze at the instant
    /// 't' was pressed. Between ticks the cache holds (no SQLite on the render path);
    /// once the collector folds a new frame the window is re-queried with its right
    /// edge back at "now" — an edge-pinned cursor rides the edge, a scrolled-back
    /// cursor keeps its wall-clock position.
    #[test]
    fn timeline_refreshes_on_collector_tick() {
        let (mut app, path) = seeded_app();
        app.handle_key(KeyCode::Char('t'));
        assert_eq!(app.mode, Mode::Timeline);

        // No tick since the window was built: the cache holds (sentinel survives).
        app.timeline.as_mut().unwrap().to_ms = 12_345;
        app.timeline_tick();
        assert_eq!(
            app.timeline.as_ref().unwrap().to_ms,
            12_345,
            "no tick → no re-query"
        );

        // A tick landed: the window is rebuilt ending at "now", and the cursor —
        // sitting on the newest edge — rides it.
        let before = gpuviewer_core::now_ms();
        app.collector.shared.lock().unwrap().tick_seq += 1;
        app.timeline_tick();
        let to_ms = app.timeline.as_ref().unwrap().to_ms;
        assert!(
            to_ms >= before,
            "a tick must pull the stale right edge back to now"
        );
        assert_eq!(
            app.timeline_cursor_ms, to_ms,
            "a cursor pinned to the newest edge rides the refreshed edge"
        );

        // A scrolled-back cursor stays put across a refresh.
        app.timeline_cols = 100;
        app.handle_key(KeyCode::Home);
        app.handle_key(KeyCode::Right);
        app.handle_key(KeyCode::Right);
        let scrolled = app.timeline_cursor_ms;
        app.collector.shared.lock().unwrap().tick_seq += 1;
        app.timeline_tick();
        assert_eq!(
            app.timeline_cursor_ms, scrolled,
            "a scrolled-back cursor must keep its wall-clock position on refresh"
        );
        cleanup(&path);
    }

    /// The file viewer's overview never tick-refreshes — a recording does not grow (and
    /// its stationary collector never ticks; the guard holds even if the seq moved).
    #[test]
    fn viewer_timeline_never_tick_refreshes() {
        let (mut app, path, _dev) = seeded_viewer();
        app.handle_key(KeyCode::Char('t'));
        app.timeline.as_mut().unwrap().to_ms = 12_345;
        app.collector.shared.lock().unwrap().tick_seq += 1;
        app.timeline_tick();
        assert_eq!(
            app.timeline.as_ref().unwrap().to_ms,
            12_345,
            "a pinned recording must never be re-queried on ticks"
        );
        cleanup(&path);
    }

    /// 'c' cycles braille↔solid in live and replay — same data, same gaps, different
    /// paint — and the timeline ignores it (its strips are always solid). 's' must NOT
    /// touch the style: it is wasd-down (story selection) since the Mac-alias change.
    #[test]
    fn chart_style_toggles_in_live_and_replay_but_not_timeline() {
        let (mut app, path) = seeded_app();
        assert_eq!(
            app.chart_style,
            ChartStyle::Braille,
            "braille is the default"
        );

        fn has_braille(s: &str) -> bool {
            s.chars().any(|c| ('\u{2800}'..='\u{28FF}').contains(&c))
        }

        app.handle_key(KeyCode::Char('s'));
        assert_eq!(
            app.chart_style,
            ChartStyle::Braille,
            "'s' is story-down now, never the style toggle"
        );
        app.handle_key(KeyCode::Char('c'));
        assert_eq!(app.chart_style, ChartStyle::Solid, "'c' toggles in live");
        app.handle_key(KeyCode::Char('r'));
        let screen = draw(&app);
        assert!(
            screen.contains("util 80% REPLAY"),
            "solid replay shows the same cursor value:\n{screen}"
        );
        assert!(
            !has_braille(&screen),
            "solid mode must not draw braille outlines:\n{screen}"
        );

        app.handle_key(KeyCode::Char('c'));
        assert_eq!(
            app.chart_style,
            ChartStyle::Braille,
            "'c' toggles in replay"
        );
        let screen = draw(&app);
        assert!(
            has_braille(&screen),
            "braille mode draws the step outline:\n{screen}"
        );
        assert!(
            screen.contains("c style"),
            "the footer advertises the toggle:\n{screen}"
        );

        app.handle_key(KeyCode::Char('t'));
        app.handle_key(KeyCode::Char('c'));
        assert_eq!(
            app.chart_style,
            ChartStyle::Braille,
            "the timeline ignores 'c' — its strips are always solid"
        );
        cleanup(&path);
    }

    /// Mac laptops have no PgUp/PgDn/Home/End and terminals eat Fn+arrows, so every
    /// navigation key has a letter alias: wasd = arrows, A/D = PgUp/PgDn, g/G =
    /// Home/End. The aliases must land in the SAME match arms as the keys they mirror —
    /// this walks each mode through the letters and asserts identical movement.
    #[test]
    fn mac_letter_aliases_mirror_navigation_keys() {
        let (mut app, path) = seeded_app();

        // Live: a/d switch device exactly like ←/→. (The live story ring is empty in
        // this harness — w/s are exercised against the replay window below.)
        app.handle_key(KeyCode::Char('d'));
        assert_eq!(app.selected, 1, "'d' switches device forward in live");
        app.handle_key(KeyCode::Char('a'));
        assert_eq!(app.selected, 0, "'a' switches device back in live");

        // Replay: a/d scrub 10s, A/D scrub a 5m page, g/G jump to the recorded ends —
        // all clamped to the recorded range exactly like the keys they alias — and
        // w/s walk the story feed like ↑/↓.
        app.handle_key(KeyCode::Char('r'));
        assert_eq!(app.cursor_ms, BASE + 20_000);
        app.handle_key(KeyCode::Char('s'));
        assert_eq!(
            app.story_selected,
            Some(0),
            "'s' selects down the story feed"
        );
        app.handle_key(KeyCode::Char('s'));
        assert_eq!(app.story_selected, Some(1), "'s' again steps deeper");
        app.handle_key(KeyCode::Char('w'));
        assert_eq!(app.story_selected, Some(0), "'w' selects back up");
        app.handle_key(KeyCode::Char('a'));
        assert_eq!(app.cursor_ms, BASE + 10_000, "'a' scrubs back 10s");
        app.handle_key(KeyCode::Char('d'));
        assert_eq!(app.cursor_ms, BASE + 20_000, "'d' scrubs forward 10s");
        app.handle_key(KeyCode::Char('A'));
        assert_eq!(
            app.cursor_ms, BASE,
            "'A' pages back, clamped at the earliest"
        );
        app.handle_key(KeyCode::Char('D'));
        assert_eq!(app.cursor_ms, BASE + 20_000, "'D' pages forward, clamped");
        app.handle_key(KeyCode::Char('g'));
        assert_eq!(app.cursor_ms, BASE, "'g' jumps to the earliest bucket");
        app.handle_key(KeyCode::Char('G'));
        assert_eq!(
            app.cursor_ms,
            BASE + 20_000,
            "'G' jumps to the newest bucket"
        );
        app.handle_key(KeyCode::End);
        assert_eq!(
            app.cursor_ms,
            BASE + 20_000,
            "End matches 'G' (new alias pair)"
        );

        // Timeline: a/d move the cursor one column, A/D a page of columns, g/G the
        // window edges.
        app.handle_key(KeyCode::Char('t'));
        app.timeline_cols = 100;
        app.handle_key(KeyCode::Char('g'));
        let from = app.timeline_cursor_ms;
        app.handle_key(KeyCode::Char('d'));
        assert!(app.timeline_cursor_ms > from, "'d' steps the cursor right");
        app.handle_key(KeyCode::Char('a'));
        assert_eq!(app.timeline_cursor_ms, from, "'a' steps it back");
        app.handle_key(KeyCode::Char('D'));
        let paged = app.timeline_cursor_ms;
        assert!(paged > from, "'D' pages the cursor right");
        app.handle_key(KeyCode::Char('A'));
        assert_eq!(app.timeline_cursor_ms, from, "'A' pages it back");
        app.handle_key(KeyCode::Char('G'));
        let to = app.timeline_cursor_ms;
        assert!(to > from, "'G' jumps to the window's newest edge");
        app.handle_key(KeyCode::Char('g'));
        assert_eq!(
            app.timeline_cursor_ms, from,
            "'g' jumps back to the oldest edge"
        );
        cleanup(&path);
    }

    /// README screenshot source (not a check): with `GPV_SHOTS_DIR` set, seeds the real
    /// 8h demo recording, renders the replay view (at the last throttle onset) and the
    /// timeline overview through the real `ui::render` into a 144×32 buffer, and writes
    /// every cell (symbol, fg, bg, modifiers) as JSON. `tools/make-screenshots.py` turns
    /// those into `docs/assets/{replay,timeline}.svg`. Run:
    /// `GPV_SHOTS_DIR=/tmp/shots cargo test -p gpuviewer-tui --bin gpuviewer -- --ignored screenshot_dump`
    #[test]
    #[ignore = "screenshot generator, run on demand"]
    fn screenshot_dump() {
        let Ok(dir) = std::env::var("GPV_SHOTS_DIR") else {
            eprintln!("GPV_SHOTS_DIR not set — nothing to do");
            return;
        };
        let dir = PathBuf::from(dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = scratch_path();
        let now = gpuviewer_core::now_ms();
        crate::seed_demo(&path, now - 8 * 3_600_000, now).unwrap();
        let anchor = SqliteStore::open_readonly(&path)
            .unwrap()
            .latest_event_ms(Some(EventKind::ThrottleStart))
            .unwrap();
        let collector = test_collector(Some(path.clone()));
        let mut app = App::new(collector);

        let dump = |app: &App, name: &str| {
            let mut terminal = Terminal::new(TestBackend::new(144, 32)).unwrap();
            {
                let sh = app.collector.shared.lock().unwrap();
                terminal.draw(|f| crate::ui::render(f, app, &sh)).unwrap();
            }
            let buf = terminal.backend().buffer().clone();
            let mut rows = Vec::new();
            for y in 0..buf.area.height {
                let mut row = Vec::new();
                for x in 0..buf.area.width {
                    let c = &buf[(x, y)];
                    row.push(serde_json::json!([
                        c.symbol(),
                        format!("{:?}", c.fg),
                        format!("{:?}", c.bg),
                        format!("{:?}", c.modifier),
                    ]));
                }
                rows.push(row);
            }
            std::fs::write(
                dir.join(format!("{name}.json")),
                serde_json::to_string(&rows).unwrap(),
            )
            .unwrap();
        };

        app.enter_replay(anchor);
        // Select the onset row so the feed shows the selection highlight, as a user
        // pressing Enter on it would see.
        let sel = app
            .replay_window()
            .and_then(|w| w.events.iter().position(|e| Some(e.ts_ms) == anchor));
        app.story_selected = sel;
        dump(&app, "replay");

        app.enter_timeline();
        // 1h rung (10s tier): narrow enough that the stalls and throttle episodes show as
        // real dips, instead of every column's peak reading ~99%. Cursor on the onset.
        while app.timeline_zoom > 0 {
            app.handle_key(KeyCode::Char('+'));
        }
        if let Some(a) = anchor {
            app.timeline_cursor_ms = a;
        }
        dump(&app, "timeline");
        cleanup(&path);
    }
}