返回 DeepSeek-Reasonix
responses_terminal_helpers_test.go
根目录 / internal / agent / responses_terminal_helpers_test.go
1 package agent
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "reflect"
12 "strings"
13 "sync/atomic"
14 "testing"
15 "time"
16
17 "reasonix/internal/event"
18 "reasonix/internal/provider"
19 "reasonix/internal/provider/responses"
20 "reasonix/internal/tool"
21 )
22
23 type terminalExpectation struct {
24 requests int32
25 outputs map[string]string
26 finals int
27 final string
28 cause error
29 streamInterrupted bool
30 notice string
31 noNotices bool
32 isolateCause bool
33 }
34
35 func runTerminalFixture(t *testing.T, events []string, want terminalExpectation) {
36 t.Helper()
37 var requests, executions atomic.Int32
38 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
39 n := requests.Add(1)
40 body, err := io.ReadAll(r.Body)
41 if err != nil {
42 t.Error(err)
43 return
44 }
45 if n > 1 {
46 assertTerminalOutputs(t, body, want.outputs)
47 if want.isolateCause && strings.Contains(string(body), want.cause.Error()) {
48 t.Error("protocol error cause reached model request")
49 }
50 }
51 w.Header().Set("Content-Type", "text/event-stream")
52 if n > 1 {
53 _, _ = io.WriteString(w, responsesFinalAnswerSSE)
54 return
55 }
56 for _, s := range events {
57 _, _ = fmt.Fprintf(w, "data: %s\n\n", s)
58 }
59 }))
60 defer srv.Close()
61 p := responses.New(responses.Config{Name: "mimo-diagnostic", APIKey: "fake-local-only", BaseURL: "https://api.xiaomimimo.com/v1", RequestURL: srv.URL, Model: "mimo-v2.6-flash", Effort: "high"})
62 reg := tool.NewRegistry()
63 reg.Add(terminalEchoTool{calls: &executions})
64 reg.Add(terminalReadyTool{calls: &executions})
65 sink := &recordSink{}
66 a := New(p, reg, NewSession(""), Options{MissingReasoningWarnStateDir: t.TempDir()}, sink)
67 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
68 defer cancel()
69 err := a.Run(ctx, "执行所需工具,然后报告结果")
70 if !errors.Is(err, want.cause) {
71 t.Errorf("Run error=%v, want cause %v", err, want.cause)
72 }
73 if want.cause != nil && !errors.Is(fmt.Errorf("caller: %w", err), want.cause) {
74 t.Error("wrapped Run error lost identity")
75 }
76 if provider.IsStreamInterrupted(err) != want.streamInterrupted {
77 t.Errorf("stream interruption=%v want=%v", provider.IsStreamInterrupted(err), want.streamInterrupted)
78 }
79 if want.isolateCause && provider.ClassifyRecovery(err).Retryable {
80 t.Error("protocol error became retryable")
81 }
82 if requests.Load() != want.requests {
83 t.Errorf("requests=%d want=%d", requests.Load(), want.requests)
84 }
85 if executions.Load() != int32(len(want.outputs)) {
86 t.Errorf("actual executions=%d want=%d", executions.Load(), len(want.outputs))
87 }
88 if len(sink.kinds(event.Retrying)) != 0 {
89 t.Error("unexpected automatic retry")
90 }
91 gotIDs := map[string]int{}
92 for _, e := range sink.kinds(event.ToolResult) {
93 gotIDs[e.Tool.ID]++
94 }
95 if len(gotIDs) != len(want.outputs) {
96 t.Errorf("tool results=%v want=%v", gotIDs, want.outputs)
97 }
98 for id := range want.outputs {
99 if gotIDs[id] != 1 {
100 t.Errorf("call %s result count=%d want=1", id, gotIDs[id])
101 }
102 }
103 var finals []string
104 calls := map[string]int{}
105 for _, m := range a.Session().Snapshot() {
106 if m.LocalOnly {
107 continue
108 }
109 if want.isolateCause && strings.Contains(m.Content, want.cause.Error()) {
110 t.Error("protocol error cause committed to model history")
111 }
112 if m.Role == provider.RoleAssistant {
113 finals = append(finals, m.Content)
114 for _, call := range m.ToolCalls {
115 calls[call.ID]++
116 }
117 }
118 }
119 if !reflect.DeepEqual(calls, gotIDs) {
120 t.Errorf("committed calls=%v tool results=%v", calls, gotIDs)
121 }
122 if len(finals) != want.finals || (len(finals) > 0 && finals[len(finals)-1] != want.final) {
123 t.Errorf("finals=%q want count=%d final=%q", finals, want.finals, want.final)
124 }
125 notices := sink.kinds(event.Notice)
126 var texts []string
127 for _, e := range notices {
128 texts = append(texts, e.Text)
129 }
130 if want.noNotices && len(notices) > 0 {
131 t.Errorf("unexpected notices=%q", texts)
132 }
133 if want.notice != "" && !strings.Contains(strings.Join(texts, " "), want.notice) {
134 t.Errorf("notices=%q missing %q", texts, want.notice)
135 }
136 if want.isolateCause {
137 // Explicit user continuation is separate from the refused attempt: it must
138 // remain possible without leaking the host's error cause into model input.
139 if err := a.Run(ctx, "继续"); err != nil {
140 t.Fatalf("explicit continuation: %v", err)
141 }
142 if requests.Load() != want.requests+1 {
143 t.Errorf("explicit continuation requests=%d", requests.Load())
144 }
145 }
146 }
147
148 func assertTerminalOutputs(t *testing.T, body []byte, want map[string]string) {
149 t.Helper()
150 var request struct {
151 Input []struct {
152 Type string `json:"type"`
153 CallID string `json:"call_id"`
154 Output string `json:"output"`
155 } `json:"input"`
156 }
157 if err := json.Unmarshal(body, &request); err != nil {
158 t.Error(err)
159 return
160 }
161 got := map[string]string{}
162 counts := map[string]int{}
163 for _, item := range request.Input {
164 if item.Type == "function_call_output" {
165 got[item.CallID] = item.Output
166 counts[item.CallID]++
167 }
168 }
169 if len(got) != len(want) {
170 t.Errorf("continuation outputs=%v want=%v", got, want)
171 }
172 for id, output := range want {
173 if counts[id] != 1 || got[id] != output {
174 t.Errorf("continuation call=%s count=%d output=%q want=%q", id, counts[id], got[id], output)
175 }
176 }
177 }
178
179 type terminalEchoTool struct {
180 echoTool
181 calls *atomic.Int32
182 }
183
184 func (t terminalEchoTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
185 t.calls.Add(1)
186 return t.echoTool.Execute(ctx, args)
187 }
188
189 type terminalReadyTool struct{ calls *atomic.Int32 }
190
191 func (terminalReadyTool) Name() string { return "ready" }
192 func (terminalReadyTool) Description() string { return "report readiness without arguments" }
193 func (terminalReadyTool) Schema() json.RawMessage {
194 return json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`)
195 }
196 func (terminalReadyTool) ReadOnly() bool { return true }
197 func (t terminalReadyTool) Execute(context.Context, json.RawMessage) (string, error) {
198 t.calls.Add(1)
199 return "ready", nil
200 }
201
201 lines GO