turboreview 0.1.3

A terminal code-review tool for git: review working-tree changes and commits, stage files, leave line comments, and hand off to an AI 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
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::comments::Comments;
use crate::tree::{Row, RowKind};

/// Which storage scope is currently active for comments and reviewed flags.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommentScope {
    /// Working-tree scope: `.turboreview/`
    Worktree,
    /// Per-commit scope: `.turboreview/commits/<sha>/`
    Commit(String),
}

/// Active file-history overlay over the diff pane.
#[derive(Clone, Debug)]
pub struct FileHistory {
    /// The file whose history is being browsed (repo-relative).
    pub file: PathBuf,
    /// Commits touching `file`, newest first. Capped at MAX_FILE_HISTORY.
    pub commits: Vec<crate::git::CommitInfo>,
    /// 0 = baseline (live diff). 1..=commits.len() = commits[idx-1].
    pub idx: usize,
    /// Comment scope active when H was pressed; restored on exit.
    pub baseline_scope: CommentScope,
}

/// In-diff substring search state (committed query with matches).
#[derive(Clone, Debug)]
pub struct SearchState {
    /// Lowercased query (matching is case-insensitive).
    pub query: String,
    /// Indices into `diff` of matching lines, ascending.
    pub matches: Vec<usize>,
    /// Position within `matches` of the focused match.
    pub cur: usize,
}

const MAX_FILE_HISTORY: usize = 50;
/// Largest hunks-only context before `+` switches to full-file diff.
pub const MAX_CONTEXT_LINES: u32 = 50;
const MAX_HSCROLL: usize = 500;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Section {
    Unstaged,
    Staged,
    Commit,
    /// All tracked files ("view all" mode), not just changed ones.
    All,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    Unstaged,
    Staged,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pane {
    Files,
    Diff,
    /// The right pane. It is tabbed (see `RightTab`): Comments or Debug.
    Comments,
}

/// Which tab the right pane shows. Switched with `[` / `]` when focused.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum RightTab {
    #[default]
    Comments,
    Debug,
}

/// A row in the comment-list pane.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommentRow {
    /// A status group header: (status, count)
    Header(crate::comments::CommentStatus, usize),
    /// An item: index into app.comments.items
    Item(usize),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ViewMode {
    Changes,
    Commits,
}

/// Run-state of a single debug session.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SessionState {
    /// Launching / building, no adapter responses yet.
    Starting,
    /// Debuggee running (not at a breakpoint).
    Running,
    /// Stopped at a breakpoint/step; stack + variables are populated.
    Stopped,
    /// Debuggee exited or adapter terminated.
    Exited,
}

/// Recursively flatten `vars` into [`DebugRow::Var`] rows, descending into the
/// children of any var that is currently `expanded`.
fn push_var_rows(
    vars: &[crate::dap::VarRow],
    frame: usize,
    prefix: &mut Vec<usize>,
    out: &mut Vec<DebugRow>,
) {
    for (i, v) in vars.iter().enumerate() {
        prefix.push(i);
        out.push(DebugRow::Var(frame, prefix.clone()));
        if v.expanded {
            push_var_rows(&v.children, frame, prefix, out);
        }
        prefix.pop();
    }
}

/// Walk a `path` of child indices into a nested var list, returning a shared
/// reference to the target var.
pub fn var_at_path<'a>(
    vars: &'a [crate::dap::VarRow],
    path: &[usize],
) -> Option<&'a crate::dap::VarRow> {
    let (first, rest) = path.split_first()?;
    let v = vars.get(*first)?;
    if rest.is_empty() {
        Some(v)
    } else {
        var_at_path(&v.children, rest)
    }
}

/// Walk a `path` of child indices into a nested var list, returning a mutable
/// reference to the target var.
fn var_at_path_mut<'a>(
    vars: &'a mut [crate::dap::VarRow],
    path: &[usize],
) -> Option<&'a mut crate::dap::VarRow> {
    let (first, rest) = path.split_first()?;
    let v = vars.get_mut(*first)?;
    if rest.is_empty() {
        Some(v)
    } else {
        var_at_path_mut(&mut v.children, rest)
    }
}

/// One debug session's UI-facing state. The live adapter handle (process +
/// request channel) is attached by the threaded client layer; this struct holds
/// only what the UI renders so it stays `Clone`/testable.
#[derive(Clone, Debug)]
pub struct DebugSession {
    /// Stable id assigned at spawn (also tags incoming events).
    pub id: u64,
    /// Human label, e.g. "worktree" or "commit a1b2c3".
    pub label: String,
    pub state: SessionState,
    /// Thread the adapter last reported stopped on (for follow-up requests).
    pub stopped_thread: Option<i64>,
    /// File + line where it stopped (absolute path), if known.
    pub stopped_at: Option<(PathBuf, u32)>,
    /// Current call stack (innermost first).
    pub stack: Vec<crate::dap::Frame>,
    /// Index of the selected stack frame.
    pub frame_sel: usize,
    /// Locals for the selected frame.
    pub locals: Vec<crate::dap::VarRow>,
}

impl DebugSession {
    pub fn new(id: u64, label: String) -> Self {
        DebugSession {
            id,
            label,
            state: SessionState::Starting,
            stopped_thread: None,
            stopped_at: None,
            stack: Vec::new(),
            frame_sel: 0,
            locals: Vec::new(),
        }
    }
}

/// Top-level debugger overlay state. Present (`Some`) only while debugging.
/// Breakpoints are keyed by absolute source path → set of 1-based line numbers,
/// shared across all sessions.
/// Which tab the right-hand debug pane is showing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum DebugTab {
    /// Call stack + variables of the active session.
    #[default]
    Vars,
    /// The breakpoint list (navigate / enable / delete).
    Breakpoints,
}

#[derive(Clone, Debug, Default)]
pub struct DebugState {
    pub sessions: Vec<DebugSession>,
    /// Index into `sessions` of the active session (panel focus).
    pub active: usize,
    /// Which tab the debug pane shows.
    pub tab: DebugTab,
    /// Breakpoints: absolute source path → (1-based line → enabled). Disabled
    /// breakpoints are kept (greyed in the list) but not sent to adapters.
    pub breakpoints: std::collections::BTreeMap<PathBuf, std::collections::BTreeMap<u32, bool>>,
    /// Selection index within the active session's variables/stack panel.
    pub panel_sel: usize,
    /// Selection index within the breakpoint-list pane.
    pub bp_sel: usize,
    /// Horizontal scroll offset (chars) for the debug pane's content.
    pub hscroll: usize,
}

/// A flattened, selectable row in the Vars panel: either a stack frame, or a
/// variable belonging to a frame (identified by a path of child indices for
/// nested/expanded values). Indentation = path depth.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DebugRow {
    Frame(usize),
    /// (frame index, path of indices from the frame's locals down to this var).
    Var(usize, Vec<usize>),
}

impl DebugState {
    pub fn active_session(&self) -> Option<&DebugSession> {
        self.sessions.get(self.active)
    }

    /// Flatten the active session into selectable rows: every frame followed by
    /// its locals, recursing into expanded structured values.
    pub fn debug_rows(&self) -> Vec<DebugRow> {
        let mut rows = Vec::new();
        let Some(sess) = self.active_session() else {
            return rows;
        };
        for (fi, frame) in sess.stack.iter().enumerate() {
            rows.push(DebugRow::Frame(fi));
            push_var_rows(&frame.locals, fi, &mut Vec::new(), &mut rows);
        }
        rows
    }

    /// Flat, ordered list of all breakpoints as `(file, line, enabled)`. Order
    /// matches the breakpoint pane (by path, then line).
    pub fn breakpoint_list(&self) -> Vec<(PathBuf, u32, bool)> {
        self.breakpoints
            .iter()
            .flat_map(|(f, lines)| lines.iter().map(move |(l, on)| (f.clone(), *l, *on)))
            .collect()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
    Added,
    Modified,
    Deleted,
    Renamed,
    Other,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineKind {
    Hunk,
    Add,
    Del,
    Context,
}

#[derive(Clone, Debug)]
pub struct FileChange {
    pub path: PathBuf,
    pub status: Status,
}

#[derive(Clone, Debug)]
pub struct DiffLine {
    pub kind: LineKind,
    pub text: String,
    pub old_lineno: Option<u32>,
    pub new_lineno: Option<u32>,
}

impl DiffLine {
    pub fn context(text: &str, old: u32, new: u32) -> Self {
        DiffLine {
            kind: LineKind::Context,
            text: text.into(),
            old_lineno: Some(old),
            new_lineno: Some(new),
        }
    }
}

/// State for the modal comment input box.
pub struct InputState {
    pub buffer: String, // current text (may contain \n for multi-line)
    pub target_file: PathBuf,
    pub target_line: u32,
    pub target_hunk: String,
    /// Anchor captured at the moment the modal was opened (Fix 4: don't re-derive at Ctrl-S).
    pub anchor_line_text: String,
    pub anchor_before: Vec<String>,
    pub anchor_after: Vec<String>,
    /// Debug snapshot available to attach (set when a session is stopped at this
    /// line). Shown in the modal; only saved onto the comment when `attach_debug`.
    pub debug_snapshot: Option<crate::dap::DebugSnapshot>,
    /// Whether the snapshot will be attached on save (toggled with Ctrl-D).
    pub attach_debug: bool,
}

/// Result of committing a comment input (returned by `input_commit`).
pub struct CommittedComment {
    pub file: PathBuf,
    pub line: u32,
    pub hunk: String,
    pub text: String,
    pub line_text: String,
    pub context_before: Vec<String>,
    pub context_after: Vec<String>,
    /// Debug snapshot to attach to the comment (None unless the user kept it on).
    pub debug_snapshot: Option<crate::dap::DebugSnapshot>,
}

pub struct App {
    pub repo_root: PathBuf,
    pub focus: Pane,
    pub view: ViewMode,
    pub unstaged: Vec<FileChange>,
    pub staged: Vec<FileChange>,
    /// All tracked files (populated lazily when "view all" is toggled on).
    pub all_files: Vec<FileChange>,
    /// When true the file pane lists all tracked files instead of just changes.
    pub show_all_files: bool,
    pub selected: usize,
    pub diff: Vec<DiffLine>,
    pub diff_cursor: usize,
    pub diff_hscroll: usize,
    /// Some(anchor) when visual-select is active; anchor is a diff index.
    pub select_anchor: Option<usize>,
    pub reviewed: HashSet<PathBuf>,
    pub status_msg: Option<String>,
    pub collapsed: HashSet<(Section, PathBuf)>,
    pub rows: Vec<Row>,
    pub hide_reviewed: bool,
    pub context_lines: u32,
    pub full_file: bool,
    pub show_files: bool,
    pub file_pane_pct: u16,
    /// Width (% of the main area) of the right pane (comments / debug).
    pub right_pane_pct: u16,
    pub comments: Comments,
    pub input: Option<InputState>,
    pub commits: Vec<crate::git::CommitInfo>,
    pub selected_commit: usize,
    /// Number of commits currently requested from git (page size, grows on demand).
    pub commit_limit: usize,
    /// Lazily-computed per-commit diff stats, keyed by full oid. Filled for the
    /// visible window each frame; missing entries render a placeholder.
    pub commit_stats: std::collections::HashMap<String, crate::git::CommitStat>,
    pub open_commit: Option<String>,
    pub commit_files: Vec<FileChange>,
    pub show_help: bool,
    pub comment_scope: CommentScope,
    pub show_comments: bool,
    pub comment_selected: usize,
    pub theme: crate::theme::Theme,
    /// false = unified diff (default), true = side-by-side (split) diff.
    pub split_diff: bool,
    pub history: Option<FileHistory>,
    pub search: Option<SearchState>,
    pub search_input: Option<String>,
    /// Debugger overlay state; `Some` only while debugging.
    pub debug: Option<DebugState>,
    /// Which tab the right pane shows (Comments or Debug).
    pub right_tab: RightTab,
    /// Parsed LCOV coverage, loaded on demand for the coverage highlight.
    pub coverage: Option<crate::coverage::Coverage>,
    /// Whether coverage highlighting is shown in the diff gutter.
    pub show_coverage: bool,
    /// When `Some`, the debug launch-type picker is open with this selection.
    pub debug_launch_pick: Option<usize>,
    /// When `Some`, the attach-to-process picker is open.
    pub proc_picker: Option<ProcPicker>,
}

/// The launch modes offered by the debug picker.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LaunchMode {
    /// Build + debug the current working tree.
    Worktree,
    /// Build + debug the selected commit (Commits view) via a temp worktree.
    Commit,
    /// Attach to the configured remote target (gdbserver / Docker).
    Remote,
    /// Attach to a running local process (opens the process picker).
    Process,
}

/// State for the "attach to process" picker: the full process list, a filter
/// string the user types, and the selection index into the filtered view.
#[derive(Clone, Debug, Default)]
pub struct ProcPicker {
    pub procs: Vec<crate::process::ProcInfo>,
    pub filter: String,
    pub sel: usize,
}

impl ProcPicker {
    /// Processes matching the filter (case-insensitive substring of name or pid).
    pub fn filtered(&self) -> Vec<&crate::process::ProcInfo> {
        if self.filter.is_empty() {
            return self.procs.iter().collect();
        }
        let f = self.filter.to_lowercase();
        self.procs
            .iter()
            .filter(|p| {
                p.command.to_lowercase().contains(&f) || p.pid.to_string().contains(&f)
            })
            .collect()
    }
}

enum RowId {
    File(Section, std::path::PathBuf),
    Dir(Section, std::path::PathBuf),
}

impl App {
    pub fn new(unstaged: Vec<FileChange>, staged: Vec<FileChange>, repo_root: PathBuf) -> Self {
        let mut app = App {
            repo_root,
            focus: Pane::Files,
            view: ViewMode::Changes,
            unstaged,
            staged,
            all_files: Vec::new(),
            show_all_files: false,
            selected: 0,
            diff: Vec::new(),
            diff_cursor: 0,
            diff_hscroll: 0,
            select_anchor: None,
            reviewed: HashSet::new(),
            status_msg: None,
            collapsed: HashSet::new(),
            rows: Vec::new(),
            hide_reviewed: false,
            context_lines: 3,
            full_file: false,
            show_files: true,
            file_pane_pct: 25,
            right_pane_pct: 30,
            comments: Comments::default(),
            input: None,
            commits: Vec::new(),
            selected_commit: 0,
            commit_limit: crate::COMMIT_PAGE,
            commit_stats: std::collections::HashMap::new(),
            open_commit: None,
            commit_files: Vec::new(),
            show_help: false,
            comment_scope: CommentScope::Worktree,
            show_comments: false,
            comment_selected: 0,
            theme: crate::theme::Theme::Dark,
            split_diff: false,
            history: None,
            search: None,
            search_input: None,
            debug: None,
            right_tab: RightTab::Comments,
            coverage: None,
            show_coverage: false,
            debug_launch_pick: None,
            proc_picker: None,
        };
        app.rebuild_rows();
        app
    }

    pub fn toggle_full_file(&mut self) {
        self.full_file = !self.full_file;
    }

    pub fn toggle_help(&mut self) {
        self.show_help = !self.show_help;
    }

    pub fn toggle_theme(&mut self) {
        self.theme = match self.theme {
            crate::theme::Theme::Dark => crate::theme::Theme::Light,
            crate::theme::Theme::Light => crate::theme::Theme::Dark,
        };
    }

    /// Toggle side-by-side (split) diff rendering.
    pub fn toggle_split(&mut self) {
        self.split_diff = !self.split_diff;
    }

    pub fn palette(&self) -> crate::theme::Palette {
        crate::theme::Palette::for_theme(self.theme)
    }

    pub fn toggle_files(&mut self) {
        self.show_files = !self.show_files;
        // Only move focus if the hidden pane was the focused one.
        if !self.show_files && self.focus == Pane::Files {
            self.focus = Pane::Diff;
        }
    }

    pub fn widen_files(&mut self) {
        self.file_pane_pct = (self.file_pane_pct + 5).min(60);
    }

    pub fn narrow_files(&mut self) {
        self.file_pane_pct = self.file_pane_pct.saturating_sub(5).max(10);
    }

    pub fn widen_right(&mut self) {
        self.right_pane_pct = (self.right_pane_pct + 5).min(60);
    }

    pub fn narrow_right(&mut self) {
        self.right_pane_pct = self.right_pane_pct.saturating_sub(5).max(15);
    }

    /// Resize the pane relevant to the current focus. `bigger` follows the key
    /// direction toward the pane's content: for the left file pane `>` grows it
    /// (rightward); for the right pane the directions are mirrored, so `<` (which
    /// points toward the right pane's inner edge) grows it and `>` shrinks it.
    pub fn resize_focused_pane(&mut self, bigger: bool) {
        if self.focus == Pane::Comments {
            // Right pane: mirror — `<` widens, `>` narrows.
            if bigger {
                self.narrow_right();
            } else {
                self.widen_right();
            }
        } else if bigger {
            self.widen_files();
        } else {
            self.narrow_files();
        }
    }

    pub fn effective_context(&self) -> u32 {
        if self.full_file {
            u32::MAX
        } else {
            self.context_lines
        }
    }

    pub fn rebuild_rows(&mut self) {
        let prev = self.selected_identity();
        let empty = HashSet::new();
        let hidden = if self.hide_reviewed {
            &self.reviewed
        } else {
            &empty
        };
        self.rows = if self.view == ViewMode::Commits && self.open_commit.is_some() {
            crate::tree::build_commit_rows(&self.commit_files, &self.collapsed, hidden)
        } else if self.show_all_files {
            crate::tree::build_all_rows(&self.all_files, &self.collapsed)
        } else {
            crate::tree::build_rows(&self.unstaged, &self.staged, &self.collapsed, hidden)
        };
        self.selected = match prev.and_then(|id| self.find_row(&id)) {
            Some(i) => i,
            None => self.selected.min(self.rows.len().saturating_sub(1)),
        };
    }

    fn selected_identity(&self) -> Option<RowId> {
        let row = self.rows.get(self.selected)?;
        match &row.kind {
            RowKind::File {
                section,
                file_index,
            } => {
                return self
                    .section_files(*section)
                    .get(*file_index)
                    .map(|f| RowId::File(*section, f.path.clone()));
            }
            RowKind::Dir { section, path, .. } => Some(RowId::Dir(*section, path.clone())),
            RowKind::Header { .. } => None,
        }
    }

    fn find_row(&self, id: &RowId) -> Option<usize> {
        self.rows.iter().position(|r| match (&r.kind, id) {
            (
                RowKind::File {
                    section: rs,
                    file_index,
                },
                RowId::File(s, p),
            ) if rs == s => self
                .section_files(*rs)
                .get(*file_index)
                .map_or(false, |f| &f.path == p),
            (
                RowKind::Dir {
                    section: rs, path, ..
                },
                RowId::Dir(s, p),
            ) if rs == s => path == p,
            _ => false,
        })
    }

    /// Whether the selected row is a file in the "view all" file list.
    pub fn selected_is_all_file(&self) -> bool {
        self.show_all_files
            && matches!(
                self.rows.get(self.selected).map(|r| &r.kind),
                Some(RowKind::File { section: Section::All, .. })
            )
    }

    pub fn section_files(&self, section: Section) -> &[FileChange] {
        match section {
            Section::Unstaged => &self.unstaged,
            Section::Staged => &self.staged,
            Section::Commit => &self.commit_files,
            Section::All => &self.all_files,
        }
    }

    pub fn toggle_hide_reviewed(&mut self) {
        self.hide_reviewed = !self.hide_reviewed;
        self.rebuild_rows();
    }

    pub fn selected_path(&self) -> Option<&PathBuf> {
        match self.rows.get(self.selected) {
            Some(Row {
                kind:
                    RowKind::File {
                        section,
                        file_index,
                    },
                ..
            }) => self
                .section_files(*section)
                .get(*file_index)
                .map(|f| &f.path),
            _ => None,
        }
    }

    pub fn selected_section(&self) -> Option<Section> {
        match self.rows.get(self.selected) {
            Some(Row {
                kind: RowKind::File { section, .. },
                ..
            }) => Some(*section),
            _ => None,
        }
    }

    pub fn selected_file_index(&self) -> Option<usize> {
        match self.rows.get(self.selected) {
            Some(Row {
                kind: RowKind::File { file_index, .. },
                ..
            }) => Some(*file_index),
            _ => None,
        }
    }

    pub fn set_diff(&mut self, diff: Vec<DiffLine>) {
        self.diff = diff;
        self.diff_cursor = 0;
        self.diff_hscroll = 0;
        self.search = None;
        self.search_input = None;
    }

    pub fn move_selection(&mut self, delta: isize) {
        if self.rows.is_empty() {
            return;
        }
        let max = self.rows.len() as isize - 1;
        let next = (self.selected as isize + delta).clamp(0, max);
        self.selected = next as usize;
    }

    pub fn scroll_h(&mut self, delta: isize) {
        let next = (self.diff_hscroll as isize + delta).max(0);
        self.diff_hscroll = (next as usize).min(MAX_HSCROLL);
    }

    pub fn move_diff_cursor(&mut self, delta: isize) {
        if self.diff.is_empty() {
            self.diff_cursor = 0;
            return;
        }
        let max = self.diff.len() as isize - 1;
        let mut pos = (self.diff_cursor as isize + delta).clamp(0, max);
        // Lines the cursor should not rest on, in the direction of travel:
        //  - Hunk headers (can't comment on them; resting makes split view jump).
        //  - In side-by-side mode, Del (old) lines too: each del/add pair shares a
        //    visual row whose new side is the comment target, so landing on the del
        //    would highlight the same row twice. Comments aren't allowed on old
        //    lines anyway, so the cursor tracks only the new side.
        let skip = |k: LineKind| -> bool {
            k == LineKind::Hunk || (self.split_diff && k == LineKind::Del)
        };
        let step = if delta >= 0 { 1 } else { -1 };
        while skip(self.diff[pos as usize].kind) {
            let next = pos + step;
            if next < 0 || next > max {
                // Edge of the diff: reverse to find the nearest acceptable line.
                let mut back = pos - step;
                while (0..=max).contains(&back) && skip(self.diff[back as usize].kind) {
                    back -= step;
                }
                if (0..=max).contains(&back) {
                    pos = back;
                }
                break;
            }
            pos = next;
        }
        self.diff_cursor = pos as usize;
    }

    pub fn select_active(&self) -> bool {
        self.select_anchor.is_some()
    }

    pub fn start_select(&mut self) {
        self.select_anchor = Some(self.diff_cursor);
    }

    pub fn cancel_select(&mut self) {
        self.select_anchor = None;
    }

    /// Inclusive (lo, hi) diff-index range of the current selection, or the
    /// single cursor line when not selecting.
    pub fn select_range(&self) -> (usize, usize) {
        match self.select_anchor {
            Some(a) => (a.min(self.diff_cursor), a.max(self.diff_cursor)),
            None => (self.diff_cursor, self.diff_cursor),
        }
    }

    /// Text of the selected range: each line's clean `text`, '\n'-joined, with a
    /// trailing '\n'. Hunk headers carry no useful content, so they are skipped.
    pub fn selection_text(&self) -> String {
        let (lo, hi) = self.select_range();
        let mut out = String::new();
        for dl in &self.diff[lo..=hi] {
            if dl.kind == LineKind::Hunk {
                continue;
            }
            out.push_str(&dl.text);
            out.push('\n');
        }
        out
    }

    pub fn to_top(&mut self) {
        match self.focus {
            Pane::Files => self.selected = 0,
            Pane::Diff => self.diff_cursor = 0,
            Pane::Comments => match self.right_tab {
                RightTab::Comments => self.comment_selected = 0,
                RightTab::Debug => {
                    if let Some(d) = self.debug.as_mut() {
                        d.panel_sel = 0;
                    }
                }
            },
        }
    }

    pub fn to_bottom(&mut self) {
        match self.focus {
            Pane::Files => self.selected = self.rows.len().saturating_sub(1),
            Pane::Diff => self.diff_cursor = self.diff.len().saturating_sub(1),
            Pane::Comments => match self.right_tab {
                RightTab::Comments => {
                    let len = self.comment_rows().len();
                    self.comment_selected = len.saturating_sub(1);
                }
                RightTab::Debug => {
                    let len = self.debug_panel_len();
                    if let Some(d) = self.debug.as_mut() {
                        d.panel_sel = len.saturating_sub(1);
                    }
                }
            },
        }
    }

    /// Whether the right pane is visible (the Comments tab is enabled, or a
    /// debug session is active so the Debug tab has content).
    pub fn right_pane_visible(&self) -> bool {
        self.show_comments || self.debug_active()
    }

    /// Cycle focus Files -> Diff -> Right -> Files. Skips Files when
    /// !show_files and the Right pane when it isn't visible.
    pub fn toggle_focus(&mut self) {
        let panes: Vec<Pane> = [Pane::Files, Pane::Diff, Pane::Comments]
            .iter()
            .copied()
            .filter(|&p| match p {
                Pane::Files => self.show_files,
                Pane::Diff => true,
                Pane::Comments => self.right_pane_visible(),
            })
            .collect();
        if panes.len() <= 1 {
            return; // nothing to cycle
        }
        let current = panes.iter().position(|&p| p == self.focus).unwrap_or(0);
        self.focus = panes[(current + 1) % panes.len()];
    }

    /// Horizontally scroll the debug pane content (clamped at 0).
    pub fn debug_scroll_h(&mut self, delta: isize) {
        if let Some(d) = self.debug.as_mut() {
            d.hscroll = (d.hscroll as isize + delta).max(0) as usize;
        }
    }

    /// Whether the Debug tab of the right pane is focused.
    pub fn is_debug_focused(&self) -> bool {
        self.focus == Pane::Comments && self.right_tab == RightTab::Debug
    }

    /// Switch the right-pane tab (Comments <-> Debug). Debug only when active.
    pub fn toggle_right_tab(&mut self) {
        self.right_tab = match self.right_tab {
            RightTab::Comments if self.debug_active() => RightTab::Debug,
            RightTab::Debug => RightTab::Comments,
            other => other,
        };
    }

    /// Coverage state of a repo-relative `(file, line)` when the highlight is on.
    /// Returns `LineCov::None` when coverage is off or there's no data.
    pub fn line_coverage(&self, file: &Path, line: u32) -> crate::coverage::LineCov {
        if !self.show_coverage {
            return crate::coverage::LineCov::None;
        }
        self.coverage
            .as_ref()
            .map(|c| c.line_cov(file, line))
            .unwrap_or(crate::coverage::LineCov::None)
    }

    // ─── Debugger ────────────────────────────────────────────────────────────

    /// Launch modes available in the current context: Commit only in the
    /// Commits list; Worktree always; Remote always (validated on select).
    pub fn launch_modes(&self) -> Vec<LaunchMode> {
        let mut modes = Vec::new();
        if self.view == ViewMode::Commits && self.open_commit.is_none() {
            modes.push(LaunchMode::Commit);
        }
        modes.push(LaunchMode::Worktree);
        modes.push(LaunchMode::Process);
        modes.push(LaunchMode::Remote);
        modes
    }

    pub fn open_launch_picker(&mut self) {
        self.debug_launch_pick = Some(0);
    }

    pub fn close_launch_picker(&mut self) {
        self.debug_launch_pick = None;
    }

    pub fn launch_picker_active(&self) -> bool {
        self.debug_launch_pick.is_some()
    }

    pub fn move_launch_pick(&mut self, delta: isize) {
        let len = self.launch_modes().len();
        if let Some(sel) = self.debug_launch_pick.as_mut() {
            let max = len as isize - 1;
            *sel = ((*sel as isize + delta).clamp(0, max)) as usize;
        }
    }

    /// The currently highlighted launch mode in the picker, if open.
    pub fn selected_launch_mode(&self) -> Option<LaunchMode> {
        let sel = self.debug_launch_pick?;
        self.launch_modes().get(sel).copied()
    }

    // ─── Attach-to-process picker ────────────────────────────────────────────

    /// Open the process picker, loading the running-process list.
    pub fn open_proc_picker(&mut self) {
        let procs = crate::process::list_processes().unwrap_or_default();
        self.proc_picker = Some(ProcPicker {
            procs,
            filter: String::new(),
            sel: 0,
        });
    }

    pub fn proc_picker_active(&self) -> bool {
        self.proc_picker.is_some()
    }

    pub fn close_proc_picker(&mut self) {
        self.proc_picker = None;
    }

    pub fn move_proc_pick(&mut self, delta: isize) {
        if let Some(p) = self.proc_picker.as_mut() {
            let len = p.filtered().len();
            if len == 0 {
                return;
            }
            let max = len as isize - 1;
            p.sel = ((p.sel as isize + delta).clamp(0, max)) as usize;
        }
    }

    pub fn proc_filter_push(&mut self, ch: char) {
        if let Some(p) = self.proc_picker.as_mut() {
            p.filter.push(ch);
            p.sel = 0;
        }
    }

    pub fn proc_filter_backspace(&mut self) {
        if let Some(p) = self.proc_picker.as_mut() {
            p.filter.pop();
            p.sel = 0;
        }
    }

    /// The selected process `(pid, name)` in the filtered list, if any.
    pub fn selected_process(&self) -> Option<(i64, String)> {
        let p = self.proc_picker.as_ref()?;
        p.filtered()
            .get(p.sel)
            .map(|pi| (pi.pid, pi.command.clone()))
    }

    /// Whether a debug session/overlay is active.
    pub fn debug_active(&self) -> bool {
        self.debug.is_some()
    }

    /// Absolute path + 1-based line of the diff line under the cursor, if it maps
    /// to a real source line (skips hunk headers and pure-deletion lines that have
    /// no new-side line number). Used to anchor breakpoints to disk locations.
    pub fn cursor_source_loc(&self) -> Option<(PathBuf, u32)> {
        let file = self.selected_path()?;
        let line = self.cursor_lineno()?;
        Some((self.repo_root.join(file), line))
    }

    /// Whether `(abs_file, line)` currently has a breakpoint (enabled or not).
    pub fn has_breakpoint(&self, file: &Path, line: u32) -> bool {
        self.debug
            .as_ref()
            .and_then(|d| d.breakpoints.get(file))
            .is_some_and(|lines| lines.contains_key(&line))
    }

    /// Whether `(abs_file, line)` has an ENABLED breakpoint (drives the marker).
    pub fn breakpoint_enabled(&self, file: &Path, line: u32) -> bool {
        self.debug
            .as_ref()
            .and_then(|d| d.breakpoints.get(file))
            .and_then(|lines| lines.get(&line))
            .copied()
            .unwrap_or(false)
    }

    /// Toggle a breakpoint on the diff line under the cursor. Lazily creates the
    /// `DebugState` so breakpoints can be set before any session is launched.
    /// Returns `true` if a breakpoint now exists at that line, `false` if it was
    /// removed (or there was no valid source line under the cursor).
    pub fn toggle_breakpoint_at_cursor(&mut self) -> bool {
        let Some((file, line)) = self.cursor_source_loc() else {
            return false;
        };
        let d = self.debug.get_or_insert_with(DebugState::default);
        let lines = d.breakpoints.entry(file.clone()).or_default();
        let now_set = if lines.contains_key(&line) {
            lines.remove(&line);
            false
        } else {
            lines.insert(line, true); // new breakpoints start enabled
            true
        };
        // Drop empty file entries to keep the map tidy.
        if lines.is_empty() {
            d.breakpoints.remove(&file);
        }
        // If we created an empty DebugState only to remove the last breakpoint
        // and there are no sessions, leave it — it's harmless and cheap, and the
        // gutter still needs the (now-empty) map. (debug_active stays true only
        // while breakpoints or sessions exist; tidy that here.)
        if d.breakpoints.is_empty() && d.sessions.is_empty() {
            self.debug = None;
        }
        now_set
    }

    // ─── Breakpoint pane ─────────────────────────────────────────────────────

    /// Number of breakpoints (for clamping the pane selection).
    pub fn breakpoint_count(&self) -> usize {
        self.debug.as_ref().map_or(0, |d| {
            d.breakpoints.values().map(|m| m.len()).sum()
        })
    }

    /// Move the selection within the breakpoint pane, clamped.
    pub fn move_breakpoint_selection(&mut self, delta: isize) {
        let len = self.breakpoint_count();
        if len == 0 {
            return;
        }
        let max = len as isize - 1;
        if let Some(d) = self.debug.as_mut() {
            d.bp_sel = (d.bp_sel as isize + delta).clamp(0, max) as usize;
        }
    }

    /// The selected breakpoint `(abs_file, line, enabled)`, if any.
    pub fn selected_breakpoint(&self) -> Option<(PathBuf, u32, bool)> {
        let d = self.debug.as_ref()?;
        d.breakpoint_list().into_iter().nth(d.bp_sel)
    }

    /// Toggle enabled/disabled for the selected breakpoint. Returns the new
    /// enabled state, or None if there's no selection.
    pub fn toggle_selected_breakpoint(&mut self) -> Option<bool> {
        let (file, line, _) = self.selected_breakpoint()?;
        let d = self.debug.as_mut()?;
        let on = d.breakpoints.get_mut(&file)?.get_mut(&line)?;
        *on = !*on;
        Some(*on)
    }

    /// Delete the selected breakpoint entirely. Returns true if one was removed.
    pub fn delete_selected_breakpoint(&mut self) -> bool {
        let Some((file, line, _)) = self.selected_breakpoint() else {
            return false;
        };
        let Some(d) = self.debug.as_mut() else {
            return false;
        };
        if let Some(lines) = d.breakpoints.get_mut(&file) {
            lines.remove(&line);
            if lines.is_empty() {
                d.breakpoints.remove(&file);
            }
        }
        let len = self.breakpoint_count();
        if let Some(d) = self.debug.as_mut() {
            d.bp_sel = d.bp_sel.min(len.saturating_sub(1));
        }
        true
    }

    /// Jump the diff cursor to the selected breakpoint's file+line. Requires the
    /// file to be the one currently shown in the diff; returns true on success.
    pub fn jump_to_selected_breakpoint(&mut self) -> bool {
        let Some((file, line, _)) = self.selected_breakpoint() else {
            return false;
        };
        // Only jump within the currently-open file's diff.
        let cur_abs = self.selected_path().map(|p| self.repo_root.join(p));
        if cur_abs.as_deref() != Some(file.as_path()) {
            self.status_msg =
                Some("breakpoint is in another file — open it first".into());
            return false;
        }
        if let Some(idx) = self
            .diff
            .iter()
            .position(|dl| dl.new_lineno == Some(line) || dl.old_lineno == Some(line))
        {
            self.diff_cursor = idx;
            self.focus = Pane::Diff;
            true
        } else {
            self.status_msg = Some("breakpoint line not visible in this diff".into());
            false
        }
    }

    /// Whether the debug pane is currently on the Breakpoints tab.
    pub fn debug_tab_is_breakpoints(&self) -> bool {
        self.debug.as_ref().map(|d| d.tab) == Some(DebugTab::Breakpoints)
    }

    /// Switch the debug pane between the Vars and Breakpoints tabs.
    pub fn toggle_debug_tab(&mut self) {
        if let Some(d) = self.debug.as_mut() {
            d.tab = match d.tab {
                DebugTab::Vars => DebugTab::Breakpoints,
                DebugTab::Breakpoints => DebugTab::Vars,
            };
        }
    }

    /// Move selection in whichever debug tab is active.
    pub fn move_debug_selection(&mut self, delta: isize) {
        match self.debug.as_ref().map(|d| d.tab) {
            Some(DebugTab::Breakpoints) => self.move_breakpoint_selection(delta),
            _ => self.move_debug_panel_selection(delta),
        }
    }

    /// Number of selectable rows in the Vars panel (frames + their locals,
    /// recursing into expanded values).
    pub fn debug_panel_len(&self) -> usize {
        self.debug.as_ref().map_or(0, |d| d.debug_rows().len())
    }

    /// Move the selection within the debug panel, clamped to its row count.
    pub fn move_debug_panel_selection(&mut self, delta: isize) {
        let len = self.debug_panel_len();
        if len == 0 {
            return;
        }
        let max = len as isize - 1;
        if let Some(d) = self.debug.as_mut() {
            d.panel_sel = ((d.panel_sel as isize + delta).clamp(0, max)) as usize;
        }
    }

    /// Toggle expansion of the selected variable (if structured). When expanding
    /// a value that has no children yet, returns `(frame_idx, var_ref, path)` so
    /// the caller can fetch them; otherwise returns None.
    pub fn toggle_expand_selected_var(&mut self) -> Option<(usize, i64, Vec<usize>)> {
        let d = self.debug.as_mut()?;
        let row = d.debug_rows().get(d.panel_sel).cloned()?;
        let DebugRow::Var(fi, path) = row else {
            return None;
        };
        let sess = d.sessions.get_mut(d.active)?;
        let v = var_at_path_mut(&mut sess.stack.get_mut(fi)?.locals, &path)?;
        if v.var_ref == 0 {
            return None; // scalar, nothing to expand
        }
        v.expanded = !v.expanded;
        if v.expanded && v.children.is_empty() {
            Some((fi, v.var_ref, path))
        } else {
            None
        }
    }

    /// Set the expanded flag on the var at `(frame, path)` in the active session.
    pub fn set_var_expanded(&mut self, frame: usize, path: &[usize], expanded: bool) {
        if let Some(d) = self.debug.as_mut() {
            if let Some(sess) = d.sessions.get_mut(d.active) {
                if let Some(f) = sess.stack.get_mut(frame) {
                    if let Some(v) = var_at_path_mut(&mut f.locals, path) {
                        v.expanded = expanded;
                    }
                }
            }
        }
    }

    /// Store fetched children onto the var at `(frame, path)` in the active
    /// session.
    pub fn set_var_children(&mut self, frame: usize, path: &[usize], children: Vec<crate::dap::VarRow>) {
        if let Some(d) = self.debug.as_mut() {
            if let Some(sess) = d.sessions.get_mut(d.active) {
                if let Some(f) = sess.stack.get_mut(frame) {
                    if let Some(v) = var_at_path_mut(&mut f.locals, path) {
                        v.children = children;
                    }
                }
            }
        }
    }

    /// End all debug sessions, keeping any breakpoints. If no breakpoints
    /// remain, the debug overlay is dropped entirely. Moves focus off the Debug
    /// pane.
    pub fn exit_debug(&mut self) {
        if let Some(d) = self.debug.as_mut() {
            d.sessions.clear();
            d.active = 0;
            d.panel_sel = 0;
            if d.breakpoints.is_empty() {
                self.debug = None;
            }
        }
        // If the Debug tab was showing, fall back to the Comments tab (and move
        // focus off the right pane if it's no longer useful).
        if self.right_tab == RightTab::Debug {
            self.right_tab = RightTab::Comments;
            if self.is_debug_focused() {
                self.focus = Pane::Diff;
            }
        }
        if self.focus == Pane::Comments && !self.right_pane_visible() {
            self.focus = Pane::Diff;
        }
    }

    /// Attach a captured debug snapshot to the comment at its stopped line,
    /// creating a placeholder comment there if none exists. The stopped file is
    /// stored repo-relative to match how comments key their file.
    /// Build a debug snapshot from the active session if it is currently stopped
    /// (call stack + locals at the stop). Used to offer attaching runtime state
    /// to a comment from the comment modal. Caps the stack depth.
    pub fn current_debug_snapshot(&self) -> Option<crate::dap::DebugSnapshot> {
        let sess = self.debug.as_ref()?.active_session()?;
        if sess.state != SessionState::Stopped {
            return None;
        }
        let (file, line) = sess.stopped_at.clone()?;
        const MAX_SNAPSHOT_FRAMES: usize = 8;
        let stack = sess
            .stack
            .iter()
            .take(MAX_SNAPSHOT_FRAMES)
            .cloned()
            .collect();
        Some(crate::dap::DebugSnapshot {
            session_label: sess.label.clone(),
            stopped_file: file.to_string_lossy().into_owned(),
            stopped_line: line,
            stack,
            locals: sess.locals.clone(),
            captured: crate::storage::now_secs(),
        })
    }

    pub fn attach_debug_snapshot(&mut self, snap: crate::dap::DebugSnapshot) {
        // Map the absolute stopped path back to a repo-relative path.
        let abs = PathBuf::from(&snap.stopped_file);
        let rel = abs
            .strip_prefix(&self.repo_root)
            .map(Path::to_path_buf)
            .unwrap_or(abs);
        let line = snap.stopped_line;
        // Find an existing comment on (file,line), else create a minimal one.
        if let Some(c) = self
            .comments
            .items
            .iter_mut()
            .find(|c| c.file == rel && c.line == line)
        {
            c.debug_snapshot = Some(snap);
            c.updated = crate::storage::now_secs();
        } else {
            self.comments.set(
                rel,
                line,
                String::new(),
                String::new(),
                String::new(),
                vec![],
                vec![],
                crate::storage::now_secs(),
            );
            if let Some(c) = self.comments.items.last_mut() {
                c.debug_snapshot = Some(snap);
            }
        }
    }

    /// Toggle the comment pane. If hiding while Comments has focus, move focus to Diff.
    pub fn toggle_comment_pane(&mut self) {
        self.show_comments = !self.show_comments;
        if self.show_comments {
            // Opening the pane focuses it so it can be navigated immediately.
            self.focus = Pane::Comments;
        } else if self.focus == Pane::Comments {
            self.focus = Pane::Diff;
        }
    }

    /// Build the displayable rows for the comment-list pane.
    /// Groups items by status in order: Open, NeedsInfo, Wontfix, Resolved.
    /// Each non-empty group gets a Header(status, count) followed by Item(i) for each match,
    /// sorted by `updated` descending (newest first). Ties are stable by original index.
    pub fn comment_rows(&self) -> Vec<CommentRow> {
        use crate::comments::CommentStatus;
        let order = [
            CommentStatus::Open,
            CommentStatus::NeedsInfo,
            CommentStatus::Wontfix,
            CommentStatus::Resolved,
        ];
        let mut rows = Vec::new();
        for status in &order {
            let mut indices: Vec<usize> = self
                .comments
                .items
                .iter()
                .enumerate()
                .filter(|(_, c)| &c.status == status)
                .map(|(i, _)| i)
                .collect();
            if !indices.is_empty() {
                // Sort by updated descending (newest first); stable by original index for ties.
                indices.sort_by(|&a, &b| {
                    self.comments.items[b]
                        .updated
                        .cmp(&self.comments.items[a].updated)
                });
                rows.push(CommentRow::Header(*status, indices.len()));
                for i in indices {
                    rows.push(CommentRow::Item(i));
                }
            }
        }
        rows
    }

    /// Move the comment pane selection by `delta`, clamping to valid range.
    pub fn move_comment_selection(&mut self, delta: isize) {
        let len = self.comment_rows().len();
        if len == 0 {
            self.comment_selected = 0;
            return;
        }
        let max = len as isize - 1;
        self.comment_selected = (self.comment_selected as isize + delta).clamp(0, max) as usize;
    }

    /// Returns the Comment at the current comment_selected index, or None if it's a header.
    pub fn selected_comment(&self) -> Option<&crate::comments::Comment> {
        match self.comment_rows().get(self.comment_selected) {
            Some(CommentRow::Item(i)) => self.comments.items.get(*i),
            _ => None,
        }
    }

    /// Scan rows for a File row whose path matches `path`. If found, set self.selected and return true.
    pub fn select_row_for_path(&mut self, path: &Path) -> bool {
        for (i, row) in self.rows.iter().enumerate() {
            if let RowKind::File {
                section,
                file_index,
            } = &row.kind
            {
                if let Some(fc) = self.section_files(*section).get(*file_index) {
                    if fc.path == path {
                        self.selected = i;
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Line number under the diff cursor (`new_lineno`, else `old_lineno`).
    pub fn cursor_lineno(&self) -> Option<u32> {
        self.diff
            .get(self.diff_cursor)
            .and_then(|l| l.new_lineno.or(l.old_lineno))
    }

    /// True if any diff line carries `lineno` as its new or old line number.
    pub fn diff_has_lineno(&self, lineno: u32) -> bool {
        self.diff
            .iter()
            .any(|l| l.new_lineno == Some(lineno) || l.old_lineno == Some(lineno))
    }

    /// Scan self.diff for the first line matching `lineno` (new, then old); set diff_cursor.
    /// If not found, reset diff_cursor to 0.
    pub fn move_cursor_to_lineno(&mut self, lineno: u32) {
        for (i, dl) in self.diff.iter().enumerate() {
            if dl.new_lineno == Some(lineno) {
                self.diff_cursor = i;
                return;
            }
        }
        for (i, dl) in self.diff.iter().enumerate() {
            if dl.old_lineno == Some(lineno) {
                self.diff_cursor = i;
                return;
            }
        }
        self.diff_cursor = 0;
    }

    /// Scan self.diff for the first line whose new_lineno == new_lineno; set diff_cursor to it.
    /// If not found, reset diff_cursor to 0.
    pub fn move_cursor_to_line(&mut self, new_lineno: u32) {
        self.move_cursor_to_lineno(new_lineno);
    }

    pub fn toggle_reviewed(&mut self) {
        let Some(path) = self.selected_path().cloned() else {
            return;
        };
        if !self.reviewed.remove(&path) {
            self.reviewed.insert(path);
        }
        self.rebuild_rows();
    }

    pub fn is_reviewed_path(&self, path: &Path) -> bool {
        self.reviewed.contains(path)
    }

    /// Legacy helper used by existing tests — checks by index into the combined
    /// unstaged list (tests that use `sample()` with only unstaged files).
    pub fn is_reviewed(&self, idx: usize) -> bool {
        self.unstaged
            .get(idx)
            .map(|f| self.reviewed.contains(&f.path))
            .unwrap_or(false)
    }

    pub fn toggle_collapse(&mut self) {
        if let Some(row) = self.rows.get(self.selected) {
            if let RowKind::Dir { section, path, .. } = &row.kind {
                let key = (*section, path.clone());
                if self.collapsed.contains(&key) {
                    self.collapsed.remove(&key);
                } else {
                    self.collapsed.insert(key);
                }
                self.rebuild_rows();
            }
        }
    }

    /// Which sections are shown in the current view (for fold-all enumeration).
    fn active_sections(&self) -> Vec<Section> {
        if self.in_commit_detail() {
            vec![Section::Commit]
        } else {
            vec![Section::Unstaged, Section::Staged]
        }
    }

    /// All `(section, dir_path)` keys for every directory ancestor of every file
    /// in the active view's sections. Independent of current collapse state, so
    /// it can both fully expand and fully collapse.
    fn all_dir_keys(&self) -> HashSet<(Section, PathBuf)> {
        let mut keys = HashSet::new();
        for section in self.active_sections() {
            for fc in self.section_files(section) {
                let mut acc = PathBuf::new();
                let comps: Vec<_> = fc.path.components().collect();
                // Every component except the last (the file name) is a directory.
                for comp in comps.iter().take(comps.len().saturating_sub(1)) {
                    acc.push(comp);
                    keys.insert((section, acc.clone()));
                }
            }
        }
        keys
    }

    /// Smart fold-all toggle. If any directory in the active view is currently
    /// expanded, collapse them all; otherwise expand them all. No-op when there
    /// are no directories.
    pub fn toggle_fold_all(&mut self) {
        let dirs = self.all_dir_keys();
        if dirs.is_empty() {
            return;
        }
        let any_expanded = dirs.iter().any(|k| !self.collapsed.contains(k));
        if any_expanded {
            for k in dirs {
                self.collapsed.insert(k);
            }
        } else {
            for k in &dirs {
                self.collapsed.remove(k);
            }
        }
        self.rebuild_rows();
    }

    pub fn next_view(&mut self) {
        let prev = self.view;
        self.view = match self.view {
            ViewMode::Changes => ViewMode::Commits,
            ViewMode::Commits => ViewMode::Changes,
        };
        // When leaving Commits, clear any open commit so returning shows a fresh list.
        if prev == ViewMode::Commits && self.view == ViewMode::Changes {
            self.open_commit = None;
            self.commit_files.clear();
            self.comment_scope = CommentScope::Worktree;
        }
        // Rows reference the previous view's file set; rebuild so they can't point
        // into a now-cleared list (e.g. commit_files after leaving a commit detail).
        self.rebuild_rows();
    }

    pub fn prev_view(&mut self) {
        // With only two modes, prev and next are equivalent toggles
        self.next_view();
    }

    pub fn move_commit_selection(&mut self, delta: isize) {
        if self.commits.is_empty() {
            return;
        }
        let max = self.commits.len() as isize - 1;
        let next = (self.selected_commit as isize + delta).clamp(0, max);
        self.selected_commit = next as usize;
    }

    pub fn selected_commit_info(&self) -> Option<&crate::git::CommitInfo> {
        self.commits.get(self.selected_commit)
    }

    /// Open a commit detail view: set the commit's changed files, record its id,
    /// reset the row selection to the first row, and rebuild rows.
    /// Also sets `comment_scope` to `Commit(id)`.
    pub fn open_commit(&mut self, id: String, files: Vec<FileChange>) {
        self.comment_scope = CommentScope::Commit(id.clone());
        self.commit_files = files;
        self.open_commit = Some(id);
        self.selected = 0;
        self.rebuild_rows();
    }

    /// Close the commit detail view, returning to the commit list.
    /// Also resets `comment_scope` to `Worktree`.
    pub fn close_commit(&mut self) {
        self.open_commit = None;
        self.commit_files.clear();
        self.comment_scope = CommentScope::Worktree;
        self.rebuild_rows();
    }

    /// Return a string label for the current comment scope suitable for the comment log.
    /// `"worktree"` for working-tree scope, `"commit:<sha>"` for per-commit scope.
    pub fn scope_label(&self) -> String {
        match &self.comment_scope {
            CommentScope::Worktree => "worktree".to_string(),
            CommentScope::Commit(sha) => format!("commit:{}", sha),
        }
    }

    /// True when we are in the Commits view AND a commit has been drilled into.
    pub fn in_commit_detail(&self) -> bool {
        self.view == ViewMode::Commits && self.open_commit.is_some()
    }

    /// Return the short id of the open commit (looked up from `self.commits`).
    pub fn open_commit_short(&self) -> Option<&str> {
        let id = self.open_commit.as_deref()?;
        self.commits
            .iter()
            .find(|c| c.id == id)
            .map(|c| c.short.as_str())
    }

    /// Public so callers can cap their `file_history` request consistently.
    pub const MAX_FILE_HISTORY: usize = MAX_FILE_HISTORY;
    pub const MAX_CONTEXT_LINES: u32 = MAX_CONTEXT_LINES;

    /// Enter history mode for the selected file. Returns false (no state change) if
    /// `commits` is empty or no file is selected. On success, idx starts at 1
    /// (newest commit) and the current comment scope is saved as the baseline.
    pub fn start_history(&mut self, commits: Vec<crate::git::CommitInfo>) -> bool {
        if commits.is_empty() {
            return false;
        }
        let Some(file) = self.selected_path().cloned() else {
            return false;
        };
        self.history = Some(FileHistory {
            file,
            commits,
            idx: 1,
            baseline_scope: self.comment_scope.clone(),
        });
        true
    }

    /// Step the history index by `delta` (+1 = older, -1 = newer), clamped to
    /// `0..=commits.len()`. No-op when not in history mode.
    pub fn history_step(&mut self, delta: isize) {
        if let Some(h) = self.history.as_mut() {
            let max = h.commits.len() as isize;
            h.idx = (h.idx as isize + delta).clamp(0, max) as usize;
        }
    }

    /// The commit for the current revision (None at baseline idx 0 or when inactive).
    pub fn history_current_commit(&self) -> Option<&crate::git::CommitInfo> {
        let h = self.history.as_ref()?;
        if h.idx == 0 {
            None
        } else {
            h.commits.get(h.idx - 1)
        }
    }

    /// Exit history mode, restoring the baseline comment scope.
    pub fn exit_history(&mut self) {
        if let Some(h) = self.history.take() {
            self.comment_scope = h.baseline_scope;
        }
    }

    pub fn history_active(&self) -> bool {
        self.history.is_some()
    }

    /// Open the search input line (typing phase). Caller guards on Diff focus.
    pub fn search_start(&mut self) {
        self.search_input = Some(String::new());
    }

    pub fn search_input_active(&self) -> bool {
        self.search_input.is_some()
    }

    pub fn search_active(&self) -> bool {
        self.search.is_some()
    }

    pub fn search_input_push(&mut self, ch: char) {
        if let Some(buf) = self.search_input.as_mut() {
            buf.push(ch);
        }
    }

    pub fn search_input_backspace(&mut self) {
        if let Some(buf) = self.search_input.as_mut() {
            buf.pop();
        }
    }

    pub fn search_input_cancel(&mut self) {
        self.search_input = None;
    }

    pub fn search_clear(&mut self) {
        self.search = None;
        self.search_input = None;
    }

    /// Commit the typed query: compute matches (case-insensitive substring) over the
    /// current diff. If none, leave `search` None and return false. Otherwise set
    /// `search` with `cur` = first match index at/after `diff_cursor` (wrapping),
    /// move `diff_cursor` there, and return true. Clears the input buffer either way.
    pub fn search_commit(&mut self) -> bool {
        let query = match self.search_input.take() {
            Some(q) if !q.is_empty() => q.to_lowercase(),
            _ => return false,
        };
        let matches: Vec<usize> = self
            .diff
            .iter()
            .enumerate()
            .filter(|(_, l)| l.text.to_lowercase().contains(&query))
            .map(|(i, _)| i)
            .collect();
        if matches.is_empty() {
            self.search = None;
            return false;
        }
        // First match at/after the current cursor, else wrap to the first.
        let cur = matches
            .iter()
            .position(|&i| i >= self.diff_cursor)
            .unwrap_or(0);
        self.diff_cursor = matches[cur];
        self.search = Some(SearchState {
            query,
            matches,
            cur,
        });
        true
    }

    /// Move to the next (+1) / previous (-1) match with wraparound. No-op if inactive.
    pub fn search_next(&mut self, delta: isize) {
        if let Some(s) = self.search.as_mut() {
            let len = s.matches.len() as isize;
            if len == 0 {
                return;
            }
            s.cur = ((s.cur as isize + delta) % len + len) as usize % len as usize;
            self.diff_cursor = s.matches[s.cur];
        }
    }

    pub fn inc_context(&mut self) {
        if self.full_file {
            return;
        }
        if self.context_lines >= MAX_CONTEXT_LINES {
            self.full_file = true;
        } else {
            self.context_lines = (self.context_lines + 5).min(MAX_CONTEXT_LINES);
        }
    }

    pub fn dec_context(&mut self) {
        if self.full_file {
            self.full_file = false;
            return;
        }
        self.context_lines = self.context_lines.saturating_sub(5);
    }

    // ── Comment input methods ──────────────────────────────────────────────

    /// Return the diff line currently under the cursor, if any.
    pub fn current_diff_line(&self) -> Option<&DiffLine> {
        self.diff.get(self.diff_cursor)
    }

    /// Scan backwards from `diff_cursor` to find the nearest preceding Hunk
    /// line's text. Returns empty string if none found.
    pub fn current_hunk_header(&self) -> String {
        let end = self.diff_cursor.min(self.diff.len().saturating_sub(1));
        for i in (0..=end).rev() {
            if self.diff[i].kind == LineKind::Hunk {
                return self.diff[i].text.clone();
            }
        }
        String::new()
    }

    /// Open the comment modal for the current diff line.
    /// Only activates when Diff focused, a file is selected, and the current
    /// line has a new_lineno and is not itself a Hunk header.
    pub fn start_comment(&mut self) {
        if self.focus != Pane::Diff {
            return;
        }
        let Some(file) = self.selected_path().cloned() else {
            self.status_msg = Some("comment: no file selected".to_string());
            return;
        };
        let Some(dl) = self.diff.get(self.diff_cursor) else {
            self.status_msg = Some("comment: place cursor on a line".to_string());
            return;
        };
        if dl.kind == LineKind::Hunk {
            self.status_msg = Some("comment: place cursor on a line".to_string());
            return;
        }
        let Some(line_no) = dl.new_lineno else {
            self.status_msg = Some("comment: place cursor on a line".to_string());
            return;
        };
        let hunk = self.current_hunk_header();
        let existing = self
            .comments
            .get(&file, line_no)
            .map(|c| c.text.clone())
            .unwrap_or_default();
        // FIX 4: capture the anchor at the time the modal is opened, not at Ctrl-S time.
        let (anchor_line_text, anchor_before, anchor_after) = self.comment_anchor();
        // If debugging and stopped, offer the current stack/locals for attaching.
        // Prefer a snapshot already on the existing comment so re-editing keeps it.
        let existing_snap = self
            .comments
            .get(&file, line_no)
            .and_then(|c| c.debug_snapshot.clone());
        let live_snap = self.current_debug_snapshot();
        let debug_snapshot = existing_snap.or(live_snap);
        let attach_debug = debug_snapshot.is_some();
        self.input = Some(InputState {
            buffer: existing,
            target_file: file,
            target_line: line_no,
            target_hunk: hunk,
            anchor_line_text,
            anchor_before,
            anchor_after,
            debug_snapshot,
            attach_debug,
        });
    }

    pub fn input_active(&self) -> bool {
        self.input.is_some()
    }

    /// Push a character to the input buffer.
    pub fn input_push(&mut self, ch: char) {
        if let Some(ref mut s) = self.input {
            s.buffer.push(ch);
        }
    }

    /// Remove the last character from the input buffer.
    pub fn input_backspace(&mut self) {
        if let Some(ref mut s) = self.input {
            s.buffer.pop();
        }
    }

    /// Push a newline to the input buffer.
    pub fn input_newline(&mut self) {
        if let Some(ref mut s) = self.input {
            s.buffer.push('\n');
        }
    }

    /// Cancel the input modal without saving.
    pub fn input_cancel(&mut self) {
        self.input = None;
    }

    /// Finalise the input: takes the InputState, clears `self.input`,
    /// and returns a `CommittedComment` so the caller can decide whether to set or remove it.
    /// The anchor fields come from the InputState (captured at `start_comment` time, Fix 4).
    pub fn input_commit(&mut self) -> Option<CommittedComment> {
        let s = self.input.take()?;
        let debug_snapshot = if s.attach_debug { s.debug_snapshot } else { None };
        Some(CommittedComment {
            file: s.target_file,
            line: s.target_line,
            hunk: s.target_hunk,
            text: s.buffer,
            line_text: s.anchor_line_text,
            context_before: s.anchor_before,
            context_after: s.anchor_after,
            debug_snapshot,
        })
    }

    /// Toggle whether the captured debug snapshot will be attached on save.
    /// No-op when there's no snapshot to attach.
    pub fn input_toggle_attach_debug(&mut self) {
        if let Some(s) = self.input.as_mut() {
            if s.debug_snapshot.is_some() {
                s.attach_debug = !s.attach_debug;
            }
        }
    }

    /// Build the anchor (line_text, context_before, context_after) for the current cursor line.
    /// Returns trimmed text of the cursor line plus up to 2 non-Hunk lines before and after.
    /// FIX 2: if the cursor line's trimmed text is empty, returns "\u{0}" (NUL blank-line marker)
    /// instead of "" (which is the legacy "no anchor" sentinel).
    pub fn comment_anchor(&self) -> (String, Vec<String>, Vec<String>) {
        let raw_trimmed = self
            .diff
            .get(self.diff_cursor)
            .map(|l| l.text.trim().to_string())
            .unwrap_or_default();
        // Use NUL sentinel for blank lines so relocate can distinguish them from legacy no-anchor.
        let line_text = if raw_trimmed.is_empty() {
            "\u{0}".to_string()
        } else {
            raw_trimmed
        };

        let cursor = self.diff_cursor.min(self.diff.len());
        let before: Vec<String> = self.diff[..cursor]
            .iter()
            .rev()
            .filter(|l| l.kind != LineKind::Hunk)
            .take(2)
            .map(|l| l.text.trim().to_string())
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();

        let after: Vec<String> = self
            .diff
            .get(self.diff_cursor + 1..)
            .unwrap_or(&[])
            .iter()
            .filter(|l| l.kind != LineKind::Hunk)
            .take(2)
            .map(|l| l.text.trim().to_string())
            .collect();

        (line_text, before, after)
    }

    /// Return the Comment for `line` if one exists, for the currently selected file.
    pub fn comment_for<'a>(&'a self, line: &DiffLine) -> Option<&'a crate::comments::Comment> {
        let n = line.new_lineno?;
        let file = self.selected_path()?;
        self.comments.get(file, n)
    }

    /// Whether `line` has a comment attached.
    pub fn has_comment(&self, line: &DiffLine) -> bool {
        if let Some(n) = line.new_lineno {
            if let Some(file) = self.selected_path() {
                return self.comments.get(file, n).is_some();
            }
        }
        false
    }

    /// Return the comment text for `line`, if any.
    pub fn comment_text_for<'a>(&'a self, line: &DiffLine) -> Option<&'a str> {
        let n = line.new_lineno?;
        let file = self.selected_path()?;
        self.comments.get(file, n).map(|c| c.text.as_str())
    }
}

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

    /// Build an App with files in the unstaged list only (mirrors the old `App::new(files, root)` pattern).
    fn sample() -> App {
        let files = vec![
            FileChange {
                path: PathBuf::from("a.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("b.rs"),
                status: Status::Added,
            },
            FileChange {
                path: PathBuf::from("c.rs"),
                status: Status::Deleted,
            },
        ];
        App::new(files, vec![], PathBuf::from("/repo"))
    }

    #[test]
    fn selection_moves_and_clamps() {
        let mut app = sample();
        // rows: Header(Unstaged) + a.rs + b.rs + c.rs + Header(Staged) = 5 rows
        // selected starts at 0 (Header row), but move_selection starts at 0
        assert_eq!(app.selected, 0);
        app.move_selection(1);
        assert_eq!(app.selected, 1);
        app.move_selection(-5);
        assert_eq!(app.selected, 0); // clamp low
        app.move_selection(99);
        assert_eq!(app.selected, 4); // clamp high to last row (Header(Staged))
    }

    #[test]
    fn focus_toggle() {
        let mut app = sample();
        assert_eq!(app.focus, Pane::Files);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Diff);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Files);
    }

    #[test]
    fn gg_g_on_files_pane_moves_selection() {
        let mut app = sample();
        app.focus = Pane::Files;
        app.to_bottom();
        // 5 rows total; last index = 4
        assert_eq!(app.selected, 4);
        app.to_top();
        assert_eq!(app.selected, 0);
    }

    #[test]
    fn set_diff_resets_cursor() {
        let mut app = sample();
        app.set_diff(vec![DiffLine::context("x", 1, 1); 5]);
        app.focus = Pane::Diff;
        app.move_diff_cursor(3);
        assert_eq!(app.diff_cursor, 3);
        app.set_diff(vec![DiffLine::context("y", 1, 1); 2]);
        assert_eq!(app.diff_cursor, 0);
    }

    #[test]
    fn diff_cursor_moves_and_clamps() {
        let mut app = sample();
        app.set_diff(vec![DiffLine::context("x", 1, 1); 5]);
        app.focus = Pane::Diff;
        app.move_diff_cursor(-3);
        assert_eq!(app.diff_cursor, 0);
        app.move_diff_cursor(100);
        assert_eq!(app.diff_cursor, 4);
        app.to_top();
        assert_eq!(app.diff_cursor, 0);
        app.to_bottom();
        assert_eq!(app.diff_cursor, 4);
    }

    #[test]
    fn move_diff_cursor_skips_hunk_headers() {
        let mut app = sample();
        app.focus = Pane::Diff;
        // ctx(0) hunk(1) add(2) hunk(3) ctx(4)
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "c0".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ a @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "a2".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ b @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Context,
                text: "c4".into(),
                old_lineno: Some(5),
                new_lineno: Some(5),
            },
        ]);
        app.diff_cursor = 0;
        // Down: 0 -> skip hunk(1) -> land add(2)
        app.move_diff_cursor(1);
        assert_eq!(app.diff_cursor, 2);
        // Down again: 2 -> skip hunk(3) -> land ctx(4)
        app.move_diff_cursor(1);
        assert_eq!(app.diff_cursor, 4);
        // Up: 4 -> skip hunk(3) -> land add(2)
        app.move_diff_cursor(-1);
        assert_eq!(app.diff_cursor, 2);
    }

    #[test]
    fn move_diff_cursor_split_skips_del_lines() {
        let mut app = sample();
        app.focus = Pane::Diff;
        app.split_diff = true;
        // ctx(0) del(1) add(2) ctx(3)
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "c0".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Del,
                text: "old".into(),
                old_lineno: Some(2),
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "new".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "c3".into(),
                old_lineno: Some(3),
                new_lineno: Some(3),
            },
        ]);
        app.diff_cursor = 0;
        // Down: skip del(1) -> land add(2)
        app.move_diff_cursor(1);
        assert_eq!(app.diff_cursor, 2);
        // Down: ctx(3)
        app.move_diff_cursor(1);
        assert_eq!(app.diff_cursor, 3);
        // Up from ctx(3): skip del(1) -> add(2)
        app.move_diff_cursor(-1);
        assert_eq!(app.diff_cursor, 2);
    }

    #[test]
    fn move_diff_cursor_unified_does_not_skip_del() {
        let mut app = sample();
        app.focus = Pane::Diff;
        app.split_diff = false; // unified
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "c0".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Del,
                text: "old".into(),
                old_lineno: Some(2),
                new_lineno: None,
            },
        ]);
        app.diff_cursor = 0;
        // Unified: del IS a valid cursor target.
        app.move_diff_cursor(1);
        assert_eq!(app.diff_cursor, 1);
    }

    #[test]
    fn move_diff_cursor_all_hunks_does_not_hang() {
        let mut app = sample();
        app.focus = Pane::Diff;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ a @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ b @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
        ]);
        app.diff_cursor = 0;
        // No non-hunk line exists; must terminate (lands somewhere in range).
        app.move_diff_cursor(1);
        assert!(app.diff_cursor <= 1);
    }

    fn three_line_diff() -> Vec<DiffLine> {
        vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ a @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "alpha".into(),
                old_lineno: None,
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "beta".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
        ]
    }

    #[test]
    fn select_range_single_when_no_anchor() {
        let mut app = sample();
        app.set_diff(three_line_diff());
        app.diff_cursor = 2;
        assert!(!app.select_active());
        assert_eq!(app.select_range(), (2, 2));
    }

    #[test]
    fn select_range_orders_anchor_and_cursor() {
        let mut app = sample();
        app.set_diff(three_line_diff());
        // Anchor below cursor: anchor=2, cursor=1 -> (1, 2)
        app.diff_cursor = 2;
        app.start_select();
        app.diff_cursor = 1;
        assert!(app.select_active());
        assert_eq!(app.select_range(), (1, 2));
    }

    #[test]
    fn selection_text_joins_with_trailing_newline() {
        let mut app = sample();
        app.set_diff(three_line_diff());
        app.diff_cursor = 1;
        app.start_select();
        app.diff_cursor = 2;
        assert_eq!(app.selection_text(), "alpha\nbeta\n");
    }

    #[test]
    fn selection_text_skips_hunk_lines() {
        let mut app = sample();
        app.set_diff(three_line_diff());
        // Range covers hunk(0)..add(2); hunk text must be omitted.
        app.diff_cursor = 0;
        app.start_select();
        app.diff_cursor = 2;
        assert_eq!(app.selection_text(), "alpha\nbeta\n");
    }

    #[test]
    fn cancel_select_clears_anchor() {
        let mut app = sample();
        app.set_diff(three_line_diff());
        app.start_select();
        assert!(app.select_active());
        app.cancel_select();
        assert!(!app.select_active());
        assert_eq!(app.select_range(), (app.diff_cursor, app.diff_cursor));
    }

    #[test]
    fn toggle_reviewed_tracks_selected_file() {
        let mut app = sample();
        // selected=0 is Header row; move to row 1 (a.rs)
        app.selected = 1;
        assert!(!app.is_reviewed(0));
        app.toggle_reviewed();
        assert!(app.is_reviewed(0));
        app.toggle_reviewed();
        assert!(!app.is_reviewed(0));
    }

    #[test]
    fn hscroll_clamps_at_zero_and_resets_on_set_diff() {
        let mut app = sample();
        app.scroll_h(-5);
        assert_eq!(app.diff_hscroll, 0); // clamp low
        app.scroll_h(3);
        assert_eq!(app.diff_hscroll, 3);
        app.set_diff(vec![DiffLine::context("x", 1, 1); 2]);
        assert_eq!(app.diff_hscroll, 0); // reset on new diff
    }

    // --- NEW TREE-BASED TESTS ---

    #[test]
    fn flat_files_selected_path_resolves_via_rows() {
        // With the two-section model, row 0 is Header(Unstaged), row 1 is a.rs
        let mut app = sample();
        app.selected = 1; // a.rs row
        assert_eq!(app.selected_path(), Some(&PathBuf::from("a.rs")));
    }

    #[test]
    fn selected_file_index_returns_correct_index() {
        let mut app = sample();
        // row 2 is b.rs (index 1 in unstaged)
        app.selected = 2;
        assert_eq!(app.selected_file_index(), Some(1));
    }

    #[test]
    fn move_selection_clamps_against_rows_length() {
        let mut app = sample();
        // 3 flat files in unstaged: rows = Header(U) + a + b + c + Header(S) = 5
        app.move_selection(99);
        assert_eq!(app.selected, 4); // clamped to last row
    }

    #[test]
    fn toggle_collapse_hides_and_shows_dir_children() {
        // Build app with src/main.rs, src/ui.rs, README.md in unstaged
        let files = vec![
            FileChange {
                path: PathBuf::from("src/main.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("src/ui.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("README.md"),
                status: Status::Modified,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // rows: Header(U), Dir "src" (1), main.rs (2), ui.rs (3), README.md (4), Header(S) (5)
        assert_eq!(app.rows.len(), 6);

        // Select the Dir row (index 1) and collapse it
        app.selected = 1;
        app.toggle_collapse();
        // Now rows should be: Header(U), Dir "src" (collapsed), README.md, Header(S) → 4 rows
        assert_eq!(app.rows.len(), 4);
        assert!(matches!(
            app.rows[1].kind,
            crate::tree::RowKind::Dir {
                collapsed: true,
                ..
            }
        ));

        // Toggle again → expand back to 6 rows
        app.selected = 1;
        app.toggle_collapse();
        assert_eq!(app.rows.len(), 6);
    }

    #[test]
    fn toggle_collapse_on_file_row_does_nothing() {
        let mut app = sample(); // flat files → all File rows (plus 2 Headers)
        let initial_len = app.rows.len();
        app.selected = 1; // a.rs File row
        app.toggle_collapse();
        assert_eq!(app.rows.len(), initial_len);
    }

    #[test]
    fn fold_all_collapses_then_expands_every_dir() {
        let files = vec![
            FileChange {
                path: PathBuf::from("src/a/x.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("src/b/y.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("top.rs"),
                status: Status::Modified,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // Fully expanded baseline: Header(U) + src + a + x.rs + b + y.rs + top.rs + Header(S) = 8
        assert_eq!(app.rows.len(), 8);

        // First press: collapse all. Nested dirs hidden; only top-level src + top.rs show.
        app.toggle_fold_all();
        // Header(U) + src(collapsed) + top.rs + Header(S) = 4
        assert_eq!(app.rows.len(), 4);
        // src, src/a, src/b all collapsed
        assert!(app
            .collapsed
            .contains(&(Section::Unstaged, PathBuf::from("src"))));
        assert!(app
            .collapsed
            .contains(&(Section::Unstaged, PathBuf::from("src/a"))));
        assert!(app
            .collapsed
            .contains(&(Section::Unstaged, PathBuf::from("src/b"))));

        // Second press: expand all → back to 8 rows.
        app.toggle_fold_all();
        assert_eq!(app.rows.len(), 8);
        assert!(app.collapsed.is_empty());
    }

    #[test]
    fn fold_all_with_partial_collapse_collapses_remaining() {
        let files = vec![
            FileChange {
                path: PathBuf::from("src/a/x.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("lib/b.rs"),
                status: Status::Modified,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // Collapse only "lib" manually; "src"/"src/a" still expanded → fold-all should collapse all.
        app.collapsed
            .insert((Section::Unstaged, PathBuf::from("lib")));
        app.toggle_fold_all();
        assert!(app
            .collapsed
            .contains(&(Section::Unstaged, PathBuf::from("src"))));
        assert!(app
            .collapsed
            .contains(&(Section::Unstaged, PathBuf::from("src/a"))));
        assert!(app
            .collapsed
            .contains(&(Section::Unstaged, PathBuf::from("lib"))));
    }

    #[test]
    fn fold_all_no_dirs_is_noop() {
        let mut app = sample(); // flat files, no dirs
        let before = app.collapsed.len();
        app.toggle_fold_all();
        assert_eq!(app.collapsed.len(), before);
    }

    #[test]
    fn selected_path_returns_none_for_dir_row() {
        let files = vec![FileChange {
            path: PathBuf::from("src/main.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // rows: Header(U)(0), Dir "src" (1), File "main.rs" (2), Header(S) (3)
        app.selected = 1; // Dir row
        assert_eq!(app.selected_path(), None);
    }

    #[test]
    fn rebuild_rows_called_after_app_new() {
        let app = sample();
        // rows should be pre-built in App::new
        assert!(!app.rows.is_empty());
        // 3 flat files → Header(U) + 3 files + Header(S) = 5 rows
        assert_eq!(app.rows.len(), 5);
    }

    #[test]
    fn to_bottom_uses_rows_length() {
        let mut app = sample();
        app.focus = Pane::Files;
        app.to_bottom();
        assert_eq!(app.selected, app.rows.len() - 1);
    }

    #[test]
    fn hide_reviewed_hides_reviewed_file() {
        let files = vec![
            FileChange {
                path: PathBuf::from("a.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("b.rs"),
                status: Status::Added,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // Select a.rs (row 1) and review it
        app.selected = 1;
        app.toggle_reviewed();
        assert!(app.is_reviewed(0));
        // before hiding: Header(U) + a.rs + b.rs + Header(S) = 4 rows
        assert_eq!(app.rows.len(), 4);
        app.toggle_hide_reviewed();
        // a.rs hidden -> Header(U) + b.rs + Header(S) = 3 rows
        assert_eq!(app.rows.len(), 3);
        app.toggle_hide_reviewed();
        assert_eq!(app.rows.len(), 4); // shown again
    }

    #[test]
    fn rebuild_preserves_selection_identity() {
        let files = vec![
            FileChange {
                path: PathBuf::from("a.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("b.rs"),
                status: Status::Added,
            },
            FileChange {
                path: PathBuf::from("c.rs"),
                status: Status::Deleted,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // row 3 is c.rs (index 2 in unstaged); rows: H(U)(0) a(1) b(2) c(3) H(S)(4)
        app.selected = 3;
        app.rebuild_rows();
        // c.rs still selected (identity preserved)
        assert_eq!(app.selected_path().unwrap(), &PathBuf::from("c.rs"));
    }

    #[test]
    fn toggle_reviewed_on_dir_row_does_nothing() {
        let files = vec![FileChange {
            path: PathBuf::from("src/main.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // rows: Header(U)(0), Dir "src"(1), File "main.rs"(2), Header(S)(3)
        app.selected = 1; // Dir "src" row
        app.toggle_reviewed();
        // reviewed set should remain empty
        assert!(app.reviewed.is_empty());
    }

    #[test]
    fn reviewing_in_hide_mode_drops_file_and_keeps_valid_selection() {
        let files = vec![
            FileChange {
                path: PathBuf::from("a.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("b.rs"),
                status: Status::Added,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.toggle_hide_reviewed(); // hide-mode on, nothing reviewed yet
                                    // rows: Header(U)(0) + a.rs(1) + b.rs(2) + Header(S)(3) = 4 rows
        assert_eq!(app.rows.len(), 4);
        // select a.rs and review it
        app.selected = 1;
        app.toggle_reviewed();
        // rows: Header(U)(0) + b.rs(1) + Header(S)(2) = 3 rows
        assert_eq!(app.rows.len(), 3);
        // selection must still be valid; after clamping, row 1 = b.rs
        assert_eq!(app.selected_path().unwrap(), &PathBuf::from("b.rs"));
    }

    #[test]
    fn selected_section_returns_correct_section() {
        let unstaged = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let staged = vec![FileChange {
            path: PathBuf::from("b.rs"),
            status: Status::Added,
        }];
        let mut app = App::new(unstaged, staged, PathBuf::from("/repo"));
        // rows: Header(U)(0), a.rs(1), Header(S)(2), b.rs(3)
        app.selected = 1;
        assert_eq!(app.selected_section(), Some(Section::Unstaged));
        app.selected = 3;
        assert_eq!(app.selected_section(), Some(Section::Staged));
        app.selected = 0; // Header row
        assert_eq!(app.selected_section(), None);
    }

    #[test]
    fn effective_context_returns_context_lines_or_max() {
        let mut app = sample();
        // default: full_file is false -> effective_context == context_lines
        assert_eq!(app.effective_context(), app.context_lines);
        // toggle full_file on -> effective_context == u32::MAX
        app.toggle_full_file();
        assert_eq!(app.effective_context(), u32::MAX);
        // toggle back off -> effective_context == context_lines again
        app.toggle_full_file();
        assert_eq!(app.effective_context(), app.context_lines);
    }

    #[test]
    fn context_lines_inc_dec_clamp() {
        let mut app = sample();
        assert_eq!(app.context_lines, 3);
        // step is 5
        app.inc_context();
        assert_eq!(app.context_lines, 8);
        app.dec_context();
        assert_eq!(app.context_lines, 3);
        // inc clamps at MAX_CONTEXT_LINES then + switches to full file
        for _ in 0..60 {
            app.inc_context();
        }
        assert_eq!(app.context_lines, MAX_CONTEXT_LINES);
        assert!(app.full_file);
        // dec from full file restores hunks-only at max context
        app.dec_context();
        assert!(!app.full_file);
        assert_eq!(app.context_lines, MAX_CONTEXT_LINES);
        // dec clamps at 0
        for _ in 0..60 {
            app.dec_context();
        }
        assert_eq!(app.context_lines, 0);
        // one more dec stays at 0
        app.dec_context();
        assert_eq!(app.context_lines, 0);
    }

    #[test]
    fn inc_context_at_max_context_enables_full_file() {
        let mut app = sample();
        app.context_lines = MAX_CONTEXT_LINES;
        app.inc_context();
        assert!(app.full_file);
        assert_eq!(app.context_lines, MAX_CONTEXT_LINES);
        app.inc_context(); // no-op while full file
        assert!(app.full_file);
    }

    #[test]
    fn dec_context_from_full_file_via_f_keeps_context_lines() {
        let mut app = sample();
        app.context_lines = 8;
        app.toggle_full_file();
        app.dec_context();
        assert!(!app.full_file);
        assert_eq!(app.context_lines, 8);
    }

    #[test]
    fn resize_targets_right_pane_when_focused() {
        let mut app = sample();
        let f0 = app.file_pane_pct;
        let r0 = app.right_pane_pct;
        // Focus the right pane → resize affects it, not files. Directions are
        // mirrored: `>` (bigger=true) narrows it, `<` (bigger=false) widens it.
        app.focus = Pane::Comments;
        app.resize_focused_pane(false); // `<` widens
        assert_eq!(app.right_pane_pct, r0 + 5);
        assert_eq!(app.file_pane_pct, f0);
        app.resize_focused_pane(true); // `>` narrows
        assert_eq!(app.right_pane_pct, r0);
        // Focus files → resize affects files.
        app.focus = Pane::Files;
        app.resize_focused_pane(true);
        assert_eq!(app.file_pane_pct, f0 + 5);
    }

    #[test]
    fn file_pane_resize_clamps() {
        let mut app = sample();
        assert_eq!(app.file_pane_pct, 25);
        // widen to clamp at 60
        for _ in 0..20 {
            app.widen_files();
        }
        assert_eq!(app.file_pane_pct, 60);
        // narrow to clamp at 10
        for _ in 0..20 {
            app.narrow_files();
        }
        assert_eq!(app.file_pane_pct, 10);
    }

    #[test]
    fn toggle_files_sets_focus() {
        let mut app = sample();
        assert_eq!(app.show_files, true);
        assert_eq!(app.focus, Pane::Files);
        // toggle off while focused on Files -> show_files false, focus moves to Diff
        app.toggle_files();
        assert_eq!(app.show_files, false);
        assert_eq!(app.focus, Pane::Diff);
        // toggle on -> show_files true, but focus stays on Diff (no auto-steal back to Files)
        app.toggle_files();
        assert_eq!(app.show_files, true);
        assert_eq!(app.focus, Pane::Diff);
    }

    // ── Comment input tests ───────────────────────────────────────────────

    /// Build an App focused on Diff with a hunk + add line diff loaded.
    fn app_with_add_diff() -> App {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs row
        app.focus = Pane::Diff;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1,4 +1,8 @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "let x = 1;".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
        ]);
        app.diff_cursor = 1; // cursor on the Add line
        app
    }

    #[test]
    fn start_comment_sets_input_with_correct_target() {
        let mut app = app_with_add_diff();
        app.start_comment();
        assert!(app.input.is_some());
        let input = app.input.as_ref().unwrap();
        assert_eq!(input.target_file, PathBuf::from("a.rs"));
        assert_eq!(input.target_line, 2);
        assert_eq!(input.target_hunk, "@@ -1,4 +1,8 @@");
        assert_eq!(input.buffer, "");
    }

    #[test]
    fn start_comment_prefills_buffer_with_existing_comment() {
        let mut app = app_with_add_diff();
        // pre-load a comment for a.rs line 2
        app.comments.set(
            PathBuf::from("a.rs"),
            2,
            "@@ -1,4 +1,8 @@".to_string(),
            "existing note".to_string(),
            "let x = 1;".to_string(),
            vec![],
            vec![],
            0,
        );
        app.start_comment();
        let input = app.input.as_ref().unwrap();
        assert_eq!(input.buffer, "existing note");
    }

    #[test]
    fn start_comment_does_nothing_on_hunk_line() {
        let mut app = app_with_add_diff();
        app.diff_cursor = 0; // cursor on Hunk line
        app.start_comment();
        assert!(app.input.is_none());
    }

    #[test]
    fn start_comment_does_nothing_when_not_diff_focused() {
        let mut app = app_with_add_diff();
        app.focus = Pane::Files;
        app.start_comment();
        assert!(app.input.is_none());
    }

    #[test]
    fn input_push_backspace_newline_mutate_buffer() {
        let mut app = app_with_add_diff();
        app.start_comment();
        app.input_push('h');
        app.input_push('i');
        assert_eq!(app.input.as_ref().unwrap().buffer, "hi");
        app.input_newline();
        assert_eq!(app.input.as_ref().unwrap().buffer, "hi\n");
        app.input_push('!');
        assert_eq!(app.input.as_ref().unwrap().buffer, "hi\n!");
        app.input_backspace();
        assert_eq!(app.input.as_ref().unwrap().buffer, "hi\n");
        app.input_backspace();
        assert_eq!(app.input.as_ref().unwrap().buffer, "hi");
    }

    #[test]
    fn input_commit_returns_committed_comment_and_clears_input() {
        let mut app = app_with_add_diff();
        app.start_comment();
        app.input_push('g');
        app.input_push('o');
        let result = app.input_commit();
        assert!(result.is_some());
        let committed = result.unwrap();
        assert_eq!(committed.file, PathBuf::from("a.rs"));
        assert_eq!(committed.line, 2);
        assert_eq!(committed.hunk, "@@ -1,4 +1,8 @@");
        assert_eq!(committed.text, "go");
        // Anchor from the diff: cursor on "let x = 1;" at new_lineno 2
        assert_eq!(committed.line_text, "let x = 1;");
        // input cleared
        assert!(app.input.is_none());
    }

    #[test]
    fn current_hunk_header_finds_preceding_hunk() {
        let mut app = app_with_add_diff();
        app.diff_cursor = 1; // past the Hunk line at index 0
        let hunk = app.current_hunk_header();
        assert_eq!(hunk, "@@ -1,4 +1,8 @@");
    }

    #[test]
    fn current_hunk_header_returns_empty_when_no_hunk() {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.focus = Pane::Diff;
        app.selected = 1;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Context,
            text: "ctx".into(),
            old_lineno: Some(1),
            new_lineno: Some(1),
        }]);
        app.diff_cursor = 0;
        assert_eq!(app.current_hunk_header(), "");
    }

    #[test]
    fn comment_anchor_captures_line_text_and_context() {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.focus = Pane::Diff;
        app.selected = 1;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1 +1 @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Context,
                text: "  let a = 1;  ".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "  fn target()  ".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "  let b = 2;  ".into(),
                old_lineno: Some(3),
                new_lineno: Some(3),
            },
        ]);
        app.diff_cursor = 2; // cursor on the Add line

        let (line_text, before, after) = app.comment_anchor();
        assert_eq!(line_text, "fn target()"); // trimmed
                                              // context_before: last non-hunk line before index 2 = index 1 (Context)
        assert_eq!(before, vec!["let a = 1;"]);
        // context_after: next non-hunk line after index 2 = index 3 (Context)
        assert_eq!(after, vec!["let b = 2;"]);
    }

    #[test]
    fn comment_anchor_skips_hunk_lines_in_context() {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.focus = Pane::Diff;
        app.selected = 1;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1 +1 @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "first".into(),
                old_lineno: None,
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -5 +5 @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "target".into(),
                old_lineno: None,
                new_lineno: Some(5),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "after".into(),
                old_lineno: Some(6),
                new_lineno: Some(6),
            },
        ]);
        app.diff_cursor = 3; // cursor on "target" Add line

        let (line_text, before, after) = app.comment_anchor();
        assert_eq!(line_text, "target");
        // Hunk line at index 2 is skipped; next non-hunk before is "first" at index 1
        assert_eq!(before, vec!["first"]);
        assert_eq!(after, vec!["after"]);
    }

    // FIX 4 TDD: anchor captured at start_comment time, not at commit time
    #[test]
    fn start_comment_captures_anchor_in_input_state() {
        // Build an app with context lines so comment_anchor() returns real data
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "  let a = 1;  ".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "  fn target()  ".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "  let b = 2;  ".into(),
                old_lineno: Some(3),
                new_lineno: Some(3),
            },
        ]);
        app.diff_cursor = 1; // cursor on Add line "fn target()"
        app.start_comment();

        let input = app.input.as_ref().expect("input should be active");
        // Anchor captured at start_comment time
        assert_eq!(input.anchor_line_text, "fn target()");
        assert_eq!(input.anchor_before, vec!["let a = 1;"]);
        assert_eq!(input.anchor_after, vec!["let b = 2;"]);
    }

    // ── Help overlay tests ───────────────────────────────────────────────────

    #[test]
    fn toggle_help_flips_show_help() {
        let mut app = sample();
        assert!(!app.show_help);
        app.toggle_help();
        assert!(app.show_help);
        app.toggle_help();
        assert!(!app.show_help);
    }

    #[test]
    fn toggle_theme_flips_dark_light() {
        let mut app = sample();
        assert_eq!(app.theme, crate::theme::Theme::Dark);
        app.toggle_theme();
        assert_eq!(app.theme, crate::theme::Theme::Light);
        app.toggle_theme();
        assert_eq!(app.theme, crate::theme::Theme::Dark);
    }

    #[test]
    fn toggle_split_flips_flag() {
        let mut app = sample();
        assert!(!app.split_diff);
        app.toggle_split();
        assert!(app.split_diff);
        app.toggle_split();
        assert!(!app.split_diff);
    }

    #[test]
    fn palette_returns_matching_palette_for_theme() {
        let mut app = sample();
        // Dark theme
        let dark_pal = app.palette();
        assert_eq!(
            dark_pal.accent,
            crate::theme::Palette::for_theme(crate::theme::Theme::Dark).accent
        );
        // Switch to light
        app.toggle_theme();
        let light_pal = app.palette();
        assert_eq!(
            light_pal.accent,
            crate::theme::Palette::for_theme(crate::theme::Theme::Light).accent
        );
        assert_ne!(dark_pal.accent, light_pal.accent);
    }

    // ── NEW: ViewMode / commit list state tests ──────────────────────────────

    fn make_commit_info(summary: &str) -> crate::git::CommitInfo {
        crate::git::CommitInfo {
            id: "abcdef1234567890".to_string(),
            short: "abcdef12".to_string(),
            summary: summary.to_string(),
            author: "test".to_string(),
            time: "2024-01-01".to_string(),
        }
    }

    #[test]
    fn start_history_empty_commits_returns_false() {
        let mut app = sample();
        app.selected = 1; // a.rs
        let ok = app.start_history(vec![]);
        assert!(!ok);
        assert!(app.history.is_none());
    }

    #[test]
    fn start_history_sets_state_at_rev_one() {
        let mut app = sample();
        app.selected = 1; // a.rs
        let ok = app.start_history(vec![make_commit_info("c1"), make_commit_info("c2")]);
        assert!(ok);
        let h = app.history.as_ref().unwrap();
        assert_eq!(h.file, std::path::PathBuf::from("a.rs"));
        assert_eq!(h.commits.len(), 2);
        assert_eq!(h.idx, 1); // newest commit, one step back from baseline
        assert_eq!(h.baseline_scope, CommentScope::Worktree);
    }

    #[test]
    fn history_step_clamps_to_zero_and_len() {
        let mut app = sample();
        app.selected = 1;
        app.start_history(vec![make_commit_info("c1"), make_commit_info("c2")]);
        // idx starts at 1
        app.history_step(1); // older -> 2
        assert_eq!(app.history.as_ref().unwrap().idx, 2);
        app.history_step(1); // older past oldest -> stays 2
        assert_eq!(app.history.as_ref().unwrap().idx, 2);
        app.history_step(-1); // newer -> 1
        app.history_step(-1); // newer -> 0 (baseline)
        assert_eq!(app.history.as_ref().unwrap().idx, 0);
        app.history_step(-1); // never negative -> stays 0
        assert_eq!(app.history.as_ref().unwrap().idx, 0);
    }

    #[test]
    fn history_current_commit_none_at_baseline() {
        let mut app = sample();
        app.selected = 1;
        app.start_history(vec![make_commit_info("c1")]);
        assert!(app.history_current_commit().is_some()); // idx 1
        app.history_step(-1); // idx 0
        assert!(app.history_current_commit().is_none());
    }

    #[test]
    fn exit_history_restores_scope_and_clears() {
        let mut app = sample();
        app.selected = 1;
        app.comment_scope = CommentScope::Worktree;
        app.start_history(vec![make_commit_info("c1")]);
        // Simulate the main loop swapping scope into the revision's commit.
        app.comment_scope = CommentScope::Commit("abcdef1234567890".into());
        app.exit_history();
        assert!(app.history.is_none());
        assert_eq!(app.comment_scope, CommentScope::Worktree);
    }

    fn app_with_search_diff() -> App {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "fn alpha() {".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "let Beta = 2;".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "let gamma = 3;".into(),
                old_lineno: Some(3),
                new_lineno: Some(3),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "return beta;".into(),
                old_lineno: None,
                new_lineno: Some(4),
            },
        ]);
        app
    }

    #[test]
    fn search_commit_finds_case_insensitive_matches() {
        let mut app = app_with_search_diff();
        app.search_start();
        for ch in "beta".chars() {
            app.search_input_push(ch);
        }
        let ok = app.search_commit();
        assert!(ok);
        let s = app.search.as_ref().unwrap();
        // "let Beta = 2;" (idx 1) and "return beta;" (idx 3)
        assert_eq!(s.matches, vec![1, 3]);
        // cursor jumped to first match at/after current cursor (cursor was 0) -> idx 1
        assert_eq!(app.diff_cursor, 1);
    }

    #[test]
    fn search_commit_no_match_returns_false() {
        let mut app = app_with_search_diff();
        app.search_start();
        for ch in "zzz".chars() {
            app.search_input_push(ch);
        }
        let ok = app.search_commit();
        assert!(!ok);
        assert!(app.search.is_none());
    }

    #[test]
    fn search_next_wraps_forward_and_back() {
        let mut app = app_with_search_diff();
        app.search_start();
        for ch in "beta".chars() {
            app.search_input_push(ch);
        }
        app.search_commit(); // cursor at idx 1 (cur=0)
        app.search_next(1); // -> idx 3 (cur=1)
        assert_eq!(app.diff_cursor, 3);
        app.search_next(1); // wrap -> idx 1 (cur=0)
        assert_eq!(app.diff_cursor, 1);
        app.search_next(-1); // wrap back -> idx 3 (cur=1)
        assert_eq!(app.diff_cursor, 3);
    }

    #[test]
    fn set_diff_clears_active_search() {
        let mut app = app_with_search_diff();
        app.search_start();
        for ch in "beta".chars() {
            app.search_input_push(ch);
        }
        app.search_commit();
        assert!(app.search.is_some());
        app.set_diff(vec![DiffLine::context("x", 1, 1)]);
        assert!(app.search.is_none());
        assert!(app.search_input.is_none());
    }

    #[test]
    fn search_input_push_backspace_cancel() {
        let mut app = app_with_search_diff();
        app.search_start();
        app.search_input_push('a');
        app.search_input_push('b');
        assert_eq!(app.search_input.as_deref(), Some("ab"));
        app.search_input_backspace();
        assert_eq!(app.search_input.as_deref(), Some("a"));
        app.search_input_cancel();
        assert!(app.search_input.is_none());
        assert!(app.search.is_none());
    }

    #[test]
    fn view_mode_toggles_with_next_and_prev_view() {
        let mut app = sample();
        assert_eq!(app.view, ViewMode::Changes);
        app.next_view();
        assert_eq!(app.view, ViewMode::Commits);
        app.next_view();
        assert_eq!(app.view, ViewMode::Changes);
        app.prev_view();
        assert_eq!(app.view, ViewMode::Commits);
        app.prev_view();
        assert_eq!(app.view, ViewMode::Changes);
    }

    #[test]
    fn move_commit_selection_clamps() {
        let mut app = sample();
        app.commits = vec![
            make_commit_info("first"),
            make_commit_info("second"),
            make_commit_info("third"),
        ];
        // start at 0
        assert_eq!(app.selected_commit, 0);
        app.move_commit_selection(1);
        assert_eq!(app.selected_commit, 1);
        app.move_commit_selection(99);
        assert_eq!(app.selected_commit, 2); // clamped to max index
        app.move_commit_selection(-99);
        assert_eq!(app.selected_commit, 0); // clamped to 0
    }

    #[test]
    fn input_commit_includes_anchor_fields() {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "before_line".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "the_target_line".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "after_line".into(),
                old_lineno: Some(3),
                new_lineno: Some(3),
            },
        ]);
        app.diff_cursor = 1;
        app.start_comment();
        app.input_push('n');
        app.input_push('o');
        app.input_push('t');
        app.input_push('e');
        let result = app.input_commit();
        assert!(result.is_some());
        let committed = result.unwrap();
        assert_eq!(committed.file, PathBuf::from("a.rs"));
        assert_eq!(committed.line, 2);
        assert_eq!(committed.hunk, ""); // no hunk header in this diff
        assert_eq!(committed.text, "note");
        assert_eq!(committed.line_text, "the_target_line");
        assert_eq!(committed.context_before, vec!["before_line"]);
        assert_eq!(committed.context_after, vec!["after_line"]);
        assert!(app.input.is_none());
    }

    // ── Part 2 TDD: commit-detail open/close/section_files ─────────────────

    fn make_commit_files(paths: &[&str]) -> Vec<FileChange> {
        paths
            .iter()
            .map(|p| FileChange {
                path: PathBuf::from(p),
                status: Status::Modified,
            })
            .collect()
    }

    #[test]
    fn open_commit_sets_state_and_builds_commit_rows() {
        let mut app = sample();
        app.view = ViewMode::Commits;
        // Give it a commit info so open_commit_short can resolve.
        app.commits = vec![crate::git::CommitInfo {
            id: "aaaa1111bbbb2222".to_string(),
            short: "aaaa1111".to_string(),
            summary: "test commit".to_string(),
            author: "tester".to_string(),
            time: "2024-01-01".to_string(),
        }];
        let files = make_commit_files(&["src/main.rs", "lib.rs"]);
        app.open_commit("aaaa1111bbbb2222".to_string(), files);

        // open_commit field set, commit_files populated
        assert_eq!(app.open_commit, Some("aaaa1111bbbb2222".to_string()));
        assert_eq!(app.commit_files.len(), 2);
        // selected reset
        assert_eq!(app.selected, 0);
        // in_commit_detail() is true
        assert!(app.in_commit_detail());
        // rows should have: Header(Commit) + Dir(src) + File(main.rs) + File(lib.rs)
        // = 1 header + 1 dir + 1 file under dir + 1 flat file = 4 rows
        assert!(
            app.rows.len() >= 3,
            "expected at least 3 rows (header + files), got {}",
            app.rows.len()
        );
        // First row is a Commit header
        assert!(matches!(
            app.rows[0].kind,
            crate::tree::RowKind::Header {
                section: Section::Commit,
                ..
            }
        ));
        // At least one File row with Section::Commit
        let has_commit_file = app.rows.iter().any(|r| {
            matches!(
                &r.kind,
                crate::tree::RowKind::File {
                    section: Section::Commit,
                    ..
                }
            )
        });
        assert!(has_commit_file, "expected File rows with Section::Commit");
    }

    #[test]
    fn close_commit_clears_state_and_rebuilds() {
        let mut app = sample();
        app.view = ViewMode::Commits;
        let files = make_commit_files(&["a.rs"]);
        app.open_commit("deadbeef12345678".to_string(), files);
        assert!(app.in_commit_detail());

        app.close_commit();

        assert_eq!(app.open_commit, None);
        assert!(app.commit_files.is_empty());
        assert!(!app.in_commit_detail());
        // rows rebuilt (no open_commit means back to normal unstaged/staged rows from sample)
        // sample() has 3 unstaged files -> Header(U) + 3 files + Header(S) = 5 rows
        assert_eq!(app.rows.len(), 5);
    }

    #[test]
    fn switching_view_from_commit_detail_rebuilds_rows() {
        // Regression: leaving a commit detail via [ / ] cleared commit_files but
        // left rows pointing into them, causing an out-of-bounds panic on next access.
        let mut app = sample();
        app.view = ViewMode::Commits;
        let files = make_commit_files(&["a.rs", "b.rs"]);
        app.open_commit("deadbeef12345678".to_string(), files);
        assert!(app.in_commit_detail());

        app.next_view(); // leave Commits -> Changes; must clear AND rebuild

        assert_eq!(app.open_commit, None);
        assert!(app.commit_files.is_empty());
        // No row may reference Section::Commit anymore.
        assert!(!app.rows.iter().any(|r| matches!(
            &r.kind,
            crate::tree::RowKind::File {
                section: Section::Commit,
                ..
            } | crate::tree::RowKind::Header {
                section: Section::Commit,
                ..
            }
        )));
        // selected must be in bounds for the rebuilt rows.
        assert!(app.selected < app.rows.len().max(1));
    }

    #[test]
    fn section_files_commit_returns_commit_files() {
        let mut app = sample();
        let files = make_commit_files(&["x.rs", "y.rs", "z.rs"]);
        app.commit_files = files.clone();
        let result = app.section_files(Section::Commit);
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].path, PathBuf::from("x.rs"));
        assert_eq!(result[1].path, PathBuf::from("y.rs"));
        assert_eq!(result[2].path, PathBuf::from("z.rs"));
    }

    // ── Part 2 TDD: comment pane state, Pane::Comments, comment_rows, jump ─────

    fn sample_with_comments() -> App {
        let files = vec![
            FileChange {
                path: PathBuf::from("a.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("b.rs"),
                status: Status::Added,
            },
        ];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // Add comments of various statuses
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "@@".to_string(),
            "open note".to_string(),
            "fn a()".to_string(),
            vec![],
            vec![],
            0,
        );
        // items[0] is Open by default
        app.comments.set(
            PathBuf::from("a.rs"),
            5,
            "@@".to_string(),
            "resolved note".to_string(),
            "fn b()".to_string(),
            vec![],
            vec![],
            0,
        );
        app.comments.items[1].status = crate::comments::CommentStatus::Resolved;
        app.comments.set(
            PathBuf::from("b.rs"),
            3,
            "@@".to_string(),
            "wontfix note".to_string(),
            "fn c()".to_string(),
            vec![],
            vec![],
            0,
        );
        app.comments.items[2].status = crate::comments::CommentStatus::Wontfix;
        app.comments.set(
            PathBuf::from("b.rs"),
            7,
            "@@".to_string(),
            "needs info note".to_string(),
            "fn d()".to_string(),
            vec![],
            vec![],
            0,
        );
        app.comments.items[3].status = crate::comments::CommentStatus::NeedsInfo;
        app
    }

    #[test]
    fn comment_rows_groups_by_status_open_first() {
        let app = sample_with_comments();
        let rows = app.comment_rows();
        // Expected: Header(Open,1) Item(0) Header(NeedsInfo,1) Item(3) Header(Wontfix,1) Item(2) Header(Resolved,1) Item(1)
        // Order: Open, NeedsInfo, Wontfix, Resolved
        assert!(!rows.is_empty(), "comment_rows must not be empty");
        // First row is Header(Open)
        assert!(matches!(
            rows[0],
            CommentRow::Header(crate::comments::CommentStatus::Open, 1)
        ));
        // Second row is Item pointing to index 0 (the Open comment)
        assert!(matches!(rows[1], CommentRow::Item(0)));
        // Find Header(NeedsInfo)
        let ni_pos = rows.iter().position(|r| {
            matches!(
                r,
                CommentRow::Header(crate::comments::CommentStatus::NeedsInfo, 1)
            )
        });
        assert!(ni_pos.is_some(), "NeedsInfo header must be present");
        // Find Header(Wontfix)
        let wf_pos = rows.iter().position(|r| {
            matches!(
                r,
                CommentRow::Header(crate::comments::CommentStatus::Wontfix, 1)
            )
        });
        assert!(wf_pos.is_some(), "Wontfix header must be present");
        // Find Header(Resolved)
        let res_pos = rows.iter().position(|r| {
            matches!(
                r,
                CommentRow::Header(crate::comments::CommentStatus::Resolved, 1)
            )
        });
        assert!(res_pos.is_some(), "Resolved header must be present");
        // Order: Open < NeedsInfo < Wontfix < Resolved
        let open_pos = rows
            .iter()
            .position(|r| {
                matches!(
                    r,
                    CommentRow::Header(crate::comments::CommentStatus::Open, _)
                )
            })
            .unwrap();
        assert!(
            open_pos < ni_pos.unwrap(),
            "Open must come before NeedsInfo"
        );
        assert!(
            ni_pos.unwrap() < wf_pos.unwrap(),
            "NeedsInfo must come before Wontfix"
        );
        assert!(
            wf_pos.unwrap() < res_pos.unwrap(),
            "Wontfix must come before Resolved"
        );
    }

    #[test]
    fn comment_rows_skips_empty_groups() {
        let mut app = sample();
        // Only add an Open comment — other groups should be absent
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "@@".to_string(),
            "only open".to_string(),
            "fn a()".to_string(),
            vec![],
            vec![],
            0,
        );
        let rows = app.comment_rows();
        // No Resolved header
        let has_resolved = rows.iter().any(|r| {
            matches!(
                r,
                CommentRow::Header(crate::comments::CommentStatus::Resolved, _)
            )
        });
        assert!(
            !has_resolved,
            "Resolved header should not appear when no resolved comments"
        );
        // Total: Header(Open) + Item(0) = 2
        assert_eq!(rows.len(), 2);
    }

    #[test]
    fn move_comment_selection_clamps() {
        let mut app = sample_with_comments();
        // 4 comments, 4 groups => 8 rows (4 headers + 4 items)
        let row_count = app.comment_rows().len();
        assert_eq!(row_count, 8);
        // Move beyond end clamps
        app.move_comment_selection(100);
        assert_eq!(app.comment_selected, row_count - 1);
        // Move below 0 clamps
        app.move_comment_selection(-100);
        assert_eq!(app.comment_selected, 0);
        // Normal step
        app.move_comment_selection(1);
        assert_eq!(app.comment_selected, 1);
    }

    #[test]
    fn selected_comment_returns_none_on_header_some_on_item() {
        let mut app = sample_with_comments();
        // Row 0 is a Header
        app.comment_selected = 0;
        assert!(
            app.selected_comment().is_none(),
            "selected_comment must be None for a header row"
        );
        // Row 1 is an Item
        app.comment_selected = 1;
        assert!(
            app.selected_comment().is_some(),
            "selected_comment must be Some for an item row"
        );
    }

    #[test]
    fn select_row_for_path_finds_file_row() {
        let mut app = sample();
        // rows: Header(U)(0), a.rs(1), b.rs(2), c.rs(3), Header(S)(4)
        let found = app.select_row_for_path(Path::new("b.rs"));
        assert!(
            found,
            "select_row_for_path must return true for an existing file path"
        );
        assert_eq!(app.selected_path(), Some(&PathBuf::from("b.rs")));
    }

    #[test]
    fn select_row_for_path_returns_false_for_missing() {
        let mut app = sample();
        let found = app.select_row_for_path(Path::new("nonexistent.rs"));
        assert!(
            !found,
            "select_row_for_path must return false for a path not in rows"
        );
    }

    #[test]
    fn cursor_lineno_prefers_new_over_old() {
        let mut app = sample();
        app.set_diff(vec![DiffLine {
            kind: LineKind::Del,
            text: "gone".into(),
            old_lineno: Some(7),
            new_lineno: None,
        }]);
        app.diff_cursor = 0;
        assert_eq!(app.cursor_lineno(), Some(7));
    }

    #[test]
    fn diff_has_lineno_matches_new_or_old() {
        let mut app = sample();
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Del,
                text: "gone".into(),
                old_lineno: Some(7),
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "new".into(),
                old_lineno: None,
                new_lineno: Some(9),
            },
        ]);
        assert!(app.diff_has_lineno(7));
        assert!(app.diff_has_lineno(9));
        assert!(!app.diff_has_lineno(1));
    }

    #[test]
    fn move_cursor_to_lineno_falls_back_to_old_lineno() {
        let mut app = sample();
        app.set_diff(vec![DiffLine {
            kind: LineKind::Del,
            text: "gone".into(),
            old_lineno: Some(7),
            new_lineno: None,
        }]);
        app.move_cursor_to_lineno(7);
        assert_eq!(app.diff_cursor, 0);
    }

    #[test]
    fn move_cursor_to_line_positions_diff_cursor() {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "x".into(),
                old_lineno: Some(1),
                new_lineno: Some(1),
            },
            DiffLine {
                kind: LineKind::Context,
                text: "y".into(),
                old_lineno: Some(2),
                new_lineno: Some(2),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "z".into(),
                old_lineno: None,
                new_lineno: Some(5),
            },
        ]);
        app.move_cursor_to_line(5);
        assert_eq!(
            app.diff_cursor, 2,
            "diff_cursor must point to the line with new_lineno==5"
        );
        // Non-existent line: cursor stays unchanged
        app.move_cursor_to_line(99);
        assert_eq!(
            app.diff_cursor, 0,
            "cursor should reset to 0 when line not found"
        );
    }

    #[test]
    fn toggle_focus_cycles_through_visible_panes() {
        let mut app = sample();
        // Default: show_files=true, show_comments=false
        // Cycle: Files -> Diff -> Files (Comments skipped since show_comments=false)
        assert_eq!(app.focus, Pane::Files);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Diff);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Files);

        // Enable comments pane
        app.show_comments = true;
        // Cycle: Files -> Diff -> Comments -> Files
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Diff);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Comments);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Files);
    }

    #[test]
    fn toggle_focus_only_diff_visible_stays_diff() {
        let mut app = sample();
        app.show_files = false;
        app.show_comments = false;
        app.focus = Pane::Diff;
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Diff);
    }

    #[test]
    fn toggle_comment_pane_flips_show_comments() {
        let mut app = sample();
        assert!(!app.show_comments);
        app.toggle_comment_pane();
        assert!(app.show_comments);
        app.toggle_comment_pane();
        assert!(!app.show_comments);
    }

    #[test]
    fn toggle_comment_pane_focuses_comments_when_opening() {
        let mut app = sample();
        app.focus = Pane::Files;
        app.toggle_comment_pane(); // opens
        assert!(app.show_comments);
        assert_eq!(app.focus, Pane::Comments);
    }

    #[test]
    fn toggle_comment_pane_moves_focus_when_hiding_comments() {
        let mut app = sample();
        app.show_comments = true;
        app.focus = Pane::Comments;
        // Hiding comments while focused on Comments -> focus moves to Diff
        app.toggle_comment_pane();
        assert!(!app.show_comments);
        assert_eq!(app.focus, Pane::Diff);
    }

    // ── Part 2 TDD: sort within group by updated desc ────────────────────────

    #[test]
    fn comment_rows_within_open_group_sorted_by_updated_desc() {
        let mut app = sample();
        // Add two Open comments: one with updated=500 (older), one with updated=1500 (newer)
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "@@".to_string(),
            "older comment".to_string(),
            "fn a()".to_string(),
            vec![],
            vec![],
            500,
        );
        // items[0].updated = 500
        app.comments.set(
            PathBuf::from("a.rs"),
            2,
            "@@".to_string(),
            "newer comment".to_string(),
            "fn b()".to_string(),
            vec![],
            vec![],
            1500,
        );
        // items[1].updated = 1500
        let rows = app.comment_rows();
        // Expected: Header(Open,2), Item(?newer), Item(?older)
        // The newer-updated comment (items[1], updated=1500) should come first
        assert_eq!(rows.len(), 3, "Header + 2 items");
        assert!(matches!(
            rows[0],
            CommentRow::Header(crate::comments::CommentStatus::Open, 2)
        ));
        // First Item should be the one with updated=1500 (items index 1)
        match rows[1] {
            CommentRow::Item(idx) => {
                assert_eq!(
                    app.comments.items[idx].text, "newer comment",
                    "first item in group must be the newer-updated comment"
                );
            }
            _ => panic!("expected Item at rows[1]"),
        }
        match rows[2] {
            CommentRow::Item(idx) => {
                assert_eq!(
                    app.comments.items[idx].text, "older comment",
                    "second item in group must be the older-updated comment"
                );
            }
            _ => panic!("expected Item at rows[2]"),
        }
    }

    // ── CommentScope tests ─────────────────────────────────────────────────────

    #[test]
    fn open_commit_sets_comment_scope_to_commit() {
        let mut app = sample();
        app.view = ViewMode::Commits;
        assert_eq!(app.comment_scope, CommentScope::Worktree);

        let files = make_commit_files(&["a.rs"]);
        app.open_commit("deadbeef1234567890abcdef".to_string(), files);

        assert_eq!(
            app.comment_scope,
            CommentScope::Commit("deadbeef1234567890abcdef".to_string())
        );
    }

    #[test]
    fn close_commit_resets_comment_scope_to_worktree() {
        let mut app = sample();
        app.view = ViewMode::Commits;
        let files = make_commit_files(&["a.rs"]);
        app.open_commit("deadbeef1234567890abcdef".to_string(), files);
        assert_eq!(
            app.comment_scope,
            CommentScope::Commit("deadbeef1234567890abcdef".to_string())
        );

        app.close_commit();

        assert_eq!(app.comment_scope, CommentScope::Worktree);
    }

    #[test]
    fn next_view_from_commits_resets_scope_to_worktree() {
        let mut app = sample();
        app.view = ViewMode::Commits;
        let files = make_commit_files(&["a.rs"]);
        app.open_commit("aabbccdd11223344".to_string(), files);
        assert_eq!(
            app.comment_scope,
            CommentScope::Commit("aabbccdd11223344".to_string())
        );

        // next_view from Commits -> Changes clears open_commit and resets scope
        app.next_view();

        assert_eq!(app.view, ViewMode::Changes);
        assert_eq!(app.comment_scope, CommentScope::Worktree);
    }

    #[test]
    fn scope_label_worktree() {
        let app = sample();
        assert_eq!(app.scope_label(), "worktree");
    }

    #[test]
    fn scope_label_commit() {
        let mut app = sample();
        app.view = ViewMode::Commits;
        let files = make_commit_files(&["a.rs"]);
        app.open_commit("abc123def456".to_string(), files);
        assert_eq!(app.scope_label(), "commit:abc123def456");
    }

    // ─── Debugger: breakpoint toggle + panel ─────────────────────────────────

    /// App with file `a.rs` selected and a diff whose cursor sits on new line 2.
    fn app_on_diff_line() -> App {
        let mut app = sample();
        app.selected = 1; // a.rs (row 0 is the Unstaged header)
        app.focus = Pane::Diff;
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Add,
                text: "let x = 1;".into(),
                old_lineno: None,
                new_lineno: Some(2),
            },
            DiffLine::context("ctx", 3, 3),
        ]);
        app.diff_cursor = 0; // on new line 2
        app
    }

    #[test]
    fn toggle_breakpoint_adds_then_removes() {
        let mut app = app_on_diff_line();
        let abs = PathBuf::from("/repo").join("a.rs");
        assert!(!app.has_breakpoint(&abs, 2));

        // First toggle sets it.
        assert!(app.toggle_breakpoint_at_cursor());
        assert!(app.has_breakpoint(&abs, 2));
        assert!(app.debug_active());

        // Second toggle clears it; with no sessions/bps left, debug state drops.
        assert!(!app.toggle_breakpoint_at_cursor());
        assert!(!app.has_breakpoint(&abs, 2));
        assert!(!app.debug_active());
    }

    #[test]
    fn toggle_breakpoint_noop_without_source_line() {
        let mut app = sample();
        app.focus = Pane::Diff;
        // No file selected / no diff → no source loc.
        assert!(!app.toggle_breakpoint_at_cursor());
        assert!(!app.debug_active());
    }

    #[test]
    fn debug_panel_selection_clamps_to_rows() {
        let mut app = app_on_diff_line();
        let mut st = DebugState::default();
        let mut sess = DebugSession::new(1, "worktree".into());
        sess.stack = vec![crate::dap::Frame {
            name: "main".into(),
            file: None,
            line: 0,
            id: 0,
            locals: vec![],
        }];
        sess.locals = vec![
            crate::dap::VarRow {
                name: "x".into(),
                value: "1".into(),
                ty: None,
                var_ref: 0,
                memory_ref: None,
                expanded: false,
                children: vec![],
            },
            crate::dap::VarRow {
                name: "y".into(),
                value: "2".into(),
                ty: None,
                var_ref: 0,
                memory_ref: None,
                expanded: false,
                children: vec![],
            },
        ];
        // Three frames; selection is over frames (locals nest under the selected).
        let frame = |n: &str| crate::dap::Frame {
            name: n.into(),
            file: None,
            line: 0,
            id: 0,
            locals: vec![],
        };
        sess.stack = vec![frame("a"), frame("b"), frame("c")];
        st.sessions.push(sess);
        app.debug = Some(st);

        assert_eq!(app.debug_panel_len(), 3); // 3 frames, no locals
        app.focus = Pane::Comments;
        app.right_tab = RightTab::Debug;
        app.move_debug_panel_selection(99);
        assert_eq!(app.debug.as_ref().unwrap().panel_sel, 2); // clamped to last row
        app.move_debug_panel_selection(-99);
        assert_eq!(app.debug.as_ref().unwrap().panel_sel, 0);
    }

    #[test]
    fn expand_var_flattens_children_and_requests_fetch() {
        let mut app = app_on_diff_line();
        let mut st = DebugState::default();
        let mut sess = DebugSession::new(1, "s".into());
        let var = |name: &str, vref: i64| crate::dap::VarRow {
            name: name.into(),
            value: "..".into(),
            ty: None,
            var_ref: vref,
            memory_ref: None,
            expanded: false,
            children: vec![],
        };
        sess.stack = vec![crate::dap::Frame {
            name: "f".into(),
            file: None,
            line: 0,
            id: 7,
            locals: vec![var("s", 1004)], // expandable String
        }];
        st.sessions.push(sess);
        app.debug = Some(st);

        // Rows: frame + 1 var = 2.
        assert_eq!(app.debug_panel_len(), 2);
        // Select the var (row 1) and expand it.
        app.debug.as_mut().unwrap().panel_sel = 1;
        let req = app.toggle_expand_selected_var();
        assert_eq!(req, Some((0, 1004, vec![0]))); // needs a fetch

        // Supply children → they flatten in (frame + var + 2 children = 4).
        app.set_var_children(0, &[0], vec![var("[0]", 0), var("[1]", 0)]);
        assert_eq!(app.debug_panel_len(), 4);

        // Collapsing hides them again (no fetch needed).
        app.debug.as_mut().unwrap().panel_sel = 1;
        assert_eq!(app.toggle_expand_selected_var(), None);
        assert_eq!(app.debug_panel_len(), 2);
    }

    #[test]
    fn attach_snapshot_creates_comment_with_stack() {
        let mut app = app_on_diff_line();
        let snap = crate::dap::DebugSnapshot {
            session_label: "worktree".into(),
            stopped_file: "/repo/a.rs".into(), // abs; repo_root is /repo
            stopped_line: 2,
            stack: vec![crate::dap::Frame {
                name: "main".into(),
                file: Some("/repo/a.rs".into()),
                line: 2,
                id: 0,
                locals: vec![],
            }],
            locals: vec![],
            captured: 1,
        };
        app.attach_debug_snapshot(snap);
        let c = app
            .comments
            .items
            .iter()
            .find(|c| c.file == PathBuf::from("a.rs") && c.line == 2)
            .expect("comment created at stopped line");
        assert!(c.debug_snapshot.is_some());
        assert_eq!(c.debug_snapshot.as_ref().unwrap().stack[0].name, "main");
    }

    #[test]
    fn breakpoint_list_toggle_and_delete() {
        let mut app = app_on_diff_line();
        app.toggle_breakpoint_at_cursor(); // /repo/a.rs:2, enabled
        let abs = PathBuf::from("/repo").join("a.rs");
        assert!(app.breakpoint_enabled(&abs, 2));
        assert_eq!(app.breakpoint_count(), 1);

        // Select it and disable.
        let on = app.toggle_selected_breakpoint();
        assert_eq!(on, Some(false));
        assert!(app.has_breakpoint(&abs, 2)); // still present
        assert!(!app.breakpoint_enabled(&abs, 2)); // but disabled

        // Re-enable.
        assert_eq!(app.toggle_selected_breakpoint(), Some(true));
        assert!(app.breakpoint_enabled(&abs, 2));

        // Delete removes it entirely.
        assert!(app.delete_selected_breakpoint());
        assert_eq!(app.breakpoint_count(), 0);
        assert!(!app.has_breakpoint(&abs, 2));
    }

    #[test]
    fn launch_picker_modes_depend_on_view() {
        let mut app = sample();
        // Changes view: Worktree + Remote (no Commit).
        app.open_launch_picker();
        assert!(app.launch_picker_active());
        assert_eq!(
            app.launch_modes(),
            vec![LaunchMode::Worktree, LaunchMode::Process, LaunchMode::Remote]
        );
        assert_eq!(app.selected_launch_mode(), Some(LaunchMode::Worktree));
        app.move_launch_pick(9); // clamp to last
        assert_eq!(app.selected_launch_mode(), Some(LaunchMode::Remote));
        app.close_launch_picker();
        assert!(!app.launch_picker_active());

        // Commits view: Commit option appears first.
        app.view = ViewMode::Commits;
        assert_eq!(
            app.launch_modes(),
            vec![
                LaunchMode::Commit,
                LaunchMode::Worktree,
                LaunchMode::Process,
                LaunchMode::Remote
            ]
        );
    }

    #[test]
    fn proc_picker_filters_and_selects() {
        let mut app = sample();
        app.proc_picker = Some(ProcPicker {
            procs: vec![
                crate::process::ProcInfo { pid: 100, command: "zsh".into() },
                crate::process::ProcInfo { pid: 200, command: "myapp".into() },
                crate::process::ProcInfo { pid: 300, command: "myapp-helper".into() },
            ],
            filter: String::new(),
            sel: 0,
        });
        assert!(app.proc_picker_active());
        // Filter to the two "myapp*" entries.
        app.proc_filter_push('m');
        app.proc_filter_push('y');
        assert_eq!(app.proc_picker.as_ref().unwrap().filtered().len(), 2);
        assert_eq!(app.selected_process(), Some((200, "myapp".into())));
        app.move_proc_pick(1);
        assert_eq!(app.selected_process(), Some((300, "myapp-helper".into())));
        // Filter by pid digits too.
        app.proc_filter_backspace();
        app.proc_filter_backspace();
        app.proc_filter_push('3');
        assert_eq!(app.selected_process(), Some((300, "myapp-helper".into())));
    }

    #[test]
    fn debug_tab_toggles() {
        let mut app = app_on_diff_line();
        app.toggle_breakpoint_at_cursor();
        assert!(!app.debug_tab_is_breakpoints());
        app.toggle_debug_tab();
        assert!(app.debug_tab_is_breakpoints());
        app.toggle_debug_tab();
        assert!(!app.debug_tab_is_breakpoints());
    }

    #[test]
    fn exit_debug_keeps_breakpoints_drops_sessions() {
        let mut app = app_on_diff_line();
        app.toggle_breakpoint_at_cursor(); // a breakpoint exists
        let mut st = app.debug.take().unwrap();
        st.sessions.push(DebugSession::new(1, "worktree".into()));
        app.debug = Some(st);
        app.focus = Pane::Comments;
        app.right_tab = RightTab::Debug;

        app.exit_debug();
        // Sessions gone, breakpoints kept, debug overlay still present, the
        // right tab fell back to Comments and focus moved off the Debug tab.
        let d = app.debug.as_ref().unwrap();
        assert!(d.sessions.is_empty());
        assert!(!d.breakpoints.is_empty());
        assert_eq!(app.right_tab, RightTab::Comments);
        assert!(!app.is_debug_focused());
    }

    #[test]
    fn right_pane_joins_focus_cycle_when_active() {
        let mut app = sample();
        app.show_comments = false; // right pane hidden unless debugging
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Diff);
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Files); // no right pane in cycle yet

        // Activate debug → the right pane (Debug tab) joins the cycle.
        app.debug = Some(DebugState::default());
        app.right_tab = RightTab::Debug;
        app.focus = Pane::Diff;
        app.toggle_focus();
        assert_eq!(app.focus, Pane::Comments);
        assert!(app.is_debug_focused());
    }

    #[test]
    fn toggle_right_tab_only_to_debug_when_active() {
        let mut app = sample();
        assert_eq!(app.right_tab, RightTab::Comments);
        app.toggle_right_tab(); // no debug → stays on Comments
        assert_eq!(app.right_tab, RightTab::Comments);
        app.debug = Some(DebugState::default());
        app.toggle_right_tab();
        assert_eq!(app.right_tab, RightTab::Debug);
        app.toggle_right_tab();
        assert_eq!(app.right_tab, RightTab::Comments);
    }
}