1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
use anyhow::{Context, Result, anyhow};
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
/// Duration of a single hunk-to-hunk scroll animation. 150 ms lands in
/// the "noticeable but not slow" band and matches the research doc.
const SCROLL_ANIM_DURATION: Duration = Duration::from_millis(150);
/// Maximum number of per-file raw `git diff` snapshots retained in
/// [`App::diff_snapshots`]. The entry cost is dominated by each diff
/// string (commonly a few KB for a small edit, tens of KB for a large
/// one). 500 paths is a comfortable upper bound for agent sessions
/// that churn through many files, while capping peak memory at a few
/// MB. When the cap is hit the least-recently-touched entry is
/// evicted — the same discipline `prune_event_log` enforces for the
/// on-disk event log.
pub const DEFAULT_DIFF_SNAPSHOTS_CAP: usize = 500;
/// LRU-ish cap for per-file raw `git diff` text. Each hook event
/// touches a path (read its previous snapshot, write the new one); a
/// touch moves the path to the "most recently used" end so the next
/// eviction drops something the agent has stopped touching instead of
/// a hot file.
///
/// Intentionally a thin wrapper over [`HashMap`] + [`VecDeque`]: the
/// cardinality is bounded (<= `cap`) and the workload is "insert or
/// refresh one entry per event", so the O(n) `VecDeque::retain` on
/// re-insert is cheaper than pulling in `indexmap` or writing a
/// doubly-linked LRU for a few hundred entries.
#[derive(Debug, Clone)]
pub struct DiffSnapshots {
map: HashMap<PathBuf, String>,
order: VecDeque<PathBuf>,
cap: usize,
}
impl Default for DiffSnapshots {
fn default() -> Self {
Self::with_cap(DEFAULT_DIFF_SNAPSHOTS_CAP)
}
}
impl DiffSnapshots {
pub fn with_cap(cap: usize) -> Self {
Self {
map: HashMap::new(),
order: VecDeque::new(),
cap: cap.max(1),
}
}
pub fn get(&self, path: &Path) -> Option<&String> {
self.map.get(path)
}
pub fn insert(&mut self, path: PathBuf, diff: String) {
// Re-insert refreshes recency: pull the prior position out of
// `order` before appending to the back, otherwise `d` getting
// re-written would still look older than a `c` inserted once.
if self.map.contains_key(&path) {
self.order.retain(|p| p != &path);
}
self.order.push_back(path.clone());
self.map.insert(path, diff);
while self.map.len() > self.cap {
if let Some(evicted) = self.order.pop_front() {
self.map.remove(&evicted);
} else {
break;
}
}
}
pub fn clear(&mut self) {
self.map.clear();
self.order.clear();
}
#[cfg(test)]
pub fn contains_key(&self, path: &Path) -> bool {
self.map.contains_key(path)
}
#[cfg(test)]
pub fn len(&self) -> usize {
self.map.len()
}
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
#[cfg(test)]
pub fn keys(&self) -> impl Iterator<Item = &PathBuf> {
self.map.keys()
}
/// Replace all entries with the ones from `map`, preserving the
/// configured cap. Iteration order of [`HashMap`] is unspecified,
/// so new entries land in whatever order the incoming map yields
/// — acceptable here because the caller only needs "recent after
/// bootstrap", not a precise total order.
pub fn replace_from_map(&mut self, map: HashMap<PathBuf, String>) {
self.clear();
for (path, diff) in map {
self.insert(path, diff);
}
}
}
use crate::git::{self, DiffContent, FileDiff, FileStatus, LineKind};
use crate::hook::SanitizedEvent;
use crate::scar::ScarKind;
use crate::watcher::{self, WatchEvent, WatchSource};
/// Which TUI view is currently active.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ViewMode {
/// Main diff view — filesystem-based state view ("what does the repo look like now?").
#[default]
Diff,
/// Stream mode — event-log-based operation history ("what did the agent do?").
Stream,
}
/// One entry in the stream mode view. Combines the sanitized event
/// metadata (from `hook-log-event`) with optionally captured diff
/// snapshots for per-operation diff display.
#[derive(Debug, Clone)]
pub struct StreamEvent {
pub metadata: SanitizedEvent,
/// Per-file operation diffs captured by the TUI in real-time,
/// keyed by the same path entries as `metadata.file_paths`.
/// A `MultiEdit` or multi-file `Write` carries one entry per
/// touched path so the stream view can render per-path hunks
/// instead of collapsing everything onto the first path.
/// Empty for events that occurred before the TUI was started.
pub per_file_diffs: BTreeMap<PathBuf, String>,
}
/// Half-page scroll constant for `Ctrl-d` / `Ctrl-u`. M5+ may swap this for
/// the real viewport height once we plumb it through; until then a fixed
/// value keeps `handle_key` testable as a pure function.
const HALF_PAGE: usize = 12;
/// Canned scar body bound to the `a` key — "ask". The
/// `@kizu[ask]:` marker itself is added by
/// [`crate::scar::CommentSyntax::render_scar`],
/// so this constant holds *just the instruction text*. Plain English
/// imperatives travel across agents (Claude Code / Codex / Cursor /
/// Gemini) without translation layers — the scar is read by the
/// agent as part of the source file itself.
pub(crate) const SCAR_TEXT_ASK: &str = "explain this change";
/// Canned scar body bound to the `r` key — "reject".
pub(crate) const SCAR_TEXT_REJECT: &str = "revert this change";
/// Top-level application state. Single-threaded, mutated by the event loop
/// via `&mut self` (we run on tokio's `current_thread` flavor — see ADR-0003).
pub struct App {
pub root: PathBuf,
pub git_dir: PathBuf,
/// Shared "common" git dir — equal to `git_dir` for normal repos,
/// distinct for linked worktrees where `refs/heads/**` lives in the
/// main repo's `.git/`. The watcher needs both to catch commits
/// performed inside a linked worktree (ADR-0005 addendum).
pub common_git_dir: PathBuf,
/// Full ref name that HEAD pointed at when the session started
/// (e.g. `refs/heads/main`). `None` if HEAD was detached. Used
/// by the watcher to narrow the baseline-affecting path set —
/// unrelated ref activity (remotes, tags, sibling branches) no
/// longer raises false HEAD-dirty signals (ADR-0007).
pub current_branch_ref: Option<String>,
pub baseline_sha: String,
/// Files in the diff, sorted by `mtime` ascending. The newest file is the
/// last entry so the scroll view reads top-to-bottom chronologically.
pub files: Vec<FileDiff>,
/// Derived flat row plan for the scroll view. Rebuilt whenever `files`
/// changes via `build_layout`.
pub layout: ScrollLayout,
/// The cursor's row index inside `layout.rows`. The renderer derives
/// the actual viewport top from this + [`Self::cursor_placement`].
pub scroll: usize,
/// Intra-row visual offset of the cursor. **Always 0 in nowrap
/// mode.** In wrap mode this is how many visual lines into the
/// logical row at `scroll` the cursor has walked via Ctrl-d /
/// Ctrl-u / J / K. The cursor's visual y is
/// `VisualIndex::visual_y(scroll) + cursor_sub_row`; the
/// placement target and the render-time arrow both respect it,
/// so Ctrl-d inside a 200-char minified JSON edit is no longer a
/// no-op (ADR-0009 fix). Resets to 0 on any hunk jump
/// (`scroll_to`, `next_hunk`, `prev_hunk`, `g`, `G`, follow),
/// wrap toggle, or layout rebuild.
pub cursor_sub_row: usize,
/// Where the cursor sits visually inside the viewport. Toggled by `z`.
pub cursor_placement: CursorPlacement,
/// Path-tracked anchor: which `(path, hunk_old_start)` the user is
/// looking at. Lets `recompute_diff` slide `scroll` to the same hunk
/// even when the row count has shifted.
pub anchor: Option<HunkAnchor>,
/// Modal file picker. `Some` when the user has pressed `s`.
pub picker: Option<PickerState>,
/// Free-text scar input overlay. `Some` when the user has pressed
/// `c` on a scar-able row and is composing the comment body.
pub scar_comment: Option<ScarCommentState>,
/// Hunk-revert confirmation overlay. `Some` when the user has
/// pressed `x` on a hunk and is being asked `(y/N)`.
pub revert_confirm: Option<RevertConfirmState>,
/// Transient `/` query composer. `Some` while the user is
/// typing the search query; cleared on Enter (confirm) or Esc.
pub search_input: Option<SearchInputState>,
/// File-view zoom state. `Some` when the user has pressed
/// `Enter` on a hunk and is looking at the whole file.
pub file_view: Option<FileViewState>,
/// Confirmed search state (query + matches + current index).
/// Survives across normal-mode navigation so `n` / `N` can
/// jump between hits.
pub search: Option<SearchState>,
/// "Seen" marks for hunks the user has visually reviewed and
/// wants to hide from the attention surface. Keyed by
/// `(relative file path, hunk.old_start)` so the mark survives
/// a watcher-driven `compute_diff` as long as the hunk's
/// pre-image anchor doesn't move — same fingerprint used by
/// [`HunkAnchor`]. Space toggles; nothing is written to disk
/// (see plans/v0.2.md M4).
pub seen_hunks: BTreeSet<(PathBuf, usize)>,
pub follow_mode: bool,
/// Set when the most recent `compute_diff` failed. Cleared on success.
pub last_error: Option<String>,
/// Terminal input health. Tracked separately from `last_error`
/// so a successful `git diff` recompute cannot silently erase the
/// fact that keyboard input has failed.
pub input_health: Option<String>,
/// Set whenever HEAD/refs move; the user must press `R` to re-baseline.
pub head_dirty: bool,
pub should_quit: bool,
/// Last viewport height (in rows) the renderer used. Updated through
/// interior mutability so the next `J`/`K` press can size its scroll
/// chunk relative to the current screen — bigger window, bigger jumps.
/// Defaults to 24 before the first render.
pub last_body_height: Cell<usize>,
/// Last wrap body width the renderer used, or `None` when wrap
/// mode is disabled. Key handlers read this to drive visual-row
/// scroll math (see [`VisualIndex`]). Updated every frame in
/// tandem with `last_body_height`.
pub last_body_width: Cell<Option<usize>>,
/// The row position the renderer actually drew the viewport at on
/// the last frame. Matches the logical [`Self::viewport_top`] when
/// idle; lags behind during a [`ScrollAnim`]. Used as the `from`
/// value when a new animation kicks off (so key mashes don't
/// snap — the next tween picks up from wherever the current one
/// happened to be).
pub visual_top: Cell<f32>,
/// Active viewport-top tween. `None` when the renderer should
/// draw at the logical target.
pub anim: Option<ScrollAnim>,
/// Line-wrap mode. When `true`, long diff lines wrap to the
/// viewport width (preserving the `+`/`-`/` ` prefix on every
/// continuation row) and a `¶` marker is drawn at the end of
/// each logical line so real newlines can be distinguished from
/// wrap boundaries. Toggled by the `w` key.
pub wrap_lines: bool,
/// Watcher backend health, tracked **separately** from
/// `last_error` so that a successful one-off `git diff` recompute
/// does not silently clear a live filesystem-watcher failure
/// (ADR-0008). `Failed` persists until a subsequent non-Error
/// watcher event confirms recovery, or the watcher is restarted.
pub watcher_health: WatcherHealth,
/// Lazy-initialized syntax highlighter. Loaded on first render
/// to avoid paying syntect's SyntaxSet load cost at startup.
pub highlighter: std::cell::OnceCell<crate::highlight::Highlighter>,
/// User configuration loaded from `~/.config/kizu/config.toml`.
/// Controls keybindings, colors, debounce timing, editor command,
/// and terminal auto-split preferences.
pub config: crate::config::KizuConfig,
/// Active view mode: Diff (default) or Stream.
pub view_mode: ViewMode,
/// Saved scroll position for the diff view, restored when Tab
/// switches back from stream mode.
pub saved_diff_scroll: usize,
/// Saved scroll position for the stream view, restored when Tab
/// switches back from diff mode.
pub saved_stream_scroll: usize,
/// Stream mode events, ordered by timestamp ascending.
pub stream_events: Vec<StreamEvent>,
/// Event-log file paths that have already been ingested by
/// [`Self::handle_event_log`]. Prevents double-processing when
/// `replay_events_dir` scans startup-gap files and the watcher
/// later re-delivers the same path (some notify backends fire
/// pre-existing files on arm). Keyed on absolute event-file
/// path, which is stable because `hook::write_event` uses a
/// uniqueness suffix.
pub processed_event_paths: std::collections::HashSet<PathBuf>,
/// Unix epoch millisecond at which this kizu TUI session started.
/// `handle_event_log` rejects events whose `timestamp_ms` is
/// earlier than this value so stream mode never ingests:
/// (a) leftover events from a previous kizu session on the
/// same project (replacing the destructive bulk-delete of
/// `clean_stale_events`), or
/// (b) any other concurrent session's historical events that
/// existed before this session was bootstrapped.
pub session_start_ms: u64,
/// Agent `session_id` this TUI is bound to. Populated on the
/// first `handle_event_log` ingest that carries a session_id;
/// later events with a different session_id are dropped so two
/// concurrent agents writing to the same repo cannot cross-
/// pollute `diff_snapshots` or the stream history. `None`
/// before the first bound ingest; stays bound for the rest of
/// the session.
pub bound_session_id: Option<String>,
/// Per-file diff snapshots used to compute per-operation diffs.
/// Maps file path → most recent cumulative diff output. Capped
/// via [`DiffSnapshots`] so long sessions that touch many files
/// don't accumulate unbounded state.
pub diff_snapshots: DiffSnapshots,
/// Session-scoped undo stack for scar insertions. Each successful
/// [`crate::scar::insert_scar`] pushes an entry; the `u` key pops
/// the top and calls [`crate::scar::remove_scar`], reversing only
/// that one write. Receipts capture the post-insert line number and
/// rendered line so undo refuses to delete content the user edited
/// in the meantime (scar.rs `ScarRemove::Mismatch`).
pub scar_undo_stack: Vec<ScarUndoEntry>,
/// Sticky cursor target set when a scar is inserted or undone.
/// Persists across watcher-driven `recompute_diff` calls so the
/// asynchronous filesystem notification can't snap the cursor
/// back to the hunk header. Cleared as soon as the user presses
/// any navigation key.
pub scar_focus: Option<(PathBuf, usize)>,
/// Viewport pin: when `Some(y)`, the renderer forces the viewport
/// top so the cursor lands at visual row `y` on screen, overriding
/// the placement-derived default. Set by `apply_computed_files`
/// when a watcher-driven recompute relocates the anchored hunk
/// (e.g. the anchored file floats to the end of the mtime-sorted
/// list after being edited) — the pin keeps the user's focused
/// hunk at the same screen row instead of sliding with the
/// layout. Cleared on any user-initiated cursor move (`scroll_to`,
/// `scroll_by`, `follow_restore`, `open_file_view`, ...).
pub pinned_cursor_y: Option<usize>,
}
/// One entry on the scar undo stack: the path that was edited, plus
/// the receipt returned by `insert_scar`. The pair `(line, rendered)`
/// is what `remove_scar` uses to verify the line still matches before
/// deleting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScarUndoEntry {
pub path: PathBuf,
pub line_1indexed: usize,
pub rendered: String,
}
/// Tracks whether the underlying notify debouncers are still pushing
/// events into the channel. Decoupled from `App.last_error`: a failing
/// `compute_diff` must not pretend the watcher has recovered, and a
/// successful recompute must not pretend a dropped FSEvents queue has
/// repaired itself. See ADR-0008.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WatcherHealth {
/// Source-scoped watcher failures. Multiple debouncers back the
/// watcher layer (worktree + several git-state roots), so one live
/// event must not erase the failure of a different source.
failures: BTreeMap<WatchSource, String>,
}
impl WatcherHealth {
pub fn record_failure(&mut self, source: WatchSource, message: String) {
self.failures.insert(source, message);
}
pub fn clear_source(&mut self, source: WatchSource) {
self.failures.remove(&source);
}
#[cfg(test)]
pub fn is_healthy(&self) -> bool {
self.failures.is_empty()
}
pub fn summary(&self) -> Option<String> {
if self.failures.is_empty() {
return None;
}
let mut parts = self.failures.values().cloned().collect::<Vec<_>>();
parts.sort();
Some(parts.join("; "))
}
#[cfg(test)]
fn has_failure(&self, source: WatchSource, needle: &str) -> bool {
self.failures
.get(&source)
.is_some_and(|msg| msg.contains(needle))
}
}
/// Follow-up work the event loop must perform after dispatching a
/// key. Keeps `App::handle_key` a pure state mutator while still
/// letting specific keys request out-of-band side effects such as
/// watcher reconfiguration (ADR-0008). New variants should be added
/// here rather than threading side-effect channels through every
/// handler method.
///
/// Not `#[must_use]`: the event loop is the one caller that
/// genuinely needs to act on the effect, and tagging the enum
/// would force every existing `handle_key` test to wrap results in
/// `let _ = …` for zero actual benefit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyEffect {
/// No extra work. Most key handlers return this.
None,
/// The symbolic HEAD ref has changed — the event loop must
/// hot-swap the watcher's `BaselineMatcherInner` so subsequent
/// branch-ref writes raise `WatchEvent::GitHead`. Without this
/// the watcher would stay pinned to the session's startup
/// branch after `R`.
ReconfigureWatcher,
/// The user pressed `e` on a scar-able row — the event loop
/// must suspend the ratatui terminal, spawn the resolved
/// editor, wait for it, and then re-enter the alternate screen.
/// The `EditorInvocation` carries a fully-resolved
/// `(program, args)` pair so the event loop does not need to
/// re-read `$EDITOR`.
OpenEditor(EditorInvocation),
}
/// Fully-resolved external-editor invocation. Produced inside
/// [`App::open_in_editor`] via [`build_editor_invocation`] so the
/// event loop can spawn the editor with no further parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditorInvocation {
pub program: String,
pub args: Vec<String>,
}
/// Build an [`EditorInvocation`] from the user's `$EDITOR` value.
///
/// `$EDITOR` is split on whitespace (no shell quoting — matching
/// `git`'s `GIT_EDITOR` conventions for MVP). The first token is
/// the program; any remaining tokens are kept as leading args.
///
/// Line-number format depends on the editor:
/// - vim/nvim/vi/nano/emacs/kak use `+<line> <file>`
/// - zed/code/subl/hx/cursor and others use `<file>:<line>`
///
/// Returns `None` when `editor_env` is `None` or empty / all
/// whitespace, so callers get a single consistent "no editor
/// configured → no-op" path.
pub fn build_editor_invocation(
editor_env: Option<&str>,
line: usize,
file: &Path,
) -> Option<EditorInvocation> {
let env = editor_env?.trim();
if env.is_empty() {
return None;
}
let mut parts = env.split_whitespace().map(String::from);
let program = parts.next()?;
let mut args: Vec<String> = parts.collect();
let basename = Path::new(&program)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
if uses_plus_line_format(basename) {
args.push(format!("+{line}"));
args.push(file.display().to_string());
} else {
args.push(format!("{}:{line}", file.display()));
}
Some(EditorInvocation { program, args })
}
/// Editors that accept `+<line> <file>` for line-jump. All others
/// default to the `<file>:<line>` convention (VS Code, Zed,
/// Sublime, Helix, Cursor, etc.).
fn uses_plus_line_format(basename: &str) -> bool {
matches!(
basename,
"vim" | "nvim" | "vi" | "nano" | "emacs" | "emacsclient" | "kak" | "mg" | "nvi"
)
}
/// Linear membership probe for [`App::seen_hunks`] that takes the
/// path by reference, so the renderer can check every visible hunk
/// header without allocating a `PathBuf` per frame. The set size is
/// bounded by user toggles (typically tens of entries), so the scan
/// is cheaper than the clone it replaces.
pub fn is_hunk_seen(seen: &BTreeSet<(PathBuf, usize)>, path: &Path, old_start: usize) -> bool {
seen.iter()
.any(|(p, o)| *o == old_start && p.as_path() == path)
}
/// Insert a single character at `cursor_pos` (char index) and advance
/// the cursor. Works correctly with multi-byte characters.
fn edit_insert_char(text: &mut String, cursor_pos: &mut usize, c: char) {
let byte_idx = text
.char_indices()
.nth(*cursor_pos)
.map(|(i, _)| i)
.unwrap_or(text.len());
text.insert(byte_idx, c);
*cursor_pos += 1;
}
/// Insert a string at `cursor_pos` (char index) and advance the
/// cursor by the number of inserted characters.
fn edit_insert_str(text: &mut String, cursor_pos: &mut usize, s: &str) {
let byte_idx = text
.char_indices()
.nth(*cursor_pos)
.map(|(i, _)| i)
.unwrap_or(text.len());
text.insert_str(byte_idx, s);
*cursor_pos += s.chars().count();
}
/// Delete the character before `cursor_pos` and move the cursor back.
fn edit_backspace(text: &mut String, cursor_pos: &mut usize) {
if *cursor_pos == 0 {
return;
}
let remove_idx = *cursor_pos - 1;
let byte_range = text
.char_indices()
.nth(remove_idx)
.map(|(i, c)| i..i + c.len_utf8());
if let Some(range) = byte_range {
text.drain(range);
*cursor_pos -= 1;
}
}
/// Two ways the renderer can park the cursor inside the viewport.
/// Defaults to [`CursorPlacement::Centered`]; `z` toggles to
/// [`CursorPlacement::Top`] (the cursor sits at the viewport ceiling
/// and the selected hunk body reads downward from there — the
/// natural direction for diff reading).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CursorPlacement {
Centered,
Top,
}
impl CursorPlacement {
/// Compute the viewport's top-row index given the cursor's logical
/// row, the total layout size, and the viewport height. The result
/// is clamped to `[0, total - height]` so we never reveal phantom
/// rows past either end of the layout.
pub fn viewport_top(self, cursor: usize, total: usize, height: usize) -> usize {
if total <= height {
return 0;
}
let max_top = total - height;
let raw = match self {
CursorPlacement::Centered => cursor.saturating_sub(height / 2),
// Cursor at viewport row 0. The selected hunk flows
// downward from there into the body.
CursorPlacement::Top => cursor,
};
raw.min(max_top)
}
/// Short human label used in the footer indicator.
pub fn label(self) -> &'static str {
match self {
CursorPlacement::Centered => "center",
CursorPlacement::Top => "top",
}
}
}
/// Pre-computed layout for the scroll view. Built once per `recompute_diff`,
/// then sliced into a viewport at render time.
#[derive(Debug, Default, Clone)]
pub struct ScrollLayout {
/// Every visible row in order.
pub rows: Vec<RowKind>,
/// `rows` indices that point at a `HunkHeader` — used by `j/k` to jump
/// hunk-by-hunk regardless of how many context lines sit in between.
pub hunk_starts: Vec<usize>,
/// For each file in `App.files`, the row index of its first hunk header
/// (or the file header for binaries / empty hunks). `None` only when the
/// layout build couldn't produce any anchorable row for that file.
pub file_first_hunk: Vec<Option<usize>>,
/// `file_of_row[i]` is the index into `App.files` for whichever file row
/// `i` belongs to. The footer reads this to display the current file.
pub file_of_row: Vec<usize>,
/// `(start, end_exclusive)` row spans of every contiguous `+`/`-` block
/// across the entire layout. `J` / `K` walk these spans in *both*
/// directions: short runs collapse to a one-press jump, long runs are
/// walked in [`App::chunk_size`]-sized scroll chunks (= viewport
/// height / 3), and once the cursor passes the end of a run the next
/// press flows into the next run even when that run lives in a
/// different file.
pub change_runs: Vec<(usize, usize)>,
}
/// Default body height assumed before the first render has had a chance
/// to update [`App::last_body_height`]. 24 is the classic VT100 height.
const DEFAULT_BODY_HEIGHT: usize = 24;
/// Threshold for treating a change run as "long" in adaptive motion.
/// Long runs get walked chunk-by-chunk so their body isn't teleported
/// past; short runs are atomic landings (one press per run). A run is
/// long when its visual height exceeds this fraction of the viewport —
/// so a run filling 80% of the screen or more is considered long.
const LONG_RUN_RATIO: f32 = 0.8;
fn is_long_run(run_visual: usize, viewport: usize) -> bool {
run_visual as f32 > viewport as f32 * LONG_RUN_RATIO
}
/// Per-render map from logical row index → visual y offset, computed
/// against the current wrap body width. Every frame the renderer
/// rebuilds a fresh index (cheap: O(rows) with the 2000-row cap from
/// `SCROLL_ROW_LIMIT`) so scroll math can talk about visual y instead
/// of logical rows.
///
/// The key invariant: `prefix[i]` is the visual y-offset where logical
/// row `i` begins, and `prefix[i+1] - prefix[i]` is the visual height
/// of row `i`. In **nowrap** mode every row is exactly 1 visual row
/// tall, so `prefix` is `[0, 1, 2, …, n]` and `visual_y(row)` is the
/// identity — all existing logical-row tests stay numerically correct.
/// In **wrap** mode, diff lines whose content exceeds `body_width`
/// contribute multiple visual rows and the prefix becomes non-trivial.
///
/// Animation (`ScrollAnim`) and viewport placement operate over this
/// coordinate space, not logical rows. That's the crux of the wrap-mode
/// fix — logical-row scrolling against wrap rendering was pushing the
/// cursor off-screen because a few wrapped rows ahead of the cursor
/// could silently consume the entire viewport before the cursor's
/// logical row was ever emitted.
#[derive(Debug, Clone)]
pub struct VisualIndex {
/// Cumulative visual y-offsets, length `rows.len() + 1`.
/// `prefix[rows.len()]` is the total visual height of the layout.
prefix: Vec<usize>,
/// Wrap body width this index was built against. `None` means
/// nowrap, in which case `prefix` is the identity mapping — kept
/// on the value so downstream code (and tests) can tell at a
/// glance whether visual and logical coordinates coincide.
#[allow(dead_code)]
pub body_width: Option<usize>,
}
impl VisualIndex {
/// Build a fresh prefix sum against the current layout and the
/// supplied wrap body width. Pass `None` for nowrap mode; the
/// resulting index acts as the identity and keeps the legacy
/// logical-row scroll model intact.
pub fn build(layout: &ScrollLayout, files: &[FileDiff], body_width: Option<usize>) -> Self {
let n = layout.rows.len();
let mut prefix = Vec::with_capacity(n + 1);
prefix.push(0);
let mut acc = 0usize;
for row in &layout.rows {
let h = Self::row_visual_height(row, files, body_width);
acc += h;
prefix.push(acc);
}
Self { prefix, body_width }
}
/// Visual y offset where logical row `row_idx` begins.
pub fn visual_y(&self, row_idx: usize) -> usize {
self.prefix.get(row_idx).copied().unwrap_or(0)
}
/// Visual-row height of logical row `row_idx`. Falls back to 1
/// for out-of-range indices so callers don't need to bounds-check.
pub fn visual_height(&self, row_idx: usize) -> usize {
match (self.prefix.get(row_idx), self.prefix.get(row_idx + 1)) {
(Some(&a), Some(&b)) => b - a,
_ => 1,
}
}
/// Total visual height of the layout.
pub fn total_visual(&self) -> usize {
self.prefix.last().copied().unwrap_or(0)
}
/// Given a visual y offset, return `(logical_row, skip_within_row)`
/// where `logical_row` is the logical row that contains y and
/// `skip_within_row` is how many visual lines of that row sit at
/// or above y. Used by the renderer to begin drawing mid-row
/// when wrap pushes the viewport's top into the middle of a
/// wrapped diff line.
pub fn logical_at(&self, y: usize) -> (usize, usize) {
if self.prefix.len() < 2 {
return (0, 0);
}
// Clamp past-the-end to the last row's final visual line.
let total = self.total_visual();
if y >= total {
let last = self.prefix.len() - 2;
return (last, self.visual_height(last).saturating_sub(1));
}
// Binary search: smallest `i` such that prefix[i+1] > y.
let mut lo = 0usize;
let mut hi = self.prefix.len() - 1;
while lo < hi {
let mid = lo + (hi - lo) / 2;
if self.prefix[mid + 1] > y {
hi = mid;
} else {
lo = mid + 1;
}
}
let within = y - self.prefix[lo];
(lo, within)
}
fn row_visual_height(row: &RowKind, files: &[FileDiff], body_width: Option<usize>) -> usize {
let Some(width) = body_width else {
return 1;
};
let RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} = row
else {
return 1;
};
let Some(file) = files.get(*file_idx) else {
return 1;
};
let DiffContent::Text(hunks) = &file.content else {
return 1;
};
let Some(hunk) = hunks.get(*hunk_idx) else {
return 1;
};
let Some(line) = hunk.lines.get(*line_idx) else {
return 1;
};
// Visual row count = ceil(display-width(content) / body_width).
// CJK / emoji consume 2 cells each, so counting chars would
// under-estimate the height and ratatui's scroll math would
// push the cursor off-screen in wrap mode.
let cells = unicode_width::UnicodeWidthStr::width(line.content.as_str());
if cells == 0 {
1
} else {
cells.div_ceil(width.max(1))
}
}
}
/// One displayable row in the scroll view. The renderer turns each variant
/// into a styled `Line`; the App layer cares about `(file_idx, hunk_idx)`
/// for navigation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RowKind {
/// `path ── status ── +A/-D ── mtime`
FileHeader { file_idx: usize },
/// `@@ -... +... @@`
HunkHeader { file_idx: usize, hunk_idx: usize },
/// One ` `/`+`/`-` line within a hunk.
DiffLine {
file_idx: usize,
hunk_idx: usize,
line_idx: usize,
},
/// `[binary file - diff suppressed]`
BinaryNotice { file_idx: usize },
/// Visual breathing room between files.
Spacer,
}
/// Identifies "the hunk the user is looking at" across `recompute_diff`.
/// `hunk_old_start` is enough of a fingerprint to find the same hunk even
/// when neighbouring hunks shift around.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HunkAnchor {
pub path: PathBuf,
pub hunk_old_start: usize,
}
/// Modal file picker state. `cursor` indexes into `picker_results()`, not
/// into `App.files` directly.
#[derive(Debug, Clone, Default)]
pub struct PickerState {
pub query: String,
pub cursor: usize,
}
/// Free-text scar input overlay. The `c` key enters this mode when the
/// cursor is on a scar-able row; `Enter` commits the accumulated
/// [`Self::body`] as a `@kizu[free]:` scar above the target line and
/// `Esc` cancels without touching the file. The target is captured at
/// entry time (not re-read on commit) so that a watcher-driven diff
/// recompute during typing cannot silently retarget the write.
#[derive(Debug, Clone)]
pub struct ScarCommentState {
pub target_path: PathBuf,
pub target_line: usize,
pub body: String,
/// Cursor position as a **char index** (not byte offset).
/// 0 = before the first character, `body.chars().count()` = end.
pub cursor_pos: usize,
}
/// One hit inside the scroll layout. `row` is the logical layout
/// row index (suitable for `scroll_to`); `byte_start` / `byte_end`
/// delimit the match inside the row's diff-line content for inline
/// highlighting in a later M4b slice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatchLocation {
pub row: usize,
pub byte_start: usize,
pub byte_end: usize,
}
/// Active search query + the row hits it produced, plus a cursor
/// into that hit list that `n` / `N` advance. Created by confirming
/// the [`SearchInputState`] composer; lives until the next `/` or
/// until a recompute invalidates the row indices.
#[derive(Debug, Clone)]
pub struct SearchState {
// Reserved for M4b UI slice (footer echo + recompute
// rehydration). Dead_code for now so clippy-as-error builds
// don't fail between slices.
#[allow(dead_code)]
pub query: String,
pub matches: Vec<MatchLocation>,
pub current: usize,
}
/// Transient query-composing overlay. `/` opens it, typing appends
/// to `query`, Backspace deletes, Enter confirms into a
/// [`SearchState`], Esc cancels without touching the confirmed state.
#[derive(Debug, Clone, Default)]
pub struct SearchInputState {
pub query: String,
/// Cursor position as a char index within `query`.
pub cursor_pos: usize,
}
/// Find every occurrence of `query` across the **DiffLine** rows of
/// `layout`, in row order. Empty queries return an empty vector so
/// callers can treat "no matches" and "no query" identically.
///
/// Case handling is **smart case** (vim-style): a query with no
/// uppercase characters matches case-insensitively, anything with
/// at least one uppercase character matches case-sensitively.
/// `byte_end` is guaranteed to be a UTF-8 char boundary because
/// `str::find` always returns a char-boundary-aligned index.
pub fn find_matches(layout: &ScrollLayout, files: &[FileDiff], query: &str) -> Vec<MatchLocation> {
if query.is_empty() {
return Vec::new();
}
let case_sensitive = query.chars().any(|c| c.is_uppercase());
let needle: String = if case_sensitive {
query.to_string()
} else {
query.to_lowercase()
};
let mut out = Vec::new();
for (row_idx, row) in layout.rows.iter().enumerate() {
let RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} = row
else {
continue;
};
let Some(file) = files.get(*file_idx) else {
continue;
};
let DiffContent::Text(hunks) = &file.content else {
continue;
};
let Some(hunk) = hunks.get(*hunk_idx) else {
continue;
};
let Some(line) = hunk.lines.get(*line_idx) else {
continue;
};
// For smart-case insensitive matching we lowercase the
// haystack too. `str::to_lowercase` can change byte length
// under Unicode (e.g. `İ` → `i̇`), so we fall back to
// ASCII-only needles for the insensitive path to keep
// byte offsets meaningful. Non-ASCII lowercase queries
// degrade to case-sensitive matching, which is a clean
// failure mode.
let ascii_only = needle.is_ascii() && line.content.is_ascii();
let (haystack, search_needle): (String, String) = if case_sensitive || !ascii_only {
(line.content.clone(), needle.clone())
} else {
(line.content.to_ascii_lowercase(), needle.clone())
};
let mut start = 0;
while let Some(idx) = haystack[start..].find(&search_needle) {
let byte_start = start + idx;
let byte_end = byte_start + search_needle.len();
out.push(MatchLocation {
row: row_idx,
byte_start,
byte_end,
});
if byte_end == start {
// Defensive: empty needles already bail at the
// top, but if a future code path sends an empty
// after normalization we must not spin forever.
break;
}
start = byte_end;
}
}
out
}
/// Full-file zoom view entered via `Enter` on a hunk. The user
/// sees the entire worktree file with diff-touched lines
/// highlighted in `BG_ADDED` / `BG_DELETED`. `Esc` or `Enter`
/// returns to the normal scroll view at the cursor position
/// captured at entry time.
///
/// Navigation uses the same keys as normal mode (`j`/`k`/`J`/`K`/
/// `g`/`G`/`Ctrl-d`/`Ctrl-u`) but addresses 1-indexed file lines
/// instead of layout rows. Scar keys are deferred to a later
/// slice.
#[derive(Debug, Clone)]
pub struct FileViewState {
pub path: PathBuf,
pub return_scroll: usize,
pub lines: Vec<String>,
pub line_bg: std::collections::HashMap<usize, ratatui::style::Color>,
pub cursor: usize,
pub scroll_top: usize,
/// Easing tween for the file view's scroll_top, matching the
/// main diff view's 150ms ease-out cubic animation.
pub anim: Option<ScrollAnim>,
/// Last rendered scroll position (in row units). Used as the
/// tween's start point when a new animation begins.
pub visual_top: f32,
}
/// Confirmation overlay for hunk revert (`x` key). Holds the
/// `(file_idx, hunk_idx)` captured the moment the user pressed `x`
/// so a watcher-driven recompute while the dialog is open cannot
/// re-target the operation. `y`/`Y`/`Enter` confirms and runs
/// `git apply --reverse`; any other key closes the overlay without
/// touching the worktree. See plans/v0.2.md M4 Decision Log.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RevertConfirmState {
pub file_idx: usize,
pub hunk_idx: usize,
pub file_path: PathBuf,
/// Stable hunk identity: `old_start` captured when the dialog was
/// opened. Used in `confirm_revert` to re-resolve the hunk by
/// identity (path + old_start) instead of trusting the stale
/// index pair, which can drift after a watcher-driven refresh.
pub hunk_old_start: usize,
}
/// Single-shot easing state for the viewport's top-row tween.
///
/// The tween sources its start point from `from` (captured at the moment
/// the animation began, in row-units) and its endpoint from the *current*
/// logical [`App::viewport_top`] — recomputed every frame so `git diff`
/// fires that shuffle the layout mid-animation still land on the right
/// row. Easing is ease-out cubic: fast at the start, settling softly.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScrollAnim {
pub from: f32,
pub start: Instant,
pub dur: Duration,
}
impl ScrollAnim {
/// Sample the tween at `now` against a (possibly moving) `target`.
/// Returns `(visual, done)` where `visual` is the row position the
/// renderer should use and `done` flips to `true` once the animation
/// has finished (`now >= start + dur`).
pub fn sample(&self, target: f32, now: Instant) -> (f32, bool) {
let elapsed = now.saturating_duration_since(self.start).as_secs_f32();
let dur_secs = self.dur.as_secs_f32().max(1e-6);
let t = (elapsed / dur_secs).clamp(0.0, 1.0);
// ease-out cubic: 1 - (1 - t)^3
let inv = 1.0 - t;
let e = 1.0 - inv * inv * inv;
let v = self.from + (target - self.from) * e;
(v, t >= 1.0)
}
}
impl App {
/// Construct an `App` for `root`. Resolves git layout, loads the initial
/// diff, and parks the scroll cursor on the most-recently-modified hunk.
///
/// **Fail-fast:** if the very first `git diff` errors out, bootstrap
/// propagates the error instead of entering the event loop with an
/// empty `files` snapshot. The watcher-driven path (see
/// [`Self::recompute_diff`]) still swallows errors into `last_error`
/// so that later transient failures preserve the last good snapshot,
/// but an initial-load failure must never render as a silent "clean"
/// view — the user would not be able to tell whether the worktree is
/// actually empty or the tool is broken.
pub fn bootstrap(root: PathBuf) -> Result<Self> {
let root = git::find_root(&root).context("resolving worktree root")?;
let git_dir = git::git_dir(&root).context("resolving git directory")?;
let common_git_dir =
git::git_common_dir(&root).context("resolving common git directory")?;
let current_branch_ref =
git::current_branch_ref(&root).context("resolving current branch ref")?;
let baseline_sha = git::head_sha(&root).context("capturing baseline HEAD")?;
// One `git diff --no-renames <baseline>` gives us both the
// parsed FileDiff list **and** the per-file raw text. Routing
// the raw text straight into `diff_snapshots` collapses the
// old "compute_diff + N × diff_single_file" startup pattern
// into a single subprocess.
let (diff, snapshots) = match git::compute_diff_with_snapshots(&root, &baseline_sha) {
Ok((files, snaps)) => (Ok(files), snaps),
Err(e) => (Err(e), std::collections::HashMap::new()),
};
let mut app = Self::bootstrap_with_diff(
root,
git_dir,
common_git_dir,
current_branch_ref,
baseline_sha,
diff,
)?;
app.diff_snapshots.replace_from_map(snapshots);
Ok(app)
}
/// Inner bootstrap: takes already-resolved git layout plus the
/// **result** of the initial `compute_diff`. Propagates the diff
/// error with context when it is `Err`, otherwise constructs the
/// `App` and applies the computed files. Factored out so tests can
/// drive both branches deterministically without spinning up a
/// real repository.
pub(crate) fn bootstrap_with_diff(
root: PathBuf,
git_dir: PathBuf,
common_git_dir: PathBuf,
current_branch_ref: Option<String>,
baseline_sha: String,
diff: Result<Vec<FileDiff>>,
) -> Result<Self> {
let initial =
diff.with_context(|| format!("initial git diff against baseline {baseline_sha}"))?;
let config = crate::config::load_config();
let mut app = Self {
root,
git_dir,
common_git_dir,
current_branch_ref,
baseline_sha,
files: Vec::new(),
layout: ScrollLayout::default(),
scroll: 0,
cursor_sub_row: 0,
cursor_placement: CursorPlacement::Centered,
anchor: None,
picker: None,
scar_comment: None,
revert_confirm: None,
file_view: None,
search_input: None,
search: None,
seen_hunks: BTreeSet::new(),
follow_mode: true,
last_error: None,
input_health: None,
head_dirty: false,
should_quit: false,
last_body_height: Cell::new(DEFAULT_BODY_HEIGHT),
last_body_width: Cell::new(None),
visual_top: Cell::new(0.0),
anim: None,
wrap_lines: false,
watcher_health: WatcherHealth::default(),
highlighter: std::cell::OnceCell::new(),
config,
view_mode: ViewMode::default(),
saved_diff_scroll: 0,
saved_stream_scroll: 0,
stream_events: Vec::new(),
processed_event_paths: std::collections::HashSet::new(),
session_start_ms: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0),
bound_session_id: None,
diff_snapshots: DiffSnapshots::default(),
scar_undo_stack: Vec::new(),
scar_focus: None,
pinned_cursor_y: None,
};
// If the agent handing off to kizu published its session id
// via the `KIZU_SESSION_ID` environment variable, pre-bind
// the TUI to it. That shuts the first-writer-wins window
// where a foreign concurrent agent could capture the
// binding before our own agent's first event landed,
// silently hiding every edit we were supposed to review.
if let Ok(sid) = std::env::var("KIZU_SESSION_ID") {
let trimmed = sid.trim();
if !trimmed.is_empty() {
app.bound_session_id = Some(trimmed.to_string());
}
}
app.apply_computed_files(initial);
Ok(app)
}
/// Half-page-ish chunk size used by `J`/`K` when scrolling within a
/// long change run. Scales with the actual viewport so a 12-row pane
/// gets 4-row chunks and a 36-row pane gets 12-row chunks. Always at
/// least 1 so the cursor still moves on tiny terminals.
pub fn chunk_size(&self) -> usize {
(self.last_body_height.get() / 3).max(1)
}
/// Toggle the cursor placement between centered and bottom-pinned.
/// `z` calls this — same vibe as `vim`'s `zz` (centre on cursor).
pub fn toggle_cursor_placement(&mut self) {
self.cursor_placement = match self.cursor_placement {
CursorPlacement::Centered => CursorPlacement::Top,
CursorPlacement::Top => CursorPlacement::Centered,
};
}
/// Toggle line-wrap mode. `w` calls this. When on, the renderer
/// wraps long diff lines at the viewport width and decorates every
/// logical line end with a `¶` marker.
///
/// Also kills any in-flight scroll animation: under wrap the
/// viewport's top position is tracked in visual-row space
/// ([`VisualIndex`]), while under nowrap it's logical rows. The
/// two scales diverge as soon as a single diff line wraps to more
/// than one visual row, so tweening between them would produce a
/// disorienting jump. Clearing `anim` makes the next frame snap
/// to the correct target instead.
pub fn toggle_wrap_lines(&mut self) {
self.wrap_lines = !self.wrap_lines;
self.anim = None;
// `cursor_sub_row` is only meaningful under wrap mode; when
// we flip the flag, drop any intra-row offset so the cursor
// lands cleanly on the row's first visual line under the
// new coordinate system.
self.cursor_sub_row = 0;
}
/// Toggle between Diff and Stream view modes. Rebuilds `files`
/// and `layout` from the appropriate data source so the existing
/// scroll/render infrastructure handles both modes identically.
pub fn toggle_view_mode(&mut self) {
match self.view_mode {
ViewMode::Diff => {
// Save diff scroll, restore stream scroll.
self.saved_diff_scroll = self.scroll;
self.view_mode = ViewMode::Stream;
let stream_files = build_stream_files(&self.stream_events);
self.apply_computed_files(stream_files);
let max = self.last_row_index();
self.scroll_to(self.saved_stream_scroll.min(max));
}
ViewMode::Stream => {
// Save stream scroll, restore diff scroll.
self.saved_stream_scroll = self.scroll;
self.view_mode = ViewMode::Diff;
self.recompute_diff();
let max = self.last_row_index();
self.scroll_to(self.saved_diff_scroll.min(max));
}
}
}
/// Canonicalize an agent-supplied path and project it onto the
/// repo-relative form used by `git::compute_diff` outputs. Returns
/// `None` when the path does not resolve inside `self.root`.
///
/// `self.root` is canonicalized by `git::find_root`
/// (`git rev-parse --show-toplevel`), so on macOS it lives on the
/// `/private/...` side of the `/tmp` → `/private/tmp` symlink.
/// Agent-provided file paths often follow the symlinked side
/// instead; `canonicalize` resolves both to the same absolute
/// path so downstream keys (`diff_snapshots`, `per_file_diffs`,
/// `StreamEvent.metadata.file_paths`) stay stable regardless of
/// symlink spelling.
///
/// Falls back to the raw path when the file no longer exists
/// (deleted between the hook write and this handler); in that
/// case we still try to strip `self.root` so a fresh path that
/// already starts with the canonical root becomes repo-relative.
fn normalize_event_path(&self, p: &Path) -> Option<PathBuf> {
let canon = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
if let Ok(rel) = canon.strip_prefix(&self.root) {
return Some(rel.to_path_buf());
}
if let Ok(rel) = p.strip_prefix(&self.root) {
return Some(rel.to_path_buf());
}
// Already repo-relative? Accept only when every component is
// forward-only (no `..` traversal) AND the resolved absolute
// form still lives inside `self.root`. Checking parent
// components is required because
// `root.join("../outside.rs").starts_with(root)` is true
// lexically — the filesystem escape happens only at resolve
// time. This is the security boundary for stream mode's
// repo filter.
if p.is_relative()
&& p.components()
.all(|c| !matches!(c, std::path::Component::ParentDir))
&& self.root.join(p).starts_with(&self.root)
{
return Some(p.to_path_buf());
}
None
}
/// Handle a new event-log file notification. Reads the event file,
/// captures the per-operation diff snapshot, and appends to
/// `stream_events`. Failures are silently ignored (non-critical).
///
/// Idempotent per-path: if this exact event file was already
/// ingested (e.g. replayed at startup and then re-delivered by
/// the watcher), the call is a no-op. The path key is stable
/// because `hook::write_event` embeds a uniqueness suffix.
pub fn handle_event_log(&mut self, path: PathBuf) {
if !self.processed_event_paths.insert(path.clone()) {
return;
}
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => return,
};
let mut event: SanitizedEvent = match serde_json::from_str(&content) {
Ok(e) => e,
Err(_) => return,
};
// Session isolation — layer 1: drop events that predate this
// session's start. The previous implementation used
// `clean_stale_events` to bulk-delete the shared per-project
// events directory, which destroyed a concurrently-running
// kizu session's live history. Filtering on `timestamp_ms`
// keeps our stream clean of leftover noise without touching
// other sessions' files on disk.
if event.timestamp_ms < self.session_start_ms {
return;
}
// Session isolation — layer 2: if an **explicit** expected
// session_id was set at bootstrap (from `KIZU_SESSION_ID`
// or a future CLI flag), drop events that carry a
// different session_id. Auto-binding to the first observed
// session was intentionally removed: under concurrent
// agent activity it locked the TUI onto whichever session
// happened to fire first, which could easily be a foreign
// agent and would silently hide the edits the user was
// attached to review. Unbound sessions accept all events
// (round-5 behavior) so the default path is non-trapping
// when no explicit binding is provided.
if let (Some(expected), Some(sid)) =
(self.bound_session_id.as_ref(), event.session_id.as_ref())
&& expected != sid
{
return;
}
// Normalize every file path to repo-relative form **once**,
// up front. Downstream snapshot lookups, per-file diff keys,
// and the stored `metadata.file_paths` must all agree on the
// same key shape — otherwise an event on `/abs/src/foo.rs`
// misses the seeded `src/foo.rs` entry and the first event
// for a pre-existing dirty file is rendered as the entire
// cumulative diff instead of only the tool call's delta.
// Paths that do not resolve inside the repo root are dropped
// from the event (edits to `~/.config`, `/tmp`, etc.) so
// they never appear as empty noise in the stream.
let normalized: Vec<PathBuf> = event
.file_paths
.iter()
.filter_map(|p| self.normalize_event_path(p))
.collect();
if normalized.is_empty() {
return;
}
event.file_paths = normalized;
// Capture per-operation diff for each affected file separately
// so multi-file events keep one hunk set per path.
let mut per_file_diffs: BTreeMap<PathBuf, String> = BTreeMap::new();
for file_path in &event.file_paths {
// Preserve prior snapshot on transient git failure. An
// `Err` here (e.g. the baseline object was pruned by a
// rebase, or the index is locked mid-operation) must not
// clobber `diff_snapshots[file_path]` — otherwise the
// *next* event for this file would diff against an empty
// baseline and spuriously emit the entire cumulative diff
// as the next operation's op_diff.
let Ok(current_diff) = git::diff_single_file(&self.root, &self.baseline_sha, file_path)
else {
continue;
};
let op_diff = if let Some(prev) = self.diff_snapshots.get(file_path) {
// Previous snapshot exists — compute delta.
compute_operation_diff(prev, ¤t_diff)
} else {
// No previous snapshot (first event for this file).
// Use the cumulative diff as the operation diff — this
// is accurate when seed_diff_snapshots ran at startup
// (the seed captured the pre-event state so current_diff
// minus seed = this operation's change). For truly new
// files, current_diff IS the operation's change.
current_diff.clone()
};
if !op_diff.is_empty() {
per_file_diffs.insert(file_path.clone(), op_diff);
}
self.diff_snapshots.insert(file_path.clone(), current_diff);
}
let stream_event = StreamEvent {
metadata: event,
per_file_diffs,
};
self.stream_events.push(stream_event);
// If in stream mode, rebuild files/layout to include the new event.
if self.view_mode == ViewMode::Stream {
let stream_files = build_stream_files(&self.stream_events);
self.apply_computed_files(stream_files);
}
}
/// Scan an events directory in timestamp order and feed each
/// `.json` file through [`Self::handle_event_log`]. Closes the
/// gap between session startup and `watcher::start`: any
/// `hook-log-event` written in that window lands on disk but is
/// never delivered by the notify backend because the watcher is
/// not yet armed. Calling this once after watcher startup drains
/// those files before the main loop begins.
///
/// Dedup is handled by [`Self::handle_event_log`]: if the watcher
/// later re-delivers one of these paths (some notify backends
/// fire pre-existing entries on arm), the call becomes a no-op.
pub fn replay_events_dir(&mut self, dir: &Path) {
if !dir.is_dir() {
return;
}
let Ok(read_dir) = std::fs::read_dir(dir) else {
return;
};
// Replay order is driven by the JSON payload's
// `timestamp_ms` (agent-side wall clock), with the on-disk
// file modification time as the tie-break for events that
// share a millisecond. The earlier implementation sorted by
// filename (`<ms>-<tool>-<uniq>.json`), which meant two
// same-millisecond events were reordered by tool name
// instead of by actual write sequence. Because
// `handle_event_log` mutates `diff_snapshots` in the order
// it receives events, out-of-order replay fabricated
// per-operation diffs and poisoned the baseline the next
// event diffed against.
//
// Tie-break chain: (timestamp_ms, mtime, path).
let mut entries: Vec<(u64, std::time::SystemTime, PathBuf)> = Vec::new();
for entry in read_dir.flatten() {
let name = entry.file_name();
let s = name.to_string_lossy();
if s.starts_with('.') || !s.ends_with(".json") {
continue;
}
let path = entry.path();
let ts_ms = std::fs::read_to_string(&path)
.ok()
.and_then(|c| serde_json::from_str::<SanitizedEvent>(&c).ok())
.map(|e| e.timestamp_ms)
.unwrap_or(0);
let mtime = entry
.metadata()
.and_then(|m| m.modified())
.unwrap_or(std::time::UNIX_EPOCH);
entries.push((ts_ms, mtime, path));
}
entries.sort_by(|a, b| {
a.0.cmp(&b.0)
.then_with(|| a.1.cmp(&b.1))
.then_with(|| a.2.cmp(&b.2))
});
for (_, _, path) in entries {
self.handle_event_log(path);
}
}
/// Re-run `git diff`, populate per-file mtimes, sort files by mtime
/// **ascending** (oldest first → newest last), rebuild the row layout,
/// and restore the anchor. The ascending order is intentional so that
/// the scroll view reads top-to-bottom in chronological order, like
/// `tail -f`: the newest hunk lives at the bottom and follow mode is
/// "pinned to the floor". On failure, record the error in `last_error`
/// and keep the previous `files` snapshot intact.
pub fn recompute_diff(&mut self) {
match git::compute_diff(&self.root, &self.baseline_sha) {
Ok(files) => self.apply_computed_files(files),
Err(e) => {
self.last_error = Some(format!("{e:#}"));
// self.files / self.layout intentionally untouched.
}
}
}
/// Accept a freshly-computed file set: populate mtimes, sort, clear
/// any prior error, rebuild layout, and refresh the anchor. Shared
/// between [`Self::bootstrap_with_diff`] (initial load) and
/// [`Self::recompute_diff`] (watcher-driven refreshes).
///
/// Also decides whether to set [`Self::pinned_cursor_y`]: when the
/// user is in manual mode and had the cursor on-screen before this
/// recompute, we preserve the cursor's screen row so a watcher-
/// driven reorder (edited file floats to the tail of the mtime
/// sort) does not slide the viewport out from under the user.
fn apply_computed_files(&mut self, mut files: Vec<FileDiff>) {
// Snapshot pre-state BEFORE any mutation. `visual_top` is the
// Cell the renderer updates each frame, so subtracting the
// cursor's visual y from it yields the screen row we last
// drew the cursor at.
let pre_had_layout = !self.layout.rows.is_empty();
let pre_scroll = self.scroll;
let pre_visual_top = self.visual_top.get();
let pre_body_height = self.last_body_height.get();
let pre_body_width = self.last_body_width.get();
let pre_cursor_visual_y: usize = match pre_body_width {
None => pre_scroll,
Some(_) => {
let vi = VisualIndex::build(&self.layout, &self.files, pre_body_width);
vi.visual_y(pre_scroll) + self.cursor_sub_row
}
};
let pre_screen_y_f = pre_cursor_visual_y as f32 - pre_visual_top;
let pre_in_viewport =
pre_had_layout && pre_screen_y_f >= 0.0 && (pre_screen_y_f as usize) < pre_body_height;
let pre_screen_y = pre_screen_y_f.max(0.0) as usize;
// Snapshot the cursor's "content identity" — `(abs_path,
// new_file_line)` when the cursor is on a DiffLine. Used as a
// fallback when `refresh_anchor` can only offer a HunkHeader
// row (its anchor lookup resolves hunks, not individual
// lines) and `scar_focus` is unavailable or invalid.
let pre_cursor_content = self.scroll_cursor_new_line();
let picker_selected_path = self.picker_selected_path();
// Stream mode files are already ordered by event timestamp and
// must not have their mtime overwritten by the filesystem. Diff
// mode files need filesystem mtime for chronological sorting.
if self.view_mode != ViewMode::Stream {
self.populate_mtimes(&mut files);
files.sort_by_key(|a| a.mtime);
}
self.last_error = None;
self.files = files;
self.build_layout();
self.refresh_picker_cursor(picker_selected_path.as_deref());
// Layout rebuild may shift row counts and wrap geometry, so
// any previously-stored intra-row offset is no longer valid.
// `refresh_anchor` then repositions the cursor on the same
// hunk if possible; the sub-row offset starts fresh there.
self.cursor_sub_row = 0;
self.refresh_anchor();
// Sticky scar focus: if a scar op recently set a focus
// target, re-apply it after `refresh_anchor` so the
// asynchronous watcher-driven recompute doesn't snap the
// cursor back to the hunk header. If the target line is no
// longer representable in the layout (e.g. the surrounding
// code was edited so the scar's new-file line number is
// gone or now points at different content), clear the
// focus and fall through to the pin path below so the
// cursor doesn't jump to the hunk header.
let mut scar_focus_applied = false;
if let Some((abs, line)) = self.scar_focus.clone() {
if let Some(row) = self.find_new_file_line_row(&abs, line) {
// `scroll_to` clears `pinned_cursor_y` — scar focus
// takes precedence over the pin, which is the right
// call since the user's explicit action was the scar.
self.scroll_to(row);
scar_focus_applied = true;
} else {
self.scar_focus = None;
}
}
// Content-preservation fallback: `refresh_anchor` can only
// resolve `(path, hunk_old_start)` — if that resolves, the
// cursor lands on the hunk's `@@` header row, not on the
// specific DiffLine the user was inspecting. When the user
// was on a DiffLine before the recompute, re-target the
// cursor to the DiffLine at (or nearest to) the pre-recompute
// new-file line. This avoids the "cursor snaps to @@" the
// user sees when a scar is edited away and `scar_focus`
// falls through.
//
// Uses direct `self.scroll = row` instead of `scroll_to`
// because the pin below still needs to fire — `scroll_to`
// would clear it.
if !scar_focus_applied
&& let Some((abs, pre_line)) = pre_cursor_content.clone()
&& matches!(
self.layout.rows.get(self.scroll),
Some(RowKind::HunkHeader { .. })
)
&& let Some(row) = self.find_nearest_new_file_line_row(&abs, pre_line)
{
self.scroll = row;
self.update_anchor_from_scroll();
}
// Viewport pin: preserve the cursor's screen row when this
// recompute is not user-initiated **and** scar focus didn't
// already relocate the cursor. Sequenced after the scar
// path so that a scar_focus whose line was edited away
// (anchor falls back to the hunk header in `refresh_anchor`)
// still gets its screen row preserved — otherwise the
// cursor would visibly jump to the HunkHeader row.
let should_pin = !self.follow_mode && !scar_focus_applied && pre_in_viewport;
if should_pin {
self.pinned_cursor_y = Some(pre_screen_y);
// A pin is a snap, not a slide: cancel any in-flight
// viewport tween so the next frame redraws at the pinned
// target directly. Otherwise the animation would
// interpolate from the stale pre-recompute viewport top
// to the new pinned target, visibly undoing the pin.
self.anim = None;
}
// else: pin is either already cleared by scroll_to above
// (scar_focus_applied = true) or was never set (bootstrap
// / follow mode / cursor off-screen) — nothing to do.
}
/// Drop any pending scar-focus target. Called from navigation
/// key dispatch so the user's explicit movement "sticks" — the
/// next watcher-driven recompute won't yank them back to the
/// scar line they've since moved past.
pub(crate) fn clear_scar_focus_on_nav(&mut self) {
self.scar_focus = None;
}
/// Re-capture HEAD as the new baseline (R key).
///
/// The reset is transactional: the new `baseline_sha` and the
/// cleared `head_dirty` flag are only committed **after** the
/// fresh `git diff` against that new baseline succeeds. If either
/// `head_sha` or `compute_diff` fails, every piece of visible
/// state is preserved so the user keeps looking at the same diff
/// with the `HEAD*` warning still present, rather than a stale
/// snapshot under a silently-advanced baseline.
///
/// Also re-resolves the symbolic HEAD ref. If the user has
/// switched branches since startup (or toggled detached HEAD on
/// or off), `self.current_branch_ref` is updated and the caller
/// must reconfigure the watcher — that's what the return value
/// `KeyEffect::ReconfigureWatcher` signals. Without this, the
/// watcher would stay pinned to the old branch ref and stop
/// raising `GitHead` for commits on the new branch (ADR-0008).
pub fn reset_baseline(&mut self) -> KeyEffect {
let new_sha = match git::head_sha(&self.root) {
Ok(sha) => sha,
Err(e) => {
self.last_error = Some(format!("R: {e:#}"));
return KeyEffect::None;
}
};
// Re-resolve the symbolic HEAD ref *before* running the
// diff so we know whether a reconfigure will be needed once
// the transaction commits.
let new_branch = match git::current_branch_ref(&self.root) {
Ok(b) => b,
Err(e) => {
self.last_error = Some(format!("R: {e:#}"));
return KeyEffect::None;
}
};
// Seed snapshots from the same `git diff` call that produces
// the FileDiff list. `apply_reset` clears the map on success;
// we populate it right after so the next event computes its
// op_diff against a correct pre-event reference.
let (diff, snapshots) = match git::compute_diff_with_snapshots(&self.root, &new_sha) {
Ok((files, snaps)) => (Ok(files), Some(snaps)),
Err(e) => (Err(e), None),
};
let effect = self.apply_reset(new_sha, new_branch, diff);
if let Some(snaps) = snapshots {
self.diff_snapshots.replace_from_map(snaps);
}
effect
}
/// Commit a freshly-resolved baseline + diff into the app. Split
/// out from [`Self::reset_baseline`] so tests can inject a failing
/// diff without touching the filesystem and verify that the old
/// baseline, `head_dirty`, and `files` snapshot all survive.
///
/// Returns [`KeyEffect::ReconfigureWatcher`] when the resolved
/// branch differs from the session's previous tracking, so the
/// event loop can hot-swap the watcher's `BaselineMatcherInner`
/// without rebuilding the debouncers.
pub(crate) fn apply_reset(
&mut self,
new_sha: String,
new_branch: Option<String>,
diff: Result<Vec<FileDiff>>,
) -> KeyEffect {
match diff {
Ok(files) => {
let branch_changed = new_branch != self.current_branch_ref;
self.baseline_sha = new_sha;
self.current_branch_ref = new_branch;
self.head_dirty = false;
self.apply_computed_files(files);
// Drop stream-mode snapshots captured against the
// previous baseline. Every entry in `diff_snapshots`
// was `git diff <old_baseline> -- <path>` output;
// comparing the next hook-log-event against that
// would misattribute lines that belong to the change
// between baselines (not to the agent's edit).
// The caller (`reset_baseline`) repopulates the map
// from the same `compute_diff_with_snapshots` call
// that produced `files`, so there's no need to run
// a second per-file diff sweep here.
self.diff_snapshots.clear();
if branch_changed {
KeyEffect::ReconfigureWatcher
} else {
KeyEffect::None
}
}
Err(e) => {
self.last_error = Some(format!("R: {e:#}"));
// baseline_sha / current_branch_ref / head_dirty /
// files / diff_snapshots intentionally untouched:
// the HEAD* warning stays visible and the user keeps
// seeing the same diff they had before R. Watcher
// also stays pinned to the old branch, which is the
// correct behavior for an aborted reset.
KeyEffect::None
}
}
}
/// HEAD/refs moved without the user re-baselining yet.
pub fn mark_head_dirty(&mut self) {
self.head_dirty = true;
}
/// Fold a coalesced burst of watcher events into the app's
/// health / refresh state and return the follow-up the event
/// loop still needs to perform: `(needs_recompute, needs_head_dirty)`.
///
/// Split out of [`run_loop`] so the state transitions can be
/// tested without a real debouncer. Every caller of `run_loop`
/// and every test that simulates a watcher burst must route
/// through this method so the health / recovery rules stay
/// consistent.
pub fn handle_watch_burst(
&mut self,
events: impl IntoIterator<Item = WatchEvent>,
) -> (bool, bool) {
let mut worktree = false;
let mut head = false;
let mut recovered_sources = Vec::new();
let mut failed_sources: BTreeMap<WatchSource, String> = BTreeMap::new();
for event in events {
match event {
WatchEvent::Worktree => {
worktree = true;
recovered_sources.push(WatchSource::Worktree);
}
WatchEvent::GitHead(source) => {
head = true;
recovered_sources.push(source);
}
WatchEvent::EventLog(path) => {
self.handle_event_log(path);
}
WatchEvent::Error { source, message } => {
failed_sources.insert(source, message);
}
}
}
for source in recovered_sources {
if !failed_sources.contains_key(&source) {
self.watcher_health.clear_source(source);
}
}
if !failed_sources.is_empty() {
// Backend failure: record it in the dedicated
// `watcher_health` slot (NOT `last_error`) so a
// subsequent successful recompute from some *other*
// watcher source does not silently erase the fact that
// live monitoring is partially dead.
worktree = true;
for (source, message) in failed_sources {
self.watcher_health.record_failure(source, message);
}
}
(worktree, head)
}
/// Top-level key dispatch. Picker mode shadows the normal bindings.
/// Returns a [`KeyEffect`] describing any post-dispatch work that
/// the event loop must perform — currently only `R` can trigger
/// a watcher reconfigure, but the same channel scales to future
/// side-effects without threading explicit parameters through
/// every handler.
pub fn handle_key(&mut self, key: KeyEvent) -> KeyEffect {
if self.picker.is_some() {
self.handle_picker_key(key);
KeyEffect::None
} else if self.scar_comment.is_some() {
self.handle_scar_comment_key(key);
KeyEffect::None
} else if self.revert_confirm.is_some() {
self.handle_revert_confirm_key(key);
KeyEffect::None
} else if self.search_input.is_some() {
self.handle_search_input_key(key);
KeyEffect::None
} else if self.file_view.is_some() {
self.handle_file_view_key(key)
} else {
self.handle_normal_key(key)
}
}
// ---- normal-mode keys --------------------------------------------
fn handle_normal_key(&mut self, key: KeyEvent) -> KeyEffect {
// Quit shortcuts.
if matches!(key.code, KeyCode::Char('q'))
|| (matches!(key.code, KeyCode::Char('c'))
&& key.modifiers.contains(KeyModifiers::CONTROL))
{
self.should_quit = true;
return KeyEffect::None;
}
// Any user keypress drops the sticky scar-focus target. Scar
// actions (`a`/`r`/`c`/`u`) re-establish the focus later in
// this frame via `refresh_after_scar_write`, so clearing here
// costs nothing for them but protects every other key from
// leaving the cursor pinned to the last scar.
self.clear_scar_focus_on_nav();
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('d') => {
self.scroll_by(HALF_PAGE as isize);
self.follow_mode = false;
return KeyEffect::None;
}
KeyCode::Char('u') => {
self.scroll_by(-(HALF_PAGE as isize));
self.follow_mode = false;
return KeyEffect::None;
}
_ => {}
}
}
match key.code {
// Lowercase `j`/`k` + arrows are the *daily driver*: adaptive
// motion that reads like continuous scrolling in long hunks
// (chunk scroll) but collapses to a one-press hunk jump in
// short hunks.
//
// v0.2 key remap (ADR-0015 / plans/v0.2.md M4):
// - `J` / `K` now move the cursor by **exactly one visual row**.
// The old hunk-header jump behavior was relocated to `l` /
// `h` so add/delete scar decisions can be made row-by-row.
// - `l` / `h` strictly jump to the next / previous hunk header,
// mirroring the pre-v0.2 `J` / `K` binding.
// - Picker open moved from `Space` to `s` so `Space` can be
// used for the scar "seen" mark (wired up in a later M4 slice).
KeyCode::Char('j') | KeyCode::Down => {
self.next_change();
self.follow_mode = false;
}
KeyCode::Char('k') | KeyCode::Up => {
self.prev_change();
self.follow_mode = false;
}
KeyCode::Char('J') => {
self.scroll_by(1);
// Snap for 1-row moves: the 150ms ease-out tween
// restarts on every key-repeat tick, causing visible
// jitter when holding J/K. Clearing the animation
// makes rapid single-row scrolling buttery smooth.
self.anim = None;
self.follow_mode = false;
}
KeyCode::Char('K') => {
self.scroll_by(-1);
self.anim = None;
self.follow_mode = false;
}
KeyCode::Char('l') => {
self.next_hunk();
self.follow_mode = false;
}
KeyCode::Char('h') => {
self.prev_hunk();
self.follow_mode = false;
}
KeyCode::Char('g') => {
self.scroll_to(0);
self.follow_mode = false;
}
KeyCode::Char('G') => {
self.scroll_to(self.last_row_index());
self.follow_mode = false;
}
KeyCode::Tab => {
self.toggle_view_mode();
}
KeyCode::Enter => {
self.open_file_view();
}
KeyCode::Char(ch) => {
// Remappable keys resolved via config. Navigation
// keys (j/k/J/K/h/l/g/G) are handled above; these
// are the action keys that users can remap in
// ~/.config/kizu/config.toml.
let k = &self.config.keys;
if ch == k.follow {
self.follow_restore();
} else if ch == k.picker {
self.open_picker();
} else if ch == k.ask {
self.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
} else if ch == k.reject {
self.insert_canned_scar(ScarKind::Reject, SCAR_TEXT_REJECT);
} else if ch == k.comment {
self.open_scar_comment();
} else if ch == k.revert {
self.open_revert_confirm();
} else if ch == k.seen {
self.toggle_seen_current_hunk();
} else if ch == k.search {
self.open_search_input();
} else if ch == k.search_next {
self.search_jump_next();
} else if ch == k.search_prev {
self.search_jump_prev();
} else if ch == k.editor {
// Read `$EDITOR` at dispatch time (not at bootstrap)
// so users who `export EDITOR=` mid-session pick up
// the new value without restarting kizu.
let editor_cmd = if self.config.editor.command.is_empty() {
std::env::var("EDITOR").ok()
} else {
Some(self.config.editor.command.clone())
};
if let Some(inv) = self.open_in_editor(editor_cmd.as_deref()) {
return KeyEffect::OpenEditor(inv);
}
} else if ch == k.reset_baseline {
return self.reset_baseline();
} else if ch == k.cursor_placement {
self.toggle_cursor_placement();
} else if ch == k.wrap_toggle {
self.toggle_wrap_lines();
} else if ch == k.undo {
self.undo_scar();
}
}
_ => {}
}
KeyEffect::None
}
// ---- picker-mode keys --------------------------------------------
fn handle_picker_key(&mut self, key: KeyEvent) {
// Ctrl-* shortcuts: navigation + cancel. Picker uses fzf-style
// bindings so any non-control char (including 'j' / 'k') is a
// filter character.
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('n') | KeyCode::Char('j') => self.picker_cursor_down(),
KeyCode::Char('p') | KeyCode::Char('k') => self.picker_cursor_up(),
KeyCode::Char('c') => self.close_picker(),
_ => {}
}
return;
}
match key.code {
KeyCode::Esc => self.close_picker(),
KeyCode::Enter => {
let results = self.picker_results();
let cursor = self.picker.as_ref().map(|p| p.cursor).unwrap_or(0);
let target = results.get(cursor).copied();
self.close_picker();
if let Some(file_idx) = target {
// Picker selection is an explicit manual navigation:
// a subsequent watcher-driven recompute must not
// snap the viewport back to the newest file via
// follow mode. Drop follow before jumping so the
// anchor captured by `scroll_to` sticks.
self.follow_mode = false;
self.jump_to_file_first_hunk(file_idx);
}
}
KeyCode::Up => self.picker_cursor_up(),
KeyCode::Down => self.picker_cursor_down(),
KeyCode::Backspace => {
if let Some(picker) = self.picker.as_mut() {
picker.query.pop();
picker.cursor = 0;
}
}
KeyCode::Char(c) => {
if let Some(picker) = self.picker.as_mut() {
picker.query.push(c);
picker.cursor = 0;
}
}
_ => {}
}
}
// ---- picker helpers ----------------------------------------------
pub fn open_picker(&mut self) {
self.picker = Some(PickerState::default());
}
pub fn close_picker(&mut self) {
self.picker = None;
}
/// Indices into `self.files` for the picker's filtered view. The picker
/// follows the file-picker convention of **newest first** even though
/// `self.files` itself is stored in ascending mtime order: this way an
/// empty-query → `Enter` lands on whatever the agent just touched.
pub fn picker_results(&self) -> Vec<usize> {
let needle = match &self.picker {
Some(p) if !p.query.is_empty() => p.query.to_lowercase(),
_ => return (0..self.files.len()).rev().collect(),
};
self.files
.iter()
.enumerate()
.rev()
.filter(|(_, f)| f.path.to_string_lossy().to_lowercase().contains(&needle))
.map(|(i, _)| i)
.collect()
}
fn picker_selected_path(&self) -> Option<PathBuf> {
let picker = self.picker.as_ref()?;
let results = self.picker_results();
let file_idx = results.get(picker.cursor).copied()?;
self.files.get(file_idx).map(|f| f.path.clone())
}
fn refresh_picker_cursor(&mut self, selected_path: Option<&Path>) {
let Some(cursor) = self.picker.as_ref().map(|p| p.cursor) else {
return;
};
let results = self.picker_results();
let new_cursor = if results.is_empty() {
0
} else if let Some(path) = selected_path {
results
.iter()
.position(|&idx| self.files.get(idx).is_some_and(|f| f.path == path))
.unwrap_or_else(|| cursor.min(results.len() - 1))
} else {
cursor.min(results.len() - 1)
};
if let Some(picker) = self.picker.as_mut() {
picker.cursor = new_cursor;
}
}
fn picker_cursor_down(&mut self) {
let len = self.picker_results().len();
if let Some(picker) = self.picker.as_mut()
&& len > 0
&& picker.cursor + 1 < len
{
picker.cursor += 1;
}
}
fn picker_cursor_up(&mut self) {
if let Some(picker) = self.picker.as_mut() {
picker.cursor = picker.cursor.saturating_sub(1);
}
}
// ---- navigation helpers ------------------------------------------
pub fn scroll_by(&mut self, delta: isize) {
let last = self.last_row_index();
let body_width = self.last_body_width.get();
if body_width.is_none() {
// Nowrap fast path: one logical row == one visual row,
// sub-row is always 0. Delegate to `scroll_to` which
// resets `cursor_sub_row` unconditionally.
let next = (self.scroll as isize + delta).clamp(0, last as isize) as usize;
let next = self.normalize_row_target(next, delta.signum());
self.scroll_to(next);
return;
}
// Wrap mode: `delta` is interpreted as **visual rows** and
// the cursor's position is the sum of its logical-row visual
// y and its intra-row `cursor_sub_row`. ADR-0009 fix: the
// previous implementation discarded the intra-row offset
// returned by `VisualIndex::logical_at`, so Ctrl-d inside a
// single long wrapped line stayed pinned to the same logical
// row — `scroll_to(row)` treated the move as a no-op and
// the user could never walk through a minified JSON edit.
//
// The fix routes wrap-mode navigation through `scroll_to_visual`
// which preserves the sub-row offset so the visual cursor
// genuinely advances.
let vi = VisualIndex::build(&self.layout, &self.files, body_width);
let cur_y = vi.visual_y(self.scroll) + self.cursor_sub_row;
let new_y = (cur_y as isize + delta).max(0) as usize;
let clamped = new_y.min(vi.total_visual().saturating_sub(1));
let (target_row, target_sub) = vi.logical_at(clamped);
let target_row = self.normalize_row_target(target_row.min(last), delta.signum());
self.scroll_to_visual(target_row, target_sub, &vi);
}
/// Wrap-aware cursor move that preserves an intra-row visual
/// offset. Nowrap callers must keep going through [`Self::scroll_to`]
/// because they have no `VisualIndex` to clamp against and would
/// just set `cursor_sub_row` to 0 anyway.
///
/// Behaves like [`Self::scroll_to`] for the row side: starts a
/// fresh animation when either the logical row or the sub-row
/// actually changes, and updates the anchor. `sub_row` is
/// clamped to the target row's visual height so callers can
/// pass a speculative value without risking an out-of-range
/// cursor.
pub(crate) fn scroll_to_visual(&mut self, row: usize, sub_row: usize, vi: &VisualIndex) {
// Any explicit cursor move drops the watcher-set pin so
// subsequent renders fall back to normal placement.
self.pinned_cursor_y = None;
let last = self.last_row_index();
let target_row = row.min(last);
let row_height = vi.visual_height(target_row).max(1);
let clamped_sub = sub_row.min(row_height - 1);
if (target_row, clamped_sub) != (self.scroll, self.cursor_sub_row) {
self.anim = Some(ScrollAnim {
from: self.visual_top.get(),
start: Instant::now(),
dur: SCROLL_ANIM_DURATION,
});
}
self.scroll = target_row;
self.cursor_sub_row = clamped_sub;
self.update_anchor_from_scroll();
}
/// Animated scroll: move the cursor row to `row` and kick off a
/// viewport-top tween from the currently drawn visual position.
/// No animation is started when `row` is already the cursor row
/// (a no-op), which keeps idle frames free of needless ticks.
///
/// Also resets `cursor_sub_row` to 0 — every caller of
/// `scroll_to` is a "jump to a specific row" operation (next
/// hunk, previous hunk, g, G, follow restore, picker jump,
/// anchor restore) and those should all land on the first
/// visual line of the destination logical row. Wrap-mode
/// **intra-row** walks go through [`Self::scroll_to_visual`]
/// instead.
pub fn scroll_to(&mut self, row: usize) {
// Any explicit cursor move drops the watcher-set pin so
// subsequent renders fall back to normal placement.
self.pinned_cursor_y = None;
let last = self.last_row_index();
let target = self.normalize_row_target(row.min(last), 1);
if target != self.scroll || self.cursor_sub_row != 0 {
self.anim = Some(ScrollAnim {
from: self.visual_top.get(),
start: Instant::now(),
dur: SCROLL_ANIM_DURATION,
});
}
self.scroll = target;
self.cursor_sub_row = 0;
self.update_anchor_from_scroll();
}
fn normalize_row_target(&self, row: usize, preferred_direction: isize) -> usize {
if !matches!(self.layout.rows.get(row), Some(RowKind::Spacer)) {
return row;
}
if preferred_direction >= 0
&& let Some(next) = self
.layout
.rows
.iter()
.enumerate()
.skip(row + 1)
.find_map(|(idx, r)| (!matches!(r, RowKind::Spacer)).then_some(idx))
{
return next;
}
if let Some(prev) = self.layout.rows[..row]
.iter()
.rposition(|r| !matches!(r, RowKind::Spacer))
{
return prev;
}
row
}
/// Mark the active animation as finished if enough time has passed.
/// Returns `true` while an animation is still running, `false` once
/// the run loop can stop scheduling frame ticks. Pure (`&mut self`
/// only for the clear side-effect) so tests can inject `now`.
pub fn tick_anim(&mut self, now: Instant) -> bool {
let Some(anim) = self.anim else {
return false;
};
let done = now.saturating_duration_since(anim.start) >= anim.dur;
if done {
self.anim = None;
false
} else {
true
}
}
/// Animated variant of [`Self::viewport_top`]: feeds the logical
/// target through the active [`ScrollAnim`], sampling at `now`.
/// Stores the result in [`Self::visual_top`] so the next animation
/// kick-off starts from the exact row the last frame drew.
///
/// This is the **nowrap** helper: it operates purely in logical
/// row units and is retained for the existing centering/hunk-anchor
/// tests plus nowrap renders. Wrap renders go through
/// [`Self::viewport_placement`] instead, which speaks visual y.
pub fn visual_viewport_top(&self, viewport_height: usize, now: Instant) -> usize {
let target = self.viewport_top(viewport_height) as f32;
let visual = match self.anim.as_ref() {
Some(anim) => anim.sample(target, now).0,
None => target,
};
self.visual_top.set(visual);
visual.round().max(0.0) as usize
}
/// Compute the viewport's top position for the current render,
/// returning `(top_row, skip_visual)` where `top_row` is the first
/// logical layout row to draw and `skip_visual` is the number of
/// visual lines of `top_row` the renderer should discard off the
/// top so that the cursor lands at its desired placement target.
///
/// In **nowrap** mode every logical row is one visual row tall,
/// so the result is always `(visual_viewport_top(h), 0)` — the
/// legacy scroll model is preserved byte-for-byte. In **wrap**
/// mode `viewport_placement` converts the hunk-anchored placement
/// logic from logical-row space into visual-row space via
/// [`VisualIndex`]; the cursor's first visual row always lands at
/// the centre-of-viewport (or viewport ceiling under `Top`
/// placement), regardless of how much the preceding diff content
/// wraps. Animation is preserved across the transition: the tween
/// runs in visual y, which in nowrap collapses to logical rows
/// and matches the pre-rework behaviour numerically.
pub fn viewport_placement(
&self,
viewport_height: usize,
body_width: Option<usize>,
now: Instant,
) -> (usize, usize) {
let Some(_width) = body_width else {
// Nowrap fast path — identical to the old visual_viewport_top.
return (self.visual_viewport_top(viewport_height, now), 0);
};
let vi = VisualIndex::build(&self.layout, &self.files, body_width);
let target_y = self.placement_target_visual_y(viewport_height, &vi);
let sampled_y = match self.anim.as_ref() {
Some(anim) => anim.sample(target_y as f32, now).0,
None => target_y as f32,
};
self.visual_top.set(sampled_y);
let y = sampled_y.round().max(0.0) as usize;
vi.logical_at(y)
}
/// Visual-y coordinate of the viewport's top edge under wrap mode,
/// chosen so that the cursor (or its enclosing hunk) lands at the
/// current [`CursorPlacement`]'s preferred target. Mirrors the
/// nowrap [`Self::viewport_top`] hunk-anchoring logic, but in
/// visual-row units.
fn placement_target_visual_y(&self, viewport_height: usize, vi: &VisualIndex) -> usize {
let total_visual = vi.total_visual();
if total_visual <= viewport_height {
return 0;
}
let max_top_y = total_visual - viewport_height;
// Viewport pin: matches nowrap `viewport_top`. When a watcher-
// driven recompute relocates the cursor, hold the cursor's
// visual y at the pre-recompute screen row so the viewport
// doesn't slide.
if let Some(pinned_y) = self.pinned_cursor_y {
let cursor_y = vi.visual_y(self.scroll) + self.cursor_sub_row;
return cursor_y.saturating_sub(pinned_y).min(max_top_y);
}
// Hunk-fits-in-viewport case: anchor the entire hunk at the
// placement target so the user always sees the full selected
// change as a single block, matching nowrap behaviour.
if let Some((hunk_top, hunk_end)) = self.current_hunk_range() {
let hunk_visual = vi.visual_y(hunk_end).saturating_sub(vi.visual_y(hunk_top));
if hunk_visual <= viewport_height {
let hunk_top_y = vi.visual_y(hunk_top);
let desired = match self.cursor_placement {
CursorPlacement::Centered => {
let pad = (viewport_height - hunk_visual) / 2;
hunk_top_y.saturating_sub(pad)
}
CursorPlacement::Top => hunk_top_y,
};
return desired.min(max_top_y);
}
}
// Long-hunk / non-hunk fallback: place the cursor at the
// placement target, measured in visual y. ADR-0009 fix:
// include `cursor_sub_row` so intra-row walks through a
// wrapped diff line actually move the viewport instead of
// parking it at the logical row's first visual line.
let cursor_y = vi.visual_y(self.scroll) + self.cursor_sub_row;
let desired = match self.cursor_placement {
CursorPlacement::Centered => {
// Keep the cursor's current visual row at mid-viewport.
// `cursor_sub_row` is already the intra-row offset, so
// the 1-row cursor height is the right subtraction
// here — wrap-continuation lines below the cursor
// are drawn by the renderer.
cursor_y.saturating_sub(viewport_height.saturating_sub(1) / 2)
}
CursorPlacement::Top => cursor_y,
};
desired.min(max_top_y)
}
fn last_row_index(&self) -> usize {
self.layout
.rows
.iter()
.rposition(|row| !matches!(row, RowKind::Spacer))
.unwrap_or(0)
}
pub fn next_hunk(&mut self) {
// Only advance when there is actually a hunk after the cursor.
// The previous fallback to `hunk_starts.last()` caused `j` to
// jump **backward** whenever the cursor sat past the final hunk
// header (e.g. on the last diff line of a long hunk), which is
// the opposite of what "next" should mean.
if let Some(&row) = self
.layout
.hunk_starts
.iter()
.find(|&&start| start > self.scroll)
{
self.scroll_to(row);
}
}
pub fn prev_hunk(&mut self) {
if let Some(&row) = self
.layout
.hunk_starts
.iter()
.rev()
.find(|&&start| start < self.scroll)
{
self.scroll_to(row);
} else if let Some(&row) = self.layout.hunk_starts.first() {
self.scroll_to(row);
}
}
/// `j` — adaptive forward motion. Only lands on **reviewable
/// rows**: change-run starts, long-run bodies (chunk-walked), or
/// the next hunk's header (via [`Self::next_hunk`]). Never parks
/// the cursor mid-context.
///
/// Decision ladder:
///
/// 1. **Inside a long run, not at its last row** — chunk-scroll
/// forward by [`Self::chunk_size`], clamped to the run's last
/// row. A 30-line Added block gets walked top-to-bottom in a
/// few presses instead of teleporting past its body.
/// 2. **Next run exists within this hunk** — land on its start.
/// (The jump is visually tweened by [`ScrollAnim`] so the
/// motion feels gradual even though the cursor doesn't stop
/// on any intermediate context rows.)
/// 3. **No more runs in this hunk** — hand off to
/// [`Self::next_hunk`].
///
/// A change run is a maximal stretch of non-`Context` rows — `-`
/// and `+` lines share a run because a typical one-line edit
/// (`-old\n+new`) is reviewed as a single unit.
pub fn next_change(&mut self) {
let cursor = self.scroll;
let viewport = self.last_body_height.get().max(1);
let body_width = self.last_body_width.get();
let Some((_, hunk_end)) = self.current_hunk_range() else {
self.next_hunk();
return;
};
let vi = VisualIndex::build(&self.layout, &self.files, body_width);
// Inside a long run, not at its last row → chunk forward
// within the run so its body isn't teleported past.
if let Some(&(run_start, run_end)) = self
.layout
.change_runs
.iter()
.find(|(s, e)| *s <= cursor && cursor < *e)
{
let run_visual = vi.visual_y(run_end).saturating_sub(vi.visual_y(run_start));
if is_long_run(run_visual, viewport) && cursor + 1 < run_end {
let last_row = run_end.saturating_sub(1);
let target = (cursor + self.chunk_size()).min(last_row);
self.scroll_to(target);
return;
}
}
// Next run start in this hunk → jump (never lands on the
// intervening context).
if let Some(&(run_start, _)) = self
.layout
.change_runs
.iter()
.find(|(s, _)| *s > cursor && *s < hunk_end)
{
self.scroll_to(run_start);
return;
}
self.next_hunk();
}
/// `k` — adaptive backward motion. Mirror of [`Self::next_change`].
/// Only lands on change-run starts, long-run bodies, or the prev
/// hunk's last run start (via [`Self::prev_hunk_last_run_start`]).
pub fn prev_change(&mut self) {
let cursor = self.scroll;
let viewport = self.last_body_height.get().max(1);
let body_width = self.last_body_width.get();
let Some((hunk_top, _)) = self.current_hunk_range() else {
self.prev_hunk_last_run_start();
return;
};
let vi = VisualIndex::build(&self.layout, &self.files, body_width);
// Inside a long run, not at its start → chunk back within.
if let Some(&(run_start, run_end)) = self
.layout
.change_runs
.iter()
.find(|(s, e)| *s <= cursor && cursor < *e)
{
let run_visual = vi.visual_y(run_end).saturating_sub(vi.visual_y(run_start));
if is_long_run(run_visual, viewport) && cursor > run_start {
let target = cursor.saturating_sub(self.chunk_size()).max(run_start);
self.scroll_to(target);
return;
}
}
// Prev run start in this hunk → jump.
if let Some(&(run_start, _)) = self
.layout
.change_runs
.iter()
.rev()
.find(|(s, _)| *s < cursor && *s >= hunk_top)
{
self.scroll_to(run_start);
return;
}
self.prev_hunk_last_run_start();
}
/// Land the cursor on the **start of the last change run** inside
/// the hunk immediately before the current one. Used by
/// [`Self::prev_change`] as the boundary-crossing handoff.
///
/// Landing on the last run's start (rather than the hunk's literal
/// last row) keeps the cursor parked on reviewable code. A hunk
/// frequently ends with trailing `Context` lines; landing there
/// would drop the reader on unchanged code. From the last run's
/// start, subsequent `k` presses walk backward through the hunk's
/// runs naturally.
///
/// "Prev hunk" is defined relative to the *current hunk's header*,
/// not the scroll position — otherwise, when the cursor sits past
/// the current hunk's header (e.g. on its first change run), this
/// helper would pick the current hunk's own header as the "prev"
/// and bounce the cursor back inside the same hunk. When there is
/// no preceding hunk, this is a no-op.
fn prev_hunk_last_run_start(&mut self) {
let threshold = self
.current_hunk_range()
.map(|(top, _)| top)
.unwrap_or(self.scroll);
let Some(&prev_start) = self
.layout
.hunk_starts
.iter()
.rev()
.find(|&&s| s < threshold)
else {
return;
};
// Extract the (file_idx, hunk_idx) of the prev hunk so we can
// scope the run search to it.
let (target_file, target_hunk) = match self.layout.rows.get(prev_start) {
Some(RowKind::HunkHeader { file_idx, hunk_idx }) => (*file_idx, *hunk_idx),
_ => {
self.scroll_to(prev_start);
return;
}
};
// Walk forward from the prev hunk's header to find its
// exclusive end row (first row that no longer belongs to it).
let mut prev_hunk_end = prev_start + 1;
for (i, row) in self.layout.rows.iter().enumerate().skip(prev_start + 1) {
let belongs = match row {
RowKind::HunkHeader { file_idx, hunk_idx }
| RowKind::DiffLine {
file_idx, hunk_idx, ..
} => *file_idx == target_file && *hunk_idx == target_hunk,
_ => false,
};
if belongs {
prev_hunk_end = i + 1;
} else {
break;
}
}
// Last change-run start inside the prev hunk. Defensive
// fallback to the hunk header if (somehow) no runs exist.
let landing = self
.layout
.change_runs
.iter()
.rev()
.find(|(s, _)| *s >= prev_start && *s < prev_hunk_end)
.map(|(s, _)| *s)
.unwrap_or(prev_start);
self.scroll_to(landing);
}
pub fn jump_to_file_first_hunk(&mut self, file_idx: usize) {
if let Some(Some(row)) = self.layout.file_first_hunk.get(file_idx).copied() {
self.scroll_to(row);
}
}
pub fn follow_restore(&mut self) {
self.follow_mode = true;
if let Some(idx) = self.follow_target_row() {
self.scroll_to(idx);
}
}
/// Row that "follow mode" parks the scroll cursor on: the
/// **last hunk header** of the newest file (files are sorted
/// mtime-ascending, so the last file is the most recently
/// touched one). Landing on the last @@ header lets the user
/// see the most recent change's context and diff body below.
fn follow_target_row(&self) -> Option<usize> {
if self.files.is_empty() {
return None;
}
let newest = self.files.len() - 1;
// Walk from the end to find the last HunkHeader of the newest file.
for (i, row) in self.layout.rows.iter().enumerate().rev() {
if matches!(row, RowKind::HunkHeader { file_idx, .. } if *file_idx == newest) {
return Some(i);
}
}
// Fallback: try file header, then the absolute last row.
for (i, row) in self.layout.rows.iter().enumerate() {
if matches!(row, RowKind::FileHeader { file_idx } if *file_idx == newest) {
return Some(i);
}
}
self.layout.rows.len().checked_sub(1)
}
/// File index that the row at `self.scroll` belongs to.
pub fn current_file_idx(&self) -> Option<usize> {
self.layout.file_of_row.get(self.scroll).copied()
}
pub fn current_file_path(&self) -> Option<&Path> {
self.current_file_idx()
.and_then(|i| self.files.get(i))
.map(|f| f.path.as_path())
}
/// `(file_idx, hunk_idx)` of the hunk the cursor is currently inside,
/// or `None` when scroll is parked on a non-hunk row (file header,
/// binary notice, spacer). The renderer uses this to pick the bright
/// style for selected hunk rows and DIM for everyone else.
pub fn current_hunk(&self) -> Option<(usize, usize)> {
match self.layout.rows.get(self.scroll)? {
RowKind::HunkHeader { file_idx, hunk_idx } => Some((*file_idx, *hunk_idx)),
RowKind::DiffLine {
file_idx, hunk_idx, ..
} => Some((*file_idx, *hunk_idx)),
_ => None,
}
}
/// Scroll to the first row of the file matching `path`. No-op if
/// the file is not in the current layout.
/// Insert a scar of the given `kind` with `body` as the human
/// text, at the cursor's current position. No-op when the
/// cursor is not on a diff row (file header, hunk header,
/// spacer, binary notice). Write failures from
/// [`crate::scar::insert_scar`] are captured in `last_error` so
/// the footer surfaces them instead of panicking. The watcher
/// picks up the resulting write on its next tick and re-runs
/// `compute_diff`, which shows the new scar line in place.
pub fn insert_canned_scar(&mut self, kind: ScarKind, body: &str) {
// Stream mode shows historical diffs with synthetic line numbers;
// scar insertion would target nonsensical positions. Switch to
// diff mode to scar the current file state.
if self.view_mode == ViewMode::Stream {
return;
}
let Some((path, line)) = self.scar_target_line() else {
return;
};
match crate::scar::insert_scar(&path, line, kind, body) {
Ok(Some(receipt)) => {
let focus = Some((path.clone(), receipt.line_1indexed));
self.scar_undo_stack.push(ScarUndoEntry {
path,
line_1indexed: receipt.line_1indexed,
rendered: receipt.rendered,
});
self.refresh_after_scar_write(focus);
}
Ok(None) => {
// Idempotent no-op (same scar already above target).
// Nothing to undo; don't pollute the stack with a
// phantom entry.
}
Err(err) => {
self.last_error = Some(format!("scar: {err:#}"));
}
}
}
/// Enter free-text scar input mode. Captures the current
/// cursor's target `(path, line)` so a watcher-driven recompute
/// while the user is typing cannot retarget the write. No-op
/// when the cursor is not on a scar-able row.
pub fn open_scar_comment(&mut self) {
if self.view_mode == ViewMode::Stream {
return;
}
let Some((target_path, target_line)) = self.scar_target_line() else {
return;
};
self.scar_comment = Some(ScarCommentState {
target_path,
target_line,
body: String::new(),
cursor_pos: 0,
});
}
/// Abort free-text scar input without writing anything.
pub fn close_scar_comment(&mut self) {
self.scar_comment = None;
}
/// Commit the currently-composed free-text scar, if any. Empty
/// body is treated as a cancel (so double-`Enter` on an empty
/// input does not write a blank scar). Write failures land on
/// `last_error` with the same `scar:` prefix used by the canned
/// `a` / `r` dispatch.
pub fn commit_scar_comment(&mut self) {
let Some(state) = self.scar_comment.take() else {
return;
};
let body = state.body.trim();
if body.is_empty() {
return;
}
match crate::scar::insert_scar(&state.target_path, state.target_line, ScarKind::Free, body)
{
Ok(Some(receipt)) => {
let focus = Some((state.target_path.clone(), receipt.line_1indexed));
self.scar_undo_stack.push(ScarUndoEntry {
path: state.target_path,
line_1indexed: receipt.line_1indexed,
rendered: receipt.rendered,
});
self.refresh_after_scar_write(focus);
}
Ok(None) => {}
Err(err) => {
self.last_error = Some(format!("scar: {err:#}"));
}
}
}
/// Sync the on-screen diff + file view with the on-disk state
/// after a scar write or undo. Without this, the user would wait
/// for the watcher debounce (~300ms) before seeing their scar
/// appear. We run `git diff` synchronously and re-read the file
/// view's line buffer — cheap on any normal repo, and eliminates
/// the visible input lag.
///
/// `focus` is an optional `(absolute path, 1-indexed new-file
/// line)` pair. After the diff rebuild, the cursor is snapped to
/// the layout row that represents that line. This is what keeps
/// the user parked on the scar they just inserted (otherwise
/// `refresh_anchor` re-targets to the hunk header in follow mode).
///
/// Best-effort: a git-diff failure here is swallowed. The scar
/// write itself already succeeded, the watcher will retry on its
/// next tick, and this keeps `last_error` from being polluted by
/// the refresh attempt (tests running against a non-git scratch
/// dir also benefit).
fn refresh_after_scar_write(&mut self, focus: Option<(PathBuf, usize)>) {
// Pin the focus target *before* the recompute so
// `apply_computed_files`'s tail will honour it. The pin then
// persists through the asynchronous watcher tick that fires
// ~300ms later — without it, that second recompute would snap
// the cursor back to the hunk header.
self.scar_focus = focus;
if let Ok(files) = git::compute_diff(&self.root, &self.baseline_sha) {
self.apply_computed_files(files);
}
if let Some(fv) = self.file_view.as_mut() {
let abs = self.root.join(&fv.path);
if let Ok(content) = std::fs::read_to_string(&abs) {
fv.lines = content.lines().map(String::from).collect();
// line_bg stays stale until the next full rebuild;
// reopening file view (Esc → Enter) refreshes it.
// Clamp cursor so a shortened file doesn't point past
// the end.
let max = fv.lines.len().saturating_sub(1);
if fv.cursor > max {
fv.cursor = max;
}
}
}
}
/// Find the layout row that renders the given new-file line
/// (1-indexed) in the file whose **absolute** path matches `abs`.
/// Returns `None` if the file isn't in the current diff, or the
/// line isn't currently part of any hunk's new-side window.
fn find_new_file_line_row(&self, abs: &Path, line_1indexed: usize) -> Option<usize> {
let rel = abs.strip_prefix(&self.root).unwrap_or(abs);
let file_idx = self.files.iter().position(|f| f.path == rel)?;
let DiffContent::Text(hunks) = &self.files[file_idx].content else {
return None;
};
for (hunk_idx, hunk) in hunks.iter().enumerate() {
let mut new_line = hunk.new_start;
for (offset, dl) in hunk.lines.iter().enumerate() {
if matches!(dl.kind, LineKind::Deleted) {
continue;
}
if new_line == line_1indexed {
return self.layout.rows.iter().position(|r| {
matches!(
r,
RowKind::DiffLine {
file_idx: f,
hunk_idx: hi,
line_idx: li,
} if *f == file_idx && *hi == hunk_idx && *li == offset,
)
});
}
new_line += 1;
}
}
None
}
/// Content identity of the cursor's current row, when (and only
/// when) it's on a `RowKind::DiffLine`. Returns `(absolute_path,
/// new_file_line)` so it can be fed back into
/// [`Self::find_new_file_line_row`] /
/// [`Self::find_nearest_new_file_line_row`] after a layout
/// rebuild. Distinct from [`Self::scar_target_line`] which also
/// covers hunk headers and file-view; this one intentionally
/// returns `None` on any non-DiffLine row so callers can
/// detect "we were on a specific line" versus "we were on a
/// structural row".
fn scroll_cursor_new_line(&self) -> Option<(PathBuf, usize)> {
let row = self.layout.rows.get(self.scroll)?;
let RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} = *row
else {
return None;
};
let file = self.files.get(file_idx)?;
let DiffContent::Text(hunks) = &file.content else {
return None;
};
let hunk = hunks.get(hunk_idx)?;
let mut new_line = hunk.new_start;
for (i, dl) in hunk.lines.iter().enumerate() {
if i == line_idx {
return Some((self.root.join(&file.path), new_line));
}
if !matches!(dl.kind, LineKind::Deleted) {
new_line += 1;
}
}
None
}
/// Layout row of the DiffLine in `abs` whose new-file line
/// number is closest to `target_line`. Breaks ties toward the
/// earliest occurrence (first hunk, earliest line within the
/// hunk). Returns `None` when the file is absent or has no
/// non-deleted lines in the diff (binary, pure-deletion hunks).
fn find_nearest_new_file_line_row(&self, abs: &Path, target_line: usize) -> Option<usize> {
let rel = abs.strip_prefix(&self.root).unwrap_or(abs);
let file_idx = self.files.iter().position(|f| f.path == rel)?;
let DiffContent::Text(hunks) = &self.files[file_idx].content else {
return None;
};
let mut best: Option<(usize, usize, usize)> = None; // (distance, hunk_idx, line_idx)
for (hunk_idx, hunk) in hunks.iter().enumerate() {
let mut new_line = hunk.new_start;
for (offset, dl) in hunk.lines.iter().enumerate() {
if matches!(dl.kind, LineKind::Deleted) {
continue;
}
let distance = new_line.abs_diff(target_line);
if best.is_none_or(|(d, _, _)| distance < d) {
best = Some((distance, hunk_idx, offset));
}
new_line += 1;
}
}
let (_, hunk_idx, line_idx) = best?;
self.layout.rows.iter().position(|r| {
matches!(
r,
RowKind::DiffLine {
file_idx: f,
hunk_idx: h,
line_idx: l,
} if *f == file_idx && *h == hunk_idx && *l == line_idx,
)
})
}
/// Reverse the most recent scar insertion on the session's undo
/// stack. No-op when the stack is empty. If the target file has
/// been edited such that the captured line no longer matches,
/// the op is popped (so repeated `u` presses walk further back)
/// and an informational message is placed on `last_error`.
pub fn undo_scar(&mut self) {
let Some(entry) = self.scar_undo_stack.pop() else {
return;
};
match crate::scar::remove_scar(&entry.path, entry.line_1indexed, &entry.rendered) {
Ok(crate::scar::ScarRemove::Removed) => {
// The scar is gone; focus the line that now sits at
// its old position (the code the scar was annotating).
self.refresh_after_scar_write(Some((entry.path.clone(), entry.line_1indexed)));
}
Ok(crate::scar::ScarRemove::Mismatch) => {
self.last_error = Some(format!(
"undo: line {} in {} was edited — skipped",
entry.line_1indexed,
entry.path.display(),
));
}
Ok(crate::scar::ScarRemove::OutOfRange) => {
self.last_error = Some(format!(
"undo: {} has fewer than {} lines — skipped",
entry.path.display(),
entry.line_1indexed,
));
}
Err(err) => {
self.last_error = Some(format!("undo: {err:#}"));
}
}
}
/// Toggle the "seen" mark on the hunk the cursor is currently
/// inside. No-op when the cursor is on a file header, spacer,
/// binary notice, or any other row with no enclosing hunk.
/// Pure state change — nothing is written to disk (the mark
/// lives only for the session, see plans/v0.2.md M4).
pub fn toggle_seen_current_hunk(&mut self) {
let Some((file_idx, hunk_idx)) = self.current_hunk() else {
return;
};
let Some(file) = self.files.get(file_idx) else {
return;
};
let DiffContent::Text(hunks) = &file.content else {
return;
};
let Some(hunk) = hunks.get(hunk_idx) else {
return;
};
let key = (file.path.clone(), hunk.old_start);
if !self.seen_hunks.remove(&key) {
self.seen_hunks.insert(key);
}
}
/// Open the full-file zoom view for the cursor's current hunk.
/// Reads the worktree file, builds a line_bg map from diff
/// hunks, and parks the viewport so the **cursor's current
/// new-file line** is visible (not the hunk header). That way
/// zooming into a hunk keeps the reader on whatever row they
/// were already inspecting instead of snapping back to the top
/// of the hunk. No-op when the cursor is not on a text hunk,
/// or the file cannot be read.
pub fn open_file_view(&mut self) {
use ratatui::style::Color;
use std::collections::HashMap;
let Some((file_idx, _hunk_idx)) = self.current_hunk() else {
return;
};
let Some(file) = self.files.get(file_idx) else {
return;
};
let DiffContent::Text(hunks) = &file.content else {
return;
};
let abs = self.root.join(&file.path);
let content = match std::fs::read_to_string(&abs) {
Ok(c) => c,
Err(e) => {
self.last_error = Some(format!("file view: {e}"));
return;
}
};
let lines: Vec<String> = content.lines().map(String::from).collect();
let mut line_bg: HashMap<usize, Color> = HashMap::new();
for hunk in hunks {
let mut new_line = hunk.new_start; // 1-indexed
for dl in &hunk.lines {
match dl.kind {
LineKind::Added => {
if new_line >= 1 && (new_line - 1) < lines.len() {
line_bg.insert(new_line - 1, self.config.colors.bg_added_color());
}
new_line += 1;
}
LineKind::Context => {
new_line += 1;
}
LineKind::Deleted => {
// Deleted lines don't exist in the worktree;
// they're not rendered in file view.
}
}
}
}
// Inherit the cursor's current new-file line instead of
// snapping to the hunk header: `scar_target_line` already
// does this mapping (DiffLine → new-file line, HunkHeader →
// first changed line). Fall back to the hunk's `new_start`
// when the cursor is on a row with no mapping, e.g. a file
// header.
let target_1indexed = self
.scar_target_line()
.map(|(_, line)| line)
.or_else(|| {
self.current_hunk()
.and_then(|(_, hi)| hunks.get(hi))
.map(|h| h.new_start)
})
.unwrap_or(1);
let initial_cursor = target_1indexed
.saturating_sub(1)
.min(lines.len().saturating_sub(1));
let scroll_top = initial_cursor.saturating_sub(self.last_body_height.get() / 2);
self.file_view = Some(FileViewState {
path: file.path.clone(),
return_scroll: self.scroll,
lines,
line_bg,
cursor: initial_cursor,
scroll_top,
anim: None,
visual_top: scroll_top as f32,
});
}
/// Close the file view and restore the normal-mode cursor to
/// the position it was at when the user entered.
pub fn close_file_view(&mut self) {
if let Some(state) = self.file_view.take() {
self.scroll_to(state.return_scroll);
}
}
/// Keystroke handler for the file-view zoom mode. Supports
/// `Enter`/`Esc` to exit, `j`/`k`/`J`/`K` for cursor
/// movement, `g`/`G` for top/bottom, and `q` to quit.
fn handle_file_view_key(&mut self, key: KeyEvent) -> KeyEffect {
if matches!(key.code, KeyCode::Char('q'))
|| (matches!(key.code, KeyCode::Char('c'))
&& key.modifiers.contains(KeyModifiers::CONTROL))
{
self.should_quit = true;
return KeyEffect::None;
}
// Same sticky-focus discipline as normal mode: every keypress
// drops the scar-focus pin; scar action keys re-establish it.
self.clear_scar_focus_on_nav();
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('d') => {
self.file_view_scroll_by(HALF_PAGE as isize, true);
return KeyEffect::None;
}
KeyCode::Char('u') => {
self.file_view_scroll_by(-(HALF_PAGE as isize), true);
return KeyEffect::None;
}
_ => {}
}
}
match key.code {
KeyCode::Enter | KeyCode::Esc => self.close_file_view(),
// j/k: chunk scroll (viewport/3), matching normal-mode
// adaptive-motion feel. J/K: exact 1-row move.
KeyCode::Char('j') | KeyCode::Down => {
let chunk = self.chunk_size() as isize;
self.file_view_scroll_by(chunk, true);
}
KeyCode::Char('k') | KeyCode::Up => {
let chunk = self.chunk_size() as isize;
self.file_view_scroll_by(-chunk, true);
}
KeyCode::Char('J') => {
self.file_view_scroll_by(1, false);
}
KeyCode::Char('K') => {
self.file_view_scroll_by(-1, false);
}
KeyCode::Char('g') => {
self.file_view_goto(0);
}
KeyCode::Char('G') => {
let last = self
.file_view
.as_ref()
.map(|fv| fv.lines.len().saturating_sub(1))
.unwrap_or(0);
self.file_view_goto(last);
}
KeyCode::Char('e') => {
// Open external editor at the file-view cursor's
// 1-indexed line. Uses the same path stored in
// FileViewState so the editor opens the exact file.
let env = std::env::var("EDITOR").ok();
if let Some(fv) = self.file_view.as_ref() {
let line_1indexed = fv.cursor + 1;
let abs = self.root.join(&fv.path);
if let Some(inv) = build_editor_invocation(env.as_deref(), line_1indexed, &abs)
{
return KeyEffect::OpenEditor(inv);
}
}
}
// Scar operations reuse the diff-view handlers, which
// already consult `scar_target_line()` — and that function
// is now file-view aware. Config bindings apply (so a user
// who remaps `ask` to `A` gets the new key here too).
KeyCode::Char(ch) => {
let k = &self.config.keys;
if ch == k.ask {
self.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
} else if ch == k.reject {
self.insert_canned_scar(ScarKind::Reject, SCAR_TEXT_REJECT);
} else if ch == k.comment {
self.open_scar_comment();
} else if ch == k.undo {
self.undo_scar();
}
}
_ => {}
}
KeyEffect::None
}
fn file_view_scroll_by(&mut self, delta: isize, animate: bool) {
let Some(fv) = self.file_view.as_mut() else {
return;
};
let max = fv.lines.len().saturating_sub(1);
let new = (fv.cursor as isize + delta).clamp(0, max as isize) as usize;
fv.cursor = new;
let vh = self.last_body_height.get();
let old_top = fv.scroll_top;
if fv.cursor < fv.scroll_top {
fv.scroll_top = fv.cursor;
} else if fv.cursor >= fv.scroll_top + vh {
fv.scroll_top = fv.cursor.saturating_sub(vh - 1);
}
if animate && fv.scroll_top != old_top {
fv.anim = Some(ScrollAnim {
from: fv.visual_top,
start: Instant::now(),
dur: SCROLL_ANIM_DURATION,
});
} else if !animate {
// Snap: clear any in-flight animation (J/K 1-row moves).
fv.anim = None;
fv.visual_top = fv.scroll_top as f32;
}
}
/// Advance the file-view scroll animation by one frame.
/// Updates `visual_top` and clears `anim` when the tween finishes.
pub fn tick_file_view_anim(&mut self) {
let Some(fv) = self.file_view.as_mut() else {
return;
};
let Some(anim) = &fv.anim else {
return;
};
let (v, done) = anim.sample(fv.scroll_top as f32, Instant::now());
fv.visual_top = v;
if done {
fv.anim = None;
}
}
fn file_view_goto(&mut self, line: usize) {
let Some(fv) = self.file_view.as_mut() else {
return;
};
let max = fv.lines.len().saturating_sub(1);
fv.cursor = line.min(max);
let vh = self.last_body_height.get();
if fv.cursor < fv.scroll_top {
fv.scroll_top = fv.cursor;
} else if fv.cursor >= fv.scroll_top + vh {
fv.scroll_top = fv.cursor.saturating_sub(vh - 1);
}
// g/G are instant jumps — no animation.
fv.anim = None;
fv.visual_top = fv.scroll_top as f32;
}
/// Enter the `/` search-query composer. Any previously
/// confirmed [`SearchState`] is left untouched until the user
/// actually commits the new query with Enter — Esc restores
/// everything, vim-style.
pub fn open_search_input(&mut self) {
self.search_input = Some(SearchInputState::default());
}
/// Abort the query composer without touching confirmed state.
pub fn close_search_input(&mut self) {
self.search_input = None;
}
/// Commit the composed query: run [`find_matches`] against the
/// current layout, install the resulting `SearchState`, and
/// jump the cursor to the first match (if any). Empty queries
/// close the composer without touching confirmed state so a
/// stray `/` + `Enter` does not wipe an existing search.
pub fn commit_search_input(&mut self) {
let Some(input) = self.search_input.take() else {
return;
};
let query = input.query;
if query.is_empty() {
return;
}
let matches = find_matches(&self.layout, &self.files, &query);
let first_row = matches.first().map(|m| m.row);
self.search = Some(SearchState {
query,
matches,
current: 0,
});
if let Some(row) = first_row {
self.follow_mode = false;
self.scroll_to(row);
}
}
/// `/`-composer keystroke handler. Typing appends, Backspace
/// deletes, Enter commits, Esc cancels. Ctrl-C also cancels
/// (matches the other modal overlays).
fn handle_search_input_key(&mut self, key: KeyEvent) {
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('c') => self.close_search_input(),
KeyCode::Char('a') => {
if let Some(s) = self.search_input.as_mut() {
s.cursor_pos = 0;
}
}
KeyCode::Char('e') => {
if let Some(s) = self.search_input.as_mut() {
s.cursor_pos = s.query.chars().count();
}
}
_ => {}
}
return;
}
match key.code {
KeyCode::Esc => self.close_search_input(),
KeyCode::Enter => self.commit_search_input(),
KeyCode::Backspace => {
if let Some(s) = self.search_input.as_mut() {
edit_backspace(&mut s.query, &mut s.cursor_pos);
}
}
KeyCode::Left => {
if let Some(s) = self.search_input.as_mut() {
s.cursor_pos = s.cursor_pos.saturating_sub(1);
}
}
KeyCode::Right => {
if let Some(s) = self.search_input.as_mut() {
s.cursor_pos = (s.cursor_pos + 1).min(s.query.chars().count());
}
}
KeyCode::Home => {
if let Some(s) = self.search_input.as_mut() {
s.cursor_pos = 0;
}
}
KeyCode::End => {
if let Some(s) = self.search_input.as_mut() {
s.cursor_pos = s.query.chars().count();
}
}
KeyCode::Char(c) => {
if let Some(s) = self.search_input.as_mut() {
edit_insert_char(&mut s.query, &mut s.cursor_pos, c);
}
}
_ => {}
}
}
/// `n` — advance to the next confirmed search hit and jump the
/// cursor to its row. Wraps around at the end. No-op when
/// there is no confirmed search or it has zero matches.
pub fn search_jump_next(&mut self) {
let Some(state) = self.search.as_mut() else {
return;
};
if state.matches.is_empty() {
return;
}
state.current = (state.current + 1) % state.matches.len();
let row = state.matches[state.current].row;
self.follow_mode = false;
self.scroll_to(row);
}
/// `N` — step back to the previous confirmed search hit,
/// wrapping to the tail at the start.
pub fn search_jump_prev(&mut self) {
let Some(state) = self.search.as_mut() else {
return;
};
if state.matches.is_empty() {
return;
}
state.current = if state.current == 0 {
state.matches.len() - 1
} else {
state.current - 1
};
let row = state.matches[state.current].row;
self.follow_mode = false;
self.scroll_to(row);
}
/// Read helper: does `(file_idx, hunk_idx)` currently carry a
/// "seen" mark? Used by the renderer to decorate the hunk
/// header without learning the fingerprint scheme.
pub fn hunk_is_seen(&self, file_idx: usize, hunk_idx: usize) -> bool {
let Some(file) = self.files.get(file_idx) else {
return false;
};
let DiffContent::Text(hunks) = &file.content else {
return false;
};
let Some(hunk) = hunks.get(hunk_idx) else {
return false;
};
is_hunk_seen(&self.seen_hunks, &file.path, hunk.old_start)
}
/// Resolve the cursor's current target (path + 1-indexed line)
/// into an [`EditorInvocation`], reading the user's `$EDITOR`
/// preference from `editor_env`. Returns `None` when the cursor
/// is not on a scar-able row **or** the environment has no
/// editor configured — in either case the `e` key should be a
/// silent no-op.
pub fn open_in_editor(&self, editor_env: Option<&str>) -> Option<EditorInvocation> {
if self.view_mode == ViewMode::Stream {
return None;
}
let (path, line) = self.scar_target_line()?;
build_editor_invocation(editor_env, line, &path)
}
/// Enter the hunk-revert confirmation overlay. No-op when the
/// cursor is not inside a diff hunk (file headers, spacers,
/// binary notices) or when the enclosing file is not text.
pub fn open_revert_confirm(&mut self) {
if self.view_mode == ViewMode::Stream {
return;
}
let Some((file_idx, hunk_idx)) = self.current_hunk() else {
return;
};
let Some(file) = self.files.get(file_idx) else {
return;
};
let DiffContent::Text(hunks) = &file.content else {
return;
};
let Some(hunk) = hunks.get(hunk_idx) else {
return;
};
self.revert_confirm = Some(RevertConfirmState {
file_idx,
hunk_idx,
file_path: file.path.clone(),
hunk_old_start: hunk.old_start,
});
}
/// Abort the revert overlay without touching the worktree.
pub fn close_revert_confirm(&mut self) {
self.revert_confirm = None;
}
/// Commit the revert: build a single-hunk patch from the
/// captured `(file_idx, hunk_idx)` and run
/// `git apply --reverse`. Closes the overlay unconditionally;
/// write failures surface on `last_error` with the `revert:`
/// prefix so the footer flags them.
pub fn confirm_revert(&mut self) {
let Some(state) = self.revert_confirm.take() else {
return;
};
// Re-resolve the hunk by stable identity (path + old_start)
// instead of trusting the saved indices, which may have
// drifted after a watcher-driven refresh.
let hunk = self
.files
.iter()
.find(|f| f.path == state.file_path)
.and_then(|f| match &f.content {
DiffContent::Text(hunks) => {
hunks.iter().find(|h| h.old_start == state.hunk_old_start)
}
_ => None,
});
let Some(hunk) = hunk else {
self.last_error = Some("revert: hunk no longer present".into());
return;
};
let patch = git::build_hunk_patch(&state.file_path, hunk);
if let Err(err) = git::revert_hunk(&self.root, &patch) {
self.last_error = Some(format!("revert: {err:#}"));
}
}
/// Keystroke handler for the revert confirmation overlay.
/// `y` / `Y` / `Enter` confirms; every other key (including
/// `n` / `N` / `Esc` and stray navigation keys) cancels. This
/// is intentional — the overlay is a hard "did you mean to do
/// this?" gate, and any ambiguous input should bias toward
/// "no" so the user's work is preserved.
fn handle_revert_confirm_key(&mut self, key: KeyEvent) {
if key.modifiers.contains(KeyModifiers::CONTROL) {
self.close_revert_confirm();
return;
}
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => self.confirm_revert(),
_ => self.close_revert_confirm(),
}
}
/// Keystroke handler used while the scar-comment overlay is
/// active. Typing characters appends to the body, Backspace
/// deletes one char, Enter commits, Esc cancels.
/// Handle pasted text (from bracketed paste or IME commit).
/// Routes to whichever text-input overlay is currently active.
/// No-op when no text input is open — stray pastes in normal
/// mode are silently ignored.
pub fn handle_paste(&mut self, text: &str) {
if let Some(state) = self.scar_comment.as_mut() {
edit_insert_str(&mut state.body, &mut state.cursor_pos, text);
} else if let Some(state) = self.search_input.as_mut() {
edit_insert_str(&mut state.query, &mut state.cursor_pos, text);
}
}
fn handle_scar_comment_key(&mut self, key: KeyEvent) {
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('c') => self.close_scar_comment(),
KeyCode::Char('a') => {
if let Some(s) = self.scar_comment.as_mut() {
s.cursor_pos = 0;
}
}
KeyCode::Char('e') => {
if let Some(s) = self.scar_comment.as_mut() {
s.cursor_pos = s.body.chars().count();
}
}
_ => {}
}
return;
}
match key.code {
KeyCode::Esc => self.close_scar_comment(),
KeyCode::Enter => self.commit_scar_comment(),
KeyCode::Backspace => {
if let Some(s) = self.scar_comment.as_mut() {
edit_backspace(&mut s.body, &mut s.cursor_pos);
}
}
KeyCode::Left => {
if let Some(s) = self.scar_comment.as_mut() {
s.cursor_pos = s.cursor_pos.saturating_sub(1);
}
}
KeyCode::Right => {
if let Some(s) = self.scar_comment.as_mut() {
s.cursor_pos = (s.cursor_pos + 1).min(s.body.chars().count());
}
}
KeyCode::Home => {
if let Some(s) = self.scar_comment.as_mut() {
s.cursor_pos = 0;
}
}
KeyCode::End => {
if let Some(s) = self.scar_comment.as_mut() {
s.cursor_pos = s.body.chars().count();
}
}
KeyCode::Char(c) => {
if let Some(s) = self.scar_comment.as_mut() {
edit_insert_char(&mut s.body, &mut s.cursor_pos, c);
}
}
_ => {}
}
}
/// Resolve the cursor's current row to an absolute file path and a
/// 1-indexed **new-file** line number, suitable for
/// [`crate::scar::insert_scar`].
///
/// - Returns `None` when the cursor is parked on a row that has no
/// scar-able location: file headers (they point at a whole file,
/// not a specific line), spacers, binary notices, or files whose
/// content is binary / truncated.
/// - For a cursor on a **hunk header** row, returns the hunk's
/// `new_start` so `insert_scar` drops the scar immediately above
/// the first line of the hunk body. This is what the user wants
/// when they hit `a` / `r` with the cursor on the `@@` header
/// of a multi-line hunk: one scar that annotates the whole block.
/// - For a cursor on an **Added or Context line**, returns the
/// new-file line number of that line itself. The scar lands
/// directly above it, matching the "comment above the code"
/// convention.
/// - For a cursor on a **Deleted line**, the line has no new-file
/// position; we return the new-file line number of the next
/// non-deleted line in the same hunk (i.e. the line that
/// effectively "replaces" it). If the deleted run reaches the
/// hunk tail we fall through to the same offset, which matches
/// "insert the scar right after the deletion block".
pub fn scar_target_line(&self) -> Option<(PathBuf, usize)> {
// File-view override: when the user is zoomed into a whole file,
// the cursor addresses a direct worktree line. Every line is
// scar-able, so there's no hunk/deletion mapping to do — just
// return `(path, cursor + 1)` (1-indexed).
if let Some(fv) = &self.file_view {
return Some((self.root.join(&fv.path), fv.cursor + 1));
}
let row = self.layout.rows.get(self.scroll)?;
let (file_idx, hunk_idx, diff_line_idx) = match *row {
RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} => (file_idx, hunk_idx, Some(line_idx)),
RowKind::HunkHeader { file_idx, hunk_idx } => (file_idx, hunk_idx, None),
_ => return None,
};
let file = self.files.get(file_idx)?;
let DiffContent::Text(hunks) = &file.content else {
return None;
};
let hunk = hunks.get(hunk_idx)?;
// Hunk header cursor: target the first *changed* line (Added
// or Deleted) in the hunk, skipping leading Context lines. If
// the hunk is all-context (unlikely but possible in corner
// cases), fall back to `new_start`. This places the scar
// directly above the change rather than above distant context.
let Some(line_idx) = diff_line_idx else {
for (offset, dl) in hunk.lines.iter().enumerate() {
if !matches!(dl.kind, LineKind::Context) {
return Some((self.root.join(&file.path), hunk.new_start + offset));
}
}
return Some((self.root.join(&file.path), hunk.new_start));
};
// Diff line cursor: walk to compute the new-file line number.
let mut offset: usize = 0;
for (i, line) in hunk.lines.iter().enumerate() {
if i > line_idx {
break;
}
let is_deleted = matches!(line.kind, LineKind::Deleted);
if i == line_idx {
return Some((self.root.join(&file.path), hunk.new_start + offset));
}
if !is_deleted {
offset += 1;
}
}
None
}
/// `(start, end_exclusive)` row range of the cursor's current hunk.
/// Walks `layout.rows` from the start of the hunk header through
/// every consecutive `DiffLine` belonging to the same hunk. Returns
/// `None` when the cursor is not inside a hunk.
pub fn current_hunk_range(&self) -> Option<(usize, usize)> {
let (file_idx, hunk_idx) = self.current_hunk()?;
let mut start = None;
let mut end = None;
for (i, row) in self.layout.rows.iter().enumerate() {
let belongs = match row {
RowKind::HunkHeader {
file_idx: f,
hunk_idx: h,
} => *f == file_idx && *h == hunk_idx,
RowKind::DiffLine {
file_idx: f,
hunk_idx: h,
..
} => *f == file_idx && *h == hunk_idx,
_ => false,
};
if belongs {
if start.is_none() {
start = Some(i);
}
end = Some(i + 1);
} else if start.is_some() {
// Already walked past the hunk's last row.
break;
}
}
Some((start?, end?))
}
/// Where the renderer should park the viewport top, given a body
/// height. Both placement modes prefer to anchor on the cursor's
/// *whole hunk* when it fits in the viewport, so you always see
/// the full selected change as one block.
///
/// - `Centered` + short hunk: centre the hunk in the viewport,
/// breathing room above and below.
/// - `Top` + short hunk: pin the hunk's **first** row (its
/// header) to the viewport ceiling, so the whole hunk body
/// flows downward from the top into the rest of the viewport.
/// - Either mode + long hunk: fall back to the placement's raw
/// cursor-row rule (centred or ceiling-pinned), which is the
/// correct behaviour while the user is walking through a hunk
/// that can't fit in one screen.
pub fn viewport_top(&self, viewport_height: usize) -> usize {
let total = self.layout.rows.len();
if total <= viewport_height {
return 0;
}
let max_top = total - viewport_height;
// Viewport pin: keep the cursor at the screen row captured by
// the most recent `apply_computed_files`. Overrides both the
// hunk-fit anchoring and the placement-mode cursor rule.
if let Some(pinned_y) = self.pinned_cursor_y {
return self.scroll.saturating_sub(pinned_y).min(max_top);
}
if let Some((hunk_top, hunk_end)) = self.current_hunk_range() {
let hunk_size = hunk_end - hunk_top;
if hunk_size <= viewport_height {
let raw = match self.cursor_placement {
CursorPlacement::Centered => {
let pad = (viewport_height - hunk_size) / 2;
hunk_top.saturating_sub(pad)
}
CursorPlacement::Top => hunk_top,
};
return raw.min(max_top);
}
}
// Long hunk, or cursor parked on a non-hunk row → fall back
// to the placement's raw cursor-row rule.
self.cursor_placement
.viewport_top(self.scroll, total, viewport_height)
}
// ---- layout build / anchor ----------------------------------------
fn populate_mtimes(&self, files: &mut [FileDiff]) {
// Single `now` sample shared across every deleted file in this
// batch so that a mixed edit+delete burst keeps the destructive
// action at the top of the recency order (= bottom of the
// ascending layout, which is where follow mode parks). A deleted
// file has no on-disk mtime to read — the filesystem lookup
// would fail and the pre-fix fallback pushed it to UNIX_EPOCH,
// burying the delete under every real change.
let now = SystemTime::now();
for f in files {
if matches!(f.status, FileStatus::Deleted) {
f.mtime = now;
continue;
}
f.mtime = self
.root
.join(&f.path)
.metadata()
.and_then(|m| m.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
}
}
pub(crate) fn build_layout(&mut self) {
let mut layout = ScrollLayout {
file_first_hunk: vec![None; self.files.len()],
..ScrollLayout::default()
};
for (file_idx, file) in self.files.iter().enumerate() {
let header_row = layout.rows.len();
layout.rows.push(RowKind::FileHeader { file_idx });
match &file.content {
DiffContent::Binary => {
let notice_row = layout.rows.len();
layout.rows.push(RowKind::BinaryNotice { file_idx });
layout.file_first_hunk[file_idx] = Some(notice_row);
}
DiffContent::Text(hunks) => {
if hunks.is_empty() {
// Treat the file header itself as the anchor row when
// there are no hunks at all (extremely rare in
// practice; happens for empty `git diff` payloads).
layout.file_first_hunk[file_idx] = Some(header_row);
} else {
let first_hunk_row = layout.rows.len();
layout.file_first_hunk[file_idx] = Some(first_hunk_row);
for (hunk_idx, hunk) in hunks.iter().enumerate() {
let row = layout.rows.len();
layout.rows.push(RowKind::HunkHeader { file_idx, hunk_idx });
layout.hunk_starts.push(row);
for line_idx in 0..hunk.lines.len() {
layout.rows.push(RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
});
}
}
}
}
}
layout.rows.push(RowKind::Spacer);
}
// Fill the file_of_row map by walking rows once.
layout.file_of_row = layout
.rows
.iter()
.scan(0usize, |last_file, row| {
let f = match row {
RowKind::FileHeader { file_idx } => *file_idx,
RowKind::HunkHeader { file_idx, .. } => *file_idx,
RowKind::DiffLine { file_idx, .. } => *file_idx,
RowKind::BinaryNotice { file_idx } => *file_idx,
RowKind::Spacer => *last_file,
};
*last_file = f;
Some(f)
})
.collect();
// Detect change-run spans: a "change run" is a maximal contiguous
// range of `+`/`-` DiffLine rows. We record `(start, end_exclusive)`
// pairs; `J`/`K` use these to know when they are *inside* a run
// (and should scroll within it) versus *between* runs (and should
// jump to the next/prev run).
let mut current_run_start: Option<usize> = None;
for (row_idx, row) in layout.rows.iter().enumerate() {
let is_change = match row {
RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} => match &self.files[*file_idx].content {
DiffContent::Text(hunks) => {
hunks[*hunk_idx].lines[*line_idx].kind != LineKind::Context
}
DiffContent::Binary => false,
},
_ => false,
};
match (is_change, current_run_start) {
(true, None) => {
current_run_start = Some(row_idx);
}
(false, Some(start)) => {
layout.change_runs.push((start, row_idx));
current_run_start = None;
}
_ => {}
}
}
if let Some(start) = current_run_start {
layout.change_runs.push((start, layout.rows.len()));
}
self.layout = layout;
}
/// Slide `scroll` to the row of `self.anchor` in the new layout.
/// In follow mode (or when the anchor is gone) re-anchor to the
/// follow target instead.
pub(crate) fn refresh_anchor(&mut self) {
if self.layout.rows.is_empty() {
self.scroll = 0;
self.anchor = None;
return;
}
if !self.follow_mode {
if let Some(anchor) = self.anchor.clone() {
if let Some(row) = self.find_anchor_row(&anchor) {
self.scroll = row;
return;
}
if let Some(row) = self.find_anchor_file_row(&anchor) {
self.scroll = row;
self.update_anchor_from_scroll();
return;
}
}
// Manual mode should preserve the user's approximate viewport
// position even when the anchored file disappeared entirely.
// Falling back to follow mode here would silently violate the
// "manual" contract and snap to the newest file.
self.scroll = self.scroll.min(self.last_row_index());
self.update_anchor_from_scroll();
return;
}
// Follow-mode (or anchor missing): jump to the follow target.
if let Some(target) = self.follow_target_row() {
self.scroll = target;
} else {
self.scroll = 0;
}
self.update_anchor_from_scroll();
}
fn find_anchor_row(&self, anchor: &HunkAnchor) -> Option<usize> {
// Find the file index for the anchor path.
let file_idx = self.files.iter().position(|f| f.path == anchor.path)?;
// Walk the file's hunks to find one whose old_start matches.
match &self.files[file_idx].content {
DiffContent::Text(hunks) => {
let target_hunk = hunks
.iter()
.position(|h| h.old_start == anchor.hunk_old_start)?;
// Now walk the layout to find the matching HunkHeader row.
self.layout.rows.iter().position(|row| {
matches!(
row,
RowKind::HunkHeader { file_idx: f, hunk_idx } if *f == file_idx && *hunk_idx == target_hunk
)
})
}
DiffContent::Binary => self.layout.file_first_hunk.get(file_idx).copied().flatten(),
}
}
fn find_anchor_file_row(&self, anchor: &HunkAnchor) -> Option<usize> {
let file_idx = self.files.iter().position(|f| f.path == anchor.path)?;
match &self.files[file_idx].content {
DiffContent::Text(hunks) if !hunks.is_empty() => {
let nearest_hunk = hunks
.iter()
.enumerate()
.min_by_key(|(_, hunk)| hunk.old_start.abs_diff(anchor.hunk_old_start))
.map(|(idx, _)| idx)?;
self.layout.rows.iter().position(|row| {
matches!(
row,
RowKind::HunkHeader { file_idx: f, hunk_idx } if *f == file_idx && *hunk_idx == nearest_hunk
)
})
}
_ => self
.layout
.file_first_hunk
.get(file_idx)
.copied()
.flatten()
.or_else(|| {
self.layout.rows.iter().position(|row| {
matches!(
row,
RowKind::FileHeader { file_idx: f } if *f == file_idx
)
})
}),
}
}
fn update_anchor_from_scroll(&mut self) {
let Some(row) = self.layout.rows.get(self.scroll) else {
self.anchor = None;
return;
};
let (file_idx, hunk_idx) = match row {
RowKind::HunkHeader { file_idx, hunk_idx } => (*file_idx, Some(*hunk_idx)),
RowKind::DiffLine {
file_idx, hunk_idx, ..
} => (*file_idx, Some(*hunk_idx)),
RowKind::BinaryNotice { file_idx } | RowKind::FileHeader { file_idx } => {
(*file_idx, None)
}
RowKind::Spacer => {
if let Some(file_idx) = self.layout.file_of_row.get(self.scroll).copied() {
(file_idx, None)
} else {
self.anchor = None;
return;
}
}
};
let path = self.files.get(file_idx).map(|f| f.path.clone());
match (path, hunk_idx) {
(Some(path), Some(hunk_idx)) => {
if let Some(file) = self.files.get(file_idx)
&& let DiffContent::Text(hunks) = &file.content
&& let Some(hunk) = hunks.get(hunk_idx)
{
self.anchor = Some(HunkAnchor {
path,
hunk_old_start: hunk.old_start,
});
}
}
(Some(path), None) => {
self.anchor = Some(HunkAnchor {
path,
hunk_old_start: 0,
});
}
(None, _) => self.anchor = None,
}
}
}
/// Async event loop. See ADR-0003 / ADR-0005.
/// Convert stream events into virtual [`FileDiff`] entries so the
/// existing scroll infrastructure can render them identically to
/// git diff output. Each event becomes one `FileDiff` with:
/// - `header_prefix`: "HH:MM:SS Tool" for display in the file header
/// - `path`: the edited file path
/// - `content`: parsed diff lines from the captured snapshot
pub fn build_stream_files(events: &[StreamEvent]) -> Vec<FileDiff> {
let mut out: Vec<FileDiff> = Vec::new();
for (i, ev) in events.iter().enumerate() {
let ts = ev.metadata.timestamp_ms;
let time_str = crate::ui::format_local_time(ts);
let tool = ev.metadata.tool_name.as_deref().unwrap_or("?");
let prefix = format!("{time_str} {tool}");
let mtime = SystemTime::UNIX_EPOCH + Duration::from_millis(ts);
// Use `file_paths` order as the stable render order so a
// multi-file tool call presents files in the order the agent
// reported them, not in the BTreeMap's sort order.
let paths: Vec<PathBuf> = if ev.metadata.file_paths.is_empty() {
// Preserve the "empty placeholder" behavior for events
// whose file_paths could not be resolved — they still
// need to be visible in the stream as a metadata row.
vec![PathBuf::new()]
} else {
ev.metadata.file_paths.clone()
};
// Space each (event, path) pair's old_start apart so hunk
// anchors (keyed on path + old_start) stay unique across
// events and paths.
for (j, path) in paths.into_iter().enumerate() {
let anchor_base = (i * 10_000) + (j * 100) + 1;
let diff_text = ev.per_file_diffs.get(&path);
let (hunks, added, deleted) = match diff_text {
Some(t) if !t.is_empty() => parse_stream_diff_to_hunk(t, anchor_base),
_ => (vec![], 0, 0),
};
out.push(FileDiff {
path,
status: git::FileStatus::Modified,
added,
deleted,
content: git::DiffContent::Text(hunks),
mtime,
header_prefix: Some(prefix.clone()),
});
}
}
out
}
/// Parse raw diff text (from a stream event snapshot) into a single
/// `Hunk` with `DiffLine` entries. Hunk header lines (`@@`) are
/// skipped; `+`/`-`/` ` prefix determines `LineKind`.
fn parse_stream_diff_to_hunk(diff_text: &str, old_start: usize) -> (Vec<git::Hunk>, usize, usize) {
let mut lines = Vec::new();
let mut added = 0usize;
let mut deleted = 0usize;
for raw in diff_text.lines() {
if raw.starts_with("@@")
|| raw.starts_with("diff ")
|| raw.starts_with("---")
|| raw.starts_with("+++")
|| raw.starts_with("index ")
{
continue;
}
let (kind, content) = if let Some(rest) = raw.strip_prefix('+') {
added += 1;
(LineKind::Added, rest.to_string())
} else if let Some(rest) = raw.strip_prefix('-') {
deleted += 1;
(LineKind::Deleted, rest.to_string())
} else if let Some(rest) = raw.strip_prefix(' ') {
(LineKind::Context, rest.to_string())
} else {
(LineKind::Context, raw.to_string())
};
lines.push(git::DiffLine {
kind,
content,
has_trailing_newline: true,
});
}
if lines.is_empty() {
return (vec![], 0, 0);
}
let hunk = git::Hunk {
old_start,
old_count: deleted,
new_start: old_start,
new_count: added,
lines,
context: None,
};
(vec![hunk], added, deleted)
}
/// Compute the "operation diff" — the lines in `current` that were
/// not already present in `previous`, counted as a **multiset** so
/// duplicate lines (e.g. two blank `+` lines, or two identical
/// closing-brace context rows) survive when `current` has more copies
/// than `previous`.
///
/// This is not a true diff-of-diff — hunk boundaries, line numbers,
/// and ordering drift are ignored. In practice the cumulative
/// snapshots differ by the lines one Write/Edit operation added or
/// re-shaped, so a multiset difference gives a readable approximation.
/// Limitations and design rationale are documented in ADR-0016.
fn compute_operation_diff(previous: &str, current: &str) -> String {
use std::collections::HashMap;
let mut prev_counts: HashMap<&str, usize> = HashMap::new();
for line in previous.lines() {
*prev_counts.entry(line).or_insert(0) += 1;
}
let mut result = String::new();
for line in current.lines() {
match prev_counts.get_mut(line) {
Some(count) if *count > 0 => {
*count -= 1;
}
_ => {
result.push_str(line);
result.push('\n');
}
}
}
result
}
pub async fn run() -> Result<()> {
use std::io::Write;
let log_path = std::env::var("KIZU_STARTUP_TIMING_FILE").ok();
let stage = |label: &str, t: Instant| {
if let Some(path) = log_path.as_deref()
&& let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
let _ = writeln!(f, "[kizu-startup] {label:<28} +{:?}", t.elapsed());
}
};
let t_total = Instant::now();
let cwd = std::env::current_dir().context("reading current directory")?;
stage("current_dir", t_total);
let mut terminal = ratatui::try_init().context("initializing terminal")?;
// Enable bracketed paste so terminals send IME-committed text
// (e.g. Japanese kanji) as Event::Paste instead of individual
// keystrokes. Without this, IME composition is invisible in
// raw mode and committed text may arrive garbled.
{
use crossterm::ExecutableCommand;
let _ = std::io::stdout().execute(crossterm::event::EnableBracketedPaste);
}
stage("ratatui::try_init", t_total);
let result = async {
// Show something immediately, even before the initial bootstrap
// `git diff` completes. On large repos this avoids a black screen
// during the synchronous bootstrap shell-outs.
terminal
.draw(|frame| {
let area = frame.area();
frame.render_widget(
ratatui::widgets::Paragraph::new("Loading kizu...")
.alignment(ratatui::layout::Alignment::Center),
area,
);
})
.context("ratatui loading draw")?;
stage("draw Loading...", t_total);
let t_bootstrap = Instant::now();
let mut app = App::bootstrap(cwd)?;
stage("App::bootstrap", t_bootstrap);
// Write session file so the Stop hook can scope its scan
// to files changed since this baseline. Best-effort: a
// failure here is not fatal to the TUI itself.
if let Err(e) = crate::session::write_session(&app.root, &app.baseline_sha) {
eprintln!("warning: failed to write kizu session file: {e}");
}
// Session isolation: older events are now filtered on ingest
// via `session_start_ms` rather than by bulk-deleting the
// shared events directory. The delete path used to destroy a
// concurrently-running kizu session's live history on the
// same project; the filter approach is non-destructive.
// Diff snapshots were already seeded inside `App::bootstrap`
// from the same `git diff` that produced the initial file
// list, so the first stream event shows only the per-op
// delta without an extra startup subprocess sweep.
// Draw one static frame before watcher startup. On macOS the
// PollWatcher fallback may take noticeable time to arm because it
// performs an initial scan; showing the bootstrap snapshot first
// keeps startup feeling immediate instead of blank-screening until
// watcher init finishes.
terminal
.draw(|frame| crate::ui::render(frame, &app))
.context("ratatui initial draw")?;
stage("draw bootstrap snapshot", t_total);
let t_watcher = Instant::now();
let mut watch = watcher::start(
&app.root,
&app.git_dir,
&app.common_git_dir,
app.current_branch_ref.as_deref(),
)?;
stage("watcher::start", t_watcher);
// Replay any event files that were written in the gap
// between `clean_stale_events` and `watcher::start`. Without
// this the next event for the same file would absorb the
// dropped operation's contents into its op_diff because the
// seeded snapshot is still the pre-edit state. Dedup inside
// `handle_event_log` makes this safe even when the watcher
// later re-delivers the same file.
if let Some(events_dir) = crate::paths::events_dir(&app.root) {
app.replay_events_dir(&events_dir);
}
stage("replay startup-gap events", t_total);
let result = run_loop(&mut terminal, &mut app, &mut watch).await;
crate::session::remove_session(&app.root);
result
}
.await;
{
use crossterm::ExecutableCommand;
let _ = std::io::stdout().execute(crossterm::event::DisableBracketedPaste);
}
let _ = ratatui::try_restore();
result
}
async fn run_loop(
terminal: &mut ratatui::DefaultTerminal,
app: &mut App,
watch: &mut watcher::WatchHandle,
) -> Result<()> {
use crossterm::event::{Event, EventStream};
use futures_util::StreamExt;
use tokio::time::{MissedTickBehavior, interval, sleep};
let mut events = EventStream::new();
// ~60 fps frame tick. Only polled inside `select!` when an animation
// is live — idle frames never pay the cost. `Skip` means a long
// idle gap doesn't turn into a burst of catch-up ticks once the
// user kicks off a new animation.
let mut frame = interval(Duration::from_millis(16));
frame.set_missed_tick_behavior(MissedTickBehavior::Skip);
// notify backends can have a short arm-up window right after startup.
// Without a one-shot self-heal refresh, an edit that lands during that
// gap can be missed forever until the *next* filesystem event. The
// existing watcher tests used `sleep(150ms)` to paper over this; the app
// should instead recover on its own.
let startup_refresh = sleep(Duration::from_millis(400));
tokio::pin!(startup_refresh);
let mut startup_refresh_pending = true;
while !app.should_quit {
// Draw at the top of the loop so the bootstrap state is visible
// before we ever block on `select!`.
terminal
.draw(|frame| crate::ui::render(frame, app))
.context("ratatui draw")?;
// Retire finished animations after the frame that showed their
// final position — the next frame will then draw the static
// target without another tween sample.
app.tick_anim(Instant::now());
app.tick_file_view_anim();
tokio::select! {
event = events.next() => {
match event {
Some(Ok(Event::Key(key))) => {
app.input_health = None;
let effect = app.handle_key(key);
match effect {
KeyEffect::OpenEditor(inv) => {
if let Err(err) = run_external_editor(terminal, inv) {
app.last_error = Some(format!("editor: {err:#}"));
}
}
other => apply_key_effect(other, app, watch),
}
}
Some(Ok(Event::Paste(text))) => {
app.input_health = None;
app.handle_paste(&text);
}
Some(Ok(_)) => {
app.input_health = None;
}
Some(Err(e)) => {
app.input_health = Some(format!("input: {e}"));
}
None => {
app.input_health = Some("input: event stream ended".into());
app.should_quit = true;
}
}
}
watch_event = watch.events.recv() => {
if let Some(first) = watch_event {
startup_refresh_pending = false;
// Drain any events that piled up behind `first` and
// hand the whole burst to `handle_watch_burst` so the
// coalescing + health-transition rules stay testable
// in one place.
let mut burst: Vec<WatchEvent> = vec![first];
while let Ok(more) = watch.events.try_recv() {
burst.push(more);
}
let (need_recompute, need_head_dirty) = app.handle_watch_burst(burst);
if need_recompute {
watch.refresh_worktree_watches();
// In stream mode, don't overwrite files/layout with
// git diff — the scroll view shows stream events.
// The diff will be refreshed when the user tabs back.
if app.view_mode != ViewMode::Stream {
app.recompute_diff();
}
}
if need_head_dirty {
app.mark_head_dirty();
}
} else {
app.last_error = Some("watcher: event channel closed".into());
app.should_quit = true;
}
}
_ = &mut startup_refresh, if startup_refresh_pending => {
startup_refresh_pending = false;
if app.view_mode != ViewMode::Stream {
app.recompute_diff();
}
}
_ = frame.tick(), if app.anim.is_some() || app.file_view.as_ref().is_some_and(|fv| fv.anim.is_some()) => {
// The tick itself carries no payload — falling through
// the bottom of the select! loops back to the `draw`
// call at the top, which is the whole point.
}
}
}
Ok(())
}
/// Dispatch post-key-handler side effects back onto the watcher.
/// Factored out so `run_loop` stays focused on the event-loop
/// plumbing and tests can reason about the effect contract without
/// spinning up a real terminal.
fn apply_key_effect(effect: KeyEffect, app: &App, watch: &watcher::WatchHandle) {
match effect {
KeyEffect::None => {}
KeyEffect::ReconfigureWatcher => {
watch.update_current_branch_ref(app.current_branch_ref.as_deref());
}
KeyEffect::OpenEditor(_) => {
// Handled inline inside `run_loop`: the editor
// spawn needs mutable access to the terminal for the
// suspend/resume dance, which this `&App` /
// `&WatchHandle` helper cannot provide. Any
// `OpenEditor` that reaches this arm is a caller
// bug.
debug_assert!(
false,
"OpenEditor must be handled by run_loop, not apply_key_effect"
);
}
}
}
/// Suspend the ratatui terminal, run an external editor
/// synchronously, then re-enter the alternate screen and force a
/// full repaint on the next draw tick. Blocks the event loop for
/// the editor's lifetime — intentional, because the user is
/// inside the editor anyway and no diff-view update would be
/// visible under it.
fn run_external_editor(
terminal: &mut ratatui::DefaultTerminal,
invocation: EditorInvocation,
) -> Result<()> {
use crossterm::{
ExecutableCommand,
event::{DisableBracketedPaste, EnableBracketedPaste},
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use std::io::stdout;
// Tear down the ratatui terminal state so the child editor
// sees a plain cooked terminal. Errors here are surfaced —
// half-suspended state is worse than not launching the editor
// at all.
disable_raw_mode().context("disable raw mode before editor")?;
let mut out = stdout();
out.execute(LeaveAlternateScreen)
.context("leave alternate screen before editor")?;
out.execute(DisableBracketedPaste).ok();
let status = std::process::Command::new(&invocation.program)
.args(&invocation.args)
.status()
.with_context(|| format!("spawning editor `{}`", invocation.program));
// Always re-arm the alternate screen + raw mode even if the
// spawn itself failed. Otherwise a mistyped `$EDITOR` would
// leave the user stranded at a raw-mode prompt.
enable_raw_mode().context("re-enable raw mode after editor")?;
stdout()
.execute(EnterAlternateScreen)
.context("re-enter alternate screen after editor")?;
stdout().execute(EnableBracketedPaste).ok();
terminal.clear().ok();
let status = status?;
if !status.success() {
return Err(anyhow!(
"editor `{}` exited with status {}",
invocation.program,
status
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::git::{DiffContent, DiffLine, FileStatus, Hunk, LineKind};
use std::time::Duration;
#[test]
fn diff_snapshots_evicts_oldest_when_cap_exceeded() {
// Long agent sessions can pile up one snapshot per unique file
// touched. Without a cap the map grows unboundedly; a LRU-ish
// eviction keeps working-set size predictable. The eldest
// inserted key must be the first to go when the cap is hit.
let mut snaps = DiffSnapshots::with_cap(3);
snaps.insert(PathBuf::from("a"), "diff-a".into());
snaps.insert(PathBuf::from("b"), "diff-b".into());
snaps.insert(PathBuf::from("c"), "diff-c".into());
assert_eq!(snaps.len(), 3);
snaps.insert(PathBuf::from("d"), "diff-d".into());
assert_eq!(snaps.len(), 3, "cap must hold after overflow");
assert!(
!snaps.contains_key(&PathBuf::from("a")),
"eldest entry must be evicted first"
);
assert!(snaps.contains_key(&PathBuf::from("d")));
}
#[test]
fn diff_snapshots_reinsert_refreshes_recency() {
// When handle_event_log re-inserts the snapshot for a path it
// already knows about, that path must move to the "most
// recently used" end so a subsequent overflow drops an older
// path instead.
let mut snaps = DiffSnapshots::with_cap(3);
snaps.insert(PathBuf::from("a"), "diff-a".into());
snaps.insert(PathBuf::from("b"), "diff-b".into());
snaps.insert(PathBuf::from("c"), "diff-c".into());
// Touch "a" so it is no longer the eldest.
snaps.insert(PathBuf::from("a"), "diff-a-updated".into());
snaps.insert(PathBuf::from("d"), "diff-d".into());
assert!(
snaps.contains_key(&PathBuf::from("a")),
"recently-touched entry must survive the next overflow"
);
assert!(
!snaps.contains_key(&PathBuf::from("b")),
"after touching a, b is now the eldest and must be dropped"
);
assert_eq!(
snaps.get(&PathBuf::from("a")),
Some(&"diff-a-updated".to_string()),
"re-insert must keep the newer value",
);
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn ctrl(c: char) -> KeyEvent {
KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
}
fn diff_line(kind: LineKind, content: &str) -> DiffLine {
DiffLine {
kind,
content: content.to_string(),
has_trailing_newline: true,
}
}
fn hunk(old_start: usize, lines: Vec<DiffLine>) -> Hunk {
let added = lines.iter().filter(|l| l.kind == LineKind::Added).count();
let deleted = lines.iter().filter(|l| l.kind == LineKind::Deleted).count();
Hunk {
old_start,
old_count: deleted,
new_start: old_start,
new_count: added,
lines,
context: None,
}
}
fn make_file(name: &str, hunks: Vec<Hunk>, secs: u64) -> FileDiff {
let added: usize = hunks
.iter()
.flat_map(|h| h.lines.iter())
.filter(|l| l.kind == LineKind::Added)
.count();
let deleted: usize = hunks
.iter()
.flat_map(|h| h.lines.iter())
.filter(|l| l.kind == LineKind::Deleted)
.count();
FileDiff {
path: PathBuf::from(name),
status: FileStatus::Modified,
added,
deleted,
content: DiffContent::Text(hunks),
mtime: SystemTime::UNIX_EPOCH + Duration::from_secs(secs),
header_prefix: None,
}
}
fn binary_file(name: &str, secs: u64) -> FileDiff {
FileDiff {
path: PathBuf::from(name),
status: FileStatus::Modified,
added: 0,
deleted: 0,
content: DiffContent::Binary,
mtime: SystemTime::UNIX_EPOCH + Duration::from_secs(secs),
header_prefix: None,
}
}
/// Build an `App` against `/tmp/fake` with no real filesystem use; the
/// `populate_mtimes` step is bypassed by writing `mtime` directly on the
/// fixtures. Files are sorted in ascending mtime order to match the
/// real `recompute_diff` path.
fn fake_app(files: Vec<FileDiff>) -> App {
let mut app = App {
root: PathBuf::from("/tmp/fake"),
git_dir: PathBuf::from("/tmp/fake/.git"),
common_git_dir: PathBuf::from("/tmp/fake/.git"),
current_branch_ref: Some("refs/heads/main".into()),
baseline_sha: "abcdef1234567890abcdef1234567890abcdef12".into(),
files: Vec::new(),
layout: ScrollLayout::default(),
scroll: 0,
cursor_sub_row: 0,
cursor_placement: CursorPlacement::Centered,
anchor: None,
picker: None,
scar_comment: None,
revert_confirm: None,
file_view: None,
search_input: None,
search: None,
seen_hunks: BTreeSet::new(),
follow_mode: true,
last_error: None,
input_health: None,
head_dirty: false,
should_quit: false,
last_body_height: Cell::new(DEFAULT_BODY_HEIGHT),
last_body_width: Cell::new(None),
visual_top: Cell::new(0.0),
anim: None,
wrap_lines: false,
watcher_health: WatcherHealth::default(),
highlighter: std::cell::OnceCell::new(),
config: crate::config::KizuConfig::default(),
view_mode: ViewMode::default(),
saved_diff_scroll: 0,
saved_stream_scroll: 0,
stream_events: Vec::new(),
processed_event_paths: std::collections::HashSet::new(),
// Tests use small timestamps (1000, 2000, …) for events.
// Leave `session_start_ms` at 0 so the session-isolation
// filter in `handle_event_log` is a no-op by default;
// tests that exercise the filter set this field explicitly.
session_start_ms: 0,
bound_session_id: None,
diff_snapshots: DiffSnapshots::default(),
scar_undo_stack: Vec::new(),
scar_focus: None,
pinned_cursor_y: None,
};
app.files = files;
app.files.sort_by_key(|a| a.mtime);
app.build_layout();
app.refresh_anchor();
app
}
fn file_idx(app: &App, name: &str) -> usize {
app.files
.iter()
.position(|f| f.path == Path::new(name))
.unwrap_or_else(|| panic!("file {name} not in app.files"))
}
#[test]
fn build_layout_produces_header_then_hunks_then_spacer_per_file() {
let app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
// Expected sequence:
// FileHeader, HunkHeader, DiffLine, Spacer
assert_eq!(app.layout.rows.len(), 4);
assert!(matches!(
app.layout.rows[0],
RowKind::FileHeader { file_idx: 0 }
));
assert!(matches!(
app.layout.rows[1],
RowKind::HunkHeader {
file_idx: 0,
hunk_idx: 0
}
));
assert!(matches!(
app.layout.rows[2],
RowKind::DiffLine {
file_idx: 0,
hunk_idx: 0,
line_idx: 0
}
));
assert!(matches!(app.layout.rows[3], RowKind::Spacer));
assert_eq!(app.layout.hunk_starts, vec![1]);
assert_eq!(app.layout.file_first_hunk, vec![Some(1)]);
}
#[test]
fn build_layout_marks_binary_file_with_notice_row() {
let app = fake_app(vec![binary_file("icon.png", 100)]);
// FileHeader, BinaryNotice, Spacer
assert_eq!(app.layout.rows.len(), 3);
assert!(matches!(
app.layout.rows[1],
RowKind::BinaryNotice { file_idx: 0 }
));
assert!(app.layout.hunk_starts.is_empty());
assert_eq!(app.layout.file_first_hunk, vec![Some(1)]);
}
#[test]
fn next_hunk_jumps_across_file_boundaries() {
let app_files = vec![
// a.rs: newest, 2 hunks
make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(10, vec![diff_line(LineKind::Added, "y")]),
],
200,
),
// b.rs: older, 1 hunk
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "z")])],
100,
),
];
let mut app = fake_app(app_files);
// Three hunks total → three hunk_starts.
assert_eq!(app.layout.hunk_starts.len(), 3);
// Start at the very top.
app.scroll_to(0);
app.next_hunk();
assert_eq!(app.scroll, app.layout.hunk_starts[0]);
app.next_hunk();
assert_eq!(app.scroll, app.layout.hunk_starts[1]);
app.next_hunk();
assert_eq!(app.scroll, app.layout.hunk_starts[2]);
// Already past the last; stays put on the last.
app.next_hunk();
assert_eq!(app.scroll, app.layout.hunk_starts[2]);
}
#[test]
fn prev_hunk_walks_backwards() {
let app_files = vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(10, vec![diff_line(LineKind::Added, "y")]),
],
100,
)];
let mut app = fake_app(app_files);
let last_hunk = *app.layout.hunk_starts.last().unwrap();
app.scroll_to(last_hunk);
app.prev_hunk();
assert_eq!(app.scroll, app.layout.hunk_starts[0]);
// Already on the first; clamps.
app.prev_hunk();
assert_eq!(app.scroll, app.layout.hunk_starts[0]);
}
#[test]
fn follow_target_row_is_last_hunk_header_of_newest_file() {
// Follow mode should park on the **last hunk header** of
// the newest file so the user sees the most recent @@
// context and the diff body below it.
let app = fake_app(vec![
make_file(
"older.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "c")])],
100,
),
make_file(
"newest.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "a")]),
hunk(20, vec![diff_line(LineKind::Added, "b")]),
],
300,
),
]);
assert!(
matches!(app.layout.rows[app.scroll], RowKind::HunkHeader { .. }),
"follow target must be a HunkHeader row, got {:?}",
app.layout.rows[app.scroll]
);
// Should be the LAST hunk header (hunk at line 20), not the first.
let newest_idx = app.files.len() - 1;
let last_hunk_header = app
.layout
.rows
.iter()
.enumerate()
.rev()
.find_map(|(i, r)| match r {
RowKind::HunkHeader { file_idx, .. } if *file_idx == newest_idx => Some(i),
_ => None,
})
.expect("newest file must have a HunkHeader");
assert_eq!(app.scroll, last_hunk_header);
}
#[test]
fn follow_target_row_lands_on_hunk_header_even_for_tall_hunk() {
// Even with a 20-line hunk, follow parks on the hunk header
// so the user sees the @@ context and diff body from the top.
let huge_hunk = hunk(
1,
(0..20)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect(),
);
let app = fake_app(vec![make_file("big.rs", vec![huge_hunk], 500)]);
assert!(
matches!(app.layout.rows[app.scroll], RowKind::HunkHeader { .. }),
"follow should land on HunkHeader, got {:?}",
app.layout.rows[app.scroll]
);
}
#[test]
fn current_file_path_reports_the_file_under_the_cursor() {
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
200,
),
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
// a.rs has the larger mtime → it sorts to the bottom of the
// layout, and bootstrap follow lands on it.
assert_eq!(app.current_file_path(), Some(Path::new("a.rs")));
// Jump to b.rs's first hunk by looking it up by path so the test
// doesn't rely on a specific index.
let b = file_idx(&app, "b.rs");
app.jump_to_file_first_hunk(b);
assert_eq!(app.current_file_path(), Some(Path::new("b.rs")));
}
#[test]
fn handle_key_j_walks_changes_and_disables_follow() {
// Lowercase `j` is run-forward: from the file header it jumps
// to the first hunk's header (no hunk to look inside yet),
// then to the Added line within that hunk (the run), then to
// the next hunk. Repeatedly pressing `j` eventually crosses
// into the next hunk even without a "short hunk shortcut".
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(20, vec![diff_line(LineKind::Added, "y")]),
],
100,
)]);
app.scroll_to(0);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, app.layout.hunk_starts[0]);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, app.layout.hunk_starts[0] + 1, "walks to run");
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, app.layout.hunk_starts[1]);
assert!(!app.follow_mode);
}
#[test]
fn l_jumps_to_next_hunk_header() {
// v0.2 remap: `l` takes over the strict hunk-jump role the old
// SHIFT-J used to play. Two short hunks; pressing `l` from the
// first lands on the second; pressing `l` again stays put
// because there is no third hunk.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "alpha")]),
hunk(10, vec![diff_line(LineKind::Added, "beta")]),
],
100,
)]);
assert_eq!(app.layout.hunk_starts.len(), 2);
let first_hunk = app.layout.hunk_starts[0];
let second_hunk = app.layout.hunk_starts[1];
app.scroll_to(first_hunk);
app.handle_key(key(KeyCode::Char('l')));
assert_eq!(app.scroll, second_hunk);
assert!(!app.follow_mode);
// No more hunks after this one → stay put.
app.handle_key(key(KeyCode::Char('l')));
assert_eq!(app.scroll, second_hunk);
}
#[test]
fn lowercase_j_at_last_row_of_only_hunk_stays_put() {
// Cursor parked on the bottom-most row of a long hunk. There is
// no next hunk to walk into, so pressing `j` must be a no-op
// instead of snapping back up to the hunk's header row — the
// old `next_hunk` fallback to `hunk_starts.last()` made the
// cursor leap backward, which is the opposite of what `j`
// should mean.
let lines: Vec<DiffLine> = (0..20)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect();
let mut app = fake_app(vec![make_file("a.rs", vec![hunk(1, lines)], 100)]);
app.last_body_height.set(15);
let (_start, end) = app.layout.change_runs[0];
let last = end - 1;
app.scroll_to(last);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(
app.scroll, last,
"j at the bottom of the only change run must stay put"
);
}
#[test]
fn lowercase_j_in_long_run_chunk_scrolls_through_body() {
// Long run (20 Added lines, viewport = 15). `j` must not
// teleport past the run body — it chunk-scrolls through it so
// the user actually sees the change. Once the cursor reaches
// the run's last row, the next `j` hands off to the straight
// hunk-cross path (no trailing-context dwell).
let lines: Vec<DiffLine> = (0..20)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect();
let mut app = fake_app(vec![make_file("a.rs", vec![hunk(1, lines)], 100)]);
app.last_body_height.set(15);
let chunk = app.chunk_size();
assert_eq!(chunk, 5, "viewport=15 → chunk=5");
let (start, end) = app.layout.change_runs[0];
let last = end - 1;
app.scroll_to(start);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, start + chunk, "first `j`: chunk forward");
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, start + 2 * chunk);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, start + 3 * chunk);
// Fourth press clamps to run_end - 1 (4 * 5 = 20 > 19 span).
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, last, "clamps to last row of run");
// Fifth press: at run end, no next run, no next hunk → stay put.
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, last);
}
#[test]
fn l_crosses_hunk_and_file_boundaries() {
// v0.2 remap: `l` walks to the next hunk regardless of the
// file boundary between them. One tiny hunk per file so the
// jump has to cross from a.rs into b.rs.
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "alpha")])],
100,
),
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "beta")])],
200,
),
]);
assert_eq!(app.layout.hunk_starts.len(), 2);
let first_hunk = app.layout.hunk_starts[0];
let second_hunk = app.layout.hunk_starts[1];
app.scroll_to(first_hunk);
app.handle_key(key(KeyCode::Char('l')));
assert_eq!(
app.scroll, second_hunk,
"`l` on a short hunk must cross hunk + file boundaries"
);
}
#[test]
fn lowercase_k_in_long_run_chunk_scrolls_back_through_body() {
// Backward mirror of `lowercase_j_in_long_run_chunk_scrolls_through_body`.
// A 20-line run with viewport = 15 gives chunk = 5. `k` from
// the tail chunk-walks back until the cursor reaches the run
// start; subsequent `k` hands off to the prev-hunk pathway (no
// prev hunk here → stay put; no hunk-top dwell).
let lines: Vec<DiffLine> = (0..20)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect();
let mut app = fake_app(vec![make_file("a.rs", vec![hunk(1, lines)], 100)]);
app.last_body_height.set(15);
let chunk = app.chunk_size();
let (run_start, run_end) = app.layout.change_runs[0];
let last = run_end - 1;
app.scroll_to(last);
app.handle_key(key(KeyCode::Char('k')));
assert_eq!(app.scroll, last - chunk, "first `k`: chunk back");
app.handle_key(key(KeyCode::Char('k')));
app.handle_key(key(KeyCode::Char('k')));
app.handle_key(key(KeyCode::Char('k')));
assert_eq!(
app.scroll, run_start,
"keeps chunking back; magnet snaps to run_start once it's in range"
);
// From run_start, `k` continues chunking back toward the hunk
// header (no magnet hit, no current-run re-snap).
// At run_start: no more runs in this hunk and no prev hunk →
// `prev_hunk_last_run_start` is a no-op, cursor stays put.
// (No chunk through the hunk header — that would be stopping
// on a non-reviewable row.)
app.handle_key(key(KeyCode::Char('k')));
assert_eq!(app.scroll, run_start, "no prev hunk → stay put");
}
#[test]
fn lowercase_j_teleports_between_runs_never_landing_on_context() {
// Hunk with three separate change runs. `j` teleports straight
// from run to run — never parks the cursor on an intermediate
// Context row. ScrollAnim (not tested here) supplies the
// visual "gradual" feel via its 150ms tween.
let lines: Vec<DiffLine> = vec![
diff_line(LineKind::Added, "r1-a1"), // run 1 start
diff_line(LineKind::Deleted, "r1-d1"), // still run 1
diff_line(LineKind::Context, "ctx1"),
diff_line(LineKind::Added, "r2-a1"), // run 2 start
diff_line(LineKind::Context, "ctx2"),
diff_line(LineKind::Context, "ctx3"),
diff_line(LineKind::Context, "ctx4"),
diff_line(LineKind::Context, "ctx5"),
diff_line(LineKind::Context, "ctx6"),
diff_line(LineKind::Context, "ctx7"),
diff_line(LineKind::Context, "ctx8"),
diff_line(LineKind::Context, "ctx9"),
diff_line(LineKind::Context, "ctx10"),
diff_line(LineKind::Added, "r3-a1"), // run 3 start
diff_line(LineKind::Context, "ctx11"),
];
let mut app = fake_app(vec![make_file("a.rs", vec![hunk(1, lines)], 100)]);
app.last_body_height.set(10);
let runs: Vec<_> = app.layout.change_runs.clone();
assert_eq!(runs.len(), 3);
let hunk_top = app.layout.hunk_starts[0];
app.scroll_to(hunk_top);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, runs[0].0, "1st `j`: run 1 start");
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, runs[1].0, "2nd `j`: run 2 start");
// Run 3 is 10 rows past run 2; `j` still teleports straight to
// it, skipping all intervening Context rows.
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(
app.scroll, runs[2].0,
"3rd `j`: teleports across context directly to run 3"
);
}
#[test]
fn lowercase_j_walks_runs_even_in_short_hunk() {
// Even when the whole hunk fits on screen (viewport = 40, hunk
// is ~4 rows), `j` still walks change runs — short hunks have
// no special skip. This keeps the press count consistent with
// what the user sees needs reviewing: 2 runs = 2 landings, not
// "the hunk's small so let's just skip".
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "a1"),
diff_line(LineKind::Context, "c1"),
diff_line(LineKind::Added, "a2"),
],
)],
100,
),
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "b1")])],
200,
),
]);
app.last_body_height.set(40);
let runs = app.layout.change_runs.clone();
let second_hunk_top = app.layout.hunk_starts[1];
app.scroll_to(app.layout.hunk_starts[0]);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, runs[0].0, "1st `j`: run 1 start");
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, runs[1].0, "2nd `j`: run 2 start (same hunk)");
// 3rd press: no more runs in hunk a → crosses to hunk b's
// header. The run inside hunk b is reached on the 4th press.
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, second_hunk_top, "3rd `j`: next hunk header");
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(app.scroll, runs[2].0, "4th `j`: run in hunk 2");
}
#[test]
fn lowercase_k_at_hunk_top_lands_on_prev_hunk_last_run_start() {
// `k` at the second hunk's header must jump into the previous
// hunk — landing on the **start of its last change run**, not
// its literal last row. In this fixture the first hunk's 3
// Added lines form a single run; the run's start is the first
// Added line ("a1"), so that's the landing.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(
1,
vec![
diff_line(LineKind::Added, "a1"),
diff_line(LineKind::Added, "a2"),
diff_line(LineKind::Added, "a3"),
],
),
hunk(10, vec![diff_line(LineKind::Added, "b1")]),
],
100,
)]);
let second_hunk_top = app.layout.hunk_starts[1];
// First hunk's sole run: its start row.
let (first_hunk_last_run_start, _) = app.layout.change_runs[0];
app.scroll_to(second_hunk_top);
app.handle_key(key(KeyCode::Char('k')));
assert_eq!(
app.scroll, first_hunk_last_run_start,
"`k` crosses into prev hunk and lands on its last run's start"
);
}
#[test]
fn lowercase_k_skips_prev_hunk_trailing_context() {
// Prev hunk has a run followed by trailing context rows.
// Backward `k` must land on the RUN start, skipping the
// context that trails it — landing on the literal last row
// would park the cursor on unchanged code.
let mut lines_a: Vec<DiffLine> = vec![diff_line(LineKind::Added, "change")];
for _ in 0..5 {
lines_a.push(diff_line(LineKind::Context, "tail"));
}
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, lines_a),
hunk(20, vec![diff_line(LineKind::Added, "b1")]),
],
100,
)]);
let second_hunk_top = app.layout.hunk_starts[1];
// First hunk's sole run's start (the Added "change" row).
let (first_run_start, _) = app.layout.change_runs[0];
app.scroll_to(second_hunk_top);
app.handle_key(key(KeyCode::Char('k')));
assert_eq!(
app.scroll, first_run_start,
"`k` skips trailing context and lands on the run's start"
);
}
#[test]
fn lowercase_j_skips_trailing_context_and_crosses_to_next_hunk() {
// Hunk with a single change run followed by trailing context.
// `j` from the run's sole row crosses straight into the next
// hunk (ScrollAnim tweens the motion) — never stops on any of
// the Context rows between.
let mut lines: Vec<DiffLine> = vec![];
for _ in 0..4 {
lines.push(diff_line(LineKind::Context, "lead"));
}
lines.push(diff_line(LineKind::Added, "change"));
for _ in 0..4 {
lines.push(diff_line(LineKind::Context, "trail"));
}
let mut app = fake_app(vec![
make_file("a.rs", vec![hunk(1, lines)], 100),
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
200,
),
]);
app.last_body_height.set(10);
let (run_start, _) = app.layout.change_runs[0];
app.scroll_to(run_start);
app.handle_key(key(KeyCode::Char('j')));
assert_eq!(
app.scroll, app.layout.hunk_starts[1],
"`j` skips trailing context and crosses directly to next hunk header"
);
}
#[test]
fn h_jumps_to_previous_hunk_header() {
// v0.2 remap: `h` is the strict previous-hunk jump that the
// old SHIFT-K used to do. Two short hunks, cursor on the
// second — pressing `h` lands on the first hunk header.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "alpha")]),
hunk(10, vec![diff_line(LineKind::Added, "beta")]),
],
100,
)]);
let first_hunk = app.layout.hunk_starts[0];
let second_hunk = app.layout.hunk_starts[1];
app.scroll_to(second_hunk);
app.handle_key(key(KeyCode::Char('h')));
assert_eq!(app.scroll, first_hunk);
}
#[test]
fn shift_j_moves_cursor_down_by_exactly_one_visual_row() {
// v0.2 remap: `J` is a one-row forward cursor move, not a
// hunk jump. Starting at the file header row, `J` walks one
// row at a time (header → hunk header → first diff line).
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "one"),
diff_line(LineKind::Added, "two"),
diff_line(LineKind::Added, "three"),
],
)],
100,
)]);
app.scroll_to(0);
let before = app.scroll;
app.handle_key(key(KeyCode::Char('J')));
assert_eq!(app.scroll, before + 1);
app.handle_key(key(KeyCode::Char('J')));
assert_eq!(app.scroll, before + 2);
assert!(!app.follow_mode);
}
#[test]
fn shift_k_moves_cursor_up_by_exactly_one_visual_row() {
// v0.2 remap: `K` is a one-row backward cursor move.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "one"),
diff_line(LineKind::Added, "two"),
diff_line(LineKind::Added, "three"),
],
)],
100,
)]);
app.scroll_to(3);
app.handle_key(key(KeyCode::Char('K')));
assert_eq!(app.scroll, 2);
app.handle_key(key(KeyCode::Char('K')));
assert_eq!(app.scroll, 1);
assert!(!app.follow_mode);
}
#[test]
fn l_flows_from_end_of_long_hunk_into_next_hunk_header() {
// Even from the last row of a long hunk, `l` jumps to the
// next hunk's header. This mirrors the old SHIFT-J "flow
// across boundary" behavior but now lives on `l`.
let lines: Vec<DiffLine> = (0..20)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect();
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, lines),
hunk(100, vec![diff_line(LineKind::Added, "tail")]),
],
100,
)]);
app.last_body_height.set(15);
let second_hunk = app.layout.hunk_starts[1];
// Park on the last row of the long hunk (row 21: 1 header + 20
// diff lines starting at row 1).
app.scroll_to(21);
// `l` from there must leap into the next hunk's header.
app.handle_key(key(KeyCode::Char('l')));
assert_eq!(app.scroll, second_hunk);
}
#[test]
fn viewport_top_centers_short_hunk_inside_viewport() {
// Layout shape (after mtime-ascending sort):
// 0 FileHeader before.rs
// 1 HunkHeader
// 2..5 four context lines
// 6 Spacer
// 7 FileHeader target.rs (← cursor will park here)
// 8 HunkHeader
// 9 +alpha
// 10 +beta
// 11 Spacer
// 12 FileHeader after.rs (lots of trailing space so we
// 13 HunkHeader aren't clamped against max_top)
// 14..17 four context lines
// 18 Spacer
// Total = 19 rows. Viewport = 9. max_top = 10.
// Hunk spans rows [8, 11) → size 3.
// Centring 3 rows in a 9-row viewport means
// viewport_top = 8 - (9 - 3)/2 = 8 - 3 = 5.
let mut app = fake_app(vec![
make_file(
"before.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Context, " a"),
diff_line(LineKind::Context, " b"),
diff_line(LineKind::Context, " c"),
diff_line(LineKind::Context, " d"),
],
)],
100,
),
make_file(
"target.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "alpha"),
diff_line(LineKind::Added, "beta"),
],
)],
200,
),
make_file(
"after.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Context, " a"),
diff_line(LineKind::Context, " b"),
diff_line(LineKind::Context, " c"),
diff_line(LineKind::Context, " d"),
],
)],
300,
),
]);
// Park the cursor on target.rs's hunk header.
let target_hunk_row = app.layout.hunk_starts[1];
app.scroll_to(target_hunk_row);
let (hunk_top, hunk_end) = app.current_hunk_range().unwrap();
assert_eq!(hunk_end - hunk_top, 3);
let viewport = app.viewport_top(9);
assert_eq!(
viewport, 5,
"expected the 3-row hunk centred at viewport_top = 5 in a 9-row viewport"
);
}
#[test]
fn viewport_top_falls_back_to_cursor_centered_for_long_hunks() {
// Single long hunk, much taller than the viewport: should fall
// back to centring the cursor row instead of trying to centre
// the whole hunk.
let lines: Vec<DiffLine> = (0..40)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect();
let mut app = fake_app(vec![make_file("a.rs", vec![hunk(1, lines)], 100)]);
let header = app.layout.hunk_starts[0];
// Park well inside the long hunk.
app.scroll_to(header + 20);
let height = 12;
let viewport = app.viewport_top(height);
// For the long-hunk fall-through, viewport_top = cursor - height/2.
assert_eq!(viewport, (header + 20) - height / 2);
}
#[test]
fn top_mode_anchors_short_hunk_to_viewport_ceiling() {
// Cursor on a short hunk's header in Top mode pins the hunk's
// *first* row (its header) to the viewport ceiling so the body
// flows downward into the rest of the viewport.
//
// Layout (mtime-ascending sort):
// 0 FileHeader before.rs
// 1 HunkHeader
// 2..5 four context lines
// 6 Spacer
// 7 FileHeader target.rs
// 8 HunkHeader ← cursor parks here
// 9 +alpha
// 10 +beta
// 11 Spacer
// 12 FileHeader after.rs
// 13 HunkHeader
// 14..17 four context lines
// 18 Spacer
// Total = 19 rows. Viewport = 9. max_top = 10.
// target hunk spans [8, 11) → size 3.
// Top mode pins hunk_top (8) to the viewport ceiling, so
// viewport_top = 8.
let mut app = fake_app(vec![
make_file(
"before.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Context, " a"),
diff_line(LineKind::Context, " b"),
diff_line(LineKind::Context, " c"),
diff_line(LineKind::Context, " d"),
],
)],
100,
),
make_file(
"target.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "alpha"),
diff_line(LineKind::Added, "beta"),
],
)],
200,
),
make_file(
"after.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Context, " a"),
diff_line(LineKind::Context, " b"),
diff_line(LineKind::Context, " c"),
diff_line(LineKind::Context, " d"),
],
)],
300,
),
]);
app.cursor_placement = CursorPlacement::Top;
let target_hunk_row = app.layout.hunk_starts[1];
app.scroll_to(target_hunk_row);
let (hunk_top, hunk_end) = app.current_hunk_range().unwrap();
assert_eq!((hunk_top, hunk_end), (8, 11));
let viewport = app.viewport_top(9);
assert_eq!(
viewport, 8,
"top mode should anchor hunk_top to the viewport ceiling"
);
}
#[test]
fn top_mode_long_hunk_still_pins_cursor_row() {
// When hunk_size > viewport, Top mode falls back to pinning
// the cursor row itself to the ceiling so J/K chunk scroll
// keeps working.
let lines: Vec<DiffLine> = (0..40)
.map(|i| diff_line(LineKind::Added, &format!("line {i}")))
.collect();
let mut app = fake_app(vec![make_file("a.rs", vec![hunk(1, lines)], 100)]);
app.cursor_placement = CursorPlacement::Top;
let header = app.layout.hunk_starts[0];
app.scroll_to(header + 20);
let height = 12;
// Long-hunk fall-through: viewport_top = cursor (cursor at row 0).
let viewport = app.viewport_top(height);
assert_eq!(viewport, header + 20);
}
#[test]
fn viewport_top_clamps_short_hunk_centring_against_layout_edges() {
// A short hunk near the very start of the layout: padding above
// would push viewport_top below 0 → clamp at 0.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "alpha"),
diff_line(LineKind::Added, "beta"),
],
)],
100,
)]);
let hunk_row = app.layout.hunk_starts[0];
app.scroll_to(hunk_row);
// 12-row viewport, but hunk starts at row 1 (after the file
// header). hunk_top - pad would be negative; clamped to 0.
let viewport = app.viewport_top(12);
assert_eq!(viewport, 0);
}
#[test]
fn chunk_size_scales_with_last_body_height() {
let app = fake_app(vec![]);
// Default body height is 24 → chunk = 24/3 = 8.
assert_eq!(app.chunk_size(), 8);
// A taller pane should yield a bigger chunk.
app.last_body_height.set(36);
assert_eq!(app.chunk_size(), 12);
// A tiny pane should never go below 1 row.
app.last_body_height.set(2);
assert_eq!(app.chunk_size(), 1);
// Zero height (degenerate) still gives at least 1.
app.last_body_height.set(0);
assert_eq!(app.chunk_size(), 1);
}
#[test]
fn cursor_placement_centered_keeps_cursor_in_the_middle() {
// 100 row layout, viewport 20 rows, cursor at row 50.
// Centered → viewport_top = 50 - 10 = 40, cursor visually at row 10.
let placement = CursorPlacement::Centered;
assert_eq!(placement.viewport_top(50, 100, 20), 40);
}
#[test]
fn cursor_placement_centered_clamps_at_top_and_bottom() {
let placement = CursorPlacement::Centered;
// Cursor near the start: viewport_top can't go below 0.
assert_eq!(placement.viewport_top(2, 100, 20), 0);
// Cursor near the end: viewport_top clamped at total - height.
assert_eq!(placement.viewport_top(99, 100, 20), 80);
}
#[test]
fn cursor_placement_top_pins_cursor_to_the_ceiling() {
// Cursor at row 50, viewport 20: cursor visually at row 0
// (top of viewport), viewport_top = 50.
let placement = CursorPlacement::Top;
assert_eq!(placement.viewport_top(50, 100, 20), 50);
}
#[test]
fn cursor_placement_top_clamps_against_max_top() {
// Cursor near the end of the layout: Top mode would push
// viewport_top past max_top, so it clamps.
let placement = CursorPlacement::Top;
assert_eq!(placement.viewport_top(95, 100, 20), 80);
}
#[test]
fn cursor_placement_returns_zero_when_layout_fits_in_viewport() {
// 5 rows, viewport 20 → no scrolling possible regardless of mode.
assert_eq!(CursorPlacement::Centered.viewport_top(3, 5, 20), 0);
assert_eq!(CursorPlacement::Top.viewport_top(3, 5, 20), 0);
}
#[test]
fn z_key_toggles_cursor_placement() {
let mut app = fake_app(vec![]);
assert_eq!(app.cursor_placement, CursorPlacement::Centered);
app.handle_key(key(KeyCode::Char('z')));
assert_eq!(app.cursor_placement, CursorPlacement::Top);
app.handle_key(key(KeyCode::Char('z')));
assert_eq!(app.cursor_placement, CursorPlacement::Centered);
}
#[test]
fn change_runs_collapse_consecutive_same_kind_lines_into_one_entry() {
// Three contiguous +/- lines should be a single change run, not three.
let app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "a"),
diff_line(LineKind::Added, "b"),
diff_line(LineKind::Deleted, "c"),
],
)],
100,
)]);
assert_eq!(
app.layout.change_runs.len(),
1,
"expected one change run for an all-contiguous +/- block"
);
let (start, end) = app.layout.change_runs[0];
assert_eq!(end - start, 3);
}
#[test]
fn w_key_toggles_wrap_lines() {
let mut app = fake_app(vec![]);
assert!(!app.wrap_lines);
app.handle_key(key(KeyCode::Char('w')));
assert!(app.wrap_lines);
app.handle_key(key(KeyCode::Char('w')));
assert!(!app.wrap_lines);
}
#[test]
fn handle_key_g_and_capital_g_move_to_top_and_bottom() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "x"),
diff_line(LineKind::Added, "y"),
diff_line(LineKind::Added, "z"),
],
)],
100,
)]);
app.handle_key(key(KeyCode::Char('G')));
assert_eq!(app.scroll, app.layout.rows.len() - 2);
assert!(
!matches!(app.layout.rows[app.scroll], RowKind::Spacer),
"G must land on the last content row, not the trailing spacer"
);
app.handle_key(key(KeyCode::Char('g')));
assert_eq!(app.scroll, 0);
}
#[test]
fn scroll_to_does_not_land_on_spacer_rows() {
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
),
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "y")])],
200,
),
]);
let spacer = app
.layout
.rows
.iter()
.position(|row| matches!(row, RowKind::Spacer))
.expect("layout has spacer");
app.scroll_to(spacer);
assert!(
!matches!(app.layout.rows[app.scroll], RowKind::Spacer),
"scroll_to must normalize spacer targets to real content rows"
);
}
#[test]
fn scroll_by_skips_spacer_rows_in_nowrap_mode() {
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
),
make_file(
"b.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "y")])],
200,
),
]);
app.follow_mode = false;
let first_file_last_diff = app
.layout
.rows
.iter()
.enumerate()
.find_map(|(idx, row)| {
matches!(row, RowKind::DiffLine { file_idx: 0, .. }).then_some(idx)
})
.expect("first file diff row");
app.scroll = first_file_last_diff;
// +1 would have landed on the inter-file spacer before the fix.
app.scroll_by(1);
assert!(
!matches!(app.layout.rows[app.scroll], RowKind::Spacer),
"scroll_by must skip cosmetic spacer rows"
);
assert_eq!(app.current_file_path(), Some(Path::new("b.rs")));
}
#[test]
fn handle_key_f_restores_follow_mode_and_jumps_to_target() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(20, vec![diff_line(LineKind::Added, "y")]),
],
100,
)]);
app.handle_key(key(KeyCode::Char('g'))); // jump to top, drops follow
assert!(!app.follow_mode);
app.handle_key(key(KeyCode::Char('f')));
assert!(app.follow_mode);
// Follow target = last HunkHeader of the newest file.
assert!(matches!(
app.layout.rows[app.scroll],
RowKind::HunkHeader { .. }
));
}
#[test]
fn handle_key_q_and_ctrl_c_quit_in_normal_mode() {
let mut app = fake_app(vec![]);
app.handle_key(key(KeyCode::Char('q')));
assert!(app.should_quit);
let mut app = fake_app(vec![]);
app.handle_key(ctrl('c'));
assert!(app.should_quit);
}
#[test]
fn s_opens_picker_and_esc_closes_it() {
// v0.2 remap: picker trigger moved from `Space` to `s` so
// `Space` is free for the scar "seen" mark (wired up in a
// later M4 slice).
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
app.handle_key(key(KeyCode::Char('s')));
assert!(app.picker.is_some());
app.handle_key(key(KeyCode::Esc));
assert!(app.picker.is_none());
}
#[test]
fn space_toggles_seen_mark_on_current_hunk() {
// M4 slice 6: Space flips the cursor's enclosing hunk
// into and out of the "seen" set. Pure TUI state — no
// file write, no cursor movement, no picker.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
cursor_on_nth_diff_line(&mut app, 0);
let before_scroll = app.scroll;
app.handle_key(key(KeyCode::Char(' ')));
assert!(
app.hunk_is_seen(0, 0),
"Space must toggle the current hunk into the seen set"
);
assert!(app.picker.is_none(), "Space must not open the picker");
assert_eq!(app.scroll, before_scroll, "Space must not move cursor");
// Second press removes the mark.
app.handle_key(key(KeyCode::Char(' ')));
assert!(
!app.hunk_is_seen(0, 0),
"a second Space must remove the seen mark"
);
}
#[test]
fn space_on_file_header_row_is_noop() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
let header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::FileHeader { .. }))
.expect("header");
app.scroll_to(header_row);
app.handle_key(key(KeyCode::Char(' ')));
assert!(
app.seen_hunks.is_empty(),
"file-header Space must not add anything to seen_hunks"
);
}
#[test]
fn seen_mark_persists_across_a_recompute_that_preserves_hunk_old_start() {
// seen_hunks is keyed by (path, hunk.old_start) so a
// watcher-driven recompute that rebuilds the FileDiff
// list without moving the hunk's pre-image anchor must
// leave the mark in place.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(42, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char(' ')));
assert!(app.hunk_is_seen(0, 0));
let fresh = vec![make_file(
"a.rs",
vec![hunk(42, vec![diff_line(LineKind::Added, "y")])],
100,
)];
app.apply_computed_files(fresh);
assert!(
app.hunk_is_seen(0, 0),
"recompute that preserves hunk.old_start must preserve the seen mark"
);
}
#[test]
fn picker_filters_by_substring_case_insensitively() {
let mut app = fake_app(vec![
make_file(
"src/Auth.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
300,
),
make_file(
"src/handler.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "y")])],
200,
),
make_file(
"tests/auth_test.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "z")])],
100,
),
]);
app.open_picker();
for c in "auth".chars() {
app.handle_key(key(KeyCode::Char(c)));
}
let results = app.picker_results();
// src/Auth.rs and tests/auth_test.rs match; src/handler.rs does not.
assert_eq!(results.len(), 2);
let paths: Vec<_> = results.iter().map(|&i| app.files[i].path.clone()).collect();
assert!(paths.contains(&PathBuf::from("src/Auth.rs")));
assert!(paths.contains(&PathBuf::from("tests/auth_test.rs")));
}
#[test]
fn picker_enter_jumps_to_selected_file_first_hunk_and_closes() {
let mut app = fake_app(vec![
make_file(
"newest.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
300,
),
make_file(
"older.rs",
vec![hunk(50, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
app.open_picker();
// picker_results runs newest-first regardless of how files are
// stored internally, so cursor 0 = newest.rs and cursor 1 = older.rs.
app.handle_key(key(KeyCode::Down));
app.handle_key(key(KeyCode::Enter));
assert!(app.picker.is_none());
let older = file_idx(&app, "older.rs");
let expected = app.layout.file_first_hunk[older].unwrap();
assert_eq!(app.scroll, expected);
assert_eq!(app.current_file_path(), Some(Path::new("older.rs")));
}
#[test]
fn populate_mtimes_keeps_deleted_files_recent_so_follow_mode_lands_on_them() {
// Regression for the Codex finding: a freshly-deleted file used
// to fall to `UNIX_EPOCH` because `metadata()` failed, which
// sorted it to the very **top** of the mtime-ascending layout
// and pushed follow mode onto the newest surviving file. That
// hid destructive actions in the exact moment they most needed
// to be visible.
//
// Setup: one real file on disk with its mtime backdated into
// the early 70s, plus one deleted file whose path does not
// exist. After bootstrap the deleted file must sort **last**
// (= newest) and follow mode must park on it.
let tmp = tempfile::tempdir().expect("create tempdir");
let kept_path = tmp.path().join("kept.rs");
std::fs::write(&kept_path, "hi\n").expect("write kept");
let ancient = SystemTime::UNIX_EPOCH + Duration::from_secs(60 * 60 * 24);
let f = std::fs::File::options()
.write(true)
.open(&kept_path)
.expect("reopen kept for mtime set");
f.set_modified(ancient).expect("backdate kept.rs");
let kept = FileDiff {
path: PathBuf::from("kept.rs"),
status: FileStatus::Modified,
added: 1,
deleted: 0,
content: DiffContent::Text(vec![hunk(1, vec![diff_line(LineKind::Added, "hi2")])]),
mtime: SystemTime::UNIX_EPOCH,
header_prefix: None,
};
let gone = FileDiff {
path: PathBuf::from("gone.rs"),
status: FileStatus::Deleted,
added: 0,
deleted: 1,
content: DiffContent::Text(vec![hunk(1, vec![diff_line(LineKind::Deleted, "bye")])]),
mtime: SystemTime::UNIX_EPOCH,
header_prefix: None,
};
let app = App::bootstrap_with_diff(
tmp.path().to_path_buf(),
tmp.path().join(".git"),
tmp.path().join(".git"),
Some("refs/heads/main".into()),
"abcdef1234567890abcdef1234567890abcdef12".into(),
Ok(vec![kept, gone]),
)
.expect("bootstrap succeeds");
assert_eq!(
app.files.last().map(|f| f.path.as_path()),
Some(Path::new("gone.rs")),
"deleted file must land at the newest end of the mtime sort"
);
assert_eq!(
app.current_file_path(),
Some(Path::new("gone.rs")),
"follow mode must keep the deletion on screen"
);
}
#[test]
fn apply_reset_preserves_old_state_when_diff_fails() {
// Regression for the adversarial finding on `reset_baseline`:
// the old implementation assigned `baseline_sha` and cleared
// `head_dirty` BEFORE running `git diff`, so a transient diff
// failure left the user staring at a stale `files` snapshot
// under a silently-advanced baseline with no `HEAD*` warning
// to signal that the reset never actually landed.
//
// `apply_reset` now takes the diff `Result` directly so we
// can exercise the failure path without touching the
// filesystem. Every piece of baseline-adjacent state must
// survive a failed reset unchanged.
let mut app = fake_app(vec![
make_file(
"older.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "keep me")])],
100,
),
make_file(
"newer.rs",
vec![hunk(2, vec![diff_line(LineKind::Added, "also keep")])],
200,
),
]);
let old_sha = app.baseline_sha.clone();
let old_files = app.files.clone();
let old_branch = app.current_branch_ref.clone();
app.head_dirty = true;
let effect = app.apply_reset(
"feedfacefeedfacefeedfacefeedfacefeedface".into(),
Some("refs/heads/feature".into()),
Err(anyhow::anyhow!("simulated git diff failure")),
);
assert_eq!(
effect,
KeyEffect::None,
"a failed reset must not ask the loop to reconfigure the watcher — \
doing so would leave the watcher pointing at a branch the user \
never actually reached"
);
assert_eq!(
app.baseline_sha, old_sha,
"baseline_sha must not advance when the post-reset diff fails"
);
assert_eq!(
app.current_branch_ref, old_branch,
"current_branch_ref must not advance when the post-reset diff fails"
);
assert!(
app.head_dirty,
"head_dirty must survive a failed reset so the HEAD* warning stays visible"
);
assert_eq!(
app.files, old_files,
"files snapshot must be preserved when the post-reset diff fails"
);
let err = app
.last_error
.as_deref()
.expect("failed reset must record last_error");
assert!(
err.starts_with("R:"),
"last_error must carry the `R:` prefix so the footer identifies the source: {err}"
);
}
#[test]
fn apply_reset_reports_reconfigure_watcher_when_branch_changes() {
// ADR-0008 fix: if the user checked out a different branch
// after starting kizu, `R` must not only update the baseline
// SHA but also signal the event loop that the watcher's
// branch tracking needs to move with it. Otherwise the
// watcher stays pinned to the startup branch and silently
// stops firing `GitHead` for future commits.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
assert_eq!(
app.current_branch_ref.as_deref(),
Some("refs/heads/main"),
"fake_app defaults to main for determinism"
);
let effect = app.apply_reset(
"feedfacefeedfacefeedfacefeedfacefeedface".into(),
Some("refs/heads/feature".into()),
Ok(Vec::new()),
);
assert_eq!(
effect,
KeyEffect::ReconfigureWatcher,
"branch change must request a watcher reconfigure"
);
assert_eq!(
app.current_branch_ref.as_deref(),
Some("refs/heads/feature"),
"current_branch_ref must advance to the new branch once the reset commits"
);
}
#[test]
fn apply_reset_signals_reconfigure_on_attach_detach_transitions() {
// Transitioning from attached to detached HEAD (and back) is
// a branch-set change from the matcher's perspective —
// previously matched `refs/heads/main` now becomes `None`,
// and only the per-worktree HEAD file matters. The reset
// path must surface that so the watcher drops the stale
// branch ref.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
// main → detached
let effect = app.apply_reset(
"feedfacefeedfacefeedfacefeedfacefeedface".into(),
None,
Ok(Vec::new()),
);
assert_eq!(effect, KeyEffect::ReconfigureWatcher);
assert!(app.current_branch_ref.is_none());
// detached → main
let effect = app.apply_reset(
"0123456701234567012345670123456701234567".into(),
Some("refs/heads/main".into()),
Ok(Vec::new()),
);
assert_eq!(effect, KeyEffect::ReconfigureWatcher);
assert_eq!(app.current_branch_ref.as_deref(), Some("refs/heads/main"));
}
#[test]
fn apply_reset_commits_new_baseline_when_diff_succeeds() {
// Dual of the above: the happy path must still swap the
// baseline, clear head_dirty, and install the new file set so
// a successful reset is visibly a reset and not a no-op.
let mut app = fake_app(vec![make_file(
"old.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "stale")])],
100,
)]);
app.head_dirty = true;
app.last_error = Some("stale error".into());
let new_file = FileDiff {
path: PathBuf::from("fresh.rs"),
status: FileStatus::Modified,
added: 1,
deleted: 0,
content: DiffContent::Text(vec![hunk(1, vec![diff_line(LineKind::Added, "fresh")])]),
mtime: SystemTime::UNIX_EPOCH + Duration::from_secs(500),
header_prefix: None,
};
let new_sha = "feedfacefeedfacefeedfacefeedfacefeedface".to_string();
// Same branch as the existing fake_app default — a successful
// reset that does NOT switch branches should report
// `KeyEffect::None` (no reconfigure needed).
let effect = app.apply_reset(
new_sha.clone(),
Some("refs/heads/main".into()),
Ok(vec![new_file]),
);
assert_eq!(effect, KeyEffect::None);
assert_eq!(app.baseline_sha, new_sha);
assert!(!app.head_dirty, "successful reset must clear head_dirty");
assert!(
app.last_error.is_none(),
"successful reset must clear prior last_error"
);
assert_eq!(
app.files
.iter()
.map(|f| f.path.as_path())
.collect::<Vec<_>>(),
vec![Path::new("fresh.rs")]
);
}
#[test]
fn bootstrap_with_diff_propagates_initial_compute_diff_error() {
// If the very first `git diff` fails, bootstrap must abort — we
// refuse to enter the event loop in a state where the main pane
// would render as "clean" rooted in a silent error.
let diff: Result<Vec<FileDiff>> = Err(anyhow::anyhow!("object file missing"));
let result = App::bootstrap_with_diff(
PathBuf::from("/tmp/fake"),
PathBuf::from("/tmp/fake/.git"),
PathBuf::from("/tmp/fake/.git"),
Some("refs/heads/main".into()),
"abcdef1234567890abcdef1234567890abcdef12".into(),
diff,
);
let err = match result {
Ok(_) => panic!("initial compute_diff failure must be propagated"),
Err(e) => e,
};
let chain = format!("{err:#}");
assert!(
chain.contains("initial git diff"),
"error chain should mention the initial git diff context, got: {chain}"
);
assert!(
chain.contains("object file missing"),
"error chain should preserve the underlying cause, got: {chain}"
);
}
#[test]
fn bootstrap_with_diff_applies_successful_diff_and_clears_error_state() {
// Success path: bootstrap populates files, sorts them ascending by
// mtime, builds a layout, and lands on the follow target.
let diff = Ok(vec![
make_file(
"newer.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "a")])],
200,
),
make_file(
"older.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "b")])],
100,
),
]);
let app = App::bootstrap_with_diff(
PathBuf::from("/tmp/fake"),
PathBuf::from("/tmp/fake/.git"),
PathBuf::from("/tmp/fake/.git"),
Some("refs/heads/main".into()),
"abcdef1234567890abcdef1234567890abcdef12".into(),
diff,
)
.expect("bootstrap should succeed on Ok diff");
assert_eq!(app.files.len(), 2);
assert!(app.last_error.is_none());
assert!(app.follow_mode);
assert!(
!app.layout.rows.is_empty(),
"layout should be built from the initial diff"
);
}
#[test]
fn bootstrap_with_diff_reads_expected_session_id_from_env() {
// First-writer-wins binding can silently attach the TUI to
// the wrong agent when a second agent in the same repo fires
// faster than the one the user is attached to. Pre-binding
// the expected `session_id` at bootstrap (here via the
// `KIZU_SESSION_ID` environment variable) closes that
// window. Once bound, `handle_event_log` drops events from
// any other session instead of auto-binding to the first
// arrival.
//
// Serialized via a static Mutex so cargo's parallel runner
// doesn't interleave `set_var` / `remove_var` with other
// env-touching tests in this file.
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe { std::env::set_var("KIZU_SESSION_ID", "agent-xyz") };
let diff = Ok(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "a")])],
100,
)]);
let app = App::bootstrap_with_diff(
PathBuf::from("/tmp/fake"),
PathBuf::from("/tmp/fake/.git"),
PathBuf::from("/tmp/fake/.git"),
Some("refs/heads/main".into()),
"abcdef1234567890abcdef1234567890abcdef12".into(),
diff,
)
.expect("bootstrap must succeed");
unsafe { std::env::remove_var("KIZU_SESSION_ID") };
assert_eq!(
app.bound_session_id,
Some("agent-xyz".to_string()),
"bootstrap must pre-bind the TUI to the env-provided session_id"
);
}
#[test]
fn picker_enter_disables_follow_mode_so_selection_survives_recompute() {
// bootstrap lands in follow mode. A picker selection is an
// explicit manual navigation — the next recompute must not yank
// the user back to the newest file's last hunk.
let mut app = fake_app(vec![
make_file(
"newest.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
300,
),
make_file(
"older.rs",
vec![hunk(50, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
assert!(app.follow_mode, "bootstrap starts in follow mode");
app.open_picker();
app.handle_key(key(KeyCode::Down));
app.handle_key(key(KeyCode::Enter));
assert_eq!(app.current_file_path(), Some(Path::new("older.rs")));
assert!(
!app.follow_mode,
"picker Enter is a manual navigation and must disable follow mode"
);
// Simulate a watcher-driven recompute (another file write bumping
// newest.rs again, picking up a second hunk). refresh_anchor
// should honour the anchor on older.rs instead of snapping us back
// to newest.rs's last hunk.
let newest = file_idx(&app, "newest.rs");
app.files[newest] = make_file(
"newest.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(30, vec![diff_line(LineKind::Added, "z")]),
],
400,
);
app.files.sort_by_key(|a| a.mtime);
app.build_layout();
app.refresh_anchor();
assert_eq!(
app.current_file_path(),
Some(Path::new("older.rs")),
"picker-selected file must survive a subsequent recompute"
);
}
#[test]
fn picker_cursor_tracks_same_file_across_recompute_reordering() {
let mut app = fake_app(vec![
make_file(
"newest.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
300,
),
make_file(
"older.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
app.open_picker();
app.handle_key(key(KeyCode::Down));
let before = app
.picker_selected_path()
.expect("picker target before recompute");
assert_eq!(before, PathBuf::from("older.rs"));
// Recompute adds a brand-new newest file. The filtered results
// reorder newest-first, so a cursor tracked only by index would now
// point at a different file.
app.apply_computed_files(vec![
make_file(
"brand_new.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "z")])],
400,
),
make_file(
"newest.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
300,
),
make_file(
"older.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
let after = app
.picker_selected_path()
.expect("picker target after recompute");
assert_eq!(
after,
PathBuf::from("older.rs"),
"picker cursor must stay on the same file even when results reorder"
);
}
#[test]
fn refresh_anchor_keeps_us_on_the_same_hunk_after_recompute() {
// First snapshot: 2 files, scroll parked on b.rs's hunk.
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
200,
),
make_file(
"b.rs",
vec![hunk(42, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
// Move to b.rs's hunk by path lookup and disable follow so the
// anchor stays put.
let b = file_idx(&app, "b.rs");
app.jump_to_file_first_hunk(b);
app.follow_mode = false;
app.update_anchor_from_scroll();
let anchor_before = app.anchor.clone().expect("anchor set");
assert_eq!(anchor_before.path, PathBuf::from("b.rs"));
assert_eq!(anchor_before.hunk_old_start, 42);
// Simulate a recompute by appending a new (older) file. The list
// is re-sorted ascending; b.rs stays in the layout but its row
// index moves. The anchor must still resolve to it.
app.files.push(make_file(
"c.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "z")])],
50, // older than b.rs
));
app.files.sort_by_key(|x| x.mtime);
app.build_layout();
app.refresh_anchor();
assert_eq!(app.current_file_path(), Some(Path::new("b.rs")));
}
#[test]
fn refresh_anchor_keeps_manual_mode_on_same_file_when_hunk_identity_changes() {
let mut app = fake_app(vec![
make_file(
"newest.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
300,
),
make_file(
"older.rs",
vec![hunk(50, vec![diff_line(LineKind::Added, "y")])],
100,
),
]);
let older = file_idx(&app, "older.rs");
app.jump_to_file_first_hunk(older);
app.follow_mode = false;
app.update_anchor_from_scroll();
assert_eq!(app.current_file_path(), Some(Path::new("older.rs")));
// Same file survives, but the old hunk identity no longer does
// (e.g. git merged/split hunks after a nearby edit). Manual mode
// should stay on the same file instead of snapping to the newest
// file's follow target.
app.files[older] = make_file(
"older.rs",
vec![hunk(99, vec![diff_line(LineKind::Added, "y2")])],
100,
);
app.build_layout();
app.refresh_anchor();
assert_eq!(
app.current_file_path(),
Some(Path::new("older.rs")),
"manual mode must stay on the same file when only hunk identity changes"
);
}
#[test]
fn refresh_anchor_prefers_nearest_hunk_within_same_file() {
let mut app = fake_app(vec![make_file(
"only.rs",
vec![
hunk(10, vec![diff_line(LineKind::Added, "first")]),
hunk(50, vec![diff_line(LineKind::Added, "second")]),
],
100,
)]);
app.scroll_to(
app.layout
.rows
.iter()
.position(|row| {
matches!(
row,
RowKind::HunkHeader {
file_idx: 0,
hunk_idx: 1
}
)
})
.expect("second hunk header"),
);
app.follow_mode = false;
app.update_anchor_from_scroll();
app.files[0] = make_file(
"only.rs",
vec![
hunk(10, vec![diff_line(LineKind::Added, "first")]),
hunk(60, vec![diff_line(LineKind::Added, "second shifted")]),
],
100,
);
app.build_layout();
app.refresh_anchor();
let (_, hunk_idx) = app.current_hunk().expect("cursor on hunk");
assert_eq!(
hunk_idx, 1,
"manual fallback should stay near the previously viewed hunk, not jump to the file's first hunk"
);
}
#[test]
fn apply_computed_files_pins_cursor_screen_row_across_reorder() {
// Scenario: user is parked on a hunk in b.rs. A watcher-driven
// recompute fires because b.rs was edited, bumping its mtime so
// it now sorts to the end of the ascending list. Without the
// pin, `refresh_anchor` follows the hunk to its new row index,
// which slides the viewport — jarring when the user was only
// reviewing that one change.
//
// Expected: cursor continues to point at the same hunk identity
// AND the viewport top shifts so the cursor lands at the same
// screen row as before the recompute.
let mut body_lines = Vec::new();
for i in 0..30 {
body_lines.push(diff_line(LineKind::Context, &format!("ctx {i}")));
}
body_lines.push(diff_line(LineKind::Added, "y"));
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
200,
),
make_file("b.rs", vec![hunk(42, body_lines.clone())], 100),
]);
// fake_app sorts ascending by mtime, so a.rs (200) is at the
// bottom and b.rs (100) is at the top. Park on b.rs's only
// hunk and pin the app into manual mode.
let b = file_idx(&app, "b.rs");
app.jump_to_file_first_hunk(b);
app.follow_mode = false;
app.update_anchor_from_scroll();
// Skip populate_mtimes / sort in apply_computed_files so the
// test controls the post-recompute order deterministically.
app.view_mode = ViewMode::Stream;
// Simulate one render cycle: pick a viewport height, let the
// renderer resolve viewport_top, and stash that top as
// visual_top (the Cell the renderer updates every frame).
let body_height = 24;
app.last_body_height.set(body_height);
let initial_top = app.viewport_top(body_height);
app.visual_top.set(initial_top as f32);
let initial_screen_row = app
.scroll
.checked_sub(initial_top)
.expect("cursor above viewport_top — test setup wrong");
// Fresh file set: same two files, but b.rs has been edited
// and its mtime bumped past a.rs's, so its position in the
// layout moves from first to last.
let fresh = vec![
make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
200,
),
make_file("b.rs", vec![hunk(42, body_lines.clone())], 400),
];
app.apply_computed_files(fresh);
// Anchor still points at the same hunk in b.rs.
assert_eq!(app.current_file_path(), Some(Path::new("b.rs")));
// Viewport top is chosen so the cursor lands at the same
// screen row it was on before the recompute — the hallmark
// of the pin.
let new_top = app.viewport_top(body_height);
let new_screen_row = app
.scroll
.checked_sub(new_top)
.expect("cursor above viewport_top after recompute");
assert_eq!(
new_screen_row, initial_screen_row,
"cursor must stay at the same screen row across a \
reorder-driven apply_computed_files"
);
}
#[test]
fn scar_line_edited_away_does_not_snap_cursor_to_hunk_header() {
// Reproduces the user-reported bug: user inserts a scar, then
// edits the scar away (or shifts it). The watcher-driven
// recompute should leave the cursor on a DiffLine near the
// scar's position, not on the hunk's `@@` header row.
//
// Current chain:
// - refresh_anchor maps anchor → HunkHeader row
// - scar_focus's `find_new_file_line_row` returns None because
// the scar line is gone → scar_focus cleared
// - pin preserves screen row, but the LOGICAL cursor is still
// on HunkHeader (placed by refresh_anchor)
// Expected: cursor lands on a DiffLine at (or near) the
// pre-edit new-file line.
let pre_edit_body = vec![
diff_line(LineKind::Added, "line one"),
diff_line(LineKind::Added, "scar target"),
diff_line(LineKind::Added, "line three"),
];
let mut app = fake_app(vec![make_file("b.rs", vec![hunk(1, pre_edit_body)], 100)]);
// Park cursor on the "scar target" DiffLine (hunk_idx=0,
// line_idx=1) and pretend a scar was just inserted there —
// scar_focus points at new-file line 2.
let scar_target_row = app
.layout
.rows
.iter()
.position(|r| {
matches!(
r,
RowKind::DiffLine {
file_idx: 0,
hunk_idx: 0,
line_idx: 1,
},
)
})
.expect("scar target DiffLine row must exist");
app.scroll_to(scar_target_row);
app.follow_mode = false;
let abs = app.root.join("b.rs");
app.scar_focus = Some((abs, 2));
// Prime visual_top as a render would.
let body_height = 20;
app.last_body_height.set(body_height);
let initial_top = app.viewport_top(body_height);
app.visual_top.set(initial_top as f32);
// Edit: scar target is removed. The hunk now has only two
// lines. find_new_file_line_row(path, 2) will still find a
// line ("line three" at new-line 2) OR the hunk may have
// shrunk — depends on the edit. To reliably reproduce the
// "line gone" branch we cut the hunk down to one line so
// new-line 2 is past the end.
let edited_body = vec![diff_line(LineKind::Added, "line one")];
let fresh = vec![make_file("b.rs", vec![hunk(1, edited_body)], 100)];
app.view_mode = ViewMode::Stream;
app.apply_computed_files(fresh);
// The bug: cursor on HunkHeader row after the recompute.
let landed = app
.layout
.rows
.get(app.scroll)
.cloned()
.expect("cursor on some row");
assert!(
!matches!(landed, RowKind::HunkHeader { .. }),
"cursor must not land on a @@ HunkHeader after the scar line is edited away; \
landed on {landed:?}"
);
}
// ---- scroll animation --------------------------------------------
#[test]
fn scroll_anim_sample_at_start_returns_from_not_done() {
let start = Instant::now();
let anim = ScrollAnim {
from: 10.0,
start,
dur: Duration::from_millis(150),
};
let (v, done) = anim.sample(20.0, start);
assert!((v - 10.0).abs() < 1e-4, "expected 10.0, got {v}");
assert!(!done);
}
#[test]
fn scroll_anim_sample_at_duration_returns_target_done() {
let start = Instant::now();
let anim = ScrollAnim {
from: 10.0,
start,
dur: Duration::from_millis(150),
};
let (v, done) = anim.sample(20.0, start + Duration::from_millis(150));
assert!((v - 20.0).abs() < 1e-4, "expected 20.0, got {v}");
assert!(done);
}
#[test]
fn scroll_anim_sample_past_halfway_is_biased_toward_target() {
// ease-out cubic: e(0.5) = 1 - 0.5^3 = 0.875
let start = Instant::now();
let anim = ScrollAnim {
from: 0.0,
start,
dur: Duration::from_millis(100),
};
let (v, done) = anim.sample(10.0, start + Duration::from_millis(50));
assert!((v - 8.75).abs() < 1e-3, "expected ~8.75 at t=0.5, got {v}");
assert!(!done);
}
#[test]
fn scroll_anim_sample_handles_moving_target_mid_tween() {
let start = Instant::now();
let anim = ScrollAnim {
from: 0.0,
start,
dur: Duration::from_millis(100),
};
// Target moved from 10 to 20 mid-animation.
let (v, _) = anim.sample(20.0, start + Duration::from_millis(50));
// e(0.5) = 0.875, so v = 0 + (20 - 0) * 0.875 = 17.5
assert!((v - 17.5).abs() < 1e-3, "expected ~17.5, got {v}");
}
#[test]
fn scroll_to_starts_animation_when_row_changes() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(
10,
vec![
diff_line(LineKind::Added, "y1"),
diff_line(LineKind::Added, "y2"),
],
),
],
100,
)]);
app.anim = None;
app.scroll = 0;
app.scroll_to(3);
assert!(app.anim.is_some(), "anim should be set after scroll_to");
}
#[test]
fn scroll_to_does_not_start_animation_on_noop() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
app.anim = None;
let current = app.scroll;
app.scroll_to(current);
assert!(app.anim.is_none(), "no-op scroll must not start anim");
}
#[test]
fn scroll_to_carries_current_visual_into_animation_from() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![
hunk(1, vec![diff_line(LineKind::Added, "x")]),
hunk(
20,
vec![
diff_line(LineKind::Added, "y1"),
diff_line(LineKind::Added, "y2"),
],
),
],
100,
)]);
app.scroll = 0;
app.anim = None;
app.visual_top.set(7.25);
app.scroll_to(3);
let from = app.anim.as_ref().expect("anim set").from;
assert!((from - 7.25).abs() < 1e-4);
}
#[test]
fn tick_anim_clears_anim_once_duration_elapsed() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
let start = Instant::now() - Duration::from_millis(500);
app.anim = Some(ScrollAnim {
from: 0.0,
start,
dur: Duration::from_millis(150),
});
let still_running = app.tick_anim(Instant::now());
assert!(!still_running);
assert!(app.anim.is_none());
}
#[test]
fn tick_anim_keeps_anim_while_still_running() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
let start = Instant::now();
app.anim = Some(ScrollAnim {
from: 0.0,
start,
dur: Duration::from_millis(150),
});
let still_running = app.tick_anim(start + Duration::from_millis(50));
assert!(still_running);
assert!(app.anim.is_some());
}
#[test]
fn visual_viewport_top_matches_target_when_idle() {
// Build a multi-file layout so the viewport has something to center.
let app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(
1,
(0..8)
.map(|i| diff_line(LineKind::Added, &format!("a{i}")))
.collect(),
)],
100,
),
make_file(
"b.rs",
vec![hunk(
1,
(0..8)
.map(|i| diff_line(LineKind::Added, &format!("b{i}")))
.collect(),
)],
200,
),
]);
// Idle: no anim. visual_viewport_top should equal viewport_top.
let target = app.viewport_top(9);
let visual = app.visual_viewport_top(9, Instant::now());
assert_eq!(visual, target);
}
#[test]
fn visual_viewport_top_tweens_between_from_and_target() {
let mut app = fake_app(vec![
make_file(
"a.rs",
vec![hunk(
1,
(0..8)
.map(|i| diff_line(LineKind::Added, &format!("a{i}")))
.collect(),
)],
100,
),
make_file(
"b.rs",
vec![hunk(
1,
(0..8)
.map(|i| diff_line(LineKind::Added, &format!("b{i}")))
.collect(),
)],
200,
),
]);
// Park scroll at a later row so target != 0.
app.scroll = app.layout.rows.len() - 1;
let target = app.viewport_top(9) as f32;
assert!(target > 0.0);
let start = Instant::now();
app.anim = Some(ScrollAnim {
from: 0.0,
start,
dur: Duration::from_millis(100),
});
// Sample at t=0.5: e(0.5) = 0.875, so visual ≈ 0.875 * target
let v = app.visual_viewport_top(9, start + Duration::from_millis(50));
let expected = (target * 0.875).round() as usize;
assert_eq!(v, expected);
}
// ---- wrap-mode visual scroll model (ADR-0007) --------------------
/// Build an app with a single file containing one diff line whose
/// content is `width * wrap_factor` characters long — so at wrap
/// body_width=`width` the one logical DiffLine produces `wrap_factor`
/// visual rows. Used by the wrap regression tests below.
fn wrap_regression_app(wrap_factor: usize, width: usize) -> App {
let content: String = std::iter::repeat_n('x', width * wrap_factor).collect();
fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, &content)])],
100,
)])
}
#[test]
fn visual_index_nowrap_is_identity() {
// With body_width=None every logical row is exactly one
// visual row, so the prefix is [0, 1, …, n] and visual_y is
// the identity. This is the invariant that keeps every
// nowrap test numerically unchanged after the rework.
let app = wrap_regression_app(4, 10);
let vi = VisualIndex::build(&app.layout, &app.files, None);
assert_eq!(vi.total_visual(), app.layout.rows.len());
for i in 0..app.layout.rows.len() {
assert_eq!(vi.visual_y(i), i, "nowrap visual_y must be identity");
assert_eq!(vi.visual_height(i), 1);
}
}
#[test]
fn visual_index_wrap_expands_long_diff_lines() {
// 40 chars of content at body_width=10 must produce 4 visual
// rows for the single wrapped DiffLine. Non-diff rows (file
// header, hunk header, spacer) still contribute exactly 1.
let app = wrap_regression_app(4, 10);
let vi = VisualIndex::build(&app.layout, &app.files, Some(10));
// Find the one DiffLine row in the layout.
let diff_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::DiffLine { .. }))
.expect("layout must contain a DiffLine");
assert_eq!(
vi.visual_height(diff_row),
4,
"40 chars at width 10 = 4 visual rows"
);
// logical_at must round-trip: the first visual y inside the
// diff row maps back to that row with skip=0, and the second
// visual y maps to the same row with skip=1.
let base = vi.visual_y(diff_row);
assert_eq!(vi.logical_at(base), (diff_row, 0));
assert_eq!(vi.logical_at(base + 1), (diff_row, 1));
assert_eq!(vi.logical_at(base + 3), (diff_row, 3));
}
#[test]
fn viewport_placement_keeps_cursor_visible_across_wrapped_preceding_rows() {
// Adversarial case for Codex finding #3: the cursor sits
// just after a very long wrapped DiffLine. Under the old
// logical-row scroll model, `viewport_top` would put the
// wrapped line right at the top, let it consume the entire
// viewport in visual rows, and push the cursor OFF the
// bottom. With visual-row placement the cursor must always
// fall inside the viewport.
//
// Build a layout with two diff rows: a heavily-wrapped one,
// then a short one the cursor sits on.
let long_content: String = std::iter::repeat_n('x', 80).collect();
let short_content = "short".to_string();
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, &long_content),
diff_line(LineKind::Added, &short_content),
],
)],
100,
)]);
// Park the cursor on the second (short) diff row.
let short_row = app
.layout
.rows
.iter()
.enumerate()
.filter_map(|(i, r)| match r {
RowKind::DiffLine { line_idx, .. } if *line_idx == 1 => Some(i),
_ => None,
})
.next()
.expect("second diff row");
app.scroll = short_row;
app.follow_mode = false;
let body_width = Some(10);
let body_height = 6;
app.last_body_width.set(body_width);
app.last_body_height.set(body_height);
let (top_row, skip_visual) =
app.viewport_placement(body_height, body_width, Instant::now());
// With 80 chars at width 10 the long line occupies 8 visual
// rows. Viewport is only 6 tall. If placement parked at
// `top_row = 0, skip = 0`, the cursor would be at visual y
// 8 (after FileHeader + HunkHeader + 8 wrap rows) and never
// render. The new placement must push the viewport forward
// far enough that the cursor's visual y falls inside [0, 6).
let vi = VisualIndex::build(&app.layout, &app.files, body_width);
let cursor_y = vi.visual_y(app.scroll);
let viewport_top_y = vi.visual_y(top_row) + skip_visual;
assert!(
cursor_y >= viewport_top_y && cursor_y < viewport_top_y + body_height,
"cursor at visual y {cursor_y} must sit inside viewport \
[y={viewport_top_y}, h={body_height}); got top_row={top_row} skip={skip_visual}"
);
}
#[test]
fn scroll_by_in_wrap_mode_advances_by_visual_rows_not_logical() {
// Under wrap, `scroll_by(delta)` must treat `delta` as
// visual rows so Ctrl-d/Ctrl-u move a screenful's worth of
// visible lines — not a screenful of logical rows, which in
// a long wrapped hunk could teleport the cursor past the
// whole block in one press.
let mut app = wrap_regression_app(6, 10); // 60 chars → 6 visual rows
app.last_body_width.set(Some(10));
app.last_body_height.set(6);
app.follow_mode = false;
// Park cursor on the file header (row 0, visual y 0).
app.scroll = 0;
// Advance by 3 visual rows. Layout: [FileHeader, HunkHeader,
// DiffLine(6 visual rows), …]. Visual ys: 0, 1, 2, 3, 4, 5,
// 6, 7. Visual y = 3 falls inside the DiffLine at logical
// row 2, with skip=1. `scroll_by` lands on logical row 2
// with `cursor_sub_row = 1` (ADR-0009 fix).
app.scroll_by(3);
assert_eq!(
app.scroll, 2,
"scroll_by(3) in wrap mode should land on the diff row at visual y 3"
);
assert_eq!(
app.cursor_sub_row, 1,
"cursor_sub_row must capture the intra-row visual offset"
);
}
#[test]
fn scroll_by_in_wrap_mode_walks_inside_a_single_long_wrapped_line() {
// Regression for Codex round-4 finding #1: on a single
// long wrapped diff line (minified JSON / 1-line edit) the
// old wrap-mode `scroll_by` discarded the intra-row offset
// returned by `VisualIndex::logical_at`, so any target y
// landing inside the SAME wrapped logical row resolved to
// the same logical row and `scroll_to` became a no-op.
// The user could never walk through the wrapped content.
//
// Setup: one diff line that wraps to 10 visual rows (100
// chars at body width 10). Park the cursor on row 2 (the
// DiffLine) with cursor_sub_row = 0 and call scroll_by(3).
// The logical row must stay 2 but cursor_sub_row must
// advance to 3 — visible evidence that the cursor actually
// moved.
let mut app = wrap_regression_app(10, 10);
app.last_body_width.set(Some(10));
app.last_body_height.set(6);
app.follow_mode = false;
// Find the diff row and park on its first visual line.
let diff_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::DiffLine { .. }))
.expect("layout has a DiffLine");
app.scroll = diff_row;
app.cursor_sub_row = 0;
// Walk 3 visual rows forward inside the same wrapped line.
app.scroll_by(3);
assert_eq!(
app.scroll, diff_row,
"visual walk inside a long wrapped line must stay on the same logical row"
);
assert_eq!(
app.cursor_sub_row, 3,
"cursor_sub_row must advance to 3 so the cursor is genuinely moving"
);
// One more walk of 4 → sub_row = 7, still same logical row.
app.scroll_by(4);
assert_eq!(app.scroll, diff_row);
assert_eq!(app.cursor_sub_row, 7);
}
#[test]
fn scroll_to_always_resets_cursor_sub_row() {
// Every jump-to-row operation (next_hunk, prev_hunk, g, G,
// follow) funnels through `scroll_to`, which must land on
// the destination row's first visual line. The sub-row
// offset only makes sense for in-place wrap walks.
let mut app = wrap_regression_app(10, 10);
app.last_body_width.set(Some(10));
app.cursor_sub_row = 5;
app.scroll_to(0);
assert_eq!(app.cursor_sub_row, 0);
}
#[test]
fn toggle_wrap_lines_resets_cursor_sub_row() {
// Wrap toggle changes the coordinate system entirely — any
// intra-row offset captured under the old mode has no
// meaning under the new one. Drop it to land cleanly.
let mut app = wrap_regression_app(10, 10);
app.cursor_sub_row = 4;
app.toggle_wrap_lines();
assert_eq!(app.cursor_sub_row, 0);
}
// ---- watcher health decoupling (ADR-0008) ------------------------
#[test]
fn handle_watch_burst_records_failure_in_watcher_health_not_last_error() {
// Regression for Codex round-3 finding: the previous design
// wrote watcher backend failures into `last_error`, so a
// subsequent successful `recompute_diff` would silently
// clear them via `apply_computed_files`. The new design
// parks backend failures in a dedicated `watcher_health`
// slot, which survives diff success and only clears when
// a non-Error event proves the backend is alive again.
let mut app = fake_app(vec![]);
assert!(app.watcher_health.is_healthy());
let (need_recompute, need_head_dirty) = app.handle_watch_burst([WatchEvent::Error {
source: WatchSource::Worktree,
message: "watcher [worktree]: fsevents dropped".into(),
}]);
assert!(
need_recompute,
"backend failure must force a recompute so the UI falls back to fresh data"
);
assert!(!need_head_dirty);
assert!(
app.watcher_health
.has_failure(WatchSource::Worktree, "fsevents dropped"),
"error must land in watcher_health, not last_error"
);
assert!(
app.last_error.is_none(),
"last_error must stay untouched — it's the diff-level error slot"
);
}
#[test]
fn watcher_health_survives_successful_recompute_through_apply_computed_files() {
// The core decoupling: a diff computation succeeding must
// NOT imply the watcher recovered. This test pins the
// invariant that `apply_computed_files` leaves
// `watcher_health` alone.
let mut app = fake_app(vec![]);
app.watcher_health.record_failure(
WatchSource::GitRefs,
"watcher [git.refs]: kqueue overflow".into(),
);
// Directly exercise apply_computed_files with a fresh
// successful payload. The pre-rework bug cleared
// watcher_health via the same code path that clears
// last_error.
app.apply_computed_files(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
assert!(
app.watcher_health
.has_failure(WatchSource::GitRefs, "kqueue overflow"),
"a successful diff recompute must not imply watcher recovery"
);
}
#[test]
fn input_health_survives_successful_recompute_through_apply_computed_files() {
let mut app = fake_app(vec![]);
app.input_health = Some("input: stream hiccup".into());
app.apply_computed_files(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
assert_eq!(
app.input_health.as_deref(),
Some("input: stream hiccup"),
"a successful diff recompute must not imply input recovery"
);
}
#[test]
fn handle_watch_burst_clears_failed_health_for_the_same_source_only() {
let mut app = fake_app(vec![]);
app.watcher_health.record_failure(
WatchSource::Worktree,
"watcher [worktree]: transient".into(),
);
let (need_recompute, _) = app.handle_watch_burst([WatchEvent::Worktree]);
assert!(need_recompute, "Worktree event still triggers a recompute");
assert!(
app.watcher_health.is_healthy(),
"a live event from the same source must clear that source's failure"
);
}
#[test]
fn handle_watch_burst_does_not_flip_healthy_on_mixed_bursts() {
// When a single coalesced burst contains BOTH a live event
// and an Error, the Error wins: the backend may have failed
// after emitting the earlier event and we can't prove
// recovery from a burst that ends in failure. Precedence
// goes to the pessimistic state.
let mut app = fake_app(vec![]);
app.handle_watch_burst([
WatchEvent::Worktree,
WatchEvent::Error {
source: WatchSource::Worktree,
message: "watcher [worktree]: late failure".into(),
},
]);
assert!(
app.watcher_health
.has_failure(WatchSource::Worktree, "late failure"),
"a burst that includes an Error for a source must keep that source failed"
);
}
#[test]
fn handle_watch_burst_does_not_clear_git_failure_when_worktree_recovers() {
let mut app = fake_app(vec![]);
app.watcher_health.record_failure(
WatchSource::GitRefs,
"watcher [git.refs]: still dead".into(),
);
let (need_recompute, need_head_dirty) = app.handle_watch_burst([WatchEvent::Worktree]);
assert!(need_recompute);
assert!(!need_head_dirty);
assert!(
app.watcher_health
.has_failure(WatchSource::GitRefs, "still dead"),
"worktree recovery must not clear an unrelated git watcher failure"
);
}
#[test]
fn handle_watch_burst_does_not_clear_other_git_source_failure() {
let mut app = fake_app(vec![]);
app.watcher_health.record_failure(
WatchSource::GitCommonRoot,
"watcher [git.root]: still dead".into(),
);
let (_, need_head_dirty) =
app.handle_watch_burst([WatchEvent::GitHead(WatchSource::GitRefs)]);
assert!(need_head_dirty);
assert!(
app.watcher_health
.has_failure(WatchSource::GitCommonRoot, "still dead"),
"a GitHead from one git source must not clear a different git source failure"
);
}
#[test]
fn toggle_wrap_lines_clears_in_flight_scroll_animation() {
// Wrap toggling changes the coordinate system that anim
// tweens live in. The cleanest thing to do is snap: clear
// the anim so the next frame draws at the new target and
// no disorienting cross-system tween ever shows up.
let mut app = wrap_regression_app(2, 10);
app.anim = Some(ScrollAnim {
from: 5.0,
start: Instant::now(),
dur: Duration::from_millis(150),
});
app.toggle_wrap_lines();
assert!(
app.anim.is_none(),
"wrap toggle must clear scroll animation to avoid cross-coordinate tween"
);
}
// ---- M4: scar dispatch (a / r canned insertion) -----------------
/// Build an `App` backed by a real tempdir on disk so `insert_scar`
/// can actually read + write the target file. The source files and
/// the `FileDiff` layout are kept in sync by hand — enough to
/// exercise the `a` / `r` keybinding end-to-end without booting a
/// full git repo.
fn scar_app_with_real_fs(
tmp: &tempfile::TempDir,
rel_path: &str,
source: &str,
hunk_new_start: usize,
lines: Vec<DiffLine>,
) -> App {
let abs = tmp.path().join(rel_path);
if let Some(parent) = abs.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&abs, source).expect("seed source file");
let file = make_file(rel_path, vec![hunk(hunk_new_start, lines)], 100);
let mut app = fake_app(vec![file]);
app.root = tmp.path().to_path_buf();
app
}
/// Park the cursor on the Nth DiffLine row in the layout (0-indexed
/// across the whole scroll, not per file). Panics if there aren't
/// enough DiffLine rows — the tests control the layout exactly so
/// this is a loud-failure helper on purpose.
fn cursor_on_nth_diff_line(app: &mut App, n: usize) {
let mut seen = 0;
for (i, row) in app.layout.rows.iter().enumerate() {
if matches!(row, RowKind::DiffLine { .. }) {
if seen == n {
app.scroll_to(i);
return;
}
seen += 1;
}
}
panic!("layout has fewer than {} DiffLine rows", n + 1);
}
#[test]
fn handle_key_a_inserts_ask_scar_above_cursor_line() {
let tmp = tempfile::tempdir().expect("tmp");
// Simulate a diff where line 2 of main.rs was newly added. The
// cursor lands on that added row, and pressing `a` should insert
// the canned "ask" scar directly above it.
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
"fn one() {}\nfn two() {}\n",
2,
vec![diff_line(LineKind::Added, "fn two() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('a')));
let after = std::fs::read_to_string(tmp.path().join("src/main.rs")).expect("read back");
assert_eq!(
after, "fn one() {}\n// @kizu[ask]: explain this change\nfn two() {}\n",
"`a` key must insert the canned ask scar above the cursor row",
);
assert!(
app.last_error.is_none(),
"successful scar insert must not touch last_error"
);
}
#[test]
fn handle_key_r_inserts_reject_scar_above_cursor_line() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"auth.py",
"def main():\n return 1\n",
2,
vec![diff_line(LineKind::Added, " return 1")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('r')));
let after = std::fs::read_to_string(tmp.path().join("auth.py")).expect("read back");
assert_eq!(
after, "def main():\n # @kizu[reject]: revert this change\n return 1\n",
"`r` key must insert the canned reject scar using python # syntax",
);
}
#[test]
fn handle_key_a_is_noop_when_cursor_is_on_a_file_header_row() {
// File header rows have no hunk id → `scar_target_line`
// returns None → `a` must be a no-op. The source file on
// disk stays untouched and no error is recorded.
let tmp = tempfile::tempdir().expect("tmp");
let original = "fn one() {}\n";
let mut app = scar_app_with_real_fs(
&tmp,
"lib.rs",
original,
1,
vec![diff_line(LineKind::Added, "fn one() {}")],
);
// Park the cursor on the FileHeader row explicitly.
let file_header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::FileHeader { .. }))
.expect("file header exists");
app.scroll_to(file_header_row);
app.handle_key(key(KeyCode::Char('a')));
let after = std::fs::read_to_string(tmp.path().join("lib.rs")).expect("read back");
assert_eq!(after, original, "header-row `a` must not touch the file");
assert!(app.last_error.is_none(), "header-row `a` is a clean no-op");
}
#[test]
fn handle_key_a_surfaces_insert_failure_on_last_error() {
// Point `file.path` at a path that does not exist on disk.
// `insert_scar` will fail inside the read phase, and the
// dispatch must surface that through `last_error` without
// panicking.
let tmp = tempfile::tempdir().expect("tmp");
let file = make_file(
"ghost.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "fn missing()")])],
100,
);
let mut app = fake_app(vec![file]);
app.root = tmp.path().to_path_buf();
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('a')));
assert!(
app.last_error
.as_deref()
.is_some_and(|msg| msg.starts_with("scar:")),
"missing-file scar failure must land on last_error, got {:?}",
app.last_error
);
}
#[test]
fn scar_target_line_maps_hunk_header_to_first_changed_line_no_context() {
// Hunk starts immediately with Added lines (no leading context).
// The first changed line IS new_start, so the result equals new_start.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
42,
vec![
diff_line(LineKind::Added, "first"),
diff_line(LineKind::Added, "second"),
],
)],
100,
)]);
let header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::HunkHeader { .. }))
.expect("hunk header row exists");
app.scroll_to(header_row);
let (_, line) = app.scar_target_line().expect("target");
assert_eq!(
line, 42,
"no-context hunk header → first changed line = new_start"
);
}
#[test]
fn scar_target_line_maps_hunk_header_skipping_leading_context() {
// Hunk has 2 leading Context lines before the first Added line.
// The scar should land above the Added line, not above the context.
// new_start=10, context, context, added → target = 10 + 2 = 12.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
10,
vec![
diff_line(LineKind::Context, "ctx1"),
diff_line(LineKind::Context, "ctx2"),
diff_line(LineKind::Added, "new_stuff"),
diff_line(LineKind::Context, "ctx3"),
],
)],
100,
)]);
let header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::HunkHeader { .. }))
.expect("hunk header row exists");
app.scroll_to(header_row);
let (_, line) = app.scar_target_line().expect("target");
assert_eq!(
line, 12,
"hunk header with 2 leading context lines → first changed line at new_start+2"
);
}
#[test]
fn handle_key_a_on_hunk_header_writes_scar_above_first_hunk_line() {
// Real tempdir end-to-end: cursor on the hunk header row,
// press `a`, and the source file should now carry the
// canned ask scar directly above the first body line.
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/lib.rs",
"line_a\nline_b\n",
2,
vec![diff_line(LineKind::Added, "line_b")],
);
let header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::HunkHeader { .. }))
.expect("hunk header row exists");
app.scroll_to(header_row);
app.handle_key(key(KeyCode::Char('a')));
let after = std::fs::read_to_string(tmp.path().join("src/lib.rs")).expect("read back");
assert_eq!(
after, "line_a\n// @kizu[ask]: explain this change\nline_b\n",
"`a` on a hunk header must drop the scar above hunk.new_start",
);
}
// ---- M4 slice 3: `c` free-text scar overlay --------------------
#[test]
fn handle_key_c_opens_scar_comment_overlay_with_captured_target() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/foo.rs",
"fn alpha() {}\nfn beta() {}\n",
2,
vec![diff_line(LineKind::Added, "fn beta() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
let state = app
.scar_comment
.as_ref()
.expect("`c` must open the comment overlay on a diff row");
assert_eq!(state.body, "", "body starts empty");
assert_eq!(state.target_line, 2, "captures current diff-row line");
assert_eq!(
state.target_path,
tmp.path().join("src/foo.rs"),
"captures absolute target path"
);
let after = std::fs::read_to_string(tmp.path().join("src/foo.rs")).expect("read");
assert_eq!(
after, "fn alpha() {}\nfn beta() {}\n",
"`c` must not touch the file until `Enter` commits"
);
}
#[test]
fn handle_key_c_is_noop_on_file_header_row() {
let tmp = tempfile::tempdir().expect("tmp");
let original = "fn one() {}\n";
let mut app = scar_app_with_real_fs(
&tmp,
"lib.rs",
original,
1,
vec![diff_line(LineKind::Added, "fn one() {}")],
);
let header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::FileHeader { .. }))
.expect("file header exists");
app.scroll_to(header_row);
app.handle_key(key(KeyCode::Char('c')));
assert!(
app.scar_comment.is_none(),
"file-header `c` must not open the overlay"
);
}
#[test]
fn scar_comment_typing_appends_characters_to_body() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"a.rs",
"x\ny\n",
2,
vec![diff_line(LineKind::Added, "y")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
app.handle_key(key(KeyCode::Char('h')));
app.handle_key(key(KeyCode::Char('i')));
app.handle_key(key(KeyCode::Char('!')));
let state = app.scar_comment.as_ref().expect("still open");
assert_eq!(state.body, "hi!");
}
#[test]
fn scar_comment_backspace_deletes_last_character() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"a.rs",
"x\ny\n",
2,
vec![diff_line(LineKind::Added, "y")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
for ch in "ab".chars() {
app.handle_key(key(KeyCode::Char(ch)));
}
app.handle_key(key(KeyCode::Backspace));
let state = app.scar_comment.as_ref().expect("still open");
assert_eq!(state.body, "a");
}
#[test]
fn scar_comment_esc_cancels_without_writing_to_file() {
let tmp = tempfile::tempdir().expect("tmp");
let original = "fn one() {}\nfn two() {}\n";
let mut app = scar_app_with_real_fs(
&tmp,
"cancel.rs",
original,
2,
vec![diff_line(LineKind::Added, "fn two() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
for ch in "dont".chars() {
app.handle_key(key(KeyCode::Char(ch)));
}
app.handle_key(key(KeyCode::Esc));
assert!(app.scar_comment.is_none(), "Esc closes the overlay");
let after = std::fs::read_to_string(tmp.path().join("cancel.rs")).expect("read");
assert_eq!(after, original, "cancel must not touch the file");
assert!(app.last_error.is_none(), "cancel is not an error");
}
#[test]
fn scar_comment_enter_commits_free_scar_above_target_line() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"commit.rs",
"fn one() {}\nfn two() {}\n",
2,
vec![diff_line(LineKind::Added, "fn two() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
for ch in "why two?".chars() {
app.handle_key(key(KeyCode::Char(ch)));
}
app.handle_key(key(KeyCode::Enter));
assert!(app.scar_comment.is_none(), "commit closes the overlay");
let after = std::fs::read_to_string(tmp.path().join("commit.rs")).expect("read");
assert_eq!(
after, "fn one() {}\n// @kizu[free]: why two?\nfn two() {}\n",
"Enter must write a free-scar above the captured target line"
);
}
#[test]
fn scar_comment_enter_on_empty_body_is_cancel() {
let tmp = tempfile::tempdir().expect("tmp");
let original = "fn one() {}\nfn two() {}\n";
let mut app = scar_app_with_real_fs(
&tmp,
"empty.rs",
original,
2,
vec![diff_line(LineKind::Added, "fn two() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
app.handle_key(key(KeyCode::Enter));
assert!(
app.scar_comment.is_none(),
"empty commit closes the overlay"
);
let after = std::fs::read_to_string(tmp.path().join("empty.rs")).expect("read");
assert_eq!(after, original, "empty body must not write a blank scar");
}
#[test]
fn normal_keys_are_inert_while_scar_comment_overlay_is_open() {
// While the overlay is open, typing `q` must accumulate into
// the body instead of quitting the app. Proves the router
// correctly parks normal-mode dispatch behind the overlay.
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"quit.rs",
"x\ny\n",
2,
vec![diff_line(LineKind::Added, "y")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('c')));
app.handle_key(key(KeyCode::Char('q')));
assert!(!app.should_quit, "q while overlay open must not quit");
let state = app.scar_comment.as_ref().expect("still open");
assert_eq!(state.body, "q");
}
// ---- M4c: Enter file-view zoom ---------------------------------
#[test]
fn enter_transitions_to_file_view_from_hunk() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
let before_scroll = app.scroll;
app.handle_key(key(KeyCode::Enter));
let fv = app.file_view.as_ref().expect("file view opened");
assert_eq!(fv.path, PathBuf::from("foo.rs"));
assert_eq!(fv.return_scroll, before_scroll);
assert_eq!(fv.lines.len(), 2, "file has 2 lines");
assert_eq!(fv.lines[0], "fn one() {}");
assert_eq!(fv.lines[1], "fn two() {}");
assert!(
fv.line_bg.contains_key(&1),
"line 1 (fn two) should have added bg"
);
assert!(!fv.line_bg.contains_key(&0), "line 0 is context — no bg");
}
#[test]
fn enter_file_view_starts_at_cursor_not_hunk_header() {
// Context + two added lines. The diff surfaces all 3 as
// DiffLine rows: [Context "fn one", Added "fn two", Added
// "fn three"] with `hunk.new_start = 1`. Parking the cursor
// on the 3rd DiffLine (Added "fn three" → new-file line 3)
// must take file view to 0-indexed line 2, NOT to 0 (the old
// behavior which snapped to `hunk.new_start - 1`).
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\nfn three() {}\n",
);
cursor_on_nth_diff_line(&mut app, 2);
app.handle_key(key(KeyCode::Enter));
let fv = app.file_view.as_ref().expect("file view opened");
assert_eq!(
fv.cursor, 2,
"file view cursor must track the diff cursor's new-file line (was snapping to hunk.new_start - 1 = 0)",
);
}
#[test]
fn file_view_esc_returns_to_scroll_and_restores_cursor() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
let saved = app.scroll;
app.handle_key(key(KeyCode::Enter));
assert!(app.file_view.is_some());
app.handle_key(key(KeyCode::Esc));
assert!(app.file_view.is_none(), "Esc closes file view");
assert_eq!(app.scroll, saved, "cursor restored");
}
#[test]
fn file_view_enter_also_exits() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Enter)); // open
app.handle_key(key(KeyCode::Enter)); // close
assert!(app.file_view.is_none());
}
#[test]
fn file_view_j_k_chunk_scroll_and_shift_j_k_single_row() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) =
revert_app_with_real_repo(&tmp, "foo.rs", "a\nb\nc\n", "a\nb\nc\nd\n");
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Enter));
let start = app.file_view.as_ref().unwrap().cursor;
// j moves by chunk_size (viewport/3, at least 1)
let chunk = app.chunk_size();
app.handle_key(key(KeyCode::Char('j')));
let after_j = app.file_view.as_ref().unwrap().cursor;
assert_eq!(after_j, (start + chunk).min(3));
// k reverses it
app.handle_key(key(KeyCode::Char('k')));
assert_eq!(app.file_view.as_ref().unwrap().cursor, start);
// J moves exactly 1 row
app.handle_key(key(KeyCode::Char('J')));
assert_eq!(app.file_view.as_ref().unwrap().cursor, start + 1);
// K reverses 1 row
app.handle_key(key(KeyCode::Char('K')));
assert_eq!(app.file_view.as_ref().unwrap().cursor, start);
}
#[test]
#[allow(non_snake_case)]
fn file_view_g_goes_to_top_and_G_to_bottom() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) =
revert_app_with_real_repo(&tmp, "foo.rs", "a\nb\nc\n", "a\nb\nc\nd\n");
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Enter));
app.handle_key(key(KeyCode::Char('G')));
assert_eq!(app.file_view.as_ref().unwrap().cursor, 3); // 4 lines, 0-indexed last = 3
app.handle_key(key(KeyCode::Char('g')));
assert_eq!(app.file_view.as_ref().unwrap().cursor, 0);
}
#[test]
fn enter_is_noop_on_file_header_row() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
let header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::FileHeader { .. }))
.expect("header");
app.scroll_to(header_row);
app.handle_key(key(KeyCode::Enter));
assert!(app.file_view.is_none());
}
// ---- M4b slice 1: `/` search + first-match jump ---------------
fn find_first_row_matching<F: Fn(&RowKind) -> bool>(app: &App, f: F) -> usize {
app.layout.rows.iter().position(f).expect("row exists")
}
#[test]
fn find_matches_returns_empty_for_empty_query() {
let app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "hello world")])],
100,
)]);
let m = find_matches(&app.layout, &app.files, "");
assert!(m.is_empty());
}
#[test]
fn find_matches_finds_substring_case_insensitive_when_query_is_lowercase() {
let app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "Hello WORLD"),
diff_line(LineKind::Context, "no match here"),
diff_line(LineKind::Added, "World wide"),
],
)],
100,
)]);
let m = find_matches(&app.layout, &app.files, "world");
assert_eq!(m.len(), 2, "smart-case lowercase query matches both rows");
assert!(m.iter().all(|loc| loc.byte_start < loc.byte_end));
}
#[test]
fn find_matches_is_case_sensitive_when_query_has_uppercase() {
let app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "hello World"),
diff_line(LineKind::Added, "hello world"),
],
)],
100,
)]);
let m = find_matches(&app.layout, &app.files, "World");
assert_eq!(m.len(), 1, "uppercase query is case-sensitive");
}
#[test]
fn find_matches_captures_multiple_hits_on_one_row() {
let app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "foo foo foo")])],
100,
)]);
let m = find_matches(&app.layout, &app.files, "foo");
assert_eq!(m.len(), 3);
assert_eq!(m[0].byte_start, 0);
assert_eq!(m[1].byte_start, 4);
assert_eq!(m[2].byte_start, 8);
}
#[test]
fn slash_opens_search_input_composer() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
app.handle_key(key(KeyCode::Char('/')));
assert!(app.search_input.is_some(), "/ must open the composer");
assert_eq!(app.search_input.as_ref().unwrap().query, "");
}
#[test]
fn search_input_typing_appends_to_query_and_backspace_deletes() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "x")])],
100,
)]);
app.handle_key(key(KeyCode::Char('/')));
for c in "foo".chars() {
app.handle_key(key(KeyCode::Char(c)));
}
assert_eq!(app.search_input.as_ref().unwrap().query, "foo");
app.handle_key(key(KeyCode::Backspace));
assert_eq!(app.search_input.as_ref().unwrap().query, "fo");
}
#[test]
fn search_input_esc_cancels_without_installing_search_state() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "foo")])],
100,
)]);
app.handle_key(key(KeyCode::Char('/')));
app.handle_key(key(KeyCode::Char('f')));
app.handle_key(key(KeyCode::Esc));
assert!(app.search_input.is_none());
assert!(app.search.is_none());
}
#[test]
fn search_input_enter_commits_and_jumps_cursor_to_first_match() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "alpha"),
diff_line(LineKind::Added, "beta"),
diff_line(LineKind::Added, "gamma"),
],
)],
100,
)]);
// Park the cursor on the first diff row (alpha).
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('/')));
for c in "beta".chars() {
app.handle_key(key(KeyCode::Char(c)));
}
app.handle_key(key(KeyCode::Enter));
assert!(app.search_input.is_none(), "composer closed on commit");
let state = app.search.as_ref().expect("search installed");
assert_eq!(state.matches.len(), 1);
assert_eq!(state.current, 0);
// Cursor landed on the "beta" row — not the first diff row.
let beta_row =
find_first_row_matching(&app, |r| matches!(r, RowKind::DiffLine { line_idx: 1, .. }));
assert_eq!(app.scroll, beta_row);
assert!(!app.follow_mode, "manual jump drops follow mode");
}
#[test]
fn search_input_enter_with_empty_query_does_not_wipe_existing_search() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "alpha")])],
100,
)]);
// Pre-install a fake confirmed search state.
app.search = Some(SearchState {
query: "alpha".into(),
matches: vec![MatchLocation {
row: 0,
byte_start: 0,
byte_end: 5,
}],
current: 0,
});
app.handle_key(key(KeyCode::Char('/')));
app.handle_key(key(KeyCode::Enter)); // empty body
assert!(
app.search.is_some(),
"empty-query commit must preserve prior search state"
);
}
// ---- M4b slice 2: n/N navigation ------------------------------
fn commit_search(app: &mut App, query: &str) {
app.handle_key(key(KeyCode::Char('/')));
for c in query.chars() {
app.handle_key(key(KeyCode::Char(c)));
}
app.handle_key(key(KeyCode::Enter));
}
#[test]
fn search_jump_next_walks_matches_in_order() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "foo"),
diff_line(LineKind::Added, "bar"),
diff_line(LineKind::Added, "foo"),
diff_line(LineKind::Added, "foo"),
],
)],
100,
)]);
cursor_on_nth_diff_line(&mut app, 0);
commit_search(&mut app, "foo");
// After commit, current = 0 (first foo row). Advance twice.
app.handle_key(key(KeyCode::Char('n')));
let mid = app.search.as_ref().unwrap().current;
app.handle_key(key(KeyCode::Char('n')));
let tail = app.search.as_ref().unwrap().current;
assert_eq!(mid, 1);
assert_eq!(tail, 2);
}
#[test]
fn search_jump_next_wraps_around_at_end() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "foo"),
diff_line(LineKind::Added, "foo"),
],
)],
100,
)]);
cursor_on_nth_diff_line(&mut app, 0);
commit_search(&mut app, "foo");
// current=0 → n → 1 → n → 0 (wrap)
app.handle_key(key(KeyCode::Char('n')));
app.handle_key(key(KeyCode::Char('n')));
assert_eq!(app.search.as_ref().unwrap().current, 0);
}
#[test]
fn search_jump_prev_wraps_around_at_start() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
1,
vec![
diff_line(LineKind::Added, "foo"),
diff_line(LineKind::Added, "foo"),
diff_line(LineKind::Added, "foo"),
],
)],
100,
)]);
cursor_on_nth_diff_line(&mut app, 0);
commit_search(&mut app, "foo");
// current=0 → N → 2 (wrap to tail)
app.handle_key(key(KeyCode::Char('N')));
assert_eq!(app.search.as_ref().unwrap().current, 2);
}
#[test]
fn search_jump_next_is_noop_when_no_search_state() {
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "foo")])],
100,
)]);
cursor_on_nth_diff_line(&mut app, 0);
let before = app.scroll;
app.handle_key(key(KeyCode::Char('n')));
assert!(app.search.is_none());
assert_eq!(app.scroll, before, "stray `n` must not move the cursor");
}
// ---- M4 slice 5: `e` external editor --------------------------
#[test]
fn build_editor_invocation_vim_uses_plus_line_format() {
let inv = build_editor_invocation(Some("vim"), 42, Path::new("/tmp/foo.rs"))
.expect("some invocation");
assert_eq!(inv.program, "vim");
assert_eq!(inv.args, vec!["+42", "/tmp/foo.rs"]);
}
#[test]
fn build_editor_invocation_nvim_preserves_leading_args_and_plus_line() {
let inv = build_editor_invocation(Some("nvim -f"), 7, Path::new("x.rs")).unwrap();
assert_eq!(inv.program, "nvim");
assert_eq!(inv.args, vec!["-f", "+7", "x.rs"]);
}
#[test]
fn build_editor_invocation_zed_uses_colon_line_format() {
let inv = build_editor_invocation(Some("zed"), 10, Path::new("a.rs")).unwrap();
assert_eq!(inv.program, "zed");
assert_eq!(inv.args, vec!["a.rs:10"]);
}
#[test]
fn build_editor_invocation_code_with_flags_uses_colon_format() {
let inv = build_editor_invocation(Some("code --wait --new-window"), 1, Path::new("a.rs"))
.unwrap();
assert_eq!(inv.program, "code");
assert_eq!(inv.args, vec!["--wait", "--new-window", "a.rs:1"]);
}
#[test]
fn build_editor_invocation_helix_uses_colon_format() {
let inv = build_editor_invocation(Some("hx"), 5, Path::new("b.rs")).unwrap();
assert_eq!(inv.program, "hx");
assert_eq!(inv.args, vec!["b.rs:5"]);
}
#[test]
fn build_editor_invocation_nano_uses_plus_line_format() {
let inv = build_editor_invocation(Some("nano"), 3, Path::new("c.py")).unwrap();
assert_eq!(inv.program, "nano");
assert_eq!(inv.args, vec!["+3", "c.py"]);
}
#[test]
fn build_editor_invocation_returns_none_when_env_is_unset() {
assert!(build_editor_invocation(None, 1, Path::new("x.rs")).is_none());
}
#[test]
fn build_editor_invocation_returns_none_when_env_is_blank() {
assert!(build_editor_invocation(Some(" "), 1, Path::new("x.rs")).is_none());
assert!(build_editor_invocation(Some(""), 1, Path::new("x.rs")).is_none());
}
#[test]
fn open_in_editor_pairs_cursor_target_line_with_env_program() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/bar.rs",
"a\nb\n",
2,
vec![diff_line(LineKind::Added, "b")],
);
cursor_on_nth_diff_line(&mut app, 0);
let inv = app.open_in_editor(Some("vim")).expect("invocation");
assert_eq!(inv.program, "vim");
assert_eq!(inv.args.len(), 2);
assert_eq!(inv.args[0], "+2");
assert_eq!(
inv.args[1],
tmp.path().join("src/bar.rs").display().to_string()
);
}
#[test]
fn open_in_editor_returns_none_when_cursor_is_on_file_header() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"lib.rs",
"x\n",
1,
vec![diff_line(LineKind::Added, "x")],
);
let header = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::FileHeader { .. }))
.expect("header");
app.scroll_to(header);
assert!(app.open_in_editor(Some("vim")).is_none());
}
#[test]
fn open_in_editor_returns_none_when_env_is_empty() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"a.rs",
"x\n",
1,
vec![diff_line(LineKind::Added, "x")],
);
cursor_on_nth_diff_line(&mut app, 0);
assert!(app.open_in_editor(None).is_none());
}
// ---- M4 slice 4: `x` hunk revert confirmation dialog ----------
/// Build a real git repo in `tmp` with a single committed file,
/// modify it so there's a one-line diff, bootstrap an App
/// against it, and return both the App and the worktree file
/// path. Lets `x`-key tests exercise the real `git apply
/// --reverse` path end-to-end.
fn revert_app_with_real_repo(
tmp: &tempfile::TempDir,
rel_path: &str,
committed: &str,
modified: &str,
) -> (App, PathBuf) {
use std::process::Command;
let repo = tmp.path();
let run = |args: &[&str]| {
let status = Command::new("git")
.args(args)
.current_dir(repo)
.status()
.expect("git");
assert!(status.success(), "git {args:?} failed");
};
run(&["init", "--quiet", "--initial-branch=main"]);
run(&["config", "user.email", "test@example.com"]);
run(&["config", "user.name", "kizu test"]);
let abs = repo.join(rel_path);
if let Some(parent) = abs.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::fs::write(&abs, committed).expect("seed");
run(&["add", rel_path]);
run(&["commit", "--quiet", "-m", "seed"]);
std::fs::write(&abs, modified).expect("modify");
let app = App::bootstrap(repo.to_path_buf()).expect("bootstrap");
(app, abs)
}
#[test]
fn handle_key_x_opens_revert_confirm_overlay_without_touching_file() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('x')));
let state = app
.revert_confirm
.as_ref()
.expect("x must open the confirmation overlay");
assert_eq!(state.file_path, PathBuf::from("foo.rs"));
assert_eq!(
std::fs::read_to_string(&abs).expect("read"),
"fn one() {}\nfn two() {}\n",
"opening the overlay must not touch the file"
);
}
#[test]
fn revert_confirm_n_cancels_without_reverting() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('x')));
app.handle_key(key(KeyCode::Char('n')));
assert!(app.revert_confirm.is_none(), "`n` must close the overlay");
assert_eq!(
std::fs::read_to_string(&abs).expect("read"),
"fn one() {}\nfn two() {}\n",
"`n` must not touch the worktree"
);
assert!(app.last_error.is_none());
}
#[test]
fn revert_confirm_esc_cancels_without_reverting() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('x')));
app.handle_key(key(KeyCode::Esc));
assert!(app.revert_confirm.is_none());
assert_eq!(
std::fs::read_to_string(&abs).expect("read"),
"fn one() {}\nfn two() {}\n",
"Esc must not touch the worktree"
);
}
#[test]
fn revert_confirm_y_reverts_hunk_on_disk() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('x')));
app.handle_key(key(KeyCode::Char('y')));
assert!(
app.revert_confirm.is_none(),
"confirm must close the overlay"
);
assert_eq!(
std::fs::read_to_string(&abs).expect("read"),
"fn one() {}\n",
"`y` must run git apply --reverse on the target hunk"
);
assert!(
app.last_error.is_none(),
"successful revert leaves last_error clean"
);
}
#[test]
fn revert_confirm_enter_also_confirms() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('x')));
app.handle_key(key(KeyCode::Enter));
assert!(app.revert_confirm.is_none());
assert_eq!(
std::fs::read_to_string(&abs).expect("read"),
"fn one() {}\n"
);
}
#[test]
fn handle_key_x_on_file_header_row_is_noop() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
let file_header_row = app
.layout
.rows
.iter()
.position(|r| matches!(r, RowKind::FileHeader { .. }))
.expect("file header exists");
app.scroll_to(file_header_row);
app.handle_key(key(KeyCode::Char('x')));
assert!(
app.revert_confirm.is_none(),
"x on the file header must not open the overlay"
);
}
#[test]
fn normal_keys_are_inert_while_revert_confirm_overlay_is_open() {
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, _abs) = revert_app_with_real_repo(
&tmp,
"foo.rs",
"fn one() {}\n",
"fn one() {}\nfn two() {}\n",
);
cursor_on_nth_diff_line(&mut app, 0);
app.handle_key(key(KeyCode::Char('x')));
// `q` while the overlay is open must CANCEL the dialog, not quit.
app.handle_key(key(KeyCode::Char('q')));
assert!(!app.should_quit, "q while overlay open must not quit");
assert!(
app.revert_confirm.is_none(),
"any key other than y/Y/Enter closes the dialog"
);
}
#[test]
fn scar_target_line_maps_cursor_on_deleted_line_to_next_live_line() {
// hunk: Added "x" (new file line 10), Deleted "y" (no new pos),
// Added "z" (new file line 11). Cursor on the Deleted
// row should resolve to line 11 — the replacement.
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
10,
vec![
diff_line(LineKind::Added, "x"),
diff_line(LineKind::Deleted, "y"),
diff_line(LineKind::Added, "z"),
],
)],
100,
)]);
// Cursor on the Deleted row (2nd diff line in the hunk = nth=1).
cursor_on_nth_diff_line(&mut app, 1);
let (_, line) = app.scar_target_line().expect("target");
assert_eq!(
line, 11,
"deleted-row cursor must map to the next live line"
);
}
#[test]
fn scar_target_line_on_all_deleted_hunk_returns_hunk_new_start() {
// A pure-deletion hunk has no Added/Context lines in the
// new file. The cursor on any deleted row should still
// resolve to `hunk.new_start` — the position in the new
// file where the deletion gap sits. The scar will land
// above that line (which may be a surviving neighbour or
// the end of the file).
let mut app = fake_app(vec![make_file(
"a.rs",
vec![hunk(
5,
vec![
diff_line(LineKind::Deleted, "gone_a"),
diff_line(LineKind::Deleted, "gone_b"),
diff_line(LineKind::Deleted, "gone_c"),
],
)],
100,
)]);
// Cursor on the first deleted row.
cursor_on_nth_diff_line(&mut app, 0);
let (_, line) = app.scar_target_line().expect("target");
assert_eq!(
line, 5,
"pure-deletion hunk cursor must resolve to hunk.new_start"
);
// Middle deleted row — same target.
cursor_on_nth_diff_line(&mut app, 1);
let (_, line) = app.scar_target_line().expect("target");
assert_eq!(line, 5);
// Last deleted row — same target.
cursor_on_nth_diff_line(&mut app, 2);
let (_, line) = app.scar_target_line().expect("target");
assert_eq!(line, 5);
}
#[test]
fn scar_on_deleted_line_writes_above_next_surviving_line() {
// End-to-end: commit "a\nb\nc\n", worktree becomes "a\nc\n"
// (line "b" deleted). Cursor on the deleted "b" row, press
// `a` → scar should land above line 2 of the new file
// (which is "c", the survivor after the deletion).
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(&tmp, "del.rs", "a\nb\nc\n", "a\nc\n");
// Find the deleted row (LineKind::Deleted for "b").
let del_row = app
.layout
.rows
.iter()
.position(|r| {
if let RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} = r
{
app.files
.get(*file_idx)
.and_then(|f| match &f.content {
DiffContent::Text(hunks) => hunks
.get(*hunk_idx)
.and_then(|h| h.lines.get(*line_idx))
.map(|l| l.kind == LineKind::Deleted),
_ => None,
})
.unwrap_or(false)
} else {
false
}
})
.expect("a deleted row exists");
app.scroll_to(del_row);
app.handle_key(key(KeyCode::Char('a')));
let after = std::fs::read_to_string(&abs).expect("read back");
assert_eq!(
after, "a\n// @kizu[ask]: explain this change\nc\n",
"scar on a deleted row must land above the next surviving line"
);
}
#[test]
fn scar_on_all_deleted_hunk_writes_at_deletion_point() {
// Commit "a\nb\nc\nd\n", worktree "a\nd\n" (lines b,c
// deleted). The hunk's new_start points at the gap between
// "a" and "d". Scar should land above line 2 of the new
// file (which is "d").
let tmp = tempfile::tempdir().expect("tmp");
let (mut app, abs) = revert_app_with_real_repo(&tmp, "gap.rs", "a\nb\nc\nd\n", "a\nd\n");
// Park on the first deleted row.
let del_row = app
.layout
.rows
.iter()
.position(|r| {
if let RowKind::DiffLine {
file_idx,
hunk_idx,
line_idx,
} = r
{
app.files
.get(*file_idx)
.and_then(|f| match &f.content {
DiffContent::Text(hunks) => hunks
.get(*hunk_idx)
.and_then(|h| h.lines.get(*line_idx))
.map(|l| l.kind == LineKind::Deleted),
_ => None,
})
.unwrap_or(false)
} else {
false
}
})
.expect("deleted row");
app.scroll_to(del_row);
app.handle_key(key(KeyCode::Char('a')));
let after = std::fs::read_to_string(&abs).expect("read back");
assert_eq!(
after, "a\n// @kizu[ask]: explain this change\nd\n",
"scar on all-deleted hunk must land at the deletion gap"
);
}
// ---- scar undo stack ----
#[test]
fn insert_canned_scar_pushes_entry_to_undo_stack() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
"fn a() {}\nfn b() {}\n",
2,
vec![diff_line(LineKind::Added, "fn b() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
assert_eq!(app.scar_undo_stack.len(), 1);
let entry = &app.scar_undo_stack[0];
assert_eq!(entry.line_1indexed, 2);
assert_eq!(entry.rendered, "// @kizu[ask]: explain this change");
assert_eq!(entry.path, tmp.path().join("src/main.rs"));
}
#[test]
fn idempotent_scar_reinsert_does_not_grow_undo_stack() {
// Pre-seed the file with the same scar one line above the
// intended target. `insert_scar` sees the duplicate and
// returns `None`, so the undo stack must stay empty (no
// phantom entry that would otherwise cause `u` to "undo" a
// write that never happened).
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
"fn a() {}\n// @kizu[ask]: explain this change\nfn b() {}\n",
1,
vec![diff_line(LineKind::Context, "fn a() {}")],
);
// Use file-view mode to target line 3 (where `fn b` lives)
// deterministically — the line above is the pre-existing scar.
app.file_view = Some(FileViewState {
path: PathBuf::from("src/main.rs"),
return_scroll: 0,
lines: vec![
"fn a() {}".into(),
"// @kizu[ask]: explain this change".into(),
"fn b() {}".into(),
],
line_bg: std::collections::HashMap::new(),
cursor: 2, // 0-indexed → 1-indexed line 3
scroll_top: 0,
anim: None,
visual_top: 0.0,
});
app.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
assert!(
app.scar_undo_stack.is_empty(),
"no-op insert must not push an undo entry"
);
}
#[test]
fn undo_scar_on_empty_stack_is_noop() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
"fn a() {}\n",
1,
vec![diff_line(LineKind::Context, "fn a() {}")],
);
app.undo_scar();
assert!(app.last_error.is_none(), "empty undo must not error");
}
#[test]
fn undo_scar_removes_the_last_inserted_line() {
let tmp = tempfile::tempdir().expect("tmp");
let abs = tmp.path().join("src/main.rs");
let before = "fn a() {}\nfn b() {}\n".to_string();
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
&before,
2,
vec![diff_line(LineKind::Added, "fn b() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
let inserted = std::fs::read_to_string(&abs).expect("read after insert");
assert_ne!(inserted, before);
app.undo_scar();
let after_undo = std::fs::read_to_string(&abs).expect("read after undo");
assert_eq!(after_undo, before, "undo must restore the original file");
assert!(app.scar_undo_stack.is_empty());
}
#[test]
fn undo_scar_mismatch_surfaces_on_last_error_and_pops_stack() {
let tmp = tempfile::tempdir().expect("tmp");
let abs = tmp.path().join("src/main.rs");
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
"fn a() {}\nfn b() {}\n",
2,
vec![diff_line(LineKind::Added, "fn b() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
app.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
// User edits the scar line between insert and undo.
std::fs::write(&abs, "fn a() {}\n// @kizu[ask]: USER EDIT\nfn b() {}\n").expect("rewrite");
app.undo_scar();
assert!(
app.last_error
.as_deref()
.map(|s| s.contains("edited"))
.unwrap_or(false),
"mismatched undo must set a last_error with 'edited', got {:?}",
app.last_error,
);
assert!(app.scar_undo_stack.is_empty(), "entry must still pop");
}
#[test]
fn undo_unwinds_multiple_inserts_in_reverse_order() {
let tmp = tempfile::tempdir().expect("tmp");
let abs = tmp.path().join("src/main.rs");
let before = "fn a() {}\nfn b() {}\nfn c() {}\n".to_string();
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
&before,
2,
vec![diff_line(LineKind::Added, "fn b() {}")],
);
cursor_on_nth_diff_line(&mut app, 0);
// First insertion above line 2.
app.insert_canned_scar(ScarKind::Ask, SCAR_TEXT_ASK);
// Reuse the diff view layout — second insertion at same logical
// position now lands above what shifted to line 3 (the scar
// occupies line 2).
app.insert_canned_scar(ScarKind::Reject, SCAR_TEXT_REJECT);
assert_eq!(app.scar_undo_stack.len(), 2);
// LIFO: the second scar must come off first.
app.undo_scar();
app.undo_scar();
let after = std::fs::read_to_string(&abs).expect("read back");
assert_eq!(after, before, "two undos must fully restore the file");
assert!(app.scar_undo_stack.is_empty());
}
#[test]
fn file_view_scar_target_line_is_cursor_plus_one() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
"line1\nline2\nline3\n",
1,
vec![diff_line(LineKind::Added, "line1")],
);
// Fake a file-view state directly (bypassing open_file_view's
// hunk-centering logic). `cursor: 1` is 0-indexed → scar
// targets 1-indexed line 2.
app.file_view = Some(FileViewState {
path: PathBuf::from("src/main.rs"),
return_scroll: 0,
lines: vec!["line1".into(), "line2".into(), "line3".into()],
line_bg: std::collections::HashMap::new(),
cursor: 1,
scroll_top: 0,
anim: None,
visual_top: 0.0,
});
let (path, line) = app.scar_target_line().expect("target");
assert_eq!(line, 2);
assert_eq!(path, tmp.path().join("src/main.rs"));
}
#[test]
fn file_view_a_key_inserts_scar_at_cursor_line_and_u_undoes() {
let tmp = tempfile::tempdir().expect("tmp");
let abs = tmp.path().join("src/main.rs");
let before = "line1\nline2\nline3\n".to_string();
let mut app = scar_app_with_real_fs(
&tmp,
"src/main.rs",
&before,
1,
vec![diff_line(LineKind::Added, "line1")],
);
// Enter file view programmatically (don't rely on the Enter
// key, which requires the diff layout to have a hunk under
// the cursor).
app.file_view = Some(FileViewState {
path: PathBuf::from("src/main.rs"),
return_scroll: 0,
lines: vec!["line1".into(), "line2".into(), "line3".into()],
line_bg: std::collections::HashMap::new(),
cursor: 1,
scroll_top: 0,
anim: None,
visual_top: 0.0,
});
// `a` in file view must route to insert_canned_scar via
// handle_file_view_key.
app.handle_key(key(KeyCode::Char('a')));
let inserted = std::fs::read_to_string(&abs).expect("read after insert");
assert_eq!(
inserted, "line1\n// @kizu[ask]: explain this change\nline2\nline3\n",
"`a` in file view must scar above the cursor's 1-indexed line"
);
assert_eq!(app.scar_undo_stack.len(), 1);
// `u` in file view reverses that one write.
app.handle_key(key(KeyCode::Char('u')));
let undone = std::fs::read_to_string(&abs).expect("read after undo");
assert_eq!(undone, before, "`u` in file view must undo the scar");
assert!(app.scar_undo_stack.is_empty());
}
#[test]
fn scar_focus_sticks_across_subsequent_recomputes() {
// Regression: the watcher fires a second `recompute_diff` ~300ms
// after the scar write, which used to yank the cursor back to
// the hunk header via `refresh_anchor`. A sticky `scar_focus`
// pin should survive both that second recompute and any further
// ones until the user explicitly navigates.
let mut app = fake_app(vec![make_file(
"src/main.rs",
vec![hunk(
2,
vec![
diff_line(LineKind::Added, "// @kizu[ask]: explain this change"),
diff_line(LineKind::Added, "fn two() {}"),
],
)],
100,
)]);
app.scar_focus = Some((PathBuf::from("/tmp/fake/src/main.rs"), 2));
// Directly drive `apply_computed_files` with the same file
// set — simulates a watcher tick that re-delivers the diff.
// The sticky focus must push the scroll to the scar row (line
// 2 = the Added "// @kizu[ask]..." line), not the hunk header.
let files_snapshot = app.files.clone();
app.apply_computed_files(files_snapshot.clone());
let scroll_after_first = app.scroll;
assert!(
matches!(
app.layout.rows[scroll_after_first],
RowKind::DiffLine { .. }
),
"first recompute must land on a DiffLine, not a header"
);
// Second apply (another watcher tick): focus still sticks.
app.apply_computed_files(files_snapshot);
assert_eq!(
app.scroll, scroll_after_first,
"repeated recomputes must keep the cursor on the scar line"
);
assert!(app.scar_focus.is_some(), "focus persists until user nav");
}
#[test]
fn scar_focus_cleared_by_navigation_keys() {
// After any user navigation in normal mode, the sticky focus
// pin is released so subsequent recomputes follow normal
// anchoring rules (the user has explicitly moved elsewhere).
let mut app = fake_app(vec![make_file(
"src/main.rs",
vec![hunk(1, vec![diff_line(LineKind::Added, "a")])],
100,
)]);
app.scar_focus = Some((PathBuf::from("/tmp/fake/src/main.rs"), 1));
app.handle_key(key(KeyCode::Char('j')));
assert!(
app.scar_focus.is_none(),
"j must clear scar_focus so the next recompute doesn't pull the cursor back"
);
}
// ---- stream mode tests ----
fn make_stream_event(tool: &str, path: &str, diff: Option<&str>, ts: u64) -> StreamEvent {
let mut per_file = std::collections::BTreeMap::new();
if let Some(d) = diff {
per_file.insert(PathBuf::from(path), d.to_string());
}
StreamEvent {
metadata: crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some(tool.into()),
file_paths: vec![PathBuf::from(path)],
cwd: PathBuf::from("/tmp"),
timestamp_ms: ts,
},
per_file_diffs: per_file,
}
}
#[test]
fn handle_event_log_skips_files_outside_project_root() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = fake_app(vec![]);
app.root = tmp.path().to_path_buf();
// Write an event file whose file_path is outside the project root.
let events_dir = tmp.path().join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Write".into()),
file_paths: vec![PathBuf::from("/home/user/.config/kizu/config.toml")],
cwd: tmp.path().to_path_buf(),
timestamp_ms: 1000,
};
let json = serde_json::to_string(&event).unwrap();
let event_path = events_dir.join("1000-Write.json");
std::fs::write(&event_path, &json).unwrap();
app.handle_event_log(event_path);
assert!(
app.stream_events.is_empty(),
"events for files outside project root should be ignored"
);
}
#[test]
fn handle_event_log_accepts_files_inside_project_root() {
let tmp = tempfile::tempdir().expect("tmp");
let mut app = fake_app(vec![]);
app.root = tmp.path().to_path_buf();
let events_dir = tmp.path().join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Write".into()),
file_paths: vec![tmp.path().join("src/main.rs")],
cwd: tmp.path().to_path_buf(),
timestamp_ms: 2000,
};
let json = serde_json::to_string(&event).unwrap();
let event_path = events_dir.join("2000-Write.json");
std::fs::write(&event_path, &json).unwrap();
app.handle_event_log(event_path);
assert_eq!(
app.stream_events.len(),
1,
"events for files inside project root should be accepted"
);
}
#[test]
fn build_stream_files_converts_events_to_file_diffs() {
let events = vec![
make_stream_event(
"Write",
"src/auth.rs",
Some("+fn verify() {}\n+ ok\n"),
1700000000000,
),
make_stream_event("Edit", "src/main.rs", Some("+use auth;\n"), 1700000001000),
];
let files = build_stream_files(&events);
assert_eq!(files.len(), 2);
// First event
assert_eq!(files[0].path, PathBuf::from("src/auth.rs"));
assert_eq!(files[0].added, 2);
assert!(files[0].header_prefix.as_ref().unwrap().contains("Write"));
// Second event
assert_eq!(files[1].path, PathBuf::from("src/main.rs"));
assert_eq!(files[1].added, 1);
assert!(files[1].header_prefix.as_ref().unwrap().contains("Edit"));
}
#[test]
fn build_stream_files_empty_diff_produces_empty_hunk() {
let events = vec![make_stream_event("Write", "a.rs", None, 1000)];
let files = build_stream_files(&events);
assert_eq!(files.len(), 1);
match &files[0].content {
DiffContent::Text(hunks) => assert!(hunks.is_empty()),
_ => panic!("expected Text"),
}
}
#[test]
fn build_stream_files_produces_one_entry_per_path_for_multi_file_event() {
// A single MultiEdit / multi-file Write touches several paths.
// Every path must get its own FileDiff so the stream view does
// not collapse secondary files onto the first path's header.
let mut per_file = std::collections::BTreeMap::new();
per_file.insert(
PathBuf::from("src/a.rs"),
"diff --git a/src/a.rs b/src/a.rs\n@@ -0,0 +1,1 @@\n+a\n".to_string(),
);
per_file.insert(
PathBuf::from("src/b.rs"),
"diff --git a/src/b.rs b/src/b.rs\n@@ -0,0 +1,1 @@\n+b\n".to_string(),
);
let events = vec![StreamEvent {
metadata: crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("MultiEdit".into()),
file_paths: vec![PathBuf::from("src/a.rs"), PathBuf::from("src/b.rs")],
cwd: PathBuf::from("/tmp"),
timestamp_ms: 1_700_000_000_000,
},
per_file_diffs: per_file,
}];
let files = build_stream_files(&events);
assert_eq!(files.len(), 2, "one FileDiff per touched path");
let paths: Vec<&PathBuf> = files.iter().map(|f| &f.path).collect();
assert!(paths.contains(&&PathBuf::from("src/a.rs")));
assert!(paths.contains(&&PathBuf::from("src/b.rs")));
// Each must carry a non-empty hunk (their own `+` line).
for f in &files {
match &f.content {
DiffContent::Text(hunks) => {
assert!(
!hunks.is_empty(),
"per-path FileDiff must have its own hunk, got empty for {:?}",
f.path
);
}
_ => panic!("expected Text content"),
}
}
}
#[test]
fn toggle_view_mode_switches_between_diff_and_stream() {
let mut app = fake_app(vec![]);
assert_eq!(app.view_mode, ViewMode::Diff);
app.toggle_view_mode();
assert_eq!(app.view_mode, ViewMode::Stream);
app.toggle_view_mode();
assert_eq!(app.view_mode, ViewMode::Diff);
}
#[test]
fn tab_key_toggles_view_mode() {
let mut app = fake_app(vec![]);
assert_eq!(app.view_mode, ViewMode::Diff);
app.handle_key(key(KeyCode::Tab));
assert_eq!(app.view_mode, ViewMode::Stream);
app.handle_key(key(KeyCode::Tab));
assert_eq!(app.view_mode, ViewMode::Diff);
}
#[test]
fn compute_operation_diff_returns_new_lines_only() {
let prev = "+added line 1\n context\n";
let curr = "+added line 1\n+added line 2\n context\n";
let op = super::compute_operation_diff(prev, curr);
assert_eq!(op, "+added line 2\n");
}
#[test]
fn compute_operation_diff_empty_when_identical() {
let prev = "+line 1\n+line 2\n";
let op = super::compute_operation_diff(prev, prev);
assert!(op.is_empty());
}
#[test]
fn compute_operation_diff_preserves_duplicate_added_lines() {
// Edit adds another identical `}` line on top of an already-added `}`.
// A set-based diff would drop this because `+}` is already in prev;
// a multiset/count-based diff must preserve the second copy.
let prev = "+fn a() {}\n+}\n";
let curr = "+fn a() {}\n+}\n+}\n";
let op = super::compute_operation_diff(prev, curr);
assert_eq!(op, "+}\n", "second duplicate added line must survive");
}
#[test]
fn compute_operation_diff_preserves_duplicate_blank_lines() {
// Many real edits add blank lines. prev already has one blank,
// curr has two. The NEW blank line must appear in op_diff.
let prev = "+foo\n+\n bar\n";
let curr = "+foo\n+\n+\n bar\n";
let op = super::compute_operation_diff(prev, curr);
assert_eq!(op, "+\n", "second blank-line addition must survive");
}
#[test]
fn apply_reset_clears_stale_diff_snapshots() {
// Previously, `R` would rewrite `baseline_sha` + `files` but
// leave `diff_snapshots` pinned to the OLD baseline. The next
// hook-log-event for a file in the map would then compute
// op_diff against an outdated snapshot — semantic garbage.
// The fix: clear the map on every successful reset so the
// next event rebuilds from the new baseline.
let mut app = fake_app(vec![]);
app.diff_snapshots
.insert(PathBuf::from("stale.rs"), "OLD\n".to_string());
assert!(!app.diff_snapshots.is_empty());
// Simulate a successful reset to a new baseline + branch.
let effect = app.apply_reset(
"new-sha-xxx".to_string(),
Some("refs/heads/main".to_string()),
Ok(Vec::new()),
);
assert_eq!(effect, super::KeyEffect::None);
assert!(
app.diff_snapshots.is_empty(),
"stale diff snapshots must be dropped after a baseline reset"
);
}
#[test]
fn apply_reset_failure_preserves_diff_snapshots() {
// If the reset transaction fails (new SHA unresolvable, etc.)
// the app keeps showing the old diff — and must therefore
// keep the snapshots that were valid against the OLD baseline,
// otherwise the very next event would misattribute lines.
let mut app = fake_app(vec![]);
app.diff_snapshots
.insert(PathBuf::from("keep.rs"), "content\n".to_string());
let effect = app.apply_reset("new-sha".to_string(), None, Err(anyhow::anyhow!("boom")));
assert_eq!(effect, super::KeyEffect::None);
assert_eq!(
app.diff_snapshots.get(&PathBuf::from("keep.rs")),
Some(&"content\n".to_string()),
"failed reset must not touch snapshot state",
);
}
#[test]
fn handle_event_log_accepts_path_with_symlink_variant() {
// On macOS `/tmp` is a symlink to `/private/tmp` (and similarly
// `/var/folders` → `/private/var/folders`). `git rev-parse
// --show-toplevel` canonicalizes, so `app.root` ends up on the
// `/private/...` side. But an agent hook that records the
// current working directory may still write file_paths on the
// symlinked side. A naive `starts_with` comparison silently
// drops those events — which is exactly what the e2e stream
// tests hit on macOS runners. `handle_event_log` must
// canonicalize before matching so symlink-variant paths are
// accepted.
let tmp = tempfile::tempdir().unwrap();
let Ok(canonical_root) = tmp.path().canonicalize() else {
return; // tempdir not canonicalizable; nothing to test.
};
if tmp.path() == canonical_root {
return; // No symlink divergence on this runner; skip.
}
let mut app = fake_app(vec![]);
app.root = canonical_root.clone();
let file_canonical = canonical_root.join("a.rs");
std::fs::write(&file_canonical, "").unwrap();
let symlinked_file = tmp.path().join("a.rs");
let events_dir = canonical_root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Write".into()),
file_paths: vec![symlinked_file],
cwd: canonical_root.clone(),
timestamp_ms: 3000,
};
let event_path = events_dir.join("3000-Write.json");
std::fs::write(&event_path, serde_json::to_string(&event).unwrap()).unwrap();
app.handle_event_log(event_path);
assert_eq!(
app.stream_events.len(),
1,
"event whose file_path resolves to a path inside the canonical root must be accepted"
);
}
#[test]
fn handle_event_log_preserves_snapshot_on_git_error() {
// When `git diff` fails (e.g. baseline SHA is missing after a
// rebase that garbage-collected the old object), the previous
// file snapshot MUST NOT be clobbered — otherwise the next
// event for the same file will compute op_diff against an
// empty baseline and emit the entire cumulative diff as
// "what this operation changed", which is wrong.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let mut app = fake_app(vec![]);
app.root = root.to_path_buf();
// Bogus baseline — every `git diff <bogus> -- file` call will fail.
app.baseline_sha = "0000000000000000000000000000000000000000".to_string();
let file = root.join("foo.rs");
std::fs::write(&file, "fn main() {}\n").unwrap();
// Seed a realistic prior snapshot as if a previous event had
// captured the cumulative baseline → current diff.
let prev_diff = "@@ -1 +1 @@\n-fn main() {}\n+fn main() { 1 }\n".to_string();
app.diff_snapshots.insert(file.clone(), prev_diff.clone());
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![file.clone()],
cwd: root.to_path_buf(),
timestamp_ms: 1000,
};
let event_path = events_dir.join("1000-Edit.json");
std::fs::write(&event_path, serde_json::to_string(&event).unwrap()).unwrap();
app.handle_event_log(event_path);
assert_eq!(
app.diff_snapshots.get(&file),
Some(&prev_diff),
"snapshot must survive a failing `git diff` so the next event is still accurate"
);
}
#[test]
fn handle_event_log_filters_by_explicit_bound_session_id() {
// Under concurrent agent activity on the same repo, a foreign
// session's events must not pollute the stream or
// `diff_snapshots`. When the TUI was started with a
// preconfigured `bound_session_id` (via `KIZU_SESSION_ID`
// or a future CLI flag), `handle_event_log` drops events
// from any other session. Auto-binding was intentionally
// removed because it locked onto whichever session fired
// first — often the wrong one under real concurrency.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
app.bound_session_id = Some("session-A".into());
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
// Matching session: accepted.
let a = crate::hook::SanitizedEvent {
session_id: Some("session-A".into()),
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![root.join("src/a.rs")],
cwd: root.clone(),
timestamp_ms: 10_000,
};
let a_path = events_dir.join("10000-Edit-aaa.json");
std::fs::write(&a_path, serde_json::to_string(&a).unwrap()).unwrap();
app.handle_event_log(a_path);
assert_eq!(
app.stream_events.len(),
1,
"event matching the bound session must be ingested"
);
// Foreign session: dropped.
let b = crate::hook::SanitizedEvent {
session_id: Some("session-B".into()),
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![root.join("src/a.rs")],
cwd: root.clone(),
timestamp_ms: 11_000,
};
let b_path = events_dir.join("11000-Edit-bbb.json");
std::fs::write(&b_path, serde_json::to_string(&b).unwrap()).unwrap();
app.handle_event_log(b_path);
assert_eq!(
app.stream_events.len(),
1,
"foreign-session event must not advance stream or diff_snapshots"
);
}
#[test]
fn handle_event_log_accepts_any_session_when_unbound() {
// When no explicit binding exists (no env / no CLI), we
// accept every session_id instead of auto-latching to the
// first we see. This keeps concurrent-session trap-free:
// users who want strict filtering opt in by setting
// `KIZU_SESSION_ID`.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
assert!(app.bound_session_id.is_none());
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
for (i, sid) in ["session-A", "session-B"].iter().enumerate() {
let ev = crate::hook::SanitizedEvent {
session_id: Some((*sid).into()),
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![root.join(format!("src/{i}.rs"))],
cwd: root.clone(),
timestamp_ms: 20_000 + i as u64,
};
let path = events_dir.join(format!("2000{i}-Edit-{sid}.json"));
std::fs::write(&path, serde_json::to_string(&ev).unwrap()).unwrap();
app.handle_event_log(path);
}
assert_eq!(
app.stream_events.len(),
2,
"unbound TUI must accept events from any session"
);
assert!(
app.bound_session_id.is_none(),
"unbound state must stay unbound; no auto-latch"
);
}
#[test]
fn handle_event_log_filters_out_events_predating_session_start() {
// Two kizu sessions on the same repo: session B must not
// ingest session A's historical events. The earlier
// implementation used `clean_stale_events` to delete the
// shared per-project events directory at startup, which
// destroyed session A's live history. The replacement is a
// timestamp filter: events whose `timestamp_ms` is older
// than this session's start are silently dropped without
// touching the shared files on disk.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
app.session_start_ms = 5_000;
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let old_event = crate::hook::SanitizedEvent {
session_id: Some("other-agent-session".into()),
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![root.join("src/a.rs")],
cwd: root.clone(),
timestamp_ms: 1_000, // earlier than session_start_ms
};
let old_path = events_dir.join("1000-Edit-xyz.json");
std::fs::write(&old_path, serde_json::to_string(&old_event).unwrap()).unwrap();
app.handle_event_log(old_path.clone());
assert!(
app.stream_events.is_empty(),
"pre-session events must be filtered out of stream mode"
);
// The file itself must not be deleted — other sessions may
// still own it. Only the ingest is suppressed.
assert!(
old_path.exists(),
"filter must be non-destructive: leave the event file in place"
);
}
#[test]
fn replay_events_dir_ingests_files_written_during_startup_gap() {
// During startup there is a window between
// `clean_stale_events` and `watcher::start`. Any event
// file written in that gap is never delivered via the
// watcher, so the next event for that file would include
// the dropped operation's contents in its `op_diff`.
// A replay step must drain the directory once at startup
// so no event is silently skipped.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Write".into()),
file_paths: vec![root.join("src/a.rs")],
cwd: root.clone(),
timestamp_ms: 6000,
};
let event_path = events_dir.join("6000-Write-abc.json");
std::fs::write(&event_path, serde_json::to_string(&event).unwrap()).unwrap();
// `replay_events_dir` must scan the directory and feed each
// event through `handle_event_log`, just as the watcher
// would once it is armed.
app.replay_events_dir(&events_dir);
assert_eq!(
app.stream_events.len(),
1,
"replay must ingest the pre-existing event, got: {:?}",
app.stream_events
.iter()
.map(|e| e.metadata.tool_name.as_deref().unwrap_or("?"))
.collect::<Vec<_>>()
);
}
#[test]
fn replay_events_dir_orders_same_millisecond_events_chronologically() {
// Two events in the same millisecond must replay in the
// order they were written, not in alphabetical order by
// tool name. The previous implementation sorted the
// directory by filename, so `<ms>-<tool>-<uniq>.json`
// placed `Edit` before `Write` regardless of which event
// actually fired first. `handle_event_log` advances
// `diff_snapshots` as it goes, so an out-of-order replay
// fabricates the operation diff for whichever event lands
// on the wrong side of the split.
//
// Assertion: `handle_event_log` is called in write order so
// `stream_events` appears in the same order as the on-disk
// write sequence (which we control via the uniqueness
// suffix in the filename).
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
// Same millisecond, different tool names. The *intended*
// write order is `Write` first, then `Edit` — encoded by
// a monotonic uniqueness prefix `001` < `002`.
let first = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Write".into()),
file_paths: vec![root.join("src/x.rs")],
cwd: root.clone(),
timestamp_ms: 20_000,
};
let second = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![root.join("src/x.rs")],
cwd: root.clone(),
timestamp_ms: 20_000,
};
// Use the production filename layout `<ms>-<tool>-<uniq>.json`
// with tool names picked so filename lex sort disagrees with
// write order: `Edit` < `Write` alphabetically, but the
// intended chronological order is `Write` first. Replay
// must honour the write order (derived from on-disk mtime)
// rather than naïve filename sort.
let first_path = events_dir.join("20000-Write-aaa.json");
let second_path = events_dir.join("20000-Edit-zzz.json");
std::fs::write(&first_path, serde_json::to_string(&first).unwrap()).unwrap();
// Ensure distinct on-disk mtimes so the replay's tie-break
// reflects the actual sequence.
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(&second_path, serde_json::to_string(&second).unwrap()).unwrap();
app.replay_events_dir(&events_dir);
let tools: Vec<&str> = app
.stream_events
.iter()
.filter_map(|e| e.metadata.tool_name.as_deref())
.collect();
assert_eq!(
tools,
vec!["Write", "Edit"],
"replay must honour monotonic write order, got {tools:?}"
);
}
#[test]
fn replay_events_dir_does_not_double_process_already_seen_events() {
// If `replay_events_dir` runs and then the watcher also
// delivers the same event (because the watcher was armed
// after the file already existed on some notify backends),
// the event must be recorded exactly once — otherwise
// stream history shows phantom duplicates.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![root.join("src/b.rs")],
cwd: root.clone(),
timestamp_ms: 7000,
};
let event_path = events_dir.join("7000-Edit-def.json");
std::fs::write(&event_path, serde_json::to_string(&event).unwrap()).unwrap();
app.replay_events_dir(&events_dir);
// Simulate the watcher later delivering the same file.
app.handle_event_log(event_path.clone());
assert_eq!(
app.stream_events.len(),
1,
"same event must not be recorded twice"
);
}
#[test]
fn handle_event_log_rejects_parent_traversal_relative_paths() {
// `normalize_event_path` must not accept a relative path that
// escapes the repo via `..`. The earlier implementation only
// checked `root.join(p).starts_with(root)` lexically, so
// `../outside.rs` slipped through (the joined string starts
// with `root` before lexical resolution). Any such path
// would pollute stream mode with rows that sit outside the
// worktree and whose git-diff lookups always fail.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Write".into()),
// Traversal path — lexically begins with root but the
// `..` escapes the worktree.
file_paths: vec![PathBuf::from("../outside.rs")],
cwd: root.clone(),
timestamp_ms: 5000,
};
let event_path = events_dir.join("5000-Write.json");
std::fs::write(&event_path, serde_json::to_string(&event).unwrap()).unwrap();
app.handle_event_log(event_path);
assert!(
app.stream_events.is_empty(),
"traversal path must not pass the repo-root filter, got {:?}",
app.stream_events
.iter()
.map(|e| &e.metadata.file_paths)
.collect::<Vec<_>>()
);
}
#[test]
fn handle_event_log_matches_seeded_snapshot_via_repo_relative_key() {
// `seed_diff_snapshots` keys the map by repo-relative paths
// (from `git::compute_diff`). Agent hooks, however, usually
// emit **absolute** paths. Without normalization, the seeded
// `src/foo.rs` entry is never found for an event on
// `/<root>/src/foo.rs`, so the first event for a
// pre-existing dirty file shows the entire cumulative diff
// as one tool call instead of only the delta.
let tmp = tempfile::tempdir().unwrap();
let root = tmp
.path()
.canonicalize()
.unwrap_or_else(|_| tmp.path().to_path_buf());
let mut app = fake_app(vec![]);
app.root = root.clone();
// Seed map with the repo-relative key, mirroring the
// `git::compute_diff` output shape that `seed_diff_snapshots`
// uses in production.
let rel = PathBuf::from("src/foo.rs");
let seeded = "diff --git a/src/foo.rs b/src/foo.rs\n@@ -1 +1 @@\n-old\n+seed\n".to_string();
app.diff_snapshots.insert(rel.clone(), seeded.clone());
// The agent supplies an absolute path on the repo root.
let abs = root.join(&rel);
let events_dir = root.join("events");
std::fs::create_dir_all(&events_dir).unwrap();
let event = crate::hook::SanitizedEvent {
session_id: None,
hook_event_name: "PostToolUse".into(),
tool_name: Some("Edit".into()),
file_paths: vec![abs.clone()],
cwd: root.clone(),
timestamp_ms: 4000,
};
let event_path = events_dir.join("4000-Edit.json");
std::fs::write(&event_path, serde_json::to_string(&event).unwrap()).unwrap();
app.handle_event_log(event_path);
// After the event fires, both the lookup side and the
// insert side must use the repo-relative key so a subsequent
// seed/event for the same file lands on the same entry.
assert_eq!(
app.diff_snapshots.keys().collect::<Vec<_>>(),
vec![&rel],
"snapshot map must not split one file across raw and repo-relative keys, \
found keys: {:?}",
app.diff_snapshots.keys().collect::<Vec<_>>()
);
// The seeded op_diff was `-old / +seed`. Regardless of what
// the current `git diff` returns (likely Err because no real
// repo), the seeded snapshot must have been consulted — so
// there must be exactly one StreamEvent and it must be keyed
// on the repo-relative path.
assert_eq!(app.stream_events.len(), 1);
let recorded = &app.stream_events[0];
let paths: Vec<&PathBuf> = recorded.metadata.file_paths.iter().collect();
assert_eq!(
paths,
vec![&rel],
"StreamEvent.metadata.file_paths must be stored repo-relative, got {paths:?}"
);
}
#[test]
fn compute_operation_diff_preserves_repeated_context_lines() {
// Two different hunks may share an identical context line
// (e.g. a closing brace). If prev has one hunk containing ` }`
// and curr adds a second hunk that also contains ` }`, the
// second occurrence in curr must appear in op_diff.
let prev = " }\n";
let curr = " }\n+new\n }\n";
let op = super::compute_operation_diff(prev, curr);
// op contains +new and the second occurrence of context ` }`.
assert!(op.contains("+new\n"));
assert!(
op.matches(" }\n").count() == 1,
"one of the two context ` }}` lines is new to curr; exactly one copy should appear"
);
}
}