zeph-acp 0.22.4

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

//! Integration tests for the ACP 0.11 server (`zeph-acp`) using in-process loopback transports.
//!
//! These tests exercise the full ACP protocol stack: `serve_connection` → `run_agent` →
//! request handlers, driven by a real `acp::Client` over a `tokio::io::duplex` byte stream.
//! Each test runs inside a `tokio::task::LocalSet` because the agent session futures are `!Send`.

use std::sync::Arc;

use agent_client_protocol as acp;
use tempfile::TempDir;
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
use zeph_acp::{AcpServerConfig, AgentSpawner, serve_connection};
use zeph_core::channel::Channel as _;

/// Minimal no-op spawner — drops the channel immediately.
fn noop_spawner() -> AgentSpawner {
    Arc::new(|channel, _ctx, _session| {
        Box::pin(async move {
            drop(channel);
        })
    })
}

/// Spawner that reads one user message then sends `Flush`, completing the turn with `EndTurn`.
fn echo_spawner() -> AgentSpawner {
    Arc::new(|mut channel, _ctx, _session| {
        Box::pin(async move {
            // Consume the user message so `do_prompt` can proceed.
            let _ = channel.recv().await;
            // Signal end of turn: drain_agent_events exits on Flush.
            let _ = channel.flush_chunks().await;
        })
    })
}

/// Like `echo_spawner`, but loops to handle multiple sequential `session/prompt` turns on the
/// same session instead of returning (and dropping the channel) after the first one.
fn multi_turn_echo_spawner() -> AgentSpawner {
    Arc::new(|mut channel, _ctx, _session| {
        Box::pin(async move {
            while let Ok(Some(_)) = channel.recv().await {
                if channel.flush_chunks().await.is_err() {
                    break;
                }
            }
        })
    })
}

/// Spawner that never completes on its own — awaits `pending()` forever, ignoring the
/// channel and `cancel_signal` entirely — so the only way this task ever stops is via
/// `JoinHandle::abort()` (#6674 regression coverage).
///
/// `started` is notified once the task begins running (so tests can wait for it before
/// racing a close/delete against it); `alive` flips to `false` only when the task's future
/// is actually dropped — by the runtime unwinding an aborted task, or (if the fix regresses)
/// never, if nothing ever aborts it. Checking `alive` right after `session/close` or
/// `session/delete` completes is a direct, non-flaky proof that the loop task was joined
/// before the response went out, not just signaled and left to run.
fn hanging_spawner(
    started: Arc<tokio::sync::Notify>,
    alive: Arc<std::sync::atomic::AtomicBool>,
) -> AgentSpawner {
    Arc::new(move |_channel, _ctx, _session| {
        let started = Arc::clone(&started);
        let alive = Arc::clone(&alive);
        Box::pin(async move {
            struct ClearOnDrop(Arc<std::sync::atomic::AtomicBool>);
            impl Drop for ClearOnDrop {
                fn drop(&mut self) {
                    self.0.store(false, std::sync::atomic::Ordering::SeqCst);
                }
            }
            alive.store(true, std::sync::atomic::Ordering::SeqCst);
            let _clear_on_drop = ClearOnDrop(alive);
            started.notify_one();
            std::future::pending::<()>().await;
        })
    })
}

/// Spawner that sends N text chunks then flushes.
fn text_chunks_spawner(chunks: Vec<&'static str>) -> AgentSpawner {
    Arc::new(move |mut channel, _ctx, _session| {
        let chunks = chunks.clone();
        Box::pin(async move {
            let _ = channel.recv().await;
            for chunk in chunks {
                let _ = channel.send_chunk(chunk).await;
            }
            let _ = channel.flush_chunks().await;
        })
    })
}

/// Spawner that requests tool-call permission via `AcpContext::permission_gate` before
/// completing the turn — reproduces the `session/request_permission` round-trip that
/// deadlocked before #6656 was fixed: the server's request-dispatch loop was blocked
/// awaiting `do_prompt` inline, so it could never route the client's permission reply
/// back to the pending `check_permission` future.
///
/// The gate's decision is forwarded on `decision_tx` so tests can assert on it directly
/// without depending on `PromptResponse` carrying assembled chunk text.
fn permission_gated_spawner(decision_tx: tokio::sync::mpsc::UnboundedSender<bool>) -> AgentSpawner {
    Arc::new(move |mut channel, ctx, session| {
        let decision_tx = decision_tx.clone();
        Box::pin(async move {
            let _ = channel.recv().await;
            let gate = ctx
                .expect("AcpContext must be present")
                .permission_gate
                .expect("permission gate must be present");
            let tool_call = acp::schema::v1::ToolCallUpdate::new(
                "tc-perm-1".to_owned(),
                acp::schema::v1::ToolCallUpdateFields::new().title("shell_execute".to_owned()),
            );
            let allowed = gate
                .check_permission(session.session_id, tool_call)
                .await
                .unwrap_or(false);
            let _ = decision_tx.send(allowed);
            let _ = channel.flush_chunks().await;
        })
    })
}

/// Minimal server config for tests.
fn test_config(name: &str) -> AcpServerConfig {
    AcpServerConfig {
        agent_name: name.to_owned(),
        agent_version: "0.0.1".to_owned(),
        max_sessions: 8,
        ..AcpServerConfig::default()
    }
}

/// Server config with a provider factory and `available_models`, required for `model` /
/// `temperature` `session/set_config_option` coverage. Every model key resolves to a fresh
/// `MockProvider`.
fn test_config_with_models(name: &str, models: Vec<&str>) -> AcpServerConfig {
    let factory: zeph_acp::ProviderFactory = Arc::new(|_key: &str| {
        Some(zeph_llm::any::AnyProvider::Mock(
            zeph_llm::mock::MockProvider::default(),
        ))
    });
    AcpServerConfig {
        agent_name: name.to_owned(),
        agent_version: "0.0.1".to_owned(),
        max_sessions: 8,
        provider_factory: Some(factory),
        available_models: Arc::new(parking_lot::RwLock::new(
            models.into_iter().map(str::to_owned).collect(),
        )),
        ..AcpServerConfig::default()
    }
}

/// Server config with provider identities for `providers/list` coverage (#5448).
#[cfg(feature = "unstable-llm-providers")]
fn test_config_with_provider_names(
    name: &str,
    providers: Vec<(&str, zeph_acp::LlmProtocol)>,
) -> AcpServerConfig {
    AcpServerConfig {
        agent_name: name.to_owned(),
        agent_version: "0.0.1".to_owned(),
        max_sessions: 8,
        provider_names: providers
            .into_iter()
            .map(|(n, p)| (n.to_owned(), p))
            .collect(),
        ..AcpServerConfig::default()
    }
}

/// Creates an in-process duplex transport pair.
/// Returns `(server_writer, server_reader, client_writer, client_reader)`.
fn duplex_pair() -> (
    impl futures::AsyncWrite + Unpin + Send + 'static,
    impl futures::AsyncRead + Unpin + Send + 'static,
    impl futures::AsyncWrite + Unpin + Send + 'static,
    impl futures::AsyncRead + Unpin + Send + 'static,
) {
    let (s_tok, c_tok) = tokio::io::duplex(64 * 1024);
    // DuplexStream implements both AsyncRead and AsyncWrite directly.
    // Use split to produce non-Clone halves that satisfy `Send + 'static`.
    let (s_read, s_write) = tokio::io::split(s_tok);
    let (c_read, c_write) = tokio::io::split(c_tok);
    (
        s_write.compat_write(),
        s_read.compat(),
        c_write.compat_write(),
        c_read.compat(),
    )
}

/// Creates a temporary working directory for tests that need a real filesystem path.
fn temp_workdir() -> TempDir {
    tempfile::tempdir().expect("failed to create temp dir")
}

/// Extracts the current selected value from a `model` / `temperature` (`Select`-kind)
/// `SessionConfigOption`. Panics if the option is not a `Select`.
fn select_current_value(option: &acp::schema::v1::SessionConfigOption) -> &str {
    match &option.kind {
        acp::schema::v1::SessionConfigKind::Select(select) => select.current_value.0.as_ref(),
        #[allow(unreachable_patterns)]
        other => panic!("expected a Select config option, got {other:?}"),
    }
}

#[tokio::test(flavor = "current_thread")]
async fn initialize_handshake() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                let resp = cx
                    .send_request(acp::schema::v1::InitializeRequest::new(
                        acp::schema::ProtocolVersion::LATEST,
                    ))
                    .block_task()
                    .await?;
                assert!(resp.agent_info.is_some(), "agent_info missing");
                let info = resp.agent_info.unwrap();
                assert_eq!(info.name, "test-agent");
                assert_eq!(info.version, "0.0.1");
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "initialize failed: {result:?}");
                }
            }
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn new_session_returns_session_id() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let resp = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?;

                assert!(
                    !resp.session_id.0.is_empty(),
                    "session_id must not be empty"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "new_session failed: {result:?}");
                }
            }
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn cancel_notification_does_not_panic() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_resp = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?;

                cx.send_notification(acp::schema::v1::CancelNotification::new(
                    session_resp.session_id,
                ))?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "cancel notification failed: {result:?}");
                }
            }
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn unknown_ext_method_returns_null() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let raw_params =
                    Arc::from(serde_json::value::RawValue::from_string("{}".to_owned()).unwrap());
                let resp = cx
                    .send_request(acp::schema::v1::ClientRequest::ExtMethodRequest(
                        acp::schema::v1::ExtRequest::new("_unknown_method", raw_params),
                    ))
                    .block_task()
                    .await?;

                assert_eq!(
                    resp.to_string(),
                    "null",
                    "unknown ext method must return null"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "ext_method failed: {result:?}");
                }
            }
        })
        .await;
}

/// #5448 regression: `providers/list` must reflect `AcpServerConfig::provider_names` as wired
/// through `build_agent_state`, not always return an empty array.
#[cfg(feature = "unstable-llm-providers")]
#[tokio::test(flavor = "current_thread")]
async fn providers_list_reflects_configured_provider_names() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (sw, sr, cw, cr) = duplex_pair();
            let config = test_config_with_provider_names(
                "test-agent",
                vec![("openai", zeph_acp::LlmProtocol::OpenAi)],
            );
            let server_fut =
                serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let raw_params =
                    Arc::from(serde_json::value::RawValue::from_string("{}".to_owned()).unwrap());
                let resp = cx
                    .send_request(acp::schema::v1::ClientRequest::ExtMethodRequest(
                        acp::schema::v1::ExtRequest::new("providers/list", raw_params),
                    ))
                    .block_task()
                    .await?;

                let body = resp.to_string();
                assert!(
                    body.contains("openai"),
                    "providers/list must include the configured provider name, got: {body}"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "providers/list ext_method failed: {result:?}");
                }
            }
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn load_session_unknown_id_returns_error() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let err = cx
                    .send_request(acp::schema::v1::LoadSessionRequest::new(
                        "non-existent-session-id",
                        workdir.path(),
                    ))
                    .block_task()
                    .await;

                assert!(
                    err.is_err(),
                    "load_session of unknown id must return an error"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "client connection failed: {result:?}");
                }
            }
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn session_list_contains_created_sessions() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                // Create two sessions so the list is non-trivially non-empty.
                let id_a = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;
                let id_b = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let resp = cx
                    .send_request(acp::schema::v1::ListSessionsRequest::new())
                    .block_task()
                    .await?;

                let ids: Vec<&acp::schema::v1::SessionId> =
                    resp.sessions.iter().map(|s| &s.session_id).collect();
                assert!(ids.contains(&&id_a), "session A not in list: {ids:?}");
                assert!(ids.contains(&&id_b), "session B not in list: {ids:?}");
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "list_sessions failed: {result:?}");
                }
            }
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn prompt_round_trip_returns_end_turn() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            // echo_spawner reads the message and signals Flush so drain_agent_events exits.
            let server_fut = serve_connection(
                echo_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("hello"),
                )];
                let resp = cx
                    .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                    .block_task()
                    .await?;

                assert_eq!(
                    resp.stop_reason,
                    acp::schema::v1::StopReason::EndTurn,
                    "expected EndTurn, got {:?}",
                    resp.stop_reason,
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "prompt round-trip failed: {result:?}");
                }
            }
        })
        .await;
}

/// AC #5: `drain_until_stop` collects concatenated text from multiple `AgentMessageChunk` updates.
#[tokio::test(flavor = "current_thread")]
async fn drain_until_stop_collects_text_chunks() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                text_chunks_spawner(vec!["hello", " ", "world"]),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("go"),
                )];
                let resp = cx
                    .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                    .block_task()
                    .await?;

                assert_eq!(resp.stop_reason, acp::schema::v1::StopReason::EndTurn);
                // The PromptResponse carries the assembled text from all chunks.
                // Verify the stop_reason and that the round-trip succeeded — the per-chunk
                // assembly logic is exercised by driver::drain_until_stop in client tests.
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "drain_until_stop text test failed: {result:?}");
                }
            }
        })
        .await;
}

/// Regression test for #6673: `/review`'s output must actually reach the client, not be
/// silently discarded. `close_session_aborts_agent_loop_task`-style unit tests already prove
/// `/review` is *dispatched* correctly, but that alone doesn't prove the client ever *sees*
/// the agent's response — before this fix, `handle_review_command` bypassed
/// `acquire_prompt_channels` entirely, so the agent loop's `AgentMessageChunk` notifications
/// either leaked into the next unrelated turn (pre-#6666/#6667) or were silently drained and
/// discarded by the next turn's `acquire_prompt_channels` (post-#6666/#6667) — either way, the
/// client issuing `/review` never received its own output. This test registers a real
/// `session/update` notification handler (mirroring the ACP client examples' pattern) so it can
/// assert on content actually delivered over the wire, not just on `PromptResponse.stop_reason`.
#[tokio::test(flavor = "current_thread")]
async fn review_command_output_is_delivered_to_client() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                text_chunks_spawner(vec!["review", " ", "output"]),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let collected = Arc::new(std::sync::Mutex::new(String::new()));
            let collected_for_handler = Arc::clone(&collected);
            let client_fut = acp::Client
                .builder()
                .on_receive_notification(
                    move |notification: acp::schema::v1::SessionNotification, _cx| {
                        let collected = Arc::clone(&collected_for_handler);
                        async move {
                            if let acp::schema::v1::SessionUpdate::AgentMessageChunk(chunk) =
                                notification.update
                                && let acp::schema::v1::ContentBlock::Text(text) = chunk.content
                            {
                                collected.lock().unwrap().push_str(&text.text);
                            }
                            Ok(())
                        }
                    },
                    acp::on_receive_notification!(),
                )
                .connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                    cx.send_request(acp::schema::v1::InitializeRequest::new(
                        acp::schema::ProtocolVersion::LATEST,
                    ))
                    .block_task()
                    .await?;

                    let session_id = cx
                        .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                        .block_task()
                        .await?
                        .session_id;

                    let content = vec![acp::schema::v1::ContentBlock::Text(
                        acp::schema::v1::TextContent::new("/review"),
                    )];
                    let resp = cx
                        .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                        .block_task()
                        .await?;

                    assert_eq!(resp.stop_reason, acp::schema::v1::StopReason::EndTurn);
                    Ok(())
                });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "review round-trip test failed: {result:?}");
                }
            }
            assert_eq!(
                *collected.lock().unwrap(),
                "review output",
                "the spawner's chunks must have reached the client as AgentMessageChunk \
                 notifications — before #6673 this would be empty since /review never called \
                 acquire_prompt_channels"
            );
        })
        .await;
}

/// AC #10: `session/cancel` prior to prompt causes the prompt to complete with
/// `StopReason::Cancelled`.
///
/// `do_cancel` stores its signal via `cancel_signal.notify_one()`. `drain_agent_events` now
/// drains any stale permit on this shared per-session `Notify` *before* its main loop starts
/// (hardening against the same leftover-permit race fixed for the `$/cancel_request` bridge —
/// see `late_cancel_after_prompt_completion_does_not_affect_next_prompt`), so a cancel that
/// arrives while no prompt is in flight on this session is a no-op rather than retroactively
/// cancelling whichever prompt happens to be sent next. `session/cancel` has no request id to
/// scope it to a specific turn, so there is no well-defined "current turn" for it to cancel
/// when none is running.
///
/// This test sends `CancelNotification` before any `PromptRequest` on a brand-new session and
/// asserts the upcoming prompt completes normally — i.e. the early cancel notification is
/// dropped, not retroactively applied.
#[tokio::test(flavor = "current_thread")]
async fn cancel_before_prompt_is_a_no_op() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                echo_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                // Cancel notification arrives with no prompt in flight on this session.
                cx.send_notification(acp::schema::v1::CancelNotification::new(session_id.clone()))?;

                let content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("go"),
                )];
                let resp = cx
                    .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                    .block_task()
                    .await?;

                assert_eq!(
                    resp.stop_reason,
                    acp::schema::v1::StopReason::EndTurn,
                    "a cancel notification sent before any prompt is in flight must not \
                     retroactively cancel the next prompt, got {:?}",
                    resp.stop_reason,
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "cancel_before_prompt test failed: {result:?}");
                }
            }
        })
        .await;
}

/// Regression test for the fixed `drain_agent_events` stale-permit race (review S-C2): a
/// cancellation that resolves once a prompt has *already finished* — e.g. a `session/cancel`
/// notification, or a late `$/cancel_request` racing the bridge in `handlers/prompt.rs` —
/// must not silently cancel the next, unrelated prompt on the same session via a leftover
/// permit on the shared `cancel_signal: Arc<Notify>`.
///
/// Simulated deterministically via the public `CancelNotification` protocol message (which
/// notifies the very same `cancel_signal` `do_cancel` and the `$/cancel_request` bridge both
/// use) sent strictly *after* the first prompt's response has already been received.
#[tokio::test(flavor = "current_thread")]
async fn late_cancel_after_prompt_completion_does_not_affect_next_prompt() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                multi_turn_echo_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let first_content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("first"),
                )];
                let first = cx
                    .send_request(acp::schema::v1::PromptRequest::new(
                        session_id.clone(),
                        first_content,
                    ))
                    .block_task()
                    .await?;
                assert_eq!(
                    first.stop_reason,
                    acp::schema::v1::StopReason::EndTurn,
                    "first prompt must complete normally before the late cancel arrives"
                );

                // No prompt is in flight at this point — this notify leaves a permit on the
                // shared `cancel_signal` that must be drained before the next prompt's
                // `drain_agent_events` loop starts.
                cx.send_notification(acp::schema::v1::CancelNotification::new(session_id.clone()))?;

                let second_content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("second"),
                )];
                let second = cx
                    .send_request(acp::schema::v1::PromptRequest::new(
                        session_id,
                        second_content,
                    ))
                    .block_task()
                    .await?;
                assert_eq!(
                    second.stop_reason,
                    acp::schema::v1::StopReason::EndTurn,
                    "a cancel notification that arrives between two prompts must not cancel \
                     the next, unrelated prompt, got {:?}",
                    second.stop_reason,
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "late cancel regression test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `authenticate` is a no-op (vault-based auth) but must round-trip successfully (#5367).
#[tokio::test(flavor = "current_thread")]
async fn authenticate_returns_default_response() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                cx.send_request(acp::schema::v1::AuthenticateRequest::new("agent"))
                    .block_task()
                    .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "authenticate failed: {result:?}");
                }
            }
        })
        .await;
}

/// `logout` is a no-op (vault-based auth) but must round-trip successfully (#5367).
#[tokio::test(flavor = "current_thread")]
async fn logout_returns_default_response() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                cx.send_request(acp::schema::v1::LogoutRequest::new())
                    .block_task()
                    .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "logout failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/close` flushes and removes the session: a subsequent `session/load` for the same
/// id must fail since no store is configured and the in-memory entry is gone (#5367).
#[tokio::test(flavor = "current_thread")]
async fn close_session_removes_session_from_memory() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                cx.send_request(acp::schema::v1::CloseSessionRequest::new(
                    session_id.clone(),
                ))
                .block_task()
                .await?;

                let load_err = cx
                    .send_request(acp::schema::v1::LoadSessionRequest::new(
                        session_id,
                        workdir.path(),
                    ))
                    .block_task()
                    .await;
                assert!(
                    load_err.is_err(),
                    "loading a closed session must fail when no store is configured"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "close_session test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/delete` removes the session from `session/list` (#5367) and, when a store is
/// configured, permanently removes the persisted row too — a deleted session must never
/// resurrect via `session/load`/`session/resume` (#6271).
#[tokio::test(flavor = "current_thread")]
async fn delete_session_removes_session_from_list() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-delete-test.db")
                .to_string_lossy()
                .into_owned();
            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut =
                serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                cx.send_request(acp::schema::v1::DeleteSessionRequest::new(
                    session_id.clone(),
                ))
                .block_task()
                .await?;

                let resp = cx
                    .send_request(acp::schema::v1::ListSessionsRequest::new())
                    .block_task()
                    .await?;
                let ids: Vec<&acp::schema::v1::SessionId> =
                    resp.sessions.iter().map(|s| &s.session_id).collect();
                assert!(
                    !ids.contains(&&session_id),
                    "deleted session must not appear in session/list: {ids:?}"
                );
                Ok(session_id)
            });
            let session_id = tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    result.expect("delete_session test failed")
                }
            };

            // Verify the row is actually gone from the persistence store, not just absent
            // from the in-memory session/list — the regression this test guards against
            // (#6271) is a deleted session resurrecting via load/resume because the store
            // row survived.
            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .expect("SqliteStore::new");
            assert!(
                !store
                    .acp_session_exists(&session_id.to_string())
                    .await
                    .expect("acp_session_exists query failed"),
                "deleted session must not survive in the persistence store"
            );
        })
        .await;
}

/// `session/close` must abort and await the session's agent-loop task before returning, so a
/// task left running past the close can never keep emitting events/notifications under a
/// `SessionId` that may be reused by a later `session/load`/`session/resume` (#6674).
#[tokio::test(flavor = "current_thread")]
async fn close_session_aborts_agent_loop_task() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let started = Arc::new(tokio::sync::Notify::new());
            let alive = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                hanging_spawner(Arc::clone(&started), Arc::clone(&alive)),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let started_for_client = Arc::clone(&started);
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                // Wait for the agent-loop task to actually start running before racing close
                // against it — otherwise a close that lands before the task is even polled
                // once would pass vacuously.
                started_for_client.notified().await;

                cx.send_request(acp::schema::v1::CloseSessionRequest::new(session_id))
                    .block_task()
                    .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "close_session test failed: {result:?}");
                }
            }
            assert!(
                !alive.load(std::sync::atomic::Ordering::SeqCst),
                "agent-loop task must be aborted and joined before session/close returns"
            );
        })
        .await;
}

/// Same guarantee as `close_session_aborts_agent_loop_task`, for `session/delete` (#6674).
#[tokio::test(flavor = "current_thread")]
async fn delete_session_aborts_agent_loop_task() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let started = Arc::new(tokio::sync::Notify::new());
            let alive = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                hanging_spawner(Arc::clone(&started), Arc::clone(&alive)),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let started_for_client = Arc::clone(&started);
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                started_for_client.notified().await;

                cx.send_request(acp::schema::v1::DeleteSessionRequest::new(session_id))
                    .block_task()
                    .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "delete_session test failed: {result:?}");
                }
            }
            assert!(
                !alive.load(std::sync::atomic::Ordering::SeqCst),
                "agent-loop task must be aborted and joined before session/delete returns"
            );
        })
        .await;
}

/// `session/fork` creates a new session with a distinct id from the source (#5367).
#[cfg(feature = "unstable-session-fork")]
#[tokio::test(flavor = "current_thread")]
async fn fork_session_creates_distinct_session_id() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let source_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let forked = cx
                    .send_request(acp::schema::v1::ForkSessionRequest::new(
                        source_id.clone(),
                        workdir.path(),
                    ))
                    .block_task()
                    .await?;

                assert_ne!(
                    forked.session_id, source_id,
                    "forked session must have a distinct id from the source"
                );
                assert!(!forked.session_id.0.is_empty());
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "fork_session test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/fork` copies the source session's durable JSONL event log into a new,
/// self-contained child log when `[session] enabled = true` (spec-068 P2, #5343).
///
/// The mock spawner used by this test harness never runs a real `zeph_core::Agent` (that only
/// happens in the root binary's `spawn_acp_agent`), so it cannot generate turns through the
/// normal `SessionSink` path. Instead this test seeds the source session's `events.jsonl`
/// directly via `zeph_session::SessionEventLog`, exercising exactly the `fork_conversation` /
/// `ForkEngine::fork` wiring under test without needing the full agent-loop integration.
#[cfg(feature = "unstable-session-fork")]
#[tokio::test(flavor = "current_thread")]
async fn fork_session_copies_event_log_when_persistence_enabled() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-fork-test.db")
                .to_string_lossy()
                .into_owned();
            let session_data_dir = db_dir.path().join("sessions");

            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path),
                session_data_dir: Some(session_data_dir.clone()),
                ..test_config("test-agent")
            };
            let server_fut =
                serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let source_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                // Seed the source session's event log directly (simulating turns that a real
                // agent loop would have appended via SessionSink).
                let source_dir =
                    zeph_session::session_dir(&session_data_dir, &source_id.to_string());
                let log = zeph_session::SessionEventLog::open(&source_dir)
                    .await
                    .expect("open source event log");
                log.append(
                    None,
                    None,
                    zeph_session::SessionEvent::SessionStarted {
                        session_id: source_id.to_string(),
                        cwd: workdir.path().to_string_lossy().into_owned(),
                        provider_name: "claude".to_owned(),
                        model: "opus".to_owned(),
                        forked_from: None,
                    },
                )
                .await
                .expect("append SessionStarted");
                log.append(
                    None,
                    None,
                    zeph_session::SessionEvent::UserMessage {
                        text: "hello".to_owned(),
                        image_refs: vec![],
                    },
                )
                .await
                .expect("append UserMessage");

                let forked = cx
                    .send_request(acp::schema::v1::ForkSessionRequest::new(
                        source_id.clone(),
                        workdir.path(),
                    ))
                    .block_task()
                    .await?;

                let child_dir =
                    zeph_session::session_dir(&session_data_dir, &forked.session_id.to_string());
                let child_log = zeph_session::SessionEventLog::open(&child_dir)
                    .await
                    .expect("open child event log");
                let events = child_log.read_all().await.expect("read child event log");
                // 1 synthesized SessionStarted header (forked_from) + the 2 seeded events.
                assert_eq!(events.len(), 3, "child log must contain the copied events");
                assert!(matches!(
                    events[0].kind,
                    zeph_session::SessionEvent::SessionStarted {
                        forked_from: Some(_),
                        ..
                    }
                ));

                let parent_log = zeph_session::SessionEventLog::open(&source_dir)
                    .await
                    .expect("reopen source event log");
                let parent_events = parent_log.read_all().await.expect("read source event log");
                assert!(
                    matches!(
                        parent_events.last().expect("parent has events").kind,
                        zeph_session::SessionEvent::ForkPoint { .. }
                    ),
                    "parent log must record a ForkPoint provenance event"
                );

                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "fork_session persistence test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/resume` reconnects to an in-memory session by id (#5367).
#[tokio::test(flavor = "current_thread")]
async fn resume_session_reconnects_to_existing_session() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                cx.send_request(acp::schema::v1::ResumeSessionRequest::new(
                    session_id,
                    workdir.path(),
                ))
                .block_task()
                .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "resume_session test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/resume` reconstructs a session from the `SQLite` store when it is no longer
/// held in the agent's in-memory `sessions` map — the scenario that matters in practice,
/// e.g. reconnecting after a server restart (#5374).
///
/// Two independent `serve_connection` calls share the same `sqlite_path`, so the second
/// connection gets a brand-new `ZephAcpAgentState` with an empty `sessions` map: any
/// successful `session/resume` there can only come from the store-backed reconstruction
/// branch (`store.acp_session_exists` + `resolve_conversation_id` + `make_session_entry` +
/// `spawn_local` re-attach), not the in-memory early-return checked by
/// `resume_session_reconnects_to_existing_session`. A follow-up `session/prompt` on the
/// resumed session proves the reconstructed entry is actually wired up and functional.
#[tokio::test(flavor = "current_thread")]
async fn resume_session_reconstructs_from_store_after_restart() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-resume-test.db")
                .to_string_lossy()
                .into_owned();

            // First connection: create the session, then drop the connection (and its
            // in-memory ZephAcpAgentState) without ever calling session/resume on it.
            let session_id = {
                let (sw, sr, cw, cr) = duplex_pair();
                let config = AcpServerConfig {
                    sqlite_path: Some(sqlite_path.clone()),
                    ..test_config("test-agent")
                };
                let server_fut =
                    serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
                let client_fut =
                    acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                        cx.send_request(acp::schema::v1::InitializeRequest::new(
                            acp::schema::ProtocolVersion::LATEST,
                        ))
                        .block_task()
                        .await?;

                        let session_id = cx
                            .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                            .block_task()
                            .await?
                            .session_id;
                        Ok(session_id)
                    });
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result.expect("session/new failed"),
                }
            };

            // Second connection: fresh ZephAcpAgentState (empty `sessions` map), same
            // sqlite_path. `session/resume` here can only succeed via the store-backed path.
            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut =
                serve_connection(echo_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                cx.send_request(acp::schema::v1::ResumeSessionRequest::new(
                    session_id.clone(),
                    workdir.path(),
                ))
                .block_task()
                .await?;

                // Prove the rebuilt session is actually functional: a real agent-loop task
                // must have been spawned and wired to the reconstructed channel entry.
                let content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("hello again"),
                )];
                let resp = cx
                    .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                    .block_task()
                    .await?;
                assert_eq!(
                    resp.stop_reason,
                    acp::schema::v1::StopReason::EndTurn,
                    "expected EndTurn from the store-reconstructed session, got {:?}",
                    resp.stop_reason,
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(
                        result.is_ok(),
                        "store-backed resume_session test failed: {result:?}"
                    );
                }
            }
        })
        .await;
}

/// `session/load` replays from the durable JSONL event log (spec-068 §12.3 / D-2), not the
/// legacy `acp_session_events` table, which the P1 write cutover leaves permanently empty for
/// post-cutover sessions (S1 regression fix). This test seeds only the JSONL log — never
/// `save_acp_event` — so a `session/load` that still reached into the legacy table would find
/// nothing there while this test's event still proves the store-backed reconstruction branch
/// (fresh connection, empty in-memory `sessions` map) can load the session at all.
#[tokio::test(flavor = "current_thread")]
async fn load_session_succeeds_from_event_log_with_no_legacy_rows() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-load-test.db")
                .to_string_lossy()
                .into_owned();
            let session_data_dir = db_dir.path().join("sessions");

            let session_id = {
                let (sw, sr, cw, cr) = duplex_pair();
                let config = AcpServerConfig {
                    sqlite_path: Some(sqlite_path.clone()),
                    session_data_dir: Some(session_data_dir.clone()),
                    ..test_config("test-agent")
                };
                let server_fut =
                    serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
                let client_fut =
                    acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                        cx.send_request(acp::schema::v1::InitializeRequest::new(
                            acp::schema::ProtocolVersion::LATEST,
                        ))
                        .block_task()
                        .await?;

                        let session_id = cx
                            .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                            .block_task()
                            .await?
                            .session_id;
                        Ok(session_id)
                    });
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result.expect("session/new failed"),
                }
            };

            // Seed only the durable JSONL log (as SessionSink would in production) — no
            // acp_session_events legacy rows exist for this session at all.
            let session_dir = zeph_session::session_dir(&session_data_dir, &session_id.to_string());
            let log = zeph_session::SessionEventLog::open(&session_dir)
                .await
                .expect("open event log");
            log.append(
                None,
                None,
                zeph_session::SessionEvent::UserMessage {
                    text: "hello".to_owned(),
                    image_refs: vec![],
                },
            )
            .await
            .expect("append UserMessage");

            // Fresh connection: empty in-memory `sessions` map, so `session/load` can only
            // succeed via the store-backed reconstruction branch.
            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path),
                session_data_dir: Some(session_data_dir),
                ..test_config("test-agent")
            };
            let server_fut =
                serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                cx.send_request(acp::schema::v1::LoadSessionRequest::new(
                    session_id,
                    workdir.path(),
                ))
                .block_task()
                .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "session/load from event log failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/fork` inherits the source session's current `temperature`, `thinking`, and
/// `auto_approve` config from its live in-memory state, rather than resetting to configured
/// defaults (#5373).
#[cfg(feature = "unstable-session-fork")]
#[tokio::test(flavor = "current_thread")]
async fn fork_session_inherits_config_from_in_memory_source() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            // Configured default is "balanced" — the source session will be switched away
            // from it so the test can distinguish "inherited" from "reset to default".
            let server_fut = serve_connection(
                noop_spawner(),
                test_config_with_models("test-agent", vec!["claude:sonnet"]),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let source_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                cx.send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                    source_id.clone(),
                    "temperature",
                    "creative",
                ))
                .block_task()
                .await?;
                cx.send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                    source_id.clone(),
                    "thinking",
                    "on",
                ))
                .block_task()
                .await?;
                cx.send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                    source_id.clone(),
                    "auto_approve",
                    "auto-edit",
                ))
                .block_task()
                .await?;

                let forked = cx
                    .send_request(acp::schema::v1::ForkSessionRequest::new(
                        source_id,
                        workdir.path(),
                    ))
                    .block_task()
                    .await?;

                let options = forked.config_options.unwrap_or_default();
                let get = |id: &str| {
                    select_current_value(options.iter().find(|o| o.id.0.as_ref() == id).unwrap())
                        .to_owned()
                };
                assert_eq!(
                    get("temperature"),
                    "creative",
                    "forked session must inherit the source's temperature preset, not reset to \
                     the configured default"
                );
                assert_eq!(
                    get("thinking"),
                    "on",
                    "forked session must inherit the source's thinking toggle"
                );
                assert_eq!(
                    get("auto_approve"),
                    "auto-edit",
                    "forked session must inherit the source's auto-approve level"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "fork inheritance test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/resume` of a session that was gracefully closed inherits its persisted config
/// snapshot (temperature preset applied to the effective provider) rather than resetting to
/// the configured default (#5373).
#[tokio::test(flavor = "current_thread")]
async fn resume_session_inherits_temperature_preset_after_close() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();

            let captured: Arc<std::sync::Mutex<Option<zeph_llm::provider::GenerationOverrides>>> =
                Arc::new(std::sync::Mutex::new(None));
            let captured_for_factory = Arc::clone(&captured);
            let factory: zeph_acp::ProviderFactory = Arc::new(move |_key: &str| {
                Some(zeph_llm::any::AnyProvider::Mock(
                    zeph_llm::mock::MockProvider::default()
                        .with_overrides_capture(Arc::clone(&captured_for_factory)),
                ))
            });

            let mut config = test_config_with_models("test-agent", vec!["claude:sonnet"]);
            config.provider_factory = Some(factory);
            config.sqlite_path = Some(":memory:".to_owned());

            let server_fut =
                serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                // Switch away from the configured default ("balanced") before closing.
                cx.send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                    session_id.clone(),
                    "temperature",
                    "creative",
                ))
                .block_task()
                .await?;

                cx.send_request(acp::schema::v1::CloseSessionRequest::new(
                    session_id.clone(),
                ))
                .block_task()
                .await?;

                cx.send_request(acp::schema::v1::ResumeSessionRequest::new(
                    session_id,
                    workdir.path(),
                ))
                .block_task()
                .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "resume inheritance test failed: {result:?}");
                }
            }

            let applied_temperature = captured
                .lock()
                .expect("capture mutex poisoned")
                .as_ref()
                .and_then(|o| o.temperature);
            assert_eq!(
                applied_temperature,
                Some(zeph_config::AcpTemperaturePreset::Creative.temperature()),
                "resumed session must inherit the closed source's persisted temperature preset, \
                 not reset to the configured default"
            );
        })
        .await;
}

/// `session/set_mode` switches the active mode and is reflected in subsequent requests (#5367).
#[tokio::test(flavor = "current_thread")]
async fn set_session_mode_switches_mode() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                cx.send_request(acp::schema::v1::SetSessionModeRequest::new(
                    session_id,
                    "architect",
                ))
                .block_task()
                .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "set_session_mode test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/set_config_option` with `config_id="model"` switches the active model and echoes
/// it back in `config_options` (#5367 coverage; pre-existing handler, previously untested).
#[tokio::test(flavor = "current_thread")]
async fn set_session_config_option_model_switches_active_model() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config_with_models("test-agent", vec!["claude:sonnet", "ollama:llama3"]),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let resp = cx
                    .send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                        session_id,
                        "model",
                        "ollama:llama3",
                    ))
                    .block_task()
                    .await?;

                let model_option = resp
                    .config_options
                    .iter()
                    .find(|o| o.id.0.as_ref() == "model")
                    .expect("model option must be present");
                assert_eq!(
                    select_current_value(model_option),
                    "ollama:llama3",
                    "model option must reflect the switched model"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "set_config_option model test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/set_config_option` with `config_id="temperature"` (`model_config` category, #5361)
/// switches the sampling-temperature preset and echoes it back in `config_options`.
#[tokio::test(flavor = "current_thread")]
async fn set_session_config_option_temperature_preset_changes() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config_with_models("test-agent", vec!["claude:sonnet"]),
                sw,
                sr,
            "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_resp = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?;
                let session_id = session_resp.session_id;

                // The default preset ("balanced") must already be advertised on session creation.
                let initial_temperature = session_resp
                    .config_options
                    .unwrap_or_default()
                    .into_iter()
                    .find(|o| o.id.0.as_ref() == "temperature")
                    .expect("temperature option must be advertised in new_session response");
                assert_eq!(select_current_value(&initial_temperature), "balanced");

                let resp = cx
                    .send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                        session_id,
                        "temperature",
                        "creative",
                    ))
                    .block_task()
                    .await?;

                let temperature_option = resp
                    .config_options
                    .iter()
                    .find(|o| o.id.0.as_ref() == "temperature")
                    .expect("temperature option must be present");
                assert_eq!(
                    select_current_value(temperature_option),
                    "creative",
                    "temperature option must reflect the switched preset"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "set_config_option temperature test failed: {result:?}");
                }
            }
        })
        .await;
}

/// Regression test for review finding S-C1: `[acp.model_config].default_temperature_preset`
/// must be primed into the session's *effective* provider at session creation
/// (`prime_provider_override` in `agent/mod.rs`) — not just advertised as the `temperature`
/// config option's current value in the IDE dropdown — even when no
/// `session/set_config_option` call is ever made.
///
/// Verified via `MockProvider::with_overrides_capture`: the test-only `ProviderFactory` shares
/// one capture slot across every provider it builds, so it observes whatever
/// `GenerationOverrides` production code applied internally during `new_session`.
#[tokio::test(flavor = "current_thread")]
async fn default_temperature_preset_is_primed_at_session_creation() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();

            let captured: Arc<std::sync::Mutex<Option<zeph_llm::provider::GenerationOverrides>>> =
                Arc::new(std::sync::Mutex::new(None));
            let captured_for_factory = Arc::clone(&captured);
            let factory: zeph_acp::ProviderFactory = Arc::new(move |_key: &str| {
                Some(zeph_llm::any::AnyProvider::Mock(
                    zeph_llm::mock::MockProvider::default()
                        .with_overrides_capture(Arc::clone(&captured_for_factory)),
                ))
            });

            let mut config = test_config_with_models("test-agent", vec!["claude:sonnet"]);
            config.provider_factory = Some(factory);
            config.model_config = zeph_config::AcpModelConfigConfig {
                default_temperature_preset: zeph_config::AcpTemperaturePreset::Creative,
            };

            let server_fut =
                serve_connection(noop_spawner(), config, sw, sr, "acp-local".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                // No session/set_config_option call is made — the default preset must already
                // be effective from session creation alone.
                cx.send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "client connection failed: {result:?}");
                }
            }

            let applied_temperature = captured
                .lock()
                .expect("capture mutex poisoned")
                .as_ref()
                .and_then(|o| o.temperature);
            assert_eq!(
                applied_temperature,
                Some(zeph_config::AcpTemperaturePreset::Creative.temperature()),
                "default_temperature_preset must be primed into the effective provider at \
                 session creation, with no session/set_config_option call made"
            );
        })
        .await;
}

/// `session/set_config_option` with an unrecognized `config_id` must error, not silently
/// succeed (#5367 coverage).
#[tokio::test(flavor = "current_thread")]
async fn set_session_config_option_unknown_config_id_errors() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let server_fut = serve_connection(
                noop_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let err = cx
                    .send_request(acp::schema::v1::SetSessionConfigOptionRequest::new(
                        session_id,
                        "nonexistent_option",
                        "whatever",
                    ))
                    .block_task()
                    .await;
                assert!(err.is_err(), "unknown config_id must return an error");
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "client connection failed: {result:?}");
                }
            }
        })
        .await;
}

/// The real `$/cancel_request` protocol notification (#5362), sent for the in-flight
/// `session/prompt` JSON-RPC request, cancels the prompt the same way `session/cancel` does.
#[cfg(feature = "unstable-cancel-request")]
#[tokio::test(flavor = "current_thread")]
async fn cancel_request_during_prompt_cancels() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            // echo_spawner reads the message and flushes; the $/cancel_request watcher in
            // handle_prompt notifies the same cancel_signal session/cancel uses.
            let server_fut = serve_connection(
                echo_spawner(),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;

                let session_id = cx
                    .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                    .block_task()
                    .await?
                    .session_id;

                let content = vec![acp::schema::v1::ContentBlock::Text(
                    acp::schema::v1::TextContent::new("go"),
                )];
                let request =
                    cx.send_request(acp::schema::v1::PromptRequest::new(session_id, content));
                // Cancel the specific in-flight session/prompt JSON-RPC request via the real
                // protocol-level $/cancel_request notification (distinct from session/cancel).
                request.cancel()?;

                let resp = request.block_task().await;
                // Cooperative cancellation: the handler may still finish with EndTurn if the
                // watcher loses the race, or return the standard cancellation error, or
                // (when the cancel_signal wins inside drain_agent_events) complete with
                // StopReason::Cancelled. All three are valid SDK-documented outcomes; the
                // assertion only rules out a hang or panic.
                match resp {
                    Ok(r) => {
                        assert!(matches!(
                            r.stop_reason,
                            acp::schema::v1::StopReason::EndTurn
                                | acp::schema::v1::StopReason::Cancelled
                        ));
                    }
                    Err(e) => {
                        assert_eq!(
                            i32::from(e.code),
                            -32800,
                            "expected request_cancelled error"
                        );
                    }
                }
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "cancel_request test failed: {result:?}");
                }
            }
        })
        .await;
}

// ── Cross-owner scoping at the stdio JSON-RPC layer (#5868) ──────────────────────────

/// Creates a fresh connection with the given `owner`, issues `session/new`, and disconnects.
/// Helper for the cross-owner tests below — a shared `sqlite_path` means the resulting session
/// persists with `owner` stamped as its `owner_key`.
async fn create_owned_session(
    sqlite_path: &str,
    owner: &str,
    workdir: &std::path::Path,
) -> acp::schema::v1::SessionId {
    let (sw, sr, cw, cr) = duplex_pair();
    let config = AcpServerConfig {
        sqlite_path: Some(sqlite_path.to_owned()),
        ..test_config("test-agent")
    };
    let server_fut = serve_connection(noop_spawner(), config, sw, sr, owner.to_owned());
    let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
        cx.send_request(acp::schema::v1::InitializeRequest::new(
            acp::schema::ProtocolVersion::LATEST,
        ))
        .block_task()
        .await?;
        let session_id = cx
            .send_request(acp::schema::v1::NewSessionRequest::new(workdir))
            .block_task()
            .await?
            .session_id;
        Ok(session_id)
    });
    tokio::select! {
        res = server_fut => panic!("server exited before client: {res:?}"),
        result = client_fut => result.expect("session/new failed"),
    }
}

/// `session/list` scopes persisted sessions to the calling connection's `owner_key`: a session
/// created by one connection's owner must not appear in a different owner's list, even when
/// both connections share the same `sqlite_path`.
#[tokio::test(flavor = "current_thread")]
async fn list_sessions_isolated_by_owner_across_stdio_connections() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-owner-list-test.db")
                .to_string_lossy()
                .into_owned();

            // Two distinct owners each create a session on the shared store, then disconnect.
            let alice_session = create_owned_session(&sqlite_path, "alice", workdir.path()).await;
            let bob_session = create_owned_session(&sqlite_path, "bob", workdir.path()).await;

            // A fresh connection as "alice" lists sessions: must see her own, not bob's.
            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut = serve_connection(noop_spawner(), config, sw, sr, "alice".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;
                let resp = cx
                    .send_request(acp::schema::v1::ListSessionsRequest::new())
                    .block_task()
                    .await?;
                let ids: Vec<&acp::schema::v1::SessionId> =
                    resp.sessions.iter().map(|s| &s.session_id).collect();
                assert!(
                    ids.contains(&&alice_session),
                    "alice's own session missing from her list: {ids:?}"
                );
                assert!(
                    !ids.contains(&&bob_session),
                    "bob's session leaked into alice's list: {ids:?}"
                );
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(result.is_ok(), "cross-owner list_sessions test failed: {result:?}");
                }
            }
        })
        .await;
}

/// `session/resume` on a session owned by a different connection must fail — a foreign
/// `owner_key` is indistinguishable from a nonexistent session id.
#[tokio::test(flavor = "current_thread")]
async fn resume_session_cross_owner_fails() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-owner-resume-test.db")
                .to_string_lossy()
                .into_owned();

            let session_id = {
                let (sw, sr, cw, cr) = duplex_pair();
                let config = AcpServerConfig {
                    sqlite_path: Some(sqlite_path.clone()),
                    ..test_config("test-agent")
                };
                let server_fut =
                    serve_connection(noop_spawner(), config, sw, sr, "alice".to_owned());
                let client_fut =
                    acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                        cx.send_request(acp::schema::v1::InitializeRequest::new(
                            acp::schema::ProtocolVersion::LATEST,
                        ))
                        .block_task()
                        .await?;
                        let session_id = cx
                            .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                            .block_task()
                            .await?
                            .session_id;
                        Ok(session_id)
                    });
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result.expect("session/new failed"),
                }
            };

            // A different owner ("bob") tries to resume alice's session on the same store.
            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut = serve_connection(echo_spawner(), config, sw, sr, "bob".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;
                cx.send_request(acp::schema::v1::ResumeSessionRequest::new(
                    session_id,
                    workdir.path(),
                ))
                .block_task()
                .await
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(
                        result.is_err(),
                        "bob must not be able to resume alice's session, got: {result:?}"
                    );
                }
            }
        })
        .await;
}

/// `session/load` on a session owned by a different connection must fail (mirrors
/// `resume_session_cross_owner_fails` for the `load_session` handler).
#[tokio::test(flavor = "current_thread")]
async fn load_session_cross_owner_fails() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-owner-load-test.db")
                .to_string_lossy()
                .into_owned();

            let session_id = {
                let (sw, sr, cw, cr) = duplex_pair();
                let config = AcpServerConfig {
                    sqlite_path: Some(sqlite_path.clone()),
                    ..test_config("test-agent")
                };
                let server_fut =
                    serve_connection(noop_spawner(), config, sw, sr, "alice".to_owned());
                let client_fut =
                    acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                        cx.send_request(acp::schema::v1::InitializeRequest::new(
                            acp::schema::ProtocolVersion::LATEST,
                        ))
                        .block_task()
                        .await?;
                        let session_id = cx
                            .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                            .block_task()
                            .await?
                            .session_id;
                        Ok(session_id)
                    });
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result.expect("session/new failed"),
                }
            };

            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut = serve_connection(echo_spawner(), config, sw, sr, "bob".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;
                cx.send_request(acp::schema::v1::LoadSessionRequest::new(
                    session_id,
                    workdir.path(),
                ))
                .block_task()
                .await
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(
                        result.is_err(),
                        "bob must not be able to load alice's session, got: {result:?}"
                    );
                }
            }
        })
        .await;
}

/// `session/delete` on a session owned by a different connection must not remove the
/// persisted row — mirrors `load_session_cross_owner_fails`/`resume_session_cross_owner_fails`
/// but for the delete path, at the ACP-protocol handler level (the underlying
/// `delete_acp_session_for_owner` SQL owner-scoping is already unit-tested in
/// `zeph-memory`; the HTTP CRUD transport has its own
/// `delete_session_cross_owner_returns_404_and_does_not_delete` — this is the missing
/// coverage for the `do_delete_session` ACP handler itself) (#6271).
#[tokio::test(flavor = "current_thread")]
async fn delete_session_cross_owner_fails() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-owner-delete-test.db")
                .to_string_lossy()
                .into_owned();

            let session_id = {
                let (sw, sr, cw, cr) = duplex_pair();
                let config = AcpServerConfig {
                    sqlite_path: Some(sqlite_path.clone()),
                    ..test_config("test-agent")
                };
                let server_fut =
                    serve_connection(noop_spawner(), config, sw, sr, "alice".to_owned());
                let client_fut =
                    acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                        cx.send_request(acp::schema::v1::InitializeRequest::new(
                            acp::schema::ProtocolVersion::LATEST,
                        ))
                        .block_task()
                        .await?;
                        let session_id = cx
                            .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                            .block_task()
                            .await?
                            .session_id;
                        Ok(session_id)
                    });
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result.expect("session/new failed"),
                }
            };

            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut = serve_connection(noop_spawner(), config, sw, sr, "bob".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;
                // Bob's request may return Ok (delete is a no-op for a foreign/nonexistent id,
                // same uniform non-distinguishing shape as `claim_acp_session_for_owner`) or
                // Err — either is acceptable here; what matters is verified below: alice's row
                // must survive.
                let _ = cx
                    .send_request(acp::schema::v1::DeleteSessionRequest::new(
                        session_id.clone(),
                    ))
                    .block_task()
                    .await;
                Ok(())
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    result.expect("bob's delete_session request errored unexpectedly");
                }
            }

            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .expect("SqliteStore::new");
            assert!(
                store
                    .acp_session_exists(&session_id.to_string())
                    .await
                    .expect("acp_session_exists query failed"),
                "bob must not be able to delete alice's session from the store"
            );
        })
        .await;
}

/// `session/fork` sourced from a session owned by a different connection must fail.
#[cfg(feature = "unstable-session-fork")]
#[tokio::test(flavor = "current_thread")]
async fn fork_session_cross_owner_fails() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let db_dir = tempfile::tempdir().expect("failed to create temp db dir");
            let sqlite_path = db_dir
                .path()
                .join("acp-owner-fork-test.db")
                .to_string_lossy()
                .into_owned();

            let session_id = {
                let (sw, sr, cw, cr) = duplex_pair();
                let config = AcpServerConfig {
                    sqlite_path: Some(sqlite_path.clone()),
                    ..test_config("test-agent")
                };
                let server_fut =
                    serve_connection(noop_spawner(), config, sw, sr, "alice".to_owned());
                let client_fut =
                    acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                        cx.send_request(acp::schema::v1::InitializeRequest::new(
                            acp::schema::ProtocolVersion::LATEST,
                        ))
                        .block_task()
                        .await?;
                        let session_id = cx
                            .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                            .block_task()
                            .await?
                            .session_id;
                        Ok(session_id)
                    });
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result.expect("session/new failed"),
                }
            };

            let (sw, sr, cw, cr) = duplex_pair();
            let config = AcpServerConfig {
                sqlite_path: Some(sqlite_path.clone()),
                ..test_config("test-agent")
            };
            let server_fut = serve_connection(noop_spawner(), config, sw, sr, "bob".to_owned());
            let client_fut = acp::Client.connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                cx.send_request(acp::schema::v1::InitializeRequest::new(
                    acp::schema::ProtocolVersion::LATEST,
                ))
                .block_task()
                .await?;
                cx.send_request(acp::schema::v1::ForkSessionRequest::new(
                    session_id,
                    workdir.path(),
                ))
                .block_task()
                .await
            });
            tokio::select! {
                res = server_fut => panic!("server exited before client: {res:?}"),
                result = client_fut => {
                    assert!(
                        result.is_err(),
                        "bob must not be able to fork alice's session, got: {result:?}"
                    );
                }
            }
        })
        .await;
}

/// #6656 regression: a permission-gated tool call must not deadlock the `session/prompt`
/// round-trip. Before the fix, `handle_prompt` awaited `do_prompt` inline inside the ACP SDK's
/// serial request-dispatch loop; the same loop demultiplexes the client's reply to the
/// `session/request_permission` request sent by `AcpPermissionGate::check_permission`, so the
/// loop deadlocked on itself. Wrapped in a timeout so a regression fails this test fast instead
/// of hanging the suite.
#[tokio::test(flavor = "current_thread")]
#[allow(clippy::large_futures)]
async fn permission_gated_prompt_round_trip_does_not_deadlock() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let (decision_tx, mut decision_rx) = tokio::sync::mpsc::unbounded_channel::<bool>();
            let server_fut = serve_connection(
                permission_gated_spawner(decision_tx),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client
                .builder()
                .on_receive_request(
                    async |_req: acp::schema::v1::RequestPermissionRequest,
                           responder: acp::Responder<
                        acp::schema::v1::RequestPermissionResponse,
                    >,
                           _cx| {
                        responder.respond(acp::schema::v1::RequestPermissionResponse::new(
                            acp::schema::v1::RequestPermissionOutcome::Selected(
                                acp::schema::v1::SelectedPermissionOutcome::new("allow_once"),
                            ),
                        ))
                    },
                    acp::on_receive_request!(),
                )
                .connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                    cx.send_request(acp::schema::v1::InitializeRequest::new(
                        acp::schema::ProtocolVersion::LATEST,
                    ))
                    .block_task()
                    .await?;

                    let session_id = cx
                        .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                        .block_task()
                        .await?
                        .session_id;

                    let content = vec![acp::schema::v1::ContentBlock::Text(
                        acp::schema::v1::TextContent::new("run a gated tool"),
                    )];
                    let resp = cx
                        .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                        .block_task()
                        .await?;

                    assert_eq!(
                        resp.stop_reason,
                        acp::schema::v1::StopReason::EndTurn,
                        "expected EndTurn, got {:?}",
                        resp.stop_reason,
                    );
                    Ok(())
                });

            let outcome = tokio::time::timeout(std::time::Duration::from_secs(10), async {
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result,
                }
            })
            .await;

            let result = outcome.expect(
                "permission-gated prompt round-trip timed out — likely a #6656 deadlock regression",
            );
            assert!(result.is_ok(), "prompt round-trip failed: {result:?}");

            let decision = decision_rx
                .recv()
                .await
                .expect("spawner must report a permission decision");
            assert!(
                decision,
                "IDE selected allow_once, expected the gate to allow"
            );
        })
        .await;
}

/// #6656 regression, denial path: same round-trip as
/// `permission_gated_prompt_round_trip_does_not_deadlock`, but the IDE rejects the tool call.
/// Confirms fail-closed behavior still completes correctly through the new `cx.spawn`-based
/// dispatch path instead of also deadlocking.
#[tokio::test(flavor = "current_thread")]
#[allow(clippy::large_futures)]
async fn permission_gated_prompt_denial_does_not_deadlock() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let workdir = temp_workdir();
            let (sw, sr, cw, cr) = duplex_pair();
            let (decision_tx, mut decision_rx) = tokio::sync::mpsc::unbounded_channel::<bool>();
            let server_fut = serve_connection(
                permission_gated_spawner(decision_tx),
                test_config("test-agent"),
                sw,
                sr,
                "acp-local".to_owned(),
            );
            let client_fut = acp::Client
                .builder()
                .on_receive_request(
                    async |_req: acp::schema::v1::RequestPermissionRequest,
                           responder: acp::Responder<
                        acp::schema::v1::RequestPermissionResponse,
                    >,
                           _cx| {
                        responder.respond(acp::schema::v1::RequestPermissionResponse::new(
                            acp::schema::v1::RequestPermissionOutcome::Selected(
                                acp::schema::v1::SelectedPermissionOutcome::new("reject_once"),
                            ),
                        ))
                    },
                    acp::on_receive_request!(),
                )
                .connect_with(acp::ByteStreams::new(cw, cr), async |cx| {
                    cx.send_request(acp::schema::v1::InitializeRequest::new(
                        acp::schema::ProtocolVersion::LATEST,
                    ))
                    .block_task()
                    .await?;

                    let session_id = cx
                        .send_request(acp::schema::v1::NewSessionRequest::new(workdir.path()))
                        .block_task()
                        .await?
                        .session_id;

                    let content = vec![acp::schema::v1::ContentBlock::Text(
                        acp::schema::v1::TextContent::new("run a gated tool"),
                    )];
                    let resp = cx
                        .send_request(acp::schema::v1::PromptRequest::new(session_id, content))
                        .block_task()
                        .await?;

                    assert_eq!(
                        resp.stop_reason,
                        acp::schema::v1::StopReason::EndTurn,
                        "expected EndTurn, got {:?}",
                        resp.stop_reason,
                    );
                    Ok(())
                });

            let outcome = tokio::time::timeout(std::time::Duration::from_secs(10), async {
                tokio::select! {
                    res = server_fut => panic!("server exited before client: {res:?}"),
                    result = client_fut => result,
                }
            })
            .await;

            let result = outcome.expect(
                "permission-gated prompt round-trip timed out — likely a #6656 deadlock regression",
            );
            assert!(result.is_ok(), "prompt round-trip failed: {result:?}");

            let decision = decision_rx
                .recv()
                .await
                .expect("spawner must report a permission decision");
            assert!(
                !decision,
                "IDE selected reject_once, expected the gate to deny"
            );
        })
        .await;
}