| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "reflect" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | |
| 10 | "reasonix/internal/event" |
| 11 | "reasonix/internal/provider" |
| 12 | "reasonix/internal/tool" |
| 13 | ) |
| 14 | |
| 15 | func TestRunAcceptsReasoningOnlyFinalAnswer(t *testing.T) { |
| 16 | prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{ |
| 17 | { |
| 18 | {Type: provider.ChunkReasoning, Text: "I should answer the user."}, |
| 19 | {Type: provider.ChunkDone}, |
| 20 | }, |
| 21 | }} |
| 22 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard) |
| 23 | |
| 24 | if err := a.Run(context.Background(), "answer me"); err != nil { |
| 25 | t.Fatalf("Run: %v", err) |
| 26 | } |
| 27 | if prov.call != 1 { |
| 28 | t.Fatalf("provider calls = %d, want one clean reasoning-only completion", prov.call) |
| 29 | } |
| 30 | if got := lastAssistantContent(a.sess.conversation); got != "" { |
| 31 | t.Fatalf("last assistant content = %q, want empty content beside reasoning", got) |
| 32 | } |
| 33 | if sessionHasUserMessageContaining(a.sess.conversation, "visible answer") { |
| 34 | t.Fatal("must not inject a synthetic visible-answer retry") |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestRunPrefixesReasoningLanguageOnReasoningOnlyCompletion(t *testing.T) { |
| 39 | prov := &mockProvider{name: "p", streams: [][]provider.Chunk{ |
| 40 | { |
| 41 | {Type: provider.ChunkReasoning, Text: "I should answer the user."}, |
| 42 | {Type: provider.ChunkDone}, |
| 43 | }, |
| 44 | }} |
| 45 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{ReasoningLanguage: "zh"}, event.Discard) |
| 46 | |
| 47 | if err := a.Run(context.Background(), "answer me"); err != nil { |
| 48 | t.Fatalf("Run: %v", err) |
| 49 | } |
| 50 | if len(prov.requests) != 1 { |
| 51 | t.Fatalf("provider requests = %d, want 1", len(prov.requests)) |
| 52 | } |
| 53 | got := lastUser(prov.requests[0]) |
| 54 | if !strings.HasPrefix(got, "<reasoning-language>") || !strings.Contains(got, "简体中文") { |
| 55 | t.Fatalf("last user = %q, want reasoning-language prefix", got) |
| 56 | } |
| 57 | if strings.Contains(got, "visible answer") { |
| 58 | t.Fatalf("reasoning-only completion must not receive a synthetic visible-answer retry: %q", got) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func TestRunRequiresVisibleFinalOnlyWhenExplicitlyRequested(t *testing.T) { |
| 63 | prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{ |
| 64 | {{Type: provider.ChunkReasoning, Text: "thinking 1"}, {Type: provider.ChunkDone}}, |
| 65 | {{Type: provider.ChunkReasoning, Text: "thinking 2"}, {Type: provider.ChunkDone}}, |
| 66 | {{Type: provider.ChunkReasoning, Text: "thinking 3"}, {Type: provider.ChunkDone}}, |
| 67 | }} |
| 68 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{RequireVisibleFinal: true}, event.Discard) |
| 69 | |
| 70 | err := a.Run(context.Background(), "answer me") |
| 71 | if err == nil { |
| 72 | t.Fatal("expected repeated empty final answers to stop the run") |
| 73 | } |
| 74 | if !strings.Contains(err.Error(), "visible final answer") { |
| 75 | t.Fatalf("error = %v, want visible final answer", err) |
| 76 | } |
| 77 | if prov.call != 3 { |
| 78 | t.Fatalf("provider calls = %d, want three empty-answer attempts", prov.call) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func TestRunRetriesZeroContentWithTheSameFrozenRequest(t *testing.T) { |
| 83 | prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{ |
| 84 | {{Type: provider.ChunkDone}}, |
| 85 | {{Type: provider.ChunkText, Text: "visible reply"}, {Type: provider.ChunkDone}}, |
| 86 | }} |
| 87 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard) |
| 88 | |
| 89 | if err := a.Run(context.Background(), "answer me"); err != nil { |
| 90 | t.Fatalf("Run: %v", err) |
| 91 | } |
| 92 | if prov.call != 2 { |
| 93 | t.Fatalf("provider calls = %d, want one empty-response retry", prov.call) |
| 94 | } |
| 95 | if len(prov.requests) != 2 || !reflect.DeepEqual(prov.requests[0], prov.requests[1]) { |
| 96 | t.Fatalf("retry requests differ; want the same frozen request:\nfirst=%#v\nsecond=%#v", prov.requests[0], prov.requests[1]) |
| 97 | } |
| 98 | if sessionHasUserMessageContaining(a.sess.conversation, "visible answer") { |
| 99 | t.Fatal("empty-response retry must not inject a synthetic user prompt") |
| 100 | } |
| 101 | if got := lastAssistantContent(a.sess.conversation); got != "visible reply" { |
| 102 | t.Fatalf("last assistant content = %q, want successful retry answer", got) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | func TestRunStopsAfterExhaustedZeroContentRetriesWithoutCommittingEmptyMessages(t *testing.T) { |
| 107 | turns := make([][]provider.Chunk, maxSamplingAttempts) |
| 108 | for i := range turns { |
| 109 | turns[i] = []provider.Chunk{{Type: provider.ChunkDone}} |
| 110 | } |
| 111 | prov := &scriptedProvider{name: "p", turns: turns} |
| 112 | sink := &recordSink{} |
| 113 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, sink) |
| 114 | |
| 115 | err := a.Run(context.Background(), "answer me") |
| 116 | if !errors.Is(err, provider.ErrEmptyResponse) { |
| 117 | t.Fatalf("Run error = %v, want ErrEmptyResponse", err) |
| 118 | } |
| 119 | if prov.call != maxSamplingAttempts { |
| 120 | t.Fatalf("provider calls = %d, want %d bounded attempts", prov.call, maxSamplingAttempts) |
| 121 | } |
| 122 | for _, message := range a.sess.conversation.Messages { |
| 123 | if message.Role == provider.RoleAssistant { |
| 124 | t.Fatalf("empty attempt committed assistant message: %+v", message) |
| 125 | } |
| 126 | if message.Role == provider.RoleUser && strings.Contains(message.Content, "visible answer") { |
| 127 | t.Fatalf("empty attempt injected synthetic user prompt: %q", message.Content) |
| 128 | } |
| 129 | } |
| 130 | retries := sink.kinds(event.Retrying) |
| 131 | if len(retries) != maxStreamRecoveries { |
| 132 | t.Fatalf("retry events = %d, want %d", len(retries), maxStreamRecoveries) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func lastAssistantContent(s *Session) string { |
| 137 | var out string |
| 138 | for _, m := range s.Messages { |
| 139 | if m.Role == provider.RoleAssistant { |
| 140 | out = m.Content |
| 141 | } |
| 142 | } |
| 143 | return out |
| 144 | } |
| 145 | |
| 146 | // deepseekThinkingProvider marks a scripted provider as DeepSeek thinking mode |
| 147 | // (provider.ToolCallReasoningPolicy) — the scope within which a reasoning-only |
| 148 | // finish_reason="stop" turn is accepted as a final answer. |
| 149 | type deepseekThinkingProvider struct{ *scriptedProvider } |
| 150 | |
| 151 | func (deepseekThinkingProvider) RequiresToolCallReasoning() bool { return true } |
| 152 | |
| 153 | func TestRunAcceptsReasoningOnlyFinalWhenModelStopped(t *testing.T) { |
| 154 | // DeepSeek thinking mode streams a long reasoning_content and then |
| 155 | // finishes with finish_reason="stop" but an empty content block. The |
| 156 | // model has explicitly signalled completion and its reasoning was |
| 157 | // streamed to the user, so the host must accept the turn instead of |
| 158 | // retrying and forcing another expensive thinking round. |
| 159 | prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{ |
| 160 | { |
| 161 | {Type: provider.ChunkReasoning, Text: "The user asked a simple question; I have reasoned through it and the answer is ready."}, |
| 162 | {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "stop", TotalTokens: 10}}, |
| 163 | {Type: provider.ChunkDone}, |
| 164 | }, |
| 165 | }} |
| 166 | a := New(deepseekThinkingProvider{prov}, tool.NewRegistry(), NewSession(""), Options{}, event.Discard) |
| 167 | |
| 168 | if err := a.Run(context.Background(), "answer me"); err != nil { |
| 169 | t.Fatalf("Run: %v", err) |
| 170 | } |
| 171 | if prov.call != 1 { |
| 172 | t.Fatalf("provider calls = %d, want 1 (model signalled stop; no retry)", prov.call) |
| 173 | } |
| 174 | if sessionHasUserMessageContaining(a.sess.conversation, "visible answer") { |
| 175 | t.Fatal("must not inject a synthetic visible-answer retry when the model signalled stop") |
| 176 | } |
| 177 | if got := lastAssistantContent(a.sess.conversation); got != "" { |
| 178 | t.Fatalf("last assistant content = %q, want empty (answer lived in reasoning)", got) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | func TestRunAcceptsReasoningOnlyStopWithoutDeepSeekPolicy(t *testing.T) { |
| 183 | // Same chunk sequence as the accept test, but the provider does not |
| 184 | // declare DeepSeek thinking mode (ToolCallReasoningPolicy). The accept |
| 185 | // path must stay scoped to DeepSeek: local <think>-tag models keep the |
| 186 | // retry safety net that often recovers a visible answer on the second |
| 187 | // attempt, and a gateway that mislabels truncation as "stop" must not |
| 188 | // have a degenerate turn committed as the final answer. |
| 189 | prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{ |
| 190 | { |
| 191 | {Type: provider.ChunkReasoning, Text: "thinking only, nothing visible"}, |
| 192 | {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "stop", TotalTokens: 10}}, |
| 193 | {Type: provider.ChunkDone}, |
| 194 | }, |
| 195 | }} |
| 196 | a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard) |
| 197 | |
| 198 | if err := a.Run(context.Background(), "answer me"); err != nil { |
| 199 | t.Fatalf("Run: %v", err) |
| 200 | } |
| 201 | if prov.call != 1 { |
| 202 | t.Fatalf("provider calls = %d, want 1 for a reasoning-only clean terminal", prov.call) |
| 203 | } |
| 204 | if sessionHasUserMessageContaining(a.sess.conversation, "visible answer") { |
| 205 | t.Fatal("must not inject a synthetic visible-answer retry") |
| 206 | } |
| 207 | if got := lastAssistantContent(a.sess.conversation); got != "" { |
| 208 | t.Fatalf("last assistant content = %q, want empty content beside reasoning", got) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | func BenchmarkHasVisibleFinalAnswer(b *testing.B) { |
| 213 | cases := []struct { |
| 214 | name string |
| 215 | text string |
| 216 | }{ |
| 217 | {"normal", "visible reply"}, |
| 218 | {"leading-space", strings.Repeat(" ", 256) + "visible reply"}, |
| 219 | {"all-space", strings.Repeat(" \n\t", 256)}, |
| 220 | } |
| 221 | for _, tc := range cases { |
| 222 | b.Run(tc.name, func(b *testing.B) { |
| 223 | b.ReportAllocs() |
| 224 | var got bool |
| 225 | for range b.N { |
| 226 | got = hasVisibleFinalAnswer(tc.text) |
| 227 | } |
| 228 | _ = got |
| 229 | }) |
| 230 | } |
| 231 | } |
| 232 |