Elffuss BraidHub

kikocis/continue public

feat: :zap: Improve search and release tool by supporting multiple diffs per tool call
Changeset562ef8278dce4ef714836d5f540804dad1b2e51e5220da22c7df1c499885a031
Authorchezsmithy <chezsmithy@me.com> · 2025-07-11 18:00 -07:00
Committerchezsmithy <chezsmithy@me.com> · 2025-07-12 17:05 -07:00
Parentsa2d235e8c1f1

Browse the files at this changeset

4 files changed

modified core/tools/definitions/searchAndReplaceInFile.ts +16 −11
@@ -3,7 +3,7 @@
33
44 export interface SearchAndReplaceInFileArgs {
55 filepath: string;
6- diff: string;
6+ diffs: string[];
77 }
88
99 /**
@@ -22,19 +22,22 @@
2222 function: {
2323 name: BuiltInToolNames.SearchAndReplaceInFile,
2424 description:
25- "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.",
25+ "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.",
2626 parameters: {
2727 type: "object",
28- required: ["filepath", "diff"],
28+ required: ["filepath", "diffs"],
2929 properties: {
3030 filepath: {
3131 type: "string",
3232 description:
3333 "The path of the file to modify, relative to the root of the workspace.",
3434 },
35- diff: {
36- type: "string",
37- description: `One or more SEARCH/REPLACE blocks following this exact format:
35+ diffs: {
36+ type: "array",
37+ items: {
38+ type: "string",
39+ },
40+ description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
3841 \`\`\`
3942 ------- SEARCH
4043 [exact content to find]
@@ -51,16 +54,17 @@
5154 * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
5255 * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
5356 * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
54-3. Keep SEARCH/REPLACE blocks concise:
57+3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
58+4. Keep SEARCH/REPLACE blocks concise:
5559 * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
5660 * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
5761 * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
5862 * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
59-4. Splitting up tool calls:
63+5. Splitting up tool calls:
6064 * 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
6165 * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
6266 * 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]
63-5. Special operations:
67+6. Special operations:
6468 * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
6569 * To delete code: Use empty REPLACE section
6670
@@ -78,9 +82,10 @@
7882 [new content to replace with]
7983 +++++++ REPLACE
8084 \`\`\`
81-`,
85+
86+Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
8287 },
8388 },
8489 },
8590 },
86-};
91+};
No newline at the end of the file
modified gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +2 −2
@@ -37,7 +37,7 @@
3737 return (
3838 <EditFile
3939 relativeFilePath={args.filepath ?? ""}
40- changes={args.diff ?? ""}
40+ changes={args.diffs ? args.diffs.join("\n\n---\n\n") : ""}
4141 toolCallId={toolCall.id}
4242 historyIndex={historyIndex}
4343 />
@@ -55,4 +55,4 @@
5555 }
5656 }
5757
58-export default FunctionSpecificToolCallDiv;
58+export default FunctionSpecificToolCallDiv;
No newline at the end of the file
modified gui/src/util/clientTools/searchReplaceImpl.test.ts +197 −16
@@ -53,24 +53,58 @@
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+ { filepath: "test.txt", diffs: ["valid diff", "invalid diff content"] },
91+ "tool-call-id",
92+ mockExtras,
93+ ),
94+ ).rejects.toThrow("No complete search/replace blocks found in diff 2");
95+ });
96+
97+ it("should throw error when all diffs are empty", async () => {
98+ mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
99+ mockParseAllSearchReplaceBlocks.mockReturnValue([]);
100+
101+ await expect(
102+ searchReplaceToolImpl(
103+ { filepath: "test.txt", diffs: [] },
104+ "tool-call-id",
105+ mockExtras,
106+ ),
107+ ).rejects.toThrow("No complete search/replace blocks found in any diffs");
74108 });
75109 });
76110
@@ -110,7 +144,65 @@
110144 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
111145
112146 const result = await searchReplaceToolImpl(
113- { filepath: "test.js", diff: "mock diff content" },
147+ { filepath: "test.js", diffs: ["mock diff content"] },
148+ "tool-call-id",
149+ mockExtras,
150+ );
151+
152+ // Verify the result
153+ expect(result).toEqual({
154+ respondImmediately: false,
155+ output: undefined,
156+ });
157+
158+ // Verify applyToFile was called with correct parameters
159+ expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
160+ text: expectedFinalContent,
161+ streamId: "test-stream-id",
162+ filepath: "/resolved/path/test.js",
163+ toolCallId: "tool-call-id",
164+ isSearchAndReplace: true,
165+ });
166+ });
167+ });
168+
169+ describe("single diff scenarios", () => {
170+ it("should successfully apply single diff with single search/replace block", async () => {
171+ const originalContent = `function hello() {
172+ console.log("Hello");
173+ return "world";
174+}`;
175+
176+ const expectedFinalContent = `function hello() {
177+ console.log("Hi there!");
178+ return "world";
179+}`;
180+
181+ // Setup mocks
182+ mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
183+ mockParseAllSearchReplaceBlocks.mockReturnValue([
184+ {
185+ isComplete: true,
186+ searchContent: 'console.log("Hello");',
187+ replaceContent: 'console.log("Hi there!");',
188+ },
189+ ]);
190+ mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
191+
192+ // Calculate correct positions for 'console.log("Hello");' in the original content
193+ const searchText = 'console.log("Hello");';
194+ const startIndex = originalContent.indexOf(searchText);
195+ const endIndex = startIndex + searchText.length;
196+
197+ mockFindSearchMatch.mockReturnValue({
198+ startIndex,
199+ endIndex,
200+ strategyName: "exactMatch",
201+ });
202+ mockIdeMessenger.request.mockResolvedValue({ status: "success" });
203+
204+ const result = await searchReplaceToolImpl(
205+ { filepath: "test.js", diffs: ["mock diff content"] },
114206 "tool-call-id",
115207 mockExtras,
116208 );
@@ -191,7 +283,7 @@
191283 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
192284
193285 const result = await searchReplaceToolImpl(
194- { filepath: "test.js", diff: "mock diff content" },
286+ { filepath: "test.js", diffs: ["mock diff content"] },
195287 "tool-call-id",
196288 mockExtras,
197289 );
@@ -225,6 +317,95 @@
225317 });
226318 });
227319
320+ describe("multiple diff scenarios", () => {
321+ it("should successfully apply multiple diffs each with single search/replace block", async () => {
322+ const originalContent = `const a = 1;
323+const b = 2;
324+const c = 3;`;
325+
326+ const expectedFinalContent = `const a = 100;
327+const b = 200;
328+const c = 3;`;
329+
330+ // Setup mocks - each diff returns one block
331+ mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
332+ mockParseAllSearchReplaceBlocks
333+ .mockReturnValueOnce([
334+ {
335+ isComplete: true,
336+ searchContent: "const a = 1;",
337+ replaceContent: "const a = 100;",
338+ },
339+ ])
340+ .mockReturnValueOnce([
341+ {
342+ isComplete: true,
343+ searchContent: "const b = 2;",
344+ replaceContent: "const b = 200;",
345+ },
346+ ]);
347+ mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
348+
349+ // Calculate positions for sequential replacements
350+ const firstSearchText = "const a = 1;";
351+ const secondSearchText = "const b = 2;";
352+
353+ const firstStartIndex = originalContent.indexOf(firstSearchText);
354+ const firstEndIndex = firstStartIndex + firstSearchText.length;
355+
356+ // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;"
357+ const contentAfterFirstReplacement =
358+ originalContent.substring(0, firstStartIndex) +
359+ "const a = 100;" +
360+ originalContent.substring(firstEndIndex);
361+
362+ const secondStartIndex =
363+ contentAfterFirstReplacement.indexOf(secondSearchText);
364+ const secondEndIndex = secondStartIndex + secondSearchText.length;
365+
366+ // Mock sequential search matches
367+ mockFindSearchMatch
368+ .mockReturnValueOnce({
369+ startIndex: firstStartIndex,
370+ endIndex: firstEndIndex,
371+ strategyName: "exactMatch",
372+ })
373+ .mockReturnValueOnce({
374+ startIndex: secondStartIndex,
375+ endIndex: secondEndIndex,
376+ strategyName: "exactMatch",
377+ });
378+
379+ mockIdeMessenger.request.mockResolvedValue({ status: "success" });
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(1, "first diff");
396+ expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith(2, "second diff");
397+
398+ // Verify final applyToFile call
399+ expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
400+ text: expectedFinalContent,
401+ streamId: "test-stream-id",
402+ filepath: "/resolved/path/test.js",
403+ toolCallId: "tool-call-id",
404+ isSearchAndReplace: true,
405+ });
406+ });
407+ });
408+
228409 describe("deletion scenarios", () => {
229410 it("should handle empty replacement (deletion)", async () => {
230411 const originalContent = `keep this
@@ -253,7 +434,7 @@
253434 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
254435
255436 const result = await searchReplaceToolImpl(
256- { filepath: "test.txt", diff: "mock diff content" },
437+ { filepath: "test.txt", diffs: ["mock diff content"] },
257438 "tool-call-id",
258439 mockExtras,
259440 );
@@ -293,7 +474,7 @@
293474 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
294475
295476 await searchReplaceToolImpl(
296- { filepath: "test.txt", diff: "mock diff content" },
477+ { filepath: "test.txt", diffs: ["mock diff content"] },
297478 "tool-call-id",
298479 mockExtras,
299480 );
@@ -323,7 +504,7 @@
323504
324505 await expect(
325506 searchReplaceToolImpl(
326- { filepath: "test.txt", diff: "mock diff content" },
507+ { filepath: "test.txt", diffs: ["mock diff content"] },
327508 "tool-call-id",
328509 mockExtras,
329510 ),
@@ -361,7 +542,7 @@
361542
362543 await expect(
363544 searchReplaceToolImpl(
364- { filepath: "test.txt", diff: "mock diff content" },
545+ { filepath: "test.txt", diffs: ["mock diff content"] },
365546 "tool-call-id",
366547 mockExtras,
367548 ),
@@ -385,7 +566,7 @@
385566
386567 await expect(
387568 searchReplaceToolImpl(
388- { filepath: "test.txt", diff: "mock diff content" },
569+ { filepath: "test.txt", diffs: ["mock diff content"] },
389570 "tool-call-id",
390571 mockExtras,
391572 ),
@@ -411,7 +592,7 @@
411592
412593 await expect(
413594 searchReplaceToolImpl(
414- { filepath: "test.txt", diff: "mock diff content" },
595+ { filepath: "test.txt", diffs: ["mock diff content"] },
415596 "tool-call-id",
416597 mockExtras,
417598 ),
@@ -441,7 +622,7 @@
441622 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
442623
443624 await searchReplaceToolImpl(
444- { filepath: "test.txt", diff: "mock diff content" },
625+ { filepath: "test.txt", diffs: ["mock diff content"] },
445626 "tool-call-id",
446627 mockExtras,
447628 );
@@ -476,7 +657,7 @@
476657 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
477658
478659 await searchReplaceToolImpl(
479- { filepath: "test.txt", diff: "mock diff content" },
660+ { filepath: "test.txt", diffs: ["mock diff content"] },
480661 "tool-call-id",
481662 mockExtras,
482663 );
@@ -512,7 +693,7 @@
512693 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
513694
514695 await searchReplaceToolImpl(
515- { filepath: "relative/test.txt", diff: "mock diff content" },
696+ { filepath: "relative/test.txt", diffs: ["mock diff content"] },
516697 "tool-call-id",
517698 mockExtras,
518699 );
@@ -538,4 +719,4 @@
538719 });
539720 });
540721 });
541-});
722+});
No newline at the end of the file
modified gui/src/util/clientTools/searchReplaceImpl.ts +15 −8
@@ -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,18 @@
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(`No complete search/replace blocks found in diff ${diffIndex + 1}`);
35+ }
36+ allBlocks.push(...blocks);
37+ }
3138
32- if (blocks.length === 0) {
33- throw new Error("No complete search/replace blocks found");
39+ if (allBlocks.length === 0) {
40+ throw new Error("No complete search/replace blocks found in any diffs");
3441 }
3542
3643 try {
@@ -40,8 +47,8 @@
4047 let currentContent = originalContent;
4148
4249 // Apply all replacements sequentially to build the final content
43- for (let i = 0; i < blocks.length; i++) {
44- const block = blocks[i];
50+ for (let i = 0; i < allBlocks.length; i++) {
51+ const block = allBlocks[i];
4552 const { searchContent, replaceContent } = block;
4653
4754 // Find the search content in the current state of the file
@@ -91,4 +98,4 @@
9198 `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`,
9299 );
93100 }
94-};
101+};
No newline at the end of the file