Elffuss BraidHub

kikocis/continue public

7dd3a742e7cd · 21.7 KiBRawPermalink
1import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
2import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
3import { resolveRelativePathInDir } from "core/util/ideUtils";
4import { beforeEach, describe, expect, it, vi } from "vitest";
5import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
6import { ClientToolExtras } from "./callClientTool";
7import { searchReplaceToolImpl } from "./searchReplaceImpl";
8
9// Mock the dependencies
10vi.mock("core/edit/searchAndReplace/findSearchMatch");
11vi.mock("core/edit/searchAndReplace/parseSearchReplaceBlock");
12vi.mock("core/util/ideUtils");
13vi.mock("uuid", () => ({
14 v4: vi.fn(() => "test-stream-id"),
15}));
16vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({
17 applyForEditTool: vi.fn(),
18}));
19
20const mockFindSearchMatch = vi.mocked(findSearchMatch);
21const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks);
22const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir);
23const mockApplyForEditTool = vi.mocked(applyForEditTool);
24
25describe("searchReplaceToolImpl", () => {
26 let mockExtras: ClientToolExtras;
27 let mockIdeMessenger: any;
28
29 beforeEach(() => {
30 // Reset all mocks
31 vi.clearAllMocks();
32
33 // Create mock IDE messenger
34 mockIdeMessenger = {
35 ide: {
36 readFile: vi.fn(),
37 },
38 request: vi.fn(),
39 };
40
41 // Create mock extras
42 mockExtras = {
43 ideMessenger: mockIdeMessenger,
44 getState: vi.fn<any>(() => ({
45 config: {
46 config: {
47 allowAnonymousTelemetry: false,
48 },
49 },
50 })),
51 dispatch: vi.fn(),
52 };
53 });
54
55 describe("basic validation", () => {
56 it("should throw error when file does not exist", async () => {
57 mockResolveRelativePathInDir.mockResolvedValue(undefined);
58
59 await expect(
60 searchReplaceToolImpl(
61 { filepath: "nonexistent.txt", diffs: ["some diff"] },
62 "tool-call-id",
63 mockExtras,
64 ),
65 ).rejects.toThrow("File nonexistent.txt does not exist");
66 });
67
68 it("should throw error when no search/replace blocks found in first diff", async () => {
69 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
70 mockParseAllSearchReplaceBlocks.mockReturnValue([]);
71
72 await expect(
73 searchReplaceToolImpl(
74 { filepath: "test.txt", diffs: ["invalid diff content"] },
75 "tool-call-id",
76 mockExtras,
77 ),
78 ).rejects.toThrow("No complete search/replace blocks found in diff 1");
79 });
80
81 it("should throw error when no search/replace blocks found in second diff", async () => {
82 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
83 mockParseAllSearchReplaceBlocks
84 .mockReturnValueOnce([
85 {
86 isComplete: true,
87 searchContent: "valid content",
88 replaceContent: "replacement",
89 },
90 ])
91 .mockReturnValueOnce([]);
92
93 await expect(
94 searchReplaceToolImpl(
95 {
96 filepath: "test.txt",
97 diffs: ["valid diff", "invalid diff content"],
98 },
99 "tool-call-id",
100 mockExtras,
101 ),
102 ).rejects.toThrow("No complete search/replace blocks found in diff 2");
103 });
104
105 it("should throw error when all diffs are empty", async () => {
106 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
107 mockParseAllSearchReplaceBlocks.mockReturnValue([]);
108
109 await expect(
110 searchReplaceToolImpl(
111 { filepath: "test.txt", diffs: [] },
112 "tool-call-id",
113 mockExtras,
114 ),
115 ).rejects.toThrow("No complete search/replace blocks found in any diffs");
116 });
117 });
118
119 describe("single block replacement", () => {
120 it("should successfully apply single search/replace block", async () => {
121 const originalContent = `function hello() {
122 console.log("Hello");
123 return "world";
124}`;
125
126 const expectedFinalContent = `function hello() {
127 console.log("Hi there!");
128 return "world";
129}`;
130
131 // Setup mocks
132 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
133 mockParseAllSearchReplaceBlocks.mockReturnValue([
134 {
135 isComplete: true,
136 searchContent: 'console.log("Hello");',
137 replaceContent: 'console.log("Hi there!");',
138 },
139 ]);
140 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
141
142 // Calculate correct positions for 'console.log("Hello");' in the original content
143 const searchText = 'console.log("Hello");';
144 const startIndex = originalContent.indexOf(searchText);
145 const endIndex = startIndex + searchText.length;
146
147 mockFindSearchMatch.mockReturnValue({
148 startIndex,
149 endIndex,
150 strategyName: "exactMatch",
151 });
152 const result = await searchReplaceToolImpl(
153 { filepath: "test.js", diffs: ["mock diff content"] },
154 "tool-call-id",
155 mockExtras,
156 );
157
158 // Verify the result
159 expect(result).toEqual({
160 respondImmediately: false,
161 output: undefined,
162 });
163
164 // Verify applyToFile was called with correct parameters
165 expect(mockApplyForEditTool).toHaveBeenCalledWith({
166 text: expectedFinalContent,
167 streamId: "test-stream-id",
168 filepath: "/resolved/path/test.js",
169 toolCallId: "tool-call-id",
170 isSearchAndReplace: true,
171 });
172 });
173 });
174
175 describe("single diff scenarios", () => {
176 it("should successfully apply single diff with single search/replace block", async () => {
177 const originalContent = `function hello() {
178 console.log("Hello");
179 return "world";
180}`;
181
182 const expectedFinalContent = `function hello() {
183 console.log("Hi there!");
184 return "world";
185}`;
186
187 // Setup mocks
188 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
189 mockParseAllSearchReplaceBlocks.mockReturnValue([
190 {
191 isComplete: true,
192 searchContent: 'console.log("Hello");',
193 replaceContent: 'console.log("Hi there!");',
194 },
195 ]);
196 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
197
198 // Calculate correct positions for 'console.log("Hello");' in the original content
199 const searchText = 'console.log("Hello");';
200 const startIndex = originalContent.indexOf(searchText);
201 const endIndex = startIndex + searchText.length;
202
203 mockFindSearchMatch.mockReturnValue({
204 startIndex,
205 endIndex,
206 strategyName: "exactMatch",
207 });
208 const result = await searchReplaceToolImpl(
209 { filepath: "test.js", diffs: ["mock diff content"] },
210 "tool-call-id",
211 mockExtras,
212 );
213
214 // Verify the result
215 expect(result).toEqual({
216 respondImmediately: false,
217 output: undefined,
218 });
219
220 // Verify applyToFile was called with correct parameters
221 expect(mockApplyForEditTool).toHaveBeenCalledWith({
222 text: expectedFinalContent,
223 streamId: "test-stream-id",
224 filepath: "/resolved/path/test.js",
225 toolCallId: "tool-call-id",
226 isSearchAndReplace: true,
227 });
228 });
229 });
230
231 describe("multiple block replacement", () => {
232 it("should successfully apply multiple search/replace blocks sequentially", async () => {
233 const originalContent = `const a = 1;
234const b = 2;
235const c = 3;`;
236
237 const expectedFinalContent = `const a = 100;
238const b = 200;
239const c = 3;`;
240
241 // Setup mocks
242 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
243 mockParseAllSearchReplaceBlocks.mockReturnValue([
244 {
245 isComplete: true,
246 searchContent: "const a = 1;",
247 replaceContent: "const a = 100;",
248 },
249 {
250 isComplete: true,
251 searchContent: "const b = 2;",
252 replaceContent: "const b = 200;",
253 },
254 ]);
255 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
256
257 // Calculate positions for sequential replacements
258 const firstSearchText = "const a = 1;";
259 const secondSearchText = "const b = 2;";
260
261 const firstStartIndex = originalContent.indexOf(firstSearchText);
262 const firstEndIndex = firstStartIndex + firstSearchText.length;
263
264 // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;"
265 const contentAfterFirstReplacement =
266 originalContent.substring(0, firstStartIndex) +
267 "const a = 100;" +
268 originalContent.substring(firstEndIndex);
269
270 const secondStartIndex =
271 contentAfterFirstReplacement.indexOf(secondSearchText);
272 const secondEndIndex = secondStartIndex + secondSearchText.length;
273
274 // Mock sequential search matches
275 mockFindSearchMatch
276 .mockReturnValueOnce({
277 startIndex: firstStartIndex,
278 endIndex: firstEndIndex,
279 strategyName: "exactMatch",
280 })
281 .mockReturnValueOnce({
282 startIndex: secondStartIndex,
283 endIndex: secondEndIndex,
284 strategyName: "exactMatch",
285 });
286
287 const result = await searchReplaceToolImpl(
288 { filepath: "test.js", diffs: ["mock diff content"] },
289 "tool-call-id",
290 mockExtras,
291 );
292
293 // Verify the result
294 expect(result).toEqual({
295 respondImmediately: false,
296 output: undefined,
297 });
298
299 // Verify findSearchMatch was called twice with updated content
300 expect(mockFindSearchMatch).toHaveBeenCalledTimes(2);
301 expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
302 1,
303 originalContent,
304 "const a = 1;",
305 );
306 expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
307 2,
308 contentAfterFirstReplacement,
309 "const b = 2;",
310 );
311 // Verify final applyToFile call
312 expect(mockApplyForEditTool).toHaveBeenCalledWith({
313 text: expectedFinalContent,
314 streamId: "test-stream-id",
315 filepath: "/resolved/path/test.js",
316 toolCallId: "tool-call-id",
317 isSearchAndReplace: true,
318 });
319 });
320 });
321
322 describe("multiple diff scenarios", () => {
323 it("should successfully apply multiple diffs each with single search/replace block", async () => {
324 const originalContent = `const a = 1;
325const b = 2;
326const c = 3;`;
327
328 const expectedFinalContent = `const a = 100;
329const b = 200;
330const c = 3;`;
331
332 // Setup mocks - each diff returns one block
333 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
334 mockParseAllSearchReplaceBlocks
335 .mockReturnValueOnce([
336 {
337 isComplete: true,
338 searchContent: "const a = 1;",
339 replaceContent: "const a = 100;",
340 },
341 ])
342 .mockReturnValueOnce([
343 {
344 isComplete: true,
345 searchContent: "const b = 2;",
346 replaceContent: "const b = 200;",
347 },
348 ]);
349 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
350
351 // Calculate positions for sequential replacements
352 const firstSearchText = "const a = 1;";
353 const secondSearchText = "const b = 2;";
354
355 const firstStartIndex = originalContent.indexOf(firstSearchText);
356 const firstEndIndex = firstStartIndex + firstSearchText.length;
357
358 // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;"
359 const contentAfterFirstReplacement =
360 originalContent.substring(0, firstStartIndex) +
361 "const a = 100;" +
362 originalContent.substring(firstEndIndex);
363
364 const secondStartIndex =
365 contentAfterFirstReplacement.indexOf(secondSearchText);
366 const secondEndIndex = secondStartIndex + secondSearchText.length;
367
368 // Mock sequential search matches
369 mockFindSearchMatch
370 .mockReturnValueOnce({
371 startIndex: firstStartIndex,
372 endIndex: firstEndIndex,
373 strategyName: "exactMatch",
374 })
375 .mockReturnValueOnce({
376 startIndex: secondStartIndex,
377 endIndex: secondEndIndex,
378 strategyName: "exactMatch",
379 });
380
381 const result = await searchReplaceToolImpl(
382 { filepath: "test.js", diffs: ["first diff", "second diff"] },
383 "tool-call-id",
384 mockExtras,
385 );
386
387 // Verify the result
388 expect(result).toEqual({
389 respondImmediately: false,
390 output: undefined,
391 });
392
393 // Verify parseAllSearchReplaceBlocks was called for each diff
394 expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledTimes(2);
395 expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith(
396 1,
397 "first diff",
398 );
399 expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith(
400 2,
401 "second diff",
402 );
403
404 // Verify final applyToFile call
405 expect(mockApplyForEditTool).toHaveBeenCalledWith({
406 text: expectedFinalContent,
407 streamId: "test-stream-id",
408 filepath: "/resolved/path/test.js",
409 toolCallId: "tool-call-id",
410 isSearchAndReplace: true,
411 });
412 });
413 });
414
415 describe("deletion scenarios", () => {
416 it("should handle empty replacement (deletion)", async () => {
417 const originalContent = `keep this
418remove this line
419keep this too`;
420
421 const expectedFinalContent = `keep this
422
423keep this too`;
424
425 // Setup mocks
426 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
427 mockParseAllSearchReplaceBlocks.mockReturnValue([
428 {
429 isComplete: true,
430 searchContent: "remove this line",
431 replaceContent: "",
432 },
433 ]);
434 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
435 mockFindSearchMatch.mockReturnValue({
436 startIndex: 10, // Position of "remove this line"
437 endIndex: 26, // End of "remove this line"
438 strategyName: "exactMatch",
439 });
440
441 const result = await searchReplaceToolImpl(
442 { filepath: "test.txt", diffs: ["mock diff content"] },
443 "tool-call-id",
444 mockExtras,
445 );
446
447 expect(result).toEqual({
448 respondImmediately: false,
449 output: undefined,
450 });
451
452 expect(mockApplyForEditTool).toHaveBeenCalledWith({
453 text: expectedFinalContent,
454 streamId: "test-stream-id",
455 filepath: "/resolved/path/test.txt",
456 toolCallId: "tool-call-id",
457 isSearchAndReplace: true,
458 });
459 });
460
461 it("should handle undefined replaceContent as empty string", async () => {
462 const originalContent = "line1\nline2\nline3";
463 const expectedFinalContent = "line1\n\nline3";
464
465 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
466 mockParseAllSearchReplaceBlocks.mockReturnValue([
467 {
468 isComplete: true,
469 searchContent: "line2",
470 replaceContent: undefined, // undefined should be treated as empty string
471 },
472 ]);
473 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
474 mockFindSearchMatch.mockReturnValue({
475 startIndex: 6,
476 endIndex: 11,
477 strategyName: "exactMatch",
478 });
479 await searchReplaceToolImpl(
480 { filepath: "test.txt", diffs: ["mock diff content"] },
481 "tool-call-id",
482 mockExtras,
483 );
484
485 expect(mockApplyForEditTool).toHaveBeenCalledWith({
486 text: expectedFinalContent,
487 streamId: "test-stream-id",
488 filepath: "/resolved/path/test.txt",
489 toolCallId: "tool-call-id",
490 isSearchAndReplace: true,
491 });
492 });
493 });
494
495 describe("error handling", () => {
496 it("should throw error when search content is not found", async () => {
497 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
498 mockParseAllSearchReplaceBlocks.mockReturnValue([
499 {
500 isComplete: true,
501 searchContent: "nonexistent content",
502 replaceContent: "replacement",
503 },
504 ]);
505 mockIdeMessenger.ide.readFile.mockResolvedValue("some file content");
506 mockFindSearchMatch.mockReturnValue(null); // Search content not found
507
508 await expect(
509 searchReplaceToolImpl(
510 { filepath: "test.txt", diffs: ["mock diff content"] },
511 "tool-call-id",
512 mockExtras,
513 ),
514 ).rejects.toThrow(
515 "Search content not found in block 1:\nnonexistent content",
516 );
517 });
518
519 it("should throw error when search content is not found in second block", async () => {
520 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
521 mockParseAllSearchReplaceBlocks.mockReturnValue([
522 {
523 isComplete: true,
524 searchContent: "found content",
525 replaceContent: "replacement1",
526 },
527 {
528 isComplete: true,
529 searchContent: "missing content",
530 replaceContent: "replacement2",
531 },
532 ]);
533 mockIdeMessenger.ide.readFile.mockResolvedValue(
534 "found content and other stuff",
535 );
536
537 // First search succeeds, second fails
538 mockFindSearchMatch
539 .mockReturnValueOnce({
540 startIndex: 0,
541 endIndex: 13,
542 strategyName: "exactMatch",
543 })
544 .mockReturnValueOnce(null); // Second search fails
545
546 await expect(
547 searchReplaceToolImpl(
548 { filepath: "test.txt", diffs: ["mock diff content"] },
549 "tool-call-id",
550 mockExtras,
551 ),
552 ).rejects.toThrow(
553 "Search content not found in block 2:\nmissing content",
554 );
555 });
556
557 it("should handle file read errors", async () => {
558 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
559 mockParseAllSearchReplaceBlocks.mockReturnValue([
560 {
561 isComplete: true,
562 searchContent: "content",
563 replaceContent: "replacement",
564 },
565 ]);
566 mockIdeMessenger.ide.readFile.mockRejectedValue(
567 new Error("File read error"),
568 );
569
570 await expect(
571 searchReplaceToolImpl(
572 { filepath: "test.txt", diffs: ["mock diff content"] },
573 "tool-call-id",
574 mockExtras,
575 ),
576 ).rejects.toThrow("Failed to apply search and replace: File read error");
577 });
578 });
579
580 describe("edge cases", () => {
581 it("should handle empty search content", async () => {
582 const originalContent = "existing content";
583 const expectedFinalContent = "new contentexisting content";
584
585 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
586 mockParseAllSearchReplaceBlocks.mockReturnValue([
587 {
588 isComplete: true,
589 searchContent: "",
590 replaceContent: "new content",
591 },
592 ]);
593 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
594 mockFindSearchMatch.mockReturnValue({
595 startIndex: 0, // Empty search matches at beginning
596 endIndex: 0,
597 strategyName: "exactMatch",
598 });
599 await searchReplaceToolImpl(
600 { filepath: "test.txt", diffs: ["mock diff content"] },
601 "tool-call-id",
602 mockExtras,
603 );
604
605 expect(mockApplyForEditTool).toHaveBeenCalledWith({
606 text: expectedFinalContent,
607 streamId: "test-stream-id",
608 filepath: "/resolved/path/test.txt",
609 toolCallId: "tool-call-id",
610 isSearchAndReplace: true,
611 });
612 });
613
614 it("should handle whole file replacement", async () => {
615 const originalContent = "old file content";
616 const expectedFinalContent = "completely new content";
617
618 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
619 mockParseAllSearchReplaceBlocks.mockReturnValue([
620 {
621 isComplete: true,
622 searchContent: originalContent,
623 replaceContent: "completely new content",
624 },
625 ]);
626 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
627 mockFindSearchMatch.mockReturnValue({
628 startIndex: 0,
629 endIndex: originalContent.length,
630 strategyName: "exactMatch",
631 });
632
633 await searchReplaceToolImpl(
634 { filepath: "test.txt", diffs: ["mock diff content"] },
635 "tool-call-id",
636 mockExtras,
637 );
638
639 expect(mockApplyForEditTool).toHaveBeenCalledWith({
640 text: expectedFinalContent,
641 streamId: "test-stream-id",
642 filepath: "/resolved/path/test.txt",
643 toolCallId: "tool-call-id",
644 isSearchAndReplace: true,
645 });
646 });
647 });
648
649 describe("dependency integration", () => {
650 it("should call all dependencies with correct parameters", async () => {
651 const originalContent = "test content";
652
653 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
654 mockParseAllSearchReplaceBlocks.mockReturnValue([
655 {
656 isComplete: true,
657 searchContent: "test",
658 replaceContent: "updated",
659 },
660 ]);
661 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
662 mockFindSearchMatch.mockReturnValue({
663 startIndex: 0,
664 endIndex: 4,
665 strategyName: "exactMatch",
666 });
667
668 await searchReplaceToolImpl(
669 { filepath: "relative/test.txt", diffs: ["mock diff content"] },
670 "tool-call-id",
671 mockExtras,
672 );
673
674 // Verify all dependencies were called correctly
675 expect(mockResolveRelativePathInDir).toHaveBeenCalledWith(
676 "relative/test.txt",
677 mockIdeMessenger.ide,
678 );
679 expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledWith(
680 "mock diff content",
681 );
682 expect(mockIdeMessenger.ide.readFile).toHaveBeenCalledWith(
683 "/resolved/path/test.txt",
684 );
685 expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test");
686 expect(mockApplyForEditTool).toHaveBeenCalledWith({
687 text: "updated content",
688 streamId: "test-stream-id",
689 filepath: "/resolved/path/test.txt",
690 toolCallId: "tool-call-id",
691 isSearchAndReplace: true,
692 });
693 });
694 });
695});