ghtui 0.1.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
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
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
//! Full-screen snapshots through ratatui's `TestBackend`, in light and dark
//! schemes (and 256 colors). Snapshots include cell styles, so color changes
//! show up in review. Rendering also exercises the theme's debug assertion
//! that every fg/bg pair used is declared (and therefore contrast-tested).

use crate::api::browse::{IssueKind, PrState, RepoSort, SearchKind, SearchResults};
use crate::api::model::{
    Capped, ChecksState, Label, Mergeable, PrDetail, PrRef, RepoId, ReviewDecision,
};
use crate::api::rate_limit::{Bucket, RateLimits};
use crate::theme::{ColorDepth, DEFAULT_SEED, Mode, Theme};
use crate::ui::Icons;
use ratatui::Terminal;
use ratatui::backend::TestBackend;

use crate::ui::pages::{PrTab, ProfileTab};

use crate::browse::{Data, DataKey, Need, needs};
use crate::fixtures::{self, fetched, press};
use crate::keymap::Keymap;
use crate::route::{OPEN, Route};
use crate::state::{Msg, Overlay, State, update};
use crate::view::view;

/// 2026-10-03T12:00:00Z
const NOW: u64 = 1_791_028_800;

/// A pull request as Home's sections list it.
fn row(
    pr: &str,
    title: &str,
    state: PrState,
    review: Option<ReviewDecision>,
    checks: Option<ChecksState>,
) -> crate::api::browse::IssueSummary {
    let mut row = fixtures::found_pr(pr, title, state);
    if let IssueKind::Pr {
        review: r,
        checks: c,
        ..
    } = &mut row.kind
    {
        (*r, *c) = (review, checks);
    }
    row
}

/// Home's default sections: review requests, your pull requests (2 of
/// 31), your repositories.
fn fill_home(state: &mut State) {
    let requests = vec![
        row(
            "ratatui/ratatui#1820",
            "Add a virtualized list widget for very long collections",
            PrState::Open,
            Some(ReviewDecision::ReviewRequired),
            Some(ChecksState::Passing),
        ),
        row(
            "tokio-rs/tokio#7001",
            "Fix waker leak in the multi-thread scheduler when tasks are cancelled during shutdown",
            PrState::Draft,
            None,
            Some(ChecksState::Pending),
        ),
    ];
    fixtures::section(state, 0, fixtures::found_prs(requests, 2));
    let mine = vec![
        row(
            "gold-silver-copper/ghtui#12",
            "Theme: generate syntax palette from seed",
            PrState::Open,
            Some(ReviewDecision::Approved),
            Some(ChecksState::Failing),
        ),
        row(
            "gold-silver-copper/ghtui#9",
            "Cache GraphQL responses in redb",
            PrState::Open,
            Some(ReviewDecision::ChangesRequested),
            None,
        ),
    ];
    fixtures::section(state, 1, fixtures::found_prs(mine, 31));
    let repos = vec![
        fixtures::repo_summary("gold-silver-copper/ghtui", 1234),
        fixtures::repo_summary("gold-silver-copper/fux", 87),
    ];
    let repos = SearchResults::Repos(crate::api::browse::Results {
        total: 2,
        items: repos,
        next: None,
    });
    fixtures::section(state, 2, repos);
}

pub(crate) fn pr_detail() -> PrDetail {
    PrDetail {
        id: crate::api::model::NodeId::new("PR_12"),
        merge_state: crate::api::model::MergeState::Dirty,
        behind_by: Some(2),
        may: crate::api::model::PrPermits {
            merge: true,
            merge_as_admin: false,
            close: true,
            reopen: true,
            edit: true,
            push_head: true,
        },
        merge_methods: vec![
            crate::api::change::MergeMethod::Squash,
            crate::api::change::MergeMethod::Merge,
        ],
        title: "Theme: generate syntax palette from seed".into(),
        author: "octocat".into(),
        state: PrState::Open,
        updated_at: "2026-10-03T09:00:00Z".into(),
        additions: 120,
        deletions: 34,
        review: Some(ReviewDecision::Approved),
        checks: Some(ChecksState::Failing),
        body: "Derives keyword, string and type colors from the seed's HCT palettes.\n\n\
               Every syntax role is now checked against every diff background, in both \
               schemes and at both color depths."
            .into(),
        created_at: "2026-09-30T12:00:00Z".into(),
        base_ref: "main".into(),
        head_ref: "syntax-palette".into(),
        base_oid: "0123456789abcdef0123456789abcdef01234567".into(),
        head_oid: "fedcba9876543210fedcba9876543210fedcba98".into(),
        head_repo: Some("octocat/ghtui".into()),
        changed_files: 7,
        mergeable: Mergeable::Conflicting,
        milestone: Some(crate::api::model::MilestoneRef {
            number: 3,
            title: "Links".into(),
        }),
        labels: vec![
            Label {
                name: "enhancement".into(),
                color: "a2eeef".into(),
            },
            Label {
                name: "theme".into(),
                color: "7057ff".into(),
            },
        ]
        .into(),
    }
}

fn state(mode: Mode, depth: ColorDepth) -> State {
    let mut state = State::new(
        Theme::new(DEFAULT_SEED, mode, depth),
        Icons::default(),
        Keymap::default(),
        (100, 30),
    );
    state.viewer = Some("octocat".into());
    state.clock = || NOW;
    // Never written: changes to Home's sections are commands, not run here.
    state.config_path = Some("config.toml".into());
    state.rate_limits = RateLimits {
        graphql: Some(Bucket {
            remaining: 4987,
            limit: 5000,
            reset_at: NOW + 3600,
        }),
        rest: None,
    };
    state
}

fn with_home(mode: Mode, depth: ColorDepth) -> State {
    let mut state = state(mode, depth);
    fill_home(&mut state);
    state
}

fn with_pr(mode: Mode) -> State {
    let mut state = with_home(mode, ColorDepth::TrueColor);
    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    let _ = state.push(Route::pr(pr.clone()));
    update(&mut state, Msg::Pr(pr.clone(), Box::new(Ok(pr_detail()))));
    fetched(
        &mut state,
        DataKey::PrActivity(pr),
        Data::PrActivity(Box::new(fixtures::activity())),
    );
    state
}

/// A conversation longer than what's fetched (its newest comments,
/// reviews and commits) says how much is left out, and its tabs count it
/// all.
#[test]
fn long_conversations_say_what_is_left_out() {
    let text = |state: &State| -> String {
        let crate::state::Screen::Page(p) = state.screen() else {
            panic!("not a page");
        };
        p.page()
            .lines
            .iter()
            .map(crate::ui::page::PageLine::text)
            .collect::<Vec<_>>()
            .join("\n")
    };
    let mut issue = fixtures::issue();
    issue.comments = Capped::new(issue.comments.items, 120);
    let mut state = with_issue(Mode::Dark);
    let route = Route::Issue {
        repo: ghtui(),
        number: 14,
    };
    open(&mut state, route, Data::Issue(Some(Box::new(issue))));
    assert!(text(&state).contains("… 119 earlier comments on GitHub (o)"));
    assert!(text(&state).contains("120 comments"));

    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    let mut activity = fixtures::activity();
    activity.comments = Capped::new(activity.comments.items, 101);
    activity.reviews = Capped::new(activity.reviews.items, 3);
    activity.commits = Capped::new(activity.commits.items, 250);
    let mut state = with_pr(Mode::Dark);
    fetched(
        &mut state,
        DataKey::PrActivity(pr),
        Data::PrActivity(Box::new(activity)),
    );
    let page = text(&state);
    assert!(
        page.contains("… 100 earlier comments on GitHub (o)"),
        "{page}"
    );
    assert!(page.contains("… 1 earlier review on GitHub (o)"), "{page}");
    let tabs = state.chrome().tabs;
    let count = |label: &str| {
        tabs.iter()
            .find(|(t, _)| t.label == label)
            .and_then(|(t, _)| t.count)
    };
    assert_eq!(
        (count("Conversation"), count("Commits")),
        (Some(101), Some(250))
    );
    press(&mut state, "2");
    assert!(text(&state).contains("… 248 earlier commits"));
}

/// A dismissed review, with the state the API gives it (pinned by
/// ghtui-api's `a_dismissed_reviews_wire_spelling`), reads as dismissed in
/// the conversation, not as a plain review.
#[test]
fn a_dismissed_review_reads_as_dismissed() {
    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    let mut activity = fixtures::activity();
    activity.reviews = crate::api::model::Capped::new(
        vec![crate::api::browse::ReviewSummary {
            author: "hubot".into(),
            state: crate::api::model::ReviewState::Dismissed,
            body: String::new(),
            submitted_at: "2026-10-01T10:00:00Z".into(),
        }],
        1,
    );
    let mut state = with_pr(Mode::Dark);
    fetched(
        &mut state,
        DataKey::PrActivity(pr),
        Data::PrActivity(Box::new(activity)),
    );
    let crate::state::Screen::Page(p) = state.screen() else {
        panic!("not a page");
    };
    let page = p
        .page()
        .lines
        .iter()
        .map(crate::ui::page::PageLine::text)
        .collect::<Vec<_>>()
        .join("\n");
    let hubot: Vec<&str> = page.lines().filter(|l| l.contains("hubot")).collect();
    assert!(
        page.contains("had a review dismissed"),
        "hubot's lines: {hubot:?}"
    );
}

/// Pushes `route` and delivers `data` for its page's own fetch (its last).
fn open(state: &mut State, route: Route, data: Data) {
    let Some(Need::Data(key)) = needs(&route).pop() else {
        panic!("{route:?} doesn't end in a data fetch");
    };
    let _ = state.push(route);
    fetched(state, key, data);
}

fn ghtui() -> RepoId {
    RepoId::new("gold-silver-copper", "ghtui")
}

/// A repository's Code tab with everything it asked for delivered.
fn with_repo(mode: Mode, depth: ColorDepth) -> State {
    let mut state = state(mode, depth);
    let _ = state.push(Route::Repo(ghtui()));
    fetched(
        &mut state,
        DataKey::Repo(ghtui()),
        Data::Repo(Box::new(fixtures::overview())),
    );
    fetched(
        &mut state,
        DataKey::Readme(ghtui()),
        Data::Readme(Some(Box::new(fixtures::readme()))),
    );
    fetched(
        &mut state,
        DataKey::LastCommits(ghtui(), "HEAD".into(), String::new()),
        Data::LastCommits(std::sync::Arc::new(fixtures::last_commits())),
    );
    state
}

/// A file in the repository.
fn with_file(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::blob(ghtui(), "main".into(), "src/main.rs".into());
    open(&mut state, route, Data::Blob(Box::new(fixtures::blob())));
    state
}

/// A file's blame.
fn with_blame(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let (repo, rev, path) = (ghtui(), "main".to_owned(), "src/main.rs".to_owned());
    let blob = DataKey::Blob(repo.clone(), rev.clone(), path.clone());
    let route = Route::Blame {
        repo,
        rev,
        path,
        lines: Some((5, 5)),
    };
    let _ = state.push(route.clone());
    fetched(&mut state, blob, Data::Blob(Box::new(fixtures::blob())));
    let Some(Need::Data(key)) = needs(&route).pop() else {
        panic!("a blame fetches its blame");
    };
    fetched(&mut state, key, Data::Blame(Box::new(fixtures::blame())));
    state
}
/// A gist.
fn with_gist(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let route = Route::Gist {
        owner: Some("octocat".into()),
        id: "6cad326836d38bd3a7ae".into(),
    };
    open(&mut state, route, Data::Gist(Box::new(fixtures::gist())));
    state
}

/// Someone's gists.
fn with_gists(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let route = Route::Gists("octocat".into());
    open(&mut state, route, Data::Gists(Box::new(fixtures::gists())));
    state
}
/// An organization's teams.
fn with_teams(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    open(
        &mut state,
        Route::Teams("github".into()),
        Data::Teams(Box::new(fixtures::teams())),
    );
    state
}

/// A team.
fn with_team(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let route = Route::Team {
        org: "github".into(),
        slug: "core".into(),
    };
    open(&mut state, route, Data::Team(Box::new(fixtures::team())));
    state
}
/// A repository's security advisories.
fn with_advisories(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Advisories(Some(ghtui()));
    let items = fixtures::advisories();
    let list = crate::api::browse::Results {
        total: items.len() as u64,
        items,
        next: None,
    };
    open(&mut state, route, Data::Advisories(Box::new(list)));
    state
}

/// A security advisory from GitHub's database.
fn with_advisory(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let route = Route::Advisory {
        repo: None,
        ghsa: "GHSA-6r3q-mjv7-xr8m".into(),
    };
    open(
        &mut state,
        route,
        Data::Advisory(Box::new(fixtures::advisory())),
    );
    state
}
/// A wiki's Home.
fn with_wiki(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Wiki {
        repo: ghtui(),
        page: None,
    };
    open(&mut state, route, Data::Wiki(Box::new(fixtures::wiki())));
    state
}
/// The repository's open issues.
fn with_issues(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Issues {
        repo: ghtui(),
        query: OPEN.into(),
    };
    let results = fixtures::issue_results(Some("c1"));
    open(&mut state, route, Data::Search(Box::new(results)));
    state
}

/// A commit, its repository's header loaded first.
fn with_commit(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let commit = fixtures::commit();
    let route = Route::Commit {
        repo: ghtui(),
        oid: commit.oid.clone(),
    };
    open(&mut state, route, Data::Commit(Box::new(commit)));
    state
}

/// A pull request's Checks tab.
fn with_pr_checks(mode: Mode) -> State {
    let mut state = with_pr(mode);
    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    let _ = state.push(Route::Pr {
        pr: pr.clone(),
        tab: PrTab::Checks,
    });
    // The switch refreshes the pull request; it comes back unchanged.
    update(&mut state, Msg::Pr(pr.clone(), Box::new(Ok(pr_detail()))));
    let activity = Data::PrActivity(Box::new(fixtures::activity()));
    fetched(&mut state, DataKey::PrActivity(pr.clone()), activity);
    let checks = Data::Checks(Box::new(fixtures::checks()));
    fetched(&mut state, DataKey::PrChecks(pr), checks);
    state
}

/// A repository's Actions tab.
fn with_actions(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Actions(ghtui());
    open(
        &mut state,
        route,
        Data::Checks(Box::new(fixtures::checks())),
    );
    state
}

/// `state` in a `w`×`h` terminal.
fn sized(mut state: State, w: u16, h: u16) -> State {
    update(&mut state, Msg::Resize(w, h));
    state
}

/// The repository page with `n` more tabs open after it: an issue, a
/// pull request, a profile, a file, a commit…, then back on the second.
fn with_tabs(mode: Mode, n: usize) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let more = [
        Route::Issue {
            repo: ghtui(),
            number: 14,
        },
        Route::pr(PrRef::parse("gold-silver-copper/ghtui#12").unwrap()),
        Route::user("octocat"),
        Route::blob(ghtui(), "main".into(), "crates/app/src/main.rs".into()),
        Route::Commit {
            repo: ghtui(),
            oid: fixtures::commit().oid,
        },
        Route::Releases(ghtui()),
        Route::Stargazers(ghtui()),
    ];
    for route in more.into_iter().cycle().take(n) {
        let _ = state.open_tab(crate::route::Target::Page(route).into());
    }
    let _ = state.switch_to_tab(1);
    state.notices.dismiss();
    state
}

/// An organization's profile.
fn with_org(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let route = Route::user("ratatui");
    open(
        &mut state,
        route,
        Data::Profile(Box::new(fixtures::org_profile())),
    );
    state
}

/// A repository's discussions.
fn with_discussions(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let of = crate::api::browse::DiscussionsOf::Repo(ghtui());
    let route = Route::Discussions { of, category: None };
    open(
        &mut state,
        route,
        Data::Discussions(Box::new(fixtures::discussions())),
    );
    state
}

/// A discussion.
fn with_discussion(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let of = crate::api::browse::DiscussionsOf::Repo(ghtui());
    let route = Route::Discussion { of, number: 14603 };
    open(
        &mut state,
        route,
        Data::Discussion(Box::new(fixtures::discussion())),
    );
    state
}
/// A workflow run.
fn with_run(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::WorkflowRun {
        repo: ghtui(),
        run: 7,
        attempt: None,
    };
    open(
        &mut state,
        route,
        Data::Run(Box::new(fixtures::workflow_run())),
    );
    state
}

/// A job, its failed step's log open; `step` is the step a link pointed at.
fn with_job(mode: Mode, step: Option<(u32, u32)>) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Job {
        repo: ghtui(),
        run: Some(7),
        job: 2,
        step,
        query: String::new(),
    };
    let _ = state.push(route);
    let (job, log) = fixtures::job();
    fetched(
        &mut state,
        DataKey::Job(ghtui(), 2),
        Data::Job(Box::new(job)),
    );
    let log = Data::Log(std::sync::Arc::new(log));
    fetched(&mut state, DataKey::JobLog(ghtui(), 2), log);
    state
}

/// A workflow and its runs.
fn with_workflow(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Workflow {
        repo: ghtui(),
        file: "ci.yml".into(),
    };
    let _ = state.push(route);
    let (workflow, runs) = fixtures::workflow_runs();
    let key = DataKey::Workflow(ghtui(), "ci.yml".into());
    fetched(&mut state, key, Data::Workflow(Box::new(workflow)));
    let key = DataKey::WorkflowRuns(ghtui(), "ci.yml".into());
    fetched(&mut state, key, Data::Runs(Box::new(runs)));
    state
}

/// A repository's stargazers.
fn with_stargazers(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Stargazers(ghtui());
    open(&mut state, route, Data::Users(Box::new(fixtures::people())));
    state
}

/// A repository's forks.
fn with_forks(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Forks(ghtui());
    open(
        &mut state,
        route,
        Data::RepoPage(Box::new(fixtures::forks())),
    );
    state
}

/// A repository's releases.
fn with_releases(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Releases(ghtui());
    open(
        &mut state,
        route,
        Data::Releases(Box::new(fixtures::releases())),
    );
    state
}

/// A release's page.
fn with_release(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Release {
        repo: ghtui(),
        tag: "v0.2.0".into(),
    };
    open(
        &mut state,
        route,
        Data::Release(Box::new(fixtures::release(true))),
    );
    state
}

/// A repository's tags.
fn with_tags(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    open(
        &mut state,
        Route::Tags(ghtui()),
        Data::Tags(Box::new(fixtures::tags())),
    );
    state
}

/// A repository's branches.
fn with_branches(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    open(
        &mut state,
        Route::Branches(ghtui()),
        Data::Branches(Box::new(fixtures::branches())),
    );
    state
}
/// A repository's milestones.
fn with_milestones(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Milestones {
        repo: ghtui(),
        closed: false,
    };
    open(
        &mut state,
        route,
        Data::Milestones(Box::new(fixtures::milestones())),
    );
    state
}

/// A milestone.
fn with_milestone(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Milestone {
        repo: ghtui(),
        number: 3,
    };
    open(
        &mut state,
        route,
        Data::Milestone(Box::new(fixtures::milestone())),
    );
    state
}
/// A repository's deployments.
fn with_deployments(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Deployments {
        repo: ghtui(),
        environment: None,
    };
    open(
        &mut state,
        route,
        Data::Deployments(Box::new(fixtures::deployments())),
    );
    state
}
/// Two tags compared.
fn with_compare(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Compare {
        repo: ghtui(),
        spec: "v0.1.0...v0.2.0".into(),
    };
    open(
        &mut state,
        route,
        Data::Compare(Box::new(fixtures::comparison())),
    );
    state
}
/// A branch's commits.
fn with_history(mode: Mode) -> State {
    let mut state = with_repo(mode, ColorDepth::TrueColor);
    let route = Route::Commits {
        repo: ghtui(),
        rev: "main".into(),
        path: String::new(),
    };
    open(
        &mut state,
        route,
        Data::History(Box::new(fixtures::history(Some("h1")))),
    );
    state
}

/// An issue, its repository's header loaded first.
fn with_issue(mode: Mode) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    fetched(
        &mut state,
        DataKey::Repo(ghtui()),
        Data::Repo(Box::new(fixtures::overview())),
    );
    let route = Route::Issue {
        repo: ghtui(),
        number: 14,
    };
    let issue = Data::Issue(Some(Box::new(fixtures::issue())));
    open(&mut state, route, issue);
    state
}

fn with_profile(mode: Mode, tab: ProfileTab) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let route = Route::User {
        login: "octocat".into(),
        tab,
    };
    let _ = state.push(route.clone());
    let profile = Data::Profile(Box::new(fixtures::profile()));
    fetched(&mut state, DataKey::Profile("octocat".into()), profile);
    // The tab's own list.
    if let Some(key) = crate::browse::paged(&route) {
        let list = match key {
            DataKey::Users(_) => Data::Users(Box::new(fixtures::people())),
            _ => Data::RepoPage(Box::new(fixtures::profile_repos())),
        };
        fetched(&mut state, key, list);
    }
    state
}

fn with_search(mode: Mode, kind: SearchKind, query: &str, results: SearchResults) -> State {
    let mut state = state(mode, ColorDepth::TrueColor);
    let query = query.to_owned();
    open(
        &mut state,
        Route::Search { kind, query },
        Data::Search(Box::new(results)),
    );
    state
}

/// Repositories matching "terminal file manager".
fn with_repo_search(mode: Mode) -> State {
    let results = fixtures::repo_results();
    with_search(mode, SearchKind::Repos, "terminal file manager", results)
}

fn render(state: &State) -> String {
    let (w, h) = state.size;
    let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
    terminal.draw(|frame| view(state, frame, NOW)).unwrap();
    format!("{:?}", terminal.backend().buffer())
}

#[test]
fn home_dark() {
    insta::assert_snapshot!(render(&with_home(Mode::Dark, ColorDepth::TrueColor)));
}

#[test]
fn home_light() {
    insta::assert_snapshot!(render(&with_home(Mode::Light, ColorDepth::TrueColor)));
}

#[test]
fn home_dark_256() {
    insta::assert_snapshot!(render(&with_home(Mode::Dark, ColorDepth::Ansi256)));
}

#[test]
fn home_third_row_selected_light() {
    let mut state = with_home(Mode::Light, ColorDepth::TrueColor);
    press(&mut state, "jj");
    insta::assert_snapshot!(render(&state));
}

#[test]
fn home_loading_dark() {
    let mut state = state(Mode::Dark, ColorDepth::TrueColor);
    let _ = state.load_visible(false);
    insta::assert_snapshot!(render(&state));
}

#[test]
fn home_error_light() {
    let mut state = state(Mode::Light, ColorDepth::TrueColor);
    let _ = state.load_visible(false);
    // One section fails; the others show.
    fill_home(&mut state);
    let key = state.home[1].search.clone().unwrap().key();
    state.data.remove(&key);
    let _ = state.load_visible(false);
    update(
        &mut state,
        Msg::Fetched {
            key,
            result: Err(crate::api::ApiError::Network("connection refused".into())),
            cached_at: None,
        },
    );
    insta::assert_snapshot!(render(&state));
}

#[test]
fn repo_dark() {
    insta::assert_snapshot!(render(&with_repo(Mode::Dark, ColorDepth::TrueColor)));
}

#[test]
fn repo_light() {
    insta::assert_snapshot!(render(&with_repo(Mode::Light, ColorDepth::TrueColor)));
}

#[test]
fn repo_readme_dark_256() {
    let mut state = with_repo(Mode::Dark, ColorDepth::Ansi256);
    press(&mut state, "G");
    insta::assert_snapshot!(render(&state));
}

#[test]
fn repo_wide_terminal_centers_light() {
    let mut state = with_repo(Mode::Light, ColorDepth::TrueColor);
    update(&mut state, Msg::Resize(160, 30));
    insta::assert_snapshot!(render(&state));
}

#[test]
fn pr_checks_dark() {
    insta::assert_snapshot!(render(&with_pr_checks(Mode::Dark)));
}

#[test]
fn actions_light() {
    insta::assert_snapshot!(render(&with_actions(Mode::Light)));
}

#[test]
fn profile_repositories_light() {
    let tab = ProfileTab::Repositories(RepoSort::Name);
    insta::assert_snapshot!(render(&with_profile(Mode::Light, tab)));
}

#[test]
fn profile_followers_dark() {
    insta::assert_snapshot!(render(&with_profile(Mode::Dark, ProfileTab::Followers)));
}

#[test]
fn tabs_light() {
    insta::assert_snapshot!(render(&with_tabs(Mode::Light, 3)));
}

#[test]
fn tabs_dark() {
    insta::assert_snapshot!(render(&with_tabs(Mode::Dark, 3)));
}

/// More tabs than fit: the one on screen shows, with how many are hidden
/// either side.
#[test]
fn tabs_overflow_80_dark() {
    let mut state = with_tabs(Mode::Dark, 12);
    let _ = state.switch_to_tab(6);
    state.notices.dismiss();
    insta::assert_snapshot!(render(&sized(state, 80, 24)));
}

#[test]
fn org_profile_dark() {
    insta::assert_snapshot!(render(&sized(with_org(Mode::Dark), 100, 50)));
}

/// The whole overview: README, pinned, the contribution graph, activity.
#[test]
fn profile_overview_tall_light() {
    let state = with_profile(Mode::Light, ProfileTab::Overview);
    insta::assert_snapshot!(render(&sized(state, 100, 80)));
}

/// In 256 colors the graph's shades stay apart.
#[test]
fn profile_overview_256_dark() {
    let mut state = with_profile(Mode::Dark, ProfileTab::Overview);
    state.theme = Theme::new(DEFAULT_SEED, Mode::Dark, ColorDepth::Ansi256);
    insta::assert_snapshot!(render(&sized(state, 100, 80)));
}

#[test]
fn discussions_dark() {
    insta::assert_snapshot!(render(&with_discussions(Mode::Dark)));
}

#[test]
fn discussion_light() {
    insta::assert_snapshot!(render(&sized(with_discussion(Mode::Light), 100, 50)));
}

#[test]
fn workflow_run_dark() {
    insta::assert_snapshot!(render(&with_run(Mode::Dark)));
}

#[test]
fn job_light() {
    insta::assert_snapshot!(render(&sized(with_job(Mode::Light, None), 100, 40)));
}

/// A link to a step's line opens that step's log there.
#[test]
fn job_step_dark() {
    insta::assert_snapshot!(render(&sized(with_job(Mode::Dark, Some((2, 2))), 100, 40)));
}

#[test]
fn workflow_light() {
    insta::assert_snapshot!(render(&with_workflow(Mode::Light)));
}

#[test]
fn stargazers_dark() {
    insta::assert_snapshot!(render(&with_stargazers(Mode::Dark)));
}

#[test]
fn forks_light() {
    insta::assert_snapshot!(render(&with_forks(Mode::Light)));
}

#[test]
fn releases_dark() {
    insta::assert_snapshot!(render(&with_releases(Mode::Dark)));
}

#[test]
fn release_light() {
    insta::assert_snapshot!(render(&with_release(Mode::Light)));
}

#[test]
fn tags_dark() {
    insta::assert_snapshot!(render(&with_tags(Mode::Dark)));
}

#[test]
fn milestones_dark() {
    insta::assert_snapshot!(render(&with_milestones(Mode::Dark)));
}

#[test]
fn milestone_light() {
    insta::assert_snapshot!(render(&with_milestone(Mode::Light)));
}

#[test]
fn deployments_dark() {
    insta::assert_snapshot!(render(&with_deployments(Mode::Dark)));
}

#[test]
fn compare_light() {
    insta::assert_snapshot!(render(&with_compare(Mode::Light)));
}

#[test]
fn blame_dark() {
    insta::assert_snapshot!(render(&with_blame(Mode::Dark)));
}

#[test]
fn gist_light() {
    insta::assert_snapshot!(render(&with_gist(Mode::Light)));
}

#[test]
fn gists_dark() {
    insta::assert_snapshot!(render(&with_gists(Mode::Dark)));
}

#[test]
fn teams_light() {
    insta::assert_snapshot!(render(&with_teams(Mode::Light)));
}

#[test]
fn team_dark() {
    insta::assert_snapshot!(render(&with_team(Mode::Dark)));
}

#[test]
fn advisories_dark() {
    insta::assert_snapshot!(render(&with_advisories(Mode::Dark)));
}

#[test]
fn advisory_light() {
    insta::assert_snapshot!(render(&sized(with_advisory(Mode::Light), 100, 40)));
}

#[test]
fn wiki_light() {
    insta::assert_snapshot!(render(&with_wiki(Mode::Light)));
}

#[test]
fn branches_light() {
    insta::assert_snapshot!(render(&with_branches(Mode::Light)));
}

#[test]
fn commits_light() {
    insta::assert_snapshot!(render(&with_history(Mode::Light)));
}

#[test]
fn commit_light() {
    insta::assert_snapshot!(render(&with_commit(Mode::Light)));
}

#[test]
fn commit_dark() {
    insta::assert_snapshot!(render(&with_commit(Mode::Dark)));
}

#[test]
fn file_light() {
    insta::assert_snapshot!(render(&with_file(Mode::Light)));
}

/// A link to lines opens scrolled to them, marked.
#[test]
fn file_lines_dark() {
    let mut state = with_repo(Mode::Dark, ColorDepth::TrueColor);
    let text: String = (1..=80).map(|n| format!("let x{n} = {n};\n")).collect();
    let blob = crate::api::browse::Blob {
        path: "src/main.rs".into(),
        size: text.len() as u64,
        text: Some(text),
        truncated: false,
    };
    let url = "https://github.com/gold-silver-copper/ghtui/blob/main/src/main.rs#L60-L62";
    let crate::route::Target::Page(route) = crate::route::Dest::from_url(url).target else {
        panic!("{url}");
    };
    let route = route.split(None).unwrap_or(route);
    open(&mut state, route, Data::Blob(Box::new(blob)));
    insta::assert_snapshot!(render(&state));
}

#[test]
fn issues_dark() {
    insta::assert_snapshot!(render(&with_issues(Mode::Dark)));
}

#[test]
fn issue_light() {
    insta::assert_snapshot!(render(&with_issue(Mode::Light)));
}

#[test]
fn pr_dark() {
    insta::assert_snapshot!(render(&with_pr(Mode::Dark)));
}

#[test]
fn pr_light() {
    insta::assert_snapshot!(render(&with_pr(Mode::Light)));
}

#[test]
fn pr_commits_dark() {
    let mut state = with_pr(Mode::Dark);
    press(&mut state, "2");
    insta::assert_snapshot!(render(&state));
}

#[test]
fn pr_refresh_error_dark() {
    let mut state = with_pr(Mode::Dark);
    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    update(
        &mut state,
        Msg::Pr(pr, Box::new(Err(crate::api::ApiError::RateLimited(42)))),
    );
    insta::assert_snapshot!(render(&state));
}

#[test]
fn profile_light() {
    insta::assert_snapshot!(render(&with_profile(Mode::Light, ProfileTab::Overview)));
}

#[test]
fn search_dark() {
    insta::assert_snapshot!(render(&with_repo_search(Mode::Dark)));
}

#[test]
fn search_discussions_dark() {
    let results = fixtures::discussion_results();
    let state = with_search(Mode::Dark, SearchKind::Discussions, "offline", results);
    insta::assert_snapshot!(render(&state));
}

#[test]
fn search_commits_light() {
    let results = fixtures::commit_results();
    let state = with_search(Mode::Light, SearchKind::Commits, "tui", results);
    insta::assert_snapshot!(render(&state));
}

#[test]
fn search_code_dark() {
    let results = fixtures::code_results();
    let state = with_search(Mode::Dark, SearchKind::Code, "Terminal", results);
    insta::assert_snapshot!(render(&state));
}

#[test]
fn search_users_light() {
    let results = fixtures::user_results();
    let state = with_search(Mode::Light, SearchKind::Users, "octocat", results);
    insta::assert_snapshot!(render(&state));
}

#[test]
fn quick_ways_around_dark() {
    let mut state = with_repo(Mode::Dark, ColorDepth::TrueColor);
    state.visits = vec![crate::nav::Visit {
        url: "https://github.com/octocat".into(),
        title: "@octocat".into(),
        count: 3,
        last: NOW - 600,
    }];
    press(&mut state, "i");
    insta::assert_snapshot!("hints_dark", render(&state));
    press(&mut state, "<Esc>/");
    insta::assert_snapshot!("search_empty_dark", render(&state));
    press(&mut state, "oct");
    insta::assert_snapshot!("search_typed_dark", render(&state));
    press(&mut state, "<Esc><Space>");
    insta::assert_snapshot!("menu_dark", render(&state));
    press(&mut state, "<Esc>g");
    insta::assert_snapshot!("which_key_dark", render(&state));
}

#[test]
fn go_to_file_light() {
    let mut state = with_repo(Mode::Light, ColorDepth::TrueColor);
    press(&mut state, "f");
    fetched(
        &mut state,
        DataKey::Files(ghtui(), "main".into()),
        Data::Files(
            std::sync::Arc::new(vec![
                "src/main.rs".into(),
                "crates/app/src/main.rs".into(),
                "crates/ui/src/page.rs".into(),
            ]),
            false,
        ),
    );
    press(&mut state, "main");
    insta::assert_snapshot!(render(&state));
}

#[test]
fn list_filter_light() {
    let mut state = with_repo(Mode::Light, ColorDepth::TrueColor);
    press(&mut state, "2/");
    insta::assert_snapshot!(render(&state));
}

#[test]
fn profile_stars_dark() {
    insta::assert_snapshot!(render(&with_profile(Mode::Dark, ProfileTab::Stars)));
}

#[test]
fn repo_wide_with_about_dark() {
    let mut state = with_repo(Mode::Dark, ColorDepth::TrueColor);
    update(&mut state, Msg::Resize(150, 36));
    insta::assert_snapshot!(render(&state));
}

#[test]
fn menu_overlay_dark() {
    let mut state = with_home(Mode::Dark, ColorDepth::TrueColor);
    crate::nav::open_menu(&mut state);
    insta::assert_snapshot!(render(&state));
}

#[test]
fn palette_light() {
    let mut state = with_home(Mode::Light, ColorDepth::TrueColor);
    let _ = state.open_picker(crate::picker::Kind::Commands);
    if let Some(Overlay::Picker(p)) = &mut state.overlay {
        p.input.insert_str("ratatui");
    }
    insta::assert_snapshot!(render(&state));
}

/// The common small terminal: lists go compact (one row per item).
#[test]
fn small_terminal_80x24() {
    let small = |mut state: State| {
        update(&mut state, Msg::Resize(80, 24));
        render(&state)
    };
    insta::assert_snapshot!(
        "small_home",
        small(with_home(Mode::Dark, ColorDepth::TrueColor))
    );
    insta::assert_snapshot!("small_issues", small(with_issues(Mode::Dark)));
    insta::assert_snapshot!("small_pr", small(with_pr(Mode::Dark)));
    let mut menu = with_repo(Mode::Dark, ColorDepth::TrueColor);
    crate::nav::open_menu(&mut menu);
    insta::assert_snapshot!("small_menu", small(menu));
}

#[test]
fn narrow_terminal_does_not_panic() {
    for (w, h) in [(1, 1), (9, 2), (20, 5), (40, 10)] {
        for mode in [Mode::Light, Mode::Dark] {
            let mut state = with_pr(mode);
            update(&mut state, Msg::Resize(w, h));
            render(&state);
            state.screens.truncate(1);
            update(&mut state, Msg::Resize(w, h));
            render(&state);
            crate::nav::open_menu(&mut state);
            render(&state);
            let mut state = with_repo(mode, ColorDepth::TrueColor);
            update(&mut state, Msg::Resize(w, h));
            render(&state);
        }
    }
}

// ---- diff screen -----------------------------------------------------------

pub(crate) use diff::diff_state as diff_fixture;

pub(crate) mod diff {
    use std::collections::HashSet;
    use std::sync::Arc;

    use crate::api::model::PrRef;
    use crate::diff::FileDiff;
    use crate::git::Oid;
    use crate::git::files::{ChangedFile, FileStatus, ZERO_OID};
    use crate::git::repo::PrRefs;
    use crate::theme::{ColorDepth, Mode};
    use crate::ui::diff_doc::{Doc, Pos};

    use super::{NOW, Terminal, TestBackend, press, render, state, view};
    use crate::diff_screen::{DiffOf, DiffPrefs, DiffScreen, DiffState, Pane};
    use crate::fixtures::diff_msg;
    use crate::state::{DiffMsg, Msg, Screen, State, update};

    fn pr() -> PrRef {
        PrRef::parse("o/r#7").unwrap()
    }

    fn file(
        status: FileStatus,
        old: Option<&str>,
        new: Option<&str>,
        modes: (u32, u32),
    ) -> ChangedFile {
        ChangedFile {
            status,
            old_path: old.map(Into::into),
            new_path: new.map(Into::into),
            old_mode: modes.0,
            new_mode: modes.1,
            old_oid: Oid::parse(&"1".repeat(40)).unwrap(),
            new_oid: if new.is_some() {
                Oid::parse(&"2".repeat(40)).unwrap()
            } else {
                Oid::parse(ZERO_OID).unwrap()
            },
            similarity: (status == FileStatus::Renamed).then_some(94),
        }
    }

    const OLD_RS: &str = "use std::fmt;\n\n/// A point.\npub struct Point {\n    x: i32,\n    y: i32,\n}\n\nimpl Point {\n    pub fn new(x: i32, y: i32) -> Self {\n        Point { x, y }\n    }\n}\n";
    const NEW_RS: &str = "use std::fmt;\n\n/// A point in 2D.\npub struct Point {\n    x: i32,\n    y: i32,\n}\n\nimpl Point {\n    pub fn new(x: i32, y: i32) -> Self {\n        Point { x, y }\n    }\n\n    pub fn origin() -> Self {\n        Self::new(0, \"0\".len() as i32 - 1)\n    }\n}\n";

    fn loaded(doc: &Doc) -> DiffState {
        let refs = PrRefs {
            head: Oid::parse(&"e".repeat(40)).unwrap(),
            base: Oid::parse(&"b".repeat(40)).unwrap(),
            merge_base: Oid::parse(&"c".repeat(40)).unwrap(),
        };
        DiffState::fresh().with_doc(refs, doc)
    }

    /// Opens a diff screen on `diff`, as wide as the terminal.
    fn open_diff(s: &mut State, diff: DiffState, cursor: Pos, focus: Pane) {
        s.diffs.insert(DiffOf::Pr(pr()), diff);
        let mut screen = DiffScreen::new(DiffOf::Pr(pr()), DiffPrefs::fit(s.size.0));
        screen.cursor = cursor;
        screen.focus = focus;
        s.screens.push(Screen::Diff(Box::new(screen)));
        let _ = s.settle_diff();
    }

    /// The fixture's changed files.
    fn fixture_files() -> Vec<ChangedFile> {
        let regular = (0o100644, 0o100644);
        vec![
            file(
                FileStatus::Modified,
                Some("src/point.rs"),
                Some("src/point.rs"),
                regular,
            ),
            file(
                FileStatus::Renamed,
                Some("docs/old.md"),
                Some("docs/new.md"),
                regular,
            ),
            file(FileStatus::Added, None, Some("notes.txt"), (0, 0o100644)),
            file(FileStatus::Deleted, Some("gone.py"), None, (0o100644, 0)),
            file(
                FileStatus::Modified,
                Some("logo.png"),
                Some("logo.png"),
                regular,
            ),
            file(
                FileStatus::Modified,
                Some("run.sh"),
                Some("run.sh"),
                (0o100644, 0o100755),
            ),
            file(
                FileStatus::Modified,
                Some("Cargo.lock"),
                Some("Cargo.lock"),
                regular,
            ),
            file(
                FileStatus::Modified,
                Some("zz/pending.rs"),
                Some("zz/pending.rs"),
                regular,
            ),
        ]
    }

    pub(crate) fn diff_state() -> DiffState {
        let files = fixture_files();
        let mut doc = Doc::new(files, &HashSet::new(), Default::default());
        let diffs = [
            FileDiff::compute(
                "src/point.rs",
                Some(OLD_RS.as_bytes()),
                Some(NEW_RS.as_bytes()),
            ),
            FileDiff::compute("docs/new.md", Some(b"# Title\n"), Some(b"# Title\n")),
            FileDiff::compute("notes.txt", None, Some(b"first\nsecond, no newline")),
            FileDiff::compute("gone.py", Some(b"def f():\n    return 1\n"), None),
            FileDiff::compute("logo.png", Some(b"\x89PNG\0a"), Some(b"\x89PNG\0bc")),
            FileDiff::compute("run.sh", Some(b"echo hi\n"), Some(b"echo hi\n")),
            FileDiff::compute("Cargo.lock", Some(b"a\n"), Some(b"b\n")),
        ];
        for (i, d) in diffs.into_iter().enumerate() {
            doc.set_diff(i, Arc::new(d));
        }
        loaded(&doc)
    }

    pub(super) fn screen_state(mode: Mode, depth: ColorDepth, cursor: Pos, focus: Pane) -> State {
        let mut s = state(mode, depth);
        s.size = (110, 34);
        open_diff(&mut s, diff_state(), cursor, focus);
        s
    }

    /// The fixture's diff in true color, the cursor on `row` of `file`.
    fn diff_at(mode: Mode, file: usize, row: usize) -> State {
        screen_state(mode, ColorDepth::TrueColor, Pos { file, row }, Pane::Diff)
    }

    pub(super) fn commit_of() -> DiffOf {
        DiffOf::Commit(
            super::ghtui(),
            Oid::parse(&crate::fixtures::commit().oid).unwrap(),
        )
    }

    /// A commit's files: its tabs instead of a pull request's.
    #[test]
    fn commit_files_dark() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        s.size = (110, 34);
        let of = commit_of();
        s.diffs.insert(of.clone(), diff_state());
        s.screens.push(Screen::Diff(Box::new(DiffScreen::new(
            of,
            DiffPrefs::fit(s.size.0),
        ))));
        let _ = s.settle_diff();
        insta::assert_snapshot!(render(&s));
    }

    /// A link to a file in a diff (`#diff-<hash>`, maybe with a line) goes
    /// to that file once the files are listed.
    #[test]
    fn diff_links_go_to_their_file() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        let hash = crate::diff_screen::path_hash("notes.txt");
        let url = format!("https://github.com/o/r/pull/7/files#diff-{hash}R1");
        let _ = s.follow(&crate::ui::page::Link::Url(url));
        s.diffs.insert(DiffOf::Pr(pr()), diff_state());
        let _ = s.settle_diff();
        let Screen::Diff(d) = s.screen() else {
            panic!("the link didn't open a diff");
        };
        let doc = &s.diffs[&d.of].doc;
        assert_eq!(doc.files()[d.cursor.file].meta.path(), "notes.txt");
        assert_eq!(d.anchor, None);
    }

    /// A link to a review comment (`#discussion_r<id>`) opens the diff at
    /// its thread once the threads are in.
    #[test]
    fn review_comment_links_go_to_their_thread() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        let url = "https://github.com/o/r/pull/7#discussion_r42".to_owned();
        let _ = s.follow(&crate::ui::page::Link::Url(url));
        s.diffs.insert(DiffOf::Pr(pr()), diff_state());
        let _ = s.settle_diff();
        let Screen::Diff(d) = s.screen() else {
            panic!("the link didn't open a diff");
        };
        assert!(d.anchor.is_some(), "waits for the threads");
        let mut thread = crate::fixtures::thread("t", Some(3), false, false);
        thread.comments[0].url = "https://github.com/o/r/pull/7#discussion_r42".into();
        if let Some(diff) = s.diffs.get_mut(&DiffOf::Pr(pr())) {
            diff.edit(|i| {
                i.threads = vec![crate::fixtures::thread("u", Some(1), false, false), thread];
            });
        }
        let _ = s.settle_diff();
        let Screen::Diff(d) = s.screen() else {
            panic!("not a diff");
        };
        let doc = &s.diffs[&d.of].doc;
        assert_eq!(d.anchor, None);
        assert_eq!(doc.annotation_at(d.cursor), Some(1), "the second thread");
    }

    /// A commit's diff has no review threads: a review comment's anchor
    /// there is let go rather than waited on.
    #[test]
    fn review_comment_anchors_on_a_commit_are_let_go() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        let of = commit_of();
        s.diffs.insert(of.clone(), diff_state());
        let mut screen = DiffScreen::new(of, DiffPrefs::fit(s.size.0));
        screen.anchor = Some("discussion_r42".into());
        s.screens.push(Screen::Diff(Box::new(screen)));
        let _ = s.settle_diff();
        assert!(matches!(s.screen(), Screen::Diff(d) if d.anchor.is_none()));
    }

    /// Threads that come before their file's diff don't lose the link's
    /// place: it waits for the diff, then goes to the thread.
    #[test]
    fn review_comment_links_wait_for_their_file() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        let url = "https://github.com/o/r/pull/7#discussion_r42".to_owned();
        let _ = s.follow(&crate::ui::page::Link::Url(url));
        let mut diff = loaded(&Doc::new(
            fixture_files(),
            &HashSet::new(),
            Default::default(),
        ));
        let mut thread = crate::fixtures::thread("t", Some(3), false, false);
        thread.comments[0].url = "https://github.com/o/r/pull/7#discussion_r42".into();
        diff.edit(|i| i.threads = vec![thread]);
        s.diffs.insert(DiffOf::Pr(pr()), diff);
        let _ = s.settle_diff();
        let waiting = matches!(s.screen(), Screen::Diff(d) if d.anchor.is_some());
        assert!(waiting, "waits for src/point.rs's diff");
        if let Some(diff) = s.diffs.get_mut(&DiffOf::Pr(pr())) {
            let d = FileDiff::compute(
                "src/point.rs",
                Some(OLD_RS.as_bytes()),
                Some(NEW_RS.as_bytes()),
            );
            diff.doc.set_diff(0, Arc::new(d));
        }
        let _ = s.settle_diff();
        let Screen::Diff(d) = s.screen() else {
            panic!("not a diff");
        };
        assert_eq!(d.anchor, None);
        assert_eq!(s.diffs[&d.of].doc.annotation_at(d.cursor), Some(0));
    }

    #[test]
    fn diff_dark() {
        insta::assert_snapshot!(render(&diff_at(Mode::Dark, 0, 4)));
    }

    #[test]
    fn diff_light() {
        insta::assert_snapshot!(render(&diff_at(Mode::Light, 0, 4)));
    }

    #[test]
    fn diff_dark_256_tree_focused() {
        insta::assert_snapshot!(render(&screen_state(
            Mode::Dark,
            ColorDepth::Ansi256,
            Pos { file: 2, row: 0 },
            Pane::Tree,
        )));
    }

    #[test]
    fn diff_scrolled_shows_sticky_header_light() {
        insta::assert_snapshot!(render(&diff_at(Mode::Light, 7, 1)));
    }

    #[test]
    fn diff_split_wide_light() {
        let mut s = diff_at(Mode::Light, 0, 6);
        s.size = (200, 30);
        let _ = s.settle_diff();
        insta::assert_snapshot!(render(&s));
    }

    #[test]
    fn diff_viewed_and_reviewed_dark() {
        let mut s = diff_at(Mode::Dark, 0, 3);
        let diff = s.diffs.get_mut(&DiffOf::Pr(pr())).unwrap();
        let hash = diff.doc.files()[0].blocks()[0].hash.clone();
        diff.edit(|i| {
            i.review = crate::store::ReviewState {
                reviewed_hunks: vec![hash],
                ..Default::default()
            }
        });
        let path = diff.doc.files()[1].meta.path().to_owned();
        diff.edit(|i| {
            i.viewed = Some(crate::api::model::ViewedFiles {
                pull_request_id: crate::api::model::NodeId::new("PR_1"),
                states: [(path, crate::ui::diff_doc::Viewed::Viewed)].into(),
            });
        });
        let _ = s.settle_diff();
        insta::assert_snapshot!(render(&s));
    }

    /// The pull request whose diff is on screen.
    fn diff_pr(s: &State) -> crate::api::model::PrRef {
        match s.screen() {
            Screen::Diff(d) => d.of.pr().cloned(),
            Screen::Page(_) => None,
        }
        .expect("a pull request's diff")
    }

    fn with_threads(mode: Mode) -> State {
        use crate::api::model::{NodeId, ReviewComment, ReviewThread, Side};
        let mut s = diff_at(mode, 0, 0);
        let comment = |id: &str, author: &str, body: &str, pending: bool| ReviewComment {
            id: NodeId::new(id),
            author: author.into(),
            body: body.into(),
            created_at: "2026-10-03T08:00:00Z".into(),
            url: String::new(),
            original_commit: Some("abc".into()),
            pending,
        };
        let thread = |id: &str, line: Option<u32>, resolved: bool, file_level: bool, comments| {
            ReviewThread {
                id: NodeId::new(id),
                path: "src/point.rs".into(),
                side: Side::Right,
                start_side: None,
                line,
                start_line: None,
                original_line: line,
                original_start_line: None,
                outdated: false,
                resolved,
                file_level,
                can_reply: true,
                can_resolve: true,
                can_unresolve: true,
                comments,
            }
        };
        let diff = s.diffs.get_mut(&DiffOf::Pr(pr())).unwrap();
        diff.edit(|i| i.threads = vec![
            thread(
                "t1",
                Some(3),
                false,
                false,
                vec![
                    comment("c1", "alice", "Should this say \"2D\" or \"two-dimensional\"? The rest of the docs spell it out.", false),
                    comment("c2", "octocat", "Good point, I'll spell it out.", true),
                ].into(),
            ),
            thread("t2", Some(10), true, false, vec![comment("c3", "bob", "Looks fine now.", false)].into()),
            thread("t3", None, false, true, vec![comment("c4", "carol", "Please add tests for this file.", false)].into()),
        ]);
        diff.edit(|i| {
            i.review = crate::store::ReviewState {
                pending: vec![crate::store::DraftComment {
                    id: 1,
                    path: "src/point.rs".into(),
                    body: "Prefer `Self::default()` here.".into(),
                    side: crate::store::DraftSide::Right,
                    line: Some(15),
                    start_line: None,
                    start_side: None,
                    commit: "h".into(),
                    error: Some("pull_request_review_thread.line must be part of the diff".into()),
                }],
                ..Default::default()
            }
        });
        let _ = s.settle_diff();
        s
    }

    #[test]
    fn threads_dark() {
        insta::assert_snapshot!(render(&with_threads(Mode::Dark)));
    }

    #[test]
    fn threads_light() {
        insta::assert_snapshot!(render(&with_threads(Mode::Light)));
    }

    #[test]
    fn compose_suggestion_dark() {
        use crate::diff::anchor::{LinePos, Side};
        use crate::review::{Compose, ComposeTarget, Preview};
        let mut s = with_threads(Mode::Dark);
        let target = ComposeTarget::Line {
            path: "src/point.rs".into(),
            start: LinePos {
                side: Side::Right,
                line: 14,
            },
            end: LinePos {
                side: Side::Right,
                line: 14,
            },
        };
        let mut compose = Compose::new(
            &s.theme,
            target,
            "```suggestion\n    pub fn zero() -> Self {\n```",
        );
        compose.preview = Some(Preview {
            start_line: 14,
            original: vec!["    pub fn origin() -> Self {".into()],
            suggested: vec!["    pub fn zero() -> Self {".into()],
        });
        s.overlay = Some(crate::state::Overlay::Compose(Box::new(compose)));
        insta::assert_snapshot!(render(&s));
    }

    #[test]
    fn submit_dialog_light() {
        let mut s = with_threads(Mode::Light);
        let mut dialog = crate::review::SubmitDialog::new(&s.theme, diff_pr(&s));
        dialog.cycle(true);
        dialog.input.insert_str("Nice work overall.");
        s.overlay = Some(crate::state::Overlay::Submit(Box::new(dialog)));
        insta::assert_snapshot!(render(&s));
    }

    /// Intra-line emphasis, code moved between files, and a
    /// formatting-only change folded away.
    fn better_than_github(mode: Mode) -> State {
        let regular = (0o100644, 0o100644);
        let files = vec![
            file(
                FileStatus::Modified,
                Some("src/math.rs"),
                Some("src/math.rs"),
                regular,
            ),
            file(
                FileStatus::Modified,
                Some("src/util.rs"),
                Some("src/util.rs"),
                regular,
            ),
        ];
        let helper = "pub fn clamp(value: i32, low: i32, high: i32) -> i32 {\n    value.max(low).min(high)\n}\n";
        let math_old = format!(
            "pub fn area(width: u32, height: u32) -> u32 {{\n    width * height\n}}\n\n{helper}\nlet total = compute(alpha, beta);\n// a\n// b\n// c\n// d\ncall(\n    one,\n    two\n);\n"
        );
        let math_new = "pub fn area(width: u32, height: u32) -> u32 {\n    width * height\n}\n\nlet total = compute(alpha, gamma);\n// a\n// b\n// c\n// d\ncall(one, two);\n";
        let util_old = "// helpers\n";
        let util_new = format!("// helpers\n{helper}");
        let mut doc = Doc::new(files, &HashSet::new(), Default::default());
        doc.set_diff(
            0,
            Arc::new(FileDiff::compute(
                "src/math.rs",
                Some(math_old.as_bytes()),
                Some(math_new.as_bytes()),
            )),
        );
        doc.set_diff(
            1,
            Arc::new(FileDiff::compute(
                "src/util.rs",
                Some(util_old.as_bytes()),
                Some(util_new.as_bytes()),
            )),
        );
        let texts: Vec<_> = doc
            .files()
            .iter()
            .map(|f| f.text().unwrap().clone())
            .collect();
        let moves = crate::diff::moves::detect_moves(&[(0, &texts[0]), (1, &texts[1])]);
        assert_eq!(moves.len(), 1);
        doc.set_moves(moves);
        let mut s = state(mode, ColorDepth::TrueColor);
        s.size = (110, 30);
        open_diff(&mut s, loaded(&doc), Pos::default(), Pane::Diff);
        s
    }

    #[test]
    fn better_than_github_dark() {
        insta::assert_snapshot!(render(&better_than_github(Mode::Dark)));
    }

    #[test]
    fn better_than_github_light() {
        insta::assert_snapshot!(render(&better_than_github(Mode::Light)));
    }

    #[test]
    fn diff_loading_dark() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        let mut diff = DiffState::fresh();
        diff.progress = Some("Receiving objects:  42% (420/1000), 1.2 MiB | 3.4 MiB/s".into());
        open_diff(&mut s, diff, Pos::default(), Pane::Diff);
        insta::assert_snapshot!(render(&s));
    }

    #[test]
    fn small_diff_80x24() {
        let mut s = diff_at(Mode::Dark, 0, 4);
        s.size = (80, 24);
        let _ = s.settle_diff();
        insta::assert_snapshot!(render(&s));
    }

    /// A long git error wraps instead of being cut off.
    #[test]
    fn diff_long_error_dark() {
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        s.size = (80, 24);
        let mut diff = DiffState::fresh();
        diff.progress = None;
        diff.error = Some(
            "git fetch failed: fatal: unable to access 'https://github.com/o/r.git/': \
             Could not resolve host: github.com (is the network up?)"
                .into(),
        );
        open_diff(&mut s, diff, Pos::default(), Pane::Diff);
        let screen = render(&s);
        assert!(screen.contains("network up?)"), "{screen}");
        insta::assert_snapshot!(screen);
    }

    /// Every screen and overlay, at every tiny size and a few extreme
    /// ones: rendering never panics.
    #[test]
    fn every_screen_survives_every_size() {
        use super::{
            DataKey, Overlay, ProfileTab, fetched, ghtui, with_file, with_home, with_issue,
            with_issues, with_pr, with_profile, with_repo, with_repo_search,
        };
        use crate::browse::Data;
        type Build = Box<dyn Fn() -> State>;
        let tc = ColorDepth::TrueColor;
        let pressed = |mut s: State, keys: &str| {
            press(&mut s, keys);
            s
        };
        let builders: Vec<(&str, Build)> = vec![
            ("home", Box::new(move || with_home(Mode::Dark, tc))),
            ("home loading", Box::new(move || state(Mode::Dark, tc))),
            ("repo", Box::new(move || with_repo(Mode::Light, tc))),
            ("file", Box::new(|| with_file(Mode::Light))),
            ("issues", Box::new(|| with_issues(Mode::Dark))),
            ("issue", Box::new(|| with_issue(Mode::Light))),
            ("pr", Box::new(|| with_pr(Mode::Dark))),
            (
                "pr commits",
                Box::new(move || pressed(with_pr(Mode::Dark), "2")),
            ),
            (
                "profile",
                Box::new(|| with_profile(Mode::Light, ProfileTab::Overview)),
            ),
            ("search", Box::new(|| with_repo_search(Mode::Dark))),
            (
                "hints",
                Box::new(move || pressed(with_repo(Mode::Dark, tc), "i")),
            ),
            (
                "search box",
                Box::new(move || pressed(with_repo(Mode::Dark, tc), "/oct")),
            ),
            (
                "menu",
                Box::new(move || pressed(with_repo(Mode::Dark, tc), "<Space>")),
            ),
            (
                "which key",
                Box::new(move || pressed(with_repo(Mode::Dark, tc), "g")),
            ),
            (
                "list filter",
                Box::new(move || pressed(with_repo(Mode::Light, tc), "2/")),
            ),
            (
                "palette",
                Box::new(move || {
                    let mut s = with_home(Mode::Light, tc);
                    let _ = s.open_picker(crate::picker::Kind::Commands);
                    s
                }),
            ),
            (
                "go to file",
                Box::new(move || {
                    let mut s = pressed(with_repo(Mode::Light, tc), "f");
                    let files = vec!["src/main.rs".into(), "crates/ui/src/page.rs".into()];
                    fetched(
                        &mut s,
                        DataKey::Files(ghtui(), "main".into()),
                        Data::Files(Arc::new(files), false),
                    );
                    s
                }),
            ),
            ("diff", Box::new(|| diff_at(Mode::Dark, 0, 4))),
            (
                "diff tree",
                Box::new(move || screen_state(Mode::Dark, tc, Pos { file: 2, row: 0 }, Pane::Tree)),
            ),
            (
                "diff search",
                Box::new(move || {
                    let s = diff_at(Mode::Dark, 0, 4);
                    pressed(s, "/point")
                }),
            ),
            ("threads", Box::new(|| with_threads(Mode::Dark))),
            (
                "submit",
                Box::new(|| {
                    let mut s = with_threads(Mode::Light);
                    let dialog = crate::review::SubmitDialog::new(&s.theme, diff_pr(&s));
                    s.overlay = Some(Overlay::Submit(Box::new(dialog)));
                    s
                }),
            ),
            ("moves", Box::new(|| better_than_github(Mode::Dark))),
            (
                "diff loading",
                Box::new(move || {
                    let mut s = state(Mode::Dark, tc);
                    open_diff(&mut s, DiffState::fresh(), Pos::default(), Pane::Diff);
                    s
                }),
            ),
        ];
        let tiny = (0..=12).flat_map(|w| (0..=12).map(move |h| (w, h)));
        let sizes: Vec<(u16, u16)> = tiny.chain([(1, 200), (200, 1), (80, 24)]).collect();
        for (name, build) in &builders {
            for &(w, h) in &sizes {
                let mut s = build();
                update(&mut s, Msg::Resize(w, h));
                let _ = s.settle_diff();
                let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
                    terminal.draw(|frame| view(&s, frame, NOW)).unwrap();
                }));
                assert!(caught.is_ok(), "{name} panicked at {w}x{h}");
            }
        }
    }

    /// Scrolling stays cheap on a big PR: rendering only touches visible rows.
    /// Run with `cargo test --release -p ghtui -- --ignored scroll_timing`.
    #[test]
    #[ignore = "timing; run in release"]
    #[expect(clippy::print_stderr, reason = "reports the timings")]
    fn scroll_timing_on_500_files_20k_lines() {
        let regular = (0o100644, 0o100644);
        let files: Vec<ChangedFile> = (0..500)
            .map(|i| {
                let path = format!("src/m{i}.rs");
                file(FileStatus::Modified, Some(&path), Some(&path), regular)
            })
            .collect();
        let mut doc = Doc::new(files, &HashSet::new(), Default::default());
        let old: String = (0..60)
            .map(|i| format!("    let v{i} = compute({i}, \"x\");\n"))
            .collect();
        let new: String = old.replace("compute(", "compute_fast(");
        let diff = Arc::new(FileDiff::compute(
            "m.rs",
            Some(old.as_bytes()),
            Some(new.as_bytes()),
        ));
        for i in 0..500 {
            doc.set_diff(i, diff.clone());
        }
        let changed: u32 = doc
            .files()
            .iter()
            .map(|f| f.diff.as_ref().unwrap().additions)
            .sum();
        assert!(changed >= 20_000, "{changed}");

        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        s.size = (160, 50);
        open_diff(&mut s, loaded(&doc), Pos::default(), Pane::Diff);

        let mut terminal = Terminal::new(TestBackend::new(160, 50)).unwrap();
        let frames = 2000;
        let start = std::time::Instant::now();
        for i in 0..frames {
            press(&mut s, if i % 100 < 95 { "j" } else { "<C-d>" });
            terminal.draw(|frame| view(&s, frame, NOW)).unwrap();
        }
        let per_frame = start.elapsed() / frames;
        eprintln!("update + render per frame: {per_frame:?}");
        assert!(
            per_frame < std::time::Duration::from_millis(8),
            "{per_frame:?} per frame"
        );
    }

    /// A single 50k-line file: diffing and highlighting run on the diff job's
    /// workers (never the UI task); once its result arrives, the first screen
    /// must be ready within 100ms. This measures the worker's compute plus the
    /// UI's update and first render.
    /// Run with `cargo test --release -p ghtui -- --ignored big_file_timing`.
    #[test]
    #[ignore = "timing; run in release"]
    #[expect(clippy::print_stderr, reason = "reports the timings")]
    fn big_file_timing_50k_lines() {
        use std::time::{Duration, Instant};

        let old: String = (0..50_000)
            .map(|i| format!("    let value_{i} = compute({i}, \"label\");\n"))
            .collect();
        let new = old
            .replace("compute(100,", "compute_fast(100,")
            .replace("compute(25000,", "compute_fast(25000,")
            .replace("compute(49999,", "compute_fast(49999,");

        let start = Instant::now();
        let diff = Arc::new(FileDiff::compute(
            "big.rs",
            Some(old.as_bytes()),
            Some(new.as_bytes()),
        ));
        let compute = start.elapsed();

        let regular = (0o100644, 0o100644);
        let big = file(
            FileStatus::Modified,
            Some("big.rs"),
            Some("big.rs"),
            regular,
        );
        let mut s = state(Mode::Dark, ColorDepth::TrueColor);
        s.size = (160, 50);
        let doc = Doc::new(vec![big], &HashSet::new(), Default::default());
        open_diff(&mut s, loaded(&doc), Pos::default(), Pane::Diff);
        let mut terminal = Terminal::new(TestBackend::new(160, 50)).unwrap();

        let start = Instant::now();
        let job = s.diffs[&DiffOf::Pr(pr())].job;
        diff_msg(
            &mut s,
            &pr(),
            DiffMsg::Job(job, crate::diff_job::JobMsg::File(0, diff)),
        );
        terminal.draw(|frame| view(&s, frame, NOW)).unwrap();
        let first_screen = start.elapsed();

        // Full-file mode on 50k lines must stay interactive too.
        let start = Instant::now();
        press(&mut s, "F");
        terminal.draw(|frame| view(&s, frame, NOW)).unwrap();
        let full_file = start.elapsed();

        eprintln!("compute {compute:?}, first screen {first_screen:?}, full file {full_file:?}");
        assert!(
            compute + first_screen < Duration::from_millis(100),
            "{:?}",
            compute + first_screen
        );
        assert!(full_file < Duration::from_millis(100), "{full_file:?}");
    }
}

// ---- links that stay in ghtui ----------------------------------------------

mod links {
    use crate::theme::{ColorDepth, Mode};
    use crate::ui::pages::ProfileTab;

    use super::{
        press, with_actions, with_advisories, with_advisory, with_blame, with_branches,
        with_commit, with_compare, with_deployments, with_discussion, with_discussions, with_file,
        with_forks, with_gist, with_gists, with_history, with_home, with_issue, with_issues,
        with_job, with_milestone, with_milestones, with_pr, with_pr_checks, with_profile,
        with_release, with_releases, with_repo, with_repo_search, with_run, with_search,
        with_stargazers, with_tags, with_team, with_teams, with_wiki, with_workflow,
    };
    use crate::route::{Dest, Target};
    use crate::state::{Screen, State};

    /// A link's shape: on github.com its first four path segments, with
    /// the owner and repository, numbers and commit IDs as wildcards; on
    /// GitHub's other hosts (raw files, gists, avatars) the host.
    fn shape(url: &str) -> Vec<String> {
        let Ok(parsed) = url::Url::parse(url) else {
            return vec![url.to_owned()];
        };
        let mut shape = vec![parsed.host_str().unwrap_or_default().to_owned()];
        if parsed.host_str() != Some("github.com") {
            return shape;
        }
        let segments = parsed.path_segments().into_iter().flatten();
        for (i, s) in segments.take(4).enumerate() {
            let wild = i < 2 || s.bytes().any(|b| b.is_ascii_digit());
            shape.push(if wild { "*".into() } else { s.to_owned() });
        }
        shape
    }

    /// Whether the corpus says links shaped like `url` open the browser
    /// (or will open a page once it's built).
    fn external_in_corpus(url: &str) -> bool {
        let wanted = shape(url);
        crate::route::tests::corpus()
            .iter()
            .any(|(entry, expect, _)| {
                matches!(*expect, "external" | "todo") && shape(entry) == wanted
            })
    }

    /// Every page ghtui has a fixture for.
    fn pages() -> Vec<(&'static str, State)> {
        let tc = ColorDepth::TrueColor;
        let mut commits = with_pr(Mode::Dark);
        press(&mut commits, "2");
        vec![
            ("home", with_home(Mode::Dark, tc)),
            ("repo", with_repo(Mode::Dark, tc)),
            ("file", with_file(Mode::Dark)),
            ("issues", with_issues(Mode::Dark)),
            ("issue", with_issue(Mode::Dark)),
            ("pr", with_pr(Mode::Dark)),
            ("pr commits", commits),
            ("profile", with_profile(Mode::Dark, ProfileTab::Overview)),
            (
                "repositories",
                with_profile(
                    Mode::Dark,
                    ProfileTab::Repositories(crate::api::browse::RepoSort::Updated),
                ),
            ),
            ("stars", with_profile(Mode::Dark, ProfileTab::Stars)),
            ("search", with_repo_search(Mode::Dark)),
            ("commit", with_commit(Mode::Dark)),
            ("commits", with_history(Mode::Dark)),
            ("pr checks", with_pr_checks(Mode::Dark)),
            ("actions", with_actions(Mode::Dark)),
            ("stargazers", with_stargazers(Mode::Dark)),
            ("forks", with_forks(Mode::Dark)),
            ("releases", with_releases(Mode::Dark)),
            ("release", with_release(Mode::Dark)),
            ("tags", with_tags(Mode::Dark)),
            ("branches", with_branches(Mode::Dark)),
            (
                "discussion search",
                with_search(
                    Mode::Dark,
                    crate::api::browse::SearchKind::Discussions,
                    "q",
                    crate::fixtures::discussion_results(),
                ),
            ),
            (
                "commit search",
                with_search(
                    Mode::Dark,
                    crate::api::browse::SearchKind::Commits,
                    "q",
                    crate::fixtures::commit_results(),
                ),
            ),
            (
                "code search",
                with_search(
                    Mode::Dark,
                    crate::api::browse::SearchKind::Code,
                    "q",
                    crate::fixtures::code_results(),
                ),
            ),
            ("wiki", with_wiki(Mode::Dark)),
            ("advisories", with_advisories(Mode::Dark)),
            ("advisory", with_advisory(Mode::Dark)),
            ("teams", with_teams(Mode::Dark)),
            ("team", with_team(Mode::Dark)),
            ("gist", with_gist(Mode::Dark)),
            ("gists", with_gists(Mode::Dark)),
            ("blame", with_blame(Mode::Dark)),
            ("compare", with_compare(Mode::Dark)),
            ("deployments", with_deployments(Mode::Dark)),
            ("milestones", with_milestones(Mode::Dark)),
            ("milestone", with_milestone(Mode::Dark)),
            ("run", with_run(Mode::Dark)),
            ("discussions", with_discussions(Mode::Dark)),
            ("discussion", with_discussion(Mode::Dark)),
            ("job", with_job(Mode::Dark, None)),
            ("workflow", with_workflow(Mode::Dark)),
        ]
    }

    /// ghtui's own pages lead to the new ones as GitHub's do: an issue's
    /// and a pull request's sidebar to their milestone, a repository's
    /// toolbar to its branches and tags.
    #[test]
    fn pages_link_to_milestones_branches_and_tags() {
        use crate::route::Route;
        let routes = |s: &State| -> Vec<Route> {
            let Screen::Page(p) = s.screen() else {
                return Vec::new();
            };
            p.page()
                .links
                .iter()
                .filter_map(|l| l.url())
                .filter_map(|u| match Dest::from_url(u).target {
                    Target::Page(r) => Some(r),
                    _ => None,
                })
                .collect()
        };
        let milestone = |repo: &str| Route::Milestone {
            repo: crate::api::model::RepoId::parse(repo).unwrap(),
            number: 3,
        };
        let issue = super::sized(with_issue(Mode::Dark), 160, 40);
        assert!(routes(&issue).contains(&milestone("gold-silver-copper/ghtui")));
        let pr = super::sized(with_pr(Mode::Dark), 160, 40);
        let Screen::Page(p) = pr.screen() else {
            panic!("not a page");
        };
        let Route::Pr { pr: pr_ref, .. } = &p.route else {
            panic!("not a pull request");
        };
        assert!(routes(&pr).contains(&milestone(&pr_ref.repo.to_string())));
        let repo = with_repo(Mode::Dark, ColorDepth::TrueColor);
        let repo_routes = routes(&repo);
        let id = super::ghtui();
        assert!(repo_routes.contains(&Route::Branches(id.clone())));
        assert!(repo_routes.contains(&Route::Tags(id)));
    }

    /// Every github.com link on ghtui's pages (and their tabs) opens a
    /// ghtui page, unless the corpus (`tests/github_urls.txt`) says links of
    /// its shape open the browser, and why.
    #[test]
    fn github_links_stay_in_ghtui() {
        let mut leaving = Vec::new();
        for (name, s) in pages() {
            let Screen::Page(p) = s.screen() else {
                panic!("{name} isn't a page");
            };
            let tabs = s.chrome().tabs.into_iter().map(|(_, t)| t);
            let links = p.page().links.iter().filter_map(|l| l.url());
            let targets = links.map(|u| Dest::from_url(u).target).chain(tabs);
            for target in targets {
                // A page of a kind the corpus has an example of.
                let kind = match &target {
                    Target::Page(route) => Some(crate::route::tests::variant(route)),
                    Target::Files(_) => Some("files".to_owned()),
                    Target::External(_) => None,
                };
                if let Some(kind) = kind
                    && !crate::route::tests::corpus()
                        .iter()
                        .any(|(_, e, _)| *e == kind)
                {
                    leaving.push(format!("{name}: no {kind} in the corpus"));
                }
                if let Target::External(url) = target
                    && url.contains("github")
                    && !external_in_corpus(&url)
                {
                    leaving.push(format!("{name}: {url}"));
                }
            }
        }
        leaving.sort();
        leaving.dedup();
        assert!(
            leaving.is_empty(),
            "links that leave ghtui:\n{}",
            leaving.join("\n")
        );
    }
}

// ---- keys on every screen ---------------------------------------------------

mod keys {
    use crate::theme::{ColorDepth, Mode};
    use crate::ui::diff_doc::Pos;

    use super::diff::screen_state;
    use super::{
        press, render, with_advisories, with_advisory, with_blame, with_branches, with_commit,
        with_compare, with_deployments, with_discussion, with_discussions, with_gist, with_gists,
        with_issues, with_job, with_milestone, with_milestones, with_pr, with_run, with_search,
        with_team, with_teams, with_wiki, with_workflow,
    };
    use crate::diff_screen::Pane;
    use crate::keymap::Action;
    use crate::state::{Overlay, Screen, State, apply};

    type Make = fn() -> State;

    /// A list, a pull request, the diff with each pane focused (the
    /// selection away from the edges so moving can move), and every page
    /// links lead to.
    fn screens() -> [(&'static str, Make); 25] {
        fn moved(mut s: State) -> State {
            press(&mut s, "jj");
            s
        }
        /// A page in a short terminal, scrolled into its middle, so every
        /// way of moving can move.
        fn mid(s: State) -> State {
            let mut s = super::sized(s, 100, 12);
            press(&mut s, "j");
            s
        }
        [
            ("issue list", || moved(with_issues(Mode::Dark))),
            ("pull request", || moved(with_pr(Mode::Dark))),
            ("diff", || {
                let at = Pos { file: 0, row: 4 };
                screen_state(Mode::Dark, ColorDepth::TrueColor, at, Pane::Diff)
            }),
            ("file tree", || {
                let at = Pos { file: 2, row: 0 };
                moved(screen_state(
                    Mode::Dark,
                    ColorDepth::TrueColor,
                    at,
                    Pane::Tree,
                ))
            }),
            ("commit", || with_commit(Mode::Dark)),
            ("commit files", || {
                let mut s = with_commit(Mode::Dark);
                press(&mut s, "<Right><Right>");
                if let Some((screen, _)) = s.diff_parts() {
                    screen.cursor = Pos { file: 0, row: 4 };
                }
                s.diffs
                    .insert(super::diff::commit_of(), super::diff::diff_state());
                s
            }),
            ("workflow run", || mid(with_run(Mode::Dark))),
            // From the top: a failed job opens at its first error.
            ("job", || {
                let mut s = super::sized(with_job(Mode::Dark, None), 100, 12);
                press(&mut s, "gjj");
                s
            }),
            ("workflow", || mid(with_workflow(Mode::Dark))),
            ("discussions", || mid(with_discussions(Mode::Dark))),
            ("discussion", || mid(with_discussion(Mode::Dark))),
            ("branches", || mid(with_branches(Mode::Dark))),
            ("milestones", || mid(with_milestones(Mode::Dark))),
            ("milestone", || mid(with_milestone(Mode::Dark))),
            ("deployments", || mid(with_deployments(Mode::Dark))),
            ("comparison", || mid(with_compare(Mode::Dark))),
            // Scrolled off its line, which it otherwise follows to the
            // bottom when resized.
            ("blame", || {
                let mut s = super::sized(with_blame(Mode::Dark), 100, 12);
                press(&mut s, "gj");
                s
            }),
            ("gist", || mid(with_gist(Mode::Dark))),
            ("gists", || mid(with_gists(Mode::Dark))),
            ("teams", || mid(with_teams(Mode::Dark))),
            ("team", || mid(with_team(Mode::Dark))),
            ("advisories", || mid(with_advisories(Mode::Dark))),
            ("advisory", || mid(with_advisory(Mode::Dark))),
            ("wiki", || mid(with_wiki(Mode::Dark))),
            ("code search", || {
                let results = crate::fixtures::code_results();
                mid(with_search(
                    Mode::Dark,
                    crate::api::browse::SearchKind::Code,
                    "q",
                    results,
                ))
            }),
        ]
    }

    /// Every action does something on every screen, or says why not.
    #[test]
    fn no_action_is_silent() {
        let mut silent = Vec::new();
        for (name, make) in screens() {
            for &action in Action::ALL {
                let mut s = make();
                let before = render(&s);
                let cmds = apply(&mut s, action);
                let _ = s.settle();
                if cmds.is_empty() && s.notices.shown().is_none() && !s.quit && render(&s) == before
                {
                    silent.push(format!("{name}: {}", action.name()));
                }
            }
        }
        assert!(silent.is_empty(), "silent:\n{}", silent.join("\n"));
    }

    /// `→` walks a pull request's tabs into Files changed and `←` walks
    /// back; so do `l` `h`, the numbers, and `←` `→` wrapping around.
    #[test]
    fn tabs_go_into_the_files_and_back() {
        let pairs = [
            ("<Right><Right><Right>", "<Left><Left><Left>"),
            ("lll", "hhh"),
            ("4", "1"),
            ("<Left>", "<Right>"),
        ];
        for (there, back) in pairs {
            let mut s = with_pr(Mode::Dark);
            let start = s.chrome().active;
            press(&mut s, there);
            assert!(matches!(s.screen(), Screen::Diff(_)), "{there}");
            press(&mut s, back);
            assert!(matches!(s.screen(), Screen::Page(_)), "{back}");
            assert_eq!(s.chrome().active, start, "{back}");
        }
    }

    /// A commit's tabs work the same: into its files and back.
    #[test]
    fn commit_tabs_go_into_the_files_and_back() {
        let mut s = with_commit(Mode::Dark);
        press(&mut s, "<Right>");
        assert!(matches!(
            s.route(),
            Some(crate::route::Route::CommitChecks { .. })
        ));
        press(&mut s, "<Right>");
        assert!(
            matches!(s.screen(), Screen::Diff(d) if d.of == super::diff::commit_of()),
            "the commit's diff, by its full ID"
        );
        press(&mut s, "<Left><Left>");
        assert!(matches!(
            s.route(),
            Some(crate::route::Route::Commit { .. })
        ));
    }

    /// In the menu, `h` and `l` are `←` and `→`: close it, run the row.
    #[test]
    fn vim_keys_work_in_the_menu() {
        let mut s = with_pr(Mode::Dark);
        press(&mut s, "<Space>h");
        assert!(s.overlay.is_none());
        press(&mut s, "<Space>l");
        assert!(!matches!(s.overlay, Some(Overlay::Menu(_))));
    }
}

// ---- screenshots for design review ----------------------------------------------

/// Writes the main screens as HTML (exact cells and colors) to
/// `$GHTUI_SHOTS`, for looking at the design in a browser.
#[test]
#[ignore = "design review: GHTUI_SHOTS=dir cargo test -p ghtui screenshots -- --ignored"]
fn screenshots() {
    let Some(dir) = std::env::var_os("GHTUI_SHOTS") else {
        return;
    };
    let dir = std::path::PathBuf::from(dir);
    std::fs::create_dir_all(&dir).unwrap();
    let shot = |name: &str, state: &State| {
        let (w, h) = state.size;
        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal.draw(|frame| view(state, frame, NOW)).unwrap();
        std::fs::write(
            dir.join(format!("{name}.html")),
            to_html(terminal.backend().buffer()),
        )
        .unwrap();
    };
    let sized = |mut s: State, w: u16, h: u16| {
        update(&mut s, Msg::Resize(w, h));
        s
    };
    for (mode, tag) in [(Mode::Dark, "dark"), (Mode::Light, "light")] {
        shot(
            &format!("home_{tag}"),
            &sized(with_home(mode, ColorDepth::TrueColor), 120, 36),
        );
        let mut repo = sized(with_repo(mode, ColorDepth::TrueColor), 150, 40);
        let commit = |headline: &str, date: &str| crate::api::browse::CommitInfo {
            oid: "abc1234".into(),
            headline: headline.into(),
            author: crate::api::browse::Person::User(crate::api::browse::Login::unchecked(
                "octocat",
            )),
            date: date.into(),
        };
        fetched(
            &mut repo,
            DataKey::LastCommits(ghtui(), "HEAD".into(), String::new()),
            Data::LastCommits(std::sync::Arc::new(
                [
                    (
                        ".github".to_owned(),
                        commit("ci: run clippy on stable", "2026-09-20T10:00:00Z"),
                    ),
                    (
                        "crates".to_owned(),
                        commit("Browse GitHub like the website", "2026-10-03T10:00:00Z"),
                    ),
                    (
                        "Cargo.toml".to_owned(),
                        commit("Update dependencies", "2026-09-01T10:00:00Z"),
                    ),
                    (
                        "README.md".to_owned(),
                        commit("Document single-key navigation", "2026-10-02T10:00:00Z"),
                    ),
                ]
                .into_iter()
                .collect(),
            )),
        );
        shot(&format!("repo_{tag}"), &repo);
        shot(
            &format!("repo_narrow_{tag}"),
            &sized(with_repo(mode, ColorDepth::TrueColor), 90, 36),
        );
        shot(&format!("issues_{tag}"), &sized(with_issues(mode), 130, 36));
        shot(&format!("issue_{tag}"), &sized(with_issue(mode), 130, 40));
        shot(&format!("pr_{tag}"), &sized(with_pr(mode), 130, 44));
        let mut commits = sized(with_pr(mode), 120, 30);
        press(&mut commits, "2");
        shot(&format!("pr_commits_{tag}"), &commits);
        shot(&format!("file_{tag}"), &sized(with_file(mode), 120, 24));
        let profile = with_profile(mode, ProfileTab::Overview);
        shot(&format!("profile_{tag}"), &sized(profile, 120, 36));
        shot(
            &format!("search_{tag}"),
            &sized(with_repo_search(mode), 120, 30),
        );
        let mut s = sized(with_repo(mode, ColorDepth::TrueColor), 120, 36);
        s.visits = vec![crate::nav::Visit {
            url: "https://github.com/octocat".into(),
            title: "@octocat".into(),
            count: 3,
            last: NOW,
        }];
        press(&mut s, "i");
        shot(&format!("hints_{tag}"), &s);
        press(&mut s, "<Esc>/oct");
        shot(&format!("search_box_{tag}"), &s);
        press(&mut s, "<Esc><Space>");
        shot(&format!("menu_{tag}"), &s);
        press(&mut s, "<Esc>?");
        shot(&format!("help_{tag}"), &s);
    }
}

fn to_html(buf: &ratatui::buffer::Buffer) -> String {
    use ratatui::style::{Color, Modifier};
    let css = |c: Color, fallback: &str| match c {
        Color::Rgb(r, g, b) => format!("#{r:02x}{g:02x}{b:02x}"),
        _ => fallback.to_owned(),
    };
    let mut out = String::from(
        "<!doctype html><meta charset=utf-8><style>body{margin:0;background:#000}pre{margin:0;font:14px 'JetBrains Mono','SF Mono',Menlo,monospace;letter-spacing:0}div{height:19px;line-height:19px;white-space:pre}span{display:inline-block;height:19px;vertical-align:top}</style><pre>",
    );
    let area = buf.area;
    for y in area.top()..area.bottom() {
        out.push_str("<div>");
        let mut skip = 0;
        for x in area.left()..area.right() {
            if skip > 0 {
                skip -= 1;
                continue;
            }
            let cell = &buf[(x, y)];
            let sym = cell.symbol();
            let w = crate::ui::text::width(sym).max(1);
            skip = w - 1;
            let mut style = format!(
                "color:{};background:{}",
                css(cell.fg, "#ccc"),
                css(cell.bg, "#000")
            );
            if cell.modifier.contains(Modifier::BOLD) {
                style.push_str(";font-weight:700");
            }
            if cell.modifier.contains(Modifier::ITALIC) {
                style.push_str(";font-style:italic");
            }
            if cell.modifier.contains(Modifier::UNDERLINED) {
                style.push_str(";text-decoration:underline");
            }
            let text = sym
                .replace('&', "&amp;")
                .replace('<', "&lt;")
                .replace('>', "&gt;");
            let width = if w > 1 {
                format!(";display:inline-block;width:{w}ch")
            } else {
                String::new()
            };
            out.push_str(&format!("<span style=\"{style}{width}\">{text}</span>"));
        }
        out.push_str("</div>");
    }
    out.push_str("</pre>");
    out
}

/// Text at its worst: long, wide (CJK), with emoji, ZWJ sequences, flags,
/// stacked combining marks and a right-to-left override.
fn awful(n: usize) -> String {
    "漢字かな 👩‍👩‍👧‍👦 🇯🇵 e\u{301}\u{302}\u{303} \u{202e}rtl\u{202c} Full ".repeat(n)
}

/// Stretches what's on the screens' data to its worst.
fn stretch(state: &mut State) {
    for remote in state.data.values_mut() {
        match &mut remote.data {
            Some(Data::Issue(Some(d))) => {
                d.title = awful(40);
                d.body = format!("{}\n\n```\n{}\n```", awful(30), "x".repeat(5000));
                for c in d.comments.iter_mut() {
                    c.author = "a".repeat(39);
                    c.body = awful(20);
                }
            }
            Some(Data::Branches(r)) => {
                for b in &mut r.items {
                    b.name = format!("feature/{}", awful(10));
                    b.headline = Some(awful(20));
                }
            }
            Some(Data::Blob(b)) => {
                b.text = Some(format!("{}\n{}\n", "y".repeat(10_000), awful(50)));
            }
            Some(Data::Repo(o)) => {
                o.summary.description = Some(awful(30));
                o.topics = vec![awful(2); 30].into();
            }
            _ => {}
        }
    }
    state.data_gen += 1;
}

/// Every screen, with ordinary and with awful data, renders at any size
/// (one cell, a phone, a classic terminal) without panicking or drawing
/// outside the screen.
#[test]
fn every_screen_renders_at_odd_sizes() {
    type Build = fn() -> State;
    let builders: Vec<(&str, Build)> = vec![
        ("home", || with_home(Mode::Dark, ColorDepth::TrueColor)),
        ("pr", || with_pr(Mode::Dark)),
        ("repo", || with_repo(Mode::Dark, ColorDepth::TrueColor)),
        ("file", || with_file(Mode::Dark)),
        ("blame", || with_blame(Mode::Dark)),
        ("gist", || with_gist(Mode::Dark)),
        ("teams", || with_team(Mode::Dark)),
        ("advisory", || with_advisory(Mode::Dark)),
        ("wiki", || with_wiki(Mode::Dark)),
        ("issues", || with_issues(Mode::Dark)),
        ("commit", || with_commit(Mode::Dark)),
        ("checks", || with_pr_checks(Mode::Dark)),
        ("actions", || with_actions(Mode::Dark)),
        ("tabs", || with_tabs(Mode::Dark, 9)),
        ("org", || with_org(Mode::Dark)),
        ("discussion", || with_discussion(Mode::Dark)),
        ("run", || with_run(Mode::Dark)),
        ("job", || with_job(Mode::Dark, Some((3, 2)))),
        ("releases", || with_releases(Mode::Dark)),
        ("branches", || with_branches(Mode::Dark)),
        ("milestone", || with_milestone(Mode::Dark)),
        ("deployments", || with_deployments(Mode::Dark)),
        ("compare", || with_compare(Mode::Dark)),
        ("history", || with_history(Mode::Dark)),
        ("issue", || with_issue(Mode::Dark)),
        ("profile", || with_profile(Mode::Dark, ProfileTab::Overview)),
        ("search", || with_repo_search(Mode::Dark)),
    ];
    for (name, build) in builders {
        for awful_data in [false, true] {
            for (w, h) in [(1, 1), (20, 5), (80, 24), (3, 40), (200, 2)] {
                let mut state = build();
                if awful_data {
                    stretch(&mut state);
                }
                update(&mut state, Msg::Resize(w, h));
                let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
                terminal
                    .draw(|frame| view(&state, frame, NOW))
                    .unwrap_or_else(|e| panic!("{name} at {w}x{h}: {e}"));
                assert_eq!(terminal.backend().buffer().area.width, w, "{name}");
            }
        }
    }
}

/// The page's lines, as text.
fn page_text(state: &State) -> String {
    let crate::state::Screen::Page(p) = state.screen() else {
        panic!("not a page");
    };
    p.page()
        .lines
        .iter()
        .map(crate::ui::page::PageLine::text)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Delivers a failed fetch of `key`.
fn failed(state: &mut State, key: DataKey) {
    update(
        state,
        Msg::Fetched {
            key,
            result: Err(crate::api::ApiError::Network("timed out".into())),
            cached_at: None,
        },
    );
}

/// A README that fails to load says so where it goes, under the files;
/// the overview (every repository page's header) doesn't depend on it.
#[test]
fn a_failed_readme_says_why_under_the_files() {
    let mut state = state(Mode::Dark, ColorDepth::TrueColor);
    let _ = state.push(Route::Repo(ghtui()));
    let overview = Data::Repo(Box::new(fixtures::overview()));
    fetched(&mut state, DataKey::Repo(ghtui()), overview);
    failed(&mut state, DataKey::Readme(ghtui()));
    let text = page_text(&state);
    assert!(text.contains("Cargo.toml"), "{text}");
    let why = "Couldn't load the README: network error: timed out. r tries again.";
    assert!(text.contains(why), "{text}");
    assert!(state.overview(&ghtui()).is_some());
}

/// A blame whose query fails says so, under the file that loaded.
#[test]
fn a_failed_blame_says_why_instead_of_loading() {
    let mut state = with_repo(Mode::Dark, ColorDepth::TrueColor);
    let (repo, rev, path) = (ghtui(), "main".to_owned(), "src/main.rs".to_owned());
    let blob = DataKey::Blob(repo.clone(), rev.clone(), path.clone());
    let route = Route::Blame {
        repo,
        rev,
        path,
        lines: None,
    };
    let _ = state.push(route.clone());
    fetched(&mut state, blob, Data::Blob(Box::new(fixtures::blob())));
    let Some(Need::Data(key)) = needs(&route).pop() else {
        panic!("a blame fetches its blame");
    };
    failed(&mut state, key);
    let text = page_text(&state);
    assert!(!text.contains("Loading the blame…"), "{text}");
    assert!(text.contains("timed out"), "{text}");
}

/// A pull request whose checks fail to load says so on its Checks tab.
#[test]
fn failed_pr_checks_say_why_instead_of_loading() {
    let mut state = with_pr(Mode::Dark);
    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    let _ = state.push(Route::Pr {
        pr: pr.clone(),
        tab: PrTab::Checks,
    });
    update(&mut state, Msg::Pr(pr.clone(), Box::new(Ok(pr_detail()))));
    let activity = Data::PrActivity(Box::new(fixtures::activity()));
    fetched(&mut state, DataKey::PrActivity(pr.clone()), activity);
    failed(&mut state, DataKey::PrChecks(pr));
    let text = page_text(&state);
    assert!(!text.contains("Loading checks…"), "{text}");
    assert!(text.contains("timed out"), "{text}");
}

/// While a pull request's conversation loads, the timeline under its
/// opening comment goes on to say so.
#[test]
fn a_loading_conversation_stays_on_the_timeline() {
    let mut state = with_home(Mode::Dark, ColorDepth::TrueColor);
    let pr = PrRef::parse("gold-silver-copper/ghtui#12").unwrap();
    let route = Route::pr(pr.clone());
    let _ = state.push(route.clone());
    update(&mut state, Msg::Pr(pr, Box::new(Ok(pr_detail()))));
    let lines: Vec<String> = (state.build_page(&route, 100, NOW).lines.iter())
        .map(crate::ui::page::PageLine::text)
        .collect();
    let at = lines
        .iter()
        .position(|l| l.contains("Loading the conversation…"));
    let above = at.and_then(|at| lines.get(at.checked_sub(1)?));
    assert_eq!(above.map(|l| l.trim()), Some("│"), "{lines:#?}");
}

/// A search that hasn't answered yet says it's searching.
#[test]
fn a_search_in_flight_says_searching() {
    let mut state = with_repo(Mode::Dark, ColorDepth::TrueColor);
    let route = Route::Search {
        kind: SearchKind::Repos,
        query: "ghtui".into(),
    };
    let _ = state.push(route.clone());
    let page = state.build_page(&route, 100, NOW);
    let text: Vec<String> = page
        .lines
        .iter()
        .map(crate::ui::page::PageLine::text)
        .collect();
    assert!(text.iter().any(|l| l.contains("Searching…")), "{text:#?}");
}

/// A workflow whose runs fail to load says so under the workflow.
#[test]
fn failed_workflow_runs_say_why_instead_of_loading() {
    let mut state = with_repo(Mode::Dark, ColorDepth::TrueColor);
    let _ = state.push(Route::Workflow {
        repo: ghtui(),
        file: "ci.yml".into(),
    });
    let (workflow, _) = fixtures::workflow_runs();
    let key = DataKey::Workflow(ghtui(), "ci.yml".into());
    fetched(&mut state, key, Data::Workflow(Box::new(workflow)));
    failed(&mut state, DataKey::WorkflowRuns(ghtui(), "ci.yml".into()));
    let text = page_text(&state);
    assert!(!text.contains("Loading runs…"), "{text}");
    assert!(text.contains("timed out"), "{text}");
}

/// On every page, each need that fails while the others load says why
/// where it goes, and nothing on the page looks like it's still loading.
/// One at a time, so a need shown only once another has loaded (a
/// profile's tab under the profile) fails too.
#[test]
fn every_route_says_why_when_its_needs_fail() {
    fn err<T>() -> Result<T, crate::api::ApiError> {
        Err(crate::api::ApiError::Network("timed out".into()))
    }
    let urls = [
        "https://github.com/",
        "https://github.com/o/r",
        "https://github.com/o/r/tree/main/src",
        "https://github.com/o/r/blob/main/src/main.rs",
        "https://github.com/o/r/blame/main/src/main.rs",
        "https://github.com/o/r/issues",
        "https://github.com/o/r/pulls",
        "https://github.com/search?q=tui&type=repositories",
        "https://github.com/o/r/issues/1",
        "https://github.com/o/r/pull/2",
        "https://github.com/o/r/pull/2/commits",
        "https://github.com/o/r/pull/2/checks",
        "https://github.com/o/r/stargazers",
        "https://github.com/o/r/watchers",
        "https://github.com/o/r/forks",
        "https://github.com/o/r/releases",
        "https://github.com/o/r/releases/tag/v1",
        "https://github.com/o/r/tags",
        "https://github.com/o/r/branches",
        "https://github.com/o/r/milestones",
        "https://github.com/o/r/milestone/1",
        "https://github.com/o/r/compare/a...b",
        "https://github.com/o/r/wiki",
        "https://github.com/o/r/security/advisories",
        "https://github.com/o/r/security/advisories/GHSA-2222-3333-4444",
        "https://github.com/orgs/o/teams",
        "https://github.com/orgs/o/teams/t",
        "https://gist.github.com/o/0123456789abcdef0123",
        "https://gist.github.com/o",
        "https://github.com/o/r/deployments",
        "https://github.com/o/r/discussions",
        "https://github.com/o/r/discussions/3",
        "https://github.com/o/r/actions",
        "https://github.com/o/r/actions/runs/4",
        "https://github.com/o/r/actions/runs/4/job/5",
        "https://github.com/o/r/actions/workflows/ci.yml",
        "https://github.com/o/r/commit/0123456789abcdef0123456789abcdef01234567/checks",
        "https://github.com/o/r/commits/main",
        "https://github.com/o/r/commit/0123456789abcdef0123456789abcdef01234567",
        "https://github.com/o",
        "https://github.com/o?tab=followers",
        "https://github.com/o?tab=repositories",
    ];
    for url in urls {
        let crate::route::Target::Page(route) = crate::route::Dest::from_url(url).target else {
            panic!("{url} isn't a page");
        };
        // The page a plain URL turns out to be.
        let route = route.split(None).unwrap_or(route);
        let all = state(Mode::Dark, ColorDepth::TrueColor).needs(&route);
        for failing in &all {
            let mut state = state(Mode::Dark, ColorDepth::TrueColor);
            let _ = state.push(route.clone());
            for need in all.iter().cloned() {
                let fail = &need == failing;
                let msg = match need {
                    Need::Pr(pr) => {
                        Msg::Pr(pr, Box::new(if fail { err() } else { Ok(pr_detail()) }))
                    }
                    Need::Data(key) => Msg::Fetched {
                        result: if fail { err() } else { Ok(sample(&key)) },
                        key,
                        cached_at: None,
                    },
                };
                update(&mut state, msg);
            }
            let text = page_text(&state);
            let at = format!("{url}, {failing:?} failing:\n{text}");
            assert!(!text.contains("Loading"), "{at}");
            assert_eq!(
                text.contains("timed out"),
                !decoration(&route, failing),
                "{at}"
            );
        }
    }
}

/// A need whose page leaves it out until it loads, saying nothing when it
/// fails: what the header or the chrome shows (counts, tabs, a branch, a
/// commit's title), or the latest commit beside each file.
fn decoration(route: &Route, need: &Need) -> bool {
    use DataKey as K;
    crate::browse::is_header(route, need)
        || matches!(
            (route, need),
            (_, Need::Data(K::LastCommits(..)))
                | (Route::CommitChecks { .. }, Need::Data(K::Commit(..)))
                | (
                    Route::Pr {
                        tab: PrTab::Checks,
                        ..
                    },
                    Need::Data(K::PrActivity(_))
                )
        )
}

/// What GitHub might answer for `key`, for the needs that don't fail.
fn sample(key: &DataKey) -> Data {
    use crate::api::browse::Results;
    use DataKey as K;
    use std::sync::Arc;
    let search = |kind: &SearchKind| match kind {
        SearchKind::Repos => fixtures::repo_results(),
        SearchKind::Issues | SearchKind::Pulls => fixtures::issue_results(None),
        SearchKind::Users => fixtures::user_results(),
        SearchKind::Discussions => fixtures::discussion_results(),
        SearchKind::Commits => fixtures::commit_results(),
        SearchKind::Code => fixtures::code_results(),
    };
    match key {
        K::Repo(_) => Data::Repo(Box::new(fixtures::overview())),
        K::Readme(_) => Data::Readme(Some(Box::new(fixtures::readme()))),
        K::Tree(..) => Data::Tree(fixtures::tree()),
        K::Blob(..) => Data::Blob(Box::new(fixtures::blob())),
        K::Search(kind, _) => Data::Search(Box::new(search(kind))),
        K::Issue(..) => Data::Issue(Some(Box::new(fixtures::issue()))),
        K::PrActivity(_) => Data::PrActivity(Box::new(fixtures::activity())),
        K::Profile(_) => Data::Profile(Box::new(fixtures::profile())),
        K::Files(..) => Data::Files(Arc::new(vec!["README.md".into()]), false),
        K::Refs(_) => Data::Refs(Box::default()),
        K::RefIn(..) => Data::RefIn(None),
        K::LastCommits(..) => Data::LastCommits(Arc::new(fixtures::last_commits())),
        K::Commit(..) => Data::Commit(Box::new(fixtures::commit())),
        K::History(..) => Data::History(Box::new(fixtures::history(None))),
        K::PrChecks(_) | K::BranchChecks(_) | K::CommitChecks(..) => {
            Data::Checks(Box::new(fixtures::checks()))
        }
        K::Users(_) => Data::Users(Box::new(fixtures::people())),
        K::Forks(_) | K::OwnerRepos(..) | K::Stars(_) => {
            Data::RepoPage(Box::new(fixtures::profile_repos()))
        }
        K::Releases(_) => Data::Releases(Box::new(fixtures::releases())),
        K::Release(..) => Data::Release(Box::new(fixtures::release(true))),
        K::Tags(_) => Data::Tags(Box::new(fixtures::tags())),
        K::Branches(_) => Data::Branches(Box::new(fixtures::branches())),
        K::Wiki(..) => Data::Wiki(Box::new(fixtures::wiki())),
        K::Advisories(_) => {
            let items = fixtures::advisories();
            let total = items.len() as u64;
            Data::Advisories(Box::new(Results {
                total,
                items,
                next: None,
            }))
        }
        K::Advisory(..) => Data::Advisory(Box::new(fixtures::advisory())),
        K::Teams(_) => Data::Teams(Box::new(fixtures::teams())),
        K::Team(..) => Data::Team(Box::new(fixtures::team())),
        K::Gist(_) => Data::Gist(Box::new(fixtures::gist())),
        K::Gists(_) => Data::Gists(Box::new(fixtures::gists())),
        K::Blame(..) => Data::Blame(Box::new(fixtures::blame())),
        K::Compare(..) => Data::Compare(Box::new(fixtures::comparison())),
        K::Deployments(..) => Data::Deployments(Box::new(fixtures::deployments())),
        K::Milestones(..) => Data::Milestones(Box::new(fixtures::milestones())),
        K::Milestone(..) => Data::Milestone(Box::new(fixtures::milestone())),
        K::Discussions(..) => Data::Discussions(Box::new(fixtures::discussions())),
        K::Discussion(..) => Data::Discussion(Box::new(fixtures::discussion())),
        K::Run(..) => Data::Run(Box::new(fixtures::workflow_run())),
        K::Job(..) => Data::Job(Box::new(fixtures::job().0)),
        K::JobLog(..) => Data::Log(Arc::new(fixtures::job().1)),
        K::Workflow(..) => Data::Workflow(Box::new(fixtures::workflow_runs().0)),
        K::WorkflowRuns(..) => Data::Runs(Box::new(fixtures::workflow_runs().1)),
    }
}

/// Changing GitHub: each action asks first where it should, says why
/// when it can't, sends one change, and ends up showing what GitHub says.
mod changes {
    use crate::api::ApiError;
    use crate::api::browse::{CheckOutcome, IssueState, PrState, Status};
    use crate::api::change::{Change, MergeMethod};
    use crate::api::model::{MergeState, NodeId, PrRef, ReviewEvent};
    use crate::store::{DraftComment, DraftSide, ReviewState};
    use crate::theme::Mode;

    use super::{ghtui, pr_detail, render, with_job, with_pr, with_repo, with_run};
    use crate::act::{By, Subject};
    use crate::browse::{Data, DataKey};
    use crate::fixtures::{answer, fetched, press, says, warns};
    use crate::keymap::Action;
    use crate::review::SubmitOutcome;
    use crate::route::Route;
    use crate::state::{Api, Cmd, DiffMsg, Msg, Overlay, State, Timer, timers, update};

    fn pr() -> PrRef {
        PrRef::parse("gold-silver-copper/ghtui#12").unwrap()
    }

    fn confirm(s: &State) -> &crate::act::Confirm {
        match &s.overlay {
            Some(Overlay::Confirm(c)) => c,
            _ => panic!("no confirmation"),
        }
    }

    /// A pull request whose state is `state`.
    fn pr_in(state: PrState) -> State {
        pr_with(|d| d.state = state)
    }

    /// The pull request, changed by `f`.
    fn pr_with(f: impl FnOnce(&mut crate::api::model::PrDetail)) -> State {
        let mut s = with_pr(Mode::Dark);
        update(&mut s, Msg::Pr(pr(), Box::new(Ok(mergeable(f)))));
        s
    }

    /// The pull request without its conflicts (GitHub would merge it),
    /// changed by `f`.
    fn mergeable(f: impl FnOnce(&mut crate::api::model::PrDetail)) -> crate::api::model::PrDetail {
        let mut detail = pr_detail();
        detail.mergeable = crate::api::model::Mergeable::Yes;
        detail.merge_state = MergeState::Unstable;
        f(&mut detail);
        detail
    }

    #[test]
    fn merge_confirm_dark() {
        let mut s = pr_with(|_| {});
        press(&mut s, "M");
        insta::assert_snapshot!(render(&s));
    }

    /// Merging asks first, saying what stands in the way; a refusal stays
    /// in the dialog, with the permission it needs; once GitHub says it's
    /// merged, the pull request is fetched again.
    #[test]
    fn merging_asks_first_and_ends_up_as_github_has_it() {
        let mut s = pr_with(|_| {});
        assert!(press(&mut s, "M").is_empty());
        let c = confirm(&s);
        let problems: Vec<&str> = (c.facts.iter())
            .filter(|(_, p)| *p)
            .map(|(f, _)| f.as_str())
            .collect();
        assert_eq!(problems, ["Some checks failed"], "{:?}", c.facts);
        assert!(
            c.facts
                .iter()
                .any(|(f, _)| f == "Its branch is 2 commits behind main (B updates it)"),
            "{:?}",
            c.facts
        );
        let methods: Vec<&str> = c.choices.iter().map(|(l, _)| l.as_str()).collect();
        assert_eq!(methods, ["Squash and merge", "Create a merge commit"]);
        press(&mut s, "<Tab>");
        let merge = Change::Merge {
            pr: NodeId::new("PR_12"),
            method: MergeMethod::Merge,
            head: pr_detail().head_oid,
        };
        let sent = press(&mut s, "<Enter>");
        assert_eq!(
            sent,
            vec![Cmd::Api(Api::Change(merge, By::Confirm(Subject::Pr(pr()))))]
        );
        assert!(confirm(&s).sending);
        // Keys wait while it's sent.
        assert!(press(&mut s, "<Enter>").is_empty());

        let refused = ApiError::GraphQl(vec!["Must have push access to repository".into()]);
        answer(&mut s, &sent, Err(refused));
        let error = confirm(&s).error.clone().unwrap_or_default();
        assert!(error.contains("Must have push access"), "{error}");
        assert!(error.contains("Contents: write"), "{error}");
        assert!(!confirm(&s).sending);

        press(&mut s, "<Enter>");
        let cmds = answer(&mut s, &sent, Ok(()));
        assert!(s.overlay.is_none());
        says(&s, "Merged");
        assert!(
            cmds.contains(&Cmd::Api(Api::FetchPr(pr()))),
            "the pull request is fetched again: {cmds:?}"
        );
        // Until GitHub shows it merged, nothing else is offered.
        press(&mut s, "X");
        says(&s, "hasn't shown the last change");
        let merged = mergeable(|d| d.state = PrState::Merged);
        update(&mut s, Msg::Pr(pr(), Box::new(Ok(merged))));
        assert!(s.awaiting.is_none());
    }

    /// On Home, an action works on the selected row: the pull request
    /// loads, then the dialog opens about it, and stays about it when the
    /// list changes under it. Once GitHub shows the merge, Home is fetched
    /// again.
    #[test]
    fn acting_on_a_homes_row_is_about_that_row() {
        let mut s = super::with_home(Mode::Dark, crate::theme::ColorDepth::TrueColor);
        s.prs.clear();
        press(&mut s, "jj");
        let cmds = press(&mut s, "M");
        assert_eq!(cmds, vec![Cmd::Api(Api::FetchPr(pr()))]);
        says(&s, "Loading gold-silver-copper/ghtui#12");
        update(&mut s, Msg::Pr(pr(), Box::new(Ok(mergeable(|_| {})))));
        assert_eq!(confirm(&s).about, Subject::Pr(pr()));
        assert!(
            confirm(&s)
                .title
                .starts_with("Merge gold-silver-copper/ghtui#12")
        );
        // The list moves; the dialog is still about #12.
        press(&mut s, "<Esc>");
        press(&mut s, "M");
        let mine = crate::fixtures::found_prs(Vec::new(), 0);
        crate::fixtures::section(&mut s, 1, mine);
        assert_eq!(confirm(&s).about, Subject::Pr(pr()));
        let sent = press(&mut s, "<Enter>");
        answer(&mut s, &sent, Ok(()));
        let w = s.awaiting.clone().unwrap();
        assert_eq!(
            (w.route, w.about),
            (Route::Home, crate::act::Subject::Pr(pr()))
        );
        // Home asked again at once; GitHub's search may not show it yet.
        for i in 0..2 {
            let none = crate::fixtures::found_prs(Vec::new(), 0);
            crate::fixtures::section(&mut s, i, none);
        }
        let merged = mergeable(|d| d.state = PrState::Merged);
        let cmds = update(&mut s, Msg::Pr(pr(), Box::new(Ok(merged))));
        assert!(s.awaiting.is_none());
        let home = s.home[1].search.clone().unwrap().key();
        let refetched = |c: &Cmd| matches!(c, Cmd::Api(Api::Fetch { key, .. }) if *key == home);
        assert!(cmds.iter().any(refetched), "{cmds:?}");
        // An issue row offers closing, not merging.
        crate::fixtures::section(
            &mut s,
            1,
            crate::fixtures::found_prs(
                vec![crate::fixtures::issue_summary(
                    3,
                    Status::Issue(IssueState::Open),
                )],
                1,
            ),
        );
        press(&mut s, "gjj");
        press(&mut s, "M");
        says(&s, "That works on a pull request");
    }

    /// Updating the branch, the page follows GitHub until it shows the new
    /// head (GitHub moves it after it answers), and merging then names that
    /// head: merging the old one is refused as "Head branch was modified".
    #[test]
    fn after_updating_the_branch_merging_waits_for_the_new_head() {
        // Behind, though the repository doesn't require it up to date.
        let mut s = pr_with(|_| {});
        press(&mut s, "B");
        let update_branch = Change::UpdateBranch {
            pr: NodeId::new("PR_12"),
            rebase: false,
            head: pr_detail().head_oid,
        };
        assert_eq!(confirm(&s).choices[0].1, update_branch);
        assert_eq!(
            confirm(&s).facts[0].0,
            "Its branch, syntax-palette, is 2 commits behind main; updating pushes to it"
        );
        let sent = press(&mut s, "<Enter>");
        answer(&mut s, &sent, Ok(()));
        // GitHub still shows the old head.
        update(&mut s, Msg::Pr(pr(), Box::new(Ok(mergeable(|_| {})))));
        press(&mut s, "M");
        says(&s, "hasn't shown the last change");
        let cmds = timers(&mut s);
        assert!(cmds.contains(&Cmd::Timer(Timer::Live, 5_000)), "{cmds:?}");
        let cmds = update(&mut s, Msg::Timer(Timer::Live));
        assert!(cmds.contains(&Cmd::Api(Api::FetchPr(pr()))), "{cmds:?}");
        let moved = mergeable(|d| {
            d.head_oid = "1".repeat(40);
            d.behind_by = Some(0);
        });
        update(&mut s, Msg::Pr(pr(), Box::new(Ok(moved))));
        press(&mut s, "M");
        let head = match &confirm(&s).choices[0].1 {
            Change::Merge { head, .. } => head.clone(),
            other => panic!("{other:?}"),
        };
        assert_eq!(head, "1".repeat(40));
        press(&mut s, "<Esc>");
        press(&mut s, "B");
        says(&s, "It's up to date with main");
    }

    /// What GitHub says you may not do is refused, saying why, and what
    /// GitHub says stops a merge is refused before asking.
    #[test]
    fn what_github_forbids_is_refused() {
        let mut s = pr_with(|d| d.may = crate::api::model::PrPermits::default());
        press(&mut s, "M");
        says(&s, "Merging takes write access to gold-silver-copper/ghtui");
        press(&mut s, "X");
        says(&s, "GitHub doesn't let you close it");
        press(&mut s, "B");
        says(&s, "which you can't push to");

        let mut s = with_pr(Mode::Dark);
        press(&mut s, "M");
        says(&s, "It conflicts with main: resolve that on GitHub");
        let mut s = pr_with(|d| d.merge_state = MergeState::Blocked);
        press(&mut s, "M");
        says(&s, "blocked");
        let mut s = pr_with(|d| d.merge_state = MergeState::Behind);
        press(&mut s, "M");
        says(&s, "B updates it");

        let mut s = with_run(Mode::Dark);
        let mut repo = crate::fixtures::overview();
        repo.can_write = false;
        fetched(&mut s, DataKey::Repo(ghtui()), Data::Repo(Box::new(repo)));
        press(&mut s, "<C-r>");
        says(
            &s,
            "Re-running and cancelling take write access to gold-silver-copper/ghtui",
        );
    }

    /// An action that can't apply says why, on the key and in the menu
    /// alike, and sends nothing.
    #[test]
    fn what_cant_be_done_says_why() {
        let mut s = pr_in(PrState::Merged);
        assert!(press(&mut s, "M").is_empty());
        assert!(s.overlay.is_none());
        says(&s, "It's merged");
        let merge = (s.doables().into_iter())
            .find(|d| d.action == Action::Merge)
            .unwrap();
        assert_eq!(merge.unavailable.as_deref(), Some("It's merged"));
        press(&mut s, "X");
        says(&s, "can't be reopened");

        let mut s = with_pr(Mode::Dark);
        press(&mut s, "W");
        says(&s, "It isn't a draft");
        s.viewer = Some(pr_detail().author);
        press(&mut s, "A");
        says(&s, "You can't approve your own pull request");

        let mut s = with_repo(Mode::Dark, crate::theme::ColorDepth::TrueColor);
        press(&mut s, "M");
        says(&s, "That works on a pull request (or its row in a list)");
        press(&mut s, "<C-r>");
        says(&s, "Re-running works on a workflow run or a job");
    }

    /// Marking a draft ready asks nothing: it's sent at once. GitHub's
    /// answer goes back to what sent it: a dialog or a comment opened while
    /// it's on its way is left as it is.
    #[test]
    fn a_draft_is_marked_ready_at_once_and_hears_back_alone() {
        let mut s = pr_in(PrState::Draft);
        let ready = Change::ReadyForReview {
            pr: NodeId::new("PR_12"),
        };
        let sent = press(&mut s, "W");
        assert_eq!(
            sent,
            vec![Cmd::Api(Api::Change(ready, By::Act(Subject::Pr(pr()))))]
        );
        press(&mut s, "X");
        let refused = ApiError::GraphQl(vec!["Not now".into()]);
        answer(&mut s, &sent, Err(refused));
        assert_eq!(confirm(&s).error, None);
        warns(&s, "Not now");
        press(&mut s, "<Esc>WcLGTM");
        answer(&mut s, &sent, Ok(()));
        says(&s, "Ready for review");
        assert!(
            matches!(&s.overlay, Some(Overlay::Compose(c)) if c.text() == "LGTM"),
            "the comment is still being written"
        );
    }

    /// A star answered while a re-run from a list's row is on its way, or
    /// once GitHub accepted it, leaves the page following that run.
    #[test]
    fn a_star_leaves_the_wait_for_another_change_alone() {
        let mut s = super::with_workflow(Mode::Dark);
        let run = Data::Run(Box::new(crate::fixtures::workflow_run()));
        fetched(&mut s, DataKey::Run(ghtui(), 7, None), run);
        let rerun = press(&mut s, "<C-r><Enter>");
        press(&mut s, "<Esc>");
        let star = press(&mut s, "s");
        answer(&mut s, &star, Ok(()));
        answer(&mut s, &rerun, Ok(()));
        // The page follows the run, not the list.
        let run = vec![crate::browse::Need::Data(DataKey::Run(ghtui(), 7, None))];
        assert_eq!(crate::act::poll(&mut s), run);
        answer(&mut s, &star, Ok(()));
        assert_eq!(crate::act::poll(&mut s), run);
    }

    /// Approving from the pull request's page reads your saved drafts
    /// first, submits them with the approval, and saves what's left.
    #[test]
    fn approving_from_the_page_takes_your_saved_drafts() {
        let mut s = with_pr(Mode::Dark);
        s.viewer = Some("me".into());
        assert_eq!(
            press(&mut s, "A"),
            vec![
                Cmd::Api(Api::FetchPendingReview(pr())),
                Cmd::LoadReview(pr())
            ]
        );
        let Some(Overlay::Submit(dialog)) = &s.overlay else {
            panic!("no dialog");
        };
        assert_eq!((dialog.event, dialog.quick), (ReviewEvent::Approve, true));
        // Enter before the drafts are read waits for them.
        assert!(press(&mut s, "<Enter>").is_empty());

        let draft = DraftComment {
            id: 3,
            path: "src/lib.rs".into(),
            body: "nit".into(),
            side: DraftSide::Right,
            line: Some(4),
            start_line: None,
            start_side: None,
            commit: pr_detail().head_oid,
            error: None,
        };
        let saved = ReviewState {
            pending: vec![draft.clone()],
            ..ReviewState::default()
        };
        update(
            &mut s,
            Msg::Diff(pr().into(), DiffMsg::ReviewLoaded(Ok(saved))),
        );
        press(&mut s, "LGTM");
        let cmds = press(&mut s, "<Enter>");
        assert_eq!(
            cmds,
            vec![Cmd::Api(Api::SubmitReview {
                pr: pr(),
                head: crate::git::Oid::parse(&pr_detail().head_oid).unwrap(),
                drafts: vec![draft],
                event: ReviewEvent::Approve,
                body: "LGTM".into(),
                seen: 0,
            })]
        );
        let outcome = SubmitOutcome {
            accepted: vec![3],
            submitted: true,
            ..SubmitOutcome::default()
        };
        let cmds = update(
            &mut s,
            Msg::Diff(pr().into(), DiffMsg::ReviewSubmitted(outcome)),
        );
        assert!(s.overlay.is_none());
        says(&s, "Approved gold-silver-copper/ghtui#12");
        let left = ReviewState {
            last_reviewed_head: Some(pr_detail().head_oid),
            ..ReviewState::default()
        };
        assert!(cmds.contains(&Cmd::SaveReview(pr(), left)), "{cmds:?}");
    }

    /// A finished run offers its failed jobs or all of them; a job adds
    /// itself; a finished run has nothing to cancel.
    #[test]
    fn runs_rerun_and_cancel() {
        let mut s = with_run(Mode::Dark);
        press(&mut s, "<C-r>");
        let choices: Vec<&str> = confirm(&s)
            .choices
            .iter()
            .map(|(l, _)| l.as_str())
            .collect();
        assert_eq!(choices, ["Re-run failed jobs", "Re-run all jobs"]);
        assert_eq!(
            press(&mut s, "<Enter>"),
            vec![Cmd::Api(Api::Change(
                Change::Rerun {
                    repo: ghtui(),
                    run: 7,
                    failed_only: true
                },
                By::Confirm(Subject::Run(ghtui(), 7, None))
            ))]
        );
        let mut s = with_run(Mode::Dark);
        press(&mut s, "X");
        says(&s, "The run has finished: there's nothing to cancel");

        let mut s = with_job(Mode::Dark, None);
        press(&mut s, "<C-r>");
        assert_eq!(confirm(&s).title, "Re-run CI #412?");
        let first = confirm(&s).choices.first().map(|(l, _)| l.clone());
        assert_eq!(first.as_deref(), Some("Re-run this job"));
    }

    /// A job that ended in a run still going is the run's to cancel, and
    /// not to re-run yet.
    #[test]
    fn a_finished_job_in_a_running_run_cancels_the_run() {
        let mut s = with_job(Mode::Dark, None);
        let (mut job, _) = crate::fixtures::job();
        job.run.outcome = CheckOutcome::Pending;
        fetched(
            &mut s,
            DataKey::Job(ghtui(), 2),
            Data::Job(Box::new(job.clone())),
        );
        press(&mut s, "<C-r>");
        says(&s, "The run is still going: X cancels it");
        press(&mut s, "X");
        assert_eq!(confirm(&s).title, "Cancel CI #412?");
        let cancel = Change::CancelRun {
            repo: ghtui(),
            run: 7,
        };
        let sent = press(&mut s, "<Enter>");
        assert_eq!(
            sent,
            vec![Cmd::Api(Api::Change(
                cancel,
                By::Confirm(Subject::Job(ghtui(), Some(7), 2))
            ))]
        );
        answer(&mut s, &sent, Ok(()));
        // GitHub takes a while to stop it: it's asked for once.
        press(&mut s, "X");
        says(&s, "hasn't shown the last change");
        assert!(s.busy().is_some_and(|b| b.starts_with("Cancel requested")));
        job.run.outcome = CheckOutcome::Cancelled;
        fetched(&mut s, DataKey::Job(ghtui(), 2), Data::Job(Box::new(job)));
        assert!(s.awaiting.is_none());
    }

    /// Re-running a job, the page moves to the job GitHub re-runs it as,
    /// once GitHub has it, and follows that one.
    #[test]
    fn a_rerun_job_is_followed_to_its_new_attempt() {
        let mut s = with_job(Mode::Dark, None);
        let rerun = Change::RerunJob {
            repo: ghtui(),
            job: 2,
        };
        let by = By::Confirm(Subject::Job(ghtui(), Some(7), 2));
        update(&mut s, Msg::Changed(rerun, by, Ok(())));
        let (mut job, _) = crate::fixtures::job();
        job.run.attempt = 2;
        job.run.outcome = CheckOutcome::Pending;
        fetched(
            &mut s,
            DataKey::Job(ghtui(), 2),
            Data::Job(Box::new(job.clone())),
        );
        assert!(
            matches!(s.route(), Some(Route::Job { job: 2, .. })),
            "not there yet"
        );
        job.run.rerun = Some(9);
        let cmds = update(
            &mut s,
            Msg::Fetched {
                key: DataKey::Job(ghtui(), 2),
                result: Ok(Data::Job(Box::new(job))),
                cached_at: None,
            },
        );
        assert!(
            matches!(s.route(), Some(Route::Job { job: 9, .. })),
            "{:?}",
            s.route()
        );
        let fetch = Cmd::Api(Api::Fetch {
            key: DataKey::Job(ghtui(), 9),
            cached: true,
        });
        assert!(cmds.contains(&fetch), "{cmds:?}");
    }

    /// While a job on screen is running, it's fetched again on a timer
    /// (never two at once); once it's done, the timer stops.
    #[test]
    fn a_running_job_is_followed_until_it_ends() {
        let mut s = with_job(Mode::Dark, None);
        let live = Cmd::Timer(Timer::Live, 5_000);
        assert!(
            !timers(&mut s).contains(&live),
            "a finished job isn't followed"
        );
        let (mut job, mut log) = crate::fixtures::job();
        job.outcome = CheckOutcome::Pending;
        log.running = true;
        fetched(
            &mut s,
            DataKey::Job(ghtui(), 2),
            Data::Job(Box::new(job.clone())),
        );
        fetched(
            &mut s,
            DataKey::JobLog(ghtui(), 2),
            Data::Log(std::sync::Arc::new(log)),
        );
        let cmds = timers(&mut s);
        assert!(cmds.contains(&live), "{cmds:?}");
        assert!(!timers(&mut s).contains(&live), "one timer at a time");
        let cmds = update(&mut s, Msg::Timer(Timer::Live));
        let fetch = |key| Cmd::Api(Api::Fetch { key, cached: false });
        assert!(cmds.contains(&fetch(DataKey::Job(ghtui(), 2))), "{cmds:?}");
        assert!(
            cmds.contains(&fetch(DataKey::JobLog(ghtui(), 2))),
            "{cmds:?}"
        );
        // It ends: no more fetching.
        job.outcome = CheckOutcome::Failure;
        let (_, log) = crate::fixtures::job();
        fetched(&mut s, DataKey::Job(ghtui(), 2), Data::Job(Box::new(job)));
        fetched(
            &mut s,
            DataKey::JobLog(ghtui(), 2),
            Data::Log(std::sync::Arc::new(log)),
        );
        assert!(s.running_here().is_empty());
    }
}