1package agent
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "sync/atomic"
11 "testing"
12
13 "github.com/bnema/zut/packages/agent/scheduler"
14 "github.com/bnema/zut/packages/core"
15 "github.com/bnema/zut/packages/provider"
16)
17
18// TestBotSessionPersistsPlanMutation guards GO-002 for the bot mode: the bot
19// session must persist a plan mutation through the tool-result commit path so
20// the next resume seeds from the file instead of an empty core state.
21func TestBotSessionPersistsPlanMutation(t *testing.T) {
22 t.Setenv("ZUT_HOME", t.TempDir())
23 ag := core.NewAgent(nil, "model", "", nil)
24
25 sess, _, err := openOrCreateSessionForBot(Args{}, Resolved{Provider: "provider", Model: "model"}, ag, "test")
26 if err != nil {
27 t.Fatal(err)
28 }
29 t.Cleanup(func() { _ = sess.Close() })
30 if ag.CommitToolResult == nil {
31 t.Fatal("bot session did not wire CommitToolResult")
32 }
33
34 want := []core.PlanStep{{Step: "one", Status: core.PlanPending}}
35 if err := ag.CommitToolResult("plan-call", planMutationResult(want)); err != nil {
36 t.Fatal(err)
37 }
38 if sess.Meta.Plan == nil {
39 t.Fatal("plan mutation did not write SessionMeta.Plan")
40 }
41
42 path := sess.Path
43 if err := sess.Close(); err != nil {
44 t.Fatal(err)
45 }
46 reopened, _, err := core.OpenSession(path)
47 if err != nil {
48 t.Fatal(err)
49 }
50 defer reopened.Close()
51 if reopened.Meta.Plan == nil {
52 t.Fatal("reopened bot session lost the persisted plan")
53 }
54}
55
56// TestScheduledSessionPersistsPlanMutation guards GO-002 for the scheduled mode:
57// a scheduled turn that calls plan must persist the mutation to the session it
58// reconstructed.
59func TestScheduledSessionPersistsPlanMutation(t *testing.T) {
60 home := t.TempDir()
61 t.Setenv("ZUT_HOME", home)
62 server := scheduledPlanProvider(t)
63 defer server.Close()
64
65 sess, err := core.NewSession(home, t.TempDir(), "openai", "gpt-5", "test")
66 if err != nil {
67 t.Fatal(err)
68 }
69 if err := sess.AppendMessage(provider.Message{
70 Role: provider.RoleUser,
71 Content: []provider.Content{provider.TextBlock{Text: "scheduled task"}},
72 }); err != nil {
73 t.Fatal(err)
74 }
75 id := sess.Meta.ID
76 path := sess.Path
77 if err := sess.Close(); err != nil {
78 t.Fatal(err)
79 }
80
81 args := Args{Provider: "openai", Model: "gpt-5", BaseURL: server.URL, APIKey: "test-key"}
82 base, err := Resolve(args, true)
83 if err != nil {
84 t.Fatal(err)
85 }
86 task := scheduler.Task{ID: "task-1", SessionID: id, Message: "scheduled task"}
87 if err := runScheduledSession(context.Background(), task, args, base, nil, nil); err != nil {
88 t.Fatal(err)
89 }
90
91 reopened, _, err := core.OpenSession(path)
92 if err != nil {
93 t.Fatal(err)
94 }
95 defer reopened.Close()
96 if reopened.Meta.Plan == nil {
97 t.Fatal("scheduled session did not persist the plan mutation")
98 }
99}
100
101// scheduledPlanProvider answers the first request with a plan tool call and the
102// follow-up with a final answer, matching the OpenAI streaming shape the
103// provider parses.
104func scheduledPlanProvider(t *testing.T) *httptest.Server {
105 t.Helper()
106 var calls atomic.Int32
107 return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
108 _, _ = io.ReadAll(r.Body)
109 w.Header().Set("content-type", "text/event-stream")
110 if calls.Add(1) == 1 {
111 arguments := `{"action":"set","steps":[{"step":"one","status":"pending"}]}`
112 chunk := map[string]any{
113 "choices": []any{map[string]any{
114 "index": 0,
115 "delta": map[string]any{"tool_calls": []any{map[string]any{
116 "index": 0,
117 "id": "plan-call-1",
118 "type": "function",
119 "function": map[string]string{"name": "plan", "arguments": arguments},
120 }}},
121 "finish_reason": "tool_calls",
122 }},
123 "usage": map[string]int{"prompt_tokens": 8, "completion_tokens": 2},
124 }
125 data, _ := json.Marshal(chunk)
126 _, _ = fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", data)
127 return
128 }
129 chunk := map[string]any{
130 "choices": []any{map[string]any{"index": 0, "delta": map[string]string{"content": "done"}, "finish_reason": "stop"}},
131 "usage": map[string]int{"prompt_tokens": 8, "completion_tokens": 2},
132 }
133 data, _ := json.Marshal(chunk)
134 _, _ = fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", data)
135 }))
136}