diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index f4c601009..5dd546315 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -3,7 +3,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export interface SearchAndReplaceInFileArgs { filepath: string; - diff: string; + diffs: string[]; } /** @@ -22,19 +22,22 @@ export const searchAndReplaceInFileTool: Tool = { function: { name: BuiltInToolNames.SearchAndReplaceInFile, 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.", + "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.", parameters: { type: "object", - required: ["filepath", "diff"], + required: ["filepath", "diffs"], properties: { filepath: { type: "string", description: "The path of the file to modify, relative to the root of the workspace.", }, - diff: { - type: "string", - description: `One or more SEARCH/REPLACE blocks following this exact format: + diffs: { + type: "array", + items: { + type: "string", + }, + description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: \`\`\` ------- SEARCH [exact content to find] @@ -51,16 +54,17 @@ Critical rules: * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. -3. Keep SEARCH/REPLACE blocks concise: +3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. +4. Keep SEARCH/REPLACE blocks concise: * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. * Include just the changing lines, and a few surrounding lines if needed for uniqueness. * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. -4. Splitting up tool calls: +5. Splitting up tool calls: * 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 * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls * 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] -5. Special operations: +6. Special operations: * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) * To delete code: Use empty REPLACE section @@ -78,9 +82,10 @@ Usage: [new content to replace with] +++++++ REPLACE \`\`\` -`, + +Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, }, }, }, }, -}; +}; \ No newline at end of file diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 37c1911dc..e3d9a0d8a 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -37,7 +37,7 @@ function FunctionSpecificToolCallDiv({ return ( @@ -55,4 +55,4 @@ function FunctionSpecificToolCallDiv({ } } -export default FunctionSpecificToolCallDiv; +export default FunctionSpecificToolCallDiv; \ No newline at end of file diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts index b8db3f830..0ecb07c8f 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.test.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.test.ts @@ -53,24 +53,58 @@ describe("searchReplaceToolImpl", () => { await expect( searchReplaceToolImpl( - { filepath: "nonexistent.txt", diff: "some diff" }, + { filepath: "nonexistent.txt", diffs: ["some diff"] }, "tool-call-id", mockExtras, ), ).rejects.toThrow("File nonexistent.txt does not exist"); }); - it("should throw error when no search/replace blocks found", async () => { + it("should throw error when no search/replace blocks found in first diff", async () => { mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); mockParseAllSearchReplaceBlocks.mockReturnValue([]); await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "invalid diff content" }, + { filepath: "test.txt", diffs: ["invalid diff content"] }, "tool-call-id", mockExtras, ), - ).rejects.toThrow("No complete search/replace blocks found"); + ).rejects.toThrow("No complete search/replace blocks found in diff 1"); + }); + + it("should throw error when no search/replace blocks found in second diff", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); + mockParseAllSearchReplaceBlocks + .mockReturnValueOnce([ + { + isComplete: true, + searchContent: "valid content", + replaceContent: "replacement", + }, + ]) + .mockReturnValueOnce([]); + + await expect( + searchReplaceToolImpl( + { filepath: "test.txt", diffs: ["valid diff", "invalid diff content"] }, + "tool-call-id", + mockExtras, + ), + ).rejects.toThrow("No complete search/replace blocks found in diff 2"); + }); + + it("should throw error when all diffs are empty", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); + mockParseAllSearchReplaceBlocks.mockReturnValue([]); + + await expect( + searchReplaceToolImpl( + { filepath: "test.txt", diffs: [] }, + "tool-call-id", + mockExtras, + ), + ).rejects.toThrow("No complete search/replace blocks found in any diffs"); }); }); @@ -110,7 +144,65 @@ describe("searchReplaceToolImpl", () => { mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( - { filepath: "test.js", diff: "mock diff content" }, + { filepath: "test.js", diffs: ["mock diff content"] }, + "tool-call-id", + mockExtras, + ); + + // Verify the result + expect(result).toEqual({ + respondImmediately: false, + output: undefined, + }); + + // Verify applyToFile was called with correct parameters + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + text: expectedFinalContent, + streamId: "test-stream-id", + filepath: "/resolved/path/test.js", + toolCallId: "tool-call-id", + isSearchAndReplace: true, + }); + }); + }); + + describe("single diff scenarios", () => { + it("should successfully apply single diff with single search/replace block", async () => { + const originalContent = `function hello() { + console.log("Hello"); + return "world"; +}`; + + const expectedFinalContent = `function hello() { + console.log("Hi there!"); + return "world"; +}`; + + // Setup mocks + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); + mockParseAllSearchReplaceBlocks.mockReturnValue([ + { + isComplete: true, + searchContent: 'console.log("Hello");', + replaceContent: 'console.log("Hi there!");', + }, + ]); + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); + + // Calculate correct positions for 'console.log("Hello");' in the original content + const searchText = 'console.log("Hello");'; + const startIndex = originalContent.indexOf(searchText); + const endIndex = startIndex + searchText.length; + + mockFindSearchMatch.mockReturnValue({ + startIndex, + endIndex, + strategyName: "exactMatch", + }); + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); + + const result = await searchReplaceToolImpl( + { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -191,7 +283,7 @@ const c = 3;`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( - { filepath: "test.js", diff: "mock diff content" }, + { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -225,6 +317,95 @@ const c = 3;`; }); }); + describe("multiple diff scenarios", () => { + it("should successfully apply multiple diffs each with single search/replace block", async () => { + const originalContent = `const a = 1; +const b = 2; +const c = 3;`; + + const expectedFinalContent = `const a = 100; +const b = 200; +const c = 3;`; + + // Setup mocks - each diff returns one block + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); + mockParseAllSearchReplaceBlocks + .mockReturnValueOnce([ + { + isComplete: true, + searchContent: "const a = 1;", + replaceContent: "const a = 100;", + }, + ]) + .mockReturnValueOnce([ + { + isComplete: true, + searchContent: "const b = 2;", + replaceContent: "const b = 200;", + }, + ]); + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); + + // Calculate positions for sequential replacements + const firstSearchText = "const a = 1;"; + const secondSearchText = "const b = 2;"; + + const firstStartIndex = originalContent.indexOf(firstSearchText); + const firstEndIndex = firstStartIndex + firstSearchText.length; + + // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;" + const contentAfterFirstReplacement = + originalContent.substring(0, firstStartIndex) + + "const a = 100;" + + originalContent.substring(firstEndIndex); + + const secondStartIndex = + contentAfterFirstReplacement.indexOf(secondSearchText); + const secondEndIndex = secondStartIndex + secondSearchText.length; + + // Mock sequential search matches + mockFindSearchMatch + .mockReturnValueOnce({ + startIndex: firstStartIndex, + endIndex: firstEndIndex, + strategyName: "exactMatch", + }) + .mockReturnValueOnce({ + startIndex: secondStartIndex, + endIndex: secondEndIndex, + strategyName: "exactMatch", + }); + + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); + + const result = await searchReplaceToolImpl( + { filepath: "test.js", diffs: ["first diff", "second diff"] }, + "tool-call-id", + mockExtras, + ); + + // Verify the result + expect(result).toEqual({ + respondImmediately: false, + output: undefined, + }); + + // Verify parseAllSearchReplaceBlocks was called for each diff + expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledTimes(2); + expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith(1, "first diff"); + expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith(2, "second diff"); + + // Verify final applyToFile call + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + text: expectedFinalContent, + streamId: "test-stream-id", + filepath: "/resolved/path/test.js", + toolCallId: "tool-call-id", + isSearchAndReplace: true, + }); + }); + }); + describe("deletion scenarios", () => { it("should handle empty replacement (deletion)", async () => { const originalContent = `keep this @@ -253,7 +434,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -293,7 +474,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -323,7 +504,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -361,7 +542,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -385,7 +566,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -411,7 +592,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -441,7 +622,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -476,7 +657,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -512,7 +693,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "relative/test.txt", diff: "mock diff content" }, + { filepath: "relative/test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -538,4 +719,4 @@ keep this too`; }); }); }); -}); +}); \ No newline at end of file diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts index 9594b9480..91448173a 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.ts @@ -10,7 +10,7 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( toolCallId, extras, ) => { - const { filepath, diff } = args; + const { filepath, diffs } = args; const state = extras.getState(); const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; @@ -26,11 +26,18 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( throw new Error(`File ${filepath} does not exist`); } - // Parse all search/replace blocks from the diff content - const blocks = parseAllSearchReplaceBlocks(diff); + // Parse all search/replace blocks from all diff strings + const allBlocks = []; + for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) { + const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]); + if (blocks.length === 0) { + throw new Error(`No complete search/replace blocks found in diff ${diffIndex + 1}`); + } + allBlocks.push(...blocks); + } - if (blocks.length === 0) { - throw new Error("No complete search/replace blocks found"); + if (allBlocks.length === 0) { + throw new Error("No complete search/replace blocks found in any diffs"); } try { @@ -40,8 +47,8 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( let currentContent = originalContent; // Apply all replacements sequentially to build the final content - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; + for (let i = 0; i < allBlocks.length; i++) { + const block = allBlocks[i]; const { searchContent, replaceContent } = block; // Find the search content in the current state of the file @@ -91,4 +98,4 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`, ); } -}; +}; \ No newline at end of file