mahbot 0.10.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
use std::collections::HashSet;
use std::path::Path;

use crate::git::commands::{parse_numstat_lines, run_git_output};
use crate::pipeline::board::{Ticket, TicketComment, TicketLabel, TicketPhase};

use iced::widget::{Column, Row, Space, button, column, container, markdown, row, text, tooltip};
use iced::{Alignment, Element, Length, Task};

use iced_fonts::lucide;

use super::common::MAX_INPUT_CHARS;
use super::dialog;
use super::theme;
use super::widgets::{
    self, PILL_COMPACT, PILL_MODAL, PillMetrics, badge_pill, diff_stats_row, selectable_text,
    tooltip_hint,
};

#[derive(Debug, Clone)]
struct FileStat {
    path: String,
    additions: i64,
    deletions: i64,
}

#[derive(Debug, Clone)]
pub(crate) struct CommitStats {
    files: Vec<FileStat>,
}

#[derive(Debug, Clone)]
#[expect(clippy::large_enum_variant)]
pub(crate) enum BoardMessage {
    Refreshed {
        tickets: Vec<Ticket>,
        generation: u64,
    },
    /// A failed board read. Carries the board generation captured at dispatch,
    /// mirroring [`BoardMessage::Refreshed`], so a stale failure is dropped.
    RefreshError {
        error: String,
        generation: u64,
    },
    /// A ticket change delivered by the CDC change stream (see
    /// [`crate::db::cdc`]). The board applies the delta idempotently by ticket id.
    TicketChanged(Box<crate::db::cdc::ChangeEvent>),
    /// The change stream lagged — force a full board refresh (the delta was
    /// lost, so the snapshot is the only safe way to recover).
    BoardRefreshNeeded,
    TicketUpserted(Ticket),
    TicketDetails(Box<Ticket>),
    DetailError(String),
    /// CDC-driven re-fetch of the open ticket detail (see
    /// [`BoardState::refresh_selected_ticket`]). Carries the comment
    /// generation captured at dispatch so stale callbacks (modal closed
    /// or ticket switched while in flight) are dropped. Unlike
    /// `TicketDetails`, this is non-destructive: an in-progress comment draft survives.
    TicketDetailsRefreshed(u64, Box<Ticket>),
    /// CDC-driven re-fetch of the open ticket detail failed. Carries the
    /// generation for the same stale-callback detection as
    /// `TicketDetailsRefreshed`. Kept separate from `DetailError` so a
    /// stale refresh error cannot clear `selected_loading` mid-open.
    TicketDetailsRefreshError(u64, String),
    PerformAction(String, String), // ticket_id, new_phase
    ActionResult(Result<(), String>),

    /// User clicked the cancel action on a ticket. Checks the freshest
    /// cached ticket state synchronously
    /// ([`BoardState::cancel_confirmation_needed`]): a mid-pipeline
    /// (implementation-phase) ticket opens the confirmation modal
    /// ([`BoardMessage::ConfirmCancel`]); otherwise the cancel executes
    /// directly (non-pipeline phases stay single-click). `PerformAction`
    /// re-checks at execution, so the real pause decision is always authoritative.
    RequestCancel(String),
    ConfirmCancel(String),
    DismissCancel,

    OpenModal(String),

    CloseModal,

    /// Dismiss modals/panels (Escape key).
    Escape,

    LinkClicked(String),

    Toast(super::ToastMessage),

    ArchiveAllCompleted,

    ArchiveAllCompletedResult(Result<u64, String>),

    PauseAllQueued,

    PauseAllQueuedResult(Result<u64, String>),

    ArchiveTicket(String),

    FetchCommitStats(String),
    CommitStatsLoaded(String, u64, Result<CommitStats, String>),

    ViewCommitDiff {
        commit_hash: String,
        workspace_name: String,
    },

    ToggleCommentExpand(usize),

    CommentInputChanged(super::editor_widget::EditorAction),
    SendComment,
    /// Result of adding a comment via the backend. Carries the generation
    /// counter captured at send-time for stale-callback detection.
    CommentSent(u64, Result<(), String>),

    SearchInputChanged(super::editor_widget::EditorAction),
    SearchResults(Vec<Ticket>, u64),
    /// The async FTS query failed. Carries the generation counter so a stale
    /// failure cannot replace the results of a newer search.
    SearchError(String, u64),
    SearchCleared,
}

pub struct BoardState {
    pub(crate) tickets: Vec<Ticket>,
    pub(crate) load_state: super::common::AsyncLoadState,
    selected_ticket: Option<Ticket>,
    selected_loading: bool,
    action_loading: Option<String>,
    description_md: Option<Vec<markdown::Item>>,
    comments_md: Vec<(usize, Vec<markdown::Item>)>,
    /// Bumped on every refresh request by [`Self::refresh`]. A read outcome is
    /// applied only while its generation still matches, so an older in-flight
    /// read cannot overwrite the newest one (see [`Self::applied_read`]).
    board_generation: u64,
    /// Ticket ids a CDC delta archived/removed since the last baseline. A
    /// baseline snapshot read before such a delta must not re-add the ticket,
    /// so `apply_refreshed` skips these ids from the snapshot.
    pub(crate) delta_removed_ids: HashSet<String>,
    /// True on a lag recovery ([`BoardMessage::BoardRefreshNeeded`]) so the
    /// recovery snapshot is authoritative and replaces the board, dropping
    /// tickets a lost removal delta would have removed. Cleared on the first
    /// snapshot; subsequent refreshes merge.
    pub(crate) replace_on_refresh: bool,
    commit_stats: Option<CommitStats>,
    commit_stats_error: Option<String>,
    commit_stats_loading: bool,
    commit_stats_generation: u64,
    /// Ticket awaiting mid-pipeline cancel confirmation. `Some(ticket_id)`
    /// while the cancel-confirmation modal is shown; the cancel only runs
    /// on [`BoardMessage::ConfirmCancel`].
    pending_cancel: Option<String>,
    expanded_comments: HashSet<usize>,
    detail_error: Option<String>,
    detail_refresh_in_flight: bool,

    comment_input: super::editor_widget::EditorBuffer,
    sending_comment: bool,
    /// Whether the comment input is focused (for Escape-key blur behavior).
    ///
    /// Note: tracking is imperfect — clicking elsewhere (natural focus loss)
    /// won't clear this flag, so the first Escape after a natural blur still
    /// acts as "blur" instead of "close". A second Escape always closes the
    /// modal, which is acceptable UX for Iced 0.14's widget focus API limits.
    comment_focused: bool,
    /// Monotonic counter incremented when the modal context changes
    /// (modal close via `reset_modal()`, or ticket switch via
    /// `TicketDetails`). Captured in `SendComment` and verified in
    /// `CommentSent` to detect stale async callbacks.
    comment_generation: u64,
    undo_stack: super::common::UndoStack,

    pub(crate) search_query: super::common::SingleLineEditorState,
    pub(crate) search_results: Vec<Ticket>,
    pub(crate) search_error: Option<String>,
    pub(crate) search_generation: u64,
}

impl BoardState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            tickets: Vec::new(),
            load_state: super::common::AsyncLoadState::new(),
            selected_ticket: None,
            selected_loading: false,
            action_loading: None,
            description_md: None,
            comments_md: Vec::new(),
            board_generation: 0,
            delta_removed_ids: HashSet::new(),
            replace_on_refresh: false,
            commit_stats: None,
            commit_stats_error: None,
            commit_stats_loading: false,
            commit_stats_generation: 0,
            pending_cancel: None,
            expanded_comments: HashSet::new(),
            detail_error: None,
            detail_refresh_in_flight: false,
            comment_input: super::editor_widget::EditorBuffer::with_text(
                "",
                Some(super::highlight::HighlightLanguage::Markdown),
            ),
            sending_comment: false,
            comment_focused: false,
            comment_generation: 0,
            undo_stack: super::common::UndoStack::new(),
            search_query: super::common::SingleLineEditorState::new(""),
            search_results: Vec::new(),
            search_error: None,
            search_generation: 0,
        }
    }

    /// Dismiss an open mid-pipeline cancel confirmation without touching
    /// the ticket. Shared by `Escape` and the modal's own dismiss actions
    /// (`DismissCancel`), so both paths stay in sync.
    fn dismiss_pending_cancel(&mut self) {
        self.pending_cancel = None;
    }

    /// Whether `ticket_id` is in a mid-pipeline (implementation) phase, using
    /// the freshest synchronous state available: the open detail modal's
    /// `selected_ticket` (a fresh DB fetch, refreshed on change/periodic
    /// detail refresh), then the search results (the exact cards the user
    /// sees while a search is active), then the board list (CDC-driven,
    /// paused during search). Decides between the confirmation
    /// modal and a single-click cancel in `RequestCancel`. `PerformAction`
    /// re-checks the phase at execution, so the real
    /// pause decision is always authoritative regardless of staleness here.
    fn cancel_confirmation_needed(&self, ticket_id: &str) -> bool {
        self.selected_ticket
            .as_ref()
            .filter(|t| t.id == ticket_id)
            .or_else(|| self.search_results.iter().find(|t| t.id == ticket_id))
            .or_else(|| self.tickets.iter().find(|t| t.id == ticket_id))
            .is_some_and(|t| t.phase.is_pipeline_occupied())
    }

    fn reset_modal(&mut self) {
        self.dismiss_pending_cancel();
        self.selected_ticket = None;
        self.selected_loading = false;
        self.detail_error = None;
        self.description_md = None;
        self.comments_md.clear();
        self.expanded_comments.clear();
        self.commit_stats = None;
        self.commit_stats_error = None;
        self.commit_stats_loading = false;
        self.commit_stats_generation += 1;
        self.reset_comment_state();
    }

    fn reset_comment_state(&mut self) {
        self.comment_input.clear();
        self.sending_comment = false;
        self.comment_focused = false;
        self.comment_generation += 1;
        self.undo_stack.clear();
    }

    /// Whether a read outcome carrying `generation` is the board's current read
    /// — the shape both [`BoardMessage::Refreshed`] and
    /// [`BoardMessage::RefreshError`] apply through, so a caller can tell an
    /// applied read from one that lost its race.
    pub(crate) fn applied_read(&self, generation: u64) -> bool {
        generation == self.board_generation
    }

    /// Request a full board snapshot — every workspace's non-archived
    /// tickets. Bumps [`Self::board_generation`] so only the newest request's snapshot applies.
    pub fn refresh(&mut self) -> Task<BoardMessage> {
        self.board_generation += 1;
        let generation = self.board_generation;
        Task::perform(
            async move {
                crate::pipeline::board::store()
                    .list_all_tickets(None, None)
                    .await
                    .map_err(|e| e.to_string())
            },
            move |res| match res {
                Ok(tickets) => BoardMessage::Refreshed {
                    tickets,
                    generation,
                },
                Err(error) => BoardMessage::RefreshError { error, generation },
            },
        )
    }

    /// Non-archived queued tickets in the listed board — the bulk pause's
    /// scope. The search never narrows it: the bulk actions cover the list,
    /// not what a query matched.
    fn queued_tickets(&self) -> impl Iterator<Item = &Ticket> {
        self.tickets
            .iter()
            .filter(|t| !t.is_archived && t.phase == TicketPhase::Queued)
    }

    pub(crate) fn has_queued_tickets(&self) -> bool {
        self.queued_tickets().next().is_some()
    }

    /// Whether the board has been read successfully and holds no ticket to show
    /// — the one state in which the Home page omits its ticket column. A board
    /// that has not loaded yet and a failed read are not empty: each renders in
    /// the column instead of hiding it.
    pub(crate) fn has_nothing_to_show(&self) -> bool {
        self.load_state.has_loaded() && self.load_state.error().is_none() && self.tickets.is_empty()
    }

    fn queued_workspaces(&self) -> Vec<String> {
        let mut workspaces: Vec<String> = Vec::new();
        for ticket in self.queued_tickets() {
            if !workspaces.contains(&ticket.workspace_name) {
                workspaces.push(ticket.workspace_name.clone());
            }
        }
        workspaces
    }

    /// Apply a CDC ticket change delta to the board, idempotently by ticket id.
    ///
    /// A DELETE (or an archived row) removes the ticket and records it in `delta_removed_ids`, so a
    /// stale baseline snapshot cannot re-add it. An INSERT/UPDATE re-fetches the ticket by id (with
    /// the board's own parsing, so the delta carries a consistent snapshot) and upserts it, and the
    /// render path re-sorts each frame. There is deliberately no global `change_id` watermark:
    /// `change_id` is a WAL `NewRowid` that restarts after `turso_cdc` is fully pruned, so a
    /// watermark would silently drop deltas. A change to the open detail modal's ticket whose
    /// `updated_at` moved re-refreshes the modal.
    /// Comment inserts bump `tickets.updated_at`, so a tickets delta fires for comment activity;
    /// the board LIST does not load comment content (`LoadComments::No`).
    fn apply_ticket_change(&mut self, event: &crate::db::cdc::ChangeEvent) -> Task<BoardMessage> {
        use crate::db::cdc::ChangeType;
        let Some(id) = event.ticket_id().map(str::to_string) else {
            return Task::none();
        };
        let detail_refresh = if self.selected_ticket.as_ref().is_some_and(|t| t.id == id) {
            let changed = match &event.after {
                Some(after) => {
                    let new_at = after
                        .get("updated_at")
                        .and_then(crate::db::cdc::CdcValue::as_text);
                    new_at != self.selected_ticket.as_ref().map(|t| t.updated_at.as_str())
                }
                None => true,
            };
            if changed {
                self.refresh_selected_ticket()
            } else {
                Task::none()
            }
        } else {
            Task::none()
        };
        let is_removed = match event.change_type {
            ChangeType::Delete => true,
            _ => {
                event
                    .after
                    .as_ref()
                    .and_then(|r| r.get("is_archived"))
                    .and_then(crate::db::cdc::CdcValue::as_integer)
                    == Some(1)
            }
        };
        let upsert = if is_removed {
            self.tickets.retain(|t| t.id != id);
            self.delta_removed_ids.insert(id.clone());
            Task::none()
        } else {
            self.delta_removed_ids.remove(&id);
            // Re-fetch current state: the render path re-sorts each frame, so no
            // manual sort maintenance is needed, and a re-fetch always returns the
            // freshest snapshot (so an out-of-order delta cannot clobber the board).
            Task::perform(
                async move {
                    let board = crate::pipeline::board::store();
                    match board
                        .get_tickets_by_ids(&[id], crate::pipeline::board::LoadComments::No)
                        .await
                        .map_err(|e| e.to_string())
                    {
                        Ok(mut v) => match v.pop() {
                            Some(ticket) => BoardMessage::TicketUpserted(ticket),
                            None => BoardMessage::BoardRefreshNeeded,
                        },
                        Err(_) => BoardMessage::BoardRefreshNeeded,
                    }
                },
                |msg| msg,
            )
        };
        Task::batch([upsert, detail_refresh])
    }

    /// Apply a baseline snapshot.
    ///
    /// - On a lag recovery (`replace_on_refresh`) the snapshot is authoritative and replaces the
    ///   board, so a ticket a lost removal delta would have removed cannot linger. It also clears
    ///   `delta_removed_ids` — the recovery snapshot carries its own removal history.
    /// - Otherwise it merges by per-ticket `updated_at` freshness: a snapshot ticket older than the
    ///   cached one is left alone (so a newer delta already applied is never clobbered), while a
    ///   newer snapshot ticket updates the board (recovering a lost delta). This is correct even if
    ///   two snapshots arrive out of order, and — unlike a global `change_id` watermark — is immune
    ///   to `change_id` restarting after `turso_cdc` is fully pruned.
    /// - Tickets a delta archived/removed (`delta_removed_ids`) are never re-added by a stale
    ///   snapshot. A board ticket **absent** from the snapshot is kept: with no guaranteed
    ///   snapshot/delta ordering an omission is ambiguous (the snapshot may predate the ticket's
    ///   creation/delta). Dropping it risks a permanent loss (a live ticket that never changes
    ///   again), while keeping it is self-healing — a removal delta arrives and removes it, or a lag
    ///   recovery snapshot replaces the board.
    fn apply_refreshed(&mut self, tickets: Vec<Ticket>) {
        if self.replace_on_refresh {
            self.tickets = tickets;
            self.delta_removed_ids.clear();
            self.replace_on_refresh = false;
        } else {
            let mut merged: Vec<Ticket> = Vec::with_capacity(tickets.len());
            for snap in tickets {
                if self.delta_removed_ids.contains(&snap.id) {
                    continue;
                }
                match self.tickets.iter().find(|t| t.id == snap.id) {
                    Some(cur) => merged.push(if Self::is_at_least_as_fresh(cur, &snap) {
                        cur.clone()
                    } else {
                        snap
                    }),
                    None => merged.push(snap),
                }
            }
            for cur in &self.tickets {
                if !merged.iter().any(|t| t.id == cur.id) {
                    merged.push(cur.clone());
                }
            }
            self.tickets = merged;
        }
        self.load_state.clear_error();
        self.load_state.finish_loading();
    }

    /// Whether `cached` is at least as fresh as `snap` by parsed RFC 3339
    /// `updated_at` (each tickets write bumps it, so it is a sound per-ticket
    /// freshness signal). Falls back to lexicographic comparison so a malformed
    /// timestamp cannot panic.
    fn is_at_least_as_fresh(cached: &Ticket, snap: &Ticket) -> bool {
        let a = crate::db::parse_utc_timestamp(&cached.updated_at);
        let b = crate::db::parse_utc_timestamp(&snap.updated_at);
        match (a, b) {
            (Ok(a), Ok(b)) => a >= b,
            _ => cached.updated_at >= snap.updated_at,
        }
    }

    fn apply_ticket_upsert(&mut self, ticket: Ticket) {
        if ticket.is_archived {
            self.tickets.retain(|t| t.id != ticket.id);
            // Track the removal so a stale snapshot read before the archive cannot re-add it.
            self.delta_removed_ids.insert(ticket.id.clone());
            return;
        }
        if let Some(pos) = self.tickets.iter().position(|t| t.id == ticket.id) {
            self.tickets[pos] = ticket;
        } else {
            self.tickets.push(ticket);
        }
    }

    /// Re-fetch the currently open ticket detail (CDC-driven refresh).
    ///
    /// Fired alongside the ticket-list refresh so an open ticket window
    /// always shows the latest phase/comments without close/reopen.
    /// No-ops while the initial modal load is in flight, while a comment
    /// send is in progress (the DB snapshot would predate the optimistic
    /// comment push — `CommentSent` refetches on completion), or while a
    /// previous refresh is still in flight (so an older snapshot cannot
    /// land after a newer one on slow reads).
    ///
    /// Carries the comment generation captured at dispatch; the
    /// [`BoardMessage::TicketDetailsRefreshed`] handler drops stale
    /// callbacks (modal closed or ticket switched while in flight).
    fn refresh_selected_ticket(&mut self) -> Task<BoardMessage> {
        if self.selected_loading || self.sending_comment || self.detail_refresh_in_flight {
            return Task::none();
        }
        let Some(ticket) = &self.selected_ticket else {
            return Task::none();
        };
        self.detail_refresh_in_flight = true;
        let id = ticket.id.clone();
        let generation = self.comment_generation;
        Task::perform(
            async move {
                let board = crate::pipeline::board::store();
                board.get_ticket(&id).await.map_err(|e| e.to_string())
            },
            move |res| match res {
                Ok(Some(ticket)) => {
                    BoardMessage::TicketDetailsRefreshed(generation, Box::new(ticket))
                }
                Ok(None) => {
                    BoardMessage::TicketDetailsRefreshError(generation, "Ticket not found".into())
                }
                Err(e) => BoardMessage::TicketDetailsRefreshError(generation, e),
            },
        )
    }

    fn parse_comments_md(comments: &[TicketComment]) -> Vec<(usize, Vec<markdown::Item>)> {
        comments
            .iter()
            .enumerate()
            .map(|(i, c)| (i, markdown::parse(&c.content).collect()))
            .collect()
    }

    /// Apply fresh ticket detail to the modal display state: clears the stale error, rebuilds the
    /// description/comment markdown caches, replaces the selected ticket, and reconciles commit
    /// stats. A (project, commit) pair that appeared or changed triggers a fresh stats fetch, gated
    /// on the hash being `Some` so a hash can never leave the loading state stuck; an unchanged
    /// pair keeps the loaded stats, because the refresh is event-driven and unconditional fetches
    /// would hammer the git CLI and flash "Loading commit stats" each time; no hash clears stale
    /// stats and any stuck loading flag. Returns the task to run (stats fetch or none). Callers
    /// must have verified the incoming ticket belongs to the open modal (id + generation guards).
    /// The comment input, undo stack and generation counter stay the caller's.
    fn apply_ticket_display(&mut self, ticket: Ticket) -> Task<BoardMessage> {
        self.detail_error = None;
        self.description_md = if ticket.description.is_empty() {
            None
        } else {
            Some(markdown::parse(&ticket.description).collect())
        };
        self.comments_md = Self::parse_comments_md(&ticket.comments);
        // Commit statistics belong to a (project, commit) pair: two projects can
        // share git history, so the hash alone cannot say whether what is
        // loaded still describes the ticket being shown.
        let stats_current = self.selected_ticket.as_ref().is_some_and(|t| {
            t.workspace_name == ticket.workspace_name && t.commit_hash == ticket.commit_hash
        });
        let ticket_id = ticket.id.clone();
        let has_hash = ticket.commit_hash.is_some();
        self.selected_ticket = Some(ticket);

        if !stats_current && has_hash {
            self.commit_stats = None;
            self.commit_stats_error = None;
            self.commit_stats_loading = true;
            self.commit_stats_generation += 1;
            Task::done(BoardMessage::FetchCommitStats(ticket_id))
        } else if !has_hash {
            self.commit_stats = None;
            self.commit_stats_error = None;
            self.commit_stats_loading = false;
            Task::none()
        } else {
            Task::none()
        }
    }

    fn available_actions(phase: TicketPhase) -> Vec<(&'static str, TicketPhase)> {
        match phase {
            TicketPhase::Queued => vec![
                ("⏸ Pause", TicketPhase::Planning),
                ("🛑 Cancel", TicketPhase::Cancelled),
            ],
            TicketPhase::Planning => vec![
                ("✅ Queued", TicketPhase::Queued),
                ("↩ Back to Backlog", TicketPhase::Backlog),
                ("🛑 Cancel", TicketPhase::Cancelled),
            ],
            TicketPhase::Failed | TicketPhase::Backlog | TicketPhase::Analysis => vec![
                ("✅ Queued", TicketPhase::Queued),
                ("🛑 Cancel", TicketPhase::Cancelled),
            ],
            TicketPhase::Done | TicketPhase::Cancelled => {
                vec![]
            }
            _ => vec![("🛑 Cancel", TicketPhase::Cancelled)],
        }
    }

    /// Map an action label to its lucide icon (16px) and tooltip text.
    ///
    /// Keyed off the action label. The keyword chain
    /// (Cancel → Pause → Queued → Backlog) drives both the icon and the
    /// tooltip, so the two can never drift apart. Rework is automatic via a
    /// bounce — there is no manual rework action anymore.
    /// The trailing `circle_check`/"move phase" pair is a defensive
    /// catch-all for labels outside [`Self::available_actions`].
    fn action_icon_and_tooltip<'a>(
        label: &str,
    ) -> (
        iced::widget::Text<'a, iced::Theme, iced::Renderer>,
        &'static str,
    ) {
        if label.contains("Cancel") {
            (lucide::circle_x(), "cancel ticket")
        } else if label.contains("Pause") {
            (lucide::pause(), "move to planning")
        } else if label.contains("Queued") {
            (lucide::play(), "queued")
        } else if label.contains("Backlog") {
            (lucide::rotate_ccw(), "back to backlog")
        } else {
            (lucide::circle_check(), "move phase")
        }
    }

    /// Build a row of icon-only action buttons for the given ticket and actions.
    /// Icons are 16px with 4px spacing. Cancel buttons render by phase: while the
    /// ticket is not pipeline-occupied ([`TicketPhase::is_pipeline_occupied`] —
    /// backlog/analysis/planning/queued/failed) the cancel is the shared compact
    /// gray [`widgets::compact_x_button`]; once the ticket occupies the pipeline
    /// it keeps the red 16px `circle_x` with [`theme::button_text_danger`].
    /// All others use [`theme::button_text`]. When `is_disabled` is true all
    /// buttons dim to [`theme::TEXT_MUTED`] and become non-interactive.
    fn action_icon_row<'a>(
        ticket_id: &str,
        current_phase: TicketPhase,
        actions: &[(&'static str, TicketPhase)],
        is_disabled: bool,
    ) -> Row<'a, BoardMessage> {
        let mut icon_row = Row::new()
            .spacing(theme::SPACE_4)
            .align_y(Alignment::Center);
        for (label, phase) in actions {
            let is_cancel = label.contains("Cancel");
            if is_cancel && !current_phase.is_pipeline_occupied() {
                icon_row = icon_row.push(widgets::compact_x_button(
                    theme::TEXT_SECONDARY,
                    theme::TEXT_12,
                    iced::Padding {
                        top: 7.0,
                        bottom: 7.0,
                        left: 12.0,
                        right: 12.0,
                    },
                    if is_disabled {
                        None
                    } else {
                        Some(BoardMessage::RequestCancel(ticket_id.to_string()))
                    },
                    Some("cancel ticket"),
                ));
                continue;
            }
            let (icon, tooltip_text) = Self::action_icon_and_tooltip(label);
            let icon_color = if is_disabled {
                theme::TEXT_MUTED
            } else if is_cancel {
                theme::STATUS_ERROR
            } else {
                theme::TEXT_PRIMARY
            };
            let style_fn: fn(
                &iced::Theme,
                iced::widget::button::Status,
            ) -> iced::widget::button::Style = if is_cancel {
                theme::button_text_danger
            } else {
                theme::button_text
            };
            icon_row = icon_row.push(widgets::icon_tooltip_button(
                icon.size(widgets::ACTION_ICON_SIZE).color(icon_color),
                tooltip_text,
                if is_disabled {
                    None
                } else if is_cancel {
                    // Cancels go through the eligibility gate first
                    // (`RequestCancel`): mid-pipeline (implementation-phase)
                    // cancels require explicit confirmation; other cancels
                    // execute directly, exactly as before.
                    Some(BoardMessage::RequestCancel(ticket_id.to_string()))
                } else {
                    Some(BoardMessage::PerformAction(
                        ticket_id.to_string(),
                        phase.to_string(),
                    ))
                },
                button::DEFAULT_PADDING,
                style_fn,
                tooltip::Position::Top,
            ));
        }
        icon_row
    }

    fn phase_badge<'a>(phase: TicketPhase, metrics: PillMetrics) -> Element<'a, BoardMessage> {
        let (fg, bg) = theme::ticket_phase_color(phase);
        let pill = badge_pill(phase.display_name(), (fg, bg), metrics);
        tooltip_hint(pill, "Current phase")
    }

    fn priority_badge<'a>(priority: i64, metrics: PillMetrics) -> Element<'a, BoardMessage> {
        let (fg, bg) = theme::ticket_priority_color(priority);
        let pill = badge_pill(format!("P{priority}"), (fg, bg), metrics);
        tooltip_hint(pill, "Priority")
    }

    fn label_badge<'a>(label: TicketLabel, metrics: PillMetrics) -> Element<'a, BoardMessage> {
        let (fg, bg) = theme::ticket_label_color(label);
        badge_pill(label.to_string(), (fg, bg), metrics)
    }

    fn bounce_badge<'a>(
        bounce_count: i64,
        icon_size: f32,
        text_size: f32,
    ) -> Option<Element<'a, BoardMessage>> {
        if bounce_count <= 0 {
            return None;
        }
        let count = usize::try_from(bounce_count).unwrap_or(0);
        let color = if count > crate::pipeline::BOUNCE_BADGE_WARNING_THRESHOLD {
            theme::STATUS_WARNING
        } else {
            theme::TEXT_SECONDARY
        };
        let indicator = row![
            lucide::rotate_ccw::<iced::Theme, iced::Renderer>()
                .size(icon_size)
                .color(color),
            text(format!("{bounce_count}")).size(text_size).color(color),
        ]
        .spacing(theme::SPACE_2)
        .align_y(Alignment::Center);
        let tooltip_text = format!(
            "Verification bounces: {bounce_count} (max {})",
            crate::pipeline::MAX_BOUNCES,
        );
        Some(tooltip_hint(indicator, tooltip_text))
    }

    /// Compute how many of this ticket's prerequisites are still unfulfilled.
    /// A prerequisite is considered fulfilled if its ticket cannot be found in the
    /// loaded set (per manager clarification: missing = archived = fulfilled) or if
    /// its phase passes [`TicketPhase::is_unblocking()`].
    fn unfulfilled_prereq_count(&self, ticket: &Ticket) -> (usize, Vec<String>) {
        if ticket.prerequisites.is_empty() {
            return (0, Vec::new());
        }
        let phase_map: std::collections::HashMap<&str, TicketPhase> = self
            .tickets
            .iter()
            .map(|t| (t.id.as_str(), t.phase))
            .collect();
        let mut unfulfilled_ids = Vec::new();
        for prereq_id in &ticket.prerequisites {
            let is_unfulfilled = match phase_map.get(prereq_id.as_str()) {
                Some(phase) => !phase.is_unblocking(),
                None => false, // missing = archived = fulfilled
            };
            if is_unfulfilled {
                unfulfilled_ids.push(prereq_id.clone());
            }
        }
        let count = unfulfilled_ids.len();
        (count, unfulfilled_ids)
    }

    fn fetch_ticket(id: String) -> Task<BoardMessage> {
        Task::perform(
            async move {
                let board = crate::pipeline::board::store();
                board.get_ticket(&id).await.map_err(|e| e.to_string())
            },
            |res| match res {
                Ok(Some(ticket)) => BoardMessage::TicketDetails(Box::new(ticket)),
                Ok(None) => BoardMessage::DetailError("Ticket not found".into()),
                Err(e) => BoardMessage::DetailError(e),
            },
        )
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, msg: BoardMessage) -> Task<BoardMessage> {
        match msg {
            BoardMessage::Refreshed {
                tickets,
                generation,
            } => {
                // Stale-generation guard: drop a snapshot whose refresh was
                // superseded by a newer one so it cannot clobber the current list.
                if self.applied_read(generation) {
                    self.apply_refreshed(tickets);
                }
                Task::none()
            }
            BoardMessage::RefreshError { error, generation } => {
                // Stale-result guard, mirroring `Refreshed`: a failed read for a
                // refresh the board has since superseded must not paint its
                // failure over the current list.
                if self.applied_read(generation) {
                    self.load_state.fail(error);
                }
                Task::none()
            }
            BoardMessage::TicketChanged(event) => self.apply_ticket_change(&event),
            BoardMessage::BoardRefreshNeeded => {
                // The CDC stream lagged (a delta was lost). Our delta-derived
                // state may be wrong (e.g. a removal delta was dropped, leaving
                // a resurrected ticket), so the recovery snapshot is
                // authoritative: mark a replace so the next Refreshed drops a
                // ticket a lost removal delta would have removed.
                self.replace_on_refresh = true;
                self.refresh()
            }
            BoardMessage::TicketUpserted(ticket) => {
                self.apply_ticket_upsert(ticket);
                Task::none()
            }
            BoardMessage::OpenModal(id) => {
                self.selected_loading = true;
                self.detail_error = None;
                self.comment_generation += 1;
                Self::fetch_ticket(id)
            }
            BoardMessage::CloseModal => {
                self.reset_modal();
                Task::none()
            }
            BoardMessage::Escape => {
                if self.pending_cancel.is_some() {
                    self.dismiss_pending_cancel();
                    Task::none()
                } else if self.comment_focused {
                    // On first Escape, blur the comment input (clear focus flag)
                    // so a second Escape closes the modal.
                    self.comment_focused = false;
                    Task::none()
                } else {
                    self.reset_modal();
                    Task::none()
                }
            }
            BoardMessage::TicketDetails(ticket) => {
                let ticket = *ticket;
                let stats_task = self.apply_ticket_display(ticket);
                self.selected_loading = false;
                self.reset_comment_state();
                stats_task
            }
            BoardMessage::TicketDetailsRefreshed(generation, ticket) => {
                let ticket = *ticket;
                self.detail_refresh_in_flight = false;
                if generation != self.comment_generation {
                    return Task::none();
                }
                if self.sending_comment || self.selected_ticket.is_none() {
                    return Task::none();
                }
                // Display state only — the comment input, undo stack, and
                // generation counter stay untouched so a draft survives.
                self.apply_ticket_display(ticket)
            }
            BoardMessage::TicketDetailsRefreshError(generation, e) => {
                self.detail_refresh_in_flight = false;
                if generation != self.comment_generation {
                    return Task::none();
                }
                // Keep the last known good detail visible; the next
                // refresh retries. Unlike `DetailError`, this
                // never clears `selected_loading`.
                self.detail_error = Some(e);
                Task::none()
            }
            BoardMessage::DetailError(e) => {
                self.detail_error = Some(e);
                self.selected_loading = false;
                Task::none()
            }
            BoardMessage::PerformAction(ticket_id, new_phase) => {
                self.action_loading = Some(ticket_id.clone());
                Task::perform(
                    async move {
                        let board = crate::pipeline::board::store();
                        let phase: TicketPhase = new_phase
                            .parse()
                            .map_err(|_| format!("Invalid phase: {new_phase}"))?;
                        let ticket = board
                            .get_ticket(&ticket_id)
                            .await
                            .map_err(|e| e.to_string())?
                            .ok_or_else(|| format!("Ticket {ticket_id} not found"))?;
                        let source = ticket.phase;
                        // Cancelling a ticket in an implementation phase pauses
                        // the workspace so queued development tickets don't
                        // cascade. This is the phase-based gate
                        // (`is_pipeline_occupied`), independent of whether an
                        // agent is currently in flight. Supersede auto-cancels
                        // and Manager-tool cancels don't go through here;
                        // shutdown and already-paused are handled inside the helper.
                        if phase == TicketPhase::Cancelled && source.is_pipeline_occupied() {
                            crate::pipeline::pause_workspace_on_failure(
                                &ticket,
                                "user cancelled a ticket in the development pipeline",
                            )
                            .await;
                        }
                        // This is the authoritative user-cancel signal: stop any
                        // in-flight ticket agents so their work ends promptly.
                        // The GUI-path `transition_to(Cancelled)` below is the
                        // single source of the terminal state (the agent-side
                        // failure tail no longer drives a user cancel).
                        if phase == TicketPhase::Cancelled {
                            crate::agent::registry::AGENT_REGISTRY.cancel_by_ticket_id(&ticket_id);
                        }
                        board
                            .transition_to(&ticket_id, None, phase, "user")
                            .await
                            .map_err(|e| e.to_string())?;
                        Ok(())
                    },
                    BoardMessage::ActionResult,
                )
            }
            BoardMessage::ActionResult(Ok(())) => {
                self.action_loading = None;
                let refresh = self.refresh();
                let detail_refetch = self
                    .selected_ticket
                    .as_ref()
                    .map(|t| t.id.clone())
                    .map_or(Task::none(), Self::fetch_ticket);
                let toast = Task::done(BoardMessage::Toast(super::ToastMessage::Saved));
                Task::batch([refresh, detail_refetch, toast])
            }
            BoardMessage::ActionResult(Err(e)) => {
                self.action_loading = None;
                Task::done(BoardMessage::Toast(super::ToastMessage::Error(e)))
            }
            BoardMessage::RequestCancel(ticket_id) => {
                // Synchronous eligibility check against the freshest cached
                // state (`cancel_confirmation_needed`): a mid-pipeline ticket
                // requires explicit confirmation; otherwise the cancel stays
                // single-click, exactly as before. There is no async fetch
                // to race with, so no stale-callback machinery is needed —
                // `PerformAction` re-checks the phase at execution.
                if self.cancel_confirmation_needed(&ticket_id) {
                    self.pending_cancel = Some(ticket_id);
                    Task::none()
                } else {
                    Task::done(BoardMessage::PerformAction(
                        ticket_id,
                        TicketPhase::Cancelled.to_string(),
                    ))
                }
            }
            BoardMessage::ConfirmCancel(ticket_id) => {
                self.pending_cancel = None;
                Task::done(BoardMessage::PerformAction(
                    ticket_id,
                    TicketPhase::Cancelled.to_string(),
                ))
            }
            BoardMessage::DismissCancel => {
                self.dismiss_pending_cancel();
                Task::none()
            }
            BoardMessage::ToggleCommentExpand(i) => {
                if !self.expanded_comments.remove(&i) {
                    self.expanded_comments.insert(i);
                }
                Task::none()
            }
            BoardMessage::CommentInputChanged(action) => {
                self.comment_focused = true;
                super::common::apply_editor_action(
                    &mut self.comment_input,
                    &mut self.undo_stack,
                    action,
                );
                Task::none()
            }
            BoardMessage::SendComment => {
                let text = self.comment_input.text();
                let trimmed = match super::common::send_guard(
                    &text,
                    self.sending_comment,
                    super::common::SendRules::Board,
                    |count| {
                        Task::done(BoardMessage::Toast(super::ToastMessage::Warning(format!(
                            "Comment too long: {count} characters (maximum {MAX_INPUT_CHARS}). \
                                 Please shorten your comment."
                        ))))
                    },
                ) {
                    Ok(t) => t.to_string(),
                    Err(task) => return task,
                };

                let Some(ticket_id) = self.selected_ticket.as_ref().map(|t| t.id.clone()) else {
                    return Task::none();
                };

                let role = format!("user:{}", crate::users::ADMIN_USER_NAME);
                let now = crate::db::now();
                let content = trimmed;

                if let Some(ref mut ticket) = self.selected_ticket {
                    ticket.comments.push(crate::pipeline::board::TicketComment {
                        role: role.clone(),
                        content: content.clone(),
                        created_at: now,
                    });
                    self.comments_md = Self::parse_comments_md(&ticket.comments);
                }

                self.sending_comment = true;
                self.comment_input.clear();
                self.undo_stack.clear();
                let generation = self.comment_generation;

                Task::perform(
                    async move {
                        let board = crate::pipeline::board::store();
                        let result = board
                            .add_comment(&ticket_id, &role, &content)
                            .await
                            .map_err(|e| e.to_string());
                        (generation, result)
                    },
                    |(g, result)| BoardMessage::CommentSent(g, result),
                )
            }
            BoardMessage::CommentSent(generation, result) => {
                if generation != self.comment_generation {
                    self.sending_comment = false;
                    return Task::none();
                }
                self.sending_comment = false;
                if let Err(e) = &result {
                    tracing::warn!(error = %e, "Board: failed to add comment");
                }
                let refresh = match self.selected_ticket.as_ref() {
                    Some(ticket) => Self::fetch_ticket(ticket.id.clone()),
                    None => Task::none(),
                };
                let toast = match (&result, self.selected_ticket.as_ref()) {
                    (Ok(()), Some(_)) => Task::done(BoardMessage::Toast(
                        super::ToastMessage::SuccessMsg("Comment added.".into()),
                    )),
                    (Ok(()), None) => Task::none(),
                    (Err(e), _) => Task::done(BoardMessage::Toast(super::ToastMessage::Error(
                        format!("Failed to add comment: {e}"),
                    ))),
                };
                Task::batch([refresh, toast])
            }
            BoardMessage::LinkClicked(_)
            | BoardMessage::Toast(_)
            | BoardMessage::ViewCommitDiff { .. } => {
                // Intercepted by the Dashboard before reaching board_state.update().
                // Arms must remain for match exhaustiveness even though functionally dead.
                Task::none()
            }
            BoardMessage::ArchiveAllCompleted => Task::perform(
                async move {
                    crate::pipeline::board::store()
                        .archive_all_done_and_cancelled()
                        .await
                        .map_err(|e| e.to_string())
                },
                BoardMessage::ArchiveAllCompletedResult,
            ),
            BoardMessage::ArchiveAllCompletedResult(Ok(count)) => {
                let toast = Task::done(BoardMessage::Toast(super::ToastMessage::SuccessMsg(
                    format!(
                        "Archived {count} ticket{} across all workspaces",
                        if count == 1 { "" } else { "s" }
                    ),
                )));
                Task::batch([self.refresh(), toast])
            }
            BoardMessage::ArchiveAllCompletedResult(Err(e))
            | BoardMessage::PauseAllQueuedResult(Err(e)) => {
                Task::done(BoardMessage::Toast(super::ToastMessage::Error(e)))
            }
            BoardMessage::PauseAllQueued => {
                let workspaces = self.queued_workspaces();
                Task::perform(
                    async move {
                        let board = crate::pipeline::board::store();
                        let mut total = 0u64;
                        for ws in &workspaces {
                            match board.drain_queued_to_planning(ws, "user").await {
                                Ok(moved) => total += moved,
                                Err(e) => return Err(e.to_string()),
                            }
                        }
                        Ok(total)
                    },
                    BoardMessage::PauseAllQueuedResult,
                )
            }
            BoardMessage::PauseAllQueuedResult(Ok(count)) => {
                let toast = Task::done(BoardMessage::Toast(super::ToastMessage::SuccessMsg(
                    format!(
                        "Paused {count} ticket{} across all workspaces",
                        if count == 1 { "" } else { "s" }
                    ),
                )));
                Task::batch([self.refresh(), toast])
            }
            BoardMessage::ArchiveTicket(ticket_id) => {
                self.action_loading = Some(ticket_id.clone());
                Task::perform(
                    async move {
                        let board = crate::pipeline::board::store();
                        board
                            .set_archived(&ticket_id)
                            .await
                            .map_err(|e| e.to_string())?;
                        Ok(())
                    },
                    BoardMessage::ActionResult,
                )
            }
            BoardMessage::FetchCommitStats(ticket_id) => {
                let Some(ticket) = &self.selected_ticket else {
                    return Task::none();
                };
                let Some(ref commit_hash) = ticket.commit_hash else {
                    return Task::none();
                };
                let generation = self.commit_stats_generation;
                let ws_name = ticket.workspace_name.clone();
                let hash = commit_hash.clone();
                let id = ticket_id;
                Task::perform(
                    async move {
                        let ws_path = match crate::workspace::get_by_name(&ws_name).await {
                            Ok(Some(ws)) => ws.path,
                            Ok(None) => {
                                return Err(format!("Workspace '{ws_name}' not found"));
                            }
                            Err(e) => {
                                return Err(format!("{e:#}"));
                            }
                        };
                        Self::run_git_numstat(&ws_path, &hash)
                            .await
                            .map_err(|e| e.to_string())
                    },
                    move |res| BoardMessage::CommitStatsLoaded(id.clone(), generation, res),
                )
            }
            BoardMessage::CommitStatsLoaded(id, generation, result) => {
                if self.selected_ticket.as_ref().map(|t| t.id.as_str()) != Some(id.as_str())
                    || generation != self.commit_stats_generation
                {
                    return Task::none();
                }
                self.commit_stats_loading = false;
                match result {
                    Ok(stats) => {
                        self.commit_stats = Some(stats);
                        self.commit_stats_error = None;
                    }
                    Err(e) => {
                        self.commit_stats = None;
                        self.commit_stats_error = Some(e);
                    }
                }
                Task::none()
            }

            BoardMessage::SearchInputChanged(action) => {
                if let Some(task) = super::common::focus_navigation_task(&action) {
                    return task;
                }
                let changes_text = action.changes_text();
                self.search_query.apply_action(action);
                // The shared widget emits every action (cursor moves too);
                // only re-run the search/debounce pipeline on actual text
                // changes (edits and undo/redo).
                if !changes_text {
                    return Task::none();
                }
                let query = self.search_query.text();
                self.search_generation += 1;

                if query.is_empty() {
                    self.search_results.clear();
                    self.search_error = None;
                    return Task::none();
                }

                let generation = self.search_generation;
                Task::perform(
                    async move {
                        // Debounce: wait 300ms before executing the FTS query
                        // so rapid typing doesn't trigger per-keystroke DB hits.
                        //
                        // Effective latency is ~300ms plus the render after
                        // results arrive — the results render as soon as their
                        // message is delivered, so the debounce is the dominant
                        // wait. In-flight tasks from earlier
                        // keystrokes are NOT cancelled — they run to completion
                        // and their results are discarded by the generation
                        // counter guard below. For typical typing speeds this
                        // creates at most a handful of short-lived sleep-only
                        // tasks, which is acceptably cheap.
                        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                        let board = crate::pipeline::board::store();
                        board
                            .search_by_fts(&query, 20)
                            .await
                            .map_err(|e| e.to_string())
                    },
                    move |res| match res {
                        Ok(tickets) => BoardMessage::SearchResults(tickets, generation),
                        Err(e) => BoardMessage::SearchError(e, generation),
                    },
                )
            }
            BoardMessage::SearchResults(tickets, generation) => {
                if generation == self.search_generation {
                    // Apply only if still the latest generation (stale callback guard)
                    self.search_results = tickets;
                    self.search_error = None;
                }
                Task::none()
            }
            BoardMessage::SearchError(e, generation) => {
                if generation == self.search_generation {
                    self.search_results.clear();
                    self.search_error = Some(e);
                }
                Task::none()
            }
            BoardMessage::SearchCleared => {
                self.search_query.clear();
                self.search_results.clear();
                self.search_error = None;
                self.search_generation += 1;
                Task::none()
            }
        }
    }

    async fn run_git_numstat(
        ws_path: &str,
        commit_hash: &str,
    ) -> Result<CommitStats, anyhow::Error> {
        let is_merge = match run_git_output(
            Path::new(ws_path),
            &["rev-list", "--parents", "-n", "1", commit_hash],
        )
        .await
        {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let parts: Vec<&str> = stdout.split_whitespace().collect();
                parts.len() > 2 // hash + parent1 + parent2... = merge
            }
            Err(_) => false, // if rev-list fails, assume non-merge
        };

        let mut args: Vec<&str> = vec!["show", "--numstat", "--format="];
        if is_merge {
            args.push("-m");
        }
        args.push(commit_hash);

        let output = run_git_output(Path::new(ws_path), &args)
            .await
            .map_err(|e| anyhow::anyhow!("git show failed: {e}"))?;

        if !output.status.success() {
            anyhow::bail!(
                "git show failed: {}",
                String::from_utf8_lossy(&output.stderr).trim()
            );
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut files: Vec<FileStat> = Vec::new();

        for entry in parse_numstat_lines(&stdout) {
            let Some(additions) = entry.additions else {
                continue;
            };
            let Some(deletions) = entry.deletions else {
                continue;
            };
            // Skip rename-only (0 additions, 0 deletions)
            if additions == 0 && deletions == 0 {
                continue;
            }

            files.push(FileStat {
                path: entry.path,
                additions,
                deletions,
            });
        }

        Ok(CommitStats { files })
    }

    pub(crate) fn board_sections(tickets: &[Ticket]) -> [Vec<&Ticket>; 4] {
        crate::pipeline::board::BoardStore::board_sections(tickets)
    }

    #[expect(clippy::too_many_lines)]
    pub fn render_ticket_card<'a>(&'a self, ticket: &'a Ticket) -> Element<'a, BoardMessage> {
        let is_action_disabled = self.action_loading.as_deref() == Some(&ticket.id);

        let actions = Self::available_actions(ticket.phase);
        let mut icon_row =
            Self::action_icon_row(&ticket.id, ticket.phase, &actions, is_action_disabled);
        if actions.is_empty() {
            icon_row = icon_row.push(widgets::ghost_icon_button());
        }

        let (unfulfilled_count, unfulfilled_ids) = self.unfulfilled_prereq_count(ticket);

        let mut badge_row = row![
            Self::priority_badge(ticket.priority, PILL_COMPACT),
            Self::label_badge(ticket.label, PILL_COMPACT),
            Self::phase_badge(ticket.phase, PILL_COMPACT),
        ]
        .spacing(theme::SPACE_6);

        if let Some(bounce) =
            Self::bounce_badge(ticket.bounce_count, theme::TEXT_12, theme::TEXT_10)
        {
            badge_row = badge_row.push(bounce);
        }

        if unfulfilled_count > 0 {
            let tooltip_text = format!("Blocked by: {}", unfulfilled_ids.join(", "));
            let pause_icon = lucide::pause::<iced::Theme, iced::Renderer>()
                .size(theme::TEXT_12)
                .color(theme::STATUS_WARNING);
            let count_text = text(format!("{unfulfilled_count}"))
                .size(theme::TEXT_10)
                .color(theme::STATUS_WARNING);
            let indicator = row![pause_icon, count_text]
                .spacing(theme::SPACE_2)
                .align_y(Alignment::Center);
            badge_row = badge_row.push(tooltip_hint(indicator, tooltip_text));
        }

        // Inline commit stats: +added/−removed with color coding,
        // positioned after prereq indicator and before fill spacer.
        // Zero-valued sides are hidden; only the non-zero side displays.
        if let Some(hash) = &ticket.commit_hash {
            let added = ticket.lines_added.unwrap_or(0);
            let removed = ticket.lines_removed.unwrap_or(0);
            let stats_parts = row![
                text("\u{2387} ")
                    .size(theme::TEXT_10)
                    .color(theme::TEXT_SECONDARY),
                diff_stats_row::<BoardMessage>(added, removed, 10.0),
            ]
            .spacing(0)
            .align_y(Alignment::Center);
            let stats_button = widgets::icon_tooltip_button(
                stats_parts,
                "ticket commit diff",
                Some(BoardMessage::ViewCommitDiff {
                    commit_hash: hash.clone(),
                    workspace_name: ticket.workspace_name.clone(),
                }),
                [theme::PAD_2, theme::PAD_6],
                theme::button_text,
                tooltip::Position::Top,
            );
            badge_row = badge_row.push(stats_button);
        }

        badge_row = badge_row.push(Space::new().width(Length::Fill));
        badge_row = badge_row.push(icon_row);

        if matches!(ticket.phase, TicketPhase::Done | TicketPhase::Cancelled) && !ticket.is_archived
        {
            let archive_btn = widgets::icon_tooltip_button(
                lucide::archive::<iced::Theme, iced::Renderer>()
                    .size(widgets::ACTION_ICON_SIZE)
                    .color(theme::TEXT_MUTED),
                "archive ticket",
                if is_action_disabled {
                    None
                } else {
                    Some(BoardMessage::ArchiveTicket(ticket.id.clone()))
                },
                button::DEFAULT_PADDING,
                theme::button_text,
                tooltip::Position::Top,
            );
            badge_row = badge_row.push(archive_btn);
        }

        let mut card_children: Vec<Element<'_, BoardMessage>> = vec![tooltip_hint(
            button(
                column![
                    text(&ticket.title)
                        .size(theme::TEXT_13)
                        .color(theme::TEXT_PRIMARY),
                    text(&ticket.id)
                        .size(theme::TEXT_10)
                        .color(theme::TEXT_SECONDARY),
                ]
                .spacing(theme::SPACE_2),
            )
            .padding(iced::Padding::new(theme::PAD_8).bottom(theme::PAD_2))
            .width(Length::Fill)
            .style(theme::button_text)
            .on_press(BoardMessage::OpenModal(ticket.id.clone())),
            "open ticket details",
        )];

        card_children.push(
            badge_row
                .align_y(Alignment::Center)
                .padding([0.0, theme::PAD_8])
                .into(),
        );

        let card = Column::from_vec(card_children)
            .spacing(0)
            .width(Length::Fill);

        container(card)
            .style(theme::elevated_card_style)
            .width(Length::Fill)
            .into()
    }

    const fn is_modal_open(&self) -> bool {
        self.selected_ticket.is_some() || self.selected_loading || self.detail_error.is_some()
    }

    fn modal_dialog<'a>(
        content: impl Into<Element<'a, BoardMessage>>,
        width: f32,
    ) -> Element<'a, BoardMessage> {
        let dialog = dialog::dialog_shell(content, width, 24.0);

        widgets::modal_backdrop(dialog, BoardMessage::CloseModal, 0.5)
    }

    /// Render the modal overlay for ticket detail.
    ///
    /// Always a two-layer `Stack`: the ticket detail modal (or a
    /// type-stable placeholder) at child 0 and the cancel-confirmation
    /// layer (or a type-stable placeholder) at child 1. Both slots keep a
    /// `Stack` shape whether empty or populated, so the outer widget's
    /// shape never changes when the confirmation is shown or dismissed —
    /// child 0's tag stays stable and the detail subtree's transient
    /// widget state (e.g. scroll position) survives the confirm cycle.
    #[must_use]
    pub fn render_modal_overlay(&self) -> Element<'_, BoardMessage> {
        let detail_layer = if self.is_modal_open() {
            if self.selected_loading {
                Self::modal_dialog(
                    column![
                        text("Loading details\u{2026}")
                            .size(theme::TEXT_16)
                            .color(theme::TEXT_SECONDARY),
                        Space::new().height(12),
                        text("Fetching ticket information\u{2026}")
                            .size(theme::TEXT_13)
                            .color(theme::TEXT_SECONDARY),
                    ]
                    .align_x(Alignment::Center),
                    400.0,
                )
            } else if self.selected_ticket.is_none()
                && let Some(ref err) = self.detail_error
            {
                Self::modal_dialog(
                    column![
                        text("Failed to load ticket")
                            .size(theme::TEXT_16)
                            .color(theme::STATUS_ERROR),
                        Space::new().height(12),
                        text(err).size(theme::TEXT_13).color(theme::TEXT_SECONDARY),
                        Space::new().height(16),
                        button(
                            text("Close")
                                .size(theme::TEXT_13)
                                .color(theme::TEXT_PRIMARY)
                                .align_x(Alignment::Center),
                        )
                        .style(theme::button_secondary)
                        .on_press(BoardMessage::CloseModal),
                    ]
                    .align_x(Alignment::Center),
                    400.0,
                )
            } else {
                Self::modal_dialog(self.modal_detail(), 720.0)
            }
        } else {
            iced::widget::stack([widgets::empty_stack_placeholder()]).into()
        };

        let confirm_layer = if let Some(ref ticket_id) = self.pending_cancel {
            Self::cancel_confirm_dialog(ticket_id)
        } else {
            iced::widget::stack([widgets::empty_stack_placeholder()]).into()
        };

        // Stack sizes from its first child: when the details modal is closed
        // `detail_layer` is a zero-size placeholder, so without explicit Fill
        // sizing the confirm layer collapses to 0x0 and is invisible. Pin the
        // stack to the full content area so the confirm dialog renders from
        // the sidebar-card path too.
        iced::widget::stack([detail_layer, confirm_layer])
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

    /// Build the mid-pipeline cancel confirmation dialog for a ticket.
    ///
    /// Shown when the eligibility check (`RequestCancel` →
    /// [`BoardState::cancel_confirmation_needed`]) reports a mid-pipeline
    /// (implementation-phase) ticket; the listed consequences are real as of
    /// that check. If the ticket leaves the pipeline before the user confirms,
    /// `PerformAction` re-pauses authoritatively at execution, so the pause
    /// decision is always made there; the cancel transition itself is
    /// unconditional (no expected-phase guard).
    fn cancel_confirm_dialog(ticket_id: &str) -> Element<'_, BoardMessage> {
        widgets::modal_backdrop(
            dialog::confirm_dialog(
                dialog::dialog_title(format!("Cancel ticket {ticket_id}?")),
                dialog::dialog_body([
                    "This ticket is in the middle of the development pipeline. Confirming will:",
                    "• cancel the ticket immediately — it is archived \
                     automatically afterwards;\n\
                     • stop any running agent — the current tool may finish, \
                     but no further work happens;\n\
                     • leave uncommitted changes in the working tree — not \
                     committed, not reverted;\n\
                     • pause the workspace pipeline — all in-flight work stops \
                     and no pipeline stage advances until you manually resume it.",
                ]),
                [
                    dialog::DialogAction::secondary("Keep ticket", BoardMessage::DismissCancel),
                    dialog::DialogAction::danger(
                        "Cancel ticket",
                        BoardMessage::ConfirmCancel(ticket_id.to_string()),
                    ),
                ],
            ),
            BoardMessage::DismissCancel,
            0.5,
        )
    }

    fn modal_detail(&self) -> Element<'_, BoardMessage> {
        let Some(ticket) = &self.selected_ticket else {
            return text("No ticket selected.")
                .size(theme::TEXT_13)
                .color(theme::TEXT_MUTED)
                .into();
        };

        let is_action_disabled = self.action_loading.as_deref() == Some(&ticket.id);

        let mut sections: Vec<Element<'_, BoardMessage>> = Vec::new();
        sections.push(Self::render_header_metadata(ticket, is_action_disabled));

        if let Some(el) = Self::render_commit_stats(
            ticket,
            self.commit_stats.as_ref(),
            self.commit_stats_loading,
            self.commit_stats_error.as_deref(),
        ) {
            sections.push(el);
        }

        if let Some(el) = Self::render_description(ticket, self.description_md.as_deref()) {
            sections.push(Space::new().height(8).into());
            sections.push(el);
        }

        if let Some(el) = Self::render_comments(ticket, &self.expanded_comments, &self.comments_md)
        {
            sections.push(Space::new().height(12).into());
            sections.push(
                text("Comments:")
                    .size(theme::TEXT_16)
                    .color(theme::TEXT_SECONDARY)
                    .into(),
            );
            sections.push(el);
        }

        let scrollable_content = widgets::vscroll(
            Column::from_vec(sections)
                .spacing(theme::SPACE_4)
                .width(Length::Fill),
        );

        let input_area = self.render_comment_input();

        column![scrollable_content, input_area,]
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

    /// Relative timestamp label falling back to the absolute format when the
    /// stored timestamp is unparseable ([`theme::format_relative_time`]
    /// yields an empty string then). Callers comparing multiple labels should
    /// pass one shared `now` so the outcome is deterministic within a render.
    fn relative_timestamp(ts: &str, now: chrono::DateTime<chrono::Local>) -> String {
        let relative = theme::format_relative_time(ts, now);
        if relative.is_empty() {
            theme::format_timestamp(ts)
        } else {
            relative
        }
    }

    fn render_header_metadata(
        ticket: &Ticket,
        is_action_disabled: bool,
    ) -> Element<'_, BoardMessage> {
        let actions = Self::available_actions(ticket.phase);
        let icon_row =
            Self::action_icon_row(&ticket.id, ticket.phase, &actions, is_action_disabled);

        let now = chrono::Local::now();
        let created = Self::relative_timestamp(&ticket.created_at, now);
        let updated = Self::relative_timestamp(&ticket.updated_at, now);

        // Hide the updated label only when created renders non-empty and both
        // display strings are identical (same relative bucket).
        let show_updated = created.is_empty() || created != updated;

        let mut meta_els: Vec<Element<'_, BoardMessage>> = vec![
            text(&ticket.id)
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY)
                .into(),
            text(" · ")
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY)
                .into(),
            text(format!("Workspace: {}", ticket.workspace_name))
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY)
                .into(),
            text(" · ")
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY)
                .into(),
            text(format!("Created: {created}"))
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY)
                .into(),
        ];
        if show_updated {
            meta_els.extend([
                text(" · ")
                    .size(theme::TEXT_12)
                    .color(theme::TEXT_SECONDARY)
                    .into(),
                text(format!("Updated: {updated}"))
                    .size(theme::TEXT_12)
                    .color(theme::TEXT_SECONDARY)
                    .into(),
            ]);
        }

        let mut secondary: Vec<String> = Vec::new();
        if !ticket.prerequisites.is_empty() {
            secondary.push(format!(
                "Prerequisites: {}",
                ticket.prerequisites.join(", ")
            ));
        }
        if let Some(ref supersedes) = ticket.supersedes {
            secondary.push(format!("Supersedes: {supersedes}"));
        }
        if let Some(ref superseded_by) = ticket.superseded_by {
            secondary.push(format!("Superseded by: {superseded_by}"));
        }

        let first_row: Element<'_, BoardMessage> =
            Row::from_vec(meta_els).align_y(Alignment::Center).into();

        let metadata_block: Element<'_, BoardMessage> = if secondary.is_empty() {
            first_row
        } else {
            let second_row: Element<'_, BoardMessage> = text(secondary.join(" · "))
                .size(theme::TEXT_12)
                .color(theme::TEXT_SECONDARY)
                .into();
            column![first_row, second_row]
                .spacing(theme::SPACE_2)
                .into()
        };

        column![
            text(&ticket.title)
                .size(theme::TEXT_16)
                .color(theme::TEXT_PRIMARY)
                .font(theme::FONT_BOLD),
            metadata_block,
            {
                let mut badges = vec![
                    Self::priority_badge(ticket.priority, PILL_MODAL),
                    Self::label_badge(ticket.label, PILL_MODAL),
                    Self::phase_badge(ticket.phase, PILL_MODAL),
                ];
                if let Some(bounce) =
                    Self::bounce_badge(ticket.bounce_count, theme::TEXT_14, theme::TEXT_12)
                {
                    badges.push(bounce);
                }
                badges.push(Space::new().width(Length::Fill).into());
                badges.push(icon_row.into());
                // `Fill` on the row, not just the spacer: a `Shrink` row sizes from its
                // children, which leaves the spacer at zero and the actions after the chips.
                Row::from_vec(badges)
                    .width(Length::Fill)
                    .align_y(Alignment::Center)
                    .spacing(theme::SPACE_8)
                    .padding([theme::PAD_4, 0.0])
            },
        ]
        .spacing(theme::SPACE_4)
        .into()
    }

    fn render_commit_stats<'a>(
        ticket: &'a Ticket,
        stats: Option<&'a CommitStats>,
        loading: bool,
        error: Option<&'a str>,
    ) -> Option<Element<'a, BoardMessage>> {
        let hash = ticket.commit_hash.as_ref()?;

        if loading {
            return Some(
                column![Space::new().height(8), widgets::loading_text(),]
                    .spacing(theme::SPACE_4)
                    .into(),
            );
        }

        let Some(stats) = stats else {
            let error = error?;
            return Some(
                column![
                    Space::new().height(8),
                    text(format!("Commit stats unavailable: {error}"))
                        .size(theme::TEXT_12)
                        .color(theme::STATUS_WARNING),
                ]
                .spacing(theme::SPACE_4)
                .into(),
            );
        };

        let total_additions: i64 = stats.files.iter().map(|f| f.additions).sum();
        let total_deletions: i64 = stats.files.iter().map(|f| f.deletions).sum();
        let file_count = stats.files.len();
        let mut summary_parts: Vec<Element<'_, BoardMessage>> = Vec::new();
        summary_parts.push(
            text(format!("{hash:.8}"))
                .size(theme::TEXT_11)
                .color(theme::TEXT_SECONDARY)
                .into(),
        );
        summary_parts.push(Space::new().width(theme::SPACE_6).into());
        summary_parts.push(
            text(format!(
                "{file_count} file{} changed",
                if file_count == 1 { "" } else { "s" }
            ))
            .size(theme::TEXT_11)
            .color(theme::TEXT_SECONDARY)
            .into(),
        );
        summary_parts
            .push(diff_stats_row::<BoardMessage>(total_additions, total_deletions, 11.0).into());
        let summary_header = container(
            row(summary_parts)
                .spacing(theme::SPACE_4)
                .align_y(Alignment::Center),
        )
        .padding([theme::PAD_4, theme::PAD_8])
        .width(Length::Fill);

        let mut file_col = Column::new().spacing(theme::SPACE_2);
        for f in &stats.files {
            file_col = file_col.push(
                row![
                    container(text(&f.path).size(theme::TEXT_11).font(theme::FONT_REGULAR))
                        .width(Length::Fixed(400.0))
                        .clip(true),
                    Space::new().width(Length::Fill),
                    diff_stats_row::<BoardMessage>(f.additions, f.deletions, 11.0),
                ]
                .align_y(Alignment::Center),
            );
        }

        Some(
            column![
                summary_header,
                container(file_col)
                    .padding([theme::PAD_4, theme::PAD_8])
                    .style(theme::surface_card_style),
            ]
            .spacing(theme::SPACE_4)
            .into(),
        )
    }

    fn render_description<'a>(
        ticket: &'a Ticket,
        description_md: Option<&'a [markdown::Item]>,
    ) -> Option<Element<'a, BoardMessage>> {
        if ticket.description.is_empty() {
            return None;
        }

        Some(if let Some(items) = description_md {
            container(widgets::vscroll_sized(
                super::selectable::markdown::view(items, theme::markdown_settings())
                    .map(BoardMessage::LinkClicked),
                Length::Fill,
                Length::Shrink,
            ))
            .width(Length::Fill)
            .padding([theme::PAD_10, theme::PAD_2])
            .style(theme::bubble_style(
                theme::BG_SURFACE,
                Some(theme::TEXT_PRIMARY),
            ))
            .into()
        } else {
            container(
                selectable_text(&ticket.description, theme::TEXT_PRIMARY).size(theme::TEXT_13),
            )
            .width(Length::Fill)
            .padding(theme::PAD_10)
            .style(theme::bubble_style(
                theme::BG_SURFACE,
                Some(theme::TEXT_PRIMARY),
            ))
            .into()
        })
    }

    fn render_comment_input(&self) -> Element<'_, BoardMessage> {
        container(super::widgets::chat_composer(
            &self.comment_input,
            BoardMessage::CommentInputChanged,
            BoardMessage::SendComment,
            "Add a comment… (Enter to send, Shift+Enter for newline)",
            super::widgets::ChatComposerOptions {
                sending: self.sending_comment,
                min_height: 44.0,
                max_height: 132.0,
                controls: Vec::new(),
                // Board keeps its legacy always-active send button look
                // (Home greys it out on empty input).
                grey_on_empty: false,
                send_tooltip: "send comment",
                id: Some(iced::widget::Id::new("board_comment_composer")),
                attachments_on_paste: false,
            },
        ))
        .width(Length::Fill)
        .into()
    }

    fn render_comments<'a>(
        ticket: &'a Ticket,
        expanded: &'a HashSet<usize>,
        comments_md: &'a [(usize, Vec<markdown::Item>)],
    ) -> Option<Element<'a, BoardMessage>> {
        if ticket.comments.is_empty() {
            return None;
        }

        let mut cmt_col = Column::new().spacing(theme::SPACE_12);
        for (i, comment) in ticket.comments.iter().enumerate().rev() {
            // For diagnostics comments, optionally show only the summary
            let is_diag = comment.role == crate::agent::role::DIAGNOSTICS_ROLE;
            let is_expanded = expanded.contains(&i);

            let summary = if is_diag {
                comment
                    .content
                    .rfind("\n---\n")
                    .map(|pos| &comment.content[pos + 5..])
            } else {
                None
            };

            let comment_content: Element<'_, BoardMessage> = if is_diag && !is_expanded {
                selectable_text(
                    summary.unwrap_or(&comment.content).trim(),
                    theme::TEXT_PRIMARY,
                )
                .size(theme::TEXT_13)
                .into()
            } else if let Some((_, items)) = comments_md.iter().find(|(idx, _)| *idx == i) {
                super::selectable::markdown::view(items, theme::markdown_settings())
                    .map(BoardMessage::LinkClicked)
            } else {
                selectable_text(&comment.content, theme::TEXT_PRIMARY)
                    .size(theme::TEXT_13)
                    .into()
            };

            let toggle_button: Option<Element<'_, BoardMessage>> = if is_diag {
                let (icon, label) = if is_expanded {
                    (
                        lucide::chevron_up::<iced::Theme, iced::Renderer>().size(theme::TEXT_12),
                        " Collapse",
                    )
                } else {
                    (
                        lucide::chevron_down::<iced::Theme, iced::Renderer>().size(theme::TEXT_12),
                        " Show full output",
                    )
                };
                Some(
                    button(
                        row![
                            icon.color(theme::TEXT_SECONDARY),
                            text(label)
                                .size(theme::TEXT_11)
                                .color(theme::TEXT_SECONDARY),
                        ]
                        .spacing(theme::SPACE_2)
                        .align_y(Alignment::Center),
                    )
                    .style(theme::button_text)
                    .on_press(BoardMessage::ToggleCommentExpand(i))
                    .into(),
                )
            } else {
                None
            };

            let author_el: Element<'_, BoardMessage> =
                if let Some((icon, color)) = theme::comment_author_icon(&comment.role) {
                    icon.size(theme::TEXT_14).color(color).into()
                } else {
                    // User comments show the bare user name; "system" and
                    // legacy labels render as plain muted text.
                    let label = comment.role.strip_prefix("user:").unwrap_or(&comment.role);
                    text(label)
                        .size(theme::TEXT_11)
                        .color(theme::TEXT_SECONDARY)
                        .into()
                };
            let mut header = row![author_el]
                .align_y(Alignment::Center)
                .spacing(theme::SPACE_6);
            let ts = theme::format_relative_time(&comment.created_at, chrono::Local::now());
            if !ts.is_empty() {
                header = header.push(text(ts).size(theme::TEXT_11).color(theme::TEXT_SECONDARY));
            }

            let mut comment_col = Column::new().spacing(theme::SPACE_4);
            comment_col = comment_col.push(header);
            comment_col = comment_col.push(comment_content);
            if let Some(btn) = toggle_button {
                comment_col = comment_col.push(btn);
            }

            cmt_col = cmt_col.push(
                container(comment_col)
                    .width(Length::Fill)
                    .padding(theme::PAD_10)
                    .style(theme::bubble_style(
                        theme::BG_SURFACE,
                        Some(theme::TEXT_PRIMARY),
                    )),
            );
        }

        Some(cmt_col.into())
    }
}

#[cfg(test)]
mod tests {
    use super::super::editor_widget::{EditorAction, EditorBuffer};
    use super::super::highlight::HighlightLanguage;
    use super::*;
    use crate::util::test::TicketFixture;

    fn make_board_state() -> BoardState {
        let mut state = BoardState::new();
        state.selected_ticket = Some(TicketFixture::new("T-1", TicketPhase::Backlog).build());
        state
    }

    fn make_ticket(id: &str, phase: TicketPhase) -> Ticket {
        TicketFixture::new(id, phase).build()
    }

    fn ticket_in(workspace: &str, id: &str, phase: TicketPhase, archived: bool) -> Ticket {
        TicketFixture::new(id, phase)
            .workspace(workspace)
            .archived(archived)
            .build()
    }

    fn draft(text: &str) -> EditorBuffer {
        EditorBuffer::with_text(text, Some(HighlightLanguage::Markdown))
    }

    fn mv(line: usize, col: usize) -> EditorAction {
        EditorAction::MoveTo { line, col }
    }

    fn sel(line: usize, col: usize) -> EditorAction {
        EditorAction::SelectTo { line, col }
    }

    fn typed(text: &str) -> Vec<EditorAction> {
        text.chars().map(EditorAction::Insert).collect()
    }

    #[derive(Clone, Copy, PartialEq)]
    enum Close {
        None,
        Message,
        Reset,
    }

    struct CursorUndoCase {
        name: &'static str,
        initial: &'static str,
        actions: Vec<EditorAction>,
        expected_text: &'static str,
        selection: bool,
        undoes: bool,
        close: Close,
    }

    #[test]
    fn test_comment_input_cursor_actions_and_undo_edits() {
        let text = "hello world";
        let cases = [
            CursorUndoCase {
                name: "a non-edit cursor move passes through",
                initial: text,
                actions: vec![mv(0, 0)],
                expected_text: text,
                selection: false,
                undoes: false,
                close: Close::None,
            },
            CursorUndoCase {
                name: "SelectTo creates a selection",
                initial: text,
                actions: vec![mv(0, 0), sel(0, 5)],
                expected_text: text,
                selection: true,
                undoes: false,
                close: Close::None,
            },
            CursorUndoCase {
                name: "a plain MoveTo keeps the content",
                initial: text,
                actions: vec![mv(0, 3)],
                expected_text: text,
                selection: false,
                undoes: false,
                close: Close::None,
            },
            CursorUndoCase {
                name: "undo restores content and redo restores the undone state",
                initial: "",
                actions: typed("abc"),
                expected_text: "abc",
                selection: false,
                undoes: true,
                close: Close::None,
            },
            CursorUndoCase {
                name: "redo with no undo history is a no-op",
                initial: "",
                actions: vec![EditorAction::Redo],
                expected_text: "",
                selection: false,
                undoes: false,
                close: Close::None,
            },
            CursorUndoCase {
                name: "undo is a no-op after a modal reset",
                initial: "",
                actions: typed("hel"),
                expected_text: "",
                selection: false,
                undoes: false,
                close: Close::Message,
            },
            CursorUndoCase {
                name: "reset_modal clears the undo history",
                initial: "",
                actions: typed("hel"),
                expected_text: "",
                selection: false,
                undoes: false,
                close: Close::Reset,
            },
        ];

        for case in cases {
            let name = case.name;
            let expected = case.expected_text;
            let mut state = make_board_state();
            state.comment_input = draft(case.initial);
            for action in case.actions {
                let _task = state.update(BoardMessage::CommentInputChanged(action));
                assert!(state.comment_focused, "case {name}: comment_focused is set");
            }
            if case.undoes {
                // An undo with history must restore the content, and redo the undo.
                let before = state.comment_input.text();
                let _task = state.update(BoardMessage::CommentInputChanged(EditorAction::Undo));
                let changed = state.comment_input.text() != before;
                assert!(changed, "case {name}: undo should change the content");
                let _task = state.update(BoardMessage::CommentInputChanged(EditorAction::Redo));
            }
            if case.close == Close::Reset {
                state.reset_modal();
            } else if case.close == Close::Message {
                let _task = state.update(BoardMessage::CloseModal);
            }
            if case.close != Close::None {
                assert_eq!(state.comment_input.text(), "", "case {name}: closed");
                let _task = state.update(BoardMessage::CommentInputChanged(EditorAction::Undo));
            }
            assert_eq!(state.comment_input.text(), expected, "case {name}: content");
            let selected = state.comment_input.cursor().selection.is_some();
            assert_eq!(selected, case.selection, "case {name}: selection");
        }
    }

    struct SendCommentCase {
        name: &'static str,
        send: bool,
        ticket_open: bool,
        draft: &'static str,
        expected_draft: &'static str,
        sending: bool,
        comments: usize,
    }

    /// A comment send needs a ticket, and a stale completion only drops the guard.
    #[test]
    fn test_comment_send_accepts_only_with_a_ticket_and_drops_stale_callbacks() {
        let cases = [
            SendCommentCase {
                name: "a within-limit comment is accepted and clears the input",
                send: true,
                ticket_open: true,
                draft: "hello world",
                expected_draft: "",
                sending: true,
                comments: 1,
            },
            SendCommentCase {
                name: "no selected ticket leaves the draft and sends nothing",
                send: true,
                ticket_open: false,
                draft: "hello",
                expected_draft: "hello",
                sending: false,
                comments: 0,
            },
            SendCommentCase {
                name: "a stale completion only releases the send guard",
                send: false,
                ticket_open: true,
                draft: "hello",
                expected_draft: "hello",
                sending: false,
                comments: 0,
            },
        ];

        for case in cases {
            let name = case.name;
            let mut state = make_board_state();
            if !case.ticket_open {
                state.selected_ticket = None;
            }
            state.comment_input = draft(case.draft);
            if case.send {
                let _task = state.update(BoardMessage::SendComment);
            } else {
                state.sending_comment = true;
                state.comment_generation = 42;
                let _task = state.update(BoardMessage::CommentSent(0, Ok(())));
            }
            assert_eq!(
                state.comment_input.text(),
                case.expected_draft,
                "case {name}: comment input"
            );
            assert_eq!(
                state.sending_comment, case.sending,
                "case {name}: sending_comment"
            );
            let optimistic = state
                .selected_ticket
                .as_ref()
                .map_or(0, |t| t.comments.len());
            assert_eq!(optimistic, case.comments, "case {name}: optimistic comment");
        }
    }

    #[test]
    fn a_new_modal_context_bumps_the_comment_generation_and_clears_the_draft() {
        let cases = [
            ("opening the modal", false),
            ("switching to another ticket", true),
        ];
        for (name, switch_ticket) in cases {
            let mut state = make_board_state();
            state.comment_input = draft("draft comment");
            let before = state.comment_generation;
            let _task = if switch_ticket {
                state.sending_comment = true;
                state.comment_focused = true;
                let ticket = TicketFixture::new("T-2", TicketPhase::Backlog);
                state.update(BoardMessage::TicketDetails(Box::new(
                    ticket.title("New").build(),
                )))
            } else {
                state.update(BoardMessage::OpenModal("T-2".into()))
            };
            assert!(state.comment_generation > before, "case {name}: bumped");
            if switch_ticket {
                assert!(
                    state.comment_input.text().is_empty(),
                    "case {name}: cleared"
                );
                assert!(!state.sending_comment, "case {name}: send reset");
                assert!(!state.comment_focused, "case {name}: focus reset");
            }
        }
    }

    fn refreshed_ticket(phase: TicketPhase) -> Ticket {
        TicketFixture::new("T-1", phase)
            .comment("engineer", "fixed the flaky test", "2026-01-01T00:00:05Z")
            .build()
    }
    struct TicketDetailsRefreshCase {
        name: &'static str,
        generation: u64,
        sending: bool,
        callback_generation: u64,
        phase: TicketPhase,
        comments: usize,
        applied: bool,
    }

    #[test]
    fn ticket_details_refresh_applies_only_when_fresh_and_idle() {
        let (backlog, verification) = (TicketPhase::Backlog, TicketPhase::Verification);
        let cases = [
            TicketDetailsRefreshCase {
                name: "a same-ticket refresh updates the detail and keeps the draft",
                generation: 0,
                sending: false,
                callback_generation: 0,
                phase: verification,
                comments: 1,
                applied: true,
            },
            TicketDetailsRefreshCase {
                name: "a stale-generation callback is dropped",
                generation: 42,
                sending: false,
                callback_generation: 0,
                phase: backlog,
                comments: 0,
                applied: false,
            },
            TicketDetailsRefreshCase {
                name: "a refresh never clobbers an optimistic comment send",
                generation: 7,
                sending: true,
                callback_generation: 7,
                phase: backlog,
                comments: 0,
                applied: false,
            },
        ];

        for case in cases {
            let name = case.name;
            let mut state = make_board_state(); // selected_ticket: T-1, Backlog
            state.comment_input = draft("draft comment");
            state.comment_generation = case.generation;
            state.sending_comment = case.sending;
            let gen_before = state.comment_generation;

            let _task = state.update(BoardMessage::TicketDetailsRefreshed(
                case.callback_generation,
                Box::new(refreshed_ticket(verification)),
            ));

            let ticket = state.selected_ticket.as_ref().expect("modal still open");
            assert_eq!(ticket.phase, case.phase, "case {name}: phase");
            assert_eq!(
                ticket.comments.len(),
                case.comments,
                "case {name}: comments"
            );
            assert!(
                !state.detail_refresh_in_flight,
                "case {name}: the completed fetch must clear the in-flight flag"
            );
            if case.applied {
                assert_eq!(
                    state.comment_input.text(),
                    "draft comment",
                    "case {name}: an in-progress comment draft must survive the refresh"
                );
                assert_eq!(
                    state.comment_generation, gen_before,
                    "case {name}: the refresh must not bump the generation (would invalidate in-flight callbacks)"
                );
                assert!(!state.sending_comment, "case {name}: no send in flight");
                assert!(
                    !state.commit_stats_loading,
                    "case {name}: no stats fetch is started"
                );
            }
        }
    }

    #[test]
    fn test_ticket_details_refreshed_stats_reconciliation() {
        const HASH: &str = "abcdef0123456789abcdef0123456789abcdef01";
        let hashed = || {
            let mut ticket = make_ticket("T-1", TicketPhase::Done);
            ticket.commit_hash = Some(HASH.into());
            ticket
        };

        let mut state = make_board_state();
        let (g, stats_gen) = (state.comment_generation, state.commit_stats_generation);
        let _task = state.update(BoardMessage::TicketDetailsRefreshed(g, Box::new(hashed())));
        assert!(state.commit_stats_loading, "new hash should fetch stats");
        assert!(
            state.commit_stats_generation > stats_gen,
            "stats generation bumps"
        );

        let mut state = make_board_state();
        state.selected_ticket.as_mut().unwrap().commit_hash = Some(HASH.into());
        state.commit_stats = Some(CommitStats { files: Vec::new() });
        state.commit_stats_generation = 5;
        let g = state.comment_generation;
        let _task = state.update(BoardMessage::TicketDetailsRefreshed(g, Box::new(hashed())));
        assert_eq!(state.commit_stats_generation, 5, "no refetch");
        assert!(state.commit_stats.is_some(), "the loaded stats are kept");

        let mut state = make_board_state();
        state.selected_ticket.as_mut().unwrap().commit_hash = Some(HASH.into());
        state.commit_stats = Some(CommitStats { files: Vec::new() });
        state.commit_stats_error = Some("Workspace 'first' not found".into());
        let mut elsewhere = hashed();
        elsewhere.workspace_name = "other_ws".into();
        let g = state.comment_generation;
        let _task = state.update(BoardMessage::TicketDetailsRefreshed(g, Box::new(elsewhere)));
        assert!(state.commit_stats_loading, "another project refetches");
        assert!(state.commit_stats.is_none());
        assert!(
            state.commit_stats_error.is_none(),
            "the first failure is gone"
        );

        // Hash vanished (latent) → loading must not stay stuck.
        let mut state = make_board_state();
        state.selected_ticket.as_mut().unwrap().commit_hash = Some(HASH.into());
        state.commit_stats_loading = true;
        let bare = make_ticket("T-1", TicketPhase::Done);
        let g = state.comment_generation;
        let _task = state.update(BoardMessage::TicketDetailsRefreshed(g, Box::new(bare)));
        assert!(
            !state.commit_stats_loading,
            "a hash-less ticket clears loading"
        );
    }

    #[test]
    fn test_ticket_details_refresh_error_is_non_destructive() {
        let mut state = make_board_state();
        let g = state.comment_generation;

        // A refresh error keeps the last known good detail visible and must not
        // clear the modal loading state (that is `DetailError`'s job, for the initial modal load).
        let _task = state.update(BoardMessage::TicketDetailsRefreshError(
            g,
            "db hiccup".into(),
        ));
        let shown = state.selected_ticket.as_ref().unwrap();
        assert_eq!(shown.phase, TicketPhase::Backlog, "the detail survives");
        assert_eq!(state.detail_error.as_deref(), Some("db hiccup"));
        assert!(!state.detail_refresh_in_flight);

        state.comment_generation += 1; // simulate modal close/switch
        let _task = state.update(BoardMessage::TicketDetailsRefreshError(0, "late".into()));
        assert_eq!(
            state.detail_error.as_deref(),
            Some("db hiccup"),
            "stale error"
        );
    }

    #[test]
    fn test_refresh_selected_ticket_dispatch_gating() {
        let mut state = BoardState::new();
        let _task = state.refresh_selected_ticket();
        assert!(!state.detail_refresh_in_flight);

        let mut state = make_board_state();
        let _task = state.refresh_selected_ticket();
        assert!(state.detail_refresh_in_flight);

        let _task = state.refresh_selected_ticket();
        assert!(state.detail_refresh_in_flight);

        let g = state.comment_generation;
        let ticket = make_ticket("T-1", TicketPhase::Backlog);
        let _task = state.update(BoardMessage::TicketDetailsRefreshed(g, Box::new(ticket)));
        assert!(!state.detail_refresh_in_flight);

        let mut state = make_board_state();
        state.selected_loading = true;
        let _task = state.refresh_selected_ticket();
        assert!(!state.detail_refresh_in_flight);

        let mut state = make_board_state();
        state.sending_comment = true;
        let _task = state.refresh_selected_ticket();
        assert!(!state.detail_refresh_in_flight);
    }

    #[test]
    fn test_escape_first_blurs_then_closes() {
        let mut state = make_board_state();
        state.comment_focused = true;

        // First Escape: focused → blur (clear flag), modal stays open.
        let _task = state.update(BoardMessage::Escape);
        assert!(!state.comment_focused, "the first Escape blurs the input");
        assert!(state.selected_ticket.is_some(), "the modal stays open");

        // Second Escape: not focused → close modal.
        let _task = state.update(BoardMessage::Escape);
        assert!(
            state.selected_ticket.is_none(),
            "the second Escape closes it"
        );
    }

    fn page(id: &str, phase: TicketPhase) -> Vec<Ticket> {
        vec![make_ticket(id, phase)]
    }

    #[test]
    fn snapshots_follow_their_generation_and_lag_recovery_replaces() {
        let cases = [
            (
                "a stale-generation snapshot is dropped",
                (2, false, false, vec![]),
                Some((1, page("T-1", TicketPhase::Backlog))),
                (&[][..], false, None),
            ),
            (
                "a current-generation snapshot applies and finishes loading",
                (2, true, false, vec![]),
                Some((2, page("T-1", TicketPhase::Backlog))),
                (&["T-1"][..], false, Some(true)),
            ),
            (
                "a lag-recovery snapshot drops a lost ticket",
                (0, false, true, page("T-old", TicketPhase::Backlog)),
                Some((0, page("T-new", TicketPhase::Analysis))),
                (&["T-new"][..], false, None),
            ),
            (
                // A ticket a delta updated, later removed by a delta the lagged
                // broadcast dropped: the recovery snapshot must be able to drop it.
                "a lag recovery marks the next snapshot as authoritative",
                (0, false, false, page("T-1", TicketPhase::Done)),
                None,
                (&["T-1"][..], true, None),
            ),
        ];

        for (name, setup, snapshot, expected) in cases {
            let (generation_before, loading, replace, tickets) = setup;
            let mut state = BoardState::new();
            state.board_generation = generation_before;
            if loading {
                state.load_state.start_loading();
            }
            state.replace_on_refresh = replace;
            state.tickets = tickets;
            let _task = match snapshot {
                Some((generation, tickets)) => state.update(BoardMessage::Refreshed {
                    tickets,
                    generation,
                }),
                None => state.update(BoardMessage::BoardRefreshNeeded),
            };
            let (ids, replaces, loaded) = expected;
            let actual: Vec<&str> = state.tickets.iter().map(|t| t.id.as_str()).collect();
            assert_eq!(actual, ids, "case {name}: board tickets");
            assert_eq!(
                state.replace_on_refresh, replaces,
                "case {name}: replace flag"
            );
            if let Some(loaded) = loaded {
                assert_eq!(
                    state.load_state.has_loaded(),
                    loaded,
                    "case {name}: load state"
                );
            }
        }
    }

    #[test]
    fn refreshed_merge_keeps_newer_updated_at_and_does_not_readd_removed() {
        const OLD: &str = "2026-08-27T04:00:00.000000+00:00";
        const NEW: &str = "2026-08-27T04:00:01.000000+00:00";
        let refresh = |state: &mut BoardState, tickets: Vec<Ticket>| {
            let _task = state.update(BoardMessage::Refreshed {
                tickets,
                generation: 0,
            });
        };
        let mut state = BoardState::new();
        let mut ticket = make_ticket("T-1", TicketPhase::Backlog);
        ticket.updated_at = OLD.into();
        state.tickets = vec![ticket];

        let mut newer = make_ticket("T-1", TicketPhase::Analysis);
        newer.updated_at = NEW.into();
        refresh(&mut state, vec![newer]);
        assert_eq!(state.tickets[0].phase, TicketPhase::Analysis);
        assert_eq!(state.tickets[0].updated_at, NEW);

        state.delta_removed_ids.insert("T-2".into());
        let mut removed = make_ticket("T-2", TicketPhase::Done);
        removed.updated_at = OLD.into();
        refresh(&mut state, vec![removed]);
        assert!(
            state.tickets.iter().all(|t| t.id != "T-2"),
            "an archived ticket must not be re-added from a stale snapshot"
        );

        let mut created = make_ticket("T-3", TicketPhase::Backlog);
        created.updated_at = OLD.into();
        state.tickets = vec![created];
        refresh(&mut state, vec![]);
        assert_eq!(state.tickets.len(), 1, "an omission preserves the ticket");
        assert_eq!(state.tickets[0].id, "T-3");
    }

    #[test]
    fn ticket_change_tracks_removal_for_snapshot_merge() {
        let mut state = BoardState::new();
        let mut ticket = make_ticket("T-1", TicketPhase::Done);
        ticket.workspace_name = "other_ws".into();
        state.tickets = vec![ticket];
        let event = crate::db::cdc::ChangeEvent {
            table: "tickets".into(),
            change_id: 5,
            change_time: 1_750_000_000,
            change_type: crate::db::cdc::ChangeType::Delete,
            pk: crate::db::cdc::Pk::Text("T-1".into()),
            before: None,
            after: None,
        };
        let _task = state.apply_ticket_change(&event);
        assert!(
            state.tickets.is_empty(),
            "a DELETE (or archived row) is removed from the board list"
        );
        assert!(
            state.delta_removed_ids.contains("T-1"),
            "a removed ticket is tracked so a stale snapshot cannot re-add it"
        );
    }

    #[test]
    fn ticket_upsert_accepts_other_workspaces_and_dedupes_by_id() {
        let mut state = BoardState::new();
        let mut other = make_ticket("T-a", TicketPhase::Backlog);
        other.workspace_name = "other_ws".into();
        state.apply_ticket_upsert(other);
        assert_eq!(
            state.tickets.len(),
            1,
            "a ticket of any workspace is accepted"
        );

        let ticket = make_ticket("T-1", TicketPhase::InDevelopment);
        state.apply_ticket_upsert(ticket.clone());
        assert_eq!(state.tickets.len(), 2);
        // Idempotent upsert by id — no duplicate.
        state.apply_ticket_upsert(ticket);
        assert_eq!(state.tickets.len(), 2);

        let mut archived = make_ticket("T-1", TicketPhase::Done);
        archived.is_archived = true;
        state.apply_ticket_upsert(archived);
        assert_eq!(state.tickets.len(), 1);
        assert!(state.tickets.iter().all(|t| t.id != "T-1"));
    }

    #[derive(Clone, Copy, PartialEq)]
    enum Follow {
        None,
        Dismiss,
        Confirm,
        Escape,
    }

    struct CancelConfirmCase {
        name: &'static str,
        ticket_id: &'static str,
        detail_phase: Option<TicketPhase>,
        listed_phase: Option<TicketPhase>,
        search_phase: Option<TicketPhase>,
        follow_up: Follow,
        opens_confirm: bool,
        stays_pending: bool,
    }

    const CANCEL_CONFIRM_CASES: &[CancelConfirmCase] = &[
        CancelConfirmCase {
            name: "a pipeline-occupied cancel opens the confirmation modal",
            ticket_id: "T-1",
            detail_phase: None,
            listed_phase: Some(TicketPhase::InDevelopment),
            search_phase: None,
            follow_up: Follow::None,
            opens_confirm: true,
            stays_pending: true,
        },
        CancelConfirmCase {
            name: "dismissal leaves the ticket untouched",
            ticket_id: "T-1",
            detail_phase: None,
            listed_phase: Some(TicketPhase::InDevelopment),
            search_phase: None,
            follow_up: Follow::Dismiss,
            opens_confirm: true,
            stays_pending: false,
        },
        CancelConfirmCase {
            name: "a non-pipeline cancel stays single-click",
            ticket_id: "T-1",
            detail_phase: None,
            listed_phase: Some(TicketPhase::Backlog),
            search_phase: None,
            follow_up: Follow::None,
            opens_confirm: false,
            stays_pending: false,
        },
        CancelConfirmCase {
            name: "confirming closes the modal",
            ticket_id: "T-1",
            detail_phase: None,
            listed_phase: Some(TicketPhase::InDevelopment),
            search_phase: None,
            follow_up: Follow::Confirm,
            opens_confirm: true,
            stays_pending: false,
        },
        CancelConfirmCase {
            name: "Escape dismisses the confirm modal before anything else",
            ticket_id: "T-1",
            detail_phase: Some(TicketPhase::InDevelopment),
            listed_phase: None,
            search_phase: None,
            follow_up: Follow::Escape,
            opens_confirm: true,
            stays_pending: false,
        },
        CancelConfirmCase {
            name: "the fresher open detail wins over a stale list",
            ticket_id: "T-1",
            detail_phase: Some(TicketPhase::Backlog),
            listed_phase: Some(TicketPhase::InDevelopment),
            search_phase: None,
            follow_up: Follow::None,
            opens_confirm: false,
            stays_pending: false,
        },
        CancelConfirmCase {
            name: "a pipeline-occupied detail opens the confirmation modal",
            ticket_id: "T-1",
            detail_phase: Some(TicketPhase::Verification),
            listed_phase: Some(TicketPhase::Backlog),
            search_phase: None,
            follow_up: Follow::None,
            opens_confirm: true,
            stays_pending: true,
        },
        CancelConfirmCase {
            name: "search results are consulted while a search is active",
            ticket_id: "T-1",
            detail_phase: None,
            listed_phase: Some(TicketPhase::Backlog),
            search_phase: Some(TicketPhase::Verification),
            follow_up: Follow::None,
            opens_confirm: true,
            stays_pending: true,
        },
        CancelConfirmCase {
            name: "an unknown ticket stays single-click",
            ticket_id: "T-unknown",
            detail_phase: Some(TicketPhase::Backlog),
            listed_phase: None,
            search_phase: None,
            follow_up: Follow::None,
            opens_confirm: false,
            stays_pending: false,
        },
    ];

    /// Only a pipeline-occupied ticket asks before cancelling.
    #[test]
    fn cancel_confirmation_opens_only_for_a_pipeline_occupied_ticket() {
        for case in CANCEL_CONFIRM_CASES {
            let name = case.name;
            let mut state = BoardState::new();
            state.selected_ticket = case.detail_phase.map(|phase| make_ticket("T-1", phase));
            state.tickets = case
                .listed_phase
                .map(|phase| vec![make_ticket("T-1", phase)])
                .unwrap_or_default();
            state.search_results = case
                .search_phase
                .map(|phase| vec![make_ticket("T-1", phase)])
                .unwrap_or_default();
            if case.follow_up == Follow::Escape {
                state.comment_focused = true;
            }

            let _task = state.update(BoardMessage::RequestCancel(case.ticket_id.into()));
            let asked = state.pending_cancel.as_deref();
            assert_eq!(
                asked,
                case.opens_confirm.then_some("T-1"),
                "case {name}: asked"
            );
            let _task = match case.follow_up {
                Follow::None => Task::none(),
                Follow::Dismiss => state.update(BoardMessage::DismissCancel),
                Follow::Confirm => state.update(BoardMessage::ConfirmCancel("T-1".into())),
                Follow::Escape => state.update(BoardMessage::Escape),
            };
            let pending_now = state.pending_cancel.as_deref();
            assert_eq!(
                pending_now,
                case.stays_pending.then_some("T-1"),
                "case {name}: pending"
            );
            if case.follow_up == Follow::Escape {
                assert!(state.comment_focused, "case {name}: Escape must not blur");
                assert!(state.selected_ticket.is_some(), "case {name}: modal stays");
            }
        }
    }

    struct SearchInputCase {
        name: &'static str,
        query: &'static str,
        had_results: bool,
        error: Option<&'static str>,
        generation: u64,
        pasted: Option<&'static str>,
        expected_generation: Option<u64>,
        drops_error: bool,
    }

    #[test]
    fn search_input_updates_query_and_generation() {
        let cases = [
            SearchInputCase {
                name: "an empty input clears the results",
                query: "",
                had_results: true,
                error: Some("stale"),
                generation: 5,
                pasted: Some(""),
                expected_generation: Some(6),
                drops_error: true,
            },
            SearchInputCase {
                name: "a non-empty input stores the query and bumps the generation",
                query: "",
                had_results: false,
                error: None,
                generation: 3,
                pasted: Some("network"),
                expected_generation: None,
                drops_error: false,
            },
            SearchInputCase {
                name: "clearing the search resets the query and results",
                query: "something",
                had_results: true,
                error: None,
                generation: 7,
                pasted: None,
                expected_generation: Some(8),
                drops_error: false,
            },
        ];

        for case in cases {
            let name = case.name;
            let mut state = make_board_state();
            state.search_query = super::super::common::SingleLineEditorState::new(case.query);
            if case.had_results {
                state.search_results = page("T-1", TicketPhase::Backlog);
            }
            state.search_generation = case.generation;
            state.search_error = case.error.map(str::to_string);

            match case.pasted {
                Some(query) => {
                    let action = EditorAction::Paste(query.to_string());
                    let _task = state.update(BoardMessage::SearchInputChanged(action));
                }
                None => {
                    let _task = state.update(BoardMessage::SearchCleared);
                }
            }

            let expected_query = case.pasted.unwrap_or("");
            assert_eq!(
                state.search_query.text(),
                expected_query,
                "case {name}: query"
            );
            assert!(
                state.search_results.is_empty(),
                "case {name}: results empty"
            );
            assert!(
                state.search_generation > case.generation,
                "case {name}: bumped"
            );
            if let Some(expected) = case.expected_generation {
                assert_eq!(state.search_generation, expected, "case {name}: generation");
            }
            assert_eq!(
                state.search_error.is_some(),
                case.error.is_some() && !case.drops_error,
                "case {name}: the previous failure is dropped"
            );
        }
    }

    #[test]
    fn search_results_and_errors_follow_the_generation() {
        let bl = TicketPhase::Backlog;
        let cases = [
            (
                "a stale result callback is discarded",
                (99, false, None),
                (Ok((page("T-stale", bl), 50)), &[][..], None),
            ),
            (
                "a current result replaces the window and clears the failure",
                (42, false, Some("previous")),
                (Ok((page("T-fresh", bl), 42)), &["T-fresh"][..], None),
            ),
            (
                "a current failure clears the stale results",
                (7, true, None),
                (
                    Err(("fts unavailable", 7)),
                    &[][..],
                    Some("fts unavailable"),
                ),
            ),
            (
                "a stale failure is discarded",
                (9, false, None),
                (Err(("old failure", 3)), &[][..], None),
            ),
        ];

        for (name, before, callback) in cases {
            let (generation, results, error) = before;
            let (outcome, ids, wanted) = callback;
            let mut state = make_board_state();
            state.search_generation = generation;
            if results {
                state.search_results = page("T-stale", bl);
            }
            state.search_error = error.map(str::to_string);

            let _task = match outcome {
                Ok((tickets, generation)) => {
                    state.update(BoardMessage::SearchResults(tickets, generation))
                }
                Err((error, generation)) => {
                    state.update(BoardMessage::SearchError(error.to_string(), generation))
                }
            };

            let actual: Vec<&str> = state
                .search_results
                .iter()
                .map(|ticket| ticket.id.as_str())
                .collect();
            assert_eq!(actual, ids, "case {name}: results");
            assert_eq!(state.search_error.as_deref(), wanted, "case {name}: error");
        }
    }

    #[test]
    fn refresh_error_is_visible_until_a_successful_refresh() {
        let mut state = make_board_state();

        let _ = state.update(BoardMessage::RefreshError {
            error: "db down".to_string(),
            generation: state.board_generation,
        });
        assert_eq!(state.load_state.error(), Some("db down"));
        assert!(!state.load_state.has_loaded());

        // A failure carrying a stale generation must not overwrite the current list's load state.
        let stale_generation = state.board_generation.wrapping_sub(1);
        let _ = state.update(BoardMessage::RefreshError {
            error: "stale".to_string(),
            generation: stale_generation,
        });
        assert_eq!(state.load_state.error(), Some("db down"));

        let _ = state.update(BoardMessage::Refreshed {
            tickets: Vec::new(),
            generation: state.board_generation,
        });
        assert!(state.load_state.error().is_none());
        assert!(state.load_state.has_loaded());
    }

    fn test_ticket(
        id: &str,
        phase: TicketPhase,
        created_at: &str,
        done_at: Option<&str>,
    ) -> Ticket {
        TicketFixture::new(id, phase)
            .created_at(created_at)
            .done_at(done_at)
            .build()
    }

    #[test]
    fn test_partition_completed_sorts_done_then_cancelled() {
        let tickets = vec![
            test_ticket("c3", TicketPhase::Cancelled, "2026-01-01T00:00:00Z", None),
            test_ticket(
                "d2",
                TicketPhase::Done,
                "2026-01-01T00:00:00Z",
                Some("2026-06-02T00:00:00Z"),
            ),
            test_ticket(
                "d1",
                TicketPhase::Done,
                "2026-01-01T00:00:00Z",
                Some("2026-06-03T00:00:00Z"),
            ),
            test_ticket("d3", TicketPhase::Done, "2026-01-02T00:00:00Z", None),
            test_ticket("c1", TicketPhase::Cancelled, "2026-01-03T00:00:00Z", None),
            test_ticket("c2", TicketPhase::Cancelled, "2026-01-02T00:00:00Z", None),
        ];
        let [_, _, _, completed] = BoardState::board_sections(&tickets);
        let ids: Vec<&str> = completed.iter().map(|t| t.id.as_str()).collect();
        // Done first (newest done_at, created_at fallback), then cancelled
        // (newest created_at). A cancelled ticket's stale done_at must not
        // promote it into the done block.
        assert_eq!(ids, ["d1", "d2", "d3", "c1", "c2", "c3"]);
    }

    #[test]
    fn has_queued_tickets_reads_the_listed_board() {
        let cases = [
            (
                "true when a queued ticket is listed",
                vec![
                    ticket_in("ws1", "t1", TicketPhase::Queued, false),
                    ticket_in("ws1", "t2", TicketPhase::Backlog, false),
                ],
                false,
                true,
            ),
            (
                "false without a queued ticket",
                vec![
                    ticket_in("ws1", "t1", TicketPhase::Backlog, false),
                    ticket_in("ws1", "t2", TicketPhase::Planning, false),
                ],
                false,
                false,
            ),
            (
                "archived queued tickets do not count",
                vec![ticket_in("ws1", "t1", TicketPhase::Queued, true)],
                false,
                false,
            ),
            (
                "an active search only gates what the sidebar renders",
                vec![ticket_in("ws1", "t1", TicketPhase::Queued, false)],
                true,
                true,
            ),
        ];

        for (name, tickets, searching, expected) in cases {
            let mut state = make_board_state();
            state.tickets = tickets;
            if searching {
                state.search_query = super::super::common::SingleLineEditorState::new("foo");
                state.search_results = vec![ticket_in("ws1", "t2", TicketPhase::Backlog, false)];
            }
            assert_eq!(state.has_queued_tickets(), expected, "case {name}");
        }
    }

    #[test]
    fn the_ticket_column_is_hidden_only_by_a_loaded_empty_board() {
        let mut state = BoardState::new();
        assert!(!state.has_nothing_to_show());

        state.load_state.start_loading();
        assert!(!state.has_nothing_to_show());

        state.load_state.finish_loading();
        assert!(state.has_nothing_to_show(), "a read, empty board hides it");

        // A failed read never hides the column: the failure renders in it.
        state.load_state.fail("db hiccup".to_string());
        assert!(!state.has_nothing_to_show());

        state.load_state.clear_error();
        state.tickets = vec![ticket_in("ws1", "t1", TicketPhase::Backlog, false)];
        assert!(!state.has_nothing_to_show());
    }

    #[test]
    fn queued_workspaces_come_from_the_listed_board() {
        let cases = [
            (
                "derived from the listed queued tickets",
                vec![ticket_in("ws1", "t1", TicketPhase::Queued, false)],
                false,
                vec!["ws1"],
            ),
            (
                "derived and deduped across workspaces",
                vec![
                    ticket_in("ws1", "t1", TicketPhase::Queued, false),
                    ticket_in("ws1", "t2", TicketPhase::Queued, false),
                    ticket_in("ws2", "t3", TicketPhase::Queued, false),
                    ticket_in("ws3", "t4", TicketPhase::Planning, false),
                ],
                false,
                vec!["ws1", "ws2"],
            ),
            (
                "an active search never contributes its workspaces",
                vec![ticket_in("hidden", "t1", TicketPhase::Queued, false)],
                true,
                vec!["hidden"],
            ),
        ];

        for (name, tickets, searching, expected) in cases {
            let mut state = make_board_state();
            state.tickets = tickets;
            if searching {
                // The bulk pause covers the listed board: the workspace set
                // comes from `state.tickets`, never the search results.
                state.search_query = super::super::common::SingleLineEditorState::new("foo");
                state.search_results = vec![
                    ticket_in("ws1", "t2", TicketPhase::Queued, false),
                    ticket_in("ws2", "t3", TicketPhase::Queued, false),
                ];
            }
            let workspaces: Vec<String> = state.queued_workspaces();
            assert_eq!(workspaces, expected, "case {name}");
        }
    }
}