mahbot 0.4.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
//! Home page — native GUI chat interface with user impersonation.
//!
//! Users pick an identity from the user picker, select a workspace via the
//! Dashboard sidebar/global picker, and chat with MahBot agents in real time
//! with full markdown rendering and typing indicators.

use crate::ChatDirection;
use crate::Role;
use crate::chat_history::ChatHistoryEntry;
use futures_util::SinkExt;
use iced::widget::rule;
use iced::widget::{
    Column, Id, Space, button, column, container, row, scrollable, text, text_editor, tooltip,
};
use iced::{Alignment, Element, Length, Task, keyboard};
use iced_fonts::lucide;
use std::collections::HashSet;

use super::ToastMessage;
use super::common::MAX_INPUT_CHARS;
use super::context_menu::{ContextMenu, MenuItem};
use super::role_menu::{RoleMenu, RoleMenuItem};
use super::theme;
use super::widgets::PickOption;

/// Maximum number of message IDs to keep in the dedup set before pruning.
const DEDUP_PRUNE_THRESHOLD: usize = 500;

/// 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");

/// A displayed chat message in the scroll view.
#[derive(Debug, Clone)]
pub struct DisplayMessage {
    /// Database row ID (Some for history-loaded, None for live arrivals).
    pub id: Option<i64>,
    pub message_id: String,
    pub content: String,
    pub direction: ChatDirection,
    pub agent_role: Option<String>,
    /// Pre-parsed markdown items for rendering.
    pub md_items: Vec<iced::widget::markdown::Item>,
    /// True when this is 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).
/// `id` is `Some` for history-loaded entries, `None` for live/optimistic
/// messages.
fn display_message(
    id: Option<i64>,
    message_id: String,
    content: String,
    direction: ChatDirection,
    agent_role: Option<String>,
    is_optimistic: bool,
) -> DisplayMessage {
    use iced::widget::markdown;
    let md_items: Vec<markdown::Item> = if direction == ChatDirection::Divider {
        Vec::new()
    } else {
        let processed = super::media_markers::preprocess(&content);
        markdown::parse(&processed).collect()
    };
    DisplayMessage {
        id,
        message_id,
        content,
        direction,
        agent_role,
        md_items,
        is_optimistic,
    }
}

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

/// Wrap a chat bubble in a 3:1 FillPortion row so it occupies 75% width,
/// aligned to the right for user messages or to the left for agent/typing.
///
/// The caller must set `.width(Length::FillPortion(3))` on the bubble before
/// passing it — this function only creates the spacer row.
fn align_bubble<'a>(
    bubble: impl Into<Element<'a, HomeMessage>>,
    is_user: bool,
) -> Element<'a, HomeMessage> {
    let bubble = bubble.into();
    if is_user {
        // User: bubble left, spacer right
        row![bubble, Space::new().width(Length::FillPortion(1)),].into()
    } else {
        // Agent: spacer left, bubble right
        row![Space::new().width(Length::FillPortion(1)), bubble,].into()
    }
}

#[derive(Debug, Clone)]
pub enum HomeMessage {
    /// User selected (from picker, Users page icon, or auto-selected at boot).
    UserSelected(String),
    /// Workspace changed (from global picker — propagated via Dashboard).
    WorkspaceChanged(Option<String>),
    /// Text editor content changed.
    InputChanged(text_editor::Action),
    /// Send button pressed or Enter key in editor.
    SendMessage,
    /// Chat history loaded from the store (entries, has_more).
    HistoryLoaded(Vec<ChatHistoryEntry>, bool),
    /// History load failed.
    HistoryLoadError(String),
    /// Live chat event from CHAT_BROADCAST subscription.
    ChatEvent(crate::ChatEvent),
    /// Stream lagged — resync needed.
    StreamLagged,
    /// Scroll position changed in the chat scrollable.
    ScrollChanged(scrollable::Viewport),
    /// User clicked "Load older messages" button.
    LoadOlderMessages,
    /// Older history loaded (entries, has_more, pagination_gen for staleness check).
    OlderHistoryLoaded(Vec<ChatHistoryEntry>, bool, u64),
    /// Older history load failed.
    OlderHistoryLoadError(String),
    /// User list loaded for the picker.
    UsersLoaded(Vec<PickOption>),
    /// Markdown link was clicked.
    LinkClicked(String),
    /// Request a workspace change at the Dashboard level (reverse sync:
    /// DB-stored workspace differs from sidebar). Intercepted by Dashboard;
    /// never reaches Home's own update handler.
    RequestWorkspaceChange(String),
    /// Internal signal: reverse-sync check completed. Carries the user
    /// (staleness guard for fast user switches), the sidebar workspace to
    /// show (the user's DB-stored workspace, normalized — empty means
    /// Personal) and the user's DB-selected project workspace (the merge
    /// partner for the Personal-picker chat view; `None` when unset or
    /// personal). Proceeds with a normal history refresh for the selected user.
    ResolveUserSelected {
        user: String,
        sidebar_ws: Option<String>,
        project_ws: Option<String>,
    },
    /// Refreshed DB-selected project workspace for a user (re-read on
    /// workspace change so the Personal-picker merge partner never goes
    /// stale). Carries `(user, project_workspace)`.
    ProjectWorkspaceRefreshed(String, Option<String>),
    /// Reset session button pressed — reset session and display.
    ClearChat,
    /// Copy a chat message's raw markdown content to the clipboard.
    /// Carries the exact stored/transmitted text (original media markers
    /// included), not the rendered view.
    CopyMessage(String),
    /// Switch user's active role. Carries (user_name, new_role).
    SwitchRole(String, Role),
    /// Chat history cleared successfully — divider inserted.
    ChatCleared,
    /// Chat history clear failed.
    ChatClearError(String),
    /// Toast notification to show via Dashboard.
    /// Intercepted by Dashboard; never reaches Home's own update handler.
    Toast(ToastMessage),
    /// Typing indicator animation: cycles through 0, 1, 2 → ".", "..", "...".
    TypingTick,
    /// Timeout safety net: if `sending` stays stuck for 30+ seconds,
    /// auto-clear it. Carries the generation counter to prevent stale
    /// timeouts from interfering with a fresh send.
    SendingTimeout(u64),
    /// Undo the last text edit in the chat input.
    Undo,
    /// Redo a previously undone text edit in the chat input.
    Redo,
    /// Keyboard modifiers changed (shift, ctrl, alt, etc.).
    /// Used to track shift state for shift+click selection in the text editor.
    ModifiersChanged(keyboard::Modifiers),
    /// Mic button clicked — start a voice message recording to the active role.
    StartVoiceRecording,
    /// Recording popup: stop recording, transcribe, and send the voice message.
    StopVoiceRecordingSend,
    /// Recording popup: stop recording and discard the voice message.
    StopVoiceRecordingDiscard,
    /// Toggle the composer role dropdown open/closed.
    RoleMenuToggled,
    /// Close the composer role dropdown (on role selection, message send,
    /// chat clear, or user switch).
    RoleMenuClosed,
}

pub struct HomeState {
    /// Currently selected user (sender identifier).
    pub(crate) selected_user: Option<String>,
    /// Currently selected workspace name (synced from dashboard sidebar).
    /// Empty string `""` means the "Personal" workspace — must be resolved
    /// to `personal:<user_name>` before querying chat_history or sessions.
    selected_workspace: Option<String>,
    /// The selected user's DB-stored project workspace (None when unset or
    /// personal). The merge partner for the Personal-picker chat view: at
    /// the Personal picker the chat shows this workspace alongside the
    /// user's personal workspace.
    user_project_workspace: Option<String>,
    /// Displayed chat messages.
    messages: Vec<DisplayMessage>,
    /// Deduplication set of seen message IDs.
    seen_ids: HashSet<String>,
    /// Text editor content.
    editor_content: text_editor::Content,
    /// Whether a message is currently being sent / agent is responding.
    sending: bool,
    /// Whether a typing indicator is active.
    typing: bool,
    /// Typing animation dot cycle state: 0=".", 1="..", 2="...".
    typing_tick_state: u8,
    /// Whether the initial history load has happened for the current user+workspace.
    history_loaded: bool,
    /// Generation counter for stale sending timeout detection.
    sending_gen: u64,
    /// True when WorkspaceChanged arrived before a user was selected — the
    /// deferred `refresh_history()` will be triggered by `ResolveUserSelected`.
    pending_workspace_refresh: bool,
    /// Whether auto-scroll is enabled (user is scrolled to the bottom).
    auto_scroll_enabled: bool,
    /// The database ID of the oldest loaded message, if any.
    oldest_loaded_id: Option<i64>,
    /// Whether there are more older messages to load.
    has_more: bool,
    /// Whether an older-messages load is in-flight.
    loading_older: bool,
    /// Generation counter for stale OlderHistoryLoaded callback detection.
    pagination_gen: u64,
    /// Undo/redo stack for the chat input text editor.
    undo_stack: super::common::UndoStack,
    /// Current keyboard modifiers (shift, ctrl, alt, etc.).
    /// Updated from `ModifiersChanged` events. Used to detect shift+click
    /// for extending text selection.
    modifiers: keyboard::Modifiers,
    /// Whether the composer role dropdown is open.
    role_menu_open: bool,
}

/// The chat view for the selected user: two workspaces — the picker-resolved
/// one plus a merge partner. Symmetric visibility: the picker only selects
/// the recipient, it never filters the view (personal Assistant/Artist
/// messages show at any picker, and the user's project chat shows at the
/// Personal picker).
#[derive(Debug, Clone, PartialEq, Eq)]
struct VisibleChat {
    /// The picker-resolved workspace: the selected workspace, or
    /// `personal:{user}` at the Personal picker.
    primary: String,
    /// The merge partner: `personal:{user}` at a project picker, or the
    /// user's DB-selected project workspace at the Personal picker. `None`
    /// only when the primary is the personal workspace and the user has no
    /// project workspace (deduplicated).
    merge: Option<String>,
}

impl VisibleChat {
    /// Whether `workspace` is part of this visible chat.
    fn contains(&self, workspace: &str) -> bool {
        self.primary == workspace || self.merge.as_deref() == Some(workspace)
    }
}

impl HomeState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            selected_user: None,
            selected_workspace: None,
            user_project_workspace: None,
            messages: Vec::new(),
            seen_ids: HashSet::new(),
            editor_content: text_editor::Content::new(),
            sending: false,
            typing: false,
            typing_tick_state: 0,
            history_loaded: false,
            sending_gen: 0,
            pending_workspace_refresh: false,
            auto_scroll_enabled: true,
            oldest_loaded_id: None,
            has_more: false,
            loading_older: false,
            pagination_gen: 0,
            undo_stack: super::common::UndoStack::new(),
            modifiers: keyboard::Modifiers::empty(),
            role_menu_open: false,
        }
    }

    /// Load users for the user picker.
    #[allow(clippy::unused_self)]
    pub fn load_users(&self) -> Task<HomeMessage> {
        Task::perform(
            async {
                let Some(store) = crate::users::USER_STORE.get() else {
                    return Vec::new();
                };
                let users = store.list_users().await.unwrap_or_default();
                users
                    .iter()
                    .map(|u| PickOption {
                        value: u.name.clone(),
                        label: u.name.clone(),
                    })
                    .collect()
            },
            HomeMessage::UsersLoaded,
        )
    }

    /// Resolve the workspace name for chat history and session queries.
    /// `None` or empty string (Personal) → `personal:<user_name>`.
    /// Non-empty workspace → the workspace name as-is.
    fn resolve_workspace_name(&self) -> Option<String> {
        match &self.selected_workspace {
            Some(w) if !w.is_empty() => Some(w.clone()),
            _ => {
                let user = self.selected_user.as_ref()?;
                Some(format!("personal:{user}"))
            }
        }
    }

    /// Whether `workspace` is the selected user's personal workspace
    /// (`personal:{user}`) — the Assistant/Artist chat shown at any picker.
    fn is_selected_user_personal_workspace(&self, workspace: &str) -> bool {
        self.selected_user
            .as_deref()
            .is_some_and(|user| crate::users::personal_user_name(workspace) == Some(user))
    }

    /// The visible chat set for the selected user (see [`VisibleChat`]), or
    /// `None` when no user is selected.
    fn visible_workspaces(&self) -> Option<VisibleChat> {
        let user = self.selected_user.as_ref()?;
        let personal = format!("personal:{user}");
        let chat = match self.resolve_workspace_name() {
            Some(sel) if !self.is_selected_user_personal_workspace(&sel) => VisibleChat {
                primary: sel,
                merge: Some(personal),
            },
            _ => VisibleChat {
                primary: personal,
                merge: self.user_project_workspace.clone(),
            },
        };
        Some(chat)
    }

    /// Whether a message or typing event in `workspace` belongs to the
    /// selected user's visible chat (see [`VisibleChat::contains`]).
    fn workspace_visible(&self, workspace: &str) -> bool {
        self.visible_workspaces()
            .is_some_and(|chat| chat.contains(workspace))
    }

    /// Whether the picker selects the selected user's personal workspace —
    /// projected from [`Self::visible_workspaces`] (its `primary` is the
    /// personal workspace only at the Personal picker), so the merge-partner
    /// decision keeps a single shape across the refresh paths.
    fn at_personal_picker(&self) -> bool {
        self.visible_workspaces()
            .is_some_and(|chat| self.is_selected_user_personal_workspace(&chat.primary))
    }

    /// Reverse-sync the DB-stored workspace preference for a user.
    ///
    /// Returns [`ResolveUserSelected`] carrying the sidebar workspace to show
    /// and the user's DB-selected project workspace. Home's handler emits
    /// [`RequestWorkspaceChange`] when the sidebar must move (Dashboard-level
    /// change cascading to [`WorkspaceChanged`] → `refresh_history`);
    /// otherwise it refreshes history directly.
    ///
    /// NOTE: We deliberately do NOT write the sidebar workspace to the
    /// impersonated user's DB record.  The GUI sidebar is a per-session
    /// context — persisting it would silently overwrite the user's real
    /// workspace choice.
    async fn resolve_user_workspace_sync(user: String, current_ws: Option<String>) -> HomeMessage {
        match crate::users::get_raw_selected_workspace(&user).await {
            Ok(Some(ws_name)) => {
                // User has an explicit stored workspace preference. Normalize
                // personal workspaces to the GUI sentinel ""; the project
                // workspace is the merge partner at the Personal picker.
                let (sidebar_ws, project_ws) = if crate::users::is_personal_workspace(&ws_name) {
                    (String::new(), None)
                } else {
                    (ws_name.clone(), Some(ws_name))
                };
                HomeMessage::ResolveUserSelected {
                    user,
                    sidebar_ws: Some(sidebar_ws),
                    project_ws,
                }
            }
            Ok(None) => {
                // User has no stored preference — keep current sidebar selection.
                HomeMessage::ResolveUserSelected {
                    user,
                    sidebar_ws: current_ws.clone(),
                    project_ws: None,
                }
            }
            Err(e) => {
                tracing::warn!("Failed to get raw workspace for user {user}: {e}");
                HomeMessage::ResolveUserSelected {
                    user,
                    sidebar_ws: current_ws.clone(),
                    project_ws: None,
                }
            }
        }
    }

    /// The user's DB-selected project workspace (None when unset or
    /// personal). The Personal-picker merge partner — re-read on workspace
    /// changes so it never goes stale (Users-page edits flow through
    /// [`WorkspaceChanged`]).
    async fn project_workspace_for(user: String) -> Option<String> {
        crate::users::get_raw_selected_workspace(&user)
            .await
            .ok()
            .flatten()
            .filter(|ws| !crate::users::is_personal_workspace(ws))
    }

    /// Refresh chat history from the store for the current user's visible
    /// workspaces (the selected workspace plus the user's personal workspace).
    fn refresh_history(&self) -> Task<HomeMessage> {
        let user_name = match &self.selected_user {
            Some(s) => s.clone(),
            None => return Task::none(),
        };
        let Some(chat) = self.visible_workspaces() else {
            return Task::none();
        };
        Task::perform(
            async move {
                let store = crate::chat_history::store();
                store
                    .load_for_user_workspaces(&user_name, &chat.primary, chat.merge.as_deref())
                    .await
                    .map_err(|e| e.to_string())
            },
            |result| match result {
                Ok((entries, has_more)) => HomeMessage::HistoryLoaded(entries, has_more),
                Err(e) => HomeMessage::HistoryLoadError(e),
            },
        )
    }

    /// Push a new chat message to the display. Returns the message's ID for dedup tracking.
    fn push_message(&mut self, entry: ChatHistoryEntry) -> String {
        let msg_id = entry.message_id.clone();
        self.messages.push(entry.into());
        msg_id
    }

    /// Reset pagination and auto-scroll state. Called at all cleanup sites
    /// (user change, workspace change, role change, clear, stream lag).
    const fn reset_pagination_state(&mut self) {
        self.oldest_loaded_id = None;
        self.has_more = false;
        self.loading_older = false;
        self.auto_scroll_enabled = true;
        self.pagination_gen = self.pagination_gen.wrapping_add(1);
    }

    /// Reset session display state: messages, dedup set, history flag, pagination.
    fn reset_chat_state(&mut self) {
        self.messages.clear();
        self.seen_ids.clear();
        self.history_loaded = false;
        self.role_menu_open = false;
        self.reset_pagination_state();
    }

    /// 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()
        }
    }

    /// Replace an optimistic placeholder with a confirmed pipeline message.
    ///
    /// If `optimistic_id` matches a locally-inserted optimistic message
    /// (`is_optimistic && message_id == optimistic_id`), swaps in the real
    /// [`DisplayMessage`], marks the canonical ID as seen, clears `sending`,
    /// and returns `Some(snap_task)` so the caller can early-return.
    /// Returns `None` when no replacement was performed.
    fn replace_optimistic(
        &mut self,
        optimistic_id: Option<&str>,
        message_id: &str,
        content: &str,
        direction: ChatDirection,
        agent_role: Option<&str>,
    ) -> 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)
            {
                self.messages[pos] = display_message(
                    None,
                    message_id.to_string(),
                    content.to_string(),
                    direction,
                    agent_role.map(std::string::ToString::to_string),
                    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.
    ///
    /// Returns `true` if the message was already seen (caller should bail).
    /// Inserts fresh IDs into `seen_ids` and prunes the set (keeping the
    /// most recent 200 IDs) when 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(200)
                .map(|m| m.message_id.clone())
                .collect();
            self.seen_ids.retain(|id| retain.contains(id));
        }
        false
    }

    /// Update typing/sending state based on message direction and sender.
    ///
    /// * **Agent** responses for the selected user → clear both `typing`
    ///   and `sending` (the agent has replied).
    /// * **User** message echo for the selected user → clear `sending`
    ///   only (re-enables the send button). Does **not** clear `typing`
    ///   — the typing indicator persists until an agent response arrives.
    ///
    /// Does nothing when `workspace` is not visible for the selected user
    /// (see [`Self::workspace_visible`]) — this prevents an agent response
    /// from an unrelated workspace from clearing the typing/sending
    /// indicators for the visible chat.
    fn update_sending_state(&mut self, direction: ChatDirection, user_name: &str, workspace: &str) {
        if !self.workspace_visible(workspace) {
            return;
        }
        if Some(user_name) != self.selected_user.as_deref() {
            return;
        }

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

    /// Append a chat message if it belongs to the selected user's visible
    /// chat (selected workspace or the user's personal workspace).
    ///
    /// Does nothing when `user_name` is not the selected user, or when
    /// `workspace` is not visible (see [`Self::workspace_visible`]).
    /// Takes ownership of the message fields so the caller avoids extra
    /// clones on the common (append) path.
    ///
    /// The caller should call [`maybe_snap()`](Self::maybe_snap)
    /// unconditionally after this (snap is always safe when nothing was
    /// appended).
    fn append_message(
        &mut self,
        user_name: &str,
        workspace: &str,
        message_id: String,
        content: String,
        direction: ChatDirection,
        agent_role: Option<String>,
    ) {
        if Some(user_name) != self.selected_user.as_deref() {
            return;
        }
        if !self.workspace_visible(workspace) {
            return;
        }

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

    #[expect(clippy::too_many_lines)]
    pub fn view(
        &self,
        active_role: Option<Role>,
        role_pool: &[Role],
        draining: bool,
    ) -> Element<'_, HomeMessage> {
        // ── Chat message area ────────────────────────────────────
        let chat_area = if self.messages.is_empty() {
            let empty_hint = if self.selected_user.is_none() {
                "No user selected. Create users via the Users page."
            } else if self.selected_workspace.is_none() {
                "No workspace selected."
            } else {
                "No messages yet. Type something below to start."
            };
            container(text(empty_hint).color(theme::TEXT_SECONDARY).size(13))
                .width(Length::Fill)
                .height(Length::Fill)
                .center_x(Length::Fill)
                .center_y(Length::Fill)
                .style(theme::base_container_style)
        } else {
            // Build message bubbles with typing indicator.
            let mut children: Vec<Element<'_, HomeMessage>> = self
                .messages
                .iter()
                .map(|msg| {
                    // ── Divider marker ────────────────────────────────────
                    if msg.direction == ChatDirection::Divider {
                        // Render as a horizontal rule with a label.
                        let label: Element<'_, HomeMessage> = container(
                            text("─ Session cleared ─")
                                .color(theme::TEXT_MUTED)
                                .size(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(4)
                        .padding(8)
                        .width(Length::Fill);

                        return divider.into();
                    }

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

                    // Render markdown content
                    let content: Element<'_, HomeMessage> = if msg.md_items.is_empty() {
                        super::widgets::selectable_text(&msg.content, theme::TEXT_PRIMARY)
                            .size(13)
                            .into()
                    } else {
                        super::media_markers::selectable_markdown_view(
                            &msg.md_items,
                            theme::markdown_settings(),
                        )
                        .map(HomeMessage::LinkClicked)
                    };

                    // Build bubble body: role icon header for agents, or just content for users.
                    let bubble_body: Element<'_, HomeMessage> = if is_user {
                        content
                    } else {
                        // Strip numeric suffix (e.g. "analyst_3" → "analyst") and parse.
                        let maybe_role = msg.agent_role.as_ref().and_then(|r| {
                            let stripped = r
                                .rsplit_once('_')
                                .and_then(|(base, suffix)| {
                                    if suffix.chars().all(|c| c.is_ascii_digit()) {
                                        Some(base)
                                    } else {
                                        None
                                    }
                                })
                                .unwrap_or(r.as_str());
                            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(14).color(icon_color);
                            column![row![icon].align_y(Alignment::Center), content]
                                .spacing(4)
                                .into()
                        } else {
                            content
                        }
                    };

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

                    // Per-bubble context menu: right-clicking the bubble offers
                    // copying the raw markdown content (the exact stored text
                    // with original media markers). Wrapping only the bubble —
                    // not the align_bubble row — keeps the spacer beside it a
                    // fall-through: spacer/empty-space right-clicks reach the
                    // outer "Reset session" menu in gui/mod.rs instead.
                    let bubble: Element<'_, HomeMessage> = ContextMenu::new(
                        bubble,
                        vec![MenuItem::new(
                            "Copy message".into(),
                            HomeMessage::CopyMessage(msg.content.clone()),
                        )],
                    )
                    .into();

                    align_bubble(bubble, is_user)
                })
                .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(10)
                    .style(theme::bubble_style(theme::BG_SURFACE, None))
                    .width(Length::FillPortion(3));

                children.push(align_bubble(typing_bubble, false));
            }

            // Prepend "Load older messages" button when applicable.
            if self.has_more && self.history_loaded {
                let load_text = if self.loading_older {
                    "Loading older messages..."
                } else {
                    "▲ Load older messages"
                };
                let load_btn = button(text(load_text).size(12).color(theme::TEXT_SECONDARY))
                    .style(move |_t: &iced::Theme, _status| {
                        use iced::widget::button;
                        button::Style {
                            background: Some(iced::Background::Color(theme::BG_SURFACE)),
                            border: iced::Border {
                                radius: 4.0.into(),
                                width: 0.0,
                                color: iced::Color::TRANSPARENT,
                            },
                            text_color: theme::TEXT_SECONDARY,
                            ..button::Style::default()
                        }
                    })
                    .width(Length::Fill)
                    .on_press_maybe(if self.loading_older {
                        None
                    } else {
                        Some(HomeMessage::LoadOlderMessages)
                    });
                children.insert(0, container(load_btn).padding(4).into());
            }

            container(
                scrollable(Column::with_children(children).spacing(12).padding(8))
                    .id(CHAT_SCROLL_ID)
                    .on_scroll(HomeMessage::ScrollChanged)
                    .direction(theme::vertical_scrollbar())
                    .style(theme::scrollbar_style)
                    .width(Length::Fill)
                    .height(Length::Fill),
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .style(theme::base_container_style)
        };

        // ── Input area ───────────────────────────────────────────
        let voice_status = crate::audio::voice::get_status();
        let recording = matches!(
            voice_status,
            crate::audio::voice::VoiceStatus::RecordingManual
        );
        // The Transcribing status is shared between the manual and wake-word
        // paths; only a mic-button recording shows the composer popup.
        let transcribing = matches!(voice_status, crate::audio::voice::VoiceStatus::Transcribing)
            && crate::audio::voice::is_manual_recording();
        // The mic is busy while the pipeline owns the mic for any recording
        // or ASR (manual or wake-word) — the button must not look active
        // when a new recording would be rejected.
        let mic_busy = matches!(
            voice_status,
            crate::audio::voice::VoiceStatus::Recording
                | crate::audio::voice::VoiceStatus::RecordingManual
                | crate::audio::voice::VoiceStatus::Transcribing
        );
        // With local transcription disabled the shared ASR model never loads,
        // so a mic-button recording can never start — present the control as
        // unavailable instead of a loading state that can never complete.
        let transcription_disabled = crate::audio::voice::is_transcription_disabled();
        let recording_unavailable = mic_busy || transcription_disabled;

        // Right-edge controls column: role selector + mic button.
        let mut controls: Vec<Element<'_, HomeMessage>> = Vec::new();
        let role_icon = match active_role {
            Some(role) => {
                let (fg, _) = theme::role_badge_color_for(&role);
                theme::role_icon(&role).size(15).color(fg)
            }
            None => lucide::bot::<iced::Theme, iced::Renderer>()
                .size(15)
                .color(theme::TEXT_MUTED),
        };
        let role_btn = button(role_icon)
            .on_press_maybe(
                (self.selected_user.is_some() && !role_pool.is_empty())
                    .then_some(HomeMessage::RoleMenuToggled),
            )
            .style(theme::icon_button_style(false))
            .padding(3);

        // ── Role dropdown (overlay, above the composer) ────────────
        // The role list floats above the whole widget tree via
        // `RoleMenu`'s overlay (Widget::overlay + Overlay trait) anchored
        // to the role button — opening it no longer shifts the chat
        // layout. Items carry the same roles/selection as before; the
        // current role is disabled with a checkmark, and selecting a role
        // publishes SwitchRole, which the Dashboard intercepts and persists
        // (it also sends RoleMenuClosed). Outside-click / Escape dismissal
        // is handled by the popup itself via RoleMenuClosed.
        let role_btn: Element<'_, HomeMessage> = if !role_pool.is_empty() {
            let user = self.selected_user.clone().unwrap_or_default();
            let items: Vec<RoleMenuItem<HomeMessage>> = role_pool
                .iter()
                .map(|role| {
                    let is_current = active_role.as_ref() == Some(role);
                    RoleMenuItem::new(
                        *role,
                        is_current,
                        (!is_current).then(|| HomeMessage::SwitchRole(user.clone(), *role)),
                    )
                })
                .collect();
            RoleMenu::new(
                role_btn,
                items,
                self.role_menu_open,
                HomeMessage::RoleMenuClosed,
            )
            .into()
        } else {
            role_btn.into()
        };
        controls.push(
            tooltip(
                role_btn,
                text("switch agent").size(11),
                tooltip::Position::Top,
            )
            .style(theme::tooltip_style)
            .into(),
        );

        let mic_btn = tooltip(
            button(lucide::mic::<iced::Theme, iced::Renderer>().size(14).color(
                if recording_unavailable {
                    theme::TEXT_MUTED
                } else {
                    theme::TEXT_SECONDARY
                },
            ))
            .on_press_maybe(
                (self.selected_user.is_some() && !recording_unavailable)
                    .then_some(HomeMessage::StartVoiceRecording),
            )
            .style(theme::icon_button_style(recording_unavailable))
            .padding(3),
            text(if transcription_disabled {
                "voice recording unavailable — local transcription is disabled"
            } else {
                "record voice message"
            })
            .size(11),
            tooltip::Position::Top,
        )
        .style(theme::tooltip_style);
        controls.push(mic_btn.into());

        let input_area = 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.sending || draining,
                // One line taller than the plain composer so the controls
                // column (role + mic) fits above the send button.
                min_height: 88.0,
                max_height: 330.0,
                controls,
                grey_on_empty: true,
                send_tooltip: "send text message",
            },
        );

        // ── Recording popup (stop + send / stop + discard) ───────
        // While transcribing, the popup stays visible as a passive
        // "Transcribing…" indicator (no stop controls — the ASR is finalizing).
        let recording_popup: Element<'_, HomeMessage> = if recording {
            let status_label = text("Recording voice message…")
                .size(13)
                .color(theme::STATUS_ERROR);
            let send_btn = button(text("Stop + Send").size(12))
                .on_press(HomeMessage::StopVoiceRecordingSend)
                .style(theme::button_primary)
                .padding(5);
            let discard_btn = button(text("Stop + Discard").size(12))
                .on_press(HomeMessage::StopVoiceRecordingDiscard)
                .style(theme::button_secondary)
                .padding(5);
            container(
                row![
                    status_label,
                    Space::new().width(Length::Fill),
                    send_btn,
                    discard_btn
                ]
                .spacing(8)
                .align_y(Alignment::Center),
            )
            .padding(8)
            .style(theme::surface_container_style)
            .width(Length::Fill)
            .into()
        } else if transcribing {
            container(
                row![
                    text("Transcribing voice message…")
                        .size(13)
                        .color(theme::TEXT_MUTED),
                    Space::new().width(Length::Fill),
                ]
                .spacing(8)
                .align_y(Alignment::Center),
            )
            .padding(8)
            .style(theme::surface_container_style)
            .width(Length::Fill)
            .into()
        } else {
            Space::new().height(0).into()
        };

        // ── Full layout ──────────────────────────────────────────
        column![chat_area, recording_popup, input_area,]
            .align_x(Alignment::End)
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

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

        // Keyboard shortcuts: Cmd+Z → undo, Cmd+Shift+Z → redo.
        // Also track modifier changes for shift+click text selection.
        subs.push(keyboard::listen().filter_map(|event| {
            super::common::composer_keyboard_event(
                event,
                HomeMessage::ModifiersChanged,
                || HomeMessage::Undo,
                || HomeMessage::Redo,
            )
        }));

        // Reset keyboard modifiers when the window loses focus, preventing
        // stale shift/ctrl/alt state from affecting the editor if the user
        // presses a modifier, switches apps, releases it, and returns.
        subs.push(iced::window::events().filter_map(|(_id, event)| {
            if matches!(event, iced::window::Event::Unfocused) {
                Some(HomeMessage::ModifiersChanged(keyboard::Modifiers::empty()))
            } else {
                None
            }
        }));

        iced::Subscription::batch(subs)
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, msg: HomeMessage) -> Task<HomeMessage> {
        match msg {
            HomeMessage::UserSelected(user) => {
                if self.selected_user.as_deref() == Some(&user) {
                    return Task::none();
                }
                self.selected_user = Some(user.clone());
                self.reset_chat_state();
                self.user_project_workspace = None; // re-resolved below

                Task::perform(
                    Self::resolve_user_workspace_sync(user, self.selected_workspace.clone()),
                    |msg| msg,
                )
            }
            HomeMessage::WorkspaceChanged(ws_name) => {
                self.selected_workspace.clone_from(&ws_name);
                self.reset_chat_state();

                // When a user is already selected, refresh history immediately.
                // Otherwise defer — `ResolveUserSelected` will pick it up once
                // a user is chosen (e.g. first boot before UsersLoaded fires).
                let Some(user) = self.selected_user.clone() else {
                    self.pending_workspace_refresh = true;
                    return Task::none();
                };
                self.pending_workspace_refresh = false;
                // At the Personal picker the view merges the user's DB-selected
                // project workspace — re-read it so Users-page edits (which
                // flow through WorkspaceChanged) are reflected, then load in
                // one shot. At a project picker the merge partner is the
                // selected workspace itself, so a direct refresh suffices.
                if self.at_personal_picker() {
                    let read_user = user.clone();
                    Task::perform(Self::project_workspace_for(read_user), move |project| {
                        HomeMessage::ProjectWorkspaceRefreshed(user, project)
                    })
                } else {
                    self.refresh_history()
                }
            }
            HomeMessage::ProjectWorkspaceRefreshed(user, project) => {
                // Stale resolve (user switched while reading) — the newer
                // selection owns its own resolution.
                if self.selected_user.as_deref() != Some(&user) {
                    return Task::none();
                }
                let at_personal_picker = self.at_personal_picker();
                self.user_project_workspace = project;
                // Re-load only while the merge partner is part of the view; a
                // later project-picker switch already refreshed.
                if at_personal_picker {
                    self.refresh_history()
                } else {
                    Task::none()
                }
            }
            HomeMessage::InputChanged(action) => {
                super::common::apply_editor_action(
                    &mut self.editor_content,
                    &mut self.undo_stack,
                    action,
                    self.modifiers.shift(),
                );
                Task::none()
            }
            HomeMessage::ModifiersChanged(modifiers) => {
                self.modifiers = modifiers;
                Task::none()
            }
            HomeMessage::Undo => {
                let snapshot = self.undo_stack.undo(&self.editor_content);
                super::common::restore_undo_snapshot(&mut self.editor_content, snapshot);
                Task::none()
            }
            HomeMessage::Redo => {
                let snapshot = self.undo_stack.redo(&self.editor_content);
                super::common::restore_undo_snapshot(&mut self.editor_content, snapshot);
                Task::none()
            }
            HomeMessage::ResolveUserSelected {
                user,
                sidebar_ws,
                project_ws,
            } => {
                // Stale resolve (user switched while reading) — the newer
                // selection owns its own resolution.
                if self.selected_user.as_deref() != Some(&user) {
                    return Task::none();
                }
                // The user's DB-selected project workspace is the merge
                // partner for the Personal-picker chat view.
                self.user_project_workspace = project_ws;
                if sidebar_ws != self.selected_workspace {
                    // Sidebar must move to the user's DB workspace — the
                    // Dashboard intercepts RequestWorkspaceChange and cascades
                    // a WorkspaceChanged refresh.
                    return Task::done(HomeMessage::RequestWorkspaceChange(
                        sidebar_ws.unwrap_or_default(),
                    ));
                }
                // Reverse-sync check completed: either the user's DB workspace
                // matches the sidebar (no disagreement), or no DB workspace
                // exists for this user.
                self.selected_workspace = sidebar_ws;
                //
                // If WorkspaceChanged arrived before a user was selected
                // (boot timing), it deferred the refresh via the flag.
                // Clear stale state now before loading history.
                if self.pending_workspace_refresh {
                    self.pending_workspace_refresh = false;
                    self.reset_chat_state();
                }
                self.refresh_history()
            }
            HomeMessage::SendMessage => {
                self.role_menu_open = false;
                self.send_message()
            }
            HomeMessage::HistoryLoaded(entries, has_more) => {
                // Track oldest loaded ID and whether more exist for pagination.
                self.oldest_loaded_id = entries.first().map(|e| e.id);
                self.has_more = has_more;
                for entry in entries {
                    let msg_id = self.push_message(entry);
                    self.seen_ids.insert(msg_id);
                }
                self.history_loaded = true;
                // Snap to end only if auto-scroll is enabled.
                self.maybe_snap()
            }
            HomeMessage::HistoryLoadError(e) => {
                tracing::warn!(error = %e, "Home: failed to load chat history");
                Task::none()
            }
            HomeMessage::UsersLoaded(options) => {
                // If no user is selected, auto-select the first one (admin at boot).
                if self.selected_user.is_none() && !options.is_empty() {
                    let first = options[0].value.clone();
                    return Task::done(HomeMessage::UserSelected(first));
                }
                // If the selected user no longer exists in the loaded list
                // (deleted from another session), auto-select the first user.
                if let Some(ref user) = self.selected_user {
                    if !options.iter().any(|opt| opt.value == *user) && !options.is_empty() {
                        let first = options[0].value.clone();
                        return Task::done(HomeMessage::UserSelected(first));
                    }
                }
                Task::none()
            }
            HomeMessage::ClearChat => {
                // Clear messages synchronously first (prevents flash).
                self.messages.clear();
                self.seen_ids.clear();
                self.sending = false;
                self.typing = false;
                self.typing_tick_state = 0;
                self.role_menu_open = false;
                self.reset_pagination_state();

                // Build agent ID and schedule async cleanup.
                let sender = match &self.selected_user {
                    Some(s) => s.clone(),
                    None => return Task::none(),
                };
                Task::perform(
                    async move {
                        // Clear the session the user actually talks to — the
                        // same (role, workspace) resolution as routing and
                        // Telegram /clear (see
                        // [`crate::users::resolve_session_target`]): the
                        // starting workspace is the user's DB workspace, never
                        // the GUI picker position, so the Personal picker
                        // clears the project Manager conversation instead of
                        // a phantom Analyst session in the personal workspace.
                        let (effective_role, ws) =
                            crate::users::resolve_session_target(&sender).await;
                        let _ = crate::session::clear_session(
                            &sender,
                            effective_role.as_str(),
                            &ws.name,
                        )
                        .await;
                        // Insert a divider marker instead of deleting history.
                        let store = crate::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),
                    },
                )
            }
            HomeMessage::ChatCleared => {
                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::SwitchRole(user, role) => {
                // Intercepted by Dashboard — no-op in Home
                tracing::debug!("Home: SwitchRole({user}, {role}) — handled by Dashboard");
                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,
                } => {
                    // 1. Replace optimistic placeholder if present.
                    if let Some(task) = self.replace_optimistic(
                        optimistic_id.as_deref(),
                        &message_id,
                        &content,
                        direction,
                        agent_role.as_deref(),
                    ) {
                        return task;
                    }

                    // 2. Deduplicate against already-seen IDs.
                    if self.try_dedup(&message_id) {
                        return Task::none();
                    }

                    // 3. Clear sending/typing state based on direction, sender, and workspace.
                    self.update_sending_state(direction, &user_name, &workspace);

                    // 4. Append the message (filtered by selected user + workspace).
                    self.append_message(
                        &user_name, &workspace, message_id, content, direction, agent_role,
                    );

                    self.maybe_snap()
                }
                crate::ChatEvent::Typing {
                    user_name,
                    is_typing,
                    workspace,
                } => {
                    // Apply user + workspace filter — only show typing indicator
                    // for the selected user in a visible workspace.
                    if Some(&user_name) == self.selected_user.as_ref()
                        && self.workspace_visible(&workspace)
                    {
                        self.typing = is_typing;
                        if is_typing {
                            self.typing_tick_state = 0;
                        }
                    }
                    Task::none()
                }
            },
            HomeMessage::StreamLagged => {
                // Resync: reload history. Also clear sending as a safety
                // net — if the agent response was dropped due to the lag,
                // this prevents the send button from staying stuck.
                self.sending = false;
                self.seen_ids.clear();
                self.reset_pagination_state();
                self.refresh_history()
            }
            HomeMessage::ScrollChanged(viewport) => {
                // Determine if the user is at the bottom. Two checks:
                // 1. Content is taller than viewport AND relative offset >= 0.99
                // 2. Content fits entirely in viewport (no scrolling needed)
                let at_bottom = {
                    let bounds = viewport.bounds();
                    let content = viewport.content_bounds();
                    if content.height > bounds.height {
                        viewport.relative_offset().y >= 0.99
                    } else {
                        content.height <= bounds.height
                    }
                };
                self.auto_scroll_enabled = at_bottom;
                Task::none()
            }
            HomeMessage::LoadOlderMessages => {
                // Guard against double-clicks.
                if self.loading_older {
                    return Task::none();
                }
                self.loading_older = true;
                let sender = match &self.selected_user {
                    Some(s) => s.clone(),
                    None => return Task::none(),
                };
                let Some(chat) = self.visible_workspaces() else {
                    return Task::none();
                };
                let Some(before_id) = self.oldest_loaded_id else {
                    self.loading_older = false;
                    return Task::none();
                };
                let generation = self.pagination_gen;
                Task::perform(
                    async move {
                        let store = crate::chat_history::store();
                        store
                            .load_older_for_user_workspaces(
                                &sender,
                                &chat.primary,
                                chat.merge.as_deref(),
                                before_id,
                            )
                            .await
                            .map(|(entries, has_more)| (entries, has_more, generation))
                            .map_err(|e| e.to_string())
                    },
                    |result| match result {
                        Ok((entries, has_more, generation)) => {
                            HomeMessage::OlderHistoryLoaded(entries, has_more, generation)
                        }
                        Err(e) => HomeMessage::OlderHistoryLoadError(e),
                    },
                )
            }
            HomeMessage::OlderHistoryLoaded(display_entries, has_more, generation) => {
                // Guard against stale callbacks.
                if generation != self.pagination_gen {
                    self.loading_older = false;
                    return Task::none();
                }
                // Prepend entries to the beginning of messages.
                let mut prepended: Vec<DisplayMessage> = display_entries
                    .into_iter()
                    .map(DisplayMessage::from)
                    .collect();
                // Track seen_ids for the prepended messages.
                for msg in &prepended {
                    self.seen_ids.insert(msg.message_id.clone());
                }
                prepended.append(&mut self.messages);
                self.messages = prepended;
                // Update oldest_loaded_id and has_more.
                self.oldest_loaded_id = self.messages.first().and_then(|m| m.id);
                self.has_more = has_more;
                self.loading_older = false;
                // Snap to end if auto-scroll enabled.
                self.maybe_snap()
            }
            HomeMessage::OlderHistoryLoadError(msg) => {
                self.loading_older = false;
                Task::done(HomeMessage::Toast(ToastMessage::Error(msg)))
            }
            HomeMessage::RequestWorkspaceChange(_) => {
                // This variant is intercepted by the Dashboard and should
                // never reach Home's update handler.  No-op fallback.
                Task::none()
            }
            HomeMessage::Toast(_) => {
                // Intercepted by Dashboard.  No-op fallback.
                Task::none()
            }
            HomeMessage::LinkClicked(url) => {
                super::open_url(&url);
                Task::none()
            }
            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::RoleMenuToggled => {
                self.role_menu_open = !self.role_menu_open;
                Task::none()
            }
            HomeMessage::RoleMenuClosed => {
                self.role_menu_open = false;
                Task::none()
            }
            HomeMessage::StartVoiceRecording => {
                self.role_menu_open = false;
                // 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::manual_recording_blocked_reason() {
                    return Task::done(HomeMessage::Toast(ToastMessage::Warning(msg.to_string())));
                }
                crate::audio::voice::send_command(
                    crate::audio::voice::VoiceCommand::StartRecording,
                );
                Task::none()
            }
            HomeMessage::StopVoiceRecordingSend => {
                crate::audio::voice::send_command(
                    crate::audio::voice::VoiceCommand::StopRecordingSend,
                );
                Task::none()
            }
            HomeMessage::StopVoiceRecordingDiscard => {
                crate::audio::voice::send_command(
                    crate::audio::voice::VoiceCommand::StopRecordingDiscard,
                );
                Task::none()
            }
        }
    }

    /// Construct and send the user's message through the GUI channel.
    fn send_message(&mut self) -> Task<HomeMessage> {
        let text = self.editor_content.text();
        let trimmed = match super::common::send_guard(&text, self.sending, true, |count| {
            Task::done(HomeMessage::Toast(ToastMessage::Warning(format!(
                "Message too long: {count} characters (maximum {MAX_INPUT_CHARS}). Please shorten your message and try again."
            ))))
        }) {
            Ok(t) => t,
            Err(task) => return task,
        };

        let content = trimmed.to_string();

        let sender = match &self.selected_user {
            Some(s) => s.clone(),
            None => return Task::none(),
        };

        // 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 Task::none();
        }

        // Generate an optimistic ID for non-command messages so the Home page
        // can display the user's message immediately and replace it when the
        // pipeline confirmation arrives. Commands (starting with "/") are NOT
        // optimistically shown because `handle_bot_command` intercepts
        // them before the GUI broadcast in `process_channel_message` — the
        // confirmation never arrives, so an optimistic entry would become an orphan.
        let is_command = content.starts_with('/');
        let optimistic_id = if is_command {
            None
        } else {
            Some(crate::generate_id())
        };

        // Clear the editor.
        self.editor_content = text_editor::Content::new();
        self.undo_stack.clear();
        self.sending = true;

        // Push optimistic message immediately so the user sees their own
        // message without waiting for the pipeline round-trip.
        if let Some(ref opt_id) = optimistic_id {
            self.messages.push(display_message(
                None,
                opt_id.clone(),
                content.clone(),
                ChatDirection::User,
                None,
                true,
            ));
        }

        let msg = crate::ChannelMessage {
            user_name: sender.clone(),
            reply_target: sender,
            content,
            channel: "gui".to_string(),
            workspace: self.selected_workspace.clone().unwrap_or_default(),
            optimistic_id,
            callback_query_id: None,
        };

        // Push to GUI_MESSAGE_TX.
        if let Some(tx) = crate::GUI_MESSAGE_TX.get() {
            if let Err(e) = tx.send(msg) {
                tracing::error!("Home: failed to send message via GUI_MESSAGE_TX: {e}");
                self.sending = false;
                return Task::none();
            }
        } else {
            tracing::error!("Home: GUI_MESSAGE_TX not initialized");
            self.sending = false;
            return Task::none();
        }

        // Spawn a safety timeout: if sending stays true for 30 seconds
        // (silent agent failure, crash, cancellation), auto-clear it.
        // Generation counter prevents a stale timeout from clearing
        // sending during a new send.
        self.sending_gen = self.sending_gen.wrapping_add(1);
        let generation = self.sending_gen;
        let timeout_task = Task::perform(
            async move {
                tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                HomeMessage::SendingTimeout(generation)
            },
            |msg| msg,
        );
        // Snap to end on optimistic push if auto-scroll enabled.
        Task::batch([timeout_task, self.maybe_snap()])
    }
}

/// 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;
        })
    })
}

/// 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::*;

    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------

    fn make_home_state(user: &str, workspace: &str) -> HomeState {
        let mut state = HomeState::new();
        state.selected_user = Some(user.to_string());
        state.selected_workspace = Some(workspace.to_string());
        state
    }

    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),
            md_items: Vec::new(),
            is_optimistic,
        }
    }

    // ------------------------------------------------------------------
    // replace_optimistic
    // ------------------------------------------------------------------

    #[test]
    fn test_replace_optimistic_found() {
        let mut state = make_home_state("alice", "ws1");
        state.messages.push(make_msg(
            "opt-1",
            "(placeholder)",
            ChatDirection::User,
            None,
            true,
        ));

        let task = state.replace_optimistic(
            Some("opt-1"),
            "real-42",
            "Hello!",
            ChatDirection::User,
            None,
        );

        assert!(task.is_some(), "expected Some(task) for found optimistic");
        assert_eq!(state.messages.len(), 1);
        let replaced = &state.messages[0];
        assert_eq!(replaced.message_id, "real-42");
        assert_eq!(replaced.content, "Hello!");
        assert!(!replaced.is_optimistic, "should no longer be optimistic");
        assert!(
            state.seen_ids.contains("real-42"),
            "seen_ids should track canonical ID"
        );
        assert!(!state.sending, "sending should be cleared");
    }

    #[test]
    fn test_replace_optimistic_not_found() {
        let mut state = make_home_state("alice", "ws1");
        state.messages.push(make_msg(
            "opt-1",
            "(placeholder)",
            ChatDirection::User,
            None,
            true,
        ));

        // optimistic_id does not match any message
        let task = state.replace_optimistic(
            Some("wrong-opt"),
            "real-42",
            "Hello!",
            ChatDirection::User,
            None,
        );

        assert!(task.is_none(), "expected None when no optimistic match");
        assert_eq!(state.messages.len(), 1);
        assert_eq!(
            state.messages[0].message_id, "opt-1",
            "original should be untouched"
        );
    }

    #[test]
    fn test_replace_optimistic_no_opt_id() {
        let mut state = make_home_state("alice", "ws1");

        let task = state.replace_optimistic(None, "real-42", "Hello!", ChatDirection::User, None);

        assert!(task.is_none(), "expected None when optimistic_id is None");
    }

    // ------------------------------------------------------------------
    // try_dedup
    // ------------------------------------------------------------------

    #[test]
    fn test_try_dedup_fresh() {
        let mut state = make_home_state("alice", "ws1");
        assert!(!state.try_dedup("msg-1"), "fresh ID should return false");
        assert!(state.seen_ids.contains("msg-1"), "fresh ID should be added");
    }

    #[test]
    fn test_try_dedup_duplicate() {
        let mut state = make_home_state("alice", "ws1");
        state.seen_ids.insert("msg-1".to_string());
        assert!(state.try_dedup("msg-1"), "duplicate should return true");
    }

    #[test]
    fn test_try_dedup_pruning() {
        let mut state = make_home_state("alice", "ws1");
        // Add 500 IDs.
        for i in 0..DEDUP_PRUNE_THRESHOLD {
            state.seen_ids.insert(format!("old-{i}"));
        }
        // Push 200 messages so there is a retain pool.
        for i in 0..200u32 {
            state.messages.push(make_msg(
                &format!("old-{i}"),
                "",
                ChatDirection::User,
                None,
                false,
            ));
        }
        // Add one more (breaches the threshold).
        state.seen_ids.insert("extra".to_string());
        assert_eq!(state.seen_ids.len(), 501);

        // Calling try_dedup on a fresh ID triggers pruning.
        assert!(!state.try_dedup("fresh"));

        // After pruning, seen_ids only has the 200 message IDs.
        // "fresh" and "extra" are dropped because they are not in messages.
        assert_eq!(state.seen_ids.len(), 200);
        assert!(!state.seen_ids.contains("fresh"));
        assert!(!state.seen_ids.contains("extra"));
        // An ID that is in messages is retained.
        assert!(state.seen_ids.contains("old-0"));
        assert!(state.seen_ids.contains("old-199"));
    }

    // ------------------------------------------------------------------
    // update_sending_state
    // ------------------------------------------------------------------

    #[test]
    fn test_update_sending_state() {
        let cases = [
            (
                "agent match",
                ChatDirection::Agent,
                "alice",
                "ws1",
                false,
                false,
            ),
            (
                "user match",
                ChatDirection::User,
                "alice",
                "ws1",
                false,
                true,
            ),
            ("wrong user", ChatDirection::Agent, "bob", "ws1", true, true),
            (
                "wrong workspace",
                ChatDirection::Agent,
                "alice",
                "ws2",
                true,
                true,
            ),
        ];
        for (name, direction, user, workspace, exp_sending, exp_typing) in cases {
            let mut state = make_home_state("alice", "ws1");
            state.sending = true;
            state.typing = true;
            state.update_sending_state(direction, user, workspace);
            assert_eq!(state.sending, exp_sending, "{name}: sending");
            assert_eq!(state.typing, exp_typing, "{name}: typing");
        }
    }

    // ------------------------------------------------------------------
    // append_message
    // ------------------------------------------------------------------

    #[test]
    fn test_append_message_match() {
        let mut state = make_home_state("alice", "ws1");
        assert_eq!(state.messages.len(), 0);

        state.append_message(
            "alice",
            "ws1",
            "msg-1".to_string(),
            "Hello!".to_string(),
            ChatDirection::User,
            None,
        );

        assert_eq!(state.messages.len(), 1);
        assert_eq!(state.messages[0].message_id, "msg-1");
        assert_eq!(state.messages[0].content, "Hello!");
    }

    #[test]
    fn test_append_message_no_match_user() {
        let mut state = make_home_state("alice", "ws1");

        state.append_message(
            "bob",
            "ws1",
            "msg-1".to_string(),
            "Hello!".to_string(),
            ChatDirection::User,
            None,
        );

        assert_eq!(
            state.messages.len(),
            0,
            "bob's message should be filtered out"
        );
    }

    #[test]
    fn test_append_message_no_match_workspace() {
        let mut state = make_home_state("alice", "ws1");

        state.append_message(
            "alice",
            "ws2",
            "msg-1".to_string(),
            "Hello!".to_string(),
            ChatDirection::User,
            None,
        );

        assert_eq!(
            state.messages.len(),
            0,
            "ws2 message should be filtered out"
        );
    }

    #[test]
    fn test_append_message_agent_response() {
        let mut state = make_home_state("alice", "ws1");

        state.append_message(
            "alice",
            "ws1",
            "msg-agent".to_string(),
            "Agent answer".to_string(),
            ChatDirection::Agent,
            Some("engineer".to_string()),
        );

        assert_eq!(state.messages.len(), 1);
        assert_eq!(state.messages[0].direction, ChatDirection::Agent);
        assert_eq!(state.messages[0].agent_role.as_deref(), Some("engineer"),);
    }

    // ------------------------------------------------------------------
    // personal-workspace visibility (Assistant/Artist at any picker)
    // ------------------------------------------------------------------

    #[test]
    fn test_visible_chat_symmetric_at_any_picker() {
        // Project picker: project + personal visible; unrelated stays hidden.
        let project = make_home_state("alice", "ws1");
        assert_eq!(
            project.visible_workspaces(),
            Some(VisibleChat {
                primary: "ws1".to_string(),
                merge: Some("personal:alice".to_string()),
            })
        );
        assert!(project.workspace_visible("ws1"));
        assert!(
            project.workspace_visible("personal:alice"),
            "personal Assistant/Artist messages must be visible at any picker"
        );
        assert!(!project.workspace_visible("ws2"));
        assert!(
            !project.workspace_visible("personal:bob"),
            "another user's personal workspace is not visible"
        );

        // Personal picker: personal + the user's DB project workspace visible
        // (symmetric — the picker selects the recipient, not the view).
        let mut personal = make_home_state("alice", "");
        personal.user_project_workspace = Some("ws1".to_string());
        assert_eq!(
            personal.resolve_workspace_name().as_deref(),
            Some("personal:alice"),
            "empty picker selection resolves to the personal workspace"
        );
        assert_eq!(
            personal.visible_workspaces(),
            Some(VisibleChat {
                primary: "personal:alice".to_string(),
                merge: Some("ws1".to_string()),
            }),
            "personal picker merges the user's project workspace"
        );
        assert!(personal.workspace_visible("personal:alice"));
        assert!(
            personal.workspace_visible("ws1"),
            "project messages must be visible at the personal picker"
        );
        assert!(
            !personal.workspace_visible("ws2"),
            "a non-selected project workspace stays hidden at the personal picker"
        );

        // No DB project workspace → personal-only view; no user → no chat.
        let personal_only = make_home_state("alice", "");
        assert_eq!(
            personal_only.visible_workspaces(),
            Some(VisibleChat {
                primary: "personal:alice".to_string(),
                merge: None,
            }),
            "personal picker without a project workspace shows only the personal chat"
        );
        assert!(!personal_only.workspace_visible("ws1"));
        assert_eq!(HomeState::new().visible_workspaces(), None);
    }

    #[test]
    fn test_workspace_changed_at_personal_picker_resets_and_defers() {
        // Switching to the Personal picker resets the chat and re-reads the
        // user's DB project workspace (completion via ProjectWorkspaceRefreshed
        // is covered by test_project_workspace_refreshed_updates_merge_partner).
        let mut state = make_home_state("alice", "ws1");
        state.user_project_workspace = Some("ws1".to_string());
        state
            .messages
            .push(make_msg("m1", "hi", ChatDirection::User, None, false));

        let _task = state.update(HomeMessage::WorkspaceChanged(Some(String::new())));
        assert_eq!(state.selected_workspace.as_deref(), Some(""));
        assert!(
            state.messages.is_empty(),
            "chat state resets on workspace change"
        );
        assert_eq!(
            state.resolve_workspace_name().as_deref(),
            Some("personal:alice"),
            "empty picker selection resolves to the personal workspace"
        );

        // A project-picker change refreshes history directly and keeps the
        // merge partner untouched (it only matters at the Personal picker).
        let mut state = make_home_state("alice", "ws1");
        state.user_project_workspace = Some("ws1".to_string());
        let _task = state.update(HomeMessage::WorkspaceChanged(Some("ws2".to_string())));
        assert_eq!(state.selected_workspace.as_deref(), Some("ws2"));
        assert_eq!(state.user_project_workspace.as_deref(), Some("ws1"));
    }

    #[test]
    fn test_project_workspace_refreshed_updates_merge_partner() {
        // At the Personal picker the refreshed DB project workspace drives
        // the view (the wiring that keeps the merge partner fresh after a
        // Users-page workspace edit).
        let mut state = make_home_state("alice", "");
        state.user_project_workspace = Some("ws1".to_string());

        // A stale read for a different user is ignored.
        let _ = state.update(HomeMessage::ProjectWorkspaceRefreshed(
            "bob".to_string(),
            Some("ws9".to_string()),
        ));
        assert_eq!(state.user_project_workspace.as_deref(), Some("ws1"));

        // The current user's refreshed value applies and the view follows.
        let _ = state.update(HomeMessage::ProjectWorkspaceRefreshed(
            "alice".to_string(),
            Some("ws2".to_string()),
        ));
        assert_eq!(state.user_project_workspace.as_deref(), Some("ws2"));
        assert!(state.workspace_visible("ws2"));
        assert!(!state.workspace_visible("ws1"));
        assert_eq!(
            state.visible_workspaces(),
            Some(VisibleChat {
                primary: "personal:alice".to_string(),
                merge: Some("ws2".to_string()),
            })
        );

        // At a project picker the refreshed value is stored but the view is
        // the selected workspace (no reload needed there).
        let mut state = make_home_state("alice", "ws1");
        state.user_project_workspace = Some("ws1".to_string());
        let _ = state.update(HomeMessage::ProjectWorkspaceRefreshed(
            "alice".to_string(),
            Some("ws2".to_string()),
        ));
        assert_eq!(state.user_project_workspace.as_deref(), Some("ws2"));
        assert_eq!(
            state.visible_workspaces(),
            Some(VisibleChat {
                primary: "ws1".to_string(),
                merge: Some("personal:alice".to_string()),
            })
        );
    }

    #[test]
    fn test_resolve_user_selected_stale_user_guard() {
        // A resolve for a user that is no longer selected must not apply
        // (fast user switch while the DB read was in flight) — same guard as
        // ProjectWorkspaceRefreshed.
        let mut state = make_home_state("alice", "");
        let _ = state.update(HomeMessage::ResolveUserSelected {
            user: "bob".to_string(),
            sidebar_ws: Some("ws_bob".to_string()),
            project_ws: Some("ws_bob".to_string()),
        });
        assert_eq!(state.selected_user.as_deref(), Some("alice"));
        assert_eq!(state.selected_workspace.as_deref(), Some(""));
        assert_eq!(state.user_project_workspace, None);

        // The current user's resolve applies the merge partner.
        let _ = state.update(HomeMessage::ResolveUserSelected {
            user: "alice".to_string(),
            sidebar_ws: Some("ws1".to_string()),
            project_ws: Some("ws1".to_string()),
        });
        assert_eq!(state.user_project_workspace.as_deref(), Some("ws1"));
    }

    #[tokio::test]
    async fn test_project_workspace_for_reads_db_normalized() {
        crate::util::test::init_test_stores().await;
        let user = "home_project_workspace_for";
        let store = crate::users::USER_STORE
            .get()
            .expect("users store initialized");
        store
            .add_user(user, Some("full"), &[Role::Manager])
            .await
            .expect("add user");

        // Unset → None.
        assert_eq!(
            HomeState::project_workspace_for(user.to_string()).await,
            None
        );

        // Personal DB workspace → None.
        store
            .update_user(
                user,
                crate::users::FieldUpdate::Unchanged,
                crate::users::FieldUpdate::Set("personal:home_project_workspace_for"),
                crate::users::FieldUpdate::Unchanged,
            )
            .await
            .expect("set personal workspace");
        assert_eq!(
            HomeState::project_workspace_for(user.to_string()).await,
            None
        );

        // Project DB workspace → Some(ws).
        crate::util::test::create_test_workspace(
            "/tmp/home_project_workspace_for_ws",
            "ws_home_project_workspace_for",
        )
        .await;
        store
            .update_user(
                user,
                crate::users::FieldUpdate::Unchanged,
                crate::users::FieldUpdate::Set("ws_home_project_workspace_for"),
                crate::users::FieldUpdate::Unchanged,
            )
            .await
            .expect("set project workspace");
        assert_eq!(
            HomeState::project_workspace_for(user.to_string())
                .await
                .as_deref(),
            Some("ws_home_project_workspace_for")
        );
    }

    #[test]
    fn test_call_site_wiring_symmetric_at_any_picker() {
        // (picker, message workspace, agent role, content) — both directions:
        // at the project picker personal Assistant/Artist messages append and
        // clear sending/typing; at the personal picker the same holds for
        // Manager replies in the user's DB project workspace.
        let cases = [
            ("ws1", "personal:alice", "assistant", "Assistant reply"),
            ("", "ws1", "manager", "Manager reply"),
        ];
        for (picker, msg_ws, role, content) in cases {
            let mut state = make_home_state("alice", picker);
            state.user_project_workspace = Some("ws1".to_string());
            state.append_message(
                "alice",
                msg_ws,
                "msg".to_string(),
                content.to_string(),
                ChatDirection::Agent,
                Some(role.to_string()),
            );
            assert_eq!(state.messages.len(), 1);
            assert_eq!(state.messages[0].content, content);
            state.sending = true;
            state.typing = true;
            state.update_sending_state(ChatDirection::Agent, "alice", msg_ws);
            assert!(!state.sending);
            assert!(!state.typing);
        }

        // A project workspace that is not the user's own stays hidden at the
        // personal picker.
        let mut state = make_home_state("alice", "");
        state.user_project_workspace = Some("ws1".to_string());
        state.append_message(
            "alice",
            "ws2",
            "msg-other".to_string(),
            "other".to_string(),
            ChatDirection::Agent,
            None,
        );
        assert_eq!(
            state.messages.len(),
            0,
            "messages from an unrelated workspace must not append at the personal picker"
        );
    }

    // ------------------------------------------------------------------
    // entry_to_display_message
    // ------------------------------------------------------------------

    #[test]
    fn test_display_message_from_user() {
        let entry = ChatHistoryEntry {
            id: 1,
            message_id: "msg-1".to_string(),
            content: "Hello **world**".to_string(),
            direction: ChatDirection::User,
            agent_role: None,
        };
        let msg = DisplayMessage::from(entry);

        assert_eq!(msg.id, Some(1));
        assert_eq!(msg.direction, ChatDirection::User);
        assert_eq!(msg.content, "Hello **world**");
        assert!(
            !msg.md_items.is_empty(),
            "user message should produce markdown items"
        );
        assert!(!msg.is_optimistic);
    }

    #[test]
    fn test_display_message_divider() {
        let entry = ChatHistoryEntry {
            id: 42,
            message_id: "divider-1".to_string(),
            content: "2026-07-17T20:30:00Z".to_string(),
            direction: ChatDirection::Divider,
            agent_role: None,
        };
        let msg = DisplayMessage::from(entry);

        assert_eq!(msg.id, Some(42));
        assert_eq!(msg.direction, ChatDirection::Divider);
        assert_eq!(msg.content, "2026-07-17T20:30:00Z");
        // Dividers should produce NO markdown items — they render as rules.
        assert!(
            msg.md_items.is_empty(),
            "divider entry should produce empty markdown items, got {} items",
            msg.md_items.len()
        );
        assert!(!msg.is_optimistic);
    }

    // ------------------------------------------------------------------
    // ModifiersChanged + shift+click
    // ------------------------------------------------------------------

    #[test]
    fn test_modifiers_changed_updates_state() {
        let mut state = make_home_state("alice", "ws1");

        // Default is empty modifiers
        assert!(!state.modifiers.shift());

        // Simulate Shift pressed
        let shift_mods = keyboard::Modifiers::SHIFT;
        let _task = state.update(HomeMessage::ModifiersChanged(shift_mods));

        assert!(state.modifiers.shift());

        // Simulate reset via Unfocused (empty modifiers)
        let _task = state.update(HomeMessage::ModifiersChanged(keyboard::Modifiers::empty()));

        assert!(!state.modifiers.shift());
    }

    #[test]
    fn test_shift_click_converts_to_drag() {
        use iced::Point;

        let mut state = make_home_state("alice", "ws1");
        state.editor_content = text_editor::Content::with_text("hello world");

        // Click somewhere to position cursor. Even without a font system,
        // hit-testing at (0,0) on non-empty text typically resolves to
        // the first cursor position (line 0, col 0).
        state
            .editor_content
            .perform(text_editor::Action::Click(Point { x: 0.0, y: 0.0 }));

        let cursor_before = state.editor_content.cursor();
        // Click clears selection
        assert!(
            cursor_before.selection.is_none(),
            "Click should clear selection"
        );

        // Now hold Shift
        state.modifiers = keyboard::Modifiers::SHIFT;

        // Dispatch a Click at a different position — should be converted to Drag
        let _task = state.update(HomeMessage::InputChanged(text_editor::Action::Click(
            Point { x: 100.0, y: 0.0 },
        )));

        let cursor_after = state.editor_content.cursor();

        // Drag anchors selection at current cursor when none exists. Even if
        // hit-testing at (100, 0) yields the same or no position, the selection
        // should now be Some — verifying the Click→Drag conversion happened.
        assert!(
            cursor_after.selection.is_some(),
            "shift+click should create selection via Action::Drag conversion; \
             got selection={:?}",
            cursor_after.selection
        );
    }

    // ------------------------------------------------------------------
    // send_message
    // ------------------------------------------------------------------

    #[test]
    fn test_send_message_empty_is_noop() {
        let mut state = make_home_state("alice", "ws1");
        // Empty content — should return Task::none() and not change state.
        state.editor_content = text_editor::Content::new();
        let _task = state.send_message();
        assert!(!state.sending);
        assert!(state.editor_content.text().is_empty());

        // Whitespace-only content should also be treated as empty.
        state.editor_content = text_editor::Content::with_text("   ");
        let _task = state.send_message();
        assert!(!state.sending);
    }

    #[test]
    fn test_send_message_within_limit_clears_editor() {
        let mut state = make_home_state("alice", "ws1");
        state.editor_content = text_editor::Content::with_text("hello world");
        let _task = state.send_message();
        // Editor must be cleared before the GUI_MESSAGE_TX send attempt.
        assert!(
            state.editor_content.text().is_empty(),
            "editor should be cleared after accepting a within-limit message"
        );
        // Assert the optimistic push, not `sending` — GUI_MESSAGE_TX is uninitialized in tests.
        assert!(
            state
                .messages
                .iter()
                .any(|m| m.is_optimistic && m.content == "hello world"),
            "optimistic message should be pushed for accepted non-command text"
        );
    }
}