cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
//! Key event handlers for TUI
//!
//! This module contains helper functions to handle keyboard input in the TUI.

use crate::ai_command_runner::AiCommandRunner;
use crate::config::OrchestratorConfig;
use crate::error::Result;
use crate::tui::events::{LogEntry, OrchestratorEvent, TuiCommand};
use crate::tui::state::AppState;
use crate::tui::types::{AppExecutionMode, ModalState, StopMode};
use crate::vcs::VcsResult;
use async_trait::async_trait;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::DefaultTerminal;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::debug;

use super::terminal::{execute_worktree_command, suspend_terminal_and_execute_sync};
use super::worktrees::load_worktrees_with_conflict_check;

#[async_trait]
trait WorktreePlusRuntime {
    async fn check_git_repo(&self, repo_root: &Path) -> VcsResult<bool>;
    async fn generate_unique_branch_name(
        &self,
        repo_root: &Path,
        prefix: &str,
        max_attempts: u32,
    ) -> VcsResult<String>;
    async fn worktree_add(
        &self,
        repo_root: &Path,
        worktree_path: &str,
        branch_name: &str,
        base_commit: &str,
    ) -> VcsResult<()>;
    async fn validate_worktree_command_cwd(
        &self,
        repo_root: &Path,
        worktree_path: &Path,
    ) -> VcsResult<()>;
    async fn run_worktree_setup(&self, repo_root: &Path, worktree_path: &Path) -> VcsResult<()>;
    async fn worktree_remove_after_setup_failure(
        &self,
        repo_root: &Path,
        worktree_path: &str,
    ) -> VcsResult<()>;
    async fn execute_worktree_command(
        &self,
        terminal: &mut DefaultTerminal,
        command: &str,
        worktree_path: &Path,
        ai_runner: &AiCommandRunner,
        app: &mut AppState,
    ) -> Result<()>;
}

struct ProductionWorktreePlusRuntime;

#[async_trait]
impl WorktreePlusRuntime for ProductionWorktreePlusRuntime {
    async fn check_git_repo(&self, repo_root: &Path) -> VcsResult<bool> {
        crate::vcs::git::commands::check_git_repo(repo_root).await
    }

    async fn generate_unique_branch_name(
        &self,
        repo_root: &Path,
        prefix: &str,
        max_attempts: u32,
    ) -> VcsResult<String> {
        crate::vcs::git::commands::generate_unique_branch_name(repo_root, prefix, max_attempts)
            .await
    }

    async fn worktree_add(
        &self,
        repo_root: &Path,
        worktree_path: &str,
        branch_name: &str,
        base_commit: &str,
    ) -> VcsResult<()> {
        crate::vcs::git::commands::worktree_add(repo_root, worktree_path, branch_name, base_commit)
            .await
    }

    async fn validate_worktree_command_cwd(
        &self,
        repo_root: &Path,
        worktree_path: &Path,
    ) -> VcsResult<()> {
        crate::vcs::git::commands::validate_worktree_command_cwd(repo_root, worktree_path).await
    }

    async fn run_worktree_setup(&self, repo_root: &Path, worktree_path: &Path) -> VcsResult<()> {
        // The TUI-created worktree path only needs success or the actionable
        // failure; the setup report's diagnostics are already logged.
        crate::vcs::git::commands::run_worktree_setup(repo_root, worktree_path)
            .await
            .map(|_report| ())
    }

    async fn worktree_remove_after_setup_failure(
        &self,
        repo_root: &Path,
        worktree_path: &str,
    ) -> VcsResult<()> {
        crate::vcs::git::commands::worktree_remove_with_options(
            repo_root,
            worktree_path,
            crate::vcs::git::commands::WorktreeRemoveOptions {
                skip_teardown: true,
            },
        )
        .await
    }

    async fn execute_worktree_command(
        &self,
        terminal: &mut DefaultTerminal,
        command: &str,
        worktree_path: &Path,
        ai_runner: &AiCommandRunner,
        app: &mut AppState,
    ) -> Result<()> {
        execute_worktree_command(terminal, command, worktree_path, ai_runner, app).await
    }
}

/// Context for key event handling containing necessary state and channels
pub struct KeyEventContext<'a> {
    pub app: &'a mut AppState,
    pub terminal: &'a mut DefaultTerminal,
    pub repo_root: &'a Path,
    pub config: &'a OrchestratorConfig,
    pub worktree_base_dir: &'a Path,
    pub tx: &'a mpsc::Sender<OrchestratorEvent>,
    pub cmd_tx: &'a mpsc::Sender<TuiCommand>,
    pub ai_runner: &'a AiCommandRunner,
    /// The local run supervisor, shared with the run-control service.
    pub supervisor: &'a Arc<crate::tui::run_supervisor::TuiRunSupervisor>,
}

fn request_local_tui_quit(
    app: &mut AppState,
    supervisor: &crate::tui::run_supervisor::TuiRunSupervisor,
) {
    app.should_quit = true;
    if let Some(cancel) = supervisor.cancel_token() {
        cancel.cancel();
        app.add_log(LogEntry::warn(
            "Quit requested: cancelling local orchestration before TUI shutdown",
        ));
    }
}

/// Handle Tab key: Switch between Changes and Worktrees views
pub async fn handle_tab_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;
    let new_view = match ctx.app.view_mode {
        ViewMode::Changes => ViewMode::Worktrees,
        ViewMode::Worktrees => ViewMode::Changes,
    };

    // Load worktrees with conflict check when switching to Worktrees view
    if new_view == ViewMode::Worktrees {
        let load_tx = ctx.tx.clone();
        let load_repo_root = ctx.repo_root.to_path_buf();
        tokio::spawn(async move {
            match load_worktrees_with_conflict_check(&load_repo_root).await {
                Ok(worktrees) => {
                    let _ = load_tx
                        .send(OrchestratorEvent::WorktreesRefreshed { worktrees })
                        .await;
                }
                Err(e) => {
                    let _ = load_tx
                        .send(OrchestratorEvent::Log(LogEntry::error(format!(
                            "Failed to load worktrees: {}",
                            e
                        ))))
                        .await;
                }
            }
        });
    }

    ctx.app.view_mode = new_view;
    Ok(())
}

/// Handle cursor movement keys (Up/Down/k/j)
pub fn handle_cursor_movement(app: &mut AppState, is_up: bool) {
    use crate::tui::types::ViewMode;
    match app.view_mode {
        ViewMode::Changes => {
            if is_up {
                app.cursor_up()
            } else {
                app.cursor_down()
            }
        }
        ViewMode::Worktrees => {
            if is_up {
                app.worktree_cursor_up()
            } else {
                app.worktree_cursor_down()
            }
        }
    }
}

/// Handle 'e' key: Launch editor for change or worktree
pub async fn handle_editor_launch(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    let view_mode = ctx.app.view_mode;
    let change_id = if !ctx.app.changes.is_empty() && ctx.app.cursor_index < ctx.app.changes.len() {
        Some(ctx.app.changes[ctx.app.cursor_index].id.clone())
    } else {
        None
    };
    let worktree_path = ctx.app.get_selected_worktree_path();
    if view_mode == ViewMode::Worktrees && ctx.app.suppress_if_selected_worktree_deleting() {
        ctx.app.add_log(LogEntry::warn(
            "Editor ignored: worktree is already being deleted",
        ));
        return Ok(());
    }

    suspend_terminal_and_execute_sync(ctx.terminal, || {
        // Launch editor based on view mode
        match view_mode {
            ViewMode::Changes => {
                if let Some(id) = change_id {
                    if let Err(e) = crate::tui::utils::launch_editor_for_change(&id) {
                        eprintln!("Failed to launch editor: {}", e);
                    }
                }
            }
            ViewMode::Worktrees => {
                if let Some(path) = worktree_path {
                    if let Err(e) = crate::tui::utils::launch_editor_in_dir(&path) {
                        eprintln!("Failed to launch editor: {}", e);
                    }
                }
            }
        }
        Ok(())
    })
}

/// Handle 'M' key: Merge operations (resolve in Changes view, merge in Worktrees view)
pub async fn handle_merge_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    debug!("M key pressed: view_mode={:?}", ctx.app.view_mode);

    match ctx.app.view_mode {
        ViewMode::Changes => {
            // Changes view: resolve deferred merge
            debug!("M key (Changes view): attempting resolve_merge");
            if let Some(cmd) = ctx.app.resolve_merge() {
                debug!("M key (Changes view): sending command {:?}", cmd);
                let _ = ctx.cmd_tx.send(cmd).await;
            } else {
                debug!("M key (Changes view): resolve_merge returned None");
            }
        }
        ViewMode::Worktrees => {
            // Worktrees view: merge branch to base
            debug!("M key (Worktrees view): attempting request_merge_worktree_branch");
            if let Some(cmd) = ctx.app.request_merge_worktree_branch() {
                debug!("M key (Worktrees view): sending command {:?}", cmd);
                let _ = ctx.cmd_tx.send(cmd).await;
            } else {
                debug!("M key (Worktrees view): request_merge_worktree_branch returned None");
            }
        }
    }
    Ok(())
}

/// What the Esc key must do for the current typed TUI state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EscStopAction {
    /// First Esc: request a graceful stop at the next safe boundary.
    RequestGracefulStop,
    /// Second Esc: enqueue the shared immediate-stop command.
    ///
    /// The key path never applies stop effects itself, so it cannot claim a
    /// force stop from `AppExecutionMode::Stopping` alone.
    RequestImmediateStop,
    /// Esc is not a stop control in this state, or an immediate stop was already
    /// requested and must not be duplicated.
    None,
}

/// Decide the Esc stop action from typed TUI state only.
///
/// `persistent_scheduler_idle` is what separates the two kinds of Ready: pre-run
/// Select has no scheduler to stop and Esc stays inert, while Ready backed by a
/// live idle scheduler keeps the ordinary first-Esc graceful stop and, once that
/// has projected Stopping, the ordinary second-Esc force stop.
pub(crate) fn esc_stop_action(
    mode: &AppExecutionMode,
    stop_mode: &StopMode,
    persistent_scheduler_idle: bool,
) -> EscStopAction {
    match mode {
        AppExecutionMode::Running => EscStopAction::RequestGracefulStop,
        AppExecutionMode::Select if persistent_scheduler_idle => EscStopAction::RequestGracefulStop,
        AppExecutionMode::Stopping if *stop_mode == StopMode::ImmediatePending => {
            EscStopAction::None
        }
        AppExecutionMode::Stopping => EscStopAction::RequestImmediateStop,
        _ => EscStopAction::None,
    }
}

pub(crate) async fn handle_esc_key_inner(app: &mut AppState, cmd_tx: &mpsc::Sender<TuiCommand>) {
    match esc_stop_action(
        &app.execution_mode,
        &app.stop_mode,
        app.persistent_scheduler_idle,
    ) {
        EscStopAction::RequestGracefulStop => {
            // The stop effect itself belongs to the shared service, so the first
            // Esc enqueues the same command a remote `stop` submits. Recording
            // the pending mode here is what makes the second Esc an immediate
            // stop rather than a duplicate graceful request.
            app.stop_mode = StopMode::GracefulPending;
            let _ = cmd_tx.send(TuiCommand::Stop).await;
        }
        EscStopAction::RequestImmediateStop => {
            app.stop_mode = StopMode::ImmediatePending;
            let _ = cmd_tx.send(TuiCommand::ForceStop).await;
        }
        EscStopAction::None => {}
    }
}

/// Handle Esc key: Graceful stop or immediate stop
///
/// The second Esc does not apply stop effects here. It enqueues the shared
/// [`TuiCommand::ForceStop`] so both the key path and the command-dispatch path
/// consume one runtime activity snapshot, issue one cancellation request, and
/// report force stop only when an agent execution was actually active.
pub async fn handle_esc_key(ctx: &mut KeyEventContext<'_>) {
    handle_esc_key_inner(ctx.app, ctx.cmd_tx).await;
}

fn handle_start_key_inner(app: &mut AppState) -> Option<TuiCommand> {
    // Handle the configured start key in Stopping mode to cancel graceful stop.
    // Whether a cancellable run still exists is a runtime fact the shared service
    // owns, so the key path only expresses the intent.
    if app.execution_mode == AppExecutionMode::Stopping {
        return Some(TuiCommand::CancelStop);
    }

    // The configured start key is a cursor-independent orchestration control.
    // It must not inspect the selected row for MergeWait/ResolveWait and must
    // not resolve cursor-local merge waits; Changes-view M is the cursor-local
    // resolve-intent key. Which of start/resume/retry applies is decided by the
    // shared service from the mode it is given.
    Some(TuiCommand::StartProcessing(Vec::new()))
}

/// Handle the configured start key: start, resume, or retry orchestration; or cancel stop.
pub fn handle_start_key(ctx: &mut KeyEventContext<'_>) -> Option<TuiCommand> {
    handle_start_key_inner(ctx.app)
}

/// Handle Enter key: Execute worktree command in selected worktree
pub async fn handle_enter_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    use crate::tui::types::ViewMode;

    if ctx.app.view_mode != ViewMode::Worktrees {
        // Enter on an `error` row opens the Error Details popup. Every other
        // Changes-view row keeps the pre-existing behavior below.
        if ctx.app.open_error_details_popup() {
            return Ok(());
        }
        ctx.app
            .add_log(LogEntry::warn("Enter ignored: not in Worktrees view"));
        return Ok(());
    }

    let Some(worktree_path_str) = ctx.app.get_selected_worktree_path() else {
        ctx.app
            .add_log(LogEntry::warn("Enter ignored: no worktree selected"));
        return Ok(());
    };

    if ctx.app.suppress_if_selected_worktree_deleting() {
        ctx.app.add_log(LogEntry::warn(
            "Enter ignored: worktree is already being deleted",
        ));
        return Ok(());
    }

    let Some(template) = ctx.config.get_worktree_command().map(str::to_string) else {
        ctx.app.add_log(LogEntry::warn(
            "Enter ignored: worktree_command not configured",
        ));
        return Ok(());
    };

    let Some(repo_root_str) = ctx.repo_root.to_str() else {
        ctx.app.add_log(LogEntry::error(
            "Failed to resolve repo root path".to_string(),
        ));
        return Ok(());
    };

    let command =
        OrchestratorConfig::expand_worktree_command(&template, &worktree_path_str, repo_root_str);

    ctx.app.add_log(LogEntry::info(format!(
        "Running worktree command in {}",
        worktree_path_str
    )));

    let worktree_path = Path::new(&worktree_path_str);
    execute_worktree_command(
        ctx.terminal,
        &command,
        worktree_path,
        ctx.ai_runner,
        ctx.app,
    )
    .await
}

/// Handle '+' key: Create new worktree and execute worktree command
pub async fn handle_plus_key(ctx: &mut KeyEventContext<'_>) -> Result<()> {
    handle_plus_key_with_runtime(ctx, &ProductionWorktreePlusRuntime).await
}

struct PreparedWorktreeCommand {
    command: String,
    worktree_path: PathBuf,
}

async fn handle_plus_key_with_runtime(
    ctx: &mut KeyEventContext<'_>,
    runtime: &dyn WorktreePlusRuntime,
) -> Result<()> {
    let Some(prepared) = prepare_plus_worktree_command(
        ctx.app,
        ctx.config,
        ctx.repo_root,
        ctx.worktree_base_dir,
        runtime,
    )
    .await
    else {
        return Ok(());
    };

    runtime
        .execute_worktree_command(
            ctx.terminal,
            &prepared.command,
            &prepared.worktree_path,
            ctx.ai_runner,
            ctx.app,
        )
        .await
}

async fn prepare_plus_worktree_command(
    app: &mut AppState,
    config: &OrchestratorConfig,
    repo_root: &Path,
    worktree_base_dir: &Path,
    runtime: &dyn WorktreePlusRuntime,
) -> Option<PreparedWorktreeCommand> {
    use crate::tui::types::ViewMode;

    // Only work in Worktrees view
    if app.view_mode != ViewMode::Worktrees {
        return None;
    }

    let template = config.get_worktree_command().map(str::to_string)?;

    let is_git_repo = match runtime.check_git_repo(repo_root).await {
        Ok(is_repo) => is_repo,
        Err(err) => {
            app.add_log(LogEntry::error(format!(
                "Failed to check git repo: {}",
                err
            )));
            return None;
        }
    };

    if !super::worktrees::should_trigger_worktree_command(config, is_git_repo) {
        return None;
    }

    if let Err(err) = std::fs::create_dir_all(worktree_base_dir) {
        app.add_log(LogEntry::error(format!(
            "Failed to prepare worktree base dir: {}",
            err
        )));
        return None;
    }

    let worktree_path = super::worktrees::build_worktree_path(worktree_base_dir);
    let Some(worktree_path_str) = worktree_path.to_str() else {
        app.add_log(LogEntry::error(
            "Failed to resolve worktree path".to_string(),
        ));
        return None;
    };
    let Some(repo_root_str) = repo_root.to_str() else {
        app.add_log(LogEntry::error(
            "Failed to resolve repo root path".to_string(),
        ));
        return None;
    };

    // Generate unique branch name with format: ws-session-<random>
    let branch_name = match runtime
        .generate_unique_branch_name(repo_root, "ws-session", 10)
        .await
    {
        Ok(name) => name,
        Err(err) => {
            app.add_log(LogEntry::error(format!(
                "Failed to generate unique branch name: {}",
                err
            )));
            return None;
        }
    };

    // Create worktree with branch instead of detached HEAD
    if let Err(err) = runtime
        .worktree_add(repo_root, worktree_path_str, &branch_name, "HEAD")
        .await
    {
        app.add_log(LogEntry::error(format!(
            "Failed to create worktree: {}",
            err
        )));
        return None;
    }

    app.add_log(LogEntry::info(format!(
        "Created worktree with branch '{}' at {}",
        branch_name, worktree_path_str
    )));

    if !validate_plus_worktree_cwd(app, runtime, repo_root, &worktree_path, "after create").await {
        return None;
    }

    // Execute setup script if it exists
    if let Err(err) = runtime.run_worktree_setup(repo_root, &worktree_path).await {
        app.add_log(LogEntry::error(format!(
            "Failed to run worktree setup for {}: {}",
            worktree_path.display(),
            err
        )));
        app.add_log(LogEntry::warn(format!(
            "Cleaning up worktree after setup failure: {}",
            worktree_path.display()
        )));
        match runtime
            .worktree_remove_after_setup_failure(repo_root, worktree_path_str)
            .await
        {
            Ok(()) => app.add_log(LogEntry::info(format!(
                "Cleaned up worktree after setup failure: {}",
                worktree_path.display()
            ))),
            Err(cleanup_err) => app.add_log(LogEntry::error(format!(
                "Failed to cleanup worktree after setup failure at {}: {}",
                worktree_path.display(),
                cleanup_err
            ))),
        }
        return None;
    }

    if !validate_plus_worktree_cwd(app, runtime, repo_root, &worktree_path, "after setup").await {
        return None;
    }

    if !validate_plus_worktree_cwd(
        app,
        runtime,
        repo_root,
        &worktree_path,
        "before command launch",
    )
    .await
    {
        return None;
    }

    let command =
        OrchestratorConfig::expand_worktree_command(&template, worktree_path_str, repo_root_str);
    app.add_log(LogEntry::info(format!(
        "Running worktree command in {}",
        worktree_path_str
    )));

    Some(PreparedWorktreeCommand {
        command,
        worktree_path,
    })
}

async fn validate_plus_worktree_cwd(
    app: &mut AppState,
    runtime: &dyn WorktreePlusRuntime,
    repo_root: &Path,
    worktree_path: &Path,
    phase: &str,
) -> bool {
    match runtime
        .validate_worktree_command_cwd(repo_root, worktree_path)
        .await
    {
        Ok(()) => true,
        Err(err) => {
            app.add_log(LogEntry::error(format!(
                "Suppressing worktree command launch: invalid cwd {} during {}: {}",
                worktree_path.display(),
                phase,
                err
            )));
            false
        }
    }
}

pub(crate) fn handle_warning_popup_key(app: &mut AppState, key: KeyEvent) -> bool {
    if app.warning_popup.is_none() {
        return false;
    }

    match key.code {
        KeyCode::Esc => {
            app.clear_warning_popup();
        }
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_warning_popup(-1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            app.scroll_warning_popup(1);
        }
        KeyCode::PageUp => {
            app.scroll_warning_popup(-5);
        }
        KeyCode::PageDown => {
            app.scroll_warning_popup(5);
        }
        _ => {}
    }

    true
}

/// Handle input for the Error Details popup.
///
/// The popup owns every key it handles, so scrolling, copying, and closing it
/// cannot move the Changes cursor, the Logs panel, or an interaction modal
/// underneath. It sits below the warning popup (which is dispatched first) and
/// above interaction modals.
///
/// `Ctrl`- and `Alt`-modified keys are deliberately not claimed at all, so
/// `Ctrl+C` keeps its global quit meaning rather than being redefined as the
/// popup copy action. Copy itself is spec'd as *unmodified* `c`, so any other
/// modifier (`Shift`, `Super`, …) is swallowed by the popup without copying.
///
/// Returns true when the key was consumed by the popup.
pub(crate) fn handle_error_details_popup_key(app: &mut AppState, key: KeyEvent) -> bool {
    if app.error_details_popup.is_none() {
        return false;
    }

    if key
        .modifiers
        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        return false;
    }

    match key.code {
        KeyCode::Esc => {
            app.close_error_details_popup();
        }
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_error_details_popup(-1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            app.scroll_error_details_popup(1);
        }
        KeyCode::PageUp => {
            app.scroll_error_details_popup(-5);
        }
        KeyCode::PageDown => {
            app.scroll_error_details_popup(5);
        }
        KeyCode::Char('c') if key.modifiers.is_empty() => {
            app.copy_error_details();
        }
        _ => {}
    }

    true
}

/// Handle input for the active typed modal.
///
/// Modal input sits between warning-popup input (highest priority) and ordinary
/// view input. An active modal consumes *every* key: QR closes on any key, and a
/// confirmation acts only on its documented keys while still swallowing the rest,
/// so `x`, navigation, stop, and retry can never leak to the view underneath.
///
/// Returns true when the key was consumed by a modal.
pub(crate) async fn handle_modal_key(key: KeyEvent, ctx: &mut KeyEventContext<'_>) -> bool {
    let Some(modal) = ctx.app.modal.clone() else {
        return false;
    };

    match modal {
        ModalState::QrPopup => {
            ctx.app.hide_qr_popup();
        }
        ModalState::ConfirmForceKill { .. } => match (key.code, key.modifiers) {
            (KeyCode::Char('y'), _) | (KeyCode::Char('Y'), _) => {
                if let Some(cmd) = ctx.app.confirm_force_kill() {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) | (KeyCode::Esc, _) => {
                ctx.app.cancel_force_kill();
            }
            _ => {}
        },
        ModalState::ConfirmWorktreeDelete { .. } => match (key.code, key.modifiers) {
            (KeyCode::Char('y'), _) | (KeyCode::Char('Y'), _) => {
                if let Some(cmd) = ctx.app.confirm_worktree_action_delete() {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) | (KeyCode::Esc, _) => {
                ctx.app.cancel_worktree_action();
            }
            (KeyCode::Char('s'), _) | (KeyCode::Char('S'), _) => {
                if let Some(cmd) = ctx.app.confirm_worktree_action_delete_with_options(true) {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            _ => {}
        },
        // Uppercase `X` alone discards uncommitted work. The keys that opened
        // this confirmation — `Y` and `S` — deliberately do nothing here: an
        // operator repeating the keypress that got them a refusal must not
        // thereby grant the permission the refusal was about. Lowercase `x` is
        // the Changes view's bulk-mark key and is likewise inert, so a mistimed
        // habit cannot destroy work.
        ModalState::ConfirmDirtyDiscard { .. } => match (key.code, key.modifiers) {
            (KeyCode::Char('X'), _) => {
                if let Some(cmd) = ctx.app.confirm_dirty_discard() {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) | (KeyCode::Esc, _) => {
                ctx.app.cancel_worktree_action();
            }
            _ => {}
        },
        // Same fail-safe key set, for the heavier decision: `X` here also
        // deletes an unmerged branch, so `Y`, `S`, and lowercase `x` stay just
        // as inert as they are in the dirty confirmation.
        ModalState::ConfirmAheadDiscard { .. } => match (key.code, key.modifiers) {
            (KeyCode::Char('X'), _) => {
                if let Some(cmd) = ctx.app.confirm_ahead_discard() {
                    let _ = ctx.cmd_tx.send(cmd).await;
                }
            }
            (KeyCode::Char('n'), _) | (KeyCode::Char('N'), _) | (KeyCode::Esc, _) => {
                ctx.app.cancel_worktree_action();
            }
            _ => {}
        },
    }

    true
}

/// Handle the bulk execution-mark toggle (`x`) in the Changes view.
///
/// Target classification and exclusion reporting are enforced in
/// `AppState::toggle_all_marks`, which writes next-run intent and nothing else:
/// no queue command is emitted in any execution mode, matching single-row Space
/// semantics.
pub(crate) fn handle_bulk_toggle_key(app: &mut AppState) -> Vec<TuiCommand> {
    use crate::tui::types::ViewMode;
    if app.view_mode != ViewMode::Changes {
        return Vec::new();
    }

    app.toggle_all_marks()
}

/// Handle the selected-proposal log filter toggle (`f`) in the Changes view.
///
/// This is presentation-only: it changes which buffered entries the Logs panel
/// renders and never touches execution marks, queue state, or any other
/// workflow-control input. Other views ignore the key.
pub(crate) fn handle_selected_proposal_log_filter_key(app: &mut AppState) {
    use crate::tui::types::ViewMode;
    if app.view_mode != ViewMode::Changes {
        return;
    }

    app.toggle_selected_proposal_log_filter();
}

/// Handle main key events
///
/// Returns Some(TuiCommand) if the key event should trigger the configured start control
pub async fn handle_key_event(
    key: KeyEvent,
    ctx: &mut KeyEventContext<'_>,
) -> Result<Option<TuiCommand>> {
    // Clear the legacy one-line warning message up front so a handler that sets
    // a new warning during this key press keeps it visible.
    ctx.app.warning_message = None;

    if handle_warning_popup_key(ctx.app, key) {
        return Ok(None);
    }

    if handle_error_details_popup_key(ctx.app, key) {
        return Ok(None);
    }

    if handle_modal_key(key, ctx).await {
        return Ok(None);
    }

    let mut cmd_to_start: Option<TuiCommand> = None;

    match (key.code, key.modifiers) {
        (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
            request_local_tui_quit(ctx.app, ctx.supervisor);
        }
        (KeyCode::Tab, _) => {
            handle_tab_key(ctx).await?;
        }
        (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
            handle_cursor_movement(ctx.app, true);
        }
        (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
            handle_cursor_movement(ctx.app, false);
        }
        (KeyCode::Char(' '), _) => {
            // Marks are process-local intent, so this emits no command at all:
            // the pending mark write is drained through the shared store.
            ctx.app.toggle_selection();
        }
        (KeyCode::Char('x'), _) => {
            for cmd in handle_bulk_toggle_key(ctx.app) {
                let _ = ctx.cmd_tx.send(cmd).await;
            }
        }

        (KeyCode::Char('e'), _) => {
            handle_editor_launch(ctx).await?;
        }
        (KeyCode::Char('m'), _) | (KeyCode::Char('M'), _) => {
            handle_merge_key(ctx).await?;
        }
        (KeyCode::Char('d'), _) => {
            use crate::tui::types::ViewMode;
            match ctx.app.view_mode {
                // Worktree view: delete selected worktree. Unchanged, and the
                // only `d` that touches the repository.
                ViewMode::Worktrees => {
                    ctx.app.request_worktree_delete_from_list();
                }
                // Changes view: hide the focused `merged` row immediately. No
                // confirmation — this is presentation-only and a restart brings
                // the row back. A non-merged row is a silent no-op.
                ViewMode::Changes => {
                    ctx.app.dismiss_merged_row();
                }
            }
        }
        (KeyCode::Char('D'), _) => {
            use crate::tui::types::ViewMode;
            match ctx.app.view_mode {
                ViewMode::Worktrees => {
                    ctx.app.request_worktree_delete_from_list();
                }
                // Changes view: hide every projected `merged` row immediately.
                // An empty target set is a silent no-op.
                ViewMode::Changes => {
                    ctx.app.dismiss_all_merged_rows();
                }
            }
        }
        (KeyCode::Esc, _) => {
            handle_esc_key(ctx).await;
        }
        _ if ctx.app.tui_config.matches_start_key(&key) => {
            cmd_to_start = handle_start_key(ctx);
        }
        (KeyCode::PageUp, _) => {
            // Scroll logs up (show older entries)
            ctx.app.scroll_logs_up(5);
        }
        (KeyCode::PageDown, _) => {
            // Scroll logs down (show newer entries)
            ctx.app.scroll_logs_down(5);
        }
        (KeyCode::Home, _) => {
            // Jump to oldest log entry
            ctx.app.scroll_logs_to_top();
        }
        (KeyCode::End, _) => {
            // Jump to newest log entry and re-enable auto-scroll
            ctx.app.scroll_logs_to_bottom();
        }
        (KeyCode::Enter, _) => {
            handle_enter_key(ctx).await?;
        }
        (KeyCode::Char('+'), _) => {
            handle_plus_key(ctx).await?;
        }
        (KeyCode::Char('w'), _) if ctx.app.web_url.is_some() => {
            // Show QR code popup (only if web_url is set)
            ctx.app.show_qr_popup();
        }
        (KeyCode::Char('l'), _) => {
            // Toggle log panel visibility (only in Changes view)
            use crate::tui::types::ViewMode;
            if ctx.app.view_mode == ViewMode::Changes {
                ctx.app.toggle_logs_panel();
            }
        }
        (KeyCode::Char('f'), _) => {
            handle_selected_proposal_log_filter_key(ctx.app);
        }
        (KeyCode::Char('K'), _) => {
            // Open the force-kill confirmation overlay for active changes in
            // Running mode. Only the modal axis moves; execution stays Running.
            ctx.app.request_force_kill_confirmation();
        }
        _ => {}
    }

    Ok(cmd_to_start)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::openspec::{Change, ProposalMetadata};
    use crate::tui::config::TuiConfig;
    use crate::tui::types::ViewMode;
    use crossterm::event::KeyCode;
    use std::sync::atomic::Ordering;

    fn create_test_change(id: &str) -> Change {
        Change {
            id: id.to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: ProposalMetadata::default(),
        }
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// A supervisor with no launch context behind it.
    ///
    /// Key handling only ever asks the supervisor for the live cancellation
    /// token, so an unstarted supervisor is the whole surface these tests need.
    fn idle_supervisor() -> Arc<crate::tui::run_supervisor::TuiRunSupervisor> {
        let (tx, _rx) = mpsc::channel(1);
        let state = Arc::new(tokio::sync::RwLock::new(
            crate::orchestration::state::OrchestratorState::new(Vec::new(), 1),
        ));
        Arc::new(crate::tui::run_supervisor::TuiRunSupervisor::new(
            PathBuf::from("."),
            OrchestratorConfig::default(),
            Arc::new(crate::events::EventDispatcher::new(
                state.clone(),
                vec![Arc::new(crate::tui::events::TuiEventSink::new(tx))],
            )),
            crate::tui::queue::DynamicQueue::new(),
            state,
            Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            crate::parallel::PostArchiveAction::MergeToBase,
            None,
            Arc::new(std::sync::atomic::AtomicBool::new(false)),
        ))
    }

    /// Logs panel wide enough that each short entry is exactly one display line.
    const LOG_VIEWPORT_WIDTH: usize = 60;
    /// Panel height 7 => 5 usable rows.
    const LOG_VIEWPORT_HEIGHT: usize = 7;

    fn log_nav_app(entries: usize) -> AppState {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        app.logs.clear();
        app.set_log_viewport(LOG_VIEWPORT_WIDTH, LOG_VIEWPORT_HEIGHT);
        for index in 0..entries {
            app.add_log(LogEntry::info(format!("log {index}")));
        }
        app
    }

    /// Messages rendered by the current anchor, oldest first.
    fn visible_log_text(app: &AppState) -> Vec<String> {
        let lines = app.log_display_lines();
        let start = app.log_start_line(&lines);
        let end = lines.len().min(start + app.log_viewport.visible_height());
        lines[start..end]
            .iter()
            .map(|line| line.text.clone())
            .collect()
    }

    #[test]
    fn log_navigation_state_methods_preserve_existing_key_semantics() {
        // 12 short entries => 12 display lines, 5 visible rows.
        let mut app = log_nav_app(12);
        assert_eq!(app.log_anchor, None);
        assert!(app.log_auto_scroll);
        assert_eq!(visible_log_text(&app).first().unwrap(), "log 7");

        app.scroll_logs_up(5);
        assert!(!app.log_auto_scroll);
        assert_eq!(visible_log_text(&app).first().unwrap(), "log 2");

        app.scroll_logs_down(5);
        assert_eq!(app.log_anchor, None);
        assert!(app.log_auto_scroll);
        assert_eq!(visible_log_text(&app).first().unwrap(), "log 7");

        app.scroll_logs_to_top();
        assert!(!app.log_auto_scroll);
        assert_eq!(visible_log_text(&app).first().unwrap(), "log 0");

        app.scroll_logs_to_bottom();
        assert_eq!(app.log_anchor, None);
        assert!(app.log_auto_scroll);
        assert_eq!(visible_log_text(&app).first().unwrap(), "log 7");

        assert!(app.logs_panel_enabled);
        app.toggle_logs_panel();
        assert!(!app.logs_panel_enabled);
        app.toggle_logs_panel();
        assert!(app.logs_panel_enabled);
    }

    /// A single entry whose wrapped height far exceeds the viewport.
    ///
    /// 60 columns - 2 borders - 9 timestamp = 49 message columns on the first
    /// line and 58 on every continuation line, so 1,000 characters wrap to 18
    /// display lines against 5 visible rows.
    fn oversized_entry_app() -> AppState {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        app.logs.clear();
        app.set_log_viewport(LOG_VIEWPORT_WIDTH, LOG_VIEWPORT_HEIGHT);
        let message: String = (0..1000)
            .map(|i| char::from(b'a' + (i % 26) as u8))
            .collect();
        app.add_log(LogEntry::info(message));
        app
    }

    #[test]
    fn page_keys_move_inside_one_entry_taller_than_the_viewport() {
        let mut app = oversized_entry_app();
        let total = app.log_display_lines().len();
        assert_eq!(total, 18);
        assert!(total > app.log_viewport.visible_height());

        // Auto-scroll shows the tail of the entry, not its head.
        assert_eq!(app.log_start_line(&app.log_display_lines()), 13);

        // Home reaches the first wrapped segment of that same entry.
        app.scroll_logs_to_top();
        assert_eq!(app.log_start_line(&app.log_display_lines()), 0);
        assert_eq!(app.log_anchor.unwrap().source_byte_offset, 0);
        assert!(!app.log_auto_scroll);

        // PgDn walks forward one display page at a time, still inside the entry.
        app.scroll_logs_down(5);
        assert_eq!(app.log_start_line(&app.log_display_lines()), 5);
        assert!(!app.log_auto_scroll);

        // PgUp walks back to the line it came from.
        app.scroll_logs_up(5);
        assert_eq!(app.log_start_line(&app.log_display_lines()), 0);

        // Reaching the newest line re-enables auto-scroll.
        app.scroll_logs_down(total);
        assert!(app.log_auto_scroll);
        assert_eq!(app.log_anchor, None);
    }

    #[tokio::test]
    async fn routed_page_keys_navigate_display_lines_without_changing_assignments() {
        let mut app = oversized_entry_app();

        route_key_event(&mut app, key(KeyCode::Home)).await;
        assert_eq!(app.log_start_line(&app.log_display_lines()), 0);

        route_key_event(&mut app, key(KeyCode::PageDown)).await;
        assert_eq!(app.log_start_line(&app.log_display_lines()), 5);

        route_key_event(&mut app, key(KeyCode::PageUp)).await;
        assert_eq!(app.log_start_line(&app.log_display_lines()), 0);

        route_key_event(&mut app, key(KeyCode::End)).await;
        assert!(app.log_auto_scroll);
        assert_eq!(app.log_start_line(&app.log_display_lines()), 13);
    }

    #[test]
    fn anchor_survives_a_width_change_and_stays_on_the_same_source_content() {
        let mut app = oversized_entry_app();
        app.scroll_logs_to_top();
        app.scroll_logs_down(3);
        let anchored_offset = app.log_anchor.unwrap().source_byte_offset;
        assert_eq!(anchored_offset, 49 + 2 * 58);

        // A wider panel re-wraps everything; the anchor keeps the same source
        // position rather than resetting to the newest line.
        app.set_log_viewport(120, LOG_VIEWPORT_HEIGHT);
        let lines = app.log_display_lines();
        let start = app.log_start_line(&lines);
        let line = &lines[start];
        assert!(line.source_byte_offset <= anchored_offset);
        assert!(anchored_offset < line.source_byte_offset + line.text.len());
        assert!(!app.log_auto_scroll);
    }

    #[test]
    fn appending_logs_keeps_a_manual_anchor_and_a_stale_one_clamps() {
        let mut app = log_nav_app(12);
        app.scroll_logs_to_top();
        let anchor = app.log_anchor.unwrap();

        app.add_log(LogEntry::info("newest"));
        assert_eq!(
            app.log_anchor,
            Some(anchor),
            "append must not move a manual anchor"
        );
        assert_eq!(visible_log_text(&app).first().unwrap(), "log 0");
        assert!(!app.log_auto_scroll);

        // An anchor newer than every surviving line clamps to the last page
        // instead of overrunning, and never silently resumes auto-scroll.
        app.log_anchor = Some(crate::tui::state::log_logic::LogViewAnchor {
            entry_seq: u64::MAX - 1,
            source_byte_offset: 0,
        });
        let lines = app.log_display_lines();
        assert_eq!(
            app.log_start_line(&lines),
            lines
                .len()
                .saturating_sub(app.log_viewport.visible_height())
        );
        assert!(
            !app.log_auto_scroll,
            "clamping must not re-enable auto-scroll"
        );
    }

    fn log_filter_app() -> AppState {
        let mut app = AppState::new(vec![
            create_test_change("alpha"),
            create_test_change("beta"),
        ]);
        app.logs.clear();
        app.add_log(LogEntry::info("alpha apply").with_change_id("alpha"));
        app.add_log(LogEntry::info("beta apply").with_change_id("beta"));
        app.add_log(LogEntry::info("global orchestration"));
        app
    }

    #[test]
    fn f_key_toggles_selected_proposal_log_filter_in_changes_view() {
        let mut app = log_filter_app();
        assert!(!app.selected_proposal_log_filter);

        handle_selected_proposal_log_filter_key(&mut app);
        assert!(app.selected_proposal_log_filter);
        assert_eq!(app.selected_proposal_log_filter_target(), Some("alpha"));

        handle_selected_proposal_log_filter_key(&mut app);
        assert!(!app.selected_proposal_log_filter);
    }

    #[test]
    fn f_key_does_not_change_execution_marks_cursor_or_log_panel_visibility() {
        let mut app = log_filter_app();
        app.changes[0].selected = true;
        app.changes[1].selected = false;
        let statuses_before: Vec<String> = app
            .changes
            .iter()
            .map(|c| c.display_status_cache.clone())
            .collect();

        handle_selected_proposal_log_filter_key(&mut app);

        assert!(app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert_eq!(app.cursor_index, 0);
        assert!(app.logs_panel_enabled);
        assert_eq!(app.logs.len(), 3);
        let statuses_after: Vec<String> = app
            .changes
            .iter()
            .map(|c| c.display_status_cache.clone())
            .collect();
        assert_eq!(statuses_before, statuses_after);
    }

    #[test]
    fn f_key_is_ignored_in_worktrees_view() {
        let mut app = log_filter_app();
        app.view_mode = ViewMode::Worktrees;

        handle_selected_proposal_log_filter_key(&mut app);

        assert!(!app.selected_proposal_log_filter);
    }

    #[test]
    fn f_key_leaves_existing_log_panel_and_scroll_keys_intact() {
        let mut app = log_filter_app();

        // `l` semantics are unchanged by the new filter key.
        app.toggle_logs_panel();
        assert!(!app.logs_panel_enabled);
        handle_selected_proposal_log_filter_key(&mut app);
        assert!(!app.logs_panel_enabled);

        // Filtering returns to newest output; PageUp still scrolls back.
        app.scroll_logs_up(5);
        assert!(!app.log_auto_scroll);
        handle_selected_proposal_log_filter_key(&mut app);
        assert_eq!(app.log_anchor, None);
        assert!(app.log_auto_scroll);
    }

    #[test]
    fn configured_start_key_matches_default_and_custom_bindings() {
        let mut app = AppState::new(vec![create_test_change("run-me")]);
        app.changes[0].selected = true;

        assert!(app.tui_config.matches_start_key(&key(KeyCode::F(5))));
        assert!(app.tui_config.matches_start_key(&key(KeyCode::Char('!'))));

        let custom = TuiConfig::parse_jsonc(
            r#"{"keybindings":{"start":["F5","!"]}}"#,
            std::path::Path::new("/tmp/tui.jsonc"),
        )
        .unwrap();
        app.set_tui_config(custom);

        assert!(app.tui_config.matches_start_key(&key(KeyCode::F(5))));
        assert!(app.tui_config.matches_start_key(&key(KeyCode::Char('!'))));
        assert!(!app.tui_config.matches_start_key(&key(KeyCode::Char('x'))));
    }

    #[test]
    fn configured_start_key_triggers_same_command_as_f5() {
        let custom = TuiConfig::parse_jsonc(
            r#"{"keybindings":{"start":["F5","!"]}}"#,
            std::path::Path::new("/tmp/tui.jsonc"),
        )
        .unwrap();

        let mut f5_app = AppState::new(vec![create_test_change("run-me")]);
        f5_app.set_tui_config(custom.clone());
        f5_app.changes[0].selected = true;
        let f5_command = if f5_app.tui_config.matches_start_key(&key(KeyCode::F(5))) {
            handle_start_key_inner(&mut f5_app)
        } else {
            None
        };

        let mut bang_app = AppState::new(vec![create_test_change("run-me")]);
        bang_app.set_tui_config(custom);
        bang_app.changes[0].selected = true;
        let bang_command = if bang_app
            .tui_config
            .matches_start_key(&key(KeyCode::Char('!')))
        {
            handle_start_key_inner(&mut bang_app)
        } else {
            None
        };

        assert_eq!(format!("{:?}", f5_command), format!("{:?}", bang_command));
        assert!(matches!(
            bang_command,
            Some(TuiCommand::StartProcessing(ids)) if ids.is_empty()
        ));
    }

    /// The start key is cursor-independent: it never inspects the row under the
    /// cursor, so a merge-wait row can never turn it into a resolve.
    #[test]
    fn start_key_never_emits_resolve_merge_for_the_row_under_the_cursor() {
        let mut app = AppState::new(vec![
            create_test_change("merge-wait"),
            create_test_change("run-me"),
        ]);
        app.execution_mode = AppExecutionMode::Select;
        app.cursor_index = 0;
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.changes[1].selected = true;

        let command = handle_start_key_inner(&mut app);

        assert!(matches!(
            command,
            Some(TuiCommand::StartProcessing(ids)) if ids.is_empty()
        ));
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
    }

    /// Target selection belongs to the shared service, so the key path emits the
    /// same command in Select, Stopped, and Error mode; only Stopping differs,
    /// where the start key withdraws a pending graceful stop.
    #[test]
    fn start_key_emits_one_command_per_mode_class() {
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            let mut app = AppState::new(vec![create_test_change("a")]);
            app.execution_mode = mode;
            app.set_resolving("__active__");
            assert!(
                matches!(
                    handle_start_key_inner(&mut app),
                    Some(TuiCommand::StartProcessing(ref ids)) if ids.is_empty()
                ),
                "{mode:?} must delegate start to the shared service"
            );
            assert!(app.warning_message.is_none());
        }

        let mut stopping = AppState::new(vec![create_test_change("a")]);
        stopping.execution_mode = AppExecutionMode::Stopping;
        assert!(matches!(
            handle_start_key_inner(&mut stopping),
            Some(TuiCommand::CancelStop)
        ));
    }

    #[test]
    fn warning_popup_scroll_keys_do_not_move_underlying_cursor_or_close_popup() {
        let mut app = AppState::new(vec![create_test_change("a"), create_test_change("b")]);
        app.show_warning_popup("warning", "line 1\nline 2\nline 3");
        let cursor_before = app.cursor_index;

        assert!(handle_warning_popup_key(&mut app, key(KeyCode::Down)));

        assert_eq!(app.cursor_index, cursor_before);
        assert_eq!(app.warning_popup_scroll, 1);
        assert!(app.warning_popup.is_some());
    }

    #[test]
    fn warning_popup_close_key_clears_popup_and_resets_scroll() {
        let mut app = AppState::new(vec![create_test_change("a")]);
        app.show_warning_popup("warning", "diagnostic");
        app.warning_popup_scroll = 7;

        assert!(handle_warning_popup_key(&mut app, key(KeyCode::Esc)));

        assert!(app.warning_popup.is_none());
        assert_eq!(app.warning_popup_scroll, 0);
    }

    #[test]
    fn warning_popup_ignores_non_popup_keys_without_underlying_action() {
        let mut app = AppState::new(vec![create_test_change("a"), create_test_change("b")]);
        app.show_warning_popup("warning", "diagnostic");
        let cursor_before = app.cursor_index;

        assert!(handle_warning_popup_key(&mut app, key(KeyCode::Char('x'))));

        assert_eq!(app.cursor_index, cursor_before);
        assert_eq!(app.warning_popup_scroll, 0);
        assert!(app.warning_popup.is_some());
    }
    struct StubPlusRuntime {
        is_git_repo: bool,
        branch_name: String,
        fail_validation_at: Option<usize>,
        setup_error: Option<String>,
        cleanup_error: Option<String>,
        worktree_add_calls: std::sync::atomic::AtomicUsize,
        validation_calls: std::sync::atomic::AtomicUsize,
        setup_calls: std::sync::atomic::AtomicUsize,
        cleanup_calls: std::sync::atomic::AtomicUsize,
        execute_calls: std::sync::atomic::AtomicUsize,
    }

    impl StubPlusRuntime {
        fn new() -> Self {
            Self {
                is_git_repo: true,
                branch_name: "ws-session-test".to_string(),
                fail_validation_at: None,
                setup_error: None,
                cleanup_error: None,
                worktree_add_calls: std::sync::atomic::AtomicUsize::new(0),
                validation_calls: std::sync::atomic::AtomicUsize::new(0),
                setup_calls: std::sync::atomic::AtomicUsize::new(0),
                cleanup_calls: std::sync::atomic::AtomicUsize::new(0),
                execute_calls: std::sync::atomic::AtomicUsize::new(0),
            }
        }
    }

    #[async_trait]
    impl WorktreePlusRuntime for StubPlusRuntime {
        async fn check_git_repo(&self, _repo_root: &Path) -> VcsResult<bool> {
            Ok(self.is_git_repo)
        }

        async fn generate_unique_branch_name(
            &self,
            _repo_root: &Path,
            _prefix: &str,
            _max_attempts: u32,
        ) -> VcsResult<String> {
            Ok(self.branch_name.clone())
        }

        async fn worktree_add(
            &self,
            _repo_root: &Path,
            worktree_path: &str,
            _branch_name: &str,
            _base_commit: &str,
        ) -> VcsResult<()> {
            self.worktree_add_calls.fetch_add(1, Ordering::SeqCst);
            std::fs::create_dir_all(worktree_path).unwrap();
            Ok(())
        }

        async fn validate_worktree_command_cwd(
            &self,
            _repo_root: &Path,
            _worktree_path: &Path,
        ) -> VcsResult<()> {
            let call = self.validation_calls.fetch_add(1, Ordering::SeqCst) + 1;
            if self.fail_validation_at == Some(call) {
                return Err(crate::vcs::VcsError::git_command(format!(
                    "validation failed at call {call}"
                )));
            }
            Ok(())
        }

        async fn run_worktree_setup(
            &self,
            _repo_root: &Path,
            _worktree_path: &Path,
        ) -> VcsResult<()> {
            self.setup_calls.fetch_add(1, Ordering::SeqCst);
            if let Some(message) = &self.setup_error {
                return Err(crate::vcs::VcsError::git_command(message.clone()));
            }
            Ok(())
        }

        async fn worktree_remove_after_setup_failure(
            &self,
            _repo_root: &Path,
            _worktree_path: &str,
        ) -> VcsResult<()> {
            self.cleanup_calls.fetch_add(1, Ordering::SeqCst);
            if let Some(message) = &self.cleanup_error {
                return Err(crate::vcs::VcsError::git_command(message.clone()));
            }
            Ok(())
        }

        async fn execute_worktree_command(
            &self,
            _terminal: &mut DefaultTerminal,
            _command: &str,
            _worktree_path: &Path,
            _ai_runner: &AiCommandRunner,
            _app: &mut AppState,
        ) -> Result<()> {
            self.execute_calls.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    fn plus_config(template: &str) -> OrchestratorConfig {
        OrchestratorConfig {
            worktree_command: Some(template.to_string()),
            ..Default::default()
        }
    }

    fn worktrees_app() -> AppState {
        let mut app = AppState::new(vec![]);
        app.view_mode = crate::tui::types::ViewMode::Worktrees;
        app
    }

    #[tokio::test]
    async fn plus_prepare_suppresses_setup_when_created_worktree_validation_fails() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut app = worktrees_app();
        let config = plus_config("true");
        let runtime = StubPlusRuntime {
            fail_validation_at: Some(1),
            ..StubPlusRuntime::new()
        };

        let prepared = prepare_plus_worktree_command(
            &mut app,
            &config,
            temp_dir.path(),
            &temp_dir.path().join("worktrees"),
            &runtime,
        )
        .await;

        assert!(prepared.is_none());
        assert_eq!(runtime.worktree_add_calls.load(Ordering::SeqCst), 1);
        assert_eq!(runtime.setup_calls.load(Ordering::SeqCst), 0);
        assert_eq!(runtime.execute_calls.load(Ordering::SeqCst), 0);
        assert!(app.logs.iter().any(|entry| {
            entry
                .message
                .contains("Suppressing worktree command launch: invalid cwd")
                && entry.message.contains("after create")
        }));
    }

    #[tokio::test]
    async fn plus_prepare_suppresses_command_when_worktree_invalid_after_setup() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut app = worktrees_app();
        let config = plus_config("true");
        let runtime = StubPlusRuntime {
            fail_validation_at: Some(2),
            ..StubPlusRuntime::new()
        };

        let prepared = prepare_plus_worktree_command(
            &mut app,
            &config,
            temp_dir.path(),
            &temp_dir.path().join("worktrees"),
            &runtime,
        )
        .await;

        assert!(prepared.is_none());
        assert_eq!(runtime.setup_calls.load(Ordering::SeqCst), 1);
        assert_eq!(runtime.execute_calls.load(Ordering::SeqCst), 0);
        assert!(app.logs.iter().any(|entry| {
            entry
                .message
                .contains("Suppressing worktree command launch: invalid cwd")
                && entry.message.contains("after setup")
        }));
    }

    #[tokio::test]
    async fn plus_prepare_suppresses_command_when_worktree_invalid_before_launch() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut app = worktrees_app();
        let config = plus_config("true");
        let runtime = StubPlusRuntime {
            fail_validation_at: Some(3),
            ..StubPlusRuntime::new()
        };

        let prepared = prepare_plus_worktree_command(
            &mut app,
            &config,
            temp_dir.path(),
            &temp_dir.path().join("worktrees"),
            &runtime,
        )
        .await;

        assert!(prepared.is_none());
        assert_eq!(runtime.setup_calls.load(Ordering::SeqCst), 1);
        assert_eq!(runtime.execute_calls.load(Ordering::SeqCst), 0);
        assert!(app.logs.iter().any(|entry| {
            entry
                .message
                .contains("Suppressing worktree command launch: invalid cwd")
                && entry.message.contains("before command launch")
        }));
    }

    #[tokio::test]
    async fn plus_prepare_logs_setup_failure_cleanup_and_suppresses_command() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut app = worktrees_app();
        let config = plus_config("true");
        let runtime = StubPlusRuntime {
            setup_error: Some("setup exploded".to_string()),
            ..StubPlusRuntime::new()
        };

        let prepared = prepare_plus_worktree_command(
            &mut app,
            &config,
            temp_dir.path(),
            &temp_dir.path().join("worktrees"),
            &runtime,
        )
        .await;

        assert!(prepared.is_none());
        assert_eq!(runtime.cleanup_calls.load(Ordering::SeqCst), 1);
        assert_eq!(runtime.execute_calls.load(Ordering::SeqCst), 0);
        assert!(app.logs.iter().any(|entry| entry
            .message
            .contains("Failed to run worktree setup")
            && entry.message.contains("setup exploded")));
        assert!(app.logs.iter().any(|entry| entry
            .message
            .contains("Cleaning up worktree after setup failure")));
        assert!(app.logs.iter().any(|entry| entry
            .message
            .contains("Cleaned up worktree after setup failure")));
    }

    async fn init_plus_git_repo(repo: &Path) {
        let init = tokio::process::Command::new("git")
            .args(["init", "-b", "main"])
            .current_dir(repo)
            .output()
            .await
            .unwrap();
        assert!(init.status.success(), "git init failed: {init:?}");
        tokio::process::Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(repo)
            .output()
            .await
            .unwrap();
        tokio::process::Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(repo)
            .output()
            .await
            .unwrap();
        std::fs::write(repo.join("README.md"), "test").unwrap();
        tokio::process::Command::new("git")
            .args(["add", "."])
            .current_dir(repo)
            .output()
            .await
            .unwrap();
        let commit = tokio::process::Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(repo)
            .output()
            .await
            .unwrap();
        assert!(commit.status.success(), "git commit failed: {commit:?}");
    }

    #[tokio::test]
    async fn plus_prepare_returns_expanded_command_for_valid_worktree() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut app = worktrees_app();
        let config = plus_config("tmux new-window -n wt -c {workspace_dir} -- echo {repo_root}");
        let runtime = StubPlusRuntime::new();

        let prepared = prepare_plus_worktree_command(
            &mut app,
            &config,
            temp_dir.path(),
            &temp_dir.path().join("worktrees"),
            &runtime,
        )
        .await
        .expect("valid worktree should prepare command launch");

        assert_eq!(runtime.validation_calls.load(Ordering::SeqCst), 3);
        assert_eq!(runtime.setup_calls.load(Ordering::SeqCst), 1);
        assert_eq!(runtime.execute_calls.load(Ordering::SeqCst), 0);
        assert_eq!(
            prepared.worktree_path.parent().unwrap(),
            temp_dir.path().join("worktrees")
        );
        assert!(prepared.command.contains("tmux new-window -n wt -c"));
        assert!(prepared
            .command
            .contains(prepared.worktree_path.to_str().unwrap()));
        assert!(prepared.command.contains(temp_dir.path().to_str().unwrap()));
        assert!(app
            .logs
            .iter()
            .any(|entry| entry.message.contains("Running worktree command in")));
    }

    fn test_ai_runner() -> AiCommandRunner {
        let queue_config = crate::command_queue::CommandQueueConfig {
            acceptance_max_runtime_secs:
                crate::config::defaults::DEFAULT_ACCEPTANCE_MAX_RUNTIME_SECS,
            stagger_delay_ms: 0,
            max_retries: 0,
            retry_delay_ms: 0,
            retry_error_patterns: Vec::new(),
            retry_if_duration_under_secs: 0,
            inactivity_timeout_secs: 0,
            inactivity_kill_grace_secs: 0,
            inactivity_timeout_max_retries: 0,
            strict_process_cleanup: true,
            max_runtime_secs: 0,
        };
        AiCommandRunner::new(queue_config, Arc::new(tokio::sync::Mutex::new(None)))
    }

    #[tokio::test]
    async fn plus_handle_invokes_command_runner_boundary_for_valid_worktree() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut app = worktrees_app();
        let mut terminal = ratatui::Terminal::with_options(
            ratatui::backend::CrosstermBackend::new(std::io::stdout()),
            ratatui::TerminalOptions {
                viewport: ratatui::Viewport::Fixed(ratatui::layout::Rect::new(0, 0, 80, 24)),
            },
        )
        .unwrap();
        let config = plus_config("echo {workspace_dir}");
        let (tx, _rx) = mpsc::channel(1);
        let (cmd_tx, _cmd_rx) = mpsc::channel(1);
        let ai_runner = test_ai_runner();
        let runtime = StubPlusRuntime::new();
        let worktree_base_dir = temp_dir.path().join("worktrees");
        let supervisor = idle_supervisor();
        let mut ctx = KeyEventContext {
            app: &mut app,
            terminal: &mut terminal,
            repo_root: temp_dir.path(),
            config: &config,
            worktree_base_dir: &worktree_base_dir,
            tx: &tx,
            cmd_tx: &cmd_tx,
            ai_runner: &ai_runner,
            supervisor: &supervisor,
        };

        handle_plus_key_with_runtime(&mut ctx, &runtime)
            .await
            .unwrap();

        assert_eq!(runtime.validation_calls.load(Ordering::SeqCst), 3);
        assert_eq!(runtime.execute_calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn plus_prepare_with_production_runtime_creates_registered_materialized_worktree() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        init_plus_git_repo(temp_dir.path()).await;
        let mut app = worktrees_app();
        let config = plus_config("printf ok");
        let worktree_base_dir = temp_dir.path().join("worktrees");

        let prepared = prepare_plus_worktree_command(
            &mut app,
            &config,
            temp_dir.path(),
            &worktree_base_dir,
            &ProductionWorktreePlusRuntime,
        )
        .await
        .expect("valid Git fixture should prepare command launch");

        assert!(prepared.worktree_path.exists());
        assert!(prepared.worktree_path.join(".git").exists());
        assert!(prepared.worktree_path.join("README.md").exists());
        assert_eq!(prepared.command, "printf ok");
        crate::vcs::git::commands::validate_worktree_command_cwd(
            temp_dir.path(),
            &prepared.worktree_path,
        )
        .await
        .unwrap();
        let _ = crate::vcs::git::commands::worktree_remove(
            temp_dir.path(),
            prepared.worktree_path.to_str().unwrap(),
        )
        .await;
    }

    /// Builds a Changes-view app for bulk toggle boundary tests.
    fn bulk_toggle_app(rows: &[(&str, &str, bool)]) -> AppState {
        let changes = rows
            .iter()
            .map(|(id, _, _)| create_test_change(id))
            .collect();
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        for (index, (_, status, selected)) in rows.iter().enumerate() {
            app.changes[index].display_status_cache = status.to_string();
            app.changes[index].selected = *selected;
        }
        app
    }

    /// `x` marks every visible non-terminal row and emits nothing else.
    ///
    /// The active row is a target like any other: the mark it receives is
    /// next-run intent, which the in-flight run neither owns nor answers. The
    /// terminal row is skipped without a warning, because skipping a change
    /// that has no next run refuses nothing.
    #[test]
    fn bulk_toggle_key_marks_every_non_terminal_row_without_queue_effects() {
        let mut app = bulk_toggle_app(&[
            ("active", "applying", false),
            ("rejected", "rejected", false),
            ("eligible", "not queued", false),
        ]);

        let commands = handle_bulk_toggle_key(&mut app);

        assert!(
            commands.is_empty(),
            "a bulk mark emits no command: {commands:?}"
        );
        assert!(app.changes[0].selected, "an active row is a mark target");
        assert!(!app.changes[1].selected, "a terminal row is not");
        assert!(app.changes[2].selected);

        assert!(
            app.warning_message.is_none(),
            "a skipped terminal row is not a refusal: {:?}",
            app.warning_message
        );
        assert!(app
            .logs
            .iter()
            .any(|entry| entry.message == "Toggled all: 2 marked change(s)"));
    }

    /// Terminal rows only: nothing to mark, and nothing to say about it.
    #[test]
    fn bulk_toggle_key_with_only_terminal_rows_is_silent() {
        let mut app = bulk_toggle_app(&[
            ("archived", "archived", false),
            ("rejected", "rejected", true),
        ]);

        let commands = handle_bulk_toggle_key(&mut app);

        assert!(commands.is_empty());
        assert!(!app.changes[0].selected, "terminal rows must not change");
        assert!(app.changes[1].selected, "terminal rows must not change");
        assert!(
            app.warning_message.is_none(),
            "a terminal-only list refuses nothing: {:?}",
            app.warning_message
        );
        assert!(!app
            .logs
            .iter()
            .any(|entry| entry.message.contains("Toggled all")));
    }

    #[test]
    fn bulk_toggle_key_is_ignored_outside_changes_view() {
        let mut app = bulk_toggle_app(&[("eligible", "not queued", false)]);
        app.view_mode = ViewMode::Worktrees;

        let commands = handle_bulk_toggle_key(&mut app);

        assert!(commands.is_empty());
        assert!(!app.changes[0].selected);
        assert!(app.warning_message.is_none());
    }

    #[tokio::test]
    async fn ctrl_c_quit_cancels_local_orchestrator_token() {
        use crate::orchestration::run_control::RunSchedulerPort;

        let mut app = AppState::new(vec![create_test_change("change-a")]);
        let supervisor = idle_supervisor();
        supervisor
            .start_run(Vec::new(), false)
            .await
            .expect("an idle supervisor accepts a launch");
        let token = supervisor.cancel_token().expect("a live run owns a token");

        request_local_tui_quit(&mut app, &supervisor);

        assert!(app.should_quit);
        assert!(token.is_cancelled());
        assert!(app
            .logs
            .iter()
            .any(|entry| entry.message.contains("cancelling local orchestration")));
        let (handle, _, _) = supervisor.take_run();
        if let Some(handle) = handle {
            handle.abort();
        }
    }

    #[test]
    fn ctrl_c_quit_without_local_orchestrator_only_sets_quit() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);

        request_local_tui_quit(&mut app, &idle_supervisor());

        assert!(app.should_quit);
    }

    #[test]
    fn idle_parallel_stop_second_esc_requests_the_shared_immediate_stop_command() {
        assert_eq!(
            esc_stop_action(&AppExecutionMode::Running, &StopMode::None, false),
            EscStopAction::RequestGracefulStop
        );
        assert_eq!(
            esc_stop_action(
                &AppExecutionMode::Stopping,
                &StopMode::GracefulPending,
                false
            ),
            EscStopAction::RequestImmediateStop
        );
    }

    #[test]
    fn idle_parallel_stop_repeated_esc_does_not_duplicate_the_stop_request() {
        assert_eq!(
            esc_stop_action(
                &AppExecutionMode::Stopping,
                &StopMode::ImmediatePending,
                false
            ),
            EscStopAction::None
        );
        assert_eq!(
            esc_stop_action(&AppExecutionMode::Stopped, &StopMode::None, false),
            EscStopAction::None
        );
    }

    #[tokio::test]
    async fn idle_parallel_stop_second_esc_routes_through_force_stop_command() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        app.execution_mode = AppExecutionMode::Stopping;
        app.stop_mode = StopMode::GracefulPending;
        let (cmd_tx, mut cmd_rx) = mpsc::channel(4);

        handle_esc_key_inner(&mut app, &cmd_tx).await;

        assert!(
            matches!(cmd_rx.try_recv(), Ok(TuiCommand::ForceStop)),
            "the second Esc must route through the shared stop command"
        );
        assert_eq!(app.stop_mode, StopMode::ImmediatePending);
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Stopping,
            "the key path must not apply terminal stop effects itself"
        );
        assert!(
            !app.logs
                .iter()
                .any(|entry| entry.message.contains("Force stopped")),
            "the key path must not claim a force stop from AppExecutionMode::Stopping alone"
        );
        assert!(
            !app.logs
                .iter()
                .any(|entry| entry.message.contains("Processing stopped")),
            "terminal stop reporting is owned by the Stopped transition"
        );
    }

    #[tokio::test]
    async fn idle_parallel_stop_repeated_esc_sends_one_stop_command() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        app.execution_mode = AppExecutionMode::Stopping;
        app.stop_mode = StopMode::GracefulPending;
        let (cmd_tx, mut cmd_rx) = mpsc::channel(4);

        handle_esc_key_inner(&mut app, &cmd_tx).await;
        handle_esc_key_inner(&mut app, &cmd_tx).await;

        assert!(matches!(cmd_rx.try_recv(), Ok(TuiCommand::ForceStop)));
        assert!(
            cmd_rx.try_recv().is_err(),
            "a repeated Esc must not enqueue a second cancellation request"
        );
    }

    #[tokio::test]
    async fn idle_parallel_stop_first_esc_keeps_graceful_stop_contract() {
        let mut app = AppState::new(vec![create_test_change("change-a")]);
        app.execution_mode = AppExecutionMode::Running;
        let (cmd_tx, mut cmd_rx) = mpsc::channel(4);

        handle_esc_key_inner(&mut app, &cmd_tx).await;

        // The key path records the pending mode so a second Esc is an immediate
        // stop, but the graceful-stop effect itself is the shared service's.
        assert_eq!(app.stop_mode, StopMode::GracefulPending);
        assert!(matches!(cmd_rx.try_recv(), Ok(TuiCommand::Stop)));
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "the key path must not apply the stop transition itself"
        );
    }

    // ========================================================================
    // Input routing priority: warning popup → typed modal → view/execution keys
    // ========================================================================

    /// Keys that would visibly mutate underlying state if an overlay leaked them.
    const HIGH_IMPACT_KEYS: [KeyCode; 10] = [
        KeyCode::Char('x'),
        KeyCode::Char(' '),
        KeyCode::Down,
        KeyCode::Up,
        KeyCode::Char('j'),
        KeyCode::Char('K'),
        KeyCode::Char('M'),
        KeyCode::Esc,
        KeyCode::F(5),
        KeyCode::Tab,
    ];

    /// Underlying state a leaked key would be visible in.
    #[derive(Debug, PartialEq)]
    struct UnderlyingState {
        execution_mode: AppExecutionMode,
        stop_mode: StopMode,
        cursor_index: usize,
        view_mode: ViewMode,
        marks: Vec<bool>,
        statuses: Vec<String>,
    }

    impl UnderlyingState {
        fn capture(app: &AppState) -> Self {
            Self {
                execution_mode: app.execution_mode,
                stop_mode: app.stop_mode.clone(),
                cursor_index: app.cursor_index,
                view_mode: app.view_mode,
                marks: app.changes.iter().map(|c| c.selected).collect(),
                statuses: app
                    .changes
                    .iter()
                    .map(|c| c.display_status_cache.clone())
                    .collect(),
            }
        }
    }

    fn routing_app() -> AppState {
        let mut app = AppState::new(vec![
            create_test_change("change-a"),
            create_test_change("change-b"),
        ]);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_display_status_cache("applying");
        app.changes[1].set_display_status_cache("not queued");
        app.web_url = Some("http://127.0.0.1:8080".to_string());
        app
    }

    fn test_terminal() -> DefaultTerminal {
        ratatui::Terminal::with_options(
            ratatui::backend::CrosstermBackend::new(std::io::stdout()),
            ratatui::TerminalOptions {
                viewport: ratatui::Viewport::Fixed(ratatui::layout::Rect::new(0, 0, 80, 24)),
            },
        )
        .unwrap()
    }

    /// Feed one key through the full routing entry point.
    async fn route_key(app: &mut AppState, code: KeyCode) -> Vec<TuiCommand> {
        route_key_event(app, key(code)).await
    }

    /// Feed one fully specified key event through the full routing entry point.
    async fn route_key_event(app: &mut AppState, event: KeyEvent) -> Vec<TuiCommand> {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let mut terminal = test_terminal();
        let config = OrchestratorConfig::default();
        let (tx, _rx) = mpsc::channel(8);
        let (cmd_tx, mut cmd_rx) = mpsc::channel(8);
        let ai_runner = test_ai_runner();
        let supervisor = idle_supervisor();
        let worktree_base_dir = temp_dir.path().join("worktrees");
        let mut ctx = KeyEventContext {
            app,
            terminal: &mut terminal,
            repo_root: temp_dir.path(),
            config: &config,
            worktree_base_dir: &worktree_base_dir,
            tx: &tx,
            cmd_tx: &cmd_tx,
            ai_runner: &ai_runner,
            supervisor: &supervisor,
        };

        handle_key_event(event, &mut ctx).await.unwrap();

        let mut commands = Vec::new();
        while let Ok(command) = cmd_rx.try_recv() {
            commands.push(command);
        }
        commands
    }

    #[tokio::test]
    async fn warning_popup_owns_input_before_the_typed_modal() {
        let mut app = routing_app();
        app.show_qr_popup();
        app.show_warning_popup("warning", "line 1\nline 2\nline 3");

        // A popup scroll key must reach the popup, not the QR overlay under it.
        let commands = route_key(&mut app, KeyCode::Down).await;

        assert!(commands.is_empty());
        assert!(app.warning_popup.is_some());
        assert_eq!(app.warning_popup_scroll, 1);
        assert_eq!(
            app.modal,
            Some(ModalState::QrPopup),
            "the interaction modal must not process a warning-popup key"
        );
        assert_eq!(app.execution_mode, AppExecutionMode::Running);
    }

    #[tokio::test]
    async fn every_overlay_consumes_high_impact_keys_without_touching_the_view() {
        type OpenOverlay = fn(&mut AppState);
        let overlays: Vec<(&str, OpenOverlay)> = vec![
            ("qr", |app: &mut AppState| app.show_qr_popup()),
            ("worktree-delete", |app: &mut AppState| {
                app.modal = Some(ModalState::ConfirmWorktreeDelete {
                    path: PathBuf::from("/tmp/wt-a"),
                    branch: "change-b".to_string(),
                });
            }),
            ("force-kill", |app: &mut AppState| {
                app.modal = Some(ModalState::ConfirmForceKill {
                    change_id: "change-a".to_string(),
                });
            }),
            ("warning-popup", |app: &mut AppState| {
                app.show_warning_popup("warning", "diagnostic")
            }),
            ("error-details", |app: &mut AppState| {
                app.changes[1].set_error_message_cache("boom".to_string());
                app.cursor_index = 1;
                assert!(app.open_error_details_popup());
            }),
        ];

        for (name, open) in overlays {
            for code in HIGH_IMPACT_KEYS {
                let mut app = routing_app();
                open(&mut app);
                let before = UnderlyingState::capture(&app);

                let commands = route_key(&mut app, code).await;

                assert!(
                    commands.is_empty(),
                    "{name} overlay leaked {code:?} as a command"
                );
                assert_eq!(
                    UnderlyingState::capture(&app),
                    before,
                    "{name} overlay leaked {code:?} into the underlying view"
                );
            }
        }
    }

    #[tokio::test]
    async fn an_overlay_consumes_the_resolve_key_without_emitting_resolve_merge() {
        let overlays = [
            ModalState::QrPopup,
            ModalState::ConfirmWorktreeDelete {
                path: PathBuf::from("/tmp/wt-a"),
                branch: "change-b".to_string(),
            },
            ModalState::ConfirmForceKill {
                change_id: "change-a".to_string(),
            },
        ];

        for modal in overlays {
            let mut app = routing_app();
            app.execution_mode = AppExecutionMode::Select;
            // A row the resolve key would otherwise act on.
            app.changes[1].set_display_status_cache("merge wait");
            app.cursor_index = 1;
            app.modal = Some(modal.clone());

            let commands = route_key(&mut app, KeyCode::Char('M')).await;

            assert!(
                commands.is_empty(),
                "{modal:?} must not let the resolve key through"
            );
            assert_eq!(
                app.execution_mode,
                AppExecutionMode::Select,
                "{modal:?} must not let the resolve key move the execution axis"
            );
        }
    }

    #[tokio::test]
    async fn qr_closes_on_any_key_and_exposes_the_latest_execution_mode() {
        for code in [KeyCode::Esc, KeyCode::Char('x'), KeyCode::Enter] {
            let mut app = routing_app();
            app.show_qr_popup();

            // A background transition lands while the popup is open.
            app.execution_mode = AppExecutionMode::Stopping;

            let commands = route_key(&mut app, code).await;

            assert!(commands.is_empty());
            assert!(app.modal.is_none(), "{code:?} must close the QR popup");
            assert_eq!(
                app.execution_mode,
                AppExecutionMode::Stopping,
                "closing QR must expose the latest execution mode, not a captured one"
            );
        }
    }

    #[tokio::test]
    async fn force_kill_confirm_dispatches_stop_and_dequeue_without_rewriting_execution() {
        let mut app = routing_app();
        app.execution_mode = AppExecutionMode::Stopping;
        app.modal = Some(ModalState::ConfirmForceKill {
            change_id: "change-a".to_string(),
        });

        let commands = route_key(&mut app, KeyCode::Char('y')).await;

        assert!(
            matches!(commands.as_slice(), [TuiCommand::DequeueChange(id)] if id == "change-a"),
            "expected a single stop-and-dequeue command, got {commands:?}"
        );
        assert!(app.modal.is_none());
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Stopping,
            "confirming must not rewrite execution back to Running"
        );
    }

    #[tokio::test]
    async fn force_kill_cancel_preserves_the_current_execution_mode() {
        let mut app = routing_app();
        app.execution_mode = AppExecutionMode::Stopping;
        app.modal = Some(ModalState::ConfirmForceKill {
            change_id: "change-a".to_string(),
        });

        let commands = route_key(&mut app, KeyCode::Esc).await;

        assert!(commands.is_empty());
        assert!(app.modal.is_none());
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Stopping,
            "cancel must not restore Running unconditionally"
        );
        assert_eq!(app.stop_mode, StopMode::None);
    }

    #[tokio::test]
    async fn force_kill_confirm_refuses_a_stale_target_without_dispatching() {
        let mut app = routing_app();
        app.modal = Some(ModalState::ConfirmForceKill {
            change_id: "change-a".to_string(),
        });
        // The target settled between display and confirmation input.
        app.changes[0].set_display_status_cache("archived");

        let commands = route_key(&mut app, KeyCode::Char('y')).await;

        assert!(
            commands.is_empty(),
            "a stale force-kill must not reach the shared service"
        );
        assert!(app.modal.is_none());
        assert_eq!(app.changes[0].display_status_cache, "archived");
        assert!(app
            .warning_message
            .as_ref()
            .is_some_and(|msg| msg.contains("Force-kill canceled")));
    }

    #[tokio::test]
    async fn worktree_delete_confirm_dispatches_when_identity_still_matches() {
        let mut app = routing_app();
        app.view_mode = ViewMode::Worktrees;
        app.worktrees = vec![crate::tui::types::WorktreeInfo {
            path: PathBuf::from("/tmp/wt-a"),
            head: "abc1234".to_string(),
            branch: "change-b".to_string(),
            is_detached: false,
            is_main: false,
            merge_conflict: None,
            has_commits_ahead: false,
            is_merging: false,
            inspection: crate::worktree_ops::InspectionState::Checked,
        }];
        app.modal = Some(ModalState::ConfirmWorktreeDelete {
            path: PathBuf::from("/tmp/wt-a"),
            branch: "change-b".to_string(),
        });

        let commands = route_key(&mut app, KeyCode::Char('y')).await;

        assert!(
            matches!(
                commands.as_slice(),
                [TuiCommand::DeleteWorktree(intent)]
                    if intent.path == *"/tmp/wt-a"
                        && intent.branch == "change-b"
                        && !intent.skip_teardown
                        && !intent.allow_known_dirty
            ),
            "expected a single worktree delete command, got {commands:?}"
        );
        assert!(app.modal.is_none());
        assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")));
    }

    #[tokio::test]
    async fn worktree_delete_confirm_refuses_stale_identity_without_mutating_state() {
        for (name, mutate) in [
            (
                "absent",
                (|app: &mut AppState| app.worktrees.clear()) as fn(&mut AppState),
            ),
            ("rebranded", |app: &mut AppState| {
                app.worktrees[0].branch = "change-z".to_string()
            }),
            ("main", |app: &mut AppState| app.worktrees[0].is_main = true),
        ] {
            for code in [KeyCode::Char('y'), KeyCode::Char('s')] {
                let mut app = routing_app();
                app.view_mode = ViewMode::Worktrees;
                app.worktrees = vec![crate::tui::types::WorktreeInfo {
                    path: PathBuf::from("/tmp/wt-a"),
                    head: "abc1234".to_string(),
                    branch: "change-b".to_string(),
                    is_detached: false,
                    is_main: false,
                    merge_conflict: None,
                    has_commits_ahead: false,
                    is_merging: false,
                    inspection: crate::worktree_ops::InspectionState::Checked,
                }];
                app.modal = Some(ModalState::ConfirmWorktreeDelete {
                    path: PathBuf::from("/tmp/wt-a"),
                    branch: "change-b".to_string(),
                });
                mutate(&mut app);

                let commands = route_key(&mut app, code).await;

                assert!(
                    commands.is_empty(),
                    "{name}: a stale worktree delete must not be dispatched for {code:?}"
                );
                assert!(
                    app.modal.is_none(),
                    "{name}: the stale modal must be cleared"
                );
                assert!(
                    !app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")),
                    "{name}: refusing must not mark the worktree as deleting"
                );
                assert!(app
                    .warning_message
                    .as_ref()
                    .is_some_and(|msg| msg.contains("Worktree delete canceled")));
            }
        }
    }

    /// A named way the confirmation's target can drift before the keypress.
    type DriftCase = (&'static str, fn(&mut AppState));

    /// An app in the destructive dirty-discard confirmation over `/tmp/wt-a`.
    fn tui_dirty_worktree_delete_app(skip_teardown: bool) -> AppState {
        let mut app = routing_app();
        app.view_mode = ViewMode::Worktrees;
        app.worktrees = vec![crate::tui::types::WorktreeInfo {
            path: PathBuf::from("/tmp/wt-a"),
            head: "abc1234".to_string(),
            branch: "change-b".to_string(),
            is_detached: false,
            is_main: false,
            merge_conflict: None,
            has_commits_ahead: false,
            is_merging: false,
            inspection: crate::worktree_ops::InspectionState::Checked,
        }];
        app.modal = Some(ModalState::ConfirmDirtyDiscard {
            path: PathBuf::from("/tmp/wt-a"),
            identity: "gitdir: /tmp/wt-a/.git".to_string(),
            branch: "change-b".to_string(),
            head: "abc1234".to_string(),
            skip_teardown,
        });
        app
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_uppercase_x_is_the_only_key_that_discards() {
        for skip_teardown in [false, true] {
            let mut app = tui_dirty_worktree_delete_app(skip_teardown);

            let commands = route_key(&mut app, KeyCode::Char('X')).await;

            let [TuiCommand::DeleteWorktree(intent)] = commands.as_slice() else {
                panic!("expected a single delete command, got {commands:?}");
            };
            assert!(intent.allow_known_dirty);
            assert_eq!(intent.skip_teardown, skip_teardown);
            assert_eq!(intent.path, PathBuf::from("/tmp/wt-a"));
            assert_eq!(intent.branch, "change-b");
            assert_eq!(intent.identity.as_deref(), Some("gitdir: /tmp/wt-a/.git"));
            assert_eq!(intent.head.as_deref(), Some("abc1234"));
            assert!(app.modal.is_none());
            assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")));
        }
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_confirmation_ignores_every_other_key() {
        // `y`/`Y`/`s`/`S` are the keys that got the operator here, and lowercase
        // `x` is the Changes view's bulk-mark key. None of them may become the
        // destructive decision by habit or by shift key slipping.
        for code in [
            KeyCode::Char('y'),
            KeyCode::Char('Y'),
            KeyCode::Char('s'),
            KeyCode::Char('S'),
            KeyCode::Char('x'),
            KeyCode::Char('d'),
            KeyCode::Char('D'),
            KeyCode::Enter,
            KeyCode::Char(' '),
            KeyCode::Down,
            KeyCode::Tab,
            KeyCode::F(5),
        ] {
            let mut app = tui_dirty_worktree_delete_app(false);
            let before = app.modal.clone();

            let commands = route_key(&mut app, code).await;

            assert!(
                commands.is_empty(),
                "{code:?} must not dispatch anything from the destructive confirmation"
            );
            assert_eq!(
                app.modal, before,
                "{code:?} must leave the destructive confirmation exactly as it was"
            );
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")),
                "{code:?} must not start a deletion"
            );
        }
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_n_and_esc_cancel_and_retain_the_content() {
        for code in [KeyCode::Char('n'), KeyCode::Char('N'), KeyCode::Esc] {
            let mut app = tui_dirty_worktree_delete_app(false);

            let commands = route_key(&mut app, code).await;

            assert!(commands.is_empty(), "{code:?} must dispatch nothing");
            assert!(app.modal.is_none(), "{code:?} must close the confirmation");
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")),
                "{code:?} must retain the worktree and its uncommitted work"
            );
        }
    }

    #[tokio::test]
    async fn tui_dirty_worktree_delete_refuses_a_target_that_became_active_before_dispatch() {
        // The confirmation is advisory presentation state; the target can move
        // underneath it. Re-checking at input time is what stops an activation
        // that lands between the escalation and the keypress.
        let cases: [DriftCase; 6] = [
            ("absent", |app: &mut AppState| app.worktrees.clear()),
            ("main", |app: &mut AppState| app.worktrees[0].is_main = true),
            ("rebranded", |app: &mut AppState| {
                app.worktrees[0].branch = "change-z".to_string()
            }),
            ("head-moved", |app: &mut AppState| {
                app.worktrees[0].head = "def5678".to_string()
            }),
            ("active", |app: &mut AppState| {
                app.changes[1].set_display_status_cache("applying")
            }),
            ("deleting", |app: &mut AppState| {
                app.mark_worktree_deleting(PathBuf::from("/tmp/wt-a"))
            }),
        ];

        for (name, mutate) in cases {
            let mut app = tui_dirty_worktree_delete_app(false);
            mutate(&mut app);

            let commands = route_key(&mut app, KeyCode::Char('X')).await;

            assert!(
                commands.is_empty(),
                "{name}: a drifted target must not be discarded"
            );
            assert!(
                app.modal.is_none(),
                "{name}: the stale confirmation must be cleared"
            );
            assert!(app
                .warning_message
                .as_ref()
                .is_some_and(|msg| msg.contains("Dirty worktree discard canceled")));
        }
    }

    /// An app in the destructive ahead-discard confirmation over `/tmp/wt-a`.
    fn tui_ahead_worktree_delete_app(skip_teardown: bool, dirty: bool) -> AppState {
        let mut app = tui_dirty_worktree_delete_app(skip_teardown);
        app.modal = Some(ModalState::ConfirmAheadDiscard {
            path: PathBuf::from("/tmp/wt-a"),
            identity: "gitdir: /tmp/wt-a/.git".to_string(),
            branch: "change-b".to_string(),
            head: "abc1234".to_string(),
            dirty,
            skip_teardown,
        });
        app
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_uppercase_x_is_the_only_key_that_discards() {
        for dirty in [false, true] {
            for skip_teardown in [false, true] {
                let mut app = tui_ahead_worktree_delete_app(skip_teardown, dirty);

                let commands = route_key(&mut app, KeyCode::Char('X')).await;

                let [TuiCommand::DeleteWorktree(intent)] = commands.as_slice() else {
                    panic!("expected a single delete command, got {commands:?}");
                };
                assert!(intent.allow_commits_ahead);
                assert_eq!(
                    intent.allow_known_dirty, dirty,
                    "the one keypress grants dirty discard only where the modal disclosed it"
                );
                assert_eq!(intent.skip_teardown, skip_teardown);
                assert_eq!(intent.path, PathBuf::from("/tmp/wt-a"));
                assert_eq!(intent.branch, "change-b");
                assert_eq!(intent.identity.as_deref(), Some("gitdir: /tmp/wt-a/.git"));
                assert_eq!(intent.head.as_deref(), Some("abc1234"));
                assert!(app.modal.is_none());
                assert!(app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")));
            }
        }
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_confirmation_ignores_every_other_key() {
        // The keys that got the operator here, the bulk-mark key, and the
        // lowercase twin of the one destructive key: all inert. This modal
        // authorizes deleting commits, so a slipped shift may not decide it.
        for code in [
            KeyCode::Char('y'),
            KeyCode::Char('Y'),
            KeyCode::Char('s'),
            KeyCode::Char('S'),
            KeyCode::Char('x'),
            KeyCode::Char('d'),
            KeyCode::Char('D'),
            KeyCode::Enter,
            KeyCode::Char(' '),
            KeyCode::Down,
            KeyCode::Tab,
            KeyCode::F(5),
        ] {
            let mut app = tui_ahead_worktree_delete_app(false, true);
            let before = app.modal.clone();

            let commands = route_key(&mut app, code).await;

            assert!(
                commands.is_empty(),
                "{code:?} must not dispatch anything from the ahead confirmation"
            );
            assert_eq!(
                app.modal, before,
                "{code:?} must leave the ahead confirmation exactly as it was"
            );
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")),
                "{code:?} must not start a deletion"
            );
        }
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_n_and_esc_cancel_and_retain_both_resources() {
        for code in [KeyCode::Char('n'), KeyCode::Char('N'), KeyCode::Esc] {
            let mut app = tui_ahead_worktree_delete_app(false, false);

            let commands = route_key(&mut app, code).await;

            assert!(commands.is_empty(), "{code:?} must dispatch nothing");
            assert!(app.modal.is_none(), "{code:?} must close the confirmation");
            assert!(
                !app.is_worktree_deleting(&PathBuf::from("/tmp/wt-a")),
                "{code:?} must retain the worktree, its content, and its branch"
            );
        }
    }

    #[tokio::test]
    async fn tui_ahead_worktree_delete_refuses_a_target_that_drifted_before_dispatch() {
        let cases: [DriftCase; 6] = [
            ("absent", |app: &mut AppState| app.worktrees.clear()),
            ("main", |app: &mut AppState| app.worktrees[0].is_main = true),
            ("rebranded", |app: &mut AppState| {
                app.worktrees[0].branch = "change-z".to_string()
            }),
            ("head-moved", |app: &mut AppState| {
                app.worktrees[0].head = "def5678".to_string()
            }),
            ("active", |app: &mut AppState| {
                app.changes[1].set_display_status_cache("applying")
            }),
            ("deleting", |app: &mut AppState| {
                app.mark_worktree_deleting(PathBuf::from("/tmp/wt-a"))
            }),
        ];

        for (name, mutate) in cases {
            let mut app = tui_ahead_worktree_delete_app(false, false);
            mutate(&mut app);

            let commands = route_key(&mut app, KeyCode::Char('X')).await;

            assert!(
                commands.is_empty(),
                "{name}: a drifted target must not be discarded"
            );
            assert!(
                app.modal.is_none(),
                "{name}: the stale confirmation must be cleared"
            );
            assert!(app
                .warning_message
                .as_ref()
                .is_some_and(|msg| msg.contains("Ahead worktree discard canceled")));
        }
    }

    #[tokio::test]
    async fn k_key_opens_force_kill_without_leaving_running_execution() {
        let mut app = routing_app();

        let commands = route_key(&mut app, KeyCode::Char('K')).await;

        assert!(commands.is_empty());
        assert_eq!(
            app.modal,
            Some(ModalState::ConfirmForceKill {
                change_id: "change-a".to_string()
            })
        );
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "opening a confirmation must not move the execution axis"
        );
    }

    #[tokio::test]
    async fn w_key_opens_qr_over_the_current_execution_mode() {
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Running,
            AppExecutionMode::Stopping,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            let mut app = routing_app();
            app.execution_mode = mode;

            route_key(&mut app, KeyCode::Char('w')).await;

            assert_eq!(app.modal, Some(ModalState::QrPopup));
            assert_eq!(app.execution_mode, mode);
        }
    }

    #[tokio::test]
    async fn w_key_is_ignored_when_web_monitoring_is_disabled() {
        let mut app = routing_app();
        app.web_url = None;
        let before = UnderlyingState::capture(&app);

        route_key(&mut app, KeyCode::Char('w')).await;

        assert!(app.modal.is_none());
        assert_eq!(UnderlyingState::capture(&app), before);
    }

    /// `x` reaches the shared bulk mark in every execution mode.
    ///
    /// Execution mode is absent from mark admission on purpose: a mark says
    /// what the operator wants the *next* run to consider, and Stopping and
    /// Error are exactly the states in which planning the next run matters
    /// most.
    #[tokio::test]
    async fn bulk_mark_key_applies_in_every_execution_mode() {
        for mode in [
            AppExecutionMode::Select,
            AppExecutionMode::Running,
            AppExecutionMode::Stopping,
            AppExecutionMode::Stopped,
            AppExecutionMode::Error,
        ] {
            let mut app = routing_app();
            app.execution_mode = mode;

            route_key(&mut app, KeyCode::Char('x')).await;

            assert!(
                app.changes[1].selected,
                "{mode:?} must admit bulk mark for a visible non-terminal row"
            );
        }
    }

    // ========================================================================
    // Error Details popup input ownership
    // ========================================================================

    /// A Changes-view app whose cursor sits on an `error` row.
    fn error_details_app() -> AppState {
        let mut app = routing_app();
        app.changes[1].set_error_message_cache("Apply failed: stalled".to_string());
        app.cursor_index = 1;
        app
    }

    #[tokio::test]
    async fn enter_opens_the_error_details_popup_on_an_error_row() {
        let mut app = error_details_app();

        let commands = route_key(&mut app, KeyCode::Enter).await;

        assert!(commands.is_empty(), "opening a popup emits no command");
        let popup = app
            .error_details_popup
            .as_ref()
            .expect("Enter opens the Error Details popup");
        assert_eq!(popup.change_id, "change-b");
        assert_eq!(popup.error, "Apply failed: stalled");
        assert_eq!(popup.scroll, 0);
        assert!(popup.copy_feedback.is_none());
    }

    #[tokio::test]
    async fn enter_on_a_non_error_row_keeps_its_existing_behavior() {
        let mut app = error_details_app();
        app.cursor_index = 0; // `applying`
        let before = UnderlyingState::capture(&app);

        let commands = route_key(&mut app, KeyCode::Enter).await;

        assert!(commands.is_empty());
        assert!(
            app.error_details_popup.is_none(),
            "only an error row opens the popup"
        );
        assert_eq!(UnderlyingState::capture(&app), before);
        assert!(
            app.logs
                .iter()
                .any(|log| log.message.contains("Enter ignored: not in Worktrees view")),
            "the pre-existing Enter behavior is unchanged"
        );
    }

    #[tokio::test]
    async fn popup_scroll_keys_do_not_move_the_underlying_views() {
        for code in [KeyCode::Down, KeyCode::Char('j'), KeyCode::PageDown] {
            let mut app = error_details_app();
            for index in 0..12 {
                app.add_log(LogEntry::info(format!("log {index}")));
            }
            app.scroll_logs_up(3);
            assert!(app.open_error_details_popup());
            let before = UnderlyingState::capture(&app);
            let log_anchor_before = app.log_anchor;

            let commands = route_key_event(&mut app, key(code)).await;

            assert!(commands.is_empty(), "{code:?} leaked a command");
            assert!(
                app.error_details_popup
                    .as_ref()
                    .is_some_and(|popup| popup.scroll > 0),
                "{code:?} must scroll the popup"
            );
            assert_eq!(
                UnderlyingState::capture(&app),
                before,
                "{code:?} moved the Changes list underneath the popup"
            );
            assert_eq!(
                app.log_anchor, log_anchor_before,
                "{code:?} moved the Logs panel underneath the popup"
            );
        }
    }

    #[tokio::test]
    async fn escape_closes_the_popup_without_a_workflow_transition() {
        let mut app = error_details_app();
        assert!(app.open_error_details_popup());
        let before = UnderlyingState::capture(&app);

        let commands = route_key(&mut app, KeyCode::Esc).await;

        assert!(commands.is_empty(), "closing a popup emits no command");
        assert!(app.error_details_popup.is_none());
        assert_eq!(UnderlyingState::capture(&app), before);
        assert_eq!(app.stop_mode, StopMode::None, "Esc must not reach the view");
    }

    #[tokio::test]
    async fn warning_popup_retains_first_claim_over_the_error_details_popup() {
        let mut app = error_details_app();
        assert!(app.open_error_details_popup());
        app.show_warning_popup("warning", "line 1\nline 2\nline 3");
        let before = UnderlyingState::capture(&app);

        route_key(&mut app, KeyCode::Down).await;

        assert_eq!(app.warning_popup_scroll, 1, "the warning popup scrolled");
        assert_eq!(
            app.error_details_popup.as_ref().map(|popup| popup.scroll),
            Some(0),
            "the Error Details popup must not process the same key"
        );
        assert_eq!(UnderlyingState::capture(&app), before);
    }

    #[tokio::test]
    async fn ctrl_c_keeps_its_global_quit_meaning_while_the_popup_is_open() {
        let mut app = error_details_app();
        app.set_clipboard(Arc::new(
            crate::tui::clipboard::test_doubles::RecordingClipboard::default(),
        ));
        assert!(app.open_error_details_popup());

        route_key_event(
            &mut app,
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
        )
        .await;

        assert!(app.should_quit, "Ctrl+C must still quit");
        assert!(
            app.error_details_popup
                .as_ref()
                .is_some_and(|popup| popup.copy_feedback.is_none()),
            "a modified key must not be treated as the popup copy action"
        );
    }

    /// Copying is unit-scoped: the clipboard boundary is injected, so the
    /// developer's real clipboard is never touched.
    #[test]
    fn unmodified_c_copies_stable_plain_text_and_keeps_the_popup_open() {
        let mut app = error_details_app();
        let clipboard =
            Arc::new(crate::tui::clipboard::test_doubles::RecordingClipboard::default());
        app.set_clipboard(clipboard.clone());
        assert!(app.open_error_details_popup());

        assert!(handle_error_details_popup_key(
            &mut app,
            key(KeyCode::Char('c'))
        ));

        assert_eq!(
            clipboard.copies(),
            vec!["Change: change-b\nError: Apply failed: stalled".to_string()]
        );
        let popup = app.error_details_popup.as_ref().expect("popup stays open");
        assert_eq!(popup.error, "Apply failed: stalled");
        assert_eq!(
            popup.copy_feedback,
            Some(crate::tui::state::CopyFeedback::Copied)
        );
    }

    /// Copy is spec'd as *unmodified* `c`. Any other modifier combination stays
    /// owned by the popup but must not reach the clipboard, and `Ctrl+C` keeps
    /// falling through to the global quit binding.
    #[tokio::test]
    async fn only_unmodified_c_copies_and_ctrl_c_still_quits() {
        for (code, modifiers) in [
            (KeyCode::Char('c'), KeyModifiers::SHIFT),
            (KeyCode::Char('C'), KeyModifiers::SHIFT),
            (KeyCode::Char('c'), KeyModifiers::SUPER),
            (
                KeyCode::Char('c'),
                KeyModifiers::SHIFT | KeyModifiers::SUPER,
            ),
        ] {
            let mut app = error_details_app();
            let clipboard =
                Arc::new(crate::tui::clipboard::test_doubles::RecordingClipboard::default());
            app.set_clipboard(clipboard.clone());
            assert!(app.open_error_details_popup());

            assert!(
                handle_error_details_popup_key(&mut app, KeyEvent::new(code, modifiers)),
                "{code:?}+{modifiers:?} stays owned by the popup"
            );

            assert!(
                clipboard.copies().is_empty(),
                "{code:?}+{modifiers:?} must not copy"
            );
            let popup = app.error_details_popup.as_ref().expect("popup stays open");
            assert!(
                popup.copy_feedback.is_none(),
                "{code:?}+{modifiers:?} reports no copy feedback"
            );
        }

        let mut app = error_details_app();
        let clipboard =
            Arc::new(crate::tui::clipboard::test_doubles::RecordingClipboard::default());
        app.set_clipboard(clipboard.clone());
        assert!(app.open_error_details_popup());

        assert!(handle_error_details_popup_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)
        ));

        assert_eq!(
            clipboard.copies(),
            vec!["Change: change-b\nError: Apply failed: stalled".to_string()],
            "unmodified c is the one binding that copies"
        );
        assert!(!app.should_quit, "unmodified c never quits");

        let mut app = error_details_app();
        let clipboard =
            Arc::new(crate::tui::clipboard::test_doubles::RecordingClipboard::default());
        app.set_clipboard(clipboard.clone());
        assert!(app.open_error_details_popup());

        route_key_event(
            &mut app,
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
        )
        .await;

        assert!(app.should_quit, "Ctrl+C keeps its global quit meaning");
        assert!(clipboard.copies().is_empty(), "Ctrl+C must not copy");
    }

    #[test]
    fn a_refused_copy_keeps_the_popup_open_with_actionable_feedback() {
        let mut app = error_details_app();
        app.set_clipboard(Arc::new(
            crate::tui::clipboard::test_doubles::FailingClipboard::new("no clipboard provider"),
        ));
        assert!(app.open_error_details_popup());

        assert!(handle_error_details_popup_key(
            &mut app,
            key(KeyCode::Char('c'))
        ));

        let popup = app.error_details_popup.as_ref().expect("popup stays open");
        assert_eq!(popup.error, "Apply failed: stalled");
        let feedback = popup.copy_feedback.clone().expect("failure is reported");
        assert_eq!(
            feedback,
            crate::tui::state::CopyFeedback::Failed("no clipboard provider".to_string())
        );
        let message = feedback.message();
        assert!(message.contains("no clipboard provider"), "{message}");
        assert!(message.contains("manually"), "{message}");
    }

    #[test]
    fn popup_keys_are_ignored_when_no_popup_is_open() {
        let mut app = error_details_app();

        for code in [
            KeyCode::Char('c'),
            KeyCode::Char('j'),
            KeyCode::Esc,
            KeyCode::PageDown,
        ] {
            assert!(
                !handle_error_details_popup_key(&mut app, key(code)),
                "{code:?} must fall through when the popup is closed"
            );
        }
    }

    // ========================================================================
    // Merged-row dismissal routing
    // ========================================================================

    /// A Changes-view app with two merged rows around one active row.
    ///
    /// The cursor starts on `merged-a`, so `d` has a target and `D` has three
    /// of them minus the active one.
    fn dismissal_routing_app() -> AppState {
        let mut app = AppState::new(vec![
            create_test_change("merged-a"),
            create_test_change("change-b"),
            create_test_change("merged-c"),
        ]);
        app.view_mode = ViewMode::Changes;
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_display_status_cache("merged");
        app.changes[1].set_display_status_cache("applying");
        app.changes[2].set_display_status_cache("merged");
        app.web_url = Some("http://127.0.0.1:8080".to_string());
        app
    }

    fn row_ids(app: &AppState) -> Vec<String> {
        app.changes.iter().map(|c| c.id.clone()).collect()
    }

    #[tokio::test]
    async fn changes_view_d_dismisses_the_focused_row_in_one_key_event() {
        let mut app = dismissal_routing_app();

        let commands = route_key(&mut app, KeyCode::Char('d')).await;

        assert!(commands.is_empty(), "dismissal dispatches no command");
        assert_eq!(app.modal, None, "no confirmation may open");
        assert_eq!(row_ids(&app), vec!["change-b", "merged-c"]);
        assert!(app.dismissed_merged_ids().contains("merged-a"));
        assert!(!app.dismissed_merged_ids().contains("merged-c"));
    }

    #[tokio::test]
    async fn changes_view_d_is_silent_on_a_non_merged_row() {
        let mut app = dismissal_routing_app();
        app.cursor_index = 1;

        let commands = route_key(&mut app, KeyCode::Char('d')).await;

        assert!(commands.is_empty());
        assert_eq!(app.modal, None);
        assert_eq!(row_ids(&app), vec!["merged-a", "change-b", "merged-c"]);
        assert!(app.dismissed_merged_ids().is_empty());
    }

    #[tokio::test]
    async fn changes_view_shift_d_dismisses_every_projected_merged_row_in_one_key_event() {
        let mut app = dismissal_routing_app();
        // Cursor position is irrelevant to the bulk target set.
        app.cursor_index = 1;

        let commands = route_key(&mut app, KeyCode::Char('D')).await;

        assert!(commands.is_empty());
        assert_eq!(app.modal, None, "no confirmation may open");
        assert_eq!(row_ids(&app), vec!["change-b"]);
        assert!(app.dismissed_merged_ids().contains("merged-a"));
        assert!(app.dismissed_merged_ids().contains("merged-c"));
    }

    #[tokio::test]
    async fn changes_view_shift_d_is_silent_without_a_merged_row() {
        let mut app = dismissal_routing_app();
        app.changes[0].set_display_status_cache("archived");
        app.changes[2].set_display_status_cache("pushed");

        let commands = route_key(&mut app, KeyCode::Char('D')).await;

        assert!(commands.is_empty());
        assert_eq!(app.modal, None);
        assert_eq!(row_ids(&app), vec!["merged-a", "change-b", "merged-c"]);
        assert!(app.dismissed_merged_ids().is_empty());
    }

    #[tokio::test]
    async fn y_n_and_esc_no_longer_carry_any_dismissal_meaning() {
        // With the confirmation gone there is no dismissal overlay for these
        // keys to answer, so a stray press must leave the rows alone. Esc keeps
        // its own stop semantics, which are not this module's business.
        for code in [
            KeyCode::Char('y'),
            KeyCode::Char('Y'),
            KeyCode::Char('n'),
            KeyCode::Char('N'),
            KeyCode::Esc,
        ] {
            let mut app = dismissal_routing_app();

            route_key(&mut app, code).await;

            assert_eq!(app.modal, None, "{code:?} must open no overlay");
            assert_eq!(row_ids(&app), vec!["merged-a", "change-b", "merged-c"]);
            assert!(
                app.dismissed_merged_ids().is_empty(),
                "{code:?} must not dismiss anything"
            );
        }
    }

    #[tokio::test]
    async fn an_overlay_that_owns_input_keeps_d_and_shift_d_away_from_the_rows() {
        // Another overlay already claims keys, so the view action underneath
        // must not run even though a merged row is focused.
        for code in [KeyCode::Char('d'), KeyCode::Char('D')] {
            let mut app = dismissal_routing_app();
            let overlay = ModalState::ConfirmForceKill {
                change_id: "change-b".to_string(),
            };
            app.modal = Some(overlay.clone());

            let commands = route_key(&mut app, code).await;

            assert!(commands.is_empty(), "{code:?} must dispatch nothing");
            assert_eq!(app.modal, Some(overlay), "{code:?}");
            assert_eq!(row_ids(&app), vec!["merged-a", "change-b", "merged-c"]);
            assert!(app.dismissed_merged_ids().is_empty(), "{code:?}");
        }
    }

    #[tokio::test]
    async fn dismissal_leaves_every_other_changes_view_control_intact() {
        let mut app = dismissal_routing_app();
        let marks_before: Vec<bool> = app.changes.iter().map(|c| c.selected).collect();

        route_key(&mut app, KeyCode::Char('d')).await;

        assert_eq!(
            app.view_mode,
            ViewMode::Changes,
            "dismissal must not switch views"
        );
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "dismissal must not touch the execution axis"
        );
        assert_eq!(
            app.changes.iter().map(|c| c.selected).collect::<Vec<_>>(),
            marks_before[1..].to_vec(),
            "surviving rows keep their execution marks"
        );
    }

    #[tokio::test]
    async fn worktrees_view_keeps_d_and_shift_d_as_worktree_deletion() {
        for code in [KeyCode::Char('d'), KeyCode::Char('D')] {
            let mut app = tui_dirty_worktree_delete_app(false);
            app.modal = None;
            // A merged row exists in the Changes projection; the Worktrees view
            // must still be the one that answers for these keys.
            app.changes[1].set_display_status_cache("merged");

            let commands = route_key(&mut app, code).await;

            assert!(commands.is_empty());
            assert_eq!(
                app.modal,
                Some(ModalState::ConfirmWorktreeDelete {
                    path: PathBuf::from("/tmp/wt-a"),
                    branch: "change-b".to_string(),
                }),
                "{code:?} must keep opening the worktree delete confirmation"
            );
            assert!(app.dismissed_merged_ids().is_empty());
        }
    }
}