chore: remove unused search and replace tool (#7487)

* chore: remove unused search and replace tool

* chore: remove search and replace, continued

* chore: remove search and replace part 3

* chore: remove search replace tool p4
This commit is contained in:
Dallin Romney 2025-08-29 15:18:40 -07:00 • committed by GitHub
parent 457195484a
commit e9641b00a3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 11 additions and 2897 deletions

View file

@ -1,618 +0,0 @@
import { findSearchMatch, SearchMatchResult } from "./findSearchMatch";
/**
* Helper function to perform a replacement using the match result
* This simulates what the actual replacement tool would do
*/
function performReplacement(
fileContent: string,
match: SearchMatchResult,
replacement: string,
): string {
return (
fileContent.substring(0, match.startIndex) +
replacement +
fileContent.substring(match.endIndex)
);
}
/**
* Helper function to test a specific strategy by crafting inputs that
* will fail all previous strategies
*/
function testSpecificStrategy(
fileContent: string,
searchContent: string,
expectedStrategy: string,
): SearchMatchResult | null {
const result = findSearchMatch(fileContent, searchContent);
if (result && result.strategyName !== expectedStrategy) {
throw new Error(
`Expected strategy ${expectedStrategy} but got ${result.strategyName}`,
);
}
return result;
}
/**
* Helper function to verify that a match result correctly identifies
* the intended content and replacement works properly
*/
function verifyMatchAndReplacement(
fileContent: string,
searchContent: string,
expectedMatchedText: string,
replacementText: string,
expectedResult: string,
): void {
const match = findSearchMatch(fileContent, searchContent);
if (!match) {
throw new Error("No match found");
}
// Verify the match captures the expected text
const actualMatchedText = fileContent.substring(
match.startIndex,
match.endIndex,
);
expect(actualMatchedText).toBe(expectedMatchedText);
// Verify replacement works correctly
const result = performReplacement(fileContent, match, replacementText);
expect(result).toBe(expectedResult);
}
describe("Strategy-specific tests", () => {
describe("exactMatch strategy", () => {
it("should handle exact match at various positions", () => {
const testCases = [
{
name: "at start",
fileContent: "abc def ghi",
searchContent: "abc",
expectedStart: 0,
expectedEnd: 3,
},
{
name: "in middle",
fileContent: "abc def ghi",
searchContent: "def",
expectedStart: 4,
expectedEnd: 7,
},
{
name: "at end",
fileContent: "abc def ghi",
searchContent: "ghi",
expectedStart: 8,
expectedEnd: 11,
},
{
name: "entire content",
fileContent: "abc def ghi",
searchContent: "abc def ghi",
expectedStart: 0,
expectedEnd: 11,
},
];
testCases.forEach(
({ name, fileContent, searchContent, expectedStart, expectedEnd }) => {
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(expectedStart);
expect(result!.endIndex).toBe(expectedEnd);
// Verify the matched content
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
},
);
});
it("should handle multiline exact matches", () => {
const fileContent = `line1
line2
line3
line4`;
const searchContent = `line2
line3`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(6); // After "line1\n"
expect(result!.endIndex).toBe(17); // End of "line3"
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should handle content with special characters", () => {
const fileContent = `const regex = /[a-z]+/gi;
const str = "Hello, World!";
const result = str.match(regex);`;
const searchContent = `const str = "Hello, World!";`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should verify replacement works correctly for exact matches", () => {
verifyMatchAndReplacement(
"const a = 1;\nconst b = 2;\nconst c = 3;",
"const b = 2;",
"const b = 2;",
"const b = 42;",
"const a = 1;\nconst b = 42;\nconst c = 3;",
);
});
it("should handle Windows-style line endings", () => {
const fileContent = "line1\r\nline2\r\nline3";
const searchContent = "line2";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(7); // After "line1\r\n"
expect(result!.endIndex).toBe(12); // End of "line2"
});
it("should handle mixed line endings", () => {
const fileContent = "line1\nline2\r\nline3\rline4";
const searchContent = "line2\r\nline3";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
});
describe("trimmedMatch strategy", () => {
it("should match when only whitespace differs at edges", () => {
const testCases = [
{
name: "leading spaces",
fileContent: "abc\n def\nghi",
searchContent: " def",
trimmedSearch: "def",
},
{
name: "trailing spaces",
fileContent: "abc\ndef \nghi",
searchContent: "def ",
trimmedSearch: "def",
},
{
name: "both leading and trailing",
fileContent: "abc\n def \nghi",
searchContent: " def ",
trimmedSearch: "def",
},
{
name: "tabs and spaces",
fileContent: "abc\n\t def \t\nghi",
searchContent: "\t def \t",
trimmedSearch: "def",
},
];
testCases.forEach(
({ name, fileContent, searchContent, trimmedSearch }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// For cases where exact match exists, it should be preferred
if (fileContent.indexOf(searchContent) !== -1) {
expect(result!.strategyName).toBe("exactMatch");
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
} else {
expect(result!.strategyName).toBe("trimmedMatch");
// The match should find the trimmed content with surrounding whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(trimmedSearch);
}
},
);
});
it("should handle multiline content with edge whitespace", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2; `;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used
expect(result!.strategyName).toBe("trimmedMatch");
});
it("should verify replacement with trimmed matches", () => {
const fileContent = "start\n targetContent \nend";
const searchContent = " targetContent ";
const replacement = "newContent";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("trimmedMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe("start\nnewContent\nend");
});
it("should handle edge case with only whitespace", () => {
const fileContent = " \n \n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find exact match since the content matches exactly
expect(result!.strategyName).toBe("exactMatch");
});
});
describe("whitespaceIgnoredMatch strategy", () => {
it("should match content with different indentation", () => {
const fileContent = `function test() {
const x = 1;
if (x > 0) {
return true;
}
}`;
const searchContent = `const x=1;
if(x>0){
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the match covers the intended code block
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("const x = 1");
expect(matchedContent).toContain("return true");
});
it("should handle complex whitespace variations", () => {
const testCases = [
{
name: "spaces vs tabs",
fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}",
searchContent: "if (condition) { return true; }",
},
{
name: "multiple spaces collapsed",
fileContent: "const result = calculate( x , y );",
searchContent: "const result=calculate(x,y);",
},
{
name: "newlines removed",
fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}",
searchContent: "function test(){return 1;}",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the entire content is matched
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent.replace(/\s/g, "")).toBe(
searchContent.replace(/\s/g, ""),
);
});
});
it("should handle partial matches with whitespace differences", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.items = [];
}
addItem(item) {
this.items.push(item);
}
}`;
const searchContent = `constructor(name){this.name=name;this.items=[];}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// The match should cover the constructor method
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("constructor");
expect(matchedContent).toContain("this.items = []");
});
it("should verify replacement with whitespace-ignored matches", () => {
const fileContent = `function calculate ( a , b ) {
return a + b ;
}`;
const searchContent = `function calculate(a,b){return a+b;}`;
const replacement = `function calculate(x, y) {
return x + y;
}`;
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("whitespaceIgnoredMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge cases with empty content after whitespace removal", () => {
const fileContent = " \n\t\r\n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
// Since search content doesn't exist in file but trims to empty, should return emptySearch
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("emptySearch");
});
it("should match correctly when multiple potential matches exist", () => {
const fileContent = `const a=1;
const a = 1 ;
const a = 1;`;
const searchContent = "const a = 1;";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find the exact match first (third occurrence)
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(33); // After first two lines
});
});
describe("Empty search content", () => {
it("should always return position 0 for empty search", () => {
const testCases = [
{ fileContent: "some content" },
{ fileContent: "" },
{ fileContent: "line1\nline2\nline3" },
{ fileContent: " spaces " },
];
testCases.forEach(({ fileContent }) => {
const result = findSearchMatch(fileContent, "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
it("should treat whitespace-only search as empty", () => {
const searchVariants = [" ", "\n\n", "\t\t", " \n\t "];
searchVariants.forEach((searchContent) => {
const result = findSearchMatch("test content", searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
});
describe("Strategy precedence", () => {
it("should always prefer exact match over other strategies", () => {
const fileContent = `exact match
exact match with spaces
exactmatch`;
// This should find exact match even though fuzzy would also work
const result = findSearchMatch(fileContent, "exact match");
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(0);
});
it("should prefer trimmed match over whitespace-ignored", () => {
const fileContent = " content ";
const searchContent = " content ";
// Should find exact match
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("exactMatch");
});
it("should prefer whitespace-ignored over fuzzy", () => {
const fileContent = "const x = 1;";
const searchContent = "const x=1;";
// Should use whitespace-ignored, not fuzzy
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
});
});
describe("Replacement verification tests", () => {
it("should correctly replace content found by each strategy", () => {
const testCases = [
{
name: "exact match replacement",
fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;",
searchContent: "const b = 2;",
replacement: "const b = 42;",
expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;",
expectedStrategy: "exactMatch",
},
{
name: "trimmed match replacement",
fileContent: "start\n target \nend",
searchContent: " target ",
replacement: "replaced",
expectedResult: "start\nreplaced\nend",
expectedStrategy: "trimmedMatch",
},
{
name: "whitespace-ignored replacement",
fileContent: "if ( x > 0 ) { return true; }",
searchContent: "if(x>0){return true;}",
replacement: "if (x > 0) { return false; }",
expectedResult: "if (x > 0) { return false; }",
expectedStrategy: "whitespaceIgnoredMatch",
},
];
testCases.forEach(
({
name,
fileContent,
searchContent,
replacement,
expectedResult,
expectedStrategy,
}) => {
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe(expectedStrategy);
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(expectedResult);
},
);
});
it("should handle edge cases in replacement", () => {
// Empty replacement
verifyMatchAndReplacement(
"before target after",
"target",
"target",
"",
"before after",
);
// Replacement longer than original
verifyMatchAndReplacement(
"short",
"short",
"short",
"much longer replacement",
"much longer replacement",
);
// Multiline replacement
verifyMatchAndReplacement(
"single line",
"single",
"single",
"multi\nline\nreplacement",
"multi\nline\nreplacement line",
);
});
});
describe("Performance and edge cases", () => {
it("should handle very long content efficiently", () => {
const longContent = "x".repeat(10000) + "target" + "y".repeat(10000);
const result = findSearchMatch(longContent, "target");
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(10000);
expect(result!.endIndex).toBe(10006);
});
it("should handle unicode and special characters", () => {
const testCases = [
{
fileContent: "const emoji = '🚀🌟🎉';",
searchContent: "🚀🌟🎉",
},
{
fileContent: "const chinese = '你好世界';",
searchContent: "你好世界",
},
{
fileContent: "const regex = /\\d+/g;",
searchContent: "/\\d+/g",
},
];
testCases.forEach(({ fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(searchContent);
});
});
it("should handle null bytes and control characters", () => {
const fileContent = "before\x00null\x01byte\x02after";
const searchContent = "\x00null\x01byte\x02";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("exactMatch");
});
});
});

View file

@ -1,587 +0,0 @@
import { findSearchMatch } from "./findSearchMatch";
describe("Exact matches", () => {
it("should find exact match at the beginning of file", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match in the middle of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}
const b = 2;`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match at the end of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b = 2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with whitespace preserved", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2;`;
const result = findSearchMatch(fileContent, searchContent);
// The actual indexOf result is 18, not 17
expect(result).toEqual({
startIndex: 18,
endIndex: 18 + searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Trimmed matches", () => {
it("should find trimmed match when exact match fails due to leading newlines", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction hello() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length, // Uses trimmed length
strategyName: "trimmedMatch",
});
});
it("should find trimmed match when exact match fails due to trailing newlines", () => {
const fileContent = `const a = 1;
function hello() {
return "world";
}
const b = 2;`;
const searchContent = `\nfunction hello() {
return "world";
}\n`;
const result = findSearchMatch(fileContent, searchContent);
// The function finds the exact match first (at index 12), not the trimmed match
expect(result).toEqual({
startIndex: 12,
endIndex: 12 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find trimmed match for single line with extra whitespace", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `\n const b = 2; \n`;
const result = findSearchMatch(fileContent, searchContent);
const trimmedSearchContent = searchContent.trim();
const expectedStart = fileContent.indexOf(trimmedSearchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + trimmedSearchContent.length,
strategyName: "trimmedMatch",
});
});
});
describe("Empty search content", () => {
it("should match at beginning for empty search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should match at beginning for whitespace-only search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "\n\n \t \n";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should match at beginning for empty file and empty search", () => {
const fileContent = "";
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
const searchContent = "function hello() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle very large content", () => {
const repeatedLine = "const x = 1;\n";
const fileContent =
repeatedLine.repeat(1000) +
"const target = 2;\n" +
repeatedLine.repeat(1000);
const searchContent = "const target = 2;";
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = repeatedLine.length * 1000;
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should handle special characters and symbols", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();
const unicode = "🚀 Hello 世界";`;
const searchContent = `const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should prefer exact match over trimmed match", () => {
const fileContent = `function test() {
const x = 1;
}
function test() {
const x = 1;
}`;
const searchContent = `function test() {
const x = 1;
}`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match, not a trimmed version
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
it("should handle multiple occurrences and return first match", () => {
const fileContent = `const a = 1;
const b = 2;
const a = 1;`;
const searchContent = `const a = 1;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Whitespace-ignored matches", () => {
it("should match code with different indentation", () => {
const fileContent = `function example() {
const x = 1;
const y = 2;
return x + y;
}`;
const searchContent = `const x=1;
const y=2;
return x+y;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(20); // After "function example() {\n"
expect(result!.endIndex).toBe(72); // End of " return x + y;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content contains the original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const x = 1;
const y = 2;
return x + y;`);
});
it("should match single line with different spacing", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b=2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(12); // After "const a = 1;"
expect(result!.endIndex).toBe(32); // End of "const b = 2;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original spacing
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const b = 2;`);
});
it("should match with tabs vs spaces", () => {
const fileContent = `function test() {
\tif (condition) {
\t\treturn true;
\t}
}`;
const searchContent = `if (condition) {
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function test() {"
expect(result!.endIndex).toBe(53); // End of "\t}"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original tabs
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
\tif (condition) {
\t\treturn true;
\t}`);
});
it("should match complex whitespace patterns", () => {
const fileContent = `const obj = {
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'
};`;
const searchContent = `key1:'value1',
key2:'value2',
key3:'value3'`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(13); // After "const obj = {"
expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'`);
});
it("should handle newlines and mixed whitespace", () => {
const fileContent = `function calc() {
let result = 0;
result += 5;
return result;
}`;
const searchContent = `let result=0;result+=5;return result;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
expect(result!.endIndex).toBe(78); // End of " return result;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content includes all original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
let result = 0;
result += 5;
return result;`);
});
it("should prefer exact match over whitespace-ignored match", () => {
const fileContent = `const x=1;
const x = 1;`;
const searchContent = `const x=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the exact match first (at index 0), not the whitespace-ignored match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
it("should handle empty content after whitespace removal", () => {
const fileContent = `function test() {
return 1;
}`;
const searchContent = `\n\n \t \n`;
const result = findSearchMatch(fileContent, searchContent);
// Should match at beginning for empty/whitespace-only content
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle complex code blocks with different formatting", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.value = 0;
}
getValue() {
return this.value;
}
}`;
const searchContent = `constructor(name){
this.name=name;
this.value=0;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(15); // After "class Example {"
expect(result!.endIndex).toBe(95); // End of " }"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
constructor(name) {
this.name = name;
this.value = 0;
}`);
});
it("should return null when no close match exists", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `this has nothing to do with the other option`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiple potential matches and return first", () => {
const fileContent = `const a=1;
const a = 1;
const a = 1;`;
const searchContent = `const a=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
});
describe("Real-world scenarios", () => {
it("should match typical function replacement", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
reset() {
this.result = 0;
return this;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = ` reset() {
this.result = 0;
return this;
}`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match import statement", () => {
const fileContent = `import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function App() {
return <div>Hello World</div>;
}`;
const searchContent = `import { useState, useEffect } from 'react';`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match comment block", () => {
const fileContent = `/**
* This is a comment
* that spans multiple lines
*/
function test() {
// Single line comment
return true;
}`;
const searchContent = `/**
* This is a comment
* that spans multiple lines
*/`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
});

View file

@ -1,203 +0,0 @@
/**
* Represents a basic match result with start and end character positions
*/
interface BasicMatchResult {
/** The starting character index of the match in the file content */
startIndex: number;
/** The ending character index of the match in the file content */
endIndex: number;
}
/**
* Represents a match result with start and end character positions
*/
export interface SearchMatchResult extends BasicMatchResult {
/** The name of the strategy that successfully matched */
strategyName: string;
}
/**
* Strategy function type for finding matches
*/
type MatchStrategy = (
fileContent: string,
searchContent: string,
) => BasicMatchResult | null;
/**
* Exact string matching strategy
*/
function exactMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
};
}
return null;
}
/**
* Trimmed content matching strategy
* Finds content where the search content (when trimmed) matches content in the file,
* and returns the span that includes the file content's whitespace
*/
function trimmedMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const trimmedSearchContent = searchContent.trim();
// Don't apply if search content has no leading/trailing whitespace to trim
if (trimmedSearchContent === searchContent) {
return null;
}
// Don't match if trimmed content is empty
if (trimmedSearchContent === "") {
return null;
}
// Look for the trimmed content in the file
const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedContentIndex === -1) {
return null;
}
// Find the boundaries that include surrounding whitespace (but not newlines)
// Look backwards for horizontal whitespace (spaces and tabs)
let startIndex = trimmedContentIndex;
while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) {
startIndex--;
}
// Look forwards for horizontal whitespace (spaces and tabs)
let endIndex = trimmedContentIndex + trimmedSearchContent.length;
while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) {
endIndex++;
}
return {
startIndex,
endIndex,
};
}
/**
* Whitespace-ignored matching strategy
* Removes all whitespace from both content and search, then finds the match
*/
function whitespaceIgnoredMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
// Remove all whitespace (spaces, tabs, newlines, etc.)
const strippedFileContent = fileContent.replace(/\s/g, "");
const strippedSearchContent = searchContent.replace(/\s/g, "");
if (strippedSearchContent === "") {
return null; // Empty search after stripping whitespace
}
const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
if (strippedIndex === -1) {
return null;
}
// Map the stripped position back to the original file content
let originalStartIndex = 0;
let strippedCharCount = 0;
// Find the original position by counting non-whitespace characters
for (let i = 0; i < fileContent.length; i++) {
if (strippedCharCount === strippedIndex) {
originalStartIndex = i;
break;
}
if (!/\s/.test(fileContent[i])) {
strippedCharCount++;
}
}
// Find the end position by counting the length of the search content
let originalEndIndex = originalStartIndex;
let matchedChars = 0;
for (
let i = originalStartIndex;
i < fileContent.length && matchedChars < strippedSearchContent.length;
i++
) {
if (!/\s/.test(fileContent[i])) {
matchedChars++;
}
originalEndIndex = i + 1;
}
return {
startIndex: originalStartIndex,
endIndex: originalEndIndex,
};
}
/**
* Ordered list of matching strategies to try with their names
*/
const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
];
/**
* Find the exact match position for search content in file content.
* Uses multiple matching strategies in order of preference.
*
* Matching Strategy:
* 1. If search content is empty, matches at the beginning of file (position 0)
* 2. Try each matching strategy in order until one succeeds
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @param config - Configuration options for matching behavior
* @returns Match result with character positions, or null if no match found
*/
export function findSearchMatch(
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
// Handle truly empty search content
if (searchContent === "") {
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Handle whitespace-only search content that trims to empty
const trimmedSearchContent = searchContent.trim();
if (trimmedSearchContent === "") {
// Check if the whitespace-only search content has an exact match first
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
strategyName: "exactMatch",
};
}
// If no exact match for whitespace-only content, treat as empty search
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Try each matching strategy in order
for (const { strategy, name } of matchingStrategies) {
const result = strategy(fileContent, searchContent);
if (result !== null) {
return { ...result, strategyName: name };
}
}
return null;
}

View file

@ -1,390 +0,0 @@
import {
parseAllSearchReplaceBlocks,
parseSearchReplaceBlock,
} from "./parseSearchReplaceBlock";
describe("parseSearchReplaceBlock", () => {
describe("Complete blocks", () => {
it("should parse a complete basic search/replace block", () => {
const content = `------- SEARCH
reset() {
this.result = 0;
return this;
}
=======
// Resets the calculator result to 0 and returns the instance for method chaining
reset() {
this.result = 0;
return this;
}
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe(`reset() {
this.result = 0;
return this;
}`);
expect(result.replaceContent)
.toBe(`// Resets the calculator result to 0 and returns the instance for method chaining
reset() {
this.result = 0;
return this;
}`);
expect(result.error).toBeUndefined();
});
it("should handle different marker lengths", () => {
const content = `------- SEARCH
old content
=========
new content
+++++++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("old content");
expect(result.replaceContent).toBe("new content");
});
it("should handle empty search content", () => {
const content = `------- SEARCH
=======
new content
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("");
expect(result.replaceContent).toBe("new content");
});
it("should handle empty replace content (deletion)", () => {
const content = `------- SEARCH
old content to delete
=======
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("old content to delete");
expect(result.replaceContent).toBe("");
});
it("should handle both empty search and replace content", () => {
const content = `------- SEARCH
=======
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("");
expect(result.replaceContent).toBe("");
});
});
describe("Incomplete blocks", () => {
it("should handle incomplete search block", () => {
const content = `------- SEARCH
some content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe("some content");
expect(result.replaceContent).toBe("");
expect(result.error).toBeUndefined();
});
it("should handle incomplete replace block", () => {
const content = `------- SEARCH
old content
=======
new content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe("old content");
expect(result.replaceContent).toBe("new content");
expect(result.error).toBeUndefined();
});
});
describe("Error cases", () => {
it("should error on search end without start", () => {
const content = `=======
some content
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.error).toBe(
"Found search block end marker without matching start marker",
);
});
it("should error on replace end without replace start", () => {
const content = `+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.error).toBe(
"Found replace block end marker without matching replace start marker",
);
});
});
describe("Regex pattern validation", () => {
it("should match various search start patterns", () => {
const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"];
patterns.forEach((pattern) => {
const content = `${pattern}
content
=======
replacement
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should match various search end patterns", () => {
const patterns = ["===", "=======", "=============="];
patterns.forEach((pattern) => {
const content = `------- SEARCH
content
${pattern}
replacement
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should match various replace end patterns", () => {
const patterns = [
"+++ REPLACE",
"+++++++ REPLACE",
"+++++++++++ REPLACE",
];
patterns.forEach((pattern) => {
const content = `------- SEARCH
content
=======
replacement
${pattern}`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should not match invalid patterns", () => {
const invalidPatterns = [
"-- SEARCH", // Too few dashes
"SEARCH", // No markers
"== SEARCH", // Wrong markers
"=== REPLACE", // Wrong end marker
"++++ SEARCH", // Wrong markers for search
];
invalidPatterns.forEach((pattern) => {
const content = `${pattern}
content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe(""); // Should not enter search mode
});
});
});
});
describe("parseAllSearchReplaceBlocks", () => {
it("should parse multiple complete blocks", () => {
const content = `------- SEARCH
old code 1
=======
new code 1
+++++++ REPLACE
------- SEARCH
old code 2
=======
new code 2
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("old code 1");
expect(blocks[0].replaceContent).toBe("new code 1");
expect(blocks[1].searchContent).toBe("old code 2");
expect(blocks[1].replaceContent).toBe("new code 2");
});
it("should handle blocks with different content", () => {
const content = `------- SEARCH
function old() {
return 1;
}
=======
function new() {
return 2;
}
+++++++ REPLACE
------- SEARCH
const x = 'old';
=======
const x = 'new';
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe(`function old() {
return 1;
}`);
expect(blocks[0].replaceContent).toBe(`function new() {
return 2;
}`);
expect(blocks[1].searchContent).toBe(`const x = 'old';`);
expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
});
it("should handle deletion blocks (empty replace content)", () => {
const content = `------- SEARCH
code to keep
=======
modified code
+++++++ REPLACE
------- SEARCH
code to delete
=======
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("code to keep");
expect(blocks[0].replaceContent).toBe("modified code");
expect(blocks[1].searchContent).toBe("code to delete");
expect(blocks[1].replaceContent).toBe(""); // Deletion
});
it("should handle insertion blocks (empty search content)", () => {
const content = `------- SEARCH
existing code
=======
modified existing code
+++++++ REPLACE
------- SEARCH
=======
new code to insert
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("existing code");
expect(blocks[0].replaceContent).toBe("modified existing code");
expect(blocks[1].searchContent).toBe(""); // Insertion
expect(blocks[1].replaceContent).toBe("new code to insert");
});
it("should skip incomplete blocks", () => {
const content = `------- SEARCH
incomplete block
------- SEARCH
complete block
=======
replacement
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(1);
expect(blocks[0].searchContent).toBe("complete block");
expect(blocks[0].replaceContent).toBe("replacement");
});
it("should handle single block", () => {
const content = `------- SEARCH
single block
=======
replacement
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(1);
expect(blocks[0].searchContent).toBe("single block");
expect(blocks[0].replaceContent).toBe("replacement");
});
it("should return empty array when no complete blocks found", () => {
const content = `------- SEARCH
incomplete
=======
missing replace marker`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(0);
});
it("should handle blocks with extra content between them", () => {
const content = `Some other content here
------- SEARCH
block 1
=======
replacement 1
+++++++ REPLACE
More content in between
------- SEARCH
block 2
=======
replacement 2
+++++++ REPLACE
Trailing content`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("block 1");
expect(blocks[0].replaceContent).toBe("replacement 1");
expect(blocks[1].searchContent).toBe("block 2");
expect(blocks[1].replaceContent).toBe("replacement 2");
});
it("should throw error for malformed blocks", () => {
const content = `------- SEARCH
content
+++++++ REPLACE`; // Missing =======
expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
"Found replace block end marker without matching replace start marker",
);
});
});

View file

@ -1,147 +0,0 @@
// Search and replace block markers using flexible regex patterns
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
export interface SearchReplaceBlockResult {
/** Whether a complete search/replace block has been parsed */
isComplete: boolean;
/** The content to search for in the file */
searchContent?: string;
/** The content to replace the search content with */
replaceContent?: string;
/** Error message if parsing failed */
error?: string;
}
/**
* Parses a search and replace block from content.
*
* Expected format:
* ------- SEARCH
* [content to find]
* =======
* [content to replace with]
* +++++++ REPLACE
*
* @param content - The content to parse
* @returns ParseResult with completion status and extracted content
*/
export function parseSearchReplaceBlock(
content: string,
): SearchReplaceBlockResult {
const lines = content.split("\n");
let currentSearchContent = "";
let currentReplaceContent = "";
let inSearch = false;
let inReplace = false;
for (const line of lines) {
if (SEARCH_BLOCK_START_REGEX.test(line)) {
inSearch = true;
inReplace = false;
currentSearchContent = "";
currentReplaceContent = "";
continue;
}
if (SEARCH_BLOCK_END_REGEX.test(line)) {
if (!inSearch) {
return {
isComplete: false,
error: "Found search block end marker without matching start marker",
};
}
inSearch = false;
inReplace = true;
continue;
}
if (REPLACE_BLOCK_END_REGEX.test(line)) {
if (!inReplace) {
return {
isComplete: false,
error:
"Found replace block end marker without matching replace start marker",
};
}
// Complete block found
return {
isComplete: true,
searchContent: currentSearchContent.trim(),
replaceContent: currentReplaceContent.trim(),
};
}
// Accumulate content
if (inSearch) {
currentSearchContent += line + "\n";
} else if (inReplace) {
currentReplaceContent += line + "\n";
}
}
// Block is not yet complete
return {
isComplete: false,
searchContent: currentSearchContent.trim(),
replaceContent: currentReplaceContent.trim(),
};
}
/**
* Parses all complete search and replace blocks from content.
*
* @param content - The content containing multiple search/replace blocks
* @returns Array of complete search/replace blocks found
* @throws Error if any malformed blocks are encountered
*/
export function parseAllSearchReplaceBlocks(
content: string,
): SearchReplaceBlockResult[] {
const blocks: SearchReplaceBlockResult[] = [];
const lines = content.split("\n");
let currentBlockLines: string[] = [];
let inBlock = false;
for (const line of lines) {
if (SEARCH_BLOCK_START_REGEX.test(line)) {
// Start of new block
if (inBlock && currentBlockLines.length > 0) {
// Process previous incomplete block if any
const blockContent = currentBlockLines.join("\n");
const result = parseSearchReplaceBlock(blockContent);
if (result.isComplete) {
blocks.push(result);
} else if (result.error) {
// Fail fast on any parsing error
throw new Error(result.error);
}
// If incomplete but no error, it's just a partial block - continue processing
}
currentBlockLines = [line];
inBlock = true;
} else if (inBlock) {
currentBlockLines.push(line);
// Check if this line completes the current block
if (REPLACE_BLOCK_END_REGEX.test(line)) {
const blockContent = currentBlockLines.join("\n");
const result = parseSearchReplaceBlock(blockContent);
if (result.isComplete) {
blocks.push(result);
} else if (result.error) {
// Fail fast on any parsing error
throw new Error(result.error);
}
currentBlockLines = [];
inBlock = false;
}
}
}
return blocks;
}

View file

@ -1,7 +1,6 @@
export enum BuiltInToolNames {
ReadFile = "read_file",
EditExistingFile = "edit_existing_file",
SearchAndReplaceInFile = "search_and_replace_in_file",
SingleFindAndReplace = "single_find_and_replace",
MultiEdit = "multi_edit",
ReadCurrentlyOpenFile = "read_currently_open_file",
@ -26,7 +25,6 @@ export const BUILT_IN_GROUP_NAME = "Built-In";
export const CLIENT_TOOLS_IMPLS = [
BuiltInToolNames.EditExistingFile,
BuiltInToolNames.SearchAndReplaceInFile,
BuiltInToolNames.SingleFindAndReplace,
BuiltInToolNames.MultiEdit,
];

View file

@ -1,13 +1,15 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
export interface EditToolArgs {
filepath: string;
changes: string;
}
export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION =
"Note this tool CANNOT be called in parallel with other tools.";
const CHANGES_DESCRIPTION =
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";
@ -22,7 +24,7 @@ export const editFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.EditExistingFile,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "changes"],

View file

@ -11,7 +11,6 @@ export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
export { readFileTool } from "./readFile";
export { requestRuleTool } from "./requestRule";
export { runTerminalCommandTool } from "./runTerminalCommand";
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
export { searchWebTool } from "./searchWeb";
export { singleFindAndReplaceTool } from "./singleFindAndReplace";
export { viewDiffTool } from "./viewDiff";

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
export interface EditOperation {
old_string: string;
@ -54,6 +55,7 @@ CRITICAL REQUIREMENTS:
1. All edits follow the same requirements as the single find and replace tool
2. The edits are atomic - either all succeed or none are applied
3. Plan your edits carefully to avoid conflicts between sequential operations
4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
WARNING:

View file

@ -1,112 +0,0 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface SearchAndReplaceInFileArgs {
filepath: string;
diffs: string[];
}
// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE`;
const SEARCH_AND_REPLACE_RULES = `Critical rules:
1. SEARCH content must match the associated file section to find EXACTLY:
* Match character-for-character including whitespace, indentation, line endings
* Include all comments, docstrings, etc.
2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
* 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. **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.
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]
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
7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`;
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
\`\`\`
${SEARCH_AND_REPLACE_RULES}
Usage:
\`\`\`
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
\`\`\`
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`;
/**
* This tool is in an experimental state.
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
*/
export const searchAndReplaceInFileTool: Tool = {
type: "function",
displayTitle: "Edit File",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
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}`,
parameters: {
type: "object",
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description: `The path of the file to modify, relative to the root of the workspace.`,
},
diffs: {
type: "array",
items: {
type: "string",
},
description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION,
},
},
},
},
systemMessageDescription: {
prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
Each block should follow this format:
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
${SEARCH_AND_REPLACE_RULES}
For example, you could respond with:`,
exampleArgs: [
["filepath", "path/to/file.ts"],
[
"diffs",
`[
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}",
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}"
]`,
],
],
},
defaultToolPolicy: "allowedWithPermission",
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
export interface SingleFindAndReplaceArgs {
filepath: string;
@ -38,6 +39,8 @@ unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
a larger string with more surrounding context to make it unique or use
\`replace_all\` to change every instance of \`old_string\`.

View file

@ -36,8 +36,6 @@ export const getConfigDependentToolDefinitions = (
);
}
// OLD SEARCH AND REPLACE IS CURRENTLY NOT USED
// toolDefinitions.searchAndReplaceInFileTool
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
tools.push(toolDefinitions.multiEditTool);
} else {

View file

@ -34,23 +34,6 @@ function FunctionSpecificToolCallDiv({
historyIndex={historyIndex}
/>
);
case BuiltInToolNames.SearchAndReplaceInFile:
const changes = args?.diffs
? Array.isArray(args.diffs)
? args.diffs?.join("\n\n---\n\n")
: args.diffs
: "";
return (
<EditFile
showToolCallStatusIcon={true}
status={toolCallState.status}
relativeFilePath={args?.filepath ?? ""}
changes={changes}
toolCallId={toolCall.id}
historyIndex={historyIndex}
/>
);
case BuiltInToolNames.SingleFindAndReplace:
const edits: EditOperation[] = [
{

View file

@ -55,7 +55,6 @@ export function ToolCallDiv({
// All the info from args is displayed here
// But we'd need a nicer place to put the truncate button and the X icon when tool call fails
if (
functionName === BuiltInToolNames.SearchAndReplaceInFile ||
functionName === BuiltInToolNames.SingleFindAndReplace ||
functionName === BuiltInToolNames.MultiEdit
) {

View file

@ -50,10 +50,7 @@ import { findChatHistoryItemByToolCallId, findToolCallById } from "../util";
function filterMultipleEditToolCalls(
toolCalls: ToolCallDelta[],
): ToolCallDelta[] {
const editToolNames = [
BuiltInToolNames.EditExistingFile,
BuiltInToolNames.SearchAndReplaceInFile,
];
const editToolNames = [BuiltInToolNames.EditExistingFile];
let hasSeenEditTool = false;
return toolCalls.filter((toolCall) => {

View file

@ -16,8 +16,7 @@ export async function enhanceParsedArgs(
let enhancedArgs = { ...currentArgs };
if (
(toolName === BuiltInToolNames.SingleFindAndReplace ||
toolName === BuiltInToolNames.MultiEdit ||
toolName === BuiltInToolNames.SearchAndReplaceInFile) &&
toolName === BuiltInToolNames.MultiEdit) &&
currentArgs?.filepath &&
!currentArgs?.editingFileContents
) {

View file

@ -4,7 +4,6 @@ import { IIdeMessenger } from "../../context/IdeMessenger";
import { AppThunkDispatch, RootState } from "../../redux/store";
import { editToolImpl } from "./editImpl";
import { multiEditImpl } from "./multiEditImpl";
import { searchReplaceToolImpl } from "./searchReplaceImpl";
import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl";
export interface ClientToolExtras {
@ -39,9 +38,6 @@ export async function callClientTool(
case BuiltInToolNames.EditExistingFile:
output = await editToolImpl(parsedArgs, toolCall.id, extras);
break;
case BuiltInToolNames.SearchAndReplaceInFile:
output = await searchReplaceToolImpl(parsedArgs, toolCall.id, extras);
break;
case BuiltInToolNames.SingleFindAndReplace:
output = await singleFindAndReplaceImpl(
parsedArgs,

View file

@ -1,695 +0,0 @@
import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolExtras } from "./callClientTool";
import { searchReplaceToolImpl } from "./searchReplaceImpl";
// Mock the dependencies
vi.mock("core/edit/searchAndReplace/findSearchMatch");
vi.mock("core/edit/searchAndReplace/parseSearchReplaceBlock");
vi.mock("core/util/ideUtils");
vi.mock("uuid", () => ({
v4: vi.fn(() => "test-stream-id"),
}));
vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({
applyForEditTool: vi.fn(),
}));
const mockFindSearchMatch = vi.mocked(findSearchMatch);
const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks);
const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir);
const mockApplyForEditTool = vi.mocked(applyForEditTool);
describe("searchReplaceToolImpl", () => {
let mockExtras: ClientToolExtras;
let mockIdeMessenger: any;
beforeEach(() => {
// Reset all mocks
vi.clearAllMocks();
// Create mock IDE messenger
mockIdeMessenger = {
ide: {
readFile: vi.fn(),
},
request: vi.fn(),
};
// Create mock extras
mockExtras = {
ideMessenger: mockIdeMessenger,
getState: vi.fn<any>(() => ({
config: {
config: {
allowAnonymousTelemetry: false,
},
},
})),
dispatch: vi.fn(),
};
});
describe("basic validation", () => {
it("should throw error when file does not exist", async () => {
mockResolveRelativePathInDir.mockResolvedValue(undefined);
await expect(
searchReplaceToolImpl(
{ 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 in first diff", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([]);
await expect(
searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["invalid diff content"] },
"tool-call-id",
mockExtras,
),
).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");
});
});
describe("single block replacement", () => {
it("should successfully apply 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",
});
const result = await searchReplaceToolImpl(
{ 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(mockApplyForEditTool).toHaveBeenCalledWith({
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",
});
const result = await searchReplaceToolImpl(
{ 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(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.js",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
});
describe("multiple block replacement", () => {
it("should successfully apply multiple search/replace blocks sequentially", 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
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "const a = 1;",
replaceContent: "const a = 100;",
},
{
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",
});
const result = await searchReplaceToolImpl(
{ filepath: "test.js", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
// Verify the result
expect(result).toEqual({
respondImmediately: false,
output: undefined,
});
// Verify findSearchMatch was called twice with updated content
expect(mockFindSearchMatch).toHaveBeenCalledTimes(2);
expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
1,
originalContent,
"const a = 1;",
);
expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
2,
contentAfterFirstReplacement,
"const b = 2;",
);
// Verify final applyToFile call
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.js",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
});
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",
});
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(mockApplyForEditTool).toHaveBeenCalledWith({
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
remove this line
keep this too`;
const expectedFinalContent = `keep this
keep this too`;
// Setup mocks
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "remove this line",
replaceContent: "",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
mockFindSearchMatch.mockReturnValue({
startIndex: 10, // Position of "remove this line"
endIndex: 26, // End of "remove this line"
strategyName: "exactMatch",
});
const result = await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
expect(result).toEqual({
respondImmediately: false,
output: undefined,
});
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
it("should handle undefined replaceContent as empty string", async () => {
const originalContent = "line1\nline2\nline3";
const expectedFinalContent = "line1\n\nline3";
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "line2",
replaceContent: undefined, // undefined should be treated as empty string
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
mockFindSearchMatch.mockReturnValue({
startIndex: 6,
endIndex: 11,
strategyName: "exactMatch",
});
await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
});
describe("error handling", () => {
it("should throw error when search content is not found", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "nonexistent content",
replaceContent: "replacement",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue("some file content");
mockFindSearchMatch.mockReturnValue(null); // Search content not found
await expect(
searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
),
).rejects.toThrow(
"Search content not found in block 1:\nnonexistent content",
);
});
it("should throw error when search content is not found in second block", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "found content",
replaceContent: "replacement1",
},
{
isComplete: true,
searchContent: "missing content",
replaceContent: "replacement2",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue(
"found content and other stuff",
);
// First search succeeds, second fails
mockFindSearchMatch
.mockReturnValueOnce({
startIndex: 0,
endIndex: 13,
strategyName: "exactMatch",
})
.mockReturnValueOnce(null); // Second search fails
await expect(
searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
),
).rejects.toThrow(
"Search content not found in block 2:\nmissing content",
);
});
it("should handle file read errors", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "content",
replaceContent: "replacement",
},
]);
mockIdeMessenger.ide.readFile.mockRejectedValue(
new Error("File read error"),
);
await expect(
searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
),
).rejects.toThrow("Failed to apply search and replace: File read error");
});
});
describe("edge cases", () => {
it("should handle empty search content", async () => {
const originalContent = "existing content";
const expectedFinalContent = "new contentexisting content";
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "",
replaceContent: "new content",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
mockFindSearchMatch.mockReturnValue({
startIndex: 0, // Empty search matches at beginning
endIndex: 0,
strategyName: "exactMatch",
});
await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
it("should handle whole file replacement", async () => {
const originalContent = "old file content";
const expectedFinalContent = "completely new content";
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: originalContent,
replaceContent: "completely new content",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
mockFindSearchMatch.mockReturnValue({
startIndex: 0,
endIndex: originalContent.length,
strategyName: "exactMatch",
});
await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
});
describe("dependency integration", () => {
it("should call all dependencies with correct parameters", async () => {
const originalContent = "test content";
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "test",
replaceContent: "updated",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
mockFindSearchMatch.mockReturnValue({
startIndex: 0,
endIndex: 4,
strategyName: "exactMatch",
});
await searchReplaceToolImpl(
{ filepath: "relative/test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
// Verify all dependencies were called correctly
expect(mockResolveRelativePathInDir).toHaveBeenCalledWith(
"relative/test.txt",
mockIdeMessenger.ide,
);
expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledWith(
"mock diff content",
);
expect(mockIdeMessenger.ide.readFile).toHaveBeenCalledWith(
"/resolved/path/test.txt",
);
expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test");
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: "updated content",
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
toolCallId: "tool-call-id",
isSearchAndReplace: true,
});
});
});
});

View file

@ -1,107 +0,0 @@
import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import posthog from "posthog-js";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export const searchReplaceToolImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
const { filepath, diffs, editingFileContents } = args;
const state = extras.getState();
const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
const streamId = uuid();
// Resolve the file path
const resolvedFilepath = await resolveRelativePathInDir(
filepath,
extras.ideMessenger.ide,
);
if (!resolvedFilepath) {
throw new Error(`File ${filepath} does not exist`);
}
// 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 (allBlocks.length === 0) {
throw new Error("No complete search/replace blocks found in any diffs");
}
try {
// Read the current file content
const originalContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedFilepath));
let currentContent = originalContent;
// Apply all replacements sequentially to build the final content
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
const match = findSearchMatch(currentContent, searchContent || "");
// Because we don't have access to use hooks, we check `allowAnonymousTelemetry`
// directly rather than using `CustomPostHogProvider`
if (allowAnonymousTelemetry) {
// Capture telemetry for tool calls
posthog.capture("find_replace_match_result", {
matchStrategy: match?.strategyName ?? "noMatch",
});
}
if (!match) {
throw new Error(
`Search content not found in block ${i + 1}:\n${searchContent}`,
);
}
// Apply the replacement
currentContent =
currentContent.substring(0, match.startIndex) +
(replaceContent || "") +
currentContent.substring(match.endIndex);
}
// Single applyToFile call with all accumulated changes
// This works becaues of our logic in `applyCodeBlock` that determines
// that the full file rewrite here can be applied instantly, so the diff
// lines are generated with meyers diff and streamed instantaneously
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: currentContent,
filepath: resolvedFilepath,
isSearchAndReplace: true,
}),
);
// Return success - applyToFile will handle the completion state
return {
respondImmediately: false, // Let apply state handle completion
output: undefined,
};
} catch (error) {
throw new Error(
`Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`,
);
}
};

View file

@ -12,9 +12,6 @@ function migrateToolPolicies(dispatch: AppDispatch) {
const toFromMap: Record<string, string[]> = {
[BuiltInToolNames.ReadFile]: ["builtin_read_file"],
[BuiltInToolNames.EditExistingFile]: ["builtin_edit_existing_file"],
[BuiltInToolNames.SearchAndReplaceInFile]: [
"builtin_search_and_replace_in_file",
],
[BuiltInToolNames.ReadCurrentlyOpenFile]: [
"builtin_read_currently_open_file",
],