Elffuss BraidHub

kikocis/continue public

21cf25b4ed37 · 16.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 { 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");
12
13const mockFindSearchMatch = vi.mocked(findSearchMatch);
14const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks);
15const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir);
16
17describe("searchReplaceToolImpl", () => {
18 let mockExtras: ClientToolExtras;
19 let mockIdeMessenger: any;
20
21 beforeEach(() => {
22 // Reset all mocks
23 vi.clearAllMocks();
24
25 // Create mock IDE messenger
26 mockIdeMessenger = {
27 ide: {
28 readFile: vi.fn(),
29 },
30 request: vi.fn(),
31 };
32
33 // Create mock extras
34 mockExtras = {
35 streamId: "test-stream-id",
36 ideMessenger: mockIdeMessenger,
37 getState: vi.fn(),
38 dispatch: vi.fn(),
39 };
40 });
41
42 describe("basic validation", () => {
43 it("should throw error when no streamId is provided", async () => {
44 const extrasWithoutStreamId = {
45 ...mockExtras,
46 streamId: undefined,
47 };
48
49 await expect(
50 searchReplaceToolImpl(
51 { filepath: "test.txt", diff: "some diff" },
52 "tool-call-id",
53 extrasWithoutStreamId,
54 ),
55 ).rejects.toThrow("Invalid apply state - no streamId available");
56 });
57
58 it("should throw error when file does not exist", async () => {
59 mockResolveRelativePathInDir.mockResolvedValue(undefined);
60
61 await expect(
62 searchReplaceToolImpl(
63 { filepath: "nonexistent.txt", diff: "some diff" },
64 "tool-call-id",
65 mockExtras,
66 ),
67 ).rejects.toThrow("File nonexistent.txt does not exist");
68 });
69
70 it("should throw error when no search/replace blocks found", async () => {
71 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
72 mockParseAllSearchReplaceBlocks.mockReturnValue([]);
73
74 await expect(
75 searchReplaceToolImpl(
76 { filepath: "test.txt", diff: "invalid diff content" },
77 "tool-call-id",
78 mockExtras,
79 ),
80 ).rejects.toThrow("No complete search/replace blocks found");
81 });
82 });
83
84 describe("single block replacement", () => {
85 it("should successfully apply single search/replace block", async () => {
86 const originalContent = `function hello() {
87 console.log("Hello");
88 return "world";
89}`;
90
91 const expectedFinalContent = `function hello() {
92 console.log("Hi there!");
93 return "world";
94}`;
95
96 // Setup mocks
97 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
98 mockParseAllSearchReplaceBlocks.mockReturnValue([
99 {
100 isComplete: true,
101 searchContent: 'console.log("Hello");',
102 replaceContent: 'console.log("Hi there!");',
103 },
104 ]);
105 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
106
107 // Calculate correct positions for 'console.log("Hello");' in the original content
108 const searchText = 'console.log("Hello");';
109 const startIndex = originalContent.indexOf(searchText);
110 const endIndex = startIndex + searchText.length;
111
112 mockFindSearchMatch.mockReturnValue({
113 startIndex,
114 endIndex,
115 });
116 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
117
118 const result = await searchReplaceToolImpl(
119 { filepath: "test.js", diff: "mock diff content" },
120 "tool-call-id",
121 mockExtras,
122 );
123
124 // Verify the result
125 expect(result).toEqual({
126 respondImmediately: false,
127 output: undefined,
128 });
129
130 // Verify applyToFile was called with correct parameters
131 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
132 text: expectedFinalContent,
133 streamId: "test-stream-id",
134 filepath: "/resolved/path/test.js",
135 toolCallId: "tool-call-id",
136 });
137 });
138 });
139
140 describe("multiple block replacement", () => {
141 it("should successfully apply multiple search/replace blocks sequentially", async () => {
142 const originalContent = `const a = 1;
143const b = 2;
144const c = 3;`;
145
146 const expectedFinalContent = `const a = 100;
147const b = 200;
148const c = 3;`;
149
150 // Setup mocks
151 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
152 mockParseAllSearchReplaceBlocks.mockReturnValue([
153 {
154 isComplete: true,
155 searchContent: "const a = 1;",
156 replaceContent: "const a = 100;",
157 },
158 {
159 isComplete: true,
160 searchContent: "const b = 2;",
161 replaceContent: "const b = 200;",
162 },
163 ]);
164 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
165
166 // Calculate positions for sequential replacements
167 const firstSearchText = "const a = 1;";
168 const secondSearchText = "const b = 2;";
169
170 const firstStartIndex = originalContent.indexOf(firstSearchText);
171 const firstEndIndex = firstStartIndex + firstSearchText.length;
172
173 // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;"
174 const contentAfterFirstReplacement =
175 originalContent.substring(0, firstStartIndex) +
176 "const a = 100;" +
177 originalContent.substring(firstEndIndex);
178
179 const secondStartIndex =
180 contentAfterFirstReplacement.indexOf(secondSearchText);
181 const secondEndIndex = secondStartIndex + secondSearchText.length;
182
183 // Mock sequential search matches
184 mockFindSearchMatch
185 .mockReturnValueOnce({
186 startIndex: firstStartIndex,
187 endIndex: firstEndIndex,
188 })
189 .mockReturnValueOnce({
190 startIndex: secondStartIndex,
191 endIndex: secondEndIndex,
192 });
193
194 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
195
196 const result = await searchReplaceToolImpl(
197 { filepath: "test.js", diff: "mock diff content" },
198 "tool-call-id",
199 mockExtras,
200 );
201
202 // Verify the result
203 expect(result).toEqual({
204 respondImmediately: false,
205 output: undefined,
206 });
207
208 // Verify findSearchMatch was called twice with updated content
209 expect(mockFindSearchMatch).toHaveBeenCalledTimes(2);
210 expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
211 1,
212 originalContent,
213 "const a = 1;",
214 );
215 expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
216 2,
217 contentAfterFirstReplacement,
218 "const b = 2;",
219 );
220 // Verify final applyToFile call
221 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
222 text: expectedFinalContent,
223 streamId: "test-stream-id",
224 filepath: "/resolved/path/test.js",
225 toolCallId: "tool-call-id",
226 });
227 });
228 });
229
230 describe("deletion scenarios", () => {
231 it("should handle empty replacement (deletion)", async () => {
232 const originalContent = `keep this
233remove this line
234keep this too`;
235
236 const expectedFinalContent = `keep this
237
238keep this too`;
239
240 // Setup mocks
241 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
242 mockParseAllSearchReplaceBlocks.mockReturnValue([
243 {
244 isComplete: true,
245 searchContent: "remove this line",
246 replaceContent: "",
247 },
248 ]);
249 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
250 mockFindSearchMatch.mockReturnValue({
251 startIndex: 10, // Position of "remove this line"
252 endIndex: 26, // End of "remove this line"
253 });
254 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
255
256 const result = await searchReplaceToolImpl(
257 { filepath: "test.txt", diff: "mock diff content" },
258 "tool-call-id",
259 mockExtras,
260 );
261
262 expect(result).toEqual({
263 respondImmediately: false,
264 output: undefined,
265 });
266
267 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
268 text: expectedFinalContent,
269 streamId: "test-stream-id",
270 filepath: "/resolved/path/test.txt",
271 toolCallId: "tool-call-id",
272 });
273 });
274
275 it("should handle undefined replaceContent as empty string", async () => {
276 const originalContent = "line1\nline2\nline3";
277 const expectedFinalContent = "line1\n\nline3";
278
279 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
280 mockParseAllSearchReplaceBlocks.mockReturnValue([
281 {
282 isComplete: true,
283 searchContent: "line2",
284 replaceContent: undefined, // undefined should be treated as empty string
285 },
286 ]);
287 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
288 mockFindSearchMatch.mockReturnValue({
289 startIndex: 6,
290 endIndex: 11,
291 });
292 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
293
294 await searchReplaceToolImpl(
295 { filepath: "test.txt", diff: "mock diff content" },
296 "tool-call-id",
297 mockExtras,
298 );
299
300 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
301 text: expectedFinalContent,
302 streamId: "test-stream-id",
303 filepath: "/resolved/path/test.txt",
304 toolCallId: "tool-call-id",
305 });
306 });
307 });
308
309 describe("error handling", () => {
310 it("should throw error when search content is not found", async () => {
311 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
312 mockParseAllSearchReplaceBlocks.mockReturnValue([
313 {
314 isComplete: true,
315 searchContent: "nonexistent content",
316 replaceContent: "replacement",
317 },
318 ]);
319 mockIdeMessenger.ide.readFile.mockResolvedValue("some file content");
320 mockFindSearchMatch.mockReturnValue(null); // Search content not found
321
322 await expect(
323 searchReplaceToolImpl(
324 { filepath: "test.txt", diff: "mock diff content" },
325 "tool-call-id",
326 mockExtras,
327 ),
328 ).rejects.toThrow(
329 "Search content not found in block 1:\nnonexistent content",
330 );
331 });
332
333 it("should throw error when search content is not found in second block", async () => {
334 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
335 mockParseAllSearchReplaceBlocks.mockReturnValue([
336 {
337 isComplete: true,
338 searchContent: "found content",
339 replaceContent: "replacement1",
340 },
341 {
342 isComplete: true,
343 searchContent: "missing content",
344 replaceContent: "replacement2",
345 },
346 ]);
347 mockIdeMessenger.ide.readFile.mockResolvedValue(
348 "found content and other stuff",
349 );
350
351 // First search succeeds, second fails
352 mockFindSearchMatch
353 .mockReturnValueOnce({
354 startIndex: 0,
355 endIndex: 13,
356 })
357 .mockReturnValueOnce(null); // Second search fails
358
359 await expect(
360 searchReplaceToolImpl(
361 { filepath: "test.txt", diff: "mock diff content" },
362 "tool-call-id",
363 mockExtras,
364 ),
365 ).rejects.toThrow(
366 "Search content not found in block 2:\nmissing content",
367 );
368 });
369
370 it("should handle file read errors", async () => {
371 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
372 mockParseAllSearchReplaceBlocks.mockReturnValue([
373 {
374 isComplete: true,
375 searchContent: "content",
376 replaceContent: "replacement",
377 },
378 ]);
379 mockIdeMessenger.ide.readFile.mockRejectedValue(
380 new Error("File read error"),
381 );
382
383 await expect(
384 searchReplaceToolImpl(
385 { filepath: "test.txt", diff: "mock diff content" },
386 "tool-call-id",
387 mockExtras,
388 ),
389 ).rejects.toThrow("Failed to apply search and replace: File read error");
390 });
391
392 it("should handle applyToFile errors", async () => {
393 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
394 mockParseAllSearchReplaceBlocks.mockReturnValue([
395 {
396 isComplete: true,
397 searchContent: "content",
398 replaceContent: "replacement",
399 },
400 ]);
401 mockIdeMessenger.ide.readFile.mockResolvedValue("content");
402 mockFindSearchMatch.mockReturnValue({
403 startIndex: 0,
404 endIndex: 7,
405 });
406 mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed"));
407
408 await expect(
409 searchReplaceToolImpl(
410 { filepath: "test.txt", diff: "mock diff content" },
411 "tool-call-id",
412 mockExtras,
413 ),
414 ).rejects.toThrow("Failed to apply search and replace: Apply failed");
415 });
416 });
417
418 describe("edge cases", () => {
419 it("should handle empty search content", async () => {
420 const originalContent = "existing content";
421 const expectedFinalContent = "new contentexisting content";
422
423 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
424 mockParseAllSearchReplaceBlocks.mockReturnValue([
425 {
426 isComplete: true,
427 searchContent: "",
428 replaceContent: "new content",
429 },
430 ]);
431 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
432 mockFindSearchMatch.mockReturnValue({
433 startIndex: 0, // Empty search matches at beginning
434 endIndex: 0,
435 });
436 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
437
438 await searchReplaceToolImpl(
439 { filepath: "test.txt", diff: "mock diff content" },
440 "tool-call-id",
441 mockExtras,
442 );
443
444 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
445 text: expectedFinalContent,
446 streamId: "test-stream-id",
447 filepath: "/resolved/path/test.txt",
448 toolCallId: "tool-call-id",
449 });
450 });
451
452 it("should handle whole file replacement", async () => {
453 const originalContent = "old file content";
454 const expectedFinalContent = "completely new content";
455
456 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
457 mockParseAllSearchReplaceBlocks.mockReturnValue([
458 {
459 isComplete: true,
460 searchContent: originalContent,
461 replaceContent: "completely new content",
462 },
463 ]);
464 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
465 mockFindSearchMatch.mockReturnValue({
466 startIndex: 0,
467 endIndex: originalContent.length,
468 });
469 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
470
471 await searchReplaceToolImpl(
472 { filepath: "test.txt", diff: "mock diff content" },
473 "tool-call-id",
474 mockExtras,
475 );
476
477 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
478 text: expectedFinalContent,
479 streamId: "test-stream-id",
480 filepath: "/resolved/path/test.txt",
481 toolCallId: "tool-call-id",
482 });
483 });
484 });
485
486 describe("dependency integration", () => {
487 it("should call all dependencies with correct parameters", async () => {
488 const originalContent = "test content";
489
490 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
491 mockParseAllSearchReplaceBlocks.mockReturnValue([
492 {
493 isComplete: true,
494 searchContent: "test",
495 replaceContent: "updated",
496 },
497 ]);
498 mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
499 mockFindSearchMatch.mockReturnValue({
500 startIndex: 0,
501 endIndex: 4,
502 });
503 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
504
505 await searchReplaceToolImpl(
506 { filepath: "relative/test.txt", diff: "mock diff content" },
507 "tool-call-id",
508 mockExtras,
509 );
510
511 // Verify all dependencies were called correctly
512 expect(mockResolveRelativePathInDir).toHaveBeenCalledWith(
513 "relative/test.txt",
514 mockIdeMessenger.ide,
515 );
516 expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledWith(
517 "mock diff content",
518 );
519 expect(mockIdeMessenger.ide.readFile).toHaveBeenCalledWith(
520 "/resolved/path/test.txt",
521 );
522 expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test");
523 expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
524 text: "updated content",
525 streamId: "test-stream-id",
526 filepath: "/resolved/path/test.txt",
527 toolCallId: "tool-call-id",
528 });
529 });
530 });
531});