cflx 0.6.45

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
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
//! State management for the TUI
//!
//! This module contains AppState and ChangeState implementations,
//! organized into submodules by responsibility.
//!
//! ## Shared State Integration
//!
//! The TUI can reference the shared orchestration state from `crate::orchestration::state::OrchestratorState`
//! for unified state tracking across TUI and Web interfaces. The shared state provides:
//! - Pending/archived change tracking
//! - Apply count tracking per change
//! - Current change being processed
//! - Iteration counters
//!
//! Both TUI and Web states are updated via `ExecutionEvent` messages, ensuring consistency.

use crate::openspec::Change;
use crate::tui::events::{LogEntry, LogLevel, TuiCommand};
use crate::tui::types::{AppMode, StopMode, ViewMode, WorktreeAction, WorktreeInfo};
use ratatui::style::Color;
use ratatui::widgets::ListState;
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;

use std::time::{Duration, Instant};
use tracing::{error, info, warn};

mod log_logic;
mod processing_logic;
mod selection_logic;
mod worktree_action_logic;
mod worktree_logic;

fn apply_remote_status(change: &mut ChangeState, status: &str) {
    // Avoid regressing active/terminal states based on laggy remote snapshots.
    let current = change.display_status_cache.as_str();

    let next = match status {
        "applying" => Some("applying"),
        "archiving" => Some("archiving"),
        "accepting" => Some("accepting"),
        "resolving" => Some("resolving"),
        "archived" => Some("archived"),
        "merged" => Some("merged"),
        "merge_wait" => Some("merge wait"),
        "resolve_wait" => Some("resolve pending"),
        "blocked" => Some("blocked"),
        "stalled" => Some("stalled"),
        "gated" => Some("gated"),
        "queued" => Some("queued"),
        "idle" => Some("not queued"),
        "rejected" => Some("rejected"),
        "error" => Some("error"),
        _ => None,
    };

    let Some(next) = next else {
        return;
    };

    // Don't downgrade active states to queued/idle.
    if matches!(
        current,
        "applying" | "archiving" | "accepting" | "resolving"
    ) && matches!(next, "queued" | "not queued")
    {
        return;
    }

    // Only set queued/idle if we're not already in an immutable terminal state.
    // Note: error is intentionally excluded to allow error -> queued retry transitions.
    if matches!(next, "queued" | "not queued") && matches!(current, "archived" | "merged") {
        return;
    }

    // Transition bookkeeping for elapsed time.
    if matches!(next, "applying") && change.started_at.is_none() {
        change.started_at = Some(Instant::now());
        change.elapsed_time = None;
    }

    if !matches!(next, "applying" | "archiving" | "accepting" | "resolving")
        && matches!(
            current,
            "applying" | "archiving" | "accepting" | "resolving"
        )
    {
        if let Some(started) = change.started_at {
            change.elapsed_time = Some(started.elapsed());
        }
    }

    if next == "error" {
        if change.error_message_cache.is_none() {
            change.error_message_cache = Some("remote".to_string());
        }
        change.set_display_status_cache("error");
    } else {
        change.set_display_status_cache(next);
    }
}

// ============================================================================
// Constants
// ============================================================================

/// Auto-refresh interval in seconds
pub const AUTO_REFRESH_INTERVAL_SECS: u64 = 5;

/// Maximum number of log entries to keep
pub const MAX_LOG_ENTRIES: usize = 1000;

// ============================================================================
// Type Definitions
// ============================================================================

/// Warning popup content
pub struct WarningPopup {
    pub title: String,
    pub message: String,
}

/// State of a single change in the TUI
#[derive(Debug, Clone)]
pub struct ChangeState {
    /// Change ID
    pub id: String,
    /// Number of completed tasks
    pub completed_tasks: u32,
    /// Total number of tasks
    pub total_tasks: u32,
    /// Display status cache (from reducer/TUI events)
    pub display_status_cache: String,
    /// Display color cache for status
    pub display_color_cache: Color,
    /// Error message cache for error status
    pub error_message_cache: Option<String>,
    /// Whether this change is selected
    pub selected: bool,
    /// Whether this is a newly detected change
    pub is_new: bool,
    /// Whether this change is eligible for parallel execution
    pub is_parallel_eligible: bool,
    /// Whether a worktree exists for this change
    pub has_worktree: bool,
    /// When processing started for this change
    pub started_at: Option<Instant>,
    /// Elapsed time when processing finished (for display after completion)
    pub elapsed_time: Option<Duration>,
    /// Current iteration number (for apply/archive/acceptance operations)
    pub iteration_number: Option<u32>,
}

/// Main application state for the TUI
pub struct AppState {
    /// Current view mode (Changes or Worktrees)
    pub view_mode: ViewMode,
    /// Current mode
    pub mode: AppMode,
    /// List of changes with their states
    pub changes: Vec<ChangeState>,
    /// Current cursor position in the list
    pub cursor_index: usize,
    /// List widget state
    pub list_state: ListState,
    /// List of worktrees
    pub worktrees: Vec<WorktreeInfo>,
    /// Current cursor position in the worktree list
    pub worktree_cursor_index: usize,
    /// Worktree list widget state
    pub worktree_list_state: ListState,
    /// Pending worktree action confirmation (path, action)
    pub pending_worktree_action: Option<(String, WorktreeAction)>,
    /// Branch name associated with pending worktree action (for deletion)
    pub pending_worktree_branch: Option<String>,
    /// ID of the currently processing change
    pub current_change: Option<String>,
    /// ID of the change that caused the error (for display in Error mode)
    pub error_change_id: Option<String>,
    /// Log entries
    pub logs: Vec<LogEntry>,
    /// Last auto-refresh timestamp
    pub last_refresh: Instant,
    /// Number of newly detected changes
    pub new_change_count: usize,
    /// Known change IDs (for detecting new changes)
    pub known_change_ids: HashSet<String>,
    /// Whether the application should quit
    pub should_quit: bool,
    /// Warning message to display
    pub warning_message: Option<String>,
    /// Warning popup content
    pub warning_popup: Option<WarningPopup>,
    /// Current spinner animation frame
    pub spinner_frame: usize,
    /// Log scroll offset (0 = show most recent at bottom)
    pub log_scroll_offset: usize,
    /// Whether to auto-scroll logs to bottom on new entries
    pub log_auto_scroll: bool,
    /// Current stop mode
    pub stop_mode: StopMode,
    /// Whether parallel mode is enabled
    pub parallel_mode: bool,
    /// Whether parallel execution is available (git)
    pub parallel_available: bool,
    /// VCS backend being used (git)
    pub vcs_backend: String,
    /// Max concurrent workspaces for parallel execution
    pub max_concurrent: usize,
    /// When orchestration started (for overall elapsed time)
    pub orchestration_started_at: Option<Instant>,
    /// Total elapsed time when orchestration finished
    pub orchestration_elapsed: Option<Duration>,
    /// Mode to return to after closing modal popups
    pub previous_mode: Option<AppMode>,
    /// Web UI URL (set when web server is enabled)
    pub web_url: Option<String>,
    /// Whether resolve is currently executing (blocks M key operations)
    pub is_resolving: bool,
    /// Map of change_id to worktree path for active worktrees (for progress fallback)
    pub worktree_paths: HashMap<String, PathBuf>,
    /// Reference to shared orchestration state (for unified state tracking)
    /// TUI can query this for pending/archived status, apply counts, etc.
    pub shared_orchestrator_state:
        Option<std::sync::Arc<tokio::sync::RwLock<crate::orchestration::state::OrchestratorState>>>,
    /// Manual resolve queue (FIFO) for sequential resolve processing
    pub resolve_queue: VecDeque<String>,
    /// Set of change IDs in the resolve queue for duplicate prevention
    pub resolve_queue_set: HashSet<String>,
    /// Whether the log panel is visible in Changes view
    pub logs_panel_enabled: bool,
}

// ============================================================================
// ChangeState Implementation
// ============================================================================

impl ChangeState {
    /// Create a new ChangeState from a Change
    ///
    /// Note: This method initializes state from the Change object. Task progress
    /// is synchronized with shared orchestrator state in update_changes(), which
    /// populates OrchestratorState::task_progress() from fetched changes and then
    /// queries it back when updating UI state. This ensures consistency between
    /// TUI and orchestrator for progress tracking.
    pub fn from_change(change: &Change) -> Self {
        Self {
            id: change.id.clone(),
            // Initial values from Change object; synchronized with shared state in update_changes()
            completed_tasks: change.completed_tasks,
            total_tasks: change.total_tasks,
            selected: false, // Always start unselected
            is_new: false,
            display_status_cache: "not queued".to_string(),
            display_color_cache: Color::DarkGray,
            error_message_cache: None,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
        }
    }

    /// Calculate progress percentage
    pub fn progress_percent(&self) -> f32 {
        if self.total_tasks == 0 {
            return 0.0;
        }
        (self.completed_tasks as f32 / self.total_tasks as f32) * 100.0
    }

    pub fn set_display_status_cache(&mut self, status: &str) {
        self.display_status_cache = status.to_string();
        self.display_color_cache = match status {
            "not queued" => Color::DarkGray,
            "queued" => Color::Yellow,
            "blocked" => Color::Gray,
            "stalled" => Color::LightYellow,
            "gated" => Color::LightRed,
            "applying" => Color::Cyan,
            "accepting" => Color::LightGreen,
            "archiving" => Color::Magenta,
            "merge wait" => Color::LightMagenta,
            "resolve pending" => Color::Magenta,
            "resolving" => Color::LightCyan,
            "archived" => Color::Blue,
            "merged" => Color::LightBlue,
            "rejected" => Color::LightRed,
            "error" => Color::Red,
            _ => Color::DarkGray,
        };
        if status != "error" {
            self.error_message_cache = None;
        }
    }

    pub fn set_error_message_cache(&mut self, message: String) {
        self.error_message_cache = Some(message);
        self.set_display_status_cache("error");
    }

    pub fn is_active_display_status(&self) -> bool {
        matches!(
            self.display_status_cache.as_str(),
            "applying" | "accepting" | "archiving" | "resolving"
        )
    }

    /// Update iteration number with monotonic increase guard
    ///
    /// This helper ensures iteration display doesn't regress within the same stage.
    /// - Ignores None values (no-op)
    /// - Only updates if new_iteration > current iteration_number
    /// - Prevents display flickering when out-of-order events arrive
    pub fn update_iteration_monotonic(&mut self, new_iteration: Option<u32>) {
        if let Some(new_val) = new_iteration {
            match self.iteration_number {
                None => {
                    // First iteration for this stage, accept it
                    self.iteration_number = Some(new_val);
                }
                Some(current) => {
                    // Only update if new value is higher (monotonic increase)
                    if new_val > current {
                        self.iteration_number = Some(new_val);
                    }
                    // Otherwise, ignore (prevents regression)
                }
            }
        }
        // If new_iteration is None, ignore (no update)
    }
}

// ============================================================================
// AppState Core Implementation
// ============================================================================

impl AppState {
    /// Create a new AppState with initial changes
    ///
    /// All changes start unselected on startup.
    /// Users must explicitly select changes to process.
    pub fn new(changes: Vec<Change>) -> Self {
        let known_ids: HashSet<String> = changes.iter().map(|c| c.id.clone()).collect();

        // All changes start unselected
        let change_states: Vec<ChangeState> =
            changes.iter().map(ChangeState::from_change).collect();

        let mut list_state = ListState::default();
        if !change_states.is_empty() {
            list_state.select(Some(0));
        }

        Self {
            view_mode: ViewMode::Changes,
            mode: AppMode::Select,
            changes: change_states,
            cursor_index: 0,
            list_state,
            worktrees: Vec::new(),
            worktree_cursor_index: 0,
            worktree_list_state: ListState::default(),
            pending_worktree_action: None,
            pending_worktree_branch: None,
            current_change: None,
            error_change_id: None,
            logs: Vec::new(),
            last_refresh: Instant::now(),
            new_change_count: 0,
            known_change_ids: known_ids,
            should_quit: false,
            warning_message: None,
            warning_popup: None,
            spinner_frame: 0,
            log_scroll_offset: 0,
            log_auto_scroll: true,
            stop_mode: StopMode::None,
            parallel_mode: false,
            parallel_available: crate::cli::check_parallel_available(),
            vcs_backend: "git".to_string(),
            max_concurrent: 4, // Default value, can be overridden from config
            orchestration_started_at: None,
            orchestration_elapsed: None,
            previous_mode: None,
            web_url: None,
            is_resolving: false,
            worktree_paths: HashMap::new(),
            shared_orchestrator_state: None,
            resolve_queue: VecDeque::new(),
            resolve_queue_set: HashSet::new(),
            logs_panel_enabled: true, // Default: logs panel visible
        }
    }

    /// Set reference to shared orchestration state for unified tracking.
    /// This allows TUI to query core orchestration state (pending/archived, apply counts, etc.)
    pub fn set_shared_state(
        &mut self,
        shared_state: std::sync::Arc<
            tokio::sync::RwLock<crate::orchestration::state::OrchestratorState>,
        >,
    ) {
        self.shared_orchestrator_state = Some(shared_state);
    }

    /// Show QR popup (only when web_url is set)
    pub fn show_qr_popup(&mut self) {
        if self.web_url.is_some() {
            self.previous_mode = Some(self.mode.clone());
            self.mode = AppMode::QrPopup;
        }
    }

    /// Hide QR popup and return to previous mode
    pub fn hide_qr_popup(&mut self) {
        if let Some(mode) = self.previous_mode.take() {
            self.mode = mode;
        } else {
            self.mode = AppMode::Select;
        }
    }

    /// Move cursor up
    pub fn cursor_up(&mut self) {
        if self.changes.is_empty() {
            return;
        }
        self.cursor_index = if self.cursor_index == 0 {
            self.changes.len() - 1
        } else {
            self.cursor_index - 1
        };
        self.list_state.select(Some(self.cursor_index));
    }

    /// Move cursor down
    pub fn cursor_down(&mut self) {
        if self.changes.is_empty() {
            return;
        }
        self.cursor_index = (self.cursor_index + 1) % self.changes.len();
        self.list_state.select(Some(self.cursor_index));
    }

    /// Move worktree cursor up
    pub fn worktree_cursor_up(&mut self) {
        let Some(next_index) = worktree_logic::previous_worktree_cursor_index(
            self.worktree_cursor_index,
            self.worktrees.len(),
        ) else {
            return;
        };

        self.worktree_cursor_index = next_index;
        self.worktree_list_state
            .select(Some(self.worktree_cursor_index));
    }

    /// Move worktree cursor down
    pub fn worktree_cursor_down(&mut self) {
        let Some(next_index) = worktree_logic::next_worktree_cursor_index(
            self.worktree_cursor_index,
            self.worktrees.len(),
        ) else {
            return;
        };

        self.worktree_cursor_index = next_index;
        self.worktree_list_state
            .select(Some(self.worktree_cursor_index));
    }

    /// Get the selected worktree path (if any)
    pub fn get_selected_worktree_path(&self) -> Option<String> {
        if self.worktree_cursor_index < self.worktrees.len() {
            Some(
                self.worktrees[self.worktree_cursor_index]
                    .path
                    .display()
                    .to_string(),
            )
        } else {
            None
        }
    }

    /// Get the selected worktree (if any)
    pub fn get_selected_worktree(&self) -> Option<&WorktreeInfo> {
        if self.worktree_cursor_index < self.worktrees.len() {
            Some(&self.worktrees[self.worktree_cursor_index])
        } else {
            None
        }
    }

    /// Request worktree delete with validation
    ///
    /// Returns Some(TuiCommand) if deletion should proceed, None if it should be blocked
    pub fn request_worktree_delete_from_list(&mut self) -> Option<TuiCommand> {
        match worktree_action_logic::validate_delete_request(
            &self.worktrees,
            self.worktree_cursor_index,
            &self.changes,
        ) {
            Ok((path, branch)) => {
                worktree_action_logic::apply_delete_confirmation_state(
                    path,
                    branch,
                    &mut self.mode,
                    &mut self.pending_worktree_action,
                    &mut self.pending_worktree_branch,
                    &mut self.previous_mode,
                );
                None
            }
            Err(msg) => {
                self.warning_message = Some(msg);
                None
            }
        }
    }

    /// Confirm and execute pending worktree action
    pub fn confirm_worktree_action_delete(&mut self) -> Option<TuiCommand> {
        if let Some((path, WorktreeAction::Delete)) = self.pending_worktree_action.take() {
            // Get the branch name that was stored when the delete was requested
            let branch_name = self.pending_worktree_branch.take();

            // Restore previous mode
            if let Some(mode) = self.previous_mode.take() {
                self.mode = mode;
            } else {
                self.mode = AppMode::Select;
            }

            Some(TuiCommand::DeleteWorktreeByPath(path.into(), branch_name))
        } else {
            None
        }
    }

    /// Cancel pending worktree action
    pub fn cancel_worktree_action(&mut self) {
        self.pending_worktree_action = None;
        self.pending_worktree_branch = None;

        // Restore previous mode
        if let Some(mode) = self.previous_mode.take() {
            self.mode = mode;
        } else {
            self.mode = AppMode::Select;
        }
    }

    /// Request to merge worktree branch into base branch.
    ///
    /// Returns Some(TuiCommand) if merge should proceed, None if blocked.
    pub fn request_merge_worktree_branch(&mut self) -> Option<TuiCommand> {
        worktree_action_logic::request_merge_worktree_branch(self)
    }

    /// Toggle selection of the current change
    ///
    /// In Select mode:
    /// - Changes can be toggled between selected/unselected
    ///
    /// In Running/Completed mode:
    /// - Changes can be added to or removed from the queue
    pub fn toggle_selection(&mut self) -> Option<TuiCommand> {
        selection_logic::toggle_selection(self)
    }

    fn can_bulk_toggle_change(&self, change: &ChangeState) -> bool {
        selection_logic::can_bulk_toggle_change(self.mode.clone(), self.parallel_mode, change)
    }

    /// Returns true when at least one change can be targeted by bulk toggle.
    pub fn has_bulk_toggle_targets(&self) -> bool {
        matches!(
            self.mode,
            AppMode::Select | AppMode::Stopped | AppMode::Running
        ) && self
            .changes
            .iter()
            .any(|change| self.can_bulk_toggle_change(change))
    }

    /// Toggle all marks (select/unselect all eligible changes)
    ///
    /// In Select/Stopped/Running modes:
    /// - If any eligible unmarked change exists, mark all eligible changes
    /// - Otherwise, unmark all eligible changes
    ///
    /// Running mode excludes active rows to avoid emitting stop requests.
    /// Running mode emits `AddToQueue`/`RemoveFromQueue` commands for
    /// `NotQueued`/`Queued` rows (same semantics as single-row Space).
    /// `MergeWait`/`ResolveWait` rows only toggle the execution mark.
    /// In parallel mode, uncommitted changes remain excluded.
    pub fn toggle_all_marks(&mut self) -> Vec<TuiCommand> {
        if !self.has_bulk_toggle_targets() {
            return Vec::new();
        }

        // If any eligible unmarked change exists, we mark all; otherwise unmark all.
        let has_unmarked = self
            .changes
            .iter()
            .any(|change| !change.selected && self.can_bulk_toggle_change(change));

        let target_state = has_unmarked;
        let is_running = matches!(self.mode, AppMode::Running);
        let mut commands = Vec::new();

        // Toggle all eligible changes to the target state.
        for i in 0..self.changes.len() {
            if !self.can_bulk_toggle_change(&self.changes[i]) {
                continue;
            }

            if self.changes[i].selected != target_state {
                self.changes[i].selected = target_state;
                // Clear NEW flag when user interacts with the change
                if self.changes[i].is_new {
                    self.changes[i].is_new = false;
                    self.new_change_count = self.new_change_count.saturating_sub(1);
                }

                // In Running mode, emit queue commands for NotQueued/Queued rows
                // (same semantics as single-row Space toggle).
                // MergeWait/ResolveWait only toggle the execution mark.
                if is_running {
                    match self.changes[i].display_status_cache.as_str() {
                        "not queued" if target_state => {
                            let id = self.changes[i].id.clone();
                            self.add_log(LogEntry::info(format!("Added to queue: {}", id)));
                            commands.push(TuiCommand::AddToQueue(id));
                        }
                        "queued" if !target_state => {
                            let id = self.changes[i].id.clone();
                            self.add_log(LogEntry::info(format!("Removed from queue: {}", id)));
                            commands.push(TuiCommand::RemoveFromQueue(id));
                        }
                        _ => {}
                    }
                }
            }
        }

        let action = if target_state { "marked" } else { "unmarked" };
        let count = self
            .changes
            .iter()
            .filter(|change| self.can_bulk_toggle_change(change) && change.selected == target_state)
            .count();
        self.add_log(LogEntry::info(format!(
            "Toggled all: {} {} change(s)",
            count, action
        )));

        commands
    }

    /// Trigger merge resolution for the selected change when applicable.
    ///
    /// If resolve is already running, the change is added to the resolve queue
    /// and transitioned to ResolveWait instead of starting immediately.
    pub fn resolve_merge(&mut self) -> Option<TuiCommand> {
        // Must have valid cursor position
        if self.changes.is_empty() || self.cursor_index >= self.changes.len() {
            return None;
        }

        // Must be in correct mode
        if !matches!(
            self.mode,
            AppMode::Select | AppMode::Stopped | AppMode::Running
        ) {
            return None;
        }

        // Check current change status and get change_id
        let change_id = {
            let change = &self.changes[self.cursor_index];
            if !matches!(change.display_status_cache.as_str(), "merge wait") {
                return None;
            }
            change.id.clone()
        };

        if self.is_resolving {
            // Resolve is running: add to queue and transition to ResolveWait
            if self.add_to_resolve_queue(&change_id) {
                self.changes[self.cursor_index].set_display_status_cache("resolve pending");

                // Sync resolve intent into the shared reducer so that
                // apply_display_statuses_from_reducer() cannot regress the
                // status back to "merge wait" on the next ChangesRefreshed.
                if let Some(shared) = &self.shared_orchestrator_state {
                    if let Ok(mut guard) = shared.try_write() {
                        guard.apply_command(
                            crate::orchestration::state::ReducerCommand::ResolveMerge(
                                change_id.clone(),
                            ),
                        );
                    }
                }

                self.add_log(LogEntry::info(format!(
                    "Queued '{}' for resolve (position: {})",
                    change_id,
                    self.resolve_queue.len()
                )));
            } else {
                self.warning_message = Some(format!(
                    "Change '{}' is already queued for resolve",
                    change_id
                ));
            }
            None
        } else {
            // Resolve is not running: reserve the resolve slot immediately so
            // consecutive M key presses queue follow-up changes instead of
            // dispatching multiple immediate resolve commands in parallel.
            // Actual execution still starts when ResolveStarted event is received.
            self.is_resolving = true;
            if matches!(self.mode, AppMode::Select | AppMode::Stopped) {
                self.mode = AppMode::Running;
            }
            self.changes[self.cursor_index].set_display_status_cache("resolve pending");

            // Sync resolve intent into the shared reducer so that
            // apply_display_statuses_from_reducer() cannot regress the
            // status back to "merge wait" on the next ChangesRefreshed.
            if let Some(shared) = &self.shared_orchestrator_state {
                if let Ok(mut guard) = shared.try_write() {
                    guard.apply_command(crate::orchestration::state::ReducerCommand::ResolveMerge(
                        change_id.clone(),
                    ));
                }
            }

            Some(TuiCommand::ResolveMerge(change_id))
        }
    }

    /// Add a change to the resolve queue (with duplicate prevention).
    ///
    /// Returns true if the change was added, false if it was already in the queue.
    pub fn add_to_resolve_queue(&mut self, change_id: &str) -> bool {
        if self.resolve_queue_set.contains(change_id) {
            false
        } else {
            self.resolve_queue.push_back(change_id.to_string());
            self.resolve_queue_set.insert(change_id.to_string());
            true
        }
    }

    /// Pop the next change from the resolve queue.
    ///
    /// Returns the change ID if the queue is not empty, otherwise None.
    pub fn pop_from_resolve_queue(&mut self) -> Option<String> {
        if let Some(change_id) = self.resolve_queue.pop_front() {
            self.resolve_queue_set.remove(&change_id);
            Some(change_id)
        } else {
            None
        }
    }

    /// Check if there are queued resolves waiting.
    #[cfg(test)]
    pub fn has_queued_resolves(&self) -> bool {
        !self.resolve_queue.is_empty()
    }

    /// Update parallel eligibility status for changes.
    ///
    /// A change is eligible for parallel execution if:
    /// 1. It exists in HEAD's commit tree (committed_change_ids), AND
    /// 2. It has no uncommitted or untracked files under openspec/changes/<change_id>/
    pub fn apply_parallel_eligibility(
        &mut self,
        committed_change_ids: &HashSet<String>,
        uncommitted_file_change_ids: &HashSet<String>,
    ) {
        for change in &mut self.changes {
            // Eligible if committed AND no uncommitted files
            change.is_parallel_eligible = committed_change_ids.contains(&change.id)
                && !uncommitted_file_change_ids.contains(&change.id);
            if self.parallel_mode
                && matches!(self.mode, AppMode::Select | AppMode::Stopped)
                && !change.is_parallel_eligible
            {
                if change.selected {
                    change.selected = false;
                }
                if matches!(change.display_status_cache.as_str(), "queued") {
                    change.set_display_status_cache("not queued");
                }
            }
        }
    }

    /// Update worktree presence flags for changes.
    pub fn apply_worktree_status(&mut self, worktree_change_ids: &HashSet<String>) {
        for change in &mut self.changes {
            let sanitized = change.id.replace(['/', '\\', ' '], "-");
            change.has_worktree = worktree_change_ids.contains(&sanitized);
        }
    }

    /// Sync displayed status caches from the reducer's display status snapshot.
    ///
    /// This is Phase 6.1: TUI derives displayed change status from the shared
    /// orchestration reducer state instead of maintaining an independent lifecycle copy.
    /// Only transitions that are safe (no active execution regression) are applied.
    pub fn apply_display_statuses_from_reducer(
        &mut self,
        display_map: &HashMap<String, &'static str>,
    ) {
        for change in &mut self.changes {
            if change.display_status_cache == "rejected" {
                // rejected rows are display-only and remain immutable until marker removal.
                change.selected = false;
                continue;
            }

            if let Some(&status_str) = display_map.get(&change.id) {
                let normalized = match status_str {
                    "stopped" => "not queued",
                    other => other,
                };

                if normalized == "error" {
                    if change.display_status_cache == "error" {
                        continue;
                    }
                    if change.error_message_cache.is_none() {
                        change.error_message_cache = Some("reducer".to_string());
                    }
                    change.set_display_status_cache("error");
                } else {
                    change.set_display_status_cache(normalized);
                    if normalized == "rejected" {
                        change.selected = false;
                    }
                }
            }
        }
    }

    /// Get the number of selected changes
    pub fn selected_count(&self) -> usize {
        self.changes.iter().filter(|c| c.selected).count()
    }
}

// ============================================================================
// Mode-related Methods
// ============================================================================

impl AppState {
    /// Toggle parallel mode (only if git is available)
    ///
    /// Returns true if the mode was toggled, false if git is not available
    /// or if the mode cannot be changed in current state.
    pub fn toggle_parallel_mode(&mut self) -> bool {
        // Only allow toggling in Select or Stopped mode
        if !matches!(self.mode, AppMode::Select | AppMode::Stopped) {
            self.warning_message = Some("Cannot toggle parallel mode while processing".to_string());
            return false;
        }

        // Check if parallel execution is available (git)
        if !self.parallel_available {
            self.warning_message = Some("Parallel mode not available (requires git)".to_string());
            return false;
        }

        self.parallel_mode = !self.parallel_mode;
        let status = if self.parallel_mode {
            "enabled"
        } else {
            "disabled"
        };

        if self.parallel_mode {
            let mut removed = Vec::new();
            for change in &mut self.changes {
                if !change.is_parallel_eligible && change.selected {
                    change.selected = false;
                    if matches!(change.display_status_cache.as_str(), "queued") {
                        change.set_display_status_cache("not queued");
                    }
                    removed.push(change.id.clone());
                }
            }
            if !removed.is_empty() {
                self.warning_message = Some(format!(
                    "Removed uncommitted changes from queue in parallel mode: {}",
                    removed.join(", ")
                ));
            }
        }

        self.add_log(LogEntry::info(format!("Parallel mode {}", status)));
        true
    }

    /// Reset stop/cancel state before a new run
    pub fn reset_for_run(&mut self) {
        self.stop_mode = StopMode::None;
        self.current_change = None;
        self.error_change_id = None;
        self.orchestration_started_at = Some(Instant::now());
        self.orchestration_elapsed = None;
    }

    /// Start processing selected changes
    pub fn start_processing(&mut self) -> Option<TuiCommand> {
        selection_logic::start_processing(self)
    }

    /// Resume processing from Stopped mode
    /// Converts execution-marked (selected) changes to Queued and starts processing
    pub fn resume_processing(&mut self) -> Option<TuiCommand> {
        selection_logic::resume_processing(self)
    }

    /// Retry error changes - resets error changes to queued and returns their IDs
    /// Returns None if not in Error mode or no error changes found
    pub fn retry_error_changes(&mut self) -> Option<TuiCommand> {
        selection_logic::retry_error_changes(self)
    }
}

// ============================================================================
// Log Management
// ============================================================================

impl AppState {
    /// Get the latest log entry for a specific change_id
    ///
    /// Returns the most recent log entry that matches the given change_id.
    /// Used for displaying log previews in the change list.
    ///
    /// In remote mode, change IDs have the form `"<project_id>::<project_name>/<change_id>"`.
    /// Log entries from the remote server may have `change_id` set to the bare `project_id`
    /// (when no specific change is known). This method also matches those project-level logs
    /// by checking if the `change_id` argument starts with `"<entry.change_id>::"`.
    pub fn get_latest_log_for_change(&self, change_id: &str) -> Option<&LogEntry> {
        self.logs.iter().rev().find(|entry| {
            if let Some(entry_cid) = entry.change_id.as_deref() {
                // Exact match (local mode and remote mode with full change_id)
                if entry_cid == change_id {
                    return true;
                }
                // Project-level log match: entry has project_id, change_id starts with that project_id
                // Remote change IDs have the form "<project_id>::<project_name>/<change_id>"
                // Remote logs with only project_id set as change_id will match via this prefix check.
                let prefix = format!("{}::", entry_cid);
                if change_id.starts_with(&prefix) {
                    return true;
                }
            }
            false
        })
    }

    /// Add a log entry
    pub fn add_log(&mut self, entry: LogEntry) {
        // Send to tracing for debug file output (always enabled)
        // Include change_id, operation, iteration, and workspace_path in tracing output for context matching
        let change_id = entry.change_id.as_deref().unwrap_or("-");
        let operation = entry.operation.as_deref().unwrap_or("-");
        let iteration = entry.iteration.unwrap_or(0);
        let workspace_path = entry.workspace_path.as_deref().unwrap_or("-");

        match entry.level {
            LogLevel::Info | LogLevel::Success => {
                info!(
                    target: "tui_log",
                    change_id = change_id,
                    operation = operation,
                    iteration = iteration,
                    workspace_path = workspace_path,
                    "{}",
                    entry.message
                );
            }
            LogLevel::Warn => {
                warn!(
                    target: "tui_log",
                    change_id = change_id,
                    operation = operation,
                    iteration = iteration,
                    workspace_path = workspace_path,
                    "{}",
                    entry.message
                );
            }
            LogLevel::Error => {
                error!(
                    target: "tui_log",
                    change_id = change_id,
                    operation = operation,
                    iteration = iteration,
                    workspace_path = workspace_path,
                    "{}",
                    entry.message
                );
            }
        }

        self.logs.push(entry);

        // Handle buffer trimming when exceeding max entries
        if log_logic::apply_log_buffer_limit(self.logs.len(), MAX_LOG_ENTRIES) {
            self.logs.remove(0);
        }

        // Auto-scroll to bottom if enabled, otherwise freeze view position
        self.log_scroll_offset = log_logic::next_log_offset_on_append(
            self.log_auto_scroll,
            self.log_scroll_offset,
            self.logs.len(),
        );
    }

    /// Scroll logs up by a page (show older entries)
    pub fn scroll_logs_up(&mut self, page_size: usize) {
        self.log_scroll_offset =
            log_logic::scroll_logs_up(self.log_scroll_offset, self.logs.len(), page_size);
        // Disable auto-scroll when user scrolls up
        self.log_auto_scroll = false;
    }

    /// Scroll logs down by a page (show newer entries)
    pub fn scroll_logs_down(&mut self, page_size: usize) {
        self.log_scroll_offset = log_logic::scroll_logs_down(self.log_scroll_offset, page_size);
        // Re-enable auto-scroll when at bottom
        if self.log_scroll_offset == 0 {
            self.log_auto_scroll = true;
        }
    }

    /// Jump to the oldest log entry (top of history)
    pub fn scroll_logs_to_top(&mut self) {
        self.log_scroll_offset = log_logic::scroll_logs_to_top(self.logs.len());
        self.log_auto_scroll = false;
    }

    /// Jump to the newest log entry (bottom) and re-enable auto-scroll
    pub fn scroll_logs_to_bottom(&mut self) {
        self.log_scroll_offset = 0;
        self.log_auto_scroll = true;
    }

    /// Toggle log panel visibility
    pub fn toggle_logs_panel(&mut self) {
        self.logs_panel_enabled = log_logic::toggle_logs_panel(self.logs_panel_enabled);
    }
}

// ============================================================================
// Event Handling
// ============================================================================

mod event_handlers;

// ============================================================================
// Helper Methods
// ============================================================================

impl AppState {
    /// Update changes from a refresh
    ///
    /// Updates task progress (completed_tasks, total_tasks) from fetched changes and
    /// enriches change metadata from shared orchestration state when available (apply counts,
    /// pending/archived tracking).
    ///
    /// IMPORTANT: This method does NOT modify display_status_cache. In Stopped mode, task completion
    /// does not trigger auto-queue. Changes are only queued through explicit user action (Space key).
    ///
    /// Note: Task progress is synchronized with shared orchestration state.
    /// When changes are fetched from openspec CLI, their task progress is written
    /// to OrchestratorState::task_progress(). When updating UI state, progress is
    /// read from shared state to ensure consistency across TUI and orchestrator.
    fn update_changes(&mut self, fetched_changes: Vec<Change>) {
        processing_logic::update_changes(self, fetched_changes);
    }

    #[cfg(test)]
    fn update_changes_with_rejected_for_test(
        &mut self,
        fetched_changes: Vec<Change>,
        rejected_changes: Vec<Change>,
    ) {
        processing_logic::update_changes_with_rejected(self, fetched_changes, rejected_changes);
    }
}
// Note: auto_clear_merge_wait() and apply_merge_wait_status() have been removed in Phase 5.3.
// Their logic is now handled by the shared reducer's apply_observation() path.
// The TUI syncs display_status_cache via apply_display_statuses_from_reducer() in the runner.

// ============================================================================
// Guard Logic
// ============================================================================

mod guards {
    use super::{ChangeState, TuiCommand, ViewMode, WorktreeInfo};

    /// Result type for merge validation
    pub enum MergeGuardResult {
        /// Merge is allowed
        Allowed,
        /// Merge is blocked with a warning message
        Blocked(String),
    }

    /// Validates that the view mode is correct for merge operations
    pub fn validate_view_mode(view_mode: ViewMode) -> MergeGuardResult {
        if view_mode != ViewMode::Worktrees {
            MergeGuardResult::Blocked("Switch to Worktrees view to merge".to_string())
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates that no resolve operation is in progress
    pub fn validate_not_resolving(is_resolving: bool) -> MergeGuardResult {
        if is_resolving {
            MergeGuardResult::Blocked("Cannot merge: resolve operation in progress".to_string())
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates that worktrees list is not empty
    pub fn validate_worktrees_not_empty(worktrees_len: usize) -> MergeGuardResult {
        if worktrees_len == 0 {
            MergeGuardResult::Blocked("No worktrees loaded".to_string())
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates that cursor index is within bounds
    pub fn validate_cursor_in_bounds(
        cursor_index: usize,
        worktrees_len: usize,
    ) -> MergeGuardResult {
        if cursor_index >= worktrees_len {
            MergeGuardResult::Blocked(format!(
                "Cursor out of range: {} >= {}",
                cursor_index, worktrees_len
            ))
        } else {
            MergeGuardResult::Allowed
        }
    }

    /// Validates worktree-specific constraints for merging
    pub fn validate_worktree_mergeable(worktree: &WorktreeInfo) -> MergeGuardResult {
        // Cannot merge main worktree
        if worktree.is_main {
            return MergeGuardResult::Blocked("Cannot merge main worktree".to_string());
        }

        // Cannot merge detached HEAD
        if worktree.is_detached {
            return MergeGuardResult::Blocked("Cannot merge detached HEAD".to_string());
        }

        // Cannot merge if conflicts detected
        if worktree.has_merge_conflict() {
            return MergeGuardResult::Blocked(format!(
                "Cannot merge: {} conflict(s) detected",
                worktree.conflict_file_count()
            ));
        }

        // Branch name must not be empty
        if worktree.branch.is_empty() {
            return MergeGuardResult::Blocked("Cannot merge: no branch name".to_string());
        }

        // Cannot merge if no commits ahead of base branch
        if !worktree.has_commits_ahead {
            return MergeGuardResult::Blocked(
                "Cannot merge: no commits ahead of base branch".to_string(),
            );
        }

        // Cannot merge if already merging (redundant check after has_commits_ahead,
        // but kept for explicit validation)
        if worktree.is_merging {
            return MergeGuardResult::Blocked(
                "Cannot merge: merge already in progress".to_string(),
            );
        }

        MergeGuardResult::Allowed
    }

    /// Result type for toggle selection validation
    pub enum ToggleGuardResult {
        /// Operation is allowed
        Allowed,
        /// Operation is blocked with a warning message
        Blocked(String),
    }

    impl ToggleGuardResult {
        /// Check if the operation is allowed
        pub fn is_allowed(&self) -> bool {
            matches!(self, ToggleGuardResult::Allowed)
        }
    }

    /// Validates that a change can be toggled for selection
    pub fn validate_change_toggleable(
        is_parallel_eligible: bool,
        parallel_mode: bool,
        display_status_cache: &str,
        change_id: &str,
    ) -> ToggleGuardResult {
        // Active (in-flight) changes can be stopped via Space key in Running mode
        // This is allowed and handled by handle_toggle_running_mode
        // No need to block here

        // Cannot select uncommitted changes in parallel mode (only applies to non-active states)
        if parallel_mode
            && !is_parallel_eligible
            && !matches!(
                display_status_cache,
                "applying" | "accepting" | "archiving" | "resolving"
            )
        {
            return ToggleGuardResult::Blocked(format!(
                "Cannot queue uncommitted change '{}' in parallel mode. Commit it first.",
                change_id
            ));
        }

        if display_status_cache == "rejected" {
            return ToggleGuardResult::Blocked(format!(
                "Change '{}' is rejected and read-only",
                change_id
            ));
        }

        // MergeWait and ResolveWait can toggle execution mark (selected)
        // but cannot change display_status_cache or modify DynamicQueue
        // This is handled by the mode-specific handlers
        ToggleGuardResult::Allowed
    }

    /// Result of toggle selection action
    pub enum ToggleActionResult {
        /// No command needed (state change only), with optional log message
        StateOnly(Option<String>),
        /// Return a TuiCommand, with optional log message
        Command(TuiCommand, Option<String>),
        /// Do nothing (no state change, no command)
        None,
    }

    /// Handle toggle selection in Select mode
    pub fn handle_toggle_select_mode(
        change: &mut ChangeState,
        new_change_count: &mut usize,
    ) -> ToggleActionResult {
        change.selected = !change.selected;
        // Clear NEW flag when user interacts with the change
        if change.is_new {
            change.is_new = false;
            *new_change_count = new_change_count.saturating_sub(1);
        }
        ToggleActionResult::StateOnly(None)
    }

    /// Handle toggle selection in Running mode
    pub fn handle_toggle_running_mode(
        change: &mut ChangeState,
        new_change_count: &mut usize,
    ) -> ToggleActionResult {
        match change.display_status_cache.as_str() {
            "not queued" => {
                // Emit AddToQueue command; do NOT directly assign display_status_cache here.
                // The shared reducer state will be updated via apply_command in command_handlers,
                // and the TUI will derive the display status from the shared state.
                change.selected = true;
                // Clear NEW flag when user adds to queue
                if change.is_new {
                    change.is_new = false;
                    *new_change_count = new_change_count.saturating_sub(1);
                }
                let id = change.id.clone();
                let log_msg = format!("Added to queue: {}", id);
                ToggleActionResult::Command(TuiCommand::AddToQueue(id), Some(log_msg))
            }
            "queued" => {
                // Emit RemoveFromQueue command; do NOT directly assign display_status_cache here.
                change.selected = false;
                let id = change.id.clone();
                let log_msg = format!("Removed from queue: {}", id);
                ToggleActionResult::Command(TuiCommand::RemoveFromQueue(id), Some(log_msg))
            }
            "merge wait" | "resolve pending" => {
                // Only toggle execution mark (selected), do not modify display_status_cache or DynamicQueue
                change.selected = !change.selected;
                // Clear NEW flag when user interacts with the change
                if change.is_new {
                    change.is_new = false;
                    *new_change_count = new_change_count.saturating_sub(1);
                }
                let id = change.id.clone();
                let log_msg = if change.selected {
                    format!("Marked for execution: {}", id)
                } else {
                    format!("Unmarked: {}", id)
                };
                ToggleActionResult::StateOnly(Some(log_msg))
            }
            "applying" | "accepting" | "archiving" | "resolving" => {
                // Active changes: Space does NOT trigger force-kill.
                // Use K key to enter force-kill confirmation mode instead.
                ToggleActionResult::None
            }
            "error" => {
                // Error rows in Running mode must mirror queue operations:
                // selected=true => AddToQueue, selected=false => RemoveFromQueue.
                change.selected = !change.selected;
                if change.is_new {
                    change.is_new = false;
                    *new_change_count = new_change_count.saturating_sub(1);
                }
                let id = change.id.clone();
                let log_msg = if change.selected {
                    format!("Marked for retry and added to queue: {}", id)
                } else {
                    format!("Retry mark cleared and removed from queue: {}", id)
                };
                if change.selected {
                    ToggleActionResult::Command(TuiCommand::AddToQueue(id), Some(log_msg))
                } else {
                    ToggleActionResult::Command(TuiCommand::RemoveFromQueue(id), Some(log_msg))
                }
            }
            // Completed, Archived, Merged, Blocked - cannot change status
            _ => ToggleActionResult::None,
        }
    }

    /// Handle toggle selection in Stopped mode
    pub fn handle_toggle_stopped_mode(
        change: &mut ChangeState,
        new_change_count: &mut usize,
    ) -> ToggleActionResult {
        // In Stopped mode, only toggle execution mark (selected), not display_status_cache.
        // For wait states (MergeWait/ResolveWait), display_status_cache MUST remain unchanged.
        // For NotQueued, display_status_cache remains NotQueued until resume.
        if !matches!(
            change.display_status_cache.as_str(),
            "not queued" | "merge wait" | "resolve pending" | "error"
        ) {
            // Cannot modify processing/completed states.
            return ToggleActionResult::None;
        }

        // Toggle execution mark only
        change.selected = !change.selected;

        // Clear NEW flag when user interacts with the change
        if change.is_new {
            change.is_new = false;
            *new_change_count = new_change_count.saturating_sub(1);
        }

        let id = change.id.clone();
        let log_msg = if change.selected {
            format!("Marked for execution: {}", id)
        } else {
            format!("Unmarked: {}", id)
        };
        ToggleActionResult::StateOnly(Some(log_msg))
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::events::OrchestratorEvent;

    fn create_test_change(id: &str, completed: u32, total: u32) -> Change {
        Change {
            id: id.to_string(),
            completed_tasks: completed,
            total_tasks: total,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: crate::openspec::ProposalMetadata::default(),
        }
    }

    #[test]
    fn test_change_state_progress() {
        let change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 3,
            total_tasks: 6,
            display_status_cache: "not queued".to_string(),
            display_color_cache: Color::DarkGray,
            error_message_cache: None,
            selected: false,
            is_new: false,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
        };

        assert_eq!(change.progress_percent(), 50.0);
    }

    #[test]
    fn test_app_state_new_all_not_selected() {
        // All changes should start unselected on startup
        let changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-b", 0, 3),
        ];

        let app = AppState::new(changes);

        assert_eq!(app.mode, AppMode::Select);
        assert_eq!(app.changes.len(), 2);
        assert_eq!(app.cursor_index, 0);
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
    }

    #[test]
    fn test_app_state_no_auto_selection() {
        // Changes should NOT be auto-selected on startup
        let changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-b", 0, 3),
        ];

        let app = AppState::new(changes);

        assert_eq!(app.mode, AppMode::Select);
        assert_eq!(app.changes.len(), 2);
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        // Should NOT have log entry for auto-queued changes
        assert!(!app
            .logs
            .iter()
            .any(|log| log.message.contains("Auto-queued")));
    }

    #[test]
    fn test_cursor_navigation() {
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);

        assert_eq!(app.cursor_index, 0);

        app.cursor_down();
        assert_eq!(app.cursor_index, 1);

        app.cursor_down();
        assert_eq!(app.cursor_index, 2);

        app.cursor_down();
        assert_eq!(app.cursor_index, 0); // Wraps around

        app.cursor_up();
        assert_eq!(app.cursor_index, 2); // Wraps around
    }

    #[test]
    fn test_toggle_selection() {
        // Changes start unselected
        let changes = vec![create_test_change("a", 0, 1)];

        let mut app = AppState::new(changes);

        assert!(!app.changes[0].selected);

        app.toggle_selection();
        assert!(app.changes[0].selected);

        app.toggle_selection();
        assert!(!app.changes[0].selected);
    }

    #[test]
    fn test_toggle_all_marks_select_mode() {
        // Test toggle all in Select mode - mark all then unmark all
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);
        assert_eq!(app.mode, AppMode::Select);

        // All start unselected
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);

        // First toggle: should mark all
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);

        // Second toggle: should unmark all
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);
    }

    #[test]
    fn test_toggle_all_marks_stopped_mode() {
        // Test toggle all in Stopped mode
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Stopped;

        // First toggle: should mark all
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);

        // Second toggle: should unmark all
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
    }

    #[test]
    fn test_toggle_all_marks_parallel_mode_excludes_uncommitted() {
        // Test that toggle all respects parallel mode restrictions
        let changes = vec![
            create_test_change("committed", 0, 1),
            create_test_change("uncommitted", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Select;
        app.parallel_mode = true;
        app.parallel_available = true;

        // Mark first as committed, second as uncommitted
        app.changes[0].is_parallel_eligible = true;
        app.changes[1].is_parallel_eligible = false;

        // Toggle all should only mark the committed change
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(!app.changes[1].selected); // Excluded due to parallel mode

        // Toggle all again should unmark
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
    }

    #[test]
    fn test_toggle_all_marks_partial_selection() {
        // Test that if any unmarked change exists, toggle marks all
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);

        // Manually select one change
        app.changes[0].selected = true;

        // Toggle all should mark the rest (because unmarked changes exist)
        app.toggle_all_marks();
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);

        // Toggle all again should unmark all
        app.toggle_all_marks();
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);
    }

    #[test]
    fn test_toggle_all_marks_running_mode_toggles_non_active_rows_only() {
        let changes = vec![
            create_test_change("resolving", 0, 1),
            create_test_change("not-queued", 0, 1),
            create_test_change("merge-wait", 0, 1),
            create_test_change("resolve-wait", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.is_resolving = true;
        app.changes[0].display_status_cache = "resolving".to_string();
        app.changes[1].display_status_cache = "not queued".to_string();
        app.changes[2].display_status_cache = "merge wait".to_string();
        app.changes[3].display_status_cache = "resolve pending".to_string();

        app.toggle_all_marks();
        assert!(!app.changes[0].selected, "active row must stay unchanged");
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);
        assert!(app.changes[3].selected);

        // Wait states must keep display_status_cache unchanged.
        assert_eq!(app.changes[2].display_status_cache, "merge wait");
        assert_eq!(app.changes[3].display_status_cache, "resolve pending");

        // Second toggle unmarks only non-active rows.
        app.toggle_all_marks();
        assert!(!app.changes[0].selected, "active row must stay unchanged");
        assert!(!app.changes[1].selected);
        assert!(!app.changes[2].selected);
        assert!(!app.changes[3].selected);
    }

    #[test]
    fn test_bulk_toggle_running_mode_emits_add_to_queue_commands() {
        // When bulk toggle marks NotQueued rows in Running mode,
        // it must emit AddToQueue commands (same as single-row Space).
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "not queued".to_string();
        app.changes[1].display_status_cache = "not queued".to_string();
        app.changes[2].display_status_cache = "not queued".to_string();

        let commands = app.toggle_all_marks();

        // All three should be marked
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);

        // Must emit AddToQueue for each NotQueued row
        assert_eq!(commands.len(), 3);
        assert!(matches!(&commands[0], TuiCommand::AddToQueue(id) if id == "a"));
        assert!(matches!(&commands[1], TuiCommand::AddToQueue(id) if id == "b"));
        assert!(matches!(&commands[2], TuiCommand::AddToQueue(id) if id == "c"));
    }

    #[test]
    fn test_bulk_toggle_running_mode_emits_remove_from_queue_commands() {
        // When all eligible rows are Queued and marked, bulk toggle must
        // unmark them and emit RemoveFromQueue commands.
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "queued".to_string();
        app.changes[0].selected = true;
        app.changes[1].display_status_cache = "queued".to_string();
        app.changes[1].selected = true;

        let commands = app.toggle_all_marks();

        // Both should be unmarked
        assert!(!app.changes[0].selected);
        assert!(!app.changes[1].selected);

        // Must emit RemoveFromQueue for each Queued row
        assert_eq!(commands.len(), 2);
        assert!(matches!(&commands[0], TuiCommand::RemoveFromQueue(id) if id == "a"));
        assert!(matches!(&commands[1], TuiCommand::RemoveFromQueue(id) if id == "b"));
    }

    #[test]
    fn test_bulk_toggle_running_mode_no_commands_for_wait_states() {
        // MergeWait/ResolveWait rows should only toggle execution mark,
        // NOT emit queue commands.
        let changes = vec![
            create_test_change("not-queued", 0, 1),
            create_test_change("merge-wait", 0, 1),
            create_test_change("resolve-wait", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "not queued".to_string();
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.changes[2].display_status_cache = "resolve pending".to_string();

        let commands = app.toggle_all_marks();

        // All eligible rows should be marked
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(app.changes[2].selected);

        // Wait state display_status_cache must remain unchanged
        assert_eq!(app.changes[1].display_status_cache, "merge wait");
        assert_eq!(app.changes[2].display_status_cache, "resolve pending");

        // Only the NotQueued row should emit AddToQueue
        assert_eq!(commands.len(), 1);
        assert!(matches!(&commands[0], TuiCommand::AddToQueue(id) if id == "not-queued"));
    }

    #[test]
    fn test_bulk_toggle_running_mode_excludes_active_rows_from_commands() {
        // Active rows (Applying, Accepting, etc.) must NOT be toggled
        // and must NOT receive stop requests via bulk toggle.
        let changes = vec![
            create_test_change("applying", 0, 1),
            create_test_change("not-queued", 0, 1),
        ];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "applying".to_string();
        app.changes[1].display_status_cache = "not queued".to_string();

        let commands = app.toggle_all_marks();

        // Active row must NOT be selected
        assert!(!app.changes[0].selected);
        // NotQueued row should be selected
        assert!(app.changes[1].selected);

        // Only one command: AddToQueue for the non-active row
        assert_eq!(commands.len(), 1);
        assert!(matches!(&commands[0], TuiCommand::AddToQueue(id) if id == "not-queued"));
        // No StopChange command should appear
        assert!(!commands
            .iter()
            .any(|c| matches!(c, TuiCommand::DequeueChange(_))));
    }

    #[test]
    fn test_bulk_toggle_running_mode_mixed_queued_and_not_queued() {
        // When there's a mix of Queued and NotQueued, and at least one
        // unmarked row exists, all should be marked and NotQueued rows
        // get AddToQueue. (Queued rows already selected stay as-is.)
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "queued".to_string();
        app.changes[0].selected = true; // already marked
        app.changes[1].display_status_cache = "not queued".to_string();
        app.changes[1].selected = false; // not yet marked

        let commands = app.toggle_all_marks();

        // Both should be marked (a stays marked, b becomes marked)
        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);

        // Only the newly toggled NotQueued row should emit AddToQueue
        assert_eq!(commands.len(), 1);
        assert!(matches!(&commands[0], TuiCommand::AddToQueue(id) if id == "b"));
    }

    #[test]
    fn test_bulk_toggle_select_mode_returns_no_commands() {
        // In Select mode, toggle_all_marks should NOT emit any queue commands.
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Select;

        let commands = app.toggle_all_marks();

        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(
            commands.is_empty(),
            "Select mode must not emit queue commands"
        );
    }

    #[test]
    fn test_bulk_toggle_stopped_mode_returns_no_commands() {
        // In Stopped mode, toggle_all_marks should NOT emit any queue commands.
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Stopped;

        let commands = app.toggle_all_marks();

        assert!(app.changes[0].selected);
        assert!(app.changes[1].selected);
        assert!(
            commands.is_empty(),
            "Stopped mode must not emit queue commands"
        );
    }

    #[test]
    fn test_has_bulk_toggle_targets_running_mode_requires_non_active_rows() {
        let changes = vec![create_test_change("a", 0, 1), create_test_change("b", 0, 1)];

        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "applying".to_string();
        app.changes[1].display_status_cache = "resolving".to_string();
        assert!(!app.has_bulk_toggle_targets());

        app.changes[1].display_status_cache = "resolve pending".to_string();
        assert!(app.has_bulk_toggle_targets());
    }

    #[test]
    fn test_start_processing_blocked_while_resolving() {
        let changes = vec![create_test_change("a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.is_resolving = true;

        let command = app.start_processing();
        assert!(
            matches!(command, Some(TuiCommand::StartProcessing(ids)) if ids == vec!["a".to_string()])
        );
        assert_eq!(app.mode, AppMode::Running);
        assert!(app.warning_message.is_none());
        assert_eq!(app.changes[0].display_status_cache, "queued");
    }

    #[test]
    fn test_resume_processing_blocked_while_resolving() {
        let changes = vec![create_test_change("a", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Stopped;
        app.changes[0].selected = true;
        app.is_resolving = true;

        let command = app.resume_processing();
        assert!(
            matches!(command, Some(TuiCommand::StartProcessing(ids)) if ids == vec!["a".to_string()])
        );
        assert_eq!(app.mode, AppMode::Running);
        assert!(app.warning_message.is_none());
        assert_eq!(app.changes[0].display_status_cache, "queued");
    }

    #[test]
    fn test_retry_error_changes_blocked_while_resolving() {
        let changes = vec![create_test_change("a", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Error;
        app.changes[0].set_error_message_cache("boom".to_string());
        app.is_resolving = true;

        let command = app.retry_error_changes();
        assert!(
            matches!(command, Some(TuiCommand::StartProcessing(ids)) if ids == vec!["a".to_string()])
        );
        assert_eq!(app.mode, AppMode::Running);
        assert!(app.warning_message.is_none());
        assert_eq!(app.changes[0].display_status_cache, "queued");
    }

    #[test]
    fn test_retry_error_changes_returns_error_rows_to_queued_status() {
        let change_a = create_test_change("error-a", 0, 1);
        let change_b = create_test_change("error-b", 0, 1);
        let change_ok = create_test_change("ok", 0, 1);

        let mut app = AppState::new(vec![change_a, change_b, change_ok]);
        app.mode = AppMode::Error;
        app.changes[0].set_error_message_cache("boom-a".to_string());
        app.changes[1].set_error_message_cache("boom-b".to_string());

        let command = app.retry_error_changes();

        assert!(
            matches!(command, Some(TuiCommand::StartProcessing(ids)) if ids == vec!["error-a".to_string(), "error-b".to_string()])
        );
        assert_eq!(app.mode, AppMode::Running);
        assert_eq!(app.changes[0].display_status_cache, "queued");
        assert_eq!(app.changes[1].display_status_cache, "queued");
        assert_eq!(app.changes[2].display_status_cache, "not queued");
    }

    #[test]
    fn test_selected_count() {
        // Changes start unselected
        let changes = vec![
            create_test_change("a", 0, 1),
            create_test_change("b", 0, 1),
            create_test_change("c", 0, 1),
        ];

        let mut app = AppState::new(changes);

        assert_eq!(app.selected_count(), 0);

        app.toggle_selection(); // Select first
        assert_eq!(app.selected_count(), 1);
    }

    #[test]
    fn test_update_change_status_blocks_archived_and_merged_to_queued() {
        let mut archived = ChangeState {
            id: "archived-change".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "archived".to_string(),
            display_color_cache: Color::Blue,
            error_message_cache: None,
            selected: false,
            is_new: false,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
        };
        apply_remote_status(&mut archived, "queued");
        assert_eq!(archived.display_status_cache, "archived");

        let mut merged = ChangeState {
            id: "merged-change".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "merged".to_string(),
            display_color_cache: Color::LightBlue,
            error_message_cache: None,
            selected: false,
            is_new: false,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
        };
        apply_remote_status(&mut merged, "queued");
        assert_eq!(merged.display_status_cache, "merged");
    }

    #[test]
    fn test_running_mode_error_change_toggle_sets_retry_mark() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].set_error_message_cache("boom".to_string());
        app.changes[0].selected = false;

        let command = app.toggle_selection();

        assert!(
            matches!(command, Some(TuiCommand::AddToQueue(ref id)) if id == "test-change"),
            "error retry mark should emit AddToQueue command"
        );
        assert!(
            app.changes[0].selected,
            "Space should set retry mark on error change"
        );
        assert!(app.logs.iter().any(|log| log
            .message
            .contains("Marked for retry and added to queue: test-change")));
    }

    #[test]
    fn test_running_mode_error_change_toggle_queue() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].set_error_message_cache("boom".to_string());
        app.changes[0].selected = false;

        // First space: mark retry and add to queue
        let first_command = app.toggle_selection();
        assert!(
            matches!(first_command, Some(TuiCommand::AddToQueue(ref id)) if id == "test-change")
        );
        assert!(app.changes[0].selected);

        // Simulate queue state reflected by reducer
        app.changes[0].set_display_status_cache("error");

        // Second space: clear retry mark and remove from queue
        let second_command = app.toggle_selection();
        assert!(
            matches!(second_command, Some(TuiCommand::RemoveFromQueue(ref id)) if id == "test-change")
        );
        assert!(!app.changes[0].selected);
        assert!(app.logs.iter().any(|log| log
            .message
            .contains("Retry mark cleared and removed from queue: test-change")));
    }

    #[test]
    fn test_stopped_mode_error_change_toggle_sets_retry_mark() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Stopped;
        app.changes[0].set_error_message_cache("boom".to_string());
        app.changes[0].selected = false;

        let command = app.toggle_selection();

        assert!(
            command.is_none(),
            "stopped retry mark should be local state only"
        );
        assert!(
            app.changes[0].selected,
            "Space should set retry mark in stopped mode"
        );
        assert!(app
            .logs
            .iter()
            .any(|log| log.message.contains("Marked for execution: test-change")));
    }

    // Iteration guard tests

    #[test]
    fn test_iteration_monotonic_update_from_none() {
        let mut change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "applying".to_string(),
            display_color_cache: Color::Cyan,
            error_message_cache: None,
            selected: false,
            is_new: false,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: None,
        };

        // First iteration should be accepted
        change.update_iteration_monotonic(Some(1));
        assert_eq!(change.iteration_number, Some(1));

        // Higher iteration should update
        change.update_iteration_monotonic(Some(2));
        assert_eq!(change.iteration_number, Some(2));
    }

    #[test]
    fn test_iteration_monotonic_prevents_regression() {
        let mut change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "applying".to_string(),
            display_color_cache: Color::Cyan,
            error_message_cache: None,
            selected: false,
            is_new: false,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: Some(3),
        };

        // Lower iteration should be ignored
        change.update_iteration_monotonic(Some(1));
        assert_eq!(change.iteration_number, Some(3));

        // Same iteration should be ignored
        change.update_iteration_monotonic(Some(3));
        assert_eq!(change.iteration_number, Some(3));

        // Higher iteration should update
        change.update_iteration_monotonic(Some(5));
        assert_eq!(change.iteration_number, Some(5));
    }

    #[test]
    fn test_iteration_monotonic_ignores_none() {
        let mut change = ChangeState {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 1,
            display_status_cache: "applying".to_string(),
            display_color_cache: Color::Cyan,
            error_message_cache: None,
            selected: false,
            is_new: false,
            is_parallel_eligible: true,
            has_worktree: false,
            started_at: None,
            elapsed_time: None,
            iteration_number: Some(2),
        };

        // None should be ignored
        change.update_iteration_monotonic(None);
        assert_eq!(change.iteration_number, Some(2));
    }

    #[test]
    fn test_resolve_queue_fifo_order() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
            create_test_change("change-c", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Add changes to resolve queue
        assert!(app.add_to_resolve_queue("change-a"));
        assert!(app.add_to_resolve_queue("change-b"));
        assert!(app.add_to_resolve_queue("change-c"));

        // Pop in FIFO order
        assert_eq!(app.pop_from_resolve_queue(), Some("change-a".to_string()));
        assert_eq!(app.pop_from_resolve_queue(), Some("change-b".to_string()));
        assert_eq!(app.pop_from_resolve_queue(), Some("change-c".to_string()));
        assert_eq!(app.pop_from_resolve_queue(), None);
    }

    #[test]
    fn test_resolve_queue_duplicate_prevention() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        // Add change-a once
        assert!(app.add_to_resolve_queue("change-a"));
        // Try to add change-a again - should be blocked
        assert!(!app.add_to_resolve_queue("change-a"));

        // Queue should only have one entry
        assert_eq!(app.pop_from_resolve_queue(), Some("change-a".to_string()));
        assert_eq!(app.pop_from_resolve_queue(), None);
    }

    #[test]
    fn test_resolve_queue_auto_start_on_completion() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Set change-a to Resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        // Queue change-b for resolve
        app.add_to_resolve_queue("change-b");
        app.changes[1].display_status_cache = "resolve pending".to_string();

        // Simulate resolve completion for change-a
        let cmd = app.handle_resolve_completed("change-a".to_string(), None);

        // Should return command to start change-b
        assert!(matches!(cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-b"));
        // is_resolving should be cleared
        assert!(!app.is_resolving);
        // Queue should be empty
        assert!(!app.has_queued_resolves());
    }

    #[test]
    fn test_resolve_queue_no_auto_start_when_queue_empty() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        // Set change-a to Resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        // Simulate resolve completion with empty queue
        let cmd = app.handle_resolve_completed("change-a".to_string(), None);

        // Should NOT return a command
        assert!(cmd.is_none());
        // is_resolving should be cleared
        assert!(!app.is_resolving);
    }

    #[test]
    fn test_resolve_merge_queues_when_resolving() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Set up: change-a is currently resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        // Set up: change-b is in MergeWait
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.cursor_index = 1;
        app.mode = AppMode::Running;

        // Call resolve_merge on change-b (should queue it)
        let cmd = app.resolve_merge();

        // Should NOT return a command (queued instead)
        assert!(cmd.is_none());
        // change-b should transition to ResolveWait
        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        // change-b should be in the queue
        assert!(app.has_queued_resolves());
    }

    /// Regression test: resolve_merge() in the queued path must sync intent to the shared
    /// reducer so that the display_status is "resolve pending" (not "merge wait").
    #[test]
    fn test_resolve_merge_queues_syncs_reducer() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::sync::Arc;

        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Set up shared orchestrator state with both changes.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string(), "change-b".to_string()],
            0,
        )));

        // Pre-condition: change-b must be in MergeWait in the reducer
        // (simulates workspace detected as Archived).
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-b", WorkspaceObservation::WorkspaceArchived);
        }

        app.set_shared_state(shared.clone());

        // change-a is currently resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        // change-b is in MergeWait
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.cursor_index = 1;
        app.mode = AppMode::Running;

        // Queue change-b for resolve via M key
        let cmd = app.resolve_merge();
        assert!(cmd.is_none());
        assert_eq!(app.changes[1].display_status_cache, "resolve pending");

        // Verify the shared reducer reflects "resolve pending" for change-b
        let display_map = shared.blocking_read().all_display_statuses();
        assert_eq!(
            display_map.get("change-b"),
            Some(&"resolve pending"),
            "reducer must reflect 'resolve pending' after queued resolve_merge()"
        );
    }

    /// Regression test: after queuing a resolve via M key, a ChangesRefreshed event
    /// with the change still in merge_wait_ids must NOT regress ResolveWait back to MergeWait.
    #[test]
    fn test_resolve_wait_survives_changes_refreshed() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Set up shared orchestrator state.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string(), "change-b".to_string()],
            0,
        )));
        // Pre-condition: change-b is in MergeWait in the reducer.
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-b", WorkspaceObservation::WorkspaceArchived);
        }
        app.set_shared_state(shared.clone());

        // change-a is currently resolving
        app.changes[0].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        // change-b is in MergeWait; user presses M to queue resolve
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.cursor_index = 1;
        app.mode = AppMode::Running;

        let cmd = app.resolve_merge();
        assert!(cmd.is_none());
        assert_eq!(app.changes[1].display_status_cache, "resolve pending");

        // Simulate a ChangesRefreshed event where workspace still reports change-b
        // as Archived (which would normally set MergeWait in the reducer).
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::ChangesRefreshed {
                changes: vec![],
                committed_change_ids: HashSet::new(),
                uncommitted_file_change_ids: HashSet::new(),
                worktree_change_ids: HashSet::new(),
                worktree_paths: HashMap::new(),
                worktree_not_ahead_ids: HashSet::new(),
                merge_wait_ids: ["change-b".to_string()].into_iter().collect(),
            });
        }

        // apply_display_statuses_from_reducer should preserve ResolveWait
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[1].display_status_cache, "resolve pending",
            "ResolveWait must survive ChangesRefreshed + apply_display_statuses_from_reducer"
        );
    }

    #[test]
    fn test_resolve_merge_select_transitions_to_running() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.mode = AppMode::Select;
        app.is_resolving = false;

        let cmd = app.resolve_merge();

        assert!(matches!(cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"));
        assert_eq!(app.mode, AppMode::Running);
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
    }

    #[test]
    fn test_resolve_merge_stopped_transitions_to_running() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.mode = AppMode::Stopped;
        app.is_resolving = false;

        let cmd = app.resolve_merge();

        assert!(matches!(cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"));
        assert_eq!(app.mode, AppMode::Running);
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
    }

    #[test]
    fn test_resolve_merge_running_stays_running() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.mode = AppMode::Running;
        app.is_resolving = false;

        let cmd = app.resolve_merge();

        assert!(matches!(cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"));
        assert_eq!(app.mode, AppMode::Running);
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
    }

    /// Regression test: resolve_merge() in the immediate path (is_resolving == false) must
    /// sync intent to the shared reducer so that display_status is "resolve pending".
    #[test]
    fn test_resolve_merge_immediate_syncs_reducer() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        // Set up shared orchestrator state.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));

        // Pre-condition: change-a must be in MergeWait in the reducer
        // (simulates workspace detected as Archived).
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-a", WorkspaceObservation::WorkspaceArchived);
        }

        app.set_shared_state(shared.clone());

        // change-a is in MergeWait, no resolve in progress
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.mode = AppMode::Running;
        app.is_resolving = false;

        // Trigger immediate resolve via M key
        let cmd = app.resolve_merge();
        assert!(
            matches!(&cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"),
            "immediate resolve must return TuiCommand::ResolveMerge"
        );
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");

        // Verify the shared reducer reflects "resolve pending" for change-a
        let display_map = shared.blocking_read().all_display_statuses();
        assert_eq!(
            display_map.get("change-a"),
            Some(&"resolve pending"),
            "reducer must reflect 'resolve pending' after immediate resolve_merge()"
        );
    }

    /// Regression test: after immediate resolve (is_resolving == false), a ChangesRefreshed
    /// event with the change still in merge_wait_ids must NOT regress ResolveWait back to
    /// MergeWait.
    #[test]
    fn test_resolve_wait_survives_changes_refreshed_after_immediate_resolve() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        // Set up shared orchestrator state.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        // Pre-condition: change-a is in MergeWait in the reducer.
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-a", WorkspaceObservation::WorkspaceArchived);
        }
        app.set_shared_state(shared.clone());

        // change-a is in MergeWait, no resolve in progress; user presses M
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.mode = AppMode::Running;
        app.is_resolving = false;

        let cmd = app.resolve_merge();
        assert!(cmd.is_some());
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");

        // Simulate a ChangesRefreshed event where workspace still reports change-a
        // as needing merge (which would normally set MergeWait in the reducer).
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::ChangesRefreshed {
                changes: vec![],
                committed_change_ids: HashSet::new(),
                uncommitted_file_change_ids: HashSet::new(),
                worktree_change_ids: HashSet::new(),
                worktree_paths: HashMap::new(),
                worktree_not_ahead_ids: HashSet::new(),
                merge_wait_ids: ["change-a".to_string()].into_iter().collect(),
            });
        }

        // apply_display_statuses_from_reducer should preserve ResolveWait
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "resolve pending",
            "ResolveWait must survive ChangesRefreshed after immediate resolve"
        );
    }

    #[test]
    fn test_resolve_merge_consecutive_m_key_presses_queue_second_change() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Both changes are merge-wait candidates.
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.mode = AppMode::Running;
        app.is_resolving = false;

        // 1st M press on change-a: should start immediate resolve and set is_resolving.
        app.cursor_index = 0;
        let first_cmd = app.resolve_merge();
        assert!(matches!(first_cmd, Some(TuiCommand::ResolveMerge(id)) if id == "change-a"));
        assert!(
            app.is_resolving,
            "first resolve_merge() must set is_resolving=true immediately"
        );
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");

        // 2nd M press on change-b: must take queue path and not start immediately.
        app.cursor_index = 1;
        let second_cmd = app.resolve_merge();
        assert!(
            second_cmd.is_none(),
            "second resolve_merge() must queue while resolve is in progress"
        );
        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        assert!(
            app.resolve_queue_set.contains("change-b"),
            "second change must be queued for resolve"
        );
    }

    /// Regression: reducer-driven display must not demote a Merged change to MergeWait.
    #[test]
    fn test_apply_merge_wait_status_does_not_demote_merged() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        // Simulate that the change has already reached Merged state.
        app.changes[0].display_status_cache = "merged".to_string();

        // The reducer display map says "merged" → TUI must keep Merged.
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "merged");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "merged",
            "reducer-driven display must not demote a Merged change to MergeWait"
        );
    }

    /// Regression: reducer-driven display must not demote a Blocked change to MergeWait.
    #[test]
    fn test_apply_merge_wait_status_does_not_demote_blocked() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        // The reducer display map says "blocked".
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "blocked");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "blocked",
            "reducer-driven display must not demote a Blocked change to MergeWait"
        );
    }

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

        app.changes[0].display_status_cache = "rejected".to_string();
        app.changes[0].selected = true;

        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "not queued");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "rejected",
            "rejected row must stay immutable during reducer display sync"
        );
        assert!(
            !app.changes[0].selected,
            "rejected row must remain unselected"
        );
    }

    #[test]
    fn test_update_changes_reactivates_rejected_row_when_marker_removed() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes.clone());
        app.changes[0].display_status_cache = "rejected".to_string();
        app.changes[0].selected = true;

        app.update_changes(changes);

        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "active refresh without marker should reactivate rejected row"
        );
        assert!(
            !app.changes[0].selected,
            "reactivated row must remain unselected until explicit user action"
        );
    }

    #[test]
    fn test_update_changes_new_rejected_row_is_not_new_and_not_counted() {
        let mut app = AppState::new(vec![]);

        let rejected = create_test_change("change-rejected", 0, 1);
        app.update_changes_with_rejected_for_test(vec![], vec![rejected]);

        let row = app
            .changes
            .iter()
            .find(|c| c.id == "change-rejected")
            .expect("rejected row should be added");
        assert_eq!(row.display_status_cache, "rejected");
        assert!(
            !row.is_new,
            "newly surfaced rejected row must not carry NEW badge"
        );
        assert_eq!(
            app.new_change_count, 0,
            "rejected rows must not increment NEW counter"
        );
    }

    #[test]
    fn test_toggle_selection_blocks_rejected_row() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].display_status_cache = "rejected".to_string();
        app.mode = AppMode::Select;

        let cmd = app.toggle_selection();

        assert!(cmd.is_none(), "rejected row must not emit toggle commands");
        assert!(
            !app.changes[0].selected,
            "rejected row must remain unselected"
        );
        assert!(
            app.warning_message
                .as_deref()
                .is_some_and(|m| m.contains("read-only")),
            "rejected toggle should explain read-only guard"
        );
    }

    #[test]
    fn test_start_processing_excludes_rejected_rows() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Select;
        app.changes[0].display_status_cache = "rejected".to_string();
        app.changes[0].selected = true;

        let cmd = app.start_processing();

        assert!(cmd.is_none(), "F5 start must ignore rejected rows");
        assert_eq!(app.changes[0].display_status_cache, "rejected");
        assert_eq!(app.mode, AppMode::Select);
    }

    #[test]
    fn test_toggle_all_marks_ignores_rejected_rows() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Select;
        app.changes[0].display_status_cache = "rejected".to_string();
        app.changes[1].display_status_cache = "not queued".to_string();

        let _ = app.toggle_all_marks();

        assert!(
            !app.changes[0].selected,
            "bulk mark (@) must not mark rejected rows"
        );
        assert!(
            app.changes[1].selected,
            "eligible rows should still be marked"
        );
    }

    #[test]
    fn test_apply_display_statuses_rejected_clears_selection() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;

        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "rejected");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(app.changes[0].display_status_cache, "rejected");
        assert!(
            !app.changes[0].selected,
            "rejected terminal row must not keep execution mark"
        );
    }

    /// Regression: reducer-driven display must not affect a Merged change via merge_wait.
    #[test]
    fn test_auto_clear_merge_wait_does_not_affect_merged() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        // The reducer display map says "merged" — TUI keeps Merged.
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "merged");
        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(
            app.changes[0].display_status_cache, "merged",
            "reducer-driven display must not transition a Merged change away from Merged"
        );
    }

    #[test]
    fn test_start_processing_does_not_queue_blocked_changes() {
        // Regression: Blocked+selected changes must NOT be transitioned to Queued by F5
        let changes = vec![
            create_test_change("applying", 0, 1),
            create_test_change("blocked-b", 0, 1),
            create_test_change("blocked-c", 0, 1),
        ];
        let mut app = AppState::new(changes);

        // Simulate: A is Applying, B and C are Blocked+selected (execution marks present)
        app.changes[0].display_status_cache = "applying".to_string();
        app.changes[0].selected = false;
        app.changes[1].display_status_cache = "blocked".to_string();
        app.changes[1].selected = true;
        app.changes[2].display_status_cache = "blocked".to_string();
        app.changes[2].selected = true;

        // Press F5 (start_processing) – should return None (no NotQueued changes)
        let result = app.start_processing();

        assert!(
            result.is_none(),
            "start_processing must return None when only Blocked changes are selected"
        );
        assert_eq!(
            app.changes[1].display_status_cache, "blocked",
            "Blocked change B must remain Blocked after start_processing"
        );
        assert_eq!(
            app.changes[2].display_status_cache, "blocked",
            "Blocked change C must remain Blocked after start_processing"
        );
    }

    // -----------------------------------------------------------------------
    // Phase 6.1: TUI uses reducer display_status (apply_display_statuses_from_reducer)
    // -----------------------------------------------------------------------

    #[test]
    fn test_tui_uses_reducer_display_status() {
        use std::collections::HashMap;

        let changes = vec![
            create_test_change("c1", 0, 3),
            create_test_change("c2", 0, 3),
        ];
        let mut app = AppState::new(changes);

        // Simulate reducer snapshot with various statuses.
        let mut display_map: HashMap<String, &'static str> = HashMap::new();
        display_map.insert("c1".to_string(), "applying");
        display_map.insert("c2".to_string(), "merge wait");

        app.apply_display_statuses_from_reducer(&display_map);

        assert_eq!(app.changes[0].display_status_cache, "applying");
        assert_eq!(app.changes[1].display_status_cache, "merge wait");

        // Verify active classification works correctly.
        assert!(matches!(
            app.changes[0].display_status_cache.as_str(),
            "applying"
        ));
    }

    // -----------------------------------------------------------------------
    // Phase 6.4: TUI and Web display vocabulary consistency
    // -----------------------------------------------------------------------

    #[test]
    fn test_display_status_consistency_between_tui_and_web() {
        use std::collections::HashMap;

        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);

        // Scenarios: dependency blocked, merge wait, resolving.
        let scenarios: &[(&str, &str)] = &[
            ("blocked", "blocked"),
            ("merge wait", "merge wait"),
            ("resolve pending", "resolve pending"),
            ("resolving", "resolving"),
            ("archived", "archived"),
            ("merged", "merged"),
            ("queued", "queued"),
            ("not queued", "not queued"),
        ];

        for (reducer_str, expected_tui_status) in scenarios {
            let mut display_map: HashMap<String, &'static str> = HashMap::new();
            display_map.insert("c1".to_string(), reducer_str);
            app.apply_display_statuses_from_reducer(&display_map);

            assert_eq!(
                app.changes[0].display_status_cache, *expected_tui_status,
                "reducer '{}' should map to {:?}",
                reducer_str, expected_tui_status
            );
        }
    }

    // -----------------------------------------------------------------------
    // Phase 3.3: toggle_selection in Running mode emits commands without
    // mutating display_status_cache locally.
    // -----------------------------------------------------------------------

    #[test]
    fn test_running_mode_toggle_emits_commands_without_local_status_mutation() {
        let changes = vec![
            create_test_change("c1", 0, 3),
            create_test_change("c2", 0, 3),
        ];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;

        // Simulate c1 in NotQueued state.
        app.changes[0].display_status_cache = "not queued".to_string();

        // toggle_selection should return AddToQueue command and NOT mutate display_status_cache.
        let cmd = app.toggle_selection();
        assert!(
            matches!(cmd, Some(TuiCommand::AddToQueue(ref id)) if id == "c1"),
            "expected AddToQueue command, got {:?}",
            cmd
        );
        // display_status_cache must NOT have been locally changed to Queued.
        assert_eq!(
            app.changes[0].display_status_cache, "not queued",
            "display_status_cache must NOT be mutated locally; reducer drives it"
        );

        // Simulate c2 already Queued.
        app.cursor_index = 1;
        app.changes[1].display_status_cache = "queued".to_string();
        let cmd2 = app.toggle_selection();
        assert!(
            matches!(cmd2, Some(TuiCommand::RemoveFromQueue(ref id)) if id == "c2"),
            "expected RemoveFromQueue command, got {:?}",
            cmd2
        );
        // display_status_cache must NOT have been locally changed to NotQueued.
        assert_eq!(
            app.changes[1].display_status_cache, "queued",
            "display_status_cache must NOT be mutated locally; reducer drives it"
        );
    }

    // -----------------------------------------------------------------------
    // Force-kill: Space on active change must NOT trigger stop
    // -----------------------------------------------------------------------

    #[test]
    fn test_running_mode_space_on_active_change_does_not_stop() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "applying".to_string();

        let cmd = app.toggle_selection();
        assert!(
            cmd.is_none(),
            "Space on active change must NOT issue any command, got {:?}",
            cmd
        );
    }

    #[test]
    fn test_running_mode_space_on_accepting_does_not_stop() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "accepting".to_string();

        let cmd = app.toggle_selection();
        assert!(
            cmd.is_none(),
            "Space on accepting change must NOT issue any command, got {:?}",
            cmd
        );
    }

    // -----------------------------------------------------------------------
    // Phase 3.4: MergeWait / ResolveWait Space and M key behaviour
    // -----------------------------------------------------------------------

    #[test]
    fn test_merge_wait_queue_operations() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "merge wait".to_string();

        // Space on MergeWait toggles selection only (no queue change).
        let cmd = app.toggle_selection();
        // Should NOT return AddToQueue/RemoveFromQueue.
        assert!(
            !matches!(
                cmd,
                Some(TuiCommand::AddToQueue(_)) | Some(TuiCommand::RemoveFromQueue(_))
            ),
            "Space on MergeWait must not issue queue commands, got {:?}",
            cmd
        );
        // display_status_cache must still be MergeWait.
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
    }

    #[test]
    fn test_resolve_wait_queue_operations() {
        let changes = vec![create_test_change("c1", 0, 3)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "resolve pending".to_string();

        // Space on ResolveWait toggles selection only (no queue change).
        let cmd = app.toggle_selection();
        assert!(
            !matches!(
                cmd,
                Some(TuiCommand::AddToQueue(_)) | Some(TuiCommand::RemoveFromQueue(_))
            ),
            "Space on ResolveWait must not issue queue commands, got {:?}",
            cmd
        );
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
    }

    // -----------------------------------------------------------------------
    // Fix: parallel TUI queued/blocked state regression
    // -----------------------------------------------------------------------

    /// start_processing must sync queue intent into the shared reducer so that a
    /// subsequent ChangesRefreshed display sync cannot regress the row back to
    /// "not queued" before the orchestrator processes it.
    #[test]
    fn test_start_processing_syncs_reducer_queue_intent() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.changes[0].is_parallel_eligible = true;

        // Attach a real shared reducer.
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        let cmd = app.start_processing();
        assert!(cmd.is_some(), "start_processing should return a command");

        // Reducer must now know about the queue intent.
        let guard = shared.blocking_read();
        assert_eq!(
            guard.display_status("change-a"),
            "queued",
            "reducer queue_intent must be Queued after start_processing"
        );

        // A subsequent ChangesRefreshed-driven display sync must not overwrite Queued.
        drop(guard);
        let mut display_map = std::collections::HashMap::new();
        display_map.insert("change-a".to_string(), "not queued");
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache,
            "not queued",
            "display sync should apply reducer snapshot – but reducer already says queued, so this tests the raw override path"
        );

        // Verify with the reducer's own snapshot (the correct integration path).
        let guard2 = shared.blocking_read();
        let real_map = guard2.all_display_statuses();
        drop(guard2);
        app.changes[0].display_status_cache = "queued".to_string(); // restore as start_processing set
        app.apply_display_statuses_from_reducer(&real_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "reducer snapshot must preserve Queued through ChangesRefreshed display sync"
        );
    }

    /// resume_processing must sync queue intent into the shared reducer.
    #[test]
    fn test_resume_processing_syncs_reducer_queue_intent() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Stopped;
        app.changes[0].selected = true;
        app.changes[0].display_status_cache = "not queued".to_string();

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        let cmd = app.resume_processing();
        assert!(cmd.is_some(), "resume_processing should return a command");

        let guard = shared.blocking_read();
        assert_eq!(
            guard.display_status("change-a"),
            "queued",
            "reducer queue_intent must be Queued after resume_processing"
        );
    }

    /// After start_processing, the reducer snapshot must preserve Queued through an
    /// initial parallel ChangesRefreshed display sync (startup refresh regression).
    #[test]
    fn test_parallel_start_refresh_preserves_queued_rows() {
        use crate::orchestration::state::OrchestratorState;
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.changes[0].is_parallel_eligible = true;
        app.parallel_mode = true;

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // F5 – queues the change and syncs the reducer.
        let cmd = app.start_processing();
        assert!(cmd.is_some());
        assert_eq!(app.changes[0].display_status_cache, "queued");

        // Simulate initial parallel ChangesRefreshed (workspace scan returns nothing special).
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::ChangesRefreshed {
                changes: vec![],
                committed_change_ids: HashSet::new(),
                uncommitted_file_change_ids: HashSet::new(),
                worktree_change_ids: HashSet::new(),
                worktree_paths: HashMap::new(),
                worktree_not_ahead_ids: HashSet::new(),
                merge_wait_ids: HashSet::new(),
            });
        }

        // Display sync from the reducer must keep the row as Queued.
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "initial parallel ChangesRefreshed must not regress a queued row to not-queued"
        );
    }

    /// Regression: after run_orchestrator_parallel resets shared state with with_mode(), it must
    /// re-apply AddToQueue so that the subsequent ChangesRefreshed display sync does not regress
    /// the TUI's Queued rows back to NotQueued.
    #[test]
    fn test_parallel_start_state_reset_preserves_queued_rows() {
        use crate::orchestration::state::{OrchestratorState, ReducerCommand};
        use std::collections::{HashMap, HashSet};
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);
        app.changes[0].selected = true;
        app.changes[0].is_parallel_eligible = true;
        app.parallel_mode = true;

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // F5 – queues the change in TUI and syncs the reducer.
        let cmd = app.start_processing();
        assert!(cmd.is_some());
        assert_eq!(app.changes[0].display_status_cache, "queued");

        // Simulate run_orchestrator_parallel replacing shared state (the regression source).
        // Without the fix this would clear queue_intent back to NotQueued.
        {
            let mut guard = shared.blocking_write();
            *guard = OrchestratorState::with_mode(
                vec!["change-a".to_string()],
                0,
                crate::orchestration::state::ExecutionMode::Parallel,
            );
            // The fix: re-apply AddToQueue after the state reset.
            guard.apply_command(ReducerCommand::AddToQueue("change-a".to_string()));
        }

        // Simulate the initial ChangesRefreshed that fires at parallel startup.
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::ChangesRefreshed {
                changes: vec![],
                committed_change_ids: HashSet::new(),
                uncommitted_file_change_ids: HashSet::new(),
                worktree_change_ids: HashSet::new(),
                worktree_paths: HashMap::new(),
                worktree_not_ahead_ids: HashSet::new(),
                merge_wait_ids: HashSet::new(),
            });
        }

        // Display sync from the reducer must keep the row as Queued.
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "state reset followed by AddToQueue must preserve Queued through ChangesRefreshed"
        );
    }

    /// DependencyBlocked sets Blocked in both TUI and reducer; DependencyResolved restores
    /// Queued display because the reducer still holds queue_intent = Queued.
    #[test]
    fn test_dependency_block_preserves_queued_intent() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // Simulate F5 path (queues change in both TUI and reducer).
        app.changes[0].selected = true;
        app.changes[0].is_parallel_eligible = true;
        app.start_processing();

        // Verify reducer has queued intent.
        assert_eq!(shared.blocking_read().display_status("change-a"), "queued");

        // Dependency block arrives.
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::DependencyBlocked {
                change_id: "change-a".to_string(),
                dependency_ids: vec!["dep".to_string()],
            });
        }
        // Reducer should show "blocked"; queue_intent is still Queued underneath.
        assert_eq!(shared.blocking_read().display_status("change-a"), "blocked");
    }

    /// After DependencyResolved the reducer restores "queued" display because queue_intent
    /// was never cleared during the block.
    #[test]
    fn test_dependency_resolved_restores_queued_display() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        app.changes[0].selected = true;
        app.changes[0].is_parallel_eligible = true;
        app.start_processing();

        // Block then resolve.
        {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::DependencyBlocked {
                change_id: "change-a".to_string(),
                dependency_ids: vec!["dep".to_string()],
            });
            guard.apply_execution_event(&crate::events::ExecutionEvent::DependencyResolved {
                change_id: "change-a".to_string(),
            });
        }

        // After resolution, reducer must report "queued" (not "not queued").
        let display_map = shared.blocking_read().all_display_statuses();
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "queued",
            "dependency resolution must restore queued display, not not-queued"
        );
    }

    /// ParallelStartRejected must also clear the reducer queue intent so subsequent
    /// ChangesRefreshed display syncs don't re-queue the rejected row.
    #[test]
    fn test_parallel_start_rejected_does_not_clear_other_rows() {
        use crate::orchestration::state::OrchestratorState;
        use std::sync::Arc;

        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string(), "change-b".to_string()],
            0,
        )));
        app.set_shared_state(shared.clone());

        // Queue both changes in reducer.
        {
            let mut guard = shared.blocking_write();
            guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
                "change-a".to_string(),
            ));
            guard.apply_command(crate::orchestration::state::ReducerCommand::AddToQueue(
                "change-b".to_string(),
            ));
        }
        app.changes[0].display_status_cache = "queued".to_string();
        app.changes[1].display_status_cache = "queued".to_string();
        app.mode = AppMode::Running;

        // Backend rejects only change-a.
        app.handle_orchestrator_event(OrchestratorEvent::ParallelStartRejected {
            change_ids: vec!["change-a".to_string()],
            reason: "uncommitted".to_string(),
        });

        // change-a must be reset in both TUI and reducer.
        assert_eq!(app.changes[0].display_status_cache, "not queued");
        assert_eq!(
            shared.blocking_read().display_status("change-a"),
            "not queued",
            "reducer must clear queue intent for rejected change-a"
        );

        // change-b must remain Queued in both TUI and reducer.
        assert_eq!(app.changes[1].display_status_cache, "queued");
        assert_eq!(
            shared.blocking_read().display_status("change-b"),
            "queued",
            "reducer must not touch change-b which was not rejected"
        );
    }

    // -----------------------------------------------------------------------
    // Resolving mode transition tests (fix-resolving-mode-transition)
    // -----------------------------------------------------------------------

    #[test]
    fn test_all_completed_transitions_to_select_even_when_resolving() {
        // Scheduler側でResolveWaitを管理するため、TUI側のhandle_all_completedは
        // Resolving changeがある場合でも即座にSelectに遷移する。
        let changes = vec![
            create_test_change("change-a", 3, 3),
            create_test_change("change-b", 2, 4),
        ];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "resolving".to_string();

        app.handle_all_completed();

        assert_eq!(
            app.mode,
            AppMode::Select,
            "Should transition to Select because scheduler manages ResolveWait"
        );
    }

    #[test]
    fn test_resolve_completed_transitions_to_select_when_no_active() {
        // After the last Resolving change completes and no other active changes remain,
        // the mode should transition to Select.
        let changes = vec![
            create_test_change("change-a", 3, 3),
            create_test_change("change-b", 2, 4),
        ];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "merged".to_string(); // already done
        app.changes[1].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        // Simulate resolve completion
        app.handle_resolve_completed("change-b".to_string(), None);

        assert_eq!(
            app.mode,
            AppMode::Select,
            "Should transition to Select when no active changes remain after resolve"
        );
    }

    #[test]
    fn test_resolve_completed_stays_running_when_other_active() {
        // If another change is still active (e.g. Applying), mode stays Running.
        let changes = vec![
            create_test_change("change-a", 1, 3),
            create_test_change("change-b", 2, 4),
        ];
        let mut app = AppState::new(changes);
        app.mode = AppMode::Running;
        app.changes[0].display_status_cache = "applying".to_string(); // still active
        app.changes[1].display_status_cache = "resolving".to_string();
        app.is_resolving = true;

        app.handle_resolve_completed("change-b".to_string(), None);

        assert_eq!(
            app.mode,
            AppMode::Running,
            "Should stay Running when other active changes remain"
        );
    }
}