Elffuss BraidHub

kikocis/continue public

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