mahbot 0.7.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
//! Native Iced dashboard — application entry point, navigation, and shared state.
//!
//! Iced owns the process Tokio runtime (`iced` feature `tokio`). MahBot
//! bootstraps via a startup [`iced::Task`] before the UI becomes interactive.

#![expect(
    clippy::struct_excessive_bools,
    clippy::if_not_else,
    clippy::collapsible_if
)]

pub(crate) mod alarms;
pub(crate) mod board;
pub(crate) mod common;
pub(crate) mod custom_tools;
pub(crate) mod dialog;
pub(crate) mod diff;
pub(crate) mod diff_widget;
pub(crate) mod editor;
pub(crate) mod editor_widget;
pub(crate) mod git;
pub(crate) mod highlight;
pub(crate) mod home;
pub(crate) mod logs;
pub(crate) mod markdown_breaks;
pub(crate) mod media_markers;
pub(crate) mod menus;
pub(crate) mod running;
pub(crate) mod session_view;
pub(crate) mod sessions;
pub(crate) mod settings;
pub(crate) mod shell;
pub(crate) mod spinner;
pub(crate) mod text_rendering;
pub(crate) mod theme;
pub(crate) mod tool_failures;
pub(crate) mod users;
pub(crate) mod widgets;
pub(crate) mod workspaces;

pub(crate) use self::spinner::spinner;

use crate::logs::LogStore;
use crate::pipeline::board::Ticket;

use iced::keyboard;
use iced::widget::{
    Column, Row, Space, button, column, container, image, pick_list, row, rule, text, tooltip,
};
use iced::window;
use iced::{Alignment, Element, Length, Task};

use crate::Role;
use crate::Workspace;
#[cfg(target_os = "macos")]
use crate::audio::voice::VoiceStatus;

use self::menus::ContextMenu;

use iced_fonts::lucide;

pub use theme::JETBRAINS_MONO;

use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tokio::sync::broadcast;

use futures_util::StreamExt;

/// Coalescing window for runtime-change re-renders. Bounds re-render frequency
/// for per-message / per-tool-call broadcasts while keeping the Running Agents
/// cards and footer responsive.
const RUNTIME_REFRESH_COALESCE: Duration = Duration::from_millis(250);

/// How long an exit requested before boot finished waits for the boot task to
/// deliver its result before the exit path runs anyway. The boot is the only
/// writer to the stores until then, and a store left before its first catalog
/// run is refused on the next start (`db::has_product_schema`) — so waiting is
/// the normal case (a boot takes well under a second), and this limit covers
/// only a start that never finishes, which must stay closable.
const BOOT_EXIT_WAIT: Duration = Duration::from_secs(15);

// ── Global log broadcast for live streaming ──────────────────────

/// Global broadcast sender for live log streaming. Set during `startup()`.
pub static LOG_BROADCAST: OnceLock<broadcast::Sender<String>> = OnceLock::new();

/// Initialise the git file-change broadcast before the iced application runs
/// (matching the [`LOG_BROADCAST`] convention) so the file-change subscription
/// always has a source. Called from `main`.
pub fn init_git_file_change_tx() {
    git::init_file_change_tx();
}

/// Initialise the git-commit broadcast before the iced application runs
/// (matching the [`LOG_BROADCAST`] convention) so the pipeline-commit
/// subscription always has a source. Called from `main`.
pub fn init_git_commit_tx() {
    crate::git::commands::init_git_commit_tx();
}

/// Initialise the CDC ticket change broadcast before the iced application runs
/// (same convention as [`init_git_file_change_tx`] / [`LOG_BROADCAST`]) so the
/// board change subscription always has a source. An uninitialized `OnceLock`
/// would end the subscription stream on its first poll and freeze the board at
/// the initial snapshot — Iced does not re-spawn an ended subscription. Called
/// from `main` before `iced::application(...).run()`.
pub fn init_board_change_tx() {
    let _ = crate::db::cdc::ticket_sender();
}

/// Warm the CDC workspaces-table sender before the iced application runs (same
/// convention as [`init_board_change_tx`]) so the workspaces CDC subscription
/// always has a source. Called from `main`.
pub fn init_workspace_tx() {
    crate::db::cdc::init_workspace_tx();
}

/// Warm the CDC users-table sender before the iced application runs (same
/// convention as [`init_board_change_tx`]). Called from `main`.
pub fn init_users_tx() {
    crate::db::cdc::init_users_tx();
}

/// Warm the CDC user_channels-table sender before the iced application runs
/// (same convention as [`init_board_change_tx`]). Called from `main`.
pub fn init_user_channels_tx() {
    crate::db::cdc::init_user_channels_tx();
}

/// Initialise the runtime-change broadcast before the iced application runs
/// (same convention as [`init_board_change_tx`]) so the dashboard's
/// runtime-change subscription always has a source. Called from `main`.
pub fn init_runtime_event_tx() {
    crate::runtime_events::init_runtime_event_tx();
}

// ── Navigation pages ─────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Page {
    Home,
    Sessions,
    Logs,
    Shell,
    Editor,
    Settings,
    Alarms,
    /// Live view of running agents and in-flight non-agent LLM work.
    RunningAgents,
}

impl Page {
    /// Pages in the sidebar top nav — the Cmd+number keyboard map. Membership
    /// is positional: the shortcut is the page's 1-based index here, and the top
    /// nav renders this list minus the pages [`Dashboard::page_available`]
    /// excludes, so the keyboard map stays fixed regardless of what is shown.
    const fn sidebar_pages() -> &'static [Page] {
        &[Page::Home, Page::Editor, Page::Shell, Page::Alarms]
    }

    /// Pages in the sidebar bottom nav — click-only, no keyboard shortcut.
    const fn sidebar_bottom_pages() -> &'static [Page] {
        &[Page::Sessions, Page::Logs, Page::Settings]
    }

    const fn label(self) -> &'static str {
        match self {
            Page::Home => "Home",
            Page::Sessions => "Sessions",
            Page::Logs => "Logs",
            Page::Shell => "Shell",
            Page::Editor => "Editor",
            Page::Settings => "Settings",
            Page::Alarms => "Alarms",
            Page::RunningAgents => "Running Agents",
        }
    }
}

// ── Main message type ────────────────────────────────────────────

/// Toast notification kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToastKind {
    Success,
    Warning,
    Error,
}

/// Stable toast id source — monotonically increasing, never reused, so a
/// toast's expiry timer cannot dismiss a later toast that reused its slot.
static NEXT_TOAST_ID: AtomicU64 = AtomicU64::new(0);

/// A floating toast notification.
#[derive(Debug, Clone)]
pub(crate) struct Toast {
    /// Stable id used to dismiss the toast when its expiry timer fires.
    pub id: u64,
    pub message: String,
    pub kind: ToastKind,
}

/// Message emitted by a page to request a toast from the dashboard.
#[derive(Debug, Clone)]
pub enum ToastMessage {
    Saved,
    Deleted,
    Error(String),
    Warning(String),
    /// Generic success with custom message.
    SuccessMsg(String),
}

impl Toast {
    fn new(message: String, kind: ToastKind) -> Self {
        Self {
            id: NEXT_TOAST_ID.fetch_add(1, Ordering::Relaxed),
            message,
            kind,
        }
    }

    fn from_toast_msg(msg: &ToastMessage) -> Self {
        match msg {
            ToastMessage::Saved => Toast::new("Saved".to_string(), ToastKind::Success),
            ToastMessage::Deleted => Toast::new("Deleted".to_string(), ToastKind::Success),
            ToastMessage::Error(s) => Toast::new(format!("Failed: {s}"), ToastKind::Error),
            ToastMessage::Warning(s) => Toast::new(s.clone(), ToastKind::Warning),
            ToastMessage::SuccessMsg(s) => Toast::new(s.clone(), ToastKind::Success),
        }
    }

    const fn duration(&self) -> Duration {
        match self.kind {
            ToastKind::Success => Duration::from_secs(2),
            ToastKind::Warning | ToastKind::Error => Duration::from_secs(4),
        }
    }
}

/// Distinguishes between pause-toggle and maintenance-toggle toggles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ToggleKind {
    /// Pause/unpause the pipeline.
    Pause,
    /// Enable/disable the maintainer.
    Maintenance,
}

impl ToggleKind {
    fn label_on(self) -> &'static str {
        match self {
            Self::Pause => "Pipeline paused",
            Self::Maintenance => "Maintainer enabled",
        }
    }

    fn label_off(self) -> &'static str {
        match self {
            Self::Pause => "Pipeline resumed",
            Self::Maintenance => "Maintainer disabled",
        }
    }

    fn label_err(self) -> &'static str {
        match self {
            Self::Pause => "Failed to toggle pipeline pause",
            Self::Maintenance => "Failed to toggle maintainer",
        }
    }

    /// Persist the new toggle state to the workspace store.
    async fn persist_to_store(self, name: String, state: bool) -> Result<(), String> {
        let store = crate::workspace::store();
        match self {
            Self::Pause => store
                .set_paused(&name, state)
                .await
                .map_err(|e| e.to_string()),
            Self::Maintenance => store
                .set_maintenance_enabled(&name, state)
                .await
                .map_err(|e| e.to_string()),
        }
    }
}

#[derive(Debug, Clone)]
#[expect(private_interfaces)]
pub enum Message {
    /// MahBot finished async startup (or failed). On success, [`BOOT_LOG_STORE`] is set.
    Boot(Result<(), String>),
    Navigation(Page),
    /// A toast's expiry timer fired — dismiss the toast by its stable id.
    /// Dismissing an already-expired/unknown id is a safe no-op.
    ToastExpired(u64),
    /// Coalesced notification that the agent/non-agent registries, live
    /// transcript content, or voice status changed — triggers a re-render.
    RuntimeChanged,
    /// A workspaces-table row changed (or the CDC stream lagged/baseline
    /// fired) — triggers one full map reload via `load_workspace_map`.
    WorkspacesCdcChanged,
    /// A users-table or user_channels-table row changed (or the CDC stream
    /// lagged) — triggers a full users re-list on the Settings page and a
    /// read-back of the admin's active workspace (the phone-side switcher
    /// writes that same column).
    UsersCdcChanged,
    /// The admin's DB-stored active workspace read back after a users-table
    /// change — the desktop and the chat are one and the same choice, so a
    /// switch made on the phone applies here without a restart. `generation` is
    /// the `active_workspace_gen` guard value captured at dispatch, so a read a
    /// newer pick or read superseded cannot apply.
    ActiveWorkspaceSynced {
        generation: u64,
        name: Option<String>,
    },
    /// Shutdown signaled — leave the iced runtime for the product's exit path
    /// (`save_and_exit`), which `main` continues after `run()` returns.
    /// Triggered by the shutdown token: a self-update restart, SIGTERM/SIGINT, and the
    /// end of a drain a window close or a macOS quit began.
    Shutdown,
    /// The graceful-drain window began (first signal / window-close / quit /
    /// self-update). Draining disables input; iced::exit is deferred until
    /// the drain completes (the token fires).
    DrainStarted,
    /// The dashboard window's close button: an exit request, handled by
    /// `request_exit` — the graceful drain once boot has finished, the exit path directly
    /// before it.
    CloseRequested(window::Id),
    /// One of the platform's own ordinary quit asks — macOS's ⌘Q, the application menu's Quit
    /// item or the Dock's Quit — delivered by `quit_requests_subscription`, subscribed from the
    /// first frame. Runs the same exit handling as a window close, the second-quit escape
    /// included; the system's asks during a log-out, restart or shut-down are not delivered here
    /// (see `shutdown`).
    QuitRequested,
    /// Window geometry event (move/resize) — tracks state for persist-on-close.
    WindowEvent(window::Id, window::Event),
    /// The dashboard window was created, carrying the id of the new window.
    /// Windows only: the icons the taskbar and Alt-Tab show have to be attached to
    /// the window's own handle (see [`crate::app_icon`]).
    #[cfg(target_os = "windows")]
    WindowOpened(window::Id),
    /// The window's own platform handle, the answer to [`Message::WindowOpened`].
    /// Windows only — the value is the window's `HWND`.
    #[cfg(target_os = "windows")]
    WindowHandle(u64),
    /// Keyboard shortcut: Cmd+F — focus the primary search input on the current page.
    FocusSearch,
    /// Keyboard shortcut: Escape — dismiss modal/panel/confirmation on the current page.
    EscapePressed,
    /// Update button pressed — open the self-update confirmation modal.
    UpdateBot,
    /// Self-update confirmed — start the background update.
    ConfirmUpdate,
    /// Self-update confirmation dismissed — nothing happens.
    CancelUpdate,
    /// Self-update result.
    UpdateResult(Result<String, String>),
    /// Toggle the selected workspace's pipeline pause or maintainer state.
    Toggle(ToggleKind),
    /// Footer workspace picker: switch the admin's workspace (shared
    /// workspaces only).
    WorkspacePick(String),
    /// Result of a per-workspace toggle DB write. Carries (kind, result, workspace_name, intended_state).
    /// On success, the workspace map is reloaded from the store; on error an error toast is shown.
    ToggleResult(ToggleKind, Result<(), String>, String, bool),
    /// No-op — the completion message for a fire-and-forget write whose
    /// failure is already logged at the write site.
    Nop,
    /// Workspace info and restored selection loaded during boot. The read
    /// result is carried as-is so a failed boot read surfaces in the picker
    /// and Settings list instead of silently rendering as "no workspaces".
    /// The selection is the resolved name. The generation is the reload
    /// generation the read was issued under, so a reload that answered while
    /// it was in flight wins.
    BootWorkspaces {
        workspaces: Result<HashMap<String, Workspace>, String>,
        restored_name: String,
        generation: u64,
    },
    /// The wait for a still-running boot expired ([`BOOT_EXIT_WAIT`], a start
    /// that hangs): run the exit path for the exit request that was waiting.
    BootExitWaitExpired,
    /// Full workspace map reloaded from the store (CDC workspaces event,
    /// stream lag/baseline, toggle completion, or a settings add/delete). The
    /// handler replaces the map and re-resolves the live selection against it,
    /// but never substitutes one the fresh map does not carry: that is the DB
    /// read-back's call (see `Message::ActiveWorkspaceSynced`). The generation
    /// is the reload it answers, so a slow read cannot overwrite a newer one.
    WorkspacesReloaded {
        workspaces: HashMap<String, Workspace>,
        generation: u64,
    },
    /// The post-ready workspace map reload failed (all retries exhausted). The
    /// current map is preserved and the failure is rendered where the picker /
    /// Settings list would be — unless a newer reload has already answered.
    WorkspacesReloadFailed {
        error: String,
        generation: u64,
    },
    Home(home::HomeMessage),
    Logs(logs::LogMessage),
    Board(board::BoardMessage),
    Sessions(sessions::SessionsMessage),
    /// Alarms page messages (refresh and card-menu deletion).
    Alarms(alarms::AlarmsMessage),
    /// Running Agents page messages (manual research-run cancel).
    RunningAgents(running::RunningMessage),
    /// Diff modal overlay (not a page) — wraps [`diff::DiffMessage`].
    /// Named `DiffModal` rather than `Diff` to avoid ambiguity with the
    /// removed `Page::Diff` variant and the existing page-message convention.
    DiffModal(diff::DiffMessage),
    /// Git sub-state message.
    Git(git::GitMessage),
    Shell(shell::ShellMessage),
    Editor(editor::EditorMessage),
    Settings(settings::SettingsMessage),

    // ── Diff modal ──────────────────────────────────────────────
    /// Open the diff modal. Optional commit hash — `None` = working tree diff.
    OpenDiffModal(Option<String>),
    /// Close the diff modal.
    CloseDiffModal,
    /// TTS model download progress event.
    #[cfg(target_os = "macos")]
    TtsDownloadEvent(crate::audio::tts::TtsDownloadEvent),
}

// ── Message introspection helpers ────────────────────────────────
//
// These methods let [`Dashboard::update`] intercept Toast and
// LinkClicked messages before dispatching to page handlers,
// consolidating what would otherwise be per-page boilerplate.

impl Message {
    /// Returns a reference to the inner [`ToastMessage`] if this message wraps one.
    pub(crate) fn as_toast(&self) -> Option<&ToastMessage> {
        match self {
            Message::Home(home::HomeMessage::Toast(tm))
            | Message::Board(board::BoardMessage::Toast(tm))
            | Message::DiffModal(diff::DiffMessage::Toast(tm))
            | Message::Git(git::GitMessage::Toast(tm))
            | Message::Editor(editor::EditorMessage::Toast(tm))
            | Message::Sessions(sessions::SessionsMessage::Toast(tm))
            | Message::Alarms(alarms::AlarmsMessage::Toast(tm))
            | Message::Settings(
                settings::SettingsMessage::WorkspaceMsg(workspaces::WorkspacesMessage::Toast(tm))
                | settings::SettingsMessage::UserMsg(users::UsersMessage::Toast(tm)),
            ) => Some(tm),
            _ => None,
        }
    }

    /// Returns the URL string if this message wraps a `LinkClicked`.
    ///
    /// # Design note
    ///
    /// [`HomeMessage::LinkClicked`] is deliberately **not** included here
    /// because `home.rs` handles its own inline context links internally
    /// (see `HomeState::update`).  Do not add it without understanding
    /// the Home page's self-handling logic.
    fn as_link_url(&self) -> Option<&str> {
        match self {
            Message::Board(board::BoardMessage::LinkClicked(url))
            | Message::Sessions(sessions::SessionsMessage::LinkClicked(url))
            | Message::Settings(settings::SettingsMessage::WorkspaceMsg(
                workspaces::WorkspacesMessage::LinkClicked(url),
            )) => Some(url.as_str()),
            _ => None,
        }
    }
}

// ── Keyboard modifier helper ─────────────────────────────────────

/// Platform-aware keyboard modifier state computed from a
/// [`keyboard::Modifiers`] value.  Centralises the duplicated
/// `#[cfg]`-gated setup that was repeated across four GUI keyboard
/// subscription handlers.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct KeyboardMods {
    /// True if the Command key (macOS) is held (⌘).
    pub is_cmd: bool,
    /// True if the platform modifier is held — Command (⌘) on macOS,
    /// Control (Ctrl) on other platforms.
    pub is_platform_mod: bool,
    /// True if the Control key is held (any platform).
    pub ctrl_held: bool,
    /// On macOS: true if Ctrl is held without Cmd (triggers terminal
    /// control characters / emacs bindings).  Always false on other
    /// platforms.
    pub is_emacs_ctrl: bool,
    /// On non-macOS: true if Ctrl+Alt is held (AltGr character input).
    /// Always false on macOS.
    pub altgr_active: bool,
}

impl KeyboardMods {
    /// Platform modifier for shortcut-like navigation
    /// (arrow-key movement, line start/end, etc.).
    ///
    /// On macOS: Cmd only — Ctrl is reserved for Emacs-style bindings
    /// (Ctrl+F/B/A/E/P/N etc.) and terminal control characters.
    ///
    /// On other platforms: Cmd or Ctrl.
    #[must_use]
    pub(crate) fn is_nav_platform_mod(self) -> bool {
        if cfg!(target_os = "macos") {
            self.is_cmd
        } else {
            self.is_platform_mod
        }
    }

    /// Platform modifier for text-affecting shortcuts
    /// (clipboard C/X/V, IME guard).
    ///
    /// Stricter than [`is_nav_platform_mod`]: on macOS, Cmd+Ctrl combos
    /// are excluded (Ctrl+C/X/V are terminal control characters); on
    /// other platforms, AltGr (Ctrl+Alt) is excluded because it produces
    /// text characters for international keyboard layouts.
    #[must_use]
    pub(crate) fn is_text_platform_mod(self) -> bool {
        if cfg!(target_os = "macos") {
            self.is_cmd && !self.ctrl_held
        } else {
            self.is_platform_mod && !self.altgr_active
        }
    }

    /// Platform modifier for general keyboard shortcuts
    /// (everything except navigation and text operations).
    ///
    /// On macOS: Cmd is pressed (with or without Ctrl), but not Ctrl alone
    /// (which triggers terminal control characters / Emacs bindings).
    ///
    /// On other platforms: Cmd or Ctrl is pressed, but not AltGr
    /// (Ctrl+Alt, which produces international text characters).
    #[must_use]
    pub(crate) fn is_shortcut_platform_mod(self) -> bool {
        self.is_platform_mod && !self.is_emacs_ctrl && !self.altgr_active
    }
}

/// Compute [`KeyboardMods`] from an Iced [`keyboard::Modifiers`] value.
///
/// Encapsulates the `cfg!()`-based platform branching that every keyboard
/// subscription handler previously inlined.
pub(crate) fn detect_keyboard_mods(modifiers: keyboard::Modifiers) -> KeyboardMods {
    let is_cmd = modifiers.command();
    let is_platform_mod = modifiers.command() || modifiers.control();
    let ctrl_held = modifiers.control();

    let is_emacs_ctrl = cfg!(target_os = "macos") && modifiers.control() && !modifiers.command();
    let altgr_active = !cfg!(target_os = "macos") && modifiers.alt() && modifiers.control();

    KeyboardMods {
        is_cmd,
        is_platform_mod,
        ctrl_held,
        is_emacs_ctrl,
        altgr_active,
    }
}

/// Extract the key, modifiers, and physical key from a `KeyPressed` event.
#[must_use]
pub(crate) fn parse_key_press(
    event: keyboard::Event,
) -> Option<(keyboard::Key, keyboard::Modifiers, keyboard::key::Physical)> {
    let keyboard::Event::KeyPressed {
        key,
        modifiers,
        physical_key,
        ..
    } = event
    else {
        return None;
    };
    Some((key, modifiers, physical_key))
}

// ── Dashboard state ──────────────────────────────────────────────

/// Log store created during boot; read when handling [`Message::Boot`].
pub static BOOT_LOG_STORE: OnceLock<LogStore> = OnceLock::new();

pub struct Dashboard {
    ready: bool,
    boot_error: Option<String>,
    /// An exit requested while the boot task was still running: the exit waits
    /// for the boot's result (bounded by [`BOOT_EXIT_WAIT`]) instead of
    /// interrupting the store bring-up. See `request_exit`.
    exit_after_boot: bool,
    page: Page,
    log_store: Option<LogStore>,

    /// Tracked window geometry for persist-on-close.
    last_size: iced::Size,
    last_position: iced::Point,
    /// Toast notification stack.
    toasts: Vec<Toast>,

    /// Full per-workspace records (path, paused, maintenance, metadata),
    /// keyed by name. Populated during boot and updated via CDC-driven
    /// [`Message::WorkspacesReloaded`], which rebuilds the whole map from the
    /// store (no incremental boolean patching).
    workspaces: HashMap<String, Workspace>,
    /// Last workspace-map read failure (boot or a post-ready reload), rendered
    /// where the footer picker and the Settings workspace list would be.
    /// `None` once a successful read replaces it.
    workspaces_error: Option<String>,
    /// Generation of the latest workspace-map reload, so a slow read cannot
    /// apply its (now stale) outcome over a newer one.
    workspaces_reload_gen: u64,
    /// The read-back guard: bumped on every active-workspace pick this app
    /// applies and on every read-back it dispatches. Each read carries the
    /// generation it was dispatched with and applies only while it still matches,
    /// so a read dispatched before a local pick — or before a newer read — can
    /// never apply. A read dispatched *after* a pick can still observe that pick's
    /// pre-commit row (the commit lands after the write is issued) and revert the
    /// display until the pick's own CDC event re-reads it.
    active_workspace_gen: u64,
    /// The `(name, path)` pair last pushed to the workspace-scoped surfaces;
    /// `None` while none has been pushed. A workspace-map reload compares
    /// against it, so a change of *resolvability* alone — the selected name
    /// staying the same — still re-pushes (see [`Self::sync_workspace_surfaces`]).
    pushed_workspace: Option<(String, String)>,
    /// Currently selected workspace name. `Some("personal:admin")` = the
    /// admin's "Personal" workspace; `Some("ws")` = a shared workspace;
    /// `None` = nothing selected.
    selected_workspace_name: Option<String>,
    /// True when a genuine exit request — the window's close or a platform quit — arrived
    /// while the update was in its finalizing window (daemon shut down; checkpoint + spawn +
    /// exit pending). Only a real request sets this: the update's own shutdown step also fires
    /// `Message::Shutdown` via the subscription, which must not be mistaken for one. If the
    /// update fails, this flag makes the GUI run its own checkpoint + exit.
    exit_requested_during_update: bool,
    /// Graceful-drain window active: the window stays open with input
    /// disabled until the drain completes.
    draining: bool,
    /// Whether the self-update confirmation modal is open. Set by
    /// [`Message::UpdateBot`]; the update itself only starts on
    /// [`Message::ConfirmUpdate`], so dismissing leaves the system untouched.
    show_update_confirm: bool,
    /// Research run awaiting manual-cancel confirmation — the run's durable
    /// job id. `Some` while the confirm dialog is shown on the Running Agents
    /// page; the cancel runs only on [`running::RunningMessage::CancelConfirmed`].
    /// The id is never displayed as text — the button message carries it.
    pending_research_cancel: Option<String>,
    /// Running Agents page expanded-card state, keyed by (agent_id, generation)
    /// so a recycled agent_id never inherits a stale expansion. Pruned against
    /// the live agent list on each [`Message::RuntimeChanged`] registry event.
    running_expanded: HashSet<(String, u64)>,
    logs_state: logs::LogsState,
    board_state: board::BoardState,
    sessions_state: sessions::SessionsState,
    alarms_state: alarms::AlarmsState,
    diff_state: diff::DiffState,
    home_state: home::HomeState,
    shell_state: shell::ShellState,
    editor_state: editor::EditorState,
    settings_state: settings::SettingsState,

    // ── Diff modal ──────────────────────────────────────────────
    show_diff_modal: bool,

    // ── Git state ───────────────────────────────────────────────
    /// All git-related state (branch info, sync, branch modal).
    git_state: git::GitState,

    // ── TTS download progress ───────────────────────────────────
    /// Current TTS download progress: (file_name, progress 0.0–1.0).
    /// `None` when no download is active.
    #[cfg(target_os = "macos")]
    tts_download_progress: Option<(String, f32)>,
}

impl Dashboard {
    #[must_use]
    pub fn loading() -> Self {
        Self {
            ready: false,
            boot_error: None,
            exit_after_boot: false,
            page: Page::Home,
            log_store: None,
            last_size: iced::Size::new(1500.0, 800.0),
            last_position: iced::Point::new(-1.0, -1.0),
            toasts: Vec::new(),
            workspaces: HashMap::new(),
            workspaces_error: None,
            workspaces_reload_gen: 0,
            active_workspace_gen: 0,
            pushed_workspace: None,
            selected_workspace_name: None,
            exit_requested_during_update: false,
            draining: false,
            show_update_confirm: false,
            pending_research_cancel: None,
            running_expanded: HashSet::new(),
            logs_state: logs::LogsState::new(),
            board_state: board::BoardState::new(),
            sessions_state: sessions::SessionsState::new(),
            alarms_state: alarms::AlarmsState::new(),
            diff_state: diff::DiffState::new(),
            home_state: home::HomeState::new(),
            shell_state: shell::ShellState::new(),
            editor_state: editor::EditorState::new(),
            settings_state: settings::SettingsState::new(),
            show_diff_modal: false,
            git_state: git::GitState::new(),
            #[cfg(target_os = "macos")]
            tts_download_progress: None,
        }
    }

    fn finish_boot(&mut self, result: Result<(), String>) -> Task<Message> {
        match result {
            Ok(()) => {
                let log_store = BOOT_LOG_STORE
                    .get()
                    .cloned()
                    .expect("BOOT_LOG_STORE set before Boot(Ok)");
                self.ready = true;
                self.boot_error = None;
                let refresh_logs = self.logs_state.refresh(&log_store);
                let refresh_board = self.board_state.refresh();
                self.log_store = Some(log_store);
                let boot_workspaces = Task::perform(
                    load_workspace_options(self.workspaces_reload_gen),
                    std::convert::identity,
                );

                // The Home chat now runs the Phase-1 scripted onboarding
                // scenario while no LLM provider is configured (and fires the
                // Phase-2 Assistant kickoff once a provider is set), so no boot
                // redirect to Settings is needed here. The decision is made
                // after the config is fully loaded (bootstrap_mahbot
                // finished), not in the initial loading state where CONFIG
                // still holds defaults. A trimmed non-empty key counts as set
                // — `provider_key()` collapses empty/whitespace to None, so
                // those re-arm the script; an active custom endpoint counts as
                // configured too.
                Task::batch([
                    refresh_logs.map(Message::Logs),
                    refresh_board.map(Message::Board),
                    boot_workspaces,
                ])
            }
            Err(e) => {
                self.boot_error = Some(e);
                Task::none()
            }
        }
    }

    /// Returns the [`Workspace`] for the currently selected workspace, if any.
    fn selected_workspace_info(&self) -> Option<&Workspace> {
        self.selected_workspace_name
            .as_ref()
            .and_then(|name| self.workspaces.get(name))
    }

    /// The workspace resolved for the current selection: a registered workspace
    /// present in the loaded map with a non-empty path. A personal name, a name
    /// missing from the map and an empty path resolve to nothing.
    fn resolved_workspace(&self) -> Option<(&str, &str)> {
        let name = self.selected_workspace_name.as_deref()?;
        if crate::users::is_personal_workspace(name) {
            return None;
        }
        let path = self.workspaces.get(name)?.path.as_str();
        (!path.is_empty()).then_some((name, path))
    }

    /// Whether `page` is offered in the navigation. Only the editor and the
    /// shell are conditional, on [`Self::resolved_workspace`].
    fn page_available(&self, page: Page) -> bool {
        !matches!(page, Page::Editor | Page::Shell) || self.resolved_workspace().is_some()
    }

    /// Whether the selected workspace's pipeline is paused (a strict freeze:
    /// all in-flight work stops and no pipeline stage advances until resume).
    fn paused(&self) -> bool {
        self.selected_workspace_info().is_some_and(|w| w.paused)
    }

    /// Whether the selected workspace's maintainer is enabled.
    fn maintenance_enabled(&self) -> bool {
        self.selected_workspace_info()
            .is_some_and(|w| w.maintenance_enabled)
    }

    pub const fn theme(&self) -> iced::Theme {
        iced::Theme::Dark
    }

    /// Persist the current window position and size.
    fn persist_window_state(&self) {
        save_window_state(self.last_position, self.last_size);
    }

    /// Act on a request for the product to exit: name the route that asked, then start the wait
    /// the request calls for.
    ///
    /// The two requests that reach it — the window's own close and an ordinary platform quit —
    /// are handled identically, because full parity is the point of the interception; so are the
    /// states with no drain to complete (a self-update finalizing, a boot that has not finished,
    /// a boot that failed). `route` is the platform's wording for the ask
    /// ([`crate::shutdown::MACOS_QUIT_TRIGGER`], beside the route that produces it), or `None`
    /// for the window's own close, whose wording the exit line already falls back to.
    /// It is recorded where this request is what drives the exit (or, in the self-update window,
    /// may yet drive it once the update is seen to fail); a request that finds the exit already
    /// pending leaves the record to the one that caused it.
    fn request_exit(&mut self, route: Option<&'static str>) -> Task<Message> {
        if crate::self_update::update_in_progress() && crate::self_update::update_is_finalizing() {
            // The update owns the exit (its own drain + checkpoint + swap + spawn): record the
            // request and wait — a force-cancel here would abort the update's full drain. The
            // route is recorded because a failed update re-enters the exit path for this request
            // (see `exit_requested_during_update`); a request that finds the update window
            // already claimed changes nothing, and must not take the record over from the
            // request that claimed it.
            if !self.exit_requested_during_update {
                record_exit_route(route);
            }
            self.persist_window_state();
            self.exit_requested_during_update = true;
            Task::none()
        } else if !self.ready {
            // An exit request before boot finished has no drain to complete: the drain-watch,
            // and the shutdown subscription that turns the token into an exit, both exist only
            // after a successful boot — so the exit path runs directly. Not while the boot is
            // still writing the stores, though: a store left before its first catalog run is
            // refused on the next start (`db::has_product_schema`), so a request that arrives
            // mid-boot waits for the boot's result instead, and [`BOOT_EXIT_WAIT`] bounds that
            // wait so a start which never finishes stays closable.
            if self.boot_error.is_some() {
                // The start failed, so the boot stopped with it: nothing is writing the stores
                // any more.
                record_exit_route(route);
                self.save_and_exit()
            } else if self.exit_after_boot {
                // Nothing changes: this exit is already pending, so the request is not what ends
                // the process and must not take the exit record over from the one that is.
                Task::none()
            } else {
                record_exit_route(route);
                self.exit_after_boot = true;
                Task::perform(async { tokio::time::sleep(BOOT_EXIT_WAIT).await }, |()| {
                    Message::BootExitWaitExpired
                })
            }
        } else if crate::shutdown::is_draining() {
            // An exit request during a drain = second request: force-cancel (fires the token →
            // Message::Shutdown → exit path). The rule is the drain flag's, not the gesture's:
            // a first ⌘Q after a window close's drain forces that drain too. A drain whose token
            // has already fired is an exit under way, though — this request changes nothing about
            // it and must not take the record over.
            if !crate::shutdown::shutdown_token().is_cancelled() {
                record_exit_route(route);
            }
            crate::shutdown::force_cancel();
            Task::none()
        } else {
            // Begin the GRACEFUL drain: the window stays open with input disabled; the
            // drain-watch fires the token when no in-flight work remains (or force-cancels at
            // the cap). save_and_exit is deferred until Message::Shutdown.
            record_exit_route(route);
            crate::shutdown::drain_begin();
            Task::none()
        }
    }

    /// Leave the iced runtime for the product's exit path: flush the draft, record the window
    /// geometry, fire the shutdown token, then exit the runtime.
    ///
    /// The ordinary exit for everything the interface handles — a window close, a platform
    /// quit, SIGINT/SIGTERM, the clean end of a drain — and the entry to the teardown in
    /// `main` that the token's cancellation is checked against. It is not the only way this
    /// process ends: [`crate::shutdown`]'s module docs name the exits that never reach it.
    fn save_and_exit(&self) -> Task<Message> {
        crate::channels::chat_draft::flush_global();
        self.persist_window_state();
        if crate::self_update::update_in_progress() && crate::self_update::update_is_finalizing() {
            // The update path has shut down the daemon and owns the exit: checkpoint,
            // temp-root cleanup, lock release, spawn, exit(0). Exiting here would drop the
            // iced runtime and abort that sequence mid-checkpoint, leaving the daemon down
            // without a replacement — so wait instead. A request that arrives meanwhile is
            // recorded by `request_exit`; if the update fails, UpdateResult re-enters this path
            // (in-progress cleared, flag cleared) and honors it.
            return Task::none();
        }
        // Fire the token before the runtime drops — `shutdown_after_dashboard` relies on it
        // being cancelled by then (see its note in main.rs), and a request that arrives before
        // boot finished reaches here with no drain to have fired it. Idempotent: every other
        // arrival has it cancelled already.
        crate::shutdown::force_cancel();
        // The checkpoint is deliberately NOT run here: it relocated to
        // shutdown_after_dashboard, which runs after the iced runtime drops — genuinely
        // single-writer (today's in-iced checkpoint ran while background writers were still
        // live).
        iced::exit()
    }

    /// Window title with page name.
    pub fn title(&self) -> String {
        let page_name = self.page.label();
        format!("MahBot — {page_name}")
    }

    /// Apply workspace configuration loaded during boot. The boot path must
    /// complete either way: a failed read leaves an empty map beside the failure
    /// that stands in for it.
    ///
    /// `read_generation` is the reload generation the read was issued under. A
    /// reload that landed while it was in flight read the same table later, so
    /// its map (or its failure) wins and this read's outcome is dropped — the
    /// rest of the boot path still completes. The restored selection is applied
    /// and propagated either way; the workspace-scoped surfaces stay empty until
    /// it resolves (see [`Self::sync_workspace_surfaces`]).
    fn apply_boot_workspaces(
        &mut self,
        workspaces: Result<HashMap<String, Workspace>, String>,
        restored_name: &str,
        read_generation: u64,
    ) -> Task<Message> {
        if read_generation == self.workspaces_reload_gen {
            self.apply_boot_workspace_map(workspaces);
        }

        // The boot read always yields a name — a shared workspace or the
        // admin's `personal:admin` fallback.
        self.selected_workspace_name = Some(restored_name.to_owned());
        self.propagate_workspace_selection(restored_name)
    }

    /// Navigate to a page, refreshing page-specific state as needed.
    fn navigate_to(&mut self, page: Page) -> Task<Message> {
        self.page = page;
        // Every navigation notifies the editor of its visibility AFTER
        // `self.page` is set, so the handler sees the new state. This is the
        // single source of truth for the editor's page-visible gating: on the
        // Editor page it triggers refresh-on-entry, on any other page it closes
        // the editor's modals (modals do not survive a page switch).
        let visibility = Task::done(Message::Editor(
            editor::EditorMessage::PageVisibilityChanged(self.page == Page::Editor),
        ));
        let refresh = match page {
            // Logs and Shell maintain their own internal state; Editor
            // receives workspace state via WorkspaceSelected from the
            // Dashboard — none need a refresh on navigation. Running Agents
            // reads the live registries at render time.
            Page::Logs | Page::Shell | Page::Editor | Page::RunningAgents => Task::none(),
            Page::Home => {
                let snap = iced::widget::operation::snap_to_end::<Message>(home::CHAT_SCROLL_ID);
                let board_refresh = self.board_state.refresh().map(Message::Board);
                Task::batch([snap, board_refresh])
            }
            Page::Sessions => sessions::SessionsState::refresh().map(Message::Sessions),
            // The Alarms page renders nothing but its polled list, so entering
            // it starts a read rather than a render of stale entries.
            Page::Alarms => self.alarms_state.refresh().map(Message::Alarms),
            Page::Settings => {
                self.settings_state.refresh();
                // Workspace list comes from the shared map; only the users
                // list and the custom-tools area need a DB / folder read on
                // navigation.
                self.sync_settings_workspaces_from_map();
                Task::batch([
                    self.refresh_settings_users(),
                    self.refresh_settings_custom_tools(),
                ])
            }
        };
        Task::batch([visibility, refresh])
    }

    /// Refresh the Settings users list. The workspace list is not read here —
    /// it is synced from the dashboard's shared workspace map. Does not absorb
    /// the config snapshot (`settings_state.refresh()`).
    fn refresh_settings_users(&self) -> Task<Message> {
        self.settings_state
            .users_state
            .refresh()
            .map(|msg| Message::Settings(settings::SettingsMessage::UserMsg(msg)))
    }

    /// Refresh the Settings custom-tools area (its tool-folder read). Does not
    /// absorb the config snapshot (`settings_state.refresh()`).
    fn refresh_settings_custom_tools(&mut self) -> Task<Message> {
        self.settings_state
            .custom_tools_state
            .refresh()
            .map(|msg| Message::Settings(settings::SettingsMessage::CustomToolsMsg(msg)))
    }

    /// Sync the Settings workspaces section list from the shared workspace map
    /// (sorted by name, matching the store's `ORDER BY name`). No DB read — the
    /// map is the single source of truth.
    fn sync_settings_workspaces_from_map(&mut self) {
        let mut list: Vec<Workspace> = self.workspaces.values().cloned().collect();
        list.sort_by(|a, b| a.name.cmp(&b.name));
        self.settings_state.workspaces_state.workspaces = list;
    }

    /// Toggle the selected workspace's pause or maintainer state.
    fn toggle_workspace_state(&mut self, kind: ToggleKind) -> Task<Message> {
        let current_state = match kind {
            ToggleKind::Pause => self.paused(),
            ToggleKind::Maintenance => self.maintenance_enabled(),
        };
        let Some(ws_name) = self.active_workspace_name() else {
            return self.push_toast(
                "No workspace selected — select a workspace first".to_string(),
                ToastKind::Warning,
            );
        };
        let new_state = !current_state;
        let ws_name_clone = ws_name.clone();
        Task::perform(
            kind.persist_to_store(ws_name_clone, new_state),
            move |result| Message::ToggleResult(kind, result, ws_name, new_state),
        )
    }

    /// Handle the result of a workspace toggle write.
    fn finish_toggle(
        &mut self,
        kind: ToggleKind,
        result: Result<(), String>,
        ws_name: &str,
        intended_state: bool,
    ) -> Task<Message> {
        match result {
            Ok(()) => {
                let label = if intended_state {
                    kind.label_on()
                } else {
                    kind.label_off()
                };
                let toast = self.push_toast(format!("{label} for {ws_name}"), ToastKind::Success);
                // Immediate post-toggle refresh; the CDC stream provides the
                // durable confirmation later.
                let refresh = self.reload_workspace_map();
                Task::batch([toast, refresh])
            }
            Err(e) => self.push_toast(format!("{}: {e}", kind.label_err()), ToastKind::Error),
        }
    }

    /// Push a toast with a kind-specific expiry timer. The timer is a
    /// fire-and-forget task that emits [`Message::ToastExpired`] with the
    /// toast's stable id when it fires.
    fn push_toast(&mut self, message: String, kind: ToastKind) -> Task<Message> {
        self.spawn_toast(Toast::new(message, kind))
    }

    /// Push a toast from a [`ToastMessage`] (see [`Self::push_toast`]).
    fn push_toast_msg(&mut self, msg: &ToastMessage) -> Task<Message> {
        self.spawn_toast(Toast::from_toast_msg(msg))
    }

    fn spawn_toast(&mut self, toast: Toast) -> Task<Message> {
        let id = toast.id;
        let duration = toast.duration();
        self.toasts.push(toast);
        Task::perform(
            async move { tokio::time::sleep(duration).await },
            move |()| Message::ToastExpired(id),
        )
    }

    /// Handle Escape key: dismiss modals in priority order (self-update
    /// confirmation → diff modal → git branch modal → page-level escape
    /// dispatch).
    fn process_escape(&mut self) -> Task<Message> {
        // Modal close priority: self-update confirmation first, then diff
        // modal, then branch modal, then page-level escapes.
        if self.show_update_confirm {
            self.show_update_confirm = false;
            Task::none()
        } else if self.show_diff_modal {
            self.show_diff_modal = false;
            Task::done(Message::DiffModal(diff::DiffMessage::ClearCommitState))
        } else if self.git_state.is_modal_open() {
            self.git_state
                .update(git::GitMessage::CloseModal)
                .map(Message::Git)
        } else {
            match self.page {
                Page::Home => self
                    .board_state
                    .update(board::BoardMessage::Escape)
                    .map(Message::Board),
                // Shell and Alarms have no escape handling.
                // Running Agents: Escape dismisses the pending research-cancel
                // confirmation (Keep) — never confirms it.
                Page::RunningAgents => {
                    self.pending_research_cancel = None;
                    Task::none()
                }
                Page::Shell | Page::Alarms => Task::none(),
                Page::Logs => self
                    .logs_state
                    .update(
                        logs::LogMessage::Escape,
                        self.log_store.as_ref().expect("ready"),
                    )
                    .map(Message::Logs),
                Page::Sessions => self
                    .sessions_state
                    .update(sessions::SessionsMessage::Escape)
                    .map(Message::Sessions),
                Page::Editor => self
                    .editor_state
                    .update(editor::EditorMessage::Escape)
                    .map(Message::Editor),
                Page::Settings => self
                    .settings_state
                    .update(settings::SettingsMessage::Escape)
                    .map(Message::Settings),
            }
        }
    }

    /// Process a Settings message, optionally reloading the workspace map when
    /// workspaces are added or deleted.
    fn process_settings_message(&mut self, msg: settings::SettingsMessage) -> Task<Message> {
        // Any successful Settings-side workspace mutation (add, delete,
        // reanalyze, diagnostics/notes edits) refreshes the shared
        // workspace map from one full DB read — the map is the single source
        // of truth, and syncing the Settings workspace list from it (see
        // [`Self::sync_settings_workspaces_from_map`]) gives the page its immediate
        // post-op feedback. The workspaces sub-state itself never reads the
        // store.
        let needs_global_reload = matches!(
            msg,
            settings::SettingsMessage::WorkspaceMsg(
                workspaces::WorkspacesMessage::DeleteResult(Ok(()))
                    | workspaces::WorkspacesMessage::ReanalyzeResult(Ok(()))
                    | workspaces::WorkspacesMessage::DiagnosticsSaved(_, Ok(()))
                    | workspaces::WorkspacesMessage::RediscoverDiagnosticsResult(_, Ok(()))
                    | workspaces::WorkspacesMessage::NotesSaved(_, Ok(()))
            ) | settings::SettingsMessage::AddWorkspaceResult(Ok(_))
        );

        let settings_task = self.settings_state.update(msg).map(Message::Settings);

        if needs_global_reload {
            Task::batch([settings_task, self.reload_workspace_map()])
        } else {
            settings_task
        }
    }

    /// Process a Running Agents page message — the manual research-run
    /// cancel flow: button → pending-confirmation → async cancel → toast.
    fn process_running_message(&mut self, msg: running::RunningMessage) -> Task<Message> {
        match msg {
            running::RunningMessage::CancelRequest(run_key) => {
                // Pending-confirmation only: the dialog renders over the
                // Running Agents page; the run key is never displayed.
                self.pending_research_cancel = Some(run_key);
                Task::none()
            }
            running::RunningMessage::CancelConfirmed => {
                let Some(run_key) = self.pending_research_cancel.take() else {
                    return Task::none();
                };
                // The cancel is async: fire the run's signal and stop the run's
                // agents. Silent to the Manager/caller — only the GUI gets a
                // toast. The cancelled-run handoff (or a no-orchestrator sweep)
                // owns the cleanup dispatch and folder release.
                Task::perform(
                    async move { crate::research_cancel::cancel_research_run(&run_key).await },
                    |()| Message::RunningAgents(running::RunningMessage::CancelFinished),
                )
            }
            running::RunningMessage::CancelDismissed => {
                self.pending_research_cancel = None;
                Task::none()
            }
            running::RunningMessage::CancelFinished => {
                // cancel_research_run is infallible — the handoff (or the
                // no-orchestrator sweep) always makes progress.
                self.push_toast_msg(&ToastMessage::SuccessMsg(
                    "Research run cancelled — agents stopped; the run's temporary \
                     traces are being removed."
                        .to_string(),
                ))
            }
            running::RunningMessage::ToggleAgentExpanded {
                agent_id,
                generation,
            } => {
                if self
                    .running_expanded
                    .contains(&(agent_id.clone(), generation))
                {
                    self.running_expanded.remove(&(agent_id, generation));
                } else {
                    self.running_expanded.insert((agent_id, generation));
                }
                Task::none()
            }
        }
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, message: Message) -> Task<Message> {
        // ── Centralized Toast and LinkClicked interception ──────────
        // Intercepted at the Dashboard level (before page dispatch)
        // so page handlers only need a Task::none() arm for match exhaustiveness.
        // HomeMessage::LinkClicked is handled by Home itself — see
        // as_link_url() for details.
        if self.ready {
            if let Some(tm) = message.as_toast() {
                return self.push_toast_msg(tm);
            }

            if let Some(url) = message.as_link_url() {
                open_url(url);
                return Task::none();
            }
        }

        match message {
            // ── Pre-ready handlers (execute regardless of ready state) ──
            Message::Boot(result) => {
                // An exit request that arrived while the boot was still writing the
                // stores takes effect now — the boot has stopped, so it cannot
                // be left mid-bring-up (see `request_exit`).
                if std::mem::take(&mut self.exit_after_boot) {
                    return self.save_and_exit();
                }
                self.finish_boot(result)
            }
            Message::BootExitWaitExpired => {
                // The boot did not deliver a result within [`BOOT_EXIT_WAIT`] (a
                // start that hangs): the exit request that was waiting ends the
                // process anyway.
                self.save_and_exit()
            }
            Message::BootWorkspaces {
                workspaces,
                restored_name,
                generation,
            } => self.apply_boot_workspaces(workspaces, &restored_name, generation),
            Message::CloseRequested(_) => self.request_exit(None),
            Message::QuitRequested => self.request_exit(Some(crate::shutdown::MACOS_QUIT_TRIGGER)),
            Message::Shutdown => self.save_and_exit(),
            Message::DrainStarted => {
                // Restart toast: only when the update has finished and finalize
                // is shutting the service down — a plain window close, quit or
                // signal during an update still in flight (not yet finalizing)
                // must not show a false "restarting" toast. `!self.draining` is
                // defensive single-emission protection.
                if !self.draining
                    && crate::self_update::update_in_progress()
                    && crate::self_update::update_is_finalizing()
                {
                    let toast = self.push_toast(
                        "Update complete — restarting…".to_string(),
                        ToastKind::Warning,
                    );
                    self.draining = true;
                    return toast;
                }
                self.draining = true;
                Task::none()
            }
            Message::WindowEvent(_, event) => match event {
                window::Event::Resized(new_size) => {
                    self.last_size = new_size;
                    Task::none()
                }
                window::Event::Moved(new_pos) => {
                    self.last_position = new_pos;
                    Task::none()
                }
                _ => Task::none(),
            },
            #[cfg(target_os = "windows")]
            Message::WindowOpened(id) => window::raw_id::<Message>(id).map(Message::WindowHandle),
            #[cfg(target_os = "windows")]
            Message::WindowHandle(raw) => {
                crate::app_icon::apply_window_icons(raw);
                Task::none()
            }
            Message::CloseDiffModal => {
                self.show_diff_modal = false;
                Task::done(Message::DiffModal(diff::DiffMessage::ClearCommitState))
            }
            // Navigation has explicit before/after-ready handling
            Message::Navigation(_) if !self.ready => Task::none(),
            Message::Navigation(page) => self.navigate_to(page),

            // ── Everything else before boot → silent no-op ──
            _ if !self.ready => Task::none(),

            // ── Post-ready handlers (no per-arm guards needed) ──
            Message::WorkspacePick(name) => self.select_workspace(&name),
            Message::ToastExpired(id) => {
                // Dismissing an already-expired/unknown id is a safe no-op.
                self.toasts.retain(|t| t.id != id);
                Task::none()
            }
            Message::RuntimeChanged => {
                running::prune_expanded(
                    &mut self.running_expanded,
                    &crate::agent::registry::AGENT_REGISTRY.list(),
                );
                // The tick's Sessions work (list-cache refresh + live
                // transcript merge) is only observable while the page is
                // visible; navigating onto it refreshes, so gating here
                // cannot go stale.
                if self.page == Page::Sessions {
                    self.sessions_state
                        .update(sessions::SessionsMessage::RuntimeChanged)
                        .map(Message::Sessions)
                } else {
                    Task::none()
                }
            }
            Message::Home(msg) => self.home_state.update(msg).map(Message::Home),
            Message::Shell(msg) => self.shell_state.update(msg).map(Message::Shell),
            Message::Logs(msg) => self
                .logs_state
                .update(msg, self.log_store.as_ref().expect("ready"))
                .map(Message::Logs),
            Message::Board(msg) => {
                // Intercept ViewCommitDiff for cross-page navigation
                // before it reaches board_state.update.
                if let board::BoardMessage::ViewCommitDiff {
                    ref commit_hash, ..
                } = msg
                {
                    return self.open_diff_modal(Some(commit_hash.clone()));
                }
                self.board_state.update(msg).map(Message::Board)
            }
            Message::Sessions(msg) => self.sessions_state.update(msg).map(Message::Sessions),
            Message::Alarms(msg) => self.alarms_state.update(msg).map(Message::Alarms),
            Message::RunningAgents(msg) => self.process_running_message(msg),
            // Intercept CloseModal from successful manual commit — auto-close
            // the diff modal while keeping the diff state in working-tree view.
            // ClearCommitState is intentionally not emitted; the commit handler
            // already cleared commit state and kicked off a diff refresh.
            Message::DiffModal(diff::DiffMessage::CloseModal) => {
                self.show_diff_modal = false;
                Task::none()
            }
            Message::DiffModal(msg) => {
                // A manual commit is a ref-only change (HEAD + `.git/index`)
                // that the file watcher never reports, so refresh the git footer
                // promptly — otherwise diff_stats/behind_ahead stay stale until
                // the periodic timer.
                let commit_succeeded = matches!(&msg, diff::DiffMessage::CommitResult(Ok(_)));
                let diff_task = self.diff_state.update(msg).map(Message::DiffModal);
                if commit_succeeded {
                    Task::batch([
                        diff_task,
                        self.git_state
                            .update(git::GitMessage::RefreshAfterCommit)
                            .map(Message::Git),
                    ])
                } else {
                    diff_task
                }
            }
            Message::Editor(msg) => {
                // The editor's commit/staging mtime detector requests a
                // git-status refresh. Route it through GitState's standard
                // throttle/coalescing file-change path instead of the editor's
                // own handler, so it reuses the 300ms refresh coalescing (and
                // the resulting WorktreeSnapshot flows back to the editor via
                // the usual GitStatusUpdated forward).
                if matches!(msg, editor::EditorMessage::RequestGitStatusRefresh) {
                    self.git_state
                        .update(git::GitMessage::FileChanged)
                        .map(Message::Git)
                } else {
                    self.editor_state.update(msg).map(Message::Editor)
                }
            }
            Message::Settings(msg) => self.process_settings_message(msg),
            // ── Diff modal ────────────────────────────────────────
            Message::OpenDiffModal(commit_hash) => self.open_diff_modal(commit_hash),
            // ── Git state (routed to self.git_state) ─────────────────
            Message::Git(msg) => {
                // Cross-modal close: if opening the branch modal,
                // close the diff modal from Dashboard side.
                if matches!(msg, git::GitMessage::OpenModal) {
                    self.show_diff_modal = false;
                }
                let snapshot = matches!(msg, git::GitMessage::WorktreeSnapshot(..));
                let task = self.git_state.update(msg).map(Message::Git);
                // A current-generation worktree snapshot (Ok or Err) hands the
                // editor the latest (possibly last-known-good) per-file statuses
                // so its file-tree colors track GitState — the editor no longer
                // runs its own `git status` subprocess.
                if snapshot {
                    if let Some((workspace, statuses)) = self.git_state.take_status_forward() {
                        return Task::batch([
                            task,
                            Task::done(Message::Editor(editor::EditorMessage::GitStatusUpdated {
                                workspace,
                                statuses,
                            })),
                        ]);
                    }
                }
                task
            }
            Message::FocusSearch => match self.page {
                Page::Logs => self
                    .logs_state
                    .update(
                        logs::LogMessage::FocusSearch,
                        self.log_store.as_ref().expect("ready"),
                    )
                    .map(Message::Logs),
                _ => Task::none(),
            },
            Message::EscapePressed => self.process_escape(),
            Message::UpdateBot => {
                // Only opens the confirmation modal — the update
                // starts on `ConfirmUpdate`. Availability is read from the
                // shared cache, so a Telegram-initiated update disables the
                // button here too.
                let availability = crate::self_update::update_availability();
                if availability.available && !availability.in_progress {
                    self.show_update_confirm = true;
                }
                Task::none()
            }
            Message::ConfirmUpdate => {
                self.show_update_confirm = false;
                let availability = crate::self_update::update_availability();
                if !availability.available || availability.in_progress {
                    return Task::none();
                }
                // Save window state before update (synchronous).
                self.persist_window_state();
                // Transient confirmation that the update has kicked off; the
                // update itself tells the admin the same thing in its own words.
                let toast = self.push_toast("Update started…".to_string(), ToastKind::Success);
                Task::batch([
                    toast,
                    Task::perform(
                        async {
                            match crate::self_update::execute_update().await {
                                Ok(()) => Ok("ok".to_string()),
                                Err(e) => {
                                    // Report to the admin (Telegram) as well as
                                    // the GUI toast, preserving the prior behavior
                                    // where the update path notified on failure.
                                    // `execute_update` no longer notifies; each caller
                                    // composes its own failure text.
                                    let msg = format!("❌ Update failed:\n{e:#}");
                                    let target =
                                        crate::self_update::resolve_admin_telegram_target().await;
                                    crate::self_update::notify_admin(
                                        &crate::self_update::update_failure_notification(&e),
                                        target.as_deref(),
                                    )
                                    .await;
                                    Err(msg)
                                }
                            }
                        },
                        Message::UpdateResult,
                    ),
                ])
            }
            Message::CancelUpdate => {
                self.show_update_confirm = false;
                Task::none()
            }
            Message::UpdateResult(result) => {
                // execute_update() calls exit(0) on success, so we never
                // actually reach this branch for the Ok case. The update
                // toasts (start + restart) are the success signals; the
                // window closing is the final confirmation. On failure
                // `execute_update` already cleared the shared in-progress
                // flag, so the exit guards below no longer wait.
                if let Err(err) = result {
                    let toast = self.push_toast_msg(&ToastMessage::Error(err));
                    if self.exit_requested_during_update {
                        // A window close or a platform quit arrived while the
                        // update owned the exit; it failed, so run the normal
                        // exit checkpoint.
                        self.exit_requested_during_update = false;
                        return Task::batch([toast, self.save_and_exit()]);
                    }
                    return toast;
                }
                Task::none()
            }
            Message::Toggle(kind) => self.toggle_workspace_state(kind),
            Message::ToggleResult(kind, result, ws_name, intended_state) => {
                self.finish_toggle(kind, result, &ws_name, intended_state)
            }
            // A workspaces-table row changed (or the stream lagged/baseline
            // fired) — one full map reload; the handler below re-resolves the
            // live selection against the fresh map.
            Message::WorkspacesCdcChanged => self.reload_workspace_map(),
            Message::WorkspacesReloaded {
                workspaces,
                generation,
            } => {
                // Stale-result guard: a slow reload must not overwrite a newer
                // one that has already answered.
                if generation != self.workspaces_reload_gen {
                    return Task::none();
                }
                self.apply_workspace_reload(Ok(workspaces));

                // A selection this map does not contain is NOT re-resolved to
                // "Personal": the map can lag the stored choice (a workspace
                // registered and selected in one go is missing from a read that
                // started before its insert), and resolving here would leave the
                // desktop on the personal space while the chat and the DB keep
                // the project active. The DB owns the choice and its read-back
                // applies it (see `active_workspace_gen`), so only the
                // now-unresolved surfaces are re-pushed.
                let unknown = self.selected_workspace_name.as_deref().is_some_and(|name| {
                    !self.workspaces.contains_key(name)
                        && !crate::users::is_personal_workspace(name)
                });
                if unknown {
                    return self.sync_workspace_surfaces();
                }

                // Otherwise re-resolve the LIVE selection against the fresh map
                // instead of a value captured when the reload was triggered, so a
                // reload that lands before the boot selection is applied cannot
                // clobber it. Only a resolution that differs from the live
                // selection — the "Personal" default of nothing selected yet —
                // propagates (propagate is heavy); otherwise only the
                // workspace-scoped surfaces are re-pushed.
                let personal_name =
                    crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
                let resolved = resolve_workspace_selection(
                    &self.workspaces,
                    self.selected_workspace_name.as_deref(),
                    &personal_name,
                );
                let current = self.selected_workspace_name.as_deref().unwrap_or_default();
                if current != resolved.as_str() {
                    self.selected_workspace_name = Some(resolved.clone());
                    return self.propagate_workspace_selection(&resolved);
                }
                // The name is unchanged, but this map can still have changed
                // whether it resolves to a workspace path: the boot race leaves
                // the restored selection resolved against the map that was
                // dropped as stale, so the workspace-scoped surfaces stayed
                // empty. Re-push them, and only them.
                self.sync_workspace_surfaces()
            }
            // A users-table / user_channels-table row changed (or the stream
            // lagged) — the event does not say which column changed, so the
            // read-back is the authority on the shared selection. Full re-list
            // is its own recovery.
            Message::UsersCdcChanged => {
                self.active_workspace_gen += 1;
                let generation = self.active_workspace_gen;
                Task::batch([
                    self.refresh_settings_users(),
                    Task::perform(read_active_workspace(), move |name| {
                        Message::ActiveWorkspaceSynced { generation, name }
                    }),
                ])
            }
            Message::ActiveWorkspaceSynced {
                generation,
                name: Some(name),
            } => {
                // Stale reads are dropped (see `active_workspace_gen`); an
                // unchanged value must not re-run the heavy propagate.
                if generation != self.active_workspace_gen
                    || self.selected_workspace_name.as_deref() == Some(name.as_str())
                {
                    Task::none()
                } else {
                    // Applied as stored, not resolved against the loaded map the
                    // way a reload is: the map can be a reload behind while the DB
                    // is authoritative about the choice. In memory only — writing
                    // the value back would answer our own CDC event.
                    self.apply_workspace_selection(&name)
                }
            }
            // A failed read-back changes nothing: the live selection stands.
            Message::ActiveWorkspaceSynced { name: None, .. } => Task::none(),
            Message::WorkspacesReloadFailed { error, generation } => {
                // Stale-result guard, mirroring the success arm: without it a
                // reload that fails after a newer one succeeded would re-set the
                // failure over the map that read produced.
                if generation != self.workspaces_reload_gen {
                    return Task::none();
                }
                // Keep the current map (the selection may still resolve) and
                // render the failure where the picker / Settings list would be.
                self.apply_workspace_reload(Err(error));
                Task::none()
            }
            Message::Nop => Task::none(),
            #[cfg(target_os = "macos")]
            Message::TtsDownloadEvent(event) => self.handle_tts_download_event(event),
        }
    }

    /// Handle a TTS download progress event.
    #[cfg(target_os = "macos")]
    #[expect(clippy::cast_precision_loss)]
    fn handle_tts_download_event(
        &mut self,
        event: crate::audio::tts::TtsDownloadEvent,
    ) -> Task<Message> {
        match event {
            crate::audio::tts::TtsDownloadEvent::FileStarted { name, .. } => {
                self.tts_download_progress = Some((name, 0.0));
                Task::none()
            }
            crate::audio::tts::TtsDownloadEvent::FileProgress {
                name,
                bytes_downloaded,
                total_bytes,
            } => {
                let progress = if total_bytes > 0 {
                    (bytes_downloaded as f32 / total_bytes as f32).clamp(0.0, 1.0)
                } else {
                    0.0
                };
                self.tts_download_progress = Some((name, progress));
                Task::none()
            }
            crate::audio::tts::TtsDownloadEvent::FileCompleted { name } => {
                // Mark the file as fully done; next FileStarted will show the next file.
                self.tts_download_progress = Some((name, 1.0));
                Task::none()
            }
            crate::audio::tts::TtsDownloadEvent::Complete
            | crate::audio::tts::TtsDownloadEvent::Failed { .. } => {
                self.tts_download_progress = None;
                Task::none()
            }
        }
    }

    /// Open the diff modal, closing any board or branch modal first.
    ///
    /// When `commit_hash` is `Some`, navigates to that commit; when `None`,
    /// navigates to the working tree (clearing any stale commit state).
    ///
    /// The change/diff view is workspace-scoped, so this refuses to open while
    /// nothing is resolved — including the board's ticket commit link.
    fn open_diff_modal(&mut self, commit_hash: Option<String>) -> Task<Message> {
        if self.resolved_workspace().is_none() {
            return Task::none();
        }
        // Close any board modal
        let close_board = self
            .board_state
            .update(board::BoardMessage::CloseModal)
            .map(Message::Board);
        self.show_diff_modal = true;
        // Close branch modal synchronously if open.
        // CloseModal always returns Task::none() so discarding is safe.
        let _ = self.git_state.update(git::GitMessage::CloseModal);
        let diff_task = match commit_hash {
            Some(hash) => Task::done(Message::DiffModal(diff::DiffMessage::NavigateToCommit(
                hash,
            ))),
            None => Task::done(Message::DiffModal(diff::DiffMessage::BackToWorkingTree)),
        };
        Task::batch([close_board, diff_task])
    }

    /// Apply a workspace selection in memory and broadcast it to all pages,
    /// without writing the DB. Used where the DB write happened (or happens)
    /// elsewhere — the footer picker's [`Self::select_workspace`] and the
    /// read-back in the `Message::ActiveWorkspaceSynced` arm.
    fn apply_workspace_selection(&mut self, name: &str) -> Task<Message> {
        // Git state is cleared and eagerly refreshed below via
        // propagate_workspace_selection → set_workspace_path.
        self.selected_workspace_name = Some(name.to_string());
        self.propagate_workspace_selection(name)
    }

    /// Canonical entry point for workspace switching in the dashboard: applies
    /// the selection in memory and persists it as the admin's
    /// `users.selected_workspace` (the DB is the single source of truth; a
    /// personal selection stores NULL). The DB write is best-effort — failures
    /// are logged, the GUI selection still applies.
    ///
    /// A name missing from the workspace map is never persisted: the picker
    /// renders from the map, so a reload that dropped the picked name between
    /// render and click must not write a dangling value into the DB. The
    /// in-memory selection still applies; the DB read-back decides if it stands.
    fn select_workspace(&mut self, name: &str) -> Task<Message> {
        let propagate = self.apply_workspace_selection(name);
        let known = crate::users::is_personal_workspace(name) || self.workspaces.contains_key(name);
        // Supersedes any in-flight read-back (see `active_workspace_gen`).
        self.active_workspace_gen += 1;
        let db_write = known.then(|| {
            let ws = name.to_string();
            Task::perform(
                async move {
                    if let Err(e) = users::set_selected_workspace_field(
                        crate::users::ADMIN_USER_NAME.to_string(),
                        ws,
                    )
                    .await
                    {
                        tracing::warn!(error = %e, "Failed to persist workspace selection");
                    }
                },
                |()| Message::Nop,
            )
        });
        Task::batch(std::iter::once(propagate).chain(db_write))
    }

    /// Propagate the global workspace selection to the board and to the Home
    /// page, then push the resolved workspace to the workspace-scoped
    /// surfaces (see [`Self::sync_workspace_surfaces`]).
    fn propagate_workspace_selection(&mut self, name: &str) -> Task<Message> {
        // Set board's workspace filter directly, then refresh.
        // Clear any active search when switching workspaces so stale results
        // from the previous workspace don't persist.
        self.board_state.workspace_name = Some(name.to_string());
        self.board_state.search_query.clear();
        self.board_state.search_results.clear();
        self.board_state.search_error = None;
        self.board_state.search_generation += 1;
        // The previous workspace's load failure does not describe the board
        // being loaded now.
        self.board_state.load_state.clear_error();
        // Bump the board generation so a stale in-flight snapshot from the
        // previous workspace is dropped on arrival.
        self.board_state.board_generation += 1;
        // On switch the next snapshot REPLACES the board (the previous
        // workspace's tickets must not linger), and the removal-tracking set is
        // cleared so old-workspace removals are not applied to the new snapshot.
        self.board_state.replace_on_refresh = true;
        self.board_state.delta_removed_ids.clear();
        let board_refresh = self.board_state.refresh().map(Message::Board);

        // Notify the Home page so it can reload chat history: the selection as
        // stored, with no substitution. A selection the loaded map has not
        // caught up with yet — a project activated from the chat while a reload
        // read was in flight — is still the account's active choice, and Home
        // (its transcript read key and its per-workspace draft) must key on the
        // same choice the picker and the DB carry. Same rule as
        // `sync_workspace_surfaces`: an unresolved selection is never shown the
        // personal workspace.
        let home_task: Task<Message> =
            Task::done(home::HomeMessage::WorkspaceChanged(Some(name.to_string())))
                .map(Message::Home);

        let surfaces = self.sync_workspace_surfaces();
        Task::batch([board_refresh, home_task, surfaces])
    }

    /// Push the resolved workspace to the four workspace-scoped surfaces — the
    /// editor, the shell, the footer git status and the change/diff view — and
    /// to nothing else. No substitution of any kind happens here: an unresolved
    /// selection is never shown the personal workspace.
    ///
    /// The editor and the shell own per-workspace tab state, so they are only
    /// ever pushed a real resolution; while nothing is resolved the Dashboard
    /// hides their pages and drops the editor's subscription instead of tearing
    /// their tabs down. The footer git status and the change/diff view hold
    /// derived state only, so they are cleared — that is what drops the
    /// watcher, the refresh loop and the diff tick of a workspace that is no
    /// longer selected.
    ///
    /// An unchanged resolution is a no-op: the workspace-map reload path calls
    /// this on every CDC event and the push must not run then.
    fn sync_workspace_surfaces(&mut self) -> Task<Message> {
        let resolved = self
            .resolved_workspace()
            .map(|(name, path)| (name.to_string(), path.to_string()));
        // The change/diff view is an overlay of the current page: while nothing
        // is resolved it is closed rather than left open and empty (it would
        // keep owning Escape and the diff keyboard shortcuts).
        if resolved.is_none() {
            self.show_diff_modal = false;
        }
        if resolved == self.pushed_workspace {
            return Task::none();
        }
        self.pushed_workspace.clone_from(&resolved);
        if let Some((name, path)) = resolved {
            Task::batch([
                Task::done(editor::EditorMessage::WorkspaceSelected(
                    name.clone(),
                    path.clone(),
                ))
                .map(Message::Editor),
                Task::done(shell::ShellMessage::WorkspaceSelected(
                    name.clone(),
                    path.clone(),
                ))
                .map(Message::Shell),
                self.git_state
                    .set_workspace_path(Some(name.clone()), Some(path.clone()))
                    .map(Message::Git),
                Task::done(diff::DiffMessage::WorkspaceSelected(path)).map(Message::DiffModal),
            ])
        } else {
            Task::batch([
                self.git_state
                    .set_workspace_path(None, None)
                    .map(Message::Git),
                Task::done(diff::DiffMessage::WorkspaceUnresolved).map(Message::DiffModal),
            ])
        }
    }

    /// Reload the full workspace map from storage (e.g. after add/delete on
    /// the Workspaces page or a post-toggle refresh). Resolution happens in
    /// [`Message::WorkspacesReloaded`], from the live selection.
    ///
    /// The reload carries the generation it was issued under: this read retries
    /// for a second on a transient failure, so without it a delayed failure
    /// could re-set the error over a newer read that has already succeeded.
    fn reload_workspace_map(&mut self) -> Task<Message> {
        self.workspaces_reload_gen = self.workspaces_reload_gen.wrapping_add(1);
        let generation = self.workspaces_reload_gen;
        Task::perform(load_workspace_map(generation), std::convert::identity)
    }

    /// Apply the boot workspace-map read. There is no previous map to keep, so a
    /// failure leaves an empty map beside the failure that stands in for it and
    /// the boot path completes either way. The Settings list is re-derived here,
    /// so it can never diverge from the map.
    fn apply_boot_workspace_map(&mut self, result: Result<HashMap<String, Workspace>, String>) {
        match result {
            Ok(map) => {
                self.workspaces = map;
                self.workspaces_error = None;
            }
            Err(e) => {
                self.workspaces = HashMap::new();
                self.workspaces_error = Some(e);
            }
        }
        self.sync_settings_workspaces_from_map();
    }

    /// Apply a post-ready workspace-map reload: a failed read keeps the map the
    /// live selection may still resolve against, while the failure is recorded
    /// for the picker and the Settings list.
    fn apply_workspace_reload(&mut self, result: Result<HashMap<String, Workspace>, String>) {
        match result {
            Ok(map) => {
                self.workspaces = map;
                self.workspaces_error = None;
            }
            Err(e) => self.workspaces_error = Some(e),
        }
        self.sync_settings_workspaces_from_map();
    }

    /// Return the selected shared-workspace name, or `None` if the "Personal"
    /// workspace is selected (no shared workspace).
    fn active_workspace_name(&self) -> Option<String> {
        match self.selected_workspace_name.as_deref() {
            Some(n) if !crate::users::is_personal_workspace(n) => Some(n.to_string()),
            _ => None,
        }
    }

    /// Returns `true` when a shared (non-Personal) workspace is selected.
    /// Avoids the allocation of [`active_workspace_name`] for presence-only checks.
    fn has_active_workspace(&self) -> bool {
        self.selected_workspace_name
            .as_deref()
            .is_some_and(|n| !crate::users::is_personal_workspace(n))
    }

    /// Whether a dashboard-level overlay modal is open over the current page.
    /// Used to gate the editor page's keyboard ownership. The board ticket
    /// modal is not included: it renders only inside the Home page content
    /// (never the global overlay stack), so it cannot sit above the editor.
    ///
    /// `pending_research_cancel` is likewise excluded: it is rendered inside
    /// the Running Agents page body, not as an overlay over other pages.
    fn overlay_modal_open(&self) -> bool {
        self.show_diff_modal || self.show_update_confirm || self.git_state.is_modal_open()
    }

    #[expect(clippy::too_many_lines)]
    pub fn view(&self) -> Element<'_, Message> {
        if let Some(err) = &self.boot_error {
            return container(
                column![
                    text("MahBot failed to start")
                        .size(20)
                        .color(theme::STATUS_ERROR),
                    text(err).size(theme::TEXT_14).color(theme::TEXT_SECONDARY),
                ]
                .spacing(theme::SPACE_12)
                .padding(theme::PAGE_PADDING),
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .center_x(Length::Fill)
            .center_y(Length::Fill)
            .into();
        }

        if !self.ready {
            return container(
                column![
                    image(crate::app_icon::widget_image()).width(96).height(96),
                    text("MahBot")
                        .size(theme::TEXT_24)
                        .color(theme::TEXT_PRIMARY),
                    text("Starting…")
                        .size(theme::TEXT_16)
                        .color(theme::TEXT_MUTED),
                ]
                .spacing(theme::SPACE_16)
                .align_x(Alignment::Center),
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .center_x(Length::Fill)
            .center_y(Length::Fill)
            .into();
        }

        let sidebar = self.sidebar_view();
        let footer = self.footer_view();
        let content = match self.page {
            Page::Home => {
                let home_view = self.home_state.view(self.draining).map(Message::Home);
                let sidebar = ticket_sidebar(&self.board_state);
                // Wrap chat area in a right-click context menu with
                // "Reset session". Per-bubble ContextMenus (Copy message,
                // see home.rs) capture bubble right-clicks; this outer
                // menu is the fallback for empty-space right-clicks.
                let home_view: Element<'_, Message> = ContextMenu::new(
                    home_view,
                    vec![menus::MenuItem::new(
                        "Reset session".into(),
                        Message::Home(home::HomeMessage::ClearChat),
                    )],
                )
                .into();
                // Wrap sidebar in a right-click context menu with "Archive done
                // & cancelled", plus the bulk pause item when a
                // queued ticket is listed.
                let mut menu_items = vec![menus::MenuItem::new(
                    "Archive done & cancelled".into(),
                    Message::Board(board::BoardMessage::ArchiveAllCompleted),
                )];
                if self.board_state.has_visible_queued_tickets() {
                    menu_items.push(menus::MenuItem::new(
                        "Pause all queued tickets".into(),
                        Message::Board(board::BoardMessage::PauseAllQueued),
                    ));
                }
                let sidebar: Element<'_, Message> = ContextMenu::new(sidebar, menu_items).into();
                let base = row![
                    container(home_view).width(Length::FillPortion(7)),
                    container(sidebar).width(Length::FillPortion(3))
                ];
                let modal = self.board_state.render_modal_overlay().map(Message::Board);
                iced::widget::stack([base.into(), modal]).into()
            }
            Page::Logs => self.logs_state.view().map(Message::Logs),
            Page::Sessions => self.sessions_state.view().map(Message::Sessions),
            Page::Alarms => self.alarms_state.view().map(Message::Alarms),
            Page::Shell => {
                if self.page_available(Page::Shell) {
                    self.shell_state.view().map(Message::Shell)
                } else {
                    unresolved_workspace_page(Page::Shell)
                }
            }
            Page::Editor => {
                if self.page_available(Page::Editor) {
                    self.editor_state
                        .view(self.overlay_modal_open())
                        .map(Message::Editor)
                } else {
                    unresolved_workspace_page(Page::Editor)
                }
            }
            Page::Settings => self
                .settings_state
                .view(self.workspaces_error.as_deref())
                .map(Message::Settings),
            Page::RunningAgents => running::view(
                &self.workspaces,
                self.pending_research_cancel.as_deref(),
                &self.running_expanded,
            ),
        };

        let body = column![
            row![sidebar, content]
                .width(Length::Fill)
                .height(Length::Fill),
            footer,
        ]
        .width(Length::Fill)
        .height(Length::Fill);

        // Keep Stack widget type stable to prevent state loss on toast
        // transitions. A type tag change (Column ↔ Stack) would cause Iced
        // to destroy the entire widget tree, losing scroll positions, cursor
        // states, and all other widget state.
        let overlay: Element<'_, Message> = if self.toasts.is_empty() {
            widgets::empty_stack_placeholder()
        } else {
            let mut toast_col = Column::new()
                .spacing(theme::SPACE_6)
                .align_x(Alignment::Center);
            for toast in &self.toasts {
                let (color, _bg) = match toast.kind {
                    ToastKind::Success => (theme::STATUS_SUCCESS, theme::BG_ELEVATED),
                    ToastKind::Warning => (theme::STATUS_WARNING, theme::BG_ELEVATED),
                    ToastKind::Error => (theme::STATUS_ERROR, theme::BG_ELEVATED),
                };
                let pill = container(text(&toast.message).size(theme::TEXT_12).color(color))
                    .padding([theme::PAD_6, theme::PAD_14])
                    .style(move |_theme: &iced::Theme| container::Style {
                        background: Some(iced::Background::Color(theme::BG_ELEVATED)),
                        border: iced::Border {
                            radius: 20.0.into(),
                            width: 1.0,
                            color: theme::BORDER,
                        },
                        ..container::Style::default()
                    });
                toast_col = toast_col.push(pill);
            }
            container(toast_col)
                .width(Length::Fill)
                .align_x(Alignment::Center)
                .padding(iced::Padding {
                    bottom: 44.0,
                    ..Default::default()
                })
                .align_bottom(Length::Fill)
                .into()
        };

        // ── Diff modal overlay ─────────────────────────────────────
        // `show_diff_modal` is only ever set for a resolved workspace, and
        // `sync_workspace_surfaces` clears it when the resolution is lost.
        let diff_overlay: Element<'_, Message> = if self.show_diff_modal {
            render_diff_modal(&self.diff_state)
        } else {
            widgets::empty_stack_placeholder()
        };

        // ── Branch management modal (small centered dialog) ──────────
        let branch_overlay: Element<'_, Message> = if self.git_state.is_modal_open() {
            let dialog = dialog::dialog_shell(self.git_state.view().map(Message::Git), 400.0, 24.0);
            widgets::modal_backdrop(dialog, Message::Git(git::GitMessage::CloseModal), 0.5)
        } else {
            widgets::empty_stack_placeholder()
        };

        // ── Self-update confirmation modal overlay ─────────────────
        let update_overlay: Element<'_, Message> = self.render_update_confirm();

        iced::widget::stack![body, diff_overlay, branch_overlay, update_overlay, overlay].into()
    }
}

/// Wrap dialog content in a modal overlay with a semi-transparent backdrop
/// and centered 80%-width dialog container.
///
/// Creates a backdrop that dismisses the modal on click, wraps `inner` in the
/// standard dialog container style with 16px padding, and centers it at 80%
/// width using a `FillPortion(1/8/1)` row layout. The dialog rectangle is
/// click-claimed (via [`widgets::dialog_click_guard`]) so interior clicks do
/// not fall through to the backdrop, while the surrounding margin still does.
fn modal_overlay<'a>(
    inner: impl Into<Element<'a, Message>>,
    on_close: Message,
) -> Element<'a, Message> {
    let dialog = container(inner)
        .height(Length::Fill)
        .padding(theme::PAD_16)
        .style(theme::dialog_container_style);

    let centered = row![
        Space::new().width(Length::FillPortion(1)), // 10% margin
        widgets::dialog_click_guard(dialog.width(Length::FillPortion(8))), // 80% content
        Space::new().width(Length::FillPortion(1)), // 10% margin
    ]
    .width(Length::Fill)
    .height(Length::Fill);

    iced::widget::stack([
        widgets::modal_backdrop_layer(on_close, 0.5),
        centered.into(),
    ])
    .into()
}

/// Render the diff modal (80% width, 100% height, centered).
fn render_diff_modal(diff_state: &diff::DiffState) -> Element<'_, Message> {
    let viewing_commit = diff_state.is_viewing_commit();

    // Outer header: commit message (large, bold) + short hash (muted) for
    // historical commits, or "Uncommitted changes" for working-tree diff.
    let header: Element<'_, Message> = if viewing_commit {
        let msg = diff_state
            .commit_message()
            .unwrap_or("(no commit message)")
            .to_string();
        let hash = diff_state.commit_short_hash().unwrap_or("???????");
        column![
            widgets::section_heading(msg),
            text(hash).size(theme::TEXT_12).color(theme::TEXT_SECONDARY),
        ]
        .spacing(theme::SPACE_2)
        .padding(iced::Padding {
            bottom: theme::PAD_12,
            ..iced::Padding::ZERO
        })
        .into()
    } else {
        column![
            widgets::section_heading("Uncommitted changes"),
            text("Working tree diff \u{2014} press Escape to close")
                .size(theme::TEXT_11)
                .color(theme::TEXT_SECONDARY),
        ]
        .spacing(theme::SPACE_4)
        .padding(iced::Padding {
            bottom: theme::PAD_12,
            ..iced::Padding::ZERO
        })
        .into()
    };

    let diff_content: Element<'_, diff::DiffMessage> = diff_state.view();
    let inner = column![header, diff_content.map(Message::DiffModal)].spacing(0);

    modal_overlay(inner, Message::CloseDiffModal)
}

// ── Ticket sidebar (Home page, right side) ────────────────────────

/// Ticket sidebar shown on the right side of the Home page.
/// Displays all non-archived tickets grouped by phase. A right-click
/// context menu on this panel offers "Archive done & cancelled".
fn ticket_sidebar(board_state: &board::BoardState) -> Element<'_, Message> {
    let search_active = !board_state.search_query.text().is_empty();

    // ── Search input row ───────────────────────────────────────────
    let search_input = widgets::single_line_editor(
        &board_state.search_query.buffer,
        "Search tickets…",
        false,
        Length::Fill,
        Some(iced::widget::Id::new("board_ticket_search")),
        |action| Message::Board(board::BoardMessage::SearchInputChanged(action)),
    );
    let clear_btn = widgets::icon_tooltip_button(
        text("×").size(theme::TEXT_14),
        "clear search",
        Some(Message::Board(board::BoardMessage::SearchCleared)),
        theme::PAD_4,
        theme::button_text,
        tooltip::Position::Top,
    );
    let mut search_row_children: Vec<Element<'_, Message>> = Vec::with_capacity(2);
    search_row_children.push(search_input);
    if search_active {
        search_row_children.push(clear_btn);
    }
    let search_row = Row::with_children(search_row_children)
        .spacing(theme::SPACE_4)
        .padding([0.0, theme::PAD_8])
        .align_y(Alignment::Center);

    // ── Body: search results or normal ticket groups ────────────────
    let body: Element<'_, Message> = if search_active {
        render_search_results(board_state)
    } else {
        render_normal_ticket_list(board_state)
    };

    let content = column![
        Space::new().height(8),
        search_row,
        Space::new().height(8),
        body,
    ]
    .spacing(0);

    container(content)
        .padding([theme::PAD_8, theme::PAD_4])
        .width(Length::Fill)
        .height(Length::Fill)
        .style(theme::surface_container_style)
        .into()
}

/// Hint line for empty/loading ticket-list states.
fn section_hint(label: &str) -> Element<'_, Message> {
    column![
        Space::new().height(8),
        text(label)
            .size(theme::TEXT_12)
            .color(theme::TEXT_SECONDARY),
    ]
    .spacing(theme::SPACE_4)
    .padding(theme::PAD_8)
    .into()
}

/// Render the normal ticket list partitioned into groups (In Progress,
/// Queued, Pending, Completed).
fn render_normal_ticket_list(board_state: &board::BoardState) -> Element<'_, Message> {
    // A failed list read must show the failure in the body itself — otherwise
    // a first failure renders "Loading…" forever and a later failure leaves a
    // stale list that looks current.
    if let Some(err) = board_state.load_state.error() {
        return widgets::error_banner(err);
    }

    let [in_progress, queued, pending, completed] =
        board::BoardState::board_sections(&board_state.tickets);

    let is_empty =
        in_progress.is_empty() && queued.is_empty() && pending.is_empty() && completed.is_empty();

    if !board_state.load_state.has_loaded() {
        section_hint("Loading…")
    } else if is_empty {
        section_hint("No tickets")
    } else {
        let mut groups = Column::new().spacing(theme::SPACE_8);
        if !in_progress.is_empty() {
            groups = groups.push(group_section("In Progress", &in_progress, board_state));
        }
        if !queued.is_empty() {
            groups = groups.push(group_section("Queued", &queued, board_state));
        }
        if !pending.is_empty() {
            groups = groups.push(group_section("Pending", &pending, board_state));
        }
        if !completed.is_empty() {
            groups = groups.push(group_section("Completed", &completed, board_state));
        }
        widgets::vscroll(groups)
    }
}

/// Render FTS search results as ticket cards in a scrollable list.
fn render_search_results(board_state: &board::BoardState) -> Element<'_, Message> {
    // A failed search must not render as "No matching tickets".
    if let Some(err) = board_state.search_error.as_deref() {
        return widgets::error_banner(err);
    }
    if board_state.search_results.is_empty() {
        section_hint("No matching tickets")
    } else {
        let mut cards = Column::new().spacing(theme::SPACE_2);
        for ticket in &board_state.search_results {
            cards = cards.push(board_state.render_ticket_card(ticket).map(Message::Board));
        }
        widgets::vscroll(cards)
    }
}

/// Render a group of tickets with a header label.
fn group_section<'a>(
    label: &'static str,
    tickets: &[&'a Ticket],
    board_state: &'a board::BoardState,
) -> Element<'a, Message> {
    let header = text(label)
        .size(theme::TEXT_11)
        .color(theme::TEXT_SECONDARY);

    let mut cards = Column::new().spacing(theme::SPACE_2);
    for ticket in tickets {
        cards = cards.push(board_state.render_ticket_card(ticket).map(Message::Board));
    }

    column![header, Space::new().height(4), cards]
        .spacing(0)
        .into()
}

impl Dashboard {
    pub fn subscription(&self) -> iced::Subscription<Message> {
        // Window events are subscribed from the start, before boot completes —
        // a close request included: it must reach the dashboard in every state
        // (see `request_exit`). Pre-boot Resized/Moved events update
        // last_size/last_position, which are persisted to window-state.json on
        // close — without them, closing a never-resized window would overwrite
        // the restored geometry with the hardcoded defaults (iced does not
        // replay missed window events).
        //
        // The platform's quit requests are subscribed from the start for the
        // same reason: the platform can ask before boot has finished.
        let always_on = iced::Subscription::batch([
            window::resize_events()
                .map(|(id, size)| Message::WindowEvent(id, window::Event::Resized(size))),
            window::events().filter_map(|(id, event)| match &event {
                window::Event::Moved(_) => Some(Message::WindowEvent(id, event)),
                // The window is created after this subscription is registered, so
                // its first `Opened` event arrives here. Windows needs the id it
                // carries: it is the window's handle, and the taskbar/Alt-Tab icon
                // has to be attached to it (see `crate::app_icon`).
                #[cfg(target_os = "windows")]
                window::Event::Opened { .. } => Some(Message::WindowOpened(id)),
                _ => None,
            }),
            window::close_requests().map(Message::CloseRequested),
            iced::Subscription::run(quit_requests_subscription),
        ]);
        if !self.ready {
            return always_on;
        }
        iced::Subscription::batch([
            always_on,
            keyboard::listen().filter_map(|event| {
                use keyboard::Key;
                let (key, modifiers, physical_key) = parse_key_press(event)?;
                let km = detect_keyboard_mods(modifiers);

                let latin = key.to_latin(physical_key);
                // Cmd+F (macOS) / Ctrl+F (other) → focus search.
                if !km.altgr_active && km.is_cmd && !modifiers.shift() && latin == Some('f') {
                    return Some(Message::FocusSearch);
                }
                if let Key::Named(iced::keyboard::key::Named::Escape) = key {
                    Some(Message::EscapePressed)
                } else if km.is_cmd && !km.altgr_active {
                    // Cmd+number → navigate to page.
                    if let Some(digit) = latin.and_then(|c| c.to_digit(10)) {
                        let idx = digit as usize;
                        if idx >= 1 {
                            let pages = Page::sidebar_pages();
                            if let Some(page) = pages.get(idx - 1).copied() {
                                return Some(Message::Navigation(page));
                            }
                        }
                    }
                    None
                } else {
                    None
                }
            }),
            self.shell_state.subscription().map(Message::Shell),
            self.logs_state.subscription().map(Message::Logs),
            // The editor is a workspace-scoped page: while nothing is resolved
            // its page is not shown, so it is given no subscription at all — no
            // tick, no tree ping and no shortcut may act on the workspace it
            // still holds in memory (its tabs are deliberately kept).
            if self.page_available(Page::Editor) {
                self.editor_state
                    .subscription(self.overlay_modal_open())
                    .map(Message::Editor)
            } else {
                iced::Subscription::none()
            },
            self.home_state.subscription().map(Message::Home),
            // The Alarms page and the Settings page's custom-tools area re-read
            // their source while they are shown; the tick is page-gated so a
            // page nobody is looking at reads nothing.
            match self.page {
                Page::Alarms => iced::time::every(common::POLLED_LIST_REFRESH_INTERVAL)
                    .map(|_| Message::Alarms(alarms::AlarmsMessage::Tick)),
                Page::Settings => {
                    iced::time::every(common::POLLED_LIST_REFRESH_INTERVAL).map(|_| {
                        Message::Settings(settings::SettingsMessage::CustomToolsMsg(
                            custom_tools::CustomToolsMessage::Tick,
                        ))
                    })
                }
                _ => iced::Subscription::none(),
            },
            iced::Subscription::run(shutdown_subscription),
            // Git file-change subscription: drives the event-driven local git
            // footer refresh when workspace files change.
            iced::Subscription::run(git_file_changes_subscription),
            // Git pipeline-commit subscription: refreshes the footer promptly
            // after a pipeline auto-commit (ref-only change the watcher misses).
            iced::Subscription::run(git_commit_subscription),
            // Standalone 60s remote-sync subscription (replaces the tick duty;
            // also the recovery path for ref-only/commit-only changes).
            iced::time::every(git::REMOTE_REFRESH_INTERVAL)
                .map(|_| Message::Git(git::GitMessage::PeriodicSyncTick)),
            // Board change-stream subscription: drives the board ticket list from
            // CDC deltas instead of a 1s full re-poll.
            iced::Subscription::run(board_change_subscription),
            // Workspaces change-stream subscription: a full map reload whenever
            // a workspaces row changes (or the stream lags / the baseline fires).
            iced::Subscription::run(workspaces_cdc_subscription),
            // Users / user_channels change-stream subscriptions: re-list the
            // Settings users page when a users/user_channels row changes (or
            // the stream lags — full re-list is its own recovery).
            iced::Subscription::run(users_cdc_subscription),
            iced::Subscription::run(user_channels_cdc_subscription),
            // Runtime-change subscription: coalesces agent/non-agent registry,
            // live transcript, and voice-status broadcasts into a single
            // re-render, driving the Running Agents page and footer.
            iced::Subscription::run(runtime_change_subscription),
            // TTS download progress subscription (always active while ready).
            #[cfg(target_os = "macos")]
            iced::Subscription::run(tts_download_subscription).map(Message::TtsDownloadEvent),
            // Diff modal subscription (keyboard shortcuts, auto-refresh).
            // Only active when the modal is open to avoid intercepting
            // global keyboard shortcuts unnecessarily.
            if self.show_diff_modal {
                self.diff_state.subscription().map(Message::DiffModal)
            } else {
                iced::Subscription::none()
            },
        ])
    }
}

/// Subscription that emits [`Message::Shutdown`] when the global shutdown
/// token fires (self-update restart, SIGTERM/SIGINT, the end of a drain), and
/// [`Message::DrainStarted`] when the graceful-drain window begins (first
/// signal / window-close / quit / self-update) — the token does NOT fire on the
/// first signal, so the GUI needs a separate drain signal to disable input
/// while the drain runs.
fn shutdown_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    iced::stream::channel(1, |mut output: mpsc::Sender<Message>| async move {
        let token = crate::shutdown::shutdown_token();
        // Wait for the drain flag OR the token (a drain always precedes the
        // token in the two-signal protocol, but the token may fire without a
        // drain on force-cancel paths).
        tokio::select! {
            () = crate::shutdown::drain_wait() => {
                let _ = output.try_send(Message::DrainStarted);
            }
            () = token.cancelled() => {}
        }
        token.cancelled().await;
        let _ = output.try_send(Message::Shutdown);
    })
}

/// Record `route` as the exit route, where the ask has wording of its own — a platform quit passes
/// its label, a window close passes `None`, and this is the one home of the rule that `None` leaves
/// the record alone. Nothing is shown for it (the exit path's line is dropped with the iced
/// runtime — see `shutdown::EXIT_TRIGGER`), so it is set for accuracy, not for reporting.
fn record_exit_route(route: Option<&'static str>) {
    if let Some(route) = route {
        crate::shutdown::record_exit_trigger(route);
    }
}

/// Subscription that turns an ordinary quit the platform's own application machinery delivered
/// — one of the asks [`Message::QuitRequested`] names — into that message.
///
/// The source is the process-lifetime channel the quit source fills
/// ([`crate::shutdown::install_stop_request_sources`], called before the iced application runs).
fn quit_requests_subscription() -> impl futures_util::Stream<Item = Message> {
    use futures_util::SinkExt;
    use iced::futures::channel::mpsc;
    iced::stream::channel(1, |mut output: mpsc::Sender<Message>| async move {
        let Some(mut requests) = crate::shutdown::take_quit_requests() else {
            return;
        };
        while requests.recv().await.is_some() {
            // Backpressure, not a dropped request: the next quit gesture during a drain is
            // what forces the exit, so it must not be lost to a full channel.
            if output.send(Message::QuitRequested).await.is_err() {
                return;
            }
        }
    })
}

/// Subscription that emits [`crate::audio::tts::TtsDownloadEvent`]s from the global
/// TTS download broadcast channel, forwarded as [`Message::TtsDownloadEvent`].
///
/// Unlike the hand-rolled channel loop this replaces, an uninitialized
/// `DOWNLOAD_EVENTS` source yields an empty stream instead of panicking
/// (unreachable in practice — `tts::init_global` precedes GUI startup).
#[cfg(target_os = "macos")]
fn tts_download_subscription()
-> impl futures_util::Stream<Item = crate::audio::tts::TtsDownloadEvent> {
    use iced::futures::channel::mpsc;
    common::broadcast_stream_producer(
        1,
        &crate::audio::tts::DOWNLOAD_EVENTS,
        |output: &mut mpsc::Sender<crate::audio::tts::TtsDownloadEvent>,
         event: Option<crate::audio::tts::TtsDownloadEvent>| {
            Box::pin(async move {
                // Best-effort delivery: drop events if the GUI channel is full;
                // lagged progress slots are dropped (next event is current state).
                if let Some(event) = event {
                    let _ = output.try_send(event);
                }
            })
        },
    )
}

/// Subscription that emits [`Message::RuntimeChanged`] (coalesced) when any
/// runtime source the GUI renders directly changes: agent/non-agent registries,
/// live transcript content, or voice status. The [`RuntimeEvent`] broadcast is
/// initialized in `main` before the iced application runs (matching the
/// [`LOG_BROADCAST`] convention); an uninitialized source would yield an
/// immediately-ending stream, which iced's subscription tracker does not
/// re-spawn. A burst of per-message / per-tool-call events collapses into a
/// single trailing [`Message::RuntimeChanged`] per [`RUNTIME_REFRESH_COALESCE`]
/// window — only "something changed" matters for a re-render.
fn runtime_change_subscription() -> impl futures_util::Stream<Item = Message> {
    common::coalesced_broadcast_producer(
        128,
        &crate::runtime_events::RUNTIME_EVENTS,
        RUNTIME_REFRESH_COALESCE,
        || Message::RuntimeChanged,
    )
}

/// Subscription that emits [`Message::Git`] with [`GitMessage::FileChanged`]
/// when workspace files change. Filesystem events are delivered by the
/// fff-search watcher on a dedicated thread (which only does a non-blocking
/// broadcast send) and consumed here to drive the event-driven git local
/// refresh. The broadcast is initialized in `main` before the iced application
/// runs (matching the [`LOG_BROADCAST`] convention); an uninitialized source
/// would yield an immediately-ending stream, which iced's subscription tracker
/// does not re-spawn.
fn git_file_changes_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    common::broadcast_stream_producer(
        1,
        &git::FILE_CHANGE_TX,
        |output: &mut mpsc::Sender<Message>, event: Option<()>| {
            Box::pin(async move {
                if event.is_some() {
                    let _ = output.try_send(Message::Git(git::GitMessage::FileChanged));
                }
            })
        },
    )
}

/// Subscription that emits [`Message::Git`] with
/// [`GitMessage::PipelineCommit`] when a pipeline auto-commit completes. A
/// commit is a ref-only change the file watcher never reports, so the footer
/// is refreshed promptly via [`GitState`]`s path-matched handler.
fn git_commit_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    common::broadcast_stream_producer(
        1,
        &crate::git::commands::GIT_COMMIT_TX,
        |output: &mut mpsc::Sender<Message>, event: Option<std::path::PathBuf>| {
            Box::pin(async move {
                if let Some(path) = event {
                    let _ = output.try_send(Message::Git(git::GitMessage::PipelineCommit(path)));
                }
            })
        },
    )
}

/// Subscription that emits [`BoardMessage::TicketChanged`] deltas from the
/// CDC change stream, and [`BoardMessage::BoardRefreshNeeded`] on a lagged
/// channel (a delta was lost — force a full snapshot refresh). The change
/// source is the shared [`crate::db::cdc`] tickets sender, initialised before
/// the iced app runs via [`crate::gui::init_board_change_tx`]; an uninitialized
/// source would yield an immediately-ending stream (Iced does not re-spawn it),
/// so the warm-up in `main` is required for the board to receive any delta.
fn board_change_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    common::broadcast_stream_producer(
        128,
        crate::db::cdc::ticket_sender_lock(),
        |output: &mut mpsc::Sender<Message>, event: Option<crate::db::cdc::ChangeEvent>| {
            Box::pin(async move {
                // Awaited send (backpressure): a full/lagged channel triggers a
                // refresh rather than silently dropping a delta.
                let msg = Message::Board(match event {
                    Some(ev) => board::BoardMessage::TicketChanged(Box::new(ev)),
                    None => board::BoardMessage::BoardRefreshNeeded,
                });
                let _ = futures_util::SinkExt::send(output, msg).await;
            })
        },
    )
}

/// Subscription that emits [`Message::WorkspacesCdcChanged`] for a full
/// workspace-map reload. The source is the shared [`crate::db::cdc`] workspaces
/// sender, warmed in `main` before the iced app runs (same immediately-ending-
/// stream rationale as the board sender — Iced does not re-spawn an ended
/// subscription).
///
/// The stream opens with one synthetic BASELINE event, so a full read happens
/// at stream start regardless of upstream activity. Because this subscription
/// only exists in the post-boot (`ready`) branch of [`Dashboard::subscription`],
/// the baseline is delivered after the `Boot` arm has set `ready` — it can
/// never be swallowed by the pre-boot no-op catch-all. Every received delta AND
/// a lagged channel map to the same message (a full reload is its own Lagged
/// recovery).
fn workspaces_cdc_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    futures_util::stream::once(async { Message::WorkspacesCdcChanged }).chain(
        common::broadcast_stream_producer(
            128,
            crate::db::cdc::workspace_sender_lock(),
            |output: &mut mpsc::Sender<Message>, _event: Option<crate::db::cdc::ChangeEvent>| {
                Box::pin(async move {
                    // Awaited send (backpressure): a dropped reload trigger
                    // would leave the sidebar stale until the next event.
                    let _ =
                        futures_util::SinkExt::send(output, Message::WorkspacesCdcChanged).await;
                })
            },
        ),
    )
}

/// Subscription that emits [`Message::UsersCdcChanged`] when a users-table row
/// changes or the stream lags. Both map to the same message: the full users
/// re-list and the DB read-back of the active workspace (the same single choice
/// the chat's switcher writes) that follow are each their own recovery.
///
/// The stream opens with one synthetic BASELINE event, like
/// [`workspaces_cdc_subscription`]: a switch written between the boot selection
/// read and this subscription's first poll would otherwise be missed for the
/// rest of the run, leaving the dashboard showing a project the account no
/// longer has active. The subscription only exists in the post-boot (`ready`)
/// branch of [`Dashboard::subscription`], so the baseline can never be
/// swallowed by the pre-boot no-op catch-all. Source is the shared
/// [`crate::db::cdc`] users sender, warmed in `main` before the iced app runs.
fn users_cdc_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    futures_util::stream::once(async { Message::UsersCdcChanged }).chain(
        common::broadcast_stream_producer(
            128,
            crate::db::cdc::users_sender_lock(),
            |output: &mut mpsc::Sender<Message>, _event: Option<crate::db::cdc::ChangeEvent>| {
                Box::pin(async move {
                    // Awaited send: a dropped trigger would leave the list stale
                    // until the next event (same rationale as the board stream).
                    let _ = futures_util::SinkExt::send(output, Message::UsersCdcChanged).await;
                })
            },
        ),
    )
}

/// Subscription that emits [`Message::UsersCdcChanged`] when a user_channels
/// row changes or the stream lags — the Settings users page re-lists on either
/// (a channel bind/unbind updates the user_channels table). Source is the shared
/// [`crate::db::cdc`] user_channels sender, warmed in `main` before the iced app
/// runs.
fn user_channels_cdc_subscription() -> impl futures_util::Stream<Item = Message> {
    use iced::futures::channel::mpsc;
    common::broadcast_stream_producer(
        128,
        crate::db::cdc::user_channels_sender_lock(),
        |output: &mut mpsc::Sender<Message>, _event: Option<crate::db::cdc::ChangeEvent>| {
            Box::pin(async move {
                // Awaited send: a dropped trigger would leave the list stale
                // until the next event (same rationale as the board stream).
                let _ = futures_util::SinkExt::send(output, Message::UsersCdcChanged).await;
            })
        },
    )
}

// ── Navigation sidebar ──────────────────────────────────────────

/// Map a [`Page`] variant to its corresponding Lucide icon element, unstyled so
/// each call site sizes and colors it.
///
/// Exhaustive match — adding a new `Page` variant produces a compile error
/// until its icon is assigned here.
fn page_icon(page: Page) -> iced::widget::Text<'static, iced::Theme, iced::Renderer> {
    match page {
        Page::Home => lucide::layout_dashboard::<iced::Theme, iced::Renderer>(),
        Page::Editor => lucide::pencil_line::<iced::Theme, iced::Renderer>(),
        Page::Shell => lucide::terminal::<iced::Theme, iced::Renderer>(),
        Page::Sessions => lucide::scroll_text::<iced::Theme, iced::Renderer>(),
        Page::Alarms => lucide::bell::<iced::Theme, iced::Renderer>(),
        Page::Logs => lucide::activity::<iced::Theme, iced::Renderer>(),
        Page::Settings => lucide::settings::<iced::Theme, iced::Renderer>(),
        Page::RunningAgents => lucide::radar::<iced::Theme, iced::Renderer>(),
    }
}

/// Stand-in for a workspace-scoped page while no workspace is resolved. Such a
/// page is absent from the navigation then, so it is reachable only by a
/// keyboard shortcut — and it must show no workspace content at all.
fn unresolved_workspace_page(page: Page) -> Element<'static, Message> {
    widgets::empty_state_placeholder(
        page_icon(page),
        "Select a workspace to open this page",
        theme::TEXT_MUTED,
    )
}

impl Dashboard {
    fn sidebar_view(&self) -> Element<'_, Message> {
        let col = column![
            self.render_sidebar_nav(),
            Space::new().height(Length::Fill),
            self.render_sidebar_bottom_nav(),
        ];
        container(col.spacing(theme::SPACE_2))
            .width(Length::Fixed(56.0))
            .height(Length::Fill)
            .style(theme::surface_container_style)
            .padding(theme::PAD_4)
            .into()
    }

    /// Shared nav-icon column for the sidebar top and bottom navs. Each page is
    /// a 48px-tall full-width icon button (28px icon) with the active page
    /// accent-colored; a page that is not available ([`Self::page_available`]) is
    /// absent from the column entirely.
    ///
    /// Uses Position::Right — iced snaps Top tooltips into the viewport,
    /// overlapping the topmost sidebar button.
    fn sidebar_nav_column(&self, pages: &[Page]) -> Column<'_, Message> {
        let mut col = Column::new().spacing(theme::SPACE_2);
        for page in pages {
            if !self.page_available(*page) {
                continue;
            }
            let color = if self.page == *page {
                theme::ACCENT
            } else {
                theme::TEXT_MUTED
            };
            // The container's generous vertical padding gives the button a large
            // hit area within the fixed 56px rail.
            col = col.push(
                tooltip(
                    button(
                        container(page_icon(*page).size(28).color(color))
                            .width(Length::Fill)
                            .center_x(Length::Fill)
                            .padding([theme::PAD_10, 0.0]),
                    )
                    .width(Length::Fill)
                    .padding(0)
                    .style(theme::button_text)
                    .on_press(Message::Navigation(*page)),
                    text(page.label()).size(theme::TEXT_11),
                    tooltip::Position::Right,
                )
                .style(theme::tooltip_style),
            );
        }
        col
    }

    /// Sidebar top nav icons (see [`Page::sidebar_pages`]). Running Agents
    /// is not in the sidebar — it is reachable only via the footer activity
    /// indicators.
    fn render_sidebar_nav(&self) -> Element<'_, Message> {
        self.sidebar_nav_column(Page::sidebar_pages()).into()
    }

    /// Sidebar bottom nav icons (see [`Page::sidebar_bottom_pages`]) —
    /// click-only, no keyboard shortcut.
    fn render_sidebar_bottom_nav(&self) -> Element<'_, Message> {
        self.sidebar_nav_column(Page::sidebar_bottom_pages()).into()
    }

    /// Footer per-workspace Maintainer toggle icon button.
    fn render_maintainer_toggle(&self) -> Element<'_, Message> {
        let enabled = self.maintenance_enabled();
        let icon: Element<'_, Message> = theme::role_icon(&Role::Maintainer)
            .size(theme::TEXT_24)
            .color(if enabled {
                theme::ACCENT
            } else {
                theme::TEXT_MUTED
            })
            .into();
        widgets::icon_tooltip_button(
            icon,
            if enabled {
                "stop maintenance"
            } else {
                "start maintenance"
            },
            Some(Message::Toggle(ToggleKind::Maintenance)),
            theme::PAD_3,
            theme::button_text,
            tooltip::Position::Top,
        )
    }

    /// Footer per-workspace pipeline pause/unpause toggle icon button.
    fn render_pause_toggle(&self) -> Element<'_, Message> {
        let paused = self.paused();
        let icon: Element<'_, Message> = if paused {
            lucide::play::<iced::Theme, iced::Renderer>()
                .size(24)
                .color(theme::ACCENT)
                .into()
        } else {
            lucide::pause::<iced::Theme, iced::Renderer>()
                .size(24)
                .color(theme::TEXT_MUTED)
                .into()
        };
        let tooltip_text = if paused {
            "Resume pipeline"
        } else {
            "Pause pipeline"
        };
        widgets::icon_tooltip_button(
            icon,
            tooltip_text,
            Some(Message::Toggle(ToggleKind::Pause)),
            theme::PAD_3,
            theme::button_text,
            tooltip::Position::Top,
        )
    }

    /// The failure the footer picker must show in place of its dropdown: a
    /// failed workspace-map read that left nothing to pick. A read that failed
    /// but preserved a usable map keeps the working picker — the Settings
    /// workspace list shows that failure.
    fn picker_failure<'a>(&'a self, options: &[widgets::PickOption]) -> Option<&'a str> {
        if options.is_empty() {
            self.workspaces_error.as_deref()
        } else {
            None
        }
    }

    /// Footer workspace picker: shared workspaces only, persists via
    /// [`Self::select_workspace`]. With a single shared workspace the
    /// dropdown degrades to a static label (that workspace's display name,
    /// or the "Select workspace" placeholder when nothing is selected —
    /// including a Personal/unset selection). When a failed workspace-map read
    /// leaves nothing to pick, a static, non-selectable "Workspaces
    /// unavailable" pill replaces it in the same footprint. Returns `None` for
    /// the zero-shared-workspaces state.
    fn render_workspace_picker(&self) -> Option<Element<'_, Message>> {
        // Nothing left to pick: the failed read renders a static, non-selectable
        // failure pill in the picker's footprint. The error text lives only in
        // the tooltip — it must never become an option of the dropdown.
        let options = shared_workspace_options(&self.workspaces);
        if let Some(err) = self.picker_failure(&options) {
            return Some(widgets::tooltip_hint(
                container(
                    text("Workspaces unavailable")
                        .size(theme::TEXT_14)
                        .color(theme::STATUS_ERROR),
                )
                .width(Length::Fixed(140.0))
                .padding([theme::PAD_4, theme::PAD_8])
                .style(theme::pill_style(theme::STATUS_ERROR.scale_alpha(0.08))),
                err,
            ));
        }
        if options.is_empty() {
            // No shared workspaces exist — an inert placeholder dropdown would
            // suggest a choice that isn't there; hide the picker instead.
            return None;
        }
        if options.len() == 1 {
            // A one-option dropdown offers no choice; render the sole
            // workspace as a static label (140px, matching the dropdown's
            // footprint so the footer chrome doesn't shift).
            let sole = &options[0];
            let label = if self.active_workspace_name().as_deref() == Some(sole.value.as_str()) {
                sole.label.clone()
            } else {
                "Select workspace".to_string()
            };
            return Some(widgets::tooltip_hint(
                container(text(label).size(theme::TEXT_14).color(theme::TEXT_PRIMARY))
                    .width(Length::Fixed(140.0))
                    .padding([theme::PAD_4, theme::PAD_8])
                    .style(theme::pill_style(theme::BG_ELEVATED)),
                "Active workspace",
            ));
        }
        // Guard the displayed selection: a dangling persisted value (the
        // workspace vanished from the map) renders no highlight; a personal
        // selection (`active_workspace_name()` → None) renders the placeholder.
        let selected = self
            .active_workspace_name()
            .and_then(|name| options.iter().find(|o| o.value == name).cloned());
        Some(widgets::tooltip_hint(
            pick_list(options, selected, |opt| Message::WorkspacePick(opt.value))
                .placeholder("Select workspace")
                .style(theme::pick_list_style)
                .menu_style(theme::pick_list_menu_style)
                .padding([theme::PAD_4, theme::PAD_8])
                .width(Length::Fixed(140.0)),
            "Active workspace",
        ))
    }

    /// Render the self-update confirmation modal (opened by
    /// [`Message::UpdateBot`], confirmed by [`Message::ConfirmUpdate`]).
    /// Returns a type-stable placeholder when closed.
    ///
    /// The text truthfully reflects the real sequence for this copy: the update
    /// runs in the background while the system keeps working — nothing is paused
    /// during it — then in-flight work drains, databases are checkpointed, and the
    /// app restarts and resumes work automatically. The window closing is the
    /// success signal.
    fn render_update_confirm(&self) -> Element<'_, Message> {
        if !self.show_update_confirm {
            // Keep the Stack widget type stable across open/close transitions
            // (see `empty_stack_placeholder`): the open state is a Stack.
            return iced::widget::stack([widgets::empty_stack_placeholder()]).into();
        }
        let mode_desc = match crate::self_update::update_mode() {
            crate::self_update::UpdateMode::Downloaded => {
                "The ready-made file for this system is downloaded in the background \
                 while the system keeps working, and put at the standard location: it \
                 replaces the file this copy runs from when that is already where it \
                 sits, and for a copy running from anywhere else it is placed there \
                 while the file it came from is taken away. Nothing is paused during \
                 it.\n\n\
                 When it is in place, current in-flight work is drained (up to \
                 ~10 min), databases are checkpointed, and the app restarts from \
                 the standard location, automatically resuming work afterwards. \
                 The window closing signals the restart."
            }
            crate::self_update::UpdateMode::SourceTree => {
                "The new version is built from this working tree in the \
                 background while the system keeps working — the build can take \
                 10–60 minutes and nothing is paused during it.\n\n\
                 When the build finishes, current in-flight work is drained \
                 (up to ~10 min), databases are checkpointed, and the app \
                 restarts, automatically resuming work afterwards. The window \
                 closing signals the restart."
            }
        };
        widgets::modal_backdrop(
            dialog::confirm_dialog(
                dialog::dialog_title("Update MahBot?"),
                dialog::dialog_body([mode_desc]),
                [
                    dialog::DialogAction::secondary("Cancel", Message::CancelUpdate),
                    dialog::DialogAction::secondary("Update", Message::ConfirmUpdate),
                ],
            ),
            Message::CancelUpdate,
            0.5,
        )
    }

    /// Render the self-update button in the footer bar.
    /// Returns `None` when self-update is not available on this installation.
    ///
    /// Visibility is driven entirely by the shared availability cache — no
    /// platform gate is needed: a downloaded copy finds and puts this system's
    /// ready-made file at the standard location on every platform, and replacing a
    /// file that is in use there is the platform's own rename-aside, so a running
    /// copy is never in the way.
    fn render_update_button() -> Option<Element<'static, Message>> {
        let availability = crate::self_update::update_availability();
        // Show the button while an update is in flight even if `available` was
        // transiently clobbered, so "Updating…" is never hidden mid-update.
        if !availability.available && !availability.in_progress {
            return None;
        }
        let (update_color, tooltip_text, clickable) = if availability.in_progress {
            (theme::TEXT_FAINT, "Updating…".to_string(), false)
        } else {
            let tooltip = match crate::self_update::update_latest() {
                Some(v) => format!("Update MahBot to v{v}"),
                None => "Update MahBot".to_string(),
            };
            (theme::ACCENT, tooltip, true)
        };
        let update_icon = lucide::refresh_cw::<iced::Theme, iced::Renderer>()
            .size(theme::TEXT_24)
            .color(update_color);
        Some(widgets::icon_tooltip_button(
            update_icon,
            tooltip_text,
            if clickable {
                Some(Message::UpdateBot)
            } else {
                None
            },
            theme::PAD_3,
            theme::button_text,
            tooltip::Position::Top,
        ))
    }

    /// Vertical divider between the footer activity chrome and git blocks.
    fn render_git_divider() -> Element<'static, Message> {
        rule::vertical(1)
            .style(|_: &iced::Theme| rule::Style {
                color: theme::TEXT_MUTED,
                radius: 0.0.into(),
                fill_mode: rule::FillMode::Padded(8),
                snap: true,
            })
            .into()
    }

    /// Render the current git branch button (clickable -> branch modal).
    /// Returns `None` when no branch is known.
    fn render_git_branch(&self) -> Option<Element<'_, Message>> {
        let b = self.git_state.current_branch()?;
        let truncated = if b.len() > 20 {
            format!("{}…", crate::util::truncate_bytes(b, 19))
        } else {
            b.to_string()
        };
        let branch_content = row![
            lucide::git_branch::<iced::Theme, iced::Renderer>()
                .size(theme::TEXT_24)
                .color(theme::ACCENT),
            text(truncated).size(theme::TEXT_16).color(theme::ACCENT),
        ]
        .spacing(theme::SPACE_6)
        .align_y(Alignment::Center);
        Some(widgets::icon_tooltip_button(
            branch_content,
            "active branch",
            Some(Message::Git(git::GitMessage::OpenModal)),
            theme::PAD_3,
            theme::button_text,
            tooltip::Position::Top,
        ))
    }

    /// Render the git sync indicator (behind/ahead counts, clickable).
    /// Uses lucide arrow_up/arrow_down at 16px (same as the number text) so
    /// all elements share the same vertical baseline.
    /// Returns `None` when there are no behind/ahead counts or both are zero.
    fn render_git_sync(&self) -> Option<Element<'_, Message>> {
        let (behind, ahead) = self.git_state.behind_ahead()?;
        if behind == 0 && ahead == 0 {
            return None;
        }
        // Build arrow+number text using lucide icons (not Unicode arrows)
        // so all elements share the same vertical baseline.
        let sync_text_label: Element<'_, Message> = {
            let mut parts: Vec<Element<'_, Message>> = Vec::new();
            if ahead > 0 {
                parts.push(
                    lucide::arrow_up::<iced::Theme, iced::Renderer>()
                        .size(theme::TEXT_16)
                        .color(theme::TEXT_SECONDARY)
                        .into(),
                );
                parts.push(
                    text(format!("{ahead}"))
                        .size(theme::TEXT_16)
                        .color(theme::TEXT_SECONDARY)
                        .into(),
                );
            }
            if behind > 0 {
                if ahead > 0 {
                    parts.push(Space::new().width(theme::SPACE_8).into());
                }
                parts.push(
                    lucide::arrow_down::<iced::Theme, iced::Renderer>()
                        .size(theme::TEXT_16)
                        .color(theme::TEXT_SECONDARY)
                        .into(),
                );
                parts.push(
                    text(format!("{behind}"))
                        .size(theme::TEXT_16)
                        .color(theme::TEXT_SECONDARY)
                        .into(),
                );
            }
            Row::with_children(parts)
                .spacing(theme::SPACE_2)
                .align_y(Alignment::Center)
                .into()
        };
        Some(widgets::icon_tooltip_button(
            sync_text_label,
            "sync commits pull and push",
            if self.git_state.is_syncing() {
                None
            } else {
                Some(Message::Git(git::GitMessage::Sync))
            },
            theme::PAD_3,
            theme::button_text,
            tooltip::Position::Top,
        ))
    }

    /// Render the git diff stats button (+X/−Y, clickable -> diff modal).
    /// Returns `None` when there are no non-zero changes (including no
    /// oversized/binary untracked files to report).
    fn render_git_diff_stats(&self) -> Option<Element<'_, Message>> {
        let stats = self.git_state.diff_stats()?;
        Some(widgets::icon_tooltip_button(
            widgets::git_footer_stats::<Message>(
                stats.added,
                stats.removed,
                stats.huge_binary_file_count,
                15.0,
            )?,
            "uncommitted changes",
            Some(Message::OpenDiffModal(None)),
            theme::PAD_3,
            theme::button_text,
            tooltip::Position::Top,
        ))
    }

    /// Render the git block: divider, branch, sync, and diff stats.
    ///
    /// `None` while nothing is resolved: the path that
    /// [`Self::sync_workspace_surfaces`] owns *is* the resolution.
    fn render_git_block(&self) -> Option<Element<'_, Message>> {
        if !self.git_state.has_filesystem_path() {
            return None;
        }
        let mut elements: Vec<Element<'_, Message>> = Vec::with_capacity(4);
        elements.push(Self::render_git_divider());
        if let Some(el) = self.render_git_branch() {
            elements.push(el);
        }
        if let Some(el) = self.render_git_sync() {
            elements.push(el);
        }
        if let Some(el) = self.render_git_diff_stats() {
            elements.push(el);
        }
        Some(
            Row::with_children(elements)
                .spacing(theme::SPACE_6)
                .align_y(Alignment::Center)
                .into(),
        )
    }

    /// Render the active agent icons in the right side of the footer.
    /// Returns `None` when no agents are running.
    ///
    /// Each role-icon indicator is a clickable button navigating to the
    /// Running Agents page; its tooltip carries the role name.
    fn render_active_agents() -> Option<Element<'static, Message>> {
        let handles = crate::agent::registry::AGENT_REGISTRY.list();
        let mut role_counts: std::collections::BTreeMap<&str, usize> =
            std::collections::BTreeMap::new();
        for h in &handles {
            *role_counts.entry(h.role.as_str()).or_insert(0) += 1;
        }
        if role_counts.is_empty() {
            return None;
        }
        let mut icons: Vec<Element<'_, Message>> = Vec::new();
        for (role_str, count) in &role_counts {
            let role: crate::Role = role_str.parse().unwrap_or(crate::Role::Engineer);
            let (color, _bg) = theme::role_badge_color_for(&role);
            let icon = theme::role_icon(&role).size(theme::TEXT_24).color(color);
            let content: Element<'_, Message> = if *count > 1 {
                container(
                    row![
                        icon,
                        text(format!("×{count}")).size(theme::TEXT_14).color(color)
                    ]
                    .spacing(theme::SPACE_3)
                    .align_y(Alignment::Center),
                )
                .padding([0.0, theme::PAD_3])
                .into()
            } else {
                container(icon).padding([0.0, theme::PAD_3]).into()
            };
            icons.push(widgets::icon_tooltip_button(
                content,
                role.display_label(),
                Some(Message::Navigation(Page::RunningAgents)),
                0,
                theme::button_text,
                tooltip::Position::Top,
            ));
        }
        Some(
            Row::with_children(icons)
                .spacing(theme::SPACE_12)
                .align_y(Alignment::Center)
                .into(),
        )
    }

    /// Render the in-flight non-agent LLM call counter next to the agent
    /// icons. Distinct marker (zap glyph in accent color); a tooltip lists
    /// the in-flight call kinds as human-readable labels. The whole indicator
    /// is a clickable button navigating to the Running Agents page.
    /// Returns `None` when none are in flight.
    fn render_non_agent_calls() -> Option<Element<'static, Message>> {
        let handles = crate::agent::registry::NON_AGENT_CALLS.list();
        if handles.is_empty() {
            return None;
        }
        let color = theme::ACCENT;
        let content = container(
            row![
                lucide::zap::<iced::Theme, iced::Renderer>()
                    .size(theme::TEXT_24)
                    .color(color),
                text(format!("×{}", handles.len()))
                    .size(theme::TEXT_14)
                    .color(color),
            ]
            .spacing(theme::SPACE_3)
            .align_y(Alignment::Center),
        )
        .padding([0.0, theme::PAD_3]);
        // Tooltip lists the in-flight kinds as static human-readable labels —
        // raw snake_case kind names never surface. Map to labels FIRST, then
        // dedup: two unknown kinds share the generic fallback label, so
        // deduping raw kinds first could repeat it.
        let mut labels: Vec<&str> = handles
            .iter()
            .map(|h| crate::agent::registry::call_kind_label(h.kind))
            .collect();
        labels.sort_unstable();
        labels.dedup();
        let tooltip_text = labels.join(", ");
        Some(widgets::icon_tooltip_button(
            content,
            tooltip_text,
            Some(Message::Navigation(Page::RunningAgents)),
            0,
            theme::button_text,
            tooltip::Position::Top,
        ))
    }

    /// Render the TTS download progress indicator in the centre of the footer bar.
    /// Shows the current file name and percentage (e.g. "duration_predictor.onnx 83%").
    #[cfg(target_os = "macos")]
    fn render_tts_download_progress(&self) -> Element<'_, Message> {
        let Some((file_name, progress)) = &self.tts_download_progress else {
            return Space::new().width(0).into();
        };
        #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let pct = (progress * 100.0).round() as u32;
        let label = format!("TTS: {file_name} {pct}%");
        footer_status_label(label)
    }

    /// Render a compact voice status indicator in the footer bar.
    ///
    /// Shows a compact indicator for every [`VoiceStatus`] variant except
    /// [`VoiceStatus::Disabled`] (which is hidden — voice is off).
    /// [`VoiceStatus::Error`] displays the actual error string rather than
    /// a hardcoded message.
    #[cfg(target_os = "macos")]
    fn render_voice_status() -> Element<'static, Message> {
        let label: String = match crate::audio::voice::get_status() {
            // Hidden when voice is disabled.
            VoiceStatus::Disabled => return Space::new().width(0).into(),
            VoiceStatus::LoadingModels => "🔊 Loading…".into(),
            VoiceStatus::ModelError => "🔊 ⚠ Model error".into(),
            VoiceStatus::Listening => "🔊 Listening".into(),
            VoiceStatus::Recording | VoiceStatus::RecordingManual => "🔊 Recording…".into(),
            VoiceStatus::Transcribing => "🔊 Transcribing…".into(),
            VoiceStatus::MicPermissionDenied => "🔊 No mic access".into(),
            VoiceStatus::MicDisconnected => "🔊 Mic disconnected".into(),
            VoiceStatus::Enrolling { sample, total, .. } => {
                format!("🔊 Enrolling {sample}/{total}")
            }
            VoiceStatus::ListeningDuringEnrollment { sample, total } => {
                format!("🔊 Listen… {sample}/{total}")
            }
            VoiceStatus::WaitingForSilenceDuringEnrollment { sample, total } => {
                format!("🔊 Wait… {sample}/{total}")
            }
            VoiceStatus::EnrollingNegatives {
                accumulated_secs,
                target_secs,
                ..
            } => {
                format!("🔊 Collecting negatives {accumulated_secs}s/{target_secs}s")
            }
            VoiceStatus::Enrolled => "🔊 ✅ Enrolled".into(),
            VoiceStatus::Error(msg) => format!("🔊 Error: {msg}"),
        };
        footer_status_label(label)
    }

    /// 42px footer bar — update/picker/toggle chrome (left) and active
    /// agents (right).
    fn footer_view(&self) -> Element<'_, Message> {
        let mut left_elements: Vec<Element<'_, Message>> = Vec::with_capacity(5);

        if let Some(el) = Self::render_update_button() {
            left_elements.push(el);
        }
        if let Some(el) = self.render_workspace_picker() {
            left_elements.push(el);
        }
        if self.has_active_workspace() {
            left_elements.push(self.render_maintainer_toggle());
            left_elements.push(self.render_pause_toggle());
        }
        if let Some(el) = self.render_git_block() {
            left_elements.push(el);
        }

        let left = Row::with_children(left_elements)
            .spacing(theme::SPACE_6)
            .align_y(Alignment::Center);

        // TTS download progress and voice status indicator (center of footer bar)
        #[cfg(target_os = "macos")]
        let center = row![
            self.render_tts_download_progress(),
            Self::render_voice_status(),
        ]
        .spacing(theme::SPACE_8)
        .align_y(Alignment::Center);
        // Off macOS there is no audio subsystem, so the centre slot collapses to
        // nothing — the footer row below is shared and stays untouched.
        #[cfg(not(target_os = "macos"))]
        let center = Space::new().width(0);

        let right = Row::with_children(
            [Self::render_active_agents(), Self::render_non_agent_calls()]
                .into_iter()
                .flatten()
                .collect::<Vec<_>>(),
        )
        .spacing(theme::SPACE_12)
        .align_y(Alignment::Center);

        let footer_row = row![left, center, Space::new().width(Length::Fill), right]
            .align_y(Alignment::Center)
            .padding([theme::PAD_3, theme::PAD_18]);

        container(footer_row)
            .align_y(Alignment::Center)
            .height(Length::Fixed(42.0))
            .width(Length::Fill)
            .style(theme::surface_container_style)
            .into()
    }
}

/// Muted 12px status label with side padding, shown in the centre of the footer bar.
#[cfg(target_os = "macos")]
fn footer_status_label(label: String) -> Element<'static, Message> {
    container(
        text(label)
            .size(theme::TEXT_12)
            .color(theme::TEXT_SECONDARY),
    )
    .padding([0.0, theme::PAD_12])
    .into()
}

/// Persisted window geometry.
#[derive(serde::Deserialize)]
pub struct WindowState {
    pub width: f32,
    pub height: f32,
    pub x: i32,
    pub y: i32,
}

impl WindowState {
    /// Position to use when restoring the window.
    #[expect(clippy::cast_precision_loss)]
    #[must_use]
    pub const fn position(&self) -> iced::window::Position {
        iced::window::Position::Specific(iced::Point::new(self.x as f32, self.y as f32))
    }
}

impl Default for WindowState {
    fn default() -> Self {
        Self {
            width: 1500.0,
            height: 800.0,
            x: -1,
            y: -1,
        }
    }
}

/// The window geometry file in the storage root.
const WINDOW_STATE_FILE: &str = "window-state.json";

/// Read persisted window state, falling back to defaults when it is missing or unreadable.
#[must_use]
pub fn read_window_state() -> WindowState {
    let Ok(dir) = crate::config::default_config_dir() else {
        return WindowState::default();
    };
    std::fs::read_to_string(dir.join(WINDOW_STATE_FILE))
        .ok()
        .and_then(|json| serde_json::from_str(&json).ok())
        .unwrap_or_default()
}

/// Save current window geometry.
#[expect(clippy::cast_possible_truncation)]
fn save_window_state(pos: iced::Point, size: iced::Size) {
    let state = serde_json::json!({
        "width": size.width,
        "height": size.height,
        "x": pos.x as i32,
        "y": pos.y as i32,
    });
    if let Ok(dir) = crate::config::default_config_dir() {
        let _ = std::fs::create_dir_all(&dir);
        let _ = std::fs::write(dir.join(WINDOW_STATE_FILE), state.to_string());
    }
}

/// Reload the full workspace map from the store after boot (CDC workspaces
/// event, stream lag, toggle completion, or a settings add/delete). The
/// [`Message::WorkspacesReloaded`] handler re-resolves the live selection at
/// apply time.
///
/// On a transient read failure — the one scoped retry in this reload path — it
/// retries once after a short delay; if the retry also fails, it returns
/// [`Message::WorkspacesReloadFailed`] so the current (non-empty) map is
/// preserved and the failure is rendered instead of silently vanishing.
async fn load_workspace_map(generation: u64) -> Message {
    // Transient read failure: retry once after a short delay, then report the
    // failure while keeping the current map.
    let mut attempt = 0;
    let workspaces = loop {
        match read_workspace_map().await {
            Ok(map) => break map,
            Err(e) => {
                tracing::warn!(error = %e, attempt = attempt + 1, "Failed to load workspaces");
                if attempt == 0 {
                    attempt += 1;
                    tokio::time::sleep(Duration::from_secs(1)).await;
                } else {
                    return Message::WorkspacesReloadFailed {
                        error: e.to_string(),
                        generation,
                    };
                }
            }
        }
    };
    Message::WorkspacesReloaded {
        workspaces,
        generation,
    }
}

/// Read the full workspace map from the store (one row per name).
async fn read_workspace_map() -> anyhow::Result<HashMap<String, Workspace>> {
    let list = crate::workspace::store().list().await?;
    Ok(list.into_iter().map(|ws| (ws.name.clone(), ws)).collect())
}

/// Resolve the restored workspace selection against a freshly loaded map:
/// the previous selection is kept when it still exists (a `personal:{user}`
/// name is never in the map, so it always falls through to the personal
/// default); anything else falls back to the "Personal" default (the admin's
/// `personal:{user}` name).
#[must_use]
fn resolve_workspace_selection(
    map: &HashMap<String, Workspace>,
    prev_selection: Option<&str>,
    personal_name: &str,
) -> String {
    match prev_selection {
        Some(name) if map.contains_key(name) => name.to_string(),
        _ => personal_name.to_string(),
    }
}

/// Load the full workspace map during boot and resolve the selected
/// workspace from the DB (`users.selected_workspace` for the admin — the
/// single source of truth) via the admin-aware
/// [`crate::users::resolve_selected_workspace_name`] primitive. Degrades to
/// the "Personal" default (`personal:admin`) when the stored value is
/// NULL/personal, the read fails, or the stored workspace is missing from the
/// map (the boot path must complete).
///
/// The read result travels to [`Dashboard::apply_boot_workspaces`] as-is: a
/// failed boot read still completes with an empty map, but the failure is
/// rendered by the workspace picker / Settings list instead of being
/// indistinguishable from an installation with no workspaces.
///
/// `generation` is captured when the read is dispatched and travels back with
/// it, so a reload that answered meanwhile supersedes this read.
async fn load_workspace_options(generation: u64) -> Message {
    let user = crate::users::ADMIN_USER_NAME;
    let prev = crate::users::resolve_selected_workspace_name(user).await;
    // The personal default is the admin's `personal:{user}` name.
    let personal_name = crate::users::personal_workspace_name(user);
    let (workspaces, restored) = match read_workspace_map().await {
        Ok(map) => {
            let restored = resolve_workspace_selection(&map, prev.as_deref(), &personal_name);
            (Ok(map), restored)
        }
        Err(e) => {
            tracing::warn!(error = %e, "Failed to load workspaces during boot");
            // A failed read leaves no map to resolve against, i.e. the Personal
            // default (nothing else can be selected from an unknown map).
            (Err(e.to_string()), personal_name)
        }
    };
    Message::BootWorkspaces {
        workspaces,
        restored_name: restored,
        generation,
    }
}

/// Read the admin's stored active workspace back from the DB (the admin-aware
/// resolution: a NULL/personal value yields the canonical `personal:{user}`
/// name). `None` — the read failed; the live selection is kept.
async fn read_active_workspace() -> Option<String> {
    crate::users::resolve_selected_workspace_name(crate::users::ADMIN_USER_NAME).await
}

/// Build the footer workspace picker options from the shared workspace map:
/// values sorted by name, labeled by each workspace's display name. A personal
/// workspace is never an option — a lingering `personal:{user}` row is filtered
/// out, so this picker and the chat's switcher offer the same set.
#[must_use]
fn shared_workspace_options(map: &HashMap<String, Workspace>) -> Vec<widgets::PickOption> {
    let mut values: Vec<&Workspace> = map
        .values()
        .filter(|ws| !crate::users::is_personal_workspace(&ws.name))
        .collect();
    values.sort_by(|a, b| a.name.cmp(&b.name));
    values
        .into_iter()
        .map(|ws| widgets::PickOption {
            value: ws.name.clone(),
            label: ws.display_name(),
        })
        .collect()
}

/// Open an address with the platform's own handler (fire-and-forget).
///
/// The address is handed over as data — never to something that reads it as a
/// command line.
fn open_url(url: &str) {
    #[cfg(target_os = "windows")]
    shell_open(url);

    #[cfg(target_os = "macos")]
    let _ = std::process::Command::new("open").arg(url).spawn();

    #[cfg(target_os = "linux")]
    let _ = std::process::Command::new("xdg-open").arg(url).spawn();

    // No other target has a handler to reach; this keeps `url` used there.
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let _ = url;
}

/// Hand an address to the Windows shell as a *data* argument.
///
/// `ShellExecuteExW` resolves the address against the registered protocol and
/// file associations, and takes it whole in `lpFile`, with `lpParameters` NULL
/// and `lpVerb` NULL (the system's default verb for the item — forcing `open`
/// would change what some addresses do). The address is therefore one opaque
/// value: `&`, `^`, `%`, `"`, `?`, `|` or a space in it is data, never a command,
/// a second command or an argument of one. `SEE_MASK_DOENVSUBST` is left out of
/// `fMask` too, so the shell does not expand a `%NAME%`-shaped address either.
///
/// The launch runs on a throw-away thread because `ShellExecuteExW` is a
/// synchronous shell call and `open_url` is called on the iced event-loop thread,
/// which must not wait on the shell. The thread is detached, so a process that
/// exits right after the click takes the launch with it.
///
/// An empty or whitespace-only address is not an address: it never reaches the
/// shell, because there is nothing to open and nothing may be launched for one.
#[cfg(target_os = "windows")]
fn shell_open(address: &str) {
    if address.trim().is_empty() {
        return;
    }
    let address = address.to_owned();
    // The NUL-terminated UTF-16 spelling the Win32 API takes; an interior NUL in
    // the address would end the string the shell sees there.
    let mut wide: Vec<u16> = address.encode_utf16().collect();
    wide.push(0);
    let spawned = std::thread::Builder::new()
        .name("shell-open".to_owned())
        .spawn(move || {
            if let Some(code) = shell_execute_address(&wide) {
                tracing::warn!(%address, code, "ShellExecuteExW did not open the address");
            }
        });
    if let Err(e) = spawned {
        tracing::warn!(error = %e, "Failed to spawn the thread that opens an address");
    }
}

/// One `ShellExecuteExW` call for the NUL-terminated UTF-16 `address`, on a
/// thread whose COM apartment has just been initialised for it. Returns the
/// `GetLastError` code when the shell did not open the address.
///
/// The apartment is the single-threaded one the API documents for itself (some
/// of the shell extensions it may activate require it). `SEE_MASK_NOASYNC` is
/// the one `fMask` flag the call needs: the API requires it of a caller without
/// a message loop that does not outlive the call. No `SEE_MASK_*` suppression
/// flag is set — whatever the shell shows for an address it cannot open is its
/// own, and the `GetLastError` code is logged alongside it.
#[cfg(target_os = "windows")]
fn shell_execute_address(address: &[u16]) -> Option<u32> {
    use windows_sys::Win32::Foundation::{FALSE, GetLastError};
    use windows_sys::Win32::System::Com::{
        COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, CoInitializeEx, CoUninitialize,
    };
    use windows_sys::Win32::UI::Shell::{SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW};
    use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;

    // `CoInitializeEx` takes the flags as an unsigned word, while `windows-sys`
    // types the constants as the signed `COINIT` alias.
    let coinit = u32::try_from(COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
        .expect("COINIT flags are small positives");
    // SAFETY: `pv_reserved` is required to be null, and the apartment is the one
    // the API's own documentation names.
    let apartment = unsafe { CoInitializeEx(std::ptr::null(), coinit) };
    // SAFETY: all-zero is this struct's "nothing optional set" form. `cbSize`,
    // `fMask`, `lpVerb`, `lpFile`, `lpParameters` and `nShow` are written below;
    // every remaining member is an output, or an optional input whose NULL/zero
    // means "not set".
    let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() };
    info.cbSize = u32::try_from(std::mem::size_of::<SHELLEXECUTEINFOW>())
        .expect("shell execute info fits in u32");
    info.fMask = SEE_MASK_NOASYNC;
    info.lpVerb = std::ptr::null();
    info.lpFile = address.as_ptr();
    info.lpParameters = std::ptr::null();
    info.nShow = SW_SHOWNORMAL;
    // SAFETY: `info` is fully initialised and its `lpFile` borrows `address`,
    // which outlives the call.
    let failed = unsafe { ShellExecuteExW(&raw mut info) } == FALSE;
    // SAFETY: `GetLastError` takes no arguments, and it is read before any other
    // call can overwrite the error the failed launch set.
    let code = failed.then(|| unsafe { GetLastError() });
    if apartment >= 0 {
        // SAFETY: pairs with the successful `CoInitializeEx` above, on the same
        // thread.
        unsafe { CoUninitialize() };
    }
    code
}

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

    /// Build a minimal [`Workspace`] with a name + derived path for map fixtures.
    fn ws(name: &str) -> Workspace {
        Workspace {
            name: name.to_string(),
            path: format!("/p/{name}"),
            ..Default::default()
        }
    }

    /// A ready dashboard so post-ready handlers (e.g. `WorkspacesReloaded`)
    /// run instead of the `!ready` guard.
    fn ready_dashboard() -> Dashboard {
        let mut dash = Dashboard::loading();
        dash.ready = true;
        dash
    }

    /// A `WorkspacesReloaded` for generation 0 — the generation a dashboard that
    /// has not reloaded yet carries (the reload guard drops anything older).
    fn reloaded(map: HashMap<String, Workspace>) -> Message {
        Message::WorkspacesReloaded {
            workspaces: map,
            generation: 0,
        }
    }

    /// [`reloaded`]'s failure counterpart.
    fn reload_failed(error: &str) -> Message {
        Message::WorkspacesReloadFailed {
            error: error.to_string(),
            generation: 0,
        }
    }

    #[test]
    fn workspaces_reloaded_replaces_map_and_defers_an_unknown_selection() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([
            ("ws1".to_string(), ws("ws1")),
            ("ws2".to_string(), ws("ws2")),
        ]);
        dash.selected_workspace_name = Some("ws2".to_string());
        let _ = dash.apply_workspace_selection("ws2");
        assert_eq!(dash.resolved_workspace(), Some(("ws2", "/p/ws2")));

        // A reload whose map lacks ws2 replaces the map, but leaves the live
        // selection standing — never substituted with the admin's Personal
        // workspace — and the now-unresolved surfaces are dropped with it: the
        // DB read-back, not this map, decides whether the selection survives.
        let new_map = HashMap::from([
            ("ws1".to_string(), ws("ws1")),
            ("ws3".to_string(), ws("ws3")),
        ]);
        let _ = dash.update(reloaded(new_map));
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws2"));
        assert_eq!(dash.resolved_workspace(), None);
        assert_eq!(dash.pushed_workspace, None);
        assert!(dash.workspaces.contains_key("ws1"));
        assert!(dash.workspaces.contains_key("ws3"));
        assert!(!dash.workspaces.contains_key("ws2"));

        // A reload whose map still contains the selection → unchanged. This is
        // the live re-resolution: the selection is preserved regardless of what
        // the trigger-time snapshot was — the boot-race regression where a
        // reload triggered while the selection was still None must not reset it.
        dash.selected_workspace_name = Some("ws3".to_string());
        let new_map2 = HashMap::from([("ws3".to_string(), ws("ws3"))]);
        let _ = dash.update(reloaded(new_map2));
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws3"));
    }

    /// A phone-side switch reaches a running dashboard: the read-back applies
    /// the stored choice in memory, an unchanged value is a no-op, and a read
    /// superseded by a local pick or by a newer read is dropped — the two
    /// surfaces are one choice, and the running app follows it.
    #[test]
    fn active_workspace_sync_follows_an_external_switch_and_drops_a_superseded_read() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([
            ("ws1".to_string(), ws("ws1")),
            ("ws2".to_string(), ws("ws2")),
        ]);
        dash.selected_workspace_name = Some("ws1".to_string());

        // A switch made elsewhere — the chat — is adopted as soon as it is read
        // back.
        let _ = dash.update(Message::ActiveWorkspaceSynced {
            generation: 0,
            name: Some("ws2".to_string()),
        });
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws2"));

        // A pick made here issues a write of its own, so a read dispatched
        // before it is stale by construction and must not revert the pick.
        let _ = dash.select_workspace("ws1");
        assert_eq!(dash.active_workspace_gen, 1);
        let _ = dash.update(Message::ActiveWorkspaceSynced {
            generation: 0,
            name: Some("ws2".to_string()),
        });
        assert_eq!(
            dash.selected_workspace_name.as_deref(),
            Some("ws1"),
            "a superseded read must not revert the live selection"
        );

        // A failed read changes nothing, and an unchanged value must not re-run
        // the heavy propagate (the board generation it bumps stays put).
        let _ = dash.update(Message::ActiveWorkspaceSynced {
            generation: 1,
            name: None,
        });
        let board_gen = dash.board_state.board_generation;
        let _ = dash.update(Message::ActiveWorkspaceSynced {
            generation: 1,
            name: Some("ws1".to_string()),
        });
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws1"));
        assert_eq!(
            dash.board_state.board_generation, board_gen,
            "an unchanged value must not re-propagate the selection"
        );

        // Two reads in flight: the one dispatched first cannot land last and
        // revert the newer answer, because the newer dispatch bumped the guard.
        let stale = dash.active_workspace_gen;
        dash.active_workspace_gen += 1; // a newer read is dispatched
        let _ = dash.update(Message::ActiveWorkspaceSynced {
            generation: stale,
            name: Some("ws2".to_string()),
        });
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws1"));

        // A stored shared name the loaded map does not hold is still adopted:
        // the map can simply be a reload behind (a workspace registered and
        // selected at once) and the DB is authoritative about the choice, so the
        // read-back must not pin Personal here.
        assert!(!dash.workspaces.contains_key("late"));
        let _ = dash.update(Message::ActiveWorkspaceSynced {
            generation: dash.active_workspace_gen,
            name: Some("late".to_string()),
        });
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("late"));

        // And a reload whose map read predates that workspace must not settle the
        // desktop on Personal either — the two surfaces stay one choice until the
        // DB says otherwise.
        let _ = dash.update(reloaded(HashMap::from([("ws1".to_string(), ws("ws1"))])));
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("late"));
    }

    #[test]
    fn workspaces_reloaded_preserves_boot_restored_selection() {
        // Models the exact boot race: a CDC baseline reload was triggered while
        // the selection was still None, but lands after `finish_boot` applied
        // the DB-restored selection ("mahbot"). Re-resolving from the live
        // selection keeps it instead of wiping it to Personal.
        let mut dash = ready_dashboard();
        dash.selected_workspace_name = Some("mahbot".to_string());
        let map = HashMap::from([("mahbot".to_string(), ws("mahbot"))]);
        let _ = dash.update(reloaded(map));
        assert_eq!(dash.selected_workspace_name.as_deref(), Some("mahbot"));
    }

    /// The boot race: the map read during boot is dropped as stale while the
    /// restored selection is applied, so the selection is resolved against an
    /// empty map. The workspace-scoped surfaces must stay empty — never the
    /// admin's Personal workspace — and must come back by
    /// themselves once the map arrives, with the selected NAME unchanged
    /// throughout.
    #[test]
    fn boot_without_the_workspace_map_pushes_nothing_then_recovers() {
        let mut dash = ready_dashboard();

        let _ = dash.apply_boot_workspaces(Ok(HashMap::new()), "ws1", 0);

        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws1"));
        assert_eq!(dash.resolved_workspace(), None);
        assert_eq!(
            dash.pushed_workspace, None,
            "an unresolvable selection must not be substituted with a workspace"
        );

        let _ = dash.update(reloaded(HashMap::from([("ws1".to_string(), ws("ws1"))])));

        assert_eq!(dash.selected_workspace_name.as_deref(), Some("ws1"));
        assert_eq!(dash.resolved_workspace(), Some(("ws1", "/p/ws1")));
        assert_eq!(
            dash.pushed_workspace
                .as_ref()
                .map(|(name, path)| (name.as_str(), path.as_str())),
            Some(("ws1", "/p/ws1")),
            "the reload that made the unchanged selection resolvable must re-push it"
        );
    }

    /// Only a registered workspace present in the loaded map with a usable path
    /// resolves; everything else — a personal selection however it arose, a
    /// name missing from the map, an entry without a path, no selection —
    /// resolves to nothing.
    #[test]
    fn only_a_registered_workspace_with_a_path_resolves() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([
            ("ws1".to_string(), ws("ws1")),
            (
                "pathless".to_string(),
                Workspace {
                    name: "pathless".to_string(),
                    ..Default::default()
                },
            ),
        ]);

        dash.selected_workspace_name = Some("personal:admin".to_string());
        assert_eq!(dash.resolved_workspace(), None);
        dash.selected_workspace_name = Some("gone".to_string());
        assert_eq!(dash.resolved_workspace(), None);
        dash.selected_workspace_name = Some("pathless".to_string());
        assert_eq!(dash.resolved_workspace(), None);
        dash.selected_workspace_name = Some(String::new());
        assert_eq!(dash.resolved_workspace(), None);
        dash.selected_workspace_name = None;
        assert_eq!(dash.resolved_workspace(), None);

        dash.selected_workspace_name = Some("ws1".to_string());
        assert_eq!(dash.resolved_workspace(), Some(("ws1", "/p/ws1")));
    }

    /// The editor page, the shell page, the footer git status and the diff view
    /// follow the resolution: hidden while nothing resolves, back by themselves
    /// once it does. Every step goes through the real selection entry point
    /// (the single push point for all four), so what the dashboard derives from
    /// that push is asserted here.
    #[test]
    fn unresolved_selection_hides_the_workspace_scoped_surfaces() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([("ws1".to_string(), ws("ws1"))]);

        let _ = dash.apply_workspace_selection("ws1");
        assert!(dash.render_git_block().is_some());

        // A personal selection never resolves.
        let _ = dash.apply_workspace_selection("personal:admin");
        assert!(!dash.page_available(Page::Editor));
        assert!(!dash.page_available(Page::Shell));
        assert!(
            dash.page_available(Page::Home),
            "other pages stay available"
        );
        assert!(dash.render_git_block().is_none());
        let _ = dash.open_diff_modal(None);
        assert!(!dash.show_diff_modal, "the diff view must not open");

        // Neither does a selected name missing from the loaded map.
        let _ = dash.apply_workspace_selection("gone");
        assert!(!dash.page_available(Page::Editor));
        assert!(dash.render_git_block().is_none());

        let _ = dash.apply_workspace_selection("ws1");
        assert!(dash.page_available(Page::Editor));
        assert!(dash.page_available(Page::Shell));
        assert!(dash.render_git_block().is_some());
        let _ = dash.open_diff_modal(None);
        assert!(dash.show_diff_modal);
    }

    /// An open diff view is closed when the resolution is lost — from then on
    /// nothing of that workspace may be displayed.
    #[test]
    fn losing_the_resolution_closes_the_diff_view() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([("ws1".to_string(), ws("ws1"))]);
        let _ = dash.apply_workspace_selection("ws1");
        let _ = dash.open_diff_modal(None);
        assert!(dash.show_diff_modal);

        let _ = dash.apply_workspace_selection("personal:admin");

        assert!(!dash.show_diff_modal);
        assert_eq!(dash.resolved_workspace(), None);
        assert_eq!(dash.pushed_workspace, None);
    }

    /// A workspace switch drops the board failure that described the previous
    /// workspace: its banner must not paint over the board being loaded now.
    #[test]
    fn workspace_switch_clears_the_previous_board_failure() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([("ws1".to_string(), ws("ws1"))]);
        dash.board_state.load_state.fail("db down".to_string());

        let _ = dash.propagate_workspace_selection("ws1");

        assert!(dash.board_state.load_state.error().is_none());
    }

    /// A reload that lands after a newer one has answered is dropped: its
    /// failure must not re-set the error over the map the newer read produced
    /// (the reload retries for a second, so this window is real).
    #[test]
    fn stale_workspace_reload_outcomes_are_dropped() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([("ws1".to_string(), ws("ws1"))]);
        dash.workspaces_reload_gen = 2;

        let _ = dash.update(Message::WorkspacesReloadFailed {
            error: "db down".to_string(),
            generation: 1,
        });
        assert!(
            dash.workspaces_error.is_none(),
            "a stale failure must not re-set the error"
        );

        let _ = dash.update(Message::WorkspacesReloaded {
            workspaces: HashMap::from([("ws2".to_string(), ws("ws2"))]),
            generation: 1,
        });
        assert!(
            dash.workspaces.contains_key("ws1"),
            "a stale map must not replace the newer one"
        );
    }

    #[test]
    fn resolve_workspace_selection_keeps_valid_falls_back_personal() {
        let map = HashMap::from([("ws1".to_string(), ws("ws1"))]);
        let personal = "personal:alice";
        assert_eq!(
            resolve_workspace_selection(&map, Some("ws1"), personal),
            "ws1"
        );
        assert_eq!(
            resolve_workspace_selection(&map, Some("gone"), personal),
            personal
        );
        assert_eq!(resolve_workspace_selection(&map, None, personal), personal);
    }

    /// A personal workspace is never a picker option — a lingering
    /// `personal:{user}` row in the map is filtered out — so the footer picker
    /// and the chat's switcher offer the same set.
    #[test]
    fn shared_workspace_options_never_offer_a_personal_workspace() {
        let map = HashMap::from([
            ("personal:admin".to_string(), ws("personal:admin")),
            ("ws2".to_string(), ws("ws2")),
            ("ws1".to_string(), ws("ws1")),
        ]);

        let options = shared_workspace_options(&map);

        assert_eq!(
            options.iter().map(|o| o.value.as_str()).collect::<Vec<_>>(),
            vec!["ws1", "ws2"],
            "shared workspaces only, ordered by name"
        );
    }

    #[test]
    fn workspaces_reloaded_syncs_settings_lists() {
        let mut dash = ready_dashboard();
        let map = HashMap::from([
            ("beta".to_string(), ws("beta")),
            ("alpha".to_string(), ws("alpha")),
        ]);
        let _ = dash.update(reloaded(map));

        // Settings workspace list = map values sorted by name.
        let ws_names: Vec<&str> = dash
            .settings_state
            .workspaces_state
            .workspaces
            .iter()
            .map(|w| w.name.as_str())
            .collect();
        assert_eq!(ws_names, vec!["alpha", "beta"]);
    }

    /// A failed workspace-map read is a persistent, visible state: the current
    /// map is preserved, the failure stays on the Dashboard for the picker and
    /// the Settings list, and a later successful reload clears it.
    #[test]
    fn workspaces_reload_failure_sets_and_clears_error() {
        let mut dash = ready_dashboard();
        dash.workspaces = HashMap::from([("ws1".to_string(), ws("ws1"))]);

        let _ = dash.update(reload_failed("db down"));

        assert_eq!(dash.workspaces_error.as_deref(), Some("db down"));
        assert!(
            dash.workspaces.contains_key("ws1"),
            "a failed reload must preserve the current map"
        );
        assert!(
            dash.picker_failure(&shared_workspace_options(&dash.workspaces))
                .is_none(),
            "a preserved map keeps the picker working — the pill is for a read that left nothing to pick"
        );

        let new_map = HashMap::from([("ws2".to_string(), ws("ws2"))]);
        let _ = dash.update(reloaded(new_map));

        assert!(dash.workspaces_error.is_none());
    }

    /// A failed boot read still completes boot: the map stays empty and the
    /// failure is carried so the picker / Settings list can render it.
    #[test]
    fn boot_workspace_read_failure_completes_with_error_state() {
        let mut dash = Dashboard::loading();

        let _ =
            dash.apply_boot_workspaces(Err("boot read failed".to_string()), "personal:admin", 0);

        assert_eq!(dash.workspaces_error.as_deref(), Some("boot read failed"));
        assert!(dash.workspaces.is_empty());
        assert_eq!(
            dash.picker_failure(&shared_workspace_options(&dash.workspaces)),
            Some("boot read failed"),
            "a read that left nothing to pick must show the failure in the picker"
        );
    }

    /// A reload that answered while the boot read was in flight read the same
    /// table later: its map (and its cleared failure) stands, and the boot read's
    /// outcome is dropped.
    #[test]
    fn late_boot_read_does_not_replace_a_newer_reload() {
        let mut dash = Dashboard::loading();
        let read_generation = dash.workspaces_reload_gen;
        dash.workspaces = HashMap::from([("ws1".to_string(), ws("ws1"))]);
        dash.workspaces_reload_gen = read_generation + 1; // a reload answered

        let _ = dash.apply_boot_workspaces(
            Err("boot read failed".to_string()),
            "personal:admin",
            read_generation,
        );

        assert!(
            dash.workspaces_error.is_none(),
            "the superseded boot read must not set the failure over the newer read"
        );
        assert!(
            dash.workspaces.contains_key("ws1"),
            "the superseded boot read must not clear the newer map"
        );
    }

    /// The DB-sourced boot resolution: the seeded admin with a shared stored
    /// workspace present in the map restores it; a stored value missing from
    /// the map falls back to the "Personal" default.
    #[tokio::test]
    #[serial_test::serial(gui_admin_workspace)] // writes the shared seeded admin row
    async fn boot_workspace_options_resolve_from_db() {
        crate::util::test::init_test_stores().await;
        crate::workspace::store()
            .conn
            .execute(
                "INSERT OR IGNORE INTO workspaces (name, path, created_at, updated_at) \
                 VALUES ('boot_ws_gui', '/p/boot_ws_gui', '2026-01-01T00:00:00+00:00', \
                         '2026-01-01T00:00:00+00:00')",
                crate::db::params![],
            )
            .await
            .expect("seed workspace");

        let store = crate::users::store();
        // The guard restores the shared seeded admin row even when an assertion
        // below panics.
        crate::users::test_util::with_admin_workspace_restored(async {
            // A shared stored workspace present in the map → restored.
            store
                .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("boot_ws_gui"))
                .await
                .expect("update admin selected_workspace");
            let Message::BootWorkspaces {
                workspaces: Ok(map),
                restored_name,
                ..
            } = load_workspace_options(0).await
            else {
                panic!("expected BootWorkspaces with a loaded map");
            };
            assert!(map.contains_key("boot_ws_gui"));
            assert_eq!(restored_name, "boot_ws_gui");

            // A stored value missing from the map → the Personal default.
            store
                .set_selected_workspace(crate::users::ADMIN_USER_NAME, Some("gone_ws_gui"))
                .await
                .expect("update admin selected_workspace");
            let Message::BootWorkspaces { restored_name, .. } = load_workspace_options(0).await
            else {
                panic!("expected BootWorkspaces");
            };
            assert_eq!(restored_name, "personal:admin");
        })
        .await;
    }
}