choreo-daemon 0.2.0

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

/// Bound for joining a connection's writer thread during cleanup. A healthy
/// writer exits immediately on channel disconnect (dropping `writer_tx` in
/// `cleanup_client` disconnects `writer_rx`); the grace covers a writer
/// wedged in a blocking socket write — a client that is open but not reading
/// — which cannot exit on the channel disconnect alone (see the comment at
/// the call site in `cleanup_client`).
const WRITER_JOIN_GRACE: Duration = Duration::from_secs(5);

/// Socket write timeout applied to every connection's writer. Bounds a single
/// blocking `write` syscall so a wedged client — one whose socket receive
/// window is permanently zero — cannot stall its writer thread forever.
///
/// This is the mechanism that makes LAG EVICTION work without the daemon
/// holding a force-close handle on the connection (no retained socket clone,
/// no extra FD per connection): when the daemon evicts a lagging client it
/// enqueues the best-effort `Evicted` advisory and drops every sink; a
/// healthy writer flushes the advisory and closes its own socket (notify-
/// before-EOF), while a wedged writer hits this timeout on its in-flight
/// write, the write fails, and the writer shuts the socket down itself —
/// which unblocks the reader's blocking read and runs the normal
/// `cleanup_client` teardown. Either way the connection is reaped promptly
/// and its queued bytes released.
///
/// A slow-but-alive client is never falsely killed: the timeout is per
/// syscall, so a socket that makes any progress (each write completes in
/// under this) survives; only a client that stops reading entirely trips it,
/// which is exactly the lag condition eviction targets.
const WRITER_WRITE_TIMEOUT: Duration = Duration::from_secs(5);

/// A per-connection message sink implementing the single-writer contract.
///
/// Both transports (Unix socket and TCP/Noise) implement this so the writer
/// thread loop in [`writer_thread`] lives in exactly one place. The
/// `ShuttingDown` special case — flush the notification, close the socket,
/// stop draining — is what makes notify-before-EOF deterministic: the thread
/// that writes the message is the same thread that closes the socket.
trait ConnectionWriter {
    /// Serialize and send one message. Errors are fatal for the connection
    /// (the socket is broken) — the caller stops draining.
    fn send_message(&mut self, msg: &DaemonMessage) -> Result<(), String>;
    /// Close the underlying socket (both directions).
    fn shutdown(&mut self);
}

impl ConnectionWriter for BufWriter<UnixStream> {
    fn send_message(&mut self, msg: &DaemonMessage) -> Result<(), String> {
        write_message(self, msg).map_err(|e| e.to_string())?;
        self.flush().map_err(|e| e.to_string())
    }
    fn shutdown(&mut self) {
        let _ = self.get_ref().shutdown(Shutdown::Both);
    }
}

impl ConnectionWriter for choreo_transport::noise::NoiseStream {
    fn send_message(&mut self, msg: &DaemonMessage) -> Result<(), String> {
        self.send_daemon_message(msg).map_err(|e| e.to_string())
    }
    fn shutdown(&mut self) {
        let _ = self.get_ref().shutdown(Shutdown::Both);
    }
}

/// The embedded (in-process) transport's writer: forward the message as a
/// Rust VALUE over a channel instead of serializing + encrypting it.
///
/// The embedded connection never becomes bytes: `ClientMessage`s travel
/// GUI→daemon as values over one channel, `DaemonMessage`s daemon→GUI as
/// values over the writer's target channel. `send_message` therefore just
/// forwards `msg.clone()` — the clone is the price of the `&msg` signature,
/// and it is strictly cheaper than the socket path's msgpack encode +
/// AES-GCM encrypt + syscall per message.
struct ChannelConnectionWriter {
    /// Forward target = the GUI's read half. Wrapped in an Option so
    /// [`shutdown`] can DROP it: a dropped sender closes the receiver
    /// immediately — the channel analogue of `Shutdown::Both` — which is
    /// what preserves notify-before-close (the writer thread forwards the
    /// special-cased `ShuttingDown`/`Evicted` FIRST, then calls
    /// `shutdown()`, then breaks; the GUI observes the value, then `Err`
    /// on the next recv).
    tx: Option<crossbeam_channel::Sender<DaemonMessage>>,
}

impl ChannelConnectionWriter {
    fn new(tx: crossbeam_channel::Sender<DaemonMessage>) -> Self {
        Self { tx: Some(tx) }
    }
}

impl ConnectionWriter for ChannelConnectionWriter {
    fn send_message(&mut self, msg: &DaemonMessage) -> Result<(), String> {
        match &self.tx {
            Some(tx) => tx.send(msg.clone()).map_err(|_| {
                // The receiver (GUI read half) is gone — the embedded client
                // dropped its link. Same "connection is broken" class as a
                // broken pipe on the socket paths.
                "embedded client receiver dropped".to_string()
            }),
            None => Err("embedded writer already shut down".to_string()),
        }
    }
    fn shutdown(&mut self) {
        // Dropping the sender closes the GUI's receiver immediately (see the
        // field docs): the embedded analogue of closing the socket, ordered
        // AFTER the ShuttingDown/Evicted flush by the shared writer_thread.
        self.tx = None;
    }
}

/// Drain a connection's writer channel — the connection's SOLE writer.
///
/// Each connection has exactly one writer thread, so messages on `rx` are
/// serialized and fragments of one logical message can never interleave.
/// `ShuttingDown` and `Evicted` are special-cased identically: each is
/// flushed, then the socket is closed HERE (by the writer thread itself), so
/// the client observes the notification before the EOF with no other thread
/// ever writing to or closing the socket. (ShuttingDown is only ever enqueued
/// by the daemon's shutdown broadcast; Evicted by a lag eviction.) An error at
/// any point stops the loop and SHUTS THE SOCKET DOWN — a send error can be a
/// broken pipe (socket gone) or a [`WRITER_WRITE_TIMEOUT`] on a wedged client
/// whose receive window is zero (socket still open); either way, shutting
/// down unblocks the reader's blocking read so `cleanup_client` reaps the
/// connection (shutdown on an already-broken socket is a harmless no-op).
///
/// Byte accounting: on EACH dequeue the per-client and daemon-wide lag
/// counters are decremented by the message's approximate wire size, the exact
/// counterpart of [`SubscriberSink::enqueue`]'s increment. Decrementing even
/// on a failed send keeps the daemon-wide backlog honest — the bytes left the
/// queue regardless of whether the socket accepted them, and the connection
/// is being torn down either way. Whatever is still QUEUED when the loop
/// stops (send error, or the `Evicted`/`ShuttingDown` stop) is drained below
/// the loop and decremented too, so an abandoned backlog can never stay
/// frozen in the daemon-wide counter and silently eat the global budget.
fn writer_thread<W: ConnectionWriter>(
    mut writer: W,
    rx: crossbeam_channel::Receiver<DaemonMessage>,
    bytes: Arc<AtomicUsize>,
    global: Arc<AtomicUsize>,
) {
    for msg in &rx {
        let size = msg.approx_wire_size();
        if let Err(e) = writer.send_message(&msg) {
            warn!("writer thread error: {e}");
            // The failing message still left the queue — account it so the
            // backlog reflects what is actually still queued, then stop.
            bytes.fetch_sub(size, Ordering::Relaxed);
            global.fetch_sub(size, Ordering::Relaxed);
            writer.shutdown();
            break;
        }
        bytes.fetch_sub(size, Ordering::Relaxed);
        global.fetch_sub(size, Ordering::Relaxed);
        if matches!(msg, DaemonMessage::ShuttingDown | DaemonMessage::Evicted) {
            writer.shutdown();
            break;
        }
    }
    // Drain-and-decrement whatever is still queued: after a send error or a
    // ShuttingDown/Evicted stop, the socket is closed and these messages will
    // never be written — but they were all counted at enqueue. Subtracting
    // them here keeps the daemon-wide total honest (the per-client counter
    // dies with the sink, but `global` is shared across every client: an
    // evicted client's abandoned backlog would otherwise stay frozen in it
    // forever and, accumulated across evictions, permanently exhaust the
    // global budget — cascading evictions of healthy clients). The drain is
    // non-blocking on purpose: the writer must exit promptly so the receiver
    // drops and any producer that enqueues after this point gets a failed
    // send, which it self-corrects (see [`SubscriberSink::send_accounted`]).
    //
    // The one residual race, bounded and accepted: a producer whose `send`
    // lands in the microsecond window between this drain's last pass and the
    // receiver being dropped (at function return) SUCCEEDS — the receiver is
    // still alive — and that message is never dequeued, so its bytes stay in
    // the daemon-wide counter forever. The leak is bounded to whatever a
    // producer manages to enqueue in that window — in practice zero or one
    // message (the daemon removes the sink from its maps in the same command
    // that starts this teardown, so no producer keeps broadcasting to it
    // beyond a straggler or two) — and a producer that sends after the
    // receiver is gone self-corrects, so the accounting stays honest to
    // within that tiny, event-bounded slack. It is not a strict one-message
    // guarantee, but it is never an unbounded stream.
    for msg in rx.try_iter() {
        let size = msg.approx_wire_size();
        bytes.fetch_sub(size, Ordering::Relaxed);
        global.fetch_sub(size, Ordering::Relaxed);
    }
}

/// Create a connection's writer channel and register it with the daemon,
/// returning the client id and both channel ends for the connection thread.
///
/// Registration happens HERE — in the acceptor, BEFORE the connection thread
/// is spawned — so a connection accepted concurrently with shutdown is
/// guaranteed to receive `ShuttingDown`:
///
/// * Unix: the accept loop registers (then spawns) before it can observe the
///   shutdown flag and break out to broadcast, so the register command is
///   enqueued before the broadcast on the same FIFO command channel.
/// * TCP: the accept thread registers before spawning the handshake thread,
///   and `run_server` joins the accept thread BEFORE broadcasting, so the
///   register (sent strictly before the accept thread exited) is ordered
///   before the broadcast in the command channel.
///
/// If registration were deferred to inside the connection thread, a handshake
/// still in flight when shutdown began could land its register after the
/// broadcast was processed — and that client would miss the notification.
pub(crate) fn register_client_writer(
    daemon_tx: &mpsc::Sender<DaemonCommand>,
) -> (
    u64,
    crate::broadcast::SubscriberSink,
    crossbeam_channel::Receiver<DaemonMessage>,
) {
    let (writer_tx, writer_rx) = crossbeam_channel::unbounded::<DaemonMessage>();
    let sink = crate::broadcast::SubscriberSink::new(writer_tx);
    let client_id = rand::random::<u64>();
    let _ = daemon_tx.send(DaemonCommand::RegisterClientWriter {
        client_id,
        writer: sink.clone(),
    });
    (client_id, sink, writer_rx)
}

/// Send a reply to a client's writer channel.
///
/// Replies ride the same unbounded channel as broadcasts, so they MUST keep
/// the lag counters consistent: `send_accounted` increments both before the
/// send (the writer thread decrements them on every dequeue) and self-
/// corrects both if the receiver is gone. The lag limits are NOT enforced
/// here: a reply is a request/response contract that must never be dropped
/// (lossless for replies was already true — a blocking send never dropped,
/// it just blocked; with an unbounded channel it can no longer block
/// either), and replies are small and infrequent next to broadcast streams,
/// so they cannot meaningfully inflate a lagging client's backlog. A dropped
/// reply on a dead receiver is fine: the connection is being torn down
/// anyway.
fn send_to_writer(ctx: &ClientCtx, msg: DaemonMessage) {
    ctx.writer.send_accounted(&msg, ctx.global_lag);
}

/// Shared per-client context passed through the dispatch and handler functions.
/// Bundles the channels and mutable per-connection state into one struct so
/// the call sites don't pass 5–6 individual arguments to every function.
struct ClientCtx<'a> {
    /// This connection's delivery sink (see `send_to_writer`).
    writer: &'a crate::broadcast::SubscriberSink,
    /// Daemon-wide lag counter, shared by every connection; replies must
    /// increment it so the writer thread's per-dequeue decrement stays
    /// balanced (see `send_to_writer`).
    global_lag: &'a AtomicUsize,
    daemon_tx: &'a mpsc::Sender<DaemonCommand>,
    attached_session_id: &'a mut Option<u64>,
    attached_session_tx: &'a mut Option<mpsc::Sender<SessionCommand>>,
    client_id: u64,
    /// Whether this connection arrived over the local Unix socket (vs the
    /// TCP/Noise listener). Trust-boundary input for local-only commands:
    /// `AclAdd` is refused on TCP because the approver for a trust decision
    /// must be at the machine, not on the network.
    is_unix: bool,
}

/// Clean up a client connection: detach from session, unregister the summary
/// subscriber, wait for the writer thread to drain, and record the disconnect
/// metric.  Owns the writer_tx sender and writer handle so both are consumed.
fn cleanup_client(
    attached_session_tx: Option<mpsc::Sender<SessionCommand>>,
    client_id: u64,
    daemon_tx: &mpsc::Sender<DaemonCommand>,
    writer: crate::broadcast::SubscriberSink,
    writer_handle: std::thread::JoinHandle<()>,
) {
    if let Some(ref tx) = attached_session_tx {
        let _ = tx.send(SessionCommand::Detach { client_id });
    }
    let _ = daemon_tx.send(DaemonCommand::ClientDisconnected { client_id });
    drop(writer);
    // Join the writer with a bound: a wedged writer (client open but not
    // reading) is stuck in a blocking socket write and cannot exit on the
    // channel disconnect alone. Cleanup must not hang the connection thread on
    // that forever; the daemon shutdown drain is the backstop, and the
    // concurrent-connection cap bounds how many wedged writers can accumulate.
    // A writer that times out is detached — it keeps its socket until the
    // client goes away, then exits on its own.
    crate::server::lifecycle::join_thread_bounded(
        writer_handle,
        Instant::now() + WRITER_JOIN_GRACE,
    );
    crate::metrics::record_client_disconnected();
}

/// Dispatch a decoded ClientMessage through the shared handler functions.
/// Returns an error only when the daemon has disconnected (caller should
/// terminate the client connection).
fn dispatch_client_message(msg: ClientMessage, ctx: &mut ClientCtx) -> io::Result<()> {
    match msg {
        ClientMessage::CreateSession {
            title,
            parent_session_id,
            working_dir,
            context_config,
            account_name,
            selected_model,
            reasoning_effort,
        } => {
            if !handle_client_create_session(
                title,
                parent_session_id,
                working_dir,
                context_config,
                account_name,
                selected_model,
                reasoning_effort,
                ctx,
            ) {
                return Err(io::Error::new(
                    io::ErrorKind::ConnectionAborted,
                    "daemon disconnected",
                ));
            }
        }
        ClientMessage::AttachSession { session_id } => {
            if !handle_client_attach_session(session_id, ctx) {
                return Err(io::Error::new(
                    io::ErrorKind::ConnectionAborted,
                    "daemon disconnected",
                ));
            }
        }
        ClientMessage::ListSessions => {
            debug!("client {}: ListSessions", ctx.client_id);
            let (reply, rx) = mpsc::channel();
            let _ = ctx.daemon_tx.send(DaemonCommand::ListSessions { reply });
            if let Ok(sessions) = rx.recv() {
                send_to_writer(ctx, DaemonMessage::Sessions { sessions });
            }
        }
        ClientMessage::SubscribeSessionsSummary => {
            let _ = ctx
                .daemon_tx
                .send(DaemonCommand::RegisterSummarySubscriber {
                    client_id: ctx.client_id,
                    writer: ctx.writer.clone(),
                });
        }
        ClientMessage::UnsubscribeSessionsSummary => {
            let _ = ctx
                .daemon_tx
                .send(DaemonCommand::UnregisterSummarySubscriber {
                    client_id: ctx.client_id,
                });
        }
        ClientMessage::RunInput { request_id, input } => {
            debug!("client {}: RunInput id={}", ctx.client_id, request_id);
            if let Some(tx) = ctx.attached_session_tx {
                let _ = tx.send(SessionCommand::RunInput { request_id, input });
            } else {
                // This connection-level reply has no origin session, so the
                // envelope carries `session_id: None` (used in every "no
                // session attached" arm in this dispatch). The TUI resolves
                // it as a connection-level failure via
                // `App::resolve_daemon_session`.
                send_to_writer(
                    ctx,
                    DaemonMessage::Session {
                        session_id: None,
                        event: SessionEvent::Failed {
                            request_id,
                            error: "no session attached".to_string(),
                        },
                    },
                );
            }
        }
        ClientMessage::Cancel { request_id } => {
            debug!("client {}: Cancel id={}", ctx.client_id, request_id);
            // Route through the daemon so it can also cancel child
            // sub-sessions without requiring a round-trip message.
            if let Some(session_id) = *ctx.attached_session_id {
                let _ = ctx.daemon_tx.send(DaemonCommand::CancelRequest {
                    session_id,
                    request_id,
                });
            }
        }
        ClientMessage::Undo => {
            debug!("client {}: Undo", ctx.client_id);
            if let Some(tx) = ctx.attached_session_tx {
                let _ = tx.send(SessionCommand::Undo);
            }
        }
        ClientMessage::Redo => {
            debug!("client {}: Redo", ctx.client_id);
            if let Some(tx) = ctx.attached_session_tx {
                let _ = tx.send(SessionCommand::Redo);
            }
        }
        ClientMessage::ContinueGeneration { request_id } => {
            debug!(
                "client {}: ContinueGeneration id={}",
                ctx.client_id, request_id
            );
            if let Some(tx) = ctx.attached_session_tx {
                let _ = tx.send(SessionCommand::RunInput {
                    request_id,
                    input: b"Continue.".to_vec(),
                });
            } else {
                send_to_writer(
                    ctx,
                    DaemonMessage::Session {
                        session_id: None,
                        event: SessionEvent::Failed {
                            request_id,
                            error: "no session attached".to_string(),
                        },
                    },
                );
            }
        }
        ClientMessage::Ping => {
            debug!("client {}: Ping", ctx.client_id);
            send_to_writer(ctx, DaemonMessage::Pong);
        }
        ClientMessage::SetModel { model } => {
            info!(
                "client {}: SetModel model={} attached={}",
                ctx.client_id,
                model,
                ctx.attached_session_tx.is_some()
            );
            if let Some(tx) = ctx.attached_session_tx {
                let _ = tx.send(SessionCommand::SetModel { model });
            } else {
                send_to_writer(
                    ctx,
                    DaemonMessage::Session {
                        session_id: None,
                        event: SessionEvent::ModelSelectionFailed {
                            model,
                            error: "no session attached".to_string(),
                        },
                    },
                );
            }
        }
        ClientMessage::SetReasoningEffort { effort } => {
            info!(
                "client {}: SetReasoningEffort effort={} attached={}",
                ctx.client_id,
                effort,
                ctx.attached_session_tx.is_some()
            );
            if let Some(tx) = ctx.attached_session_tx {
                let _ = tx.send(SessionCommand::SetReasoningEffort { effort });
            } else {
                send_to_writer(
                    ctx,
                    DaemonMessage::Session {
                        session_id: None,
                        event: SessionEvent::ReasoningEffortSetFailed {
                            effort,
                            error: "no session attached".to_string(),
                        },
                    },
                );
            }
        }
        ClientMessage::GetReasoningEffort => {
            if let Some(tx) = ctx.attached_session_tx {
                let (reply, rx) = mpsc::channel();
                let _ = tx.send(SessionCommand::GetReasoningEffort { reply });
                if let Ok(effort) = rx.recv() {
                    // Session-scoped reply to the attached session: carry its
                    // real id (do NOT fall back to the None sentinel).
                    send_to_writer(
                        ctx,
                        DaemonMessage::Session {
                            session_id: *ctx.attached_session_id,
                            event: SessionEvent::ReasoningEffortSet { effort },
                        },
                    );
                }
            } else {
                send_to_writer(
                    ctx,
                    DaemonMessage::Session {
                        session_id: None,
                        event: SessionEvent::ReasoningEffortSet {
                            effort: "off".to_string(),
                        },
                    },
                );
            }
        }
        ClientMessage::Unlock { private_key } => {
            info!("client {}: Unlock", ctx.client_id);
            handle_unlock_sync(ctx, private_key);
        }
        ClientMessage::BindKeystore { key } => {
            info!("client {}: BindKeystore", ctx.client_id);
            handle_bind_keystore_sync(ctx, key);
        }
        ClientMessage::Lock => {
            info!("client {}: Lock", ctx.client_id);
            handle_lock_sync(ctx);
        }
        ClientMessage::AddCredential {
            service,
            encrypted_payload,
            unlock_key,
        } => {
            info!(
                "client {}: AddCredential service={}",
                ctx.client_id, service
            );
            handle_add_credential_sync(ctx, service, encrypted_payload, unlock_key);
        }
        ClientMessage::RemoveCredential { service } => {
            info!(
                "client {}: RemoveCredential service={}",
                ctx.client_id, service
            );
            handle_remove_credential_sync(ctx, service);
        }
        ClientMessage::AclAdd { pubkey } => {
            info!("client {}: AclAdd (local={})", ctx.client_id, ctx.is_unix);
            handle_acl_add_sync(ctx, pubkey);
        }
        ClientMessage::ListModels => {
            debug!("client {}: ListModels", ctx.client_id);
            handle_list_models_sync(ctx, *ctx.attached_session_id);
        }
        ClientMessage::RefreshModels { force } => {
            debug!("client {}: RefreshModels force={}", ctx.client_id, force);
            handle_refresh_models_sync(ctx, force);
        }
        ClientMessage::DeleteSession { session_id } => {
            info!("client {}: DeleteSession id={}", ctx.client_id, session_id);
            handle_delete_session_sync(ctx, session_id);
        }
        ClientMessage::GetCredential { service } => {
            handle_get_credential_sync(ctx, service);
        }
        ClientMessage::AddAccount {
            name,
            provider,
            base_url,
            streaming,
            retry_max_attempts,
            connect_timeout_secs,
            request_timeout_secs,
            total_timeout_secs,
        } => {
            let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::AddAccountCmd {
                name: name.clone(),
                provider,
                base_url,
                streaming,
                retry_max_attempts,
                connect_timeout_secs,
                request_timeout_secs,
                total_timeout_secs,
                reply,
            });
            match result {
                Ok(Ok(())) => {
                    send_to_writer(ctx, DaemonMessage::AccountAdded { name });
                }
                Ok(Err(e)) => {
                    send_to_writer(ctx, DaemonMessage::AccountAddFailed { name, error: e });
                }
                Err(_) => warn!("daemon disconnected while handling add account"),
            }
        }
        ClientMessage::RemoveAccount { name } => {
            let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::RemoveAccountCmd {
                name: name.clone(),
                reply,
            });
            match result {
                Ok(Ok(())) => {
                    send_to_writer(ctx, DaemonMessage::AccountRemoved { name });
                }
                Ok(Err(e)) => {
                    send_to_writer(ctx, DaemonMessage::AccountRemoveFailed { name, error: e });
                }
                Err(_) => warn!("daemon disconnected while handling remove account"),
            }
        }
        ClientMessage::ListAccounts => {
            let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::ListAccountsCmd {
                reply,
            });
            match result {
                Ok(Ok(accounts)) => {
                    send_to_writer(ctx, DaemonMessage::Accounts { accounts });
                }
                Ok(Err(e)) => {
                    send_to_writer(ctx, DaemonMessage::AccountListFailed { error: e });
                }
                Err(_) => warn!("daemon disconnected while handling list accounts"),
            }
        }
        ClientMessage::SetSessionAccount { name } => {
            handle_client_set_session_account(name, ctx);
        }
        ClientMessage::SubscribeAllActivity => {
            let _ = ctx
                .daemon_tx
                .send(DaemonCommand::RegisterActivitySubscriber {
                    client_id: ctx.client_id,
                    writer: ctx.writer.clone(),
                });
        }
        ClientMessage::UnsubscribeAllActivity => {
            let _ = ctx
                .daemon_tx
                .send(DaemonCommand::UnregisterActivitySubscriber {
                    client_id: ctx.client_id,
                });
        }
        _ => {
            warn!(
                "unhandled client message: {:?}",
                std::mem::discriminant(&msg)
            );
        }
    }
    Ok(())
}

/// Transport-agnostic per-connection protocol state machine.
///
/// Owns everything the read loop used to thread through per-message borrowed
/// `ClientCtx` constructions: the daemon command channel, the delivery sink,
/// the daemon-wide lag counter, the attachment state, and the writer thread's
/// join handle (so `finish()` can run the bounded writer join). The three
/// connection threads (Unix socket, TCP/Noise, and the in-process embedded
/// channel path in `crate::embedded`) differ only in HOW they read one
/// message off the wire and classify transport errors; everything between
/// message read and teardown lives here.
pub(crate) struct ClientConn {
    daemon_tx: mpsc::Sender<DaemonCommand>,
    /// This connection's delivery sink (see `send_to_writer`).
    writer: crate::broadcast::SubscriberSink,
    /// Daemon-wide lag counter, shared by every connection; kept so replies
    /// can increment it in balance with the writer thread's per-dequeue
    /// decrement (see `send_to_writer`).
    global_lag: Arc<AtomicUsize>,
    client_id: u64,
    /// Whether this connection arrived over the local Unix socket (vs the
    /// TCP/Noise listener). Trust-boundary input for local-only commands
    /// (see `ClientCtx::is_unix`).
    is_unix: bool,
    attached_session_id: Option<u64>,
    attached_session_tx: Option<mpsc::Sender<SessionCommand>>,
    /// Handle to the writer thread spawned in `new`; joined (with a bound) by
    /// `finish()` via `cleanup_client`, exactly as the pre-refactor loops did.
    writer_handle: std::thread::JoinHandle<()>,
}

impl ClientConn {
    /// Build a connection and spawn its writer thread over the given
    /// transport-specific writer buffer. Spawning here keeps the socket
    /// threads to just: set write timeout, clone the stream into a writer
    /// buffer, call this, then read/dispatch/finish.
    fn new<W: ConnectionWriter + Send + 'static>(
        daemon_tx: mpsc::Sender<DaemonCommand>,
        writer: crate::broadcast::SubscriberSink,
        writer_buf: W,
        writer_rx: crossbeam_channel::Receiver<DaemonMessage>,
        global_lag: Arc<AtomicUsize>,
        client_id: u64,
        is_unix: bool,
    ) -> Self {
        // The writer thread decrements the SAME per-client byte counter the
        // daemon's sinks increment on enqueue, plus the daemon-wide counter.
        let bytes = Arc::clone(&writer.bytes_in_flight);
        let global = Arc::clone(&global_lag);
        let writer_handle =
            std::thread::spawn(move || writer_thread(writer_buf, writer_rx, bytes, global));
        Self {
            daemon_tx,
            writer,
            global_lag,
            client_id,
            is_unix,
            attached_session_id: None,
            attached_session_tx: None,
            writer_handle,
        }
    }

    /// Dispatch one decoded client message through the shared handlers.
    /// Constructs the borrowed `ClientCtx` view the handler functions expect.
    /// Returns an error only when the daemon has disconnected (caller should
    /// terminate the connection) — identical to the pre-refactor per-message
    /// `ClientCtx` construction + `dispatch_client_message` call.
    pub(crate) fn dispatch(&mut self, msg: ClientMessage) -> io::Result<()> {
        let mut ctx = ClientCtx {
            writer: &self.writer,
            global_lag: &self.global_lag,
            daemon_tx: &self.daemon_tx,
            attached_session_id: &mut self.attached_session_id,
            attached_session_tx: &mut self.attached_session_tx,
            client_id: self.client_id,
            is_unix: self.is_unix,
        };
        dispatch_client_message(msg, &mut ctx)
    }

    /// Tear the connection down: detach from any attached session, notify the
    /// daemon, drop the sink, and join the writer thread with a bound.
    pub(crate) fn finish(self) {
        cleanup_client(
            self.attached_session_tx,
            self.client_id,
            &self.daemon_tx,
            self.writer,
            self.writer_handle,
        );
    }
}

pub(crate) fn client_thread(
    stream: UnixStream,
    daemon_tx: mpsc::Sender<DaemonCommand>,
    client_id: u64,
    writer: crate::broadcast::SubscriberSink,
    writer_rx: crossbeam_channel::Receiver<DaemonMessage>,
    global_lag: Arc<AtomicUsize>,
) -> io::Result<()> {
    // Bound the writer's blocking socket writes so a wedged client (receive
    // window permanently zero) cannot stall it forever — this is what makes
    // lag eviction reap the connection without a daemon-held close handle.
    // The timeout applies to every clone of this socket.
    stream.set_write_timeout(Some(WRITER_WRITE_TIMEOUT))?;
    let reader = BufReader::new(stream.try_clone()?);
    let writer_buf = BufWriter::new(stream);

    let mut conn = ClientConn::new(
        daemon_tx, writer, writer_buf, writer_rx, global_lag, client_id, true,
    );

    // The writer channel was registered with the daemon by the acceptor
    // (register_client_writer) before this thread was spawned, so the shutdown
    // path can route `ShuttingDown` through this single writer thread instead
    // of writing to the socket from another thread.
    info!("client connected: id={}", client_id);
    crate::metrics::record_client_connected();

    let mut reader = reader;
    loop {
        match read_message::<_, ClientMessage>(&mut reader) {
            Ok(msg) => {
                if let Err(e) = conn.dispatch(msg) {
                    debug!("daemon disconnected: {e}");
                    break;
                }
            }
            Err(ProtoError::Io(e))
                if matches!(
                    e.kind(),
                    io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset
                ) =>
            {
                debug!("client disconnected");
                break;
            }
            Err(e) => {
                error!(error = %e, "failed to read client message");
                break;
            }
        }
    }

    conn.finish();
    Ok(())
}

/// TCP accept path: read the 1-byte handshake-mode preamble, run the
/// matching Noise responder handshake (IK or XX), and hand the encrypted
/// stream to [`tcp_client_thread`].
///
/// The writer channel is registered with the daemon by the acceptor BEFORE
/// this function runs (see `register_client_writer`), so every failure path
/// here — unknown preamble, silent/garbage peer, rejected handshake — must
/// unregister via `ClientDisconnected`, exactly as the old inline handshake
/// failure path in `server/lifecycle.rs` did. This keeps the daemon's
/// `client_writers` registry honest: a connection that never produced a
/// working transport must not leave a stale writer entry behind.
///
/// **The preamble is UNAUTHENTICATED by design.** It is a cleartext mode
/// selector read before any keying material exists, so it cannot carry
/// authentication itself. That is safe because it authorizes NOTHING: it
/// only selects which handshake runs. Everything that matters is
/// authenticated by the subsequent Noise handshake — IK and XX both
/// authenticate both parties' static keys via the DH operations, so a
/// man-in-the-middle cannot downgrade the mode or impersonate either side
/// (a MITM would have to complete the chosen handshake, which requires the
/// server's private key), and the daemon's ACL check runs inside whichever
/// handshake the client picked. The worst an attacker controls is which
/// of two equally-authenticated handshakes runs.
#[allow(clippy::too_many_arguments)]
pub(crate) fn tcp_handshake_and_client_thread(
    mut tcp: TcpStream,
    transport_sk: [u8; 32],
    acl: Arc<crate::server::acl::SharedAcl>,
    daemon_tx: mpsc::Sender<DaemonCommand>,
    client_id: u64,
    writer: crate::broadcast::SubscriberSink,
    writer_rx: crossbeam_channel::Receiver<DaemonMessage>,
    global_lag: Arc<AtomicUsize>,
) -> io::Result<()> {
    // The preamble read runs BEFORE any authentication, so it is bounded by
    // the transport's absolute-deadline machinery (same as the handshake
    // itself): a peer that connects and sends nothing is cut off instead of
    // holding this thread + FD open forever.
    let preamble = match choreo_transport::handshake::read_handshake_preamble(&mut tcp) {
        Ok(p) => p,
        Err(e) => {
            warn!(
                error = %e,
                "TCP client never sent a valid handshake-mode preamble; closing"
            );
            // Drop `tcp` (closes the socket) and unregister the writer
            // channel this connection registered at accept time.
            let _ = daemon_tx.send(DaemonCommand::ClientDisconnected { client_id });
            return Ok(());
        }
    };

    // Dispatch on the mode byte. Each arm runs the full responder handshake
    // with the SAME ACL closure, so XX connections are authorized exactly
    // like IK ones (the check lives inside the handshake in both cases).
    let handshake_result = match preamble {
        choreo_transport::handshake::PREAMBLE_IK => {
            debug!("TCP client selected Noise IK handshake");
            choreo_transport::handshake::handshake_responder(tcp, &transport_sk, |pk| {
                acl.contains(pk)
            })
        }
        choreo_transport::handshake::PREAMBLE_XX => {
            debug!("TCP client selected Noise XX (first-contact) handshake");
            choreo_transport::handshake::handshake_responder_xx(tcp, &transport_sk, |pk| {
                acl.contains(pk)
            })
        }
        other => {
            warn!(
                preamble = other,
                "unknown handshake-mode preamble byte; closing connection"
            );
            let _ = daemon_tx.send(DaemonCommand::ClientDisconnected { client_id });
            return Ok(()); // dropping `tcp` closes the connection
        }
    };

    let noise = match handshake_result {
        Ok(noise) => noise,
        Err(e) => {
            error!(error = %e, "Noise handshake rejected");
            let _ = daemon_tx.send(DaemonCommand::ClientDisconnected { client_id });
            return Ok(());
        }
    };

    tcp_client_thread(noise, daemon_tx, client_id, writer, writer_rx, global_lag)
}

pub(crate) fn tcp_client_thread(
    noise: choreo_transport::noise::NoiseStream,
    daemon_tx: mpsc::Sender<DaemonCommand>,
    client_id: u64,
    writer: crate::broadcast::SubscriberSink,
    writer_rx: crossbeam_channel::Receiver<DaemonMessage>,
    global_lag: Arc<AtomicUsize>,
) -> io::Result<()> {
    // Writer thread: blocks on writer_rx, sends via NoiseStream encryption.
    // Bound the underlying socket's blocking writes (see WRITER_WRITE_TIMEOUT)
    // so a wedged client cannot stall the writer forever; the timeout applies
    // to every clone of the TcpStream.
    noise
        .get_ref()
        .set_write_timeout(Some(WRITER_WRITE_TIMEOUT))?;
    let writer_buf = noise.try_clone()?;

    let mut conn = ClientConn::new(
        daemon_tx, writer, writer_buf, writer_rx, global_lag, client_id, false,
    );

    // The writer channel was registered with the daemon by the acceptor
    // (register_client_writer) before this thread was spawned, so the shutdown
    // path can route `ShuttingDown` through this single writer thread (see
    // client_thread). The NoiseStream's TransportState lock is only safe to
    // take per-message because this is the sole sender.
    info!("TCP client connected: id={}", client_id);
    crate::metrics::record_client_connected();

    // Summary subscription is an explicit client decision on this transport,
    // exactly as on the Unix path: a Noise client opts in via
    // ClientMessage::SubscribeSessionsSummary (dispatched in
    // dispatch_client_message). Previously every TCP connection was
    // auto-registered here, which pushed broadcasts about other clients'
    // sessions to clients that never asked.
    let mut reader = noise;
    loop {
        match reader.recv_client_message() {
            Ok(msg) => {
                if let Err(e) = conn.dispatch(msg) {
                    debug!("daemon disconnected: {e}");
                    break;
                }
            }
            Err(choreo_transport::error::TransportError::ConnectionClosed) => {
                info!("TCP client closed connection");
                break;
            }
            Err(e) => {
                error!(error = %e, "failed to read client message");
                break;
            }
        }
    }

    conn.finish();
    Ok(())
}

/// Per-connection inputs for the embedded (in-process) transport, bundled
/// into one struct so the spawn call site stays a single argument (and no
/// `too_many_arguments` lint ever applies). Mirrors the parameter lists the
/// Unix/TCP connection threads take, minus the socket.
pub(crate) struct EmbeddedConnArgs {
    /// GUI→daemon message values. Channel close IS the EOF.
    pub client_rx: crossbeam_channel::Receiver<ClientMessage>,
    /// The writer's forward target = the GUI's read half.
    pub out_tx: crossbeam_channel::Sender<DaemonMessage>,
    pub daemon_tx: mpsc::Sender<DaemonCommand>,
    pub client_id: u64,
    pub writer: crate::broadcast::SubscriberSink,
    pub writer_rx: crossbeam_channel::Receiver<DaemonMessage>,
    pub global_lag: Arc<AtomicUsize>,
}

/// The embedded (in-process) connection thread — the third transport, next
/// to [`client_thread`] (Unix) and [`tcp_client_thread`] (TCP/Noise).
///
/// The connection never becomes bytes: client messages arrive as Rust values
/// on `client_rx` and daemon messages leave as values on `out_tx` (via the
/// [`ChannelConnectionWriter`] the shared writer thread drains). There is no
/// error classification and no timeout machinery: the `for` loop over
/// `client_rx` ends exactly when the GUI drops its `EmbeddedLink` (channel
/// close IS the EOF), and `conn.finish()` runs the same teardown the socket
/// paths use.
///
/// `is_unix: true` — an embedded connection is the LOCAL trust domain, like
/// the Unix socket: both peers are the same process, so `/acl add` (and the
/// local-only command semantics generally) apply.
pub(crate) fn embedded_client_thread(args: EmbeddedConnArgs) -> io::Result<()> {
    let EmbeddedConnArgs {
        client_rx,
        out_tx,
        daemon_tx,
        client_id,
        writer,
        writer_rx,
        global_lag,
    } = args;

    let mut conn = ClientConn::new(
        daemon_tx,
        writer,
        ChannelConnectionWriter::new(out_tx),
        writer_rx,
        global_lag,
        client_id,
        true,
    );

    // The writer channel was registered with the daemon by `connect()`
    // (register_client_writer) BEFORE this thread was spawned, so the
    // shutdown path can route `ShuttingDown` through this single writer
    // thread — same ordering invariant as the socket paths.
    info!("embedded client connected: id={}", client_id);
    crate::metrics::record_client_connected();

    for msg in client_rx {
        if let Err(e) = conn.dispatch(msg) {
            debug!("daemon disconnected: {e}");
            break;
        }
    }
    info!("embedded client disconnected: id={}", client_id);

    conn.finish();
    Ok(())
}

/// Switch the client's attachment from the old session to a new one.
/// Skips detaching when re-attaching to the same session to avoid
/// killing the session's only subscriber.
fn switch_attached_session(
    new_session_id: u64,
    session_tx: mpsc::Sender<SessionCommand>,
    ctx: &mut ClientCtx,
) {
    // Don't detach when re-attaching to the same session.
    if Some(new_session_id) != *ctx.attached_session_id
        && let Some(old_tx) = ctx.attached_session_tx.as_ref()
    {
        let _ = old_tx.send(SessionCommand::Detach {
            client_id: ctx.client_id,
        });
    }
    let _ = session_tx.send(SessionCommand::Attach {
        client_id: ctx.client_id,
        tx: ctx.writer.clone(),
    });
    *ctx.attached_session_tx = Some(session_tx);
    *ctx.attached_session_id = Some(new_session_id);
}

#[expect(clippy::too_many_arguments)]
/// Handle a CreateSession client message. Returns false if the daemon
/// disconnected, signaling client_thread to return.
fn handle_client_create_session(
    title: Option<String>,
    parent_session_id: Option<u64>,
    working_dir: Option<String>,
    context_config: Option<ContextConfig>,
    account_name: Option<String>,
    selected_model: Option<String>,
    reasoning_effort: Option<String>,
    ctx: &mut ClientCtx,
) -> bool {
    info!("client {}: CreateSession", ctx.client_id);
    let cwd_str = working_dir.clone();
    let (reply, rx) = mpsc::channel();
    let _ = ctx.daemon_tx.send(DaemonCommand::CreateSession {
        title: title.clone(),
        parent_session_id,
        working_dir: working_dir.map(std::path::PathBuf::from),
        reasoning_effort: reasoning_effort.clone(),
        selected_model: selected_model.clone(),
        context_config,
        account_name: account_name.clone(),
        active_tool_groups: Vec::new(),
        reply,
    });
    match rx.recv() {
        Ok(Ok((sid, _session_tx))) => {
            // _session_tx is discarded here because the
            // daemon keeps its own clone in active_sessions
            // (keyed by sid).  When the client later calls
            // AttachSession the daemon returns another clone
            // — no need to hold one in the connection thread.
            //
            // Don't auto-attach or detach here — the TUI
            // attaches explicitly via AttachSession when
            // the user presses Enter on a session.
            // This keeps the old session alive when
            // creating from the session manager page.
            send_to_writer(
                ctx,
                DaemonMessage::Session {
                    session_id: Some(sid),
                    event: SessionEvent::SessionCreated {
                        title,
                        parent_session_id,
                        working_dir: cwd_str,
                        account_name,
                        selected_model,
                        reasoning_effort,
                    },
                },
            );
        }
        Ok(Err(e)) => {
            send_to_writer(
                ctx,
                DaemonMessage::Session {
                    session_id: None,
                    event: SessionEvent::SessionFailed {
                        operation: "create_session".into(),
                        error: e.to_string(),
                    },
                },
            );
        }
        Err(_) => return false,
    }
    true
}

/// Handle an AttachSession client message. Returns false if the daemon
/// disconnected, signaling client_thread to return.
fn handle_client_attach_session(session_id: u64, ctx: &mut ClientCtx) -> bool {
    info!("client {}: AttachSession id={}", ctx.client_id, session_id);
    let (reply, rx) = mpsc::channel();
    let _ = ctx
        .daemon_tx
        .send(DaemonCommand::AttachSession { session_id, reply });
    match rx.recv() {
        Ok(Ok(session_tx)) => {
            // Send SessionAttached before SessionCommand::Attach so that
            // the TUI's attached_session_id is set before SessionState
            // arrives — otherwise SessionState is silently dropped.
            send_to_writer(
                ctx,
                DaemonMessage::Session {
                    session_id: Some(session_id),
                    event: SessionEvent::SessionAttached,
                },
            );
            switch_attached_session(session_id, session_tx, ctx);
        }
        Ok(Err(e)) => {
            send_to_writer(
                ctx,
                DaemonMessage::Session {
                    session_id: None,
                    event: SessionEvent::SessionFailed {
                        operation: "attach_session".into(),
                        error: e.to_string(),
                    },
                },
            );
        }
        Err(_) => return false,
    }
    true
}

/// Handle a SetSessionAccount client message: verify the account exists
/// via the daemon, then set it on the attached session.
fn handle_client_set_session_account(name: String, ctx: &mut ClientCtx) {
    if let Some(tx) = ctx.attached_session_tx.as_ref() {
        // Verify the account exists before setting it.
        let (reply, rx) = mpsc::channel();
        let _ = ctx.daemon_tx.send(DaemonCommand::AccountExists {
            name: name.clone(),
            reply,
        });
        match rx.recv() {
            Ok(true) => {
                let _ = tx.send(SessionCommand::SetAccount { name });
            }
            _ => {
                // Session-scoped reply to the attached session: carry its
                // real id (do NOT fall back to the None sentinel).
                send_to_writer(
                    ctx,
                    DaemonMessage::Session {
                        session_id: *ctx.attached_session_id,
                        event: SessionEvent::SessionFailed {
                            operation: "set_account".into(),
                            error: format!("account '{name}' not found"),
                        },
                    },
                );
            }
        }
    } else {
        send_to_writer(
            ctx,
            DaemonMessage::Session {
                session_id: None,
                event: SessionEvent::SessionFailed {
                    operation: "set_account".into(),
                    error: "no session attached".to_string(),
                },
            },
        );
    }
}

/// Send a DaemonCommand that expects a reply and wait for the response.
/// Returns the reply value, or None if the daemon dropped the sender.
fn request_daemon<R>(
    daemon_tx: &mpsc::Sender<DaemonCommand>,
    make_cmd: impl FnOnce(mpsc::Sender<R>) -> DaemonCommand,
) -> Result<R, mpsc::RecvError> {
    let (reply, rx) = mpsc::channel();
    if daemon_tx.send(make_cmd(reply)).is_err() {
        return Err(mpsc::RecvError);
    }
    rx.recv()
}

fn handle_unlock_sync(ctx: &mut ClientCtx, private_key: Vec<u8>) {
    // The daemon command loop enqueues the targeted reply (Unlocked /
    // KeystoreUnbound / LockedError) DIRECTLY into this client's writer sink
    // BEFORE its lock-state broadcast — see ORDERING INVARIANT in
    // `DaemonState::handle_unlock`. This thread only waits for the ack so a
    // dropped daemon channel is reported.
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::Unlock {
        private_key,
        client_writer: Some(ctx.writer.clone()),
        reply,
    });
    if result.is_err() {
        warn!("daemon disconnected while handling unlock");
    }
}

/// Handle `ClientMessage::BindKeystore`: the ONLY path that can create the
/// keystore binding. On an unbound keystore the daemon adopts the key (loud
/// TOFU log), runs the shared unlock tail, and the client gets the targeted
/// `DaemonMessage::Bound` reply (sent by the daemon loop into this client's
/// sink BEFORE the lock-state broadcast — see ORDERING INVARIANT in
/// `handle_unlock`); on an already-bound keystore a wrong key is rejected
/// with the existing wrong-key semantics (LockedError) — no unlock, no
/// overwrite.
fn handle_bind_keystore_sync(ctx: &mut ClientCtx, key: Vec<u8>) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::BindKeystore {
        key,
        client_writer: Some(ctx.writer.clone()),
        reply,
    });
    if result.is_err() {
        warn!("daemon disconnected while handling bind keystore");
    }
}

/// Reply to a `ClientMessage::Lock` (`/lock`): the daemon clears its
/// in-memory credentials, flips to the locked state, and broadcasts `Locked`
/// to every activity subscriber. This per-action reply confirms the wipe to
/// the acting client directly; the transition broadcast reaches it too (it
/// is an activity subscriber), harmlessly idempotent — the TUI latches
/// `keystore_locked` either way.
fn handle_lock_sync(ctx: &mut ClientCtx) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::Lock { reply });
    match result {
        Ok(Ok(())) => {
            send_to_writer(ctx, DaemonMessage::Locked);
        }
        Ok(Err(e)) => {
            send_to_writer(ctx, DaemonMessage::LockedError { error: e });
        }
        Err(_) => warn!("daemon disconnected while handling lock"),
    }
}

fn handle_list_models_sync(ctx: &mut ClientCtx, attached_session_id: Option<u64>) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::ListModels {
        session_id: attached_session_id,
        reply,
    });
    match result {
        Ok(Ok((models, selected_model))) => {
            send_to_writer(
                ctx,
                DaemonMessage::Models {
                    models,
                    selected_model,
                },
            );
        }
        Ok(Err(e)) => {
            send_to_writer(ctx, DaemonMessage::ModelsFailed { error: e });
        }
        Err(_) => warn!("daemon disconnected while handling list models"),
    }
}

/// Handle a RefreshModels client message: forward the request to the daemon
/// (which hands it to the maintenance thread — the fetch never blocks this
/// connection), then route the reply back to the client. The request blocks
/// here until the maintenance thread has a result, which is the request/
/// response contract `/refresh-models` implies.
fn handle_refresh_models_sync(ctx: &mut ClientCtx, force: bool) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::RefreshModels {
        force,
        reply,
    });
    match result {
        Ok(Ok(report)) => {
            send_to_writer(
                ctx,
                DaemonMessage::ModelsRefreshed {
                    providers: report.providers,
                    models: report.models,
                    status: report.status,
                },
            );
        }
        Ok(Err(e)) => {
            send_to_writer(ctx, DaemonMessage::ModelsRefreshFailed { error: e });
        }
        Err(_) => warn!("daemon disconnected while handling refresh models"),
    }
}

fn handle_get_credential_sync(ctx: &mut ClientCtx, service: String) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::GetCredential {
        service: service.clone(),
        reply,
    });
    match result {
        Ok(Some(key)) => {
            send_to_writer(
                ctx,
                DaemonMessage::Credential {
                    service,
                    key: Some(key),
                },
            );
        }
        Ok(None) => {
            send_to_writer(ctx, DaemonMessage::Credential { service, key: None });
        }
        Err(_) => warn!("daemon disconnected while handling get credential"),
    }
}

fn handle_delete_session_sync(ctx: &mut ClientCtx, session_id: u64) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::DeleteSession {
        session_id,
        reply,
    });
    match result {
        Ok(Ok(())) => {
            // The daemon broadcasts SessionDeleted to all summary
            // subscribers (including this client when it's viewing
            // the session list), so we don't duplicate it here.
        }
        Ok(Err(e)) => {
            send_to_writer(
                ctx,
                DaemonMessage::Session {
                    session_id: Some(session_id),
                    event: SessionEvent::SessionDeleteFailed {
                        error: e.to_string(),
                    },
                },
            );
        }
        Err(_) => warn!("daemon disconnected while handling delete session"),
    }
}

fn handle_add_credential_sync(
    ctx: &mut ClientCtx,
    service: String,
    encrypted_payload: Vec<u8>,
    // REQUIRED since the per-daemon keystore TOFU design (Task 1 made the
    // proto field non-optional): the credential must be usable immediately.
    unlock_key: Vec<u8>,
) {
    // The daemon command loop enqueues the targeted replies (Unlocked +
    // CredentialAdded, or the failure variant) DIRECTLY into this client's
    // writer sink BEFORE its lock-state broadcast — see ORDERING INVARIANT in
    // `DaemonState::handle_unlock`. This thread only waits for the ack.
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::SaveCredential {
        service: service.clone(),
        encrypted_blob: encrypted_payload,
        unlock_key,
        client_writer: Some(ctx.writer.clone()),
        reply,
    });
    if result.is_err() {
        warn!("daemon disconnected while handling add credential");
    }
}

/// Enroll a client key in the daemon's ACL. LOCAL (Unix socket) connections
/// only: the check happens HERE, on the connection thread, so a remote
/// client gets its refusal without the command loop ever seeing the command.
/// The trust approver must be at the machine (console or ssh) — an
/// already-remote client must not be able to mint new trust.
fn handle_acl_add_sync(ctx: &mut ClientCtx, pubkey: String) {
    if !ctx.is_unix {
        warn!(
            "client {}: AclAdd refused: remote connections cannot change the ACL",
            ctx.client_id
        );
        send_to_writer(
            ctx,
            DaemonMessage::AclAddResult {
                ok: false,
                message: "ACL changes are only permitted from local connections".to_string(),
            },
        );
        return;
    }
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::AclAddCmd {
        pubkey: pubkey.clone(),
        reply,
    });
    match result {
        Ok(Ok(count)) => {
            send_to_writer(
                ctx,
                DaemonMessage::AclAddResult {
                    ok: true,
                    message: format!("client key authorized ({count} client(s) now trusted)"),
                },
            );
        }
        Ok(Err(e)) => {
            send_to_writer(
                ctx,
                DaemonMessage::AclAddResult {
                    ok: false,
                    message: e,
                },
            );
        }
        Err(_) => warn!("daemon disconnected while handling acl add"),
    }
}

fn handle_remove_credential_sync(ctx: &mut ClientCtx, service: String) {
    let result = request_daemon(ctx.daemon_tx, |reply| DaemonCommand::RemoveCredentialCmd {
        service: service.clone(),
        reply,
    });
    match result {
        Ok(Ok(())) => {
            send_to_writer(ctx, DaemonMessage::CredentialRemoved { service });
        }
        Ok(Err(e)) => {
            send_to_writer(
                ctx,
                DaemonMessage::CredentialRemoveFailed { service, error: e },
            );
        }
        Err(_) => warn!("daemon disconnected while handling remove credential"),
    }
}

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

    /// A `ConnectionWriter` test double that forwards every written message
    /// to a channel and records shutdown calls on another. Message-passing
    /// only (no shared state across threads): the test reads the record
    /// after joining the writer thread.
    struct MockConnectionWriter {
        sent: mpsc::Sender<DaemonMessage>,
        shutdown_tx: mpsc::Sender<()>,
        /// Fail `send_message` on the Nth call (1-based) to exercise the
        /// error path of `writer_thread`.
        fail_on: Option<usize>,
        calls: usize,
    }

    impl ConnectionWriter for MockConnectionWriter {
        fn send_message(&mut self, msg: &DaemonMessage) -> Result<(), String> {
            self.calls += 1;
            if self.fail_on == Some(self.calls) {
                return Err("mock write failure".to_string());
            }
            let _ = self.sent.send(msg.clone());
            Ok(())
        }
        fn shutdown(&mut self) {
            let _ = self.shutdown_tx.send(());
        }
    }

    fn mock_writer(
        fail_on: Option<usize>,
    ) -> (
        MockConnectionWriter,
        mpsc::Receiver<DaemonMessage>,
        mpsc::Receiver<()>,
    ) {
        let (sent_tx, sent_rx) = mpsc::channel();
        let (shutdown_tx, shutdown_rx) = mpsc::channel();
        (
            MockConnectionWriter {
                sent: sent_tx,
                shutdown_tx,
                fail_on,
                calls: 0,
            },
            sent_rx,
            shutdown_rx,
        )
    }

    /// The core `writer_thread` contract: `ShuttingDown` is flushed, the
    /// socket is shut down HERE (by the writer thread itself), and draining
    /// stops — a message enqueued after the notification is never written,
    /// so the client observes the notification before the EOF.
    #[test]
    fn writer_thread_flushes_shutting_down_then_shuts_down_and_stops() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let (writer, sent_rx, shutdown_rx) = mock_writer(None);
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(writer, rx, bytes, global)
        });

        tx.send(DaemonMessage::Pong).unwrap();
        tx.send(DaemonMessage::ShuttingDown).unwrap();
        // Queued after the notification: must never be written.
        tx.send(DaemonMessage::Pong).unwrap();

        handle.join().expect("writer thread panicked");
        let written: Vec<_> = sent_rx.try_iter().collect();
        assert_eq!(
            written,
            vec![DaemonMessage::Pong, DaemonMessage::ShuttingDown],
            "ShuttingDown must be flushed in order, then draining must stop"
        );
        assert!(
            shutdown_rx.try_recv().is_ok(),
            "the writer thread must close the socket itself after ShuttingDown"
        );
    }

    /// `Evicted` is handled exactly like `ShuttingDown`: flushed, socket shut
    /// down, draining stops — the lag-eviction advisory is also a
    /// notify-before-EOF on the graceful path (the daemon additionally
    /// force-closes the socket, but the ordering guarantee is preserved here).
    #[test]
    fn writer_thread_flushes_evicted_then_shuts_down_and_stops() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let (writer, sent_rx, shutdown_rx) = mock_writer(None);
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(writer, rx, bytes, global)
        });

        tx.send(DaemonMessage::Pong).unwrap();
        tx.send(DaemonMessage::Evicted).unwrap();
        // Queued after the advisory: must never be written.
        tx.send(DaemonMessage::Pong).unwrap();

        handle.join().expect("writer thread panicked");
        let written: Vec<_> = sent_rx.try_iter().collect();
        assert_eq!(
            written,
            vec![DaemonMessage::Pong, DaemonMessage::Evicted],
            "Evicted must be flushed in order, then draining must stop"
        );
        assert!(
            shutdown_rx.try_recv().is_ok(),
            "the writer thread must close the socket itself after Evicted"
        );
    }

    /// A send error is fatal for the connection: the loop stops AND shuts the
    /// socket down. A send error is either a broken pipe (socket gone —
    /// shutdown is a harmless no-op) or a [`WRITER_WRITE_TIMEOUT`] on a wedged
    /// client whose receive window is zero (socket still open — shutdown is
    /// what unblocks the reader's blocking read so the connection is reaped).
    #[test]
    fn writer_thread_stops_and_shuts_down_on_send_error() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        // Fail on the second write: the first Pong goes out, the loop breaks.
        let (writer, sent_rx, shutdown_rx) = mock_writer(Some(2));
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(writer, rx, bytes, global)
        });

        tx.send(DaemonMessage::Pong).unwrap();
        tx.send(DaemonMessage::Pong).unwrap();
        tx.send(DaemonMessage::ShuttingDown).unwrap();
        drop(tx); // disconnect so the thread cannot linger

        handle.join().expect("writer thread panicked");
        let written: Vec<_> = sent_rx.try_iter().collect();
        assert_eq!(written.len(), 1, "writer must stop at the failing message");
        assert!(
            shutdown_rx.try_recv().is_ok(),
            "writer must shut the socket down on a send error so the reader is unblocked"
        );
    }

    /// A disconnected channel ends the loop cleanly without shutdown — the
    /// normal drain-to-exit path for a disconnected client.
    #[test]
    fn writer_thread_exits_cleanly_on_disconnect() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let (writer, sent_rx, shutdown_rx) = mock_writer(None);
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(writer, rx, bytes, global)
        });

        tx.send(DaemonMessage::Pong).unwrap();
        drop(tx); // all senders gone: the for-loop drains and ends

        handle.join().expect("writer thread panicked");
        let written: Vec<_> = sent_rx.try_iter().collect();
        assert_eq!(written, vec![DaemonMessage::Pong]);
        assert!(shutdown_rx.try_recv().is_err());
    }

    /// The writer thread decrements the per-client and daemon-wide byte
    /// counters once per dequeued message, using each message's approximate
    /// wire size — the exact counterpart of `enqueue`'s increment. A
    /// two-message drain must zero both counters.
    #[test]
    fn writer_thread_decrements_byte_counters_per_message() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let (writer, _sent_rx, _shutdown_rx) = mock_writer(None);
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(writer, rx, bytes, global)
        });

        let m1 = DaemonMessage::Session {
            session_id: Some(1),
            event: SessionEvent::Failed {
                request_id: 1,
                error: "a".repeat(100),
            },
        };
        let m2 = DaemonMessage::Session {
            session_id: Some(2),
            event: SessionEvent::Failed {
                request_id: 2,
                error: "b".repeat(50),
            },
        };
        let s1 = m1.approx_wire_size();
        let s2 = m2.approx_wire_size();

        // Pre-seed the counters exactly as `enqueue` would have (the two
        // messages are queued and counted before the writer starts).
        bytes.fetch_add(s1 + s2, Ordering::Relaxed);
        global.fetch_add(s1 + s2, Ordering::Relaxed);

        tx.send(m1).unwrap();
        tx.send(m2).unwrap();
        drop(tx);
        handle.join().expect("writer thread panicked");

        assert_eq!(
            bytes.load(Ordering::Relaxed),
            0,
            "every dequeued message must decrement the per-client counter"
        );
        assert_eq!(
            global.load(Ordering::Relaxed),
            0,
            "every dequeued message must decrement the daemon-wide counter"
        );
    }

    /// The abandoned-backlog drain: when the writer stops at `Evicted` (or a
    /// send error), messages queued AFTER the stop point are never written —
    /// but they were counted at enqueue. The post-loop drain must decrement
    /// both counters for them, or an evicted client's backlog would stay
    /// frozen in the daemon-wide total forever (the leak that could
    /// permanently exhaust the global budget). The abandoned messages must
    /// NOT appear on the wire.
    #[test]
    fn writer_thread_drains_and_decrements_abandoned_backlog() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let (writer, sent_rx, _shutdown_rx) = mock_writer(None);
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(writer, rx, bytes, global)
        });

        let m1 = DaemonMessage::Session {
            session_id: Some(1),
            event: SessionEvent::Failed {
                request_id: 1,
                error: "a".repeat(100),
            },
        };
        let m2 = DaemonMessage::Session {
            session_id: Some(2),
            event: SessionEvent::Failed {
                request_id: 2,
                error: "b".repeat(50),
            },
        };
        let m3 = DaemonMessage::Session {
            session_id: Some(3),
            event: SessionEvent::Failed {
                request_id: 3,
                error: "c".repeat(25),
            },
        };
        let s1 = m1.approx_wire_size();
        let s2 = m2.approx_wire_size();
        let s3 = m3.approx_wire_size();

        // Pre-seed the counters exactly as `enqueue` would have for ALL four
        // messages (m1 + Evicted are written; m2/m3 are abandoned behind the
        // stop point).
        let evicted_size = DaemonMessage::Evicted.approx_wire_size();
        let total = s1 + s2 + s3 + evicted_size;
        bytes.fetch_add(total, Ordering::Relaxed);
        global.fetch_add(total, Ordering::Relaxed);

        tx.send(m1.clone()).unwrap();
        tx.send(DaemonMessage::Evicted).unwrap();
        // Queued behind the advisory: never written, but must be decremented
        // by the exit drain.
        tx.send(m2).unwrap();
        tx.send(m3).unwrap();

        handle.join().expect("writer thread panicked");
        let written: Vec<_> = sent_rx.try_iter().collect();
        assert_eq!(
            written,
            vec![m1.clone(), DaemonMessage::Evicted],
            "messages behind the advisory must never be written"
        );
        assert_eq!(
            bytes.load(Ordering::Relaxed),
            0,
            "abandoned backlog must be decremented from the per-client counter"
        );
        assert_eq!(
            global.load(Ordering::Relaxed),
            0,
            "abandoned backlog must be decremented from the daemon-wide counter"
        );
    }

    #[test]
    fn handle_acl_add_sync_refuses_remote_clients_without_dialing_daemon() {
        // A TCP client's AclAdd must be refused at the connection layer: the
        // daemon command loop is never even contacted (asserted by the
        // channel receiver staying empty), and the client gets a structured
        // refusal — the approver for a trust decision must be at the machine.
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 7,
            is_unix: false, // a TCP/Noise client
        };

        handle_acl_add_sync(
            &mut ctx,
            "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=".to_string(),
        );

        let msg = writer_rx.recv().unwrap();
        match msg {
            DaemonMessage::AclAddResult { ok: false, message } => {
                assert!(
                    message.contains("local connections"),
                    "the refusal must explain the trust boundary, got: {message}"
                );
            }
            other => panic!("expected AclAddResult refusal, got {other:?}"),
        }
        // The command loop saw NOTHING (a refusal must not even route).
        assert!(
            daemon_rx.try_recv().is_err(),
            "a remote AclAdd must never reach the daemon command loop"
        );
    }

    #[test]
    fn handle_unlock_sync_ok() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        // The daemon command loop now enqueues the targeted reply itself:
        // the stub simulates that by sending Unlocked into the client_writer
        // sink BEFORE the ack (the ORDERING INVARIANT shape).
        let lag = Arc::clone(&global_lag);
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::Unlock {
                client_writer,
                reply,
                ..
            }) = daemon_rx.recv()
            {
                if let Some(w) = &client_writer {
                    w.send_accounted(&DaemonMessage::Unlocked, &lag);
                }
                let _ = reply.send(());
            }
        });
        handle_unlock_sync(&mut ctx, vec![0u8; 32]);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::Unlocked));
    }

    #[test]
    fn handle_unlock_sync_err() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        // The daemon command loop enqueues the targeted LockedError itself;
        // the stub simulates that (see the ordering-invariant note above).
        let lag = Arc::clone(&global_lag);
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::Unlock {
                client_writer,
                reply,
                ..
            }) = daemon_rx.recv()
            {
                if let Some(w) = &client_writer {
                    w.send_accounted(
                        &DaemonMessage::LockedError {
                            error: "wrong password".to_string(),
                        },
                        &lag,
                    );
                }
                let _ = reply.send(());
            }
        });
        handle_unlock_sync(&mut ctx, vec![0u8; 32]);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::LockedError { .. }));
        if let DaemonMessage::LockedError { error } = &msg {
            assert_eq!(error, "wrong password");
        }
    }

    #[test]
    fn handle_unlock_sync_disconnected() {
        let (daemon_tx, daemon_rx) = mpsc::channel::<DaemonCommand>();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        drop(daemon_rx);
        handle_unlock_sync(&mut ctx, vec![0u8; 32]);
        assert!(writer_rx.try_recv().is_err());
    }

    #[test]
    fn handle_lock_sync_ok_replies_locked() {
        // `/lock` (ClientMessage::Lock) routes a Lock command and, on success,
        // replies `Locked` to the acting client; the daemon separately
        // broadcasts `Locked` to every activity subscriber (the acting client
        // included, harmlessly idempotent).
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::Lock { reply }) = daemon_rx.recv() {
                let _ = reply.send(Ok(()));
            }
        });
        handle_lock_sync(&mut ctx);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::Locked));
    }

    #[test]
    fn handle_lock_sync_err_replies_locked_error() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::Lock { reply }) = daemon_rx.recv() {
                // Lock's reply channel still carries a plain String error:
                // /lock is not a binding-verification operation.
                let _ = reply.send(Err("cannot lock".into()));
            }
        });
        handle_lock_sync(&mut ctx);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::LockedError { .. }));
    }

    #[test]
    fn handle_list_models_sync_ok() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::ListModels { reply, .. }) = daemon_rx.recv() {
                let _ = reply.send(Ok((
                    vec!["gpt-4".into(), "gpt-3.5".into()],
                    Some("gpt-4".into()),
                )));
            }
        });
        handle_list_models_sync(&mut ctx, None);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::Models { .. }));
    }

    #[test]
    fn handle_refresh_models_sync_ok() {
        // The connection thread asks the daemon for a refresh; the daemon
        // (via the maintenance thread) replies with a report, which the
        // connection routes to the client as ModelsRefreshed.
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::RefreshModels { force, reply }) = daemon_rx.recv() {
                assert!(force);
                let _ = reply.send(Ok(crate::catalog::RefreshReport {
                    providers: 208,
                    models: 1234,
                    status: choreo_proto::RefreshStatus::Updated,
                }));
            }
        });
        handle_refresh_models_sync(&mut ctx, true);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(
            &msg,
            DaemonMessage::ModelsRefreshed {
                providers: 208,
                models: 1234,
                status: choreo_proto::RefreshStatus::Updated,
            }
        ));
    }

    #[test]
    fn handle_refresh_models_sync_err() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::RefreshModels { reply, .. }) = daemon_rx.recv() {
                let _ = reply.send(Err("daemon is locked".into()));
            }
        });
        handle_refresh_models_sync(&mut ctx, false);
        let msg = writer_rx.recv().unwrap();
        assert!(
            matches!(&msg, DaemonMessage::ModelsRefreshFailed { error } if error == "daemon is locked")
        );
    }

    #[test]
    fn handle_list_models_sync_err() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::ListModels { reply, .. }) = daemon_rx.recv() {
                let _ = reply.send(Err("daemon is locked".into()));
            }
        });
        handle_list_models_sync(&mut ctx, None);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::ModelsFailed { .. }));
        if let DaemonMessage::ModelsFailed { error } = &msg {
            assert_eq!(error, "daemon is locked");
        }
    }

    #[test]
    fn handle_get_credential_sync_some() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::GetCredential { service, reply }) = daemon_rx.recv() {
                assert_eq!(service, "openai");
                let _ = reply.send(Some("sk-123".into()));
            }
        });
        handle_get_credential_sync(&mut ctx, "openai".into());
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::Credential { .. }));
        if let DaemonMessage::Credential { service, key } = &msg {
            assert_eq!(service, "openai");
            assert_eq!(key.as_deref(), Some("sk-123"));
        }
    }

    #[test]
    fn handle_get_credential_sync_none() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::GetCredential { service, reply }) = daemon_rx.recv() {
                assert_eq!(service, "openai");
                let _ = reply.send(None);
            }
        });
        handle_get_credential_sync(&mut ctx, "openai".into());
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(msg, DaemonMessage::Credential { .. }));
        if let DaemonMessage::Credential { service, key } = &msg {
            assert_eq!(service, "openai");
            assert!(key.is_none());
        }
    }

    #[test]
    fn switch_session_to_different_sends_detach_to_old() {
        let (old_tx, old_rx) = mpsc::channel();
        let (new_tx, new_rx) = mpsc::channel::<SessionCommand>();
        let (sink, _writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let (daemon_tx, _daemon_rx) = mpsc::channel();
        let mut attached_id = Some(1u64);
        let mut attached_tx = Some(old_tx);
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut attached_id,
            attached_session_tx: &mut attached_tx,
            client_id: 42,
            is_unix: true,
        };

        switch_attached_session(2, new_tx, &mut ctx);

        // Detach sent to old session
        assert!(matches!(
            old_rx.try_recv().ok(),
            Some(SessionCommand::Detach { client_id: 42 })
        ));
        // Attach sent to new session
        assert!(matches!(
            new_rx.try_recv().ok(),
            Some(SessionCommand::Attach { client_id: 42, .. })
        ));
        // State updated to new session
        assert_eq!(attached_id, Some(2));
    }

    #[test]
    fn switch_session_same_skips_detach() {
        let (old_tx, old_rx) = mpsc::channel();
        let (new_tx, new_rx) = mpsc::channel::<SessionCommand>();
        let (sink, _writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let (daemon_tx, _daemon_rx) = mpsc::channel();
        let mut attached_id = Some(1u64);
        let mut attached_tx = Some(old_tx);
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut attached_id,
            attached_session_tx: &mut attached_tx,
            client_id: 42,
            is_unix: true,
        };

        switch_attached_session(1, new_tx, &mut ctx);

        // No Detach sent — same session id
        assert!(old_rx.try_recv().is_err());
        // Attach still sent (caller expects the subscription)
        assert!(matches!(
            new_rx.try_recv().ok(),
            Some(SessionCommand::Attach { client_id: 42, .. })
        ));
        // State stays at session 1
        assert_eq!(attached_id, Some(1));
    }

    #[test]
    fn handle_delete_session_sync_success_no_message_sent() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::DeleteSession { reply, .. }) = daemon_rx.recv() {
                let _ = reply.send(Ok(()));
            }
        });
        handle_delete_session_sync(&mut ctx, 42);
        // On success, no message is sent to writer (broadcast handles it)
        assert!(writer_rx.try_recv().is_err());
    }

    #[test]
    fn handle_delete_session_sync_error() {
        let (daemon_tx, daemon_rx) = mpsc::channel();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        std::thread::spawn(move || {
            if let Ok(DaemonCommand::DeleteSession { reply, .. }) = daemon_rx.recv() {
                let _ = reply.send(Err(io::Error::other("db error")));
            }
        });
        handle_delete_session_sync(&mut ctx, 42);
        let msg = writer_rx.recv().unwrap();
        assert!(matches!(
            msg,
            DaemonMessage::Session {
                event: SessionEvent::SessionDeleteFailed { .. },
                ..
            }
        ));
        if let DaemonMessage::Session {
            session_id: Some(session_id),
            event: SessionEvent::SessionDeleteFailed { error },
        } = &msg
        {
            assert_eq!(*session_id, 42);
            assert_eq!(error, "db error");
        }
    }

    #[test]
    fn handle_delete_session_sync_disconnected() {
        let (daemon_tx, daemon_rx) = mpsc::channel::<DaemonCommand>();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };
        drop(daemon_rx);
        handle_delete_session_sync(&mut ctx, 42);
        assert!(writer_rx.try_recv().is_err());
    }

    #[test]
    fn switch_session_from_none_no_detach() {
        let (new_tx, new_rx) = mpsc::channel::<SessionCommand>();
        let (sink, _writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let (daemon_tx, _daemon_rx) = mpsc::channel();
        let mut attached_id: Option<u64> = None;
        let mut attached_tx: Option<mpsc::Sender<SessionCommand>> = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut attached_id,
            attached_session_tx: &mut attached_tx,
            client_id: 42,
            is_unix: true,
        };

        switch_attached_session(1, new_tx, &mut ctx);

        assert_eq!(attached_id, Some(1));
        assert!(matches!(
            new_rx.try_recv().ok(),
            Some(SessionCommand::Attach { client_id: 42, .. })
        ));
    }

    // ── Undo dispatch ────────────────────────────────────────────────────

    #[test]
    fn dispatch_undo_when_attached_sends_undo_command() {
        let (daemon_tx, _daemon_rx) = mpsc::channel();
        let (sink, _writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let (session_tx, session_rx) = mpsc::channel();
        let mut attached_id = Some(1u64);
        let mut attached_tx = Some(session_tx);
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut attached_id,
            attached_session_tx: &mut attached_tx,
            client_id: 42,
            is_unix: true,
        };

        dispatch_client_message(ClientMessage::Undo, &mut ctx).unwrap();

        assert!(matches!(
            session_rx.try_recv().ok(),
            Some(SessionCommand::Undo)
        ));
    }

    #[test]
    fn dispatch_undo_when_not_attached_is_noop() {
        let (daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };

        dispatch_client_message(ClientMessage::Undo, &mut ctx).unwrap();

        // No message should appear on writer or session channels.
        assert!(writer_rx.try_recv().is_err());
    }

    // ── Redo dispatch ────────────────────────────────────────────────────

    #[test]
    fn dispatch_redo_when_attached_sends_redo_command() {
        let (daemon_tx, _daemon_rx) = mpsc::channel();
        let (sink, _writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let (session_tx, session_rx) = mpsc::channel();
        let mut attached_id = Some(1u64);
        let mut attached_tx = Some(session_tx);
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut attached_id,
            attached_session_tx: &mut attached_tx,
            client_id: 42,
            is_unix: true,
        };

        dispatch_client_message(ClientMessage::Redo, &mut ctx).unwrap();

        assert!(matches!(
            session_rx.try_recv().ok(),
            Some(SessionCommand::Redo)
        ));
    }

    #[test]
    fn dispatch_redo_when_not_attached_is_noop() {
        let (daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };

        dispatch_client_message(ClientMessage::Redo, &mut ctx).unwrap();

        assert!(writer_rx.try_recv().is_err());
    }

    // ── ContinueGeneration dispatch ──────────────────────────────────────

    #[test]
    fn dispatch_continue_generation_when_attached_sends_run_input() {
        let (daemon_tx, _daemon_rx) = mpsc::channel();
        let (sink, _writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let (session_tx, session_rx) = mpsc::channel();
        let mut attached_id = Some(1u64);
        let mut attached_tx = Some(session_tx);
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut attached_id,
            attached_session_tx: &mut attached_tx,
            client_id: 42,
            is_unix: true,
        };

        dispatch_client_message(
            ClientMessage::ContinueGeneration { request_id: 7 },
            &mut ctx,
        )
        .unwrap();

        let cmd = session_rx.try_recv().expect("should receive RunInput");
        assert!(matches!(
            &cmd,
            SessionCommand::RunInput {
                request_id: 7,
                input,
            } if input == b"Continue."
        ));
    }

    #[test]
    fn dispatch_continue_generation_when_not_attached_sends_failed() {
        let (daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
        let (sink, writer_rx) = test_sink();
        let global_lag = Arc::new(AtomicUsize::new(0));
        let mut none_id = None;
        let mut none_tx = None;
        let mut ctx = ClientCtx {
            writer: &sink,
            global_lag: &global_lag,
            daemon_tx: &daemon_tx,
            attached_session_id: &mut none_id,
            attached_session_tx: &mut none_tx,
            client_id: 0,
            is_unix: true,
        };

        dispatch_client_message(
            ClientMessage::ContinueGeneration { request_id: 7 },
            &mut ctx,
        )
        .unwrap();

        let msg = writer_rx.recv().expect("should receive Failed");
        assert!(matches!(
            &msg,
            DaemonMessage::Session {
                session_id: None,
                event: SessionEvent::Failed {
                    request_id: 7,
                    error,
                },
            } if error == "no session attached"
        ));
    }

    // ── ChannelConnectionWriter (embedded transport) ─────────────────────

    /// A message sent while the writer is open arrives as a VALUE on the
    /// receiver, and dropping the last sender (writer_thread's post-loop
    /// path) closes the receiver — the channel analogue of socket EOF.
    #[test]
    fn channel_writer_forwards_values_and_receiver_sees_close() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let mut writer = ChannelConnectionWriter::new(tx);
        writer.send_message(&DaemonMessage::Pong).unwrap();
        // Dropping the writer drops the sender: the receiver sees the value,
        // then a disconnect (Err) — without any shutdown call, mirroring the
        // writer_thread exit path.
        drop(writer);
        assert!(matches!(rx.recv(), Ok(DaemonMessage::Pong)));
        assert!(
            rx.recv().is_err(),
            "dropping the sender must close the receiver"
        );
    }

    /// After `shutdown()` the sender is gone, so any subsequent send is an
    /// error and the receiver is closed immediately — the same
    /// notify-before-close contract the socket writer provides via
    /// `Shutdown::Both`.
    #[test]
    fn channel_writer_send_after_shutdown_errors() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let mut writer = ChannelConnectionWriter::new(tx);
        writer.shutdown();
        assert!(
            writer.send_message(&DaemonMessage::Pong).is_err(),
            "sending after shutdown must error (the writer thread never does this on the \
             graceful path, but the contract must hold)"
        );
        assert!(rx.recv().is_err(), "shutdown must close the receiver");
    }

    /// Through the shared (generic) writer_thread: `ShuttingDown` is
    /// delivered to the embedded receiver as a value FIRST, then the writer
    /// shuts the channel down, so the GUI observes the notification before
    /// the channel close — notify-before-close, no bytes involved.
    #[test]
    fn writer_thread_delivers_shutting_down_before_channel_close() {
        let (tx, rx) = crossbeam_channel::unbounded::<DaemonMessage>();
        let (out_tx, out_rx) = crossbeam_channel::unbounded();
        let bytes = Arc::new(AtomicUsize::new(0));
        let global = Arc::new(AtomicUsize::new(0));
        let handle = std::thread::spawn({
            let bytes = Arc::clone(&bytes);
            let global = Arc::clone(&global);
            move || writer_thread(ChannelConnectionWriter::new(out_tx), rx, bytes, global)
        });

        tx.send(DaemonMessage::Pong).unwrap();
        tx.send(DaemonMessage::ShuttingDown).unwrap();
        // Queued after the notification: must never reach the GUI.
        tx.send(DaemonMessage::Pong).unwrap();

        handle.join().expect("writer thread panicked");
        assert!(matches!(out_rx.recv(), Ok(DaemonMessage::Pong)));
        assert!(
            matches!(out_rx.recv(), Ok(DaemonMessage::ShuttingDown)),
            "ShuttingDown must be delivered BEFORE the channel closes"
        );
        assert!(
            out_rx.recv().is_err(),
            "after the notification the channel must be closed (recv errors)"
        );
    }
}