diffler 0.16.1

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
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
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
//! Diff/review screen state and handlers: a file sidebar listing every file
//! in the diff, and a pane showing only the selected file's hunks, lines, and
//! inline comments, flattened into a row list so the renderer only ever
//! materializes the visible slice.

mod comments;
mod folds;
mod nav;
mod open;
mod review;
mod rowref;
mod rows;
mod slide;

use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap, HashSet};

use diffler_core::classify::{Kind, Rules};
use diffler_core::highlight::StyledRange;
use diffler_core::model::{DiffLine, DiffModel, FileDiff};
use diffler_core::review::Review;
use diffler_core::session::Session;
use diffler_core::source::ReviewSource;
use diffler_core::syntax::ScopeIndex;
use diffler_core::walkthrough::Located;

use super::composer::{Composer, ComposerKind};
use super::rowsel::{RowSelect, RowText};
use super::{App, Flow};
pub use comments::{CommentFacts, CommentGrouping, CommentPaneRow, group_comment_rows};
pub(crate) use rowref::RowPositions;
pub use rows::{
    CommentLine, DiffRow, RowCopy, SplitRow, SplitSide, blocks_of, comment_display, summary_display,
};
use rows::{build_rows, build_split_rows};
#[cfg(test)]
pub(crate) use slide::merge_count;
use slide::stop_file_index;
pub(crate) use slide::{Slide, stop_row_offset};

use crate::app::walkthrough::FigureCache;
use crate::config::FileLayout;
use crate::tree::{self, Bucket, TreeNode, TreeRow};

/// Which pane has the keyboard: the file sidebar or the diff body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    List,
    Diff,
    /// The comments sidebar on the right, open only while `comments_open`.
    Comments,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollAlign {
    Center,
    Top,
    Bottom,
}

/// Which section headers are collapsed, across both layouts that have them.
/// What the reader did not come to read starts folded: the viewed pile, and
/// the two kinds nobody reviews by hand.
#[derive(Debug, Clone)]
pub(crate) struct BucketFolds(BTreeSet<Bucket>);

impl Default for BucketFolds {
    fn default() -> Self {
        Self(
            [
                Bucket::Viewed,
                Bucket::Kind(Kind::Generated),
                Bucket::Kind(Kind::Assets),
            ]
            .into(),
        )
    }
}

impl BucketFolds {
    fn is_folded(&self, bucket: Bucket) -> bool {
        self.0.contains(&bucket)
    }

    fn toggle_fold(&mut self, bucket: Bucket) {
        if !self.0.remove(&bucket) {
            self.0.insert(bucket);
        }
    }

    /// Open a section, reporting whether it had been folded.
    fn unfold(&mut self, bucket: Bucket) -> bool {
        self.0.remove(&bucket)
    }
}

/// Per-line syntax spans for both sides of one file, keyed by the
/// both-sides content hash so edits to either side invalidate naturally.
/// Filled by the background enrichment worker.
#[derive(Debug, Clone)]
pub struct FileHighlights {
    pub hash: String,
    pub old: Vec<Vec<StyledRange>>,
    pub new: Vec<Vec<StyledRange>>,
}

/// Enclosing-definition index for one file's new-side content, keyed by the
/// both-sides hash so edits invalidate it. Drives the sticky scope breadcrumb.
#[derive(Debug)]
pub struct FileScope {
    pub hash: String,
    pub index: ScopeIndex,
}

#[allow(clippy::struct_excessive_bools)] // independent view toggles, not a state enum
pub struct DiffView {
    pub source: ReviewSource,
    /// A commit's diff is immutable: fetched once at open and kept here.
    /// `None` means the view reads the live `review.model`.
    pub(crate) commit_model: Option<DiffModel>,
    pub focus: Pane,
    /// File-list layout for the sidebar: a flat list or a collapsible tree.
    /// Pinned at open from `ui.diff_file_layout`.
    pub(crate) layout: FileLayout,
    /// Index into `model.files`: the file shown in the diff pane. Derived from
    /// the file under `tree_cursor` whenever that lands on a File row.
    pub selected: usize,
    /// Folded directory paths in the sidebar tree; persists across refresh.
    /// Unused in the flat list (it has no directories).
    pub(crate) folded_dirs: BTreeSet<String>,
    /// Section-header folds, shared by the review and kinds layouts.
    pub(crate) bucket_folds: BucketFolds,
    /// How the kinds layout buckets a path: the built-in table under the
    /// reader's `[classify]` globs. Pinned at open.
    pub(crate) rules: Rules,
    /// What the repo's own git attributes declare, for the files of the diff
    /// the kinds layout is showing. Filled from the backend when that layout
    /// is on, so the per-frame row build stays a pure path lookup.
    pub(crate) declared: HashMap<String, Kind>,
    /// Cursor into the current visible sidebar tree rows (dirs and files).
    pub(crate) tree_cursor: usize,
    /// Row within the selected file's rows.
    pub cursor: usize,
    /// Rows a walkthrough stop's anchor covers, banded so a reference reads as
    /// the segment it names rather than the line it starts on.
    pub(crate) referenced: Option<(usize, usize)>,
    /// The slide the walkthrough layout is windowed to. `None` defaults to
    /// the first stop, the way a freshly opened walkthrough view does.
    pub(crate) slide: Option<Slide>,
    /// Id and time of this source's walkthrough as the open rows were built
    /// for it, so an agent revising it under a reader is noticed.
    pub(crate) walkthrough_built: Option<(String, u64)>,
    /// Parsed bodies of the comments that hold a figure, so a diagram is
    /// parsed when it changes and not on every frame that draws a row of it.
    pub(crate) figures: FigureCache,
    /// A figure was parsed afresh, so its `click` targets still need reading.
    figures_dirty: bool,
    /// Stop and note comments whose `anchor_ref` stopped resolving, and why:
    /// the file itself is missing, or the symbol/line named inside it is
    /// gone. Only the worker can tell one from the other, or from a comment
    /// that has not been resolved yet at all.
    pub(crate) unresolved_anchors: HashMap<String, Located>,
    /// The walkthrough's own pin no longer resolves: the worker fell back to
    /// the worktree for every file, and the reader is shown live code
    /// believing it is pinned. Set by the last landed anchor resolution.
    pub(crate) pin_broken: bool,
    /// First visible row of the diff pane; the renderer keeps the cursor in
    /// view.
    pub scroll: usize,
    /// Applied once the renderer knows the wrapped row heights, then cleared.
    pub(crate) scroll_align: Option<ScrollAlign>,
    /// Side-by-side (old left / new right) pane; pinned at open from
    /// `ui.side_by_side`, then `|` toggles it live.
    pub side_by_side: bool,
    /// First visible split row while `side_by_side` is on; the renderer keeps
    /// the cursor's line in view.
    pub(crate) split_scroll: usize,
    /// Last render's sidebar/pane rects and sidebar scroll, for mouse
    /// hit-testing. The pane's own scroll is `scroll` / `split_scroll`.
    pub(crate) sidebar: ratatui::layout::Rect,
    pub(crate) sidebar_scroll: usize,
    pub(crate) pane: ratatui::layout::Rect,
    /// The comments sidebar: open state, which comment is selected, and the
    /// last render's rect and scroll for hit-testing, mirroring the file list.
    pub(crate) comments_open: bool,
    pub(crate) comments_cursor: usize,
    pub(crate) comments_scroll: usize,
    pub(crate) comments_rect: ratatui::layout::Rect,
    /// Last render's comment-sidebar line -> row index (into
    /// `App::comment_rows`), so a click on any wrapped body line selects the
    /// row it belongs to, header or comment alike.
    pub(crate) comment_lines: Vec<Option<usize>>,
    /// Comments-pane grouping cycled by `t` while it holds focus, independent
    /// of the file sidebar's own layout.
    pub(crate) comment_grouping: CommentGrouping,
    /// Folded comments-pane group keys, namespaced per grouping (`file:`,
    /// `author:`, `status:`) so switching grouping with `t` never confuses one
    /// group's fold state for another's.
    pub(crate) comment_folds: BTreeSet<String>,
    /// Row where `V` started; `Some` means line selection is active.
    pub visual_anchor: Option<usize>,
    /// Body height of the last diff-pane render, drives half-page motions.
    pub(crate) viewport: u16,
    /// The open in-place comment editor, if any. It owns the diff pane's keys
    /// while it is up and occupies the rows its result will.
    pub(crate) composer: Option<Composer>,
    /// Rows for the selected file only.
    pub(crate) rows: Vec<DiffRow>,
    /// What a visual selection yanks for each of `rows`, same length, built
    /// alongside it. A figure entry starts as a lookup key; the render pass
    /// that draws the same figure patches its box-drawing text in once it runs.
    pub(crate) row_copy: Vec<RowCopy>,
    /// Last render's pane line -> row index table; wrapped rows span several
    /// lines, so mouse hits map back through it.
    pub(crate) line_rows: Vec<Option<usize>>,
    rows_dirty: bool,
    /// Pane row width comments wrap to; set from the last draw, MAX until
    /// the first frame so unit tests see unwrapped lines.
    pub(crate) wrap_width: u16,
    /// Rows need a re-flow for a new wrap width (no content change).
    wrap_dirty: bool,
    /// Side-by-side row model, rebuilt with `rows` (not per frame).
    pub(crate) split_rows: Vec<SplitRow>,
    pub(crate) highlights: HashMap<String, FileHighlights>,
    pub(crate) scopes: HashMap<String, FileScope>,
    /// Paths whose intra-line emphasis has been computed, so the per-file
    /// enrichment runs once. Cleared whenever the underlying model is
    /// rebuilt (refresh) so a fresh unenriched file gets re-enriched.
    enriched: HashSet<String>,
    /// Per-file diff context override (path -> git context lines, `u32::MAX`
    /// for the whole file). Absent means the source's default context.
    pub(crate) context: HashMap<String, u32>,
    /// One `Unchanged` file per stop or note the active walkthrough anchors
    /// outside the diff, filled in once the anchor worker reads them. Read
    /// only by the walkthrough layout, through [`DiffView::model_for_rows`]
    /// and [`DiffView::model_for_layout`]; every other layout sees the diff
    /// alone.
    pub(crate) context_files: Vec<FileDiff>,
    /// What [`Self::ensure_rows`] last merged `context_files` into: `Some`
    /// when there was anything to append, `None` when the base model alone
    /// covers the layout, so the render path (`draw_pane`, every frame) reads
    /// this instead of rebuilding the merge itself. `on_enriched` mirrors a
    /// landed file's hunks in here too, since the merge is a snapshot taken
    /// before enrichment runs.
    pub(crate) merged_model: Option<DiffModel>,
    /// The image file preview the pane draws, once the worker built it.
    pub(crate) image_preview: Option<crate::app::image::ImagePreview>,
    /// The image the last draw showed, which `App::queue_image_preview`
    /// turns into a request.
    pub(crate) image_want: Option<crate::app::image::ImageKey>,
    /// What each unified `DiffRow::Fold` row stands for.
    pub(crate) fold_groups: Vec<folds::FoldGroup>,
    /// The hunks the reader folded, by file path then [`folds::hunk_key`].
    folded: HashMap<String, HashSet<String>>,
    /// The selected file's path as of the last row rebuild, so a fold verb
    /// can key into `folded` without needing the review in hand.
    rows_path: String,
}

impl DiffView {
    fn new(
        source: ReviewSource,
        commit_model: Option<DiffModel>,
        review: &Review,
        layout: FileLayout,
        rules: Rules,
        side_by_side: bool,
    ) -> Self {
        let mut view = Self {
            composer: None,
            source,
            commit_model,
            focus: Pane::List,
            layout,
            selected: 0,
            folded_dirs: BTreeSet::new(),
            bucket_folds: BucketFolds::default(),
            rules,
            declared: HashMap::new(),
            tree_cursor: 0,
            cursor: 0,
            referenced: None,
            slide: None,
            walkthrough_built: None,
            figures: FigureCache::new(),
            figures_dirty: false,
            unresolved_anchors: HashMap::new(),
            pin_broken: false,
            scroll: 0,
            scroll_align: None,
            side_by_side,
            split_scroll: 0,
            sidebar: ratatui::layout::Rect::default(),
            sidebar_scroll: 0,
            pane: ratatui::layout::Rect::default(),
            comments_open: false,
            comments_cursor: 0,
            comments_scroll: 0,
            comments_rect: ratatui::layout::Rect::default(),
            comment_lines: Vec::new(),
            comment_grouping: CommentGrouping::Flat,
            comment_folds: BTreeSet::from([comments::RESOLVED_FOLD_KEY.to_owned()]),
            visual_anchor: None,
            viewport: 0,
            rows: Vec::new(),
            row_copy: Vec::new(),
            line_rows: Vec::new(),
            rows_dirty: true,
            wrap_width: u16::MAX,
            wrap_dirty: false,
            split_rows: Vec::new(),
            highlights: HashMap::new(),
            scopes: HashMap::new(),
            enriched: HashSet::new(),
            context: HashMap::new(),
            context_files: Vec::new(),
            merged_model: None,
            image_preview: None,
            image_want: None,
            fold_groups: Vec::new(),
            folded: HashMap::new(),
            rows_path: String::new(),
        };
        view.ensure_rows(review);
        view
    }

    pub fn model<'a>(&'a self, review: &'a Review) -> &'a DiffModel {
        self.commit_model.as_ref().unwrap_or_else(|| review.model())
    }

    /// The model every row index (`selected`, a `DiffRow`'s file index, a
    /// comment's anchor path) resolves against for `layout`: `base` extended
    /// with `context_files` where the walkthrough layout is windowing to
    /// one, `base` alone everywhere else, since no other layout ever builds
    /// a row against a context file. A free-standing function for the same
    /// borrow-checker reason as `model_with_context`: composing it from
    /// explicit field refs keeps a caller's other field borrows disjoint
    /// from the model it still holds.
    pub(crate) fn model_for_layout<'a>(
        layout: FileLayout,
        base: &'a DiffModel,
        context_files: &'a [FileDiff],
    ) -> Cow<'a, DiffModel> {
        let context: &[FileDiff] = if layout == FileLayout::Walkthrough {
            context_files
        } else {
            &[]
        };
        Self::model_with_context(base, context)
    }

    /// What the last [`Self::ensure_rows`] merged, for a caller that must not
    /// rebuild it: `cached` (the view's own `merged_model`) when it holds
    /// one, `base` otherwise. Free-standing for the same borrow-checker
    /// reason as `model_with_context`: the render path holds other disjoint
    /// borrows of the view (and mutates several of its fields) while this
    /// reference is still alive, which a `&self` method would collide with.
    pub(crate) fn rendered_model<'a>(
        cached: Option<&'a DiffModel>,
        base: &'a DiffModel,
    ) -> &'a DiffModel {
        cached.unwrap_or(base)
    }

    /// [`Self::model_for_layout`] against this view's own base and context,
    /// for a caller that only reads: it borrows all of `self`, so a caller
    /// that also mutates another field while the result is alive (building
    /// rows, seating a stop) needs the free function above instead.
    pub(crate) fn model_for_rows<'a>(&'a self, review: &'a Review) -> Cow<'a, DiffModel> {
        Self::model_for_layout(self.layout, self.model(review), &self.context_files)
    }

    /// Attach intra-line emphasis to the selected file once, just before it
    /// is rendered. `review_model` is the live working-tree model, used only
    /// when this view is not pinned to an immutable commit model.
    pub(crate) fn is_enriched(&self, path: &str) -> bool {
        self.enriched.contains(path)
    }

    pub(crate) fn mark_enriched(&mut self, path: &str) {
        self.enriched.insert(path.to_owned());
    }

    /// Forget which files have been enriched (after the model is rebuilt).
    pub(crate) fn clear_enriched(&mut self) {
        self.enriched.clear();
    }

    pub fn rows(&self) -> &[DiffRow] {
        &self.rows
    }

    /// Map the unified cursor to its row in `split` and the column the cursor
    /// line sits in (`None` for a hunk header, comment, or context line that
    /// fills both columns), so the split renderer highlights and scrolls to it.
    pub(crate) fn split_cursor(&self, split: &[SplitRow]) -> (usize, Option<SplitSide>) {
        let Some(row) = self.rows.get(self.cursor) else {
            return (0, None);
        };
        match *row {
            DiffRow::Hunk { hunk, .. } => (
                split
                    .iter()
                    .position(|r| matches!(r, SplitRow::Hunk { hunk: h } if *h == hunk))
                    .unwrap_or(0),
                None,
            ),
            DiffRow::Line { hunk, line, .. } => {
                for (i, r) in split.iter().enumerate() {
                    if let SplitRow::Pair {
                        hunk: h,
                        left,
                        right,
                    } = r
                        && *h == hunk
                    {
                        if *left == Some(line) && *right == Some(line) {
                            return (i, None);
                        }
                        if *left == Some(line) {
                            return (i, Some(SplitSide::Left));
                        }
                        if *right == Some(line) {
                            return (i, Some(SplitSide::Right));
                        }
                    }
                }
                (0, None)
            }
            DiffRow::Comment { comment, line, .. } => (
                split
                    .iter()
                    .position(|r| {
                        matches!(r, SplitRow::Comment { comment: c, line: l, .. } if *c == comment && *l == line)
                    })
                    .unwrap_or(0),
                None,
            ),
            DiffRow::Composer { line } => (
                split
                    .iter()
                    .position(|r| matches!(r, SplitRow::Composer { line: l } if *l == line))
                    .unwrap_or(0),
                None,
            ),
            // the summary card is unified-only: split_rows never carries one
            DiffRow::Summary { .. } => (0, None),
            DiffRow::Fold { group, .. } => {
                let hunk = self.fold_groups.get(group).map(|g| g.hunk);
                (
                    split
                        .iter()
                        .position(|r| matches!(r, SplitRow::Fold { hunk: h } if Some(*h) == hunk))
                        .unwrap_or(0),
                    None,
                )
            }
        }
    }

    /// Path of the selected file, when the diff is non-empty.
    pub fn selected_path(&self, review: &Review) -> Option<String> {
        self.model_for_rows(review)
            .files
            .get(self.selected)
            .map(|f| f.path.clone())
    }

    /// Mark the row list stale so the next `ensure_rows` rebuilds it. The
    /// cursor, the visual anchor and the banded span are each named by what
    /// they sit on, so that rebuild finds every one of them again on its
    /// own. Enrichment caches survive.
    pub(crate) fn mark_rows_dirty(&mut self) {
        self.rows_dirty = true;
    }

    /// Mark rows stale and forget enrichment, so a rebuilt model re-enriches.
    pub(crate) fn invalidate(&mut self) {
        self.mark_rows_dirty();
        self.enriched.clear();
    }

    /// Adopt the diff pane's row width so comment text wraps to it; rows
    /// re-flow when it changes (a resize, the sidebar layout toggling).
    pub(crate) fn set_wrap_width(&mut self, width: u16) {
        if width > 0 && self.wrap_width != width {
            self.wrap_width = width;
            self.mark_reflow();
        }
    }

    /// Rebuild the pane's rows, leaving the sidebar's file list as it is.
    pub(crate) fn mark_reflow(&mut self) {
        self.wrap_dirty = true;
    }

    pub(crate) fn ensure_rows(&mut self, review: &Review) {
        if !self.rows_dirty && !self.wrap_dirty {
            return;
        }
        let session = review.session_for(&self.source);
        self.ensure_figures(session);
        if self.layout == FileLayout::Walkthrough {
            self.validate_slide(session);
        }
        let base = self.commit_model.as_ref().unwrap_or_else(|| review.model());
        let model_cow = Self::model_for_layout(self.layout, base, &self.context_files);
        let model: &DiffModel = &model_cow;
        self.selected = self.selected.min(model.files.len().saturating_sub(1));
        let composer = self.composer.as_ref();
        // name what the cursor, the visual anchor and the banded span sit on
        // now, while `self.rows` still holds the list they were seated
        // against, so they can be found again once it is rebuilt
        let positions = self.capture_positions(review);
        let (rows, copy) = build_rows(
            model,
            session,
            self.selected,
            self.wrap_width,
            composer,
            &self.figures,
            &self.unresolved_anchors,
        );
        let (rows, copy) = if self.layout == FileLayout::Walkthrough {
            self.window_slide(model, session, rows, copy)
        } else {
            (rows, copy)
        };
        let path = model
            .files
            .get(self.selected)
            .map(|f| f.path.clone())
            .unwrap_or_default();
        let none_folded = HashSet::new();
        let folded = self.folded.get(&path).unwrap_or(&none_folded);
        let (rows, copy, fold_groups) = folds::apply(&rows, &copy, model, folded);
        self.rows = rows;
        self.row_copy = copy;
        let split_rows = build_split_rows(
            model,
            session,
            self.selected,
            self.wrap_width,
            composer,
            &self.figures,
            &self.unresolved_anchors,
        );
        self.split_rows = folds::apply_split(split_rows, model.files.get(self.selected), folded);
        self.fold_groups = fold_groups;
        self.rows_path = path;
        // the file list may have shifted (refresh) or folds may hide the old
        // cursor row: keep the tree cursor on the pane's file. A pure wrap
        // re-flow changes neither, and must not move a browsing cursor. Read
        // ahead of `merged_model` below: it is `model`'s last use, and that
        // borrow has to end before `restore_positions`/`reseat_tree_cursor`
        // can take `&mut self`.
        let tree_rows = self.rows_dirty.then(|| self.tree_rows(model, session));
        // stash what was just merged so the render path reads it instead of
        // rebuilding it every frame
        self.merged_model = match model_cow {
            Cow::Borrowed(_) => None,
            Cow::Owned(model) => Some(model),
        };
        self.restore_positions(review, positions);
        if let Some(tree_rows) = tree_rows {
            self.reseat_tree_cursor(&tree_rows);
        }
        self.rows_dirty = false;
        self.wrap_dirty = false;
        self.seat_cursor_on_caret();
    }

    /// Park the pane cursor on the composer's caret row, so the pane scrolls
    /// to the text being written and holds it there when a rebuild shifts the
    /// card's rows.
    fn seat_cursor_on_caret(&mut self) {
        let Some(composer) = self.composer.as_ref() else {
            return;
        };
        let caret = composer.caret_line(self.wrap_width);
        if let Some(row) = self
            .rows
            .iter()
            .position(|row| matches!(row, DiffRow::Composer { line } if *line == caret))
        {
            self.cursor = row;
        }
    }

    /// Open whatever hides the selected file in the sidebar: its ancestor
    /// directories in the tree layout, its section in the ones with headers.
    /// Only the layout on screen is touched, so the others keep their folds.
    pub(crate) fn reveal_selected(&mut self, review: &Review) {
        let model = self.model_for_rows(review);
        let Some(file) = model.files.get(self.selected) else {
            return;
        };
        let path = file.path.clone();
        let viewed = review
            .session_for(&self.source)
            .is_viewed(&path, &file.content_hash());
        let revealed = match self.layout {
            FileLayout::Review => {
                let bucket = if viewed {
                    Bucket::Viewed
                } else {
                    Bucket::ToReview
                };
                self.bucket_folds.unfold(bucket)
            }
            FileLayout::Kinds => {
                let bucket = Bucket::Kind(self.kind_of(&path));
                self.bucket_folds.unfold(bucket)
            }
            // a stop list hides nothing: every stop is on screen
            FileLayout::Walkthrough => false,
            FileLayout::Tree | FileLayout::List => {
                let hidden_by = |dir: &String| path.starts_with(&format!("{dir}/"));
                let hidden = self.folded_dirs.iter().any(hidden_by);
                if hidden {
                    self.folded_dirs.retain(|dir| !hidden_by(dir));
                }
                hidden
            }
        };
        self.rows_dirty |= revealed;
    }

    /// Seat the tree cursor on the selected file's row, or clamp it into
    /// range when that row is hidden (folded away, moved between buckets).
    pub(crate) fn reseat_tree_cursor(&mut self, rows: &[TreeRow]) {
        self.tree_cursor = tree_position_of_file(rows, self.selected)
            .unwrap_or_else(|| self.tree_cursor.min(rows.len().saturating_sub(1)));
    }

    /// Move the sidebar cursor to `selected`, rebuilding the diff rows and
    /// resetting the diff cursor to the top of the new file.
    fn select(&mut self, selected: usize, review: &Review) {
        if self.selected == selected {
            return;
        }
        self.selected = selected;
        self.cursor = 0;
        self.scroll = 0;
        self.visual_anchor = None;
        self.referenced = None;
        self.rows_dirty = true;
        self.ensure_rows(review);
    }

    /// Select `file_index`, reveal it in the sidebar and rebuild the pane
    /// rows, then seat the cursor on the first row `matches` picks out.
    /// Returns the matched span, first row to last, so a caller can band it
    /// the way a stop's card does. Shared by `seat_stop` and `focus_comment`,
    /// the two verbs that jump the diff cursor onto something found by id.
    pub(crate) fn seat_on(
        &mut self,
        review: &Review,
        file_index: usize,
        matches: impl Fn(&DiffRow) -> bool,
    ) -> Option<(usize, usize)> {
        self.select(file_index, review);
        self.reveal_selected(review);
        self.ensure_rows(review);
        let first = self.rows.iter().position(&matches)?;
        let last = self.rows.iter().rposition(&matches).unwrap_or(first);
        self.cursor = first;
        Some((first, last))
    }

    /// The rows in `file_index` whose new-side line numbers fall in
    /// `line..=end`, first to last, so a caller can band the segment a comment
    /// speaks about.
    pub(crate) fn span_rows(
        &self,
        review: &Review,
        file_index: usize,
        line: u32,
        end: u32,
    ) -> Option<(usize, usize)> {
        let model = self.model_for_rows(review);
        let hunks = &model.files.get(file_index)?.hunks;
        let covered = |row: &DiffRow| {
            let DiffRow::Line { hunk, line: at, .. } = *row else {
                return false;
            };
            hunks
                .get(hunk)
                .and_then(|hunk| hunk.lines.get(at))
                .and_then(|diff_line| diff_line.new_no)
                .is_some_and(|no| line <= no && no <= end)
        };
        let first = self.rows.iter().position(covered)?;
        let last = self.rows.iter().rposition(covered).unwrap_or(first);
        Some((first, last))
    }

    /// The flattened sidebar rows over the model's files. The tree layout
    /// groups files under collapsible directory rows (honoring the folded
    /// set). The review layout splits files into a to-review and a viewed
    /// bucket under foldable Section rows; bucket membership reads the
    /// hash-keyed viewed marks, so an edited file falls back into to-review by
    /// itself. The kinds layout groups them by what they are. Files keep their
    /// model index.
    ///
    /// Inside a group, whether a directory or a section, the files already
    /// viewed come first: every layout sorts the same way the review layout's
    /// buckets do, so what is left to read is one run at the bottom of each
    /// group and marking a file moves it out of that run.
    pub(crate) fn tree_rows(&self, model: &DiffModel, session: &Session) -> Vec<TreeRow> {
        match self.layout {
            FileLayout::Review => self.section_rows(model, Self::review_groups(model, session)),
            FileLayout::Kinds => self.section_rows(model, self.kind_groups(model, session)),
            FileLayout::Walkthrough => match self.active_walkthrough(session) {
                Some(walkthrough) => walkthrough
                    .summary
                    .is_some()
                    .then_some(TreeRow {
                        depth: 0,
                        node: TreeNode::WalkthroughSummary,
                    })
                    .into_iter()
                    .chain((0..walkthrough.stops.len()).map(|index| TreeRow {
                        depth: 0,
                        node: TreeNode::Stop { index },
                    }))
                    .collect(),
                None => {
                    tree::visible_rows_promoting(&Self::paths(model), &self.folded_dirs, &|index| {
                        Self::is_viewed(model, session, index)
                    })
                }
            },
            // list belongs to the status screen (config rejects it here); a
            // stray value degrades to the tree
            FileLayout::Tree | FileLayout::List => {
                tree::visible_rows_promoting(&Self::paths(model), &self.folded_dirs, &|index| {
                    Self::is_viewed(model, session, index)
                })
            }
        }
    }

    /// Every file the sidebar lists, in the order it lists them, as if nothing
    /// were folded. A reader walks the order on screen, so the commands that
    /// step files read it from here.
    pub(crate) fn display_order(&self, model: &DiffModel, session: &Session) -> Vec<usize> {
        match self.layout {
            FileLayout::Review => Self::review_groups(model, session),
            FileLayout::Kinds => self.kind_groups(model, session),
            FileLayout::Walkthrough if self.active_walkthrough(session).is_some() => {
                let stops = self
                    .active_walkthrough(session)
                    .into_iter()
                    .flat_map(|walkthrough| &walkthrough.stops);
                let mut seen = HashSet::new();
                return stops
                    .filter_map(|id| stop_file_index(model, session, id))
                    .filter(|index| seen.insert(*index))
                    .collect();
            }
            FileLayout::Walkthrough | FileLayout::Tree | FileLayout::List => {
                let rows =
                    tree::visible_rows_promoting(&Self::paths(model), &BTreeSet::new(), &|index| {
                        Self::is_viewed(model, session, index)
                    });
                return rows.iter().filter_map(row_file_index).collect();
            }
        }
        .into_iter()
        .flat_map(|(_, indices)| indices)
        .collect()
    }

    fn paths(model: &DiffModel) -> Vec<&str> {
        model.files.iter().map(|file| file.path.as_str()).collect()
    }

    fn is_viewed(model: &DiffModel, session: &Session, index: usize) -> bool {
        model
            .files
            .get(index)
            .is_some_and(|file| session.is_viewed(&file.path, &file.content_hash()))
    }

    /// Order a group's files for display: viewed first, each run keeping the
    /// order the diff gave it.
    fn viewed_first(model: &DiffModel, session: &Session, indices: &mut [usize]) {
        indices.sort_by_key(|&index| !Self::is_viewed(model, session, index));
    }

    /// A header row per group, its files beneath it unless it is folded. The
    /// renderer reads the depths to draw the indent, so both grouped layouts
    /// emit them from here.
    fn section_rows(
        &self,
        model: &DiffModel,
        groups: impl IntoIterator<Item = (Bucket, Vec<usize>)>,
    ) -> Vec<TreeRow> {
        let mut rows = Vec::new();
        for (bucket, indices) in groups {
            let folded = self.bucket_folds.is_folded(bucket);
            rows.push(TreeRow {
                depth: 0,
                node: TreeNode::Section {
                    bucket,
                    count: indices.len(),
                    folded,
                },
            });
            if folded {
                continue;
            }
            rows.extend(indices.into_iter().filter_map(|index| {
                let file = model.files.get(index)?;
                Some(TreeRow {
                    depth: 1,
                    node: TreeNode::File {
                        index,
                        name: file.path.clone(),
                    },
                })
            }));
        }
        rows
    }

    fn review_groups(model: &DiffModel, session: &Session) -> Vec<(Bucket, Vec<usize>)> {
        let (mut fresh, mut viewed) = (Vec::new(), Vec::new());
        for index in 0..model.files.len() {
            if Self::is_viewed(model, session, index) {
                viewed.push(index);
            } else {
                fresh.push(index);
            }
        }
        vec![(Bucket::ToReview, fresh), (Bucket::Viewed, viewed)]
    }

    /// One group per kind that the diff has files for, in [`Kind::ALL`] order.
    /// Files keep their model index, and their order within the diff behind
    /// the ones already viewed.
    fn kind_groups(&self, model: &DiffModel, session: &Session) -> Vec<(Bucket, Vec<usize>)> {
        // `Kind::ALL` below is the display order
        let mut grouped: HashMap<Kind, Vec<usize>> = HashMap::new();
        for (index, file) in model.files.iter().enumerate() {
            grouped
                .entry(self.kind_of(&file.path))
                .or_default()
                .push(index);
        }
        Kind::ALL
            .into_iter()
            .filter_map(|kind| {
                let mut indices = grouped.remove(&kind)?;
                Self::viewed_first(model, session, &mut indices);
                Some((Bucket::Kind(kind), indices))
            })
            .collect()
    }

    /// Model indices a sidebar bucket holds, folded or not. Derived from the
    /// same grouping the rows come from, so a group verb covers exactly what
    /// its header stands for.
    pub(crate) fn bucket_files(
        &self,
        model: &DiffModel,
        session: &Session,
        bucket: Bucket,
    ) -> Vec<usize> {
        let groups = match bucket {
            Bucket::Kind(_) => self.kind_groups(model, session),
            Bucket::ToReview | Bucket::Viewed => Self::review_groups(model, session),
        };
        groups
            .into_iter()
            .find(|(known, _)| *known == bucket)
            .map_or_else(Vec::new, |(_, indices)| indices)
    }

    pub(crate) fn kind_of(&self, path: &str) -> Kind {
        self.rules.kind(path, self.declared.get(path).copied())
    }

    /// The paths a declared-kinds worker should ask git about, empty unless
    /// the kinds layout is the one on screen.
    fn declared_targets(&self, review: &Review) -> Vec<String> {
        if self.layout != FileLayout::Kinds {
            return Vec::new();
        }
        self.model(review)
            .files
            .iter()
            .map(|file| file.path.clone())
            .collect()
    }

    /// Advance the sidebar layout: tree → review → kinds → walkthrough → tree.
    /// The walkthrough is in the cycle only where the review has one, since a
    /// layout with nothing to list is a dead stop in the rotation. Leaving it
    /// for one of the file layouts is itself a dead stop when the diff has no
    /// files of its own (`empty`): tree/review/kinds would list nothing, so
    /// the walkthrough is the only content and stays put.
    pub(crate) fn cycle_layout(&mut self, has_walkthrough: bool, empty: bool) -> FileLayout {
        self.layout = match self.layout {
            FileLayout::Review => FileLayout::Kinds,
            FileLayout::Kinds if has_walkthrough => FileLayout::Walkthrough,
            FileLayout::Walkthrough if empty && has_walkthrough => FileLayout::Walkthrough,
            FileLayout::Kinds | FileLayout::Walkthrough => FileLayout::Tree,
            FileLayout::Tree | FileLayout::List => FileLayout::Review,
        };
        self.layout
    }

    /// Whether the rows on screen are `path`'s.
    pub(crate) fn rows_show(&self, path: &str) -> bool {
        self.rows_path == path
    }

    /// Open the hunk the fold row `group` stands for.
    fn open_fold_group(&mut self, group: usize) -> bool {
        let Some(keys) = self.fold_groups.get(group).map(|g| g.keys.clone()) else {
            return false;
        };
        if let Some(folded) = self.folded.get_mut(&self.rows_path) {
            for key in &keys {
                folded.remove(key);
            }
        }
        self.mark_rows_dirty();
        true
    }

    /// The hunk row `row` belongs to: its own for a header or a line, and for
    /// a comment or composer row, the hunk of the line above it.
    fn hunk_of_row(&self, row: usize) -> Option<usize> {
        self.rows
            .get(..=row)?
            .iter()
            .rev()
            .find_map(|row| match *row {
                DiffRow::Hunk { hunk, .. } | DiffRow::Line { hunk, .. } => Some(hunk),
                _ => None,
            })
    }

    /// Seat the cursor on line `line` of hunk `hunk`, opening the fold that
    /// hides it first. Every motion that can land inside a fold goes through
    /// here, so its target is on screen. Returns the row it landed on.
    pub(crate) fn reveal_line(
        &mut self,
        review: &Review,
        (hunk, line): (usize, usize),
    ) -> Option<usize> {
        let hiding = self
            .fold_groups
            .iter()
            .position(|group| group.lines.contains(&(hunk, line)));
        if let Some(group) = hiding {
            self.open_fold_group(group);
            self.ensure_rows(review);
        }
        let at = self.rows.iter().position(
            |row| matches!(*row, DiffRow::Line { hunk: h, line: l, .. } if h == hunk && l == line),
        )?;
        self.cursor = at;
        Some(at)
    }

    /// The lines the fold row `group` hides, with their own model data.
    pub(crate) fn fold_lines<'a>(
        &self,
        file: &'a FileDiff,
        group: usize,
    ) -> Vec<((usize, usize), &'a DiffLine)> {
        let lines = self
            .fold_groups
            .get(group)
            .map_or(&[][..], |g| g.lines.as_slice());
        folds::resolve_hidden(file, lines)
    }

    /// The code a fold row hides, one line per line and bare (no diff
    /// marker), for search to match.
    pub(crate) fn fold_text(&self, file: &FileDiff, group: usize) -> String {
        self.fold_lines(file, group)
            .iter()
            .map(|(_, diff_line)| diff_line.text.as_str())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// The text a `/` search matches against: a diff line's own text, or a
    /// fold row's hidden lines. `None` for a row search does not reach (a
    /// hunk header, a comment, the composer).
    pub(crate) fn row_search_text(&self, file: Option<&FileDiff>, row: &DiffRow) -> Option<String> {
        match *row {
            DiffRow::Line { hunk, line, .. } => {
                Some(file?.hunks.get(hunk)?.lines.get(line)?.text.clone())
            }
            DiffRow::Fold { group, .. } => Some(self.fold_text(file?, group)),
            _ => None,
        }
    }

    /// `za`/`<tab>`: open the folded hunk under the cursor, or fold the hunk
    /// the cursor sits in. `false` when the cursor is in no hunk.
    pub(crate) fn toggle_fold_at_cursor(&mut self, review: &Review) -> bool {
        if let Some(DiffRow::Fold { group, .. }) = self.rows.get(self.cursor).copied() {
            return self.open_fold_group(group);
        }
        let Some(hunk) = self.hunk_of_row(self.cursor) else {
            return false;
        };
        let Some(key) = self
            .model_for_rows(review)
            .files
            .get(self.selected)
            .and_then(|file| file.hunks.get(hunk))
            .map(folds::hunk_key)
        else {
            return false;
        };
        // the cursor goes to the header first, so the rebuild seats it on
        // the fold row that replaces it
        if let Some(header) = self
            .rows
            .iter()
            .position(|row| matches!(*row, DiffRow::Hunk { hunk: h, .. } if h == hunk))
        {
            self.cursor = header;
        }
        self.folded
            .entry(self.rows_path.clone())
            .or_default()
            .insert(key);
        self.mark_rows_dirty();
        true
    }

    /// `zR`: open every folded hunk of the file on screen. `false` when none
    /// is folded.
    pub(crate) fn open_all_folds(&mut self) -> bool {
        let opened = self
            .folded
            .remove(&self.rows_path)
            .is_some_and(|folded| !folded.is_empty());
        if opened {
            self.mark_rows_dirty();
        }
        opened
    }

    /// `zM`: fold every hunk of the file on screen. `false` when it has none.
    pub(crate) fn fold_all(&mut self, review: &Review) -> bool {
        let keys: HashSet<String> = self
            .model_for_rows(review)
            .files
            .get(self.selected)
            .map(|file| file.hunks.iter().map(folds::hunk_key).collect())
            .unwrap_or_default();
        if keys.is_empty() {
            return false;
        }
        self.folded.insert(self.rows_path.clone(), keys);
        self.mark_rows_dirty();
        true
    }
}

/// The sidebar rows for `diff`, pairing its model with its source's session
/// (the review layout needs the viewed marks).
fn sidebar_rows(diff: &DiffView, review: &Review) -> Vec<TreeRow> {
    diff.tree_rows(diff.model(review), review.session_for(&diff.source))
}

/// Model index of the next file after the selection not yet marked viewed,
/// scanning forward and coming back around only when `wrap` asks for it.
fn next_unviewed_index(diff: &DiffView, review: &Review, wrap: bool) -> Option<usize> {
    let model = diff.model(review);
    let session = review.session_for(&diff.source);
    // the order on screen: a jump has to land where the reader can see it came
    // from
    let order = diff.display_order(model, session);
    let count = order.len();
    let at = order.iter().position(|&index| index == diff.selected)?;
    (1..=count)
        .map(|step| at + step)
        .take_while(|&position| wrap || position < count)
        .filter_map(|position| order.get(position % count).copied())
        .find(|&index| !DiffView::is_viewed(model, session, index))
}

/// The model file a row addresses, for the walks that step files past the
/// directory and section headers between them.
fn row_file_index(row: &TreeRow) -> Option<usize> {
    match row.node {
        TreeNode::File { index, .. } => Some(index),
        TreeNode::Dir { .. }
        | TreeNode::Section { .. }
        | TreeNode::Stop { .. }
        | TreeNode::WalkthroughSummary => None,
    }
}

/// Visible-row index of the File row addressing `file_index`, if shown.
fn tree_position_of_file(rows: &[TreeRow], file_index: usize) -> Option<usize> {
    rows.iter()
        .position(|row| row_file_index(row) == Some(file_index))
}

/// Row position of the next thing the sidebar lists after `at`, `forward` down
/// the list or back up it, skipping the headers in between. A stop is what the
/// walkthrough layout lists, so `<c-n>` steps stops there and files everywhere
/// else.
fn step_file_row(rows: &[TreeRow], at: usize, forward: bool) -> Option<usize> {
    crate::app::step_to(rows, at, forward, |row| {
        row_file_index(row).is_some() || matches!(row.node, TreeNode::Stop { .. })
    })
}

impl RowSelect for DiffView {
    fn cursor(&self) -> usize {
        self.cursor
    }

    fn anchor(&self) -> Option<usize> {
        self.visual_anchor
    }

    fn set_anchor(&mut self, anchor: Option<usize>) {
        self.visual_anchor = anchor;
    }
}

impl RowText for DiffView {
    fn row_count(&self) -> usize {
        self.rows.len()
    }

    fn row_text(&self, row: usize) -> String {
        self.row_copy
            .get(row)
            .map(RowCopy::text)
            .unwrap_or_default()
    }
}

/// A queued re-diff of the working tree, plus whatever source is open (a
/// three-dot review or a pinned commit/range/PR), all recomputed on one
/// fresh backend under the algorithm just switched to (`<c-a>`).
#[derive(Debug)]
pub struct RediffRequest {
    /// The open diff's resolved source (a walkthrough already resolved to
    /// whatever it is about); `None` when no diff is open.
    pub about: Option<ReviewSource>,
    /// The PR's `(merge_base, head)` when `about` is one, so a landing result
    /// for a head that has since moved is dropped.
    pub pr_head: Option<(String, String)>,
    /// The request this answers; a stale one is dropped on arrival.
    pub token: u64,
}

impl RediffRequest {
    /// The re-diff itself, on a fresh backend: status, the working tree, and
    /// `about`'s own model when it is a three-dot review or a pinned source.
    pub fn run(
        &self,
        repo_root: &std::path::Path,
        settings: &diffler_core::diffalgo::DiffSettings,
    ) -> Result<diffler_core::review::Refreshed, String> {
        let against = match &self.about {
            Some(ReviewSource::Against { rev }) => Some(rev.as_str()),
            _ => None,
        };
        let pr_head = self
            .pr_head
            .as_ref()
            .map(|(base, head)| (base.as_str(), head.as_str()));
        let pinned = self
            .about
            .as_ref()
            .filter(|about| {
                matches!(
                    about,
                    ReviewSource::Commit { .. }
                        | ReviewSource::Range { .. }
                        | ReviewSource::Pr { .. }
                )
            })
            .map(|source| (source, pr_head));
        Review::compute_refresh(repo_root, settings, against, pinned).map_err(|err| err.to_string())
    }
}

/// Paths whose git attributes a worker should read, for the kinds sidebar.
#[derive(Debug, Clone)]
pub struct DeclaredRequest {
    pub paths: Vec<String>,
    /// The request this answers; an answer for a file list the view has since
    /// replaced is dropped.
    pub token: u64,
}

impl App {
    /// Ask git what the repo declares about the kinds sidebar's files. The
    /// lookup walks the attribute files per path, so it runs on a worker and
    /// the sidebar groups by the built-in table until the answer lands.
    pub(crate) fn queue_declared(&mut self) {
        let paths = self
            .diff
            .as_ref()
            .map(|diff| diff.declared_targets(&self.review))
            .unwrap_or_default();
        self.declared_token += 1;
        let token = self.declared_token;
        self.pending_declared = (!paths.is_empty()).then_some(DeclaredRequest { paths, token });
    }

    pub(crate) fn on_declared_kinds(&mut self, kinds: HashMap<String, Kind>, token: u64) -> Flow {
        let Some(diff) = self.diff.as_mut().filter(|_| token == self.declared_token) else {
            return Flow::Idle;
        };
        if diff.declared == kinds {
            return Flow::Idle;
        }
        diff.declared = kinds;
        diff.invalidate();
        diff.ensure_rows(&self.review);
        Flow::Continue
    }
}

#[cfg(test)]
mod tests {
    use diffler_core::feedback::{self, FeedbackOptions};
    use diffler_core::model::LineKind;
    use diffler_core::session::{Anchor, CommentStatus};
    use unicode_width::UnicodeWidthStr;

    use crate::app::markdown::MdSpan;

    use super::*;
    use crate::app::{App, Modal, Screen};
    use crate::config::LoadedConfig;
    use crate::event::AppEvent;
    use crate::test_support::{
        Fixture, big_file_fixture, code_key, ctrl_key, huge_span_fixture, key, settle_submit,
        standard_fixture, two_hunk_fixture,
    };

    fn diff_app(fixture: &Fixture) -> App {
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        app.open_working_tree_diff(None);
        app
    }

    /// A diff app whose sidebar layout is forced to `layout`, overriding the
    /// default tree.
    fn diff_app_with_layout(fixture: &Fixture, layout: crate::config::FileLayout) -> App {
        let mut loaded = LoadedConfig::default();
        loaded.config.ui.diff_file_layout = layout;
        let mut app = App::new(fixture.review(), loaded);
        app.author = "reviewer".to_owned();
        app.open_working_tree_diff(None);
        app
    }

    fn rows(app: &App) -> Vec<DiffRow> {
        app.diff.as_ref().expect("diff view").rows().to_vec()
    }

    fn focus(app: &App) -> Pane {
        app.diff.as_ref().expect("diff view").focus
    }

    fn selected_path(app: &App) -> String {
        app.diff
            .as_ref()
            .expect("diff view")
            .selected_path(&app.review)
            .expect("selected file")
    }

    fn tree_cursor(app: &App) -> usize {
        app.diff.as_ref().expect("diff view").tree_cursor
    }

    fn tree_row_count(app: &App) -> usize {
        let diff = app.diff.as_ref().expect("diff view");
        sidebar_rows(diff, &app.review).len()
    }

    /// Kinds of the visible sidebar tree rows: "dir", "file:<name>",
    /// "section:<label>:<count>", or "stop:<index>".
    fn tree_kinds(app: &App) -> Vec<String> {
        let diff = app.diff.as_ref().expect("diff view");
        sidebar_rows(diff, &app.review)
            .iter()
            .map(|row| match &row.node {
                crate::tree::TreeNode::Dir { .. } => "dir".to_owned(),
                crate::tree::TreeNode::File { name, .. } => format!("file:{name}"),
                crate::tree::TreeNode::Section { bucket, count, .. } => {
                    format!("section:{}:{count}", bucket.label())
                }
                crate::tree::TreeNode::Stop { index } => format!("stop:{index}"),
                crate::tree::TreeNode::WalkthroughSummary => "walkthrough_summary".to_owned(),
            })
            .collect()
    }

    /// Put focus on the diff pane (unscoped open starts on the sidebar).
    fn enter_diff_pane(app: &mut App) {
        app.diff.as_mut().expect("diff view").focus = Pane::Diff;
    }

    fn cursor_to_line(app: &mut App, pred: impl Fn(&DiffRow) -> bool) {
        let position = rows(app).iter().position(pred).expect("row present");
        app.diff.as_mut().unwrap().cursor = position;
    }

    /// Select the file at `path`, then focus the diff pane.
    fn select_file(app: &mut App, path: &str) {
        let index = app
            .diff
            .as_ref()
            .unwrap()
            .model(&app.review)
            .files
            .iter()
            .position(|f| f.path == path)
            .expect("file present");
        app.diff_select_file_index(index);
        enter_diff_pane(app);
    }

    /// Row index of the first added line ("42") in the standard fixture's
    /// src/lib.rs diff.
    fn added_line_position(app: &App) -> usize {
        let diff = app.diff.as_ref().unwrap();
        let model = diff.model(&app.review);
        rows(app)
            .iter()
            .position(|row| {
                let DiffRow::Line { file, hunk, line } = row else {
                    return false;
                };
                model.files.get(*file).is_some_and(|f| {
                    f.path == "src/lib.rs"
                        && f.hunks.get(*hunk).is_some_and(|h| {
                            h.lines
                                .get(*line)
                                .is_some_and(|l| l.new_no.is_some() && l.text.contains("42"))
                        })
                })
            })
            .expect("added line present")
    }

    fn type_text(app: &mut App, text: &str) {
        for c in text.chars() {
            app.handle(key(c));
        }
    }

    /// Row of the open composer's own caret, the row `seat_cursor_on_caret`
    /// parks the pane cursor on while a reader is typing.
    fn caret_row(app: &App) -> usize {
        let diff = app.diff.as_ref().unwrap();
        let composer = diff.composer.as_ref().expect("composer open");
        let caret = composer.caret_line(diff.wrap_width);
        diff.rows()
            .iter()
            .position(|row| matches!(row, DiffRow::Composer { line } if *line == caret))
            .expect("the caret's own row")
    }

    /// A review of nothing is a screen with no rows to read or comment on, so
    /// the opener declines and the reader stays where the answer is.
    #[test]
    fn opening_a_review_with_no_files_says_so_and_opens_nothing() {
        let fixture = Fixture::new();
        fixture.write("a.rs", "fn a() {}\n");
        fixture.commit_all("base");
        let mut app = App::new(fixture.review(), LoadedConfig::default());

        app.handle(key('D'));
        assert!(app.diff.is_none(), "no review opened over a clean tree");
        assert_eq!(app.screen(), Screen::Status);
        assert_eq!(
            app.message.as_ref().map(|m| m.text.as_str()),
            Some("nothing to review: working tree clean")
        );

        // an empty commit reaches the same guard, named by its own source
        fixture.commit_all("nothing");
        let head = app.review.vcs.resolve("HEAD").expect("head oid");
        app.open_commit_diff(&head);
        assert!(app.diff.is_none(), "no review opened over an empty commit");
        let message = app.message.as_ref().expect("message").text.clone();
        assert!(
            message.starts_with("nothing to review in commit"),
            "the source names itself: {message}"
        );
    }

    #[test]
    fn rows_flatten_the_selected_files_hunks_and_lines_in_order() {
        let fixture = two_hunk_fixture();
        let app = diff_app(&fixture);
        let rows = rows(&app);
        // no file header row: the selected file is implicit
        assert!(matches!(rows.first(), Some(DiffRow::Hunk { hunk: 0, .. })));
        let hunks: Vec<usize> = rows
            .iter()
            .filter_map(|r| match r {
                DiffRow::Hunk { hunk, .. } => Some(*hunk),
                _ => None,
            })
            .collect();
        assert_eq!(hunks, vec![0, 1], "both hunks flattened in order");
        assert!(
            rows.iter()
                .any(|r| matches!(r, DiffRow::Line { hunk: 1, .. })),
            "second hunk has line rows"
        );
    }

    #[test]
    fn open_starts_on_the_sidebar_at_the_first_file() {
        let fixture = standard_fixture();
        let app = diff_app(&fixture);
        assert_eq!(focus(&app), Pane::List);
        assert_eq!(app.diff.as_ref().unwrap().selected, 0);
    }

    #[test]
    fn list_jk_moves_over_tree_rows_and_files_under_the_cursor_become_selected() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // standard fixture tree (model order ci.yml, src/lib.rs, todo.md):
        //   0 dir src   1 file lib.rs   2 file ci.yml   3 file todo.md
        assert_eq!(
            tree_kinds(&app),
            vec![
                "dir".to_owned(),
                "file:lib.rs".to_owned(),
                "file:ci.yml".to_owned(),
                "file:todo.md".to_owned(),
            ]
        );
        // the cursor opens on the row of the shown file (ci.yml, model index 0)
        assert_eq!(tree_cursor(&app), 2);
        assert_eq!(selected_path(&app), "ci.yml");
        // gg lands on the src dir row; the pane keeps its last file
        app.handle(key('g'));
        app.handle(key('g'));
        assert_eq!(tree_cursor(&app), 0);
        assert_eq!(selected_path(&app), "ci.yml", "a dir row keeps the pane");
        // move the diff cursor down first, then j onto the lib.rs file row
        // selects it and resets the diff cursor
        enter_diff_pane(&mut app);
        app.handle(key('j'));
        assert!(app.diff.as_ref().unwrap().cursor > 0);
        app.diff.as_mut().unwrap().focus = Pane::List;
        app.handle(key('j'));
        assert_eq!(tree_cursor(&app), 1);
        assert_eq!(selected_path(&app), "src/lib.rs");
        assert_eq!(app.diff.as_ref().unwrap().cursor, 0, "diff cursor reset");
        assert_eq!(app.diff.as_ref().unwrap().scroll, 0);
        // j again advances onto the next file (ci.yml at root)
        app.handle(key('j'));
        assert_eq!(selected_path(&app), "ci.yml");
        // k back onto the lib.rs file row reselects it
        app.handle(key('k'));
        assert_eq!(selected_path(&app), "src/lib.rs");
    }

    #[test]
    fn the_default_sidebar_layout_is_a_tree_with_dir_rows() {
        let fixture = standard_fixture();
        let app = diff_app(&fixture);
        // the default keeps the collapsible tree: a src dir row precedes lib.rs
        assert_eq!(
            tree_kinds(&app),
            vec![
                "dir".to_owned(),
                "file:lib.rs".to_owned(),
                "file:ci.yml".to_owned(),
                "file:todo.md".to_owned(),
            ]
        );
    }

    /// The stop list replaces the file list: one row per stop, in the
    /// agent's order, with no group headers between them. A walkthrough with
    /// no summary has no leading row at all.
    #[test]
    fn a_walkthrough_with_no_summary_lists_only_its_stops() {
        let fixture = standard_fixture();
        let app = walkthrough_app(&fixture);
        assert_eq!(
            tree_kinds(&app),
            vec![
                "stop:0".to_owned(),
                "stop:1".to_owned(),
                "stop:2".to_owned()
            ]
        );
    }

    /// A walkthrough with a summary lists it as the leading row.
    #[test]
    fn a_walkthrough_with_a_summary_lists_it_as_the_leading_row() {
        let fixture = standard_fixture();
        let app = walkthrough_app_with_summary(&fixture);
        assert_eq!(
            tree_kinds(&app),
            vec![
                "walkthrough_summary".to_owned(),
                "stop:0".to_owned(),
                "stop:1".to_owned(),
                "stop:2".to_owned()
            ]
        );
    }

    /// Selecting the leading row shows the summary slide.
    #[test]
    fn the_leading_summary_row_selects_the_summary_slide() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app_with_summary(&fixture);
        assert_eq!(
            tree_cursor(&app),
            1,
            "starts on the first stop, one past the summary"
        );

        app.diff_tree_to(0);

        assert_eq!(
            app.diff.as_ref().expect("diff view").slide,
            Some(Slide::Summary)
        );
        assert_eq!(tree_cursor(&app), 0);
    }

    /// The summary slide renders one card and no diff rows at all, the way a
    /// stop with no anchored line already shows its own card alone.
    #[test]
    fn the_summary_slide_shows_its_card_and_no_diff_rows() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app_with_summary(&fixture);

        app.diff_tree_to(0);

        assert!(
            rows(&app)
                .iter()
                .all(|row| matches!(row, DiffRow::Summary { .. })),
            "{:?}",
            rows(&app)
        );
        assert!(!rows(&app).is_empty());
    }

    /// A `mermaid` fence in the summary renders as a figure through the same
    /// path a comment's body does.
    #[test]
    fn a_mermaid_fence_in_the_summary_becomes_a_figure() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        crate::test_support::set_walkthrough_summary(
            &mut app,
            "w1",
            "why\n\n```mermaid\nflowchart LR\n  a --> b\n```\n",
        );
        app.diff.as_mut().unwrap().invalidate();
        app.seat_summary();

        let diff = app.diff.as_ref().expect("diff view");
        let key = crate::app::walkthrough::summary_figure_key("w1");
        assert!(
            diff.figures.get(&key).is_some_and(|cached| cached
                .blocks
                .iter()
                .any(|block| matches!(block, crate::app::walkthrough::Block::Figure(_)))),
            "the fence parsed into a figure block"
        );
    }

    /// `display_order` drives the file walks, so it has to be the stops' files
    /// in stop order with the repeats dropped.
    #[test]
    fn the_walkthrough_layout_orders_files_by_their_stops() {
        let fixture = standard_fixture();
        let app = walkthrough_app(&fixture);
        let diff = app.diff.as_ref().expect("diff view");
        let model = diff.model(&app.review);
        let session = app.review.session_for(&diff.source);
        let paths: Vec<&str> = diff
            .display_order(model, session)
            .into_iter()
            .filter_map(|index| model.files.get(index))
            .map(|file| file.path.as_str())
            .collect();
        assert_eq!(paths, ["todo.md", "src/lib.rs"]);
    }

    /// A layout with nothing to list is a dead stop in the rotation: `t`
    /// reaches it only on a walkthrough's own source, never on the working
    /// tree even when a walkthrough exists elsewhere.
    #[test]
    fn t_cycles_into_the_walkthrough_only_on_its_own_source() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        seat_walkthrough(&mut app);
        for _ in 0..3 {
            app.handle(key('t'));
        }
        assert_eq!(
            layout_of(&app),
            crate::config::FileLayout::Tree,
            "a walkthrough elsewhere never enters this source's cycle"
        );

        // `open_walkthrough` seats the layout on Walkthrough directly, so the
        // cycle from here runs Tree, Review, Kinds, back to Walkthrough
        app.open_walkthrough("w1", Slide::Stop(0));
        let layouts: Vec<crate::config::FileLayout> = (0..4)
            .map(|_| {
                app.handle(key('t'));
                layout_of(&app)
            })
            .collect();
        assert_eq!(
            layouts,
            [
                crate::config::FileLayout::Tree,
                crate::config::FileLayout::Review,
                crate::config::FileLayout::Kinds,
                crate::config::FileLayout::Walkthrough,
            ]
        );
    }

    /// A clean tree has nothing of its own for tree/review/kinds to list;
    /// leaving the walkthrough for one of them would strand the reader on an
    /// empty sidebar, so `t` cycles back to it instead.
    #[test]
    fn t_stays_on_the_walkthrough_when_the_diff_has_no_files_of_its_own() {
        let fixture = Fixture::new();
        fixture.write("README.md", "hello\n");
        fixture.commit_all("initial commit");
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        crate::test_support::seat_walkthrough(
            &mut app,
            "tour",
            &[("Base", Some("README.md:1"), "why hello")],
        );
        app.open_walkthrough("w1", Slide::Stop(0));
        assert_eq!(layout_of(&app), crate::config::FileLayout::Walkthrough);

        app.handle(key('t'));

        assert_eq!(
            layout_of(&app),
            crate::config::FileLayout::Walkthrough,
            "tree/review/kinds would list nothing; t stays put"
        );
    }

    fn layout_of(app: &App) -> crate::config::FileLayout {
        app.diff.as_ref().expect("diff view").layout
    }

    /// Cycling into the walkthrough must show its stop cards immediately, and
    /// cycling back out must drop them and any span band with them.
    #[test]
    fn cycling_into_and_out_of_the_walkthrough_toggles_its_stop_cards() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.author = "reviewer".to_owned();
        seat_walkthrough(&mut app);
        app.open_walkthrough_diff("w1");
        resolve_walkthrough(&mut app);
        assert_eq!(layout_of(&app), crate::config::FileLayout::Tree);

        for _ in 0..3 {
            app.handle(key('t'));
        }
        assert_eq!(layout_of(&app), crate::config::FileLayout::Walkthrough);
        app.diff.as_mut().unwrap().ensure_rows(&app.review);
        assert!(
            stop_card_rows(&app) > 0,
            "the walkthrough shows its stop card once cycled in"
        );
        let windowed = line_rows(&app);
        assert!(
            shown_line_numbers(&app).iter().all(|no| *no <= 3),
            "and only the current stop's own span"
        );

        app.handle(key('t'));
        assert_eq!(layout_of(&app), crate::config::FileLayout::Tree);
        app.diff.as_mut().unwrap().ensure_rows(&app.review);
        assert!(
            line_rows(&app) > windowed,
            "leaving the walkthrough shows the whole file again"
        );
        assert!(
            app.diff.as_ref().expect("diff view").referenced.is_none(),
            "leaving the walkthrough drops the span band too"
        );
    }

    /// Diff-line rows on screen, deletions included.
    fn line_rows(app: &App) -> usize {
        rows(app)
            .iter()
            .filter(|row| matches!(row, DiffRow::Line { .. }))
            .count()
    }

    /// Rows of the current stop's own card on screen. Row 0 of the sidebar is
    /// the leading all-slides row, so a stop's own row sits one past it.
    fn stop_card_rows(app: &App) -> usize {
        let diff = app.diff.as_ref().expect("diff view");
        let session = app.review.session_for(&diff.source);
        let Some(walkthrough) = diff.active_walkthrough(session) else {
            return 0;
        };
        let offset = super::stop_row_offset(walkthrough);
        let Some(current) = diff
            .tree_cursor
            .checked_sub(offset)
            .and_then(|stop| walkthrough.stops.get(stop))
            .and_then(|id| session.comments.iter().position(|c| c.id == *id))
        else {
            return 0;
        };
        rows(app)
            .iter()
            .filter(|row| matches!(row, DiffRow::Comment { comment, .. } if *comment == current))
            .count()
    }

    /// Three stops over the standard fixture: two files, one of them named
    /// twice, and one stop with no anchor at all.
    fn seat_walkthrough(app: &mut App) {
        crate::test_support::seat_walkthrough(
            app,
            "How the answer moved",
            &[
                ("What changed", None, "the overview"),
                ("The list", Some("todo.md:1"), "why a list"),
                ("The answer", Some("src/lib.rs#answer"), "why 42"),
            ],
        );
    }

    fn walkthrough_app(fixture: &Fixture) -> App {
        let mut loaded = LoadedConfig::default();
        loaded.config.ui.diff_file_layout = crate::config::FileLayout::Walkthrough;
        let mut app = App::new(fixture.review(), loaded);
        app.author = "reviewer".to_owned();
        seat_walkthrough(&mut app);
        app.open_walkthrough_diff("w1");
        resolve_walkthrough(&mut app);
        app
    }

    /// Like `walkthrough_app`, with a summary set before the diff opens, so
    /// its row appears in the sidebar and the initial seat lands past it.
    fn walkthrough_app_with_summary(fixture: &Fixture) -> App {
        let mut loaded = LoadedConfig::default();
        loaded.config.ui.diff_file_layout = crate::config::FileLayout::Walkthrough;
        let mut app = App::new(fixture.review(), loaded);
        app.author = "reviewer".to_owned();
        seat_walkthrough(&mut app);
        crate::test_support::set_walkthrough_summary(&mut app, "w1", "the shape of the change");
        app.open_walkthrough_diff("w1");
        resolve_walkthrough(&mut app);
        app
    }

    /// A walkthrough app over an arbitrary fixture with an arbitrary stop
    /// list, resolved the way the worker would. Real usage always rebuilds
    /// rows on the next key or render after a resolution lands; a test that
    /// reads rows with neither has to ask explicitly.
    fn walkthrough_app_with(fixture: &Fixture, stops: &[(&str, Option<&str>, &str)]) -> App {
        let mut loaded = LoadedConfig::default();
        loaded.config.ui.diff_file_layout = crate::config::FileLayout::Walkthrough;
        let mut app = App::new(fixture.review(), loaded);
        app.author = "reviewer".to_owned();
        crate::test_support::seat_walkthrough(&mut app, "tour", stops);
        app.open_walkthrough_diff("w1");
        resolve_walkthrough(&mut app);
        app.diff.as_mut().unwrap().ensure_rows(&app.review);
        app
    }

    /// Read the anchored files the way the worker would: the live worktree,
    /// since a walkthrough always tracks it.
    fn resolve_walkthrough(app: &mut App) {
        let Some(request) = app.pending_walkthrough.take() else {
            return;
        };
        let root = app.review.repo_root.clone();
        let contents = request
            .files
            .iter()
            .filter_map(|path| Some((path.clone(), std::fs::read_to_string(root.join(path)).ok()?)))
            .collect();
        app.handle(AppEvent::WalkthroughAnchors {
            contents,
            pin_broken: false,
            token: request.token,
        });
    }

    /// The whole point of a stop: it seats the reader on the first row of the
    /// span the agent named, in the file that holds it, and shows that span.
    #[test]
    fn moving_onto_a_stop_seats_the_cursor_on_its_span() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        // stop 2 anchors src/lib.rs#answer, whose definition is lines 1..=3
        app.handle(key('j'));
        app.handle(key('j'));
        assert_eq!(selected_path(&app), "src/lib.rs");
        let diff = app.diff.as_ref().expect("diff view");
        assert_eq!(
            diff.cursor, 1,
            "the cursor lands on the first row of the span"
        );
        let last = diff.rows().len().saturating_sub(1);
        let lines: Vec<u32> = (diff.cursor..=last)
            .filter_map(|row| match diff.rows().get(row) {
                Some(DiffRow::Line { hunk, line, .. }) => diff
                    .model(&app.review)
                    .files
                    .get(diff.selected)
                    .and_then(|file| file.hunks.get(*hunk))
                    .and_then(|hunk| hunk.lines.get(*line))
                    .and_then(|line| line.new_no),
                _ => None,
            })
            .collect();
        assert_eq!(lines, [1, 2, 3], "the slide shows the whole definition");
    }

    /// A stop with nothing to point at is prose, so it leaves the pane where
    /// the reader had it rather than jumping somewhere arbitrary.
    #[test]
    fn an_anchorless_stop_leaves_the_pane_alone() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        app.handle(key('j'));
        let seated = selected_path(&app);
        assert_eq!(seated, "todo.md");
        app.handle(key('k'));
        assert_eq!(selected_path(&app), seated, "stop 1 anchors nothing");
        assert_eq!(
            app.diff.as_ref().expect("diff view").referenced,
            None,
            "and bands nothing"
        );
    }

    /// Talking back is how the walkthrough becomes a conversation, and a stop
    /// is a comment, so `r` on its card answers it in its own thread.
    #[test]
    fn r_on_a_stop_card_replies_to_that_stop() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        app.handle(key('j'));
        app.handle(key('j'));
        enter_diff_pane(&mut app);
        let card = rows(&app)
            .iter()
            .position(|row| matches!(row, DiffRow::Comment { line: 0, .. }))
            .expect("a stop card");
        app.diff.as_mut().expect("diff view").cursor = card;
        app.handle(key('r'));
        assert!(app.composer_open());
        type_text(&mut app, "why not 43?");
        app.handle(key('\n'));

        let source = app.active_review_source();
        let stop = app
            .review
            .session_for(&source)
            .comment("stop-2")
            .expect("the third stop's comment");
        assert_eq!(stop.replies.len(), 1);
        assert_eq!(stop.replies[0].body, "why not 43?");
        assert_eq!(stop.status, CommentStatus::Replied);
    }

    /// The stops are comments, so the pane that lists comments lists them
    /// with no handling of its own.
    #[test]
    fn the_comments_pane_lists_the_stops() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        app.handle(key('C'));
        assert_eq!(
            app.comment_order(),
            vec![
                "stop-2".to_owned(),
                "stop-0".to_owned(),
                "stop-1".to_owned()
            ],
            "by file as the diff orders them, then by line"
        );
    }

    /// A comment the reader left, on a line of the open review.
    fn add_comment(app: &mut App, file: &str, line: u32, body: &str) -> String {
        let source = app.active_review_source();
        let id = app
            .review
            .session_for_mut(&source)
            .add_comment(
                Anchor {
                    file: file.to_owned(),
                    line: Some(line),
                    line_end: None,
                    on_old_side: false,
                    line_text: None,
                },
                "reviewer",
                body,
            )
            .id
            .clone();
        let diff = app.diff.as_mut().expect("diff view");
        diff.invalidate();
        diff.ensure_rows(&app.review);
        id
    }

    /// Comment ids the pane currently shows a card for.
    fn shown_comment_ids(app: &App) -> Vec<String> {
        let diff = app.diff.as_ref().expect("diff view");
        let session = app.review.session_for(&diff.source);
        rows(app)
            .iter()
            .filter_map(|row| match row {
                DiffRow::Comment {
                    comment, line: 0, ..
                } => session.comments.get(*comment).map(|c| c.id.clone()),
                _ => None,
            })
            .collect()
    }

    /// Select the comment `id` in the open comments sidebar, the way a motion
    /// key in that pane does.
    fn select_comment(app: &mut App, id: &str) {
        let at = app
            .comment_order()
            .iter()
            .position(|known| known == id)
            .expect("the comment is listed");
        app.comments_to(at);
    }

    /// The bug the slides exist to fix: reaching a comment from the comments
    /// pane used to leave the pane on the whole file with the card parked at
    /// the bottom. Selecting one enters the slide that holds it.
    #[test]
    fn selecting_a_comment_from_the_pane_enters_the_slide_that_holds_it() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        let human = add_comment(&mut app, "src/lib.rs", 2, "why 42?");
        assert_eq!(tree_cursor(&app), 0, "the reader starts on the first stop");

        app.handle(key('C'));
        select_comment(&mut app, &human);

        assert_eq!(tree_cursor(&app), 2, "the sidebar follows to that stop");
        assert_eq!(selected_path(&app), "src/lib.rs");
        assert_eq!(shown_line_numbers(&app), [1, 2, 3], "the stop's own region");
        assert_eq!(
            shown_comment_ids(&app),
            vec![human, "stop-2".to_owned()],
            "cards in line order: line 2's comment before the stop's own card, \
             which sits under line 3, the last line of its span"
        );
    }

    /// A comment no stop's region holds is a slide of its own, so reaching it
    /// still shows one thing rather than the whole file.
    #[test]
    fn a_comment_outside_every_region_opens_as_its_own_slide() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        let human = add_comment(&mut app, "ci.yml", 1, "why on push?");

        app.handle(key('C'));
        select_comment(&mut app, &human);

        let diff = app.diff.as_ref().expect("diff view");
        assert_eq!(diff.slide, Some(Slide::AdHoc(human.clone())));
        assert_eq!(selected_path(&app), "ci.yml");
        assert_eq!(shown_line_numbers(&app), [1]);
        assert_eq!(shown_comment_ids(&app), vec![human]);
    }

    /// A comment on a deleted line anchors old-side. Reaching it through the
    /// comments pane must window the deleted row and its hunk header in, not
    /// just the card: `window_slide` used to compare every span against the
    /// new-side line only, so a deleted row never matched.
    #[test]
    fn a_comment_on_a_deleted_line_bands_the_deleted_row_and_its_hunk() {
        let fixture = two_hunk_fixture();
        let mut app = walkthrough_app_with(
            &fixture,
            &[("Somewhere else", None, "unrelated to the deletion")],
        );
        let source = app.active_review_source();
        let human = app
            .review
            .session_for_mut(&source)
            .add_comment(
                Anchor {
                    file: "data.txt".to_owned(),
                    line: Some(1),
                    line_end: None,
                    on_old_side: true,
                    line_text: None,
                },
                "reviewer",
                "why drop this line?",
            )
            .id
            .clone();
        app.diff.as_mut().expect("diff view").invalidate();
        app.diff
            .as_mut()
            .expect("diff view")
            .ensure_rows(&app.review);

        app.handle(key('C'));
        select_comment(&mut app, &human);

        let diff = app.diff.as_ref().expect("diff view");
        assert_eq!(diff.slide, Some(Slide::AdHoc(human.clone())));
        let shown = rows(&app);
        assert!(
            shown
                .iter()
                .any(|row| matches!(row, DiffRow::Hunk { hunk: 0, .. })),
            "the deleted row's hunk header must be windowed in: {shown:?}"
        );
        assert!(
            shown.iter().any(|row| matches!(
                row,
                DiffRow::Line {
                    hunk: 0,
                    line: 0,
                    ..
                }
            )),
            "the deleted row itself must be windowed in, not only the card: {shown:?}"
        );
    }

    /// The comment walk runs over the slides, so stepping past the last
    /// comment of one enters the next.
    #[test]
    fn stepping_past_a_slides_last_comment_enters_the_next_slide() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        let human = add_comment(&mut app, "todo.md", 1, "is this list still right?");
        app.handle(key('C'));
        select_comment(&mut app, &human);
        assert_eq!(tree_cursor(&app), 1, "the second stop holds it");
        assert_eq!(
            shown_comment_ids(&app),
            vec!["stop-1".to_owned(), human],
            "that slide holds both"
        );

        app.handle(key('}'));

        assert_eq!(tree_cursor(&app), 2, "the walk moved on to the next stop");
        assert_eq!(selected_path(&app), "src/lib.rs");
        assert_eq!(shown_line_numbers(&app), [1, 2, 3]);
        assert_eq!(shown_comment_ids(&app), vec!["stop-2".to_owned()]);
    }

    /// New-side line numbers of every `DiffRow::Line` the pane currently
    /// shows, wherever the file lives in the model.
    fn shown_line_numbers(app: &App) -> Vec<u32> {
        let diff = app.diff.as_ref().expect("diff view");
        let model = diff.model(&app.review);
        rows(app)
            .iter()
            .filter_map(|row| {
                let DiffRow::Line { file, hunk, line } = row else {
                    return None;
                };
                model
                    .files
                    .get(*file)?
                    .hunks
                    .get(*hunk)?
                    .lines
                    .get(*line)?
                    .new_no
            })
            .collect()
    }

    /// The bug this layout exists to fix: a stop anchored deep in a large file
    /// used to render the file's entire diff with the card parked partway
    /// through. The window is exactly what the agent pointed at, its hunk
    /// header and its card.
    #[test]
    fn a_stops_window_is_its_anchored_rows_its_hunk_header_and_its_card() {
        let fixture = big_file_fixture();
        let app = walkthrough_app_with(
            &fixture,
            &[("The change", Some("big.txt:100"), "why line 100 changed")],
        );
        assert_eq!(
            shown_line_numbers(&app),
            [100],
            "the anchored line and no context around it"
        );
        assert!(
            rows(&app)
                .iter()
                .any(|row| matches!(row, DiffRow::Hunk { .. })),
            "the hunk header it sits under stays"
        );
        assert!(stop_card_rows(&app) > 0, "the card still draws");
    }

    /// A wide span is what the agent chose, so the window shows all of it
    /// rather than cutting it off at a row budget.
    #[test]
    fn a_wide_span_shows_every_row_it_covers() {
        let fixture = huge_span_fixture();
        let app = walkthrough_app_with(
            &fixture,
            &[("The rewrite", Some("big.txt:51-120"), "why 70 lines moved")],
        );
        assert_eq!(shown_line_numbers(&app).len(), 70);
    }

    /// A stop whose anchor names a file but resolves to no span (here, a bare
    /// path) shows only its card.
    #[test]
    fn an_anchor_with_no_span_shows_only_its_card() {
        let fixture = standard_fixture();
        let app = walkthrough_app_with(
            &fixture,
            &[("Whole file", Some("todo.md"), "look at the whole file")],
        );
        assert!(
            rows(&app)
                .iter()
                .all(|row| matches!(row, DiffRow::Comment { .. })),
            "no hunks at all: {:?}",
            rows(&app)
        );
    }

    /// Cycling `t` out of the walkthrough drops the window: the file reads
    /// whole again, the way any other layout shows it.
    #[test]
    fn cycling_out_of_the_walkthrough_restores_the_full_file_rows() {
        let fixture = huge_span_fixture();
        let mut app = walkthrough_app_with(
            &fixture,
            &[("The rewrite", Some("big.txt:51-120"), "why 70 lines moved")],
        );
        let windowed = shown_line_numbers(&app).len();
        app.handle(key('t'));
        app.diff.as_mut().unwrap().ensure_rows(&app.review);
        assert_eq!(
            layout_of(&app),
            crate::config::FileLayout::Tree,
            "left the walkthrough"
        );
        assert!(
            shown_line_numbers(&app).len() > windowed,
            "the whole hunk shows again, not just the window"
        );
    }

    /// `<c-n>` means "the next thing the sidebar lists", which in this layout
    /// is the next stop.
    #[test]
    fn ctrl_n_steps_stops_in_the_walkthrough_layout() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        app.handle(ctrl_key('n'));
        assert_eq!(tree_cursor(&app), 1);
        assert_eq!(selected_path(&app), "todo.md");
        app.handle(ctrl_key('n'));
        assert_eq!(tree_cursor(&app), 2);
        assert_eq!(selected_path(&app), "src/lib.rs");
        app.handle(ctrl_key('p'));
        assert_eq!(tree_cursor(&app), 1);
    }

    /// `m` in the walkthrough layout marks the slide read and moves on, the
    /// way `m` on a file advances to the row below it.
    #[test]
    fn m_marks_the_current_slide_seen_and_advances_to_the_next() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        assert_eq!(app.diff.as_ref().unwrap().slide, Some(Slide::Stop(0)));

        app.handle(key('m'));

        let source = app.active_review_source();
        assert!(app.review.session_for(&source).is_stop_seen("stop-0"));
        assert_eq!(app.diff.as_ref().unwrap().slide, Some(Slide::Stop(1)));
    }

    /// `u` skips a slide already marked seen and lands on the next one that
    /// isn't.
    #[test]
    fn u_jumps_to_the_next_unseen_slide_skipping_seen_ones() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        let source = app.active_review_source();
        app.review.session_for_mut(&source).mark_stop_seen("stop-1");

        app.handle(key('u'));

        assert_eq!(
            app.diff.as_ref().unwrap().slide,
            Some(Slide::Stop(2)),
            "stop-1 is seen, so u skips past it to stop-2"
        );
    }

    #[test]
    fn u_says_every_slide_is_seen_when_none_is_left() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        let source = app.active_review_source();
        for id in ["stop-0", "stop-1", "stop-2"] {
            app.review.session_for_mut(&source).mark_stop_seen(id);
        }

        app.handle(key('u'));

        assert_eq!(
            app.message.as_ref().map(|m| m.text.as_str()),
            Some("every slide is seen")
        );
    }

    /// The diff sidebar's own heading counts the walkthrough's stops seen so
    /// far; the status screen's header counts walkthroughs, not stops.
    #[test]
    fn seen_progress_shows_in_the_sidebar_heading_not_the_status_header() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        let source = app.active_review_source();
        app.review.session_for_mut(&source).mark_stop_seen("stop-0");

        let content = crate::test_support::render(&mut app).backend().to_string();
        assert!(
            content.contains("How the answer moved (1/3)"),
            "sidebar heading: {content}"
        );

        app.handle(key('q'));
        let content = crate::test_support::render(&mut app).backend().to_string();
        assert!(
            content.contains("Walkthroughs (1)"),
            "status header: {content}"
        );
    }

    /// `d` on the walkthrough layout's leading row asks, then deletes the
    /// whole review file, closing the diff with it.
    #[test]
    fn d_on_the_leading_sidebar_row_asks_then_deletes_the_whole_walkthrough() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app_with_summary(&fixture);
        app.diff.as_mut().unwrap().tree_cursor = 0;

        app.handle(key('d'));
        assert!(matches!(app.modal, Some(crate::app::Modal::Confirm { .. })));
        app.handle(key('y'));

        assert!(app.diff.is_none(), "the diff closes with it");
        let source = diffler_core::source::ReviewSource::walkthrough("w1");
        assert!(
            app.review
                .all_reviews()
                .expect("all reviews")
                .into_iter()
                .all(|(s, _)| s != source),
            "the review file is gone"
        );
    }

    /// `d` on a stop row asks, then deletes just that stop, keeping the rest
    /// of the walkthrough.
    #[test]
    fn d_on_a_stop_row_asks_then_deletes_just_that_stop() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        // no summary, so row 0 is stop 0's own row
        app.diff.as_mut().unwrap().tree_cursor = 0;

        app.handle(key('d'));
        app.handle(key('y'));

        let source = app.active_review_source();
        let walkthrough = app
            .review
            .session_for(&source)
            .walkthrough
            .as_ref()
            .expect("the walkthrough is kept");
        assert_eq!(walkthrough.stops.len(), 2);
        assert!(!walkthrough.stops.contains(&"stop-0".to_owned()));
    }

    #[test]
    fn gg_and_g_jump_to_the_first_and_last_visible_row() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let last = tree_row_count(&app) - 1;
        app.handle(key('G'));
        assert_eq!(tree_cursor(&app), last);
        // the last visible row is a file (todo.md), so it is selected
        assert_eq!(selected_path(&app), "todo.md");
        app.handle(key('g'));
        app.handle(key('g'));
        assert_eq!(tree_cursor(&app), 0, "back to the first visible row");
    }

    #[test]
    fn folding_a_dir_hides_its_subtree_and_unfolding_restores_it() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // cursor onto the src dir row (the first visible row)
        app.handle(key('g'));
        app.handle(key('g'));
        assert_eq!(tree_kinds(&app).len(), 4);
        // za folds it: lib.rs disappears, the dir row stays
        app.handle(key('z'));
        app.handle(key('a'));
        assert_eq!(
            tree_kinds(&app),
            vec![
                "dir".to_owned(),
                "file:ci.yml".to_owned(),
                "file:todo.md".to_owned(),
            ],
            "folded src/ hides lib.rs"
        );
        // <cr> on the dir row also toggles: this unfolds it again
        app.handle(key('\n'));
        assert_eq!(
            tree_kinds(&app).len(),
            4,
            "unfolded src/ shows lib.rs again"
        );
    }

    #[test]
    fn cr_on_a_file_row_focuses_the_diff_pane() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // ci.yml's row is under the cursor at open; <cr> focuses the pane
        assert!(matches!(
            tree_kinds(&app).get(tree_cursor(&app)).map(String::as_str),
            Some("file:ci.yml")
        ));
        app.handle(key('\n'));
        assert_eq!(focus(&app), Pane::Diff);
    }

    #[test]
    fn h_and_l_focus_the_panes_and_clamp() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        assert_eq!(focus(&app), Pane::List);
        app.handle(key('l'));
        assert_eq!(focus(&app), Pane::Diff);
        app.handle(key('l'));
        assert_eq!(
            focus(&app),
            Pane::Diff,
            "repeats stay on the diff, no cycle"
        );
        app.handle(key('h'));
        assert_eq!(focus(&app), Pane::List);
        app.handle(key('h'));
        assert_eq!(
            focus(&app),
            Pane::List,
            "repeats stay on the sidebar, no cycle"
        );
    }

    #[test]
    fn arrow_keys_focus_the_panes_like_h_and_l() {
        use crossterm::event::KeyCode;
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.handle(code_key(KeyCode::Right));
        assert_eq!(focus(&app), Pane::Diff);
        app.handle(code_key(KeyCode::Left));
        assert_eq!(focus(&app), Pane::List);
    }

    #[test]
    fn tab_on_a_file_at_the_repo_root_says_there_is_nothing_to_fold() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // the tree opens on ci.yml, which sits in no folder
        let before = tree_kinds(&app);

        app.handle(key('\t'));

        assert_eq!(tree_kinds(&app), before, "nothing folded");
        assert!(
            app.message
                .as_ref()
                .is_some_and(|m| m.text.contains("nothing to fold")),
            "{:?}",
            app.message
        );
    }

    #[test]
    fn tab_folds_the_directory_the_sidebar_cursor_sits_in() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // onto src/lib.rs, a file inside the only folder
        app.handle(key('k'));
        let file = selected_path(&app);
        assert!(tree_kinds(&app).contains(&"file:lib.rs".to_owned()));

        app.handle(key('\t'));

        assert!(
            !tree_kinds(&app).contains(&"file:lib.rs".to_owned()),
            "tab folds the folder away: {:?}",
            tree_kinds(&app)
        );
        assert_eq!(selected_path(&app), file, "and steps to no other file");
        // the cursor rode up to the folder row, so the same key opens it again
        app.handle(key('\t'));
        assert!(tree_kinds(&app).contains(&"file:lib.rs".to_owned()));
    }

    #[test]
    fn cr_from_the_list_focuses_the_diff_and_cr_back_returns() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.handle(key('\n'));
        assert_eq!(focus(&app), Pane::Diff);
        app.handle(key('\n'));
        assert_eq!(focus(&app), Pane::List);
    }

    #[test]
    fn ctrl_n_switches_the_selected_file_from_the_diff_pane_keeping_focus() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        let first = selected_path(&app);
        app.handle(ctrl_key('n'));
        assert_eq!(focus(&app), Pane::Diff, "focus stays on the diff");
        assert_ne!(selected_path(&app), first, "selection advanced");
        app.handle(ctrl_key('p'));
        assert_eq!(selected_path(&app), first);
    }

    #[test]
    fn ctrl_n_and_ctrl_p_walk_only_file_rows_skipping_directories() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // tree: dir src, lib.rs, ci.yml, todo.md. c-n/c-p never land on a dir
        app.handle(key('g'));
        app.handle(key('g'));
        assert!(matches!(
            tree_kinds(&app).get(tree_cursor(&app)).map(String::as_str),
            Some("dir")
        ));
        // from the dir row, c-n jumps to the first file below it
        app.handle(ctrl_key('n'));
        assert_eq!(selected_path(&app), "src/lib.rs");
        let mut visited = vec![selected_path(&app)];
        // walk forward to the end, recording every stop is a file
        for _ in 0..2 {
            app.handle(ctrl_key('n'));
            assert!(matches!(
                tree_kinds(&app).get(tree_cursor(&app)).map(String::as_str),
                Some(kind) if kind.starts_with("file:")
            ));
            visited.push(selected_path(&app));
        }
        assert_eq!(visited, vec!["src/lib.rs", "ci.yml", "todo.md"]);
        // and back the other way, still only files
        app.handle(ctrl_key('p'));
        assert_eq!(selected_path(&app), "ci.yml");
    }

    #[test]
    fn brace_keys_walk_between_comments() {
        let fixture = two_hunk_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        let anchor = |line: u32| Anchor {
            file: "data.txt".to_owned(),
            line: Some(line),
            line_end: None,
            on_old_side: false,
            line_text: None,
        };
        app.review.session.add_comment(anchor(1), "r", "first");
        app.review.session.add_comment(anchor(20), "r", "second");
        app.open_working_tree_diff(None);
        {
            let diff = app.diff.as_mut().unwrap();
            diff.focus = Pane::Diff;
            diff.cursor = 0;
            diff.invalidate();
        }
        app.diff.as_mut().unwrap().ensure_rows(&app.review);

        let on_header = |app: &App| {
            let diff = app.diff.as_ref().unwrap();
            matches!(
                diff.rows().get(diff.cursor),
                Some(DiffRow::Comment { line: 0, .. })
            )
        };
        app.handle(key('}'));
        assert!(on_header(&app), "}} lands on a comment header");
        let first = app.diff.as_ref().unwrap().cursor;
        app.handle(key('}'));
        assert!(on_header(&app));
        let second = app.diff.as_ref().unwrap().cursor;
        assert!(second > first, "}} advances to the next comment");
        app.handle(key('{'));
        assert_eq!(
            app.diff.as_ref().unwrap().cursor,
            first,
            "{{ returns to the previous comment"
        );
    }

    #[test]
    fn comment_rows_appear_under_their_anchored_line() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position;
        app.handle(key('c'));
        assert!(app.composer_open());
        type_text(&mut app, "why 42?");
        app.handle(key('\n'));
        assert!(!app.composer_open());

        let comment = &app.review.session.comments[0];
        assert_eq!(comment.author, "reviewer");
        assert_eq!(comment.body, "why 42?");
        assert_eq!(comment.anchor.file, "src/lib.rs");
        assert_eq!(comment.anchor.line, Some(2));
        assert!(!comment.anchor.on_old_side);
        assert_eq!(comment.anchor.line_text.as_deref(), Some("    42"));

        let diff = app.diff.as_mut().unwrap();
        diff.ensure_rows(&app.review);
        let rows = rows(&app);
        let line_position = added_line_position(&app);
        let block: Vec<_> = rows
            .iter()
            .skip(line_position + 1)
            .take_while(|r| matches!(r, DiffRow::Comment { .. }))
            .collect();
        assert_eq!(
            block.len(),
            3,
            "comment block right under the line: {rows:?}"
        );
        assert!(block.iter().all(|r| matches!(
            r,
            DiffRow::Comment {
                outdated: false,
                ..
            }
        )));
    }

    /// Cursor on the added line, `c` open, a note typed: the setup every
    /// composer editor test starts from.
    fn composer_with_typed_note(app: &mut App) {
        select_file(app, "src/lib.rs");
        let position = added_line_position(app);
        app.diff.as_mut().unwrap().cursor = position;
        app.handle(key('c'));
        type_text(app, "why 42?");
    }

    #[test]
    fn ctrl_g_sends_the_composer_buffer_to_the_editor_and_reads_it_back() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        composer_with_typed_note(&mut app);

        app.handle(ctrl_key('g'));
        let request = app.pending_editor.take().expect("editor queued");
        let (path, target) = match &request.purpose {
            crate::editor::EditorPurpose::TextBox { path, target } => (path.clone(), *target),
            other => panic!("expected a text box purpose, got {other:?}"),
        };
        assert_eq!(target, crate::editor::TextBoxTarget::Composer);
        assert!(
            path.starts_with(std::env::temp_dir()),
            "scratch, not the gitdir: {}",
            path.display()
        );
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "why 42?");
        assert!(
            app.composer_open(),
            "the composer stays put while suspended"
        );

        std::fs::write(&path, "edited externally").unwrap();
        app.editor_finished(request.purpose, Ok(true));

        assert!(!path.exists(), "the scratch file is removed");
        let composer = app
            .diff
            .as_ref()
            .unwrap()
            .composer
            .as_ref()
            .expect("composer stays open");
        assert_eq!(composer.buffer, "edited externally");
    }

    #[test]
    fn a_cancelled_composer_edit_keeps_the_buffer() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        composer_with_typed_note(&mut app);

        app.handle(ctrl_key('g'));
        let request = app.pending_editor.take().expect("editor queued");
        let path = match &request.purpose {
            crate::editor::EditorPurpose::TextBox { path, .. } => path.clone(),
            other => panic!("expected a text box purpose, got {other:?}"),
        };
        // the editor wrote something before exiting non-zero (e.g. vim's :cq)
        std::fs::write(&path, "an edit the editor never saved").unwrap();

        app.editor_finished(request.purpose, Ok(false));

        assert!(!path.exists(), "the scratch file is removed regardless");
        let composer = app
            .diff
            .as_ref()
            .unwrap()
            .composer
            .as_ref()
            .expect("composer stays open");
        assert_eq!(
            composer.buffer, "why 42?",
            "the cancelled edit changed nothing"
        );
    }

    #[test]
    fn a_failed_composer_editor_keeps_the_buffer_and_says_so() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        composer_with_typed_note(&mut app);

        app.handle(ctrl_key('g'));
        let request = app.pending_editor.take().expect("editor queued");
        let path = match &request.purpose {
            crate::editor::EditorPurpose::TextBox { path, .. } => path.clone(),
            other => panic!("expected a text box purpose, got {other:?}"),
        };

        app.editor_finished(request.purpose, Err("boom".to_owned()));

        assert!(!path.exists(), "the scratch file is removed regardless");
        let composer = app
            .diff
            .as_ref()
            .unwrap()
            .composer
            .as_ref()
            .expect("composer stays open");
        assert_eq!(composer.buffer, "why 42?");
        let message = app.message.clone().expect("message");
        assert_eq!(message.severity, crate::app::Severity::Error);
        assert!(message.text.contains("editor failed"));
        assert!(message.text.contains("boom"));
    }

    #[test]
    fn outdated_comment_is_flagged_when_the_line_text_drifts() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.review.session.add_comment(
            Anchor {
                file: "src/lib.rs".to_owned(),
                line: Some(2),
                line_end: None,
                on_old_side: false,
                line_text: Some("    43".to_owned()),
            },
            "reviewer",
            "stale snapshot",
        );
        let diff = app.diff.as_mut().unwrap();
        diff.invalidate();
        diff.ensure_rows(&app.review);
        assert!(
            rows(&app)
                .iter()
                .any(|r| matches!(r, DiffRow::Comment { outdated: true, .. })),
            "drifted line_text flags the comment outdated"
        );
    }

    #[test]
    fn comment_for_a_departed_line_attaches_at_the_top() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.review.session.add_comment(
            Anchor {
                file: "src/lib.rs".to_owned(),
                line: Some(99),
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "moved on",
        );
        let diff = app.diff.as_mut().unwrap();
        diff.invalidate();
        diff.ensure_rows(&app.review);
        let rows = rows(&app);
        assert!(
            matches!(rows.first(), Some(DiffRow::Comment { outdated: true, .. })),
            "orphaned comment sits at the top, flagged outdated: {rows:?}"
        );
    }

    #[test]
    fn scoped_open_selects_the_file_and_focuses_the_diff() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.open_working_tree_file("src/lib.rs");
        assert_eq!(focus(&app), Pane::Diff);
        assert_eq!(selected_path(&app), "src/lib.rs");
        assert_eq!(app.diff.as_ref().unwrap().cursor, 0, "starts at the top");
    }

    #[test]
    fn visual_selection_comments_a_new_side_range() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        // first hunk: "-line 1" then "+line one" then context lines
        cursor_to_line(&mut app, |r| {
            matches!(
                r,
                DiffRow::Line {
                    hunk: 0,
                    line: 1,
                    ..
                }
            )
        });
        app.handle(key('V'));
        assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
        app.handle(key('j'));
        app.handle(key('j'));
        app.handle(key('c'));
        type_text(&mut app, "this block");
        app.handle(key('\n'));
        let comment = &app.review.session.comments[0];
        assert_eq!(comment.anchor.line, Some(1));
        assert_eq!(comment.anchor.line_end, Some(3));
        assert!(!comment.anchor.on_old_side);
        assert_eq!(comment.anchor.line_text.as_deref(), Some("line 3"));
        assert!(
            app.diff.as_ref().unwrap().visual_anchor.is_none(),
            "selection ends once the comment lands"
        );
    }

    #[test]
    fn visual_selection_anchored_on_a_deleted_line_uses_the_old_side() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        // hunk 0 line 0 is the deleted "line 1"
        cursor_to_line(&mut app, |r| {
            matches!(
                r,
                DiffRow::Line {
                    hunk: 0,
                    line: 0,
                    ..
                }
            )
        });
        app.handle(key('V'));
        app.handle(key('j'));
        app.handle(key('j'));
        app.handle(key('c'));
        type_text(&mut app, "old side");
        app.handle(key('\n'));
        let comment = &app.review.session.comments[0];
        assert!(comment.anchor.on_old_side);
        // selected rows: -line 1 (old 1), +line one (no old no), context
        // line 2 (old 2) → range 1..2 on the old side
        assert_eq!(comment.anchor.line, Some(1));
        assert_eq!(comment.anchor.line_end, Some(2));
    }

    #[test]
    fn escape_cancels_visual_selection() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
        app.handle(key('V'));
        assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
        app.handle(AppEvent::Key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Esc,
            crossterm::event::KeyModifiers::NONE,
        )));
        assert!(app.diff.as_ref().unwrap().visual_anchor.is_none());
        // V twice toggles off as well
        app.handle(key('V'));
        app.handle(key('V'));
        assert!(app.diff.as_ref().unwrap().visual_anchor.is_none());
    }

    #[test]
    fn reply_and_resolve_walk_the_comment_lifecycle() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position;
        app.handle(key('c'));
        type_text(&mut app, "question");
        app.handle(key('\n'));

        // the comment header row sits right under the anchored line
        settle_submit(&mut app);
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position + 1;
        app.handle(key('r'));
        assert!(app.composer_open());
        type_text(&mut app, "answer");
        app.handle(key('\n'));
        let comment = &app.review.session.comments[0];
        assert_eq!(comment.status, CommentStatus::Replied);
        assert_eq!(comment.replies.len(), 1);
        assert_eq!(comment.replies[0].body, "answer");

        // the block grew by the reply line; resolve from the same header
        settle_submit(&mut app);
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position + 1;
        app.handle(key('R'));
        assert_eq!(
            app.review.session.comments[0].status,
            CommentStatus::Resolved
        );
        let reloaded = diffler_core::store::load(&fixture.root).unwrap();
        assert_eq!(reloaded.comments[0].status, CommentStatus::Resolved);
    }

    /// Row indices of the composer's rows, in order.
    fn composer_rows(app: &App) -> Vec<usize> {
        app.diff
            .as_ref()
            .expect("diff view")
            .rows()
            .iter()
            .enumerate()
            .filter(|(_, row)| matches!(row, DiffRow::Composer { .. }))
            .map(|(index, _)| index)
            .collect()
    }

    #[test]
    fn the_composer_takes_the_rows_under_the_line_it_comments_on() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let line = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = line;
        app.handle(key('c'));
        let rows = composer_rows(&app);
        assert_eq!(
            rows.first().copied(),
            Some(line + 1),
            "the card opens directly under its line"
        );
        assert!(rows.len() >= 3, "header, a body row, and the hint footer");
        assert!(
            rows.windows(2).all(|pair| pair[1] == pair[0] + 1),
            "the card is one contiguous block: {rows:?}"
        );
    }

    #[test]
    fn the_composer_grows_a_row_when_the_text_wraps() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.diff.as_mut().unwrap().set_wrap_width(60);
        app.handle(key('c'));
        let before = composer_rows(&app).len();
        type_text(
            &mut app,
            &"x".repeat(super::super::composer::card_budget(60) + 1),
        );
        assert_eq!(
            composer_rows(&app).len(),
            before + 1,
            "one more row once the text passes the wrap budget"
        );
    }

    /// The composer wraps the raw buffer per character and the finished card
    /// word-wraps its markdown, so they only have to agree on the budget. An
    /// unbroken token exactly that wide is where a mismatch shows.
    #[test]
    fn a_draft_and_the_comment_it_becomes_wrap_to_the_same_budget() {
        let width = 48;
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().set_wrap_width(width);
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('c'));
        type_text(
            &mut app,
            &"w".repeat(super::super::composer::card_budget(width)),
        );
        let drafted = composer_rows(&app).len();
        app.handle(key('\n'));
        app.diff.as_mut().unwrap().ensure_rows(&app.review);
        let landed = app
            .diff
            .as_ref()
            .unwrap()
            .rows()
            .iter()
            .filter(|row| matches!(row, DiffRow::Comment { .. }))
            .count();
        assert_eq!(drafted, 3, "header, the one full row, footer");
        assert_eq!(
            drafted, landed,
            "writing a comment and reading it back take the same rows"
        );
    }

    /// Put the sidebar cursor on the tree row for `dir`.
    fn cursor_to_dir(app: &mut App, dir: &str) {
        let review = &app.review;
        let diff = app.diff.as_ref().expect("diff view");
        let rows = super::sidebar_rows(diff, review);
        let at = rows
            .iter()
            .position(
                |row| matches!(&row.node, crate::tree::TreeNode::Dir { path, .. } if path == dir),
            )
            .unwrap_or_else(|| panic!("a tree row for {dir}"));
        let diff = app.diff.as_mut().expect("diff view");
        diff.focus = Pane::List;
        diff.tree_cursor = at;
    }

    fn viewed_paths(app: &App) -> Vec<String> {
        let source = app.active_review_source();
        let session = app.review.session_for(&source);
        let mut out: Vec<String> = app
            .diff
            .as_ref()
            .unwrap()
            .model(&app.review)
            .files
            .iter()
            .filter(|f| session.is_viewed(&f.path, &f.content_hash()))
            .map(|f| f.path.clone())
            .collect();
        out.sort();
        out
    }

    /// Two files directly under `src/`, one nested a level deeper, and one
    /// outside it entirely, so a subtree mark has something real to cover and
    /// something to leave alone.
    fn nested_fixture() -> Fixture {
        let fixture = Fixture::new();
        fixture.write("src/lib.rs", "pub fn a() {}\n");
        fixture.write("src/main.rs", "fn main() {}\n");
        fixture.write("src/deep/inner.rs", "pub fn b() {}\n");
        fixture.write("docs/readme.md", "hi\n");
        fixture.commit_all("initial");
        fixture.write("src/lib.rs", "pub fn a() -> u32 {\n    1\n}\n");
        fixture.write("src/main.rs", "fn main() {\n    println!();\n}\n");
        fixture.write("src/deep/inner.rs", "pub fn b() -> u32 {\n    2\n}\n");
        fixture.write("docs/readme.md", "hi there\n");
        fixture
    }

    #[test]
    fn viewing_a_directory_marks_the_whole_subtree_and_nothing_outside_it() {
        let fixture = nested_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Tree);
        cursor_to_dir(&mut app, "src");
        app.handle(key('m'));
        assert_eq!(
            viewed_paths(&app),
            ["src/deep/inner.rs", "src/lib.rs", "src/main.rs"],
            "every file under src, including the nested one"
        );
    }

    #[test]
    fn viewing_a_nested_directory_leaves_its_parent_alone() {
        let fixture = nested_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Tree);
        cursor_to_dir(&mut app, "src/deep");
        app.handle(key('m'));
        assert_eq!(viewed_paths(&app), ["src/deep/inner.rs"]);
    }

    #[test]
    fn viewing_an_already_viewed_directory_puts_it_back() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Tree);
        cursor_to_dir(&mut app, "src");
        app.handle(key('m'));
        assert!(!viewed_paths(&app).is_empty());
        cursor_to_dir(&mut app, "src");
        app.handle(key('m'));
        assert!(
            viewed_paths(&app).is_empty(),
            "a second press unmarks the subtree"
        );
    }

    /// Put the sidebar cursor on the section header for `label`.
    fn cursor_to_section(app: &mut App, label: &str) {
        let review = &app.review;
        let diff = app.diff.as_ref().expect("diff view");
        let rows = super::sidebar_rows(diff, review);
        let at = rows
            .iter()
            .position(|row| {
                matches!(&row.node, crate::tree::TreeNode::Section { bucket, .. }
                    if bucket.label() == label)
            })
            .unwrap_or_else(|| panic!("a section row for {label}: {rows:?}"));
        let diff = app.diff.as_mut().expect("diff view");
        diff.focus = Pane::List;
        diff.tree_cursor = at;
    }

    /// One source file and two the built-in rules call Generated (a lockfile
    /// and a snapshot), so a kind header stands for more than one file.
    fn kinds_fixture() -> Fixture {
        let fixture = Fixture::new();
        fixture.write("src/lib.rs", "pub fn a() {}\n");
        fixture.write("tests/snapshots/render.snap", "old frame\n");
        fixture.write("package-lock.json", "{\n  \"lockfileVersion\": 3\n}\n");
        fixture.commit_all("initial");
        fixture.write("src/lib.rs", "pub fn a() -> u32 {\n    1\n}\n");
        fixture.write("tests/snapshots/render.snap", "new frame\n");
        fixture.write("package-lock.json", "{\n  \"lockfileVersion\": 4\n}\n");
        fixture
    }

    /// A kind header stands for every file in its bucket, and Generated opens
    /// folded, so the mark cannot come from the rows on screen.
    #[test]
    fn viewing_a_kind_section_marks_every_file_it_holds() {
        let fixture = kinds_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        let rows = super::sidebar_rows(app.diff.as_ref().expect("diff"), &app.review);
        assert!(
            rows.iter().any(|row| matches!(&row.node,
                crate::tree::TreeNode::Section { bucket, folded, .. }
                    if bucket.label() == "Generated" && *folded)),
            "Generated opens folded, so the mark cannot read the rows: {rows:?}"
        );
        cursor_to_section(&mut app, "Generated");
        app.handle(key('m'));
        assert_eq!(
            viewed_paths(&app),
            ["package-lock.json", "tests/snapshots/render.snap"],
            "the whole bucket, folded though it is"
        );
    }

    #[test]
    fn viewing_a_kind_section_again_puts_it_back() {
        let fixture = kinds_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        cursor_to_section(&mut app, "Generated");
        app.handle(key('m'));
        assert!(!viewed_paths(&app).is_empty());
        cursor_to_section(&mut app, "Generated");
        app.handle(key('m'));
        assert!(viewed_paths(&app).is_empty(), "a second press unmarks it");
    }

    #[test]
    fn viewing_the_to_review_section_clears_the_whole_review() {
        let fixture = kinds_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
        cursor_to_section(&mut app, "To review");
        app.handle(key('m'));
        assert_eq!(
            viewed_paths(&app),
            [
                "package-lock.json",
                "src/lib.rs",
                "tests/snapshots/render.snap"
            ]
        );
    }

    /// The bucket a header stands for is read from the grouping, so a kind the
    /// diff has nothing for cannot be reached and its neighbours are untouched.
    #[test]
    fn viewing_one_kind_leaves_the_others_alone() {
        let fixture = kinds_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        cursor_to_section(&mut app, "Source");
        app.handle(key('m'));
        assert_eq!(viewed_paths(&app), ["src/lib.rs"]);
    }

    fn tree_cursor_row(app: &App) -> String {
        let diff = app.diff.as_ref().expect("diff view");
        let rows = super::sidebar_rows(diff, &app.review);
        match &rows[diff.tree_cursor].node {
            crate::tree::TreeNode::Dir { path, .. } => format!("dir {path}"),
            crate::tree::TreeNode::Section { bucket, .. } => format!("section {}", bucket.label()),
            crate::tree::TreeNode::File { name, .. } => format!("file {name}"),
            crate::tree::TreeNode::Stop { index } => format!("stop {index}"),
            crate::tree::TreeNode::WalkthroughSummary => "walkthrough_summary".to_owned(),
        }
    }

    /// `]` walks folder to folder in the tree layout, the way it walks
    /// sections on the status screen.
    /// Four files in one group, so marking has somewhere to sort them to.
    fn flat_fixture() -> Fixture {
        let fixture = Fixture::new();
        for name in ["a.rs", "b.rs", "c.rs", "d.rs"] {
            fixture.write(name, "fn x() {}\n");
        }
        fixture.commit_all("base");
        for name in ["a.rs", "b.rs", "c.rs", "d.rs"] {
            fixture.write(name, "fn x() -> u32 {\n    1\n}\n");
        }
        fixture
    }

    /// Marking the last file in a group sorts it to the top of that group. The
    /// reader must not be dragged up there with it: they stay on the row they
    /// were reading, which is now the file that was above.
    #[test]
    fn marking_the_bottom_file_keeps_the_reader_at_the_bottom() {
        for layout in [
            crate::config::FileLayout::Tree,
            crate::config::FileLayout::Kinds,
        ] {
            let fixture = flat_fixture();
            let mut app = diff_app_with_layout(&fixture, layout);
            app.handle(key('G'));
            assert_eq!(selected_path(&app), "d.rs", "{layout:?}");
            let row = app.diff.as_ref().expect("diff").tree_cursor;

            app.handle(key('m'));
            assert_eq!(
                selected_path(&app),
                "c.rs",
                "{layout:?}: the next one to read, not the file that moved"
            );
            assert_eq!(
                app.diff.as_ref().expect("diff").tree_cursor,
                row,
                "{layout:?}: and the cursor holds its row"
            );
        }
    }

    /// Marking up the list from the bottom keeps walking the unviewed files
    /// rather than bouncing off the top of the group each time.
    #[test]
    fn marking_from_the_bottom_walks_up_through_what_is_left() {
        let fixture = flat_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        app.handle(key('G'));
        let mut walked = vec![selected_path(&app)];
        for _ in 0..3 {
            app.handle(key('m'));
            walked.push(selected_path(&app));
        }
        assert_eq!(walked, ["d.rs", "c.rs", "b.rs", "a.rs"]);
    }

    /// With a file below, the walk still goes down: the hold only applies when
    /// there is nothing under the one just marked.
    #[test]
    fn marking_with_a_file_below_still_steps_down() {
        let fixture = flat_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        assert_eq!(selected_path(&app), "a.rs");
        app.handle(key('m'));
        assert_eq!(selected_path(&app), "b.rs");
    }

    #[test]
    fn brackets_step_the_sidebar_folder_by_folder() {
        let fixture = nested_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Tree);
        // the tree opens with the cursor on the selected file, inside a folder
        assert_eq!(tree_cursor_row(&app), "file readme.md");
        app.handle(key('['));
        assert_eq!(
            tree_cursor_row(&app),
            "dir docs",
            "back to the folder holding it"
        );
        app.handle(key(']'));
        assert_eq!(tree_cursor_row(&app), "dir src");
        app.handle(key(']'));
        assert_eq!(
            tree_cursor_row(&app),
            "dir src/deep",
            "a nested folder counts"
        );
        app.handle(key('['));
        assert_eq!(tree_cursor_row(&app), "dir src", "and back up");
    }

    #[test]
    fn brackets_step_the_sidebar_section_by_section() {
        let fixture = kinds_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        app.handle(key(']'));
        assert_eq!(tree_cursor_row(&app), "section Generated");
        app.handle(key('['));
        assert_eq!(tree_cursor_row(&app), "section Source");
    }

    /// The last group has nothing after it, so the cursor stays put instead of
    /// wrapping to the top.
    #[test]
    fn stepping_past_the_last_group_stands_still() {
        let fixture = nested_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Tree);
        app.handle(key('G'));
        let last = tree_cursor_row(&app);
        app.handle(key(']'));
        assert_eq!(tree_cursor_row(&app), last);
    }

    /// The diff pane keeps the brackets for hunks: the motion moves the pane
    /// holding the keyboard.
    #[test]
    fn brackets_in_the_diff_pane_still_step_hunks() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.handle(key('\n'));
        assert_eq!(focus(&app), Pane::Diff);
        let before = app.diff.as_ref().expect("diff").cursor;
        app.handle(key(']'));
        let diff = app.diff.as_ref().expect("diff");
        assert!(
            matches!(diff.rows.get(diff.cursor), Some(DiffRow::Hunk { .. }))
                || diff.cursor == before
        );
    }

    #[test]
    fn viewing_a_file_row_still_marks_only_that_file() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Tree);
        select_file(&mut app, "src/lib.rs");
        app.handle(key('m'));
        assert_eq!(viewed_paths(&app), ["src/lib.rs"]);
    }

    #[test]
    fn a_file_level_composer_opens_above_the_diff() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        assert_eq!(focus(&app), Pane::List);
        app.handle(key('c'));
        assert_eq!(
            composer_rows(&app).first().copied(),
            Some(0),
            "a whole-file comment is written where it renders, at the top"
        );
    }

    #[test]
    fn a_reply_composer_opens_under_the_thread_it_answers() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let line = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = line;
        app.handle(key('c'));
        type_text(&mut app, "question");
        app.handle(key('\n'));
        settle_submit(&mut app);
        app.diff.as_mut().unwrap().cursor = added_line_position(&app) + 1;
        app.handle(key('r'));
        let last_comment = app
            .diff
            .as_ref()
            .unwrap()
            .rows()
            .iter()
            .rposition(|row| matches!(row, DiffRow::Comment { .. }))
            .expect("the thread being replied to");
        assert_eq!(
            composer_rows(&app).first().copied(),
            Some(last_comment + 1),
            "the draft reply sits under the whole block"
        );
        assert!(last_comment > line, "and the block sits under its line");
    }

    #[test]
    fn an_edit_composer_stands_in_for_the_block_it_rewrites() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let line = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = line;
        app.handle(key('c'));
        type_text(&mut app, "note");
        app.handle(key('\n'));
        settle_submit(&mut app);
        app.diff.as_mut().unwrap().cursor = added_line_position(&app) + 1;
        app.handle(key('c'));
        assert_eq!(composer_rows(&app).first().copied(), Some(line + 1));
        assert!(
            !app.diff
                .as_ref()
                .unwrap()
                .rows()
                .iter()
                .any(|row| matches!(row, DiffRow::Comment { .. })),
            "the comment being edited gives up its rows to the draft"
        );
    }

    #[test]
    fn the_pane_cursor_rides_the_caret_so_a_tall_card_scrolls_with_it() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().set_wrap_width(60);
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('c'));
        let caret_row = |app: &App| {
            let diff = app.diff.as_ref().unwrap();
            let caret = diff.composer.as_ref().unwrap().caret_line(diff.wrap_width);
            diff.rows()
                .iter()
                .position(|row| matches!(row, DiffRow::Composer { line } if *line == caret))
        };
        assert_eq!(Some(app.diff.as_ref().unwrap().cursor), caret_row(&app));
        // a card taller than any viewport must keep the cursor on the row the
        // text is landing on, not on the header far above it
        for _ in 0..6 {
            type_text(
                &mut app,
                &"y".repeat(super::super::composer::card_budget(60)),
            );
        }
        let rows = composer_rows(&app);
        assert!(rows.len() > 6, "the card grew tall: {}", rows.len());
        assert_eq!(Some(app.diff.as_ref().unwrap().cursor), caret_row(&app));
        assert!(
            app.diff.as_ref().unwrap().cursor > rows[0],
            "the cursor left the header behind"
        );
    }

    #[test]
    fn reopening_the_same_source_keeps_the_draft_on_screen() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let file = app.diff.as_ref().unwrap().selected;
        assert_ne!(file, 0, "the draft is not on the file a reload defaults to");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('c'));
        type_text(&mut app, "still writing");
        // a queued open landing on the source already in view
        app.open_working_tree_diff(None);
        assert_eq!(
            app.diff
                .as_ref()
                .and_then(|d| d.composer.as_ref())
                .map(|c| c.buffer.clone()),
            Some("still writing".to_owned())
        );
        assert_eq!(app.diff.as_ref().unwrap().selected, file, "same file");
        assert!(
            !composer_rows(&app).is_empty(),
            "an open composer the pane cannot draw would still eat every key"
        );
    }

    #[test]
    fn esc_closes_the_composer_and_gives_its_rows_back() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('c'));
        type_text(&mut app, "never mind");
        app.handle(crate::test_support::esc_key());
        assert!(!app.composer_open());
        assert!(composer_rows(&app).is_empty());
        assert!(app.review.session.comments.is_empty());
    }

    #[test]
    fn a_blank_composer_submits_as_a_cancel() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('c'));
        type_text(&mut app, "   ");
        app.handle(key('\n'));
        assert!(!app.composer_open());
        assert!(app.review.session.comments.is_empty());
    }

    #[test]
    fn c_over_a_comment_edits_it() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position;
        app.handle(key('c'));
        type_text(&mut app, "old note");
        app.handle(key('\n'));

        // then move onto the comment row: `c` edits, prefilled with the body
        settle_submit(&mut app);
        app.diff.as_mut().unwrap().cursor = added_line_position(&app) + 1;
        app.handle(key('c'));
        let composer = app
            .diff
            .as_ref()
            .and_then(|d| d.composer.as_ref())
            .expect("the composer opens over the comment");
        assert_eq!(
            composer.buffer, "old note",
            "prefilled with the existing body"
        );
        // clear and retype
        for _ in 0.."old note".len() {
            app.handle(crate::test_support::key_backspace());
        }
        type_text(&mut app, "new note");
        app.handle(key('\n'));

        assert_eq!(app.review.session.comments.len(), 1, "edited, not added");
        assert_eq!(app.review.session.comments[0].body, "new note");
    }

    #[test]
    fn reply_off_a_comment_row_hints() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        app.handle(key('r'));
        let message = app.message.expect("message");
        assert!(message.text.contains("comment"));
    }

    #[test]
    fn c_in_the_file_list_comments_on_the_whole_file() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        assert_eq!(focus(&app), Pane::List);
        app.handle(key('c'));
        assert!(
            app.composer_open(),
            "c on a file opens a comment, not a hint"
        );
        type_text(&mut app, "whole-file note");
        app.handle(key('\n'));
        let comment = app.review.session.comments.first().expect("a file comment");
        assert_eq!(comment.anchor.line, None, "file-level anchor (no line)");
        assert!(comment.body.contains("whole-file note"));
    }

    #[test]
    fn line_scoped_keys_in_the_list_hint_to_move_into_the_diff() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        assert_eq!(focus(&app), Pane::List);
        app.handle(key('r')); // reply needs a comment row, only in the diff pane
        let message = app.message.expect("message");
        assert!(message.text.contains("move into the diff"));
    }

    /// The walk follows the sidebar order: the row under the one just marked
    /// is where the reader was heading.
    #[test]
    fn marking_viewed_steps_to_the_file_listed_under_it() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        assert_eq!(
            tree_kinds(&app),
            vec!["dir", "file:lib.rs", "file:ci.yml", "file:todo.md"],
            "directories first, so the sidebar order is not the model order"
        );
        assert_eq!(selected_path(&app), "ci.yml");

        app.handle(key('m'));
        assert!(app.is_path_viewed("ci.yml"));
        assert_eq!(
            selected_path(&app),
            "todo.md",
            "the row under ci.yml, not the next file in the diff"
        );

        app.handle(key('m'));
        assert!(app.is_path_viewed("todo.md"));
        assert_eq!(
            selected_path(&app),
            "todo.md",
            "nothing below: the selection stays"
        );
    }

    /// Three files in one directory, so a group has an order to sort.
    fn grouped_fixture() -> Fixture {
        let fixture = Fixture::new();
        for name in ["a.rs", "b.rs", "c.rs"] {
            fixture.write(&format!("src/{name}"), "fn one() {}\n");
        }
        fixture.commit_all("base");
        for name in ["a.rs", "b.rs", "c.rs"] {
            fixture.write(&format!("src/{name}"), "fn one() -> u8 {\n    1\n}\n");
        }
        fixture
    }

    /// What is done piles at the top of a directory, so the run still to read
    /// is the bottom of the group and never moves out from under the cursor.
    #[test]
    fn a_viewed_file_sorts_to_the_top_of_its_directory() {
        let fixture = grouped_fixture();
        let mut app = diff_app(&fixture);
        assert_eq!(
            tree_kinds(&app),
            vec!["dir", "file:a.rs", "file:b.rs", "file:c.rs"]
        );

        select_file(&mut app, "src/b.rs");
        app.handle(key('m'));
        assert_eq!(
            tree_kinds(&app),
            vec!["dir", "file:b.rs", "file:a.rs", "file:c.rs"],
            "b.rs sorts above what is left to read"
        );
        assert_eq!(
            selected_path(&app),
            "src/c.rs",
            "the row that was under b.rs"
        );

        app.handle(key('m'));
        assert_eq!(
            tree_kinds(&app),
            vec!["dir", "file:b.rs", "file:c.rs", "file:a.rs"],
            "the viewed run keeps the order the diff gave it"
        );
    }

    /// Folding a group is the reader saying "not this one", so the walk stops
    /// at what is on screen and reports what it left behind. `u` is the key
    /// that goes hunting.
    #[test]
    fn the_walk_stops_at_a_folded_group_and_says_what_is_left() {
        let fixture = Fixture::new();
        fixture.write("ci.yml", "on: push\n");
        fixture.write("Cargo.lock", "# generated\n");
        fixture.commit_all("base");
        fixture.write("ci.yml", "on: [push]\n");
        fixture.write("Cargo.lock", "# generated, again\n");
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        // Generated starts folded, so Cargo.lock has no row of its own
        assert_eq!(
            tree_kinds(&app),
            vec!["section:Config:1", "file:ci.yml", "section:Generated:1"]
        );

        select_file(&mut app, "ci.yml");
        app.handle(key('m'));
        assert_eq!(
            selected_path(&app),
            "ci.yml",
            "the folded section is not walked into"
        );
        assert_eq!(
            app.message.as_ref().map(|m| m.text.as_str()),
            Some("end of the list, 1 still unviewed")
        );

        // u reaches it, folded or not
        app.handle(key('u'));
        assert_eq!(selected_path(&app), "Cargo.lock");
    }

    #[test]
    fn a_viewed_file_sorts_to_the_top_of_its_kind_section() {
        let fixture = grouped_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        assert_eq!(
            tree_kinds(&app),
            vec![
                "section:Source:3",
                "file:src/a.rs",
                "file:src/b.rs",
                "file:src/c.rs"
            ]
        );

        select_file(&mut app, "src/b.rs");
        app.handle(key('m'));
        assert_eq!(
            tree_kinds(&app),
            vec![
                "section:Source:3",
                "file:src/b.rs",
                "file:src/a.rs",
                "file:src/c.rs"
            ]
        );
        assert_eq!(selected_path(&app), "src/c.rs");
    }

    #[test]
    fn capital_u_clears_all_viewed_marks() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let paths: Vec<String> = app
            .review
            .model()
            .files
            .iter()
            .map(|f| f.path.clone())
            .collect();
        for path in &paths {
            select_file(&mut app, path);
            app.handle(key('m'));
        }
        assert!(
            paths.iter().all(|p| app.is_path_viewed(p)),
            "all marked first"
        );

        app.handle(key('U'));
        assert!(
            paths.iter().all(|p| !app.is_path_viewed(p)),
            "U cleared every viewed mark"
        );
    }

    #[test]
    fn unmarking_viewed_does_not_move_the_selection() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let first = selected_path(&app);
        assert_eq!(first, "ci.yml");
        app.handle(key('m'));
        select_file(&mut app, &first);
        app.handle(key('m'));
        assert!(!app.is_path_viewed(&first));
        assert_eq!(
            selected_path(&app),
            first,
            "unmarking keeps the selection in place"
        );
    }

    #[test]
    fn viewed_can_be_marked_from_the_diff_pane() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let first = selected_path(&app);
        enter_diff_pane(&mut app);
        app.handle(key('m'));
        assert!(app.is_path_viewed(&first));
        // marking advanced the selection past the viewed file
        assert_ne!(selected_path(&app), first);
    }

    #[test]
    fn review_layout_buckets_files_with_the_viewed_pile_folded() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
        assert_eq!(
            tree_kinds(&app),
            [
                "section:To review:3",
                "file:ci.yml",
                "file:src/lib.rs",
                "file:todo.md",
                "section:Viewed:0",
            ]
        );
        // v moves the file into the folded viewed bucket and advances
        app.handle(key('m'));
        assert_eq!(
            tree_kinds(&app),
            [
                "section:To review:2",
                "file:src/lib.rs",
                "file:todo.md",
                "section:Viewed:1",
            ]
        );
        assert_eq!(selected_path(&app), "src/lib.rs");
    }

    #[test]
    fn toggling_the_viewed_bucket_reveals_and_hides_its_files() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
        app.handle(key('m'));
        // the folded viewed header is the last row; za on it unfolds
        app.handle(key('G'));
        app.handle(key('z'));
        app.handle(key('a'));
        assert_eq!(
            tree_kinds(&app),
            [
                "section:To review:2",
                "file:src/lib.rs",
                "file:todo.md",
                "section:Viewed:1",
                "file:ci.yml",
            ]
        );
        // <cr> on the header folds it back
        app.handle(key('\n'));
        assert_eq!(
            tree_kinds(&app).last().map(String::as_str),
            Some("section:Viewed:1")
        );
    }

    #[test]
    fn editing_a_viewed_file_returns_it_to_the_to_review_bucket() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
        app.handle(key('m'));
        assert_eq!(tree_kinds(&app)[0], "section:To review:2");
        // the file changes on disk: its hash no longer matches the mark
        fixture.write("ci.yml", "on: push\njobs: {}\n");
        app.handle(AppEvent::RepoChanged);
        app.settle_refresh();
        assert_eq!(
            tree_kinds(&app)[0],
            "section:To review:3",
            "stale viewed mark drops the file back into to-review"
        );
    }

    #[test]
    fn t_cycles_the_sidebar_through_the_tree_the_review_buckets_and_the_kinds() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        assert!(tree_kinds(&app).contains(&"dir".to_owned()));
        app.handle(key('t'));
        assert_eq!(tree_kinds(&app)[0], "section:To review:3");
        app.handle(key('t'));
        assert_eq!(tree_kinds(&app)[0], "section:Source:1");
        app.handle(key('t'));
        assert!(
            tree_kinds(&app).contains(&"dir".to_owned()),
            "wraps back to the tree"
        );
    }

    #[test]
    fn the_kinds_layout_groups_by_what_a_file_is_and_hides_the_empty_buckets() {
        let fixture = standard_fixture();
        let app = diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        assert_eq!(
            tree_kinds(&app),
            vec![
                "section:Source:1",
                "file:src/lib.rs",
                "section:Docs:1",
                "file:todo.md",
                "section:Config:1",
                "file:ci.yml",
            ],
            "one header per kind the diff has, none for the kinds it does not"
        );
    }

    #[test]
    fn the_repos_declared_kinds_land_from_the_worker_and_regroup_the_sidebar() {
        let fixture = standard_fixture();
        let app = &mut diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        assert!(tree_kinds(app).contains(&"section:Source:1".to_owned()));
        let request = app.pending_declared.take().expect("a queued lookup");
        assert!(request.paths.contains(&"src/lib.rs".to_owned()));

        let kinds = HashMap::from([("src/lib.rs".to_owned(), Kind::Generated)]);
        app.handle(AppEvent::DeclaredKinds {
            kinds,
            token: request.token,
        });

        assert!(
            tree_kinds(app).contains(&"section:Generated:1".to_owned()),
            "{:?}",
            tree_kinds(app)
        );
    }

    #[test]
    fn an_answer_for_a_replaced_file_list_is_dropped() {
        let fixture = standard_fixture();
        let app = &mut diff_app_with_layout(&fixture, crate::config::FileLayout::Kinds);
        let stale = app.pending_declared.take().expect("a queued lookup").token;
        // the view moves on, so the answer in flight is about the old list
        app.queue_declared();

        app.handle(AppEvent::DeclaredKinds {
            kinds: HashMap::from([("src/lib.rs".to_owned(), Kind::Generated)]),
            token: stale,
        });

        assert!(tree_kinds(app).contains(&"section:Source:1".to_owned()));
    }

    #[test]
    fn a_reader_glob_moves_a_file_between_kind_buckets() {
        let fixture = standard_fixture();
        let mut loaded = LoadedConfig::default();
        loaded.config.ui.diff_file_layout = crate::config::FileLayout::Kinds;
        loaded.config.classify.tests = vec!["src/**".to_owned()];
        let mut app = App::new(fixture.review(), loaded);
        app.open_working_tree_diff(None);
        assert!(
            tree_kinds(&app).contains(&"section:Tests:1".to_owned()),
            "{:?}",
            tree_kinds(&app)
        );
    }

    #[test]
    fn unmarking_in_the_review_layout_reseats_the_cursor_on_the_moved_row() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
        // view everything, then unfold the viewed bucket and step onto a file
        app.handle(key('m'));
        app.handle(key('m'));
        app.handle(key('m'));
        app.handle(key('G'));
        app.handle(key('z'));
        app.handle(key('a'));
        app.handle(key('j'));
        assert_eq!(selected_path(&app), "ci.yml");
        // unmark: ci.yml jumps up into to-review; the cursor must follow it
        app.handle(key('m'));
        assert_eq!(
            tree_kinds(&app),
            [
                "section:To review:1",
                "file:ci.yml",
                "section:Viewed:2",
                "file:src/lib.rs",
                "file:todo.md",
            ]
        );
        assert_eq!(tree_cursor(&app), 1, "cursor sits on the moved file row");
    }

    #[test]
    fn marking_the_last_unviewed_file_keeps_the_cursor_in_range() {
        let fixture = standard_fixture();
        let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
        // walk the files, marking each: the last one empties the to-review
        // bucket under the cursor
        for _ in 0..app
            .diff
            .as_ref()
            .expect("diff")
            .model(&app.review)
            .files
            .len()
        {
            app.handle(key('m'));
        }
        let rows = tree_row_count(&app);
        assert_eq!(rows, 2, "both buckets, all files folded away");
        assert!(
            tree_cursor(&app) < rows,
            "cursor clamps into the shrunken row list"
        );
    }

    #[test]
    fn cycling_the_sidebar_layout_drops_a_committed_search() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.handle(key('/'));
        app.handle(key('l'));
        app.handle(key('\n'));
        assert!(app.search.is_some(), "search committed on the tree rows");
        app.handle(key('t'));
        assert!(
            app.search.is_none(),
            "layout swap invalidates the search row indices"
        );
    }

    #[test]
    fn u_jumps_to_the_next_unviewed_file_wrapping_past_viewed_ones() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.handle(key('m')); // ci.yml viewed, selection lands on todo.md
        select_file(&mut app, "todo.md");
        app.handle(key('u'));
        assert_eq!(
            selected_path(&app),
            "src/lib.rs",
            "wraps past the viewed ci.yml"
        );
    }

    #[test]
    fn u_with_everything_viewed_says_so() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        for path in ["ci.yml", "src/lib.rs", "todo.md"] {
            select_file(&mut app, path);
            app.handle(key('m'));
        }
        let before = selected_path(&app);
        app.handle(key('u'));
        assert_eq!(selected_path(&app), before);
        let message = app.message.expect("message");
        assert!(message.text.contains("every file is viewed"));
    }

    #[test]
    fn y_copies_the_selected_files_feedback_as_markdown() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position;
        app.handle(key('c'));
        type_text(&mut app, "why 42?");
        app.handle(key('\n'));
        app.review.session.add_comment(
            Anchor {
                file: "todo.md".to_owned(),
                line: None,
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "other file",
        );

        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('y'));
        let payload = app
            .pending_clipboard
            .clone()
            .expect("clipboard text queued");
        let toast = app.message.clone().expect("toast");
        assert_eq!(toast.text, "copied 1 comment (file)");
        let repo = fixture.root.file_name().unwrap().to_string_lossy();
        let expected = feedback::to_markdown(
            &app.review.session,
            app.review.model(),
            &FeedbackOptions {
                title: &format!("Review feedback: {repo} @ main (1 comment)"),
                file_filter: Some("src/lib.rs"),
                include_resolved: false,
            },
        );
        assert!(expected.contains("why 42?"));
        assert!(!expected.contains("other file"), "file filter applies");
        assert_eq!(payload, expected);

        app.handle(key('Y'));
        let message = app.message.clone().expect("toast");
        assert_eq!(message.text, "copied 2 comments (all)");
    }

    #[test]
    fn y_with_a_visual_selection_copies_the_diff_lines() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('V'));
        app.handle(key('y'));
        let text = app
            .pending_clipboard
            .clone()
            .expect("selection copied to the clipboard");
        assert!(
            text.starts_with('+'),
            "added line keeps its marker: {text:?}"
        );
        assert!(text.contains("42"), "the line text is copied: {text:?}");
        assert!(
            !text.contains("  1 "),
            "gutter line numbers are stripped: {text:?}"
        );
        assert_eq!(
            app.diff.as_ref().unwrap().visual_anchor,
            None,
            "the selection clears after copying"
        );
    }

    #[test]
    fn selecting_two_code_lines_yanks_them_with_their_markers() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| {
            matches!(
                r,
                DiffRow::Line {
                    hunk: 0,
                    line: 0,
                    ..
                }
            )
        });
        app.handle(key('V'));
        app.handle(key('j'));
        app.handle(key('y'));
        let text = app
            .pending_clipboard
            .clone()
            .expect("selection copied to the clipboard");
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, ["-line 1", "+line one"], "{lines:?}");
    }

    /// A stop with no anchor is prose alone: its card is the whole slide, so
    /// selecting it copies the paragraph the reader sees.
    #[test]
    fn selecting_a_stops_card_yanks_its_prose_lines() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        enter_diff_pane(&mut app);
        app.diff.as_mut().unwrap().cursor = 0;
        app.handle(key('V'));
        app.handle(key('G'));
        app.handle(key('y'));
        let text = app
            .pending_clipboard
            .clone()
            .expect("selection copied to the clipboard");
        assert!(text.contains("the overview"), "{text:?}");
    }

    #[test]
    fn selecting_the_summary_yanks_its_lines() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app_with_summary(&fixture);
        app.diff_tree_to(0);
        enter_diff_pane(&mut app);
        app.diff.as_mut().unwrap().cursor = 0;
        app.handle(key('V'));
        app.handle(key('G'));
        app.handle(key('y'));
        let text = app
            .pending_clipboard
            .clone()
            .expect("selection copied to the clipboard");
        assert!(text.contains("the shape of the change"), "{text:?}");
    }

    /// A whole-file comment renders above the diff, so a selection that
    /// starts on its card and runs into the first code line copies both,
    /// the card first, the same order the pane shows them in.
    #[test]
    fn selecting_across_a_card_and_the_code_below_it_yanks_both_in_order() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.review.session.add_comment(
            Anchor {
                file: "src/lib.rs".to_owned(),
                line: None,
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "why this file changed",
        );
        app.diff.as_mut().unwrap().invalidate();
        app.diff.as_mut().unwrap().ensure_rows(&app.review);
        let first_line = rows(&app)
            .iter()
            .position(|r| matches!(r, DiffRow::Line { .. }))
            .expect("a code line follows the card");
        app.diff.as_mut().unwrap().cursor = 0;
        app.handle(key('V'));
        app.diff.as_mut().unwrap().cursor = first_line;
        app.handle(key('y'));
        let text = app
            .pending_clipboard
            .clone()
            .expect("selection copied to the clipboard");
        let lines: Vec<&str> = text.lines().collect();
        let card_at = lines
            .iter()
            .position(|line| line.contains("why this file changed"))
            .expect("the card's prose is copied");
        let code_at = lines
            .iter()
            .position(|line| {
                line.starts_with('+') || line.starts_with('-') || line.starts_with(' ')
            })
            .expect("a code line is copied");
        assert!(
            card_at < code_at,
            "the card reads before the code under it: {lines:?}"
        );
    }

    #[test]
    fn y_with_no_selection_still_exports_comments_as_markdown() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.review.session.add_comment(
            Anchor {
                file: "src/lib.rs".to_owned(),
                line: None,
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "why 42?",
        );
        app.diff.as_mut().unwrap().invalidate();
        assert!(
            app.diff.as_ref().unwrap().visual_anchor.is_none(),
            "no selection is active"
        );
        app.handle(key('y'));
        let text = app
            .pending_clipboard
            .clone()
            .expect("clipboard text queued");
        assert!(text.contains("why 42?"), "exported as markdown: {text:?}");
    }

    #[test]
    fn yanking_a_selection_drops_the_anchor() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
        app.handle(key('V'));
        app.handle(key('y'));
        assert!(
            app.diff.as_ref().unwrap().visual_anchor.is_none(),
            "the yank drops the anchor"
        );
    }

    #[test]
    fn y_with_no_comments_hints_instead_of_copying() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // feedback copy lives in the diff pane; the sidebar yanks paths
        app.diff.as_mut().unwrap().focus = Pane::Diff;
        app.handle(key('y'));
        assert_eq!(app.pending_clipboard, None);
        let message = app.message.expect("message");
        assert!(message.text.contains("no comments"));
    }

    #[test]
    fn e_on_a_diff_line_opens_the_editor_at_that_line() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        // pin the editor through config so the test ignores $EDITOR
        app.config.editor.command = Some("vim".to_owned());
        select_file(&mut app, "src/lib.rs");
        let position = added_line_position(&app);
        app.diff.as_mut().unwrap().cursor = position;
        app.handle(key('e'));
        let request = app.pending_editor.clone().expect("editor request");
        assert_eq!(
            request.purpose,
            crate::editor::EditorPurpose::OpenFile {
                path: "src/lib.rs".to_owned(),
            }
        );
        // the "42" line is line 2 on the new side
        let absolute = fixture.root.join("src/lib.rs");
        assert_eq!(
            request.cmd,
            vec![
                "vim".to_owned(),
                "+2".to_owned(),
                absolute.to_string_lossy().into_owned(),
            ]
        );
    }

    #[test]
    fn e_from_the_list_opens_the_selected_file_without_a_line() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.config.editor.command = Some("vim".to_owned());
        assert_eq!(focus(&app), Pane::List);
        app.handle(key('e'));
        let request = app.pending_editor.clone().expect("editor request");
        assert!(
            request.cmd.iter().all(|arg| !arg.starts_with('+')),
            "no line jump from the list: {:?}",
            request.cmd
        );
    }

    #[test]
    fn half_page_motions_move_by_the_viewport() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        app.diff.as_mut().unwrap().viewport = 10;
        app.handle(ctrl_key('d'));
        assert_eq!(app.diff.as_ref().unwrap().cursor, 5);
        app.handle(ctrl_key('u'));
        assert_eq!(app.diff.as_ref().unwrap().cursor, 0);
    }

    /// A paging key belongs to the pane holding the keyboard, so on the
    /// sidebar it walks the file list and leaves the diff where it was.
    #[test]
    fn list_focus_half_page_walks_the_file_list() {
        let fixture = Fixture::new();
        for index in 0..30 {
            fixture.write(&format!("f{index:02}.txt"), "one\n");
        }
        fixture.commit_all("base");
        for index in 0..30 {
            fixture.write(&format!("f{index:02}.txt"), "one\ntwo\n");
        }
        let mut app = diff_app(&fixture);
        assert_eq!(focus(&app), Pane::List);
        app.diff.as_mut().unwrap().sidebar.height = 10;
        app.diff.as_mut().unwrap().viewport = 10;

        app.handle(ctrl_key('d'));
        assert_eq!(tree_cursor(&app), 5, "half the sidebar's rows");
        assert_eq!(
            app.diff.as_ref().unwrap().cursor,
            0,
            "the diff pane stays where it was"
        );
        assert_eq!(focus(&app), Pane::List);

        app.handle(ctrl_key('u'));
        assert_eq!(tree_cursor(&app), 0);
        // and the whole-page keys cover the whole pane
        app.handle(ctrl_key('f'));
        assert_eq!(tree_cursor(&app), 9);
    }

    #[test]
    fn comments_focus_half_page_walks_the_cards() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        for line in 1..=6 {
            app.review.session.add_comment(
                Anchor {
                    file: "src/lib.rs".to_owned(),
                    line: Some(line),
                    line_end: None,
                    on_old_side: false,
                    line_text: None,
                },
                "reviewer",
                "look here",
            );
        }
        app.handle(key('C'));
        assert_eq!(focus(&app), Pane::Comments);
        // one render measures the pane and the rows each card takes
        crate::test_support::render(&mut app);

        let cursor = |app: &App| app.diff.as_ref().expect("diff").comments_cursor();
        assert_eq!(cursor(&app), 0);
        app.handle(ctrl_key('d'));
        let tall = cursor(&app);
        assert!(tall > 1, "a page covers several cards, moved {tall}");
        app.handle(ctrl_key('u'));
        assert_eq!(cursor(&app), 0, "and comes back by the same step");

        // the step is what the pane can show, so a short pane covers fewer
        app.diff.as_mut().expect("diff").comments_rect.height = 6;
        app.handle(ctrl_key('d'));
        let short = cursor(&app);
        assert!(
            short < tall,
            "a 6-row pane pages {short} cards, a full-height one {tall}"
        );
    }

    #[test]
    fn hunk_jumps_move_between_headers() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        // the cursor starts on the first hunk header (no file row precedes it)
        let first = app.diff.as_ref().unwrap().cursor;
        assert!(matches!(rows(&app)[first], DiffRow::Hunk { hunk: 0, .. }));
        app.handle(key(']'));
        assert!(matches!(
            rows(&app)[app.diff.as_ref().unwrap().cursor],
            DiffRow::Hunk { hunk: 1, .. }
        ));
        app.handle(key('['));
        assert_eq!(app.diff.as_ref().unwrap().cursor, first);
    }

    #[test]
    fn noop_refresh_preserves_the_visual_selection() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
        app.handle(key('V'));
        assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
        // nothing changed on disk: a watcher echo or poll tick refresh
        // must not kill the selection
        app.handle(AppEvent::RepoChanged);
        app.settle_refresh();
        assert!(
            app.diff.as_ref().unwrap().visual_anchor.is_some(),
            "no-op refresh keeps the selection"
        );
    }

    /// The `new_no` the cursor's own row carries, read fresh each time since
    /// a rebuild can move it to a different row index.
    fn cursor_line_no(app: &App) -> u32 {
        let diff = app.diff.as_ref().unwrap();
        let model = diff.model(&app.review);
        let DiffRow::Line { hunk, line, .. } = diff.rows()[diff.cursor] else {
            panic!("cursor sits on a line")
        };
        model.files[0].hunks[hunk].lines[line].new_no.unwrap()
    }

    #[test]
    fn the_cursor_stays_on_the_same_line_after_a_comment_lands_above_it() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        app.author = "reviewer".to_owned();
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| {
            matches!(
                r,
                DiffRow::Line {
                    hunk: 1,
                    line: 2,
                    ..
                }
            )
        });
        let before_row = app.diff.as_ref().unwrap().cursor;
        let before_line = cursor_line_no(&app);

        // an unanchored comment lands at the very top of the file, above
        // every hunk the cursor could be on
        app.review.session.add_comment(
            Anchor {
                file: "data.txt".to_owned(),
                line: None,
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "look here first",
        );
        let diff = app.diff.as_mut().unwrap();
        diff.mark_rows_dirty();
        diff.ensure_rows(&app.review);

        assert_ne!(
            app.diff.as_ref().unwrap().cursor,
            before_row,
            "the new comment pushed the row down"
        );
        assert_eq!(
            cursor_line_no(&app),
            before_line,
            "and the cursor followed it"
        );
    }

    #[test]
    fn the_cursor_stays_on_the_same_line_after_a_refresh_rebuilds_every_hunk() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| {
            matches!(
                r,
                DiffRow::Line {
                    hunk: 1,
                    line: 2,
                    ..
                }
            )
        });
        let before = cursor_line_no(&app);

        // a third, unrelated edit in the middle of the file inserts a new
        // hunk before the one the cursor sits in, shifting every later
        // hunk's index
        let lines: Vec<String> = (1..=20).map(|i| format!("line {i}")).collect();
        let mut edited = lines;
        edited[0] = "line one".to_owned();
        edited[9] = "line ten edited".to_owned();
        edited[19] = "line twenty".to_owned();
        fixture.write("data.txt", &(edited.join("\n") + "\n"));
        app.handle(AppEvent::RepoChanged);
        app.settle_refresh();

        let diff = app.diff.as_ref().unwrap();
        assert_eq!(
            diff.rows()
                .iter()
                .filter(|r| matches!(r, DiffRow::Hunk { .. }))
                .count(),
            3,
            "the new edit split off a third hunk, shifting the one the cursor was in"
        );
        assert_eq!(
            cursor_line_no(&app),
            before,
            "the cursor followed the same line even though its hunk index moved"
        );
    }

    #[test]
    fn a_refresh_elsewhere_in_the_repo_keeps_the_visual_selection() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
        app.handle(key('V'));
        // a new, unrelated file changes the model's fingerprint, but the
        // selected file's own lines never moved
        fixture.write("zzz.md", "new\n");
        app.handle(AppEvent::RepoChanged);
        app.settle_refresh();
        assert!(
            app.diff.as_ref().unwrap().visual_anchor.is_some(),
            "the selected rows are still there, so the selection survives"
        );
    }

    #[test]
    fn a_refresh_while_composing_leaves_the_cursor_on_the_caret_line() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
        app.handle(key('c'));
        type_text(&mut app, "still typing");
        assert!(app.composer_open(), "composer stayed open");
        assert_eq!(
            app.diff.as_ref().unwrap().cursor,
            caret_row(&app),
            "typing seats the cursor on the caret"
        );

        // an unrelated file change forces a real refresh, rebuilding the rows
        fixture.write("zzz.md", "new\n");
        app.handle(AppEvent::RepoChanged);
        app.settle_refresh();

        assert!(app.composer_open(), "the draft survives the refresh");
        assert_eq!(
            app.diff.as_ref().unwrap().cursor,
            caret_row(&app),
            "the refresh leaves the cursor on the caret's line, not the card's header"
        );
    }

    #[test]
    fn a_selection_whose_rows_are_gone_ends_rather_than_covering_something_else() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        enter_diff_pane(&mut app);
        cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { hunk: 0, .. }));
        app.handle(key('V'));
        app.handle(key('j'));
        assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
        // revert the first hunk's edit: those rows leave the diff entirely
        let lines: Vec<String> = (1..=20).map(|i| format!("line {i}")).collect();
        let mut edited = lines;
        edited[19] = "line twenty".to_owned();
        fixture.write("data.txt", &(edited.join("\n") + "\n"));
        app.handle(AppEvent::RepoChanged);
        app.settle_refresh();
        assert!(
            app.diff.as_ref().unwrap().visual_anchor.is_none(),
            "the selected rows are gone, so the selection ends rather than \
             latching onto whatever now sits at the old index"
        );
    }

    #[test]
    fn a_banded_span_still_covers_the_same_lines_after_a_card_lands_inside_it() {
        let fixture = two_hunk_fixture();
        let mut app = diff_app(&fixture);
        app.author = "reviewer".to_owned();
        let id = app
            .review
            .session
            .add_comment(
                Anchor {
                    file: "data.txt".to_owned(),
                    line: Some(2),
                    line_end: Some(4),
                    on_old_side: false,
                    line_text: None,
                },
                "reviewer",
                "range comment",
            )
            .id
            .clone();
        app.diff.as_mut().unwrap().mark_rows_dirty();
        assert!(app.focus_comment(&id));
        let line_no = |app: &App, row: usize| -> u32 {
            let diff = app.diff.as_ref().unwrap();
            let model = diff.model(&app.review);
            let DiffRow::Line { hunk, line, .. } = diff.rows()[row] else {
                panic!("band row is a line")
            };
            model.files[0].hunks[hunk].lines[line].new_no.unwrap()
        };
        let (start, end) = app
            .diff
            .as_ref()
            .unwrap()
            .referenced
            .expect("a banded span");
        assert_eq!(line_no(&app, start), 2);
        assert_eq!(line_no(&app, end), 4);

        // a second comment anchored on line 3 lands its card between the
        // span's own endpoints
        app.review.session.add_comment(
            Anchor {
                file: "data.txt".to_owned(),
                line: Some(3),
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "in between",
        );
        let diff = app.diff.as_mut().unwrap();
        diff.mark_rows_dirty();
        diff.ensure_rows(&app.review);

        let (start, end) = app
            .diff
            .as_ref()
            .unwrap()
            .referenced
            .expect("the band survives a card landing inside it");
        assert_eq!(line_no(&app, start), 2, "band still opens on line 2");
        assert_eq!(line_no(&app, end), 4, "band still closes on line 4");
        assert!(
            end - start > 2,
            "the new card's rows now sit inside the band"
        );
    }

    #[test]
    fn refresh_keeps_the_selected_file_by_path_when_files_shift() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        let path = selected_path(&app);
        // a new file ahead of src/ shifts every file index
        fixture.write("aaa.rs", "fn nope() {}\n");
        app.handle(ctrl_key('r'));
        assert_eq!(
            selected_path(&app),
            path,
            "selection follows its file across the refresh"
        );
    }

    #[test]
    fn commit_diff_survives_refresh_untouched() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        let oid = app.status.recent[0].oid.clone();
        app.open_commit_diff(&oid);
        assert_eq!(app.screen(), Screen::Diff);
        let before = rows(&app).len();
        fixture.write("zzz.md", "new\n");
        app.handle(ctrl_key('r'));
        assert_eq!(rows(&app).len(), before, "commit model is immutable");
    }

    #[test]
    fn viewed_on_a_commit_diff_persists_to_that_source_not_the_working_tree() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        let oid = app.status.recent[0].oid.clone();
        app.open_commit_diff(&oid);
        let path = selected_path(&app);

        // a commit-diff file lives in the pinned commit model, so viewed must
        // resolve against it, not the working-tree model
        app.handle(key('m'));

        let source = ReviewSource::commit(&oid);
        assert!(
            app.review.session_for(&source).viewed.contains_key(&path),
            "viewed mark lands on the commit source"
        );
        assert!(
            app.review.session.viewed.is_empty(),
            "the working-tree session is untouched"
        );

        // a fresh open reloads the commit source's viewed mark from disk
        let mut reopened = App::new(fixture.review(), LoadedConfig::default());
        reopened.open_commit_diff(&oid);
        assert!(
            reopened
                .review
                .session_for(&source)
                .viewed
                .contains_key(&path)
        );
    }

    #[test]
    fn yank_and_editor_on_a_commit_diff_use_that_sources_comments() {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.review.session.add_comment(
            diffler_core::session::Anchor {
                file: "todo.md".into(),
                line: Some(1),
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "working-tree decoy",
        );
        let oid = app.status.recent[0].oid.clone();
        app.open_commit_diff(&oid);
        select_file(&mut app, "src/lib.rs");
        let line_row = rows(&app)
            .iter()
            .position(|row| matches!(row, DiffRow::Line { .. }))
            .expect("a diff line in the commit");
        app.diff.as_mut().unwrap().focus = Pane::Diff;
        app.diff.as_mut().unwrap().cursor = line_row;
        app.handle(key('c'));
        type_text(&mut app, "commit note");
        app.handle(key('\n'));

        app.handle(key('Y'));
        let markdown = app.pending_clipboard.take().expect("yanked feedback");
        assert!(markdown.contains("commit note"), "commit comment exported");
        assert!(
            !markdown.contains("working-tree decoy"),
            "working-tree comments stay out of a commit yank"
        );

        let comment_row = rows(&app)
            .iter()
            .position(|row| matches!(row, DiffRow::Comment { .. }))
            .expect("comment row present");
        app.diff.as_mut().unwrap().cursor = comment_row;
        app.handle(key('e'));
        let request = app.pending_editor.take().expect("editor request");
        let argv = request.cmd.join(" ");
        assert!(
            argv.contains("src/lib.rs") && !argv.contains("todo.md"),
            "editor resolves the commit comment, not the working-tree one: {argv}"
        );
    }

    #[test]
    fn comment_display_lines_cover_body_and_replies() {
        let mut session = Session::default();
        let id = session
            .add_comment(
                Anchor {
                    file: "a.rs".to_owned(),
                    line: Some(1),
                    line_end: None,
                    on_old_side: false,
                    line_text: None,
                },
                "reviewer",
                "first\nsecond",
            )
            .id
            .clone();
        session.reply(&id, "agent", "done\nand verified");
        let lines = comment_display(&session.comments[0], u16::MAX, None, None, None);
        let plain = |s: &str| MdSpan {
            text: s.to_owned(),
            ..MdSpan::default()
        };
        assert_eq!(
            lines,
            vec![
                CommentLine::Header,
                CommentLine::Body(vec![plain("first")]),
                CommentLine::Body(vec![plain("second")]),
                CommentLine::Reply {
                    author: "agent".to_owned(),
                    spans: vec![plain("done")],
                    first: true,
                },
                CommentLine::Reply {
                    author: "agent".to_owned(),
                    spans: vec![plain("and verified")],
                    first: false,
                },
                CommentLine::Footer,
            ]
        );
    }

    #[test]
    fn comment_display_wraps_long_text_to_the_pane_width() {
        let mut session = Session::default();
        let id = session
            .add_comment(
                Anchor {
                    file: "a.rs".to_owned(),
                    line: Some(1),
                    line_end: None,
                    on_old_side: false,
                    line_text: None,
                },
                "reviewer",
                "a body long enough that it cannot fit on one row",
            )
            .id
            .clone();
        session.reply(&id, "agent", "a reply that also runs past the pane");
        let lines = comment_display(&session.comments[0], 30, None, None, None);
        let budget = 30 - 4;
        let text = |runs: &[MdSpan]| runs.iter().map(|s| s.text.clone()).collect::<String>();
        for line in &lines {
            match line {
                CommentLine::Body(runs) => assert!(text(runs).width() <= budget, "{runs:?}"),
                CommentLine::Reply { spans, first, .. } => {
                    let head = if *first { "â”” agent: ".width() } else { 2 };
                    assert!(text(spans).width() + head <= budget, "{spans:?}");
                }
                _ => {}
            }
        }
        let bodies = lines
            .iter()
            .filter(|l| matches!(l, CommentLine::Body(_)))
            .count();
        assert!(bodies > 1, "the long body wrapped onto several rows");
        // words survive the wrap intact
        let joined: Vec<String> = lines
            .iter()
            .filter_map(|l| match l {
                CommentLine::Body(runs) => Some(text(runs)),
                _ => None,
            })
            .collect();
        assert_eq!(
            joined.join(" "),
            "a body long enough that it cannot fit on one row"
        );
    }

    #[test]
    fn comment_display_hard_splits_an_unbreakable_token() {
        let mut session = Session::default();
        session.add_comment(
            Anchor {
                file: "a.rs".to_owned(),
                line: Some(1),
                line_end: None,
                on_old_side: false,
                line_text: None,
            },
            "reviewer",
            "https://example.invalid/a/very/long/unbroken/path/segment/thing",
        );
        let lines = comment_display(&session.comments[0], 24, None, None, None);
        for line in &lines {
            if let CommentLine::Body(runs) = line {
                let width: usize = runs.iter().map(|s| s.text.width()).sum();
                assert!(width <= 20, "{runs:?}");
            }
        }
    }

    #[test]
    fn deleting_a_comment_asks_for_confirmation_first() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);
        app.handle(key('c'));
        type_text(&mut app, "why 42?");
        app.handle(key('\n'));

        let diff = app.diff.as_mut().unwrap();
        diff.ensure_rows(&app.review);
        let comment_row = rows(&app)
            .iter()
            .position(|r| matches!(r, DiffRow::Comment { .. }))
            .expect("comment row present");
        app.diff.as_mut().unwrap().cursor = comment_row;

        app.delete_comment_at_cursor();
        assert!(
            matches!(app.modal, Some(Modal::Confirm { .. })),
            "delete asks first"
        );
        assert_eq!(
            app.review.session.comments.len(),
            1,
            "nothing deleted before confirming"
        );
        app.confirm_modal();
        assert_eq!(
            app.review.session.comments.len(),
            0,
            "confirm deletes the comment"
        );
    }

    #[test]
    fn claiming_a_comment_toggles_authorship_and_back() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let crate::mcp::McpResponse::Added { .. } =
            app.handle_mcp(crate::mcp::McpRequestKind::AddComment {
                file: "src/lib.rs".to_owned(),
                line: 2,
                line_end: None,
                body: "looks off".to_owned(),
                as_human: false,
            })
        else {
            panic!("expected an added comment");
        };
        select_file(&mut app, "src/lib.rs");
        let diff = app.diff.as_mut().unwrap();
        diff.ensure_rows(&app.review);
        let comment_row = rows(&app)
            .iter()
            .position(|r| matches!(r, DiffRow::Comment { .. }))
            .expect("comment row present");
        app.diff.as_mut().unwrap().cursor = comment_row;

        app.claim_comment_at_cursor();
        assert_eq!(app.review.session.comments[0].author, "reviewer");

        app.claim_comment_at_cursor();
        assert_eq!(
            app.review.session.comments[0].author,
            crate::mcp::AGENT_AUTHOR
        );
    }

    #[test]
    fn claiming_on_a_row_that_is_not_a_comment_says_so() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        select_file(&mut app, "src/lib.rs");
        app.diff.as_mut().unwrap().cursor = added_line_position(&app);

        app.claim_comment_at_cursor();
        let message = app.message.clone().expect("info message");
        assert!(message.text.contains("move onto a comment"), "{message:?}");
    }

    #[test]
    fn claiming_all_comments_asks_first_claims_every_agent_comment_and_leaves_a_human_one() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let crate::mcp::McpResponse::Added { id: agent_id } =
            app.handle_mcp(crate::mcp::McpRequestKind::AddComment {
                file: "src/lib.rs".to_owned(),
                line: 2,
                line_end: None,
                body: "agent found this".to_owned(),
                as_human: false,
            })
        else {
            panic!("expected an added comment");
        };
        let human_id = app
            .review
            .session
            .add_comment(
                Anchor {
                    file: "src/lib.rs".to_owned(),
                    line: None,
                    line_end: None,
                    on_old_side: false,
                    line_text: None,
                },
                "reviewer",
                "human's own",
            )
            .id
            .clone();

        app.claim_all_comments_start();
        assert!(
            matches!(app.modal, Some(Modal::Confirm { .. })),
            "claiming all asks first"
        );
        assert_eq!(
            app.review.session.comment(&agent_id).unwrap().author,
            crate::mcp::AGENT_AUTHOR,
            "nothing claimed before confirming"
        );

        app.handle(key('n'));
        assert!(app.modal.is_none(), "declining closes the dialog");
        assert_eq!(
            app.review.session.comment(&agent_id).unwrap().author,
            crate::mcp::AGENT_AUTHOR,
            "declining changes nothing"
        );

        app.claim_all_comments_start();
        app.handle(key('y'));
        assert_eq!(
            app.review.session.comment(&agent_id).unwrap().author,
            "reviewer",
            "confirming claims the agent comment"
        );
        assert_eq!(
            app.review.session.comment(&human_id).unwrap().author,
            "reviewer",
            "the human comment was always theirs, untouched"
        );
    }

    /// A stop is never posted anywhere, and claiming it would hide it from
    /// the revision logic that prunes superseded stops by their agent
    /// authorship, so a walkthrough source refuses the verb outright.
    #[test]
    fn claiming_a_stop_on_a_walkthrough_is_refused() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);
        app.handle(key('j'));
        app.handle(key('j'));
        enter_diff_pane(&mut app);
        let card = rows(&app)
            .iter()
            .position(|row| matches!(row, DiffRow::Comment { line: 0, .. }))
            .expect("a stop card");
        app.diff.as_mut().expect("diff view").cursor = card;

        app.claim_comment_at_cursor();

        let message = app.message.clone().expect("info message");
        assert!(message.text.contains("claimable"), "{message:?}");
        let source = app.active_review_source();
        assert_eq!(
            app.review
                .session_for(&source)
                .comment("stop-2")
                .unwrap()
                .author,
            crate::mcp::AGENT_AUTHOR,
            "the stop stays the agent's"
        );
    }

    #[test]
    fn claiming_all_comments_on_a_walkthrough_is_refused_without_a_prompt() {
        let fixture = standard_fixture();
        let mut app = walkthrough_app(&fixture);

        app.claim_all_comments_start();

        assert!(app.modal.is_none(), "no confirm prompt for a walkthrough");
        let message = app.message.clone().expect("info message");
        assert!(message.text.contains("claimable"), "{message:?}");
        let source = app.active_review_source();
        assert!(
            app.review
                .session_for(&source)
                .comments
                .iter()
                .all(|c| c.author == crate::mcp::AGENT_AUTHOR),
            "every stop stays the agent's"
        );
    }

    #[test]
    fn build_split_rows_aligns_old_and_new_sides() {
        let fixture = standard_fixture();
        let app = diff_app(&fixture);
        let diff = app.diff.as_ref().unwrap();
        let model = diff.model(&app.review);
        let session = app.review.session_for(&ReviewSource::WorkingTree);
        for (index, file) in model.files.iter().enumerate() {
            for row in build_split_rows(
                model,
                session,
                index,
                u16::MAX,
                None,
                &diff.figures,
                &diff.unresolved_anchors,
            ) {
                let SplitRow::Pair { hunk, left, right } = row else {
                    continue;
                };
                assert!(left.is_some() || right.is_some(), "a pair fills a side");
                let lines = &file.hunks[hunk].lines;
                if let Some(l) = left {
                    assert!(matches!(
                        lines[l].kind,
                        LineKind::Deleted | LineKind::Context
                    ));
                }
                if let Some(r) = right {
                    assert!(matches!(lines[r].kind, LineKind::Added | LineKind::Context));
                }
                if left == right {
                    assert!(matches!(lines[left.unwrap()].kind, LineKind::Context));
                }
            }
        }
    }

    #[test]
    fn toggle_side_by_side_flips_the_mode() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.diff.as_mut().unwrap().focus = Pane::Diff;
        assert!(!app.diff.as_ref().unwrap().side_by_side);
        app.handle(key('|'));
        assert!(app.diff.as_ref().unwrap().side_by_side);
        app.handle(key('|'));
        assert!(!app.diff.as_ref().unwrap().side_by_side);
    }

    #[test]
    fn yank_in_the_sidebar_copies_the_path_the_row_names() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        app.diff.as_mut().unwrap().focus = Pane::List;
        app.handle(key('y'));
        let path = app
            .diff
            .as_ref()
            .and_then(|diff| {
                let model = diff.model(&app.review);
                model.files.get(diff.selected).map(|file| file.path.clone())
            })
            .expect("a file under the cursor");
        assert_eq!(app.pending_clipboard.as_deref(), Some(path.as_str()));
        assert!(
            app.message
                .as_ref()
                .is_some_and(|m| !m.text.contains("no comments")),
            "the sidebar never reaches the feedback copy"
        );
    }

    #[test]
    fn commenting_in_side_by_side_is_redirected_to_unified() {
        let fixture = standard_fixture();
        let mut app = diff_app(&fixture);
        let diff = app.diff.as_mut().unwrap();
        diff.focus = Pane::Diff;
        diff.side_by_side = true;
        app.handle(key('c'));
        assert!(app.modal.is_none(), "no comment modal opens in split mode");
        assert!(
            app.message
                .as_ref()
                .is_some_and(|m| m.text.contains("unified")),
            "the message points to the unified view"
        );
    }
    #[test]
    fn paren_jumps_land_on_definition_starts() {
        use crate::test_support::standard_fixture;
        let fixture = standard_fixture();
        fixture.write(
            "src/lib.rs",
            "pub fn answer() -> u32 {\n    42\n}\n\npub fn other() -> u32 {\n    7\n}\n",
        );
        let mut app =
            crate::app::App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.open_working_tree_diff(Some("src/lib.rs"));
        let (path, content) = ("src/lib.rs".to_owned(), fixture_content(&app));
        let index = app.highlighter.scope_index(&path, &content);
        assert!(!index.is_empty(), "rust definitions indexed");
        let hash = current_hash(&app);
        if let Some(diff) = app.diff.as_mut() {
            diff.scopes
                .insert(path, crate::app::diff::FileScope { hash, index });
            diff.ensure_rows(&app.review);
            diff.focus = Pane::Diff;
        }
        app.handle(crate::test_support::key(')'));
        let diff = app.diff.as_ref().expect("diff");
        let on_def = matches!(
            diff.rows().get(diff.cursor),
            Some(DiffRow::Line { file, hunk, line })
                if app.review.model().files.get(*file)
                    .and_then(|f| f.hunks.get(*hunk))
                    .and_then(|h| h.lines.get(*line))
                    .is_some_and(|l| l.text.contains("fn "))
        );
        assert!(on_def, "cursor row {} is a definition line", diff.cursor);
    }

    /// Paths of the open review's diff, in sidebar order.
    fn against_paths(app: &App) -> Vec<String> {
        app.diff
            .as_ref()
            .and_then(|diff| diff.commit_model.as_ref())
            .expect("pinned model")
            .files
            .iter()
            .map(|f| f.path.clone())
            .collect()
    }

    fn against_main(fixture: &Fixture) -> App {
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('d'));
        app.handle(key('d'));
        app
    }

    #[test]
    fn the_diff_transient_reviews_the_branch_against_its_base() {
        let fixture = crate::test_support::branch_fixture();
        let app = against_main(&fixture);
        let diff = app.diff.as_ref().expect("diff view");
        assert_eq!(diff.source, ReviewSource::against("main"));
        assert_eq!(app.against_rev(), Some("main"));
        // the branch commit and the uncommitted file, both
        assert_eq!(against_paths(&app), ["dirty.rs", "landed.rs"]);
        assert_eq!(app.screen(), Screen::Diff);
    }

    #[test]
    fn an_against_review_tracks_edits_through_the_refresh() {
        let fixture = crate::test_support::branch_fixture();
        let mut app = against_main(&fixture);
        fixture.write("later.rs", "pub fn later() {}\n");
        app.queue_refresh();
        app.settle_refresh();
        assert_eq!(against_paths(&app), ["dirty.rs", "landed.rs", "later.rs"]);
    }

    #[test]
    fn a_refresh_answering_for_another_rev_leaves_the_open_review_alone() {
        let fixture = crate::test_support::branch_fixture();
        let mut app = against_main(&fixture);
        app.apply_refresh(diffler_core::review::Refreshed {
            status: diffler_core::vcs::StatusModel::default(),
            model: DiffModel::default(),
            against: Some(("develop".to_owned(), Ok(DiffModel::default()))),
            pinned: None,
        });
        assert_eq!(against_paths(&app), ["dirty.rs", "landed.rs"]);
    }

    #[test]
    fn the_branch_picker_reviews_against_the_chosen_branch() {
        let fixture = crate::test_support::branch_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('d'));
        app.handle(key('b'));
        assert!(matches!(app.modal, Some(Modal::RevList { .. })));
        app.handle(code_key(crossterm::event::KeyCode::Tab));
        for c in "main".chars() {
            app.handle(key(c));
        }
        app.handle(key('\n'));
        assert!(app.modal.is_none());
        let diff = app.diff.as_ref().expect("diff view");
        assert_eq!(diff.source, ReviewSource::against("main"));
    }

    #[test]
    fn the_commit_picker_reviews_against_the_chosen_commit() {
        let fixture = crate::test_support::branch_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('d'));
        app.handle(key('s'));
        let Some(Modal::RevList { entries, .. }) = &app.modal else {
            panic!("rev picker open, got {:?}", app.modal);
        };
        assert!(entries[0].label.contains("feature work"), "{entries:?}");
        // newest first, so the top entry is HEAD: only the dirty file is over it
        app.handle(key('\n'));
        assert_eq!(against_paths(&app), ["dirty.rs"]);
    }

    #[test]
    fn a_rev_that_does_not_resolve_reports_instead_of_panicking() {
        let fixture = crate::test_support::branch_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.open_against_diff("no-such-branch");
        assert!(app.diff.is_none());
        assert!(
            matches!(&app.message, Some(m) if m.severity == crate::app::Severity::Error),
            "{:?}",
            app.message
        );
    }

    #[test]
    fn w_goes_back_to_the_plain_working_tree_review() {
        let fixture = crate::test_support::branch_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.handle(key('d'));
        app.handle(key('w'));
        let diff = app.diff.as_ref().expect("diff view");
        assert_eq!(diff.source, ReviewSource::WorkingTree);
        assert_eq!(app.against_rev(), None);
    }

    fn fixture_content(app: &crate::app::App) -> String {
        app.review
            .model()
            .files
            .iter()
            .find(|f| f.path == "src/lib.rs")
            .and_then(|f| f.new_text.clone())
            .expect("new text")
    }

    fn current_hash(app: &crate::app::App) -> String {
        app.review
            .model()
            .files
            .iter()
            .find(|f| f.path == "src/lib.rs")
            .map(diffler_core::model::FileDiff::sides_hash)
            .expect("hash")
    }
}