Elffuss BraidHub

kikocis/continue public

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