Elffuss BraidHub

kikocis/continue public

main · 25.1 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import { BaseLlmApi } from "@continuedev/openai-adapters";
3import type { ChatHistoryItem } from "core/index.js";
4import { convertToUnifiedHistory } from "core/util/messageConversion.js";
5import { describe, expect, it, vi } from "vitest";
6
7import {
8 compactChatHistory,
9 findCompactionIndex,
10 getHistoryForLLM,
11} from "./compaction.js";
12import { streamChatResponse } from "./stream/streamChatResponse.js";
13
14// Mock the streamChatResponse function
15vi.mock("./stream/streamChatResponse.js", () => ({
16 streamChatResponse: vi.fn(),
17}));
18
19describe("compaction", () => {
20 const mockModel: ModelConfig = {
21 name: "test-model",
22 provider: "test",
23 model: "test-model",
24 } as ModelConfig;
25
26 const mockLlmApi = {} as BaseLlmApi;
27
28 describe("findCompactionIndex", () => {
29 it("should find compaction marker in chat history", () => {
30 const history = convertToUnifiedHistory([
31 { role: "system", content: "System message" },
32 { role: "user", content: "Hello" },
33 { role: "assistant", content: "Hi there" },
34 {
35 role: "assistant",
36 content: `\nThis is a summary`,
37 },
38 { role: "user", content: "Another message" },
39 ]);
40
41 // Add conversationSummary to mark this as a compaction message
42 history[3].conversationSummary = "This is a summary";
43
44 const index = findCompactionIndex(history);
45 expect(index).toBe(3);
46 });
47
48 it("should return null if no compaction marker found", () => {
49 const history = convertToUnifiedHistory([
50 { role: "system", content: "System message" },
51 { role: "user", content: "Hello" },
52 { role: "assistant", content: "Hi there" },
53 ]);
54
55 const index = findCompactionIndex(history);
56 expect(index).toBeNull();
57 });
58
59 it("should return first compaction marker when multiple exist", () => {
60 const history = convertToUnifiedHistory([
61 { role: "system", content: "System message" },
62 { role: "assistant", content: `\nFirst summary` },
63 { role: "user", content: "Hello" },
64 { role: "assistant", content: `\nSecond summary` },
65 ]);
66
67 // Add conversationSummary to mark these as compaction messages
68 history[1].conversationSummary = "First summary";
69 history[3].conversationSummary = "Second summary";
70
71 const index = findCompactionIndex(history);
72 expect(index).toBe(1);
73 });
74
75 it("should return null for empty chat history", () => {
76 const history = convertToUnifiedHistory([]);
77 const index = findCompactionIndex(history);
78 expect(index).toBeNull();
79 });
80
81 it("should not match marker in middle of content", () => {
82 const history = convertToUnifiedHistory([
83 { role: "system", content: "System message" },
84 {
85 role: "assistant",
86 content: `Some text in the middle`,
87 },
88 { role: "user", content: "Hello" },
89 ]);
90
91 // Don't add conversationSummary - this should not be found
92 const index = findCompactionIndex(history);
93 expect(index).toBeNull();
94 });
95
96 it("should handle non-string content", () => {
97 // Create history items manually since convertToUnifiedHistory will throw on invalid content
98 const history: ChatHistoryItem[] = [
99 {
100 message: { role: "system", content: "System message" },
101 contextItems: [],
102 },
103 {
104 message: { role: "assistant", content: null as any },
105 contextItems: [],
106 },
107 {
108 message: { role: "assistant", content: undefined as any },
109 contextItems: [],
110 },
111 {
112 message: {
113 role: "assistant",
114 content: `\\nValid compaction`,
115 },
116 contextItems: [],
117 conversationSummary: "Valid compaction",
118 },
119 ];
120
121 const index = findCompactionIndex(history);
122 expect(index).toBe(3);
123 });
124
125 it("should only match messages with conversationSummary", () => {
126 const history = convertToUnifiedHistory([
127 { role: "system", content: `\nSystem compaction?` },
128 { role: "user", content: `\nUser compaction?` },
129 { role: "assistant", content: `\nReal compaction` },
130 ]);
131
132 // Only add conversationSummary to the assistant message
133 history[2].conversationSummary = "Real compaction";
134
135 const index = findCompactionIndex(history);
136 expect(index).toBe(2);
137 });
138 });
139
140 describe("getHistoryForLLM", () => {
141 it("should return full history when no compaction index", () => {
142 const history = convertToUnifiedHistory([
143 { role: "system", content: "System message" },
144 { role: "user", content: "Hello" },
145 { role: "assistant", content: "Hi there" },
146 ]);
147
148 const result = getHistoryForLLM(history, null);
149 expect(result).toEqual(history);
150 });
151
152 it("should return compacted history with system message", () => {
153 const history = convertToUnifiedHistory([
154 { role: "system", content: "System message" },
155 { role: "user", content: "Hello" },
156 { role: "assistant", content: "Hi there" },
157 {
158 role: "assistant",
159 content: `\nThis is a summary`,
160 },
161 { role: "user", content: "Another message" },
162 ]);
163
164 const result = getHistoryForLLM(history, 3);
165 expect(result).toEqual([
166 {
167 message: { role: "system", content: "System message" },
168 contextItems: [],
169 },
170 {
171 message: {
172 role: "assistant",
173 content: `\nThis is a summary`,
174 },
175 contextItems: [],
176 },
177 {
178 message: { role: "user", content: "Another message" },
179 contextItems: [],
180 },
181 ]);
182 });
183
184 it("should return compacted history without system message when compaction is at index 0", () => {
185 const history = convertToUnifiedHistory([
186 {
187 role: "assistant",
188 content: `\nThis is a summary`,
189 },
190 { role: "user", content: "Another message" },
191 ]);
192
193 const result = getHistoryForLLM(history, 0);
194 expect(result).toEqual(history);
195 });
196
197 it("should return full history when compactionIndex is out of bounds", () => {
198 const history = convertToUnifiedHistory([
199 { role: "system", content: "System message" },
200 { role: "user", content: "Hello" },
201 ]);
202
203 const result = getHistoryForLLM(history, 10);
204 expect(result).toEqual(history);
205 });
206
207 it("should handle negative compactionIndex", () => {
208 const history = convertToUnifiedHistory([
209 { role: "system", content: "System message" },
210 { role: "user", content: "Hello" },
211 ]);
212
213 const result = getHistoryForLLM(history, -1);
214 // Negative index with slice means "from the end", so -1 gives us only the last message
215 // Since compactionIndex is not > 0, system message is not included
216 expect(result).toEqual([
217 {
218 message: { role: "user", content: "Hello" },
219 contextItems: [],
220 },
221 ]);
222 });
223
224 it("should handle empty history", () => {
225 const history = convertToUnifiedHistory([]);
226 const result = getHistoryForLLM(history, 0);
227 expect(result).toEqual([]);
228 });
229
230 it("should handle history with only system message", () => {
231 const history = convertToUnifiedHistory([
232 { role: "system", content: "System message" },
233 ]);
234
235 const result = getHistoryForLLM(history, 0);
236 expect(result).toEqual(history);
237 });
238
239 it("should handle history without system message but with compaction", () => {
240 const history = convertToUnifiedHistory([
241 { role: "user", content: "First message" },
242 { role: "assistant", content: `\nSummary` },
243 { role: "user", content: "New message" },
244 ]);
245
246 const result = getHistoryForLLM(history, 1);
247 expect(result).toEqual([
248 {
249 message: {
250 role: "assistant",
251 content: `\nSummary`,
252 },
253 contextItems: [],
254 },
255 {
256 message: { role: "user", content: "New message" },
257 contextItems: [],
258 },
259 ]);
260 });
261
262 it("should include system message when first message is not system", () => {
263 const history = convertToUnifiedHistory([
264 { role: "user", content: "First user message" },
265 { role: "system", content: "System message in wrong position" },
266 { role: "assistant", content: `\nSummary` },
267 { role: "user", content: "New message" },
268 ]);
269
270 // Since system message is not at index 0, it's not included
271 const result = getHistoryForLLM(history, 2);
272 expect(result).toEqual([
273 {
274 message: {
275 role: "assistant",
276 content: `\nSummary`,
277 },
278 contextItems: [],
279 },
280 {
281 message: { role: "user", content: "New message" },
282 contextItems: [],
283 },
284 ]);
285 });
286
287 it("should preserve message order from compaction point", () => {
288 const history = convertToUnifiedHistory([
289 { role: "system", content: "System" },
290 { role: "user", content: "Old 1" },
291 { role: "assistant", content: "Old 2" },
292 { role: "assistant", content: `\nSummary` },
293 { role: "user", content: "New 1" },
294 { role: "assistant", content: "New 2" },
295 { role: "user", content: "New 3" },
296 ]);
297
298 const result = getHistoryForLLM(history, 3);
299 expect(result).toEqual([
300 {
301 message: { role: "system", content: "System" },
302 contextItems: [],
303 },
304 {
305 message: {
306 role: "assistant",
307 content: `\nSummary`,
308 },
309 contextItems: [],
310 },
311 {
312 message: { role: "user", content: "New 1" },
313 contextItems: [],
314 },
315 {
316 message: { role: "assistant", content: "New 2" },
317 contextItems: [],
318 },
319 {
320 message: { role: "user", content: "New 3" },
321 contextItems: [],
322 },
323 ]);
324 });
325 });
326
327 describe("compactChatHistory", () => {
328 it("should compact chat history successfully", async () => {
329 const mockStreamResponse = vi.mocked(streamChatResponse);
330 const mockContent = "This is a summary of the conversation";
331
332 mockStreamResponse.mockImplementation(
333 async (history, model, api, controller, callbacks) => {
334 callbacks?.onContent?.(mockContent);
335 callbacks?.onContentComplete?.(mockContent);
336 return mockContent;
337 },
338 );
339
340 const history = convertToUnifiedHistory([
341 { role: "system", content: "System message" },
342 { role: "user", content: "Hello" },
343 { role: "assistant", content: "Hi there" },
344 ]);
345
346 const result = await compactChatHistory(history, mockModel, mockLlmApi);
347
348 expect(result.compactedHistory).toHaveLength(2);
349 expect(result.compactedHistory[0]).toEqual({
350 message: {
351 role: "system",
352 content: "System message",
353 },
354 contextItems: [],
355 });
356 expect(result.compactedHistory[1]).toEqual({
357 message: {
358 role: "assistant",
359 content: mockContent,
360 },
361 contextItems: [],
362 conversationSummary: mockContent,
363 });
364 expect(result.compactionIndex).toBe(1);
365 expect(result.compactionContent).toBe(mockContent);
366 });
367
368 it("should handle callbacks correctly", async () => {
369 const mockStreamResponse = vi.mocked(streamChatResponse);
370 const mockContent = "Summary content";
371 const onStreamContent = vi.fn();
372 const onStreamComplete = vi.fn();
373
374 mockStreamResponse.mockImplementation(
375 async (history, model, api, controller, callbacks) => {
376 callbacks?.onContent?.("Summary ");
377 callbacks?.onContent?.("content");
378 callbacks?.onContentComplete?.(mockContent);
379 return mockContent;
380 },
381 );
382
383 const history = convertToUnifiedHistory([
384 { role: "user", content: "Hello" },
385 ]);
386
387 await compactChatHistory(history, mockModel, mockLlmApi, {
388 onStreamContent,
389 onStreamComplete,
390 });
391
392 expect(onStreamContent).toHaveBeenCalledWith("Summary ");
393 expect(onStreamContent).toHaveBeenCalledWith("content");
394 expect(onStreamComplete).toHaveBeenCalled();
395 });
396
397 it("should handle errors correctly", async () => {
398 const mockStreamResponse = vi.mocked(streamChatResponse);
399 const mockError = new Error("Stream failed");
400 const onError = vi.fn();
401
402 mockStreamResponse.mockRejectedValue(mockError);
403
404 const history = convertToUnifiedHistory([
405 { role: "user", content: "Hello" },
406 ]);
407
408 await expect(
409 compactChatHistory(history, mockModel, mockLlmApi, { onError }),
410 ).rejects.toThrow("Stream failed");
411
412 expect(onError).toHaveBeenCalledWith(mockError);
413 });
414
415 it("should handle history with only system message", async () => {
416 const mockStreamResponse = vi.mocked(streamChatResponse);
417 const mockContent = "Summary of system setup";
418
419 mockStreamResponse.mockImplementation(
420 async (history, model, api, controller, callbacks) => {
421 callbacks?.onContent?.(mockContent);
422 callbacks?.onContentComplete?.(mockContent);
423 return mockContent;
424 },
425 );
426
427 const history = convertToUnifiedHistory([
428 { role: "system", content: "You are a helpful assistant" },
429 ]);
430
431 const result = await compactChatHistory(history, mockModel, mockLlmApi);
432
433 expect(result.compactedHistory).toHaveLength(2);
434 expect(result.compactedHistory[0].message).toEqual({
435 role: "system",
436 content: "You are a helpful assistant",
437 });
438 expect(result.compactedHistory[1].message.content).toContain(
439 "Summary of system setup",
440 );
441 });
442
443 it("should handle empty content from stream", async () => {
444 const mockStreamResponse = vi.mocked(streamChatResponse);
445
446 mockStreamResponse.mockImplementation(
447 async (history, model, api, controller, callbacks) => {
448 callbacks?.onContent?.("");
449 callbacks?.onContentComplete?.("");
450 return "";
451 },
452 );
453
454 const history = convertToUnifiedHistory([
455 { role: "user", content: "Hello" },
456 ]);
457
458 const result = await compactChatHistory(history, mockModel, mockLlmApi);
459
460 expect(result.compactionContent).toBe("");
461 expect(result.compactedHistory[0].message.content).toBe("");
462 });
463
464 it("should correctly construct prompt for compaction", async () => {
465 const mockStreamResponse = vi.mocked(streamChatResponse);
466 let capturedHistory: ChatHistoryItem[] = [];
467
468 mockStreamResponse.mockImplementation(
469 async (history, model, api, controller, callbacks) => {
470 capturedHistory = [...history];
471 callbacks?.onContent?.("Summary");
472 callbacks?.onContentComplete?.("Summary");
473 return "Summary";
474 },
475 );
476
477 const history = convertToUnifiedHistory([
478 { role: "system", content: "System" },
479 { role: "user", content: "Hello" },
480 { role: "assistant", content: "Hi" },
481 ]);
482
483 await compactChatHistory(history, mockModel, mockLlmApi);
484
485 // Should have original history plus the compaction prompt
486 expect(capturedHistory).toHaveLength(4);
487 expect(capturedHistory[3].message).toEqual({
488 role: "user",
489 content: expect.stringContaining("provide a concise summary"),
490 });
491 });
492
493 it("should handle history with tool calls and mixed message types", async () => {
494 const mockStreamResponse = vi.mocked(streamChatResponse);
495 const mockContent = "Summary including tool usage";
496
497 mockStreamResponse.mockImplementation(
498 async (history, model, api, controller, callbacks) => {
499 callbacks?.onContent?.(mockContent);
500 callbacks?.onContentComplete?.(mockContent);
501 return mockContent;
502 },
503 );
504
505 const history = convertToUnifiedHistory([
506 { role: "system", content: "System" },
507 { role: "user", content: "Do something" },
508 { role: "assistant", content: "I'll help", tool_calls: [{} as any] },
509 { role: "tool", content: "Tool result", tool_call_id: "123" },
510 { role: "assistant", content: "Done" },
511 ]);
512
513 const result = await compactChatHistory(history, mockModel, mockLlmApi);
514
515 expect(result.compactedHistory).toHaveLength(2);
516 expect(result.compactionContent).toBe(mockContent);
517 });
518
519 it("should handle very long chat histories", async () => {
520 const mockStreamResponse = vi.mocked(streamChatResponse);
521
522 mockStreamResponse.mockImplementation(
523 async (history, model, api, controller, callbacks) => {
524 callbacks?.onContent?.("Long summary");
525 callbacks?.onContentComplete?.("Long summary");
526 return "Long summary";
527 },
528 );
529
530 // Create a very long history
531 const history = convertToUnifiedHistory([
532 { role: "system", content: "System" },
533 ]);
534
535 for (let i = 0; i < 100; i++) {
536 history.push({
537 message: { role: "user", content: `User message ${i}` },
538 contextItems: [],
539 });
540 history.push({
541 message: { role: "assistant", content: `Assistant response ${i}` },
542 contextItems: [],
543 });
544 }
545
546 const result = await compactChatHistory(history, mockModel, mockLlmApi);
547
548 expect(result.compactedHistory).toHaveLength(2); // System + compaction
549 expect(result.compactionIndex).toBe(1);
550 });
551
552 it("should handle history without system message", async () => {
553 const mockStreamResponse = vi.mocked(streamChatResponse);
554 const mockContent = "Summary without system";
555
556 mockStreamResponse.mockImplementation(
557 async (history, model, api, controller, callbacks) => {
558 callbacks?.onContent?.(mockContent);
559 callbacks?.onContentComplete?.(mockContent);
560 return mockContent;
561 },
562 );
563
564 const history = convertToUnifiedHistory([
565 { role: "user", content: "Hello" },
566 { role: "assistant", content: "Hi" },
567 ]);
568
569 const result = await compactChatHistory(history, mockModel, mockLlmApi);
570
571 expect(result.compactedHistory).toHaveLength(1); // Only compaction
572 expect(result.compactedHistory[0].message.role).toBe("assistant");
573 expect(result.compactionIndex).toBe(0);
574 });
575 });
576
577 describe("property-based tests", () => {
578 it("getHistoryForLLM should always return a subset of the original history", () => {
579 const testCases: Array<{
580 history: ChatHistoryItem[];
581 compactionIndex: number | null;
582 }> = [
583 {
584 history: convertToUnifiedHistory([
585 { role: "system", content: "System" },
586 { role: "user", content: "User 1" },
587 { role: "assistant", content: "Assistant 1" },
588 ]),
589 compactionIndex: 1,
590 },
591 {
592 history: convertToUnifiedHistory([
593 { role: "user", content: "User 1" },
594 { role: "assistant", content: "Assistant 1" },
595 { role: "user", content: "User 2" },
596 ]),
597 compactionIndex: 2,
598 },
599 {
600 history: [],
601 compactionIndex: null,
602 },
603 ];
604
605 testCases.forEach(({ history, compactionIndex }) => {
606 const result = getHistoryForLLM(history, compactionIndex);
607
608 // Every message in result should exist in original history
609 result.forEach((msg) => {
610 expect(history).toContainEqual(msg);
611 });
612
613 // Result length should be <= original length
614 expect(result.length).toBeLessThanOrEqual(history.length);
615 });
616 });
617
618 it("getHistoryForLLM should always include system message if it exists at index 0", () => {
619 const systemMessage: ChatHistoryItem = {
620 message: {
621 role: "system",
622 content: "System",
623 },
624 contextItems: [],
625 };
626 const testCases: Array<{
627 history: ChatHistoryItem[];
628 compactionIndex: number | null;
629 }> = [
630 {
631 history: convertToUnifiedHistory([
632 { role: "system", content: "System" },
633 { role: "user", content: "User 1" },
634 { role: "assistant", content: `\nSummary` },
635 ]),
636 compactionIndex: 2,
637 },
638 {
639 history: convertToUnifiedHistory([
640 { role: "system", content: "System" },
641 { role: "assistant", content: `\nSummary` },
642 ]),
643 compactionIndex: 1,
644 },
645 ];
646
647 testCases.forEach(({ history, compactionIndex }) => {
648 const result = getHistoryForLLM(history, compactionIndex);
649
650 if (
651 history[0]?.message?.role === "system" &&
652 compactionIndex !== null &&
653 compactionIndex > 0
654 ) {
655 expect(result[0]).toEqual(history[0]);
656 }
657 });
658 });
659
660 it("compaction should always reduce message count for non-trivial histories", async () => {
661 const mockStreamResponse = vi.mocked(streamChatResponse);
662
663 mockStreamResponse.mockImplementation(
664 async (history, model, api, controller, callbacks) => {
665 callbacks?.onContent?.("Summary");
666 callbacks?.onContentComplete?.("Summary");
667 return "Summary";
668 },
669 );
670
671 const testHistories: ChatHistoryItem[][] = [
672 convertToUnifiedHistory([
673 { role: "system", content: "System" },
674 { role: "user", content: "User 1" },
675 { role: "assistant", content: "Assistant 1" },
676 { role: "user", content: "User 2" },
677 { role: "assistant", content: "Assistant 2" },
678 ]),
679 convertToUnifiedHistory([
680 { role: "user", content: "User 1" },
681 { role: "assistant", content: "Assistant 1" },
682 { role: "user", content: "User 2" },
683 ]),
684 ];
685
686 for (const history of testHistories) {
687 const result = await compactChatHistory(history, mockModel, mockLlmApi);
688
689 // Compacted history should be shorter than original
690 // (system + compaction) or just compaction
691 expect(result.compactedHistory.length).toBeLessThanOrEqual(2);
692 expect(result.compactedHistory.length).toBeLessThan(history.length);
693 }
694 });
695 });
696
697 describe("invariant tests", () => {
698 it("compactionIndex should always point to a message with conversationSummary", async () => {
699 const mockStreamResponse = vi.mocked(streamChatResponse);
700
701 mockStreamResponse.mockImplementation(
702 async (history, model, api, controller, callbacks) => {
703 callbacks?.onContent?.("Summary content");
704 callbacks?.onContentComplete?.("Summary content");
705 return "Summary content";
706 },
707 );
708
709 const histories: ChatHistoryItem[][] = [
710 convertToUnifiedHistory([
711 { role: "system", content: "System" },
712 { role: "user", content: "Hello" },
713 ]),
714 convertToUnifiedHistory([
715 { role: "user", content: "Hello" },
716 { role: "assistant", content: "Hi" },
717 ]),
718 convertToUnifiedHistory([{ role: "system", content: "System" }]),
719 ];
720
721 for (const history of histories) {
722 const result = await compactChatHistory(history, mockModel, mockLlmApi);
723
724 // The message at compactionIndex should have a conversationSummary
725 const compactionMessage =
726 result.compactedHistory[result.compactionIndex];
727 expect(compactionMessage.message.role).toBe("assistant");
728 expect(compactionMessage.conversationSummary).toBeDefined();
729 }
730 });
731
732 it("system message should always be preserved in the same position", async () => {
733 const mockStreamResponse = vi.mocked(streamChatResponse);
734
735 mockStreamResponse.mockImplementation(
736 async (history, model, api, controller, callbacks) => {
737 callbacks?.onContent?.("Summary");
738 callbacks?.onContentComplete?.("Summary");
739 return "Summary";
740 },
741 );
742
743 const history = convertToUnifiedHistory([
744 { role: "system", content: "You are helpful" },
745 { role: "user", content: "Hello" },
746 { role: "assistant", content: "Hi" },
747 ]);
748
749 const result = await compactChatHistory(history, mockModel, mockLlmApi);
750
751 // System message should still be at index 0
752 expect(result.compactedHistory[0]).toEqual(history[0]);
753 });
754
755 it("findCompactionIndex should be consistent with compactChatHistory result", async () => {
756 const mockStreamResponse = vi.mocked(streamChatResponse);
757
758 mockStreamResponse.mockImplementation(
759 async (history, model, api, controller, callbacks) => {
760 callbacks?.onContent?.("Summary");
761 callbacks?.onContentComplete?.("Summary");
762 return "Summary";
763 },
764 );
765
766 const history = convertToUnifiedHistory([
767 { role: "user", content: "Hello" },
768 { role: "assistant", content: "Hi" },
769 ]);
770
771 const result = await compactChatHistory(history, mockModel, mockLlmApi);
772
773 // findCompactionIndex should find the same index
774 const foundIndex = findCompactionIndex(result.compactedHistory);
775 expect(foundIndex).toBe(result.compactionIndex);
776 });
777 });
778});