-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathpty_conversation_test.go
More file actions
1780 lines (1526 loc) · 55.7 KB
/
pty_conversation_test.go
File metadata and controls
1780 lines (1526 loc) · 55.7 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 screentracker_test
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/coder/quartz"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
st "github.com/coder/agentapi/lib/screentracker"
)
const testTimeout = 10 * time.Second
// testAgent is a goroutine-safe mock implementation of AgentIO.
type testAgent struct {
mu sync.Mutex
screen string
// onWrite is called during Write to simulate the agent reacting to
// terminal input (e.g., changing the screen), which unblocks
// writeStabilize's polling loops.
onWrite func(data []byte)
}
func (a *testAgent) ReadScreen() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.screen
}
func (a *testAgent) Write(data []byte) (int, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.onWrite != nil {
a.onWrite(data)
}
return len(data), nil
}
func (a *testAgent) setScreen(s string) {
a.mu.Lock()
defer a.mu.Unlock()
a.screen = s
}
type testEmitter struct{}
func (testEmitter) EmitMessages([]st.ConversationMessage) {}
func (testEmitter) EmitStatus(st.ConversationStatus) {}
func (testEmitter) EmitScreen(string) {}
func (testEmitter) EmitError(_ string, _ st.ErrorLevel) {}
// advanceFor is a shorthand for advanceUntil with a time-based condition.
func advanceFor(ctx context.Context, t *testing.T, mClock *quartz.Mock, total time.Duration) {
t.Helper()
target := mClock.Now().Add(total)
advanceUntil(ctx, t, mClock, func() bool { return !mClock.Now().Before(target) })
}
// advanceUntil advances the mock clock one event at a time until done returns
// true. Because the snapshot TickerFunc is always pending and WaitFor reuses a
// single timer via Reset, there is always at least one event to advance.
func advanceUntil(ctx context.Context, t *testing.T, mClock *quartz.Mock, done func() bool) {
t.Helper()
for !done() {
select {
case <-ctx.Done():
t.Fatal("context cancelled waiting for condition")
default:
}
_, w := mClock.AdvanceNext()
w.MustWait(ctx)
}
}
// sendAndAdvance calls Send() in a goroutine and advances the mock clock until
// Send completes.
func sendAndAdvance(ctx context.Context, t *testing.T, c *st.PTYConversation, mClock *quartz.Mock, parts ...st.MessagePart) {
t.Helper()
errCh := make(chan error, 1)
go func() {
errCh <- c.Send(parts...)
}()
advanceUntil(ctx, t, mClock, func() bool {
select {
case err := <-errCh:
require.NoError(t, err)
return true
default:
return false
}
})
}
func assertMessages(t *testing.T, c *st.PTYConversation, expected []st.ConversationMessage) {
t.Helper()
actual := c.Messages()
for i := range actual {
require.False(t, actual[i].Time.IsZero(), "message %d Time should be non-zero", i)
actual[i].Time = time.Time{}
}
require.Equal(t, expected, actual)
}
type statusTestStep struct {
snapshot string
status st.ConversationStatus
}
type statusTestParams struct {
cfg st.PTYConversationConfig
steps []statusTestStep
}
func statusTest(t *testing.T, params statusTestParams) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
t.Run(fmt.Sprintf("interval-%s,stability_length-%s", params.cfg.SnapshotInterval, params.cfg.ScreenStabilityLength), func(t *testing.T) {
mClock := quartz.NewMock(t)
params.cfg.Clock = mClock
agent := &testAgent{}
if params.cfg.AgentIO != nil {
if a, ok := params.cfg.AgentIO.(*testAgent); ok {
agent = a
}
}
params.cfg.AgentIO = agent
params.cfg.Logger = slog.New(slog.NewTextHandler(io.Discard, nil))
c := st.NewPTY(ctx, params.cfg, &testEmitter{})
c.Start(ctx)
assert.Equal(t, st.ConversationStatusInitializing, c.Status())
for i, step := range params.steps {
agent.setScreen(step.snapshot)
advanceFor(ctx, t, mClock, params.cfg.SnapshotInterval)
assert.Equal(t, step.status, c.Status(), "step %d", i)
}
})
}
func TestConversation(t *testing.T) {
changing := st.ConversationStatusChanging
stable := st.ConversationStatusStable
initializing := st.ConversationStatusInitializing
statusTest(t, statusTestParams{
cfg: st.PTYConversationConfig{
SnapshotInterval: 1 * time.Second,
ScreenStabilityLength: 2 * time.Second,
// stability threshold: 3
AgentIO: &testAgent{
screen: "1",
},
},
steps: []statusTestStep{
{snapshot: "1", status: initializing},
{snapshot: "1", status: initializing},
{snapshot: "1", status: stable},
{snapshot: "1", status: stable},
{snapshot: "2", status: changing},
},
})
statusTest(t, statusTestParams{
cfg: st.PTYConversationConfig{
SnapshotInterval: 2 * time.Second,
ScreenStabilityLength: 3 * time.Second,
// stability threshold: 3
},
steps: []statusTestStep{
{snapshot: "1", status: initializing},
{snapshot: "1", status: initializing},
{snapshot: "1", status: stable},
{snapshot: "1", status: stable},
{snapshot: "2", status: changing},
{snapshot: "2", status: changing},
{snapshot: "2", status: stable},
{snapshot: "2", status: stable},
{snapshot: "2", status: stable},
},
})
statusTest(t, statusTestParams{
cfg: st.PTYConversationConfig{
SnapshotInterval: 6 * time.Second,
ScreenStabilityLength: 14 * time.Second,
// stability threshold: 4
},
steps: []statusTestStep{
{snapshot: "1", status: initializing},
{snapshot: "1", status: initializing},
{snapshot: "1", status: initializing},
{snapshot: "1", status: stable},
{snapshot: "1", status: stable},
{snapshot: "1", status: stable},
{snapshot: "2", status: changing},
{snapshot: "2", status: changing},
{snapshot: "2", status: changing},
{snapshot: "2", status: stable},
},
})
}
func TestMessages(t *testing.T) {
now := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
// newConversation creates a started conversation with a mock clock and
// testAgent. Tests that Send() messages must use sendAndAdvance.
newConversation := func(ctx context.Context, t *testing.T, opts ...func(*st.PTYConversationConfig)) (*st.PTYConversation, *testAgent, *quartz.Mock) {
t.Helper()
writeCounter := 0
agent := &testAgent{}
// Default onWrite: each write produces a unique screen so that
// writeStabilize can detect screen changes.
agent.onWrite = func(data []byte) {
writeCounter++
agent.screen = fmt.Sprintf("__write_%d", writeCounter)
}
mClock := quartz.NewMock(t)
mClock.Set(now)
cfg := st.PTYConversationConfig{
Clock: mClock,
AgentIO: agent,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
for _, opt := range opts {
opt(&cfg)
}
if a, ok := cfg.AgentIO.(*testAgent); ok {
agent = a
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
return c, agent, mClock
}
// threshold = 3 (200ms / 100ms = 2, + 1 = 3)
const threshold = 3
const interval = 100 * time.Millisecond
t.Run("messages are copied", func(t *testing.T) {
c, _, _ := newConversation(context.Background(), t)
messages := c.Messages()
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "", Role: st.ConversationRoleAgent},
})
messages[0].Message = "modification"
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "", Role: st.ConversationRoleAgent},
})
})
t.Run("whitespace-padding", func(t *testing.T) {
c, _, _ := newConversation(context.Background(), t)
for _, msg := range []string{"123 ", " 123", "123\t\t", "\n123", "123\n\t", " \t123\n\t"} {
err := c.Send(st.MessagePartText{Content: msg})
assert.ErrorIs(t, err, st.ErrMessageValidationWhitespace)
}
})
t.Run("no-change-no-message-update", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
c, agent, mClock := newConversation(ctx, t)
agent.setScreen("1")
advanceFor(ctx, t, mClock, interval)
msgs := c.Messages()
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "1", Role: st.ConversationRoleAgent},
})
advanceFor(ctx, t, mClock, interval)
assert.Equal(t, msgs, c.Messages())
})
t.Run("tracking messages", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
c, agent, mClock := newConversation(ctx, t)
// Agent message is recorded when the first snapshot is taken.
agent.setScreen("1")
advanceFor(ctx, t, mClock, interval*threshold)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "1", Role: st.ConversationRoleAgent},
})
// Agent message is updated when the screen changes.
agent.setScreen("2")
advanceFor(ctx, t, mClock, interval)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "2", Role: st.ConversationRoleAgent},
})
// Fill to stable so Send can proceed (screen is "2").
agent.setScreen("2")
advanceFor(ctx, t, mClock, interval*threshold)
// User message is recorded.
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "3"})
// After send, screen is dirty from writeStabilize. Set to "4" and stabilize.
agent.setScreen("4")
advanceFor(ctx, t, mClock, interval*threshold)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "2", Role: st.ConversationRoleAgent},
{Id: 1, Message: "3", Role: st.ConversationRoleUser},
{Id: 2, Message: "4", Role: st.ConversationRoleAgent},
})
// Agent message is updated when the screen changes before a user message.
agent.setScreen("5")
advanceFor(ctx, t, mClock, interval*threshold)
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "6"})
agent.setScreen("7")
advanceFor(ctx, t, mClock, interval*threshold)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "2", Role: st.ConversationRoleAgent},
{Id: 1, Message: "3", Role: st.ConversationRoleUser},
{Id: 2, Message: "5", Role: st.ConversationRoleAgent},
{Id: 3, Message: "6", Role: st.ConversationRoleUser},
{Id: 4, Message: "7", Role: st.ConversationRoleAgent},
})
assert.Equal(t, st.ConversationStatusStable, c.Status())
// Send another message.
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "8"})
// After filling to stable, messages and status are correct.
agent.setScreen("7")
advanceFor(ctx, t, mClock, interval*threshold)
assert.Equal(t, st.ConversationStatusStable, c.Status())
})
t.Run("tracking messages overlap", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
c, agent, mClock := newConversation(ctx, t)
// Common overlap between screens is removed after a user message.
agent.setScreen("1")
advanceFor(ctx, t, mClock, interval*threshold)
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "2"})
agent.setScreen("1\n3")
advanceFor(ctx, t, mClock, interval*threshold)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "1", Role: st.ConversationRoleAgent},
{Id: 1, Message: "2", Role: st.ConversationRoleUser},
{Id: 2, Message: "3", Role: st.ConversationRoleAgent},
})
agent.setScreen("1\n3x")
advanceFor(ctx, t, mClock, interval*threshold)
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "4"})
agent.setScreen("1\n3x\n5")
advanceFor(ctx, t, mClock, interval*threshold)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "1", Role: st.ConversationRoleAgent},
{Id: 1, Message: "2", Role: st.ConversationRoleUser},
{Id: 2, Message: "3x", Role: st.ConversationRoleAgent},
{Id: 3, Message: "4", Role: st.ConversationRoleUser},
{Id: 4, Message: "5", Role: st.ConversationRoleAgent},
})
})
t.Run("format-message", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
c, agent, mClock := newConversation(ctx, t, func(cfg *st.PTYConversationConfig) {
cfg.FormatMessage = func(message string, userInput string) string {
return message + " " + userInput
}
})
// Fill to stable with screen "1", then send.
agent.setScreen("1")
advanceFor(ctx, t, mClock, interval*threshold)
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "2"})
// After send, set screen to "x" and take snapshots for new agent message.
agent.setScreen("x")
advanceFor(ctx, t, mClock, interval*threshold)
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "1 ", Role: st.ConversationRoleAgent},
{Id: 1, Message: "2", Role: st.ConversationRoleUser},
{Id: 2, Message: "x 2", Role: st.ConversationRoleAgent},
})
})
t.Run("format-message-initial", func(t *testing.T) {
c, _, _ := newConversation(context.Background(), t, func(cfg *st.PTYConversationConfig) {
cfg.FormatMessage = func(message string, userInput string) string {
return "formatted"
}
})
assertMessages(t, c, []st.ConversationMessage{
{Id: 0, Message: "", Role: st.ConversationRoleAgent},
})
})
t.Run("send-message-status-check", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
c, agent, mClock := newConversation(ctx, t)
sendMsg := func(msg string) error {
return c.Send(st.MessagePartText{Content: msg})
}
// Status is initializing, send should fail.
assert.ErrorIs(t, sendMsg("1"), st.ErrMessageValidationChanging)
// Fill to stable.
agent.setScreen("1")
advanceFor(ctx, t, mClock, interval*threshold)
assert.Equal(t, st.ConversationStatusStable, c.Status())
// Now send should succeed.
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "4"})
// After send, screen is dirty. Set to "2" (different from "1") so status is changing.
agent.setScreen("2")
advanceFor(ctx, t, mClock, interval)
assert.Equal(t, st.ConversationStatusChanging, c.Status())
assert.ErrorIs(t, sendMsg("5"), st.ErrMessageValidationChanging)
})
t.Run("send-message-empty-message", func(t *testing.T) {
c, _, _ := newConversation(context.Background(), t)
assert.ErrorIs(t, c.Send(st.MessagePartText{Content: ""}), st.ErrMessageValidationEmpty)
})
t.Run("send-message-no-echo-agent-reacts", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
// Given: an agent that doesn't echo typed input but
// reacts to carriage return by updating the screen.
c, _, mClock := newConversation(ctx, t, func(cfg *st.PTYConversationConfig) {
a := &testAgent{screen: "prompt"}
a.onWrite = func(data []byte) {
if string(data) == "\r" {
a.screen = "processing..."
}
}
cfg.AgentIO = a
})
advanceFor(ctx, t, mClock, interval*threshold)
// When: a message is sent. Phase 1 times out (no echo),
// Phase 2 writes \r and the agent reacts.
sendAndAdvance(ctx, t, c, mClock, st.MessagePartText{Content: "hello"})
// Then: Send succeeds and the user message is recorded.
msgs := c.Messages()
require.True(t, len(msgs) >= 2)
var foundUserMsg bool
for _, msg := range msgs {
if msg.Role == st.ConversationRoleUser && msg.Message == "hello" {
foundUserMsg = true
break
}
}
assert.True(t, foundUserMsg, "expected user message 'hello' in conversation")
})
t.Run("send-message-no-echo-no-react", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
// Given: an agent that is completely unresponsive — it
// neither echoes input nor reacts to carriage return.
c, _, mClock := newConversation(ctx, t, func(cfg *st.PTYConversationConfig) {
a := &testAgent{screen: "prompt"}
a.onWrite = func(data []byte) {}
cfg.AgentIO = a
})
advanceFor(ctx, t, mClock, interval*threshold)
// When: a message is sent. Both Phase 1 (echo) and
// Phase 2 (processing) time out.
// Note: can't use sendAndAdvance here because it calls
// require.NoError internally.
var sendErr error
var sendDone atomic.Bool
go func() {
sendErr = c.Send(st.MessagePartText{Content: "hello"})
sendDone.Store(true)
}()
advanceUntil(ctx, t, mClock, func() bool { return sendDone.Load() })
// Then: Send fails with a Phase 2 error (not Phase 1).
require.Error(t, sendErr)
assert.Contains(t, sendErr.Error(), "failed to wait for processing to start")
})
t.Run("send-message-no-echo-context-cancelled", func(t *testing.T) {
// Given: a non-echoing agent and a cancellable context.
// The onWrite signals when writeStabilize starts writing
// message parts — this is used to synchronize the cancel.
sendCtx, sendCancel := context.WithCancel(context.Background())
t.Cleanup(sendCancel)
writeStarted := make(chan struct{}, 1)
c, _, mClock := newConversation(sendCtx, t, func(cfg *st.PTYConversationConfig) {
a := &testAgent{screen: "prompt"}
a.onWrite = func(data []byte) {
select {
case writeStarted <- struct{}{}:
default:
}
}
cfg.AgentIO = a
})
advanceFor(sendCtx, t, mClock, interval*threshold)
// When: a message is sent and the context is cancelled
// during Phase 1 (after the message is written to the
// PTY, before echo detection completes).
var sendErr error
var sendDone atomic.Bool
go func() {
sendErr = c.Send(st.MessagePartText{Content: "hello"})
sendDone.Store(true)
}()
// Advance tick-by-tick until writeStabilize starts
// (onWrite fires). This gives the send loop goroutine
// scheduling time between advances.
advanceUntil(sendCtx, t, mClock, func() bool {
select {
case <-writeStarted:
return true
default:
return false
}
})
// writeStabilize Phase 1 is now running. Its WaitFor is
// blocked on a mock timer sleep select. Cancel: the
// select sees ctx.Done() immediately.
sendCancel()
// WaitFor returns ctx.Err(). The errors.Is guard in
// Phase 1 propagates it as fatal. Use Eventually since
// the goroutine needs scheduling time.
require.Eventually(t, sendDone.Load, 5*time.Second, 10*time.Millisecond)
// Then: the error wraps context.Canceled, not a Phase 2
// timeout. This validates the errors.Is(WaitTimedOut)
// guard.
require.Error(t, sendErr)
assert.ErrorIs(t, sendErr, context.Canceled)
assert.NotContains(t, sendErr.Error(), "failed to wait for processing to start")
})
}
func TestStatePersistence(t *testing.T) {
t.Run("SaveState creates file with correct structure", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
// Create temp directory for state file
tmpDir := t.TempDir()
stateFile := tmpDir + "/state.json"
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "initial"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: false,
SaveState: true,
},
InitialPrompt: []st.MessagePart{st.MessagePartText{Content: "test prompt"}},
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
// Generate some conversation
agent.setScreen("hello")
advanceFor(ctx, t, mClock, 300*time.Millisecond)
// Save state
err := c.SaveState()
require.NoError(t, err)
// Read and verify the saved file
data, err := os.ReadFile(stateFile)
require.NoError(t, err)
var agentState st.AgentState
err = json.Unmarshal(data, &agentState)
require.NoError(t, err)
assert.Equal(t, 1, agentState.Version)
assert.Equal(t, "test prompt", agentState.InitialPrompt)
assert.NotEmpty(t, agentState.Messages)
})
t.Run("SaveState creates valid JSON", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/state.json"
mClock := quartz.NewMock(t)
fixedTime := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
mClock.Set(fixedTime)
agent := &testAgent{screen: ""}
writeCounter := 0
agent.onWrite = func(data []byte) {
writeCounter++
// Change screen on each write so writeStabilize can detect changes
agent.screen = fmt.Sprintf("__write_%d", writeCounter)
}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: false,
SaveState: true,
},
InitialPrompt: []st.MessagePart{st.MessagePartText{Content: "test prompt"}},
ReadyForInitialPrompt: func(message string) bool {
return message == "Hello! Ready to help."
},
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
// Step 1: Agent shows initial greeting
agent.setScreen("Hello! Ready to help.")
advanceFor(ctx, t, mClock, 300*time.Millisecond)
// Step 2: Wait for initial prompt to be sent (uses advanceUntil like TestInitialPromptReadiness)
advanceUntil(ctx, t, mClock, func() bool {
return len(c.Messages()) >= 2 // greeting + user prompt
})
// Step 3: Agent shows response
agent.setScreen("Response to test prompt")
advanceFor(ctx, t, mClock, 300*time.Millisecond)
// Save state - this creates state.json
err := c.SaveState()
require.NoError(t, err)
// Read the saved state.json
actualData, err := os.ReadFile(stateFile)
require.NoError(t, err)
// Read the expected golden file
expectedData, err := os.ReadFile("testdata/expected_saved_state.json")
require.NoError(t, err)
// Parse both JSON files
var actualState, expectedState st.AgentState
err = json.Unmarshal(actualData, &actualState)
require.NoError(t, err)
err = json.Unmarshal(expectedData, &expectedState)
require.NoError(t, err)
// Compare the state files field by field
assert.Equal(t, expectedState.Version, actualState.Version, "version should match")
assert.Equal(t, expectedState.InitialPrompt, actualState.InitialPrompt, "initial_prompt should match")
assert.Equal(t, expectedState.InitialPromptSent, actualState.InitialPromptSent, "initial_prompt_sent should match")
assert.Equal(t, len(expectedState.Messages), len(actualState.Messages), "message count should match")
// Compare each message
for i := range expectedState.Messages {
if i >= len(actualState.Messages) {
break
}
assert.Equal(t, expectedState.Messages[i].Id, actualState.Messages[i].Id, "message %d: id should match", i)
assert.Equal(t, expectedState.Messages[i].Message, actualState.Messages[i].Message, "message %d: message should match", i)
assert.Equal(t, expectedState.Messages[i].Role, actualState.Messages[i].Role, "message %d: role should match", i)
}
})
t.Run("SaveState skips when not configured", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/state.json"
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "initial"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: false,
SaveState: false,
},
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
err := c.SaveState()
require.NoError(t, err)
// File should not be created
_, err = os.Stat(stateFile)
assert.True(t, os.IsNotExist(err))
})
t.Run("SaveState honors dirty flag", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/state.json"
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "initial"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: false,
SaveState: true,
},
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
// Generate conversation and save
agent.setScreen("hello")
advanceFor(ctx, t, mClock, 300*time.Millisecond)
err := c.SaveState()
require.NoError(t, err)
// Get file modification time
info1, err := os.Stat(stateFile)
require.NoError(t, err)
modTime1 := info1.ModTime()
// Save again without changes - file should not be modified
err = c.SaveState()
require.NoError(t, err)
info2, err := os.Stat(stateFile)
require.NoError(t, err)
modTime2 := info2.ModTime()
// File modification time should be the same (dirty flag prevents save)
assert.Equal(t, modTime1, modTime2)
})
t.Run("SaveState creates directory if not exists", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/nested/deep/state.json"
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "initial"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: false,
SaveState: true,
},
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
agent.setScreen("hello")
advanceFor(ctx, t, mClock, 300*time.Millisecond)
err := c.SaveState()
require.NoError(t, err)
// Verify file and directory were created
_, err = os.Stat(stateFile)
assert.NoError(t, err)
})
t.Run("LoadState restores conversation from file", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/state.json"
// Create a state file with test data
testState := st.AgentState{
Version: 1,
InitialPrompt: "restored prompt",
Messages: []st.ConversationMessage{
{Id: 0, Message: "agent message 1", Role: st.ConversationRoleAgent, Time: time.Now()},
{Id: 1, Message: "user message 1", Role: st.ConversationRoleUser, Time: time.Now()},
{Id: 2, Message: "agent message 2", Role: st.ConversationRoleAgent, Time: time.Now()},
},
}
data, err := json.MarshalIndent(testState, "", " ")
require.NoError(t, err)
err = os.WriteFile(stateFile, data, 0o644)
require.NoError(t, err)
// Create conversation with LoadState enabled
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "ready"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
FormatMessage: func(message string, userInput string) string {
return message
},
ReadyForInitialPrompt: func(message string) bool {
return message == "ready"
},
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: true,
SaveState: false,
},
}
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
// Advance until agent is ready and state is loaded
advanceFor(ctx, t, mClock, 300*time.Millisecond)
// Verify messages were restored
messages := c.Messages()
assert.Len(t, messages, 3)
assert.Equal(t, "agent message 1", messages[0].Message)
assert.Equal(t, "user message 1", messages[1].Message)
// The last agent message may have adjustments from adjustScreenAfterStateLoad
assert.Contains(t, messages[2].Message, "agent message 2")
})
t.Run("LoadState handles missing file gracefully", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/nonexistent.json"
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "ready"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
FormatMessage: func(message string, userInput string) string {
return message
},
ReadyForInitialPrompt: func(message string) bool {
return message == "ready"
},
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: true,
SaveState: false,
},
}
// Should not panic or error
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
advanceFor(ctx, t, mClock, 300*time.Millisecond)
// Should have default initial message
messages := c.Messages()
assert.Len(t, messages, 1)
})
t.Run("LoadState handles empty file gracefully", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/empty.json"
// Create empty file
err := os.WriteFile(stateFile, []byte(""), 0o644)
require.NoError(t, err)
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "ready"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
FormatMessage: func(message string, userInput string) string {
return message
},
ReadyForInitialPrompt: func(message string) bool {
return message == "ready"
},
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: true,
SaveState: false,
},
}
// Should not panic or error
c := st.NewPTY(ctx, cfg, &testEmitter{})
c.Start(ctx)
advanceFor(ctx, t, mClock, 300*time.Millisecond)
// Should have default initial message
messages := c.Messages()
assert.Len(t, messages, 1)
})
t.Run("LoadState handles corrupted JSON gracefully", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
t.Cleanup(cancel)
tmpDir := t.TempDir()
stateFile := tmpDir + "/corrupted.json"
// Create corrupted JSON file
err := os.WriteFile(stateFile, []byte("{invalid json}"), 0o644)
require.NoError(t, err)
mClock := quartz.NewMock(t)
agent := &testAgent{screen: "ready"}
cfg := st.PTYConversationConfig{
Clock: mClock,
SnapshotInterval: 100 * time.Millisecond,
ScreenStabilityLength: 200 * time.Millisecond,
AgentIO: agent,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
FormatMessage: func(message string, userInput string) string {
return message
},
ReadyForInitialPrompt: func(message string) bool {
return message == "ready"
},
StatePersistenceConfig: st.StatePersistenceConfig{
StateFile: stateFile,
LoadState: true,
SaveState: false,