This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathindex.spec.ts
More file actions
1841 lines (1619 loc) · 61.4 KB
/
Copy pathindex.spec.ts
File metadata and controls
1841 lines (1619 loc) · 61.4 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
// npx vitest core/condense/__tests__/index.spec.ts
import type { Mock } from "vitest"
import { Anthropic } from "@anthropic-ai/sdk"
import { TelemetryService } from "@roo-code/telemetry"
import { ApiHandler } from "../../../api"
import { ApiMessage } from "../../task-persistence/apiMessages"
import { maybeRemoveImageBlocks } from "../../../api/transform/image-cleaning"
import {
summarizeConversation,
getMessagesSinceLastSummary,
getKeepMessagesWithToolBlocks,
getEffectiveApiHistory,
cleanupAfterTruncation,
N_MESSAGES_TO_KEEP,
} from "../index"
vi.mock("../../../api/transform/image-cleaning", () => ({
maybeRemoveImageBlocks: vi.fn((messages: ApiMessage[], _apiHandler: ApiHandler) => [...messages]),
}))
vi.mock("@roo-code/telemetry", () => ({
TelemetryService: {
instance: {
captureContextCondensed: vi.fn(),
},
},
}))
const taskId = "test-task-id"
const DEFAULT_PREV_CONTEXT_TOKENS = 1000
describe("getKeepMessagesWithToolBlocks", () => {
it("should return keepMessages without tool blocks when no tool_result blocks in first kept message", () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "I'm good", ts: 4 },
{ role: "user", content: "What's new?", ts: 5 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.keepMessages).toHaveLength(3)
expect(result.toolUseBlocksToPreserve).toHaveLength(0)
})
it("should return all messages when messages.length <= keepCount", () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.keepMessages).toEqual(messages)
expect(result.toolUseBlocksToPreserve).toHaveLength(0)
})
it("should preserve tool_use blocks when first kept message has tool_result blocks", () => {
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_123",
name: "read_file",
input: { path: "test.txt" },
}
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_123",
content: "file contents",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Let me read that file", ts: 2 },
{ role: "user", content: "Please continue", ts: 3 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Reading file..." }, toolUseBlock],
ts: 4,
},
{
role: "user",
content: [toolResultBlock, { type: "text" as const, text: "Continue" }],
ts: 5,
},
{ role: "assistant", content: "Got it, the file says...", ts: 6 },
{ role: "user", content: "Thanks", ts: 7 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].ts).toBe(5)
expect(result.keepMessages[1].ts).toBe(6)
expect(result.keepMessages[2].ts).toBe(7)
// Should preserve the tool_use block from the preceding assistant message
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0]).toEqual(toolUseBlock)
})
it("should not preserve tool_use blocks when first kept message is assistant role", () => {
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_123",
name: "read_file",
input: { path: "test.txt" },
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "Please read", ts: 3 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Reading..." }, toolUseBlock],
ts: 4,
},
{ role: "user", content: "Continue", ts: 5 },
{ role: "assistant", content: "Done", ts: 6 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// First kept message is assistant, not user with tool_result
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].role).toBe("assistant")
expect(result.toolUseBlocksToPreserve).toHaveLength(0)
})
it("should not preserve tool_use blocks when first kept user message has string content", () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "Good", ts: 4 },
{ role: "user", content: "Simple text message", ts: 5 }, // String content, not array
{ role: "assistant", content: "Response", ts: 6 },
{ role: "user", content: "More text", ts: 7 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.keepMessages).toHaveLength(3)
expect(result.toolUseBlocksToPreserve).toHaveLength(0)
})
it("should handle multiple tool_use blocks that need to be preserved", () => {
const toolUseBlock1 = {
type: "tool_use" as const,
id: "toolu_123",
name: "read_file",
input: { path: "file1.txt" },
}
const toolUseBlock2 = {
type: "tool_use" as const,
id: "toolu_456",
name: "read_file",
input: { path: "file2.txt" },
}
const toolResultBlock1 = {
type: "tool_result" as const,
tool_use_id: "toolu_123",
content: "contents 1",
}
const toolResultBlock2 = {
type: "tool_result" as const,
tool_use_id: "toolu_456",
content: "contents 2",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Reading files..." }, toolUseBlock1, toolUseBlock2],
ts: 2,
},
{
role: "user",
content: [toolResultBlock1, toolResultBlock2],
ts: 3,
},
{ role: "assistant", content: "Got both files", ts: 4 },
{ role: "user", content: "Thanks", ts: 5 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// Should preserve both tool_use blocks
expect(result.toolUseBlocksToPreserve).toHaveLength(2)
expect(result.toolUseBlocksToPreserve).toContainEqual(toolUseBlock1)
expect(result.toolUseBlocksToPreserve).toContainEqual(toolUseBlock2)
})
it("should not preserve tool_use blocks when preceding message has no tool_use blocks", () => {
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_123",
content: "file contents",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Plain text response", ts: 2 }, // No tool_use blocks
{
role: "user",
content: [toolResultBlock], // Has tool_result but preceding message has no tool_use
ts: 3,
},
{ role: "assistant", content: "Response", ts: 4 },
{ role: "user", content: "Thanks", ts: 5 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.keepMessages).toHaveLength(3)
expect(result.toolUseBlocksToPreserve).toHaveLength(0)
})
it("should handle edge case when startIndex - 1 is negative", () => {
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_123",
content: "file contents",
}
// Only 3 messages total, so startIndex = 0 and precedingIndex would be -1
const messages: ApiMessage[] = [
{
role: "user",
content: [toolResultBlock],
ts: 1,
},
{ role: "assistant", content: "Response", ts: 2 },
{ role: "user", content: "Thanks", ts: 3 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.keepMessages).toEqual(messages)
expect(result.toolUseBlocksToPreserve).toHaveLength(0)
})
it("should preserve reasoning blocks alongside tool_use blocks for DeepSeek/Z.ai interleaved thinking", () => {
const reasoningBlock = {
type: "reasoning" as const,
text: "Let me think about this step by step...",
}
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_deepseek_123",
name: "read_file",
input: { path: "test.txt" },
}
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_deepseek_123",
content: "file contents",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Let me help", ts: 2 },
{ role: "user", content: "Please read the file", ts: 3 },
{
role: "assistant",
// DeepSeek stores reasoning as content blocks alongside tool_use
content: [reasoningBlock as any, { type: "text" as const, text: "Reading file..." }, toolUseBlock],
ts: 4,
},
{
role: "user",
content: [toolResultBlock, { type: "text" as const, text: "Continue" }],
ts: 5,
},
{ role: "assistant", content: "Got it, the file says...", ts: 6 },
{ role: "user", content: "Thanks", ts: 7 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].ts).toBe(5)
// Should preserve the tool_use block
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0]).toEqual(toolUseBlock)
// Should preserve the reasoning block for DeepSeek/Z.ai interleaved thinking
expect(result.reasoningBlocksToPreserve).toHaveLength(1)
expect((result.reasoningBlocksToPreserve[0] as any).type).toBe("reasoning")
expect((result.reasoningBlocksToPreserve[0] as any).text).toBe("Let me think about this step by step...")
})
it("should return empty reasoningBlocksToPreserve when no reasoning blocks present", () => {
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_123",
name: "read_file",
input: { path: "test.txt" },
}
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_123",
content: "file contents",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{
role: "assistant",
// No reasoning block, just text and tool_use
content: [{ type: "text" as const, text: "Reading file..." }, toolUseBlock],
ts: 2,
},
{
role: "user",
content: [toolResultBlock],
ts: 3,
},
{ role: "assistant", content: "Done", ts: 4 },
{ role: "user", content: "Thanks", ts: 5 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.reasoningBlocksToPreserve).toHaveLength(0)
})
it("should preserve tool_use when tool_result is in 2nd kept message and tool_use is 2 messages before boundary", () => {
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_second_kept",
name: "read_file",
input: { path: "test.txt" },
}
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_second_kept",
content: "file contents",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Let me help", ts: 2 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Reading file..." }, toolUseBlock],
ts: 3,
},
{ role: "user", content: "Some other message", ts: 4 },
{ role: "assistant", content: "First kept message", ts: 5 },
{
role: "user",
content: [toolResultBlock, { type: "text" as const, text: "Continue" }],
ts: 6,
},
{ role: "assistant", content: "Third kept message", ts: 7 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages (ts: 5, 6, 7)
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].ts).toBe(5)
expect(result.keepMessages[1].ts).toBe(6)
expect(result.keepMessages[2].ts).toBe(7)
// Should preserve the tool_use block from message at ts:3 (2 messages before boundary)
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0]).toEqual(toolUseBlock)
})
it("should preserve tool_use when tool_result is in 3rd kept message and tool_use is at boundary edge", () => {
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_third_kept",
name: "search",
input: { query: "test" },
}
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_third_kept",
content: "search results",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Start", ts: 1 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Searching..." }, toolUseBlock],
ts: 2,
},
{ role: "user", content: "First kept message", ts: 3 },
{ role: "assistant", content: "Second kept message", ts: 4 },
{
role: "user",
content: [toolResultBlock, { type: "text" as const, text: "Done" }],
ts: 5,
},
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages (ts: 3, 4, 5)
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].ts).toBe(3)
expect(result.keepMessages[1].ts).toBe(4)
expect(result.keepMessages[2].ts).toBe(5)
// Should preserve the tool_use block from message at ts:2 (at the search boundary edge)
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0]).toEqual(toolUseBlock)
})
it("should preserve multiple tool_uses when tool_results are in different kept messages", () => {
const toolUseBlock1 = {
type: "tool_use" as const,
id: "toolu_multi_1",
name: "read_file",
input: { path: "file1.txt" },
}
const toolUseBlock2 = {
type: "tool_use" as const,
id: "toolu_multi_2",
name: "read_file",
input: { path: "file2.txt" },
}
const toolResultBlock1 = {
type: "tool_result" as const,
tool_use_id: "toolu_multi_1",
content: "contents 1",
}
const toolResultBlock2 = {
type: "tool_result" as const,
tool_use_id: "toolu_multi_2",
content: "contents 2",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Start", ts: 1 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Reading file 1..." }, toolUseBlock1],
ts: 2,
},
{ role: "user", content: "Some message", ts: 3 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Reading file 2..." }, toolUseBlock2],
ts: 4,
},
{
role: "user",
content: [toolResultBlock1, { type: "text" as const, text: "First result" }],
ts: 5,
},
{
role: "user",
content: [toolResultBlock2, { type: "text" as const, text: "Second result" }],
ts: 6,
},
{ role: "assistant", content: "Got both files", ts: 7 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages (ts: 5, 6, 7)
expect(result.keepMessages).toHaveLength(3)
// Should preserve both tool_use blocks
expect(result.toolUseBlocksToPreserve).toHaveLength(2)
expect(result.toolUseBlocksToPreserve).toContainEqual(toolUseBlock1)
expect(result.toolUseBlocksToPreserve).toContainEqual(toolUseBlock2)
})
it("should find tool_use even when it is far back in the message history (ROO-520 fix)", () => {
// This test verifies the fix for https://linear.app/roocode/issue/ROO-520
// The bug occurred when tool_use was preserved in an earlier summary message
// after multiple condensations. The bounded search window was too small to find it,
// resulting in orphaned tool_result blocks that caused 400 errors from the API.
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_early_in_history",
content: "result",
}
// Tool_use is at index 0, tool_result is in the last 3 messages.
// The search must cover the ENTIRE condensed region to find the tool_use.
const messages: ApiMessage[] = [
{
role: "assistant",
content: [
{ type: "text" as const, text: "Early tool call..." },
{
type: "tool_use" as const,
id: "toolu_early_in_history",
name: "read_file",
input: { path: "test.txt" },
},
],
ts: 1,
},
{ role: "user", content: "Message 2", ts: 2 },
{ role: "assistant", content: "Message 3", ts: 3 },
{ role: "user", content: "Message 4", ts: 4 },
{ role: "assistant", content: "Message 5", ts: 5 },
{ role: "user", content: "Message 6", ts: 6 },
{ role: "assistant", content: "Message 7", ts: 7 },
{
role: "user",
content: [toolResultBlock],
ts: 8,
},
{ role: "assistant", content: "Message 9", ts: 9 },
{ role: "user", content: "Message 10", ts: 10 },
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].ts).toBe(8)
expect(result.keepMessages[1].ts).toBe(9)
expect(result.keepMessages[2].ts).toBe(10)
// With the fix, tool_use should be found even though it's far back in history
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0].id).toBe("toolu_early_in_history")
})
it("should find tool_use in previous summary message after multiple condensations (ROO-520)", () => {
// This test simulates the exact scenario from ROO-520:
// After first condensation, tool_use was preserved in summary1.
// After second condensation, the bounded search couldn't find tool_use in summary1
// because it was outside the N_MESSAGES_TO_KEEP search window.
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_in_summary",
name: "read_file",
input: { path: "test.txt" },
}
const toolResultBlock = {
type: "tool_result" as const,
tool_use_id: "toolu_in_summary",
content: "file contents",
}
// Simulate state after first condensation:
// summary1 contains a preserved tool_use block from the first condense
const summaryMessage: ApiMessage = {
role: "assistant",
content: [{ type: "text" as const, text: "Summary of first conversation chunk" }, toolUseBlock],
ts: 5,
isSummary: true,
condenseId: "summary-1",
}
const messages: ApiMessage[] = [
{ role: "user", content: "First message", ts: 1 },
// Messages 2-4 are tagged with condenseParent from first condensation
{ role: "assistant", content: "Message 2", ts: 2, condenseParent: "summary-1" },
{ role: "user", content: "Message 3", ts: 3, condenseParent: "summary-1" },
{ role: "assistant", content: "Message 4", ts: 4, condenseParent: "summary-1" },
// summary1 with preserved tool_use
summaryMessage,
// Messages after first condensation
{ role: "user", content: "Message 6", ts: 6 },
{ role: "assistant", content: "Message 7", ts: 7 },
{ role: "user", content: "Message 8", ts: 8 },
{ role: "assistant", content: "Message 9", ts: 9 },
{ role: "user", content: "Message 10", ts: 10 },
{ role: "assistant", content: "Message 11", ts: 11 },
// This user message has tool_result referencing the tool_use in summary1
{
role: "user",
content: [toolResultBlock, { type: "text" as const, text: "Continue" }],
ts: 12,
},
{ role: "assistant", content: "Message 13", ts: 13 },
{ role: "user", content: "Message 14", ts: 14 },
]
// Second condensation: keepCount=3 means we keep messages 12, 13, 14
// startIndex = 14 - 3 = 11
// Old bounded search would only look at messages[8:11] = [msg9, msg10, msg11]
// The tool_use in summary1 at index 4 would NOT be found!
const result = getKeepMessagesWithToolBlocks(messages, 3)
expect(result.keepMessages).toHaveLength(3)
expect(result.keepMessages[0].ts).toBe(12) // Has tool_result
expect(result.keepMessages[1].ts).toBe(13)
expect(result.keepMessages[2].ts).toBe(14)
// With the fix, we search the ENTIRE condensed region (messages[0:11])
// and find the tool_use in summary1
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0].id).toBe("toolu_in_summary")
})
it("should not duplicate tool_use blocks when same tool_result ID appears multiple times", () => {
const toolUseBlock = {
type: "tool_use" as const,
id: "toolu_duplicate",
name: "read_file",
input: { path: "test.txt" },
}
const toolResultBlock1 = {
type: "tool_result" as const,
tool_use_id: "toolu_duplicate",
content: "result 1",
}
const toolResultBlock2 = {
type: "tool_result" as const,
tool_use_id: "toolu_duplicate",
content: "result 2",
}
const messages: ApiMessage[] = [
{ role: "user", content: "Start", ts: 1 },
{
role: "assistant",
content: [{ type: "text" as const, text: "Using tool..." }, toolUseBlock],
ts: 2,
},
{
role: "user",
content: [toolResultBlock1],
ts: 3,
},
{ role: "assistant", content: "Processing", ts: 4 },
{
role: "user",
content: [toolResultBlock2], // Same tool_use_id as first result
ts: 5,
},
]
const result = getKeepMessagesWithToolBlocks(messages, 3)
// keepMessages should be the last 3 messages (ts: 3, 4, 5)
expect(result.keepMessages).toHaveLength(3)
// Should only preserve the tool_use block once, not twice
expect(result.toolUseBlocksToPreserve).toHaveLength(1)
expect(result.toolUseBlocksToPreserve[0]).toEqual(toolUseBlock)
})
})
describe("getMessagesSinceLastSummary", () => {
it("should return all messages when there is no summary", () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
]
const result = getMessagesSinceLastSummary(messages)
expect(result).toEqual(messages)
})
it("should return messages since the last summary with original first user message", () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "assistant", content: "Summary of conversation", ts: 3, isSummary: true },
{ role: "user", content: "How are you?", ts: 4 },
{ role: "assistant", content: "I'm good", ts: 5 },
]
const result = getMessagesSinceLastSummary(messages)
expect(result).toEqual([
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Summary of conversation", ts: 3, isSummary: true },
{ role: "user", content: "How are you?", ts: 4 },
{ role: "assistant", content: "I'm good", ts: 5 },
])
})
it("should handle multiple summary messages and return since the last one with original first user message", () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "First summary", ts: 2, isSummary: true },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "Second summary", ts: 4, isSummary: true },
{ role: "user", content: "What's new?", ts: 5 },
]
const result = getMessagesSinceLastSummary(messages)
expect(result).toEqual([
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Second summary", ts: 4, isSummary: true },
{ role: "user", content: "What's new?", ts: 5 },
])
})
it("should handle empty messages array", () => {
const result = getMessagesSinceLastSummary([])
expect(result).toEqual([])
})
})
describe("summarizeConversation", () => {
// Mock ApiHandler
let mockApiHandler: ApiHandler
let mockStream: AsyncGenerator<any, void, unknown>
beforeEach(() => {
// Reset mocks
vi.clearAllMocks()
// Setup mock stream with usage information
mockStream = (async function* () {
yield { type: "text" as const, text: "This is " }
yield { type: "text" as const, text: "a summary" }
yield { type: "usage" as const, totalCost: 0.05, outputTokens: 150 }
})()
// Setup mock API handler
mockApiHandler = {
createMessage: vi.fn().mockReturnValue(mockStream),
countTokens: vi.fn().mockImplementation(() => Promise.resolve(100)),
getModel: vi.fn().mockReturnValue({
id: "test-model",
info: {
contextWindow: 8000,
supportsImages: true,
supportsVision: true,
maxTokens: 4000,
supportsPromptCache: true,
maxCachePoints: 10,
minTokensPerCachePoint: 100,
cachableFields: ["system", "messages"],
},
}),
} as unknown as ApiHandler
})
// Default system prompt for tests
const defaultSystemPrompt = "You are a helpful assistant."
it("should not summarize when there are not enough messages", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
]
const result = await summarizeConversation(
messages,
mockApiHandler,
defaultSystemPrompt,
taskId,
DEFAULT_PREV_CONTEXT_TOKENS,
)
expect(result.messages).toEqual(messages)
expect(result.cost).toBe(0)
expect(result.summary).toBe("")
expect(result.newContextTokens).toBeUndefined()
expect(result.error).toBeTruthy() // Error should be set for not enough messages
expect(mockApiHandler.createMessage).not.toHaveBeenCalled()
})
it("should not summarize when there was a recent summary", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "I'm good", ts: 4 },
{ role: "user", content: "What's new?", ts: 5 },
{ role: "assistant", content: "Not much", ts: 6, isSummary: true }, // Recent summary
{ role: "user", content: "Tell me more", ts: 7 },
]
const result = await summarizeConversation(
messages,
mockApiHandler,
defaultSystemPrompt,
taskId,
DEFAULT_PREV_CONTEXT_TOKENS,
)
expect(result.messages).toEqual(messages)
expect(result.cost).toBe(0)
expect(result.summary).toBe("")
expect(result.newContextTokens).toBeUndefined()
expect(result.error).toBeTruthy() // Error should be set for recent summary
expect(mockApiHandler.createMessage).not.toHaveBeenCalled()
})
it("should summarize conversation and insert summary message", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "I'm good", ts: 4 },
{ role: "user", content: "What's new?", ts: 5 },
{ role: "assistant", content: "Not much", ts: 6 },
{ role: "user", content: "Tell me more", ts: 7 },
]
const result = await summarizeConversation(
messages,
mockApiHandler,
defaultSystemPrompt,
taskId,
DEFAULT_PREV_CONTEXT_TOKENS,
)
// Check that the API was called correctly
expect(mockApiHandler.createMessage).toHaveBeenCalled()
expect(maybeRemoveImageBlocks).toHaveBeenCalled()
// With non-destructive condensing, the result contains ALL original messages
// plus the summary message. Condensed messages are tagged but not deleted.
// Use getEffectiveApiHistory to verify the effective API view matches the old behavior.
expect(result.messages.length).toBe(messages.length + 1) // All original messages + summary
// Check that the first message is preserved
expect(result.messages[0]).toEqual(messages[0])
// Find the summary message (it has isSummary: true)
const summaryMessage = result.messages.find((m) => m.isSummary)
expect(summaryMessage).toBeDefined()
expect(summaryMessage!.role).toBe("assistant")
// Summary content is now always an array with [synthetic reasoning, text]
// for DeepSeek-reasoner compatibility (requires reasoning_content on all assistant messages)
expect(Array.isArray(summaryMessage!.content)).toBe(true)
const content = summaryMessage!.content as any[]
expect(content).toHaveLength(2)
expect(content[0].type).toBe("reasoning")
expect(content[1].type).toBe("text")
expect(content[1].text).toBe("This is a summary")
expect(summaryMessage!.isSummary).toBe(true)
// Verify that the effective API history matches expected: first + summary + last N messages
const effectiveHistory = getEffectiveApiHistory(result.messages)
expect(effectiveHistory.length).toBe(1 + 1 + N_MESSAGES_TO_KEEP) // First + summary + last N
// Check that condensed messages are properly tagged
const condensedMessages = result.messages.filter((m) => m.condenseParent !== undefined)
expect(condensedMessages.length).toBeGreaterThan(0)
// Check the cost and token counts
expect(result.cost).toBe(0.05)
expect(result.summary).toBe("This is a summary")
expect(result.newContextTokens).toBe(250) // 150 output tokens + 100 from countTokens
expect(result.error).toBeUndefined()
})
it("should handle empty summary response and return error", async () => {
// We need enough messages to trigger summarization
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "I'm good", ts: 4 },
{ role: "user", content: "What's new?", ts: 5 },
{ role: "assistant", content: "Not much", ts: 6 },
{ role: "user", content: "Tell me more", ts: 7 },
]
// Setup empty summary response with usage information
const emptyStream = (async function* () {
yield { type: "text" as const, text: "" }
yield { type: "usage" as const, totalCost: 0.02, outputTokens: 0 }
})()
// Create a new mock for createMessage that returns empty stream
const createMessageMock = vi.fn().mockReturnValue(emptyStream)
mockApiHandler.createMessage = createMessageMock as any
// We need to mock maybeRemoveImageBlocks to return the expected messages
;(maybeRemoveImageBlocks as Mock).mockImplementationOnce((messages: any) => {
return messages.map(({ role, content }: { role: string; content: any }) => ({ role, content }))
})
const result = await summarizeConversation(
messages,
mockApiHandler,
defaultSystemPrompt,
taskId,
DEFAULT_PREV_CONTEXT_TOKENS,
)
// Should return original messages when summary is empty
expect(result.messages).toEqual(messages)
expect(result.cost).toBe(0.02)
expect(result.summary).toBe("")
expect(result.error).toBeTruthy() // Error should be set
expect(result.newContextTokens).toBeUndefined()
})
it("should correctly format the request to the API", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "I'm good", ts: 4 },
{ role: "user", content: "What's new?", ts: 5 },
{ role: "assistant", content: "Not much", ts: 6 },
{ role: "user", content: "Tell me more", ts: 7 },
]
await summarizeConversation(messages, mockApiHandler, defaultSystemPrompt, taskId, DEFAULT_PREV_CONTEXT_TOKENS)
// Verify the final request message
const expectedFinalMessage = {
role: "user",
content: "Summarize the conversation so far, as described in the prompt instructions.",
}
// Verify that createMessage was called with the correct prompt
expect(mockApiHandler.createMessage).toHaveBeenCalledWith(
expect.stringContaining("Your task is to create a detailed summary of the conversation"),
expect.any(Array),
)
// Check that maybeRemoveImageBlocks was called with the correct messages
const mockCallArgs = (maybeRemoveImageBlocks as Mock).mock.calls[0][0] as any[]
expect(mockCallArgs[mockCallArgs.length - 1]).toEqual(expectedFinalMessage)
})
it("should include the original first user message in summarization input", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Initial ask", ts: 1 },
{ role: "assistant", content: "Ack", ts: 2 },
{ role: "user", content: "Follow-up", ts: 3 },
{ role: "assistant", content: "Response", ts: 4 },
{ role: "user", content: "More", ts: 5 },
{ role: "assistant", content: "Later", ts: 6 },
{ role: "user", content: "Newest", ts: 7 },
]
await summarizeConversation(messages, mockApiHandler, defaultSystemPrompt, taskId, DEFAULT_PREV_CONTEXT_TOKENS)
const mockCallArgs = (maybeRemoveImageBlocks as Mock).mock.calls[0][0] as any[]
// Expect the original first user message to be present in the messages sent to the summarizer
const hasInitialAsk = mockCallArgs.some(
(m) =>
m.role === "user" &&
(typeof m.content === "string"
? m.content === "Initial ask"
: Array.isArray(m.content) &&
m.content.some((b: any) => b.type === "text" && b.text === "Initial ask")),
)
expect(hasInitialAsk).toBe(true)
})
it("should calculate newContextTokens correctly with systemPrompt", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },
{ role: "assistant", content: "I'm good", ts: 4 },
{ role: "user", content: "What's new?", ts: 5 },
{ role: "assistant", content: "Not much", ts: 6 },
{ role: "user", content: "Tell me more", ts: 7 },
]
const systemPrompt = "You are a helpful assistant."
// Create a stream with usage information
const streamWithUsage = (async function* () {
yield { type: "text" as const, text: "This is a summary with system prompt" }
yield { type: "usage" as const, totalCost: 0.06, outputTokens: 200 }
})()
// Override the mock for this test
mockApiHandler.createMessage = vi.fn().mockReturnValue(streamWithUsage) as any
const result = await summarizeConversation(
messages,
mockApiHandler,
systemPrompt,
taskId,
DEFAULT_PREV_CONTEXT_TOKENS,
)
// Verify that countTokens was called with the correct messages including system prompt
expect(mockApiHandler.countTokens).toHaveBeenCalled()
// Check the newContextTokens calculation includes system prompt
expect(result.newContextTokens).toBe(300) // 200 output tokens + 100 from countTokens
expect(result.cost).toBe(0.06)
expect(result.summary).toBe("This is a summary with system prompt")
expect(result.error).toBeUndefined()
})
it("should return error when new context tokens >= previous context tokens", async () => {
const messages: ApiMessage[] = [
{ role: "user", content: "Hello", ts: 1 },
{ role: "assistant", content: "Hi there", ts: 2 },
{ role: "user", content: "How are you?", ts: 3 },