返回 DeepSeek-Reasonix
loop_e2e_test.go
根目录 / internal / agent / loop_e2e_test.go
1 package agent
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "path/filepath"
8 "strings"
9 "sync/atomic"
10 "testing"
11
12 "reasonix/internal/agent/testutil"
13 "reasonix/internal/event"
14 "reasonix/internal/provider"
15 "reasonix/internal/tool"
16 )
17
18 func echoRegistry() *tool.Registry {
19 reg := tool.NewRegistry()
20 reg.Add(echoTool{})
21 return reg
22 }
23
24 func TestStreamIdentityMatchesPersistedAssistant(t *testing.T) {
25 prov := testutil.NewMock("m", testutil.Turn{Text: "answer"})
26 session := NewSession("system")
27 sink := &recordSink{}
28 a := New(prov, tool.NewRegistry(), session, Options{}, sink)
29 if err := a.Run(withNoClosedLoop(context.Background()), "question"); err != nil {
30 t.Fatal(err)
31 }
32 messages := session.Snapshot()
33 users := sink.kinds(event.UserMessage)
34 if len(users) != 1 || users[0].MessageID == "" || users[0].Text != "question" {
35 t.Fatalf("missing admitted user identity: %+v", users)
36 }
37 if messages[len(messages)-2].ID != users[0].MessageID {
38 t.Fatal("user event does not identify the persisted user message")
39 }
40 assistant := messages[len(messages)-1]
41 if assistant.Role != provider.RoleAssistant || assistant.ID == "" {
42 t.Fatalf("missing persisted assistant identity: %+v", assistant)
43 }
44 for _, kind := range []event.Kind{event.Text, event.Message, event.StreamAttempt} {
45 events := sink.kinds(kind)
46 if len(events) == 0 {
47 t.Fatalf("no %v events", kind)
48 }
49 for _, e := range events {
50 if e.MessageID != assistant.ID || e.AttemptID != assistant.ID {
51 t.Fatalf("event identity differs from committed message %q: %+v", assistant.ID, e)
52 }
53 }
54 }
55 }
56
57 func TestToolEventsRetainCommittedMessageIdentityAcrossRounds(t *testing.T) {
58 prov := testutil.NewMock("m",
59 testutil.Turn{ToolCalls: []provider.ToolCall{{ID: "first", Name: "echo", Arguments: `{"text":"one"}`}}},
60 testutil.Turn{ToolCalls: []provider.ToolCall{{ID: "second", Name: "echo", Arguments: `{"text":"two"}`}}},
61 testutil.Turn{Text: "done"},
62 )
63 session := NewSession("system")
64 sink := &recordSink{}
65 a := New(prov, echoRegistry(), session, Options{}, sink)
66 if err := a.Run(withNoClosedLoop(context.Background()), "run both"); err != nil {
67 t.Fatal(err)
68 }
69 owners := map[string]string{}
70 for _, m := range session.Snapshot() {
71 for _, call := range m.ToolCalls {
72 owners[call.ID] = m.ID
73 }
74 }
75 if owners["first"] == "" || owners["second"] == "" || owners["first"] == owners["second"] {
76 t.Fatalf("invalid committed owners: %v", owners)
77 }
78 for _, kind := range []event.Kind{event.ToolDispatch, event.ToolResult} {
79 for _, e := range sink.kinds(kind) {
80 if expected := owners[e.Tool.ID]; expected != "" && e.MessageID != expected {
81 t.Fatalf("tool %s event %v owner %q, want %q", e.Tool.ID, kind, e.MessageID, expected)
82 }
83 }
84 }
85 }
86
87 func TestRunPersistsUserCreatedAtWithoutSendingItToProvider(t *testing.T) {
88 const existingCreatedAt int64 = 1_718_000_000_000
89 prov := testutil.NewMock("m", testutil.Turn{Text: "done"})
90 session := NewSession("system")
91 session.Add(provider.Message{Role: provider.RoleUser, Content: "existing", CreatedAt: existingCreatedAt})
92 agent := New(prov, tool.NewRegistry(), session, Options{}, event.Discard)
93
94 if err := agent.Run(withNoClosedLoop(context.Background()), "new prompt"); err != nil {
95 t.Fatalf("Run: %v", err)
96 }
97 request := prov.LastRequest()
98 if request == nil {
99 t.Fatal("provider received no request")
100 }
101 for i, message := range request.Messages {
102 if message.CreatedAt != 0 {
103 t.Fatalf("provider message %d leaked createdAt %d", i, message.CreatedAt)
104 }
105 }
106
107 messages := session.Snapshot()
108 if len(messages) < 3 || messages[1].CreatedAt != existingCreatedAt {
109 t.Fatalf("persisted existing timestamp changed: %+v", messages)
110 }
111 if messages[2].Role != provider.RoleUser || messages[2].CreatedAt <= 0 {
112 t.Fatalf("new user timestamp was not persisted: %+v", messages[2])
113 }
114 }
115
116 func TestRunPersistsResponsesItemsAcrossSessionReload(t *testing.T) {
117 raw := json.RawMessage(`{"id":"ws_1","type":"web_search_call","status":"completed","action":{"type":"search","query":"latest"}}`)
118 prov := testutil.NewMock("deepseek-responses", testutil.Turn{Chunks: []provider.Chunk{
119 {Type: provider.ChunkResponsesItem, ResponsesItem: raw},
120 {Type: provider.ChunkText, Text: "answer"},
121 {Type: provider.ChunkDone},
122 }})
123 session := NewSession("system")
124 agent := New(prov, tool.NewRegistry(), session, Options{}, event.Discard)
125 if err := agent.Run(withNoClosedLoop(context.Background()), "search"); err != nil {
126 t.Fatalf("Run: %v", err)
127 }
128
129 messages := session.Snapshot()
130 assistant := messages[len(messages)-1]
131 if assistant.Role != provider.RoleAssistant || len(assistant.ResponsesItems) != 1 || string(assistant.ResponsesItems[0]) != string(raw) {
132 t.Fatalf("assistant Responses items = %#v, want persisted search item", assistant.ResponsesItems)
133 }
134
135 path := filepath.Join(t.TempDir(), "responses-items.jsonl")
136 if err := session.Save(path); err != nil {
137 t.Fatalf("Save: %v", err)
138 }
139 loaded, err := LoadSession(path)
140 if err != nil {
141 t.Fatalf("LoadSession: %v", err)
142 }
143 loadedAssistant := loaded.Messages[len(loaded.Messages)-1]
144 if len(loadedAssistant.ResponsesItems) != 1 || string(loadedAssistant.ResponsesItems[0]) != string(raw) {
145 t.Fatalf("reloaded Responses items = %#v, want original item", loadedAssistant.ResponsesItems)
146 }
147 }
148
149 // TestRunMultiToolRoundEmptyIDsSurvivePairing drives the real loop through a turn
150 // that fans out two tool calls carrying no id (a gateway that streams by index),
151 // then asserts both results still pair back after SanitizeToolPairing — the repair
152 // that runs on every send. Keying on tool_call_id alone collapsed them into one,
153 // dropping a result from the model's context on the very next turn.
154 func TestRunMultiToolRoundEmptyIDsSurvivePairing(t *testing.T) {
155 mp := testutil.NewMock("m",
156 testutil.Turn{ToolCalls: []provider.ToolCall{
157 {ID: "", Name: "echo", Arguments: `{"text":"alpha"}`},
158 {ID: "", Name: "echo", Arguments: `{"text":"beta"}`},
159 }},
160 testutil.Turn{Text: "done"},
161 )
162 a := New(mp, echoRegistry(), NewSession(""), Options{}, event.Discard)
163 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
164 t.Fatalf("Run: %v", err)
165 }
166
167 repaired := provider.SanitizeToolPairing(a.Session().Messages)
168 var results []string
169 for _, m := range repaired {
170 if m.Role == provider.RoleTool {
171 results = append(results, m.Content)
172 }
173 }
174 if len(results) != 2 {
175 t.Fatalf("want 2 tool results after pairing, got %d: %v", len(results), results)
176 }
177 if results[0] == results[1] {
178 t.Fatalf("both results collapsed to %q — one was lost from the model's context", results[0])
179 }
180 if !strings.Contains(results[0], "alpha") || !strings.Contains(results[1], "beta") {
181 t.Errorf("results lost their identity: %v", results)
182 }
183 }
184
185 func TestRunPersistsCumulativeAssistantWorkDuration(t *testing.T) {
186 mp := testutil.NewMock("m",
187 testutil.Turn{ToolCalls: []provider.ToolCall{{ID: "call-1", Name: "echo", Arguments: `{"text":"hello"}`}}},
188 testutil.Turn{Text: "done"},
189 )
190 a := New(mp, echoRegistry(), NewSession(""), Options{}, event.Discard)
191 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
192 t.Fatalf("Run: %v", err)
193 }
194
195 var durations []int64
196 for _, message := range a.Session().Messages {
197 if message.Role == provider.RoleAssistant {
198 durations = append(durations, message.WorkDurationMs)
199 }
200 }
201 if len(durations) != 2 {
202 t.Fatalf("assistant durations = %v, want two rounds", durations)
203 }
204 if durations[0] <= 0 || durations[1] < durations[0] {
205 t.Fatalf("assistant durations must be positive and cumulative: %v", durations)
206 }
207 }
208
209 // TestRunCancelledMidStreamLeavesResumableSession proves a turn cancelled before
210 // the model answered leaves the session well-formed: the user message stands,
211 // nothing dangling, and the repaired history is sendable as-is on resume.
212 func TestRunCancelledMidStreamLeavesResumableSession(t *testing.T) {
213 mp := testutil.NewMock("m", testutil.ErrorTurn(context.Canceled))
214 a := New(mp, echoRegistry(), NewSession("sys"), Options{}, event.Discard)
215
216 err := a.Run(withNoClosedLoop(context.Background()), "do the thing")
217 if !errors.Is(err, context.Canceled) {
218 t.Fatalf("Run should surface the cancellation, got %v", err)
219 }
220
221 repaired := provider.SanitizeToolPairing(a.Session().Messages)
222 for i, m := range repaired {
223 if m.Role == provider.RoleTool {
224 t.Fatalf("a cancelled turn left a dangling tool message at %d: %+v", i, m)
225 }
226 }
227 last := repaired[len(repaired)-1]
228 if last.Role != provider.RoleUser || StripTransientUserBlocks(last.Content) != "do the thing" {
229 t.Errorf("the pending user message should survive a cancel, got %+v", last)
230 }
231 }
232
233 func TestRunRecoversInterruptedStreamAfterPartialText(t *testing.T) {
234 interrupted := &provider.StreamInterruptedError{Err: errors.New("deepseek-flash: read stream: unexpected EOF"), Reason: provider.StreamInterruptPrematureEOF}
235 mp := testutil.NewMock("m",
236 testutil.Turn{Text: "partial ", ChunkError: interrupted},
237 testutil.Turn{Text: "continued"},
238 )
239 sink := &recordSink{}
240 a := New(mp, echoRegistry(), NewSession(""), Options{}, sink)
241
242 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
243 t.Fatalf("Run should recover the interrupted stream, got %v", err)
244 }
245 if mp.CallCount() != 2 {
246 t.Fatalf("provider calls = %d, want 2", mp.CallCount())
247 }
248
249 reqs := mp.Requests()
250 if len(reqs) != 2 {
251 t.Fatalf("recorded requests = %d, want 2", len(reqs))
252 }
253 // Codex-style: exact original request replay — no synthetic recovery user
254 // message, no partial assistant in the provider body.
255 if !providerRequestBodiesEqual(reqs[0], reqs[1]) {
256 t.Fatalf("retry must replay the identical provider request\nfirst=%+v\nsecond=%+v", reqs[0], reqs[1])
257 }
258 for _, message := range reqs[1].Messages {
259 if message.LocalOnly || message.Content == "partial " {
260 t.Fatalf("partial assistant leaked into provider recovery request: %+v", reqs[1].Messages)
261 }
262 if strings.Contains(message.Content, "interrupted") && message.Role == provider.RoleUser {
263 t.Fatalf("synthetic stream recovery must not be injected: %+v", message)
264 }
265 }
266 // Successful recovery never persists a LocalOnly interrupted record.
267 for _, message := range a.Session().Messages {
268 if message.LocalOnly {
269 t.Fatalf("successful recovery must not leave LocalOnly interrupt records: %+v", message)
270 }
271 }
272
273 var streamed strings.Builder
274 for _, e := range sink.kinds(event.Text) {
275 streamed.WriteString(e.Text)
276 }
277 // Both attempts emit text to the sink; Desktop discards the first via
278 // stream_attempt. Agent still emits both for non-journal sinks.
279 if !strings.Contains(streamed.String(), "continued") {
280 t.Fatalf("streamed text = %q, want final continued answer", streamed.String())
281 }
282 retries := sink.kinds(event.Retrying)
283 if len(retries) != 1 || retries[0].RetryAttempt != 1 || retries[0].RetryMax != maxStreamRecoveries || retries[0].RetryScope != event.RetryScopeStream {
284 t.Fatalf("retry events = %+v, want one stream recovery retry", retries)
285 }
286 attempts := sink.kinds(event.StreamAttempt)
287 if len(attempts) < 3 {
288 t.Fatalf("stream_attempt events = %d, want begin/discard/begin/commit at least", len(attempts))
289 }
290 var sawDiscard, sawCommit bool
291 for _, e := range attempts {
292 if e.StreamAttempt.Action == event.StreamAttemptDiscard {
293 sawDiscard = true
294 if e.StreamAttempt.Reason != provider.StreamInterruptPrematureEOF {
295 t.Fatalf("discard reason = %q", e.StreamAttempt.Reason)
296 }
297 }
298 if e.StreamAttempt.Action == event.StreamAttemptCommit {
299 sawCommit = true
300 }
301 }
302 if !sawDiscard || !sawCommit {
303 t.Fatalf("stream attempts missing discard/commit: %+v", attempts)
304 }
305 }
306
307 func TestRunRecoversRepeatedInterruptedStreams(t *testing.T) {
308 interrupted := &provider.StreamInterruptedError{Err: errors.New("deepseek-flash: read stream: unexpected EOF")}
309 mp := testutil.NewMock("m",
310 testutil.Turn{Text: "first ", ChunkError: interrupted},
311 testutil.Turn{Text: "second ", ChunkError: interrupted},
312 testutil.Turn{Text: "done"},
313 )
314 sink := &recordSink{}
315 a := New(mp, echoRegistry(), NewSession(""), Options{}, sink)
316
317 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
318 t.Fatalf("Run should recover repeated interrupted streams, got %v", err)
319 }
320 if mp.CallCount() != 3 {
321 t.Fatalf("provider calls = %d, want 3", mp.CallCount())
322 }
323 reqs := mp.Requests()
324 if !providerRequestBodiesEqual(reqs[0], reqs[1]) || !providerRequestBodiesEqual(reqs[0], reqs[2]) {
325 t.Fatalf("all retries must replay the same frozen provider request")
326 }
327
328 var streamed strings.Builder
329 for _, e := range sink.kinds(event.Text) {
330 streamed.WriteString(e.Text)
331 }
332 if !strings.Contains(streamed.String(), "done") {
333 t.Fatalf("streamed text = %q, want final done", streamed.String())
334 }
335 retries := sink.kinds(event.Retrying)
336 if len(retries) != 2 || retries[0].RetryAttempt != 1 || retries[1].RetryAttempt != 2 {
337 t.Fatalf("retry events = %+v, want attempts 1 and 2", retries)
338 }
339 for _, retry := range retries {
340 if retry.RetryMax != maxStreamRecoveries || retry.RetryScope != event.RetryScopeStream {
341 t.Fatalf("retry = %+v, want max=%d scope=stream", retry, maxStreamRecoveries)
342 }
343 }
344 }
345
346 func TestRunRecoversInterruptedPartialToolCallWithoutExecutingIt(t *testing.T) {
347 interrupted := &provider.StreamInterruptedError{Err: errors.New("deepseek-flash: read stream: unexpected EOF")}
348 mp := testutil.NewMock("m",
349 testutil.Turn{Chunks: []provider.Chunk{
350 {Type: provider.ChunkToolCallStart, ToolCall: &provider.ToolCall{ID: "c1", Name: "echo"}},
351 {Type: provider.ChunkError, Err: interrupted},
352 }},
353 testutil.Turn{Text: "recovered"},
354 )
355 a := New(mp, echoRegistry(), NewSession(""), Options{}, event.Discard)
356
357 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
358 t.Fatalf("Run should recover the interrupted tool-call stream, got %v", err)
359 }
360
361 for _, m := range a.Session().Messages {
362 if m.Role == provider.RoleTool && !m.LocalOnly {
363 t.Fatalf("partial tool call should not have executed or produced a tool result: %+v", m)
364 }
365 if m.LocalOnly {
366 t.Fatalf("successful recovery must not leave LocalOnly interrupt: %+v", m)
367 }
368 }
369 reqs := mp.Requests()
370 if len(reqs) != 2 || !providerRequestBodiesEqual(reqs[0], reqs[1]) {
371 t.Fatalf("partial-tool interrupt must exact-replay without synthetic recovery")
372 }
373 }
374
375 func TestRunStreamRetryRequestCountIsLinearNotTriangular(t *testing.T) {
376 interrupted := &provider.StreamInterruptedError{Err: errors.New("eof"), Reason: provider.StreamInterruptPrematureEOF}
377 mp := testutil.NewMock("m",
378 testutil.Turn{Text: "a", Usage: &provider.Usage{PromptTokens: 30, CompletionTokens: 1, TotalTokens: 31, CacheMissTokens: 30}, ChunkError: interrupted},
379 testutil.Turn{Text: "b", Usage: &provider.Usage{PromptTokens: 30, CompletionTokens: 1, TotalTokens: 31, CacheMissTokens: 30}, ChunkError: interrupted},
380 testutil.Turn{Text: "ok", Usage: &provider.Usage{PromptTokens: 30, CompletionTokens: 2, TotalTokens: 32, CacheMissTokens: 30}},
381 )
382 sink := &recordSink{}
383 a := New(mp, echoRegistry(), NewSession(""), Options{}, sink)
384 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
385 t.Fatalf("Run: %v", err)
386 }
387 if mp.CallCount() != 3 {
388 t.Fatalf("provider calls = %d, want 3", mp.CallCount())
389 }
390 usages := sink.kinds(event.Usage)
391 if len(usages) != 1 || usages[0].Usage == nil {
392 t.Fatalf("usage events = %d, want one aggregate", len(usages))
393 }
394 u := usages[0].Usage
395 if u.RequestCount != 3 {
396 t.Fatalf("RequestCount = %d, want 3 (linear, not triangular 6)", u.RequestCount)
397 }
398 // Billable input is summed; context gauge uses ContextPromptTokens.
399 if u.PromptTokens != 90 {
400 t.Fatalf("PromptTokens = %d, want billable sum 90", u.PromptTokens)
401 }
402 if u.ContextPromptTokens != 30 {
403 t.Fatalf("ContextPromptTokens = %d, want latest 30", u.ContextPromptTokens)
404 }
405 if u.CacheHitTokens+u.CacheMissTokens != u.PromptTokens {
406 t.Fatalf("cache split %d+%d must align with PromptTokens %d", u.CacheHitTokens, u.CacheMissTokens, u.PromptTokens)
407 }
408 if u.CompletionTokens != 4 {
409 t.Fatalf("CompletionTokens = %d, want billable sum 4", u.CompletionTokens)
410 }
411 // ContextSnapshot and compaction use the latest full attempt shape.
412 if last := a.sess.output.lastUsage.Load(); last == nil || last.PromptTokens != 30 {
413 t.Fatalf("lastUsage prompt = %+v, want latest attempt prompt 30", last)
414 }
415 }
416
417 func TestRunExhaustedStreamRetriesPersistPendingLocalOnly(t *testing.T) {
418 interrupted := &provider.StreamInterruptedError{Err: errors.New("eof"), Reason: provider.StreamInterruptPrematureEOF}
419 turns := make([]testutil.Turn, 0, maxSamplingAttempts)
420 for range maxSamplingAttempts {
421 turns = append(turns, testutil.Turn{Text: "half", ChunkError: interrupted})
422 }
423 mp := testutil.NewMock("m", turns...)
424 a := New(mp, echoRegistry(), NewSession(""), Options{}, event.Discard)
425
426 err := a.Run(withNoClosedLoop(context.Background()), "go")
427 if !provider.IsStreamInterrupted(err) {
428 t.Fatalf("Run error = %v, want StreamInterruptedError after exhausting retries", err)
429 }
430 if mp.CallCount() != maxSamplingAttempts {
431 t.Fatalf("provider calls = %d, want %d", mp.CallCount(), maxSamplingAttempts)
432 }
433 var pending *provider.InterruptedTurnRecovery
434 var local provider.Message
435 for _, m := range a.Session().Messages {
436 if m.LocalOnly && m.InterruptedTurn != nil && m.InterruptedTurn.Pending {
437 pending = m.InterruptedTurn
438 local = m
439 }
440 }
441 if pending == nil || local.Content != "half" {
442 t.Fatalf("exhausted retries must leave one pending LocalOnly record: local=%+v pending=%+v", local, pending)
443 }
444 // No synthetic recovery user messages mid-turn.
445 for _, m := range a.Session().Messages {
446 if m.Role == provider.RoleUser && strings.Contains(m.Content, "previous assistant response was interrupted") {
447 t.Fatalf("must not inject synthetic stream recovery: %+v", m)
448 }
449 }
450 }
451
452 func TestRunCompleteUncommittedToolCallNeverExecutes(t *testing.T) {
453 // Full tool block arrived, but the stream was interrupted before a clean
454 // terminal — the call stays speculative and must never reach executeBatch.
455 interrupted := &provider.StreamInterruptedError{Err: errors.New("eof"), Reason: provider.StreamInterruptPrematureEOF}
456 writer := &countingWriterTool{}
457 reg := tool.NewRegistry()
458 reg.Add(writer)
459 mp := testutil.NewMock("m",
460 testutil.Turn{Chunks: []provider.Chunk{
461 {Type: provider.ChunkToolCall, ToolCall: &provider.ToolCall{ID: "w1", Name: "write_file", Arguments: `{"path":"x.txt","content":"from-writer"}`}},
462 {Type: provider.ChunkError, Err: interrupted},
463 }},
464 testutil.Turn{Text: "recovered without write"},
465 )
466 a := New(mp, reg, NewSession(""), Options{}, event.Discard)
467 if err := a.Run(withNoClosedLoop(context.Background()), "write it"); err != nil {
468 t.Fatalf("Run: %v", err)
469 }
470 if writer.calls.Load() != 0 {
471 t.Fatalf("writer executed %d times, want 0 (uncommitted tool call)", writer.calls.Load())
472 }
473 }
474
475 type countingWriterTool struct{ calls atomic.Int32 }
476
477 func (c *countingWriterTool) Name() string { return "write_file" }
478 func (c *countingWriterTool) Description() string { return "count writes" }
479 func (c *countingWriterTool) Schema() json.RawMessage {
480 return json.RawMessage(`{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}}}`)
481 }
482 func (c *countingWriterTool) ReadOnly() bool { return false }
483 func (c *countingWriterTool) Execute(context.Context, json.RawMessage) (string, error) {
484 c.calls.Add(1)
485 return "wrote", nil
486 }
487
488 // providerRequestBodiesEqual compares the provider-visible request surface
489 // (messages, tools order/bytes, temperature, token limit, response format).
490 func providerRequestBodiesEqual(a, b provider.Request) bool {
491 if a.MaxTokens != b.MaxTokens {
492 return false
493 }
494 if (a.Temperature == nil) != (b.Temperature == nil) {
495 return false
496 }
497 if a.Temperature != nil && b.Temperature != nil && *a.Temperature != *b.Temperature {
498 return false
499 }
500 if (a.ResponseFormat == nil) != (b.ResponseFormat == nil) {
501 return false
502 }
503 if a.ResponseFormat != nil && b.ResponseFormat != nil && a.ResponseFormat.Type != b.ResponseFormat.Type {
504 return false
505 }
506 if len(a.Messages) != len(b.Messages) || len(a.Tools) != len(b.Tools) {
507 return false
508 }
509 for i := range a.Messages {
510 am, bm := a.Messages[i], b.Messages[i]
511 if am.Role != bm.Role || am.Content != bm.Content || am.ReasoningContent != bm.ReasoningContent ||
512 am.Name != bm.Name || am.ToolCallID != bm.ToolCallID || am.LocalOnly != bm.LocalOnly {
513 return false
514 }
515 if len(am.ToolCalls) != len(bm.ToolCalls) {
516 return false
517 }
518 for j := range am.ToolCalls {
519 if am.ToolCalls[j].ID != bm.ToolCalls[j].ID || am.ToolCalls[j].Name != bm.ToolCalls[j].Name ||
520 am.ToolCalls[j].Arguments != bm.ToolCalls[j].Arguments {
521 return false
522 }
523 }
524 }
525 for i := range a.Tools {
526 if a.Tools[i].Name != b.Tools[i].Name || a.Tools[i].Description != b.Tools[i].Description ||
527 string(a.Tools[i].Parameters) != string(b.Tools[i].Parameters) {
528 return false
529 }
530 }
531 return true
532 }
533
534 func TestRunGenericStreamErrorPersistsLocalDisplayAndInjectsBoundedRecovery(t *testing.T) {
535 apiErr := errors.New("upstream reset")
536 mp := testutil.NewMock("m",
537 testutil.Turn{Reasoning: "private partial reasoning", Text: "visible partial", ChunkError: apiErr},
538 testutil.Turn{Text: "continued safely"},
539 )
540 session := NewSession("system")
541 a := New(mp, echoRegistry(), session, Options{}, event.Discard)
542
543 if err := a.Run(withNoClosedLoop(context.Background()), "change the file"); !errors.Is(err, apiErr) {
544 t.Fatalf("first Run error = %v, want %v", err, apiErr)
545 }
546 msgs := session.Snapshot()
547 last := msgs[len(msgs)-1]
548 if !last.LocalOnly || last.InterruptedTurn == nil || !last.InterruptedTurn.Pending {
549 t.Fatalf("terminal stream error did not leave pending local recovery: %+v", last)
550 }
551 if last.Content != "visible partial" || last.ReasoningContent != "private partial reasoning" {
552 t.Fatalf("local display lost streamed output: %+v", last)
553 }
554
555 if err := a.Run(withNoClosedLoop(context.Background()), "continue"); err != nil {
556 t.Fatalf("second Run: %v", err)
557 }
558 req := mp.Requests()[1]
559 for _, message := range req.Messages {
560 if message.LocalOnly || strings.Contains(message.Content, "visible partial") || strings.Contains(message.ReasoningContent, "private partial reasoning") {
561 t.Fatalf("unsafe partial output leaked to provider: %+v", req.Messages)
562 }
563 }
564 lastUser := req.Messages[len(req.Messages)-1]
565 if lastUser.Role != provider.RoleUser || !strings.Contains(lastUser.Content, "<interrupted-turn-recovery>") ||
566 !strings.Contains(lastUser.Content, "unsafe_partial_output: excluded") || !strings.Contains(lastUser.Content, "continue") {
567 t.Fatalf("next user turn missing bounded recovery block: %+v", lastUser)
568 }
569 if got := StripTransientUserBlocks(lastUser.Content); got != "continue" {
570 t.Fatalf("recovery block leaked into user display: %q", got)
571 }
572 }
573
574 func TestRunRecoveryKeepsCompletedToolPairAndSummarizesChangedFile(t *testing.T) {
575 session := NewSession("system")
576 session.Add(provider.Message{Role: provider.RoleUser, Content: "update config"})
577 session.Add(provider.Message{Role: provider.RoleAssistant, ToolCalls: []provider.ToolCall{{
578 ID: "done-1", Name: "write_file", Arguments: `{"path":"config.json","content":"{}"}`, Added: 1,
579 }}})
580 session.Add(provider.Message{Role: provider.RoleTool, ToolCallID: "done-1", Name: "write_file", Content: "wrote config.json"})
581 session.Add(provider.Message{
582 Role: provider.RoleTool, ToolCallID: provider.LocalOnlyToolID, Name: provider.LocalOnlyToolName, LocalOnly: true,
583 ReasoningContent: "unsafe partial reasoning",
584 InterruptedTurn: &provider.InterruptedTurnRecovery{
585 Pending: true,
586 CompletedTools: []provider.InterruptedToolSummary{{
587 ID: "done-1", Name: "write_file", Files: []string{"config.json"}, Added: 1,
588 }},
589 InterruptedTools: []string{"bash"},
590 DroppedPartialReasoning: true,
591 },
592 })
593 mp := testutil.NewMock("m", testutil.Turn{Text: "done"})
594 a := New(mp, echoRegistry(), session, Options{}, event.Discard)
595 if err := a.Run(withNoClosedLoop(context.Background()), "continue"); err != nil {
596 t.Fatalf("Run: %v", err)
597 }
598
599 req := mp.Requests()[0]
600 if len(req.Messages) != 5 {
601 t.Fatalf("provider request should contain system + user + complete pair + recovery user, got %+v", req.Messages)
602 }
603 if req.Messages[2].Role != provider.RoleAssistant || req.Messages[3].Role != provider.RoleTool {
604 t.Fatalf("completed tool pair was not replayed canonically: %+v", req.Messages)
605 }
606 last := req.Messages[len(req.Messages)-1]
607 for _, want := range []string{"write_file files=config.json diff=+1/-0", "interrupted_tools: bash", "Use these facts", "continue"} {
608 if !strings.Contains(last.Content, want) {
609 t.Fatalf("recovery user message missing %q: %s", want, last.Content)
610 }
611 }
612 if strings.Contains(last.Content, "unsafe partial reasoning") {
613 t.Fatalf("raw partial reasoning leaked into recovery summary: %s", last.Content)
614 }
615 }
616
617 // TestRunWellFormedToolLoopRoundTrips is the happy-path baseline: a tool round
618 // then a final answer. The session must end with the assistant answer and pair
619 // cleanly (the repair is a no-op on well-formed histories).
620 func TestRunWellFormedToolLoopRoundTrips(t *testing.T) {
621 mp := testutil.NewMock("m",
622 testutil.Turn{ToolCalls: []provider.ToolCall{{ID: "c1", Name: "echo", Arguments: `{"text":"hi"}`}}},
623 testutil.Turn{Text: "all set"},
624 )
625 a := New(mp, echoRegistry(), NewSession(""), Options{}, event.Discard)
626 if err := a.Run(withNoClosedLoop(context.Background()), "go"); err != nil {
627 t.Fatalf("Run: %v", err)
628 }
629
630 msgs := a.Session().Messages
631 last := msgs[len(msgs)-1]
632 if last.Role != provider.RoleAssistant || last.Content != "all set" {
633 t.Fatalf("final message should be the assistant answer, got %+v", last)
634 }
635 before := len(msgs)
636 if after := len(provider.SanitizeToolPairing(msgs)); after != before {
637 t.Errorf("repair mutated a well-formed session: %d -> %d", before, after)
638 }
639 }
640
641 // TestRunNotifiesWhenStreamRetriesExhausted pins the #9560 visibility fix:
642 // when every sampling attempt of a model round ends in a stream interruption,
643 // the run must surface a user-readable warn notice explaining the failure —
644 // not only the generic interrupted-turn record.
645 func TestRunNotifiesWhenStreamRetriesExhausted(t *testing.T) {
646 interrupted := &provider.StreamInterruptedError{Err: errors.New("dial tcp: lookup gw.invalid: no such host"), Reason: provider.StreamInterruptIdleTimeout}
647 script := make([]testutil.Turn, maxSamplingAttempts)
648 for i := range script {
649 script[i] = testutil.Turn{ChunkError: interrupted}
650 }
651 mp := testutil.NewMock("m", script...)
652 sink := &recordSink{}
653 a := New(mp, echoRegistry(), NewSession(""), Options{}, sink)
654
655 err := a.Run(withNoClosedLoop(context.Background()), "go")
656 if err == nil {
657 t.Fatal("Run must fail after exhausting stream retries")
658 }
659 if !provider.IsStreamInterrupted(err) {
660 t.Fatalf("terminal error = %v, want a stream interruption", err)
661 }
662 var sawExplanation bool
663 for _, e := range sink.kinds(event.Notice) {
664 if e.Level == event.LevelWarn && strings.Contains(e.Text, "idle timeout") {
665 sawExplanation = true
666 if e.Code != event.NoticeCodeStreamInterruptedIdleTimeout {
667 t.Fatalf("stream interruption notice code = %q", e.Code)
668 }
669 if strings.Contains(e.Text, "gw.invalid") || strings.Contains(e.Text, "dial tcp") {
670 t.Fatalf("notice leaks raw transport error text: %q", e.Text)
671 }
672 }
673 }
674 if !sawExplanation {
675 notices := sink.kinds(event.Notice)
676 t.Fatalf("no warn notice explains the exhausted stream; notices = %+v", notices)
677 }
678 }
679
679 lines GO