mirador 1.22.0

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
//! Headlines: a window on the world, not a feed.
//!
//! This is the panel that came closest to the one this dashboard turned down.
//! Unread counts were rejected for being "a doomscroll hook" that "turns a calm
//! dashboard into a nagging one", and news is *the* doomscroll surface —
//! unbounded, constantly moving, and written by professionals to be clicked.
//!
//! So the commitment is the same shape as the watch log's, and it is
//! presentational:
//!
//! - **However many stories fit, and no more.** There is no scrolling and no
//!   "more below". You cannot work through it, because there is nothing to work
//!   through. `render` keeps only the stories whose whole block fits the body,
//!   so the selection cannot leave the viewport and `List` has nothing to
//!   scroll. This was documentation rather than behaviour until #118 — every
//!   story became an item and the panel scrolled through all twelve — and the
//!   tests at the foot of this file are what stop it drifting back.
//! - **No count anywhere.** Not in the frame, not in the body.
//! - **Nothing is new.** No unread state, no marker, no reordering to put fresh
//!   items on top beyond the newest-first order they already have.
//! - **Refreshed hourly**, which is slower than news moves and about as often
//!   as a person should want to know.
//!
//! You glance at it the way you glance at the weather glass. Break any of those
//! and this becomes the feature that was turned down.
//!
//! Headlines only, never the summary — see [`crate::feed`] for why.
//!
//! **No browser is launched that the reader did not name.** That is a narrowing
//! of what this note used to say, which was that no browser is launched at all,
//! "the same answer this project gave to playing a sound file". The analogy was
//! doing more work than it could carry: the sound decision was about a
//! *dependency chain* — `rodio` reaching `cpal` reaching `alsa-sys`, C headers
//! on every Linux builder — and spawning a process costs none of that. What
//! actually settled the sound question was `[pomodoro].chime_command`: mirador
//! does not pick the program, you name it. `[news].open_command` is that same
//! answer, and empty by default, so the shipped dashboard still launches
//! nothing.

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};

use jiff::Zoned;
use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{List, ListItem, ListState, Paragraph};

use crate::config::NewsConfig;
use crate::feed::Story;
use crate::frame::{Binding, FRAME_WIDTH};
use crate::keymap::{KeysConfig, Meta, PanelKeymap};
use crate::panel::{KeyOutcome, Panel, RenderContext, describe_age};

/// What the news panel's keys do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NewsAction {
    ShowLink,
    Copy,
    Open,
    Refresh,
    Up,
    Down,
}

/// Every key the panel responds to, under `[news.keys]`. The border hint, the
/// status bar and the help overlay are derived from it, so a key the panel
/// reads is a key it advertises.
pub const ACTIONS: &[Meta<NewsAction>] = &[
    Meta {
        action: NewsAction::ShowLink,
        name: "show_link",
        defaults: &[(KeyCode::Char('o'), KeyModifiers::NONE)],
        label: "show link",
        primary: true,
        joins: false,
        about: "show the selected story's link",
    },
    Meta {
        action: NewsAction::Copy,
        name: "copy",
        defaults: &[(KeyCode::Char('y'), KeyModifiers::NONE)],
        label: "copy",
        primary: true,
        joins: false,
        about: "copy the link to the clipboard",
    },
    Meta {
        action: NewsAction::Open,
        name: "open",
        defaults: &[(KeyCode::Enter, KeyModifiers::NONE)],
        label: "open",
        primary: true,
        joins: false,
        about: "open the link with [news].open_command",
    },
    Meta {
        action: NewsAction::Refresh,
        name: "refresh",
        defaults: &[(KeyCode::Char('r'), KeyModifiers::NONE)],
        label: "refresh",
        primary: true,
        joins: false,
        about: "fetch the feeds now",
    },
    Meta {
        action: NewsAction::Up,
        name: "up",
        defaults: &[
            (KeyCode::Up, KeyModifiers::NONE),
            (KeyCode::Char('k'), KeyModifiers::NONE),
        ],
        label: "select",
        primary: false,
        joins: false,
        about: "select the story above",
    },
    Meta {
        action: NewsAction::Down,
        name: "down",
        defaults: &[
            (KeyCode::Down, KeyModifiers::NONE),
            (KeyCode::Char('j'), KeyModifiers::NONE),
        ],
        label: "select",
        primary: false,
        joins: true,
        about: "select the story below",
    },
];

/// `[news.keys]` laid over [`ACTIONS`], or why it cannot be.
pub fn keymap(keys: &KeysConfig) -> Result<PanelKeymap<NewsAction>, String> {
    PanelKeymap::new("news", ACTIONS, keys)
}

/// The keys the panel starts with, until `build` hands it the config's
/// through [`Panel::set_keys`].
fn default_keys() -> PanelKeymap<NewsAction> {
    PanelKeymap::defaults("news", ACTIONS)
}

/// Interior width past which the panel gains nothing.
///
/// A headline runs about seventy cells at the median, measured across five real
/// feeds, so this is two comfortable lines plus room for the longest to breathe.
/// Past it the text just gets further from the eye.
const USEFUL_WIDTH: u16 = 62;

/// How long a request may take before it is given up on.
const HTTP_TIMEOUT: Duration = Duration::from_secs(20);

/// Cells taken by the list's highlight symbol, `▸ ` focused and two spaces
/// not, which `List` reserves in front of every line once a story is selected.
const HIGHLIGHT_WIDTH: u16 = 2;

/// What the fetch thread has produced.
#[derive(Debug, Default)]
struct State {
    stories: Vec<Story>,
    fetched: Option<Instant>,
    /// Why the last attempt failed. The stories are kept either way — an hour
    /// old headline is still news, where an empty panel is nothing.
    error: Option<String>,
}

pub struct NewsPanel {
    /// `[news.keys]` over the defaults.
    keys: PanelKeymap<NewsAction>,
    state: Arc<Mutex<State>>,
    refresh: Arc<AtomicBool>,
    stop: Arc<AtomicBool>,
    generation: Arc<AtomicU64>,
    seen: u64,
    selected: ListState,
    /// Set by `o`; the link of whatever is selected.
    showing_link: Option<String>,
    /// What `Enter` runs, with the link appended. Empty means nothing runs.
    open_command: Vec<String>,
    /// What `y` or `Enter` just did, shown in the footer until the next key.
    ///
    /// Separate from `failing`, which belongs to the fetch: a clipboard that
    /// went nowhere says nothing about whether the feeds are readable.
    action: Option<String>,
    /// Stories drawn last frame, for clamping the selection.
    drawn: usize,
    /// The stories as of the last time the fetch thread published.
    ///
    /// Cached rather than read through the mutex on every draw. Stories change
    /// once an hour and a draw happens about once a second, so cloning them per
    /// frame was sixty allocations for the same sixty headlines — the same
    /// mistake the agenda's alert made, found in the same review.
    shown: Vec<Story>,
    fetched: Option<Instant>,
    failing: Option<String>,
}

impl Drop for NewsPanel {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
    }
}

impl NewsPanel {
    /// A panel already holding `stories`, with no fetch thread behind it, for
    /// tests in other modules. `new` spawns the thread and its first act is to
    /// read every feed; this builds the same panel around a finished state, so
    /// mastheads, headlines and the age line render with nothing leaving the
    /// process.
    #[cfg(test)]
    pub(crate) fn offline(config: &NewsConfig, stories: Vec<Story>) -> Self {
        Self {
            keys: default_keys(),
            state: Arc::new(Mutex::new(State {
                stories: stories.clone(),
                fetched: Some(Instant::now()),
                error: None,
            })),
            refresh: Arc::new(AtomicBool::new(false)),
            stop: Arc::new(AtomicBool::new(false)),
            generation: Arc::new(AtomicU64::new(1)),
            seen: 1,
            selected: ListState::default(),
            showing_link: None,
            open_command: config.open_command.clone(),
            action: None,
            drawn: 0,
            shown: stories,
            fetched: Some(Instant::now()),
            failing: None,
        }
    }

    pub fn new(config: &NewsConfig) -> Self {
        let state = Arc::new(Mutex::new(State::default()));
        let refresh = Arc::new(AtomicBool::new(false));
        let stop = Arc::new(AtomicBool::new(false));
        let generation = Arc::new(AtomicU64::new(0));

        // An hour is the floor as well as the default. A dashboard left open
        // for a week should not be re-reading somebody's feed every minute
        // because a config said so. `Config::validate` stops it at a year;
        // the multiply saturates anyway, because the floor runs before it and
        // a wrapped product is the tight loop the floor exists to prevent.
        let interval = Duration::from_secs(config.refresh_minutes.max(60).saturating_mul(60));
        let feeds: Vec<(String, String)> = config
            .feeds
            .iter()
            .filter(|feed| !feed.url.trim().is_empty())
            .map(|feed| (feed.name.clone(), feed.url.clone()))
            .collect();
        let per_feed = config.per_feed.clamp(1, 20);
        let open_command = config.open_command.clone();

        let shared = (
            Arc::clone(&state),
            Arc::clone(&refresh),
            Arc::clone(&stop),
            Arc::clone(&generation),
        );
        std::thread::Builder::new()
            .name("mirador-news".into())
            .spawn(move || {
                let (state, refresh, stop, generation) = shared;
                fetch_loop(
                    &feeds,
                    per_feed,
                    interval,
                    &state,
                    &refresh,
                    &stop,
                    &generation,
                );
            })
            .expect("spawning the news thread");

        Self {
            keys: default_keys(),
            state,
            refresh,
            stop,
            generation,
            seen: 0,
            selected: ListState::default(),
            showing_link: None,
            open_command,
            action: None,
            drawn: 0,
            shown: Vec::new(),
            fetched: None,
            failing: None,
        }
    }

    /// Punch an OSC 8 link into each headline's cells, so a terminal that
    /// renders hyperlinks makes the headline itself clickable — and one that
    /// does not sees only the glyphs, because the sequences cost no columns.
    /// This runs after the `List` has drawn, so the link wraps whatever
    /// actually reached the screen, and the per-story id keeps a wrapped
    /// headline one logical link across its rows. `linkify` is the door every
    /// URL goes through: a link a feed laced with control bytes or an off-web
    /// scheme gets no sequence at all. The `List` shifts every line right by
    /// its two-cell highlight symbol once a selection exists, and the links
    /// have to follow.
    fn link_headlines(&self, frame: &mut Frame, body: Rect, headline_rows: &[(u16, u16, usize)]) {
        let indent = self.indent();
        let buf = frame.buffer_mut();
        for &(y, w, index) in headline_rows {
            if y >= body.y + body.height {
                continue;
            }
            let x0 = body.x + indent;
            let x1 = (x0 + w).min(body.x + body.width);
            crate::link::linkify(
                buf,
                y,
                x0,
                x1,
                &self.shown[index].link,
                &format!("news-{index}"),
            );
        }
    }

    /// How far `List` shifts every line right: the width of its highlight
    /// symbol once a selection exists, and nothing before.
    ///
    /// The headlines are wrapped to the width left after it, not to the panel.
    /// Wrapped to the panel, every row the wrap filled lost its last two cells
    /// to the terminal from the first `j` onwards, with no `…` to say so —
    /// `Krakatau` drawn as `Kraka` above a row that carried on as if nothing
    /// had gone missing.
    fn indent(&self) -> u16 {
        if self.selected.selected().is_some() {
            HIGHLIGHT_WIDTH
        } else {
            0
        }
    }

    /// The link of the story the cursor is on, or the top one when it has not
    /// been placed — the same rule `o` follows, so all three keys act on the
    /// same story.
    fn link_under_cursor(&mut self) -> Option<String> {
        let index = self.selected.selected().unwrap_or(0);
        let link = self
            .shown
            .get(index)
            .map(|story| story.link.clone())
            .filter(|link| !link.is_empty())?;
        self.selected.select(Some(index));
        Some(link)
    }

    /// Ask the terminal to put the link on the clipboard.
    fn copy_link(&mut self) {
        let Some(link) = self.link_under_cursor() else {
            return;
        };
        self.action = Some(match crate::clipboard::copy(&link) {
            // Deliberately not "copied". OSC 52 is write-only — the terminal
            // may ignore it, and many do by default — so mirador cannot know
            // whether the clipboard changed. What it can say is what it did.
            Ok(()) => "sent to the clipboard — paste to check".to_string(),
            Err(e) => format!("could not reach the terminal: {e}"),
        });
    }

    /// Run `[news].open_command` with the link appended.
    fn open_link(&mut self) {
        let Some(link) = self.link_under_cursor() else {
            return;
        };
        let Some((program, rest)) = self.open_command.split_first() else {
            // Not an error. Nothing is configured, which is the default and a
            // perfectly good state to be in; the reader just asked for
            // something that has not been switched on.
            self.action = Some("set [news].open_command to open links".to_string());
            return;
        };

        // Running the program directly is no protection when the program is
        // itself a shell, and the README's own Windows example used to be one.
        if let Some(shell) = shell_name(program) {
            self.action = Some(format!("not opened: {shell} is a shell"));
            return;
        }
        // Only a web address reaches the program, encoded to the same
        // characters an OSC 8 link is held to. A feed is somebody else's file,
        // and `open` and `xdg-open` hand a `file:`, `smb:` or app-specific
        // scheme to whatever is registered for it; a link starting with `-`
        // would be read as an option.
        let Some(link) = crate::link::openable(&link) else {
            self.action = Some("not opened: not a web link".to_string());
            return;
        };

        // Run directly, never through a shell, so nothing in a URL can be taken
        // as shell syntax — the same reasoning as `[pomodoro].chime_command`,
        // and the link goes on as one argument rather than being interpolated.
        match std::process::Command::new(program)
            .args(rest)
            .arg(&link)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
        {
            Ok(mut child) => {
                // Just "opened". The program is in the reader's own config, so
                // naming it here spends the footer on something they already
                // know — and a configured path can be long enough to wrap.
                // The failure case below does name it, which is when it matters.
                self.action = Some("opened".to_string());
                // Reaped on a thread that can take as long as it likes. A
                // browser outlives the keypress by a long way, and without this
                // the zombies pile up one per link.
                std::thread::spawn(move || {
                    let _ = child.wait();
                });
            }
            Err(e) => self.action = Some(format!("{program}: {e}")),
        }
    }

    fn snapshot(&self) -> State {
        let guard = self.state.lock().unwrap_or_else(PoisonError::into_inner);
        State {
            stories: guard.stories.clone(),
            fetched: guard.fetched,
            error: guard.error.clone(),
        }
    }
}

impl Panel for NewsPanel {
    fn title(&self) -> String {
        "News".into()
    }

    /// Deliberately `None`.
    ///
    /// Every other list panel here carries a count. This one must not: a number
    /// in the border is a badge, a badge accumulates, and an accumulating badge
    /// is the unread-message count this dashboard turned down. The age of the
    /// reading is not a count and would be defensible, but it belongs to the
    /// fetch rather than to the news, and the panel already says it below.
    fn counter(&self) -> Option<String> {
        None
    }

    fn bindings(&self) -> &[Binding] {
        self.keys.bindings()
    }

    fn set_keys(&mut self, config: &crate::config::Config) {
        self.keys = PanelKeymap::or_defaults("news", ACTIONS, &config.news.keys);
    }

    fn max_width(&self) -> Option<u16> {
        Some(USEFUL_WIDTH + FRAME_WIDTH)
    }

    fn refresh_interval(&self) -> Duration {
        // How often a completed fetch reaches the screen, not how often one is
        // made — the thread owns that, and it is an hour.
        Duration::from_secs(20)
    }

    fn tick(&mut self) -> bool {
        let now = self.generation.load(Ordering::Acquire);
        let moved = now != self.seen;
        self.seen = now;
        // The one moment the stories can have changed, so the one moment worth
        // copying them out from under the lock.
        if moved {
            let state = self.snapshot();
            self.shown = state.stories;
            self.fetched = state.fetched;
            self.failing = state.error;
        }
        moved
    }

    fn handle_key(&mut self, key: KeyEvent) -> KeyOutcome {
        // Nothing here dismisses, hides or marks a story. There is no state to
        // keep up with, which is the point.
        self.showing_link = None;
        self.action = None;
        let Some(action) = self.keys.action(key) else {
            return KeyOutcome::Ignored;
        };
        match action {
            NewsAction::Refresh => self.refresh.store(true, Ordering::Release),
            NewsAction::ShowLink => {
                // The top story when the cursor has not been placed. The
                // selection starts empty, so `o` used to do nothing at all on a
                // freshly focused panel — the border advertises `o show link`
                // unconditionally, and the key silently ignored the first press.
                // Found while measuring for #117, and it compounded the
                // complaint that issue was filed about: the link was both
                // unreachable at first press and camouflaged once reached.
                let index = self.selected.selected().unwrap_or(0);
                // Shown. Opening is `Enter`, and only when the reader has
                // named a program in `[news].open_command` — mirador still
                // launches nothing of its own choosing.
                self.showing_link = self
                    .shown
                    .get(index)
                    .map(|story| story.link.clone())
                    .filter(|link| !link.is_empty());
                // Mark the story the link came from. #114's point exactly: a
                // link belonging to no story the reader can identify is the
                // thing that made the footer confusing in the first place.
                if self.showing_link.is_some() {
                    self.selected.select(Some(index));
                }
            }
            NewsAction::Copy => self.copy_link(),
            NewsAction::Open => self.open_link(),
            NewsAction::Down => crate::selection::down(&mut self.selected, 1, self.drawn),
            NewsAction::Up => crate::selection::up(&mut self.selected, 1, self.drawn),
        }
        KeyOutcome::Consumed
    }

    fn handle_mouse(&mut self, event: MouseEvent, _area: Rect) -> KeyOutcome {
        match event.kind {
            MouseEventKind::ScrollDown => {
                crate::selection::down(&mut self.selected, 1, self.drawn);
            }
            MouseEventKind::ScrollUp => crate::selection::up(&mut self.selected, 1, self.drawn),
            _ => return KeyOutcome::Ignored,
        }
        KeyOutcome::Consumed
    }

    fn shutdown(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: RenderContext<'_>) {
        let theme = ctx.theme;
        if area.width == 0 || area.height == 0 {
            return;
        }

        let width = usize::from(area.width);

        // One row at the foot for the age or a failure — but a link gets as
        // many as it needs. It used to be truncated to one row, which left the
        // URL unreadable, uncopyable, and (worse) linkified by the terminal as
        // far as the ellipsis, so clicking it went somewhere that did not exist.
        // Bounded at half the panel so a long link cannot swallow the stories.
        let foot_rows = footer_rows(
            self.action.as_deref(),
            self.showing_link.as_deref(),
            area.width,
            area.height,
        );
        let footer = Rect {
            y: area.y + area.height.saturating_sub(foot_rows),
            height: foot_rows,
            ..area
        };
        let body = Rect {
            height: area.height.saturating_sub(foot_rows),
            ..area
        };

        if self.shown.is_empty() {
            let message = empty_message(
                self.failing.as_deref(),
                self.fetched.is_some(),
                width,
                theme,
            );
            frame.render_widget(Paragraph::new(message), body);
            self.drawn = 0;
            return;
        }

        let drawn_width = area.width.saturating_sub(self.indent());
        let blocks = fitted_blocks(
            story_blocks(&self.shown, drawn_width, theme),
            usize::from(body.height),
            drawn_width,
        );
        let keep = blocks.len();

        let mut items: Vec<ListItem> = Vec::with_capacity(keep);
        // `(row, width, story)` for every title row that will reach the
        // screen, recorded while the blocks are still lines: once they become
        // `ListItem`s their geometry is the widget's business, and the links
        // punched in after the draw need to know where each headline landed.
        let mut headline_rows: Vec<(u16, u16, usize)> = Vec::new();
        let mut row = body.y;
        for (index, mut lines) in blocks.into_iter().enumerate() {
            // Every line after the masthead is a wrapped title row.
            for (offset, line) in lines.iter().enumerate().skip(1) {
                headline_rows.push((row + offset as u16, line.width() as u16, index));
            }
            // The gap goes *between* stories, not after every one. A trailing
            // blank on the last item costs a whole row, and `List` draws only
            // items that fit entirely — so that row was routinely the
            // difference between two stories and three.
            if index + 1 != keep {
                lines.push(Line::from(""));
            }
            row += lines.len() as u16;
            items.push(ListItem::new(lines));
        }

        self.drawn = items.len();
        // The cursor `o` acts on has to be visible, or the link in the footer
        // belongs to no story the reader can identify. Same marker and weight as
        // `todo`, `notes` and `stocks`, and it recedes with focus like they do.
        //
        // This is navigation, not unread state: it shows where the keyboard is
        // pointing and goes away with the focus. The panel still carries no
        // count and nothing to dismiss, which is what keeps it clear of the
        // unread-badge feature this dashboard turned down.
        //
        // Note these rows are multi-line — a masthead plus a wrapped title —
        // unlike the one-line rows the other three panels draw. `List` puts the
        // symbol on a row's first line and indents the rest to match, which is
        // what makes a wrapped title still line up under its own masthead.
        frame.render_stateful_widget(
            List::new(items)
                .highlight_symbol(if ctx.focused { "▸ " } else { "  " })
                .highlight_style(if ctx.focused {
                    Style::default().add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(theme.muted)
                }),
            body,
            &mut self.selected,
        );

        self.link_headlines(frame, body, &headline_rows);

        // A `(text, style)` pair rather than a `Span`, because the link case is
        // multi-line and a `Span` holding newlines renders as one line with the
        // breaks swallowed. `Paragraph::new(String)` splits on them properly.
        // What a key just did outranks everything: it is the answer to a
        // question the reader asked a moment ago, and it is gone on the next
        // keypress. The link, the fetch failure and the age are all standing
        // state that will still be there afterwards.
        if let Some(action) = &self.action
            && footer.height > 0
        {
            frame.render_widget(
                Paragraph::new(crate::grid::wrapped(action, area.width))
                    .style(Style::default().fg(theme.accent)),
                footer,
            );
            return;
        }

        let (foot, foot_style) = match (&self.showing_link, &self.failing) {
            // Wrapped by `grid`, never handed to ratatui's wrapper, and never
            // truncated: the whole point is that the reader can read and copy
            // the entire URL.
            // Brass, not `theme.label`. Verdigris is the masthead colour — every
            // `NASA` and `ARS TECHNICA` above wears it — so a link in it was
            // camouflaged by repetition and appeared without drawing the eye.
            // The owner missed it, which is what #117 was filed about. Brass is
            // the dashboard's attention colour and is used nowhere else in this
            // panel, so it cannot be mistaken for anything already there.
            (Some(link), _) => (
                link_lines(link, area.width).join("\n"),
                Style::default().fg(theme.accent),
            ),
            (None, Some(_)) => (
                format!(
                    "{} — refresh failing",
                    self.fetched
                        .map_or_else(|| "never read".to_string(), |at| describe_age(at.elapsed()))
                ),
                Style::default().fg(theme.warning),
            ),
            (None, None) => (
                self.fetched
                    .map_or_else(String::new, |at| describe_age(at.elapsed())),
                Style::default().fg(theme.muted),
            ),
        };
        if footer.height > 0 {
            frame.render_widget(Paragraph::new(foot).style(foot_style), footer);
        }
    }
}

/// What the panel says when it has no stories.
///
/// Three different states, and telling them apart is the point: a failing fetch
/// is a problem, "no stories" is a quiet day, and "reading" is neither. One
/// message for all three would leave a reader unable to tell a broken feed from
/// an empty one.
fn empty_message(
    failing: Option<&str>,
    has_read: bool,
    width: usize,
    theme: &crate::theme::Theme,
) -> Vec<Line<'static>> {
    match failing {
        Some(why) => vec![
            Line::from(Span::styled(
                "Cannot read the feeds",
                Style::default()
                    .fg(theme.error)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                crate::grid::truncate(why, width),
                Style::default().fg(theme.muted),
            )),
        ],
        None if has_read => vec![Line::from(Span::styled(
            "No stories.",
            Style::default().fg(theme.muted),
        ))],
        None => vec![Line::from(Span::styled(
            "Reading…",
            Style::default().fg(theme.muted),
        ))],
    }
}

/// The command interpreter `program` names, if it names one.
///
/// `cmd` and PowerShell read their arguments as a command line, so a link
/// handed to them is code: `&`, `;`, `|`, `%VAR%` and `$(…)` are all legal in
/// a URL, and Rust quotes a Windows argument only when it holds a space or a
/// tab. Matched on the file name — either separator, `.exe` or not, any case,
/// and without the trailing dots and spaces Windows ignores. `sh -c` is not on
/// the list, because a link appended after its script becomes `$0` rather
/// than part of the script. A wrapper that hands its arguments on to a shell
/// is not caught; this is a net for the example the README used to give, not
/// a sandbox around a program the reader chose.
fn shell_name(program: &str) -> Option<&str> {
    let name = program.rsplit(['/', '\\']).next().unwrap_or(program);
    let name = name.trim_end_matches(['.', ' ']);
    let stem = match name
        .len()
        .checked_sub(4)
        .and_then(|at| Some((at, name.get(at..)?)))
    {
        Some((at, ext)) if ext.eq_ignore_ascii_case(".exe") => &name[..at],
        _ => name,
    };
    ["cmd", "powershell", "pwsh"]
        .iter()
        .any(|shell| stem.eq_ignore_ascii_case(shell))
        .then_some(stem)
}

/// How many rows the footer needs.
///
/// Each case is measured by the same rule that draws it. A wrapped message sized
/// as a single row loses its tail, which is the bug #108 fixed for the link and
/// which was waiting to be reintroduced beside it the moment a second kind of
/// footer text existed.
///
/// Bounded at half the panel either way, so nothing in the footer can swallow
/// the stories.
fn footer_rows(action: Option<&str>, link: Option<&str>, width: u16, height: u16) -> u16 {
    let cap = (height / 2).max(1);
    match (action, link) {
        (Some(action), _) => crate::grid::wrapped_height(action, width).clamp(1, cap),
        (None, Some(link)) => u16::try_from(link_lines(link, width).len())
            .unwrap_or(u16::MAX)
            .clamp(1, cap),
        (None, None) => 1.min(height),
    }
}

/// The link as the footer draws it: `↳` on the first row, aligned under it after
/// that.
///
/// `↳` (U+21B3) rather than a link emoji, and the reason is invariant 10: several
/// obvious emoji report width 1 to `unicode-width` and draw two cells, which
/// silently shifts everything after them. This one measures 1 and draws 1, and it
/// says "belongs to the thing above", which is the relationship being shown.
///
/// The height of the footer is taken from this same function rather than
/// measured separately. Wrapping and measuring drifted apart once already, in
/// `grid` — the height counted an over-long word by subtracting the width a row
/// at a time, which is only right when every glyph is one cell — and a footer
/// sized by one rule and drawn by another would clip the end off a link. One
/// function, two callers, agreement by construction.
fn link_lines(link: &str, width: u16) -> Vec<String> {
    const MARK: &str = "↳ ";
    let indent = " ".repeat(crate::grid::display_width(MARK));
    let avail = usize::from(width).saturating_sub(indent.len()).max(1);
    crate::grid::wrap(link, avail)
        .into_iter()
        .enumerate()
        .map(|(row, line)| {
            if row == 0 {
                format!("{MARK}{line}")
            } else {
                format!("{indent}{line}")
            }
        })
        .collect()
}

/// One block of lines per story: its source and age, then the wrapped headline.
///
/// The blank line that separates stories is *not* here — it belongs between
/// blocks rather than to any one of them, and [`how_many_fit`] has to count it
/// that way. Air rather than rules: a separator between every story would be
/// more furniture than content at this width, and the panel is meant to read
/// like a page.
///
/// `width` is the width the lines will be *drawn* at — the panel's, less the
/// highlight symbol's once a story is selected — so the wrap and
/// [`how_many_fit`] both measure what the screen will hold. The masthead's age
/// is dropped whole when it does not fit beside the name, and a name too long
/// on its own is cut with `…`, never by the terminal.
fn story_blocks(
    stories: &[Story],
    width: u16,
    theme: &crate::theme::Theme,
) -> Vec<Vec<Line<'static>>> {
    stories
        .iter()
        .map(|story| {
            let parts = masthead(story, theme)
                .into_iter()
                .map(|span| vec![span])
                .collect();
            let mut lines = vec![crate::grid::assemble(parts, width)];
            for line in crate::grid::wrap(&story.title, usize::from(width)) {
                lines.push(Line::from(Span::styled(
                    line,
                    Style::default().fg(theme.text),
                )));
            }
            lines
        })
        .collect()
}

/// The blocks that reach the screen: as many as fit whole in `budget` rows, or
/// the first one clipped to them when not even that does.
///
/// A headline too tall for the panel would otherwise leave it blank with
/// stories loaded, which reads as broken rather than as short. `List` draws
/// only items that fit entirely, so the clipping has to happen here — and the
/// last row kept ends in `…`, because rows that fill the body look finished
/// either way.
fn fitted_blocks(
    mut blocks: Vec<Vec<Line<'static>>>,
    budget: usize,
    width: u16,
) -> Vec<Vec<Line<'static>>> {
    let keep = how_many_fit(&blocks, budget);
    if keep > 0 || budget == 0 {
        blocks.truncate(keep);
        return blocks;
    }
    blocks.truncate(1);
    if let Some(first) = blocks.first_mut() {
        first.truncate(budget);
        if let Some(last) = first.pop() {
            first.push(ends_in_ellipsis(last, width));
        }
    }
    blocks
}

/// `line` with `…` after its last visible character, abridged to `width` if
/// that does not fit.
///
/// For the last row of a story clipped to the panel's height: the rows below
/// it are never drawn, so nothing at any width shows them missing, and a row
/// that happens to end at a word reads as the end of the headline. Through
/// [`crate::grid::assemble`] as one part, so the styles survive and the `…`
/// lands wherever the cut falls. When only the masthead fits, the masthead is
/// the row that says the headline is missing.
fn ends_in_ellipsis(line: Line<'static>, width: u16) -> Line<'static> {
    let mut spans = line.spans;
    if let Some(last) = spans.last_mut() {
        last.content = last.content.trim_end().to_string().into();
    }
    let style = spans.last().map(|span| span.style).unwrap_or_default();
    spans.push(Span::styled("\u{2026}", style));
    crate::grid::assemble(vec![spans], width)
}

/// How many of `blocks` fit whole in `budget` rows.
///
/// **This is where "however many stories fit, and no more" is enforced**, and
/// for a long time nothing was: every story became a `ListItem`, so `List`
/// scrolled the moment the selection left the viewport. Twelve stories with
/// three visible made nine of them reachable only by scrolling, which is a feed
/// you work through — the thing this panel exists to not be. Filed as #118 after
/// being found by driving the panel rather than by reading it.
///
/// Bounding the *list* rather than clamping the selection afterwards is the
/// point. The cursor is limited to what was built, so it cannot walk off the
/// screen and `List` is never given anything to scroll. One rule, one place.
///
/// A story after the first is preceded by a blank line, so `n` stories cost
/// their own rows plus `n - 1` separators.
///
/// This stays a floor rather than a ceiling, per the config rule: a taller panel
/// shows more, up to whatever the feeds provided.
fn how_many_fit(blocks: &[Vec<Line<'static>>], budget: usize) -> usize {
    let mut used = 0usize;
    let mut keep = 0usize;
    for block in blocks {
        let cost = block.len() + usize::from(keep > 0);
        if used + cost > budget {
            break;
        }
        used += cost;
        keep += 1;
    }
    keep
}

/// `NASA · 2h`, in the engraved-label face.
fn masthead(story: &Story, theme: &crate::theme::Theme) -> Vec<Span<'static>> {
    let mut spans = vec![Span::styled(
        crate::glyphs::utility(&story.source),
        Style::default()
            .fg(theme.label)
            .add_modifier(Modifier::BOLD),
    )];
    if let Some(at) = &story.published {
        let age = Zoned::now().duration_since(at);
        if let Ok(age) = std::time::Duration::try_from(age) {
            spans.push(Span::styled(
                format!(" · {}", describe_age(age)),
                Style::default().fg(theme.muted),
            ));
        }
    }
    spans
}

/// Read every feed, newest first, then wait.
fn fetch_loop(
    feeds: &[(String, String)],
    per_feed: usize,
    interval: Duration,
    state: &Arc<Mutex<State>>,
    refresh: &AtomicBool,
    stop: &AtomicBool,
    generation: &Arc<AtomicU64>,
) {
    while !stop.load(Ordering::Relaxed) {
        let mut stories = Vec::new();
        let mut failures = Vec::new();

        for (name, url) in feeds {
            if stop.load(Ordering::Relaxed) {
                return;
            }
            take_feed(name, read_feed(url), per_feed, &mut stories, &mut failures);
        }

        let stories = interleave(stories);

        // A total failure keeps what is on screen; a partial one takes what
        // arrived. Either way the age below says how fresh it is.
        //
        // And a pass that found nothing with nothing failing — no feeds to
        // read, or every one read and empty — is a quiet day, and is recorded
        // as a reading like any other. It used to be recorded only when it
        // found a story, so `No stories.` could never be drawn and such a
        // panel said `Reading…` for as long as it ran.
        let replace = !stories.is_empty() || failures.is_empty();
        let failed = (!failures.is_empty()).then(|| failures.join("; "));
        let mut guard = state.lock().unwrap_or_else(PoisonError::into_inner);
        if replace {
            guard.stories = stories;
            guard.fetched = Some(Instant::now());
        }
        guard.error = failed;
        drop(guard);
        generation.fetch_add(1, Ordering::Release);

        let woke = crate::poll::wait(interval, stop, || refresh.swap(false, Ordering::AcqRel));
        if woke == crate::poll::Wake::Stop {
            return;
        }
    }
}

/// Add one feed's answer to the pass: its stories, named for the panel, and
/// its failure, named for the footer.
///
/// A feed read up to a fault gives both. The stories before the fault are
/// shown, where they used to be thrown away with the rest of the document,
/// and the feed is still reported, because it is still broken.
fn take_feed(
    name: &str,
    result: anyhow::Result<crate::feed::Feed>,
    per_feed: usize,
    stories: &mut Vec<Story>,
    failures: &mut Vec<String>,
) {
    let feed = match result {
        Ok(feed) => feed,
        Err(e) => {
            failures.push(format!("{name}: {e:#}"));
            return;
        }
    };
    if let Some(fault) = feed.fault {
        failures.push(format!("{name}: {fault}"));
    }
    for mut story in feed.stories.into_iter().take(per_feed) {
        // Bounded for the same reason the feed's own fields are: `masthead`
        // uppercases this on every frame, so an over-long name — this one
        // comes from the config rather than from the feed, but still — would
        // be re-allocated sixty times a minute.
        story.source = crate::feed::clip(name, crate::feed::MAX_SOURCE).to_string();
        stories.push(story);
    }
}

/// One story from each feed, then the next from each, and so on.
///
/// Not simply newest-first, which is what this did at first and which is wrong
/// for what the panel is. The feeds publish at wildly different rates, so date
/// order hands the whole visible window to whichever one happens to be chatty
/// — the first run showed three consecutive Phys.org space stories, which is
/// not a window on the world however fresh it is.
///
/// Round-robin guarantees that the first thing you see is the newest from each
/// feed, which is the shape "a handful of stories, however many fit" was meant
/// to have. Within a feed the order is still newest first.
fn interleave(stories: Vec<Story>) -> Vec<Story> {
    let mut by_source: Vec<Vec<Story>> = Vec::new();
    for story in stories {
        match by_source
            .iter_mut()
            .find(|group| group.first().is_some_and(|s| s.source == story.source))
        {
            Some(group) => group.push(story),
            None => by_source.push(vec![story]),
        }
    }

    // Newest first inside each feed. An undated story goes last rather than
    // first — an absent date is not "just now".
    for group in &mut by_source {
        group.sort_by(|a, b| match (&b.published, &a.published) {
            (Some(later), Some(earlier)) => later.cmp(earlier),
            (Some(_), None) => std::cmp::Ordering::Greater,
            (None, Some(_)) => std::cmp::Ordering::Less,
            (None, None) => std::cmp::Ordering::Equal,
        });
    }

    let deepest = by_source.iter().map(Vec::len).max().unwrap_or(0);
    let mut out = Vec::new();
    for rank in 0..deepest {
        for group in &by_source {
            if let Some(story) = group.get(rank) {
                out.push(story.clone());
            }
        }
    }
    out
}

/// Fetch and parse one feed.
fn read_feed(url: &str) -> anyhow::Result<crate::feed::Feed> {
    let body = crate::fetch::get(url, HTTP_TIMEOUT, None)?;
    crate::feed::parse(&body)
}

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

    /// Every key in the map works and is advertised; see
    /// [`crate::keymap::assert_every_key_works`].
    #[test]
    fn every_key_in_the_map_works_and_is_advertised() {
        crate::keymap::assert_every_key_works(&default_keys(), |event| {
            NewsPanel::offline(&NewsConfig::default(), Vec::new()).handle_key(event)
        });
    }

    /// `r` sets a flag the fetch thread's hour-long wait reads once a slice,
    /// and the read has to *take* it: a wait that never looks leaves the key
    /// dead for an hour, and one that looks without clearing re-reads every
    /// feed four times a second from then on. With no feeds the pass reads
    /// nothing, so this runs the real loop without leaving the process.
    #[test]
    fn a_refresh_asked_for_ends_the_wait_and_is_taken() {
        let state = Arc::new(Mutex::new(State::default()));
        let refresh = Arc::new(AtomicBool::new(true));
        let stop = Arc::new(AtomicBool::new(false));
        let generation = Arc::new(AtomicU64::new(0));
        let thread = {
            let (state, refresh, stop, generation) = (
                Arc::clone(&state),
                Arc::clone(&refresh),
                Arc::clone(&stop),
                Arc::clone(&generation),
            );
            std::thread::spawn(move || {
                let hour = Duration::from_hours(1);
                fetch_loop(&[], 1, hour, &state, &refresh, &stop, &generation);
            })
        };

        let deadline = Instant::now() + Duration::from_secs(5);
        while generation.load(Ordering::Acquire) < 2 && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        stop.store(true, Ordering::Relaxed);
        thread.join().expect("the fetch thread");

        assert!(
            generation.load(Ordering::Acquire) >= 2,
            "the refresh did not end the wait"
        );
        assert!(
            !refresh.load(Ordering::Acquire),
            "and the request was taken"
        );
    }

    /// #114: the panel kept a cursor that `j`/`k` moved and `o` acted on, and
    /// drew no highlight at all — so the link in the footer belonged to a story
    /// the reader could not identify. Every other list panel shows one.
    #[test]
    fn the_selected_story_is_visibly_marked() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();

        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        panel.shown = vec![
            story("NASA", "First story, the one selected", 10),
            story("PHYS.ORG", "Second story", 20),
        ];
        panel.selected.select(Some(1));

        let draw = |panel: &mut NewsPanel, focused: bool| -> String {
            let mut terminal = Terminal::new(TestBackend::new(46, 12)).unwrap();
            terminal
                .draw(|frame| {
                    panel.render(
                        frame,
                        frame.area(),
                        RenderContext {
                            theme: &config.theme,
                            gradients: &gradients,
                            focused,
                            watch: &crate::watch::WatchLog::default(),
                        },
                    );
                })
                .unwrap();
            let buffer = terminal.backend().buffer().clone();
            (0..12)
                .map(|y| {
                    (0..46)
                        .filter_map(|x| {
                            buffer
                                .cell((x, y))
                                .map(|c| crate::link::without_links(c.symbol()))
                        })
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join("\n")
        };

        let focused = draw(&mut panel, true);
        assert!(
            focused.contains('\u{25B8}'),
            "the focused panel must mark which story the cursor is on:\n{focused}"
        );

        // And it recedes with focus, like the other panels' markers do, rather
        // than leaving a stale pointer on an unfocused panel.
        let unfocused = draw(&mut panel, false);
        assert!(
            !unfocused.contains('\u{25B8}'),
            "an unfocused panel should not keep pointing:\n{unfocused}"
        );
    }

    /// #108: `o` truncated the URL to the panel width, so the reader could
    /// neither read nor copy it — and the terminal linkified the visible text,
    /// which now ended in an ellipsis, so clicking landed on a URL that did not
    /// exist. The reporter's browser showed the `…` as `%E2%80%A6`.
    ///
    /// The property: **every character of the link reaches the screen.**
    #[test]
    fn the_whole_link_is_shown_rather_than_truncated() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        use ratatui::crossterm::event::KeyModifiers;

        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();
        let link = "https://arstechnica.com/security/2026/07/mythos-attack-on-3rd-round-pqc-algorithm-puts-it-out-of-commission/";

        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        panel.shown = vec![Story {
            source: "Ars Technica".into(),
            title: "Mythos attack on 3rd-round PQC algorithm".into(),
            link: link.into(),
            published: Zoned::now().checked_sub(jiff::Span::new().minutes(30)).ok(),
        }];
        panel.selected.select(Some(0));
        panel.handle_key(KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE));

        for (width, height) in [(40u16, 14u16), (56, 18), (72, 12), (100, 20)] {
            let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
            terminal
                .draw(|frame| {
                    panel.render(
                        frame,
                        frame.area(),
                        RenderContext {
                            theme: &config.theme,
                            gradients: &gradients,
                            focused: true,
                            watch: &crate::watch::WatchLog::default(),
                        },
                    );
                })
                .unwrap();
            let buffer = terminal.backend().buffer().clone();
            let screen: String = (0..height)
                .flat_map(|y| (0..width).map(move |x| (x, y)))
                .filter_map(|(x, y)| {
                    buffer
                        .cell((x, y))
                        .map(|c| crate::link::without_links(c.symbol()))
                })
                .collect();
            let squashed: String = screen.chars().filter(|c| !c.is_whitespace()).collect();

            assert!(
                !squashed.contains('\u{2026}'),
                "the link was truncated with an ellipsis at {width}x{height}"
            );
            assert!(
                squashed.contains(&link.replace(' ', "")),
                "the whole link should be on screen at {width}x{height}"
            );
        }
    }

    fn story(source: &str, title: &str, minutes_ago: i64) -> Story {
        Story {
            source: source.into(),
            title: title.into(),
            link: String::new(),
            published: Zoned::now()
                .checked_sub(jiff::Span::new().minutes(minutes_ago))
                .ok(),
        }
    }

    /// Renders `panel` at the given size and hands back the raw buffer, links
    /// and all — the tests below are about the escape sequences themselves,
    /// which `without_links` would hide.
    fn raw_buffer(panel: &mut NewsPanel, width: u16, height: u16) -> ratatui::buffer::Buffer {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| {
                panel.render(
                    frame,
                    frame.area(),
                    RenderContext {
                        theme: &config.theme,
                        gradients: &gradients,
                        focused: true,
                        watch: &crate::watch::WatchLog::default(),
                    },
                );
            })
            .unwrap();
        terminal.backend().buffer().clone()
    }

    /// The row whose visible text contains `needle`.
    fn row_containing(buffer: &ratatui::buffer::Buffer, needle: &str) -> u16 {
        let area = buffer.area;
        (0..area.height)
            .find(|y| {
                let text: String = (0..area.width)
                    .filter_map(|x| {
                        buffer
                            .cell((x, *y))
                            .map(|c| crate::link::without_links(c.symbol()))
                    })
                    .collect();
                text.contains(needle)
            })
            .unwrap_or_else(|| panic!("no row shows {needle:?}"))
    }

    /// The headline itself is now the link: every glyph cell of a title row
    /// carries a self-contained OSC 8 sequence naming the story's URL, and
    /// the masthead above it carries none. What the reader *sees* does not
    /// change — the sequences cost no cells — which is what keeps this on the
    /// right side of the calm-panel commitments.
    #[test]
    fn a_headline_is_a_link_to_its_story() {
        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        panel.shown = vec![
            Story {
                link: "https://example.test/one".into(),
                ..story("NASA", "Orbit story", 5)
            },
            Story {
                link: "https://example.test/two".into(),
                ..story("BBC", "Second story", 10)
            },
        ];
        let buffer = raw_buffer(&mut panel, 46, 12);

        let title_row = row_containing(&buffer, "Orbit story");
        let first = buffer.cell((0, title_row)).unwrap();
        assert!(
            first
                .symbol()
                .starts_with("\x1b]8;id=news-0;https://example.test/one\x1b\\"),
            "the first title cell must open its story's link, got {:?}",
            first.symbol()
        );
        assert!(
            first.symbol().ends_with("\x1b]8;;\x1b\\"),
            "every linked cell closes its own sequence — OSC 8 is modal, and \
             a cell that leaves it open leaks the link onto whatever the diff \
             prints next"
        );

        let masthead_row = row_containing(&buffer, "NASA");
        let masthead: String = (0..46)
            .filter_map(|x| {
                buffer
                    .cell((x, masthead_row))
                    .map(|c| c.symbol().to_string())
            })
            .collect();
        assert!(
            !masthead.contains('\x1b'),
            "the masthead is not part of the link"
        );

        let second_row = row_containing(&buffer, "Second story");
        assert!(
            buffer
                .cell((0, second_row))
                .unwrap()
                .symbol()
                .contains("id=news-1;https://example.test/two"),
            "each story links to its own URL under its own id"
        );
    }

    /// A headline that wraps is one logical link: every row repeats the same
    /// id and URL, which is what tells the terminal the rows belong together.
    #[test]
    fn a_wrapped_headline_is_one_logical_link_across_its_rows() {
        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        panel.shown = vec![Story {
            link: "https://example.test/long".into(),
            ..story(
                "NASA",
                "A headline comfortably long enough to wrap onto a second row",
                5,
            )
        }];
        let buffer = raw_buffer(&mut panel, 30, 12);

        let first_row = row_containing(&buffer, "A headline");
        let mut linked_rows = 0;
        for y in first_row..buffer.area.height {
            let symbol = buffer.cell((0, y)).unwrap().symbol().to_string();
            if symbol.contains("]8;") {
                assert!(
                    symbol.contains("id=news-0;https://example.test/long"),
                    "row {y} of the wrapped headline must carry the same id \
                     and URL as the first, got {symbol:?}"
                );
                linked_rows += 1;
            }
        }
        assert!(
            linked_rows >= 2,
            "the title was meant to wrap; only {linked_rows} linked row(s) \
             found — widen the fixture if wrapping changed"
        );
    }

    /// A feed is the one input somebody else writes, and its link rides
    /// *inside* an escape sequence — so a URL carrying control bytes (an
    /// `&#27;` entity is all it takes) or an off-web scheme gets no sequence
    /// at all. The headline still renders; only the shortcut is withheld.
    #[test]
    fn a_hostile_link_never_reaches_the_terminal() {
        for link in [
            "https://example.test/\x1b]8;;https://evil.test\x1b\\",
            "https://example.test/\x07",
            "file:///etc/passwd",
        ] {
            let mut panel = NewsPanel::new(&NewsConfig {
                feeds: Vec::new(),
                ..NewsConfig::default()
            });
            panel.shown = vec![Story {
                link: link.into(),
                ..story("NASA", "An ordinary headline", 5)
            }];
            let buffer = raw_buffer(&mut panel, 46, 12);

            let title_row = row_containing(&buffer, "An ordinary headline");
            for x in 0..46 {
                let symbol = buffer.cell((x, title_row)).unwrap().symbol().to_string();
                assert!(
                    !symbol.contains('\x1b'),
                    "link {link:?} must not reach the terminal; cell {x} \
                     holds {symbol:?}"
                );
            }
        }
    }

    /// The first version sorted purely by date and handed the whole visible
    /// window to whichever feed published most often — three consecutive
    /// Phys.org stories on the first real run. However fresh that is, it is not
    /// a window on the world.
    #[test]
    fn the_top_of_the_panel_holds_one_story_from_each_feed() {
        let mixed = interleave(vec![
            story("PHYS", "phys newest", 5),
            story("PHYS", "phys second", 10),
            story("PHYS", "phys third", 15),
            story("NASA", "nasa newest", 60),
            story("ARS", "ars newest", 90),
        ]);

        let first_three: Vec<&str> = mixed.iter().take(3).map(|s| s.source.as_str()).collect();
        assert_eq!(first_three, ["PHYS", "NASA", "ARS"], "one from each first");
        assert_eq!(
            mixed[0].title, "phys newest",
            "and the newest within a feed"
        );
        assert_eq!(mixed[3].title, "phys second", "then the second round");
    }

    /// Within a feed the order is still newest first, and a story with no date
    /// sorts last rather than being taken for the freshest thing there is.
    #[test]
    fn an_undated_story_goes_last_within_its_feed() {
        let undated = Story {
            source: "PHYS".into(),
            title: "undated".into(),
            link: String::new(),
            published: None,
        };
        let ordered = interleave(vec![
            undated,
            story("PHYS", "older", 90),
            story("PHYS", "newer", 5),
        ]);
        let titles: Vec<&str> = ordered.iter().map(|s| s.title.as_str()).collect();
        assert_eq!(titles, ["newer", "older", "undated"]);
    }

    /// The fitting rule on its own, without a terminal in the way.
    ///
    /// `n` stories cost their own rows plus `n - 1` blank separators, so the
    /// arithmetic is worth pinning directly — a test that only goes through
    /// `render` cannot say whether an off-by-one is in the counting or the
    /// drawing.
    #[test]
    fn the_fitting_rule_counts_the_separators_between_stories() {
        let block = |rows: usize| vec![Line::from(""); rows];
        let three = vec![block(2), block(2), block(2)];

        assert_eq!(how_many_fit(&three, 2), 1, "one story, no separator");
        assert_eq!(
            how_many_fit(&three, 4),
            1,
            "two need a separator: 2+1+2 = 5"
        );
        assert_eq!(how_many_fit(&three, 5), 2, "exactly two");
        assert_eq!(how_many_fit(&three, 7), 2, "three need 2+1+2+1+2 = 8");
        assert_eq!(how_many_fit(&three, 8), 3, "exactly three");
        assert_eq!(how_many_fit(&three, 99), 3, "never more than there are");

        assert_eq!(how_many_fit(&three, 0), 0, "no room, no stories");
        assert_eq!(how_many_fit(&three, 1), 0, "not even one block fits");
        assert_eq!(how_many_fit(&[], 10), 0, "nothing to fit");
    }

    /// #117: the link was styled `theme.label` — the same verdigris every
    /// masthead wears — so it was camouflaged by repetition and appeared without
    /// drawing the eye. The owner missed it entirely.
    ///
    /// Brass is the dashboard's attention colour and is used nowhere else in
    /// this panel.
    ///
    /// **Read off the rendered cells**, not from the theme. The first version of
    /// this test compared `theme.accent` against the masthead's colour and never
    /// looked at what the panel drew — so it passed with the old `theme.label`
    /// pasted back in. A test whose assertion is about a fact the bug does not
    /// change is the pattern this repo keeps finding; caught here by reverting
    /// the colour and watching it stay green.
    #[test]
    fn the_link_is_not_the_colour_every_masthead_already_wears() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let config = crate::config::Config::default();
        let gradients = config.theme.gradients();
        let mut panel = loaded_panel();
        panel.handle_key(KeyEvent::from(KeyCode::Char('o')));

        let (w, h) = (46u16, 10u16);
        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal
            .draw(|frame| {
                panel.render(
                    frame,
                    frame.area(),
                    RenderContext {
                        theme: &config.theme,
                        gradients: &gradients,
                        focused: true,
                        watch: &crate::watch::WatchLog::default(),
                    },
                );
            })
            .unwrap();
        let buffer = terminal.backend().buffer().clone();

        // The row carrying the mark is the link's; the mastheads are above it.
        let link_row = (0..h)
            .find(|y| (0..w).any(|x| buffer.cell((x, *y)).is_some_and(|c| c.symbol() == "↳")))
            .expect("the link should be on screen, marked with ↳");
        let link_colour = buffer
            .cell((1, link_row))
            .and_then(|c| c.style().fg)
            .expect("the link is coloured");

        let masthead_colour = masthead(&panel.shown[0], &config.theme)
            .first()
            .and_then(|span| span.style.fg)
            .expect("the masthead is coloured");

        assert_ne!(
            link_colour, masthead_colour,
            "the link is drawn in the masthead's own colour, so it reads as more \
             furniture — which is what #117 was filed about"
        );
        assert_eq!(
            link_colour, config.theme.accent,
            "and it should be brass, the dashboard's attention colour"
        );
    }

    /// The mark is `↳`, and it has to measure what it draws — invariant 10. A
    /// glyph reporting width 1 and drawing 2 shifts everything after it.
    #[test]
    fn the_link_mark_is_one_cell_wide() {
        assert_eq!(crate::grid::display_width("↳"), 1);
    }

    /// The footer's height is taken from the same function that draws it.
    /// Measuring separately is how `grid`'s wrap and height drifted apart, and
    /// here it would clip the tail off a link — the exact bug #108 fixed.
    #[test]
    fn the_link_is_never_clipped_by_a_footer_sized_from_a_different_rule() {
        let link = "https://arstechnica.com/science/2026/07/\
                    if-a-quantum-computer-outperforms-normal-ones-can-you-tell/";
        for width in 20..80u16 {
            let lines = link_lines(link, width);
            for line in &lines {
                assert!(
                    crate::grid::display_width(line) <= usize::from(width),
                    "a link row overflowed at width {width}: {line:?}"
                );
            }
            // Every character of the link survives, in order.
            let rejoined: String = lines
                .iter()
                .map(|l| l.trim_start_matches(['↳', ' ']))
                .collect();
            assert_eq!(
                rejoined.replace('-', ""),
                link.replace(['-', ' '], ""),
                "the link lost characters at width {width}"
            );
        }
    }

    /// The selection starts empty, so `o` silently did nothing on a freshly
    /// focused panel while the border advertised `o show link` regardless.
    #[test]
    fn o_shows_the_top_story_before_the_cursor_has_been_moved() {
        let mut panel = loaded_panel();
        assert_eq!(panel.selected.selected(), None, "nothing selected yet");

        panel.handle_key(KeyEvent::from(KeyCode::Char('o')));

        assert_eq!(
            panel.showing_link.as_deref(),
            Some(panel.shown[0].link.as_str()),
            "the first press should show the top story's link"
        );
        assert_eq!(
            panel.selected.selected(),
            Some(0),
            "and mark the story it belongs to"
        );
    }

    /// `Enter` must not launch anything when nothing is configured. That is the
    /// default state, and mirador shipping a browser launch nobody asked for is
    /// the decision this feature was careful not to reverse.
    #[test]
    fn enter_launches_nothing_until_a_command_is_named() {
        let mut panel = loaded_panel();
        assert!(panel.open_command.is_empty(), "the default is empty");

        panel.handle_key(KeyEvent::from(KeyCode::Enter));

        assert_eq!(
            panel.action.as_deref(),
            Some("set [news].open_command to open links"),
            "it should say how to switch it on, not fail silently"
        );
    }

    /// And when one *is* named, the link goes on as a separate argument. Never
    /// interpolated into a string and never through a shell — a URL is full of
    /// characters a shell would take an interest in.
    #[test]
    fn a_named_command_runs_with_the_link_as_its_own_argument() {
        let mut panel = loaded_panel();
        // Checks the spawn path without depending on a browser being present.
        panel.open_command = harmless_command();

        panel.handle_key(KeyEvent::from(KeyCode::Enter));

        assert_eq!(
            panel.action.as_deref(),
            Some("opened"),
            "the spawn should have succeeded; got {:?}",
            panel.action
        );
    }

    /// A feed is somebody else's file, and the programs people name here —
    /// `open`, `xdg-open` — dispatch on the scheme to whatever handler is
    /// registered. So a link has to pass the same allowlist as an OSC 8 link
    /// before any program sees it: `http`/`https` and RFC 3986 characters.
    #[test]
    fn a_link_that_is_not_a_web_address_is_not_opened() {
        for link in [
            "file:///etc/passwd",
            "smb://evil.test/share",
            "javascript:alert(1)",
            "-flag-for-the-opener",
            "https://example.test/\x07",
            "https://example.test/\x1b]8;;evil",
        ] {
            let mut panel = loaded_panel();
            panel.shown[0].link = link.into();
            // A command that would succeed, so the refusal is the only way
            // the action can say anything but "opened".
            panel.open_command = harmless_command();

            panel.handle_key(KeyEvent::from(KeyCode::Enter));

            assert_eq!(
                panel.action.as_deref(),
                Some("not opened: not a web link"),
                "{link:?}"
            );
        }
    }

    /// The link check refuses what is not a web address, not what is merely
    /// unusual in one. A path in another script and a scheme in capitals
    /// opened before the check existed, and still do — encoded, so the
    /// program receives plain ASCII.
    #[test]
    fn a_web_address_in_another_script_still_opens() {
        for link in [
            "https://de.wikipedia.org/wiki/Gödel",
            "HTTPS://example.test/a",
        ] {
            let mut panel = loaded_panel();
            panel.shown[0].link = link.into();
            panel.open_command = harmless_command();

            panel.handle_key(KeyEvent::from(KeyCode::Enter));

            assert_eq!(panel.action.as_deref(), Some("opened"), "{link:?}");
        }
    }

    /// Running the program directly protects nothing when the program *is* a
    /// shell: `cmd` and PowerShell read their arguments as a command line, and
    /// `&`, `;`, `|`, `%` and `$(…)` are all legal in a URL. `cmd /c start`
    /// was the README's own Windows example, so a reader who followed it gets
    /// told why rather than a feed getting a command line.
    #[test]
    fn a_shell_named_as_the_opener_is_refused() {
        for (program, said) in [
            ("cmd", "cmd"),
            ("CMD.EXE", "CMD"),
            ("C:\\Windows\\System32\\cmd.exe", "cmd"),
            ("powershell", "powershell"),
            ("/usr/local/bin/pwsh", "pwsh"),
            ("cmd.exe. ", "cmd"),
        ] {
            let mut panel = loaded_panel();
            panel.open_command = vec![program.into(), "/c".into(), "start".into()];

            panel.handle_key(KeyEvent::from(KeyCode::Enter));

            assert_eq!(
                panel.action.as_deref(),
                Some(format!("not opened: {said} is a shell").as_str()),
                "{program}"
            );
        }
    }

    /// A command that is not there has to say so rather than looking like it
    /// worked. The reader named it; only they can fix it.
    #[test]
    fn a_command_that_does_not_exist_reports_itself() {
        let mut panel = loaded_panel();
        panel.open_command = vec!["mirador-no-such-program".into()];

        panel.handle_key(KeyEvent::from(KeyCode::Enter));

        let said = panel.action.clone().unwrap_or_default();
        assert!(
            said.starts_with("mirador-no-such-program:"),
            "the failure should name the program: {said:?}"
        );
    }

    /// `y` reports what mirador did, not what the terminal did. OSC 52 is
    /// write-only, so "copied" would be a claim nothing can stand behind — many
    /// terminals refuse the sequence and tmux needs `set-clipboard on`.
    #[test]
    fn copying_does_not_claim_more_than_it_knows() {
        let mut panel = loaded_panel();
        panel.handle_key(KeyEvent::from(KeyCode::Char('y')));

        let said = panel.action.clone().unwrap_or_default();
        assert!(
            !said.starts_with("copied"),
            "the terminal may have ignored it; do not assert success: {said:?}"
        );
        assert!(
            said.contains("clipboard"),
            "but it should say what was attempted: {said:?}"
        );
    }

    /// All three keys act on the same story, so the link that is copied or
    /// opened is the one the cursor marks — #114's complaint, one layer up.
    #[test]
    fn copy_and_open_act_on_the_story_the_cursor_marks() {
        let mut panel = loaded_panel();
        // The cursor is bounded by what was drawn, so the panel has to have been
        // drawn before it can move at all.
        draw(&mut panel, 46, 20);
        panel.handle_key(KeyEvent::from(KeyCode::Char('j')));
        let marked = panel.selected.selected().expect("cursor placed");

        panel.handle_key(KeyEvent::from(KeyCode::Char('o')));
        assert_eq!(
            panel.showing_link.as_deref(),
            Some(panel.shown[marked].link.as_str()),
            "`o` shows the marked story"
        );

        panel.open_command = harmless_command();
        panel.handle_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(
            panel.selected.selected(),
            Some(marked),
            "`Enter` must not move the cursor to a different story"
        );
    }

    /// A command that exists on every platform mirador ships to, and does
    /// nothing when run.
    ///
    /// **Not `true`.** That was used here for a year on the reasoning, written
    /// into the comment, that "`true` exists everywhere" — and it does not
    /// exist on Windows. What hid it is that GitHub's Windows runners ship Git
    /// for Windows, which puts a `true.exe` on `PATH`: the test passed in CI
    /// and failed for anyone building on an ordinary Windows machine. It took
    /// an outside contributor running the suite on their own box to find it
    /// (#174), which is a reminder that a green CI is evidence about the
    /// runner as much as about the code.
    ///
    /// **Not `cmd /c exit` either**, which this used on Windows until a shell
    /// named as the opener started being refused. `whoami` is in System32 on
    /// every Windows mirador ships to, and with a link as its argument it
    /// prints an error and exits — the spawn is all these tests look at.
    fn harmless_command() -> Vec<String> {
        if cfg!(windows) {
            vec!["whoami".into()]
        } else {
            vec!["true".into()]
        }
    }

    /// A panel holding twelve stories, the number the shipped config produces.
    fn loaded_panel() -> NewsPanel {
        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        panel.shown = (0..12)
            .map(|n| Story {
                link: format!("https://example.test/story-{n}"),
                ..story("NASA", &format!("Story number {n}"), n * 10)
            })
            .collect();
        panel
    }

    /// Draw the panel and return what reached the screen.
    fn draw(panel: &mut NewsPanel, width: u16, height: u16) -> String {
        let buffer = crate::widgets::testing::rendered(panel, width, height);
        (0..height)
            .map(|y| {
                (0..width)
                    .filter_map(|x| {
                        buffer
                            .cell((x, y))
                            .map(|c| crate::link::without_links(c.symbol()))
                    })
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// **The panel shows what fits and nothing more.**
    ///
    /// #118: it did not. Every story became a `ListItem`, so `List` scrolled as
    /// soon as the selection left the viewport — twelve stories with three
    /// visible made nine reachable only by scrolling. That is a feed you work
    /// through, which is precisely the thing this panel exists to not be, and
    /// the module header claimed the opposite for months because nothing here
    /// checked.
    ///
    /// If this fails, the question is not how to fix the test.
    #[test]
    fn the_panel_builds_only_the_stories_that_fit() {
        let mut panel = loaded_panel();
        draw(&mut panel, 46, 10);
        let short = panel.drawn;
        assert!(
            short > 0 && short < 12,
            "a 10-row panel should hold some of twelve stories, held {short}"
        );

        draw(&mut panel, 46, 30);
        assert!(
            panel.drawn > short,
            "a taller panel must show more, not the same {short}"
        );
    }

    /// The selection is bounded by what was built, so the cursor cannot walk off
    /// the screen — which is what leaves `List` with nothing to scroll.
    #[test]
    fn the_cursor_cannot_leave_the_visible_stories() {
        let mut panel = loaded_panel();
        let visible = {
            draw(&mut panel, 46, 10);
            panel.drawn
        };

        for _ in 0..50 {
            panel.handle_key(KeyEvent::from(KeyCode::Char('j')));
        }
        assert!(
            panel.selected.selected().unwrap_or(0) < visible,
            "the cursor reached {:?} with only {visible} stories on screen",
            panel.selected.selected()
        );

        // And what is on screen after all that walking is still the top of the
        // list: nothing scrolled underneath it.
        let after = draw(&mut panel, 46, 10);
        assert!(
            after.contains("Story number 0"),
            "the first story scrolled away; got:\n{after}"
        );
    }

    /// The panel carries no count, in the frame or the body. #118 found that
    /// `counter()` was right and nothing held it there — unlike the watch log,
    /// which has had this test all along.
    ///
    /// A number in the border is a badge, a badge accumulates, and an
    /// accumulating badge is the unread-message count this dashboard turned
    /// down. If this assertion ever fails, the question to ask is not how to
    /// fix the test.
    #[test]
    fn the_panel_never_offers_a_counter() {
        let mut panel = loaded_panel();
        assert_eq!(panel.counter(), None, "no counter in the frame");

        let screen = draw(&mut panel, 46, 10);
        for claim in ["12", "new", "more", "of 12"] {
            assert!(
                !screen.contains(claim),
                "the panel said `{claim}`, which counts or promises more below:\n{screen}"
            );
        }
    }

    /// `No stories.` is the quiet day, and nothing could reach it: the fetch
    /// thread recorded a reading only when a pass brought back at least one
    /// story, so a pass with nothing to read — or one that read every feed and
    /// found nothing — left the panel saying `Reading…` for the life of the
    /// session, which reads as a hang rather than as an empty feed.
    #[test]
    fn a_pass_that_found_nothing_says_so_rather_than_reading_for_ever() {
        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        let deadline = Instant::now() + Duration::from_secs(5);
        while !panel.tick() {
            assert!(
                Instant::now() < deadline,
                "the fetch thread never finished its pass"
            );
            std::thread::sleep(Duration::from_millis(5));
        }

        let screen = draw(&mut panel, 46, 6);
        assert!(
            screen.contains("No stories."),
            "a finished pass with nothing in it is a quiet day, got:\n{screen}"
        );
        assert!(
            !screen.contains("Reading"),
            "the pass has finished, so nothing is being read:\n{screen}"
        );
    }

    /// A feed's name is bounded where the panel takes it, by the same `clip`
    /// and the same constant the feed's own fields use; `masthead` uppercases
    /// it on every frame. Cut on a character boundary, at exactly the bound.
    #[test]
    fn a_feed_name_is_bounded_where_the_panel_names_it() {
        let name = "Ω".repeat(crate::feed::MAX_SOURCE + 5);
        let feed = "<rss><channel><item><title>T</title></item></channel></rss>";
        let mut stories = Vec::new();
        take_feed(
            &name,
            crate::feed::parse(feed),
            12,
            &mut stories,
            &mut Vec::new(),
        );
        assert_eq!(stories[0].source, "Ω".repeat(crate::feed::MAX_SOURCE));
    }

    /// A feed broken part-way down gives the panel the stories before the
    /// fault and a failure naming the feed, so the footer still says the
    /// refresh is not clean. And an Atom feed's refusal reaches the same list by
    /// name, which is the line the panel shows when nothing could be read.
    #[test]
    fn a_partly_readable_feed_is_shown_and_still_reported() {
        let broken = "<rss><channel>\
             <item><title>First</title></item>\
             <item><title>Second</title></item>\
             <item><title>Third</titel></item>\
             </channel></rss>";
        let atom = r#"<feed xmlns="http://www.w3.org/2005/Atom"><entry/></feed>"#;
        let mut stories = Vec::new();
        let mut failures = Vec::new();
        take_feed(
            "NASA",
            crate::feed::parse(broken),
            12,
            &mut stories,
            &mut failures,
        );
        take_feed(
            "RELEASES",
            crate::feed::parse(atom),
            12,
            &mut stories,
            &mut failures,
        );

        let shown: Vec<(&str, &str)> = stories
            .iter()
            .map(|s| (s.source.as_str(), s.title.as_str()))
            .collect();
        assert_eq!(shown, [("NASA", "First"), ("NASA", "Second")]);
        assert_eq!(failures.len(), 2, "{failures:?}");
        assert!(
            failures[0].starts_with("NASA: partly unreadable"),
            "{failures:?}"
        );
        assert!(
            failures[1].starts_with("RELEASES: ") && failures[1].contains("Atom"),
            "{failures:?}"
        );
    }

    /// The silent-clip sweep in `widgets/mod.rs`, run on this panel with a
    /// story selected — which that sweep never does, and which is the state the
    /// panel is in from the first `j`, `o`, `y`, `Enter` or turn of the wheel.
    ///
    /// `List` indents every item by its two-cell highlight symbol once a
    /// selection exists, and the headlines were wrapped to the whole width
    /// regardless, so any row the wrap filled lost its last two cells to the
    /// terminal with no `…`. Same differencing as the original: a row at width
    /// W that is exactly the first W cells of the same row at W+1, with
    /// something in cell W, was cut. A whole word dropped at a space, a word
    /// that reappears at the head of the next row, and anything ending in `…`
    /// are not cuts.
    #[test]
    fn no_headline_is_cut_silently_once_a_story_is_selected() {
        let stories = [
            (
                "NASA",
                "Anak Krakatau rumbles again as satellites watch the plume",
            ),
            (
                "PHYS.ORG",
                "Some black holes grow much faster than their galaxies",
            ),
            (
                "ARS TECHNICA",
                "A very long headline that has to wrap on any panel narrower than it",
            ),
        ]
        .into_iter()
        .enumerate()
        .map(|(n, (source, title))| Story {
            link: format!("https://example.test/story-{n}"),
            ..story(source, title, 10)
        })
        .collect();
        let mut panel = NewsPanel::offline(&NewsConfig::default(), stories);
        panel.selected.select(Some(0));

        let height = 14u16;
        let cells = |panel: &mut NewsPanel, width: u16| -> Vec<Vec<String>> {
            let buffer = raw_buffer(panel, width, height);
            (0..height)
                .map(|y| {
                    (0..width)
                        .map(|x| crate::link::without_links(buffer[(x, y)].symbol()))
                        .collect()
                })
                .collect()
        };

        let mut findings = Vec::new();
        let mut prev = cells(&mut panel, 6);
        for width in 7..=100u16 {
            let cur = cells(&mut panel, width);
            let w = usize::from(width) - 1;
            for (y, (narrow, wide)) in prev.iter().zip(&cur).enumerate() {
                let narrow_text: String = narrow.concat();
                let overflowed = wide[w].trim() != "";
                let same_prefix = narrow[..] == wide[..w];
                let marked = narrow_text.trim_end().ends_with('\u{2026}');
                let mid_token = narrow[w - 1].trim() != "";
                let wrapped = prev
                    .get(y + 1)
                    .is_some_and(|next| next.concat().trim_start().starts_with(wide[w].as_str()));
                if overflowed && same_prefix && !marked && mid_token && !wrapped {
                    findings.push(format!(
                        "width {w} row {y}: {:?} continues as {:?}",
                        narrow_text.trim_end(),
                        wide[w]
                    ));
                }
            }
            prev = cur;
        }
        assert!(
            panel.selected.selected().is_some(),
            "the sweep must have run with a story selected"
        );
        assert!(
            findings.is_empty(),
            "{} silent cut(s) with a story selected:\n  {}",
            findings.len(),
            findings.join("\n  ")
        );
    }

    /// A headline taller than the panel must still show something. A blank
    /// panel with stories loaded reads as broken rather than as short.
    #[test]
    fn a_story_too_tall_for_the_panel_is_clipped_rather_than_dropped() {
        let mut panel = NewsPanel::new(&NewsConfig {
            feeds: Vec::new(),
            ..NewsConfig::default()
        });
        panel.shown = vec![story("NASA", &"a very long headline ".repeat(20), 5)];

        let screen = draw(&mut panel, 24, 4);
        assert_eq!(panel.drawn, 1, "the only story must still be built");
        assert!(
            screen.contains("NASA"),
            "nothing was drawn at all; got:\n{screen}"
        );
    }

    /// And the clip says so. The rows past the body used to be dropped in
    /// silence, so the last one kept ended wherever the wrap had put it — a
    /// finished-looking line above nothing (invariant 19, along the height).
    ///
    /// `no_headline_is_cut_silently_once_a_story_is_selected` cannot see it:
    /// it varies the width and differences adjacent renders, and a row that is
    /// never drawn leaves nothing to difference. So this pins the height and
    /// sweeps the width, with and without a selection, and asserts both
    /// halves — a headline that fits carries no `…` — so an ellipsis stuck on
    /// unconditionally fails too. A body of one row holds only the masthead,
    /// and that row is the one that says the headline is missing.
    #[test]
    fn a_headline_taller_than_the_panel_ends_in_an_ellipsis() {
        const TITLE: &str = "Anak Krakatau rumbles again as satellites watch the plume from orbit";
        for selected in [false, true] {
            let mut panel =
                NewsPanel::offline(&NewsConfig::default(), vec![story("NASA", TITLE, 5)]);
            if selected {
                panel.selected.select(Some(0));
            }
            let indent = if selected { HIGHLIGHT_WIDTH } else { 0 };
            for height in 2..=5u16 {
                // The age takes the bottom row; the story has the rest.
                let body = usize::from(height) - 1;
                let (mut cut, mut whole) = (0, 0);
                for width in 12..=120u16 {
                    let screen = draw(&mut panel, width, height);
                    let rows: Vec<&str> = screen.lines().collect();
                    let last = rows[body - 1].trim_end();
                    let title_rows = crate::grid::wrap(TITLE, usize::from(width - indent)).len();
                    if 1 + title_rows > body {
                        cut += 1;
                        assert!(
                            last.ends_with('\u{2026}'),
                            "a headline needing {title_rows} rows was cut to {} without \
                             saying so at {width}x{height}:\n{screen}",
                            body - 1
                        );
                    } else {
                        whole += 1;
                        assert!(
                            !screen.contains('\u{2026}'),
                            "a headline that fits must not claim to be cut at \
                             {width}x{height}:\n{screen}"
                        );
                    }
                }
                assert!(
                    cut > 0 && (whole > 0 || body == 1),
                    "the sweep must reach both a cut and a whole headline at height \
                     {height}: cut {cut}, whole {whole}"
                );
            }
        }
    }
}