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
//! Integration tests for typed tool inputs.
//!
//! These tests verify that real Claude CLI tool use messages can be deserialized
//! and their inputs can be parsed into strongly-typed structures.

use claude_codes::io::ContentBlock;
use claude_codes::{BashInput, ClaudeOutput, ToolInput, ToolUseBlock};
use serde_json::json;

// ============================================================================
// Tests using captured real messages from test_cases/tool_use_captures/
// ============================================================================

/// Test parsing the system init message (tool_msg_0.json)
#[test]
fn test_parse_system_init_message() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_0.json");
    let output: ClaudeOutput =
        serde_json::from_str(json_str).expect("Failed to parse system init message");

    match output {
        ClaudeOutput::System(msg) => {
            assert_eq!(msg.subtype, claude_codes::SystemSubtype::Init);
            // Check that tools list is present
            let tools = msg.data.get("tools").expect("Missing tools");
            assert!(tools.is_array());
            let tools_array = tools.as_array().unwrap();
            assert!(tools_array.iter().any(|t| t.as_str() == Some("Bash")));
            assert!(tools_array.iter().any(|t| t.as_str() == Some("Read")));
            assert!(tools_array.iter().any(|t| t.as_str() == Some("Write")));
            println!(
                "System init message parsed successfully with {} tools",
                tools_array.len()
            );
        }
        _ => panic!("Expected System message, got {:?}", output.message_type()),
    }
}

/// Test parsing assistant message with Bash tool use (tool_msg_1.json)
#[test]
fn test_parse_bash_tool_use_message() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_1.json");
    let output: ClaudeOutput =
        serde_json::from_str(json_str).expect("Failed to parse assistant message");

    match output {
        ClaudeOutput::Assistant(msg) => {
            assert_eq!(msg.message.role, claude_codes::MessageRole::Assistant);
            assert_eq!(msg.message.content.len(), 1);

            if let ContentBlock::ToolUse(tool_use) = &msg.message.content[0] {
                assert_eq!(tool_use.name, "Bash");
                // Note: tool_use.id changes per session, just verify it starts with expected prefix
                assert!(tool_use.id.starts_with("toolu_"));

                // Test typed_input() method
                let typed = tool_use.typed_input().expect("Failed to get typed input");
                match typed {
                    ToolInput::Bash(bash) => {
                        assert_eq!(bash.command, "ls -la /tmp");
                        assert_eq!(
                            bash.description,
                            Some("List files in /tmp directory".to_string())
                        );
                    }
                    _ => panic!("Expected Bash input, got {:?}", typed.tool_name()),
                }
            } else {
                panic!("Expected ToolUse content block");
            }
        }
        _ => panic!("Expected Assistant message"),
    }
}

/// Test parsing assistant message with date command (tool_msg_2.json)
#[test]
fn test_parse_bash_date_command() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_2.json");
    let output: ClaudeOutput = serde_json::from_str(json_str).expect("Failed to parse");

    if let ClaudeOutput::Assistant(msg) = output {
        if let ContentBlock::ToolUse(tool_use) = &msg.message.content[0] {
            let typed = tool_use.typed_input().unwrap();
            if let ToolInput::Bash(bash) = typed {
                assert_eq!(bash.command, "date");
                // Description may vary slightly per session
                assert!(bash.description.is_some());
                assert!(bash
                    .description
                    .as_ref()
                    .unwrap()
                    .to_lowercase()
                    .contains("date"));
            } else {
                panic!("Expected Bash");
            }
        }
    }
}

/// Test parsing assistant message with complex bash command (tool_msg_3.json)
#[test]
fn test_parse_bash_complex_command() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_3.json");
    let output: ClaudeOutput = serde_json::from_str(json_str).expect("Failed to parse");

    if let ClaudeOutput::Assistant(msg) = output {
        // Note: stop_reason may or may not be present depending on API version
        // Just verify the message parses correctly

        if let ContentBlock::ToolUse(tool_use) = &msg.message.content[0] {
            let typed = tool_use.typed_input().unwrap();
            if let ToolInput::Bash(bash) = typed {
                assert!(bash.command.contains("test -f /etc/passwd"));
                // Description may vary, just check it exists and mentions passwd
                assert!(bash.description.is_some());
                assert!(bash
                    .description
                    .as_ref()
                    .unwrap()
                    .to_lowercase()
                    .contains("passwd"));
            }
        }
    }
}

/// Test parsing tool result (error) message (tool_msg_4.json)
#[test]
fn test_parse_tool_result_error() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_4.json");
    let output: ClaudeOutput = serde_json::from_str(json_str).expect("Failed to parse");

    if let ClaudeOutput::User(msg) = output {
        if let ContentBlock::ToolResult(result) = &msg.message.content[0] {
            // tool_use_id changes per session, just verify format
            assert!(result.tool_use_id.starts_with("toolu_"));
            assert_eq!(result.is_error, Some(true));
        }
    }
}

/// Test parsing tool result (success) message (tool_msg_5.json)
#[test]
fn test_parse_tool_result_success() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_5.json");
    let output: ClaudeOutput = serde_json::from_str(json_str).expect("Failed to parse");

    if let ClaudeOutput::User(msg) = output {
        if let ContentBlock::ToolResult(result) = &msg.message.content[0] {
            // tool_use_id changes per session, just verify format
            assert!(result.tool_use_id.starts_with("toolu_"));
            assert_eq!(result.is_error, Some(false));
        }
    }
}

/// Test parsing result message with permission_denials (tool_msg_7.json)
#[test]
fn test_parse_result_with_permission_denials() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_7.json");
    let output: ClaudeOutput = serde_json::from_str(json_str).expect("Failed to parse");

    if let ClaudeOutput::Result(result) = output {
        assert!(!result.is_error);
        assert_eq!(result.num_turns, 4);
        assert_eq!(result.permission_denials.len(), 2);

        // Access the first denial's fields directly (now typed)
        let denial1 = &result.permission_denials[0];
        assert_eq!(denial1.tool_name, "Bash");
        // tool_use_id changes per session, just verify format
        assert!(denial1.tool_use_id.starts_with("toolu_"));

        // Parse the tool_input as BashInput
        let bash: BashInput =
            serde_json::from_value(denial1.tool_input.clone()).expect("Failed to parse tool_input");
        assert_eq!(bash.command, "ls -la /tmp");
        // Description may vary slightly
        assert!(bash.description.is_some());

        // Access the second denial
        let denial2 = &result.permission_denials[1];
        assert_eq!(denial2.tool_name, "Bash");
        assert!(denial2.tool_use_id.starts_with("toolu_"));

        let bash2: BashInput = serde_json::from_value(denial2.tool_input.clone()).unwrap();
        assert!(bash2.command.contains("test -f /etc/passwd"));

        println!(
            "Parsed result with {} permission denials",
            result.permission_denials.len()
        );
    }
}

/// Test parsing result message with uuid field (tool_msg_8.json)
#[test]
fn test_parse_result_with_uuid() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_msg_8.json");
    let output: ClaudeOutput = serde_json::from_str(json_str).expect("Failed to parse");

    if let ClaudeOutput::Result(result) = output {
        assert!(!result.is_error);
        assert_eq!(result.num_turns, 4);
        assert_eq!(result.permission_denials.len(), 2);

        // Verify the new uuid field is parsed
        assert!(result.uuid.is_some());
        let uuid = result.uuid.as_ref().unwrap();
        assert!(uuid.contains("-"), "UUID should contain hyphens");
        println!("Parsed result with uuid: {}", uuid);

        // Verify errors array (empty in this case)
        assert!(result.errors.is_empty());

        // Verify usage info
        assert!(result.usage.is_some());
    } else {
        panic!("Expected Result message");
    }
}

// ============================================================================
// Tests for ToolInput enum deserialization
// ============================================================================

#[test]
fn test_tool_input_bash_deserialization() {
    let json = json!({
        "command": "git status",
        "description": "Check git status"
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Bash(_)));
    assert_eq!(input.tool_name(), Some("Bash"));

    let bash = input.as_bash().unwrap();
    assert_eq!(bash.command, "git status");
}

#[test]
fn test_tool_input_read_deserialization() {
    let json = json!({
        "file_path": "/home/user/code.rs",
        "offset": 100,
        "limit": 50
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Read(_)));

    let read = input.as_read().unwrap();
    assert_eq!(read.file_path, "/home/user/code.rs");
    assert_eq!(read.offset, Some(100));
    assert_eq!(read.limit, Some(50));
}

#[test]
fn test_tool_input_write_deserialization() {
    let json = json!({
        "file_path": "/tmp/output.txt",
        "content": "Hello, world!"
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Write(_)));

    let write = input.as_write().unwrap();
    assert_eq!(write.file_path, "/tmp/output.txt");
    assert_eq!(write.content, "Hello, world!");
}

#[test]
fn test_tool_input_edit_deserialization() {
    let json = json!({
        "file_path": "/home/user/code.rs",
        "old_string": "fn old_name()",
        "new_string": "fn new_name()",
        "replace_all": true
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Edit(_)));

    let edit = input.as_edit().unwrap();
    assert_eq!(edit.file_path, "/home/user/code.rs");
    assert_eq!(edit.old_string, "fn old_name()");
    assert_eq!(edit.new_string, "fn new_name()");
    assert_eq!(edit.replace_all, Some(true));
}

#[test]
fn test_tool_input_glob_deserialization() {
    let json = json!({
        "pattern": "**/*.rs",
        "path": "/home/user/project"
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Glob(_)));

    let glob = input.as_glob().unwrap();
    assert_eq!(glob.pattern, "**/*.rs");
    assert_eq!(glob.path, Some("/home/user/project".to_string()));
}

#[test]
fn test_tool_input_grep_deserialization() {
    let json = json!({
        "pattern": "fn\\s+\\w+",
        "path": "/home/user/project",
        "type": "rust",
        "-i": true,
        "-C": 3,
        "output_mode": "content"
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Grep(_)));

    let grep = input.as_grep().unwrap();
    assert_eq!(grep.pattern, "fn\\s+\\w+");
    assert_eq!(grep.file_type, Some("rust".to_string()));
    assert_eq!(grep.case_insensitive, Some(true));
    assert_eq!(grep.context, Some(3));
}

#[test]
fn test_tool_input_task_deserialization() {
    let json = json!({
        "description": "Search codebase",
        "prompt": "Find all usages of the foo function",
        "subagent_type": "Explore",
        "run_in_background": true
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Task(_)));

    let task = input.as_task().unwrap();
    assert_eq!(task.description, "Search codebase");
    assert_eq!(task.prompt, "Find all usages of the foo function");
    assert_eq!(task.subagent_type, claude_codes::SubagentType::Explore);
    assert_eq!(task.run_in_background, Some(true));
}

#[test]
fn test_tool_input_web_fetch_deserialization() {
    let json = json!({
        "url": "https://docs.rs/serde/latest",
        "prompt": "Extract the main documentation"
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::WebFetch(_)));

    let fetch = input.as_web_fetch().unwrap();
    assert_eq!(fetch.url, "https://docs.rs/serde/latest");
    assert_eq!(fetch.prompt, "Extract the main documentation");
}

#[test]
fn test_tool_input_web_search_deserialization() {
    let json = json!({
        "query": "rust serde tutorial 2026",
        "allowed_domains": ["docs.rs", "crates.io"]
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::WebSearch(_)));

    let search = input.as_web_search().unwrap();
    assert_eq!(search.query, "rust serde tutorial 2026");
}

#[test]
fn test_tool_input_todo_write_deserialization() {
    let json = json!({
        "todos": [
            {
                "content": "Implement feature",
                "status": "in_progress",
                "activeForm": "Implementing feature"
            },
            {
                "content": "Write tests",
                "status": "pending",
                "activeForm": "Writing tests"
            }
        ]
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::TodoWrite(_)));

    let todo = input.as_todo_write().unwrap();
    assert_eq!(todo.todos.len(), 2);
    assert_eq!(todo.todos[0].content, "Implement feature");
    assert_eq!(todo.todos[0].status, claude_codes::TodoStatus::InProgress);
}

#[test]
fn test_tool_input_ask_user_question_deserialization() {
    let json = json!({
        "questions": [
            {
                "question": "Which database should we use?",
                "header": "Database",
                "options": [
                    {"label": "PostgreSQL", "description": "Robust relational database"},
                    {"label": "SQLite", "description": "Lightweight embedded database"}
                ],
                "multiSelect": false
            }
        ]
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::AskUserQuestion(_)));

    let question = input.as_ask_user_question().unwrap();
    assert_eq!(question.questions.len(), 1);
    assert_eq!(
        question.questions[0].question,
        "Which database should we use?"
    );
    assert_eq!(question.questions[0].options.len(), 2);
}

#[test]
fn test_tool_input_unknown_custom_tool() {
    // Simulates a custom MCP tool with unknown structure
    let json = json!({
        "custom_field": "custom_value",
        "another_field": 123,
        "nested": {
            "foo": "bar"
        }
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::Unknown(_)));
    assert_eq!(input.tool_name(), None);
    assert!(input.is_unknown());

    let unknown = input.as_unknown().unwrap();
    assert_eq!(unknown.get("custom_field").unwrap(), "custom_value");
}

// ============================================================================
// ToolUseBlock helper method tests
// ============================================================================

#[test]
fn test_tool_use_block_typed_input() {
    let block = ToolUseBlock {
        id: "toolu_123".to_string(),
        name: "Bash".to_string(),
        input: json!({
            "command": "cargo build",
            "description": "Build the project"
        }),
    };

    let typed = block.typed_input().expect("Should parse");
    assert!(matches!(typed, ToolInput::Bash(_)));

    if let ToolInput::Bash(bash) = typed {
        assert_eq!(bash.command, "cargo build");
    }
}

#[test]
fn test_tool_use_block_try_typed_input_error() {
    let block = ToolUseBlock {
        id: "toolu_456".to_string(),
        name: "SomeCustomTool".to_string(),
        input: json!({
            "weird_field": [1, 2, 3]
        }),
    };

    // Should succeed but return Unknown variant
    let typed = block.try_typed_input().expect("Should parse as Unknown");
    assert!(matches!(typed, ToolInput::Unknown(_)));
}

// ============================================================================
// Tests for new helper methods with real message captures
// ============================================================================

/// Test assistant message with usage info and parent_tool_use_id
#[test]
fn test_parse_assistant_with_usage_and_parent() {
    let json_str = include_str!("../test_cases/tool_use_captures/assistant_with_usage.json");
    let output: ClaudeOutput =
        serde_json::from_str(json_str).expect("Failed to parse assistant message with usage");

    // Test is_assistant_message()
    assert!(output.is_assistant_message());

    // Test session_id() helper
    assert_eq!(
        output.session_id(),
        Some("08cd4ce5-1ce0-4dd4-8e7c-8b69712c514e")
    );

    // Test as_assistant() helper
    let assistant = output.as_assistant().expect("Should be assistant");
    assert_eq!(assistant.message.role, claude_codes::MessageRole::Assistant);
    assert_eq!(assistant.message.model, "claude-haiku-4-5-20251001");

    // Test tool_uses() helper
    let tools: Vec<_> = output.tool_uses().collect();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "Bash");

    // Test as_tool_use() helper
    let bash = output.as_tool_use("Bash").expect("Should find Bash tool");
    assert_eq!(bash.name, "Bash");

    // Test typed_input on the tool
    let typed = bash.typed_input().expect("Should get typed input");
    if let ToolInput::Bash(b) = typed {
        assert!(b.command.contains("grep"));
    } else {
        panic!("Expected Bash input");
    }

    // Test text_content() - should be None since it's only tool_use
    assert!(output.text_content().is_none());

    // Check parent_tool_use_id is preserved
    assert_eq!(
        assistant.parent_tool_use_id,
        Some("toolu_012hZhNyfdf6Y156ryHJSbxd".to_string())
    );

    // Check usage is preserved
    let usage = assistant.message.usage.as_ref().expect("Should have usage");
    assert_eq!(usage.input_tokens, 5);
    assert_eq!(usage.output_tokens, 250);
}

/// Test tool_result with error content (string form)
#[test]
fn test_parse_tool_result_error_message() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_result_error.json");
    let output: ClaudeOutput =
        serde_json::from_str(json_str).expect("Failed to parse tool result error");

    // Should not be assistant
    assert!(!output.is_assistant_message());

    // Test session_id() returns None for user messages
    assert!(output.session_id().is_none());

    // Test is_error() - should be false since this is a user message, not result
    assert!(!output.is_error());

    // Verify it's a user message with tool_result content
    if let ClaudeOutput::User(user) = output {
        assert_eq!(user.message.role, claude_codes::MessageRole::User);
        assert_eq!(user.message.content.len(), 1);

        if let ContentBlock::ToolResult(result) = &user.message.content[0] {
            assert_eq!(result.is_error, Some(true));
            assert_eq!(result.tool_use_id, "toolu_01F5A3vbYenHhtdEV9Zt7arW");
            // Check error message content - ToolResultContent is an enum
            if let Some(claude_codes::ToolResultContent::Text(text)) = &result.content {
                assert!(text.contains("InputValidationError"));
            } else {
                panic!("Expected Text content in tool result");
            }
        } else {
            panic!("Expected ToolResult content block");
        }
    } else {
        panic!("Expected User message");
    }
}

/// Test tool_result with structured/array-form content (for WASM consumers - issue #42)
#[test]
fn test_parse_tool_result_structured_content() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_result_structured.json");
    let output: ClaudeOutput = serde_json::from_str(json_str)
        .expect("Failed to parse tool result with structured content");

    // Verify it's a user message with tool_result content
    if let ClaudeOutput::User(user) = output {
        assert_eq!(user.message.role, claude_codes::MessageRole::User);
        assert_eq!(user.message.content.len(), 1);

        if let ContentBlock::ToolResult(result) = &user.message.content[0] {
            assert_eq!(result.tool_use_id, "toolu_01ABC123def456");
            // Check structured content - ToolResultContent is an enum with Structured variant
            if let Some(claude_codes::ToolResultContent::Structured(structured)) = &result.content {
                // Structured content is Vec<Value>
                assert!(!structured.is_empty());
                // First element should have type: "text"
                let first = &structured[0];
                assert_eq!(first.get("type").and_then(|v| v.as_str()), Some("text"));
                // Verify it contains actual text content
                let text = first.get("text").and_then(|v| v.as_str());
                assert!(text.is_some());
                assert!(text.unwrap().contains("React"));
            } else {
                panic!(
                    "Expected Structured content in tool result, got: {:?}",
                    result.content
                );
            }
        } else {
            panic!("Expected ToolResult content block");
        }
    } else {
        panic!("Expected User message");
    }
}

/// Test tool_result with multiple text items in structured content (real message from production)
#[test]
fn test_parse_tool_result_multi_text_structured() {
    let json_str = include_str!("../test_cases/tool_use_captures/tool_result_multi_text.json");
    let output: ClaudeOutput = serde_json::from_str(json_str)
        .expect("Failed to parse tool result with multi-text content");

    // Verify it's a user message with tool_result content
    if let ClaudeOutput::User(user) = output {
        assert_eq!(user.message.role, claude_codes::MessageRole::User);
        assert_eq!(user.message.content.len(), 1);

        if let ContentBlock::ToolResult(result) = &user.message.content[0] {
            assert_eq!(result.tool_use_id, "toolu_012hZhNyfdf6Y156ryHJSbxd");
            // Check structured content has multiple text items
            if let Some(claude_codes::ToolResultContent::Structured(structured)) = &result.content {
                // Should have 2 text items (the main analysis and the agentId)
                assert_eq!(structured.len(), 2);

                // First element should have type: "text" with the analysis
                let first = &structured[0];
                assert_eq!(first.get("type").and_then(|v| v.as_str()), Some("text"));
                let text = first.get("text").and_then(|v| v.as_str()).unwrap();
                assert!(text.contains("ADSBView.tsx Component Analysis"));

                // Second element should have the agentId
                let second = &structured[1];
                assert_eq!(second.get("type").and_then(|v| v.as_str()), Some("text"));
                let agent_text = second.get("text").and_then(|v| v.as_str()).unwrap();
                assert!(agent_text.contains("agentId"));
            } else {
                panic!(
                    "Expected Structured content in tool result, got: {:?}",
                    result.content
                );
            }
        } else {
            panic!("Expected ToolResult content block");
        }
    } else {
        panic!("Expected User message");
    }
}

// ============================================================================
// ExitPlanModeInput tests (issue #62)
// ============================================================================

#[test]
fn test_exit_plan_mode_with_plan_field() {
    // This is the exact JSON from issue #62 that was failing with deny_unknown_fields
    let json = json!({
        "allowedPrompts": [
            { "tool": "Bash", "prompt": "run tests" }
        ],
        "plan": "# My Plan\n\n## Summary\n..."
    });

    let input: claude_codes::ExitPlanModeInput = serde_json::from_value(json).unwrap();
    assert_eq!(input.plan, Some("# My Plan\n\n## Summary\n...".to_string()));
    assert!(input.allowed_prompts.is_some());
    let prompts = input.allowed_prompts.unwrap();
    assert_eq!(prompts.len(), 1);
    assert_eq!(prompts[0].tool, "Bash");
    assert_eq!(prompts[0].prompt, "run tests");
}

#[test]
fn test_exit_plan_mode_with_remote_session_title() {
    let json = json!({
        "pushToRemote": true,
        "remoteSessionId": "session-abc-123",
        "remoteSessionUrl": "https://claude.ai/session/abc",
        "remoteSessionTitle": "Implement auth feature"
    });

    let input: claude_codes::ExitPlanModeInput = serde_json::from_value(json).unwrap();
    assert_eq!(input.push_to_remote, Some(true));
    assert_eq!(input.remote_session_id, Some("session-abc-123".to_string()));
    assert_eq!(
        input.remote_session_url,
        Some("https://claude.ai/session/abc".to_string())
    );
    assert_eq!(
        input.remote_session_title,
        Some("Implement auth feature".to_string())
    );
}

#[test]
fn test_exit_plan_mode_all_fields() {
    let json = json!({
        "allowedPrompts": [
            { "tool": "Bash", "prompt": "run tests" },
            { "tool": "Bash", "prompt": "install dependencies" }
        ],
        "pushToRemote": true,
        "remoteSessionId": "session-xyz",
        "remoteSessionUrl": "https://claude.ai/session/xyz",
        "remoteSessionTitle": "My Plan Title",
        "plan": "# Full Plan\n\nStep 1: Do stuff"
    });

    let input: claude_codes::ExitPlanModeInput = serde_json::from_value(json).unwrap();
    assert_eq!(
        input.plan,
        Some("# Full Plan\n\nStep 1: Do stuff".to_string())
    );
    assert_eq!(
        input.remote_session_title,
        Some("My Plan Title".to_string())
    );
    assert_eq!(input.push_to_remote, Some(true));
    assert!(input.allowed_prompts.is_some());
    assert_eq!(input.allowed_prompts.unwrap().len(), 2);
}

#[test]
fn test_exit_plan_mode_empty() {
    // ExitPlanMode with no fields should still work
    let json = json!({});

    let input: claude_codes::ExitPlanModeInput = serde_json::from_value(json).unwrap();
    assert_eq!(input.plan, None);
    assert_eq!(input.remote_session_title, None);
    assert_eq!(input.allowed_prompts, None);
    assert_eq!(input.push_to_remote, None);
    assert_eq!(input.remote_session_id, None);
    assert_eq!(input.remote_session_url, None);
}

#[test]
fn test_exit_plan_mode_unknown_field_rejected() {
    // deny_unknown_fields should still reject truly unknown fields
    let json = json!({
        "plan": "my plan",
        "bogusField": "should fail"
    });

    let result: Result<claude_codes::ExitPlanModeInput, _> = serde_json::from_value(json);
    assert!(result.is_err(), "Should reject unknown fields");
}

#[test]
fn test_exit_plan_mode_via_tool_input_enum() {
    // Verify the ToolInput enum can deserialize ExitPlanModeInput with the new fields
    let json = json!({
        "allowedPrompts": [
            { "tool": "Bash", "prompt": "run build" }
        ],
        "plan": "# Build Plan"
    });

    let input: ToolInput = serde_json::from_value(json).unwrap();
    assert!(matches!(input, ToolInput::ExitPlanMode(_)));
    assert_eq!(input.tool_name(), Some("ExitPlanMode"));

    if let ToolInput::ExitPlanMode(exit) = input {
        assert_eq!(exit.plan, Some("# Build Plan".to_string()));
    } else {
        panic!("Expected ExitPlanMode variant");
    }
}

#[test]
fn test_exit_plan_mode_roundtrip() {
    let original = claude_codes::ExitPlanModeInput {
        allowed_prompts: Some(vec![claude_codes::AllowedPrompt {
            tool: "Bash".to_string(),
            prompt: "run tests".to_string(),
        }]),
        push_to_remote: Some(true),
        remote_session_id: Some("id-123".to_string()),
        remote_session_url: Some("https://example.com".to_string()),
        remote_session_title: Some("My Title".to_string()),
        plan: Some("# The Plan".to_string()),
    };

    let json = serde_json::to_value(&original).unwrap();
    let parsed: claude_codes::ExitPlanModeInput = serde_json::from_value(json).unwrap();
    assert_eq!(original, parsed);
}

// ============================================================================
// Roundtrip serialization tests
// ============================================================================

#[test]
fn test_bash_input_roundtrip() {
    let original = BashInput {
        command: "echo hello".to_string(),
        description: Some("Print hello".to_string()),
        timeout: Some(5000),
        run_in_background: Some(false),
    };

    let json = serde_json::to_value(&original).unwrap();
    let parsed: BashInput = serde_json::from_value(json).unwrap();

    assert_eq!(original, parsed);
}

#[test]
fn test_tool_input_enum_roundtrip() {
    let original = ToolInput::Bash(BashInput {
        command: "ls -la".to_string(),
        description: Some("List files".to_string()),
        timeout: None,
        run_in_background: None,
    });

    let json = serde_json::to_value(&original).unwrap();
    let parsed: ToolInput = serde_json::from_value(json).unwrap();

    assert_eq!(original, parsed);
}