-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtypes_test.go
More file actions
1654 lines (1473 loc) · 47.3 KB
/
types_test.go
File metadata and controls
1654 lines (1473 loc) · 47.3 KB
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
package main
import (
"fmt"
"testing"
)
func TestParseMessage_SystemInit(t *testing.T) {
data := []byte(`{"type":"system","subtype":"init","session_id":"test-session","model":"claude-opus-4-5-20251101"}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
sysInit, ok := msg.(*SystemInit)
if !ok {
t.Fatalf("expected *SystemInit, got %T", msg)
}
if sysInit.SessionID != "test-session" {
t.Errorf("expected session_id 'test-session', got '%s'", sysInit.SessionID)
}
if sysInit.Model != "claude-opus-4-5-20251101" {
t.Errorf("expected model 'claude-opus-4-5-20251101', got '%s'", sysInit.Model)
}
}
func TestParseMessage_AssistantMessage(t *testing.T) {
data := []byte(`{"type":"assistant","message":{"id":"msg_01","type":"message","role":"assistant","content":[{"type":"text","text":"Hello!"}]}}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
assistant, ok := msg.(*AssistantMessage)
if !ok {
t.Fatalf("expected *AssistantMessage, got %T", msg)
}
if len(assistant.Message.Content) != 1 {
t.Fatalf("expected 1 content block, got %d", len(assistant.Message.Content))
}
if assistant.Message.Content[0].Type != ContentBlockTypeText {
t.Errorf("expected content type 'text', got '%s'", assistant.Message.Content[0].Type)
}
if assistant.Message.Content[0].Text != "Hello!" {
t.Errorf("expected text 'Hello!', got '%s'", assistant.Message.Content[0].Text)
}
}
func TestParseMessage_Result(t *testing.T) {
data := []byte(`{"type":"result","subtype":"success","is_error":false,"total_cost_usd":0.05,"duration_ms":5000,"num_turns":2}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
result, ok := msg.(*Result)
if !ok {
t.Fatalf("expected *Result, got %T", msg)
}
if result.IsError {
t.Error("expected is_error to be false")
}
if result.TotalCost != 0.05 {
t.Errorf("expected total_cost 0.05, got %f", result.TotalCost)
}
if result.NumTurns != 2 {
t.Errorf("expected num_turns 2, got %d", result.NumTurns)
}
}
func TestParseMessage_StreamEvent(t *testing.T) {
data := []byte(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
event, ok := msg.(*StreamEvent)
if !ok {
t.Fatalf("expected *StreamEvent, got %T", msg)
}
if event.Type != StreamEventContentBlockDelta {
t.Errorf("expected type 'content_block_delta', got '%s'", event.Type)
}
if event.Delta == nil {
t.Fatal("expected delta to be non-nil")
}
if event.Delta.Text != "Hello" {
t.Errorf("expected delta text 'Hello', got '%s'", event.Delta.Text)
}
}
func TestParseMessage_UnknownType(t *testing.T) {
data := []byte(`{"type":"unknown_type","field":"value"}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
base, ok := msg.(*BaseMessage)
if !ok {
t.Fatalf("expected *BaseMessage, got %T", msg)
}
if base.Type != "unknown_type" {
t.Errorf("expected type 'unknown_type', got '%s'", base.Type)
}
}
func TestAppState_InitializeSession(t *testing.T) {
state := NewAppState()
sysInit := &SystemInit{
SessionID: "test-session",
Model: "claude-opus-4-5-20251101",
}
state.InitializeSession(sysInit)
if state.SessionID != "test-session" {
t.Errorf("expected session_id 'test-session', got '%s'", state.SessionID)
}
if state.Model != "claude-opus-4-5-20251101" {
t.Errorf("expected model 'claude-opus-4-5-20251101', got '%s'", state.Model)
}
if state.RootAgent == nil {
t.Fatal("expected root agent to be initialized")
}
if state.RootAgent.Type != "main" {
t.Errorf("expected root agent type 'main', got '%s'", state.RootAgent.Type)
}
}
func TestAppState_AddAndCompleteToolCall(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
toolCall := &ToolCall{
ID: "tool_123",
Name: "Read",
Status: ToolCallStatusPending,
}
state.AddOrUpdateToolCall(toolCall)
if _, ok := state.PendingTools["tool_123"]; !ok {
t.Error("expected tool call to be in pending tools")
}
state.CompleteToolCall("tool_123", "file contents", false)
tc := state.PendingTools["tool_123"]
if tc.Status != ToolCallStatusCompleted {
t.Errorf("expected status 'completed', got '%s'", tc.Status)
}
if tc.Result != "file contents" {
t.Errorf("expected result 'file contents', got '%s'", tc.Result)
}
}
func TestAppState_StreamState(t *testing.T) {
state := NewAppState()
state.AppendStreamText("Hello ")
state.AppendStreamText("World")
if state.Stream.PartialText != "Hello World" {
t.Errorf("expected 'Hello World', got '%s'", state.Stream.PartialText)
}
state.AppendStreamThinking("Let me think...")
if state.Stream.PartialThinking != "Let me think..." {
t.Errorf("expected 'Let me think...', got '%s'", state.Stream.PartialThinking)
}
state.ClearStreamState()
if state.Stream.PartialText != "" {
t.Error("expected partial text to be cleared")
}
if state.Stream.PartialThinking != "" {
t.Error("expected partial thinking to be cleared")
}
}
func TestAppState_CreateChildAgent(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
// Create first child agent
child := state.CreateChildAgent("tool_1", "Explore", "Exploring codebase")
if child == nil {
t.Fatal("expected non-nil child agent")
}
if child.ID != "tool_1" {
t.Errorf("expected ID 'tool_1', got '%s'", child.ID)
}
if child.Type != "Explore" {
t.Errorf("expected type 'Explore', got '%s'", child.Type)
}
if child.Description != "Exploring codebase" {
t.Errorf("expected description, got '%s'", child.Description)
}
if child.ParentID != "main" {
t.Errorf("expected parent ID 'main', got '%s'", child.ParentID)
}
if child.Depth != 1 {
t.Errorf("expected depth 1, got %d", child.Depth)
}
if child.Status != AgentStatusRunning {
t.Errorf("expected status 'running', got '%s'", child.Status)
}
// Verify it's registered in lookup map
if _, ok := state.AgentsByID["tool_1"]; !ok {
t.Error("expected child to be in AgentsByID map")
}
// Create nested child (grandchild)
state.SetCurrentAgent("tool_1")
grandchild := state.CreateChildAgent("tool_2", "task", "Sub-task")
if grandchild.Depth != 2 {
t.Errorf("expected depth 2 for grandchild, got %d", grandchild.Depth)
}
if grandchild.ParentID != "tool_1" {
t.Errorf("expected parent ID 'tool_1', got '%s'", grandchild.ParentID)
}
}
func TestAppState_SetCurrentAgent(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
// Create a child agent
child := state.CreateChildAgent("tool_1", "task", "Test task")
// Current should still be root
if state.CurrentAgent.ID != "main" {
t.Errorf("expected current agent to be 'main', got '%s'", state.CurrentAgent.ID)
}
// Set current to child
state.SetCurrentAgent("tool_1")
if state.CurrentAgent.ID != "tool_1" {
t.Errorf("expected current agent to be 'tool_1', got '%s'", state.CurrentAgent.ID)
}
if state.CurrentAgent.Status != AgentStatusRunning {
t.Errorf("expected status 'running', got '%s'", state.CurrentAgent.Status)
}
// Set to non-existent agent (should be a no-op)
state.SetCurrentAgent("nonexistent")
if state.CurrentAgent.ID != "tool_1" {
t.Errorf("setting non-existent agent should not change current, got '%s'", state.CurrentAgent.ID)
}
// Set back to main
state.SetCurrentAgent("main")
if state.CurrentAgent.ID != "main" {
t.Errorf("expected current agent to be 'main', got '%s'", state.CurrentAgent.ID)
}
// Verify child is still accessible
if child.Type != "task" {
t.Errorf("child agent should still exist, got type '%s'", child.Type)
}
}
func TestAppState_UpdateTokens(t *testing.T) {
state := NewAppState()
// Test nil usage (should be no-op)
state.UpdateTokens(nil)
if state.TotalTokens.InputTokens != 0 {
t.Error("nil usage should not affect tokens")
}
// First update
usage1 := &Usage{
InputTokens: 100,
OutputTokens: 50,
CacheReadInputTokens: 20,
CacheCreationInputTokens: 10,
}
state.UpdateTokens(usage1)
if state.TotalTokens.InputTokens != 100 {
t.Errorf("expected input tokens 100, got %d", state.TotalTokens.InputTokens)
}
if state.TotalTokens.OutputTokens != 50 {
t.Errorf("expected output tokens 50, got %d", state.TotalTokens.OutputTokens)
}
if state.TotalTokens.CacheReadInputTokens != 20 {
t.Errorf("expected cache read tokens 20, got %d", state.TotalTokens.CacheReadInputTokens)
}
if state.TotalTokens.CacheCreationInputTokens != 10 {
t.Errorf("expected cache creation tokens 10, got %d", state.TotalTokens.CacheCreationInputTokens)
}
if state.TotalTokens.TotalTokens != 150 {
t.Errorf("expected total tokens 150, got %d", state.TotalTokens.TotalTokens)
}
// Second update (should accumulate)
usage2 := &Usage{
InputTokens: 200,
OutputTokens: 100,
}
state.UpdateTokens(usage2)
if state.TotalTokens.InputTokens != 300 {
t.Errorf("expected accumulated input tokens 300, got %d", state.TotalTokens.InputTokens)
}
if state.TotalTokens.OutputTokens != 150 {
t.Errorf("expected accumulated output tokens 150, got %d", state.TotalTokens.OutputTokens)
}
if state.TotalTokens.TotalTokens != 450 {
t.Errorf("expected accumulated total tokens 450, got %d", state.TotalTokens.TotalTokens)
}
}
func TestToolUseResult_UnmarshalJSON_String(t *testing.T) {
jsonData := []byte(`"simple string result"`)
var result ToolUseResult
err := result.UnmarshalJSON(jsonData)
if err != nil {
t.Fatalf("UnmarshalJSON failed: %v", err)
}
if result.RawString != "simple string result" {
t.Errorf("expected RawString 'simple string result', got '%s'", result.RawString)
}
if result.Stdout != "" {
t.Error("expected Stdout to be empty for string form")
}
}
func TestToolUseResult_UnmarshalJSON_Object(t *testing.T) {
jsonData := []byte(`{"stdout":"output text","stderr":"error text","interrupted":true,"isImage":false}`)
var result ToolUseResult
err := result.UnmarshalJSON(jsonData)
if err != nil {
t.Fatalf("UnmarshalJSON failed: %v", err)
}
if result.Stdout != "output text" {
t.Errorf("expected Stdout 'output text', got '%s'", result.Stdout)
}
if result.Stderr != "error text" {
t.Errorf("expected Stderr 'error text', got '%s'", result.Stderr)
}
if !result.Interrupted {
t.Error("expected Interrupted to be true")
}
if result.IsImage {
t.Error("expected IsImage to be false")
}
if result.RawString != "" {
t.Error("expected RawString to be empty for object form")
}
}
func TestToolUseResult_UnmarshalJSON_InvalidJSON(t *testing.T) {
jsonData := []byte(`{invalid json}`)
var result ToolUseResult
err := result.UnmarshalJSON(jsonData)
if err == nil {
t.Error("expected error for invalid JSON")
}
}
func TestParseMessage_InvalidJSON(t *testing.T) {
data := []byte(`{not valid json}`)
_, err := ParseMessage(data)
if err == nil {
t.Error("expected error for invalid JSON")
}
}
func TestParseMessage_EmptyJSON(t *testing.T) {
data := []byte(`{}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
// Should return BaseMessage for empty/unknown type
base, ok := msg.(*BaseMessage)
if !ok {
t.Fatalf("expected *BaseMessage, got %T", msg)
}
if base.Type != "" {
t.Errorf("expected empty type, got '%s'", base.Type)
}
}
func TestParseMessage_StreamEventWrapper(t *testing.T) {
data := []byte(`{"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"}}}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
// Should unwrap to StreamEvent
event, ok := msg.(*StreamEvent)
if !ok {
t.Fatalf("expected *StreamEvent, got %T", msg)
}
if event.Type != StreamEventContentBlockDelta {
t.Errorf("expected content_block_delta, got '%s'", event.Type)
}
}
func TestParseMessage_CompactBoundary(t *testing.T) {
data := []byte(`{"type":"compact_boundary","subtype":"context_trim","session_id":"test-123"}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
boundary, ok := msg.(*CompactBoundary)
if !ok {
t.Fatalf("expected *CompactBoundary, got %T", msg)
}
if boundary.Subtype != "context_trim" {
t.Errorf("expected subtype 'context_trim', got '%s'", boundary.Subtype)
}
}
func TestAppState_StreamToolInput(t *testing.T) {
state := NewAppState()
// Append partial tool input
state.AppendStreamToolInput("tool_1", `{"command":`)
state.AppendStreamToolInput("tool_1", `"ls -la"}`)
result := state.GetStreamToolInput("tool_1")
if result != `{"command":"ls -la"}` {
t.Errorf("expected concatenated input, got '%s'", result)
}
// Non-existent tool should return empty string
result = state.GetStreamToolInput("nonexistent")
if result != "" {
t.Errorf("expected empty string for non-existent tool, got '%s'", result)
}
}
func TestStreamState_Reset(t *testing.T) {
stream := NewStreamState()
stream.PartialText = "some text"
stream.PartialThinking = "some thinking"
stream.PartialToolInput["tool_1"] = "some input"
stream.CurrentIndex = 5
stream.Reset()
if stream.PartialText != "" {
t.Error("expected PartialText to be cleared")
}
if stream.PartialThinking != "" {
t.Error("expected PartialThinking to be cleared")
}
if len(stream.PartialToolInput) != 0 {
t.Error("expected PartialToolInput to be cleared")
}
if stream.CurrentIndex != 0 {
t.Error("expected CurrentIndex to be reset")
}
}
func TestNewStreamState(t *testing.T) {
stream := NewStreamState()
if stream == nil {
t.Fatal("expected non-nil stream state")
}
if stream.PartialToolInput == nil {
t.Error("expected PartialToolInput map to be initialized")
}
}
func TestNewAppState(t *testing.T) {
state := NewAppState()
if state == nil {
t.Fatal("expected non-nil app state")
}
if state.PendingTools == nil {
t.Error("expected PendingTools map to be initialized")
}
if state.AgentsByID == nil {
t.Error("expected AgentsByID map to be initialized")
}
if state.TotalTokens == nil {
t.Error("expected TotalTokens to be initialized")
}
if state.Stream == nil {
t.Error("expected Stream to be initialized")
}
}
func TestAppState_CompleteToolCall_WithError(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
toolCall := &ToolCall{
ID: "tool_err",
Name: "Bash",
Status: ToolCallStatusPending,
}
state.AddOrUpdateToolCall(toolCall)
// Complete with error
state.CompleteToolCall("tool_err", "command not found", true)
tc := state.PendingTools["tool_err"]
if tc.Status != ToolCallStatusFailed {
t.Errorf("expected status 'failed', got '%s'", tc.Status)
}
if !tc.IsError {
t.Error("expected IsError to be true")
}
if tc.Result != "command not found" {
t.Errorf("expected error result, got '%s'", tc.Result)
}
}
func TestAppState_CompleteToolCall_NonExistent(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
// Complete a tool that doesn't exist - should be a no-op
state.CompleteToolCall("nonexistent", "result", false)
// Should not panic or create an entry
if _, ok := state.PendingTools["nonexistent"]; ok {
t.Error("completing non-existent tool should not create entry")
}
}
func TestAppState_AddOrUpdateToolCall_NilCurrentAgent(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
// Set CurrentAgent to nil
state.CurrentAgent = nil
toolCall := &ToolCall{
ID: "tool_123",
Name: "Read",
Status: ToolCallStatusPending,
}
// Should not panic when CurrentAgent is nil
state.AddOrUpdateToolCall(toolCall)
// Tool should still be added to PendingTools
if _, ok := state.PendingTools["tool_123"]; !ok {
t.Error("expected tool call to be in pending tools even with nil CurrentAgent")
}
}
func TestAppState_AddOrUpdateToolCall_UpdateExisting(t *testing.T) {
state := NewAppState()
state.InitializeSession(&SystemInit{SessionID: "test"})
// Add initial tool call
toolCall := &ToolCall{
ID: "tool_123",
Name: "Read",
Status: ToolCallStatusPending,
}
state.AddOrUpdateToolCall(toolCall)
// Update the same tool call
updatedCall := &ToolCall{
ID: "tool_123",
Name: "Read",
Status: ToolCallStatusRunning,
}
state.AddOrUpdateToolCall(updatedCall)
// Verify it was updated in PendingTools
tc := state.PendingTools["tool_123"]
if tc.Status != ToolCallStatusRunning {
t.Errorf("expected status 'running', got '%s'", tc.Status)
}
// Verify it was updated in CurrentAgent's ToolCalls
if len(state.CurrentAgent.ToolCalls) != 1 {
t.Errorf("expected 1 tool call in current agent, got %d", len(state.CurrentAgent.ToolCalls))
}
if state.CurrentAgent.ToolCalls[0].Status != ToolCallStatusRunning {
t.Errorf("expected agent tool call status 'running', got '%s'", state.CurrentAgent.ToolCalls[0].Status)
}
}
func TestAppState_CreateChildAgent_NilRootAgent(t *testing.T) {
state := NewAppState()
// Don't initialize session, so RootAgent will be nil
child := state.CreateChildAgent("tool_1", "Explore", "Exploring codebase")
// Should not panic when RootAgent is nil
if child == nil {
t.Fatal("expected non-nil child agent even with nil RootAgent")
}
// When RootAgent is nil, CreateChildAgent will use RootAgent as parent
// which defaults to nil, so child should be created with nil parent
if child.ID != "tool_1" {
t.Errorf("expected ID 'tool_1', got '%s'", child.ID)
}
}
func TestParseMessage_StreamEventTypes(t *testing.T) {
tests := []struct {
name string
json string
wantErr bool
}{
{
name: "message_start event",
json: `{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[]}}`,
wantErr: false,
},
{
name: "content_block_start event",
json: `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
wantErr: false,
},
{
name: "content_block_stop event",
json: `{"type":"content_block_stop","index":0}`,
wantErr: false,
},
{
name: "message_delta event",
json: `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":10,"output_tokens":5}}`,
wantErr: false,
},
{
name: "message_stop event",
json: `{"type":"message_stop"}`,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msg, err := ParseMessage([]byte(tt.json))
if (err != nil) != tt.wantErr {
t.Errorf("ParseMessage() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
event, ok := msg.(*StreamEvent)
if !ok {
t.Errorf("ParseMessage() returned %T, want *StreamEvent", msg)
} else {
// Verify the Type field matches expected
if event.Type == "" {
t.Error("ParseMessage() StreamEvent has empty Type")
}
}
}
})
}
}
func TestParseMessage_UnmarshalError(t *testing.T) {
tests := []struct {
name string
json string
wantTypeIn string // The type field that should be parsed even if inner unmarshal fails
}{
{
name: "system message with invalid inner structure",
json: `{"type":"system","subtype":"init","session_id":123}`,
wantTypeIn: "system",
},
{
name: "assistant message with invalid content",
json: `{"type":"assistant","message":"invalid"}`,
wantTypeIn: "assistant",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// These should error during unmarshal
_, err := ParseMessage([]byte(tt.json))
if err == nil {
t.Error("ParseMessage() expected error for invalid JSON structure, got nil")
}
})
}
}
func TestParseMessage_StreamEventWrapperWithNilEvent(t *testing.T) {
// Test stream_event wrapper with nil event
data := []byte(`{"type":"stream_event","event":null,"session_id":"test"}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
// Should return the wrapper itself when event is nil
wrapper, ok := msg.(*StreamEventWrapper)
if !ok {
t.Fatalf("expected *StreamEventWrapper with nil event, got %T", msg)
}
if wrapper.Event != nil {
t.Error("expected nil Event")
}
}
func TestParseMessage_UserMessage(t *testing.T) {
data := []byte(`{"type":"user","message":{"role":"user","content":[{"type":"text","text":"user input"}]},"session_id":"sess-1"}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
user, ok := msg.(*UserMessage)
if !ok {
t.Fatalf("expected *UserMessage, got %T", msg)
}
if user.Type != "user" {
t.Errorf("expected type 'user', got '%s'", user.Type)
}
if user.SessionID != "sess-1" {
t.Errorf("expected session_id 'sess-1', got '%s'", user.SessionID)
}
if len(user.Message.Content) != 1 {
t.Fatalf("expected 1 content block, got %d", len(user.Message.Content))
}
}
func TestParseMessage_SystemInit_AllOptionalFields(t *testing.T) {
data := []byte(`{
"type": "system",
"subtype": "init",
"session_id": "sess-full",
"model": "claude-opus-4-5-20251101",
"cwd": "/home/user/project",
"tools": ["Read", "Bash", "Write"],
"mcp_servers": [
{"name": "server1", "status": "running"},
{"name": "server2", "status": "stopped"}
],
"permissionMode": "auto",
"slash_commands": ["/commit", "/review"],
"apiKeySource": "env",
"claude_code_version": "1.0.0",
"output_style": "compact",
"agents": ["explore", "plan"],
"skills": ["fastapi-auth"],
"plugins": [
{"name": "plugin1", "path": "/path/to/plugin1"}
],
"uuid": "uuid-12345"
}`)
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
sysInit, ok := msg.(*SystemInit)
if !ok {
t.Fatalf("expected *SystemInit, got %T", msg)
}
if sysInit.SessionID != "sess-full" {
t.Errorf("expected session_id 'sess-full', got '%s'", sysInit.SessionID)
}
if sysInit.Model != "claude-opus-4-5-20251101" {
t.Errorf("expected model 'claude-opus-4-5-20251101', got '%s'", sysInit.Model)
}
if sysInit.CwdPath != "/home/user/project" {
t.Errorf("expected cwd '/home/user/project', got '%s'", sysInit.CwdPath)
}
if len(sysInit.Tools) != 3 {
t.Errorf("expected 3 tools, got %d", len(sysInit.Tools))
}
if len(sysInit.McpServers) != 2 {
t.Errorf("expected 2 mcp_servers, got %d", len(sysInit.McpServers))
}
if sysInit.McpServers[0].Name != "server1" {
t.Errorf("expected first mcp_server name 'server1', got '%s'", sysInit.McpServers[0].Name)
}
if sysInit.PermissionMode != "auto" {
t.Errorf("expected permissionMode 'auto', got '%s'", sysInit.PermissionMode)
}
if len(sysInit.SlashCommands) != 2 {
t.Errorf("expected 2 slash_commands, got %d", len(sysInit.SlashCommands))
}
if sysInit.APIKeySource != "env" {
t.Errorf("expected apiKeySource 'env', got '%s'", sysInit.APIKeySource)
}
if sysInit.ClaudeCodeVersion != "1.0.0" {
t.Errorf("expected claude_code_version '1.0.0', got '%s'", sysInit.ClaudeCodeVersion)
}
if sysInit.OutputStyle != "compact" {
t.Errorf("expected output_style 'compact', got '%s'", sysInit.OutputStyle)
}
if len(sysInit.Agents) != 2 {
t.Errorf("expected 2 agents, got %d", len(sysInit.Agents))
}
if len(sysInit.Skills) != 1 {
t.Errorf("expected 1 skill, got %d", len(sysInit.Skills))
}
if len(sysInit.Plugins) != 1 {
t.Errorf("expected 1 plugin, got %d", len(sysInit.Plugins))
}
if sysInit.Plugins[0].Name != "plugin1" {
t.Errorf("expected plugin name 'plugin1', got '%s'", sysInit.Plugins[0].Name)
}
if sysInit.UUID != "uuid-12345" {
t.Errorf("expected uuid 'uuid-12345', got '%s'", sysInit.UUID)
}
}
func TestParseMessage_AssistantMessage_AllContentBlockTypes(t *testing.T) {
tests := []struct {
name string
content string
validateFn func(t *testing.T, block ContentBlock)
}{
{
name: "text content block",
content: `{"type":"assistant","message":{
"id":"msg-1",
"type":"message",
"role":"assistant",
"content":[
{"type":"text","text":"Hello, world!"}
]
}}`,
validateFn: func(t *testing.T, block ContentBlock) {
if block.Type != ContentBlockTypeText {
t.Errorf("expected content type 'text', got '%s'", block.Type)
}
if block.Text != "Hello, world!" {
t.Errorf("expected text 'Hello, world!', got '%s'", block.Text)
}
},
},
{
name: "thinking content block",
content: `{"type":"assistant","message":{
"id":"msg-2",
"type":"message",
"role":"assistant",
"content":[
{"type":"thinking","thinking":"Let me analyze this..."}
]
}}`,
validateFn: func(t *testing.T, block ContentBlock) {
if block.Type != ContentBlockTypeThinking {
t.Errorf("expected content type 'thinking', got '%s'", block.Type)
}
if block.Thinking != "Let me analyze this..." {
t.Errorf("expected thinking 'Let me analyze this...', got '%s'", block.Thinking)
}
},
},
{
name: "redacted_thinking content block",
content: `{"type":"assistant","message":{
"id":"msg-3",
"type":"message",
"role":"assistant",
"content":[
{"type":"redacted_thinking","thinking":"[REDACTED]"}
]
}}`,
validateFn: func(t *testing.T, block ContentBlock) {
if block.Type != ContentBlockTypeRedactedThinking {
t.Errorf("expected content type 'redacted_thinking', got '%s'", block.Type)
}
},
},
{
name: "tool_use content block",
content: `{"type":"assistant","message":{
"id":"msg-4",
"type":"message",
"role":"assistant",
"content":[
{
"type":"tool_use",
"id":"tool_123",
"name":"Read",
"input":{"file_path":"./test.go"}
}
]
}}`,
validateFn: func(t *testing.T, block ContentBlock) {
if block.Type != ContentBlockTypeToolUse {
t.Errorf("expected content type 'tool_use', got '%s'", block.Type)
}
if block.ID != "tool_123" {
t.Errorf("expected tool id 'tool_123', got '%s'", block.ID)
}
if block.Name != "Read" {
t.Errorf("expected tool name 'Read', got '%s'", block.Name)
}
if len(block.Input) == 0 {
t.Error("expected tool input to be non-empty")
}
},
},
{
name: "tool_result content block",
content: `{"type":"assistant","message":{
"id":"msg-5",
"type":"message",
"role":"assistant",
"content":[
{
"type":"tool_result",
"tool_use_id":"tool_123",
"content":"file contents here",
"is_error":false
}
]
}}`,
validateFn: func(t *testing.T, block ContentBlock) {
if block.Type != ContentBlockTypeToolResult {
t.Errorf("expected content type 'tool_result', got '%s'", block.Type)
}
if block.ToolUseID != "tool_123" {
t.Errorf("expected tool_use_id 'tool_123', got '%s'", block.ToolUseID)
}
if block.Content != "file contents here" {
t.Errorf("expected content 'file contents here', got '%s'", block.Content)
}
if block.IsError {
t.Error("expected is_error to be false")
}
},
},
{
name: "mixed content blocks",
content: `{"type":"assistant","message":{
"id":"msg-6",
"type":"message",
"role":"assistant",
"content":[
{"type":"thinking","thinking":"I'll help with that"},
{"type":"text","text":"Here's what I found:"},
{
"type":"tool_use",
"id":"tool_456",
"name":"Bash",
"input":{"command":"ls -la"}
}
]
}}`,
validateFn: func(t *testing.T, block ContentBlock) {
// Just verify we got all 3 blocks
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msg, err := ParseMessage([]byte(tt.content))
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
assistant, ok := msg.(*AssistantMessage)
if !ok {
t.Fatalf("expected *AssistantMessage, got %T", msg)
}