Elffuss BraidHub

kikocis/continue public

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