Elffuss BraidHub

kikocis/continue public

cd9781d18fda · 45.0 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 });
440
441 expect(mockIdeMessenger.llmStreamChat).toHaveBeenCalledWith(
442 {
443 completionOptions: {},
444 legacySlashCommandData: undefined,
445 messageOptions: { precompiled: true },
446 messages: [
447 {
448 role: "user",
449 content: "Hello",
450 },
451 ],
452 title: "Claude 3.5 Sonnet",
453 },
454 expect.any(AbortSignal),
455 );
456
457 // Verify dev data logging call
458 expect(mockIdeMessenger.post).toHaveBeenCalledWith("devdata/log", {
459 name: "chatInteraction",
460 data: {
461 prompt: "Hello",
462 completion: "Hi there!",
463 modelProvider: "anthropic",
464 modelName: "Claude 3.5 Sonnet",
465 modelTitle: "Claude 3.5 Sonnet",
466 sessionId: "session-123",
467 },
468 });
469
470 // Verify session save was called
471 expect(mockIdeMessenger.request).toHaveBeenCalledWith(
472 "history/save",
473 expect.anything(),
474 );
475
476 expect(result.type).toBe("chat/streamResponse/fulfilled");
477
478 // Verify final state after thunk completion
479 const finalState = mockStore.getState();
480 expect(finalState).toEqual({
481 session: {
482 history: [
483 {
484 contextItems: [],
485 message: { id: "1", role: "user", content: "Hello" },
486 },
487 {
488 appliedRules: [],
489 contextItems: [],
490 editorState: mockEditorState,
491 message: {
492 content: "Hello, please help me with this code",
493 id: "mock-uuid-123",
494 role: "user",
495 },
496 },
497 {
498 contextItems: [],
499 isGatheringContext: false,
500 message: {
501 content: "First chunkSecond chunk", // Chunks get combined
502 id: "mock-uuid-123",
503 role: "assistant",
504 },
505 promptLogs: [
506 {
507 completion: "Hi there!",
508 modelProvider: "anthropic",
509 prompt: "Hello",
510 },
511 ],
512 },
513 ],
514 hasReasoningEnabled: false,
515 isStreaming: false,
516 id: "session-123",
517 mode: "chat",
518 streamAborter: expect.any(AbortController),
519 contextPercentage: 0.8,
520 isPruned: false,
521 isInEdit: false,
522 title: "New Session",
523 lastSessionId: undefined,
524 isSessionMetadataLoading: false,
525 allSessionMetadata: {},
526 symbols: {},
527 codeBlockApplyStates: {
528 states: [],
529 curIndex: 0,
530 },
531 newestToolbarPreviewForInput: {},
532 compactionLoading: {},
533 inlineErrorMessage: undefined,
534 },
535 config: {
536 config: {
537 tools: [],
538 rules: [],
539 tabAutocompleteModel: undefined,
540 selectedModelByRole: {
541 chat: mockClaudeModel,
542 apply: null,
543 edit: null,
544 summarize: null,
545 autocomplete: null,
546 rerank: null,
547 embed: null,
548 },
549 experimental: {
550 onlyUseSystemMessageTools: false,
551 },
552 },
553 lastSelectedModelByRole: {
554 chat: mockClaudeModel.title,
555 },
556 loading: false,
557 configError: undefined,
558 },
559 ui: {
560 toolSettings: {},
561 ruleSettings: {},
562 showDialog: false,
563 dialogMessage: undefined,
564 },
565 editModeState: {
566 isInEdit: false,
567 returnToMode: "chat",
568 },
569 indexing: {
570 indexing: {
571 statuses: {},
572 hiddenChatPeekTypes: {
573 docs: false,
574 },
575 },
576 },
577 tabs: {
578 tabsItems: [],
579 },
580 profiles: {
581 organizations: [],
582 selectedProfileId: null,
583 selectedOrganizationId: null,
584 preferencesByProfileId: {},
585 },
586 });
587 });
588
589 it("should execute streaming flow with tool call execution", async () => {
590 const { mockStore, mockIdeMessenger } = setupTest();
591
592 // Set up auto-approved tool setting for our test tool
593 const mockStoreWithToolSettings = createMockStore({
594 session: {
595 history: [
596 {
597 message: {
598 id: "1",
599 role: "user",
600 content: "Please search the codebase",
601 },
602 contextItems: [],
603 },
604 ],
605 hasReasoningEnabled: false,
606 isStreaming: true,
607 id: "session-123",
608 mode: "chat",
609 streamAborter: new AbortController(),
610 contextPercentage: 0,
611 isPruned: false,
612 isInEdit: false,
613 title: "",
614 lastSessionId: undefined,
615 isSessionMetadataLoading: false,
616 allSessionMetadata: [],
617 symbols: {},
618 codeBlockApplyStates: {
619 states: [],
620 curIndex: 0,
621 },
622 newestToolbarPreviewForInput: {},
623 compactionLoading: {},
624 inlineErrorMessage: undefined,
625 },
626 config: {
627 config: {
628 tools: [],
629 rules: [],
630 tabAutocompleteModel: undefined,
631 selectedModelByRole: {
632 chat: mockClaudeModel,
633 apply: null,
634 edit: null,
635 summarize: null,
636 autocomplete: null,
637 rerank: null,
638 embed: null,
639 },
640 experimental: {
641 onlyUseSystemMessageTools: false,
642 },
643 } as any,
644 lastSelectedModelByRole: {
645 chat: mockClaudeModel.title,
646 },
647 } as any,
648 ui: {
649 toolSettings: {
650 search_codebase: "allowedWithoutPermission", // Auto-approve this tool
651 },
652 ruleSettings: {},
653 showDialog: false,
654 dialogMessage: undefined,
655 } as any,
656 });
657
658 const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger;
659
660 // Setup successful compilation and tool responses
661 mockIdeMessengerWithTool.request.mockImplementation(
662 (endpoint: string, data: any) => {
663 if (endpoint === "llm/compileChat") {
664 return Promise.resolve({
665 status: "success",
666 content: {
667 compiledChatMessages: [
668 { role: "user", content: "Please search the codebase" },
669 ],
670 didPrune: false,
671 contextPercentage: 0.9,
672 },
673 });
674 } else if (endpoint === "tools/call") {
675 // Mock server-side tool call response
676 return Promise.resolve({
677 status: "success",
678 content: {
679 contextItems: [
680 {
681 name: "Search Results",
682 description: "Found 3 matches",
683 content: "Result 1\nResult 2\nResult 3",
684 icon: "search",
685 hidden: false,
686 },
687 ],
688 errorMessage: undefined,
689 },
690 });
691 } else if (endpoint === "history/save") {
692 // Mock session save
693 return Promise.resolve({ status: "success" });
694 } else if (endpoint === "history/list") {
695 return Promise.resolve({ status: "success", content: [] });
696 }
697 // Let other endpoints pass through or return success
698 return Promise.resolve({ status: "success", content: {} });
699 },
700 );
701
702 // Setup streaming generator with tool call
703 async function* mockStreamGeneratorWithTool() {
704 yield [
705 { role: "assistant", content: "I'll search the codebase for you." },
706 ];
707 yield [
708 {
709 role: "assistant",
710 content: "",
711 toolCalls: [
712 {
713 id: "tool-call-1",
714 type: "function",
715 function: {
716 name: "search_codebase",
717 arguments: JSON.stringify({ query: "test function" }),
718 },
719 },
720 ],
721 },
722 ];
723 return {
724 prompt: "Please search the codebase",
725 completion: "I'll search the codebase for you.",
726 modelProvider: "anthropic",
727 };
728 }
729
730 // Mock different streaming responses for multiple calls
731 let streamCallCount = 0;
732 mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => {
733 streamCallCount++;
734 if (streamCallCount === 1) {
735 // First call - main streaming with tool call
736 return mockStreamGeneratorWithTool();
737 } else {
738 // Subsequent calls from streamResponseAfterToolCall - return minimal response
739 async function* simpleGenerator() {
740 yield [{ role: "assistant", content: "Search completed." }];
741 return {
742 prompt: "continuing after tool",
743 completion: "Search completed.",
744 modelProvider: "anthropic",
745 };
746 }
747 return simpleGenerator();
748 }
749 });
750
751 // Execute thunk
752 const result = await mockStoreWithToolSettings.dispatch(
753 streamResponseThunk({
754 editorState: mockEditorState,
755 modifiers: mockModifiers,
756 }) as any,
757 );
758
759 // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist)
760 const dispatchedActions = (mockStoreWithToolSettings as any).getActions();
761
762 // Verify exact action sequence by comparing action types
763 const actionTypes = dispatchedActions.map((action: any) => action.type);
764 expect(actionTypes).toEqual([
765 "chat/streamResponse/pending",
766 "chat/streamWrapper/pending",
767 "session/submitEditorAndInitAtIndex",
768 "session/resetNextCodeBlockToApplyIndex",
769 "symbols/updateFromContextItems/pending",
770 "session/updateHistoryItemAtIndex",
771 "chat/streamNormalInput/pending",
772 "session/setAppliedRulesAtIndex",
773 "session/setActive",
774 "session/setInlineErrorMessage",
775 "session/setIsPruned",
776 "session/setContextPercentage",
777 "symbols/updateFromContextItems/fulfilled",
778 "session/streamUpdate",
779 "session/streamUpdate",
780 "session/addPromptCompletionPair",
781 "session/setToolGenerated",
782 "chat/callTool/pending",
783 "session/setToolCallCalling",
784 "session/updateToolCallOutput",
785 "session/acceptToolCall",
786 "chat/streamAfterToolCall/pending",
787 "chat/streamWrapper/pending",
788 "session/resetNextCodeBlockToApplyIndex",
789 "session/streamUpdate",
790 "chat/streamNormalInput/pending",
791 "session/setAppliedRulesAtIndex",
792 "session/setActive",
793 "session/setInlineErrorMessage",
794 "session/setIsPruned",
795 "session/setContextPercentage",
796 "session/streamUpdate",
797 "session/addPromptCompletionPair",
798 "session/setInactive",
799 "chat/streamNormalInput/fulfilled",
800 "session/saveCurrent/pending",
801 "session/update/pending",
802 "session/updateSessionMetadata",
803 "session/refreshMetadata/pending",
804 "session/setIsSessionMetadataLoading",
805 "session/setAllSessionMetadata",
806 "session/refreshMetadata/fulfilled",
807 "session/update/fulfilled",
808 "session/saveCurrent/fulfilled",
809 "chat/streamWrapper/fulfilled",
810 "chat/streamAfterToolCall/fulfilled",
811 "chat/callTool/fulfilled",
812 "chat/streamNormalInput/fulfilled",
813 "session/saveCurrent/pending",
814 "session/update/pending",
815 "session/updateSessionMetadata",
816 "session/refreshMetadata/pending",
817 "session/setIsSessionMetadataLoading",
818 "session/setAllSessionMetadata",
819 "session/refreshMetadata/fulfilled",
820 "session/update/fulfilled",
821 "session/saveCurrent/fulfilled",
822 "chat/streamWrapper/fulfilled",
823 "chat/streamResponse/fulfilled",
824 ]);
825
826 // Verify key payload data for important actions
827 const setContextPercentageAction = dispatchedActions.find(
828 (a: any) => a.type === "session/setContextPercentage",
829 );
830 expect(setContextPercentageAction.payload).toBe(0.9);
831
832 const streamUpdates = dispatchedActions.filter(
833 (a: any) => a.type === "session/streamUpdate",
834 );
835 expect(streamUpdates[0].payload).toEqual([
836 { role: "assistant", content: "I'll search the codebase for you." },
837 ]);
838 expect(streamUpdates[1].payload).toEqual([
839 {
840 role: "assistant",
841 content: "",
842 toolCalls: [
843 {
844 id: "tool-call-1",
845 type: "function",
846 function: {
847 name: "search_codebase",
848 arguments: JSON.stringify({ query: "test function" }),
849 },
850 },
851 ],
852 },
853 ]);
854
855 const completionPairs = dispatchedActions.filter(
856 (a: any) => a.type === "session/addPromptCompletionPair",
857 );
858 expect(completionPairs[0].payload).toEqual([
859 {
860 completion: "I'll search the codebase for you.",
861 modelProvider: "anthropic",
862 prompt: "Please search the codebase",
863 },
864 ]);
865
866 const toolCallActions = dispatchedActions.filter(
867 (a: any) => a.type === "session/setToolCallCalling",
868 );
869 expect(toolCallActions[0].payload).toEqual({ toolCallId: "tool-call-1" });
870
871 const toolOutputActions = dispatchedActions.filter(
872 (a: any) => a.type === "session/updateToolCallOutput",
873 );
874 expect(toolOutputActions[0].payload).toEqual({
875 toolCallId: "tool-call-1",
876 contextItems: [
877 {
878 name: "Search Results",
879 description: "Found 3 matches",
880 content: "Result 1\nResult 2\nResult 3",
881 icon: "search",
882 hidden: false,
883 },
884 ],
885 });
886
887 // Verify IDE messenger calls
888 expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith(
889 "llm/compileChat",
890 {
891 messages: [
892 {
893 role: "system",
894 content: "You are a helpful assistant.",
895 },
896 {
897 role: "user",
898 content: [
899 {
900 type: "text",
901 text: "Please search the codebase",
902 },
903 ],
904 },
905 {
906 role: "user",
907 content: [
908 {
909 type: "text",
910 text: "Hello, please help me with this code",
911 },
912 ],
913 },
914 ],
915 options: {},
916 },
917 );
918
919 expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith(
920 "tools/call",
921 {
922 toolCall: {
923 id: "tool-call-1",
924 type: "function",
925 function: {
926 name: "search_codebase",
927 arguments: JSON.stringify({ query: "test function" }),
928 },
929 },
930 },
931 );
932
933 // Verify that multiple compilation calls were made (due to tool call continuation)
934 const compileCallsCount =
935 mockIdeMessengerWithTool.request.mock.calls.filter(
936 (call: any) => call[0] === "llm/compileChat",
937 ).length;
938 expect(compileCallsCount).toBeGreaterThanOrEqual(1);
939
940 expect(result.type).toBe("chat/streamResponse/fulfilled");
941
942 // Verify final state after tool call execution
943 const finalState = mockStoreWithToolSettings.getState();
944 expect(finalState).toEqual({
945 session: {
946 history: [
947 {
948 contextItems: [],
949 message: {
950 id: "1",
951 role: "user",
952 content: "Please search the codebase",
953 },
954 },
955 {
956 appliedRules: [],
957 contextItems: [],
958 editorState: mockEditorState,
959 message: {
960 id: expect.any(String),
961 role: "user",
962 content: "Hello, please help me with this code",
963 },
964 },
965 {
966 contextItems: [],
967 message: {
968 content: "I'll search the codebase for you.",
969 id: expect.any(String),
970 role: "assistant",
971 toolCalls: [
972 {
973 id: "tool-call-1",
974 type: "function",
975 function: {
976 name: "search_codebase",
977 arguments: JSON.stringify({ query: "test function" }),
978 },
979 },
980 ],
981 },
982 promptLogs: [
983 {
984 completion: "I'll search the codebase for you.",
985 modelProvider: "anthropic",
986 prompt: "Please search the codebase",
987 },
988 ],
989 toolCallStates: [
990 {
991 toolCallId: "tool-call-1",
992 toolCall: {
993 id: "tool-call-1",
994 type: "function",
995 function: {
996 name: "search_codebase",
997 arguments: JSON.stringify({ query: "test function" }),
998 },
999 },
1000 parsedArgs: { query: "test function" },
1001 status: "done",
1002 output: [
1003 {
1004 name: "Search Results",
1005 description: "Found 3 matches",
1006 content: "Result 1\nResult 2\nResult 3",
1007 icon: "search",
1008 hidden: false,
1009 },
1010 ],
1011 },
1012 ],
1013 },
1014 {
1015 contextItems: [],
1016 message: {
1017 content: "Result 1\nResult 2\nResult 3",
1018 id: expect.any(String),
1019 role: "tool",
1020 toolCallId: "tool-call-1",
1021 },
1022 },
1023 {
1024 contextItems: [],
1025 isGatheringContext: false,
1026 message: {
1027 content: "Search completed.",
1028 id: "mock-uuid-123",
1029 role: "assistant",
1030 },
1031 promptLogs: [
1032 {
1033 completion: "Search completed.",
1034 modelProvider: "anthropic",
1035 prompt: "continuing after tool",
1036 },
1037 ],
1038 },
1039 ],
1040 hasReasoningEnabled: false,
1041 isStreaming: false,
1042 id: "session-123",
1043 mode: "chat",
1044 streamAborter: expect.any(AbortController),
1045 contextPercentage: 0.9,
1046 isPruned: false,
1047 isInEdit: false,
1048 title: "New Session",
1049 lastSessionId: undefined,
1050 isSessionMetadataLoading: false,
1051 allSessionMetadata: [],
1052 symbols: {},
1053 codeBlockApplyStates: {
1054 states: [],
1055 curIndex: 0,
1056 },
1057 newestToolbarPreviewForInput: {},
1058 compactionLoading: {},
1059 inlineErrorMessage: undefined,
1060 },
1061 config: {
1062 config: {
1063 tools: [],
1064 rules: [],
1065 tabAutocompleteModel: undefined,
1066 selectedModelByRole: {
1067 chat: mockClaudeModel,
1068 apply: null,
1069 edit: null,
1070 summarize: null,
1071 autocomplete: null,
1072 rerank: null,
1073 embed: null,
1074 },
1075 experimental: {
1076 onlyUseSystemMessageTools: false,
1077 },
1078 },
1079 lastSelectedModelByRole: {
1080 chat: mockClaudeModel.title,
1081 },
1082 loading: false,
1083 configError: undefined,
1084 },
1085 ui: {
1086 toolSettings: {
1087 search_codebase: "allowedWithoutPermission",
1088 },
1089 ruleSettings: {},
1090 showDialog: false,
1091 dialogMessage: undefined,
1092 },
1093 editModeState: {
1094 isInEdit: false,
1095 returnToMode: "chat",
1096 },
1097 indexing: {
1098 indexing: {
1099 statuses: {},
1100 hiddenChatPeekTypes: {
1101 docs: false,
1102 },
1103 },
1104 },
1105 tabs: {
1106 tabsItems: [],
1107 },
1108 profiles: {
1109 organizations: [],
1110 selectedProfileId: null,
1111 selectedOrganizationId: null,
1112 preferencesByProfileId: {},
1113 },
1114 });
1115 });
1116
1117 it("should handle streaming abort", async () => {
1118 // Create an AbortController that we'll abort during streaming
1119 const testAbortController = new AbortController();
1120
1121 // Use setupTest to get proper mock configuration
1122 const { mockStore: baseStore, mockIdeMessenger: baseMessenger } =
1123 setupTest();
1124
1125 // Create store with our test abort controller, starting from setupTest config
1126 const mockStoreWithAbort = createMockStore({
1127 session: {
1128 history: [
1129 {
1130 message: { id: "1", role: "user", content: "Hello" },
1131 contextItems: [],
1132 },
1133 ],
1134 hasReasoningEnabled: false,
1135 isStreaming: true,
1136 id: "session-123",
1137 mode: "chat",
1138 streamAborter: testAbortController, // Use our test controller
1139 contextPercentage: 0,
1140 isPruned: false,
1141 isInEdit: false,
1142 title: "",
1143 lastSessionId: undefined,
1144 isSessionMetadataLoading: false,
1145 allSessionMetadata: [],
1146 symbols: {},
1147 codeBlockApplyStates: {
1148 states: [],
1149 curIndex: 0,
1150 },
1151 newestToolbarPreviewForInput: {},
1152 compactionLoading: {},
1153 inlineErrorMessage: undefined,
1154 },
1155 config: {
1156 config: {
1157 tools: [],
1158 rules: [],
1159 tabAutocompleteModel: undefined,
1160 selectedModelByRole: {
1161 chat: mockClaudeModel,
1162 apply: null,
1163 edit: null,
1164 summarize: null,
1165 autocomplete: null,
1166 rerank: null,
1167 embed: null,
1168 },
1169 experimental: {
1170 onlyUseSystemMessageTools: false,
1171 },
1172 } as any,
1173 lastSelectedModelByRole: {
1174 chat: mockClaudeModel.title,
1175 },
1176 } as any,
1177 ui: {
1178 toolSettings: {},
1179 ruleSettings: {},
1180 showDialog: false,
1181 dialogMessage: undefined,
1182 } as any,
1183 });
1184
1185 const mockIdeMessengerAbort = mockStoreWithAbort.mockIdeMessenger;
1186
1187 // Setup successful compilation
1188 mockIdeMessengerAbort.request.mockResolvedValue({
1189 status: "success",
1190 content: {
1191 compiledChatMessages: [{ role: "user", content: "Hello" }],
1192 didPrune: false,
1193 contextPercentage: 0.8,
1194 },
1195 });
1196
1197 // Setup streaming generator that simulates abort by user interaction
1198 async function* mockStreamGeneratorWithAbort() {
1199 yield [{ role: "assistant", content: "First chunk" }];
1200
1201 // Add a delay to allow the first chunk to be processed
1202 await new Promise((resolve) => setTimeout(resolve, 5));
1203
1204 // Simulate user clicking abort button - dispatch setInactive immediately
1205 mockStoreWithAbort.dispatch({ type: "session/setInactive" });
1206
1207 // Add a small delay to let the abort action be processed
1208 await new Promise((resolve) => setTimeout(resolve, 5));
1209
1210 // Try to yield second chunk (should be ignored due to abort)
1211 yield [{ role: "assistant", content: "Second chunk" }];
1212
1213 return {
1214 prompt: "Hello",
1215 completion: "Complete response",
1216 modelProvider: "anthropic",
1217 };
1218 }
1219
1220 mockIdeMessengerAbort.llmStreamChat.mockReturnValue(
1221 mockStreamGeneratorWithAbort(),
1222 );
1223
1224 // Execute thunk - should be aborted
1225 const result = await mockStoreWithAbort.dispatch(
1226 streamResponseThunk({
1227 editorState: mockEditorState,
1228 modifiers: mockModifiers,
1229 }) as any,
1230 );
1231
1232 // Verify thunk completed successfully (abort just stops streaming early)
1233 expect(result.type).toBe("chat/streamResponse/fulfilled");
1234
1235 // Verify exact action sequence - should start but then be aborted
1236 const dispatchedActions = (mockStoreWithAbort as any).getActions();
1237 expect(dispatchedActions).toEqual([
1238 {
1239 type: "chat/streamResponse/pending",
1240 meta: {
1241 arg: {
1242 editorState: mockEditorState,
1243 modifiers: mockModifiers,
1244 },
1245 requestId: expect.any(String),
1246 requestStatus: "pending",
1247 },
1248 payload: undefined,
1249 },
1250 {
1251 type: "chat/streamWrapper/pending",
1252 meta: {
1253 arg: expect.any(Function),
1254 requestId: expect.any(String),
1255 requestStatus: "pending",
1256 },
1257 payload: undefined,
1258 },
1259 {
1260 type: "session/submitEditorAndInitAtIndex",
1261 payload: {
1262 editorState: mockEditorState,
1263 index: 1,
1264 },
1265 },
1266 {
1267 type: "session/resetNextCodeBlockToApplyIndex",
1268 payload: undefined,
1269 },
1270 {
1271 type: "symbols/updateFromContextItems/pending",
1272 meta: {
1273 arg: [],
1274 requestId: expect.any(String),
1275 requestStatus: "pending",
1276 },
1277 payload: undefined,
1278 },
1279 {
1280 type: "session/updateHistoryItemAtIndex",
1281 payload: {
1282 index: 1,
1283 updates: {
1284 contextItems: [],
1285 message: {
1286 content: "Hello, please help me with this code",
1287 id: "mock-uuid-123",
1288 role: "user",
1289 },
1290 },
1291 },
1292 },
1293 {
1294 type: "chat/streamNormalInput/pending",
1295 meta: {
1296 arg: {
1297 legacySlashCommandData: undefined,
1298 },
1299 requestId: expect.any(String),
1300 requestStatus: "pending",
1301 },
1302 payload: undefined,
1303 },
1304 {
1305 type: "session/setAppliedRulesAtIndex",
1306 payload: {
1307 appliedRules: [],
1308 index: 1,
1309 },
1310 },
1311 {
1312 type: "session/setActive",
1313 payload: undefined,
1314 },
1315 {
1316 type: "session/setInlineErrorMessage",
1317 payload: undefined,
1318 },
1319 {
1320 type: "session/setIsPruned",
1321 payload: false,
1322 },
1323 {
1324 type: "session/setContextPercentage",
1325 payload: 0.8,
1326 },
1327 {
1328 type: "symbols/updateFromContextItems/fulfilled",
1329 meta: {
1330 arg: [],
1331 requestId: expect.any(String),
1332 requestStatus: "fulfilled",
1333 },
1334 payload: undefined,
1335 },
1336 {
1337 type: "session/streamUpdate",
1338 payload: [
1339 {
1340 role: "assistant",
1341 content: "First chunk",
1342 },
1343 ],
1344 },
1345 // User abort action (dispatched by the test)
1346 {
1347 type: "session/setInactive",
1348 },
1349 // Stream abort dispatch (called by implementation)
1350 {
1351 type: "session/abortStream",
1352 payload: undefined,
1353 },
1354 // Stream end cleanup
1355 {
1356 type: "session/setInactive",
1357 payload: undefined,
1358 },
1359 {
1360 type: "chat/streamNormalInput/fulfilled",
1361 meta: {
1362 arg: {
1363 legacySlashCommandData: undefined,
1364 },
1365 requestId: expect.any(String),
1366 requestStatus: "fulfilled",
1367 },
1368 payload: undefined,
1369 },
1370 {
1371 type: "session/saveCurrent/pending",
1372 meta: {
1373 arg: {
1374 generateTitle: true,
1375 openNewSession: false,
1376 },
1377 requestId: expect.any(String),
1378 requestStatus: "pending",
1379 },
1380 payload: undefined,
1381 },
1382 {
1383 type: "session/update/pending",
1384 meta: {
1385 arg: expect.objectContaining({
1386 history: expect.any(Array),
1387 sessionId: "session-123",
1388 title: "New Session",
1389 workspaceDirectory: "",
1390 }),
1391 requestId: expect.any(String),
1392 requestStatus: "pending",
1393 },
1394 payload: undefined,
1395 },
1396 {
1397 type: "session/updateSessionMetadata",
1398 payload: {
1399 sessionId: "session-123",
1400 title: "New Session",
1401 },
1402 },
1403 {
1404 type: "session/refreshMetadata/pending",
1405 meta: {
1406 arg: {},
1407 requestId: expect.any(String),
1408 requestStatus: "pending",
1409 },
1410 payload: undefined,
1411 },
1412 {
1413 type: "session/setIsSessionMetadataLoading",
1414 payload: false,
1415 },
1416 {
1417 type: "session/setAllSessionMetadata",
1418 payload: {
1419 compiledChatMessages: [
1420 {
1421 content: "Hello",
1422 role: "user",
1423 },
1424 ],
1425 contextPercentage: 0.8,
1426 didPrune: false,
1427 },
1428 },
1429 {
1430 type: "session/refreshMetadata/fulfilled",
1431 meta: {
1432 arg: {},
1433 requestId: expect.any(String),
1434 requestStatus: "fulfilled",
1435 },
1436 payload: {
1437 compiledChatMessages: [
1438 {
1439 content: "Hello",
1440 role: "user",
1441 },
1442 ],
1443 contextPercentage: 0.8,
1444 didPrune: false,
1445 },
1446 },
1447 {
1448 type: "session/update/fulfilled",
1449 meta: {
1450 arg: expect.objectContaining({
1451 history: expect.any(Array),
1452 sessionId: "session-123",
1453 title: "New Session",
1454 workspaceDirectory: "",
1455 }),
1456 requestId: expect.any(String),
1457 requestStatus: "fulfilled",
1458 },
1459 payload: undefined,
1460 },
1461 {
1462 type: "session/saveCurrent/fulfilled",
1463 meta: {
1464 arg: {
1465 generateTitle: true,
1466 openNewSession: false,
1467 },
1468 requestId: expect.any(String),
1469 requestStatus: "fulfilled",
1470 },
1471 payload: undefined,
1472 },
1473 {
1474 type: "chat/streamWrapper/fulfilled",
1475 meta: {
1476 arg: expect.any(Function),
1477 requestId: expect.any(String),
1478 requestStatus: "fulfilled",
1479 },
1480 payload: undefined,
1481 },
1482 {
1483 type: "chat/streamResponse/fulfilled",
1484 meta: {
1485 arg: {
1486 editorState: mockEditorState,
1487 modifiers: mockModifiers,
1488 },
1489 requestId: expect.any(String),
1490 requestStatus: "fulfilled",
1491 },
1492 payload: undefined,
1493 },
1494 ]);
1495
1496 // Verify IDE messenger calls
1497 expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith(
1498 "llm/compileChat",
1499 {
1500 messages: [
1501 {
1502 role: "system",
1503 content: "You are a helpful assistant.",
1504 },
1505 {
1506 role: "user",
1507 content: [
1508 {
1509 type: "text",
1510 text: "Hello",
1511 },
1512 ],
1513 },
1514 {
1515 role: "user",
1516 content: [
1517 {
1518 type: "text",
1519 text: "Hello, please help me with this code",
1520 },
1521 ],
1522 },
1523 ],
1524 options: {},
1525 },
1526 );
1527
1528 expect(mockIdeMessengerAbort.llmStreamChat).toHaveBeenCalledWith(
1529 {
1530 completionOptions: {},
1531 legacySlashCommandData: undefined,
1532 messageOptions: { precompiled: true },
1533 messages: [
1534 {
1535 role: "user",
1536 content: "Hello",
1537 },
1538 ],
1539 title: "Claude 3.5 Sonnet",
1540 },
1541 expect.any(AbortSignal),
1542 );
1543
1544 // Dev data logging should not occur since streaming was stopped early
1545 expect(mockIdeMessengerAbort.post).not.toHaveBeenCalledWith(
1546 "devdata/log",
1547 expect.anything(),
1548 );
1549
1550 // Verify session save was called despite abort
1551 expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith(
1552 "history/save",
1553 expect.anything(),
1554 );
1555
1556 // Verify final state - streaming should be stopped, partial content preserved
1557 const finalState = mockStoreWithAbort.getState();
1558 expect(finalState).toEqual({
1559 session: {
1560 history: [
1561 {
1562 contextItems: [],
1563 message: { id: "1", role: "user", content: "Hello" },
1564 },
1565 {
1566 appliedRules: [],
1567 contextItems: [],
1568 editorState: mockEditorState,
1569 message: {
1570 content: "Hello, please help me with this code",
1571 id: "mock-uuid-123",
1572 role: "user",
1573 },
1574 },
1575 {
1576 contextItems: [],
1577 isGatheringContext: false,
1578 message: {
1579 content: "First chunk", // Only first chunk before abort
1580 id: "mock-uuid-123",
1581 role: "assistant",
1582 },
1583 // No promptLogs because streaming was stopped before completion
1584 },
1585 ],
1586 hasReasoningEnabled: false,
1587 isStreaming: false, // False because setInactive was called
1588 id: "session-123",
1589 mode: "chat",
1590 streamAborter: expect.any(AbortController), // New controller after abort
1591 contextPercentage: 0.8,
1592 isPruned: false,
1593 isInEdit: false,
1594 title: "New Session",
1595 lastSessionId: undefined,
1596 isSessionMetadataLoading: false,
1597 allSessionMetadata: {
1598 compiledChatMessages: [
1599 {
1600 content: "Hello",
1601 role: "user",
1602 },
1603 ],
1604 contextPercentage: 0.8,
1605 didPrune: false,
1606 },
1607 symbols: {},
1608 codeBlockApplyStates: {
1609 states: [],
1610 curIndex: 0,
1611 },
1612 newestToolbarPreviewForInput: {},
1613 compactionLoading: {},
1614 inlineErrorMessage: undefined,
1615 },
1616 config: {
1617 config: {
1618 tools: [],
1619 rules: [],
1620 tabAutocompleteModel: undefined,
1621 selectedModelByRole: {
1622 chat: mockClaudeModel,
1623 apply: null,
1624 edit: null,
1625 summarize: null,
1626 autocomplete: null,
1627 rerank: null,
1628 embed: null,
1629 },
1630 experimental: {
1631 onlyUseSystemMessageTools: false,
1632 },
1633 },
1634 lastSelectedModelByRole: {
1635 chat: mockClaudeModel.title,
1636 },
1637 loading: false,
1638 configError: undefined,
1639 },
1640 ui: {
1641 toolSettings: {},
1642 ruleSettings: {},
1643 showDialog: false,
1644 dialogMessage: undefined,
1645 },
1646 editModeState: {
1647 isInEdit: false,
1648 returnToMode: "chat",
1649 },
1650 indexing: {
1651 indexing: {
1652 statuses: {},
1653 hiddenChatPeekTypes: {
1654 docs: false,
1655 },
1656 },
1657 },
1658 tabs: {
1659 tabsItems: [],
1660 },
1661 profiles: {
1662 organizations: [],
1663 selectedProfileId: null,
1664 selectedOrganizationId: null,
1665 preferencesByProfileId: {},
1666 },
1667 });
1668 });
1669});