Elffuss BraidHub

kikocis/continue public

main · 45.4 KiBRawPermalink
1import { JSONContent } from "@tiptap/core";
2import { InputModifiers } from "core";
3import { describe, expect, it, vi } from "vitest";
4import { createMockStore } from "../../util/test/mockStore";
5import { streamResponseThunk } from "./streamResponse";
6
7// Mock external dependencies only - let selectors run naturally
8// Removed: modelSupportsNativeTools - let it run naturally
9
10// Removed: addSystemMessageToolsToSystemMessage - let it run naturally
11
12// Mock system message construction to keep test readable
13vi.mock("../util/getBaseSystemMessage", () => ({
14 getBaseSystemMessage: vi.fn(),
15}));
16
17import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
18
19// Removed: shouldAutoEnableSystemMessageTools - let it run naturally
20
21// Additional mocks for streamResponseThunk
22vi.mock("posthog-js", () => ({
23 default: {
24 capture: vi.fn(),
25 },
26}));
27
28vi.mock("uuid", () => ({
29 v4: vi.fn(() => "mock-uuid-123"),
30}));
31
32vi.mock(
33 "../../components/mainInput/TipTapEditor/utils/resolveEditorContent",
34 () => ({
35 resolveEditorContent: vi.fn(),
36 }),
37);
38
39import { ModelDescription } from "core";
40import posthog from "posthog-js";
41import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
42
43const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage);
44
45const mockPosthog = vi.mocked(posthog);
46const mockResolveEditorContent = vi.mocked(resolveEditorContent);
47
48const mockClaudeModel: ModelDescription = {
49 title: "Claude 3.5 Sonnet",
50 model: "claude-3-5-sonnet-20241022",
51 provider: "anthropic",
52 underlyingProviderName: "anthropic",
53 completionOptions: { reasoningBudgetTokens: 2048 },
54};
55
56// Mock editor state (what user types in the input)
57const mockEditorState: JSONContent = {
58 type: "doc",
59 content: [
60 {
61 type: "paragraph",
62 content: [{ type: "text", text: "Hello, please help me with this code" }],
63 },
64 ],
65};
66
67// Mock input modifiers (codebase context, etc.)
68const mockModifiers: InputModifiers = {
69 useCodebase: true,
70 noContext: false,
71};
72
73function setupTest() {
74 vi.clearAllMocks();
75
76 // Default mock implementations for external functions
77
78 // Default mock for resolveEditorContent (can be overridden in individual tests)
79 mockResolveEditorContent.mockResolvedValue({
80 selectedContextItems: [],
81 selectedCode: [],
82 content: "Hello, please help me with this code",
83 legacyCommandWithInput: undefined,
84 });
85
86 // Mock getBaseSystemMessage to return simple system message for readable tests
87 mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant.");
88
89 // Create store with realistic state that selectors can work with
90 const mockStore = createMockStore({
91 session: {
92 history: [
93 {
94 message: { id: "1", role: "user", content: "Hello" },
95 contextItems: [],
96 },
97 ],
98 hasReasoningEnabled: false,
99 isStreaming: true,
100 id: "session-123",
101 mode: "chat",
102 streamAborter: new AbortController(),
103 contextPercentage: 0,
104 isPruned: false,
105 isInEdit: false,
106 title: "",
107 lastSessionId: undefined,
108 isSessionMetadataLoading: false,
109 allSessionMetadata: [],
110 symbols: {},
111 codeBlockApplyStates: {
112 states: [],
113 curIndex: 0,
114 },
115 newestToolbarPreviewForInput: {},
116 compactionLoading: {},
117 inlineErrorMessage: undefined,
118 },
119 config: {
120 config: {
121 tools: [],
122 rules: [],
123 tabAutocompleteModel: undefined,
124 selectedModelByRole: {
125 chat: mockClaudeModel,
126 apply: null,
127 edit: null,
128 summarize: null,
129 autocomplete: null,
130 rerank: null,
131 embed: null,
132 },
133 experimental: {
134 onlyUseSystemMessageTools: false,
135 },
136 } as any,
137 lastSelectedModelByRole: {
138 chat: mockClaudeModel.title,
139 },
140 } as any,
141 ui: {
142 toolSettings: {},
143 ruleSettings: {},
144 showDialog: false,
145 dialogMessage: undefined,
146 } as any,
147 });
148
149 const mockIdeMessenger = mockStore.mockIdeMessenger;
150
151 return { mockStore, mockIdeMessenger };
152}
153
154describe("streamResponseThunk", () => {
155 it("should execute complete streaming flow with all dispatches", async () => {
156 const { mockStore, mockIdeMessenger } = setupTest();
157
158 // Mock all necessary IDE messenger calls
159 mockIdeMessenger.request.mockImplementation((endpoint: string) => {
160 if (endpoint === "llm/compileChat") {
161 return Promise.resolve({
162 status: "success",
163 content: {
164 compiledChatMessages: [{ role: "user", content: "Hello" }],
165 didPrune: false,
166 contextPercentage: 0.8,
167 },
168 });
169 } else if (endpoint === "history/save") {
170 return Promise.resolve({ status: "success" });
171 } else if (endpoint === "session/refreshMetadata") {
172 return Promise.resolve({
173 status: "success",
174 content: {
175 compiledChatMessages: [{ role: "user", content: "Hello" }],
176 didPrune: false,
177 contextPercentage: 0.8,
178 },
179 });
180 }
181 return Promise.resolve({ status: "success", content: {} });
182 });
183
184 // Setup streaming generator
185 async function* mockStreamGenerator() {
186 yield [{ role: "assistant", content: "First chunk" }];
187 yield [{ role: "assistant", content: "Second chunk" }];
188 return {
189 prompt: "Hello",
190 completion: "Hi there!",
191 modelProvider: "anthropic",
192 };
193 }
194
195 mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamGenerator());
196
197 // Execute thunk
198 const result = await mockStore.dispatch(
199 streamResponseThunk({
200 editorState: mockEditorState,
201 modifiers: mockModifiers,
202 }) as any,
203 );
204
205 // Verify exact sequence of dispatched actions with payloads
206 const dispatchedActions = (mockStore as any).getActions();
207
208 expect(dispatchedActions).toEqual([
209 {
210 type: "chat/streamResponse/pending",
211 meta: expect.objectContaining({
212 arg: { editorState: mockEditorState, modifiers: mockModifiers },
213 requestStatus: "pending",
214 }),
215 payload: undefined,
216 },
217 {
218 type: "chat/streamWrapper/pending",
219 meta: expect.objectContaining({
220 requestStatus: "pending",
221 }),
222 payload: undefined,
223 },
224 {
225 type: "session/submitEditorAndInitAtIndex",
226 payload: {
227 editorState: mockEditorState,
228 index: 1,
229 },
230 },
231 {
232 type: "session/resetNextCodeBlockToApplyIndex",
233 payload: undefined,
234 },
235 {
236 type: "symbols/updateFromContextItems/pending",
237 meta: expect.objectContaining({
238 arg: [],
239 requestStatus: "pending",
240 }),
241 payload: undefined,
242 },
243 {
244 type: "session/updateHistoryItemAtIndex",
245 payload: {
246 index: 1,
247 updates: {
248 contextItems: [],
249 message: {
250 content: "Hello, please help me with this code",
251 id: "mock-uuid-123",
252 role: "user",
253 },
254 },
255 },
256 },
257 {
258 type: "chat/streamNormalInput/pending",
259 meta: expect.objectContaining({
260 arg: { legacySlashCommandData: undefined },
261 requestStatus: "pending",
262 }),
263 payload: undefined,
264 },
265 {
266 type: "session/setAppliedRulesAtIndex",
267 payload: {
268 index: 1,
269 appliedRules: [],
270 },
271 },
272 {
273 type: "session/setActive",
274 payload: undefined,
275 },
276 {
277 type: "session/setInlineErrorMessage",
278 payload: undefined,
279 },
280 {
281 type: "session/setIsPruned",
282 payload: false,
283 },
284 {
285 type: "session/setContextPercentage",
286 payload: 0.8,
287 },
288 {
289 type: "symbols/updateFromContextItems/fulfilled",
290 meta: expect.objectContaining({
291 arg: [],
292 requestStatus: "fulfilled",
293 }),
294 payload: undefined,
295 },
296 {
297 type: "session/streamUpdate",
298 payload: [
299 {
300 role: "assistant",
301 content: "First chunk",
302 },
303 ],
304 },
305 {
306 type: "session/streamUpdate",
307 payload: [
308 {
309 role: "assistant",
310 content: "Second chunk",
311 },
312 ],
313 },
314 {
315 type: "session/addPromptCompletionPair",
316 payload: [
317 {
318 prompt: "Hello",
319 completion: "Hi there!",
320 modelProvider: "anthropic",
321 },
322 ],
323 },
324 {
325 type: "session/setInactive",
326 payload: undefined,
327 },
328 {
329 type: "chat/streamNormalInput/fulfilled",
330 meta: expect.objectContaining({
331 arg: { legacySlashCommandData: undefined },
332 requestStatus: "fulfilled",
333 }),
334 payload: undefined,
335 },
336 {
337 type: "session/saveCurrent/pending",
338 meta: expect.objectContaining({
339 arg: { generateTitle: true, openNewSession: false },
340 requestStatus: "pending",
341 }),
342 payload: undefined,
343 },
344 {
345 type: "session/update/pending",
346 meta: expect.objectContaining({
347 requestStatus: "pending",
348 }),
349 payload: undefined,
350 },
351 {
352 type: "session/updateSessionMetadata",
353 payload: {
354 sessionId: "session-123",
355 title: "New Session",
356 },
357 },
358 {
359 type: "session/refreshMetadata/pending",
360 meta: expect.objectContaining({
361 requestStatus: "pending",
362 }),
363 payload: undefined,
364 },
365 {
366 type: "session/setIsSessionMetadataLoading",
367 payload: false,
368 },
369 {
370 type: "session/setAllSessionMetadata",
371 payload: {},
372 },
373 {
374 type: "session/refreshMetadata/fulfilled",
375 meta: expect.objectContaining({
376 requestStatus: "fulfilled",
377 }),
378 payload: {},
379 },
380 {
381 type: "session/update/fulfilled",
382 meta: expect.objectContaining({
383 requestStatus: "fulfilled",
384 }),
385 payload: undefined,
386 },
387 {
388 type: "session/saveCurrent/fulfilled",
389 meta: expect.objectContaining({
390 arg: { generateTitle: true, openNewSession: false },
391 requestStatus: "fulfilled",
392 }),
393 payload: undefined,
394 },
395 {
396 type: "chat/streamWrapper/fulfilled",
397 meta: expect.objectContaining({
398 requestStatus: "fulfilled",
399 }),
400 payload: undefined,
401 },
402 {
403 type: "chat/streamResponse/fulfilled",
404 meta: expect.objectContaining({
405 arg: { editorState: mockEditorState, modifiers: mockModifiers },
406 requestStatus: "fulfilled",
407 }),
408 payload: undefined,
409 },
410 ]);
411
412 // Verify IDE messenger calls
413 expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", {
414 messages: [
415 {
416 role: "system",
417 content: "You are a helpful assistant.",
418 },
419 {
420 role: "user",
421 content: [
422 {
423 type: "text",
424 text: "Hello",
425 },
426 ],
427 },
428 {
429 role: "user",
430 content: [
431 {
432 type: "text",
433 text: "Hello, please help me with this code",
434 },
435 ],
436 },
437 ],
438 options: {
439 reasoning: false,
440 },
441 });
442
443 expect(mockIdeMessenger.llmStreamChat).toHaveBeenCalledWith(
444 {
445 completionOptions: {
446 reasoning: false,
447 },
448 legacySlashCommandData: undefined,
449 messageOptions: { precompiled: true },
450 messages: [
451 {
452 role: "user",
453 content: "Hello",
454 },
455 ],
456 title: "Claude 3.5 Sonnet",
457 },
458 expect.any(AbortSignal),
459 );
460
461 // Verify dev data logging call
462 expect(mockIdeMessenger.post).toHaveBeenCalledWith("devdata/log", {
463 name: "chatInteraction",
464 data: {
465 prompt: "Hello",
466 completion: "Hi there!",
467 modelProvider: "anthropic",
468 modelName: "Claude 3.5 Sonnet",
469 modelTitle: "Claude 3.5 Sonnet",
470 sessionId: "session-123",
471 },
472 });
473
474 // Verify session save was called
475 expect(mockIdeMessenger.request).toHaveBeenCalledWith(
476 "history/save",
477 expect.anything(),
478 );
479
480 expect(result.type).toBe("chat/streamResponse/fulfilled");
481
482 // Verify final state after thunk completion
483 const finalState = mockStore.getState();
484 expect(finalState).toEqual({
485 session: {
486 history: [
487 {
488 contextItems: [],
489 message: { id: "1", role: "user", content: "Hello" },
490 },
491 {
492 appliedRules: [],
493 contextItems: [],
494 editorState: mockEditorState,
495 message: {
496 content: "Hello, please help me with this code",
497 id: "mock-uuid-123",
498 role: "user",
499 },
500 },
501 {
502 contextItems: [],
503 isGatheringContext: false,
504 message: {
505 content: "First chunkSecond chunk", // Chunks get combined
506 id: "mock-uuid-123",
507 role: "assistant",
508 },
509 promptLogs: [
510 {
511 completion: "Hi there!",
512 modelProvider: "anthropic",
513 prompt: "Hello",
514 },
515 ],
516 },
517 ],
518 hasReasoningEnabled: false,
519 isStreaming: false,
520 id: "session-123",
521 mode: "chat",
522 streamAborter: expect.any(AbortController),
523 contextPercentage: 0.8,
524 isPruned: false,
525 isInEdit: false,
526 title: "New Session",
527 lastSessionId: undefined,
528 isSessionMetadataLoading: false,
529 allSessionMetadata: {},
530 symbols: {},
531 codeBlockApplyStates: {
532 states: [],
533 curIndex: 0,
534 },
535 newestToolbarPreviewForInput: {},
536 compactionLoading: {},
537 inlineErrorMessage: undefined,
538 },
539 config: {
540 config: {
541 tools: [],
542 rules: [],
543 tabAutocompleteModel: undefined,
544 selectedModelByRole: {
545 chat: mockClaudeModel,
546 apply: null,
547 edit: null,
548 summarize: null,
549 autocomplete: null,
550 rerank: null,
551 embed: null,
552 },
553 experimental: {
554 onlyUseSystemMessageTools: false,
555 },
556 },
557 lastSelectedModelByRole: {
558 chat: mockClaudeModel.title,
559 },
560 loading: false,
561 configError: undefined,
562 },
563 ui: {
564 toolSettings: {},
565 ruleSettings: {},
566 showDialog: false,
567 dialogMessage: undefined,
568 },
569 editModeState: {
570 isInEdit: false,
571 returnToMode: "chat",
572 },
573 indexing: {
574 indexing: {
575 statuses: {},
576 hiddenChatPeekTypes: {
577 docs: false,
578 },
579 },
580 },
581 tabs: {
582 tabsItems: [],
583 },
584 profiles: {
585 organizations: [],
586 selectedProfileId: null,
587 selectedOrganizationId: null,
588 preferencesByProfileId: {},
589 },
590 });
591 });
592
593 it("should execute streaming flow with tool call execution", async () => {
594 const { mockStore, mockIdeMessenger } = setupTest();
595
596 // Set up auto-approved tool setting for our test tool
597 const mockStoreWithToolSettings = createMockStore({
598 session: {
599 history: [
600 {
601 message: {
602 id: "1",
603 role: "user",
604 content: "Please search the codebase",
605 },
606 contextItems: [],
607 },
608 ],
609 hasReasoningEnabled: false,
610 isStreaming: true,
611 id: "session-123",
612 mode: "chat",
613 streamAborter: new AbortController(),
614 contextPercentage: 0,
615 isPruned: false,
616 isInEdit: false,
617 title: "",
618 lastSessionId: undefined,
619 isSessionMetadataLoading: false,
620 allSessionMetadata: [],
621 symbols: {},
622 codeBlockApplyStates: {
623 states: [],
624 curIndex: 0,
625 },
626 newestToolbarPreviewForInput: {},
627 compactionLoading: {},
628 inlineErrorMessage: undefined,
629 },
630 config: {
631 config: {
632 tools: [],
633 rules: [],
634 tabAutocompleteModel: undefined,
635 selectedModelByRole: {
636 chat: mockClaudeModel,
637 apply: null,
638 edit: null,
639 summarize: null,
640 autocomplete: null,
641 rerank: null,
642 embed: null,
643 },
644 experimental: {
645 onlyUseSystemMessageTools: false,
646 },
647 } as any,
648 lastSelectedModelByRole: {
649 chat: mockClaudeModel.title,
650 },
651 } as any,
652 ui: {
653 toolSettings: {
654 search_codebase: "allowedWithoutPermission", // Auto-approve this tool
655 },
656 ruleSettings: {},
657 showDialog: false,
658 dialogMessage: undefined,
659 } as any,
660 });
661
662 const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger;
663
664 // Setup successful compilation and tool responses
665 mockIdeMessengerWithTool.request.mockImplementation(
666 (endpoint: string, data: any) => {
667 if (endpoint === "llm/compileChat") {
668 return Promise.resolve({
669 status: "success",
670 content: {
671 compiledChatMessages: [
672 { role: "user", content: "Please search the codebase" },
673 ],
674 didPrune: false,
675 contextPercentage: 0.9,
676 },
677 });
678 } else if (endpoint === "tools/evaluatePolicy") {
679 // Mock dynamic policy evaluation - return auto-approve for this test
680 return Promise.resolve({
681 status: "success",
682 content: { policy: "allowedWithoutPermission" },
683 });
684 } else if (endpoint === "tools/call") {
685 // Mock server-side tool call response
686 return Promise.resolve({
687 status: "success",
688 content: {
689 contextItems: [
690 {
691 name: "Search Results",
692 description: "Found 3 matches",
693 content: "Result 1\nResult 2\nResult 3",
694 icon: "search",
695 hidden: false,
696 },
697 ],
698 errorMessage: undefined,
699 },
700 });
701 } else if (endpoint === "history/save") {
702 // Mock session save
703 return Promise.resolve({ status: "success" });
704 } else if (endpoint === "history/list") {
705 return Promise.resolve({ status: "success", content: [] });
706 }
707 // Let other endpoints pass through or return success
708 return Promise.resolve({ status: "success", content: {} });
709 },
710 );
711
712 // Setup streaming generator with tool call
713 async function* mockStreamGeneratorWithTool() {
714 yield [
715 { role: "assistant", content: "I'll search the codebase for you." },
716 ];
717 yield [
718 {
719 role: "assistant",
720 content: "",
721 toolCalls: [
722 {
723 id: "tool-call-1",
724 type: "function",
725 function: {
726 name: "search_codebase",
727 arguments: JSON.stringify({ query: "test function" }),
728 },
729 },
730 ],
731 },
732 ];
733 return {
734 prompt: "Please search the codebase",
735 completion: "I'll search the codebase for you.",
736 modelProvider: "anthropic",
737 };
738 }
739
740 // Mock different streaming responses for multiple calls
741 let streamCallCount = 0;
742 mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => {
743 streamCallCount++;
744 if (streamCallCount === 1) {
745 // First call - main streaming with tool call
746 return mockStreamGeneratorWithTool();
747 } else {
748 // Subsequent calls from streamResponseAfterToolCall - return minimal response
749 async function* simpleGenerator() {
750 yield [{ role: "assistant", content: "Search completed." }];
751 return {
752 prompt: "continuing after tool",
753 completion: "Search completed.",
754 modelProvider: "anthropic",
755 };
756 }
757 return simpleGenerator();
758 }
759 });
760
761 // Execute thunk
762 const result = await mockStoreWithToolSettings.dispatch(
763 streamResponseThunk({
764 editorState: mockEditorState,
765 modifiers: mockModifiers,
766 }) as any,
767 );
768
769 // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist)
770 const dispatchedActions = (mockStoreWithToolSettings as any).getActions();
771
772 // Verify exact action sequence
773 const actionTypes = dispatchedActions.map((action: any) => action.type);
774 expect(actionTypes).toEqual([
775 "chat/streamResponse/pending",
776 "chat/streamWrapper/pending",
777 "session/submitEditorAndInitAtIndex",
778 "session/resetNextCodeBlockToApplyIndex",
779 "symbols/updateFromContextItems/pending",
780 "session/updateHistoryItemAtIndex",
781 "chat/streamNormalInput/pending",
782 "session/setAppliedRulesAtIndex",
783 "session/setActive",
784 "session/setInlineErrorMessage",
785 "session/setIsPruned",
786 "session/setContextPercentage",
787 "symbols/updateFromContextItems/fulfilled",
788 "session/streamUpdate",
789 "session/streamUpdate",
790 "session/addPromptCompletionPair",
791 "session/setToolGenerated",
792 "chat/callTool/pending",
793 "session/setToolCallCalling",
794 "session/updateToolCallOutput",
795 "session/acceptToolCall",
796 "chat/streamAfterToolCall/pending",
797 "chat/streamWrapper/pending",
798 "session/resetNextCodeBlockToApplyIndex",
799 "session/streamUpdate",
800 "chat/streamNormalInput/pending",
801 "session/setAppliedRulesAtIndex",
802 "session/setActive",
803 "session/setInlineErrorMessage",
804 "session/setIsPruned",
805 "session/setContextPercentage",
806 "session/streamUpdate",
807 "session/addPromptCompletionPair",
808 "session/setInactive",
809 "chat/streamNormalInput/fulfilled",
810 "session/saveCurrent/pending",
811 "session/update/pending",
812 "session/updateSessionMetadata",
813 "session/refreshMetadata/pending",
814 "session/setIsSessionMetadataLoading",
815 "session/setAllSessionMetadata",
816 "session/refreshMetadata/fulfilled",
817 "session/update/fulfilled",
818 "session/saveCurrent/fulfilled",
819 "chat/streamWrapper/fulfilled",
820 "chat/streamAfterToolCall/fulfilled",
821 "chat/callTool/fulfilled",
822 "chat/streamNormalInput/fulfilled",
823 "session/saveCurrent/pending",
824 "session/update/pending",
825 "session/updateSessionMetadata",
826 "session/refreshMetadata/pending",
827 "session/setIsSessionMetadataLoading",
828 "session/setAllSessionMetadata",
829 "session/refreshMetadata/fulfilled",
830 "session/update/fulfilled",
831 "session/saveCurrent/fulfilled",
832 "chat/streamWrapper/fulfilled",
833 "chat/streamResponse/fulfilled",
834 ]);
835
836 // Verify key payload data for important actions
837 const setContextPercentageAction = dispatchedActions.find(
838 (a: any) => a.type === "session/setContextPercentage",
839 );
840 expect(setContextPercentageAction.payload).toBe(0.9);
841
842 const streamUpdates = dispatchedActions.filter(
843 (a: any) => a.type === "session/streamUpdate",
844 );
845 expect(streamUpdates[0].payload).toEqual([
846 { role: "assistant", content: "I'll search the codebase for you." },
847 ]);
848 expect(streamUpdates[1].payload).toEqual([
849 {
850 role: "assistant",
851 content: "",
852 toolCalls: [
853 {
854 id: "tool-call-1",
855 type: "function",
856 function: {
857 name: "search_codebase",
858 arguments: JSON.stringify({ query: "test function" }),
859 },
860 },
861 ],
862 },
863 ]);
864
865 const completionPairs = dispatchedActions.filter(
866 (a: any) => a.type === "session/addPromptCompletionPair",
867 );
868 expect(completionPairs[0].payload).toEqual([
869 {
870 completion: "I'll search the codebase for you.",
871 modelProvider: "anthropic",
872 prompt: "Please search the codebase",
873 },
874 ]);
875
876 const toolCallActions = dispatchedActions.filter(
877 (a: any) => a.type === "session/setToolCallCalling",
878 );
879 expect(toolCallActions[0].payload).toEqual({ toolCallId: "tool-call-1" });
880
881 const toolOutputActions = dispatchedActions.filter(
882 (a: any) => a.type === "session/updateToolCallOutput",
883 );
884 expect(toolOutputActions[0].payload).toEqual({
885 toolCallId: "tool-call-1",
886 contextItems: [
887 {
888 name: "Search Results",
889 description: "Found 3 matches",
890 content: "Result 1\nResult 2\nResult 3",
891 icon: "search",
892 hidden: false,
893 },
894 ],
895 });
896
897 // Verify IDE messenger calls
898 expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith(
899 "llm/compileChat",
900 {
901 messages: [
902 {
903 role: "system",
904 content: "You are a helpful assistant.",
905 },
906 {
907 role: "user",
908 content: [
909 {
910 type: "text",
911 text: "Please search the codebase",
912 },
913 ],
914 },
915 {
916 role: "user",
917 content: [
918 {
919 type: "text",
920 text: "Hello, please help me with this code",
921 },
922 ],
923 },
924 ],
925 options: {
926 reasoning: false,
927 },
928 },
929 );
930
931 expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith(
932 "tools/call",
933 {
934 toolCall: {
935 id: "tool-call-1",
936 type: "function",
937 function: {
938 name: "search_codebase",
939 arguments: JSON.stringify({ query: "test function" }),
940 },
941 },
942 },
943 );
944
945 // Verify that multiple compilation calls were made (due to tool call continuation)
946 const compileCallsCount =
947 mockIdeMessengerWithTool.request.mock.calls.filter(
948 (call: any) => call[0] === "llm/compileChat",
949 ).length;
950 expect(compileCallsCount).toBeGreaterThanOrEqual(1);
951
952 expect(result.type).toBe("chat/streamResponse/fulfilled");
953
954 // Verify final state after tool call execution
955 const finalState = mockStoreWithToolSettings.getState();
956 expect(finalState).toEqual({
957 session: {
958 history: [
959 {
960 contextItems: [],
961 message: {
962 id: "1",
963 role: "user",
964 content: "Please search the codebase",
965 },
966 },
967 {
968 appliedRules: [],
969 contextItems: [],
970 editorState: mockEditorState,
971 message: {
972 id: expect.any(String),
973 role: "user",
974 content: "Hello, please help me with this code",
975 },
976 },
977 {
978 contextItems: [],
979 message: {
980 content: "I'll search the codebase for you.",
981 id: expect.any(String),
982 role: "assistant",
983 toolCalls: [
984 {
985 id: "tool-call-1",
986 type: "function",
987 function: {
988 name: "search_codebase",
989 arguments: JSON.stringify({ query: "test function" }),
990 },
991 },
992 ],
993 },
994 promptLogs: [
995 {
996 completion: "I'll search the codebase for you.",
997 modelProvider: "anthropic",
998 prompt: "Please search the codebase",
999 },
1000 ],
1001 toolCallStates: [
1002 {
1003 toolCallId: "tool-call-1",
1004 toolCall: {
1005 id: "tool-call-1",
1006 type: "function",
1007 function: {
1008 name: "search_codebase",
1009 arguments: JSON.stringify({ query: "test function" }),
1010 },
1011 },
1012 parsedArgs: { query: "test function" },
1013 status: "done",
1014 output: [
1015 {
1016 name: "Search Results",
1017 description: "Found 3 matches",
1018 content: "Result 1\nResult 2\nResult 3",
1019 icon: "search",
1020 hidden: false,
1021 },
1022 ],
1023 },
1024 ],
1025 },
1026 {
1027 contextItems: [],
1028 message: {
1029 content: "Result 1\nResult 2\nResult 3",
1030 id: expect.any(String),
1031 role: "tool",
1032 toolCallId: "tool-call-1",
1033 },
1034 },
1035 {
1036 contextItems: [],
1037 isGatheringContext: false,
1038 message: {
1039 content: "Search completed.",
1040 id: "mock-uuid-123",
1041 role: "assistant",
1042 },
1043 promptLogs: [
1044 {
1045 completion: "Search completed.",
1046 modelProvider: "anthropic",
1047 prompt: "continuing after tool",
1048 },
1049 ],
1050 },
1051 ],
1052 hasReasoningEnabled: false,
1053 isStreaming: false,
1054 id: "session-123",
1055 mode: "chat",
1056 streamAborter: expect.any(AbortController),
1057 contextPercentage: 0.9,
1058 isPruned: false,
1059 isInEdit: false,
1060 title: "New Session",
1061 lastSessionId: undefined,
1062 isSessionMetadataLoading: false,
1063 allSessionMetadata: [],
1064 symbols: {},
1065 codeBlockApplyStates: {
1066 states: [],
1067 curIndex: 0,
1068 },
1069 newestToolbarPreviewForInput: {},
1070 compactionLoading: {},
1071 inlineErrorMessage: undefined,
1072 },
1073 config: {
1074 config: {
1075 tools: [],
1076 rules: [],
1077 tabAutocompleteModel: undefined,
1078 selectedModelByRole: {
1079 chat: mockClaudeModel,
1080 apply: null,
1081 edit: null,
1082 summarize: null,
1083 autocomplete: null,
1084 rerank: null,
1085 embed: null,
1086 },
1087 experimental: {
1088 onlyUseSystemMessageTools: false,
1089 },
1090 },
1091 lastSelectedModelByRole: {
1092 chat: mockClaudeModel.title,
1093 },
1094 loading: false,
1095 configError: undefined,
1096 },
1097 ui: {
1098 toolSettings: {
1099 search_codebase: "allowedWithoutPermission",
1100 },
1101 ruleSettings: {},
1102 showDialog: false,
1103 dialogMessage: undefined,
1104 },
1105 editModeState: {
1106 isInEdit: false,
1107 returnToMode: "chat",
1108 },
1109 indexing: {
1110 indexing: {
1111 statuses: {},
1112 hiddenChatPeekTypes: {
1113 docs: false,
1114 },
1115 },
1116 },
1117 tabs: {
1118 tabsItems: [],
1119 },
1120 profiles: {
1121 organizations: [],
1122 selectedProfileId: null,
1123 selectedOrganizationId: null,
1124 preferencesByProfileId: {},
1125 },
1126 });
1127 });
1128
1129 it("should handle streaming abort", async () => {
1130 // Create an AbortController that we'll abort during streaming
1131 const testAbortController = new AbortController();
1132
1133 // Use setupTest to get proper mock configuration
1134 const { mockStore: baseStore, mockIdeMessenger: baseMessenger } =
1135 setupTest();
1136
1137 // Create store with our test abort controller, starting from setupTest config
1138 const mockStoreWithAbort = createMockStore({
1139 session: {
1140 history: [
1141 {
1142 message: { id: "1", role: "user", content: "Hello" },
1143 contextItems: [],
1144 },
1145 ],
1146 hasReasoningEnabled: false,
1147 isStreaming: true,
1148 id: "session-123",
1149 mode: "chat",
1150 streamAborter: testAbortController, // Use our test controller
1151 contextPercentage: 0,
1152 isPruned: false,
1153 isInEdit: false,
1154 title: "",
1155 lastSessionId: undefined,
1156 isSessionMetadataLoading: false,
1157 allSessionMetadata: [],
1158 symbols: {},
1159 codeBlockApplyStates: {
1160 states: [],
1161 curIndex: 0,
1162 },
1163 newestToolbarPreviewForInput: {},
1164 compactionLoading: {},
1165 inlineErrorMessage: undefined,
1166 },
1167 config: {
1168 config: {
1169 tools: [],
1170 rules: [],
1171 tabAutocompleteModel: undefined,
1172 selectedModelByRole: {
1173 chat: mockClaudeModel,
1174 apply: null,
1175 edit: null,
1176 summarize: null,
1177 autocomplete: null,
1178 rerank: null,
1179 embed: null,
1180 },
1181 experimental: {
1182 onlyUseSystemMessageTools: false,
1183 },
1184 } as any,
1185 lastSelectedModelByRole: {
1186 chat: mockClaudeModel.title,
1187 },
1188 } as any,
1189 ui: {
1190 toolSettings: {},
1191 ruleSettings: {},
1192 showDialog: false,
1193 dialogMessage: undefined,
1194 } as any,
1195 });
1196
1197 const mockIdeMessengerAbort = mockStoreWithAbort.mockIdeMessenger;
1198
1199 // Setup successful compilation
1200 mockIdeMessengerAbort.request.mockResolvedValue({
1201 status: "success",
1202 content: {
1203 compiledChatMessages: [{ role: "user", content: "Hello" }],
1204 didPrune: false,
1205 contextPercentage: 0.8,
1206 },
1207 });
1208
1209 // Setup streaming generator that simulates abort by user interaction
1210 async function* mockStreamGeneratorWithAbort() {
1211 yield [{ role: "assistant", content: "First chunk" }];
1212
1213 // Add a delay to allow the first chunk to be processed
1214 await new Promise((resolve) => setTimeout(resolve, 5));
1215
1216 // Simulate user clicking abort button - dispatch setInactive immediately
1217 mockStoreWithAbort.dispatch({ type: "session/setInactive" });
1218
1219 // Add a small delay to let the abort action be processed
1220 await new Promise((resolve) => setTimeout(resolve, 5));
1221
1222 // Try to yield second chunk (should be ignored due to abort)
1223 yield [{ role: "assistant", content: "Second chunk" }];
1224
1225 return {
1226 prompt: "Hello",
1227 completion: "Complete response",
1228 modelProvider: "anthropic",
1229 };
1230 }
1231
1232 mockIdeMessengerAbort.llmStreamChat.mockReturnValue(
1233 mockStreamGeneratorWithAbort(),
1234 );
1235
1236 // Execute thunk - should be aborted
1237 const result = await mockStoreWithAbort.dispatch(
1238 streamResponseThunk({
1239 editorState: mockEditorState,
1240 modifiers: mockModifiers,
1241 }) as any,
1242 );
1243
1244 // Verify thunk completed successfully (abort just stops streaming early)
1245 expect(result.type).toBe("chat/streamResponse/fulfilled");
1246
1247 // Verify exact action sequence - should start but then be aborted
1248 const dispatchedActions = (mockStoreWithAbort as any).getActions();
1249 expect(dispatchedActions).toEqual([
1250 {
1251 type: "chat/streamResponse/pending",
1252 meta: {
1253 arg: {
1254 editorState: mockEditorState,
1255 modifiers: mockModifiers,
1256 },
1257 requestId: expect.any(String),
1258 requestStatus: "pending",
1259 },
1260 payload: undefined,
1261 },
1262 {
1263 type: "chat/streamWrapper/pending",
1264 meta: {
1265 arg: expect.any(Function),
1266 requestId: expect.any(String),
1267 requestStatus: "pending",
1268 },
1269 payload: undefined,
1270 },
1271 {
1272 type: "session/submitEditorAndInitAtIndex",
1273 payload: {
1274 editorState: mockEditorState,
1275 index: 1,
1276 },
1277 },
1278 {
1279 type: "session/resetNextCodeBlockToApplyIndex",
1280 payload: undefined,
1281 },
1282 {
1283 type: "symbols/updateFromContextItems/pending",
1284 meta: {
1285 arg: [],
1286 requestId: expect.any(String),
1287 requestStatus: "pending",
1288 },
1289 payload: undefined,
1290 },
1291 {
1292 type: "session/updateHistoryItemAtIndex",
1293 payload: {
1294 index: 1,
1295 updates: {
1296 contextItems: [],
1297 message: {
1298 content: "Hello, please help me with this code",
1299 id: "mock-uuid-123",
1300 role: "user",
1301 },
1302 },
1303 },
1304 },
1305 {
1306 type: "chat/streamNormalInput/pending",
1307 meta: {
1308 arg: {
1309 legacySlashCommandData: undefined,
1310 },
1311 requestId: expect.any(String),
1312 requestStatus: "pending",
1313 },
1314 payload: undefined,
1315 },
1316 {
1317 type: "session/setAppliedRulesAtIndex",
1318 payload: {
1319 appliedRules: [],
1320 index: 1,
1321 },
1322 },
1323 {
1324 type: "session/setActive",
1325 payload: undefined,
1326 },
1327 {
1328 type: "session/setInlineErrorMessage",
1329 payload: undefined,
1330 },
1331 {
1332 type: "session/setIsPruned",
1333 payload: false,
1334 },
1335 {
1336 type: "session/setContextPercentage",
1337 payload: 0.8,
1338 },
1339 {
1340 type: "symbols/updateFromContextItems/fulfilled",
1341 meta: {
1342 arg: [],
1343 requestId: expect.any(String),
1344 requestStatus: "fulfilled",
1345 },
1346 payload: undefined,
1347 },
1348 {
1349 type: "session/streamUpdate",
1350 payload: [
1351 {
1352 role: "assistant",
1353 content: "First chunk",
1354 },
1355 ],
1356 },
1357 // User abort action (dispatched by the test)
1358 {
1359 type: "session/setInactive",
1360 },
1361 // Stream abort dispatch (called by implementation)
1362 {
1363 type: "session/abortStream",
1364 payload: undefined,
1365 },
1366 // Stream end cleanup
1367 {
1368 type: "session/setInactive",
1369 payload: undefined,
1370 },
1371 {
1372 type: "chat/streamNormalInput/fulfilled",
1373 meta: {
1374 arg: {
1375 legacySlashCommandData: undefined,
1376 },
1377 requestId: expect.any(String),
1378 requestStatus: "fulfilled",
1379 },
1380 payload: undefined,
1381 },
1382 {
1383 type: "session/saveCurrent/pending",
1384 meta: {
1385 arg: {
1386 generateTitle: true,
1387 openNewSession: false,
1388 },
1389 requestId: expect.any(String),
1390 requestStatus: "pending",
1391 },
1392 payload: undefined,
1393 },
1394 {
1395 type: "session/update/pending",
1396 meta: {
1397 arg: expect.objectContaining({
1398 history: expect.any(Array),
1399 sessionId: "session-123",
1400 title: "New Session",
1401 workspaceDirectory: "",
1402 }),
1403 requestId: expect.any(String),
1404 requestStatus: "pending",
1405 },
1406 payload: undefined,
1407 },
1408 {
1409 type: "session/updateSessionMetadata",
1410 payload: {
1411 sessionId: "session-123",
1412 title: "New Session",
1413 },
1414 },
1415 {
1416 type: "session/refreshMetadata/pending",
1417 meta: {
1418 arg: {},
1419 requestId: expect.any(String),
1420 requestStatus: "pending",
1421 },
1422 payload: undefined,
1423 },
1424 {
1425 type: "session/setIsSessionMetadataLoading",
1426 payload: false,
1427 },
1428 {
1429 type: "session/setAllSessionMetadata",
1430 payload: {
1431 compiledChatMessages: [
1432 {
1433 content: "Hello",
1434 role: "user",
1435 },
1436 ],
1437 contextPercentage: 0.8,
1438 didPrune: false,
1439 },
1440 },
1441 {
1442 type: "session/refreshMetadata/fulfilled",
1443 meta: {
1444 arg: {},
1445 requestId: expect.any(String),
1446 requestStatus: "fulfilled",
1447 },
1448 payload: {
1449 compiledChatMessages: [
1450 {
1451 content: "Hello",
1452 role: "user",
1453 },
1454 ],
1455 contextPercentage: 0.8,
1456 didPrune: false,
1457 },
1458 },
1459 {
1460 type: "session/update/fulfilled",
1461 meta: {
1462 arg: expect.objectContaining({
1463 history: expect.any(Array),
1464 sessionId: "session-123",
1465 title: "New Session",
1466 workspaceDirectory: "",
1467 }),
1468 requestId: expect.any(String),
1469 requestStatus: "fulfilled",
1470 },
1471 payload: undefined,
1472 },
1473 {
1474 type: "session/saveCurrent/fulfilled",
1475 meta: {
1476 arg: {
1477 generateTitle: true,
1478 openNewSession: false,
1479 },
1480 requestId: expect.any(String),
1481 requestStatus: "fulfilled",
1482 },
1483 payload: undefined,
1484 },
1485 {
1486 type: "chat/streamWrapper/fulfilled",
1487 meta: {
1488 arg: expect.any(Function),
1489 requestId: expect.any(String),
1490 requestStatus: "fulfilled",
1491 },
1492 payload: undefined,
1493 },
1494 {
1495 type: "chat/streamResponse/fulfilled",
1496 meta: {
1497 arg: {
1498 editorState: mockEditorState,
1499 modifiers: mockModifiers,
1500 },
1501 requestId: expect.any(String),
1502 requestStatus: "fulfilled",
1503 },
1504 payload: undefined,
1505 },
1506 ]);
1507
1508 // Verify IDE messenger calls
1509 expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith(
1510 "llm/compileChat",
1511 {
1512 messages: [
1513 {
1514 role: "system",
1515 content: "You are a helpful assistant.",
1516 },
1517 {
1518 role: "user",
1519 content: [
1520 {
1521 type: "text",
1522 text: "Hello",
1523 },
1524 ],
1525 },
1526 {
1527 role: "user",
1528 content: [
1529 {
1530 type: "text",
1531 text: "Hello, please help me with this code",
1532 },
1533 ],
1534 },
1535 ],
1536 options: {
1537 reasoning: false,
1538 },
1539 },
1540 );
1541
1542 expect(mockIdeMessengerAbort.llmStreamChat).toHaveBeenCalledWith(
1543 {
1544 completionOptions: {
1545 reasoning: false,
1546 },
1547 legacySlashCommandData: undefined,
1548 messageOptions: { precompiled: true },
1549 messages: [
1550 {
1551 role: "user",
1552 content: "Hello",
1553 },
1554 ],
1555 title: "Claude 3.5 Sonnet",
1556 },
1557 expect.any(AbortSignal),
1558 );
1559
1560 // Dev data logging should not occur since streaming was stopped early
1561 expect(mockIdeMessengerAbort.post).not.toHaveBeenCalledWith(
1562 "devdata/log",
1563 expect.anything(),
1564 );
1565
1566 // Verify session save was called despite abort
1567 expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith(
1568 "history/save",
1569 expect.anything(),
1570 );
1571
1572 // Verify final state - streaming should be stopped, partial content preserved
1573 const finalState = mockStoreWithAbort.getState();
1574 expect(finalState).toEqual({
1575 session: {
1576 history: [
1577 {
1578 contextItems: [],
1579 message: { id: "1", role: "user", content: "Hello" },
1580 },
1581 {
1582 appliedRules: [],
1583 contextItems: [],
1584 editorState: mockEditorState,
1585 message: {
1586 content: "Hello, please help me with this code",
1587 id: "mock-uuid-123",
1588 role: "user",
1589 },
1590 },
1591 {
1592 contextItems: [],
1593 isGatheringContext: false,
1594 message: {
1595 content: "First chunk", // Only first chunk before abort
1596 id: "mock-uuid-123",
1597 role: "assistant",
1598 },
1599 // No promptLogs because streaming was stopped before completion
1600 },
1601 ],
1602 hasReasoningEnabled: false,
1603 isStreaming: false, // False because setInactive was called
1604 id: "session-123",
1605 mode: "chat",
1606 streamAborter: expect.any(AbortController), // New controller after abort
1607 contextPercentage: 0.8,
1608 isPruned: false,
1609 isInEdit: false,
1610 title: "New Session",
1611 lastSessionId: undefined,
1612 isSessionMetadataLoading: false,
1613 allSessionMetadata: {
1614 compiledChatMessages: [
1615 {
1616 content: "Hello",
1617 role: "user",
1618 },
1619 ],
1620 contextPercentage: 0.8,
1621 didPrune: false,
1622 },
1623 symbols: {},
1624 codeBlockApplyStates: {
1625 states: [],
1626 curIndex: 0,
1627 },
1628 newestToolbarPreviewForInput: {},
1629 compactionLoading: {},
1630 inlineErrorMessage: undefined,
1631 },
1632 config: {
1633 config: {
1634 tools: [],
1635 rules: [],
1636 tabAutocompleteModel: undefined,
1637 selectedModelByRole: {
1638 chat: mockClaudeModel,
1639 apply: null,
1640 edit: null,
1641 summarize: null,
1642 autocomplete: null,
1643 rerank: null,
1644 embed: null,
1645 },
1646 experimental: {
1647 onlyUseSystemMessageTools: false,
1648 },
1649 },
1650 lastSelectedModelByRole: {
1651 chat: mockClaudeModel.title,
1652 },
1653 loading: false,
1654 configError: undefined,
1655 },
1656 ui: {
1657 toolSettings: {},
1658 ruleSettings: {},
1659 showDialog: false,
1660 dialogMessage: undefined,
1661 },
1662 editModeState: {
1663 isInEdit: false,
1664 returnToMode: "chat",
1665 },
1666 indexing: {
1667 indexing: {
1668 statuses: {},
1669 hiddenChatPeekTypes: {
1670 docs: false,
1671 },
1672 },
1673 },
1674 tabs: {
1675 tabsItems: [],
1676 },
1677 profiles: {
1678 organizations: [],
1679 selectedProfileId: null,
1680 selectedOrganizationId: null,
1681 preferencesByProfileId: {},
1682 },
1683 });
1684 });
1685});