Elffuss BraidHub

kikocis/continue public

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