Elffuss BraidHub

kikocis/continue public

Merge pull request #6586 from chezsmithy/feat-multiple-diffs

feat: :zap: Improve search and replace tool by supporting multiple diffs per tool call
Changeset7402671ebc64ee280a8892fefa414a7a2508b8b537461774c83cc66f4808554b
AuthorPatrick Erichsen <patrick.a.erichsen@gmail.com> · 2025-07-15 14:46 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-15 14:46 -07:00
Parents0f17595b5c72, f242d509007a

Browse the files at this changeset

4 files changed

modified core/tools/definitions/searchAndReplaceInFile.ts +15 −10
@@ -3,7 +3,7 @@
33
44 export interface SearchAndReplaceInFileArgs {
55 filepath: string;
6- diff: string;
6+ diffs: string[];
77 }
88
99 // Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
@@ -25,19 +25,22 @@
2525 isInstant: false,
2626 function: {
2727 name: BuiltInToolNames.SearchAndReplaceInFile,
28- description: `Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
28+ description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
2929 parameters: {
3030 type: "object",
31- required: ["filepath", "diff"],
31+ required: ["filepath", "diffs"],
3232 properties: {
3333 filepath: {
3434 type: "string",
3535 description:
3636 "The path of the file to modify, relative to the root of the workspace.",
3737 },
38- diff: {
39- type: "string",
40- description: `One or more SEARCH/REPLACE blocks following this exact format:
38+ diffs: {
39+ type: "array",
40+ items: {
41+ type: "string",
42+ },
43+ description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
4144 \`\`\`
4245 ------- SEARCH
4346 [exact content to find]
@@ -54,16 +57,17 @@
5457 * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
5558 * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
5659 * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
57-3. Keep SEARCH/REPLACE blocks concise:
60+3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
61+4. Keep SEARCH/REPLACE blocks concise:
5862 * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
5963 * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
6064 * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
6165 * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
62-4. Splitting up tool calls:
66+5. Splitting up tool calls:
6367 * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
6468 * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
6569 * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
66-5. Special operations:
70+6. Special operations:
6771 * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
6872 * To delete code: Use empty REPLACE section
6973
@@ -81,7 +85,8 @@
8185 [new content to replace with]
8286 +++++++ REPLACE
8387 \`\`\`
84-`,
88+
89+Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
8590 },
8691 },
8792 },
modified gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +1 −1
@@ -36,7 +36,7 @@
3636 return (
3737 <EditFile
3838 relativeFilePath={args.filepath ?? ""}
39- changes={args.diff ?? ""}
39+ changes={args.diffs ? args.diffs.join("\n\n---\n\n") : ""}
4040 toolCallId={toolCall.id}
4141 historyIndex={historyIndex}
4242 />
modified gui/src/util/clientTools/searchReplaceImpl.test.ts +205 −15
@@ -53,24 +53,61 @@
5353
5454 await expect(
5555 searchReplaceToolImpl(
56- { filepath: "nonexistent.txt", diff: "some diff" },
56+ { filepath: "nonexistent.txt", diffs: ["some diff"] },
5757 "tool-call-id",
5858 mockExtras,
5959 ),
6060 ).rejects.toThrow("File nonexistent.txt does not exist");
6161 });
6262
63- it("should throw error when no search/replace blocks found", async () => {
63+ it("should throw error when no search/replace blocks found in first diff", async () => {
6464 mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
6565 mockParseAllSearchReplaceBlocks.mockReturnValue([]);
6666
6767 await expect(
6868 searchReplaceToolImpl(
69- { filepath: "test.txt", diff: "invalid diff content" },
69+ { filepath: "test.txt", diffs: ["invalid diff content"] },
7070 "tool-call-id",
7171 mockExtras,
7272 ),
73- ).rejects.toThrow("No complete search/replace blocks found");
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");
74111 });
75112 });
76113
@@ -110,7 +147,65 @@
110147 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
111148
112149 const result = await searchReplaceToolImpl(
113- { filepath: "test.js", diff: "mock diff content" },
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"] },
114209 "tool-call-id",
115210 mockExtras,
116211 );
@@ -191,7 +286,7 @@
191286 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
192287
193288 const result = await searchReplaceToolImpl(
194- { filepath: "test.js", diff: "mock diff content" },
289+ { filepath: "test.js", diffs: ["mock diff content"] },
195290 "tool-call-id",
196291 mockExtras,
197292 );
@@ -225,6 +320,101 @@
225320 });
226321 });
227322
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;
326+const b = 2;
327+const c = 3;`;
328+
329+ const expectedFinalContent = `const a = 100;
330+const b = 200;
331+const 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+
228418 describe("deletion scenarios", () => {
229419 it("should handle empty replacement (deletion)", async () => {
230420 const originalContent = `keep this
@@ -253,7 +443,7 @@
253443 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
254444
255445 const result = await searchReplaceToolImpl(
256- { filepath: "test.txt", diff: "mock diff content" },
446+ { filepath: "test.txt", diffs: ["mock diff content"] },
257447 "tool-call-id",
258448 mockExtras,
259449 );
@@ -293,7 +483,7 @@
293483 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
294484
295485 await searchReplaceToolImpl(
296- { filepath: "test.txt", diff: "mock diff content" },
486+ { filepath: "test.txt", diffs: ["mock diff content"] },
297487 "tool-call-id",
298488 mockExtras,
299489 );
@@ -323,7 +513,7 @@
323513
324514 await expect(
325515 searchReplaceToolImpl(
326- { filepath: "test.txt", diff: "mock diff content" },
516+ { filepath: "test.txt", diffs: ["mock diff content"] },
327517 "tool-call-id",
328518 mockExtras,
329519 ),
@@ -361,7 +551,7 @@
361551
362552 await expect(
363553 searchReplaceToolImpl(
364- { filepath: "test.txt", diff: "mock diff content" },
554+ { filepath: "test.txt", diffs: ["mock diff content"] },
365555 "tool-call-id",
366556 mockExtras,
367557 ),
@@ -385,7 +575,7 @@
385575
386576 await expect(
387577 searchReplaceToolImpl(
388- { filepath: "test.txt", diff: "mock diff content" },
578+ { filepath: "test.txt", diffs: ["mock diff content"] },
389579 "tool-call-id",
390580 mockExtras,
391581 ),
@@ -411,7 +601,7 @@
411601
412602 await expect(
413603 searchReplaceToolImpl(
414- { filepath: "test.txt", diff: "mock diff content" },
604+ { filepath: "test.txt", diffs: ["mock diff content"] },
415605 "tool-call-id",
416606 mockExtras,
417607 ),
@@ -441,7 +631,7 @@
441631 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
442632
443633 await searchReplaceToolImpl(
444- { filepath: "test.txt", diff: "mock diff content" },
634+ { filepath: "test.txt", diffs: ["mock diff content"] },
445635 "tool-call-id",
446636 mockExtras,
447637 );
@@ -476,7 +666,7 @@
476666 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
477667
478668 await searchReplaceToolImpl(
479- { filepath: "test.txt", diff: "mock diff content" },
669+ { filepath: "test.txt", diffs: ["mock diff content"] },
480670 "tool-call-id",
481671 mockExtras,
482672 );
@@ -512,7 +702,7 @@
512702 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
513703
514704 await searchReplaceToolImpl(
515- { filepath: "relative/test.txt", diff: "mock diff content" },
705+ { filepath: "relative/test.txt", diffs: ["mock diff content"] },
516706 "tool-call-id",
517707 mockExtras,
518708 );
modified gui/src/util/clientTools/searchReplaceImpl.ts +16 −7
@@ -10,7 +10,7 @@
1010 toolCallId,
1111 extras,
1212 ) => {
13- const { filepath, diff } = args;
13+ const { filepath, diffs } = args;
1414
1515 const state = extras.getState();
1616 const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
@@ -26,11 +26,20 @@
2626 throw new Error(`File ${filepath} does not exist`);
2727 }
2828
29- // Parse all search/replace blocks from the diff content
30- const blocks = parseAllSearchReplaceBlocks(diff);
29+ // Parse all search/replace blocks from all diff strings
30+ const allBlocks = [];
31+ for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) {
32+ const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]);
33+ if (blocks.length === 0) {
34+ throw new Error(
35+ `No complete search/replace blocks found in diff ${diffIndex + 1}`,
36+ );
37+ }
38+ allBlocks.push(...blocks);
39+ }
3140
32- if (blocks.length === 0) {
33- throw new Error("No complete search/replace blocks found");
41+ if (allBlocks.length === 0) {
42+ throw new Error("No complete search/replace blocks found in any diffs");
3443 }
3544
3645 try {
@@ -40,8 +49,8 @@
4049 let currentContent = originalContent;
4150
4251 // Apply all replacements sequentially to build the final content
43- for (let i = 0; i < blocks.length; i++) {
44- const block = blocks[i];
52+ for (let i = 0; i < allBlocks.length; i++) {
53+ const block = allBlocks[i];
4554 const { searchContent, replaceContent } = block;
4655
4756 // Find the search content in the current state of the file