1package modes
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "strings"
9 "testing"
10 "time"
11
12 "github.com/bnema/zut/packages/core"
13 "github.com/bnema/zut/packages/provider"
14)
15
16func TestRunJSONCompletionUserMessageIsValidJSONL(t *testing.T) {
17 message := core.EvUserMessage{Message: provider.Message{
18 Role: provider.RoleUser,
19 Content: []provider.Content{provider.TextBlock{Text: "[auto-subagents update] worker finished"}},
20 }}
21 var line bytes.Buffer
22 if err := json.NewEncoder(&line).Encode(EventToJSON(message)); err != nil {
23 t.Fatal(err)
24 }
25 var decoded map[string]any
26 if err := json.Unmarshal(bytes.TrimSpace(line.Bytes()), &decoded); err != nil {
27 t.Fatalf("completion event is not JSON: %v", err)
28 }
29 if decoded["type"] != "user_message" {
30 t.Fatalf("event type = %#v, want user_message", decoded["type"])
31 }
32}
33
34type failingJSONWriter struct{ err error }
35
36func (w failingJSONWriter) Write([]byte) (int, error) { return 0, w.err }
37
38func TestRunJSONPropagatesOutputErrors(t *testing.T) {
39 providerErr := errors.New("provider unavailable")
40 writerErr := errors.New("stdout unavailable")
41 ag := core.NewAgent(&streamTestClient{err: providerErr}, "test-model", "", nil)
42 _, err := RunJSONWithContextRecovery(context.Background(), ag, "hello", nil, failingJSONWriter{err: writerErr}, nil)
43 if !errors.Is(err, providerErr) || !errors.Is(err, writerErr) {
44 t.Fatalf("RunJSONWithContextRecovery error = %v, want provider and output errors", err)
45 }
46}
47
48func TestRunJSONFailureEmitsOneErrorObject(t *testing.T) {
49 client := &streamTestClient{err: errors.New("provider unavailable")}
50 ag := core.NewAgent(client, "test-model", "", nil)
51 var out bytes.Buffer
52 _, err := RunJSONWithContextRecovery(context.Background(), ag, "hello", nil, &out, nil)
53 if err == nil {
54 t.Fatal("RunJSONWithContextRecovery unexpectedly succeeded")
55 }
56 lines := strings.Split(strings.TrimSpace(out.String()), "\n")
57 errorObjects := 0
58 for _, line := range lines {
59 var decoded map[string]any
60 if err := json.Unmarshal([]byte(line), &decoded); err != nil {
61 t.Fatalf("invalid JSONL line %q: %v", line, err)
62 }
63 if decoded["type"] == "error" {
64 errorObjects++
65 }
66 }
67 if errorObjects != 1 {
68 t.Fatalf("error objects = %d, want one; output=%q", errorObjects, out.String())
69 }
70}
71
72func TestEventToJSONCacheDiagnosticsAreSanitized(t *testing.T) {
73 event := EventToJSON(core.EvCacheDiagnostics{
74 Eligible: true, Mode: "implicit", Transport: "websocket", Continuation: "incremental",
75 })
76 if event["type"] != "cache_diagnostics" || event["eligible"] != true || event["mode"] != "implicit" || event["transport"] != "websocket" || event["continuation"] != "incremental" {
77 t.Fatalf("cache diagnostics event = %#v", event)
78 }
79 for _, forbidden := range []string{"prompt", "session_id", "thread_id", "request_body", "credential"} {
80 if _, ok := event[forbidden]; ok {
81 t.Fatalf("cache diagnostics leaked %q: %#v", forbidden, event)
82 }
83 }
84}
85
86func TestEventToJSONPlanUpdate(t *testing.T) {
87 explanation := "Discovery complete"
88 event := EventToJSON(core.EvPlanUpdate{CallID: "call-7", Update: core.PlanUpdate{
89 Explanation: &explanation,
90 Plan: []core.PlanStep{{Step: "Implement", Status: core.PlanInProgress}},
91 }})
92 if event["type"] != "plan_update" || event["explanation"] != "Discovery complete" || event["id"] != "call-7" {
93 t.Fatalf("plan event = %#v", event)
94 }
95 plan, ok := event["plan"].([]core.PlanStep)
96 if !ok || len(plan) != 1 || plan[0].Status != core.PlanInProgress {
97 t.Fatalf("plan payload = %#v", event["plan"])
98 }
99 withoutExplanation := EventToJSON(core.EvPlanUpdate{Update: core.PlanUpdate{Plan: []core.PlanStep{}}})
100 if withoutExplanation["explanation"] != nil {
101 t.Fatalf("missing explanation = %#v, want null", withoutExplanation["explanation"])
102 }
103 if _, ok := withoutExplanation["id"]; ok {
104 t.Fatalf("missing call id = %#v, want omitted", withoutExplanation["id"])
105 }
106}
107
108func TestEventToJSONActivityLifecycle(t *testing.T) {
109 request := EventToJSON(core.EvRequestStarted{
110 Provider: "anthropic",
111 Model: "claude-test",
112 Scope: core.RetryScopeProvider,
113 Attempt: 2,
114 MaxAttempts: 3,
115 })
116 if got, want := request["type"], "request_started"; got != want {
117 t.Fatalf("type = %q, want %q", got, want)
118 }
119 for key, want := range map[string]any{
120 "provider": "anthropic",
121 "model": "claude-test",
122 "scope": "provider",
123 "attempt": 2,
124 "max_attempts": 3,
125 } {
126 if got := request[key]; got != want {
127 t.Errorf("request[%q] = %#v, want %#v", key, got, want)
128 }
129 }
130
131 retry := EventToJSON(core.EvRetryScheduled{
132 Scope: core.RetryScopeAgent, Attempt: 2, MaxAttempts: 4, Delay: 1500 * time.Millisecond,
133 })
134 if got, want := retry["delay_ms"], int64(1500); got != want {
135 t.Fatalf("delay_ms = %#v, want %#v", got, want)
136 }
137 if _, exists := retry["delay"]; exists {
138 t.Fatal("retry event must not serialize a duration")
139 }
140
141 tool := EventToJSON(core.EvToolExecutionStarted{ID: "call-1", Name: "read"})
142 if got, want := tool["type"], "tool_execution_started"; got != want {
143 t.Fatalf("type = %q, want %q", got, want)
144 }
145 if tool["id"] != "call-1" || tool["name"] != "read" {
146 t.Fatalf("tool event = %#v", tool)
147 }
148}