Repository navigation
Expand file tree
/
Copy pathagent_test.go
More file actions
3475 lines (3186 loc) · 126 KB
/
Copy pathagent_test.go
File metadata and controls
3475 lines (3186 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package session
import (
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
"github.com/Agent-Field/agentfield/sdk/go/ai"
"github.com/Agent-Field/codeaf/internal/effort"
"github.com/Agent-Field/codeaf/internal/exec/bare"
lanes "github.com/Agent-Field/codeaf/internal/lane"
"github.com/Agent-Field/codeaf/internal/provider"
"github.com/Agent-Field/codeaf/internal/search"
)
// ── the scripted completer ──────────────────────────────────────────────────
// step is one provider request's scripted answer. It receives the request's
// context — so it can emit stream events through provider.Emit exactly as the
// real adapter does — and the messages it was sent.
type step func(ctx context.Context, messages []ai.Message) (*ai.Response, error)
type scriptedCompleter struct {
mu sync.Mutex
steps []step
seen [][]ai.Message
models []string
efforts []provider.Effort
max []int
// aside is the escape hatch from the queue, and it exists because A SCRIPTED
// COMPLETER ANSWERS A CONCURRENT ERRAND BY THE SHAPE OF ITS REQUEST, NEVER BY
// ITS PLACE IN THE QUEUE. The steps above are one positional line: whoever
// calls next takes the next step, whichever goroutine they are on. That is
// exactly right for the turn, which makes its calls one after another, and
// exactly wrong for the errands this session runs beside a turn — a namer, a
// title, a memory pass — which are started on goroutines nothing orders
// against the turn.
//
// The incident was #392. #333 made the two roads that start work nobody typed
// ask for the name the moment they decide to, ahead of the node
// (taskname.go's [nameAhead]) — so the namer's call now lands in the middle
// of a scripted handover. Landing on the slot holding the final answer, the
// turn ran off the end of the script and ended on "(unscripted)"; landing on
// a grinding step, the namer was answered with that round's tool call and the
// task was announced under the trimmed wreckage of it. Both about one run in
// five, and neither a fact about the code under test.
//
// An aside that answers returns its own response and spends NO step, so the
// script the test wrote still reaches the turn in the order the test wrote
// it. taskname_test.go met this race first and routes by shape with
// [isNameCall]; this is the same remedy, made available to every fixture, and
// applied by default to the one errand below that no fixture is about.
aside func(messages []ai.Message) (*ai.Response, bool)
// asides is what the aside answered, kept out of [scriptedCompleter.seen] so
// that a request's index is still the index of the step it rode, and kept at
// all so a test can assert the errand did arrive.
asides [][]ai.Message
}
func (s *scriptedCompleter) CompleteWithMessages(ctx context.Context, messages []ai.Message, options ...ai.Option) (*ai.Response, error) {
// The options are applied to a throwaway request so a test can assert what
// model each step actually rode.
var request ai.Request
for _, option := range options {
_ = option(&request)
}
snapshot := make([]ai.Message, len(messages))
copy(snapshot, messages)
// On a turn a fixture has put a watch on, the conversation answers only once
// the readings beside it have landed ([answerWhenQuiet]).
answerWhenQuiet(ctx, request)
s.mu.Lock()
// THE ASIDE IS CONSULTED BEFORE THE QUEUE IS TOUCHED, which is the whole of
// the law above: an errand recognised by its shape never reaches the step
// counter, so it cannot take a step the turn was scripted to ride.
if s.aside != nil {
if answer, answered := s.aside(snapshot); answered {
s.asides = append(s.asides, snapshot)
s.mu.Unlock()
return answer, nil
}
}
// AND THE NARRATOR IS ANSWERED HERE BY DEFAULT, because it is the one errand
// beside a turn that NO fixture in this package is about. It arms half a
// second into every tool batch (caption.go), which means it can arrive in the
// middle of any scripted turn that runs a command for longer than that —
// three steer and promote fixtures read an empty tool result where the
// sentence carried back to the caller should have been, because the narrator
// had taken the step they scripted for the turn. Defaulting it here fixes
// every such fixture at once, including the ones nobody has written yet.
//
// THE NAMERS ARE NOT DEFAULTED, and that is a fact about the fixtures rather
// than about the errand: three tests in this package are ABOUT the namer —
// they assert its ordering against the work, its request and the tier it ran
// on — and a request answered here is one they can no longer see. They opt in
// with [answerTheReadingsOffTheQueue] instead.
//
// The answer is silence, which is what an errand nobody could reach already
// gives its caller and what every caller in this package already handles. A
// fixture that wants the narrator ANSWERED installs an aside, consulted
// above, which wins — caption_test.go is the one that does.
if isCaptionCall(snapshot) {
s.asides = append(s.asides, snapshot)
s.mu.Unlock()
return textResponse(""), nil
}
// AND SO IS THE SESSION'S OWN NAMER, for the narrator's reason and one
// stronger: since #653 it is started when the person's FIRST MESSAGE is
// accepted rather than when the turn ends (title.go), so it is in flight
// beside the first scripted step of every fixture whose config names a
// session file. There is no ordering between that goroutine and the turn, so
// no positional script can hold a slot for it — a fixture that tried would be
// a coin toss between the turn eating the namer's step and the namer eating
// the turn's.
//
// A fixture that is ABOUT the name installs an aside, consulted above, which
// wins ([titleAside], title_test.go). Everything else gets silence, which
// leaves the session unnamed and is what a namer nobody could reach has
// always given its caller.
if isTitleCall(snapshot) {
s.asides = append(s.asides, snapshot)
s.mu.Unlock()
// AND IT COSTS NOTHING. A namer no fixture scripted did not happen as
// far as that fixture is concerned, and a usage block here is a row on
// the ledger and tokens on the meter that the test's own arithmetic
// knows nothing about — [Agent.addDetachedUsageAs] banks nothing for a
// response that carries none (loop.go).
return &ai.Response{Choices: []ai.Choice{{Message: textMessage("assistant", "")}}}, nil
}
index := len(s.seen)
s.seen = append(s.seen, snapshot)
s.models = append(s.models, request.Model)
s.efforts = append(s.efforts, provider.ReasoningEffortFrom(ctx))
ceiling := 0
if request.MaxTokens != nil {
ceiling = *request.MaxTokens
}
s.max = append(s.max, ceiling)
var next step
if index < len(s.steps) {
next = s.steps[index]
}
s.mu.Unlock()
if next == nil {
// Past the script: answer without a tool call so a loop that ran one
// step further than the test expected terminates instead of hanging.
//
// AND THE ONE ASK THAT WOULD KEEP THE LOOP GOING IS ANSWERED PROPERLY.
// The end of a turn now asks a reader whether the person's ask is
// finished, and re-opens the turn when it is not (checkpoint.go's
// [Agent.checkpointReopen]) — so an unscripted answer of prose to THAT
// question is a test running to the meter's ceiling rather than
// terminating. The remains contract's own token is what "nothing more to
// do here" is spelled as, which is what this branch has always meant.
if len(snapshot) > 0 && strings.Contains(messageText(snapshot[len(snapshot)-1]), "[still asked]") {
return textResponse(checkpointNothingLeft), nil
}
return textResponse("(unscripted)"), nil
}
return next(ctx, snapshot)
}
func (s *scriptedCompleter) request(index int) []ai.Message {
s.mu.Lock()
defer s.mu.Unlock()
if index >= len(s.seen) {
return nil
}
return s.seen[index]
}
func (s *scriptedCompleter) requests() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.seen)
}
// asideRequestsSeen is WHAT the aside answered off the queue, for a fixture that
// has to count one kind of errand among them.
func (s *scriptedCompleter) asideRequestsSeen() [][]ai.Message {
s.mu.Lock()
defer s.mu.Unlock()
seen := make([][]ai.Message, len(s.asides))
copy(seen, s.asides)
return seen
}
// asideRequests is how many errands the aside answered off the queue.
func (s *scriptedCompleter) asideRequests() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.asides)
}
func (s *scriptedCompleter) model(index int) string {
s.mu.Lock()
defer s.mu.Unlock()
if index >= len(s.models) {
return ""
}
return s.models[index]
}
func textResponse(text string) *ai.Response {
return &ai.Response{
Choices: []ai.Choice{{Message: ai.Message{
Role: "assistant",
Content: []ai.ContentPart{{Type: "text", Text: text}},
}}},
Usage: &ai.Usage{PromptTokens: 10, CompletionTokens: 5, TotalTokens: 15},
}
}
func toolResponse(id, name, arguments string) *ai.Response {
return toolResponseWithText(id, name, arguments, "")
}
// toolResponseWithText is the shape a real provider returns when the model
// says something before calling a tool: text AND tool calls in one response.
func toolResponseWithText(id, name, arguments, text string) *ai.Response {
return &ai.Response{
Choices: []ai.Choice{{Message: ai.Message{
Role: "assistant",
Content: []ai.ContentPart{{Type: "text", Text: text}},
ToolCalls: []ai.ToolCall{{
ID: id,
Type: "function",
Function: ai.ToolCallFunction{Name: name, Arguments: arguments},
}},
}}},
Usage: &ai.Usage{PromptTokens: 20, CompletionTokens: 7, TotalTokens: 27},
}
}
// ── harness ─────────────────────────────────────────────────────────────────
func newTestAgent(t *testing.T, completer Completer, mutate func(*Config)) (*Agent, string) {
t.Helper()
workspace := t.TempDir()
config := Config{
Workspace: workspace,
Model: "test/model",
// A fixed system prompt keeps every assertion about the transcript
// independent of today's date and the machine's arch.
System: "SYSTEM",
// The product default for the spending row is ON (task.audit — the
// config row defaults on and the door wires it). A test that wants it
// off says so in mutate; a test that says nothing gets the product's own
// posture.
TaskAudit: true,
}
if mutate != nil {
mutate(&config)
}
agent, err := newAgent(config, completer)
if err != nil {
t.Fatalf("newAgent: %v", err)
}
// A SESSION'S DEFERRED WRITES ARE SETTLED BEFORE ITS DIRECTORIES GO AWAY, the
// same call an exit door owes ([Agent.SettleWrites], placemeta.go). Cleanups
// run last-registered-first, so this lands before the tempdirs above it.
//
// AND THE SETTLE IS AFTER THE CLOSE, which is the order these two were in the
// wrong way round. [Agent.Close] settles on its own way in, so a settle in
// front of it is a settle of what the session owed a moment ago; what can
// still be owed is what the CLOSE itself sets in motion — a node stopped, a
// follow-up dropped, a place referred on the way out — and a write owed there
// lands on a directory the runner has already taken away
// (`TempDir RemoveAll cleanup: directory not empty`).
t.Cleanup(agent.SettleWrites)
t.Cleanup(func() { _ = agent.Close() })
return agent, workspace
}
// collect drains one turn's stream to close, failing rather than hanging.
func collect(t *testing.T, events <-chan Event) []Event {
t.Helper()
var collected []Event
deadline := time.After(10 * time.Second)
for {
select {
case event, open := <-events:
if !open {
return collected
}
collected = append(collected, event)
case <-deadline:
t.Fatalf("turn did not finish; events so far: %v", kinds(collected))
return nil
}
}
}
func kinds(events []Event) []EventKind {
out := make([]EventKind, len(events))
for i, event := range events {
out[i] = event.Kind
}
return out
}
func lastMessage(a *Agent) ai.Message {
a.mu.Lock()
defer a.mu.Unlock()
return a.messages[len(a.messages)-1]
}
func messageText(message ai.Message) string {
var out strings.Builder
for _, part := range message.Content {
out.WriteString(part.Text)
}
return out.String()
}
// transcriptRoles is the live transcript's roles in order. It is not named
// `roles` because the package now imports internal/roles, and a package-level
// name may not shadow a file's import.
func transcriptRoles(a *Agent) []string {
a.mu.Lock()
defer a.mu.Unlock()
out := make([]string, len(a.messages))
for i, message := range a.messages {
out[i] = message.Role
}
return out
}
// ── (a) deltas stream in order and the final text is their concatenation ────
func TestSubmitStreamsDeltasInOrder(t *testing.T) {
chunks := []string{"the ", "tokenizer ", "is fine"}
completer := &scriptedCompleter{steps: []step{
func(ctx context.Context, _ []ai.Message) (*ai.Response, error) {
for _, chunk := range chunks {
provider.Emit(ctx, provider.StreamDelta, chunk)
}
return textResponse(strings.Join(chunks, "")), nil
},
}}
agent, _ := newTestAgent(t, completer, nil)
events, err := agent.Submit(context.Background(), "how is the tokenizer?")
if err != nil {
t.Fatalf("Submit: %v", err)
}
collected := collect(t, events)
var streamed []string
for _, event := range collected {
if event.Kind == EventTextDelta {
streamed = append(streamed, event.Text)
}
}
if strings.Join(streamed, "|") != strings.Join(chunks, "|") {
t.Fatalf("deltas = %q, want %q", streamed, chunks)
}
final := collected[len(collected)-1]
if final.Kind != EventTurnDone {
t.Fatalf("last event = %v, want EventTurnDone", final.Kind)
}
if final.Usage.Input != 10 || final.Usage.Output != 5 || final.Usage.Turns != 1 {
t.Fatalf("turn usage = %+v, want input 10 / output 5 / turns 1", final.Usage)
}
if final.Usage.Duration <= 0 {
t.Fatalf("turn usage carries no duration: %+v", final.Usage)
}
if got := messageText(lastMessage(agent)); got != strings.Join(chunks, "") {
t.Fatalf("recorded reply = %q, want the concatenated deltas", got)
}
if session := agent.Usage(); session.Input != 10 || session.Output != 5 || session.Turns != 1 {
t.Fatalf("session usage = %+v, want it to match the one turn", session)
}
}
// ── (b) a tool round executes and its result is appended ────────────────────
func TestSubmitRunsToolAndAppendsResult(t *testing.T) {
var workspace string
completer := &scriptedCompleter{steps: []step{
func(context.Context, []ai.Message) (*ai.Response, error) {
return toolResponse("call-1", "read", `{"path":"note.txt"}`), nil
},
func(_ context.Context, messages []ai.Message) (*ai.Response, error) {
return textResponse("read it"), nil
},
}}
agent, ws := newTestAgent(t, completer, nil)
workspace = ws
if err := os.WriteFile(filepath.Join(workspace, "note.txt"), []byte("hello from disk\n"), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
collected := collect(t, mustSubmit(t, agent, "read note.txt"))
if got, want := transcriptRoles(agent), []string{"system", "user", "assistant", "tool", "assistant"}; !equalStrings(got, want) {
t.Fatalf("transcript roles = %v, want %v", got, want)
}
agent.mu.Lock()
toolMessage := agent.messages[3]
agent.mu.Unlock()
if toolMessage.ToolCallID != "call-1" {
t.Fatalf("tool result id = %q, want call-1", toolMessage.ToolCallID)
}
if !strings.Contains(messageText(toolMessage), "hello from disk") {
t.Fatalf("tool result = %q, want the file's content", messageText(toolMessage))
}
// The second request must carry the whole round: append-only transcript.
second := completer.request(1)
if len(second) != 4 || second[2].Role != "assistant" || second[3].Role != "tool" {
t.Fatalf("second request = %v roles, want system/user/assistant/tool", rolesOf(second))
}
var begin, end *Event
for i := range collected {
switch collected[i].Kind {
case EventToolBegin:
begin = &collected[i]
case EventToolEnd:
end = &collected[i]
case EventToolFailed:
t.Fatalf("tool failed: %s", collected[i].Hint)
}
}
if begin == nil || begin.Tool != "read" || begin.Hint != "read note.txt" {
t.Fatalf("tool begin = %+v, want read/note.txt gloss", begin)
}
if end == nil || end.Tool != "read" {
t.Fatalf("tool end = %+v, want read", end)
}
// The detail a surface expands a row with: the arguments on the begin, the
// result on the end.
if begin.Args != `{"path":"note.txt"}` {
t.Fatalf("begin Args = %q, want the call's arguments", begin.Args)
}
if begin.Output != "" {
t.Fatalf("begin Output = %q, want empty — the call has not run yet", begin.Output)
}
if end.Args != `{"path":"note.txt"}` {
t.Fatalf("end Args = %q, want the call's arguments", end.Args)
}
if !strings.Contains(end.Output, "hello from disk") {
t.Fatalf("end Output = %q, want the tool's result text", end.Output)
}
// The event's copy is capped; the transcript's is the whole thing. They
// agree here because the result is short.
if end.Output != messageText(toolMessage) {
t.Fatalf("end Output = %q, want the verbatim result %q", end.Output, messageText(toolMessage))
}
}
// Event.Output is a display copy, so an oversized result is cut at the cap and
// says how much was left behind — the wire result the model reads stays whole.
func TestToolOutputIsCappedWithAByteCount(t *testing.T) {
const overflow = 500
long := strings.Repeat("x", outputLimit+overflow)
agent, _ := newTestAgent(t, &scriptedCompleter{}, nil)
agent.tools = append(agent.tools, bare.Tool{
Name: "bulk",
Description: "returns more than a screen",
Schema: json.RawMessage(`{"type":"object","properties":{}}`),
Execute: func(context.Context, json.RawMessage) (string, bool, error) {
return long, false, nil
},
})
hub := newEventHub()
events := hub.subscribe()
call := ai.ToolCall{
ID: "c1", Type: "function",
Function: ai.ToolCallFunction{Name: "bulk", Arguments: "{\n \"lines\" : 4500\n}"},
}
var results []toolResult
go func() {
results = agent.runTools(context.Background(), []ai.ToolCall{call}, hub)
hub.close()
}()
collected := collect(t, events)
var begin, end *Event
for i := range collected {
switch collected[i].Kind {
case EventToolBegin:
begin = &collected[i]
case EventToolEnd:
end = &collected[i]
case EventToolFailed:
t.Fatalf("tool failed: %s", collected[i].Hint)
}
}
if begin == nil || end == nil {
t.Fatalf("events = %v, want a begin and an end", kinds(collected))
}
// Whitespace in the model's JSON is compacted away: Args is one line.
if begin.Args != `{"lines":4500}` {
t.Fatalf("begin Args = %q, want the compacted arguments", begin.Args)
}
want := strings.Repeat("x", outputLimit) + "… (500 more bytes)"
if end.Output != want {
t.Fatalf("end Output = %q (%d bytes), want the first %d bytes plus the byte-count suffix",
clip(end.Output, 80), len(end.Output), outputLimit)
}
// The result the model reads is untouched: Output caps the display copy,
// never the wire.
if len(results) != 1 || results[0].text != long {
t.Fatalf("tool result is %d bytes, want the full %d — the cap is display-only",
len(results[0].text), len(long))
}
}
// Event.Args carries a WHOLE edit payload, because the surface computes that
// edit's "+N −M" and its unified diff from the old/new strings and from nothing
// else — the tool's own result is one sentence saying it worked. A cap that cut
// a real edit off mid-string would not shorten the diff; it would produce the
// wrong number.
func TestToolArgsCarryAWholeEditPayload(t *testing.T) {
// A replacement the size of a function: far past the old 400-byte cap, and
// an ordinary thing for a model to send.
block := strings.Repeat("\tfmt.Println(\"the quick brown fox\")\n", 40)
arguments, err := json.Marshal(map[string]any{
"path": "internal/session/loop.go",
"edits": []map[string]string{{
"oldText": block,
"newText": block + "\tfmt.Println(\"and one more\")\n",
}},
})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if len(arguments) <= 400 {
t.Fatalf("the fixture is %d bytes, which the old cap would not have cut", len(arguments))
}
got := argsText(ai.ToolCall{
ID: "c1", Type: "function",
Function: ai.ToolCallFunction{Name: "edit", Arguments: string(arguments)},
})
if got != string(arguments) {
t.Fatalf("Args is %d bytes, want the whole %d-byte payload", len(got), len(arguments))
}
// It is still a cap, and it is still display-only: past the limit the copy
// is shortened and marked, and the wire arguments are never touched.
//
// THE SHORTENING HAPPENS INSIDE THE STRING. What comes back is still a JSON
// object a surface can read a field out of — that is the contract, and the
// version of this that cut at a byte offset ended the payload mid-literal and
// made internal/tui3 draw an em dash for every write worth opening.
huge := `{"path":"f.go","edits":[{"oldText":"` + strings.Repeat("x", argsLimit) + `"}]}`
capped := argsText(ai.ToolCall{
ID: "c2", Type: "function",
Function: ai.ToolCallFunction{Name: "edit", Arguments: huge},
})
if len(capped) >= len(huge) || len(capped) > argsLimit {
t.Fatalf("an oversized payload was not capped: %d bytes, limit %d", len(capped), argsLimit)
}
var fields struct {
Path string `json:"path"`
Edits []struct {
OldText string `json:"oldText"`
} `json:"edits"`
}
if err := json.Unmarshal([]byte(capped), &fields); err != nil {
t.Fatalf("a capped payload no longer parses: %v", err)
}
if fields.Path != "f.go" || len(fields.Edits) != 1 {
t.Fatalf("a capped payload lost its shape: %+v", fields)
}
if !strings.HasPrefix(fields.Edits[0].OldText, "xxxx") ||
!strings.HasSuffix(fields.Edits[0].OldText, "more bytes)") {
t.Fatalf("the capped field is not marked: ends %q", lastRunes(fields.Edits[0].OldText, 24))
}
}
func lastRunes(s string, n int) string {
runes := []rune(s)
if len(runes) <= n {
return s
}
return string(runes[len(runes)-n:])
}
// ── (c) Interrupt keeps the partial reply ───────────────────────────────────
func TestInterruptKeepsPartialReply(t *testing.T) {
streaming := make(chan struct{})
completer := &scriptedCompleter{steps: []step{
func(ctx context.Context, _ []ai.Message) (*ai.Response, error) {
provider.Emit(ctx, provider.StreamDelta, "half an ans")
close(streaming)
<-ctx.Done()
return nil, ctx.Err()
},
}}
agent, _ := newTestAgent(t, completer, nil)
events := mustSubmit(t, agent, "explain the planner")
select {
case <-streaming:
case <-time.After(10 * time.Second):
t.Fatal("the scripted step never streamed")
}
agent.Interrupt()
collected := collect(t, events)
if last := collected[len(collected)-1]; last.Kind != EventTurnDone {
t.Fatalf("interrupted turn ended with %v, want EventTurnDone", last.Kind)
}
message := lastMessage(agent)
if message.Role != "assistant" || messageText(message) != "half an ans" {
t.Fatalf("kept message = %s/%q, want the streamed partial", message.Role, messageText(message))
}
// A second Submit must be accepted: the turn is over, not wedged.
if _, err := agent.Submit(context.Background(), "never mind"); err != nil {
t.Fatalf("Submit after interrupt: %v", err)
}
}
// ── (d) steering rides the in-flight turn ───────────────────────────────────
func TestSubmitDuringTurnSteersIt(t *testing.T) {
entered := make(chan struct{})
release := make(chan struct{})
completer := &scriptedCompleter{steps: []step{
func(context.Context, []ai.Message) (*ai.Response, error) {
close(entered)
<-release
return toolResponse("call-1", "ls", `{"path":"."}`), nil
},
func(context.Context, []ai.Message) (*ai.Response, error) {
return textResponse("folded it in"), nil
},
}}
agent, _ := newTestAgent(t, completer, nil)
events := mustSubmit(t, agent, "list the workspace")
select {
case <-entered:
case <-time.After(10 * time.Second):
t.Fatal("the first step never started")
}
steered, err := agent.Submit(context.Background(), "also count the files")
if err != nil {
t.Fatalf("steering Submit: %v", err)
}
close(release)
collect(t, events)
// The steering caller holds a live channel onto the same turn; drain it so
// the turn's pump is not left parked on a send.
collect(t, steered)
if completer.requests() != 2 {
t.Fatalf("requests = %d, want 2", completer.requests())
}
second := completer.request(1)
found := false
for _, message := range second {
if message.Role == "user" && messageText(message) == "also count the files" {
found = true
}
}
if !found {
t.Fatalf("steering message missing from the next request: %v", rolesOf(second))
}
// It lands AFTER the tool result — the step boundary, not mid-batch.
if got, want := rolesOf(second), []string{"system", "user", "assistant", "tool", "user"}; !equalStrings(got, want) {
t.Fatalf("second request roles = %v, want %v", got, want)
}
}
// ── (d2) the steering Submit gets a live stream of its own ──────────────────
// A surface that calls Submit per message reads the returned channel as "this
// turn". An already-closed channel would read as "the turn ended", which is
// the opposite of what a steering Submit just did — so the steering caller
// subscribes to the in-flight turn's hub and sees the rest of it.
func TestSteeringSubmitStreamsTheTurn(t *testing.T) {
entered := make(chan struct{})
release := make(chan struct{})
completer := &scriptedCompleter{steps: []step{
func(context.Context, []ai.Message) (*ai.Response, error) {
close(entered)
<-release
return toolResponse("call-1", "ls", `{"path":"."}`), nil
},
func(ctx context.Context, _ []ai.Message) (*ai.Response, error) {
provider.Emit(ctx, provider.StreamDelta, "folded it in")
return textResponse("folded it in"), nil
},
}}
agent, _ := newTestAgent(t, completer, nil)
first := mustSubmit(t, agent, "list the workspace")
select {
case <-entered:
case <-time.After(10 * time.Second):
t.Fatal("the first step never started")
}
// B subscribes while A's turn is blocked inside step 0, so everything the
// turn emits from here on must reach B.
second, err := agent.Submit(context.Background(), "also count the files")
if err != nil {
t.Fatalf("steering Submit: %v", err)
}
close(release)
collectedA := collect(t, first)
collectedB := collect(t, second)
if len(collectedB) == 0 {
t.Fatal("steering channel carried no events; it must stream the rest of the turn")
}
if last := collectedB[len(collectedB)-1]; last.Kind != EventTurnDone {
t.Fatalf("steering channel ended with %v, want EventTurnDone", last.Kind)
}
// Both channels closed (collect only returns on close) and both saw the
// work that happened after B subscribed: the tool round and the reply.
for name, collected := range map[string][]Event{"A": collectedA, "B": collectedB} {
var sawToolBegin, sawDelta bool
for _, event := range collected {
switch event.Kind {
case EventToolBegin:
sawToolBegin = event.Tool == "ls"
case EventTextDelta:
sawDelta = event.Text == "folded it in"
case EventToolFailed:
t.Fatalf("%s: tool failed: %s", name, event.Hint)
}
}
if !sawToolBegin || !sawDelta {
t.Fatalf("%s events = %v, want the ls round and the reply delta", name, kinds(collected))
}
}
// And the steering text still landed in the turn's next request.
if completer.requests() != 2 {
t.Fatalf("requests = %d, want 2", completer.requests())
}
if got, want := rolesOf(completer.request(1)), []string{"system", "user", "assistant", "tool", "user"}; !equalStrings(got, want) {
t.Fatalf("second request roles = %v, want %v", got, want)
}
if got := messageText(completer.request(1)[4]); got != "also count the files" {
t.Fatalf("steering message = %q, want the text B submitted", got)
}
}
// Two Submits racing inside one turn both steer and both stream.
func TestConcurrentSteeringSubmitsAllStream(t *testing.T) {
entered := make(chan struct{})
release := make(chan struct{})
completer := &scriptedCompleter{steps: []step{
func(context.Context, []ai.Message) (*ai.Response, error) {
close(entered)
<-release
return textResponse("answered"), nil
},
}}
agent, _ := newTestAgent(t, completer, nil)
first := mustSubmit(t, agent, "start")
select {
case <-entered:
case <-time.After(10 * time.Second):
t.Fatal("the first step never started")
}
var wg sync.WaitGroup
streams := make([]<-chan Event, 2)
errs := make([]error, 2)
for i, text := range []string{"steer one", "steer two"} {
wg.Add(1)
go func(index int, message string) {
defer wg.Done()
streams[index], errs[index] = agent.Submit(context.Background(), message)
}(i, text)
}
wg.Wait()
close(release)
collect(t, first)
for index, stream := range streams {
if errs[index] != nil {
t.Fatalf("racing Submit %d: %v", index, errs[index])
}
collected := collect(t, stream)
if len(collected) == 0 || collected[len(collected)-1].Kind != EventTurnDone {
t.Fatalf("racing Submit %d events = %v, want a stream ending in EventTurnDone", index, kinds(collected))
}
}
// Both texts are queued as steering; the turn ended before a second step,
// so they wait in the transcript for the next one.
pending := steeringQueue(agent)
transcript := strings.Join(pending, "|")
agent.mu.Lock()
for _, message := range agent.messages {
if message.Role == "user" {
transcript += "|" + messageText(message)
}
}
agent.mu.Unlock()
for _, want := range []string{"steer one", "steer two"} {
if !strings.Contains(transcript, want) {
t.Fatalf("steering text %q was dropped; saw %q", want, transcript)
}
}
}
// ── (e) compaction ──────────────────────────────────────────────────────────
func TestCompactionRebuildsTranscript(t *testing.T) {
long := strings.Repeat("working through the parser. ", 40)
completer := &scriptedCompleter{steps: []step{
func(context.Context, []ai.Message) (*ai.Response, error) {
return &ai.Response{Choices: []ai.Choice{{Message: ai.Message{
Role: "assistant",
Content: []ai.ContentPart{{Type: "text", Text: long}},
}}}}, nil
},
}}
agent, _ := newTestAgent(t, completer, func(config *Config) {
// A 200-token window puts the threshold at 100 and the keep-recent tail
// at 50, so one long reply is already too much.
config.ContextWindow = 200
config.CompactEnabled = true
})
collected := collect(t, mustSubmit(t, agent, "start"))
var compacted *Event
for i := range collected {
if collected[i].Kind == EventCompacted {
compacted = &collected[i]
}
}
if compacted == nil {
t.Fatalf("no EventCompacted; events = %v", kinds(collected))
}
if !strings.HasPrefix(compacted.Hint, "compacted · ") || !strings.Contains(compacted.Hint, "folded 1 message") {
t.Fatalf("compaction hint = %q", compacted.Hint)
}
agent.mu.Lock()
messages := agent.messages
agent.mu.Unlock()
if got, want := rolesOf(messages), []string{"system", "user", "user"}; !equalStrings(got, want) {
t.Fatalf("compacted transcript = %v, want system/question/marker", got)
}
if messageText(messages[0]) != "SYSTEM" {
t.Fatalf("system message was rewritten: %q", messageText(messages[0]))
}
// THE PERSON'S OWN WORDS SURVIVE. Nothing else in a transcript can be
// reconstructed from anywhere, so nothing else is protected this way.
if messageText(messages[1]) != "start" {
t.Fatalf("the question was folded away: %q", messageText(messages[1]))
}
marker := messageText(messages[2])
if !strings.HasPrefix(marker, foldMarkerPrefix) || strings.Contains(marker, "working through the parser") {
t.Fatalf("fold marker = %q", marker)
}
// AND NO MODEL RAN IN IT. One request was made — the turn's own — and the
// pass that followed it cost nothing at all.
if got := completer.requests(); got != 1 {
t.Fatalf("requests = %d, want the turn's one and no compaction call", got)
}
final := collected[len(collected)-1]
if final.Kind != EventTurnDone {
t.Fatalf("last event = %v, want EventTurnDone", final.Kind)
}
if session := agent.Usage(); session.Input != 0 || session.Output != 0 {
t.Fatalf("session usage = %+v, want a compaction that bought nothing", session)
}
}
// A fold takes an assistant message and the results answering it TOGETHER. A
// tool result whose call went is an orphan every provider rejects with a 400 —
// on this request and on every request after it, because the transcript is
// append-only.
func TestCompactionFoldsAToolBatchWhole(t *testing.T) {
agent, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) {
config.ContextWindow = 200
})
agent.mu.Lock()
agent.messages = append(agent.messages,
textMessage("user", "read them"),
ai.Message{
Role: "assistant",
Content: []ai.ContentPart{{Type: "text", Text: strings.Repeat("looking at the file. ", 40)}},
ToolCalls: []ai.ToolCall{{
ID: "c1", Type: "function",
Function: ai.ToolCallFunction{Name: "read", Arguments: `{"path":"a.go"}`},
}},
},
ai.Message{
Role: "tool",
ToolCallID: "c1",
Content: []ai.ContentPart{{Type: "text", Text: "package a"}},
},
textMessage("assistant", "done"))
agent.mu.Unlock()
compacted, err := agent.compact(context.Background(), nil)
if err != nil || !compacted {
t.Fatalf("compact = %v, %v; want a pass that ran", compacted, err)
}
agent.mu.Lock()
messages := agent.messages
agent.mu.Unlock()
for _, message := range messages {
if message.Role == "tool" {
t.Fatalf("an orphaned tool result survived the fold: %v", rolesOf(messages))
}
}
if got, want := rolesOf(messages), []string{"system", "user", "user", "assistant"}; !equalStrings(got, want) {
t.Fatalf("folded transcript = %v, want %v", got, want)
}
}
func TestCompactBelowTheFloorReportsNothingToCompact(t *testing.T) {
completer := &scriptedCompleter{}
agent, _ := newTestAgent(t, completer, nil)
collect(t, mustSubmit(t, agent, "hello"))
// A no-op reported as a success makes /compact lie. The sentinel is what
// lets the surface say "nothing to compact" in the person's words.
if err := agent.Compact(context.Background()); !errors.Is(err, ErrNothingToCompact) {
t.Fatalf("Compact = %v, want ErrNothingToCompact", err)
}
if got := completer.requests(); got != 1 {
t.Fatalf("requests = %d, want 1 — a short transcript must not compact", got)
}
}
// The threshold must stay above the verbatim tail at every window size. Below
// ~21.8k the 16k floor put it underneath, and every step compacted forever.
func TestCompactThresholdStaysAboveTheKeptTail(t *testing.T) {
for _, window := range []int{200, 1000, 4096, 8192, 16384, 21000, 21800, 32000, 128_000, 200_000} {
agent := &Agent{config: Config{ContextWindow: window}}
threshold, keep := agent.compactThreshold(), agent.keepRecentTokens()
if threshold <= keep {
t.Fatalf("window %d: threshold %d <= keep-recent %d — compaction would fire forever",
window, threshold, keep)
}
}
}
// The provider's context figure describes the request that was SENT. One huge
// tool result appended after it must still be able to trip the threshold.
func TestEstimateCountsMessagesAppendedAfterTheProviderFigure(t *testing.T) {
agent, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) {
config.ContextWindow = 128_000
})
agent.mu.Lock()
agent.contextTokens = 900 // the honest figure for the request already sent
before := agent.estimateTokensLocked()
agent.messages = append(agent.messages, ai.Message{
Role: "tool",
ToolCallID: "c1",
Content: []ai.ContentPart{{Type: "text", Text: strings.Repeat("x", 600_000)}},
})
after := agent.estimateTokensLocked()
agent.mu.Unlock()
if before != 900 {
t.Fatalf("estimate = %d, want the provider figure as the floor", before)
}
if after <= agent.compactThreshold() {
t.Fatalf("estimate after a 600KB tool result = %d, want it over the threshold %d",
after, agent.compactThreshold())
}
}
// ── interruption, retries and errors ────────────────────────────────────────