Elffuss BraidHub

kikocis/continue public

main · 20.6 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import { BaseLlmApi } from "@continuedev/openai-adapters";
3import type { ChatHistoryItem } from "core/index.js";
4import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs";
5import { vi } from "vitest";
6
7import { toolPermissionManager } from "../permissions/permissionManager.js";
8import { ToolCall } from "../tools/index.js";
9import { readFileTool } from "../tools/readFile.js";
10import { searchCodeTool } from "../tools/searchCode.js";
11import { PreprocessedToolCall } from "../tools/types.js";
12import { writeFileTool } from "../tools/writeFile.js";
13
14import {
15 executeStreamedToolCalls,
16 preprocessStreamedToolCalls,
17} from "./streamChatResponse.helpers.js";
18import { processStreamingResponse } from "./streamChatResponse.js";
19
20// Test the chunk processing logic that was identified as buggy
21describe("processStreamingResponse - content preservation", () => {
22 // Mock dependencies
23 let mockLlmApi: BaseLlmApi;
24 let mockAbortController: AbortController;
25 let mockModel: ModelConfig;
26 let chunks: ChatCompletionChunk[];
27 let chatHistory: ChatHistoryItem[];
28
29 // Helper to create a content chunk
30 function contentChunk(content: string): ChatCompletionChunk {
31 return {
32 id: "test",
33 object: "chat.completion.chunk",
34 created: Date.now(),
35 model: "test-model",
36 choices: [
37 {
38 index: 0,
39 delta: { content },
40 finish_reason: null,
41 },
42 ],
43 };
44 }
45
46 // Helper to create a tool call chunk
47 function toolCallChunk(
48 id: string,
49 name?: string,
50 args?: string,
51 ): ChatCompletionChunk {
52 return {
53 id: "test",
54 object: "chat.completion.chunk",
55 created: Date.now(),
56 model: "test-model",
57 choices: [
58 {
59 index: 0,
60 delta: {
61 tool_calls: [
62 {
63 index: 0,
64 id,
65 type: "function",
66 function: {
67 name: name || undefined,
68 arguments: args || undefined,
69 },
70 },
71 ],
72 },
73 finish_reason: null,
74 },
75 ],
76 };
77 }
78
79 // Helper to create a tool call chunk with optional ID
80 function toolCallChunkWithIndex(
81 index: number,
82 id?: string,
83 name?: string,
84 args?: string,
85 ): ChatCompletionChunk {
86 const toolCall: any = {
87 index,
88 type: "function" as const,
89 function: {},
90 };
91
92 if (id) toolCall.id = id;
93 if (name) toolCall.function.name = name;
94 if (args !== undefined) toolCall.function.arguments = args;
95
96 return {
97 id: "test",
98 object: "chat.completion.chunk" as const,
99 created: Date.now(),
100 model: "test-model",
101 choices: [
102 {
103 index: 0,
104 delta: { tool_calls: [toolCall] },
105 finish_reason: null,
106 },
107 ],
108 };
109 }
110
111 beforeEach(() => {
112 // Reset chunks for each test
113 chunks = [];
114 chatHistory = [
115 {
116 message: { role: "user", content: "Test prompt" },
117 contextItems: [],
118 },
119 ];
120
121 // Create a mock LLM API that returns our predefined chunks
122 mockLlmApi = {
123 chatCompletionStream: vi.fn().mockImplementation(async function* () {
124 for (const chunk of chunks) {
125 yield chunk;
126 }
127 }),
128 } as unknown as BaseLlmApi;
129
130 // Mock abort controller
131 mockAbortController = {
132 signal: { aborted: false },
133 } as unknown as AbortController;
134
135 // Mock model config
136 mockModel = {
137 model: "test-model",
138 provider: "test-provider",
139 } as unknown as ModelConfig;
140 });
141
142 it("content after tool calls is preserved", async () => {
143 chunks = [
144 contentChunk(""),
145 toolCallChunk("call_123", "Read", '{"filepath": "/README.md"}'),
146 contentChunk(""),
147 contentChunk("I'll read the README file for you."),
148 ];
149
150 const result = await processStreamingResponse({
151 chatHistory,
152 model: mockModel,
153 llmApi: mockLlmApi,
154 abortController: mockAbortController,
155 });
156
157 expect(result.content).toBe("I'll read the README file for you.");
158 expect(result.toolCalls.length).toBe(1);
159
160 // Fixed: finalContent should preserve the content
161 expect(result.finalContent).toBe("I'll read the README file for you.");
162 });
163
164 it("content before tool calls is preserved", async () => {
165 chunks = [
166 contentChunk("Let me search for that. "),
167 toolCallChunk("call_123", "search_code", '{"pattern": "test"}'),
168 ];
169
170 const result = await processStreamingResponse({
171 chatHistory,
172 model: mockModel,
173 llmApi: mockLlmApi,
174 abortController: mockAbortController,
175 });
176
177 expect(result.content).toBe("Let me search for that. ");
178 expect(result.toolCalls.length).toBe(1);
179
180 // Fixed: finalContent preserves content before tool calls
181 expect(result.finalContent).toBe("Let me search for that. ");
182 });
183
184 it("handles the exact problematic sequence from the logs", async () => {
185 chunks = [
186 contentChunk(""),
187 toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", "Read", ""),
188 toolCallChunk(
189 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
190 undefined,
191 '{"filepath',
192 ),
193 toolCallChunk(
194 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
195 undefined,
196 '": "/Use',
197 ),
198 toolCallChunk(
199 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
200 undefined,
201 "rs/nate/gh/c",
202 ),
203 toolCallChunk(
204 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
205 undefined,
206 "ontinuede",
207 ),
208 toolCallChunk(
209 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
210 undefined,
211 "v/cli/README",
212 ),
213 toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'),
214 contentChunk(""),
215 contentChunk("I'll read the README file for you."),
216 ];
217
218 const result = await processStreamingResponse({
219 chatHistory,
220 model: mockModel,
221 llmApi: mockLlmApi,
222 abortController: mockAbortController,
223 });
224
225 expect(result.content).toBe("I'll read the README file for you.");
226 expect(result.toolCalls.length).toBe(1);
227
228 // Fixed: content is preserved
229 expect(result.finalContent).toBe("I'll read the README file for you.");
230
231 // Verify the tool call was assembled correctly
232 expect(result.toolCalls[0].name).toBe("Read");
233 expect(result.toolCalls[0].argumentsStr).toBe(
234 '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
235 );
236 });
237
238 it("shows content works fine without tool calls", async () => {
239 chunks = [contentChunk("Hello "), contentChunk("world!")];
240
241 const result = await processStreamingResponse({
242 chatHistory,
243 model: mockModel,
244 llmApi: mockLlmApi,
245 abortController: mockAbortController,
246 });
247
248 expect(result.content).toBe("Hello world!");
249 expect(result.toolCalls.length).toBe(0);
250
251 // Without tool calls, finalContent is correct
252 expect(result.finalContent).toBe("Hello world!");
253 });
254
255 it("handles provider that only sends tool ID in first chunk then uses index", async () => {
256 chunks = [
257 contentChunk("I'll read the README.md file for you and then say hello!"),
258 // First chunk has ID
259 toolCallChunkWithIndex(
260 0,
261 "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz",
262 "Read",
263 "",
264 ),
265 // Subsequent chunks only have index, no ID
266 toolCallChunkWithIndex(
267 0,
268 undefined,
269 undefined,
270 '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
271 ),
272 ];
273
274 const result = await processStreamingResponse({
275 chatHistory,
276 model: mockModel,
277 llmApi: mockLlmApi,
278 abortController: mockAbortController,
279 });
280
281 // Content is captured correctly
282 expect(result.content).toBe(
283 "I'll read the README.md file for you and then say hello!",
284 );
285 expect(result.toolCalls.length).toBe(1);
286
287 // Fixed: finalContent preserves content
288 expect(result.finalContent).toBe(
289 "I'll read the README.md file for you and then say hello!",
290 );
291
292 // Tool call arguments are preserved using index mapping
293 expect(result.toolCalls[0].name).toBe("Read");
294 expect(result.toolCalls[0].argumentsStr).toBe(
295 '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
296 );
297 });
298
299 it("handles realistic fragmented arguments from index-based provider", async () => {
300 // Simulate the exact sequence from the user's logs with fragmented JSON
301 chunks = [
302 contentChunk("I'll read the README.md file for you and then say hello!"),
303 // First chunk has ID
304 toolCallChunkWithIndex(
305 0,
306 "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz",
307 "Read",
308 "",
309 ),
310 // Subsequent chunks fragment the JSON arguments
311 toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'),
312 toolCallChunkWithIndex(0, undefined, undefined, 'th"'),
313 toolCallChunkWithIndex(0, undefined, undefined, ": "),
314 toolCallChunkWithIndex(0, undefined, undefined, '"/U'),
315 toolCallChunkWithIndex(0, undefined, undefined, "sers/nate/gh"),
316 toolCallChunkWithIndex(0, undefined, undefined, "/c"),
317 toolCallChunkWithIndex(0, undefined, undefined, "onti"),
318 toolCallChunkWithIndex(0, undefined, undefined, "nuedev/cli"),
319 toolCallChunkWithIndex(0, undefined, undefined, "/READ"),
320 toolCallChunkWithIndex(0, undefined, undefined, "ME.m"),
321 toolCallChunkWithIndex(0, undefined, undefined, 'd"}'),
322 ];
323
324 const result = await processStreamingResponse({
325 chatHistory,
326 model: mockModel,
327 llmApi: mockLlmApi,
328 abortController: mockAbortController,
329 });
330
331 // Fixed: Both issues are resolved
332 // 1. Content is preserved
333 expect(result.finalContent).toBe(
334 "I'll read the README.md file for you and then say hello!",
335 );
336
337 // 2. Tool call arguments are assembled correctly
338 expect(result.toolCalls[0].name).toBe("Read");
339 expect(result.toolCalls[0].argumentsStr).toBe(
340 '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
341 );
342 });
343
344 it("handles malformed chunk with empty choices array without crashing", async () => {
345 // This reproduces the exact bug from the logs:
346 // {"chunk":{"choices":[],"usage":{"completion_tokens":96,"prompt_tokens":711,"total_tokens":807,"prompt_tokens_details":{"cached_tokens":3353}},"created":1754927672408,"id":"","model":"claude-sonnet-4-20250514","object":"chat.completion.chunk"}}
347 const malformedChunk: ChatCompletionChunk = {
348 id: "",
349 object: "chat.completion.chunk",
350 created: 1754927672408,
351 model: "claude-sonnet-4-20250514",
352 choices: [], // Empty choices array - this causes the bug
353 usage: {
354 completion_tokens: 96,
355 prompt_tokens: 711,
356 total_tokens: 807,
357 prompt_tokens_details: {
358 cached_tokens: 3353,
359 },
360 },
361 };
362
363 chunks = [
364 malformedChunk, // Put malformed chunk first to trigger the bug more clearly
365 contentChunk("Hello "),
366 contentChunk("world!"),
367 ];
368
369 // This should not throw an error: "Cannot read properties of undefined (reading 'delta')"
370 let caughtError: any = null;
371 try {
372 await processStreamingResponse({
373 chatHistory,
374 model: mockModel,
375 llmApi: mockLlmApi,
376 abortController: mockAbortController,
377 });
378 } catch (error) {
379 caughtError = error;
380 }
381
382 // Should NOT throw error about reading 'delta' property
383 expect(caughtError).toBeNull();
384
385 const result = await processStreamingResponse({
386 chatHistory,
387 model: mockModel,
388 llmApi: mockLlmApi,
389 abortController: mockAbortController,
390 });
391
392 expect(result.content).toBe("Hello world!");
393 expect(result.toolCalls.length).toBe(0);
394 expect(result.finalContent).toBe("Hello world!");
395 });
396});
397
398// Tests for preprocessStreamedToolCalls function
399describe.skip("preprocessStreamedToolCalls", () => {
400 // Mock dependencies
401 beforeEach(async () => {
402 // Mock setup would go here but is currently causing issues
403 });
404
405 afterEach(() => {
406 vi.restoreAllMocks();
407 });
408
409 it("preprocesses valid tool calls correctly", async () => {
410 const toolCalls: ToolCall[] = [
411 {
412 id: "call_123",
413 name: "Read",
414 arguments: { filepath: "/path/to/file.txt" },
415 argumentsStr: '{"filepath": "/path/to/file.txt"}',
416 startNotified: false,
417 },
418 ];
419
420 const callbacks = {
421 onToolStart: vi.fn(),
422 onToolError: vi.fn(),
423 };
424
425 const { preprocessedCalls, errorChatEntries } =
426 await preprocessStreamedToolCalls(toolCalls, callbacks);
427
428 // Should have one preprocessed call and no errors
429 expect(preprocessedCalls).toHaveLength(1);
430 expect(errorChatEntries).toHaveLength(0);
431 expect(preprocessedCalls[0].name).toBe("Read");
432 expect(preprocessedCalls[0].tool).toBeDefined();
433 expect(preprocessedCalls[0].preprocessResult).toBeDefined();
434
435 // Callbacks should not be called for successful preprocessing
436 expect(callbacks.onToolStart).not.toHaveBeenCalled();
437 expect(callbacks.onToolError).not.toHaveBeenCalled();
438 });
439
440 it("handles tool preprocessing errors correctly", async () => {
441 // Set the spy to throw an error
442 const toolsModule = await import("../tools/index.js");
443 vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce(
444 () => {
445 throw new Error("Missing required argument");
446 },
447 );
448
449 const toolCalls: ToolCall[] = [
450 {
451 id: "call_456",
452 name: "Read",
453 arguments: {}, // Missing required filepath
454 argumentsStr: "{}",
455 startNotified: false,
456 },
457 ];
458
459 const callbacks = {
460 onToolStart: vi.fn(),
461 onToolError: vi.fn(),
462 };
463
464 const { preprocessedCalls, errorChatEntries } =
465 await preprocessStreamedToolCalls(toolCalls, callbacks);
466
467 // Should have no preprocessed calls and one error
468 expect(preprocessedCalls).toHaveLength(0);
469 expect(errorChatEntries).toHaveLength(1);
470 expect(errorChatEntries[0].content).toContain("Missing required argument");
471
472 // Callbacks should be called for errors
473 expect(callbacks.onToolStart).toHaveBeenCalledWith("Read", {});
474 expect(callbacks.onToolError).toHaveBeenCalledWith(
475 expect.stringContaining("Missing required argument"),
476 "Read",
477 );
478 });
479
480 it("handles tool not found errors", async () => {
481 const toolCalls: ToolCall[] = [
482 {
483 id: "call_789",
484 name: "nonexistent_tool",
485 arguments: { some: "arg" },
486 argumentsStr: '{"some": "arg"}',
487 startNotified: false,
488 },
489 ];
490
491 const { preprocessedCalls, errorChatEntries } =
492 await preprocessStreamedToolCalls(toolCalls);
493
494 // Should have no preprocessed calls and one error
495 expect(preprocessedCalls).toHaveLength(0);
496 expect(errorChatEntries).toHaveLength(1);
497 expect(errorChatEntries[0].content).toContain(
498 "Tool nonexistent_tool not found",
499 );
500 });
501});
502
503// Tests for executeStreamedToolCalls function
504describe.skip("executeStreamedToolCalls", () => {
505 beforeEach(() => {
506 // Reset spies
507 vi.spyOn(toolPermissionManager, "requestPermission").mockReset();
508 vi.spyOn(toolPermissionManager, "on").mockReset();
509 vi.spyOn(toolPermissionManager, "off").mockReset();
510 });
511
512 it("executes tool calls with allowed permissions", async () => {
513 // Setup spies instead of mocks
514 const permissionsModule = await import("../permissions/index.js");
515 vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
516 permission: "allow",
517 });
518
519 const toolsModule = await import("../tools/index.js");
520 const mockedExecuteToolCall = vi
521 .spyOn(toolsModule, "executeToolCall")
522 .mockResolvedValue("Tool execution successful");
523
524 // Create preprocessed tool call
525 const preprocessedCalls: PreprocessedToolCall[] = [
526 {
527 id: "call_123",
528 name: "Read",
529 arguments: { filepath: "/test.txt" },
530 argumentsStr: '{"filepath": "/test.txt"}',
531 startNotified: false,
532 tool: readFileTool,
533 },
534 ];
535
536 const callbacks = {
537 onToolStart: vi.fn(),
538 onToolResult: vi.fn(),
539 onToolError: vi.fn(),
540 };
541
542 const { chatHistoryEntries } = await executeStreamedToolCalls(
543 preprocessedCalls,
544 callbacks,
545 );
546
547 // Verify results
548 expect(chatHistoryEntries).toHaveLength(1);
549 expect(chatHistoryEntries[0].content).toBe("Tool execution successful");
550 expect(callbacks.onToolStart).toHaveBeenCalledWith("read_file", {
551 filepath: "/test.txt",
552 });
553 expect(callbacks.onToolResult).toHaveBeenCalledWith(
554 "Tool execution successful",
555 "Read",
556 "done",
557 );
558 expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]);
559 });
560
561 it("handles permission denied correctly", async () => {
562 // Setup permission to ask
563 const permissionsModule = await import("../permissions/index.js");
564 vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
565 permission: "ask",
566 });
567
568 // Spy on permission request to be denied
569 vi.spyOn(toolPermissionManager, "requestPermission").mockResolvedValue({
570 approved: false,
571 });
572
573 // Add event listener mock
574 vi.spyOn(toolPermissionManager, "on").mockImplementation(
575 (event: any, callback: any) => {
576 if (event === "permissionRequested") {
577 // Immediately trigger the callback to simulate event
578 callback({
579 requestId: "req_123",
580 toolCall: {
581 name: "Write",
582 arguments: {
583 filepath: "/test.txt",
584 content: "data",
585 },
586 },
587 });
588 }
589 return toolPermissionManager;
590 },
591 );
592
593 // Create preprocessed tool call
594 const preprocessedCalls: PreprocessedToolCall[] = [
595 {
596 id: "call_456",
597 name: "Write",
598 arguments: { filepath: "/test.txt", content: "data" },
599 argumentsStr: '{"filepath": "/test.txt", "content": "data"}',
600 startNotified: false,
601 tool: writeFileTool,
602 },
603 {
604 id: "call_457",
605 name: "Write",
606 arguments: { filepath: "/test.txt", content: "data" },
607 argumentsStr: '{"filepath": "/test.txt", "content": "data"}',
608 startNotified: false,
609 tool: writeFileTool,
610 },
611 ];
612
613 const callbacks = {
614 onToolStart: vi.fn(),
615 onToolResult: vi.fn(),
616 onToolPermissionRequest: vi.fn(),
617 };
618
619 const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls(
620 preprocessedCalls,
621 callbacks,
622 );
623
624 // Verify results
625 expect(hasRejection).toEqual(true);
626 expect(chatHistoryEntries).toHaveLength(2);
627 expect(chatHistoryEntries[0].content).toBe("Permission denied by user");
628 expect(chatHistoryEntries[1].content).toBe(
629 "Cancelled due to previous tool rejection",
630 );
631 expect(callbacks.onToolStart).toHaveBeenCalledWith("Write", {
632 filepath: "/test.txt",
633 content: "data",
634 });
635 expect(callbacks.onToolResult).toHaveBeenCalledWith(
636 "Permission denied by user",
637 "Write",
638 "canceled",
639 );
640 expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith(
641 "Write",
642 { filepath: "/test.txt", content: "data" },
643 "req_123",
644 undefined,
645 );
646 });
647
648 it("handles tool execution errors", async () => {
649 // Setup spies
650 const permissionsModule = await import("../permissions/index.js");
651 vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
652 permission: "allow",
653 });
654
655 const toolsModule = await import("../tools/index.js");
656 vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue(
657 new Error("Execution failed"),
658 );
659
660 // Create preprocessed tool call
661 const preprocessedCalls: PreprocessedToolCall[] = [
662 {
663 id: "call_789",
664 name: "search_code",
665 arguments: { pattern: "test" },
666 argumentsStr: '{"pattern": "test"}',
667 startNotified: false,
668 tool: searchCodeTool,
669 },
670 ];
671
672 const callbacks = {
673 onToolStart: vi.fn(),
674 onToolError: vi.fn(),
675 };
676
677 const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls(
678 preprocessedCalls,
679 callbacks,
680 );
681
682 // Verify results
683 expect(chatHistoryEntries).toHaveLength(1);
684 expect(chatHistoryEntries[0].content).toContain(
685 "Error executing tool search_code",
686 );
687 expect(chatHistoryEntries[0].content).toContain("Execution failed");
688 expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", {
689 pattern: "test",
690 });
691 expect(callbacks.onToolError).toHaveBeenCalledWith(
692 expect.stringContaining(
693 "Error executing tool search_code: Execution failed",
694 ),
695 "search_code",
696 );
697 });
698});