Elffuss BraidHub

kikocis/continue public

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