Elffuss BraidHub

kikocis/continue public

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