harn-serve 0.10.122

Shared outbound workflow server core for Harn adapters
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
use super::event_log_barrier::ResetActiveEventLog;
use super::*;
use harn_vm::event_log::EventLog as _;
use harn_vm::orchestration::{save_run_record, RunRecord, RunTraceSpanRecord};
use harn_vm::session_timeline::SESSION_TIMELINE_SCHEMA_VERSION;

mod typed_observability;

async fn run_prompt_with_project_capability(
    request_tx: &mpsc::UnboundedSender<serde_json::Value>,
    response_rx: &mut mpsc::UnboundedReceiver<String>,
    session_id: &str,
    id: i64,
    prompt_text: &str,
    project_read_capability: bool,
) -> String {
    request_tx
        .send(serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "session/prompt",
            "params": {
                "sessionId": session_id,
                "prompt": [{"type": "text", "text": prompt_text}],
            },
        }))
        .expect("send session/prompt");

    let host_capabilities = if project_read_capability {
        serde_json::json!({"project": ["read_file"]})
    } else {
        serde_json::json!({})
    };
    let mut output = String::new();
    let mut saw_completed = false;
    for _ in 0..64 {
        let message = recv_json(response_rx).await;
        match message.get("method").and_then(|value| value.as_str()) {
            Some("host/capabilities") => {
                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": message["id"].clone(),
                        "result": host_capabilities.clone(),
                    }))
                    .expect("send host/capabilities response");
            }
            Some("session/update")
                if message["params"]["update"]["sessionUpdate"] == "agent_message_chunk" =>
            {
                let content = &message["params"]["update"]["content"];
                let text = content["text"].as_str().expect("chunk text");
                let visible_delta = content["_meta"]["harn"]["visible_delta"]
                    .as_str()
                    .expect("visible_delta");
                assert!(
                    !visible_delta.contains(if prompt_text == "one" { "two" } else { "one" }),
                    "each prompt turn gets a fresh bridge visible-text state"
                );
                output.push_str(text);
            }
            _ if message["id"] == id => {
                assert_eq!(message["result"]["stopReason"], "end_turn");
                saw_completed = true;
                break;
            }
            _ => {}
        }
    }
    assert!(saw_completed, "prompt {id} should complete successfully");
    output
}

async fn run_json_prompt(
    request_tx: &mpsc::UnboundedSender<serde_json::Value>,
    response_rx: &mut mpsc::UnboundedReceiver<String>,
    session_id: &str,
    id: i64,
    prompt_text: &str,
) -> serde_json::Value {
    request_tx
        .send(serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "session/prompt",
            "params": {
                "sessionId": session_id,
                "prompt": [{"type": "text", "text": prompt_text}],
            },
        }))
        .expect("send session/prompt");

    let mut output = String::new();
    for _ in 0..64 {
        let message = recv_json(response_rx).await;
        match message.get("method").and_then(|value| value.as_str()) {
            Some("host/capabilities") => {
                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": message["id"].clone(),
                        "result": {},
                    }))
                    .expect("send host/capabilities response");
            }
            Some("session/update")
                if message["params"]["update"]["sessionUpdate"] == "agent_message_chunk" =>
            {
                if let Some(text) = message["params"]["update"]["content"]["text"].as_str() {
                    output.push_str(text);
                }
            }
            _ if message["id"] == id => {
                assert_eq!(message["result"]["stopReason"], "end_turn");
                return serde_json::from_str(output.trim()).expect("prompt JSON output");
            }
            _ => {}
        }
    }
    panic!("prompt {id} did not complete")
}

async fn recv_response_with_id(
    response_rx: &mut mpsc::UnboundedReceiver<String>,
    id: u64,
) -> serde_json::Value {
    for _ in 0..32 {
        let message = recv_json(response_rx).await;
        if message["id"].as_u64() == Some(id) {
            return message;
        }
    }
    panic!("timed out waiting for response {id}");
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_timeline_query_and_subscribe_use_event_log() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let _reset = ResetActiveEventLog;
            let log = harn_vm::event_log::install_memory_for_current_thread(16);
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session().await;
            let topic = harn_vm::session_timeline::agent_events_topic(&session_id);

            log.append(
                &topic,
                harn_vm::event_log::LogEvent::new(
                    "tool_call",
                    serde_json::json!({
                        "session_id": session_id.clone(),
                        "event": {
                            "type": "tool_call",
                            "session_id": session_id.clone(),
                            "tool_call_id": "tool-1",
                            "tool_name": "read",
                            "status": "pending",
                            "raw_input": {"authorization": "should-redact"}
                        }
                    }),
                )
                .with_headers(BTreeMap::from([(
                    "session_id".to_string(),
                    session_id.clone(),
                )])),
            )
            .await
            .unwrap();

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 20,
                    "method": harn_vm::session_timeline::SESSION_TIMELINE_QUERY_METHOD,
                    "params": {"sessionId": session_id.clone()},
                }))
                .expect("send timeline query");
            let snapshot = recv_json(&mut response_rx).await;
            assert_eq!(snapshot["id"], 20);
            assert_eq!(
                snapshot["result"]["schemaVersion"],
                SESSION_TIMELINE_SCHEMA_VERSION
            );
            let expected_coverage =
                serde_json::json!({"returned": 1, "available": 1, "truncated": false});
            assert_eq!(snapshot["result"]["coverage"], expected_coverage);
            assert_eq!(snapshot["result"]["nodes"][0]["category"], "agent_event");
            assert_eq!(
                snapshot["result"]["nodes"][0]["attributes"]["event"]["raw_input"]["authorization"],
                serde_json::json!(harn_vm::redact::REDACTED_PLACEHOLDER)
            );

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 24,
                    "method": harn_vm::orchestration::SESSION_VIEW_QUERY_METHOD,
                    "params": {"sessionId": session_id.clone()},
                }))
                .expect("send session view query");
            let session_view = recv_json(&mut response_rx).await;
            assert_eq!(session_view["id"], 24);
            assert_eq!(session_view["result"]["schema"], "harn.session_view.v1");
            assert_eq!(session_view["result"]["session"]["session_id"], session_id);
            assert_eq!(session_view["result"]["session"]["last_event_id"], 1);
            assert!(session_view["result"]["projection"]["projection_hash"]
                .as_str()
                .unwrap()
                .starts_with("sha256:"));

            let temp = tempfile::tempdir().unwrap();
            let run_path = temp.path().join("timeline-run.json");
            save_run_record(
                &RunRecord {
                    id: "timeline-run".to_string(),
                    trace_spans: vec![
                        RunTraceSpanRecord {
                            trace_id: "trace-acp".to_string(),
                            span_id: 1,
                            kind: "pipeline".to_string(),
                            name: "root".to_string(),
                            start_ms: 1,
                            duration_ms: 2,
                            metadata: BTreeMap::from([(
                                "session_id".to_string(),
                                serde_json::json!(session_id.clone()),
                            )]),
                            ..RunTraceSpanRecord::default()
                        },
                        RunTraceSpanRecord {
                            trace_id: "trace-acp".to_string(),
                            span_id: 2,
                            parent_id: Some(1),
                            kind: "tool_call".to_string(),
                            name: "child".to_string(),
                            start_ms: 2,
                            duration_ms: 3,
                            metadata: BTreeMap::from([(
                                "session_id".to_string(),
                                serde_json::json!(session_id.clone()),
                            )]),
                            ..RunTraceSpanRecord::default()
                        },
                    ],
                    ..RunRecord::default()
                },
                Some(run_path.to_str().unwrap()),
            )
            .unwrap();
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 23,
                    "method": harn_vm::session_timeline::SESSION_TIMELINE_QUERY_METHOD,
                    "params": {
                        "sessionId": session_id.clone(),
                        "runId": "timeline-run",
                        "runPath": run_path.display().to_string(),
                    },
                }))
                .expect("send timeline run query");
            let run_snapshot = recv_json(&mut response_rx).await;
            assert_eq!(run_snapshot["id"], 23);
            let root = run_snapshot["result"]["nodes"]
                .as_array()
                .unwrap()
                .iter()
                .find(|node| node["id"] == "span:trace-acp:1")
                .expect("timeline root span");
            assert_eq!(root["children"][0], "span:trace-acp:2");

            let from_cursor = serde_json::json!({
                "topics": BTreeMap::from([(topic.as_str().to_string(), 1_u64)]),
            });
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 21,
                    "method": harn_vm::session_timeline::SESSION_TIMELINE_SUBSCRIBE_METHOD,
                    "params": {
                        "sessionId": session_id.clone(),
                        "subscriptionId": "timeline-test",
                        "fromCursor": from_cursor,
                    },
                }))
                .expect("send timeline subscribe");
            let subscribed = recv_json(&mut response_rx).await;
            assert_eq!(subscribed["id"], 21);
            assert_eq!(subscribed["result"]["subscriptionId"], "timeline-test");

            log.append(
                &topic,
                harn_vm::event_log::LogEvent::new(
                    "agent_message_chunk",
                    serde_json::json!({
                        "session_id": session_id.clone(),
                        "event": {
                            "type": "agent_message_chunk",
                            "session_id": session_id.clone(),
                            "content": "hello"
                        }
                    }),
                )
                .with_headers(BTreeMap::from([(
                    "session_id".to_string(),
                    session_id.clone(),
                )])),
            )
            .await
            .unwrap();
            let update = recv_json(&mut response_rx).await;
            assert_eq!(
                update["method"],
                harn_vm::session_timeline::SESSION_TIMELINE_UPDATE_METHOD
            );
            assert_eq!(update["params"]["subscriptionId"], "timeline-test");
            assert_eq!(
                update["params"]["update"]["node"]["name"],
                "agent_message_chunk"
            );

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 22,
                    "method": harn_vm::session_timeline::SESSION_TIMELINE_UNSUBSCRIBE_METHOD,
                    "params": {"subscriptionId": "timeline-test"},
                }))
                .expect("send timeline unsubscribe");
            let unsubscribed = recv_json(&mut response_rx).await;
            assert_eq!(unsubscribed["id"], 22);
            assert_eq!(unsubscribed["result"]["removed"], true);

            drop(request_tx);
            server.await.unwrap();
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_server_handles_session_flow_and_prompt_updates() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, request_rx) = mpsc::unbounded_channel();
            let (response_tx, mut response_rx) = mpsc::unbounded_channel();
            let server = tokio::task::spawn_local(super::run_acp_channel_server(
                AcpServerConfig::new(None),
                request_rx,
                response_tx,
            ));

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "initialize",
                }))
                .expect("send initialize");
            let initialize = recv_json(&mut response_rx).await;
            assert_eq!(initialize["id"], 1);
            assert_eq!(initialize["result"]["agentInfo"]["name"], "harn");
            // A file-less attach server still advertises the spec-conformant local
            // "none" method so `initialize` passes the ACP registry auth gate.
            assert_eq!(
                initialize["result"]["authMethods"],
                serde_json::json!([{
                    "id": "none",
                    "type": "agent",
                    "name": "Local (no authentication)",
                    "description": "Connect without credentials. The agent runs locally and accepts the session as an anonymous principal.",
                    "_meta": {
                        "harn": {
                            "scheme": "none",
                            "challenge": { "type": "none" }
                        }
                    }
                }])
            );
            assert_eq!(
                initialize["result"]["agentCapabilities"]["loadSession"],
                true
            );
            assert_eq!(
                initialize["result"]["agentCapabilities"]["sessionCapabilities"],
                serde_json::json!({
                    "close": {},
                    "list": {},
                    "resume": {},
                    "rollback": {},
                    "redo": {},
                    "restoreToolCall": {},
                    "cancelToolCall": {},
                })
            );
            assert!(
                initialize["result"]["agentCapabilities"]["sessionCapabilities"]
                    .get("fork")
                    .is_none(),
                "initialize must not advertise Harn-only session/fork as an ACP SessionCapability"
            );
            assert_eq!(
                initialize["result"]["agentCapabilities"]["mcpCapabilities"],
                serde_json::json!({
                    "http": true,
                    "sse": true,
                })
            );
            assert!(
                initialize["result"]["agentCapabilities"]["promptCapabilities"]["image"]
                    .is_boolean()
            );
            assert!(
                initialize["result"]["agentCapabilities"]["promptCapabilities"]["audio"]
                    .is_boolean()
            );
            assert!(
                initialize["result"]["agentCapabilities"]["promptCapabilities"]["embeddedContext"]
                    .is_boolean()
            );
            let harn_capabilities = &initialize["result"]["agentCapabilities"]["_meta"]["harn"];
            assert_eq!(harn_capabilities["schemaCompatibility"], ACP_SCHEMA_COMPATIBILITY);
            assert_eq!(
                harn_capabilities["extensionContract"],
                "https://harnlang.com/spec/harn-extensions/v1"
            );
            assert_eq!(
                harn_capabilities["sessionUpdateExtensions"],
                serde_json::json!(HARN_SESSION_UPDATE_EXTENSIONS)
            );
            let agent_event_method =
                &harn_capabilities["extensionMethods"][HARN_AGENT_EVENT_METHOD];
            assert!(
                agent_event_method.is_object(),
                "agent capabilities must advertise the {HARN_AGENT_EVENT_METHOD} \
                     ExtNotification method for clients that support it; got: {agent_event_method}"
            );
            assert_eq!(
                agent_event_method["kinds"],
                serde_json::json!(HARN_AGENT_EVENT_KINDS),
                "advertised kinds must match the canonical HARN_AGENT_EVENT_KINDS list"
            );
            assert_eq!(
                harn_capabilities["toolLifecycleExtensionFields"],
                serde_json::json!(HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS)
            );
            super::super::staged_writes::assert_capabilities(harn_capabilities);

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/new",
                    "params": {"cwd": "."},
                }))
                .expect("send session/new");
            let created = recv_json(&mut response_rx).await;
            let session_id = created["result"]["sessionId"]
                .as_str()
                .expect("session id")
                .to_string();

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "session/load",
                    "params": {"sessionId": session_id},
                }))
                .expect("send session/load");
            let loaded = recv_json(&mut response_rx).await;
            assert_eq!(loaded["result"]["session"]["sessionId"], session_id);

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 4,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [{"type": "text", "text": "harness.stdio.println(\"hello from acp\")"}],
                    },
                }))
                .expect("send session/prompt");

            let mut saw_update = false;
            let mut saw_completed = false;
            for _ in 0..16 {
                let message = recv_json(&mut response_rx).await;
                if message["method"] == "host/capabilities" {
                    request_tx
                        .send(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": message["id"].clone(),
                            "result": {},
                        }))
                        .expect("send host capabilities response");
                }
                if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "agent_message_chunk"
                {
                    assert_eq!(
                        message["params"]["update"]["content"]["_meta"]["harn"]["visible_delta"],
                        "hello from acp"
                    );
                    assert!(message["params"]["update"]["content"]
                        .get("visible_delta")
                        .is_none());
                    saw_update = true;
                }
                if message["id"] == 4 {
                    assert_eq!(message["result"]["stopReason"], "end_turn");
                    saw_completed = true;
                    break;
                }
            }
            assert!(saw_update, "prompt should emit session/update text");
            assert!(saw_completed, "prompt should finish successfully");

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_list_filters_by_workspace_anchor_and_cwd() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let primary = dir.path().join("project");
            let sibling = dir.path().join("project-tools");
            std::fs::create_dir_all(&primary).expect("primary dir");
            std::fs::create_dir_all(&sibling).expect("sibling dir");

            let (request_tx, request_rx) = mpsc::unbounded_channel();
            let (response_tx, mut response_rx) = mpsc::unbounded_channel();
            let server = tokio::task::spawn_local(super::run_acp_channel_server(
                AcpServerConfig::new(None),
                request_rx,
                response_tx,
            ));

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "session/new",
                    "params": {"cwd": primary.display().to_string()},
                }))
                .expect("send first session/new");
            let first = recv_json(&mut response_rx).await;
            let first_id = first["result"]["sessionId"]
                .as_str()
                .expect("first session id")
                .to_string();
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/new",
                    "params": {"cwd": sibling.display().to_string()},
                }))
                .expect("send second session/new");
            let second = recv_json(&mut response_rx).await;
            let second_id = second["result"]["sessionId"]
                .as_str()
                .expect("second session id")
                .to_string();

            harn_vm::agent_sessions::set_workspace_anchor(
                &first_id,
                Some(harn_vm::workspace_anchor::WorkspaceAnchor {
                    primary: primary.clone(),
                    additional_roots: Vec::new(),
                    anchored_at: "2026-05-25T00:00:00Z".to_string(),
                }),
            )
            .expect("set first anchor");
            harn_vm::agent_sessions::set_workspace_anchor(
                &second_id,
                Some(harn_vm::workspace_anchor::WorkspaceAnchor {
                    primary: sibling.clone(),
                    additional_roots: Vec::new(),
                    anchored_at: "2026-05-25T00:00:00Z".to_string(),
                }),
            )
            .expect("set second anchor");

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "session/list",
                    "params": {
                        "workspaceAnchor": {"primary": primary.display().to_string()},
                    },
                }))
                .expect("send anchored session/list");
            let anchored = recv_json(&mut response_rx).await;
            assert_eq!(
                anchored["result"]["sessions"]
                    .as_array()
                    .expect("anchored sessions")
                    .len(),
                1
            );
            assert_eq!(
                anchored["result"]["sessions"][0]["sessionId"],
                serde_json::json!(first_id)
            );
            assert_eq!(
                anchored["result"]["sessions"][0]["workspaceAnchor"]["primary"],
                serde_json::json!(primary.display().to_string())
            );
            assert_eq!(
                anchored["result"]["sessions"][0]["_meta"]["harn"]["liveState"],
                serde_json::json!("live")
            );

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 4,
                    "method": "session/list",
                    "params": {"cwd": sibling.display().to_string()},
                }))
                .expect("send cwd session/list");
            let by_cwd = recv_json(&mut response_rx).await;
            assert_eq!(
                by_cwd["result"]["sessions"][0]["sessionId"],
                serde_json::json!(second_id)
            );

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 5,
                    "method": "session/load",
                    "params": {"sessionId": first_id},
                }))
                .expect("send session/load");
            let loaded = recv_json(&mut response_rx).await;
            assert_eq!(
                loaded["result"]["session"]["_meta"]["harn"]["workspaceAnchor"]["primary"],
                serde_json::json!(primary.display().to_string())
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_harn_workspace_anchor_methods_mutate_live_session() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            harn_vm::reset_thread_local_state();
            let dir = tempfile::tempdir().expect("tempdir");
            let primary = dir.path().join("project");
            let sibling = dir.path().join("project-tools");
            let target = dir.path().join("target");
            std::fs::create_dir_all(&primary).expect("primary dir");
            std::fs::create_dir_all(&sibling).expect("sibling dir");
            std::fs::create_dir_all(&target).expect("target dir");
            let canonical_sibling = sibling.canonicalize().expect("canonical sibling");

            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session_with_config(
                    AcpServerConfig::new(None),
                    serde_json::json!(primary.display().to_string()),
                )
                .await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "harn.session_workspace_roots",
                    "params": {"sessionId": session_id},
                }))
                .expect("send roots request");
            let roots = recv_response_with_id(&mut response_rx, 2).await;
            assert_eq!(
                roots["result"]["workspaceAnchor"]["primary"],
                serde_json::json!(primary.display().to_string())
            );
            assert_eq!(
                harn_vm::agent_sessions::workspace_anchor(&session_id)
                    .expect("live anchor")
                    .primary,
                primary
            );

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "harn.session_add_root",
                    "params": {
                        "sessionId": session_id,
                        "path": sibling.display().to_string(),
                        "mountMode": "extend",
                    },
                }))
                .expect("send add-root request");
            let added = recv_response_with_id(&mut response_rx, 3).await;
            let additional = added["result"]["workspaceAnchor"]["additional_roots"]
                .as_array()
                .expect("additional roots");
            assert_eq!(additional.len(), 1);
            assert_eq!(
                additional[0]["path"],
                serde_json::json!(canonical_sibling.display().to_string())
            );
            assert_eq!(additional[0]["mount_mode"], serde_json::json!("extend"));

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 4,
                    "method": "harn.session_reanchor",
                    "params": {
                        "sessionId": session_id,
                        "path": target.display().to_string(),
                        "reason": "test reanchor",
                    },
                }))
                .expect("send reanchor request");
            let reanchored = recv_response_with_id(&mut response_rx, 4).await;
            assert_eq!(reanchored["result"]["changed"], serde_json::json!(true));
            assert_eq!(
                reanchored["result"]["previousWorkspaceAnchor"]["primary"],
                serde_json::json!(primary.display().to_string())
            );
            assert_eq!(
                reanchored["result"]["workspaceAnchor"]["primary"],
                serde_json::json!(target.display().to_string())
            );

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 5,
                    "method": "session/list",
                    "params": {
                        "workspaceAnchor": {"primary": target.display().to_string()},
                    },
                }))
                .expect("send filtered session/list");
            let listed = recv_response_with_id(&mut response_rx, 5).await;
            assert_eq!(
                listed["result"]["sessions"][0]["sessionId"],
                serde_json::json!(session_id)
            );
            assert_eq!(
                listed["result"]["sessions"][0]["workspaceAnchor"]["primary"],
                serde_json::json!(target.display().to_string())
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_harn_session_reanchor_seeds_missing_anchor_from_live_cwd() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            harn_vm::reset_thread_local_state();
            let dir = tempfile::tempdir().expect("tempdir");
            let primary = dir.path().join("project");
            let target = dir.path().join("target");
            std::fs::create_dir_all(&primary).expect("primary dir");
            std::fs::create_dir_all(&target).expect("target dir");

            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session_with_config(
                    AcpServerConfig::new(None),
                    serde_json::json!(primary.display().to_string()),
                )
                .await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "harn.session_reanchor",
                    "params": {
                        "sessionId": session_id,
                        "path": target.display().to_string(),
                    },
                }))
                .expect("send reanchor request");
            let reanchored = recv_response_with_id(&mut response_rx, 2).await;
            assert_eq!(
                reanchored["result"]["previousWorkspaceAnchor"]["primary"],
                serde_json::json!(primary.display().to_string())
            );
            assert_eq!(
                reanchored["result"]["workspaceAnchor"]["primary"],
                serde_json::json!(target.display().to_string())
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_truncate_mutates_current_session_and_notifies_client() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            harn_vm::reset_thread_local_state();
            let (request_tx, mut response_rx, server, session_id) = start_acp_code_session().await;

            let first = run_json_prompt(
                &request_tx,
                &mut response_rx,
                &session_id,
                2,
                r#"
const sid = harness.agent.current_id()
guard sid != nil else { throw "missing session id" }
harness.agent.session_record_assistant(sid, {text: "alpha"})
const messages = harness.agent.session_messages(sid)
harness.stdio.println(json_stringify({len: len(messages), messages: messages}))
"#,
            )
            .await;
            assert_eq!(first["len"], 1);
            let second = run_json_prompt(
                &request_tx,
                &mut response_rx,
                &session_id,
                3,
                r#"
const sid = harness.agent.current_id()
guard sid != nil else { throw "missing session id" }
harness.agent.session_record_assistant(sid, {text: "beta"})
const messages = harness.agent.session_messages(sid)
harness.stdio.println(json_stringify({len: len(messages), messages: messages}))
"#,
            )
            .await;
            assert_eq!(second["len"], 2);

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 4,
                    "method": "session/truncate",
                    "params": {
                        "sessionId": session_id.clone(),
                        "keepFirst": 1,
                        "reason": "user_edit",
                    },
                }))
                .expect("send session/truncate");

            let mut response = None;
            let mut notification = None;
            for _ in 0..4 {
                let message = recv_json(&mut response_rx).await;
                if message["id"] == 4 {
                    response = Some(message);
                } else if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "session_truncated"
                {
                    notification = Some(message);
                }
                if response.is_some() && notification.is_some() {
                    break;
                }
            }
            let response = response.expect("truncate response");
            assert_eq!(response["result"]["sessionId"], session_id);
            assert_eq!(response["result"]["keptTurnCount"], 1);
            assert_eq!(response["result"]["removedTurnCount"], 1);
            assert!(response["result"]["newTipTurnId"].is_string());

            let notification = notification.expect("session_truncated notification");
            assert_eq!(notification["params"]["sessionId"], session_id);
            assert_eq!(notification["params"]["update"]["keptTurnCount"], 1);
            assert_eq!(notification["params"]["update"]["removedTurnCount"], 1);
            assert_eq!(notification["params"]["update"]["reason"], "user_edit");

            let snapshot = run_json_prompt(
                &request_tx,
                &mut response_rx,
                &session_id,
                5,
                r#"
const sid = harness.agent.current_id()
guard sid != nil else { throw "missing session id" }
const messages = harness.agent.session_messages(sid)
harness.stdio.println(json_stringify({len: len(messages), messages: messages}))
"#,
            )
            .await;
            assert_eq!(snapshot["len"], 1);
            assert_eq!(snapshot["messages"][0]["content"], "alpha");

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_mcp_catalog_projects_allowlist_over_advertised_items() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            harn_vm::reset_thread_local_state();
            let (request_tx, mut response_rx, server, _session_id) =
                start_acp_channel_session().await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 7,
                    "method": "mcp/catalog",
                    "params": {
                        "allowlist": {
                            "schemaVersion": 1,
                            "defaultEnabled": true,
                            "items": [
                                {"server": "github", "kind": "tool", "name": "create_issue", "enabled": false}
                            ]
                        },
                        "advertised": {
                            "github": [
                                {"kind": "tool", "name": "create_issue"},
                                {"kind": "tool", "name": "list_issues"}
                            ]
                        }
                    },
                }))
                .expect("send mcp/catalog");

            let mut response = None;
            for _ in 0..6 {
                let message = recv_json(&mut response_rx).await;
                if message["id"] == 7 {
                    response = Some(message);
                    break;
                }
            }
            let response = response.expect("mcp/catalog response");
            let result = &response["result"];
            assert_eq!(result["schemaVersion"], 1);
            assert_eq!(result["defaultEnabled"], true);
            let github = &result["servers"][0];
            assert_eq!(github["name"], "github");
            // Items sorted by (kind, name): create_issue first, disabled by allowlist.
            assert_eq!(github["items"][0]["name"], "create_issue");
            assert_eq!(github["items"][0]["enabled"], false);
            assert_eq!(github["items"][1]["name"], "list_issues");
            assert_eq!(github["items"][1]["enabled"], true);

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_mcp_authorize_requires_url() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, _session_id) =
                start_acp_channel_session().await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 11,
                    "method": "mcp/authorize",
                    "params": {},
                }))
                .expect("send mcp/authorize");

            let mut response = None;
            for _ in 0..6 {
                let message = recv_json(&mut response_rx).await;
                if message["id"] == 11 {
                    response = Some(message);
                    break;
                }
            }
            let response = response.expect("mcp/authorize response");
            assert_eq!(response["error"]["code"], -32602);
            assert!(response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("url"));

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_mcp_oauth_callback_validates_and_rejects_unknown_state() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, _session_id) =
                start_acp_channel_session().await;

            // Missing state/code → invalid params.
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 12,
                    "method": "mcp/oauth_callback",
                    "params": {"code": "abc"},
                }))
                .expect("send mcp/oauth_callback");
            // Well-formed but no pending flow matches the state → -32000.
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 13,
                    "method": "mcp/oauth_callback",
                    "params": {"state": "no-such", "code": "abc"},
                }))
                .expect("send mcp/oauth_callback");

            let mut invalid = None;
            let mut unknown = None;
            for _ in 0..8 {
                let message = recv_json(&mut response_rx).await;
                if message["id"] == 12 {
                    invalid = Some(message);
                } else if message["id"] == 13 {
                    unknown = Some(message);
                }
                if invalid.is_some() && unknown.is_some() {
                    break;
                }
            }
            assert_eq!(invalid.expect("invalid response")["error"]["code"], -32602);
            let unknown = unknown.expect("unknown-state response");
            assert_eq!(unknown["error"]["code"], -32000);
            assert!(unknown["error"]["message"]
                .as_str()
                .unwrap()
                .contains("no pending MCP authorization"));

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_truncate_validates_inputs() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session().await;

            for (id, params, expected) in [
                (
                    2,
                    serde_json::json!({"sessionId": session_id.clone()}),
                    "Missing keepFirst",
                ),
                (
                    3,
                    serde_json::json!({"sessionId": session_id.clone(), "keepFirst": -1}),
                    "Invalid keepFirst: must be >= 0",
                ),
                (
                    4,
                    serde_json::json!({"sessionId": "missing-session", "keepFirst": 0}),
                    "Unknown session: missing-session",
                ),
            ] {
                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": id,
                        "method": "session/truncate",
                        "params": params,
                    }))
                    .expect("send session/truncate");
                let response = recv_json(&mut response_rx).await;
                assert_eq!(response["id"], id);
                assert_eq!(response["error"]["code"], -32602);
                assert_eq!(response["error"]["message"], expected);
            }

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_profile_json_appends_one_line_per_prompt_turn() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let profile_path = dir.path().join("profile.ndjson");
            let config = AcpServerConfig::new(None).with_profile(AcpProfileConfig {
                text: false,
                json_path: Some(profile_path.clone()),
            });
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session_with_config(config, serde_json::json!(dir.path())).await;

            for id in 2..=3 {
                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": id,
                        "method": "session/prompt",
                        "params": {
                            "sessionId": session_id.clone(),
                            "prompt": [{"type": "text", "text": "harness.stdio.println(\"profiled\")"}],
                        },
                    }))
                    .expect("send session/prompt");

                let mut saw_completed = false;
                for _ in 0..16 {
                    let message = recv_json(&mut response_rx).await;
                    if message["method"] == "host/capabilities" {
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send host capabilities response");
                    }
                    if message["id"] == id {
                        assert_eq!(message["result"]["stopReason"], "end_turn");
                        saw_completed = true;
                        break;
                    }
                }
                assert!(saw_completed, "prompt should finish successfully");
            }

            let lines = std::fs::read_to_string(&profile_path).expect("read profile ndjson");
            let entries = lines
                .lines()
                .map(|line| serde_json::from_str::<serde_json::Value>(line).expect("json line"))
                .collect::<Vec<_>>();
            assert_eq!(entries.len(), 2, "profile output:\n{lines}");
            assert_eq!(entries[0]["session_id"], session_id);
            assert_eq!(entries[0]["turn"], 1);
            assert_eq!(entries[1]["turn"], 2);
            assert!(entries[0]["rollup"]["by_kind"].is_array());

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_close_and_stop_alias_free_active_session() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, request_rx) = mpsc::unbounded_channel();
            let (response_tx, mut response_rx) = mpsc::unbounded_channel();
            let server = tokio::task::spawn_local(super::run_acp_channel_server(
                AcpServerConfig::new(None),
                request_rx,
                response_tx,
            ));

            for (index, method) in ["session/close", "session/stop"].into_iter().enumerate() {
                let request_base = 10 + (index as i64 * 10);
                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": request_base,
                        "method": "session/new",
                        "params": {"cwd": "."},
                    }))
                    .expect("send session/new");
                let created = recv_json(&mut response_rx).await;
                let session_id = created["result"]["sessionId"]
                    .as_str()
                    .expect("session id")
                    .to_string();
                assert!(harn_vm::agent_sessions::exists(&session_id));

                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": request_base + 1,
                        "method": method,
                        "params": {"sessionId": session_id},
                    }))
                    .expect("send session close request");
                let closed = recv_json(&mut response_rx).await;
                assert_eq!(closed["id"], request_base + 1);
                assert_eq!(closed["result"], serde_json::json!({}));
                assert!(
                    !harn_vm::agent_sessions::exists(&session_id),
                    "{method} should free VM session state"
                );

                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": request_base + 2,
                        "method": "session/list",
                        "params": {},
                    }))
                    .expect("send session/list");
                let listed = recv_json(&mut response_rx).await;
                let sessions = listed["result"]["sessions"].as_array().unwrap();
                assert!(
                    sessions
                        .iter()
                        .all(|entry| entry["sessionId"].as_str() != Some(session_id.as_str())),
                    "{method} should remove the active ACP session"
                );

                request_tx
                    .send(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": request_base + 3,
                        "method": "session/prompt",
                        "params": {
                            "sessionId": session_id,
                            "prompt": [{"type": "text", "text": "harness.stdio.println(\"closed\")"}],
                        },
                    }))
                    .expect("send session/prompt");
                let rejected = recv_json(&mut response_rx).await;
                assert_eq!(rejected["id"], request_base + 3);
                assert_eq!(rejected["error"]["code"], -32602);
            }

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_close_cancels_pending_host_bridge_call() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session().await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id.clone(),
                        "prompt": [{"type": "text", "text": "harness.stdio.println(\"after host capabilities\")"}],
                    },
                }))
                .expect("send session/prompt");

            let host_capabilities = recv_json(&mut response_rx).await;
            assert_eq!(host_capabilities["method"], "host/capabilities");
            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "session/close",
                    "params": {"sessionId": session_id.clone()},
                }))
                .expect("send session/close");

            let mut saw_cancelled_response = false;
            let mut saw_close_response = false;
            for _ in 0..8 {
                let message = recv_json(&mut response_rx).await;
                if message["id"] == 2 {
                    assert_eq!(message["result"]["stopReason"], "cancelled");
                    saw_cancelled_response = true;
                } else if message["id"] == 3 {
                    assert_eq!(message["result"], serde_json::json!({}));
                    assert!(!harn_vm::agent_sessions::exists(&session_id));
                    saw_close_response = true;
                    break;
                }
            }

            assert!(
                saw_cancelled_response,
                "prompt should observe close as cancellation"
            );
            assert!(saw_close_response, "session/close should free the session");

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_file_backed_pipeline_receives_explicit_harness_argument() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("harness.harn");
            std::fs::write(
                &pipeline_path,
                r#"
import { env_int } from "std/config"

pipeline default(harness: Harness, task: unknown) {
  harness.stdio.println(env_int(harness.env, "HARN_ACP_HARNESS_REGRESSION_UNSET", 7))
  harness.stdio.println("via-harness")
}"#,
            )
            .expect("write pipeline");

            let (request_tx, mut response_rx, server, session_id) =
                start_acp_code_session_with_config(
                    AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy().to_string()),
                    serde_json::json!(dir.path()),
                )
                .await;

            let output = run_prompt_with_project_capability(
                &request_tx,
                &mut response_rx,
                &session_id,
                3,
                "hello",
                false,
            )
            .await;
            assert_eq!(output, "7\nvia-harness\n");

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_file_backed_vm_baseline_keeps_prompt_turns_isolated() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("isolation.harn");
            let profile_path = dir.path().join("profile.ndjson");
            std::fs::write(
                &pipeline_path,
                r#"
pipeline default(harness: Harness, task: unknown) {
  const cell = harness.runtime.shared_cell({scope: "task_group", key: "turn", initial: prompt})
  harness.stdio.println(prompt)
  harness.stdio.println(harness.runtime.shared_get(cell))
  harness.runtime.shared_set(cell, "dirty")
  const held = harness.runtime.sync_gate_acquire("runner", 1)
  const blocked = harness.runtime.sync_gate_acquire("runner", 1, 0)
  harness.stdio.println(blocked == nil)
  harness.runtime.sync_release(held)
  const metrics = harness.runtime.sync_metrics("gate", "runner")
  harness.stdio.println(metrics.acquisition_count)
  harness.stdio.println(harness.runtime.host_has("project", "read_file"))
}"#,
            )
            .expect("write pipeline");
            let config =
                AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy().to_string())
                    .with_profile(AcpProfileConfig {
                        text: false,
                        json_path: Some(profile_path.clone()),
                    });
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_code_session_with_config(config, serde_json::json!(dir.path())).await;

            let first = run_prompt_with_project_capability(
                &request_tx,
                &mut response_rx,
                &session_id,
                3,
                "one",
                true,
            )
            .await;
            assert_eq!(first, "one\none\ntrue\n1\ntrue\n");

            let second = run_prompt_with_project_capability(
                &request_tx,
                &mut response_rx,
                &session_id,
                4,
                "two",
                false,
            )
            .await;
            assert_eq!(
                second, "two\ntwo\ntrue\n1\nfalse\n",
                "prompt globals, shared runtime state, sync metrics, and host capability cache must reset per turn"
            );

            let lines = std::fs::read_to_string(&profile_path).expect("read profile ndjson");
            let entries = lines
                .lines()
                .map(|line| serde_json::from_str::<serde_json::Value>(line).expect("json line"))
                .collect::<Vec<_>>();
            assert_eq!(entries.len(), 2, "profile output:\n{lines}");
            for entry in &entries {
                let buckets = entry["rollup"]["by_kind"]
                    .as_array()
                    .expect("profile kind buckets");
                assert!(
                    buckets
                        .iter()
                        .any(|bucket| bucket["kind"] == "vm_setup" && bucket["count"] == 1),
                    "ACP profile must expose vm_setup bucket: {entry}"
                );
            }

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_prompt_exposes_multimodal_prompt_messages() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("multimodal.harn");
            std::fs::write(
                &pipeline_path,
                r#"import { runtime_prompt_content } from "std/runtime"
pipeline default(harness: Harness, task: unknown) {
  harness.llm.mock_clear()
  harness.llm.mock_enqueue({text: "ok"})
  harness.llm.call("", nil, {provider: "mock", messages: [{role: "user", content: harness.runtime.prompt_content()}]})
  const blocks = harness.llm.mock_calls()[0].messages[0].content
  harness.stdio.println(blocks[0].text == "Please inspect this context.")
  harness.stdio.println(blocks[1].type == "image")
  harness.stdio.println(blocks[1].base64 == "iVBORw0KGgo=")
  harness.stdio.println(blocks[1].media_type == "image/png")
  harness.stdio.println(blocks[2].type == "audio")
  harness.stdio.println(blocks[2].base64 == "UklGRiQ=")
  harness.stdio.println(blocks[2].media_type == "audio/wav")
  harness.stdio.println(contains(blocks[3].text, "file:///tmp/example.txt"))
  harness.stdio.println(contains(blocks[3].text, "hello from embedded context"))
}"#,
            )
            .expect("write pipeline");

            let (request_tx, mut response_rx, server, session_id) =
                start_acp_code_session_with_config(
                    AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy().to_string()),
                    serde_json::json!(dir.path()),
                )
                .await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [
                            {"type": "text", "text": "Please inspect this context."},
                            {
                                "type": "image",
                                "mimeType": "image/png",
                                "data": "iVBORw0KGgo=",
                                "uri": "file:///tmp/pixel.png"
                            },
                            {
                                "type": "audio",
                                "mimeType": "audio/wav",
                                "data": "UklGRiQ="
                            },
                            {
                                "type": "resource",
                                "resource": {
                                    "uri": "file:///tmp/example.txt",
                                    "mimeType": "text/plain",
                                    "text": "hello from embedded context"
                                }
                            }
                        ],
                    },
                }))
                .expect("send session/prompt");

            let mut output = String::new();
            let mut saw_completed = false;
            for _ in 0..32 {
                let message = recv_json(&mut response_rx).await;
                if message["method"] == "host/capabilities" {
                    request_tx
                        .send(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": message["id"].clone(),
                            "result": {},
                        }))
                        .expect("send host capabilities response");
                    continue;
                }
                if message["method"] == "session/update"
                    && message["params"]["update"]["sessionUpdate"] == "agent_message_chunk"
                {
                    if let Some(text) = message["params"]["update"]["content"]["text"].as_str() {
                        output.push_str(text);
                    }
                }
                if message["id"] == 3 {
                    assert_eq!(message["result"]["stopReason"], "end_turn");
                    saw_completed = true;
                    break;
                }
            }
            assert!(saw_completed, "prompt should complete successfully");
            assert!(
                !output.contains("false"),
                "multimodal prompt assertions failed; output was:\n{output}"
            );
            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_prompt_surfaces_multimodal_capability_errors() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let dir = tempfile::tempdir().expect("tempdir");
            let pipeline_path = dir.path().join("unsupported_vision.harn");
            std::fs::write(
                &pipeline_path,
                r#"import { runtime_prompt_content } from "std/runtime"
pipeline default(harness: Harness, task: unknown) {
  harness.llm.call("", nil, {provider: "mock", model: "gpt-3.5-turbo", messages: [{role: "user", content: harness.runtime.prompt_content()}]})
}"#,
            )
            .expect("write pipeline");

            let (request_tx, mut response_rx, server, session_id) =
                start_acp_code_session_with_config(
                    AcpServerConfig::for_pipeline(pipeline_path.to_string_lossy().to_string()),
                    serde_json::json!(dir.path()),
                )
                .await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [
                            {"type": "text", "text": "caption"},
                            {
                                "type": "image",
                                "mimeType": "image/png",
                                "data": "iVBORw0KGgo="
                            }
                        ],
                    },
                }))
                .expect("send session/prompt");

            let mut saw_error = false;
            for _ in 0..24 {
                let message = recv_json(&mut response_rx).await;
                if message["method"] == "host/capabilities" {
                    request_tx
                        .send(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": message["id"].clone(),
                            "result": {},
                        }))
                        .expect("send host capabilities response");
                    continue;
                }
                if message["id"] == 3 {
                    let error = message["error"]["message"]
                        .as_str()
                        .expect("prompt error message");
                    assert!(
                        error.contains("option `vision` is not supported"),
                        "unexpected error: {error}"
                    );
                    saw_error = true;
                    break;
                }
            }
            assert!(saw_error, "prompt should return a capability error");
            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_bridge_routes_session_request_permission_response() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let server =
        AcpServer::new_with_output(AcpServerConfig::new(None), AcpOutput::Channel(tx.clone()));
    let bridge = Arc::new(AcpBridge {
        session_id: "session-1".to_string(),
        output: AcpOutput::Channel(tx),
        pending: server.pending.clone(),
        next_id_counter: AtomicU64::new(77),
        cancellation: SessionCancellation::default(),
        script_name: Mutex::new(String::new()),
        assistant_state: Mutex::new(VisibleTextState::default()),
    });

    let fixture: serde_json::Value = serde_json::from_str(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../conformance/protocols/fixtures/acp/session_request_permission.valid.json"
    )))
    .expect("permission fixture");
    let call = bridge.call_client(
        "session/request_permission",
        fixture["documents"][0]["params"].clone(),
    );
    tokio::pin!(call);

    let outgoing = tokio::select! {
        message = recv_json(&mut rx) => message,
        result = &mut call => panic!("permission call completed before host response: {result:?}"),
    };
    assert_eq!(outgoing["id"], 77);
    assert_eq!(outgoing["method"], "session/request_permission");

    let response = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 77,
        "result": {"outcome": {"outcome": "selected", "optionId": "allow"}},
    });
    crate::protocol_fixture_tests::assert_fixture_documents_match(
        "conformance/protocols/fixtures/acp/session_request_permission.valid.json",
        vec![outgoing, response.clone()],
    );

    let mut server = server;
    server.handle_incoming_message(response).await;
    let result = call.await.expect("permission response");
    assert_eq!(result["outcome"]["outcome"], "selected");
    assert_eq!(result["outcome"]["optionId"], "allow");
}

#[test]
fn prepared_session_prompt_preserves_queued_cancel() {
    let cancellation = SessionCancellation::default();
    cancellation.cancel();
    cancellation.begin_prompt();
    assert!(
        !cancellation.cancelled.load(Ordering::SeqCst),
        "stale cancellation should not leak into a later prompt"
    );

    cancellation.prepare_prompt();
    cancellation.cancel();
    cancellation.begin_prompt();
    assert!(
        cancellation.cancelled.load(Ordering::SeqCst),
        "cancellation observed after a prompt was routed must not be reset at prompt start"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_cancel_kills_active_terminal() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session().await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        // `run_command` shares ACP's terminal path with `exec`.
                        "prompt": [{"type": "text", "text": "run_command(\"sleep 999\")"}],
                    },
                }))
                .expect("send session/prompt");

            let terminal_id = "term-cancel-demo";
            let mut saw_wait = false;
            let mut saw_kill = false;
            let mut saw_release = false;
            let mut saw_cancelled_response = false;
            for _ in 0..24 {
                let message = recv_json(&mut response_rx).await;
                match message.get("method").and_then(|value| value.as_str()) {
                    Some("host/capabilities") => {
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send host capabilities response");
                    }
                    Some("terminal/create") => {
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {"terminalId": terminal_id},
                            }))
                            .expect("send terminal/create response");
                    }
                    Some("terminal/wait_for_exit") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_wait = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "method": "session/cancel",
                                "params": {"sessionId": session_id},
                            }))
                            .expect("send session/cancel");
                    }
                    Some("terminal/kill") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_kill = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send terminal/kill response");
                    }
                    Some("terminal/release") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_release = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send terminal/release response");
                    }
                    _ if message["id"] == 2 => {
                        assert_eq!(message["result"]["stopReason"], "cancelled");
                        saw_cancelled_response = true;
                        break;
                    }
                    _ => {}
                }
            }

            assert!(saw_wait, "prompt should block on terminal/wait_for_exit");
            assert!(saw_kill, "session/cancel should issue terminal/kill");
            assert!(
                saw_release,
                "cancelled terminal execution should still release the terminal"
            );
            assert!(
                saw_cancelled_response,
                "prompt should finish with stopReason=cancelled"
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_close_cancels_active_terminal_before_freeing_session() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session().await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id.clone(),
                        "prompt": [{"type": "text", "text": "run_command(\"sleep 999\")"}],
                    },
                }))
                .expect("send session/prompt");

            let terminal_id = "term-close-demo";
            let mut saw_wait = false;
            let mut saw_kill = false;
            let mut saw_release = false;
            let mut saw_cancelled_response = false;
            let mut saw_close_response = false;
            for _ in 0..32 {
                let message = recv_json(&mut response_rx).await;
                match message.get("method").and_then(|value| value.as_str()) {
                    Some("host/capabilities") => {
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send host capabilities response");
                    }
                    Some("terminal/create") => {
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {"terminalId": terminal_id},
                            }))
                            .expect("send terminal/create response");
                    }
                    Some("terminal/wait_for_exit") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_wait = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": 3,
                                "method": "session/close",
                                "params": {"sessionId": session_id.clone()},
                            }))
                            .expect("send session/close");
                    }
                    Some("terminal/kill") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_kill = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send terminal/kill response");
                    }
                    Some("terminal/release") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_release = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send terminal/release response");
                    }
                    _ if message["id"] == 2 => {
                        assert_eq!(message["result"]["stopReason"], "cancelled");
                        saw_cancelled_response = true;
                    }
                    _ if message["id"] == 3 => {
                        assert_eq!(message["result"], serde_json::json!({}));
                        assert!(!harn_vm::agent_sessions::exists(&session_id));
                        saw_close_response = true;
                        break;
                    }
                    _ => {}
                }
            }

            assert!(saw_wait, "prompt should block on terminal/wait_for_exit");
            assert!(saw_kill, "session/close should issue terminal/kill");
            assert!(
                saw_release,
                "closed terminal execution should still release the terminal"
            );
            assert!(
                saw_cancelled_response,
                "prompt should finish with stopReason=cancelled"
            );
            assert!(
                saw_close_response,
                "session/close should respond after cleanup"
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn acp_session_cancel_kills_terminal_created_during_cancel() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (request_tx, mut response_rx, server, session_id) =
                start_acp_channel_session().await;

            request_tx
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "session/prompt",
                    "params": {
                        "sessionId": session_id,
                        "prompt": [{"type": "text", "text": "run_command(\"sleep 999\")"}],
                    },
                }))
                .expect("send session/prompt");

            let terminal_id = "term-created-during-cancel";
            let mut saw_create = false;
            let mut saw_wait = false;
            let mut saw_kill = false;
            let mut saw_release = false;
            let mut saw_cancelled_response = false;
            for _ in 0..24 {
                let message = recv_json(&mut response_rx).await;
                match message.get("method").and_then(|value| value.as_str()) {
                    Some("host/capabilities") => {
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send host capabilities response");
                    }
                    Some("terminal/create") => {
                        saw_create = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "method": "session/cancel",
                                "params": {"sessionId": session_id},
                            }))
                            .expect("send session/cancel");
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {"terminalId": terminal_id},
                            }))
                            .expect("send terminal/create response");
                    }
                    Some("terminal/wait_for_exit") => {
                        saw_wait = true;
                    }
                    Some("terminal/kill") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_kill = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send terminal/kill response");
                    }
                    Some("terminal/release") => {
                        assert_eq!(message["params"]["terminalId"], terminal_id);
                        saw_release = true;
                        request_tx
                            .send(serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": message["id"].clone(),
                                "result": {},
                            }))
                            .expect("send terminal/release response");
                    }
                    _ if message["id"] == 2 => {
                        assert_eq!(message["result"]["stopReason"], "cancelled");
                        saw_cancelled_response = true;
                        break;
                    }
                    _ => {}
                }
            }

            assert!(saw_create, "prompt should request terminal/create");
            assert!(
                !saw_wait,
                "cancellation after terminal/create should not wait for process exit"
            );
            assert!(
                saw_kill,
                "created terminal should be killed when create races cancellation"
            );
            assert!(
                saw_release,
                "created terminal should be released when create races cancellation"
            );
            assert!(
                saw_cancelled_response,
                "prompt should finish with stopReason=cancelled"
            );

            drop(request_tx);
            server.await.expect("ACP channel server task");
        })
        .await;
}