返回 DeepSeek-Reasonix
client_integration_test.go
根目录 / internal / acp / client_integration_test.go
1 package acp
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "path/filepath"
8 "strings"
9 "sync"
10 "testing"
11 "time"
12
13 "reasonix/internal/agent"
14 "reasonix/internal/control"
15 "reasonix/internal/event"
16 "reasonix/internal/permission"
17 "reasonix/internal/provider"
18 )
19
20 // scriptedRequester answers agent → client requests from a per-method script
21 // and records the call order.
22 type scriptedRequester struct {
23 mu sync.Mutex
24 calls []string
25 params map[string]json.RawMessage
26 results map[string]any
27 errs map[string]error
28 }
29
30 func newScriptedRequester() *scriptedRequester {
31 return &scriptedRequester{
32 params: map[string]json.RawMessage{},
33 results: map[string]any{},
34 errs: map[string]error{},
35 }
36 }
37
38 func (r *scriptedRequester) Request(_ context.Context, method string, params any) (json.RawMessage, error) {
39 raw, _ := json.Marshal(params)
40 r.mu.Lock()
41 r.calls = append(r.calls, method)
42 r.params[method] = raw
43 res, err := r.results[method], r.errs[method]
44 r.mu.Unlock()
45 if err != nil {
46 return nil, err
47 }
48 out, _ := json.Marshal(res)
49 return out, nil
50 }
51
52 func (r *scriptedRequester) callOrder() []string {
53 r.mu.Lock()
54 defer r.mu.Unlock()
55 return append([]string(nil), r.calls...)
56 }
57
58 func TestClientIOReadWriteTextFile(t *testing.T) {
59 req := newScriptedRequester()
60 req.results["fs/read_text_file"] = FSReadTextFileResult{Content: "buffer content"}
61 req.results["fs/write_text_file"] = struct{}{}
62 io := newClientIO(req, "sess-1", ClientCapabilities{FS: FSCapabilities{ReadTextFile: true, WriteTextFile: true}})
63
64 content, ok := io.ReadTextFile(context.Background(), "/proj/a.go")
65 if !ok || content != "buffer content" {
66 t.Fatalf("ReadTextFile = %q, %v; want buffer content, true", content, ok)
67 }
68 var readParams FSReadTextFileParams
69 json.Unmarshal(req.params["fs/read_text_file"], &readParams)
70 if readParams.SessionID != "sess-1" || readParams.Path != "/proj/a.go" {
71 t.Fatalf("fs/read_text_file params = %+v", readParams)
72 }
73
74 handled, err := io.WriteTextFile(context.Background(), "/proj/a.go", "new content")
75 if !handled || err != nil {
76 t.Fatalf("WriteTextFile = %v, %v; want true, nil", handled, err)
77 }
78
79 // Without the capability, both degrade to unhandled so tools use the disk.
80 none := newClientIO(req, "sess-1", ClientCapabilities{})
81 if _, ok := none.ReadTextFile(context.Background(), "/proj/a.go"); ok {
82 t.Fatal("ReadTextFile without capability must report ok=false")
83 }
84 if handled, _ := none.WriteTextFile(context.Background(), "/proj/a.go", "x"); handled {
85 t.Fatal("WriteTextFile without capability must report handled=false")
86 }
87
88 // A client read error falls back (ok=false); a client write error surfaces
89 // (falling back could double-apply).
90 req.errs["fs/read_text_file"] = fmt.Errorf("not open")
91 if _, ok := io.ReadTextFile(context.Background(), "/proj/a.go"); ok {
92 t.Fatal("ReadTextFile client error must report ok=false")
93 }
94 req.errs["fs/write_text_file"] = fmt.Errorf("readonly buffer")
95 handled, err = io.WriteTextFile(context.Background(), "/proj/a.go", "x")
96 if !handled || err == nil {
97 t.Fatalf("WriteTextFile client error = %v, %v; want handled=true with error", handled, err)
98 }
99 }
100
101 func TestClientIORunCommandLifecycle(t *testing.T) {
102 req := newScriptedRequester()
103 req.results["terminal/create"] = TerminalCreateResult{TerminalID: "term-1"}
104 req.results["terminal/wait_for_exit"] = TerminalWaitResult{}
105 exitZero := 0
106 req.results["terminal/output"] = TerminalOutputResult{Output: "hello from client", ExitStatus: &TerminalExitStatus{ExitCode: &exitZero}}
107 req.results["terminal/release"] = struct{}{}
108 io := newClientIO(req, "sess-1", ClientCapabilities{Terminal: true})
109
110 out, ok, err := io.RunCommand(context.Background(), "echo hello", "/proj", time.Minute, nil)
111 if !ok || err != nil || out != "hello from client" {
112 t.Fatalf("RunCommand = %q, %v, %v", out, ok, err)
113 }
114 order := io2str(req.callOrder())
115 if order != "terminal/create,terminal/wait_for_exit,terminal/output,terminal/release" {
116 t.Fatalf("call order = %s", order)
117 }
118
119 // A nonzero exit surfaces as an error alongside the captured output.
120 exitOne := 1
121 req.results["terminal/output"] = TerminalOutputResult{Output: "boom", ExitStatus: &TerminalExitStatus{ExitCode: &exitOne}}
122 out, ok, err = io.RunCommand(context.Background(), "false", "/proj", time.Minute, nil)
123 if !ok || err == nil || !strings.Contains(err.Error(), "exit status 1") || out != "boom" {
124 t.Fatalf("RunCommand nonzero exit = %q, %v, %v", out, ok, err)
125 }
126
127 // No terminal capability → unhandled, local bash runs instead.
128 none := newClientIO(req, "sess-1", ClientCapabilities{})
129 if _, ok, _ := none.RunCommand(context.Background(), "echo", "/proj", time.Minute, nil); ok {
130 t.Fatal("RunCommand without capability must report ok=false")
131 }
132
133 // terminal/create failure degrades to unhandled rather than failing the call.
134 req.errs["terminal/create"] = fmt.Errorf("client rejected")
135 if _, ok, _ := io.RunCommand(context.Background(), "echo", "/proj", time.Minute, nil); ok {
136 t.Fatal("RunCommand with failed create must report ok=false")
137 }
138 }
139
140 func io2str(calls []string) string { return strings.Join(calls, ",") }
141
142 func TestUpdateSinkToolLocations(t *testing.T) {
143 s := newUpdateSink(&fakeNotifier{}, "sess")
144 cwd := t.TempDir()
145 s.bindCwd(cwd)
146
147 locs := s.toolLocations("read_file", `{"path":"pkg/a.go","offset":41}`)
148 if len(locs) != 1 || locs[0].Path != filepath.Join(cwd, "pkg", "a.go") {
149 t.Fatalf("read_file locations = %+v", locs)
150 }
151 if locs[0].Line == nil || *locs[0].Line != 42 {
152 t.Fatalf("read_file line = %v, want 42 (offset is 0-based)", locs[0].Line)
153 }
154 // A platform-absolute path passes through untouched.
155 abs := filepath.Join(t.TempDir(), "b.go")
156 absArgs, _ := json.Marshal(map[string]string{"path": abs})
157 if locs := s.toolLocations("edit_file", string(absArgs)); len(locs) != 1 || locs[0].Path != abs || locs[0].Line != nil {
158 t.Fatalf("edit_file locations = %+v, want %s", locs, abs)
159 }
160 if locs := s.toolLocations("bash", `{"command":"ls"}`); locs != nil {
161 t.Fatalf("bash should have no locations, got %+v", locs)
162 }
163 if locs := s.toolLocations("grep", `{"path":"pkg","pattern":"x"}`); locs != nil {
164 t.Fatalf("grep (directory scope) should have no locations, got %+v", locs)
165 }
166 if locs := s.toolLocations("read_file", `{"offset":1}`); locs != nil {
167 t.Fatalf("path-less args should have no locations, got %+v", locs)
168 }
169 }
170
171 func TestPlanEntriesFromTodoArgs(t *testing.T) {
172 entries, ok := planEntriesFromTodoArgs(`{"todos":[
173 {"content":"Phase one","status":"in_progress","level":0},
174 {"content":"Sub step","status":"pending","level":1},
175 {"content":"Done step","status":"completed"},
176 {"content":"","status":"pending"},
177 {"content":"Weird","status":"???"}
178 ]}`)
179 if !ok || len(entries) != 4 {
180 t.Fatalf("entries = %+v, ok=%v; want 4 entries", entries, ok)
181 }
182 if entries[0].Priority != "high" || entries[0].Status != "in_progress" {
183 t.Fatalf("phase entry = %+v", entries[0])
184 }
185 if entries[1].Priority != "medium" {
186 t.Fatalf("sub-step entry = %+v", entries[1])
187 }
188 if entries[3].Status != "pending" {
189 t.Fatalf("unknown status must degrade to pending, got %+v", entries[3])
190 }
191 if _, ok := planEntriesFromTodoArgs(`{"todos":[]}`); ok {
192 t.Fatal("empty todos must not produce a plan update")
193 }
194 if _, ok := planEntriesFromTodoArgs(`not json`); ok {
195 t.Fatal("malformed args must not produce a plan update")
196 }
197 }
198
199 func TestUpdateSinkEmitsPlanForTodoWrite(t *testing.T) {
200 n := &fakeNotifier{}
201 s := newUpdateSink(n, "sess-1")
202 s.Emit(event.Event{Kind: event.ToolDispatch, Tool: event.Tool{
203 ID: "t1", Name: "todo_write", Args: `{"todos":[{"content":"Do it","status":"pending"}]}`,
204 }})
205 // The plan update precedes the tool_call for the same dispatch.
206 plan := n.updateMap(t, 0)
207 if plan["sessionUpdate"] != "plan" {
208 t.Fatalf("first update = %v, want plan", plan["sessionUpdate"])
209 }
210 raw, _ := json.Marshal(plan)
211 if !strings.Contains(string(raw), `"content":"Do it"`) {
212 t.Fatalf("plan update missing entry: %s", raw)
213 }
214 call := n.updateMap(t, 1)
215 if call["sessionUpdate"] != "tool_call" {
216 t.Fatalf("second update = %v, want tool_call", call["sessionUpdate"])
217 }
218 }
219
220 // recordingFactory wraps e2eFactory and captures the SessionParams the service
221 // hands to NewSession, so tests can assert the client-capability wiring.
222 type recordingFactory struct {
223 inner *e2eFactory
224 mu sync.Mutex
225 params []SessionParams
226 }
227
228 func (f *recordingFactory) SessionDir() string { return f.inner.SessionDir() }
229
230 func (f *recordingFactory) NewSession(ctx context.Context, p SessionParams) (*control.Controller, error) {
231 f.mu.Lock()
232 f.params = append(f.params, p)
233 f.mu.Unlock()
234 return f.inner.NewSession(ctx, p)
235 }
236
237 func (f *recordingFactory) last() SessionParams {
238 f.mu.Lock()
239 defer f.mu.Unlock()
240 return f.params[len(f.params)-1]
241 }
242
243 func TestSessionParamsCarryClientIOFromInitializeCaps(t *testing.T) {
244 dir := t.TempDir()
245 prov := &scriptedProvider{name: "fake", responses: [][]provider.Chunk{
246 {{Type: provider.ChunkText, Text: "done"}, {Type: provider.ChunkDone}},
247 }}
248 factory := &recordingFactory{inner: &e2eFactory{
249 prov: prov,
250 tool: fakeTool{name: "peek", ro: true, out: "ok"},
251 policy: permission.New("ask", nil, nil, nil),
252 sessionDir: dir,
253 }}
254 client, stop := startServer(t, factory)
255 defer stop()
256
257 client.call(t, "initialize", InitializeParams{
258 ProtocolVersion: 1,
259 ClientCapabilities: ClientCapabilities{
260 FS: FSCapabilities{ReadTextFile: true, WriteTextFile: true},
261 Terminal: true,
262 },
263 })
264 client.call(t, "session/new", SessionNewParams{Cwd: t.TempDir()})
265 p := factory.last()
266 if p.FileOverlay == nil {
267 t.Fatal("SessionParams.FileOverlay should be bound when the client declares fs capabilities")
268 }
269 if p.Terminal == nil {
270 t.Fatal("SessionParams.Terminal should be bound when the client declares the terminal capability")
271 }
272 }
273
274 func TestSessionParamsNilClientIOWithoutCaps(t *testing.T) {
275 dir := t.TempDir()
276 prov := &scriptedProvider{name: "fake", responses: [][]provider.Chunk{
277 {{Type: provider.ChunkText, Text: "done"}, {Type: provider.ChunkDone}},
278 }}
279 factory := &recordingFactory{inner: &e2eFactory{
280 prov: prov,
281 tool: fakeTool{name: "peek", ro: true, out: "ok"},
282 policy: permission.New("ask", nil, nil, nil),
283 sessionDir: dir,
284 }}
285 client, stop := startServer(t, factory)
286 defer stop()
287
288 client.call(t, "initialize", InitializeParams{ProtocolVersion: 1})
289 client.call(t, "session/new", SessionNewParams{Cwd: t.TempDir()})
290 p := factory.last()
291 if p.FileOverlay != nil || p.Terminal != nil {
292 t.Fatalf("SessionParams overlay/terminal must stay nil without client capabilities; got %v / %v", p.FileOverlay, p.Terminal)
293 }
294 }
295
296 func TestE2ESessionModes(t *testing.T) {
297 dir := t.TempDir()
298 prov := &scriptedProvider{name: "fake", responses: [][]provider.Chunk{
299 {{Type: provider.ChunkText, Text: "done"}, {Type: provider.ChunkDone}},
300 }}
301 factory := &e2eFactory{
302 prov: prov,
303 tool: fakeTool{name: "peek", ro: true, out: "ok"},
304 policy: permission.New("ask", nil, nil, nil),
305 sessionDir: dir,
306 }
307 client, stop := startServer(t, factory)
308 defer stop()
309
310 client.call(t, "initialize", InitializeParams{ProtocolVersion: 1})
311 cwd := t.TempDir()
312 resp := client.call(t, "session/new", SessionNewParams{Cwd: cwd})
313 var nr SessionNewResult
314 if err := json.Unmarshal(resp.Result, &nr); err != nil {
315 t.Fatalf("session/new result: %v", err)
316 }
317 if nr.Modes == nil || nr.Modes.CurrentModeID != sessionModeNormal || len(nr.Modes.AvailableModes) != 3 {
318 t.Fatalf("session/new modes = %+v, want normal current with 3 available", nr.Modes)
319 }
320
321 setResp := client.call(t, "session/set_mode", SessionSetModeParams{SessionID: nr.SessionID, ModeID: sessionModePlan})
322 if setResp.Error != nil {
323 t.Fatalf("session/set_mode: %+v", setResp.Error)
324 }
325 // The switch is confirmed with a current_mode_update notification.
326 deadline := time.After(5 * time.Second)
327 for {
328 select {
329 case n := <-client.notifs:
330 var p struct {
331 Update struct {
332 SessionUpdate string `json:"sessionUpdate"`
333 CurrentModeID string `json:"currentModeId"`
334 } `json:"update"`
335 }
336 if json.Unmarshal(n.Params, &p) == nil && p.Update.SessionUpdate == "current_mode_update" {
337 if p.Update.CurrentModeID != sessionModePlan {
338 t.Fatalf("current_mode_update = %q, want plan", p.Update.CurrentModeID)
339 }
340 goto unknownMode
341 }
342 case <-deadline:
343 t.Fatal("no current_mode_update notification after session/set_mode")
344 }
345 }
346 unknownMode:
347 bad := client.call(t, "session/set_mode", SessionSetModeParams{SessionID: nr.SessionID, ModeID: "yolo"})
348 if bad.Error == nil {
349 t.Fatal("unknown modeId must be rejected")
350 }
351
352 // Reconnecting to the live session must report its actual mode, not a
353 // hardcoded default — the mode picker would otherwise go stale.
354 loadResp := client.call(t, "session/load", SessionLoadParams{SessionID: nr.SessionID, Cwd: cwd})
355 if loadResp.Error != nil {
356 t.Fatalf("session/load: %+v", loadResp.Error)
357 }
358 var lr SessionLoadResult
359 if err := json.Unmarshal(loadResp.Result, &lr); err != nil {
360 t.Fatalf("session/load result: %v", err)
361 }
362 if lr.Modes == nil || lr.Modes.CurrentModeID != sessionModePlan {
363 t.Fatalf("session/load modes = %+v, want current plan for the live session", lr.Modes)
364 }
365 }
366
367 // TestRebuildSessionKeepsClientIOAndMode pins two rebuild invariants: a
368 // model/effort switch must rebuild the controller with the same client
369 // capability wiring (fs overlay, host terminal) the original had, and must
370 // re-apply the session's ACP mode — a fresh controller boots with normal
371 // switches, which would silently drop a user-selected plan mode.
372 func TestRebuildSessionKeepsClientIOAndMode(t *testing.T) {
373 dir := t.TempDir()
374 path := filepath.Join(dir, "sess-rebuild.jsonl")
375 base := agent.NewSession("sys prompt")
376 base.Add(provider.Message{Role: provider.RoleUser, Content: "hi"})
377 if err := base.Save(path); err != nil {
378 t.Fatalf("save session: %v", err)
379 }
380
381 sink := newUpdateSink(&fakeNotifier{}, "sess-rebuild")
382 sess := &acpSession{
383 id: "sess-rebuild",
384 sink: sink,
385 cwd: dir,
386 model: "fast",
387 transcript: path,
388 modeID: sessionModePlan,
389 }
390 lease, err := agent.TryAcquireSessionLease(path)
391 if err != nil {
392 t.Fatalf("acquire session lease: %v", err)
393 }
394 sess.lease = lease
395 t.Cleanup(sess.releaseSessionLease)
396
397 factory := &configurableFactory{dir: dir}
398 svc := &service{
399 factory: factory,
400 sessions: map[string]*acpSession{sess.id: sess},
401 clientCaps: ClientCapabilities{
402 FS: FSCapabilities{ReadTextFile: true, WriteTextFile: true},
403 Terminal: true,
404 },
405 }
406 oldCtrl := control.New(control.Options{
407 Executor: agent.New(nil, nil, base, agent.Options{}, event.Discard),
408 SessionDir: dir,
409 SessionPath: path,
410 Label: "fast",
411 })
412 sess.ctrl = oldCtrl
413
414 if err := svc.rebuildSession(context.Background(), sess, SessionConfigState{Model: "pro"}, []sessionConfigDelta{{axis: "model", model: "pro"}}); err != nil {
415 t.Fatalf("rebuildSession: %v", err)
416 }
417 if sess.ctrl == oldCtrl {
418 t.Fatal("session controller was not replaced")
419 }
420
421 factory.mu.Lock()
422 last := factory.builds[len(factory.builds)-1]
423 factory.mu.Unlock()
424 if last.FileOverlay == nil {
425 t.Fatal("rebuild must keep the fs overlay wiring")
426 }
427 if last.Terminal == nil {
428 t.Fatal("rebuild must keep the host terminal wiring")
429 }
430 if !sess.ctrl.PlanMode() {
431 t.Fatal("rebuild must re-apply the session's plan mode to the new controller")
432 }
433 }
434
434 lines GO