mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
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
//! Home page — native GUI chat interface for the app's own admin identity: one conversation
//! with the Assistant in the admin's personal workspace. The footer workspace picker selects the
//! workspace the work that follows runs in — never the conversation.

use crate::ChatDirection;
use crate::Role;
use crate::audio::voice::RecordingEvent;
use crate::channels::ReplyReference;
use crate::channels::chat_history::ChatHistoryEntry;
use crate::channels::reply::{agent_author_label, normalize_reply_text};
use chrono::{DateTime, Utc};
use futures_util::SinkExt;
use iced::widget::rule;
use iced::widget::{Column, Id, Space, button, column, container, row, scrollable, text, tooltip};
use iced::{Alignment, Element, Length, Task};
use iced_fonts::lucide;
use std::collections::HashSet;
use std::sync::Arc;

use super::ToastMessage;
use super::common::MAX_INPUT_CHARS;
use super::menus::{ContextMenu, MenuItem};
use super::theme;
use super::widgets::{BubbleSide, align_bubble};

/// Dedup-set prune trigger: past this many IDs, `seen_ids` is pruned to the most recent
/// [`DEDUP_RETAIN`].
const DEDUP_PRUNE_THRESHOLD: usize = 500;

const DEDUP_RETAIN: usize = 200;

/// Debounce window (ms) after a text/reply change before the draft is persisted to disk.
const DRAFT_SETTLE_MS: u64 = 700;

/// How soon after the page is drawn the composer takes the keyboard: long enough for the frame
/// that shows it, short enough to be imperceptible.
const FOCUS_TICK: std::time::Duration = std::time::Duration::from_millis(50);

/// Scrollable ID for the chat message list, used for snap-to-end after history loads.
pub(super) const CHAT_SCROLL_ID: Id = Id::new("home_chat_scroll");

/// Focus id for the composer editor, used to refocus it after selecting a reply target and when
/// the page opens or is navigated to.
const CHAT_COMPOSER_ID: Id = Id::new("home_chat_composer");

#[derive(Debug, Clone)]
struct DisplayMessage {
    /// Row id in storage (`Some` for entries read from chat_history) or `None` for what is only on
    /// screen. Only the `Some` entries are the stored history a load replaces.
    pub id: Option<i64>,
    pub message_id: String,
    pub content: String,
    pub direction: ChatDirection,
    pub agent_role: Option<String>,
    /// Timestamp for the relative-time label and for load reconciliation: the stored row's own, or
    /// — for an on-screen-only message — the instant of the event that produced it.
    pub timestamp: Option<String>,
    pub reply_reference: Option<ReplyReference>,
    pub md_items: Vec<iced::widget::markdown::Item>,
    /// The body's attachments (pictures, named files), in body order, drawn as one block above
    /// the text.
    pub attachments: Vec<super::media_markers::MediaAttachment>,
    /// True for an optimistic placeholder pushed before the pipeline confirmation arrives; the
    /// `ChatEvent::Message` handler replaces these.
    pub is_optimistic: bool,
}

/// Build a [`DisplayMessage`] from raw parts. Media-preprocesses content and parses markdown;
/// divider directions skip markdown (rendered as rules).
///
/// Markers resolve against the conversation's own workspace — Home shows the admin's personal
/// conversation, so that is the root. A marker whose target is a reference becomes an attachment,
/// whatever its direction, and one whose file has gone still does.
#[expect(clippy::too_many_arguments)]
fn display_message(
    id: Option<i64>,
    message_id: String,
    content: String,
    direction: ChatDirection,
    agent_role: Option<String>,
    timestamp: Option<String>,
    reply_reference: Option<ReplyReference>,
    is_optimistic: bool,
) -> DisplayMessage {
    let (md_items, attachments) = if direction == ChatDirection::Divider {
        (Vec::new(), Vec::new())
    } else {
        let workspace = HomeState::conversation_workspace_path();
        super::media_markers::parse_body(&content, Some(&workspace))
    };
    DisplayMessage {
        id,
        message_id,
        content,
        direction,
        agent_role,
        timestamp,
        reply_reference,
        md_items,
        attachments,
        is_optimistic,
    }
}

impl From<ChatHistoryEntry> for DisplayMessage {
    fn from(entry: ChatHistoryEntry) -> Self {
        let ChatHistoryEntry {
            id,
            message_id,
            content,
            direction,
            agent_role,
            timestamp,
            reply_reference,
            ..
        } = entry;
        display_message(
            Some(id),
            message_id,
            content,
            direction,
            agent_role,
            timestamp,
            reply_reference,
            false,
        )
    }
}

/// The toast naming what an intake could not attach; nothing when it refused nothing.
fn refused_toast(refused: &[String]) -> Task<HomeMessage> {
    if refused.is_empty() {
        return Task::none();
    }
    Task::done(HomeMessage::Toast(ToastMessage::Warning(
        refused.join("\n"),
    )))
}

/// Remove a send's staged copy on the runtime: a discard can land while a large staging copy is
/// still running, so it must not hold the update thread.
fn discard_staged(dirs: Vec<String>) {
    if dirs.is_empty() {
        return;
    }
    tokio::spawn(async move { super::attachment::discard(&dirs).await });
}

/// Open the platform's own file chooser for the composer's attach button: several files at once,
/// no type filtered, a folder ignored by the intake; a cancelled chooser changes nothing. Native
/// modal, so it runs on a blocking thread and the window keeps painting.
///
/// The dialog API has no failure of its own — a cancelled chooser and one that never appeared both
/// come back empty — so with no portal and no `zenity` the button does nothing.
async fn pick_attachment_files() -> Result<Option<Vec<std::path::PathBuf>>, String> {
    tokio::task::spawn_blocking(|| rfd::FileDialog::new().pick_files())
        .await
        .map_err(|error| format!("The file chooser could not be opened: {error}"))
}

/// Broadcast a transient GUI chat event via [`crate::channels::broadcast_chat_event`] with the
/// constants shared by every GUI call site: the `"gui"` channel, no reply reference, a fresh
/// timestamp, and the transient flag set (shown live, never persisted).
fn broadcast_gui_transient(
    user: &str,
    workspace: &str,
    message_id: &str,
    content: &str,
    direction: ChatDirection,
    agent_role: Option<String>,
    optimistic_id: Option<String>,
) {
    crate::channels::broadcast_chat_event(
        message_id,
        user,
        content,
        direction,
        "gui",
        agent_role,
        workspace,
        optimistic_id,
        None,
        &crate::db::now(),
        true, // transient: shown live, never persisted
    );
}

/// Derive the [`ReplyReference`] captured for a reply-to action. User messages are the admin's
/// own, so they resolve to the admin's canonical name; agent messages use the shared author-label
/// derivation. Author and snippet both get angle brackets stripped (the snippet via
/// [`normalize_reply_text`], which also HTML-decodes, collapses newlines, maps media markers and
/// caps the text).
#[must_use]
fn reply_reference_for(
    direction: ChatDirection,
    agent_role: Option<&str>,
    content: &str,
) -> ReplyReference {
    let author = if direction == ChatDirection::User {
        crate::users::ADMIN_USER_NAME.to_string()
    } else {
        agent_author_label(agent_role)
    };
    ReplyReference {
        author: author.replace(['<', '>'], ""),
        snippet: normalize_reply_text(content),
    }
}

/// Shared lead row of both reply renderings: reply glyph and muted snippet, already spaced and
/// center-aligned. Callers may `push` extra trailing elements (e.g. the dismiss button).
fn reply_lead_row(reply: &ReplyReference) -> iced::widget::Row<'_, HomeMessage> {
    row![
        lucide::reply::<iced::Theme, iced::Renderer>()
            .size(theme::TEXT_12)
            .color(theme::ACCENT),
        text(&reply.snippet)
            .size(theme::TEXT_11)
            .color(theme::TEXT_MUTED),
    ]
    .spacing(theme::SPACE_4)
    .align_y(Alignment::Center)
}

/// Render the reply preview bar shown between the message list and the
/// composer when a reply reference is pending: the shared reply row (the
/// snippet's own cap produces the ellipsis) with a dismiss control.
fn reply_preview(reply: &ReplyReference) -> Element<'_, HomeMessage> {
    let dismiss = button(
        lucide::x::<iced::Theme, iced::Renderer>()
            .size(theme::composer_icon(theme::TEXT_12))
            .color(theme::TEXT_MUTED),
    )
    .on_press(HomeMessage::CancelReply)
    .style(theme::icon_button_style(false))
    .padding(theme::PAD_2);
    container(
        reply_lead_row(reply)
            .push(Space::new().width(Length::Fill))
            .push(dismiss),
    )
    .padding([theme::PAD_4, theme::PAD_8])
    .style(theme::surface_container_style)
    .width(Length::Fill)
    .into()
}

/// Composer attach button: opens the platform's file chooser. It sits in the composer action
/// toolbar before the send button and is inert while the composer is (the graceful drain disables
/// both).
fn attach_control(disabled: bool) -> Element<'static, HomeMessage> {
    super::widgets::icon_tooltip_button(
        lucide::paperclip::<iced::Theme, iced::Renderer>()
            .size(theme::composer_icon(theme::TEXT_14))
            .color(if disabled {
                theme::TEXT_MUTED
            } else {
                theme::TEXT_SECONDARY
            }),
        "attach files",
        (!disabled).then_some(HomeMessage::PickAttachments),
        theme::PAD_3,
        theme::icon_button_style(disabled),
        tooltip::Position::Top,
    )
}

/// The composer action toolbar beyond the send button: the voice controls, then the attach control.
///
/// `recording` is the caller's single derivation of "a recording the composer owns is running" —
/// the same bool the send button's empty rule takes, so the two cannot disagree.
fn composer_controls(
    voice_status: &crate::audio::voice::VoiceStatus,
    recording: bool,
    draining: bool,
) -> Vec<Element<'static, HomeMessage>> {
    let mut controls = if recording {
        // The recording replaces the mic; its cancel control discards it and leaves the field as
        // it is.
        vec![recording_dot(), cancel_recording_control()]
    } else {
        vec![mic_control(voice_status)]
    };
    controls.push(attach_control(draining));
    controls
}

fn mic_control(voice_status: &crate::audio::voice::VoiceStatus) -> Element<'static, HomeMessage> {
    // The mic is busy while the pipeline owns it for a recording or any transcription — the button
    // must not look active when a new recording would be rejected. (A composer-owned recording
    // renders the dot, not this button.)
    let mic_busy = voice_status.mic_busy();
    // With local transcription disabled the shared ASR model never loads, so a button recording
    // can never start — present the control as unavailable, not as a loading state.
    let transcription_disabled = crate::audio::voice::is_transcription_disabled();
    let recording_unavailable = mic_busy || transcription_disabled;

    let mic_tooltip = if transcription_disabled {
        "voice recording unavailable — local transcription is disabled"
    } else {
        "record voice message"
    };
    super::widgets::icon_tooltip_button(
        lucide::mic::<iced::Theme, iced::Renderer>()
            .size(theme::composer_icon(theme::TEXT_14))
            .color(if recording_unavailable {
                theme::TEXT_MUTED
            } else {
                theme::TEXT_SECONDARY
            }),
        mic_tooltip,
        (!recording_unavailable).then_some(HomeMessage::StartVoiceRecording),
        theme::PAD_3,
        theme::icon_button_style(recording_unavailable),
        tooltip::Position::Top,
    )
}

/// The recording indicator: a red dot fading in and out while a recording runs. Passive — no
/// press, no tooltip.
fn recording_dot() -> Element<'static, HomeMessage> {
    // Padded and centred in the row of icon buttons beside it: a step smaller than their glyphs.
    container(super::pulse::pulse_dot(
        theme::composer_icon(theme::TEXT_10),
        theme::STATUS_ERROR,
    ))
    .padding(theme::PAD_5)
    .into()
}

/// Cancel control for the running recording — whichever way it started: it is dropped, and the
/// field keeps its text and attachments exactly as they are.
fn cancel_recording_control() -> Element<'static, HomeMessage> {
    super::widgets::icon_tooltip_button(
        lucide::circle_x::<iced::Theme, iced::Renderer>()
            .size(theme::composer_icon(theme::TEXT_14))
            .color(theme::TEXT_SECONDARY),
        "cancel recording",
        Some(HomeMessage::StopVoiceRecordingDiscard),
        theme::PAD_3,
        theme::icon_button_style(false),
        tooltip::Position::Top,
    )
}

#[derive(Debug, Clone)]
pub enum HomeMessage {
    /// The selected workspace changed (footer picker, Settings, or the read-back of the stored
    /// selection). Recorded only: the conversation does not depend on it.
    WorkspaceChanged(String),
    InputChanged(super::editor_widget::EditorAction),
    /// Attachments joined the message being composed, and the names the size cap turned away.
    Attach {
        attachments: Vec<super::attachment::Attachment>,
        refused: Vec<String>,
    },
    PickAttachments,
    /// The file chooser returned: the files picked, nothing for a cancelled chooser, or why it
    /// could not open.
    AttachmentsPicked(Result<Option<Vec<std::path::PathBuf>>, String>),
    RemoveAttachment(usize),
    FocusComposerOnce,
    SendMessage,
    /// The composer's attachments are staged (or the copy failed) and the send continues here, off
    /// the update thread. `generation` names the send, so a result for one that was cleared
    /// meanwhile delivers nothing; `voice` is the dictated part the message leads with.
    Staged {
        generation: u64,
        voice: Option<String>,
        text: String,
        attachments: Vec<super::attachment::Attachment>,
        result: Result<super::attachment::Staged, String>,
    },
    /// The whole conversation loaded from the store, in one read. `generation` is the load counter
    /// the read was issued under: a result whose generation is no longer current belongs to a
    /// superseded load and is dropped.
    HistoryLoaded {
        entries: Vec<ChatHistoryEntry>,
        generation: u64,
    },
    /// History load failed. Carries the generation, so a failure from a superseded load is dropped.
    HistoryLoadError {
        generation: u64,
        error: String,
    },
    ChatEvent(crate::ChatEvent),
    StreamLagged,
    ScrollChanged(scrollable::Viewport),
    LinkClicked(String),
    /// A `[FILE:…]` reveal finished: `Ok` needs no action, an error becomes an error toast.
    FileRevealed(Result<(), String>),
    ClearChat,
    /// Copy a chat message's raw markdown content to the clipboard — the exact stored/transmitted
    /// text (original media markers included), not the rendered view.
    CopyMessage(String),
    /// Reply to a displayed chat message: capture its author + snippet as the pending reply
    /// reference and focus the composer. Carries what derives author/snippet
    /// (direction/agent_role/content) — deliberately not the whole [`DisplayMessage`], whose parsed
    /// markdown would be dead weight.
    ReplyTo {
        direction: ChatDirection,
        agent_role: Option<String>,
        content: String,
    },
    CancelReply,
    /// A composer-draft debounce has settled — persist the current draft. `generation` is the
    /// counter captured when the edit was staged; a settle whose generation no longer matches is
    /// stale and dropped, so per-keystroke and out-of-order writes are impossible.
    DraftSaveSettled {
        generation: u64,
    },
    ChatCleared,
    ChatClearError(String),
    /// Toast notification to show via Dashboard.
    /// Intercepted by Dashboard; never reaches Home's own update handler.
    Toast(ToastMessage),
    TypingTick,
    /// Timeout safety net: if `sending` stays stuck for 30+ seconds, auto-clear it. Carries the
    /// generation counter so a stale timeout cannot disturb a fresh send.
    SendingTimeout(u64),
    StartVoiceRecording,
    /// Cancel control clicked: stop the recording and discard it, leaving the field as it is.
    StopVoiceRecordingDiscard,
    /// Progress of a voice recording, whichever way it started: the field is committed when it
    /// stops and the message goes out once the transcript joins it.
    VoiceRecording(RecordingEvent),
    /// The scripted onboarding exchange completed (provider configured) — re-run the check, now
    /// firing the Phase-2 kickoff.
    OnboardingScriptCompleted,
    OnboardingScriptRePrompt,
    OnboardingKickoffDone,
}

pub struct HomeState {
    /// The footer workspace picker's selection, recorded for the send path (the workspace the work
    /// that follows runs in). The conversation does not depend on it.
    selected_workspace: Option<String>,
    /// Load counter for the conversation read: advanced by every load. A result carrying a
    /// superseded generation is dropped, so a slow load can never overwrite a newer one.
    history_gen: u64,
    messages: Vec<DisplayMessage>,
    seen_ids: HashSet<String>,
    editor_content: super::editor_widget::EditorBuffer,
    /// Files and images attached to the next send. Not persisted with the draft — a draft is text
    /// and its reply only.
    attachments: Vec<super::attachment::Attachment>,
    /// The composer is to take the keyboard once this page has been drawn: a focus operation
    /// applies to the frame already on screen, so it is sent one tick later, never in the task that
    /// switched the page.
    pending_focus: bool,
    sending: bool,
    typing: bool,
    typing_tick_state: u8,
    /// Whether the Phase-1 scripted onboarding scenario is active (`provider_configured()` is
    /// false).
    onboarding_script_active: bool,
    /// Names the send in flight, so a stale result is ignored: bumped when a timeout guard is armed
    /// and when the conversation is cleared.
    sending_gen: u64,
    auto_scroll_enabled: bool,
    undo_stack: super::common::UndoStack,
    /// Captured {author, snippet} of the message being replied to; `Some` while a reply preview is
    /// shown above the composer, cleared on send, cancel or chat clear.
    pending_reply: Option<ReplyReference>,
    drafts: Arc<crate::channels::chat_draft::DraftStore>,
    draft_save: super::common::DebounceState,
    /// Persistent failure of the last conversation read, rendered in place of the empty-chat hint
    /// so a failed read is never mistaken for an empty history; cleared on the next success.
    history_error: Option<String>,
    /// The message a voice recording owns in the composer: from the recording's start (the mic
    /// press or the wake word's) until the field is committed, then the committed content until the
    /// transcript joins it (or the attempt fails and it comes back). The dot, the cancel control
    /// and the send press all read it, so they can never disagree about whether a recording runs.
    voice_message: Option<VoiceMessage>,
    /// When the composer last posted a discarded-recording notice, for the notice window.
    voice_notice_at: Option<std::time::Instant>,
    /// When the composer last posted a lost-message notice: a discard must not silence a failure.
    voice_error_at: Option<std::time::Instant>,
}

#[derive(Debug)]
enum VoiceMessage {
    /// A recording owns the field: a press commits it, and the transcript that follows completes
    /// the message.
    Recording,
    /// The press took the field's content; the message waits for the recording's transcript (see
    /// [`HomeState::in_flight`] for what that lock means).
    Committed {
        text: String,
        attachments: Vec<super::attachment::Attachment>,
    },
}

/// A voice notice the composer posts, and the window it counts against — the same split the
/// pipeline keeps between discards and failures.
#[derive(Clone, Copy)]
enum VoiceNotice {
    Discarded(&'static str),
    Failed(&'static str),
}

/// The content of a sent message: its dictated part first (already carrying the spoken marker),
/// then the attachment markers, then the typed text — blank-line separated, so an ordinary send
/// keeps its markers-then-caption shape and a voice message reads transcript → attachments → text.
fn compose_content(voice: Option<&str>, markers: &str, text: &str) -> String {
    voice
        .into_iter()
        .chain([markers, text])
        .filter(|block| !block.is_empty())
        .collect::<Vec<_>>()
        .join("\n\n")
}

/// The instant a stored timestamp names, or `None` when it is absent or not a timestamp the clock
/// produced. Compared as instants, not as text: `db::now()` strings vary in fractional digits and
/// carry an offset, so their text order is the clock's only by accident.
fn instant(timestamp: Option<&str>) -> Option<DateTime<Utc>> {
    timestamp.and_then(|ts| crate::db::parse_utc_timestamp(ts).ok())
}

impl HomeState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            selected_workspace: None,
            history_gen: 0,
            messages: Vec::new(),
            seen_ids: HashSet::new(),
            editor_content: super::editor_widget::EditorBuffer::with_text(
                "",
                Some(super::highlight::HighlightLanguage::Markdown),
            ),
            attachments: Vec::new(),
            pending_focus: false,
            sending: false,
            typing: false,
            typing_tick_state: 0,
            onboarding_script_active: false,
            sending_gen: 0,
            auto_scroll_enabled: true,
            undo_stack: super::common::UndoStack::new(),
            pending_reply: None,
            drafts: crate::channels::chat_draft::DraftStore::global().clone(),
            draft_save: super::common::DebounceState::new(),
            history_error: None,
            voice_message: None,
            voice_notice_at: None,
            voice_error_at: None,
        }
    }

    /// Whether `workspace` is the admin's own personal workspace (`personal:admin`) — the only
    /// workspace the conversation lives in, and the test for whether a live event belongs to it.
    fn is_admin_personal_workspace(workspace: &str) -> bool {
        crate::users::personal_user_name(workspace).is_some_and(crate::users::is_admin_name)
    }

    /// The workspace the conversation belongs to: the admin's own personal space. The Assistant is
    /// pinned to it, so everything this chat receives — the admin's text, agent replies, the notice
    /// written when a turn fails — is tagged with it, and nothing else is.
    fn conversation_workspace() -> String {
        crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME)
    }

    /// The conversation's filesystem root: a relative marker target in this chat names a file in
    /// the admin's personal workspace, and nothing else.
    fn conversation_workspace_path() -> std::path::PathBuf {
        crate::users::personal_workspace_path(crate::users::ADMIN_USER_NAME)
    }

    /// Open the app's own conversation: bring the persisted composer draft back and load the
    /// conversation. This is the app-opening load route — the load hangs off the screen opening,
    /// never off a selection arriving.
    pub fn open(&mut self) -> Task<HomeMessage> {
        self.restore_draft();
        self.arm_composer_focus();
        self.refresh_history()
    }

    /// Give the composer the keyboard on the next frame — its focus is what lets a paste land in
    /// the input without a click first.
    pub(super) fn arm_composer_focus(&mut self) {
        // The field is about to own the text-selection shortcuts; a transcript block left active
        // by an earlier press must not also take them.
        super::selectable::deactivate();
        self.pending_focus = true;
    }

    /// The load counter: a load was issued exactly when it advanced. Read by the boot test, which
    /// proves the app opening is a load route.
    #[cfg(test)]
    pub(crate) fn history_generation(&self) -> u64 {
        self.history_gen
    }

    /// Load the conversation — the admin's own single chat, in their personal workspace,
    /// independent of the selected workspace. One read carries the whole of what the cap keeps:
    /// there is nothing older to fetch.
    fn refresh_history(&mut self) -> Task<HomeMessage> {
        self.history_gen = self.history_gen.wrapping_add(1);
        let generation = self.history_gen;
        let workspace = Self::conversation_workspace();
        Task::perform(
            async move {
                let store = crate::channels::chat_history::store();
                store
                    .load_conversation(crate::users::ADMIN_USER_NAME, &workspace)
                    .await
                    .map_err(|e| e.to_string())
            },
            move |result| match result {
                Ok(entries) => HomeMessage::HistoryLoaded {
                    entries,
                    generation,
                },
                Err(e) => HomeMessage::HistoryLoadError {
                    generation,
                    error: e,
                },
            },
        )
    }

    /// Replace the stored history with `entries`. What is on screen but not stored (the message
    /// being sent, the scripted introduction) is kept, and nothing is ever shown twice; no task is
    /// issued (the caller batches the snap and the onboarding check).
    fn replace_stored_history(&mut self, entries: Vec<ChatHistoryEntry>) {
        let mut kept: Vec<DisplayMessage> = std::mem::take(&mut self.messages)
            .into_iter()
            .filter(|m| m.id.is_none())
            .collect();
        let stored: Vec<DisplayMessage> = entries.into_iter().map(DisplayMessage::from).collect();
        // Anything the page carries in its own right goes in favour of the stored copy: a live
        // arrival and a pending send already confirmed both show under the pipeline's id.
        let stored_ids: HashSet<&str> = stored.iter().map(|m| m.message_id.as_str()).collect();
        // A pending send still shows under its local id, and a lag can drop exactly its
        // confirmation — leaving the bubble while the page brings the row back under the
        // pipeline's id. Matching the two is a heuristic: the row of that send is a page row
        // written from here, so not older than the bubble it confirms, while an older row with the
        // same text is the user having sent it before. An unmatched bubble goes when its
        // confirmation arrives.
        kept.retain(|msg| {
            if stored_ids.contains(msg.message_id.as_str()) {
                return false;
            }
            // Only a pending send is reconciled, and only against a bubble carrying the send's own
            // instant — with nothing to compare, the bubble stays.
            if !msg.is_optimistic {
                return true;
            }
            let Some(sent_at) = instant(msg.timestamp.as_deref()) else {
                return true;
            };
            !stored.iter().any(|s| {
                s.direction == ChatDirection::User
                    && s.content == msg.content
                    && instant(s.timestamp.as_deref()).is_some_and(|at| at >= sent_at)
            })
        });
        // What is kept goes back where it belongs: both a scripted transient and
        // a pending send carry the instant of the event that produced them, and
        // go before the first stored message that is newer.
        let mut merged = stored;
        for msg in kept {
            let at = instant(msg.timestamp.as_deref()).and_then(|ts| {
                merged
                    .iter()
                    .position(|m| instant(m.timestamp.as_deref()).is_some_and(|t| t > ts))
            });
            merged.insert(at.unwrap_or(merged.len()), msg);
        }
        self.messages = merged;
        self.seen_ids.clear();
        self.seen_ids
            .extend(self.messages.iter().map(|m| m.message_id.clone()));
    }

    /// Snapshot the current composer state (text + pending reply) into the
    /// draft store and schedule a debounced persist after `delay_ms`.
    ///
    /// The in-memory mutation happens synchronously at schedule time — the
    /// file write lags behind the debounce, so the in-memory draft is always current.
    fn capture_draft(&mut self, delay_ms: u64) -> Task<HomeMessage> {
        if self.onboarding_script_active {
            return Task::none();
        }
        let text = self.editor_content.text();
        let reply = self.pending_reply.clone();
        self.drafts.set(text, reply);
        self.draft_save
            .trigger(delay_ms)
            .map(|generation| HomeMessage::DraftSaveSettled { generation })
    }

    /// Bring the persisted draft back into the composer; called once when the
    /// chat starts.
    fn restore_draft(&mut self) {
        let draft = self.drafts.get();
        self.editor_content.set_text(&draft.text);
        self.pending_reply = draft.reply;
    }

    /// Remove the stored draft and schedule a persist — used on send, after the
    /// composer has been cleared.
    fn drop_draft(&mut self) {
        self.drafts.remove();
        self.drafts.clone().persist_async();
    }

    /// Produce a snap-to-end task if auto-scroll is enabled.
    fn maybe_snap(&self) -> Task<HomeMessage> {
        if self.auto_scroll_enabled {
            iced::widget::operation::snap_to_end(CHAT_SCROLL_ID)
        } else {
            Task::none()
        }
    }

    /// Start the Phase-1 scripted onboarding (no provider) or fire the Phase-2
    /// Assistant kickoff (provider configured, state Init). Called after the first
    /// history load. No-op when the scenario is already active.
    fn maybe_start_onboarding(&mut self) -> Task<HomeMessage> {
        if !crate::config::provider_configured() {
            if self.onboarding_script_active {
                return Task::none();
            }
            let workspace = Self::conversation_workspace();
            self.onboarding_script_active = true;
            for (i, msg) in crate::onboarding::intro_messages().into_iter().enumerate() {
                broadcast_gui_transient(
                    crate::users::ADMIN_USER_NAME,
                    &workspace,
                    &format!("onboarding-intro-{i}"),
                    msg,
                    crate::ChatDirection::Agent,
                    Some("assistant".to_string()),
                    None,
                );
            }
            Task::none()
        } else if crate::config::CONFIG.onboarding_stage() == crate::config::OnboardingState::Init {
            self.onboarding_script_active = false;
            Task::perform(
                async {
                    crate::onboarding::kickoff_onboarding(crate::users::ADMIN_USER_NAME).await
                },
                |_res| HomeMessage::OnboardingKickoffDone,
            )
        } else {
            self.onboarding_script_active = false;
            Task::none()
        }
    }

    /// Replace an optimistic placeholder with a confirmed pipeline message.
    ///
    /// If `optimistic_id` matches a locally-inserted optimistic message, swaps in the real
    /// [`DisplayMessage`], marks the canonical ID as seen, clears `sending`, and returns
    /// `Some(snap_task)` so the caller can early-return. When the stored copy is already on screen
    /// the bubble is the same message and is dropped instead. `None` when nothing was replaced.
    #[expect(clippy::too_many_arguments)]
    fn replace_optimistic(
        &mut self,
        optimistic_id: Option<&str>,
        message_id: &str,
        content: &str,
        direction: ChatDirection,
        agent_role: Option<&str>,
        timestamp: Option<&str>,
        reply_reference: Option<ReplyReference>,
    ) -> Option<Task<HomeMessage>> {
        if let Some(opt_id) = optimistic_id {
            if let Some(pos) = self
                .messages
                .iter()
                .position(|m| m.is_optimistic && m.message_id == *opt_id)
            {
                // The canonical copy is already shown, so the bubble is the same
                // message a second time — it goes, the stored copy stays.
                if self.seen_ids.contains(message_id) {
                    self.messages.remove(pos);
                    self.sending = false;
                    return Some(self.maybe_snap());
                }
                // Fall back to the optimistic bubble's own reference when the
                // confirmed event carries none (robustness for agent/derived
                // confirmations that drop the reference).
                let reply = reply_reference.or_else(|| self.messages[pos].reply_reference.clone());
                self.messages[pos] = display_message(
                    None,
                    message_id.to_string(),
                    content.to_string(),
                    direction,
                    agent_role.map(std::string::ToString::to_string),
                    timestamp.map(std::string::ToString::to_string),
                    reply,
                    false,
                );
                // Track the canonical ID for dedup — the optimistic ID was
                // never added to seen_ids.
                self.seen_ids.insert(message_id.to_string());
                // User's own message confirmed by pipeline — clear sending
                // so the button re-enables.
                self.sending = false;
                return Some(self.maybe_snap());
            }
        }
        None
    }

    /// Try to deduplicate a message by its ID: `true` when it was already seen (the caller should
    /// bail). Fresh IDs go into `seen_ids`, which is pruned to the most recent [`DEDUP_RETAIN`]
    /// once it exceeds [`DEDUP_PRUNE_THRESHOLD`].
    fn try_dedup(&mut self, message_id: &str) -> bool {
        if self.seen_ids.contains(message_id) {
            return true;
        }
        self.seen_ids.insert(message_id.to_string());

        if self.seen_ids.len() > DEDUP_PRUNE_THRESHOLD {
            let retain: HashSet<String> = self
                .messages
                .iter()
                .rev()
                .take(DEDUP_RETAIN)
                .map(|m| m.message_id.clone())
                .collect();
            self.seen_ids.retain(|id| retain.contains(id));
        }
        false
    }

    /// Update typing/sending state from a message's direction and sender.
    ///
    /// An agent reply for the admin clears both `typing` and `sending`; the admin's own message
    /// echo clears `sending` only — the typing indicator persists until an agent responds.
    ///
    /// Does nothing when `workspace` is not the conversation's own: live work on project tickets
    /// must not clear the conversation's state.
    fn update_sending_state(&mut self, direction: ChatDirection, user_name: &str, workspace: &str) {
        if !Self::is_admin_personal_workspace(workspace) {
            return;
        }
        if !crate::users::is_admin_name(user_name) {
            return;
        }

        self.sending = false;
        if direction == ChatDirection::Agent {
            self.typing = false;
        }
    }

    /// Append a chat message if it belongs to the conversation: the admin's own chat in their
    /// personal workspace. Nothing else is shown here, so what is shown live can never disagree
    /// with what a later load reads.
    ///
    /// Does nothing when `user_name` is not the admin or `workspace` is not the conversation's own.
    /// Takes ownership of the fields to avoid extra clones; call
    /// [`maybe_snap()`](Self::maybe_snap) unconditionally after this.
    #[expect(clippy::too_many_arguments)]
    fn append_message(
        &mut self,
        user_name: &str,
        workspace: &str,
        message_id: String,
        content: String,
        direction: ChatDirection,
        agent_role: Option<String>,
        timestamp: Option<String>,
        reply_reference: Option<ReplyReference>,
    ) {
        if !crate::users::is_admin_name(user_name) {
            return;
        }
        if !Self::is_admin_personal_workspace(workspace) {
            return;
        }

        self.messages.push(display_message(
            None,
            message_id,
            content,
            direction,
            agent_role,
            timestamp,
            reply_reference,
            false,
        ));
    }

    #[expect(clippy::too_many_lines)]
    pub fn view(&self, draining: bool) -> Element<'_, HomeMessage> {
        let chat_area = if self.messages.is_empty() {
            let empty_hint = if self.selected_workspace.is_none() {
                "No workspace selected."
            } else {
                "No messages yet. Type something below to start."
            };
            // A failed read must render in place of the empty hint and stay
            // until a successful read replaces it — a log line or toast is
            // not enough.
            let body: Element<'_, HomeMessage> = if let Some(err) = &self.history_error {
                super::widgets::error_banner(err)
            } else {
                text(empty_hint)
                    .color(theme::TEXT_SECONDARY)
                    .size(theme::TEXT_13)
                    .into()
            };
            container(body)
                .width(Length::Fill)
                .height(Length::Fill)
                .center_x(Length::Fill)
                .center_y(Length::Fill)
                .style(theme::base_container_style)
                .into()
        } else {
            let mut children: Vec<Element<'_, HomeMessage>> = self
                .messages
                .iter()
                .map(|msg| {
                    if msg.direction == ChatDirection::Divider {
                        let label: Element<'_, HomeMessage> = container(
                            text("─ Session cleared ─")
                                .color(theme::TEXT_MUTED)
                                .size(theme::TEXT_12),
                        )
                        .center_x(Length::Fill)
                        .into();

                        let divider_rule = |_: &iced::Theme| rule::Style {
                            color: theme::TEXT_MUTED,
                            radius: 0.0.into(),
                            fill_mode: rule::FillMode::Padded(0),
                            snap: true,
                        };

                        let divider = column![
                            rule::horizontal(1).style(divider_rule),
                            label,
                            rule::horizontal(1).style(divider_rule),
                        ]
                        .spacing(theme::SPACE_4)
                        .padding(theme::PAD_8)
                        .width(Length::Fill);

                        return divider.into();
                    }

                    let is_user = msg.direction == ChatDirection::User;

                    // The body as two blocks: the attachments it carries (one
                    // group, in body order) above its whole text. Nothing draws
                    // a picture inline, so no text can be swallowed by one.
                    let content: Element<'_, HomeMessage> = super::media_markers::body(
                        &msg.attachments,
                        &msg.md_items,
                        theme::markdown_settings(),
                        HomeMessage::LinkClicked,
                        // Nothing parsed and nothing to draw: the raw content
                        // stands in (an empty body, or one whose only content
                        // the preprocessing strips).
                        || {
                            super::widgets::selectable_text(&msg.content, theme::TEXT_PRIMARY)
                                .size(theme::TEXT_13)
                                .into()
                        },
                    );

                    let bubble_body: Element<'_, HomeMessage> = if is_user {
                        content
                    } else {
                        // Strip the numeric role suffix (e.g. "analyst_3" → "analyst").
                        let maybe_role = msg
                            .agent_role
                            .as_deref()
                            .map(crate::channels::reply::strip_agent_role_suffix)
                            .and_then(|stripped| stripped.parse::<Role>().ok());
                        if let Some(role) = maybe_role {
                            let (icon_color, _) = theme::role_badge_color_for(&role);
                            let icon = theme::role_icon(&role)
                                .size(theme::TEXT_14)
                                .color(icon_color);
                            let mut icon_row = row![icon]
                                .align_y(Alignment::Center)
                                .spacing(theme::SPACE_6);
                            if let Some(ts) = msg.timestamp.as_deref() {
                                let label = theme::format_relative_time(ts, chrono::Local::now());
                                if !label.is_empty() {
                                    icon_row = icon_row.push(
                                        text(label)
                                            .size(theme::TEXT_11)
                                            .color(theme::TEXT_SECONDARY),
                                    );
                                }
                            }
                            column![icon_row, content].spacing(theme::SPACE_4).into()
                        } else {
                            content
                        }
                    };

                    let bubble = container(bubble_body)
                        .padding(theme::PAD_10)
                        .style(theme::bubble_style(
                            if is_user {
                                theme::BG_ELEVATED
                            } else {
                                theme::BG_SURFACE
                            },
                            Some(theme::TEXT_PRIMARY),
                        ))
                        .width(Length::FillPortion(3));

                    // Quote header for a replied-to message: rendered above the
                    // bubble (inside the same context-menu region) so a reply
                    // stays visually tied to its target. Just the reply glyph and
                    // the snippet — the quoted author is not named. Direction-
                    // agnostic: agent messages never carry references today, but
                    // the header renders whenever one is present.
                    let bubble_region: Element<'_, HomeMessage> =
                        if let Some(reply) = &msg.reply_reference {
                            column![reply_lead_row(reply), bubble.width(Length::Fill),]
                                .spacing(theme::SPACE_4)
                                .width(Length::FillPortion(3))
                                .into()
                        } else {
                            bubble.into()
                        };

                    // Per-bubble context menu: copy the raw markdown content and reply to it
                    // (hidden on optimistic placeholders; divider rows return earlier). Wrapping
                    // only the bubble region — not the align_bubble row — keeps the spacer beside
                    // it a fall-through, so its right-clicks reach the outer menu.
                    let mut menu_items = vec![MenuItem::new(
                        "Copy message".into(),
                        HomeMessage::CopyMessage(msg.content.clone()),
                    )];
                    if !msg.is_optimistic {
                        menu_items.push(MenuItem::with_icon(
                            iced_fonts::lucide::advanced_text::reply,
                            "Reply".into(),
                            HomeMessage::ReplyTo {
                                direction: msg.direction,
                                agent_role: msg.agent_role.clone(),
                                content: msg.content.clone(),
                            },
                        ));
                    }
                    let bubble: Element<'_, HomeMessage> =
                        ContextMenu::new(bubble_region, menu_items).into();

                    align_bubble(
                        bubble,
                        if is_user {
                            BubbleSide::Left
                        } else {
                            BubbleSide::Right
                        },
                    )
                })
                .collect();

            if self.typing {
                let dots = match self.typing_tick_state {
                    1 => "..",
                    2 => "...",
                    _ => ".",
                };
                let typing_dots = text(dots).size(20).color(theme::TEXT_MUTED);
                let typing_bubble = container(typing_dots)
                    .padding(theme::PAD_10)
                    .style(theme::bubble_style(theme::BG_SURFACE, None))
                    .width(Length::FillPortion(3));

                // Typing indicator always renders on the agent (right) side.
                children.push(align_bubble(typing_bubble, BubbleSide::Right));
            }

            // A failed history read must not leave the transcript looking
            // current: the failure stays above the loaded messages until a read
            // succeeds. (This is the resync case — with an empty transcript the
            // same failure renders in the empty state above.)
            if let Some(err) = &self.history_error {
                children.insert(
                    0,
                    super::widgets::scroll_h_inset(super::widgets::error_banner(err)),
                );
            }

            super::widgets::page_bare(super::widgets::vscroll_tracked(
                Column::with_children(children)
                    .spacing(super::widgets::CHAT_VERTICAL_RHYTHM)
                    .padding([theme::PAD_8, 0.0]),
                Length::Fill,
                Length::Fill,
                CHAT_SCROLL_ID,
                HomeMessage::ScrollChanged,
            ))
        };

        // The recording's own state decides the controls and the send button's
        // empty rule — the pipeline status only says whether the mic is free.
        let voice_status = crate::audio::voice::get_status();
        let recording = matches!(self.voice_message, Some(VoiceMessage::Recording));

        // Controls for the composer action toolbar — inert while the composer is
        // (a drain).
        let controls: Vec<Element<'_, HomeMessage>> =
            composer_controls(&voice_status, recording, draining);

        // Composer strip matches the BG_BASE chat pane so the empty space around
        // the rounded bubble blends with the page instead of showing a gray panel;
        // the 8px horizontal padding matches the chat scrollable wrapper's inset,
        // and the bottom padding matches the shared chat vertical rhythm.
        // The bubble itself keeps its own elevated styling.
        let composer: Element<'_, HomeMessage> = super::widgets::chat_composer(
            &self.editor_content,
            HomeMessage::InputChanged,
            HomeMessage::SendMessage,
            "Type a message... (Enter to send, Shift+Enter for newline)",
            super::widgets::ChatComposerOptions {
                // Input disabled during the graceful drain:
                // sends are blocked while draining.
                sending: self.in_flight() || draining,
                // The action toolbar sits below the editor, so no reserved
                // height is needed.
                min_height: 44.0,
                max_height: 330.0,
                controls,
                // An attachment-only message still sends, and so does a running
                // recording (the voice is the content): keep the button live.
                grey_on_empty: self.attachments.is_empty() && !recording,
                send_tooltip: if recording {
                    "stop recording and send"
                } else {
                    "send text message"
                },
                id: Some(CHAT_COMPOSER_ID),
                attachments_on_paste: true,
            },
        );

        // Attachment chips sit above the input bubble, in the same strip, and
        // only while the message has something attached. Picture tiles are
        // taller than file chips, so the row centres on their shared middle.
        let composer: Element<'_, HomeMessage> = if self.attachments.is_empty() {
            composer
        } else {
            let chips = row(self
                .attachments
                .iter()
                .enumerate()
                .map(|(index, attachment)| {
                    super::attachment::chip(attachment, HomeMessage::RemoveAttachment(index))
                }))
            .spacing(theme::SPACE_6)
            .align_y(Alignment::Center)
            .wrap();
            column![chips, composer].spacing(theme::SPACE_6).into()
        };

        let input_area: Element<'_, HomeMessage> = container(composer)
            .style(theme::base_container_style)
            .padding(
                iced::Padding::from([0.0, theme::PAD_8])
                    .bottom(super::widgets::CHAT_VERTICAL_RHYTHM),
            )
            .width(Length::Fill)
            .into();

        // Shown between the message list and the composer while a reply target
        // is pending; the dismiss control cancels it.
        let reply_preview: Element<'_, HomeMessage> = match &self.pending_reply {
            Some(reply) => reply_preview(reply),
            None => Space::new().height(0).into(),
        };

        column![chat_area, reply_preview, input_area,]
            .align_x(Alignment::End)
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

    pub fn subscription(&self) -> iced::Subscription<HomeMessage> {
        let mut subs = vec![iced::Subscription::run(chat_stream_producer)];

        // The typing-indicator tick only advances while the user is actually
        // typing; subscribe it only then to avoid waking the runtime at 2Hz
        // when idle. The handler already no-ops when `self.typing` is false.
        if self.typing {
            subs.push(iced::Subscription::run(typing_tick));
        }

        // The focus tick exists only until the composer has taken the keyboard.
        if self.pending_focus {
            subs.push(iced::time::every(FOCUS_TICK).map(|_| HomeMessage::FocusComposerOnce));
        }

        // A running recording's progress — the dot pulses on its own clock, so
        // no tick subscription is needed.
        subs.push(iced::Subscription::run(voice_recording_stream));

        iced::Subscription::batch(subs)
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, msg: HomeMessage) -> Task<HomeMessage> {
        match msg {
            HomeMessage::WorkspaceChanged(ws_name) => {
                // Recorded for the send path only: the selection decides the
                // workspace the work that follows runs in, and the conversation
                // is not its to touch.
                self.selected_workspace = Some(ws_name);
                Task::none()
            }
            HomeMessage::InputChanged(action) => match action {
                super::editor_widget::EditorAction::PasteAttachments {
                    attachments,
                    refused,
                } => self.attach(attachments, &refused),
                action => {
                    let changes_text = action.changes_text();
                    super::common::apply_editor_action(
                        &mut self.editor_content,
                        &mut self.undo_stack,
                        action,
                    );
                    if changes_text {
                        self.capture_draft(DRAFT_SETTLE_MS)
                    } else {
                        Task::none()
                    }
                }
            },
            HomeMessage::Attach {
                attachments,
                refused,
            } => self.attach(attachments, &refused),
            HomeMessage::PickAttachments => {
                Task::perform(pick_attachment_files(), HomeMessage::AttachmentsPicked)
            }
            HomeMessage::AttachmentsPicked(result) => {
                // The chooser took the keyboard; the composer takes it back
                // whether files arrived, the choice was cancelled, or the chooser
                // never opened.
                self.arm_composer_focus();
                match result {
                    Ok(Some(paths)) => {
                        let (attachments, refused) = super::attachment::intake(paths);
                        self.attach(attachments, &refused)
                    }
                    Ok(None) => Task::none(),
                    Err(error) => Task::done(HomeMessage::Toast(ToastMessage::Error(error))),
                }
            }
            HomeMessage::RemoveAttachment(index) => {
                if index < self.attachments.len() {
                    self.attachments.remove(index);
                }
                Task::none()
            }
            HomeMessage::FocusComposerOnce => {
                if !self.pending_focus {
                    return Task::none();
                }
                self.pending_focus = false;
                iced::widget::operation::focus(CHAT_COMPOSER_ID)
            }
            HomeMessage::SendMessage => self.send_message(),
            HomeMessage::Staged {
                generation,
                voice,
                text,
                attachments,
                result,
            } => {
                if generation != self.sending_gen {
                    // A send cleared while its copy ran: nothing will deliver
                    // it, so the staged copy goes back and the files with it. A
                    // dictated part it carried goes with the conversation the
                    // user cleared.
                    if let Ok(staged) = &result {
                        discard_staged(staged.dirs.clone());
                    }
                    self.restore_attachments(attachments);
                    return Task::none();
                }
                match result {
                    Ok(staged) => self.deliver(voice.as_deref(), &text, staged, attachments),
                    Err(error) => {
                        // Nothing of this send reached the transcript, so no
                        // bubble to remove — and a dictated part it carried is
                        // gone with it.
                        self.send_failed(
                            &text,
                            attachments,
                            None,
                            voice.is_some(),
                            HomeMessage::Toast(ToastMessage::Warning(error)),
                        )
                    }
                }
            }
            HomeMessage::HistoryLoaded {
                entries,
                generation,
            } => {
                // A superseded load belongs to a transcript the page has left.
                if generation != self.history_gen {
                    return Task::none();
                }
                self.history_error = None;
                self.replace_stored_history(entries);
                let onboarding = self.maybe_start_onboarding();
                Task::batch([self.maybe_snap(), onboarding])
            }
            HomeMessage::HistoryLoadError { generation, error } => {
                tracing::warn!(error = %error, "Home: failed to load chat history");
                // A failure from a superseded load belongs to a transcript the
                // page has left: it must not paint itself over the current one.
                if generation == self.history_gen {
                    self.history_error = Some(error);
                }
                Task::none()
            }
            HomeMessage::ClearChat => {
                // Clear messages synchronously first (prevents flash).
                self.messages.clear();
                self.seen_ids.clear();
                self.sending = false;
                // A voice message the cleared conversation was waiting for goes
                // with it: its transcript must not deliver into the fresh one. A
                // recording still capturing ends here too — its cancel control
                // went with the chat, so leaving it running would record into
                // nothing that could stop it.
                if let Some(VoiceMessage::Recording) = std::mem::take(&mut self.voice_message) {
                    crate::audio::voice::send_command(
                        crate::audio::voice::VoiceCommand::StopRecordingDiscard,
                    );
                }
                // A copy staged for the conversation being cleared must not
                // deliver into the fresh one; its generation no longer matches.
                self.sending_gen = self.sending_gen.wrapping_add(1);
                self.typing = false;
                self.typing_tick_state = 0;
                self.pending_reply = None;
                // The transcript this failure described is gone; the reload the
                // `ChatCleared` callback issues reports its own outcome.
                self.history_error = None;
                // A load in flight describes the transcript this clear just
                // dropped: superseding it keeps it from landing in front of the reload.
                self.history_gen = self.history_gen.wrapping_add(1);
                // A deliberate clear empties the screen (including a message
                // being sent) and re-arms the no-provider script, so the reset
                // conversation is shown from its own beginning at the bottom.
                self.onboarding_script_active = false;
                self.auto_scroll_enabled = true;
                // Capture synchronously (not from the ChatCleared callback): the
                // reply is dropped but the draft text is kept.
                let draft = self.capture_draft(DRAFT_SETTLE_MS);
                let sender = crate::users::ADMIN_USER_NAME.to_string();
                let clear_task = Task::perform(
                    async move {
                        // Clear the session the admin actually talks to — the
                        // same resolution as routing and Telegram /clear (see
                        // [`crate::users::resolve_session_target`]): the
                        // workspace resolves from the admin's DB record, never
                        // from the GUI picker position, and the Assistant is
                        // pinned to it — so the cleared session is always the
                        // admin's personal-workspace session.
                        let (effective_role, ws) =
                            crate::users::resolve_session_target(&sender).await;
                        // Fail-closed: a failed abandon aborts the clear — the
                        // session was not cleared, so no divider is inserted.
                        if let Err(e) = crate::session::clear_session(
                            &sender,
                            effective_role.as_str(),
                            &ws.name,
                        )
                        .await
                        {
                            tracing::warn!(
                                user = %sender,
                                error = %e,
                                "Home: clear failed — session kept"
                            );
                            return Err(e.to_string());
                        }
                        // Insert a divider marker instead of deleting history.
                        let store = crate::channels::chat_history::store();
                        match store.insert_divider(&sender, &ws.name).await {
                            Ok(()) => Ok(()),
                            Err(e) => {
                                tracing::warn!(
                                    user = %sender,
                                    workspace = %ws.name,
                                    error = %e,
                                    "Home: failed to insert chat divider"
                                );
                                Err(e.to_string())
                            }
                        }
                    },
                    |result| match result {
                        Ok(()) => HomeMessage::ChatCleared,
                        Err(e) => HomeMessage::ChatClearError(e),
                    },
                );
                Task::batch([draft, clear_task])
            }
            HomeMessage::ChatCleared => {
                // Belt and suspenders: ClearChat already cleared the message
                // list and this callback reloads the conversation, so drop any
                // pending reply explicitly.
                self.pending_reply = None;
                let toast = Task::done(HomeMessage::Toast(ToastMessage::SuccessMsg(
                    "Session cleared".to_string(),
                )));
                Task::batch([self.refresh_history(), toast])
            }
            HomeMessage::CopyMessage(content) => {
                // Raw markdown copy — no toast, matching the editor's
                // copy-path context-menu actions.
                iced::clipboard::write(content)
            }
            HomeMessage::ReplyTo {
                direction,
                agent_role,
                content,
            } => {
                self.pending_reply = Some(reply_reference_for(
                    direction,
                    agent_role.as_deref(),
                    &content,
                ));
                let draft = self.capture_draft(DRAFT_SETTLE_MS);
                // Refocus the composer so the user can type the reply
                // immediately, matching the select-to-focus affordance
                // established by the composer's `Id`. The field takes the
                // text-selection shortcuts with the keyboard.
                super::selectable::deactivate();
                Task::batch([
                    iced::widget::operation::focus::<HomeMessage>(CHAT_COMPOSER_ID),
                    draft,
                ])
            }
            HomeMessage::CancelReply => {
                self.pending_reply = None;
                self.capture_draft(DRAFT_SETTLE_MS)
            }
            HomeMessage::DraftSaveSettled { generation } => {
                if self.draft_save.should_process(generation) {
                    self.drafts.clone().persist_async();
                }
                Task::none()
            }
            HomeMessage::ChatClearError(e) => {
                Task::done(HomeMessage::Toast(ToastMessage::Error(e)))
            }
            HomeMessage::ChatEvent(event) => match event {
                crate::ChatEvent::Message {
                    message_id,
                    user_name,
                    content,
                    direction,
                    timestamp,
                    channel: _,
                    agent_role,
                    workspace,
                    optimistic_id,
                    reply_reference,
                    ..
                } => {
                    if let Some(task) = self.replace_optimistic(
                        optimistic_id.as_deref(),
                        &message_id,
                        &content,
                        direction,
                        agent_role.as_deref(),
                        Some(timestamp.as_str()),
                        reply_reference.clone(),
                    ) {
                        return task;
                    }

                    // Sending/typing state is cleared before the dedup: a confirmation whose
                    // row a load already brought in is dropped below, and it must still free
                    // the composer rather than leave the send guard holding it.
                    self.update_sending_state(direction, &user_name, &workspace);

                    if self.try_dedup(&message_id) {
                        return Task::none();
                    }

                    self.append_message(
                        &user_name,
                        &workspace,
                        message_id,
                        content,
                        direction,
                        agent_role,
                        Some(timestamp),
                        reply_reference,
                    );

                    self.maybe_snap()
                }
                crate::ChatEvent::Typing {
                    user_name,
                    is_typing,
                    workspace,
                } => {
                    // Apply user + workspace filter — only show typing indicator
                    // for the admin in the conversation's own workspace.
                    if crate::users::is_admin_name(&user_name)
                        && Self::is_admin_personal_workspace(&workspace)
                    {
                        self.typing = is_typing;
                        if is_typing {
                            self.typing_tick_state = 0;
                        }
                    }
                    Task::none()
                }
            },
            HomeMessage::StreamLagged => {
                // Resync through the one load path. Clearing `sending` is the
                // safety net for an agent response the lag swallowed —
                // otherwise the send button stays stuck.
                self.sending = false;
                self.refresh_history()
            }
            HomeMessage::ScrollChanged(viewport) => {
                // The fit check must stay first: `relative_offset` divides by
                // the content/viewport height difference, so a fitting
                // transcript reads as not-pinned there (exact fit is 0/0).
                self.auto_scroll_enabled = viewport.content_bounds().height
                    <= viewport.bounds().height
                    || viewport.relative_offset().y >= 0.99;
                Task::none()
            }
            HomeMessage::Toast(_) => {
                // Intercepted by the Dashboard (Toast → toast stack). No-op fallback.
                Task::none()
            }
            HomeMessage::LinkClicked(url) => {
                if let Some(target) = super::media_markers::file_link_target(&url) {
                    let target = target.to_string();
                    let workspace = HomeState::conversation_workspace_path();
                    // The reveal stats and spawns a launcher: keep it out of the
                    // update handler.
                    Task::perform(
                        async move {
                            super::media_markers::reveal_file_marker(&target, Some(&workspace))
                        },
                        HomeMessage::FileRevealed,
                    )
                } else {
                    super::open_url(&url);
                    Task::none()
                }
            }
            HomeMessage::FileRevealed(result) => match result {
                Ok(()) => Task::none(),
                Err(error) => Task::done(HomeMessage::Toast(ToastMessage::Error(error))),
            },
            HomeMessage::TypingTick => {
                if self.typing {
                    self.typing_tick_state = (self.typing_tick_state + 1) % 3;
                }
                Task::none()
            }
            HomeMessage::SendingTimeout(generation) => {
                // Only clear sending if the generation counter matches —
                // a stale timeout from a previous send should be ignored.
                if generation == self.sending_gen && self.sending {
                    self.sending = false;
                }
                Task::none()
            }
            HomeMessage::StartVoiceRecording => {
                // A window the composer already owns belongs to a running
                // recording — whichever way it started — so this press adds
                // nothing to it.
                if self.voice_message.is_some() {
                    return Task::none();
                }
                // Best-effort pre-flight check surfaced by the pipeline itself
                // (single source of truth for the blocked-state mapping). The
                // pipeline remains the authoritative guard — this predicate can
                // drift on transient transitions but covers the common cases.
                if let Some(msg) = crate::audio::voice::recording_blocked_reason() {
                    return Task::done(HomeMessage::Toast(ToastMessage::Warning(msg.to_string())));
                }
                // The recording's message owns the field from here: a press
                // commits it, and the pipeline's outcome resolves it. With no
                // pipeline to record, nothing owns anything.
                if !crate::audio::voice::send_command(
                    crate::audio::voice::VoiceCommand::StartRecording,
                ) {
                    return Task::none();
                }
                self.voice_message = Some(VoiceMessage::Recording);
                Task::none()
            }
            HomeMessage::StopVoiceRecordingDiscard => {
                // Only a still-capturing recording can be discarded: once the
                // field is committed to its message, dropping the audio would
                // strand that message.
                if !matches!(self.voice_message, Some(VoiceMessage::Recording)) {
                    return Task::none();
                }
                // The composer drops its own message window, so nothing waits
                // for this recording's outcome — and with the window gone, so is
                // this control: it can never be left dead over a live recording.
                self.voice_message = None;
                crate::audio::voice::send_command(
                    crate::audio::voice::VoiceCommand::StopRecordingDiscard,
                );
                Task::none()
            }
            HomeMessage::VoiceRecording(event) => self.voice_recording(event),
            HomeMessage::OnboardingScriptCompleted => {
                self.sending = false;
                self.onboarding_script_active = false;
                self.maybe_start_onboarding()
            }
            HomeMessage::OnboardingScriptRePrompt => {
                self.sending = false;
                Task::none()
            }
            HomeMessage::OnboardingKickoffDone => Task::none(),
        }
    }

    /// Send button or Enter in the editor. While a recording owns the field —
    /// whichever way it started — the press belongs to its message (see
    /// [`Self::send_voice_message`]).
    fn send_message(&mut self) -> Task<HomeMessage> {
        if self.voice_message.is_some() {
            return self.send_voice_message();
        }
        let (text, attachments) = match self.take_composer_content(false) {
            Ok(taken) => taken,
            Err(task) => return task,
        };
        self.send_taken(None, text, attachments)
    }

    /// A press while a recording owns the field: commit what it holds — the
    /// message is on its way with the field's content from this moment — and stop
    /// the recording, so its transcript joins that one message. A press after the
    /// commit finds the message already in flight and does nothing.
    fn send_voice_message(&mut self) -> Task<HomeMessage> {
        if matches!(self.voice_message, Some(VoiceMessage::Committed { .. })) {
            return Task::none();
        }
        if let Err(refusal) = self.commit_voice_content() {
            // The field keeps its content, and a recording still capturing can
            // carry it on a later press.
            return refusal;
        }
        if crate::audio::voice::send_command(crate::audio::voice::VoiceCommand::StopRecordingSend) {
            return Task::none();
        }
        // Nothing took the stop, so no transcript will ever join the committed
        // message: give the field back and say the voice part is gone.
        if let Some(VoiceMessage::Committed { text, attachments }) = self.voice_message.take() {
            return self.send_failed(&text, attachments, None, true, Self::send_refused_toast());
        }
        Task::none()
    }

    /// Commit the field to the recording's message: its content leaves the
    /// composer and waits for the transcript. Idempotent — a window that is
    /// already resolved is left alone, so the recording's own stop after a press
    /// finds it done.
    fn commit_voice_content(&mut self) -> Result<(), Task<HomeMessage>> {
        if !matches!(self.voice_message, Some(VoiceMessage::Recording)) {
            return Ok(());
        }
        let (text, attachments) = self.take_composer_content(true)?;
        self.voice_message = Some(VoiceMessage::Committed { text, attachments });
        Ok(())
    }

    /// Take the composer's content for a send: validate it and empty the field.
    /// `has_voice` says the send carries a dictated part, which is content on its
    /// own — a recording that captured nothing typed or attached still sends itself.
    fn take_composer_content(
        &mut self,
        has_voice: bool,
    ) -> Result<(String, Vec<super::attachment::Attachment>), Task<HomeMessage>> {
        let text = self.editor_content.text();
        let trimmed = super::common::send_guard(
            &text,
            self.in_flight(),
            // Attachments alone are a message, and so is a recording; the length
            // limit applies to the typed text only.
            super::common::SendRules::Chat {
                has_content: has_voice || !self.attachments.is_empty(),
            },
            |count| {
                Task::done(HomeMessage::Toast(ToastMessage::Warning(format!(
                    "Message too long: {count} characters (maximum {MAX_INPUT_CHARS}). Please shorten your message and try again."
                ))))
            },
        )?;

        // Guard against sending without a selected workspace.
        if self.selected_workspace.is_none() {
            tracing::warn!("Home: attempted to send message without a workspace selected");
            return Err(Task::none());
        }

        // The scripted setup exchange reads the provider's settings and never
        // reaches the pipeline, so nothing attached could be delivered from it.
        if self.onboarding_script_active && !self.attachments.is_empty() {
            return Err(Task::done(HomeMessage::Toast(ToastMessage::Warning(
                "Attachments cannot be sent during setup. Remove them to continue.".to_string(),
            ))));
        }

        // A command is read from the message's first character, and a
        // message's attachment markers lead its text. A dictated part needs no
        // guard: the composed message opens with the spoken marker, so nothing
        // reads it as a command.
        if trimmed.starts_with('/') && !self.attachments.is_empty() {
            return Err(Task::done(HomeMessage::Toast(ToastMessage::Warning(
                "A command cannot carry attachments. Send them in a message of their own."
                    .to_string(),
            ))));
        }

        // The send owns its text and files from here on: clearing the composer
        // now means anything typed or attached while a copy runs is new, and a
        // failed copy cannot lose it.
        self.editor_content.clear();
        self.undo_stack.clear();
        self.drop_draft();
        Ok((trimmed.to_string(), std::mem::take(&mut self.attachments)))
    }

    /// Stage a taken send's attachments and hand the message to the pipeline.
    /// Staging copies up to the product's file cap, so it runs as a task and the
    /// send continues in [`HomeMessage::Staged`]; `voice` is the dictated part
    /// the message leads with, when it has one.
    fn send_taken(
        &mut self,
        voice: Option<String>,
        text: String,
        attachments: Vec<super::attachment::Attachment>,
    ) -> Task<HomeMessage> {
        // The send is in flight from here: the composer stays locked through the
        // copy and until the message is acknowledged.
        self.sending = true;
        if attachments.is_empty() {
            return self.deliver(
                voice.as_deref(),
                &text,
                super::attachment::Staged::default(),
                attachments,
            );
        }

        // Up to the attachment size cap is copied here: stage it off the update
        // thread so the window keeps painting. The timeout guard is armed for
        // the copy too, and names this send so a result that arrives after it
        // was cleared does not deliver anything.
        let timeout = self.sending_timeout_task();
        let generation = self.sending_gen;
        let staging = attachments.clone();
        Task::batch([
            timeout,
            Task::perform(
                async move { super::attachment::stage(&staging).await },
                move |result| HomeMessage::Staged {
                    generation,
                    voice,
                    text,
                    attachments,
                    result,
                },
            ),
        ])
    }

    /// Whether a send is in flight from the composer: an ordinary one, or a
    /// voice message whose transcript has not arrived yet.
    ///
    /// A voice send puts nothing on the wire until its transcript joins it, so `sending` cannot
    /// stand for that window; the committed message keeps the composer locked instead, with no
    /// timeout, because transcribing may take as long as the recording did.
    fn in_flight(&self) -> bool {
        self.sending || matches!(self.voice_message, Some(VoiceMessage::Committed { .. }))
    }

    /// Put a send's attachments back in front of anything attached since.
    fn restore_attachments(&mut self, mut attachments: Vec<super::attachment::Attachment>) {
        attachments.append(&mut self.attachments);
        self.attachments = attachments;
    }

    /// Give a send that never reached the pipeline back to the composer: the
    /// attachments, the typed text when nothing has been typed since — put back
    /// as a draft too, since sending cleared it — and no optimistic bubble left behind.
    fn restore_send(
        &mut self,
        text: &str,
        attachments: Vec<super::attachment::Attachment>,
        optimistic_id: Option<&str>,
    ) -> Task<HomeMessage> {
        self.sending = false;
        self.restore_attachments(attachments);
        if let Some(id) = optimistic_id {
            self.messages
                .retain(|message| !(message.is_optimistic && message.message_id == id));
        }
        if !self.editor_content.text().is_empty() {
            return Task::none();
        }
        self.editor_content.set_text(text);
        self.capture_draft(DRAFT_SETTLE_MS)
    }

    /// Take in what an intake produced: the attachments join the message being
    /// composed, and the names it refused are reported.
    fn attach(
        &mut self,
        attachments: Vec<super::attachment::Attachment>,
        refused: &[String],
    ) -> Task<HomeMessage> {
        self.attachments.extend(attachments);
        refused_toast(refused)
    }

    /// Hand a validated message to the pipeline: its content (see
    /// [`compose_content`]), an optimistic bubble, and the pending reply cleared
    /// once it is queued. The composer was cleared when the send started, so
    /// every way out of here that is not a queued send gives the text and the
    /// attachments back ([`Self::restore_send`]) — the dictated part cannot come
    /// back, and its loss is reported.
    fn deliver(
        &mut self,
        voice: Option<&str>,
        trimmed: &str,
        staged: super::attachment::Staged,
        attachments: Vec<super::attachment::Attachment>,
    ) -> Task<HomeMessage> {
        let sender = crate::users::ADMIN_USER_NAME.to_string();

        let super::attachment::Staged { dirs, markers } = staged;
        // The urgent mark is read on the text the user typed, before the
        // dictated part and the attachment markers are composed around it, so
        // the optimistic bubble and the stored history show the message without
        // it. A transcript never decides urgency.
        let (typed, urgent) = crate::channels::take_urgent(trimmed);
        let content = compose_content(voice, &markers, &typed);

        // Generate an optimistic ID for non-command messages so the Home page can show the user's
        // message at once and replace it when the pipeline confirms. A command is read from what
        // was typed, only when it leads the message; it is NOT optimistically shown, because
        // `handle_bot_command` intercepts it before the GUI broadcast and the confirmation never
        // arrives, leaving an orphan entry.
        let is_command = voice.is_none() && markers.is_empty() && trimmed.starts_with('/');
        let optimistic_id = if is_command {
            None
        } else {
            Some(crate::generate_id())
        };

        // Push optimistic message immediately so the user sees their own
        // message without waiting for the pipeline round-trip. The pending
        // reply reference (if any) attaches to the bubble so the quote header
        // renders live; the scripted onboarding path must never flash one, so
        // the reference is skipped (and left untouched) there.
        if let Some(ref opt_id) = optimistic_id {
            let reply = if self.onboarding_script_active {
                None
            } else {
                self.pending_reply.clone()
            };
            // Carries the instant it was sent: the load reconciles it against
            // the stored copy of the same send (see `replace_stored_history`).
            // A user bubble renders no time label, so this is not displayed.
            self.messages.push(display_message(
                None,
                opt_id.clone(),
                content.clone(),
                ChatDirection::User,
                None,
                Some(crate::db::now()),
                reply,
                true,
            ));
        }

        // Phase-1 scripted onboarding intercepts the send before the pipeline:
        // the provider entry is parsed and persisted directly, and the
        // exchange is rendered as transient (never persisted) events. The
        // pending reply is dropped with the send — scripted messages never
        // carry one, and a stale reference must not attach to a later send.
        if self.onboarding_script_active {
            // The exchange takes the text, but nothing of a staged copy reaches
            // it: a copy that started before the exchange did gives its files
            // back to the composer.
            discard_staged(dirs);
            self.restore_attachments(attachments);
            self.pending_reply = None;
            return self.send_scripted_message(content, optimistic_id);
        }

        // Capture the pending reply reference for the confirmed message — a
        // command-based message (no optimistic bubble) still carries it so it
        // surfaces on the confirmed bubble via the ChatEvent. Cleared only
        // after the send is queued (see below).
        let reply = self.pending_reply.clone();

        let msg = crate::ChannelMessage {
            user_name: sender.clone(),
            reply_target: sender,
            content,
            channel: "gui".to_string(),
            workspace: self.selected_workspace.clone().unwrap_or_default(),
            attachment_dirs: dirs,
            optimistic_id,
            reply_reference: reply,
            dictated: voice.is_some(),
            urgent,
            ..Default::default()
        };

        // Push to GUI_MESSAGE_TX. A send that never reaches the pipeline gives
        // its staged copy back, so a retry does not leave it in the temp root,
        // and gives the composer back what it cleared.
        let Some(tx) = crate::GUI_MESSAGE_TX.get() else {
            tracing::error!("Home: GUI_MESSAGE_TX not initialized");
            discard_staged(msg.attachment_dirs);
            return self.send_failed(
                trimmed,
                attachments,
                msg.optimistic_id.as_deref(),
                voice.is_some(),
                Self::send_refused_toast(),
            );
        };
        if let Err(error) = tx.send(msg) {
            tracing::error!("Home: failed to send message via GUI_MESSAGE_TX: {error}");
            discard_staged(error.0.attachment_dirs);
            return self.send_failed(
                trimmed,
                attachments,
                error.0.optimistic_id.as_deref(),
                voice.is_some(),
                Self::send_refused_toast(),
            );
        }

        // The send was queued: drop the pending reply so the preview clears.
        self.pending_reply = None;

        // Snap to end on optimistic push if auto-scroll enabled.
        Task::batch([self.sending_timeout_task(), self.maybe_snap()])
    }

    /// Give a send that could not go out back to the composer, report `why`, and
    /// — when it carried a dictated part, which no other message can carry —
    /// report that loss too.
    fn send_failed(
        &mut self,
        text: &str,
        attachments: Vec<super::attachment::Attachment>,
        optimistic_id: Option<&str>,
        has_voice: bool,
        why: HomeMessage,
    ) -> Task<HomeMessage> {
        let restored = self.restore_send(text, attachments, optimistic_id);
        let lost = if has_voice {
            self.voice_notice(VoiceNotice::Failed(
                crate::audio::voice::VOICE_UNSENT_NOTICE,
            ))
        } else {
            Task::none()
        };
        Task::batch([restored, Task::done(why), lost])
    }

    fn send_refused_toast() -> HomeMessage {
        HomeMessage::Toast(ToastMessage::Error(
            "The message could not be sent. Try again.".to_string(),
        ))
    }

    /// Report a recording's outcome in the conversation, at most one of its
    /// class per [`crate::audio::voice::NOTICE_INTERVAL`] — the windows the
    /// pipeline's own notices keep, so a rapid repeat cannot become a stream and
    /// a discard cannot silence a failure.
    fn voice_notice(&mut self, notice: VoiceNotice) -> Task<HomeMessage> {
        let (at, message) = match notice {
            VoiceNotice::Discarded(message) => (&mut self.voice_notice_at, message),
            VoiceNotice::Failed(message) => (&mut self.voice_error_at, message),
        };
        if at.is_some_and(|last| last.elapsed() < crate::audio::voice::NOTICE_INTERVAL) {
            return Task::none();
        }
        *at = Some(std::time::Instant::now());
        Task::future(crate::audio::voice::broadcast_notice(message)).discard()
    }

    /// Take in a voice recording's progress. Every outcome resolves the message
    /// the recording owns: the transcript completes it, a silent recording leaves
    /// only the field's own content to send, and a lost one gives the field back
    /// and says why.
    fn voice_recording(&mut self, event: RecordingEvent) -> Task<HomeMessage> {
        match event {
            // A recording began — the wake word's; a mic press opens the window
            // itself. One message at a time: a window still committed to an
            // earlier recording cannot take a second transcript, so this
            // recording is dropped rather than poured into that message.
            RecordingEvent::Started => {
                if matches!(self.voice_message, Some(VoiceMessage::Committed { .. })) {
                    crate::audio::voice::send_command(
                        crate::audio::voice::VoiceCommand::StopRecordingDiscard,
                    );
                } else if self.voice_message.is_none() {
                    self.voice_message = Some(VoiceMessage::Recording);
                }
                Task::none()
            }
            // A stopped recording: a press committed the field already, and both
            // the ten-minute cap and the wake word's silence end stop one no press
            // did. A refused commit keeps the field — the loss is reported when
            // the transcript has nowhere to go.
            RecordingEvent::Stopped => match self.commit_voice_content() {
                Ok(()) => Task::none(),
                Err(refusal) => refusal,
            },
            RecordingEvent::Transcript(transcript) => match self.voice_message.take() {
                Some(VoiceMessage::Committed { text, attachments }) => {
                    self.send_taken(Some(transcript), text, attachments)
                }
                // The press was refused (too long, no workspace): the words
                // exist only in this recording.
                Some(VoiceMessage::Recording) => self.voice_notice(VoiceNotice::Failed(
                    crate::audio::voice::VOICE_UNSENT_NOTICE,
                )),
                None => Task::none(),
            },
            // The recording caught nothing to say: the field's own content, if
            // it holds any, goes out as an ordinary message, and an empty one is
            // told the recording was discarded.
            RecordingEvent::NoSpeech => {
                self.send_without_words(Some(crate::audio::voice::NO_SPEECH_NOTICE))
            }
            RecordingEvent::Failed(notice) => match self.voice_message.take() {
                Some(VoiceMessage::Committed { text, attachments }) => {
                    let restored = self.restore_send(&text, attachments, None);
                    Task::batch([restored, self.voice_notice(VoiceNotice::Failed(notice))])
                }
                // The field was never committed: only the recording is lost, and
                // the notice names why.
                Some(VoiceMessage::Recording) => self.voice_notice(VoiceNotice::Failed(notice)),
                // The message went with a cleared chat; the user cleared the
                // conversation on purpose.
                None => Task::none(),
            },
            // A start that did not take: the window it opened closes, and a
            // message a press already committed can never get a transcript. The
            // recording contributed nothing, so the field's own content goes out
            // — and the pipeline's own notice already said why it never began.
            RecordingEvent::NotStarted => self.send_without_words(None),
        }
    }

    /// Resolve a recording that brought no words: what the press committed goes
    /// out as an ordinary message, and a message with nothing in it is reported
    /// as a discarded recording only when `discard` names the notice.
    fn send_without_words(&mut self, discard: Option<&'static str>) -> Task<HomeMessage> {
        match self.voice_message.take() {
            Some(VoiceMessage::Committed { text, attachments })
                if !text.is_empty() || !attachments.is_empty() =>
            {
                self.send_taken(None, text, attachments)
            }
            Some(VoiceMessage::Committed { .. }) => match discard {
                Some(notice) => self.voice_notice(VoiceNotice::Discarded(notice)),
                None => Task::none(),
            },
            // Nothing was committed: the field keeps its own content and lost nothing.
            Some(VoiceMessage::Recording) | None => Task::none(),
        }
    }

    /// Arm the 30-second SendingTimeout guard: if `sending` stays true for 30
    /// seconds (silent agent failure, crash, cancellation), auto-clear it. The
    /// generation counter prevents a stale timeout from clearing `sending`
    /// during a new send.
    fn sending_timeout_task(&mut self) -> Task<HomeMessage> {
        self.sending_gen = self.sending_gen.wrapping_add(1);
        let generation = self.sending_gen;
        Task::perform(
            async move {
                tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                HomeMessage::SendingTimeout(generation)
            },
            |msg| msg,
        )
    }

    /// Handle a Phase-1 scripted submit: broadcast the user's message
    /// (transient, replacing the optimistic bubble), persist the provider
    /// input, broadcast the success or re-prompt message, then emit the
    /// completion/re-prompt message.
    fn send_scripted_message(
        &mut self,
        content: String,
        optimistic_id: Option<String>,
    ) -> Task<HomeMessage> {
        let user = crate::users::ADMIN_USER_NAME;
        let workspace = Self::conversation_workspace();
        let send_task = Task::perform(
            async move {
                let parsed = crate::onboarding::parse_provider_input(&content);
                // Replace the optimistic bubble with the user's transient message.
                broadcast_gui_transient(
                    user,
                    &workspace,
                    &crate::generate_id(),
                    &content,
                    crate::ChatDirection::User,
                    None,
                    optimistic_id,
                );
                let outcome: Result<(), String> = match parsed {
                    crate::onboarding::ProviderInput::Invalid => {
                        broadcast_gui_transient(
                            user,
                            &workspace,
                            &crate::generate_id(),
                            crate::onboarding::invalid_message(),
                            crate::ChatDirection::Agent,
                            Some("assistant".to_string()),
                            None,
                        );
                        Err("invalid provider input".to_string())
                    }
                    valid => match crate::onboarding::persist_provider_input(&valid).await {
                        Ok(()) => {
                            broadcast_gui_transient(
                                user,
                                &workspace,
                                &crate::generate_id(),
                                crate::onboarding::success_message(),
                                crate::ChatDirection::Agent,
                                Some("assistant".to_string()),
                                None,
                            );
                            Ok(())
                        }
                        Err(e) => {
                            broadcast_gui_transient(
                                user,
                                &workspace,
                                &crate::generate_id(),
                                &format!("Couldn't save that: {e:#}"),
                                crate::ChatDirection::Agent,
                                Some("assistant".to_string()),
                                None,
                            );
                            Err(e.to_string())
                        }
                    },
                };
                match outcome {
                    Ok(()) => HomeMessage::OnboardingScriptCompleted,
                    Err(_) => HomeMessage::OnboardingScriptRePrompt,
                }
            },
            std::convert::identity,
        );
        Task::batch([send_task, self.sending_timeout_task()])
    }
}

/// Stream producer for chat events from CHAT_BROADCAST.
fn chat_stream_producer() -> impl futures_util::Stream<Item = HomeMessage> {
    super::common::broadcast_stream_producer(16, &crate::CHAT_BROADCAST, |output, item| {
        let msg = match item {
            Some(event) => HomeMessage::ChatEvent(event),
            None => HomeMessage::StreamLagged,
        };
        Box::pin(async move {
            let _ = output.send(msg).await;
        })
    })
}

/// Stream producer for a voice recording's progress: the composer commits
/// the field as the recording stops and completes the message once the
/// transcript is known.
fn voice_recording_stream() -> impl futures_util::Stream<Item = HomeMessage> {
    super::common::broadcast_stream_producer(16, &crate::audio::voice::RECORDING, |output, item| {
        // A lagged stream loses no press: the events are one per recording
        // and the channel is far larger than that.
        Box::pin(async move {
            if let Some(event) = item {
                let _ = output.send(HomeMessage::VoiceRecording(event)).await;
            }
        })
    })
}

/// Emit `TypingTick` every 500ms for the typing indicator animation.
fn typing_tick() -> impl futures_util::Stream<Item = HomeMessage> {
    iced::stream::channel(
        1,
        move |mut output: iced::futures::channel::mpsc::Sender<HomeMessage>| async move {
            loop {
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                if output.send(HomeMessage::TypingTick).await.is_err() {
                    break;
                }
            }
        },
    )
}

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

    #[test]
    fn a_sent_message_orders_its_dictated_part_first() {
        let spoken = "🔊✍️ spoken";
        assert_eq!(compose_content(Some(spoken), "", ""), spoken);
        let ordered = "🔊✍️ spoken\n\n[IMAGE:/a.png]\n\ntyped";
        assert_eq!(
            compose_content(Some(spoken), "[IMAGE:/a.png]", "typed"),
            ordered
        );
        assert_eq!(
            compose_content(None, "[IMAGE:/a.png]", "typed"),
            "[IMAGE:/a.png]\n\ntyped"
        );
    }

    fn make_home_state(workspace: &str) -> HomeState {
        let mut state = HomeState::new();
        // Hermetic draft store bound to a throwaway temp dir so tests never
        // touch the real draft file.
        state.drafts = hermetic_draft_store();
        // The selection is recorded for the send path only: the conversation
        // does not depend on it.
        state.selected_workspace = Some(workspace.to_string());
        state
    }

    fn stored_entry(id: i64, message_id: &str, content: &str) -> ChatHistoryEntry {
        ChatHistoryEntry {
            id,
            message_id: message_id.to_string(),
            content: content.to_string(),
            direction: ChatDirection::User,
            agent_role: None,
            timestamp: None,
            reply_reference: None,
        }
    }

    fn timestamped_entry(
        id: i64,
        message_id: &str,
        content: &str,
        timestamp: &str,
    ) -> ChatHistoryEntry {
        let mut entry = stored_entry(id, message_id, content);
        entry.timestamp = Some(timestamp.to_string());
        entry
    }

    /// A draft store backed by a unique throwaway file under one shared test
    /// temp dir, so tests never touch the real draft file.
    fn hermetic_draft_store() -> Arc<crate::channels::chat_draft::DraftStore> {
        static DIR: std::sync::LazyLock<tempfile::TempDir> =
            std::sync::LazyLock::new(|| tempfile::tempdir().unwrap());
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        crate::channels::chat_draft::DraftStore::at(Some(
            DIR.path().join(format!("draft-{n}.json")),
        ))
    }

    fn said(text: &str, direction: ChatDirection) -> DisplayMessage {
        display_message(
            None,
            "m1".into(),
            text.into(),
            direction,
            None,
            None,
            None,
            false,
        )
    }

    #[test]
    fn a_marker_naming_a_file_is_an_attachment_in_every_message() {
        // Both directions follow one rule: a file-shaped target is a row.
        // (case, the message, the attachment label it becomes, if any)
        let cases = [
            (
                "a marker naming a file is an attachment",
                "see [IMAGE:generated/poster.png]",
                Some("🖼️ poster.png"),
            ),
            (
                // A marker naming nothing is prose in both, and is never rewritten —
                // the whole example, angle brackets included, reaches the parser as
                // text. (`<path in your workspace>` is shape-unambiguously not a
                // path, unlike a bare word that a workspace file could match.)
                "a marker naming nothing stays prose",
                "reference the output with [FILE:<path in your workspace>]",
                None,
            ),
        ];
        for (name, text, attachment) in cases {
            for direction in [ChatDirection::Agent, ChatDirection::User] {
                let message = said(text, direction);
                let rendered = rendered_text(&message.md_items);
                let rows: Vec<&str> = message
                    .attachments
                    .iter()
                    .map(|a| a.label.as_str())
                    .collect();
                let wanted: Vec<&str> = attachment.into_iter().collect();
                assert_eq!(rows, wanted, "case {name}: the rows");
                assert!(!rendered.contains("[IMAGE:"), "case {name}: {rendered:?}");
                let kept = rendered.contains(text);
                assert_eq!(kept, attachment.is_none(), "case {name}: text stays");
            }
        }
    }

    /// All paragraph text a rendered body carries, flattened, for asserting on
    /// what the user reads.
    fn rendered_text(items: &[iced::widget::markdown::Item]) -> String {
        let style = crate::gui::theme::markdown_settings().style;
        let paragraph = |text: &iced::widget::markdown::Text| -> String {
            text.spans(style)
                .iter()
                .map(|span| span.text.to_string())
                .collect()
        };
        items
            .iter()
            .filter_map(|item| match item {
                iced::widget::markdown::Item::Paragraph(text) => Some(paragraph(text)),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn the_chat_has_one_draft_and_a_workspace_switch_leaves_it_alone() {
        let mut state = make_home_state("ws1");
        // Typing captures synchronously into the one draft.
        let _ = state.update(HomeMessage::InputChanged(EditorAction::Insert('h')));
        assert_eq!(state.drafts.get().text, "h");

        // The workspace swap does not touch the composer: the text stays, and
        // the draft is still the same single draft.
        for picker in ["ws2", "ws1"] {
            let _ = state.update(HomeMessage::WorkspaceChanged(picker.to_string()));
            assert_eq!(state.editor_content.text(), "h", "case {picker}: text kept");
            assert_eq!(state.drafts.get().text, "h", "case {picker}: one draft");
        }
    }

    #[test]
    fn restore_brings_back_the_text_and_its_pending_reply() {
        let mut state = make_home_state("ws1");
        let reply = reply_reference_for(ChatDirection::Agent, Some("assistant"), "hi there");
        state.drafts.set("typed".to_string(), Some(reply.clone()));

        // The app's opening brings the stored draft back; the boot selection
        // push lands after it and leaves the composer as it is.
        let _ = state.open();
        let _ = state.update(HomeMessage::WorkspaceChanged("ws2".to_string()));
        assert_eq!(state.editor_content.text(), "typed");
        assert_eq!(state.pending_reply, Some(reply));
        assert_eq!(state.history_gen, 1, "the opening issues exactly one load");

        // ...and a later picker change leaves it alone.
        let _ = state.update(HomeMessage::WorkspaceChanged("ws1".to_string()));
        assert_eq!(state.editor_content.text(), "typed");
        assert!(state.pending_reply.is_some());
    }

    #[test]
    fn failed_reads_stay_set_until_a_successful_load() {
        let mut state = HomeState::new();
        let g = state.history_gen;
        let error = |error: &str, generation: u64| HomeMessage::HistoryLoadError {
            generation,
            error: error.to_string(),
        };
        let loaded = |entries: Vec<ChatHistoryEntry>, generation: u64| HomeMessage::HistoryLoaded {
            entries,
            generation,
        };

        // A failed read of the current load is retained; a failure from a
        // superseded load is dropped.
        let _ = state.update(error("db down", g));
        assert_eq!(state.history_error.as_deref(), Some("db down"));
        let _ = state.update(error("stale", g.wrapping_sub(1)));
        assert_eq!(state.history_error.as_deref(), Some("db down"));

        // A superseded load replaces nothing and keeps the current failure.
        let _ = state.update(loaded(Vec::new(), g.wrapping_sub(1)));
        assert_eq!(state.history_error.as_deref(), Some("db down"));
        assert!(
            state.messages.is_empty(),
            "a superseded load replaces nothing"
        );

        // A successful load of the current generation clears it.
        let _ = state.update(loaded(Vec::new(), g));
        assert!(state.history_error.is_none());

        // A clear drops the failure and supersedes a load still in flight.
        let _ = state.update(error("db down", g));
        assert!(state.history_error.is_some());
        let in_flight = state.history_gen;
        let _ = state.update(HomeMessage::ClearChat);
        assert!(state.history_error.is_none());
        let _ = state.update(loaded(vec![stored_entry(1, "old-1", "old")], in_flight));
        assert!(state.messages.is_empty(), "a pre-clear load lands nowhere");
    }

    fn make_msg(
        message_id: &str,
        content: &str,
        direction: ChatDirection,
        agent_role: Option<&str>,
        is_optimistic: bool,
    ) -> DisplayMessage {
        DisplayMessage {
            id: None,
            message_id: message_id.to_string(),
            content: content.to_string(),
            direction,
            agent_role: agent_role.map(String::from),
            timestamp: None,
            reply_reference: None,
            md_items: Vec::new(),
            attachments: Vec::new(),
            is_optimistic,
        }
    }

    /// A message the page keeps but the store does not: a live arrival, a
    /// pending send or the scripted introduction, with its own instant and id.
    fn seed_msg(
        message_id: &str,
        content: &str,
        direction: ChatDirection,
        timestamp: Option<&str>,
        is_optimistic: bool,
        db_id: Option<i64>,
    ) -> DisplayMessage {
        let mut message = make_msg(message_id, content, direction, None, is_optimistic);
        message.timestamp = timestamp.map(str::to_string);
        message.id = db_id;
        message
    }

    /// The admin's own message as the live stream delivers it: the confirmation
    /// of a composer send (`optimistic_id`) or a plain echo.
    fn own_message(message_id: &str, optimistic_id: Option<&str>) -> HomeMessage {
        HomeMessage::ChatEvent(crate::ChatEvent::Message {
            message_id: message_id.into(),
            user_name: crate::users::ADMIN_USER_NAME.into(),
            content: "hello".into(),
            direction: ChatDirection::User,
            timestamp: crate::db::now(),
            channel: "gui".into(),
            agent_role: None,
            workspace: HomeState::conversation_workspace(),
            optimistic_id: optimistic_id.map(std::string::ToString::to_string),
            transient: false,
            reply_reference: None,
        })
    }

    /// An optimistic composer bubble waiting for its confirmation.
    fn bubble(id: &str, content: &str) -> DisplayMessage {
        make_msg(id, content, ChatDirection::User, None, true)
    }

    /// A message the pipeline delivered, already on screen.
    fn live(id: &str, content: &str, direction: ChatDirection) -> DisplayMessage {
        make_msg(id, content, direction, None, false)
    }

    /// A quoted reply the composer or the pipeline attached to a message.
    fn reply(author: &str, snippet: &str) -> ReplyReference {
        ReplyReference {
            author: author.to_string(),
            snippet: snippet.to_string(),
        }
    }

    /// An optimistic bubble carrying a quoted reply.
    fn quoting(id: &str, author: &str, snippet: &str) -> DisplayMessage {
        DisplayMessage {
            reply_reference: Some(reply(author, snippet)),
            ..bubble(id, "(placeholder)")
        }
    }

    struct SwapCase {
        name: &'static str,
        on_screen: Vec<DisplayMessage>,
        seen: &'static [&'static str],
        sending: bool,
        optimistic_id: Option<&'static str>,
        confirmed_id: &'static str,
        content: &'static str,
        reply: Option<ReplyReference>,
        expect_swapped: bool,
        expect_page: &'static [(&'static str, &'static str, bool)],
        expect_reply_author: Option<&'static str>,
        expect_seen: Option<&'static str>,
    }

    #[expect(clippy::too_many_lines)] // one table over every swap case
    #[test]
    fn replace_optimistic_swaps_only_the_matching_bubble() {
        use ChatDirection::User;
        let cases = [
            SwapCase {
                name: "a matching bubble is swapped for the confirmed message",
                on_screen: vec![bubble("opt-1", "(placeholder)")],
                seen: &[],
                sending: false,
                optimistic_id: Some("opt-1"),
                confirmed_id: "real-42",
                content: "Hello!",
                reply: None,
                expect_swapped: true,
                expect_page: &[("real-42", "Hello!", false)],
                expect_reply_author: None,
                expect_seen: Some("real-42"),
            },
            SwapCase {
                name: "no matching bubble leaves the original untouched",
                on_screen: vec![bubble("opt-1", "(placeholder)")],
                seen: &[],
                sending: false,
                optimistic_id: Some("wrong-opt"),
                confirmed_id: "real-42",
                content: "Hello!",
                reply: None,
                expect_swapped: false,
                expect_page: &[("opt-1", "(placeholder)", true)],
                expect_reply_author: None,
                expect_seen: None,
            },
            SwapCase {
                name: "no optimistic id is no replacement",
                on_screen: vec![],
                seen: &[],
                sending: false,
                optimistic_id: None,
                confirmed_id: "real-42",
                content: "Hello!",
                reply: None,
                expect_swapped: false,
                expect_page: &[],
                expect_reply_author: None,
                expect_seen: None,
            },
            SwapCase {
                name: "a bubble the page already carries is only dropped",
                on_screen: vec![live("pipeline-9", "hello", User), bubble("opt-1", "hello")],
                seen: &["pipeline-9"],
                sending: true,
                optimistic_id: Some("opt-1"),
                confirmed_id: "pipeline-9",
                content: "hello",
                reply: None,
                expect_swapped: true,
                expect_page: &[("pipeline-9", "hello", false)],
                expect_reply_author: None,
                expect_seen: None,
            },
            SwapCase {
                name: "a confirmed event with no reference keeps the bubble's own",
                on_screen: vec![quoting("opt-9", "bob", "original quote")],
                seen: &[],
                sending: false,
                optimistic_id: Some("opt-9"),
                confirmed_id: "real-9",
                content: "Hello!",
                reply: None,
                expect_swapped: true,
                expect_page: &[("real-9", "Hello!", false)],
                expect_reply_author: Some("bob"),
                expect_seen: None,
            },
            SwapCase {
                name: "a confirmed reference wins over the optimistic one",
                on_screen: vec![bubble("opt-10", "(placeholder)")],
                seen: &[],
                sending: false,
                optimistic_id: Some("opt-10"),
                confirmed_id: "real-10",
                content: "Hi",
                reply: Some(reply("carol", "ok")),
                expect_swapped: true,
                expect_page: &[("real-10", "Hi", false)],
                expect_reply_author: Some("carol"),
                expect_seen: None,
            },
        ];
        for case in cases {
            let name = case.name;
            let mut state = make_home_state("ws1");
            state.messages = case.on_screen;
            state.seen_ids = case.seen.iter().copied().map(str::to_string).collect();
            state.sending = case.sending;
            let task = state.replace_optimistic(
                case.optimistic_id,
                case.confirmed_id,
                case.content,
                User,
                None,
                None,
                case.reply,
            );
            assert_eq!(
                task.is_some(),
                case.expect_swapped,
                "case {name}: a replacement ran"
            );
            assert!(!state.sending, "case {name}: sending should be cleared");
            assert_eq!(
                state
                    .messages
                    .iter()
                    .map(|m| (m.message_id.as_str(), m.content.as_str(), m.is_optimistic))
                    .collect::<Vec<_>>(),
                case.expect_page,
                "case {name}: the page"
            );
            if let Some(author) = case.expect_reply_author {
                let kept = state.messages[0].reply_reference.as_ref();
                let kept_author = kept.map(|r| r.author.as_str());
                assert_eq!(kept_author, Some(author), "case {name}: reply");
            }
            if let Some(seen) = case.expect_seen {
                assert!(state.seen_ids.contains(seen), "case {name}: canonical id");
            }
        }
    }

    enum DedupSetup {
        Empty,
        Seen(&'static [&'static str]),
        /// The dedup set at its prune threshold, with a page to retain from.
        PrunePool,
    }

    #[test]
    fn try_dedup_admits_a_fresh_id_once_and_prunes_the_set() {
        // (case, the dedup set before, the arriving id, (deduped, set size,
        // retained ids, dropped ids))
        let cases = [
            (
                "a fresh id is admitted",
                DedupSetup::Empty,
                "msg-1",
                (false, 1, &["msg-1"][..], &[][..]),
            ),
            (
                "a duplicate id is rejected",
                DedupSetup::Seen(&["msg-1"]),
                "msg-1",
                (true, 1, &["msg-1"][..], &[][..]),
            ),
            (
                "a breached threshold prunes to the messages on the page",
                DedupSetup::PrunePool,
                "fresh",
                (
                    false,
                    DEDUP_RETAIN,
                    &["old-0", "old-199"][..],
                    &["fresh", "extra"][..],
                ),
            ),
        ];
        for (name, setup, message_id, expected) in cases {
            let (deduped, len, present, absent) = expected;
            let mut state = make_home_state("ws1");
            match setup {
                DedupSetup::Empty => {}
                DedupSetup::Seen(ids) => {
                    state.seen_ids = ids.iter().map(|id| (*id).to_string()).collect();
                }
                DedupSetup::PrunePool => {
                    for i in 0..DEDUP_PRUNE_THRESHOLD {
                        state.seen_ids.insert(format!("old-{i}"));
                    }
                    // Push messages so there is a retain pool.
                    for i in 0..DEDUP_RETAIN {
                        let message =
                            make_msg(&format!("old-{i}"), "", ChatDirection::User, None, false);
                        state.messages.push(message);
                    }
                    // One more id breaches the threshold.
                    state.seen_ids.insert("extra".to_string());
                }
            }
            let verdict = state.try_dedup(message_id);
            assert_eq!(verdict, deduped, "case {name}: dedup verdict");
            assert_eq!(state.seen_ids.len(), len, "case {name}: dedup set size");
            for id in present {
                assert!(state.seen_ids.contains(*id), "case {name}: {id} retained");
            }
            for id in absent {
                assert!(!state.seen_ids.contains(*id), "case {name}: {id} dropped");
            }
        }
    }

    struct SendingStateCase<'a> {
        name: &'static str,
        direction: ChatDirection,
        user: &'a str,
        workspace: &'a str,
        sending: bool,
        typing: bool,
    }

    #[test]
    fn test_update_sending_state() {
        let personal = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
        let admin = crate::users::ADMIN_USER_NAME;
        let cases = [
            SendingStateCase {
                name: "agent in the conversation",
                direction: ChatDirection::Agent,
                user: admin,
                workspace: personal.as_str(),
                sending: false,
                typing: false,
            },
            SendingStateCase {
                name: "user echo in the conversation",
                direction: ChatDirection::User,
                user: admin,
                workspace: personal.as_str(),
                sending: false,
                typing: true,
            },
            SendingStateCase {
                name: "another user",
                direction: ChatDirection::Agent,
                user: "bob",
                workspace: personal.as_str(),
                sending: true,
                typing: true,
            },
            SendingStateCase {
                name: "a managed workspace",
                direction: ChatDirection::Agent,
                user: admin,
                workspace: "ws1",
                sending: true,
                typing: true,
            },
        ];
        for case in cases {
            let name = case.name;
            let mut state = make_home_state("ws1");
            state.sending = true;
            state.typing = true;
            state.update_sending_state(case.direction, case.user, case.workspace);
            assert_eq!(state.sending, case.sending, "case {name}: sending");
            assert_eq!(state.typing, case.typing, "case {name}: typing");
        }
    }

    #[test]
    fn append_message_takes_only_the_conversations_own_messages() {
        let admin = crate::users::ADMIN_USER_NAME;
        // (case, (user, workspace or `None` for the conversation's own,
        // direction, agent role), what the page holds afterwards)
        let cases = [
            (
                "the admin's own message is appended",
                (admin, None, ChatDirection::User, None),
                Some(("msg-1", "Hello!", None)),
            ),
            (
                "another user's message is filtered out",
                ("bob", Some("ws1"), ChatDirection::User, None),
                None,
            ),
            (
                "a managed workspace's message is never the conversation's",
                (admin, Some("ws2"), ChatDirection::User, None),
                None,
            ),
            (
                "an agent response carries its role",
                (admin, None, ChatDirection::Agent, Some("engineer")),
                Some(("msg-agent", "Agent answer", Some("engineer"))),
            ),
        ];
        for (name, setup, expected) in cases {
            let (user, workspace, direction, role) = setup;
            let mut state = make_home_state("ws1");
            let workspace = workspace.map_or_else(
                || crate::users::personal_workspace_name(admin),
                str::to_string,
            );
            let (id, content) = expected.map_or(("msg-1", "Hello!"), |(id, text, _)| (id, text));
            state.append_message(
                user,
                &workspace,
                id.to_string(),
                content.to_string(),
                direction,
                role.map(str::to_string),
                None,
                None,
            );
            assert_eq!(
                state.messages.len(),
                usize::from(expected.is_some()),
                "case {name}: appended"
            );
            if let (Some(message), Some((id, text, role))) = (state.messages.first(), expected) {
                assert_eq!(message.message_id, id, "case {name}: id");
                assert_eq!(message.content, text, "case {name}: content");
                assert_eq!(message.direction, direction, "case {name}: direction");
                assert_eq!(message.agent_role.as_deref(), role, "case {name}: role");
            }
        }
    }

    #[test]
    fn a_selection_change_leaves_the_conversation_alone() {
        let mut state = make_home_state("ws1");
        state
            .messages
            .push(make_msg("m1", "one", ChatDirection::User, None, false));
        state
            .messages
            .push(make_msg("m2", "two", ChatDirection::Agent, None, false));
        state.seen_ids = state
            .messages
            .iter()
            .map(|m| m.message_id.clone())
            .collect();
        state.sending = true;
        state.typing = true;
        state.auto_scroll_enabled = false; // the user has scrolled up
        let generation = state.history_gen;

        // A selection change is recorded and nothing else — in any order, back
        // and forth.
        for picker in ["ws2", "ws1", "personal:admin"] {
            let task = state.update(HomeMessage::WorkspaceChanged(picker.to_string()));
            assert_eq!(task.units(), 0, "a selection change must issue no read");
            assert_eq!(state.selected_workspace.as_deref(), Some(picker));
            assert_eq!(generation, state.history_gen, "no load was issued");
            let shown: Vec<(&str, &str)> = state
                .messages
                .iter()
                .map(|m| (m.message_id.as_str(), m.content.as_str()))
                .collect();
            assert_eq!(shown, [("m1", "one"), ("m2", "two")]);
            assert!(state.sending && state.typing, "live work is not reset");
            assert!(!state.auto_scroll_enabled, "a scrolled-up view stays");
        }
    }

    #[test]
    fn live_work_follows_the_conversation_not_the_selection() {
        let personal = HomeState::conversation_workspace();
        let message = |workspace: &str, id: &str| {
            HomeMessage::ChatEvent(crate::ChatEvent::Message {
                message_id: id.to_string(),
                user_name: crate::users::ADMIN_USER_NAME.to_string(),
                content: format!("from {workspace}"),
                direction: ChatDirection::Agent,
                timestamp: crate::db::now(),
                channel: "gui".to_string(),
                agent_role: Some("assistant".to_string()),
                workspace: workspace.to_string(),
                optimistic_id: None,
                transient: false,
                reply_reference: None,
            })
        };
        let typing = |workspace: &str| {
            HomeMessage::ChatEvent(crate::ChatEvent::Typing {
                user_name: crate::users::ADMIN_USER_NAME.to_string(),
                is_typing: true,
                workspace: workspace.to_string(),
            })
        };

        // The project the picker selects is where the work that follows runs —
        // not where the conversation's live traffic lands.
        let mut state = make_home_state("ws1");
        state.sending = true;
        let _ = state.update(message("ws1", "project-1"));
        let _ = state.update(typing("ws1"));
        assert!(state.messages.is_empty(), "a project's message is filtered");
        assert!(!state.typing && state.sending, "nor is its typing cue");
        let _ = state.update(message(&personal, "own-1"));
        let _ = state.update(typing(&personal));
        assert_eq!(state.messages[0].message_id, "own-1");
        assert!(state.typing, "the conversation's own typing cue is shown");
        assert!(!state.sending, "its own live traffic clears the send");
    }

    /// A stored message the page already shows, with its row id.
    fn stored(id: &str, content: &str, db_id: i64) -> DisplayMessage {
        seed_msg(id, content, ChatDirection::User, None, false, Some(db_id))
    }

    /// A transient message the page keeps: never stored, carrying its instant.
    fn transient(id: &str, content: &str, at: &str) -> DisplayMessage {
        seed_msg(id, content, ChatDirection::Agent, Some(at), false, None)
    }

    /// A pending send whose confirmation has not arrived.
    fn pending(id: &str, content: &str, at: &str) -> DisplayMessage {
        seed_msg(id, content, ChatDirection::User, Some(at), true, None)
    }

    struct ReloadCase {
        name: &'static str,
        on_screen: Vec<DisplayMessage>,
        seen: &'static [&'static str],
        stored: &'static [(i64, &'static str, &'static str, Option<&'static str>)],
        page: &'static [(&'static str, &'static str)],
        stored_ids: Option<&'static [Option<i64>]>,
        optimistic: Option<&'static [bool]>,
    }
    #[test]
    fn a_reload_reconciles_the_stored_history_with_what_is_on_screen() {
        use ChatDirection::Agent;
        const SENT: &str = "2026-01-01T10:00:00.000000000+00:00";
        const LATER: &str = "2026-01-01T10:00:05.000000000+00:00";
        const EARLIER: &str = "2026-01-01T09:00:00.000000000+00:00";
        let cases = [
            ReloadCase {
                name: "the stored page replaces the stored and keeps the rest",
                on_screen: vec![
                    live("live-1", "live", Agent),
                    stored("old-1", "old", 1),
                    bubble("opt-1", "optimistic"),
                ],
                seen: &["live-1", "old-1", "opt-1"],
                stored: &[(1, "old-1", "old", None), (2, "new-2", "new", None)],
                page: &[
                    ("old-1", "old"),
                    ("new-2", "new"),
                    ("live-1", "live"),
                    ("opt-1", "optimistic"),
                ],
                stored_ids: Some(&[Some(1), Some(2), None, None]),
                optimistic: Some(&[false, false, false, true]),
            },
            ReloadCase {
                name: "a kept transient message goes back among the stored ones",
                // The scripted onboarding exchange is transient — never stored —
                // and carries the timestamp of the event that produced it.
                on_screen: vec![transient("intro-1", "intro", SENT)],
                seen: &[],
                stored: &[(5, "reply", "the reply", Some(LATER))],
                page: &[("intro-1", "intro"), ("reply", "the reply")],
                stored_ids: None,
                optimistic: None,
            },
            ReloadCase {
                name: "a lost confirmation does not double a pending send",
                on_screen: vec![
                    pending("opt-1", "hello", SENT),
                    live("live-1", "later", Agent),
                ],
                seen: &[],
                stored: &[(9, "pipeline-9", "hello", Some(SENT))],
                page: &[("pipeline-9", "hello"), ("live-1", "later")],
                stored_ids: None,
                optimistic: None,
            },
            ReloadCase {
                name: "an older row of the same text is not the pending send's copy",
                on_screen: vec![pending("opt-2", "hello", SENT)],
                seen: &[],
                stored: &[(1, "old-1", "hello", Some(EARLIER))],
                page: &[("old-1", "hello"), ("opt-2", "hello")],
                stored_ids: None,
                optimistic: None,
            },
            ReloadCase {
                name: "a reload never doubles history",
                on_screen: vec![live("in-flight", "text", Agent)],
                seen: &["in-flight"],
                stored: &[(5, "in-flight", "text", None)],
                page: &[("in-flight", "text")],
                stored_ids: Some(&[Some(5)]),
                optimistic: None,
            },
        ];
        for case in cases {
            let name = case.name;
            let entries = case.stored.iter().map(|(id, mid, content, at)| match at {
                Some(at) => timestamped_entry(*id, mid, content, at),
                None => stored_entry(*id, mid, content),
            });
            let mut state = HomeState::new();
            state.messages = case.on_screen;
            state.seen_ids = case.seen.iter().map(|id| (*id).to_string()).collect();
            let g = state.history_gen;
            let loaded = HomeMessage::HistoryLoaded {
                entries: entries.collect(),
                generation: g,
            };
            let _ = state.update(loaded);
            let got: Vec<(&str, &str)> = state
                .messages
                .iter()
                .map(|m| (m.message_id.as_str(), m.content.as_str()))
                .collect();
            assert_eq!(got, case.page, "case {name}: the page");
            let ids: HashSet<&str> = got.iter().map(|(id, _)| *id).collect();
            assert_eq!(ids.len(), got.len(), "case {name}: no duplicated ids");
            if let Some(stored_ids) = case.stored_ids {
                let got: Vec<Option<i64>> = state.messages.iter().map(|m| m.id).collect();
                assert_eq!(got, stored_ids, "case {name}: stored row ids");
            }
            if let Some(optimistic) = case.optimistic {
                let got: Vec<bool> = state.messages.iter().map(|m| m.is_optimistic).collect();
                assert_eq!(got, optimistic, "case {name}: optimistic flags");
            }
        }
    }

    #[test]
    fn a_deduplicated_confirmation_still_frees_the_composer() {
        // The row is already on screen and the bubble is gone, so the
        // confirmation only repeats what is shown: it adds nothing and still
        // releases the send guard.
        let mut state = HomeState::new();
        state.sending = true;
        let mut row = make_msg("pipeline-9", "hello", ChatDirection::User, None, false);
        row.id = Some(9);
        state.messages.push(row);
        state.seen_ids.insert("pipeline-9".to_string());
        let _ = state.update(own_message("pipeline-9", None));
        assert_eq!(state.messages.len(), 1, "it adds nothing");
        assert!(!state.sending, "it still frees the composer");
    }

    #[test]
    fn a_stored_entry_becomes_a_display_message() {
        use ChatDirection::{Divider, User};
        let entry = |id: i64, message_id: &str, content: &str, direction, reply| ChatHistoryEntry {
            id,
            message_id: message_id.to_string(),
            content: content.to_string(),
            direction,
            agent_role: None,
            timestamp: None,
            reply_reference: reply,
        };
        // (case, the stored row, (directional fields, the markdown it parses to,
        // its reply reference))
        let cases = [
            (
                "a user row parses its markdown",
                entry(1, "msg-1", "Hello **world**", User, None),
                (1, User, false, None),
            ),
            (
                "a divider row produces no markdown",
                entry(42, "divider-1", "2026-07-17T20:30:00Z", Divider, None),
                (42, Divider, true, None),
            ),
            (
                "a reply reference is carried over",
                entry(
                    7,
                    "msg-7",
                    "replied text",
                    User,
                    Some(reply("alice", "quote")),
                ),
                (7, User, false, Some(("alice", "quote"))),
            ),
        ];
        for (name, row, (id, direction, empty, carried)) in cases {
            let content = row.content.clone();
            let message = DisplayMessage::from(row);
            assert_eq!(message.id, Some(id), "case {name}: stored row id");
            assert_eq!(message.direction, direction, "case {name}: direction");
            assert_eq!(message.content, content, "case {name}: content");
            assert_eq!(message.md_items.is_empty(), empty, "case {name}: markdown");
            assert!(!message.is_optimistic, "case {name}: not optimistic");
            if let Some((author, snippet)) = carried {
                let got = message.reply_reference.as_ref().expect("the entry's reply");
                assert_eq!(got.author, author, "case {name}: reply author");
                assert_eq!(got.snippet, snippet, "case {name}: reply snippet");
            }
        }
    }

    struct ReplyReferenceCase {
        name: &'static str,
        direction: ChatDirection,
        role: Option<&'static str>,
        content: String,
        author: &'static str,
        snippet: Option<&'static str>,
        capped: bool,
    }

    #[test]
    fn reply_references_derive_their_author_and_normalized_snippet() {
        use ChatDirection::{Agent, User};
        let admin = crate::users::ADMIN_USER_NAME;
        // A user message is normalized: angle brackets stripped, newlines
        // collapsed (each `\n` becomes a single space, so `\n\n` yields two),
        // media marker mapped.
        let cases = [
            ReplyReferenceCase {
                name: "a user message is the admin's own",
                direction: User,
                role: None,
                content: "Hello <world>\n\nwith [IMAGE:/tmp/photo.png]".into(),
                author: admin,
                snippet: Some("Hello world  with [Photo]"),
                capped: false,
            },
            ReplyReferenceCase {
                name: "an agent message uses the shared role label",
                direction: Agent,
                role: Some("analyst_3"),
                content: "line one\n<line two> [IMAGE:/tmp/x.png] and a long tail".into(),
                author: "Analyst",
                snippet: Some("line one line two [Photo] and a long tail"),
                capped: false,
            },
            ReplyReferenceCase {
                name: "a long snippet is capped with an ellipsis",
                direction: User,
                role: None,
                content: "a".repeat(150),
                author: admin,
                snippet: None,
                capped: true,
            },
        ];
        for case in cases {
            let name = case.name;
            let reply = reply_reference_for(case.direction, case.role, &case.content);
            assert_eq!(reply.author, case.author, "case {name}: author");
            if let Some(snippet) = case.snippet {
                assert_eq!(reply.snippet, snippet, "case {name}: snippet");
            }
            if case.capped {
                let len = reply.snippet.chars().count();
                let max = crate::channels::reply::REPLY_SNIPPET_MAX_CHARS;
                assert!(len <= max, "case {name}: capped, got {len}");
                assert!(reply.snippet.ends_with('…'), "case {name}: ends with …");
            }
        }
    }

    #[test]
    fn test_select_to_creates_selection() {
        let mut state = make_home_state("ws1");
        state.editor_content =
            EditorBuffer::with_text("hello world", Some(HighlightLanguage::Markdown));
        let move_to = EditorAction::MoveTo { line: 0, col: 0 };
        let select_to = EditorAction::SelectTo { line: 0, col: 5 };

        // Move the cursor away from the anchor, then extend a selection.
        state.editor_content.perform_action(move_to);
        assert!(state.editor_content.cursor().selection.is_none(), "MoveTo");

        // Dispatch a SelectTo through the page update.
        let _task = state.update(HomeMessage::InputChanged(select_to));
        let selection = state.editor_content.cursor().selection.clone();
        assert!(
            selection.is_some(),
            "SelectTo makes a selection; got {selection:?}"
        );
    }

    #[test]
    fn send_message_sends_only_non_blank_text_and_returns_an_untaken_send() {
        // (case, composer text)
        let cases = [
            ("empty content", ""),
            ("whitespace-only content", "   "),
            (
                "within limit, nothing takes the send, so it comes back",
                "hello world",
            ),
        ];
        for (name, text) in cases {
            let mut state = make_home_state("ws1");
            let draft = EditorBuffer::with_text(text, Some(HighlightLanguage::Markdown));
            state.editor_content = draft;
            let _task = state.send_message();
            assert!(!state.sending, "case {name}: not left sending");
            assert_eq!(state.editor_content.text(), text, "case {name}: returned");
            let optimistic = state.messages.iter().any(|m| m.is_optimistic);
            assert!(!optimistic, "case {name}: no optimistic bubble");
        }
    }

    /// Put the composer where a mic press leaves it: a recording owns the field,
    /// which holds `text`. The returned receiver stands in for the pipeline that
    /// took the start, so a press's stop is taken too.
    fn a_recording_owns_the_field(
        state: &mut HomeState,
        text: &str,
    ) -> tokio::sync::mpsc::UnboundedReceiver<crate::audio::voice::VoiceCommand> {
        state.editor_content = EditorBuffer::with_text(text, Some(HighlightLanguage::Markdown));
        state.voice_message = Some(VoiceMessage::Recording);
        crate::audio::voice::install_test_command_receiver()
    }

    /// The page after a press on a recording's field, and the pipeline's end.
    fn pressed(
        text: &str,
    ) -> (
        HomeState,
        tokio::sync::mpsc::UnboundedReceiver<crate::audio::voice::VoiceCommand>,
    ) {
        let mut state = make_home_state("ws1");
        let pipeline = a_recording_owns_the_field(&mut state, text);
        let _press = state.send_message();
        (state, pipeline)
    }

    /// The text the recording's message holds, when the field was committed to it.
    fn committed_text(state: &HomeState) -> Option<&str> {
        match &state.voice_message {
            Some(VoiceMessage::Committed { text, .. }) => Some(text),
            _ => None,
        }
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_wake_word_recording_takes_the_field_and_its_controls() {
        let mut state = make_home_state("ws1");
        let _pipeline = crate::audio::voice::install_test_command_receiver();
        state.editor_content = EditorBuffer::with_text("hello", Some(HighlightLanguage::Markdown));

        // No press of ours started it: the pipeline did.
        let _started = state.voice_recording(RecordingEvent::Started);
        let owns = matches!(state.voice_message, Some(VoiceMessage::Recording));
        assert!(owns, "the field belongs to the recording");
        assert!(!state.editor_content.text().is_empty(), "the field is kept");

        // A press belongs to that recording's message, and the field joins it.
        let _press = state.send_message();
        assert!(state.editor_content.text().is_empty(), "the field is taken");
        assert_eq!(committed_text(&state), Some("hello"));
        assert!(state.in_flight(), "the message is on its way");
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_press_commits_the_field_to_the_recording_message() {
        let (state, _pipeline) = pressed("hello");
        assert!(state.editor_content.text().is_empty(), "the field is taken");
        assert_eq!(committed_text(&state), Some("hello"));
        assert!(state.in_flight(), "the message is on its way");
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_press_after_the_commit_does_nothing() {
        let (mut state, _pipeline) = pressed("hello");
        state.editor_content =
            EditorBuffer::with_text("typed since", Some(HighlightLanguage::Markdown));
        let _second = state.send_message();
        assert_eq!(
            committed_text(&state),
            Some("hello"),
            "the message is fixed"
        );
        assert_eq!(
            state.editor_content.text(),
            "typed since",
            "the field keeps it"
        );
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_transcript_completes_the_committed_message() {
        let (mut state, _pipeline) = pressed("hello");
        let _task = state.voice_recording(RecordingEvent::Transcript("🔊✍️ spoken".to_string()));
        assert!(state.voice_message.is_none(), "the message is resolved");
        // No pipeline takes the send, so the composed message comes back.
        assert_eq!(state.editor_content.text(), "hello");
        assert!(state.voice_error_at.is_some());
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_silent_recording_sends_only_what_the_field_held() {
        let (mut state, _pipeline) = pressed("hello");
        let _stopped = state.voice_recording(RecordingEvent::Stopped);
        let _task = state.voice_recording(RecordingEvent::NoSpeech);
        assert!(state.voice_message.is_none());
        assert_eq!(state.editor_content.text(), "hello", "the field's own text");
        assert!(
            state.voice_notice_at.is_none(),
            "content went out: no notice"
        );
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_silent_recording_of_an_empty_field_reports_the_discard() {
        let mut state = make_home_state("ws1");
        let _pipeline = a_recording_owns_the_field(&mut state, "");
        let _stopped = state.voice_recording(RecordingEvent::Stopped);
        let _task = state.voice_recording(RecordingEvent::NoSpeech);
        assert!(state.voice_message.is_none());
        assert!(state.voice_notice_at.is_some(), "the discard is reported");
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_lost_recording_gives_the_field_back() {
        let (mut state, _pipeline) = pressed("hello");
        let _task = state.voice_recording(RecordingEvent::Failed(
            crate::audio::voice::VOICE_UNSENT_NOTICE,
        ));
        assert!(state.voice_message.is_none());
        assert_eq!(state.editor_content.text(), "hello", "the field comes back");
        assert!(!state.sending);
        assert!(state.voice_error_at.is_some(), "the loss is reported");
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_recording_that_never_started_closes_its_message() {
        let mut state = make_home_state("ws1");
        let _pipeline = a_recording_owns_the_field(&mut state, "hello");
        let _task = state.voice_recording(RecordingEvent::NotStarted);
        assert!(state.voice_message.is_none());
        assert_eq!(state.editor_content.text(), "hello", "the field is kept");
        assert_eq!((state.voice_notice_at, state.voice_error_at), (None, None));
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_press_whose_recording_never_began_sends_the_field_it_committed() {
        let (mut state, _pipeline) = pressed("hello");
        assert!(state.editor_content.text().is_empty(), "the press took it");

        // The pipeline never started the recording, so no transcript can join
        // the committed message: the field's own content goes out as any typed
        // message does — and comes back whole, since no pipeline takes the send.
        let _task = state.voice_recording(RecordingEvent::NotStarted);
        assert!(state.voice_message.is_none(), "the window is resolved");
        assert_eq!(state.editor_content.text(), "hello");
    }

    #[test]
    #[serial_test::serial(voice)]
    fn a_recording_never_shares_a_committed_message() {
        let (mut state, mut pipeline) = pressed("hello");
        while pipeline.try_recv().is_ok() {}

        // A wake-word recording is dropped, not poured into that message.
        let _started = state.voice_recording(RecordingEvent::Started);
        assert_eq!(committed_text(&state), Some("hello"), "the window is kept");
        let dropped = matches!(
            pipeline.try_recv(),
            Ok(crate::audio::voice::VoiceCommand::StopRecordingDiscard)
        );
        assert!(dropped, "the second recording is dropped");
    }
}