claude-codes 2.1.117

A tightly typed Rust interface for the Claude Code JSON protocol
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
//! Integration tests for Claude CLI interactions
//!
//! These tests require a real Claude CLI installation and are only run
//! when the `integration-tests` feature is enabled.
//!
//! Run with: `cargo test --features integration-tests`

#![cfg(feature = "integration-tests")]

use claude_codes::io::ContentBlock;
use claude_codes::{AsyncClient, ClaudeCliBuilder, ClaudeInput, ClaudeOutput, SyncClient};
use uuid::Uuid;

/// Create an async client that works inside a Claude Code session
async fn async_client() -> AsyncClient {
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .spawn()
        .await
        .expect("Failed to spawn Claude");
    AsyncClient::new(child).expect("Failed to create async client")
}

/// Create a sync client that works inside a Claude Code session
fn sync_client() -> SyncClient {
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .spawn_sync()
        .expect("Failed to spawn Claude");
    SyncClient::new(child).expect("Failed to create sync client")
}

/// Test that we can check Claude CLI version
#[tokio::test]
async fn test_claude_cli_version() {
    use claude_codes::version::check_claude_version_async;

    // This just checks that Claude is installed and accessible
    check_claude_version_async()
        .await
        .expect("Failed to check Claude version");

    println!("Claude CLI version check passed");
}

/// Test basic async client connection and query
#[tokio::test]
async fn test_async_client_basic_query() {
    let mut client = async_client().await;

    // Query with a simple math question
    let mut stream = client
        .query_stream("What is 2 + 2? Reply with just the number.")
        .await
        .expect("Failed to send query");

    // Collect responses
    let mut found_answer = false;
    let mut message_count = 0;

    while let Some(result) = stream.next().await {
        match result {
            Ok(output) => {
                message_count += 1;
                // Check for assistant response containing "4"
                if let ClaudeOutput::Assistant(msg) = &output {
                    for content in &msg.message.content {
                        if let claude_codes::io::ContentBlock::Text(text) = content {
                            if text.text.contains("4") {
                                found_answer = true;
                            }
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                break;
            }
        }

        // Stop after finding answer or too many messages
        if found_answer || message_count > 10 {
            break;
        }
    }

    assert!(message_count > 0, "Should have received messages");
    assert!(found_answer, "Should have received answer '4'");
}

/// Test sync client with a simple query
#[test]
fn test_sync_client_basic_query() {
    let mut client = sync_client();

    // Build input
    let session_id = Uuid::new_v4();
    let input = ClaudeInput::user_message(
        "What is 10 divided by 2? Reply with just the number.",
        session_id,
    );

    // Send query and get responses
    let responses = client.query(input).expect("Failed to query");

    // Check responses
    let mut found_answer = false;
    for response in &responses {
        if let ClaudeOutput::Assistant(msg) = response {
            for content in &msg.message.content {
                if let claude_codes::io::ContentBlock::Text(text) = content {
                    if text.text.contains("5") {
                        found_answer = true;
                    }
                }
            }
        }
    }

    assert!(!responses.is_empty(), "Should have received responses");
    assert!(found_answer, "Should have received answer '5'");
}

/// Test async client with multiple queries in sequence
#[tokio::test]
async fn test_async_client_conversation() {
    let mut client = async_client().await;

    // First query
    let mut stream1 = client
        .query_stream("Remember the number 42. What number did I ask you to remember?")
        .await
        .expect("Failed to send first query");

    let mut found_42_first = false;
    while let Some(result) = stream1.next().await {
        if let Ok(ClaudeOutput::Assistant(msg)) = result {
            for content in &msg.message.content {
                if let claude_codes::io::ContentBlock::Text(text) = content {
                    if text.text.contains("42") {
                        found_42_first = true;
                    }
                }
            }
        }
    }

    assert!(
        found_42_first,
        "Should have received response mentioning 42"
    );

    // Second query in same session
    let mut stream2 = client
        .query_stream("What was that number again?")
        .await
        .expect("Failed to send second query");

    let mut found_42_second = false;
    while let Some(result) = stream2.next().await {
        if let Ok(ClaudeOutput::Assistant(msg)) = result {
            for content in &msg.message.content {
                if let claude_codes::io::ContentBlock::Text(text) = content {
                    if text.text.contains("42") {
                        found_42_second = true;
                    }
                }
            }
        }
    }

    assert!(
        found_42_second,
        "Should remember 42 from earlier in conversation"
    );
}

/// Test handling various message types
#[tokio::test]
async fn test_message_types() {
    let mut client = async_client().await;

    let mut stream = client
        .query_stream("Hello! Please respond briefly.")
        .await
        .expect("Failed to send query");

    let mut message_types = std::collections::HashSet::new();
    let mut count = 0;

    while let Some(result) = stream.next().await {
        if let Ok(output) = result {
            message_types.insert(output.message_type().to_string());
            count += 1;
        }

        // Stop after collecting several messages
        if count > 5 {
            break;
        }
    }

    // We should have received at least system and assistant messages
    assert!(count > 0, "Should have received messages");
    assert!(
        message_types.contains("system") || message_types.contains("assistant"),
        "Should have received system or assistant messages"
    );
}

/// Test with custom session ID using the builder
#[tokio::test]
async fn test_with_custom_session() {
    // Use a proper UUID for the session ID
    let session_uuid = Uuid::new_v4();

    let builder = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .session_id(session_uuid);

    let mut client = AsyncClient::from_builder(builder)
        .await
        .expect("Failed to create client with builder");

    let mut stream = client
        .query_stream("What is 1 + 1?")
        .await
        .expect("Failed to query");

    let mut received_response = false;
    let mut message_count = 0;

    while let Some(result) = stream.next().await {
        message_count += 1;
        if let Ok(ClaudeOutput::Assistant(_)) = result {
            received_response = true;
            break;
        }
        // Stop after too many messages to avoid infinite loop
        if message_count > 10 {
            break;
        }
    }

    assert!(received_response, "Should have received assistant response");
}

/// Test tool use - listing directory and file operations
#[tokio::test]
async fn test_tool_use_blocks() {
    let mut client = async_client().await;

    // Ask Claude to list the current directory
    let mut stream = client
        .query_stream("Please list the files in the current directory using ls")
        .await
        .expect("Failed to send query");

    let mut tool_use_blocks = Vec::new();
    let mut tool_result_blocks = Vec::new();
    let mut text_blocks = Vec::new();
    let mut thinking_blocks = Vec::new();
    let mut message_count = 0;

    while let Some(result) = stream.next().await {
        message_count += 1;

        match result {
            Ok(output) => {
                // Check for different message types that might contain tool use
                match &output {
                    ClaudeOutput::Assistant(msg) => {
                        for content in &msg.message.content {
                            match content {
                                claude_codes::io::ContentBlock::Text(text) => {
                                    text_blocks.push(text.text.clone());
                                }
                                claude_codes::io::ContentBlock::ToolUse(tool) => {
                                    tool_use_blocks.push((tool.id.clone(), tool.name.clone()));
                                }
                                claude_codes::io::ContentBlock::Thinking(thinking) => {
                                    thinking_blocks.push(thinking.thinking.clone());
                                }
                                claude_codes::io::ContentBlock::ToolResult(_) => {
                                    // Tool results shouldn't appear in assistant messages
                                    panic!(
                                        "Found ToolResult in Assistant message - this is wrong!"
                                    );
                                }
                                claude_codes::io::ContentBlock::Image(_) => {
                                    // Images might appear in assistant messages for generated images
                                }
                            }
                        }
                    }
                    ClaudeOutput::User(msg) => {
                        // Tool results appear in user messages (echoed back)
                        for content in &msg.message.content {
                            match content {
                                claude_codes::io::ContentBlock::ToolResult(result) => {
                                    tool_result_blocks.push((
                                        result.tool_use_id.clone(),
                                        result.is_error.unwrap_or(false),
                                    ));
                                }
                                claude_codes::io::ContentBlock::ToolUse(_) => {
                                    // Tool use shouldn't appear in user messages
                                    panic!("Found ToolUse in User message - this is wrong!");
                                }
                                _ => {}
                            }
                        }
                    }
                    _ => {}
                }
            }
            Err(e) => {
                eprintln!("Error: {}", e);
            }
        }

        // Stop after collecting enough messages
        if message_count > 15 {
            break;
        }
    }

    println!("Tool use blocks: {:?}", tool_use_blocks);
    println!("Tool result blocks: {:?}", tool_result_blocks);
    println!("Text blocks count: {}", text_blocks.len());
    println!("Thinking blocks: {:?}", thinking_blocks);

    // Verify we got tool use blocks
    assert!(
        !tool_use_blocks.is_empty(),
        "Should have received at least one ToolUse block"
    );

    // Verify we got tool results
    assert!(
        !tool_result_blocks.is_empty(),
        "Should have received at least one ToolResult block"
    );

    // Verify the tool IDs match between use and result
    for (use_id, _) in &tool_use_blocks {
        assert!(
            tool_result_blocks
                .iter()
                .any(|(result_id, _)| result_id == use_id),
            "Tool use ID {} should have a corresponding result",
            use_id
        );
    }
}

/// Test file editing tool use
#[tokio::test]
async fn test_file_edit_tool_use() {
    let mut client = async_client().await;

    // Create a test file first
    let test_file = "/tmp/claude_test_file.txt";
    std::fs::write(test_file, "Hello World").expect("Failed to create test file");

    // Ask Claude to edit the file
    let query = format!(
        "Please read the file at {} and tell me what it says. Then append ' - Modified by Claude' to it.",
        test_file
    );

    let mut stream = client
        .query_stream(&query)
        .await
        .expect("Failed to send query");

    let mut tool_uses = Vec::new();
    let mut message_count = 0;

    while let Some(result) = stream.next().await {
        message_count += 1;

        if let Ok(ClaudeOutput::Assistant(msg)) = result {
            for content in &msg.message.content {
                match content {
                    claude_codes::io::ContentBlock::ToolUse(tool) => {
                        println!("Tool use: name={}, input={:?}", tool.name, tool.input);
                        tool_uses.push(tool.name.clone());
                    }
                    claude_codes::io::ContentBlock::Text(text) => {
                        if text.text.len() < 200 {
                            println!("Text: {}", text.text);
                        }
                    }
                    _ => {}
                }
            }
        }

        if message_count > 20 {
            break;
        }
    }

    println!("Tools used: {:?}", tool_uses);

    // Clean up
    let _ = std::fs::remove_file(test_file);

    assert!(message_count > 0, "Should have received messages");
}

/// Test capturing raw tool blocks for deserialization testing
///
/// This test only writes to the test_cases directory on parse failures,
/// appending new files with incrementing numbers. This helps capture
/// new message formats that need to be added to the test suite.
#[tokio::test]
async fn test_capture_tool_blocks_for_testing() {
    use std::fs;
    use std::path::Path;

    let mut client = async_client().await;

    // Ask for multiple tool uses to get variety
    let mut stream = client
        .query_stream(
            "Please do the following:\n\
            1. List files in /tmp\n\
            2. Show the current date\n\
            3. Check if /etc/passwd exists",
        )
        .await
        .expect("Failed to send query");

    let captures_dir = Path::new("test_cases/tool_use_captures");
    fs::create_dir_all(captures_dir).ok();

    // Find the next available file number by checking existing files
    let mut next_num = 0;
    while captures_dir
        .join(format!("tool_msg_{}.json", next_num))
        .exists()
    {
        next_num += 1;
    }

    let mut capture_count = 0;
    let mut message_count = 0;

    while let Some(result) = stream.next().await {
        message_count += 1;

        match result {
            Ok(output) => {
                // Log what we're seeing
                if let ClaudeOutput::Assistant(msg) = &output {
                    for content in &msg.message.content {
                        if let claude_codes::io::ContentBlock::ToolUse(tool) = content {
                            println!("=== TOOL USE FOUND ===");
                            println!("Name: {}", tool.name);
                            println!("ID: {}", tool.id);
                            println!("Input: {:?}", tool.input);
                        }
                    }
                }
            }
            Err(e) => {
                // Only capture on parse failures - these are new message types we need to handle
                eprintln!("Parse error (new message type to handle): {}", e);

                // Get the raw JSON from the error if possible
                let error_text = format!("{}", e);
                let filename = format!("tool_msg_{}.json", next_num + capture_count);
                let filepath = captures_dir.join(&filename);

                // Try to extract raw JSON from the error, or save error details
                fs::write(&filepath, format!("// Parse error: {}\n{}", e, error_text)).ok();
                println!("Captured parse failure to {:?}", filepath);
                capture_count += 1;
            }
        }

        if message_count > 25 {
            break;
        }
    }

    if capture_count > 0 {
        println!(
            "Captured {} new message types that failed to parse",
            capture_count
        );
    }
    assert!(message_count > 0, "Should have received messages");
}

/// Test image content blocks
#[tokio::test]
async fn test_image_content_blocks() {
    use base64::{engine::general_purpose::STANDARD, Engine as _};
    use std::fs;

    // Read and encode the test image
    let image_path = "tests/test_data/hello-claude.png";
    let image_data = fs::read(image_path).expect("Failed to read test image");
    let base64_image = STANDARD.encode(&image_data);

    // Create client
    let mut client = async_client().await;

    // Send message with image
    let session_id = Uuid::new_v4();
    let input = ClaudeInput::user_message_with_image(
        base64_image.clone(),
        claude_codes::MediaType::Png,
        Some("What do you see in this image?".to_string()),
        session_id,
    )
    .expect("Failed to create image message");

    // Verify serialization includes image block
    let serialized = serde_json::to_string(&input).expect("Failed to serialize");
    assert!(
        serialized.contains("\"type\":\"image\""),
        "Should contain image type"
    );
    assert!(
        serialized.contains("\"source\""),
        "Should contain source field"
    );
    assert!(
        serialized.contains("\"media_type\":\"image/png\""),
        "Should contain media type"
    );
    assert!(
        serialized.contains("\"type\":\"base64\""),
        "Should contain source type"
    );

    // Send to Claude and collect responses
    client
        .send(&input)
        .await
        .expect("Failed to send image message");

    let mut found_image_description = false;
    let mut message_count = 0;
    let mut image_blocks_in_response = 0;

    loop {
        match client.receive().await {
            Ok(output) => {
                message_count += 1;

                // Check if assistant response mentions image content
                if let ClaudeOutput::Assistant(msg) = &output {
                    for content in &msg.message.content {
                        match content {
                            claude_codes::io::ContentBlock::Text(text) => {
                                // Claude should describe what it sees
                                if text.text.to_lowercase().contains("image")
                                    || text.text.to_lowercase().contains("hello")
                                    || text.text.to_lowercase().contains("text")
                                    || text.text.to_lowercase().contains("see")
                                {
                                    found_image_description = true;
                                    println!("Claude's description: {}", text.text);
                                }
                            }
                            claude_codes::io::ContentBlock::Image(_) => {
                                // Images in responses would be interesting
                                image_blocks_in_response += 1;
                            }
                            _ => {}
                        }
                    }
                }

                // Stop on result message
                if matches!(output, ClaudeOutput::Result(_)) {
                    break;
                }
            }
            Err(e) => {
                eprintln!("Error receiving: {}", e);
                break;
            }
        }

        // Safety limit
        if message_count > 20 {
            break;
        }
    }

    println!("Found image description: {}", found_image_description);
    println!("Image blocks in response: {}", image_blocks_in_response);

    assert!(message_count > 0, "Should have received messages");

    assert!(
        found_image_description,
        "Claude should have described the image content"
    );
}

/// Test mixed content blocks (text + image)
#[tokio::test]
async fn test_mixed_content_blocks() {
    use base64::{engine::general_purpose::STANDARD, Engine as _};

    // Create a small test image programmatically (1x1 red pixel PNG)
    let red_pixel_png = vec![
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
        0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
        0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77,
        0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08, 0x99, 0x63, 0xF8, 0xCF,
        0xC0, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x5B, 0x79, 0x53, 0x0D, 0x00, 0x00, 0x00, 0x00,
        0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, // IEND chunk
    ];

    let base64_image = STANDARD.encode(&red_pixel_png);

    // Create mixed content blocks
    let blocks = vec![
        ContentBlock::Text(claude_codes::io::TextBlock {
            text: "Here's a question with an image:".to_string(),
        }),
        ContentBlock::Image(claude_codes::io::ImageBlock {
            source: claude_codes::io::ImageSource {
                source_type: claude_codes::ImageSourceType::Base64,
                media_type: claude_codes::MediaType::Png,
                data: base64_image,
            },
        }),
        ContentBlock::Text(claude_codes::io::TextBlock {
            text: "What color is this pixel?".to_string(),
        }),
    ];

    let session_id = Uuid::new_v4();
    let input = ClaudeInput::user_message_blocks(blocks, session_id);

    // Verify serialization
    let serialized = serde_json::to_string(&input).expect("Failed to serialize");
    assert!(
        serialized.contains("\"type\":\"text\""),
        "Should contain text blocks"
    );
    assert!(
        serialized.contains("\"type\":\"image\""),
        "Should contain image block"
    );

    // Verify deserialization round-trip
    let deserialized: ClaudeInput =
        serde_json::from_str(&serialized).expect("Failed to deserialize");

    if let ClaudeInput::User(user_msg) = deserialized {
        assert_eq!(
            user_msg.message.content.len(),
            3,
            "Should have 3 content blocks"
        );

        // Verify block types
        assert!(
            matches!(&user_msg.message.content[0], ContentBlock::Text(_)),
            "First block should be text"
        );

        assert!(
            matches!(&user_msg.message.content[1], ContentBlock::Image(_)),
            "Second block should be image"
        );

        assert!(
            matches!(&user_msg.message.content[2], ContentBlock::Text(_)),
            "Third block should be text"
        );
    } else {
        panic!("Expected User message");
    }

    println!("Mixed content blocks test passed");
}

/// Test ping functionality
#[tokio::test]
async fn test_async_client_ping() {
    let mut client = async_client().await;

    // Test ping
    let ping_result = client.ping().await;
    assert!(
        ping_result,
        "Ping should return true when Claude responds with 'pong'"
    );
}

/// Test sync client ping functionality
#[test]
fn test_sync_client_ping() {
    let mut client = sync_client();

    // Test ping
    let ping_result = client.ping();
    assert!(
        ping_result,
        "Ping should return true when Claude responds with 'pong'"
    );
}

/// Test media type validation
#[test]
fn test_media_type_validation() {
    let session_id = Uuid::new_v4();
    let fake_data = "fake_base64_data".to_string();

    // Valid media types should work
    let valid_types = vec![
        claude_codes::MediaType::Jpeg,
        claude_codes::MediaType::Png,
        claude_codes::MediaType::Gif,
        claude_codes::MediaType::Webp,
    ];
    for media_type in valid_types {
        let result = ClaudeInput::user_message_with_image(
            fake_data.clone(),
            media_type.clone(),
            None,
            session_id,
        );
        assert!(result.is_ok(), "Media type {} should be valid", media_type);
    }

    // Invalid media types should fail
    let invalid_types = vec![
        claude_codes::MediaType::Unknown("image/bmp".to_string()),
        claude_codes::MediaType::Unknown("image/tiff".to_string()),
        claude_codes::MediaType::Unknown("video/mp4".to_string()),
        claude_codes::MediaType::Unknown("text/plain".to_string()),
        claude_codes::MediaType::Unknown("application/pdf".to_string()),
    ];
    for media_type in invalid_types {
        let result = ClaudeInput::user_message_with_image(
            fake_data.clone(),
            media_type.clone(),
            None,
            session_id,
        );
        assert!(
            result.is_err(),
            "Media type {} should be invalid",
            media_type
        );
        if let Err(msg) = result {
            assert!(msg.contains("Only JPEG, PNG, GIF, and WebP are supported"));
        }
    }
}

/// Test slash commands (like /help, /status, etc.)
#[tokio::test]
async fn test_slash_commands() {
    // First, let's debug what raw JSON we get for slash commands
    use std::io::Write;
    use std::process::Command;

    println!("=== Debugging slash command raw output ===");
    let debug_session_id = Uuid::new_v4().to_string();
    let mut claude_proc = Command::new("claude")
        .args([
            "--print",
            "--verbose",
            "--output-format",
            "stream-json",
            "--input-format",
            "stream-json",
            "--model",
            "sonnet",
            "--session-id",
            &debug_session_id,
        ])
        .env_remove("CLAUDECODE")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to spawn claude");

    if let Some(mut stdin) = claude_proc.stdin.take() {
        let input = format!(
            r#"{{"type":"user","message":{{"role":"user","content":[{{"type":"text","text":"/status"}}]}},"session_id":"{}"}}"#,
            debug_session_id
        );
        writeln!(stdin, "{}", input).expect("Failed to write to stdin");
        drop(stdin); // Close stdin to signal EOF
    }

    let output = claude_proc
        .wait_with_output()
        .expect("Failed to read output");

    println!("STDOUT (raw JSON lines):");
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        println!("  {}", line);
        // Try to parse each line
        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line) {
            if val.get("type") == Some(&serde_json::Value::String("result".to_string())) {
                println!(
                    "\n  RESULT MESSAGE (pretty printed):\n{}",
                    serde_json::to_string_pretty(&val).unwrap()
                );

                // Check for -1 values
                if let Some(usage) = val.get("usage") {
                    println!(
                        "\n  USAGE block:\n{}",
                        serde_json::to_string_pretty(&usage).unwrap()
                    );
                }
            }
        }
    }

    if !output.stderr.is_empty() {
        println!("\nSTDERR:");
        println!("{}", String::from_utf8_lossy(&output.stderr));
    }

    println!("=== End raw output debug ===\n");

    // Now run the actual test
    let mut client = async_client().await;

    // Test /help command
    let mut stream = client
        .query_stream("/help")
        .await
        .expect("Failed to send /help command");

    let mut received_help_response = false;
    let mut message_count = 0;
    let mut got_result = false;

    while let Some(result) = stream.next().await {
        message_count += 1;

        match result {
            Ok(output) => {
                println!("\n=== /help Response #{} ===", message_count);
                println!("Message type: {}", output.message_type());

                // Log full output for debugging
                match &output {
                    ClaudeOutput::System(msg) => {
                        println!("System message - subtype: {}", msg.subtype);
                        if let Ok(json) = serde_json::to_string_pretty(&msg.data) {
                            println!("System data:\n{}", json);
                        }
                    }
                    ClaudeOutput::User(msg) => {
                        println!("User message echoed back");
                        for content in &msg.message.content {
                            if let claude_codes::io::ContentBlock::Text(text) = content {
                                println!("User text: {}", text.text);
                            }
                        }
                    }
                    ClaudeOutput::Assistant(msg) => {
                        println!("Assistant message:");
                        for content in &msg.message.content {
                            match content {
                                claude_codes::io::ContentBlock::Text(text) => {
                                    println!("Assistant says:\n{}", text.text);
                                    // Help response typically contains commands or usage info
                                    if text.text.to_lowercase().contains("help")
                                        || text.text.to_lowercase().contains("command")
                                        || text.text.to_lowercase().contains("available")
                                        || text.text.contains("/")
                                    {
                                        received_help_response = true;
                                    }
                                }
                                _ => println!("(non-text content block)"),
                            }
                        }
                    }
                    ClaudeOutput::Result(result_msg) => {
                        println!("Result message:");
                        println!("  - Success: {}", !result_msg.is_error);
                        println!("  - Duration: {}ms", result_msg.duration_ms);
                        if let Some(result_text) = &result_msg.result {
                            println!("  - Result text: {}", result_text);
                        }
                        got_result = true;
                        if !result_msg.is_error {
                            received_help_response = true;
                            println!("Slash command completed successfully");
                        }
                        break;
                    }
                    _ => {
                        // Handle ControlRequest/ControlResponse if they appear
                    }
                }
            }
            Err(e) => {
                eprintln!("Error receiving response: {}", e);
                break;
            }
        }

        // Safety limit
        if message_count > 15 {
            break;
        }
    }

    assert!(message_count > 0, "Should have received messages");
    assert!(got_result, "Should have received a result message");
    // Slash commands might not produce assistant messages, but should complete successfully
    assert!(
        received_help_response || got_result,
        "Should have received help information or successful completion"
    );

    // Test /status command
    let mut stream = client
        .query_stream("/status")
        .await
        .expect("Failed to send /status command");

    let mut received_status_response = false;
    message_count = 0;
    got_result = false;

    while let Some(result) = stream.next().await {
        message_count += 1;

        match result {
            Ok(output) => {
                println!("\n=== /status Response #{} ===", message_count);
                println!("Message type: {}", output.message_type());

                // Log full output for debugging
                match &output {
                    ClaudeOutput::System(msg) => {
                        println!("System message - subtype: {}", msg.subtype);
                        if let Ok(json) = serde_json::to_string_pretty(&msg.data) {
                            println!("System data:\n{}", json);
                        }
                    }
                    ClaudeOutput::User(msg) => {
                        println!("User message echoed back");
                        for content in &msg.message.content {
                            if let claude_codes::io::ContentBlock::Text(text) = content {
                                println!("User text: {}", text.text);
                            }
                        }
                    }
                    ClaudeOutput::Assistant(msg) => {
                        println!("Assistant message:");
                        for content in &msg.message.content {
                            match content {
                                claude_codes::io::ContentBlock::Text(text) => {
                                    println!("Assistant says:\n{}", text.text);
                                    // Status response typically contains session info, model info, etc.
                                    if text.text.to_lowercase().contains("status")
                                        || text.text.to_lowercase().contains("session")
                                        || text.text.to_lowercase().contains("model")
                                        || text.text.to_lowercase().contains("claude")
                                    {
                                        received_status_response = true;
                                    }
                                }
                                _ => println!("(non-text content block)"),
                            }
                        }
                    }
                    ClaudeOutput::Result(result_msg) => {
                        println!("Result message:");
                        println!("  - Success: {}", !result_msg.is_error);
                        println!("  - Duration: {}ms", result_msg.duration_ms);
                        if let Some(result_text) = &result_msg.result {
                            println!("  - Result text: {}", result_text);
                        }
                    }
                    _ => {
                        // Handle ControlRequest/ControlResponse if they appear
                    }
                }

                // Check for successful result message
                if let ClaudeOutput::Result(result_msg) = &output {
                    got_result = true;
                    println!("Status result: is_error={}", result_msg.is_error);
                    if !result_msg.is_error {
                        received_status_response = true;
                        println!("/status command completed successfully");
                    }
                    break;
                }
            }
            Err(e) => {
                eprintln!("Error receiving response: {}", e);
                break;
            }
        }

        // Safety limit
        if message_count > 15 {
            break;
        }
    }

    assert!(
        message_count > 0,
        "Should have received messages for /status"
    );
    assert!(
        got_result,
        "Should have received a result message for /status"
    );
    assert!(
        received_status_response || got_result,
        "Should have received status information or successful completion"
    );

    // Test /cost command
    println!("\n=== Testing /cost command ===");

    // First, get raw output directly from the command
    let test_session_id = Uuid::new_v4().to_string();
    let mut claude_proc = Command::new("claude")
        .args([
            "--print",
            "--verbose",
            "--output-format",
            "stream-json",
            "--input-format",
            "stream-json",
            "--model",
            "sonnet",
            "--session-id",
            &test_session_id,
        ])
        .env_remove("CLAUDECODE")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to spawn claude");

    if let Some(mut stdin) = claude_proc.stdin.take() {
        let input = format!(
            r#"{{"type":"user","message":{{"role":"user","content":[{{"type":"text","text":"/cost"}}]}},"session_id":"{}"}}"#,
            test_session_id
        );
        writeln!(stdin, "{}", input).expect("Failed to write to stdin");
        drop(stdin); // Close stdin to signal EOF
    }

    let output = claude_proc
        .wait_with_output()
        .expect("Failed to read output");

    println!("RAW /cost STDOUT:");
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        println!("  RAW: {}", line);
    }

    if !output.stderr.is_empty() {
        println!("\nRAW /cost STDERR:");
        println!("{}", String::from_utf8_lossy(&output.stderr));
    }

    println!("=== End raw /cost output ===\n");

    // Now test through the client
    let mut stream = client
        .query_stream("/cost")
        .await
        .expect("Failed to send /cost command");

    let mut received_cost_response = false;
    message_count = 0;
    got_result = false;

    while let Some(result) = stream.next().await {
        message_count += 1;

        match result {
            Ok(output) => {
                println!("\n=== /cost Response #{} ===", message_count);
                println!("Message type: {}", output.message_type());

                // Log full output for debugging
                match &output {
                    ClaudeOutput::System(msg) => {
                        println!("System message - subtype: {}", msg.subtype);
                        if let Ok(json) = serde_json::to_string_pretty(&msg.data) {
                            println!("System data:\n{}", json);
                        }
                    }
                    ClaudeOutput::User(msg) => {
                        println!("User message echoed back");
                        for content in &msg.message.content {
                            if let claude_codes::io::ContentBlock::Text(text) = content {
                                println!("User text: {}", text.text);
                            }
                        }
                    }
                    ClaudeOutput::Assistant(msg) => {
                        println!("Assistant message:");
                        for content in &msg.message.content {
                            match content {
                                claude_codes::io::ContentBlock::Text(text) => {
                                    println!("Assistant says:\n{}", text.text);
                                    // Cost response typically contains cost info, subscription, or pricing
                                    if text.text.to_lowercase().contains("cost")
                                        || text.text.to_lowercase().contains("subscription")
                                        || text.text.to_lowercase().contains("claude max")
                                        || text.text.to_lowercase().contains("price")
                                        || text.text.to_lowercase().contains("$")
                                    {
                                        received_cost_response = true;
                                    }
                                }
                                _ => println!("(non-text content block)"),
                            }
                        }
                    }
                    ClaudeOutput::Result(result_msg) => {
                        println!("Result message:");
                        println!("  - Success: {}", !result_msg.is_error);
                        println!("  - Duration: {}ms", result_msg.duration_ms);
                        if let Some(result_text) = &result_msg.result {
                            println!("  - Result text: {}", result_text);
                            // Check if result contains cost information
                            if result_text.to_lowercase().contains("subscription")
                                || result_text.to_lowercase().contains("claude max")
                                || result_text.to_lowercase().contains("cost")
                            {
                                received_cost_response = true;
                            }
                        }
                        got_result = true;
                        if !result_msg.is_error {
                            received_cost_response = true;
                            println!("/cost command completed successfully");
                        }
                        break;
                    }
                    _ => {
                        // Handle ControlRequest/ControlResponse if they appear
                    }
                }
            }
            Err(e) => {
                eprintln!("Error receiving response: {}", e);
                break;
            }
        }

        // Safety limit
        if message_count > 15 {
            break;
        }
    }

    assert!(message_count > 0, "Should have received messages for /cost");
    assert!(
        got_result,
        "Should have received a result message for /cost"
    );
    assert!(
        received_cost_response || got_result,
        "Should have received cost information or successful completion"
    );
}

// ============================================================================
// Tool Approval Protocol Tests
// ============================================================================

/// Test that tool approval initialization handshake works
#[tokio::test]
async fn test_tool_approval_initialization() {
    // Create a client with permission_prompt_tool enabled
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .permission_prompt_tool("stdio")
        .spawn()
        .await
        .expect("Failed to spawn Claude with permission_prompt_tool");

    let mut client = AsyncClient::new(child).expect("Failed to create client");

    // Verify tool approval is not enabled yet
    assert!(
        !client.is_tool_approval_enabled(),
        "Tool approval should not be enabled before initialization"
    );

    // Enable tool approval (sends initialization handshake)
    client
        .enable_tool_approval()
        .await
        .expect("Tool approval initialization should succeed");

    // Verify tool approval is now enabled
    assert!(
        client.is_tool_approval_enabled(),
        "Tool approval should be enabled after initialization"
    );

    // Calling enable_tool_approval again should be a no-op (already enabled)
    client
        .enable_tool_approval()
        .await
        .expect("Second enable_tool_approval call should succeed (no-op)");

    client.shutdown().await.expect("Failed to shutdown client");
}

/// Test tool approval with a simple query that triggers tool use
#[tokio::test]
async fn test_tool_approval_with_query() {
    use claude_codes::ControlRequestPayload;

    // Create a client with permission_prompt_tool enabled
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .permission_prompt_tool("stdio")
        .spawn()
        .await
        .expect("Failed to spawn Claude with permission_prompt_tool");

    let mut client = AsyncClient::new(child).expect("Failed to create client");

    // Enable tool approval
    client
        .enable_tool_approval()
        .await
        .expect("Tool approval initialization should succeed");

    // Send a query that should trigger Read tool use
    let input = ClaudeInput::user_message(
        "Read the file /tmp/test_tool_approval.txt - if it doesn't exist just say 'file not found'",
        Uuid::new_v4(),
    );
    client.send(&input).await.expect("Failed to send query");

    // Collect responses, handling any tool permission requests
    let mut message_count = 0;
    let mut handled_permission_request = false;
    let mut got_result = false;

    loop {
        match client.receive().await {
            Ok(output) => {
                message_count += 1;
                println!("Message #{}: {}", message_count, output.message_type());

                match &output {
                    ClaudeOutput::ControlRequest(req) => {
                        println!("Got control request: {:?}", req.request_id);
                        if let ControlRequestPayload::CanUseTool(perm_req) = &req.request {
                            println!(
                                "Tool permission request for: {} with input: {:?}",
                                perm_req.tool_name, perm_req.input
                            );

                            // Allow the tool to execute
                            let response = perm_req.allow(&req.request_id);
                            client
                                .send_control_response(response)
                                .await
                                .expect("Failed to send control response");
                            handled_permission_request = true;
                        }
                    }
                    ClaudeOutput::Result(_) => {
                        got_result = true;
                        break;
                    }
                    _ => {}
                }

                // Safety limit
                if message_count > 20 {
                    break;
                }
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                break;
            }
        }
    }

    assert!(message_count > 0, "Should have received messages");
    assert!(got_result, "Should have received a result message");
    // Note: The model might not always use tools for this query, so we don't assert on handled_permission_request
    println!(
        "Test completed. Handled permission request: {}",
        handled_permission_request
    );

    client.shutdown().await.expect("Failed to shutdown client");
}

/// Test sync client tool approval initialization
#[test]
fn test_sync_tool_approval_initialization() {
    // Create a sync client with permission_prompt_tool enabled
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .permission_prompt_tool("stdio")
        .spawn_sync()
        .expect("Failed to spawn Claude with permission_prompt_tool");

    let mut client = SyncClient::new(child).expect("Failed to create client");

    // Verify tool approval is not enabled yet
    assert!(
        !client.is_tool_approval_enabled(),
        "Tool approval should not be enabled before initialization"
    );

    // Enable tool approval (sends initialization handshake)
    client
        .enable_tool_approval()
        .expect("Tool approval initialization should succeed");

    // Verify tool approval is now enabled
    assert!(
        client.is_tool_approval_enabled(),
        "Tool approval should be enabled after initialization"
    );

    client.shutdown().expect("Failed to shutdown client");
}

// ============================================================================
// Session Resume Tests (Issue #14 fix)
// ============================================================================

/// Test that resume_session works without --session-id conflict
///
/// This tests the fix for issue #14: ClaudeCliBuilder was adding --session-id
/// even when --resume was specified, causing Claude CLI to reject the command.
/// Before the fix, this would fail with:
/// "Error: --session-id can only be used with --continue or --resume if --fork-session is also specified."
#[tokio::test]
async fn test_resume_session_no_session_id_conflict() {
    // First, create a session and get its UUID
    let mut client = async_client().await;

    // Send a simple query to establish the session
    let mut stream = client
        .query_stream("Remember: the secret word is 'banana'. Say 'ok'.")
        .await
        .expect("Failed to send initial query");

    // Collect responses until we get a result
    while let Some(result) = stream.next().await {
        if let Ok(ClaudeOutput::Result(_)) = result {
            break;
        }
    }

    // Get the session UUID
    let session_uuid = client.session_uuid().expect("Should have session UUID");
    println!("Initial session UUID: {}", session_uuid);

    // Shutdown the first client
    client.shutdown().await.expect("Failed to shutdown client");

    // Now resume the session - this should NOT fail with the --session-id error
    // Before the fix, this would panic with CLI error about --session-id conflict:
    // "Error: --session-id can only be used with --continue or --resume if --fork-session is also specified."
    let resumed_result = AsyncClient::from_builder(
        ClaudeCliBuilder::new()
            .allow_recursion()
            .resume(Some(session_uuid.to_string())),
    )
    .await;

    match resumed_result {
        Ok(resumed_client) => {
            println!("Successfully created resumed client (fix verified!)");
            // The resumed session was created without the --session-id error
            // That's the main thing we're testing
            let _ = resumed_client.shutdown().await;
        }
        Err(e) => {
            // If it fails, check it's not the --session-id error
            let error_str = format!("{}", e);
            assert!(
                !error_str.contains("session-id"),
                "Should not fail with --session-id error, got: {}",
                error_str
            );
            println!("Resume failed for other reason (acceptable): {}", e);
        }
    }
}

/// Test the tool approval protocol - receive control_request and send denial
#[tokio::test]
async fn test_tool_approval_deny_flow() {
    use claude_codes::ControlRequestPayload;
    use std::fs;

    println!("=== Testing tool approval deny flow ===");

    // Create a test file that Claude will try to edit
    let test_file = "/tmp/test_tool_approval_edit.txt";
    fs::write(test_file, "Original content\n").expect("Failed to create test file");
    println!("Created test file: {}", test_file);

    // Create a client with permission_prompt_tool enabled
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .permission_prompt_tool("stdio")
        .spawn()
        .await
        .expect("Failed to spawn Claude with permission_prompt_tool");

    let mut client = AsyncClient::new(child).expect("Failed to create client");

    // Enable the tool approval protocol (handshake)
    client
        .enable_tool_approval()
        .await
        .expect("Failed to enable tool approval");

    assert!(
        client.is_tool_approval_enabled(),
        "Tool approval should be enabled"
    );
    println!("Tool approval enabled successfully");

    // Send a query that will trigger an Edit tool use (requires permission)
    let session_id = Uuid::new_v4();
    let input = ClaudeInput::user_message(
        format!(
            "Please edit the file {} and change 'Original' to 'Modified'. Do not ask for confirmation, just do it.",
            test_file
        ),
        session_id,
    );

    client.send(&input).await.expect("Failed to send query");
    println!("Sent query that should trigger tool use");

    // Receive messages until we get a control_request
    let mut received_control_request = false;
    let mut control_request_id = String::new();
    let mut tool_name = String::new();
    let mut message_count = 0;

    loop {
        message_count += 1;
        if message_count > 30 {
            println!("Reached message limit without control request");
            break;
        }

        match client.receive().await {
            Ok(output) => {
                println!(
                    "Received message #{}: type={}",
                    message_count,
                    output.message_type()
                );

                match output {
                    ClaudeOutput::ControlRequest(req) => {
                        println!("Got ControlRequest!");
                        println!("  Request ID: {}", req.request_id);

                        if let ControlRequestPayload::CanUseTool(perm_req) = &req.request {
                            println!("  Tool: {}", perm_req.tool_name);
                            println!(
                                "  Input: {}",
                                serde_json::to_string_pretty(&perm_req.input).unwrap_or_default()
                            );
                            println!(
                                "  Permission suggestions: {}",
                                perm_req.permission_suggestions.len()
                            );

                            // Store info for verification
                            received_control_request = true;
                            control_request_id = req.request_id.clone();
                            tool_name = perm_req.tool_name.clone();

                            // Send a denial response
                            let response =
                                perm_req.deny("Access denied by integration test", &req.request_id);
                            println!("Sending denial response...");
                            client
                                .send_control_response(response)
                                .await
                                .expect("Failed to send control response");
                            println!("Denial sent successfully");
                        }
                    }
                    ClaudeOutput::Result(result) => {
                        println!("Got Result: is_error={}", result.is_error);
                        if let Some(ref text) = result.result {
                            println!("  Result text: {}", text);
                        }
                        // Once we get a result, we're done
                        break;
                    }
                    ClaudeOutput::Assistant(msg) => {
                        // Check if Claude acknowledged the denial
                        for content in &msg.message.content {
                            if let ContentBlock::Text(text) = content {
                                println!("Assistant: {}", text.text);
                            }
                        }
                    }
                    _ => {}
                }
            }
            Err(e) => {
                eprintln!("Error receiving: {}", e);
                break;
            }
        }
    }

    // Verify we received and handled a control request
    assert!(
        received_control_request,
        "Should have received a ControlRequest message"
    );
    assert!(
        !control_request_id.is_empty(),
        "Should have captured request_id"
    );
    assert!(!tool_name.is_empty(), "Should have captured tool_name");

    println!("=== Tool approval deny flow test passed ===");
    println!("  Received control request for tool: {}", tool_name);
    println!("  Request ID: {}", control_request_id);

    // Cleanup
    let _ = client.shutdown().await;
    let _ = fs::remove_file(test_file);
}

/// Test the Permission builder and allow_and_remember flow
#[tokio::test]
async fn test_tool_approval_allow_and_remember() {
    use claude_codes::{ControlRequestPayload, Permission};
    use std::fs;

    println!("=== Testing tool approval with allow_and_remember ===");

    // Create a test file that Claude will try to read
    let test_file = "/tmp/test_permission_allow_remember.txt";
    fs::write(test_file, "Hello from integration test\n").expect("Failed to create test file");
    println!("Created test file: {}", test_file);

    // Create a client with permission_prompt_tool enabled
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .permission_prompt_tool("stdio")
        .spawn()
        .await
        .expect("Failed to spawn Claude with permission_prompt_tool");

    let mut client = AsyncClient::new(child).expect("Failed to create client");

    // Enable the tool approval protocol
    client
        .enable_tool_approval()
        .await
        .expect("Failed to enable tool approval");

    println!("Tool approval enabled successfully");

    // Send a query that will trigger a Read tool use
    let session_id = Uuid::new_v4();
    let input = ClaudeInput::user_message(
        format!(
            "Please read the file {} and tell me what it says.",
            test_file
        ),
        session_id,
    );

    client.send(&input).await.expect("Failed to send query");
    println!("Sent query that should trigger Read tool use");

    let mut received_control_request = false;
    let mut used_allow_and_remember = false;
    let mut message_count = 0;

    loop {
        message_count += 1;
        if message_count > 30 {
            println!("Reached message limit");
            break;
        }

        match client.receive().await {
            Ok(output) => {
                println!(
                    "Received message #{}: type={}",
                    message_count,
                    output.message_type()
                );

                match output {
                    ClaudeOutput::ControlRequest(req) => {
                        println!("Got ControlRequest!");

                        if let ControlRequestPayload::CanUseTool(perm_req) = &req.request {
                            println!("  Tool: {}", perm_req.tool_name);
                            println!(
                                "  Permission suggestions: {}",
                                perm_req.permission_suggestions.len()
                            );

                            // Test the new decision_reason and tool_use_id fields
                            if let Some(ref reason) = perm_req.decision_reason {
                                println!("  Decision reason: {}", reason);
                            }
                            if let Some(ref tool_use_id) = perm_req.tool_use_id {
                                println!("  Tool use ID: {}", tool_use_id);
                            }

                            received_control_request = true;

                            // Use the new allow_and_remember API
                            let response = if !perm_req.permission_suggestions.is_empty() {
                                // Use allow_and_remember_suggestion if suggestions are available
                                println!("Using allow_and_remember_suggestion");
                                perm_req
                                    .allow_and_remember_suggestion(&req.request_id)
                                    .unwrap_or_else(|| perm_req.allow(&req.request_id))
                            } else {
                                // Build a custom permission using Permission::allow_tool
                                println!("Using allow_and_remember with custom Permission");
                                perm_req.allow_and_remember(
                                    vec![Permission::allow_tool(&perm_req.tool_name, test_file)],
                                    &req.request_id,
                                )
                            };

                            used_allow_and_remember = true;
                            client
                                .send_control_response(response)
                                .await
                                .expect("Failed to send control response");
                            println!("Sent allow_and_remember response");
                        }
                    }
                    ClaudeOutput::Result(result) => {
                        println!("Got Result: is_error={}", result.is_error);
                        break;
                    }
                    ClaudeOutput::Assistant(msg) => {
                        for content in &msg.message.content {
                            if let ContentBlock::Text(text) = content {
                                println!("Assistant: {}", text.text);
                            }
                        }
                    }
                    _ => {}
                }
            }
            Err(e) => {
                eprintln!("Error receiving: {}", e);
                break;
            }
        }
    }

    assert!(
        received_control_request,
        "Should have received a ControlRequest"
    );
    assert!(
        used_allow_and_remember,
        "Should have used allow_and_remember API"
    );

    println!("=== Tool approval allow_and_remember test passed ===");

    // Cleanup
    let _ = client.shutdown().await;
    let _ = fs::remove_file(test_file);
}

/// Test Permission struct construction and serialization
#[test]
fn test_permission_struct_integration() {
    use claude_codes::{
        Permission, PermissionDestination, PermissionModeName, PermissionSuggestion, PermissionType,
    };

    // Test Permission::allow_tool
    let perm = Permission::allow_tool("Bash", "npm test");
    let json = serde_json::to_string(&perm).expect("Failed to serialize Permission");
    println!("Permission::allow_tool JSON: {}", json);
    assert!(json.contains("\"type\":\"addRules\""));
    assert!(json.contains("\"toolName\":\"Bash\""));
    assert!(json.contains("\"ruleContent\":\"npm test\""));

    // Test Permission::set_mode
    let mode_perm = Permission::set_mode(
        PermissionModeName::AcceptEdits,
        PermissionDestination::Session,
    );
    let mode_json = serde_json::to_string(&mode_perm).expect("Failed to serialize mode Permission");
    println!("Permission::set_mode JSON: {}", mode_json);
    assert!(mode_json.contains("\"type\":\"setMode\""));
    assert!(mode_json.contains("\"mode\":\"acceptEdits\""));

    // Test Permission::from_suggestion
    let suggestion = PermissionSuggestion {
        suggestion_type: PermissionType::SetMode,
        destination: PermissionDestination::Session,
        mode: Some(PermissionModeName::AcceptEdits),
        behavior: None,
        rules: None,
    };
    let from_suggestion = Permission::from_suggestion(&suggestion);
    assert_eq!(from_suggestion.permission_type, PermissionType::SetMode);
    assert_eq!(from_suggestion.mode, Some(PermissionModeName::AcceptEdits));

    println!("=== Permission struct integration test passed ===");
}

/// Test AnthropicError parsing and helper methods
#[test]
fn test_anthropic_error_integration() {
    use claude_codes::{AnthropicError, AnthropicErrorDetails, ClaudeOutput};

    // Test parsing various error types
    use claude_codes::ApiErrorType;

    let test_cases = vec![
        (
            r#"{"type":"error","error":{"type":"api_error","message":"Internal server error"},"request_id":"req_123"}"#,
            ApiErrorType::ApiError,
            true,  // is_server_error
            false, // is_overloaded
        ),
        (
            r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
            ApiErrorType::OverloadedError,
            false,
            true,
        ),
        (
            r#"{"type":"error","error":{"type":"rate_limit_error","message":"Rate limited"}}"#,
            ApiErrorType::RateLimitError,
            false,
            false,
        ),
    ];

    for (json, expected_type, expect_server_error, expect_overloaded) in test_cases {
        let output: ClaudeOutput = serde_json::from_str(json).expect("Failed to parse error JSON");

        assert!(output.is_api_error(), "Should be identified as API error");
        assert_eq!(output.message_type(), "error");

        if let Some(err) = output.as_anthropic_error() {
            assert_eq!(err.error.error_type, expected_type);
            assert_eq!(err.is_server_error(), expect_server_error);
            assert_eq!(err.is_overloaded(), expect_overloaded);
            println!(
                "Parsed {} error: {}",
                err.error.error_type, err.error.message
            );
        } else {
            panic!("Should be able to get AnthropicError");
        }
    }

    // Test roundtrip serialization
    let error = AnthropicError {
        error: AnthropicErrorDetails {
            error_type: ApiErrorType::ApiError,
            message: "Test error".to_string(),
        },
        request_id: Some("req_456".to_string()),
    };

    let json = serde_json::to_string(&error).expect("Failed to serialize");
    let parsed: AnthropicError = serde_json::from_str(&json).expect("Failed to parse");
    assert_eq!(parsed.error.error_type, error.error.error_type);
    assert_eq!(parsed.request_id, error.request_id);

    println!("=== AnthropicError integration test passed ===");
}

/// Test that /clear resets the conversation and re-emits an init message
#[tokio::test]
async fn test_clear_resets_session() {
    let child = ClaudeCliBuilder::new()
        .model("sonnet")
        .allow_recursion()
        .spawn()
        .await
        .expect("Failed to spawn Claude");
    let mut client = AsyncClient::new(child).expect("Failed to create async client");

    // First query to establish a session
    let mut stream = client
        .query_stream("Say 'hello'.")
        .await
        .expect("Failed to send initial query");

    let mut initial_session_id: Option<String> = None;
    while let Some(result) = stream.next().await {
        if let Ok(ref output) = result {
            if initial_session_id.is_none() {
                if let Some(sid) = output.session_id() {
                    initial_session_id = Some(sid.to_string());
                }
            }
        }
    }
    let initial_session_id = initial_session_id.expect("Should have captured initial session_id");
    println!("Initial session ID: {}", initial_session_id);

    // Send /clear to reset the conversation
    let mut stream = client
        .query_stream("/clear")
        .await
        .expect("Failed to send /clear command");

    while let Some(_result) = stream.next().await {}

    // Send another query after /clear
    let mut stream = client
        .query_stream("Say 'world'.")
        .await
        .expect("Failed to send post-clear query");

    let mut found_new_init = false;
    let mut init_session_id: Option<String> = None;
    let mut post_clear_session_ids: Vec<String> = Vec::new();

    while let Some(result) = stream.next().await {
        if let Ok(output) = result {
            if let ClaudeOutput::System(ref sys) = output {
                if sys.is_init() {
                    found_new_init = true;
                    if let Some(init) = sys.as_init() {
                        init_session_id = Some(init.session_id.clone());
                        println!("New init session_id: {}", init.session_id);
                    }
                }
            }

            if let Some(sid) = output.session_id() {
                let sid = sid.to_string();
                if !post_clear_session_ids.contains(&sid) {
                    post_clear_session_ids.push(sid);
                }
            }
        }
    }

    println!("Post-clear session IDs seen: {:?}", post_clear_session_ids);
    println!("Init session_id after /clear: {:?}", init_session_id);

    assert!(
        found_new_init,
        "Should have received a new system init message after /clear"
    );

    // Check whether /clear actually changes the session_id
    if let Some(ref new_id) = init_session_id {
        if new_id != &initial_session_id {
            println!("Session ID changed: {} -> {}", initial_session_id, new_id);
        } else {
            println!(
                "Session ID stayed the same: {} (CLI reuses session_id across /clear)",
                initial_session_id
            );
        }
    }

    client.shutdown().await.expect("Failed to shutdown client");
}