| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | |
| 13 | "reasonix/internal/event" |
| 14 | "reasonix/internal/provider" |
| 15 | "reasonix/internal/provider/openai" |
| 16 | "reasonix/internal/tool" |
| 17 | ) |
| 18 | |
| 19 | type recordSink struct { |
| 20 | mu sync.Mutex |
| 21 | evs []event.Event |
| 22 | recovery []event.ProtocolRecoveryAudit |
| 23 | } |
| 24 | |
| 25 | func (s *recordSink) Emit(e event.Event) { |
| 26 | s.mu.Lock() |
| 27 | defer s.mu.Unlock() |
| 28 | s.evs = append(s.evs, e) |
| 29 | } |
| 30 | |
| 31 | func (s *recordSink) kinds(k event.Kind) []event.Event { |
| 32 | s.mu.Lock() |
| 33 | defer s.mu.Unlock() |
| 34 | var out []event.Event |
| 35 | for _, e := range s.evs { |
| 36 | if e.Kind == k { |
| 37 | out = append(out, e) |
| 38 | } |
| 39 | } |
| 40 | return out |
| 41 | } |
| 42 | |
| 43 | func (s *recordSink) RecordProtocolRecovery(a event.ProtocolRecoveryAudit) { |
| 44 | s.mu.Lock() |
| 45 | defer s.mu.Unlock() |
| 46 | s.recovery = append(s.recovery, a) |
| 47 | } |
| 48 | |
| 49 | func (s *recordSink) recoveryCount(kind event.ProtocolRecoveryKind) int { |
| 50 | s.mu.Lock() |
| 51 | defer s.mu.Unlock() |
| 52 | var count int |
| 53 | for _, audit := range s.recovery { |
| 54 | if audit.Kind == kind { |
| 55 | count++ |
| 56 | } |
| 57 | } |
| 58 | return count |
| 59 | } |
| 60 | |
| 61 | // TestAgentEmitsRetryingThenStreams drives the whole chain end-to-end: a real |
| 62 | // OpenAI-compatible provider hits an httptest server that returns 503 twice then |
| 63 | // a valid SSE stream. The agent must emit a Retrying event per backoff (so the |
| 64 | // composer can show "retrying n/m") and still deliver the streamed answer. |
| 65 | func TestAgentEmitsRetryingThenStreams(t *testing.T) { |
| 66 | var reqs int |
| 67 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 68 | reqs++ |
| 69 | if reqs <= 2 { |
| 70 | w.WriteHeader(http.StatusServiceUnavailable) |
| 71 | _, _ = w.Write([]byte(`{"error":"overloaded"}`)) |
| 72 | return |
| 73 | } |
| 74 | w.Header().Set("Content-Type", "text/event-stream") |
| 75 | _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"hi there\"}}]}\n\ndata: [DONE]\n\n") |
| 76 | })) |
| 77 | defer srv.Close() |
| 78 | |
| 79 | prov, err := openai.New(provider.Config{Name: "deepseek", BaseURL: srv.URL, Model: "deepseek-v4", APIKey: "k"}) |
| 80 | if err != nil { |
| 81 | t.Fatalf("New provider: %v", err) |
| 82 | } |
| 83 | |
| 84 | sink := &recordSink{} |
| 85 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, sink) |
| 86 | if err := a.Run(context.Background(), "hi"); err != nil { |
| 87 | t.Fatalf("Run: %v", err) |
| 88 | } |
| 89 | |
| 90 | retries := sink.kinds(event.Retrying) |
| 91 | if len(retries) != 2 || retries[0].RetryAttempt != 1 || retries[1].RetryAttempt != 2 { |
| 92 | t.Fatalf("want two Retrying events (1,2), got %+v", retries) |
| 93 | } |
| 94 | if retries[0].RetryMax != provider.MaxRetries { |
| 95 | t.Errorf("RetryMax = %d, want %d", retries[0].RetryMax, provider.MaxRetries) |
| 96 | } |
| 97 | |
| 98 | var answer strings.Builder |
| 99 | for _, e := range sink.kinds(event.Text) { |
| 100 | answer.WriteString(e.Text) |
| 101 | } |
| 102 | if !strings.Contains(answer.String(), "hi there") { |
| 103 | t.Errorf("streamed answer = %q, want it to contain %q", answer.String(), "hi there") |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // TestDeepSeekFlashMissingReasoningRecoveryWithRealSSE exercises the actual |
| 108 | // OpenAI-compatible decoder shape used by the official Flash endpoint. The |
| 109 | // first response emits a tool call without reasoning_content; the second exact |
| 110 | // request includes it; only the adopted call reaches the session and UI. |
| 111 | func TestDeepSeekFlashMissingReasoningRecoveryWithRealSSE(t *testing.T) { |
| 112 | var mu sync.Mutex |
| 113 | var bodies [][]byte |
| 114 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 115 | body, _ := io.ReadAll(r.Body) |
| 116 | mu.Lock() |
| 117 | bodies = append(bodies, append([]byte(nil), body...)) |
| 118 | requestNo := len(bodies) |
| 119 | mu.Unlock() |
| 120 | |
| 121 | w.Header().Set("Content-Type", "text/event-stream") |
| 122 | if requestNo == 2 { |
| 123 | _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"reasoning_content":"call echo safely"}}]}`+"\n\n") |
| 124 | } |
| 125 | if requestNo <= 2 { |
| 126 | _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"echo","arguments":"{\"text\":\"hi\"}"}}]},"finish_reason":"tool_calls"}]}`+"\n\n") |
| 127 | _, _ = io.WriteString(w, `data: {"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":2,"total_tokens":12,"prompt_cache_hit_tokens":10,"prompt_cache_miss_tokens":0}}`+"\n\n") |
| 128 | _, _ = io.WriteString(w, "data: [DONE]\n\n") |
| 129 | return |
| 130 | } |
| 131 | _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"done"},"finish_reason":"stop"}]}`+"\n\n") |
| 132 | _, _ = io.WriteString(w, "data: [DONE]\n\n") |
| 133 | })) |
| 134 | defer srv.Close() |
| 135 | |
| 136 | prov, err := openai.New(provider.Config{ |
| 137 | Name: "deepseek", BaseURL: srv.URL, Model: "deepseek-v4-flash", APIKey: "k", |
| 138 | Extra: map[string]any{"reasoning_protocol": "deepseek", "thinking": "enabled"}, |
| 139 | }) |
| 140 | if err != nil { |
| 141 | t.Fatalf("New provider: %v", err) |
| 142 | } |
| 143 | sink := &recordSink{} |
| 144 | a := New(prov, echoRegistry(), NewSession(""), Options{}, sink) |
| 145 | if err := a.Run(context.Background(), "go"); err != nil { |
| 146 | t.Fatalf("Run: %v", err) |
| 147 | } |
| 148 | |
| 149 | mu.Lock() |
| 150 | gotBodies := append([][]byte(nil), bodies...) |
| 151 | mu.Unlock() |
| 152 | if len(gotBodies) != 3 { |
| 153 | t.Fatalf("HTTP requests = %d, want malformed + recovery + final", len(gotBodies)) |
| 154 | } |
| 155 | if !bytes.Equal(gotBodies[0], gotBodies[1]) { |
| 156 | t.Fatalf("recovery request changed bytes:\nfirst=%s\nretry=%s", gotBodies[0], gotBodies[1]) |
| 157 | } |
| 158 | var toolTurns int |
| 159 | for _, message := range a.Session().Messages { |
| 160 | if message.Role == provider.RoleAssistant && len(message.ToolCalls) > 0 { |
| 161 | toolTurns++ |
| 162 | if message.ReasoningContent != "call echo safely" { |
| 163 | t.Fatalf("adopted reasoning = %q", message.ReasoningContent) |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | if toolTurns != 1 { |
| 168 | t.Fatalf("saved tool turns = %d, want 1", toolTurns) |
| 169 | } |
| 170 | // One partial dispatch from the adopted SSE plus one full execution |
| 171 | // dispatch. The discarded malformed stream must not add a third card. |
| 172 | if got := len(sink.kinds(event.ToolDispatch)); got != 2 { |
| 173 | t.Fatalf("tool dispatch events = %d, want adopted partial + full", got) |
| 174 | } |
| 175 | for _, notice := range sink.kinds(event.Notice) { |
| 176 | if strings.Contains(notice.Text, "reasoning_content") || strings.Contains(notice.Detail, "reasoning_content") { |
| 177 | t.Fatalf("protocol warning leaked to UI: %+v", notice) |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 |