Merge pull request #7875 from continuedev/dallin/search-replace-fallbacks-v2

feat: restore trimmed/whitespace search and replace fallbacks
This commit is contained in:
Dallin Romney 2025-09-22 13:03:54 -07:00 • committed by GitHub
commit 69102edff3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
38 changed files with 2323 additions and 2020 deletions

View file

@ -280,11 +280,6 @@ declare global {
replacement: string;
}
export interface ContinueError {
title: string;
message: string;
}
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}

View file

@ -0,0 +1,252 @@
import { describe, expect, it } from "vitest";
import { ContinueErrorReason } from "../../util/errors";
import { executeFindAndReplace } from "./performReplace";
describe("executeFindAndReplace", () => {
describe("normal cases", () => {
it("should replace single occurrence by default", () => {
const content = "Hello world\nThis is a test file\nGoodbye";
const result = executeFindAndReplace(content, "Hello", "Hi", false);
expect(result).toBe("Hi world\nThis is a test file\nGoodbye");
});
it("should replace single occurrence when replaceAll is false", () => {
const content = "Hello world\nHello again";
const result = executeFindAndReplace(
content,
"Hello world",
"Hi world",
false,
);
expect(result).toBe("Hi world\nHello again");
});
it("should replace all occurrences when replaceAll is true", () => {
const content = "Hello world\nHello again\nHello there";
const result = executeFindAndReplace(content, "Hello", "Hi", true);
expect(result).toBe("Hi world\nHi again\nHi there");
});
it("should handle empty new string (deletion)", () => {
const content = "Hello world";
const result = executeFindAndReplace(content, "Hello ", "", false);
expect(result).toBe("world");
});
it("should handle empty old string replacement (insertion at start)", () => {
const content = "";
const result = executeFindAndReplace(content, "", "Hello world", false);
expect(result).toBe("Hello world");
});
it("should preserve whitespace and indentation", () => {
const content =
"function test() {\n const value = 'old';\n return value;\n}";
const result = executeFindAndReplace(
content,
" const value = 'old';",
" const value = 'new';",
false,
);
expect(result).toBe(
"function test() {\n const value = 'new';\n return value;\n}",
);
});
it("should handle multiline strings", () => {
const content = "line1\nline2\nline3";
const result = executeFindAndReplace(
content,
"line1\nline2",
"newline1\nnewline2",
false,
);
expect(result).toBe("newline1\nnewline2\nline3");
});
});
describe("special character handling", () => {
it("should handle regex special characters in old string", () => {
const content = "const regex = /[a-z]+/g;";
const result = executeFindAndReplace(
content,
"/[a-z]+/g",
"/[A-Z]+/g",
false,
);
expect(result).toBe("const regex = /[A-Z]+/g;");
});
it("should handle dollar signs in strings", () => {
const content = 'const text = "Hello $world"';
const result = executeFindAndReplace(
content,
'"Hello $world"',
'"Hi $universe"',
false,
);
expect(result).toBe('const text = "Hi $universe"');
});
it("should handle backslashes", () => {
const content = 'const path = "C:\\Users\\test"';
const result = executeFindAndReplace(
content,
"C:\\Users\\test",
"D:\\Users\\test",
false,
);
expect(result).toBe('const path = "D:\\Users\\test"');
});
it("should handle parentheses", () => {
const content = "function test() { return 'old'; }";
const result = executeFindAndReplace(
content,
"() { return 'old'; }",
"() { return 'new'; }",
false,
);
expect(result).toBe("function test() { return 'new'; }");
});
it("should handle square brackets", () => {
const content = "const arr = [1, 2, 3];";
const result = executeFindAndReplace(
content,
"[1, 2, 3]",
"[4, 5, 6]",
false,
);
expect(result).toBe("const arr = [4, 5, 6];");
});
});
describe("replaceAll behavior", () => {
it("should replace all occurrences including partial matches", () => {
const content = "test testing tested test";
const result = executeFindAndReplace(content, "test", "exam", true);
expect(result).toBe("exam examing examed exam");
});
it("should replace all occurrences with empty string", () => {
const content = "remove this remove that remove everything";
const result = executeFindAndReplace(content, "remove ", "", true);
expect(result).toBe("this that everything");
});
it("should handle overlapping patterns correctly", () => {
const content = "aaaa";
const result = executeFindAndReplace(content, "aa", "b", true);
expect(result).toBe("bb");
});
});
describe("error cases", () => {
it("should throw error when string not found", () => {
const content = "Hello world";
expect(() => {
executeFindAndReplace(content, "xyz", "abc", false);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error with edit context when string not found", () => {
const content = "Hello world";
expect(() => {
executeFindAndReplace(content, "xyz", "abc", false, 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error when multiple occurrences exist and replaceAll is false", () => {
const content = "Hello world\nHello again\nHello there";
expect(() => {
executeFindAndReplace(content, "Hello", "Hi", false);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
it("should throw error with edit context for multiple occurrences", () => {
const content = "test test test";
expect(() => {
executeFindAndReplace(content, "test", "exam", false, 1);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
});
describe("edge cases", () => {
it("should handle single character replacement", () => {
const content = "a b c";
const result = executeFindAndReplace(content, "b", "x", false);
expect(result).toBe("a x c");
});
it("should handle very long strings", () => {
const longString = "a".repeat(10000);
const content = `start${longString}end`;
const result = executeFindAndReplace(content, longString, "short", false);
expect(result).toBe("startshortend");
});
it("should handle strings at beginning of content", () => {
const content = "start middle end";
const result = executeFindAndReplace(content, "start", "begin", false);
expect(result).toBe("begin middle end");
});
it("should handle strings at end of content", () => {
const content = "start middle end";
const result = executeFindAndReplace(content, "end", "finish", false);
expect(result).toBe("start middle finish");
});
it("should handle entire content replacement", () => {
const content = "replace everything";
const result = executeFindAndReplace(
content,
"replace everything",
"new content",
false,
);
expect(result).toBe("new content");
});
});
});

View file

@ -0,0 +1,53 @@
import { ContinueError, ContinueErrorReason } from "../../util/errors";
export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
"Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.";
/**
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: string,
newString: string,
index?: number,
): void {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (!oldString && oldString !== "") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingOldString,
`${context}old_string is required`,
);
}
if (newString === undefined) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingNewString,
`${context}new_string is required`,
);
}
if (oldString === newString) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
`${context}old_string and new_string must be different`,
);
}
}
export function trimEmptyLines({
lines,
fromEnd,
}: {
lines: string[];
fromEnd: boolean;
}): string[] {
lines = fromEnd ? lines.slice().reverse() : lines.slice();
const newLines: string[] = [];
let shouldContinueRemoving = true;
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (shouldContinueRemoving && line.trim() === "") continue;
shouldContinueRemoving = false;
newLines.push(line);
}
return fromEnd ? newLines.reverse() : newLines;
}

View file

@ -0,0 +1,151 @@
import { describe, expect, it } from "vitest";
import { ContinueErrorReason } from "../../util/errors";
import { trimEmptyLines, validateSingleEdit } from "./findAndReplaceUtils";
describe("validateSingleEdit", () => {
describe("valid inputs", () => {
it("should not throw for valid non-empty strings", () => {
expect(() => {
validateSingleEdit("old", "new");
}).not.toThrow();
});
it("should allow empty old_string for file creation", () => {
expect(() => {
validateSingleEdit("", "new content");
}).not.toThrow();
});
it("should allow empty new_string for deletion", () => {
expect(() => {
validateSingleEdit("delete me", "");
}).not.toThrow();
});
it("should allow multiline strings", () => {
expect(() => {
validateSingleEdit("line1\nline2", "newline1\nnewline2");
}).not.toThrow();
});
it("should allow special characters", () => {
expect(() => {
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
}).not.toThrow();
});
});
describe("invalid inputs", () => {
it("should throw error when old_string is null", () => {
expect(() => {
validateSingleEdit(null as any, "new");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error when old_string is undefined", () => {
expect(() => {
validateSingleEdit(undefined as any, "new");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error when new_string is undefined", () => {
expect(() => {
validateSingleEdit("old", undefined as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should throw error when old_string and new_string are identical", () => {
expect(() => {
validateSingleEdit("same", "same");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error when both are empty strings", () => {
expect(() => {
validateSingleEdit("", "");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
});
describe("error messages with context", () => {
it("should include edit number in error messages when index provided", () => {
expect(() => {
validateSingleEdit(null as any, "new", 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should include edit number for new_string errors", () => {
expect(() => {
validateSingleEdit("old", undefined as any, 0);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should include edit number for identical strings error", () => {
expect(() => {
validateSingleEdit("same", "same", 4);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should not include context when index not provided", () => {
expect(() => {
validateSingleEdit("same", "same");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
});
});
describe("trimEmptyLines", () => {
it("trims leading empty lines from start", () => {
const input = ["", "", "a", "", "b"];
const result = trimEmptyLines({ lines: input, fromEnd: false });
expect(result).toEqual(["a", "", "b"]);
});
it("trims trailing empty lines from end", () => {
const input = ["a", "", "b", "", ""];
const result = trimEmptyLines({ lines: input, fromEnd: true });
expect(result).toEqual(["a", "", "b"]);
});
it("returns empty array when all lines are empty", () => {
const input = ["", "", ""];
const result = trimEmptyLines({ lines: input, fromEnd: false });
expect(result).toEqual([]);
});
});

View file

@ -4,7 +4,7 @@
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 */
/** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/
endIndex: number;
}
@ -81,32 +81,38 @@ function whitespaceIgnoredMatch(
}
// Map the stripped position back to the original file content
let originalStartIndex = 0;
let originalStartIndex = -1;
let strippedCharCount = 0;
// Find the original position by counting non-whitespace characters
// Find the original start 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])) {
if (strippedCharCount === strippedIndex) {
originalStartIndex = i;
break;
}
strippedCharCount++;
}
}
// Find the end position by counting the length of the search content
let originalEndIndex = originalStartIndex;
let matchedChars = 0;
if (originalStartIndex === -1) {
return null; // Should not happen if strippedIndex was valid
}
for (
let i = originalStartIndex;
i < fileContent.length && matchedChars < strippedSearchContent.length;
i++
) {
// Find the end position by counting through all characters (including whitespace)
// that correspond to the stripped search content length
let originalEndIndex = originalStartIndex;
let matchedNonWhitespaceChars = 0;
for (let i = originalStartIndex; i < fileContent.length; i++) {
if (!/\s/.test(fileContent[i])) {
matchedChars++;
matchedNonWhitespaceChars++;
if (matchedNonWhitespaceChars === strippedSearchContent.length) {
originalEndIndex = i + 1;
break;
}
}
// Always update end index to include current position (whether whitespace or not)
originalEndIndex = i + 1;
}
@ -118,6 +124,7 @@ function whitespaceIgnoredMatch(
/**
* Calculate the Jaro similarity between two strings
* TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match
*/
function jaroSimilarity(s1: string, s2: string): number {
if (s1 === s2) return 1.0;
@ -278,7 +285,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
{ strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
// { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
];
/**
@ -315,3 +322,58 @@ export function findSearchMatch(
return null;
}
/**
* Find all matches for search content in file content.
* Uses the same matching strategies as findSearchMatch, applied iteratively.
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @returns Array of match results with character positions, empty array if no matches found
*/
export function findSearchMatches(
fileContent: string,
searchContent: string,
): SearchMatchResult[] {
const matches: SearchMatchResult[] = [];
// Special case: empty search string always matches at position 0
if (searchContent.trim() === "") {
return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }];
}
let remainingContent = fileContent;
let currentOffset = 0;
while (remainingContent.length > 0) {
const match = findSearchMatch(remainingContent, searchContent);
if (match === null) {
break;
}
// Adjust match positions to account for the current offset
const adjustedMatch: SearchMatchResult = {
startIndex: match.startIndex + currentOffset,
endIndex: match.endIndex + currentOffset,
strategyName: match.strategyName,
};
// Prevent infinite loops by ensuring we're making progress
// If the new match starts at or before the last match's start position, break
if (
matches.length > 0 &&
adjustedMatch.startIndex <= matches[matches.length - 1].startIndex
) {
break;
}
matches.push(adjustedMatch);
// Update offset and truncate content after the current match
currentOffset = adjustedMatch.endIndex;
remainingContent = fileContent.slice(currentOffset);
}
return matches;
}

View file

@ -0,0 +1,571 @@
import { describe, expect, it } from "vitest";
import { findSearchMatch } from "./findSearchMatch";
describe("findSearchMatch", () => {
describe("Empty search content", () => {
it("should return position 0 for empty string", () => {
const result = findSearchMatch("some file content", "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should return position 0 for whitespace-only string", () => {
const result = findSearchMatch("some file content", " \n\t ");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle empty file content with empty search", () => {
const result = findSearchMatch("", "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("Exact match strategy", () => {
it("should find exact match at beginning of file", () => {
const fileContent = "hello world";
const searchContent = "hello";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "exactMatch",
});
});
it("should find exact match in middle of file", () => {
const fileContent = "hello world test";
const searchContent = "world";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should find exact match at end of file", () => {
const fileContent = "hello world";
const searchContent = "world";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should find multi-line exact match", () => {
const fileContent = "line1\nline2\nline3";
const searchContent = "line2\nline3";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 17,
strategyName: "exactMatch",
});
});
it("should handle exact match with special characters", () => {
const fileContent = 'function test() { return "hello"; }';
const searchContent = '{ return "hello"; }';
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 16,
endIndex: 35,
strategyName: "exactMatch",
});
});
it("should find first occurrence when multiple matches exist", () => {
const fileContent = "test test test";
const searchContent = "test";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 4,
strategyName: "exactMatch",
});
});
it("should handle case-sensitive matching", () => {
const fileContent = "Hello World";
const searchContent = "hello";
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to case sensitivity, will fall through to other strategies
expect(result).toBeNull();
});
});
describe("Trimmed match strategy fallback", () => {
it("should find match when search content has leading/trailing whitespace", () => {
const fileContent = "hello world";
const searchContent = " hello ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "trimmedMatch",
});
});
it("should find match when search content has tabs and newlines", () => {
const fileContent = "function test() {}";
const searchContent = "\t\nfunction test()\n\t";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 15,
strategyName: "trimmedMatch",
});
});
it("should handle complex whitespace trimming", () => {
const fileContent = "const x = 5;";
const searchContent = " \n\t const x = 5; \t\n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 12,
strategyName: "trimmedMatch",
});
});
});
describe("Whitespace ignored strategy fallback", () => {
it("should match content with different whitespace formatting", () => {
const fileContent = "function test() {\n return true;\n}";
const searchContent = "function test(){return true;}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 34,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle mixed whitespace differences", () => {
const fileContent = "if (condition) {\n doSomething();\n}";
const searchContent = "if(condition){doSomething();}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 37,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match with tabs vs spaces differences", () => {
const fileContent = "function test() {\n\treturn 42;\n}";
const searchContent = "function test() {\n return 42;\n}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 31,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle partial matches within larger content", () => {
const fileContent = "before\nfunction test() {\n return true;\n}\nafter";
const searchContent = "function test(){return true;}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 7,
endIndex: 41,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should recognize empty search", () => {
const fileContent = "some content";
const searchContent = " \t\n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle complex nested structures with whitespace differences", () => {
const fileContent = `{
"key": "value",
"nested": {
"prop": 123
}
}`;
const searchContent = '{"key":"value","nested":{"prop":123}}';
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 55,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match content in middle of file with complex indentation", () => {
const fileContent = `import React from 'react';
function MyComponent() {
const handleClick = () => {
console.log('clicked');
};
return <button onClick={handleClick}>Click me</button>;
}
export default MyComponent;`;
const searchContent = `const handleClick=()=>{console.log('clicked');};`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 55,
endIndex: 115,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle matches with mixed line endings and special characters", () => {
const fileContent = `<!DOCTYPE html>\r\n<html>\r\n <body>\r\n <div id="app">\r\n <p>Hello & goodbye</p>\r\n </div>\r\n </body>\r\n</html>`;
const searchContent = `<divid="app"><p>Hello&goodbye</p></div>`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 39,
endIndex: 95,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match content surrounded by different types of whitespace", () => {
const fileContent = `\tconst data = {\n\t\tname: "John",\n\t\tage: 30,\n\t\taddress: {\n\t\t\tstreet: "Main St",\n\t\t\tcity: "NYC"\n\t\t}\n\t};`;
const searchContent = `address:{street:"MainSt",city:"NYC"}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 45,
endIndex: 96,
strategyName: "whitespaceIgnoredMatch",
});
});
// IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both
it("should handle unicode characters with whitespace differences", () => {
const fileContent = `const message = {\n greeting: "Hello 👋",\n emoji: "🚀",\n unicode: "café",\n symbol: "∑"\n};`;
const searchContent = `emoji:"🚀",unicode:"café",symbol:"∑"`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 44,
endIndex: 89,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match across multiple nested blocks with varying indentation", () => {
const fileContent = `class Calculator {\n add(a, b) {\n if (typeof a === 'number' && typeof b === 'number') {\n return a + b;\n }\n throw new Error('Invalid input');\n }\n\n multiply(x, y) {\n return x * y;\n }\n}`;
const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 43,
endIndex: 132,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle regex-like patterns with escaped characters", () => {
const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`;
const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 29,
endIndex: 110,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match SQL-like content with varying whitespace", () => {
const fileContent = `SELECT users.name,\n users.email,\n profiles.bio\nFROM users\nINNER JOIN profiles ON users.id = profiles.user_id\nWHERE users.active = true\nORDER BY users.name;`;
const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 89,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => {
const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`;
const searchContent = `functionprocessdata(input){returninput.trim();}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 56,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match content with Windows-style CRLF line endings", () => {
const fileContent = `@echo off\r\nset PATH=%PATH%;C:\\tools\r\nif \"%1\"==\"\" (\r\n echo Usage: script.bat filename\r\n exit /b 1\r\n)\r\necho Processing %1...\r\necho Done.`;
const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 37,
endIndex: 105,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle deeply nested JSON with mixed formatting", () => {
const fileContent = `{\n \"config\": {\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"credentials\": {\n \"username\": \"admin\",\n \"password\": \"secret\"\n },\n \"options\": {\n \"ssl\": true,\n \"timeout\": 30000\n }\n }\n }\n}`;
const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 87,
endIndex: 243,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match XML content with attribute spacing differences", () => {
const fileContent = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n <item id = \"1\" type= \"primary\" >\n <name>Test Item</name>\n <value unit=\"px\" >100</value>\n </item>\n</root>`;
const searchContent = `<itemid=\"1\"type=\"primary\"><name>TestItem</name><valueunit=\"px\">100</value></item>`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 48,
endIndex: 155,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle mathematical expressions with varying spacing", () => {
const fileContent = `const result = (a + b) * c - d / e;\nconst complex = Math.sqrt( x ** 2 + y ** 2 );\nconst formula = ( ( a + b ) * ( c - d ) ) / ( e + f );`;
const searchContent = `constcomplex=Math.sqrt(x**2+y**2);constformula=((a+b)*(c-d))/(e+f);`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 36,
endIndex: 142,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match across comments and code with whitespace variations", () => {
const fileContent = `/* Multi-line comment\n with varying indentation */\nfunction processData(input) {\n // Single line comment\n const cleaned = input.trim();\n /* Another comment */\n return cleaned.toLowerCase();\n}`;
const searchContent = `/*Multi-linecommentwithvaryingindentation*/functionprocessData(input){//Singlelinecommentconstcleaned=input.trim();/*Anothercomment*/returncleaned.toLowerCase();}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 205,
strategyName: "whitespaceIgnoredMatch",
});
});
});
describe("No match scenarios", () => {
it("should return null when no strategy finds a match", () => {
const fileContent = "hello world";
const searchContent = "goodbye";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null for completely different content", () => {
const fileContent = "function test() { return true; }";
const searchContent = "class MyClass { }";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null when search content is longer than file content", () => {
const fileContent = "short";
const searchContent = "this is much longer than the file content";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
});
describe("Edge cases", () => {
it("should handle empty file content with non-empty search", () => {
const fileContent = "";
const searchContent = "something";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle single character matches", () => {
const fileContent = "a";
const searchContent = "a";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 1,
strategyName: "exactMatch",
});
});
it("should handle unicode characters", () => {
const fileContent = "Hello 🌍 World";
const searchContent = "🌍";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 8, // Unicode emoji takes 2 character positions
strategyName: "exactMatch",
});
});
it("should handle newlines and carriage returns", () => {
const fileContent = "line1\r\nline2\nline3";
const searchContent = "\r\nline2";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 5,
endIndex: 12,
strategyName: "exactMatch",
});
});
it("should handle very long content efficiently", () => {
const longContent = "a".repeat(10000) + "target" + "b".repeat(10000);
const searchContent = "target";
const result = findSearchMatch(longContent, searchContent);
expect(result).toEqual({
startIndex: 10000,
endIndex: 10006,
strategyName: "exactMatch",
});
});
});
describe("Strategy precedence", () => {
it("should prefer exact match over trimmed match", () => {
const fileContent = "hello world hello";
const searchContent = "hello"; // This exists exactly, so should use exactMatch
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "exactMatch",
});
});
it("should prefer trimmed match over whitespace ignored match", () => {
// Set up content where trimmed match would work but whitespace ignored would also work
const fileContent = "hello world";
const searchContent = " hello "; // Has whitespace but trimmed version exists
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "trimmedMatch",
});
});
it("should fall back through strategies in correct order", () => {
const fileContent = "function test() {\n return true;\n}";
const searchContent = " function test(){return true;} "; // Needs whitespace ignored
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 34,
strategyName: "whitespaceIgnoredMatch",
});
});
});
describe("Real-world code examples", () => {
it("should handle JavaScript function matching", () => {
const fileContent = `function calculateSum(a, b) {
const result = a + b;
return result;
}`;
const searchContent = `function calculateSum(a, b) {
const result = a + b;
return result;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 72,
strategyName: "exactMatch",
});
});
it("should handle HTML tag matching with different formatting", () => {
const fileContent = `<div class="container">
<p>Hello World</p>
</div>`;
const searchContent = `<div class="container"><p>Hello World</p></div>`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 51,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle CSS rule matching", () => {
const fileContent = `.button {
background-color: blue;
color: white;
}`;
const searchContent = `.button{background-color:blue;color:white;}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 53,
strategyName: "whitespaceIgnoredMatch",
});
});
});
});

View file

@ -0,0 +1,368 @@
import { findSearchMatches } from "./findSearchMatch";
describe("findSearchMatches", () => {
describe("exact match strategy", () => {
it("should find single occurrence", () => {
const content = "const foo = 'bar';";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "exactMatch",
});
});
it("should find multiple occurrences", () => {
const content = "const foo = 'foo';";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 13,
endIndex: 16,
strategyName: "exactMatch",
});
});
it("should find overlapping pattern occurrences correctly", () => {
const content = "aaaa";
const search = "aa";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 2,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 2,
endIndex: 4,
strategyName: "exactMatch",
});
});
it("should return empty array when no matches found", () => {
const content = "const bar = 'baz';";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toEqual([]);
});
it("should handle multi-line content", () => {
const content = `line 1 foo
line 2 bar
line 3 foo`;
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 7,
endIndex: 10,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 29,
endIndex: 32,
strategyName: "exactMatch",
});
});
});
describe("trimmed match strategy", () => {
it("should find trimmed occurrences when exact match fails", () => {
const content = "const foo = 'bar';";
const search = " foo ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "trimmedMatch",
});
});
it("should find multiple trimmed occurrences", () => {
const content = "const foo = 'foo';";
const search = " foo ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "trimmedMatch",
});
expect(matches[1]).toEqual({
startIndex: 13,
endIndex: 16,
strategyName: "trimmedMatch",
});
});
});
describe("whitespace ignored match strategy", () => {
it("should find matches ignoring internal whitespace", () => {
const content = "const foo = bar;";
const search = "const foo=bar";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 15,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should find multiple matches ignoring whitespace", () => {
const content = `const foo = bar;
const baz = foo;`;
const search = "const foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 9,
strategyName: "exactMatch",
});
});
it("should handle complex whitespace patterns", () => {
const content = `function test() {
return true;
}`;
const search = "function test(){return true;}";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 34,
strategyName: "whitespaceIgnoredMatch",
});
});
});
describe("empty search content", () => {
it("should return single match at position 0 for empty string", () => {
const content = "const foo = 'bar';";
const search = "";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should return single match at position 0 for whitespace-only string", () => {
const content = "const foo = 'bar';";
const search = " \n\t ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("edge cases", () => {
it("should handle searching in empty content", () => {
const content = "";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toEqual([]);
});
it("should handle searching for content at the beginning", () => {
const content = "foo bar baz";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 3,
strategyName: "exactMatch",
});
});
it("should handle searching for content at the end", () => {
const content = "foo bar baz";
const search = "baz";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 8,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should handle searching for the entire content", () => {
const content = "foo bar baz";
const search = "foo bar baz";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should handle special characters", () => {
const content = "const regex = /[a-z]+/g;";
const search = "/[a-z]+/g";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 14,
endIndex: 23,
strategyName: "exactMatch",
});
});
it("should handle Unicode characters", () => {
const content = "const emoji = '🚀 Hello 🌍';";
const search = "🚀 Hello 🌍";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 15,
endIndex: 26,
strategyName: "exactMatch",
});
});
});
describe("performance considerations", () => {
it("should handle long content with multiple matches", () => {
const repeatedContent = "foo bar ".repeat(1000);
const search = "foo";
const matches = findSearchMatches(repeatedContent, search);
expect(matches).toHaveLength(1000);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 3,
strategyName: "exactMatch",
});
expect(matches[999]).toEqual({
startIndex: 7992,
endIndex: 7995,
strategyName: "exactMatch",
});
});
it("should prevent infinite loops on edge cases", () => {
const content = "aaaa";
const search = "";
const matches = findSearchMatches(content, search);
// Should only return one match for empty search
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("strategy selection", () => {
it("should use exact match strategy when possible", () => {
const content = "const foo = bar;";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("exactMatch");
});
it("should fallback to trimmed match when exact fails", () => {
const content = "const foo = bar;";
const search = " foo ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("trimmedMatch");
});
it("should fallback to whitespace ignored when others fail", () => {
const content = "const foo = bar;";
const search = "const foo=bar";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch");
});
});
describe("complex patterns", () => {
it("should handle multiple matches with different line endings", () => {
const content = "foo\r\nbar\r\nfoo\nfoo";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(3);
expect(matches[0].startIndex).toBe(0);
expect(matches[1].startIndex).toBe(10);
expect(matches[2].startIndex).toBe(14);
});
it("should handle matches across different strategies", () => {
const content = "const foo = 'bar';\n const foo='baz';";
const search = "foo";
const matches = findSearchMatches(content, search);
// Both occurrences of "foo" should be found with exact match
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 29,
endIndex: 32,
strategyName: "exactMatch",
});
});
it("should handle code with mixed indentation", () => {
const content = `\tfunction test() {
return true;
\t}`;
const search = "function test(){return true;}";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch");
});
});
});

View file

@ -0,0 +1,341 @@
import { describe, expect, it } from "vitest";
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueErrorReason } from "../../util/errors";
import { validateMultiEdit } from "./multiEditValidation";
import { executeMultiFindAndReplace } from "./performReplace";
describe("multiEdit shared validation", () => {
describe("validateMultiEdit", () => {
it("should throw error if edits is not an array", () => {
expect(() => validateMultiEdit({ edits: "not an array" })).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.MultiEditEditsArrayRequired,
}),
);
});
it("should throw error if edits is missing", () => {
expect(() => validateMultiEdit({})).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.MultiEditEditsArrayRequired,
}),
);
});
it("should throw error if edits array is empty", () => {
expect(() => validateMultiEdit({ edits: [] })).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.MultiEditEditsArrayEmpty,
}),
);
});
it("should return valid edits", () => {
const edits: EditOperation[] = [
{ old_string: "hello", new_string: "world" },
];
const result = validateMultiEdit({ edits });
expect(result.edits).toEqual(edits);
});
});
describe("validateMultiEdit - individual edit validation", () => {
it("should throw error if edit has missing old_string", () => {
const args = {
edits: [
{
old_string: undefined as any,
new_string: "Hi there",
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error if edit has missing new_string", () => {
const args = {
edits: [
{
old_string: "Hello world",
new_string: undefined as any,
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should throw error if old_string and new_string are the same", () => {
const args = {
edits: [
{
old_string: "Hello world",
new_string: "Hello world",
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error if non-first edit has empty old_string", () => {
const args = {
edits: [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "",
new_string: "Invalid insertion",
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString,
}),
);
});
it("should allow first edit to have empty old_string", () => {
const args = {
edits: [
{
old_string: "",
new_string: "New content",
},
],
};
expect(() => validateMultiEdit(args)).not.toThrow();
});
});
describe("executeMultiFindAndReplace", () => {
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
it("should handle single edit", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe("Hi there\nThis is a test file\nGoodbye world");
});
it("should handle multiple edits", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "Goodbye world",
new_string: "See you later",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe("Hi there\nThis is a test file\nSee you later");
});
it("should handle replace_all", () => {
const edits = [
{
old_string: "world",
new_string: "universe",
replace_all: true,
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe(
"Hello universe\nThis is a test file\nGoodbye universe",
);
});
it("should handle empty old_string as insertion at beginning", () => {
const edits = [
{
old_string: "",
new_string: "New first line\n",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe(
"New first line\nHello world\nThis is a test file\nGoodbye world",
);
});
it("should handle empty string in empty file", () => {
const edits = [
{
old_string: "",
new_string: "Content for empty file",
},
];
// Empty old_string matches at position 0 (beginning of file)
const result = executeMultiFindAndReplace("", edits);
expect(result).toBe("Content for empty file");
});
it("should apply edits sequentially", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi universe",
},
{
old_string: "Hi universe",
new_string: "Greetings cosmos",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe(
"Greetings cosmos\nThis is a test file\nGoodbye world",
);
});
it("should throw error if old_string is not found", () => {
const edits = [
{
old_string: "Not found",
new_string: "Hi there",
},
];
expect(() =>
executeMultiFindAndReplace(originalContent, edits),
).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error if old_string appears multiple times and replace_all is false", () => {
const edits = [
{
old_string: "world",
new_string: "universe",
replace_all: false,
},
];
expect(() =>
executeMultiFindAndReplace(originalContent, edits),
).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
it("should throw if string not found in edit sequence", () => {
const content = "Hello world";
const edits = [
{ old_string: "Hello", new_string: "Hi" },
{ old_string: "not found", new_string: "test" },
];
expect(() => executeMultiFindAndReplace(content, edits)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should handle whitespace differences using findSearchMatch", () => {
const content = "function test() {\n return true;\n}";
const edits = [
{
old_string: "function test(){return true;}",
new_string: "function test() { return false; }",
},
];
const result = executeMultiFindAndReplace(content, edits);
expect(result).toBe("function test() { return false; }");
});
it("should handle mixed replace_all settings", () => {
const content = "x y x z x";
const edits = [
{ old_string: "x", new_string: "a", replace_all: true },
{ old_string: "y", new_string: "b" },
];
const result = executeMultiFindAndReplace(content, edits);
expect(result).toBe("a b a z a");
});
});
describe("preprocessing logic", () => {
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
it("should handle single edit preprocessing", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
];
const newContent = executeMultiFindAndReplace(originalContent, edits);
expect(newContent).toBe("Hi there\nThis is a test file\nGoodbye world");
});
it("should handle multiple edits preprocessing", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "Goodbye world",
new_string: "See you later",
},
];
const newContent = executeMultiFindAndReplace(originalContent, edits);
expect(newContent).toBe("Hi there\nThis is a test file\nSee you later");
});
it("should count edits correctly", () => {
const edits = [
{ old_string: "Hello", new_string: "Hi" },
{ old_string: "world", new_string: "universe", replace_all: true },
];
const newContent = executeMultiFindAndReplace(originalContent, edits);
expect(newContent).toBe(
"Hi universe\nThis is a test file\nGoodbye universe",
);
expect(edits.length).toBe(2);
});
});
});

View file

@ -0,0 +1,50 @@
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { validateSingleEdit } from "./findAndReplaceUtils";
export interface MultiEditValidationResult {
edits: EditOperation[];
}
/**
* Validates multi-edit arguments and all edits in a single pass
* @param args - The arguments object containing the edits array
* @returns Validated edits array
* @throws ContinueError if validation fails
*/
export function validateMultiEdit(args: any): MultiEditValidationResult {
const { edits } = args;
// Validate that edits is a non-empty array
if (!edits || !Array.isArray(edits)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"edits array is required",
);
}
if (edits.length === 0) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayEmpty,
"edits array must contain at least one edit",
);
}
// Validate each individual edit
for (let i = 0; i < edits.length; i++) {
const edit = edits[i];
// Use existing single edit validation
validateSingleEdit(edit.old_string, edit.new_string, i);
// Only the first edit can have empty old_string (for insertion at beginning)
if (i > 0 && edit.old_string === "") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString,
`Edit at index ${i}: old_string cannot be empty. Only the first edit can have an empty old_string for insertion at the beginning of the file.`,
);
}
}
return { edits };
}

View file

@ -0,0 +1,70 @@
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { findSearchMatches } from "./findSearchMatch";
export function executeFindAndReplace(
fileContent: string,
oldString: string,
newString: string,
replaceAll: boolean,
editIndex = 0,
): string {
const matches = findSearchMatches(fileContent, oldString);
if (matches.length === 0) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceOldStringNotFound,
`Edit at index ${editIndex}: string not found in file: "${oldString}"`,
);
}
if (replaceAll) {
// Apply replacements in reverse order to maintain correct positions
let result = fileContent;
for (let i = matches.length - 1; i >= 0; i--) {
const match = matches[i];
result =
result.substring(0, match.startIndex) +
newString +
result.substring(match.endIndex);
}
return result;
} else {
// For single replacement, check for multiple matches first
if (matches.length > 1) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMultipleOccurrences,
`Edit at index ${editIndex}: String "${oldString}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
);
}
// Apply single replacement
const match = matches[0];
return (
fileContent.substring(0, match.startIndex) +
newString +
fileContent.substring(match.endIndex)
);
}
}
export function executeMultiFindAndReplace(
fileContent: string,
edits: EditOperation[],
): string {
let result = fileContent;
// Apply edits in sequence
for (let editIndex = 0; editIndex < edits.length; editIndex++) {
const edit = edits[editIndex];
result = executeFindAndReplace(
result,
edit.old_string,
edit.new_string,
edit.replace_all ?? false,
editIndex,
);
}
return result;
}

5
core/index.d.ts vendored
View file

@ -310,11 +310,6 @@ export interface FileEdit {
replacement: string;
}
export interface ContinueError {
title: string;
message: string;
}
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}

View file

@ -2,6 +2,7 @@ import ignore from "ignore";
import path from "path";
import { fileURLToPath } from "url";
import { ContinueError, ContinueErrorReason } from "../util/errors";
// Security-focused ignore patterns - these should always be excluded for security reasons
export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
@ -259,7 +260,8 @@ export function isSecurityConcern(filePathOrUri: string) {
export function throwIfFileIsSecurityConcern(filepath: string) {
if (isSecurityConcern(filepath)) {
throw new Error(
throw new ContinueError(
ContinueErrorReason.FileIsSecurityConcern,
`Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`,
);
}

View file

@ -50,12 +50,6 @@ CRITICAL REQUIREMENTS:
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
If you want to create a new file, use:
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits are not allowed - there is no need since you are creating
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)

View file

@ -10,3 +10,44 @@ export function getRootCause(err: any): any {
}
return err;
}
export class ContinueError extends Error {
reason: ContinueErrorReason;
constructor(reason: ContinueErrorReason, message?: string) {
super(message);
this.reason = reason;
this.name = "ContinueError";
}
}
export enum ContinueErrorReason {
// Find and Replace validation errors
FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings",
FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
// Multi-edit
MultiEditEditsArrayRequired = "multi_edit_edits_array_required",
MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty",
MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation",
MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first",
// General Edit
EditToolFileNotRead = "edit_tool_file_not_yet_read",
// General File
FileAlreadyExists = "file_already_exists",
FileNotFound = "file_not_found",
FileWriteError = "file_write_error",
FileIsSecurityConcern = "file_is_security_concern",
ParentDirectoryNotFound = "parent_directory_not_found",
// Other
Unspecified = "unspecified",
Unknown = "unknown",
}

View file

@ -1,5 +1,6 @@
// Helper functions extracted from streamChatResponse.ts to reduce file size
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs";
import { checkToolPermission } from "../permissions/permissionChecker.js";
@ -354,6 +355,11 @@ export async function preprocessStreamedToolCalls(
// Notify the UI about the tool start, even though it failed
callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
const errorReason =
error instanceof ContinueError
? error.reason
: ContinueErrorReason.Unknown;
const errorMessage =
error instanceof Error ? error.message : String(error);
@ -368,6 +374,15 @@ export async function preprocessStreamedToolCalls(
success: false,
durationMs: duration,
error: errorMessage,
errorReason,
// modelName, TODO
});
void posthogService.capture("tool_call_outcome", {
succeeded: false,
toolName: toolCall.name,
errorReason,
duration_ms: duration,
// model: options.modelName, TODO
});
// Add error to chat history

View file

@ -498,9 +498,11 @@ class TelemetryService {
success: boolean;
durationMs: number;
error?: string;
errorReason?: string;
decision?: "accept" | "reject";
source?: string;
toolParameters?: string;
// modelName: string;
}) {
if (!this.isEnabled()) return;
@ -517,6 +519,12 @@ class TelemetryService {
if (options.source) attributes.source = options.source;
if (options.toolParameters)
attributes.tool_parameters = options.toolParameters;
if (options.errorReason) {
attributes.error_reason = options.errorReason;
}
if (options.error) {
attributes.error = options.error;
}
// TODO: Implement OTLP logs export
logger.debug("Tool result event", attributes);

View file

@ -1,5 +1,6 @@
import * as fs from "fs";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { editTool } from "./edit.js";
@ -52,9 +53,9 @@ describe("editTool", () => {
new_string: "Hi there",
};
await expect(editTool.preprocess!(args)).rejects.toThrow(
`You must use the Read tool to read ${testFilePath} before editing it.`,
);
const error = await editTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(ContinueErrorReason.EditToolFileNotRead);
});
it("should throw error if file does not exist", async () => {
@ -68,9 +69,9 @@ describe("editTool", () => {
new_string: "Hi",
};
await expect(editTool.preprocess!(args)).rejects.toThrow(
`File ${nonExistentFile} does not exist`,
);
const error = await editTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(ContinueErrorReason.FileNotFound);
});
it("should throw error if old_string is not found", async () => {
@ -83,8 +84,10 @@ describe("editTool", () => {
new_string: "Hi there",
};
await expect(editTool.preprocess!(args)).rejects.toThrow(
"String not found in file: Not found",
const error = await editTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(
ContinueErrorReason.FindAndReplaceOldStringNotFound,
);
});
@ -98,8 +101,10 @@ describe("editTool", () => {
replace_all: false,
};
await expect(editTool.preprocess!(args)).rejects.toThrow(
'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
const error = await editTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(
ContinueErrorReason.FindAndReplaceMultipleOccurrences,
);
});
@ -112,8 +117,10 @@ describe("editTool", () => {
new_string: "Hello world",
};
await expect(editTool.preprocess!(args)).rejects.toThrow(
"old_string and new_string must be different",
const error = await editTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(
ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
);
});
@ -194,9 +201,9 @@ describe("editTool", () => {
oldContent: originalContent,
};
await expect(editTool.run(args)).rejects.toThrow(
`Error: failed to edit ${testFilePath}: Write failed`,
);
const error = await editTool.run(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(ContinueErrorReason.FileWriteError);
});
});

View file

@ -1,6 +1,10 @@
import * as fs from "fs";
import path from "path";
import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils.js";
import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace.js";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
@ -8,15 +12,53 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { EditOperation } from "./multiEdit.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
export interface EditArgs {
export function validateAndResolveFilePath(args: any): {
originalPath: string;
resolvedPath: string;
} {
const { file_path } = args;
if (!file_path) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"file_path is required",
);
}
const absolutePath = path.isAbsolute(file_path)
? file_path
: path.resolve(process.cwd(), file_path);
const resolvedPath = fs.realpathSync(absolutePath);
throwIfFileIsSecurityConcern(resolvedPath);
// Check if file exists
if (!fs.existsSync(resolvedPath)) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${file_path} does not exist`,
);
}
// Check if file has been read
if (!readFilesSet.has(resolvedPath)) {
throw new ContinueError(
ContinueErrorReason.EditToolFileNotRead,
`You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
);
}
return { originalPath: file_path, resolvedPath: resolvedPath };
}
export interface EditArgs extends EditOperation {
file_path: string;
old_string: string;
new_string: string;
replace_all?: boolean;
}
export const editTool: Tool = {
@ -61,67 +103,20 @@ WARNINGS:
},
},
preprocess: async (args) => {
const {
file_path,
const { old_string, new_string, replace_all = false } = args as EditArgs;
const { resolvedPath } = validateAndResolveFilePath(args);
validateSingleEdit(old_string, new_string);
const oldContent = fs.readFileSync(resolvedPath, "utf-8");
const newContent = executeFindAndReplace(
oldContent,
old_string,
new_string,
replace_all = false,
} = args as EditArgs;
// Validate arguments
if (!file_path) {
throw new Error("file_path is required");
}
if (!old_string) {
throw new Error("old_string is required");
}
if (new_string === undefined) {
throw new Error("new_string is required");
}
if (old_string === new_string) {
throw new Error("old_string and new_string must be different");
}
const resolvedPath = fs.realpathSync(file_path);
// Check if file has been read
if (!readFilesSet.has(resolvedPath)) {
throw new Error(
`You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
);
}
throwIfFileIsSecurityConcern(resolvedPath);
// Check if file exists
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File ${file_path} does not exist`);
}
// Read current file content
const oldContent = fs.readFileSync(resolvedPath, "utf-8");
// Check if old_string exists in the file
if (!oldContent.includes(old_string)) {
throw new Error(`String not found in file: ${old_string}`);
}
let newContent: string;
if (replace_all) {
// Replace all occurrences
newContent = oldContent.split(old_string).join(new_string);
} else {
// Replace only the first occurrence
const occurrences = oldContent.split(old_string).length - 1;
if (occurrences > 1) {
throw new Error(
`String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
);
}
newContent = oldContent.replace(old_string, new_string);
}
replace_all,
0,
);
// Generate diff for preview
const diff = generateDiff(oldContent, newContent, resolvedPath);
@ -179,7 +174,11 @@ WARNINGS:
return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`;
} catch (error) {
throw new Error(
if (error instanceof ContinueError) {
throw error;
}
throw new ContinueError(
ContinueErrorReason.FileWriteError,
`Error: failed to edit ${args.resolvedPath}: ${
error instanceof Error ? error.message : String(error)
}`,

View file

@ -1,4 +1,8 @@
// @ts-ignore
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { posthogService } from "src/telemetry/posthogService.js";
import {
getServiceSync,
MCPServiceState,
@ -212,6 +216,11 @@ export async function executeToolCall(
durationMs: duration,
toolParameters: JSON.stringify(toolCall.arguments),
});
void posthogService.capture("tool_call_outcome", {
succeeded: true,
toolName: toolCall.name,
duration_ms: duration,
});
logger.debug("Tool execution completed", {
toolName: toolCall.name,
@ -222,14 +231,25 @@ export async function executeToolCall(
} catch (error) {
const duration = Date.now() - startTime;
const errorMessage = error instanceof Error ? error.message : String(error);
const errorReason =
error instanceof ContinueError
? error.reason
: ContinueErrorReason.Unknown;
telemetryService.logToolResult({
toolName: toolCall.name,
success: false,
durationMs: duration,
error: errorMessage,
errorReason,
toolParameters: JSON.stringify(toolCall.arguments),
});
void posthogService.capture("tool_call_outcome", {
succeeded: false,
toolName: toolCall.name,
duration_ms: duration,
errorReason,
});
return `Error executing tool "${toolCall.name}": ${errorMessage}`;
}

View file

@ -1,6 +1,7 @@
import * as fs from "fs";
import * as path from "path";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { multiEditTool } from "./multiEdit.js";
@ -15,6 +16,7 @@ vi.mock("../telemetry/utils.js", () => ({
vi.mock("./writeFile.js", () => ({
generateDiff: vi.fn().mockReturnValue("mocked diff"),
}));
vi.mock("fs", async () => {
const actual = await vi.importActual("fs");
return {
@ -27,7 +29,7 @@ vi.mock("fs", async () => {
};
});
describe("multiEditTool", () => {
describe("multiEditTool CLI specific", () => {
const testFilePath = "/tmp/test-multi-edit-file.txt";
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
@ -44,7 +46,7 @@ describe("multiEditTool", () => {
vi.clearAllMocks();
});
describe("preprocess", () => {
describe("file system validation", () => {
it("should throw error if file has not been read", async () => {
const args = {
file_path: testFilePath,
@ -56,9 +58,9 @@ describe("multiEditTool", () => {
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
`You must use the Read tool to read ${testFilePath} before editing it.`,
);
const error = await multiEditTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(ContinueErrorReason.EditToolFileNotRead);
});
it("should throw error if file does not exist", async () => {
@ -76,117 +78,31 @@ describe("multiEditTool", () => {
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
`File ${nonExistentFile} does not exist`,
);
const error = await multiEditTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(ContinueErrorReason.FileNotFound);
});
it("should throw error if edits array is empty", async () => {
markFileAsRead(testFilePath);
it("should throw error if file_path is missing", async () => {
const args = {
file_path: testFilePath,
edits: [],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
"edits array is required and must contain at least one edit",
);
});
it("should throw error if edit has missing old_string", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: undefined as any,
new_string: "Hi there",
old_string: "Hello",
new_string: "Hi",
},
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
"Edit 1: old_string is required",
const error = await multiEditTool.preprocess!(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(
ContinueErrorReason.FindAndReplaceMissingFilepath,
);
});
});
it("should throw error if edit has missing new_string", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: "Hello world",
new_string: undefined as any,
},
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
"Edit 1: new_string is required",
);
});
it("should throw error if old_string and new_string are the same", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: "Hello world",
new_string: "Hello world",
},
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
"Edit 1: old_string and new_string must be different",
);
});
it("should throw error if old_string is not found", async () => {
markFileAsRead(testFilePath);
vi.mocked(fs.readFileSync).mockReturnValue("Different content");
const args = {
file_path: testFilePath,
edits: [
{
old_string: "Not found",
new_string: "Hi there",
},
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
'Edit 1: String not found in file: "Not found"',
);
});
it("should throw error if old_string appears multiple times and replace_all is false", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: "world",
new_string: "universe",
replace_all: false,
},
],
};
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
);
});
it("should successfully preprocess single edit", async () => {
describe("preprocess CLI specific", () => {
it("should generate preview with diff", async () => {
markFileAsRead(testFilePath);
const args = {
@ -201,120 +117,16 @@ describe("multiEditTool", () => {
const result = await multiEditTool.preprocess!(args);
expect(result.args).toEqual({
file_path: testFilePath,
newContent: "Hi there\nThis is a test file\nGoodbye world",
originalContent: originalContent,
isCreatingNewFile: false,
editCount: 1,
});
expect(result.preview).toHaveLength(2);
expect(result.preview?.[0]).toEqual({
type: "text",
content: "Will apply 1 edit to modify /tmp/test-multi-edit-file.txt:",
content: "Will apply 1 edit to /tmp/test-multi-edit-file.txt:",
});
expect(result.preview?.[1]).toEqual({
type: "diff",
content: "mocked diff",
});
});
it("should successfully preprocess multiple edits", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "Goodbye world",
new_string: "See you later",
},
],
};
const result = await multiEditTool.preprocess!(args);
expect(result.args.newContent).toBe(
"Hi there\nThis is a test file\nSee you later",
);
expect(result.args.editCount).toBe(2);
expect(result.preview?.[0]?.content).toContain("Will apply 2 edits");
});
it("should successfully preprocess replace_all edit", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: "world",
new_string: "universe",
replace_all: true,
},
],
};
const result = await multiEditTool.preprocess!(args);
expect(result.args.newContent).toBe(
"Hello universe\nThis is a test file\nGoodbye universe",
);
});
it("should handle new file creation with empty old_string", async () => {
const newFilePath = "/tmp/new-file.txt";
vi.mocked(fs.existsSync).mockImplementation((path) => {
// Parent directory exists, but file doesn't
if (path === "/tmp") return true;
if (path === newFilePath) return false;
return true;
});
const args = {
file_path: newFilePath,
edits: [
{
old_string: "",
new_string: "New file content\nSecond line",
},
],
};
const result = await multiEditTool.preprocess!(args);
expect(result.args.newContent).toBe("New file content\nSecond line");
expect(result.args.isCreatingNewFile).toBe(true);
expect(result.preview?.[0]?.content).toContain("create");
});
it("should apply edits sequentially", async () => {
markFileAsRead(testFilePath);
const args = {
file_path: testFilePath,
edits: [
{
old_string: "Hello world",
new_string: "Hi universe",
},
{
old_string: "Hi universe",
new_string: "Greetings cosmos",
},
],
};
const result = await multiEditTool.preprocess!(args);
expect(result.args.newContent).toBe(
"Greetings cosmos\nThis is a test file\nGoodbye world",
);
});
});
describe("run", () => {
@ -324,7 +136,6 @@ describe("multiEditTool", () => {
file_path: testFilePath,
newContent,
originalContent: originalContent,
isCreatingNewFile: false,
editCount: 1,
};
@ -345,7 +156,6 @@ describe("multiEditTool", () => {
file_path: testFilePath,
newContent: "New content",
originalContent: originalContent,
isCreatingNewFile: false,
editCount: 3,
};
@ -356,22 +166,6 @@ describe("multiEditTool", () => {
);
});
it("should return correct message for new file creation", async () => {
const args = {
file_path: "/tmp/new-file.txt",
newContent: "New file content",
originalContent: "",
isCreatingNewFile: true,
editCount: 1,
};
const result = await multiEditTool.run(args);
expect(result).toBe(
`Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`,
);
});
it("should throw error if file write fails", async () => {
vi.mocked(fs.writeFileSync).mockImplementation(() => {
throw new Error("Write failed");
@ -381,13 +175,12 @@ describe("multiEditTool", () => {
file_path: testFilePath,
newContent: "new content",
originalContent: originalContent,
isCreatingNewFile: false,
editCount: 1,
};
await expect(multiEditTool.run(args)).rejects.toThrow(
`Error: failed to edit ${testFilePath}: Write failed`,
);
const error = await multiEditTool.run(args).catch((e) => e);
expect(error).toBeInstanceOf(ContinueError);
expect(error.reason).toBe(ContinueErrorReason.FileWriteError);
});
});
@ -473,34 +266,6 @@ describe("multiEditTool", () => {
expect(result.args.file_path).toBe(absolutePath);
});
it("should handle relative path for new file creation", async () => {
const relativePath = "new-file.txt";
const absolutePath = path.resolve(process.cwd(), relativePath);
vi.mocked(fs.existsSync).mockImplementation((path) => {
// Parent directory (cwd) exists, but file doesn't
if (path === process.cwd()) return true;
if (path === absolutePath) return false;
return true;
});
const args = {
file_path: relativePath,
edits: [
{
old_string: "",
new_string: "New file content",
},
],
};
const result = await multiEditTool.preprocess!(args);
expect(result.args.file_path).toBe(absolutePath);
expect(result.args.newContent).toBe("New file content");
expect(result.args.isCreatingNewFile).toBe(true);
});
});
describe("markFileAsRead", () => {
@ -518,7 +283,9 @@ describe("multiEditTool", () => {
};
const result = await multiEditTool.preprocess!(args);
expect(result.args.newContent).toContain("Hi there");
expect(result.args.newContent).toBe(
"Hi there\nThis is a test file\nGoodbye world",
);
});
});
});

View file

@ -1,7 +1,8 @@
import * as fs from "fs";
import * as path from "path";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation.js";
import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace.js";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
@ -9,7 +10,8 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { validateAndResolveFilePath } from "./edit.js";
import { readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
@ -24,109 +26,6 @@ export interface MultiEditArgs {
edits: EditOperation[];
}
// Helper functions for multiEdit validation
function validateMultiEditArgs(args: any): {
original_path: string;
resolved_path: string;
edits: EditOperation[];
} {
const { file_path, edits } = args as MultiEditArgs;
if (!file_path) {
throw new Error("file_path is required");
}
if (!edits || !Array.isArray(edits) || edits.length === 0) {
throw new Error(
"edits array is required and must contain at least one edit",
);
}
// Convert relative paths to absolute paths
const absolutePath = path.isAbsolute(file_path)
? file_path
: path.resolve(process.cwd(), file_path);
const resolvedPath = fs.realpathSync(absolutePath);
return { original_path: file_path, resolved_path: resolvedPath, edits };
}
function validateEdits(edits: EditOperation[]): void {
for (let i = 0; i < edits.length; i++) {
const edit = edits[i];
if (!edit.old_string && edit.old_string !== "") {
throw new Error(`Edit ${i + 1}: old_string is required`);
}
if (edit.new_string === undefined) {
throw new Error(`Edit ${i + 1}: new_string is required`);
}
if (edit.old_string === edit.new_string) {
throw new Error(
`Edit ${i + 1}: old_string and new_string must be different`,
);
}
}
}
function validateFileAccess(
resolvedPath: string,
isCreatingNewFile: boolean,
): void {
if (isCreatingNewFile) {
// For new file creation, check if parent directory exists
const parentDir = path.dirname(resolvedPath);
if (parentDir && !fs.existsSync(parentDir)) {
throw new Error(`Parent directory does not exist: ${parentDir}`);
}
} else {
// For existing files, check if file has been read
// Check with the original path first, then with absolute path
if (!readFilesSet.has(resolvedPath)) {
throw new Error(
`You must use the ${readFileTool.name} tool to read ${resolvedPath} before editing it.`,
);
}
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File ${resolvedPath} does not exist`);
}
}
}
function applyEdit(
content: string,
edit: EditOperation,
editIndex: number,
isFirstEditOfNewFile: boolean,
): string {
const { old_string, new_string, replace_all = false } = edit;
// For new file creation, the first edit can have empty old_string
if (isFirstEditOfNewFile && old_string === "") {
return new_string;
}
// Check if old_string exists in current content
if (!content.includes(old_string)) {
throw new Error(
`Edit ${editIndex + 1}: String not found in file: "${old_string}"`,
);
}
if (replace_all) {
// Replace all occurrences
return content.split(old_string).join(new_string);
} else {
// Replace only the first occurrence, but check for uniqueness
const occurrences = content.split(old_string).length - 1;
if (occurrences > 1) {
throw new Error(
`Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
);
}
return content.replace(old_string, new_string);
}
}
export const multiEditTool: Tool = {
name: "MultiEdit",
displayName: "MultiEdit",
@ -156,18 +55,15 @@ CRITICAL REQUIREMENTS:
- Always use absolute file paths (starting with /)
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
If you want to create a new file, use:
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits: normal edit operations on the created content
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
- Empty old_string can be used to insert content at the beginning of a file
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different
- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session`,
- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session
- The tool will fail if the file does not exist - it cannot create new files
- This tool cannot create new files - the file must already exist`,
parameters: {
file_path: {
type: "string",
@ -185,50 +81,27 @@ WARNINGS:
},
},
preprocess: async (args) => {
// Validate and extract arguments
const { resolved_path, edits } = validateMultiEditArgs(args);
const { resolvedPath } = validateAndResolveFilePath(args);
throwIfFileIsSecurityConcern(resolved_path);
const { edits } = validateMultiEdit(args);
// Validate each edit operation
validateEdits(edits);
// Check if this is creating a new file (first edit has empty old_string)
const isCreatingNewFile = edits[0].old_string === "";
// Validate file access
validateFileAccess(resolved_path, isCreatingNewFile);
// Read current file content (or start with empty for new files)
let currentContent = "";
if (!isCreatingNewFile) {
currentContent = fs.readFileSync(resolved_path, "utf-8");
}
const originalContent = currentContent;
let newContent = currentContent;
// Apply all edits sequentially
for (let i = 0; i < edits.length; i++) {
const isFirstEditOfNewFile = i === 0 && isCreatingNewFile;
newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile);
}
const currentContent = fs.readFileSync(resolvedPath, "utf-8");
const newContent = executeMultiFindAndReplace(currentContent, edits);
// Generate diff for preview
const diff = generateDiff(originalContent, newContent, resolved_path);
const diff = generateDiff(currentContent, newContent, resolvedPath);
return {
args: {
file_path: resolved_path,
file_path: resolvedPath,
newContent,
originalContent,
isCreatingNewFile,
originalContent: currentContent,
editCount: edits.length,
},
preview: [
{
type: "text",
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${resolved_path}:`,
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${resolvedPath}:`,
},
{
type: "diff",
@ -241,7 +114,6 @@ WARNINGS:
file_path: string;
newContent: string;
originalContent: string;
isCreatingNewFile: boolean;
editCount: number;
}) => {
try {
@ -272,10 +144,13 @@ WARNINGS:
args.file_path,
);
const action = args.isCreatingNewFile ? "created" : "edited";
return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
return `Successfully edited ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
} catch (error) {
throw new Error(
if (error instanceof ContinueError) {
throw error;
}
throw new ContinueError(
ContinueErrorReason.FileWriteError,
`Error: failed to edit ${args.file_path}: ${
error instanceof Error ? error.message : String(error)
}`,

View file

@ -1,7 +1,7 @@
import * as fs from "fs";
import * as diff from "diff";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
// Mock fs module
vi.mock("fs", async () => {
@ -30,7 +30,6 @@ import { fetchTool } from "./fetch.js";
import { listFilesTool } from "./listFiles.js";
import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js";
import { searchCodeTool } from "./searchCode.js";
import { viewDiffTool } from "./viewDiff.js";
import { writeFileTool } from "./writeFile.js";
@ -346,123 +345,4 @@ describe.skip("Tool preprocess functions", () => {
});
});
});
describe("searchAndReplaceInFileTool.preprocess", () => {
it("should process simple search and replace", async () => {
// Setup mocks
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3");
const args = {
filepath: "path/to/file.txt",
diffs: [
`------- SEARCH
old line 2
=======
new line 2
+++++++ REPLACE`,
],
};
const result = await searchAndReplaceInFileTool.preprocess!(args);
expect(mockExistsSync).toHaveBeenCalled();
expect(mockReadFileSync).toHaveBeenCalled();
expect(mockCreateTwoFilesPatch).toHaveBeenCalled();
expect(result.args).toEqual({
filepath: expect.any(String),
newContent: "old line 1\nnew line 2\nold line 3",
oldContent: "old line 1\nold line 2\nold line 3",
});
expect(result.preview).toEqual([
{
type: "text",
content: "Will make the following changes:",
},
{
type: "diff",
content: "mock diff content",
},
]);
});
it("should throw error when file doesn't exist", async () => {
mockExistsSync.mockReturnValue(false);
const args = {
filepath: "/nonexistent/file.txt",
diffs: ["some diff"],
};
await expect(
searchAndReplaceInFileTool.preprocess!(args),
).rejects.toThrowError(/file .* does not exist/);
});
it("should throw error when no search/replace blocks found", async () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("file content");
const args = {
filepath: "path/to/file.txt",
diffs: ["invalid diff format"],
};
await expect(
searchAndReplaceInFileTool.preprocess!(args),
).rejects.toThrowError(
"No complete search/replace blocks found in any diffs",
);
});
it("should throw error when search content not found", async () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3");
const args = {
filepath: "path/to/file.txt",
diffs: [
`------- SEARCH
nonexistent content
=======
replacement
+++++++ REPLACE`,
],
};
await expect(
searchAndReplaceInFileTool.preprocess!(args),
).rejects.toThrowError(/Search content not found in block 1:/);
});
it("should process multiple search/replace blocks", async () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("line 1\nline 2\nline 3\nline 4");
const args = {
filepath: "path/to/file.txt",
diffs: [
`------- SEARCH
line 1
=======
modified line 1
+++++++ REPLACE
------- SEARCH
line 3
=======
modified line 3
+++++++ REPLACE`,
],
};
const result = await searchAndReplaceInFileTool.preprocess!(args);
expect(result.args.newContent).toBe(
"modified line 1\nline 2\nmodified line 3\nline 4",
);
});
});
});

View file

@ -1,190 +0,0 @@
import * as fs from "fs";
import { telemetryService } from "../../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../../telemetry/utils.js";
import { Tool } from "../types.js";
import { generateDiff } from "../writeFile.js";
import { findSearchMatch } from "./findSearchMatch.js";
import { parseSearchAndReplaceArgs } from "./parseArgs.js";
import { parseAllSearchReplaceBlocks } from "./parseBlock.js";
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.";
/**
* 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 = {
name: "Edit",
displayName: "Edit",
readonly: false,
isBuiltIn: true,
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: {
filepath: {
type: "string",
description: "The path to the file to edit",
required: true,
},
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]
=======
[new content to replace with]
+++++++ REPLACE
\`\`\`
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
Usage:
\`\`\`
------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE
------- SEARCH
[exact content to find]
=======
[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.`,
required: true,
},
},
preprocess: async (args) => {
// Get and validate args
const { filepath, diffs } = parseSearchAndReplaceArgs(args);
// Get current file contents
if (!fs.existsSync(filepath)) {
throw new Error(`file ${filepath} does not exist`);
}
const oldContent = fs.readFileSync(filepath, "utf-8");
let newContent = oldContent;
// Parse blocks
const blocks = diffs.map(parseAllSearchReplaceBlocks).flat();
if (blocks.length === 0) {
throw new Error("No complete search/replace blocks found in any diffs");
}
// Apply all replacements sequentially to build the final content
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
const { searchContent, replaceContent } = block;
if (typeof searchContent === "undefined") {
throw new Error(`No search content defined for block ${i + 1}`);
}
if (typeof replaceContent === "undefined") {
throw new Error(`No replace content defined for block ${i + 1}`);
}
const match = findSearchMatch(newContent, searchContent);
if (!match) {
throw new Error(
`Search content not found in block ${i + 1}:\n${searchContent}`,
);
}
newContent =
newContent.substring(0, match.startIndex) +
replaceContent +
newContent.substring(match.endIndex);
}
const diff = generateDiff(oldContent, newContent, filepath);
return {
args: {
filepath,
newContent,
oldContent, // Just for telemetry later
},
preview: [
{
type: "text",
content: "Will make the following changes:",
},
{
type: "diff",
content: diff,
},
],
};
},
run: async (args) => {
try {
fs.writeFileSync(args.filepath, args.newContent, "utf-8");
// Get lines for telemetry
const { added, removed } = calculateLinesOfCodeDiff(
args.oldContent,
args.newContent,
);
const language = getLanguageFromFilePath(args.filepath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
}
if (removed > 0) {
telemetryService.recordLinesOfCodeModified(
"removed",
removed,
language,
);
}
// Record file operation
return `Successfully edited ${args.filepath}`;
} catch (error) {
throw new Error(
`Error: failed to edit ${args.filepath}:\n ${
error instanceof Error ? error.message : String(error)
}`,
);
}
},
};

View file

@ -1,34 +0,0 @@
import * as path from "path";
export function parseSearchAndReplaceArgs(args: any): {
filepath: string;
diffs: string[];
} {
const { filepath, diffs: diffsArg } = args;
if (!filepath || !diffsArg) {
throw new Error("filepath and diffs args are required");
}
if (typeof filepath !== "string") {
throw new Error("filepath must be a string");
}
const diffs: string[] = [];
if (!Array.isArray(diffsArg)) {
throw new Error("diffs must be an array of string search/replace blocks");
}
diffsArg.forEach((diff, i) => {
if (typeof diff !== "string") {
throw new Error(`Diff at ${i + 1} is not a string`);
}
diffs.push(diff);
});
const fixedPath = filepath.replace(/\/|\\/g, path.sep);
return {
filepath: fixedPath,
diffs,
};
}

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,51 +0,0 @@
import { MinusCircleIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ContinueError } from "core";
import styled from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip";
const Div = styled.div`
padding: 8px;
background-color: #ff000011;
border-radius: ${defaultBorderRadius};
border: 1px solid #cc0000;
margin: 8px;
`;
interface ErrorStepContainerProps {
error: ContinueError;
onClose: () => void;
onDelete: () => void;
}
function ErrorStepContainer(props: ErrorStepContainerProps) {
return (
<div style={{ backgroundColor: vscBackground, position: "relative" }}>
<div
style={{
position: "absolute",
right: "12px",
top: "12px",
display: "flex",
}}
>
<HeaderButtonWithToolTip
text="Collapse"
onClick={() => props.onClose()}
>
<MinusCircleIcon width="1.3em" height="1.3em" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip text="Delete" onClick={() => props.onDelete()}>
<XMarkIcon width="1.3em" height="1.3em" />
</HeaderButtonWithToolTip>
</div>
<Div>
<pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>
{props.error.message as string}
</pre>
</Div>
</div>
);
}
export default ErrorStepContainer;

View file

@ -19,16 +19,9 @@ vi.mock("../../../components/ui", () => ({
useFontSize: () => 14,
}));
vi.mock("../../../util/clientTools/findAndReplaceUtils", async () => {
const actual = await vi.importActual(
"../../../util/clientTools/findAndReplaceUtils",
);
return {
performFindAndReplace: vi.fn(),
trimEmptyLines: actual.trimEmptyLines,
};
});
vi.mock("core/edit/searchAndReplace/performReplace", () => ({
executeFindAndReplace: vi.fn(),
}));
vi.mock("./utils", () => ({
getStatusIcon: vi.fn(() => <div data-testid="status-icon">✓</div>),
@ -43,12 +36,12 @@ vi.mock("react", async () => {
});
// Import mocked modules
import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { useAppSelector } from "../../../redux/hooks";
import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils";
const mockPost = vi.fn();
const mockUseAppSelector = useAppSelector as any;
const mockPerformFindAndReplace = performFindAndReplace as any;
const mockExecuteFindAndReplace = executeFindAndReplace as any;
describe("FindAndReplaceDisplay", () => {
const defaultProps = {
@ -100,7 +93,7 @@ describe("FindAndReplaceDisplay", () => {
return selector(mockState);
});
mockPerformFindAndReplace.mockImplementation(
mockExecuteFindAndReplace.mockImplementation(
(content: string, oldStr: string, newStr: string) => {
return content.replace(oldStr, newStr);
},
@ -224,7 +217,7 @@ describe("FindAndReplaceDisplay", () => {
},
] as EditOperation[];
mockPerformFindAndReplace
mockExecuteFindAndReplace
.mockReturnValueOnce("const new = 'value';\nconst other = 'test';")
.mockReturnValueOnce("const new = 'value';\nconst other = 'updated';");
@ -233,11 +226,11 @@ describe("FindAndReplaceDisplay", () => {
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(mockPerformFindAndReplace).toHaveBeenCalledTimes(2);
expect(mockExecuteFindAndReplace).toHaveBeenCalledTimes(2);
});
it("should handle diff generation errors", () => {
mockPerformFindAndReplace.mockImplementation(() => {
mockExecuteFindAndReplace.mockImplementation(() => {
throw new Error("Test error");
});
@ -252,7 +245,7 @@ describe("FindAndReplaceDisplay", () => {
it("should show 'No changes to display' when diff is empty", () => {
// Mock the function to return the exact same content (no changes)
mockPerformFindAndReplace.mockReturnValue(
mockExecuteFindAndReplace.mockReturnValue(
defaultProps.editingFileContents,
);
@ -322,7 +315,7 @@ describe("FindAndReplaceDisplay", () => {
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(mockPerformFindAndReplace).toHaveBeenCalledWith(
expect(mockExecuteFindAndReplace).toHaveBeenCalledWith(
"const old = 'value';\nconst other = 'test';",
"const old = 'value';",
"const new = 'value';",
@ -342,7 +335,7 @@ describe("FindAndReplaceDisplay", () => {
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(mockPerformFindAndReplace).toHaveBeenCalledWith(
expect(mockExecuteFindAndReplace).toHaveBeenCalledWith(
"const old = 'value';",
"const old = 'value';",
"const new = 'value';",

View file

@ -1,5 +1,7 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { trimEmptyLines } from "core/edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { EditOperation } from "core/tools/definitions/multiEdit";
import { renderContextItems } from "core/util/messageContent";
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
@ -13,10 +15,6 @@ import {
selectApplyStateByToolCallId,
selectToolCallById,
} from "../../../redux/selectors/selectToolCalls";
import {
performFindAndReplace,
trimEmptyLines,
} from "../../../util/clientTools/findAndReplaceUtils";
import { cn } from "../../../util/cn";
import { getStatusIcon } from "./utils";
@ -139,11 +137,11 @@ export function FindAndReplaceDisplay({
new_string: newString,
replace_all: replaceAll,
} = edits[i];
newContent = performFindAndReplace(
newContent = executeFindAndReplace(
newContent,
oldString,
newString,
replaceAll,
!!replaceAll,
i,
);
}

View file

@ -1,6 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ContextItem } from "core";
import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import posthog from "posthog-js";
import { callClientTool } from "../../util/clientTools/callClientTool";
import { selectSelectedChatModel } from "../slices/configSlice";
@ -45,7 +46,7 @@ export const callToolById = createAsyncThunk<
const selectedChatModel = selectSelectedChatModel(state);
posthog.capture("gui_tool_call_decision", {
posthog.capture("tool_call_decision", {
model: selectedChatModel,
decision: isAutoApproved ? "auto_accept" : "accept",
toolName: toolCallState.toolCall.function.name,
@ -63,7 +64,7 @@ export const callToolById = createAsyncThunk<
);
let output: ContextItem[] | undefined = undefined;
let errorMessage: string | undefined = undefined;
let error: ContinueError | undefined = undefined;
let streamResponse: boolean;
// IMPORTANT:
@ -80,14 +81,14 @@ export const callToolById = createAsyncThunk<
const {
output: clientToolOutput,
respondImmediately,
errorMessage: clientToolError,
error: clientToolError,
} = await callClientTool(toolCallState, {
dispatch,
ideMessenger: extra.ideMessenger,
getState,
});
output = clientToolOutput;
errorMessage = clientToolError;
error = clientToolError;
streamResponse = respondImmediately;
} else {
// Tool is called on core side
@ -98,12 +99,17 @@ export const callToolById = createAsyncThunk<
throw new Error(result.error);
} else {
output = result.content.contextItems;
errorMessage = result.content.errorMessage;
error = result.content.errorMessage
? new ContinueError(
ContinueErrorReason.Unspecified,
result.content.errorMessage,
)
: undefined;
}
streamResponse = true;
}
if (errorMessage) {
if (error) {
dispatch(
updateToolCallOutput({
toolCallId,
@ -112,7 +118,7 @@ export const callToolById = createAsyncThunk<
icon: "problems",
name: "Tool Call Error",
description: "Tool Call Failed",
content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`,
content: `${toolCallState.toolCall.function.name} failed with the message: ${error.message}\n\nPlease try something else or request further instructions.`,
hidden: false,
},
],
@ -129,16 +135,16 @@ export const callToolById = createAsyncThunk<
// Capture telemetry for tool call execution outcome with duration
const duration_ms = Date.now() - startTime;
posthog.capture("gui_tool_call_outcome", {
posthog.capture("tool_call_outcome", {
model: selectedChatModel,
succeeded: errorMessage === undefined,
succeeded: !error,
toolName: toolCallState.toolCall.function.name,
errorMessage: errorMessage,
errorReason: error?.reason,
duration_ms: duration_ms,
});
if (streamResponse) {
if (errorMessage) {
if (error) {
logToolUsage(toolCallState, false, false, extra.ideMessenger, output);
dispatch(
errorToolCall({

View file

@ -27,7 +27,7 @@ export const cancelToolCallThunk = createAsyncThunk<
if (toolCallState) {
// Track tool call rejection
posthog.capture("gui_tool_call_decision", {
posthog.capture("tool_call_decision", {
model: selectedChatModel,
decision: "reject",
toolName: toolCallState.toolCall.function.name,

View file

@ -567,7 +567,7 @@ describe("streamResponseThunk - tool calls", () => {
// Verify telemetry events for auto-approved tool execution
// Use partial matching to allow additional fields (e.g. model) in payload
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_decision",
"tool_call_decision",
expect.objectContaining({
decision: "auto_accept",
toolName: "search_codebase",
@ -576,11 +576,11 @@ describe("streamResponseThunk - tool calls", () => {
);
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_outcome",
"tool_call_outcome",
expect.objectContaining({
succeeded: true,
toolName: "search_codebase",
errorMessage: undefined,
errorReason: undefined,
duration_ms: expect.any(Number),
}),
);
@ -2819,7 +2819,7 @@ describe("streamResponseThunk - tool calls", () => {
// Verify telemetry events for manual approval flow
// Use partial matching to allow additional fields (e.g. model) in payload
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_decision",
"tool_call_decision",
expect.objectContaining({
decision: "accept",
toolName: "search_codebase",
@ -2828,11 +2828,11 @@ describe("streamResponseThunk - tool calls", () => {
);
expect(mockPosthog.capture).toHaveBeenCalledWith(
"gui_tool_call_outcome",
"tool_call_outcome",
expect.objectContaining({
succeeded: true,
toolName: "search_codebase",
errorMessage: undefined,
errorReason: undefined,
duration_ms: expect.any(Number),
}),
);

View file

@ -1,5 +1,6 @@
import { ContextItem, ToolCallState } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { AppThunkDispatch, RootState } from "../../redux/store";
import { editToolImpl } from "./editImpl";
@ -18,7 +19,7 @@ export interface ClientToolOutput {
}
export interface ClientToolResult extends ClientToolOutput {
errorMessage: string | undefined;
error?: ContinueError;
}
export type ClientToolImpl = (
@ -51,18 +52,16 @@ export async function callClientTool(
default:
throw new Error(`Invalid client tool name ${toolCall.function.name}`);
}
return {
...output,
errorMessage: undefined,
};
return output;
} catch (e) {
let errorMessage = `${e}`;
if (e instanceof Error) {
errorMessage = e.message;
}
return {
respondImmediately: true,
errorMessage,
error:
e instanceof ContinueError
? e
: e instanceof Error
? new ContinueError(ContinueErrorReason.Unspecified, e.message)
: new ContinueError(ContinueErrorReason.Unknown, String(e)),
output: undefined,
};
}

View file

@ -1,477 +0,0 @@
import { EditOperation } from "core/tools/definitions/multiEdit";
import { describe, expect, it } from "vitest";
import {
EMPTY_NON_FIRST_EDIT_MESSAGE,
FOUND_MULTIPLE_FIND_STRINGS_ERROR,
performFindAndReplace,
trimEmptyLines,
validateCreatingForMultiEdit,
validateSingleEdit,
} from "./findAndReplaceUtils";
describe("performFindAndReplace", () => {
describe("normal cases", () => {
it("should replace single occurrence by default", () => {
const content = "Hello world\nThis is a test file\nGoodbye";
const result = performFindAndReplace(content, "Hello", "Hi");
expect(result).toBe("Hi world\nThis is a test file\nGoodbye");
});
it("should replace single occurrence when replaceAll is false", () => {
const content = "Hello world\nHello again";
const result = performFindAndReplace(
content,
"Hello world",
"Hi world",
false,
);
expect(result).toBe("Hi world\nHello again");
});
it("should replace all occurrences when replaceAll is true", () => {
const content = "Hello world\nHello again\nHello there";
const result = performFindAndReplace(content, "Hello", "Hi", true);
expect(result).toBe("Hi world\nHi again\nHi there");
});
it("should handle empty new string (deletion)", () => {
const content = "Hello world";
const result = performFindAndReplace(content, "Hello ", "");
expect(result).toBe("world");
});
it("should handle empty old string replacement (insertion at start)", () => {
const content = "";
const result = performFindAndReplace(content, "", "Hello world");
expect(result).toBe("Hello world");
});
it("should preserve whitespace and indentation", () => {
const content =
"function test() {\n const value = 'old';\n return value;\n}";
const result = performFindAndReplace(
content,
" const value = 'old';",
" const value = 'new';",
);
expect(result).toBe(
"function test() {\n const value = 'new';\n return value;\n}",
);
});
it("should handle multiline strings", () => {
const content = "line1\nline2\nline3";
const result = performFindAndReplace(
content,
"line1\nline2",
"newline1\nnewline2",
);
expect(result).toBe("newline1\nnewline2\nline3");
});
});
describe("special character handling", () => {
it("should handle regex special characters in old string", () => {
const content = "const regex = /[a-z]+/g;";
const result = performFindAndReplace(content, "/[a-z]+/g", "/[A-Z]+/g");
expect(result).toBe("const regex = /[A-Z]+/g;");
});
it("should handle dollar signs in strings", () => {
const content = 'const text = "Hello $world"';
const result = performFindAndReplace(
content,
'"Hello $world"',
'"Hi $universe"',
);
expect(result).toBe('const text = "Hi $universe"');
});
it("should handle backslashes", () => {
const content = 'const path = "C:\\Users\\test"';
const result = performFindAndReplace(
content,
"C:\\Users\\test",
"D:\\Users\\test",
);
expect(result).toBe('const path = "D:\\Users\\test"');
});
it("should handle parentheses", () => {
const content = "function test() { return 'old'; }";
const result = performFindAndReplace(
content,
"() { return 'old'; }",
"() { return 'new'; }",
);
expect(result).toBe("function test() { return 'new'; }");
});
it("should handle square brackets", () => {
const content = "const arr = [1, 2, 3];";
const result = performFindAndReplace(content, "[1, 2, 3]", "[4, 5, 6]");
expect(result).toBe("const arr = [4, 5, 6];");
});
});
describe("replaceAll behavior", () => {
it("should replace all occurrences including partial matches", () => {
const content = "test testing tested test";
const result = performFindAndReplace(content, "test", "exam", true);
expect(result).toBe("exam examing examed exam");
});
it("should replace all occurrences with empty string", () => {
const content = "remove this remove that remove everything";
const result = performFindAndReplace(content, "remove ", "", true);
expect(result).toBe("this that everything");
});
it("should handle overlapping patterns correctly", () => {
const content = "aaaa";
const result = performFindAndReplace(content, "aa", "b", true);
expect(result).toBe("bb");
});
});
describe("error cases", () => {
it("should throw error when string not found", () => {
const content = "Hello world";
expect(() => {
performFindAndReplace(content, "xyz", "abc");
}).toThrow('string not found in file: "xyz"');
});
it("should throw error with edit context when string not found", () => {
const content = "Hello world";
expect(() => {
performFindAndReplace(content, "xyz", "abc", false, 2);
}).toThrow('edit at index 2: string not found in file: "xyz"');
});
it("should throw error when multiple occurrences exist and replaceAll is false", () => {
const content = "Hello world\nHello again\nHello there";
expect(() => {
performFindAndReplace(content, "Hello", "Hi", false);
}).toThrow(
`String "Hello" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`,
);
});
it("should throw error with edit context for multiple occurrences", () => {
const content = "test test test";
expect(() => {
performFindAndReplace(content, "test", "exam", false, 1);
}).toThrow(
`edit at index 1: String "test" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`,
);
});
});
describe("edge cases", () => {
it("should handle single character replacement", () => {
const content = "a b c";
const result = performFindAndReplace(content, "b", "x");
expect(result).toBe("a x c");
});
it("should handle very long strings", () => {
const longString = "a".repeat(10000);
const content = `start${longString}end`;
const result = performFindAndReplace(content, longString, "short");
expect(result).toBe("startshortend");
});
it("should handle strings at beginning of content", () => {
const content = "start middle end";
const result = performFindAndReplace(content, "start", "begin");
expect(result).toBe("begin middle end");
});
it("should handle strings at end of content", () => {
const content = "start middle end";
const result = performFindAndReplace(content, "end", "finish");
expect(result).toBe("start middle finish");
});
it("should handle entire content replacement", () => {
const content = "replace everything";
const result = performFindAndReplace(
content,
"replace everything",
"new content",
);
expect(result).toBe("new content");
});
});
});
describe("validateSingleEdit", () => {
describe("valid inputs", () => {
it("should not throw for valid non-empty strings", () => {
expect(() => {
validateSingleEdit("old", "new");
}).not.toThrow();
});
it("should allow empty old_string for file creation", () => {
expect(() => {
validateSingleEdit("", "new content");
}).not.toThrow();
});
it("should allow empty new_string for deletion", () => {
expect(() => {
validateSingleEdit("delete me", "");
}).not.toThrow();
});
it("should allow multiline strings", () => {
expect(() => {
validateSingleEdit("line1\nline2", "newline1\nnewline2");
}).not.toThrow();
});
it("should allow special characters", () => {
expect(() => {
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
}).not.toThrow();
});
});
describe("invalid inputs", () => {
it("should throw error when old_string is null", () => {
expect(() => {
validateSingleEdit(null as any, "new");
}).toThrow("old_string is required");
});
it("should throw error when old_string is undefined", () => {
expect(() => {
validateSingleEdit(undefined as any, "new");
}).toThrow("old_string is required");
});
it("should throw error when new_string is undefined", () => {
expect(() => {
validateSingleEdit("old", undefined as any);
}).toThrow("new_string is required");
});
it("should throw error when old_string and new_string are identical", () => {
expect(() => {
validateSingleEdit("same", "same");
}).toThrow("old_string and new_string must be different");
});
it("should throw error when both are empty strings", () => {
expect(() => {
validateSingleEdit("", "");
}).toThrow("old_string and new_string must be different");
});
});
describe("error messages with context", () => {
it("should include edit number in error messages when index provided", () => {
expect(() => {
validateSingleEdit(null as any, "new", 2);
}).toThrow("edit at index 2: old_string is required");
});
it("should include edit number for new_string errors", () => {
expect(() => {
validateSingleEdit("old", undefined as any, 0);
}).toThrow("edit at index 0: new_string is required");
});
it("should include edit number for identical strings error", () => {
expect(() => {
validateSingleEdit("same", "same", 4);
}).toThrow(
"edit at index 4: old_string and new_string must be different",
);
});
it("should not include context when index not provided", () => {
expect(() => {
validateSingleEdit("same", "same");
}).toThrow("old_string and new_string must be different");
});
});
});
describe("validateCreatingForMultiEdit", () => {
describe("single edit scenarios", () => {
it("should return true for creating with single edit", () => {
const edits: EditOperation[] = [
{ old_string: "", new_string: "new file content" },
];
const isCreating = validateCreatingForMultiEdit(edits);
expect(isCreating).toBe(true);
});
it("should return false for editing with single edit", () => {
const edits: EditOperation[] = [{ old_string: "old", new_string: "new" }];
const isCreating = validateCreatingForMultiEdit(edits);
expect(isCreating).toBe(false);
});
});
describe("multiple edit scenarios - editing existing file", () => {
it("should return false for multiple edits on existing file", () => {
const edits: EditOperation[] = [
{ old_string: "old1", new_string: "new1" },
{ old_string: "old2", new_string: "new2" },
{ old_string: "old3", new_string: "new3" },
];
const isCreating = validateCreatingForMultiEdit(edits);
expect(isCreating).toBe(false);
});
it("should allow multiple valid edits on existing file", () => {
const edits: EditOperation[] = [
{ old_string: "import old", new_string: "import new" },
{ old_string: "function old()", new_string: "function new()" },
{ old_string: "return old;", new_string: "return new;" },
];
expect(() => validateCreatingForMultiEdit(edits)).not.toThrow();
expect(validateCreatingForMultiEdit(edits)).toBe(false);
});
});
describe("error cases", () => {
it("should throw error when trying to make subsequent edits on file creation", () => {
const edits: EditOperation[] = [
{ old_string: "", new_string: "new file content" },
{ old_string: "old", new_string: "new" },
];
expect(() => {
validateCreatingForMultiEdit(edits);
}).toThrow("cannot make subsequent edits on a file you are creating");
});
it("should throw error when empty old_string appears in non-first edit", () => {
const edits: EditOperation[] = [
{ old_string: "old1", new_string: "new1" },
{ old_string: "", new_string: "new2" },
];
expect(() => {
validateCreatingForMultiEdit(edits);
}).toThrow(`edit at index 1: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`);
});
it("should throw error with correct edit number for empty old_string", () => {
const edits: EditOperation[] = [
{ old_string: "old1", new_string: "new1" },
{ old_string: "old2", new_string: "new2" },
{ old_string: "", new_string: "new3" },
];
expect(() => {
validateCreatingForMultiEdit(edits);
}).toThrow(`edit at index 2: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`);
});
it("should throw error for multiple empty old_strings in subsequent edits", () => {
const edits: EditOperation[] = [
{ old_string: "old1", new_string: "new1" },
{ old_string: "", new_string: "new2" },
{ old_string: "", new_string: "new3" },
];
expect(() => {
validateCreatingForMultiEdit(edits);
}).toThrow(`edit at index 1: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`);
});
});
describe("edge cases", () => {
it("should handle empty edits array gracefully", () => {
const edits: EditOperation[] = [];
// This should not throw, but would likely cause issues elsewhere
// The function doesn't explicitly handle empty arrays
expect(() => {
validateCreatingForMultiEdit(edits);
}).toThrow(); // Will throw because edits[0] is undefined
});
it("should handle complex edit operations", () => {
const edits: EditOperation[] = [
{
old_string: "function oldFunction() {\n return 'old';\n}",
new_string: "function newFunction() {\n return 'new';\n}",
replace_all: false,
},
{
old_string: "const OLD_CONSTANT",
new_string: "const NEW_CONSTANT",
replace_all: true,
},
];
expect(() => validateCreatingForMultiEdit(edits)).not.toThrow();
expect(validateCreatingForMultiEdit(edits)).toBe(false);
});
it("should handle edits with replace_all flags", () => {
const edits: EditOperation[] = [
{ old_string: "old", new_string: "new", replace_all: true },
{ old_string: "test", new_string: "exam", replace_all: false },
];
expect(() => validateCreatingForMultiEdit(edits)).not.toThrow();
expect(validateCreatingForMultiEdit(edits)).toBe(false);
});
});
});
describe("trimEmptyLines", () => {
it("trims leading empty lines from start", () => {
const input = ["", "", "a", "", "b"];
const result = trimEmptyLines({ lines: input, fromEnd: false });
expect(result).toEqual(["a", "", "b"]);
});
it("trims trailing empty lines from end", () => {
const input = ["a", "", "b", "", ""];
const result = trimEmptyLines({ lines: input, fromEnd: true });
expect(result).toEqual(["a", "", "b"]);
});
it("returns empty array when all lines are empty", () => {
const input = ["", "", ""];
const result = trimEmptyLines({ lines: input, fromEnd: false });
expect(result).toEqual([]);
});
});

View file

@ -1,116 +0,0 @@
import { EditOperation } from "core/tools/definitions/multiEdit";
export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
"Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.";
/**
* Performs a find and replace operation on text content with proper handling of special characters
*/
export function performFindAndReplace(
content: string,
oldString: string,
newString: string,
replaceAll: boolean = false,
index?: number, // For error messages
): string {
const errorContext = index !== undefined ? `edit at index ${index}: ` : "";
// Check if old_string exists in current content
if (!content.includes(oldString)) {
throw new Error(`${errorContext}string not found in file: "${oldString}"`);
}
if (replaceAll) {
// Replace all occurrences using replaceAll for proper handling of special characters
return content.replaceAll(oldString, newString);
} else {
// Handle empty oldString case (insertion)
if (oldString === "") {
return newString + content;
}
// Count occurrences using indexOf for proper handling of special characters
let count = 0;
let searchIndex = content.indexOf(oldString);
while (searchIndex !== -1) {
count++;
searchIndex = content.indexOf(oldString, searchIndex + 1);
}
if (count > 1) {
throw new Error(
`${errorContext}String "${oldString}" appears ${count} times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`,
);
}
// Replace only the first occurrence
const firstIndex = content.indexOf(oldString);
return (
content.substring(0, firstIndex) +
newString +
content.substring(firstIndex + oldString.length)
);
}
}
/**
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: string,
newString: string,
index?: number,
): void {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (!oldString && oldString !== "") {
throw new Error(`${context}old_string is required`);
}
if (newString === undefined) {
throw new Error(`${context}new_string is required`);
}
if (oldString === newString) {
throw new Error(`${context}old_string and new_string must be different`);
}
}
export const EMPTY_NON_FIRST_EDIT_MESSAGE =
"contains empty old_string. Only the first edit can contain an empty old_string, which is only used for file creation.";
export function validateCreatingForMultiEdit(edits: EditOperation[]) {
const isCreating = edits[0].old_string === "";
if (edits.length > 1) {
if (isCreating) {
throw new Error(
"cannot make subsequent edits on a file you are creating",
);
} else {
for (let i = 1; i < edits.length; i++) {
if (edits[i].old_string === "") {
throw new Error(
`edit at index ${i}: ${EMPTY_NON_FIRST_EDIT_MESSAGE}`,
);
}
}
}
}
return isCreating;
}
export function trimEmptyLines({
lines,
fromEnd,
}: {
lines: string[];
fromEnd: boolean;
}): string[] {
lines = fromEnd ? lines.toReversed() : lines.slice();
const newLines: string[] = [];
let shouldContinueRemoving = true;
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (shouldContinueRemoving && line.trim() === "") continue;
shouldContinueRemoving = false;
newLines.push(line);
}
return fromEnd ? newLines.reverse() : newLines;
}

View file

@ -1,8 +1,8 @@
import { ContinueErrorReason } from "core/util/errors";
import * as ideUtils from "core/util/ideUtils";
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolExtras } from "./callClientTool";
import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "./findAndReplaceUtils";
import { multiEditImpl } from "./multiEditImpl";
vi.mock("uuid", () => ({
@ -11,26 +11,21 @@ vi.mock("uuid", () => ({
vi.mock("core/util/ideUtils", () => ({
resolveRelativePathInDir: vi.fn(),
inferResolvedUriFromRelativePath: vi.fn(),
}));
vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({
applyForEditTool: vi.fn(),
}));
describe("multiEditImpl", () => {
describe("multiEditImpl GUI specific", () => {
let mockExtras: ClientToolExtras;
let mockResolveRelativePathInDir: Mock;
let mockInferResolvedUriFromRelativePath: Mock;
let mockApplyForEditTool: Mock;
beforeEach(() => {
vi.clearAllMocks();
mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir);
mockInferResolvedUriFromRelativePath = vi.mocked(
ideUtils.inferResolvedUriFromRelativePath,
);
mockApplyForEditTool = vi.mocked(applyForEditTool);
mockExtras = {
@ -48,71 +43,45 @@ describe("multiEditImpl", () => {
};
});
describe("argument validation", () => {
describe("filepath validation", () => {
it("should throw if filepath is missing", async () => {
await expect(
multiEditImpl({ edits: [] }, "id", mockExtras),
).rejects.toThrow("filepath is required");
});
it("should throw if edits array is empty", async () => {
await expect(
multiEditImpl({ filepath: "test.txt", edits: [] }, "id", mockExtras),
).rejects.toThrow(
"edits array is required and must contain at least one edit",
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingFilepath,
}),
);
});
it("should throw if edit has invalid old_string", async () => {
await expect(
multiEditImpl(
{
filepath: "test.txt",
edits: [{ old_string: null, new_string: "test" }],
},
"id",
mockExtras,
),
).rejects.toThrow("edit at index 0: old_string is required");
});
it("should throw if file does not exist in workspace", async () => {
mockResolveRelativePathInDir.mockResolvedValue(null);
it("should throw if edit has undefined new_string", async () => {
await expect(
multiEditImpl(
{
filepath: "test.txt",
edits: [{ old_string: "test", new_string: undefined }],
filepath: "nonexistent.txt",
edits: [{ old_string: "test", new_string: "new" }],
},
"id",
mockExtras,
),
).rejects.toThrow("edit at index 0: new_string is required");
});
it("should throw if old_string equals new_string", async () => {
await expect(
multiEditImpl(
{
filepath: "test.txt",
edits: [{ old_string: "same", new_string: "same" }],
},
"id",
mockExtras,
),
).rejects.toThrow(
"edit at index 0: old_string and new_string must be different",
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FileNotFound,
}),
);
});
});
describe("sequential edits", () => {
describe("GUI integration", () => {
beforeEach(() => {
mockResolveRelativePathInDir.mockResolvedValue(
"file:///dir/test/file.txt",
);
});
it("should apply single edit", async () => {
it("should read file from IDE and dispatch edit", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("Hello world");
@ -126,6 +95,9 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.ide.readFile).toHaveBeenCalledWith(
"file:///dir/test/file.txt",
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
@ -135,188 +107,30 @@ describe("multiEditImpl", () => {
});
});
it("should apply multiple edits sequentially", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("Hello world\nGoodbye world");
it("should use editingFileContents if provided instead of reading file", async () => {
const editingContents = "Custom content";
await multiEditImpl(
{
filepath: "file.txt",
edits: [
{ old_string: "Hello", new_string: "Hi" },
{ old_string: "world", new_string: "universe", replace_all: true },
],
edits: [{ old_string: "content", new_string: "text" }],
editingFileContents: editingContents,
},
"id",
mockExtras,
);
expect(mockExtras.ideMessenger.ide.readFile).not.toHaveBeenCalled();
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "Hi universe\nGoodbye universe",
text: "Custom text",
filepath: "file:///dir/test/file.txt",
isSearchAndReplace: true,
});
});
it("should handle edits that depend on previous edits", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("const x = 1;");
await multiEditImpl(
{
filepath: "file.txt",
edits: [
{ old_string: "const x", new_string: "let x" },
{ old_string: "let x = 1;", new_string: "let x = 2;" },
],
},
"id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "let x = 2;",
filepath: "file:///dir/test/file.txt",
isSearchAndReplace: true,
});
});
it("should throw if string not found in edit sequence", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("Hello world");
await expect(
multiEditImpl(
{
filepath: "file.txt",
edits: [
{ old_string: "Hello", new_string: "Hi" },
{ old_string: "not found", new_string: "test" },
],
},
"id",
mockExtras,
),
).rejects.toThrow(
'edit at index 1: string not found in file: "not found"',
);
});
it("should throw if multiple occurrences without replace_all", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("test test test");
await expect(
multiEditImpl(
{
filepath: "file.txt",
edits: [{ old_string: "test", new_string: "replaced" }],
},
"id",
mockExtras,
),
).rejects.toThrow(
`edit at index 0: String "test" appears 3 times in the file. ${FOUND_MULTIPLE_FIND_STRINGS_ERROR}`,
);
});
});
describe("file creation", () => {
it("should create new file with empty old_string", async () => {
mockResolveRelativePathInDir.mockResolvedValue(null);
mockInferResolvedUriFromRelativePath.mockResolvedValue(
"file:///infered/new.txt",
);
await multiEditImpl(
{
filepath: "new.txt",
edits: [{ old_string: "", new_string: "New content\nLine 2" }],
},
"id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "New content\nLine 2",
filepath: "file:///infered/new.txt",
isSearchAndReplace: true,
});
});
});
describe("replace_all functionality", () => {
beforeEach(() => {
mockResolveRelativePathInDir.mockResolvedValue(
"file:///dir/test/file.txt",
);
});
it("should replace all occurrences when specified", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("foo bar foo baz foo");
await multiEditImpl(
{
filepath: "file.txt",
edits: [{ old_string: "foo", new_string: "qux", replace_all: true }],
},
"id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "qux bar qux baz qux",
filepath: "file:///dir/test/file.txt",
isSearchAndReplace: true,
});
});
it("should handle mixed replace_all settings", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("x y x z x");
await multiEditImpl(
{
filepath: "file.txt",
edits: [
{ old_string: "x", new_string: "a", replace_all: true },
{ old_string: "y", new_string: "b" },
],
},
"id",
mockExtras,
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "a b a z a",
filepath: "file:///dir/test/file.txt",
isSearchAndReplace: true,
});
});
});
describe("error handling", () => {
it("should wrap readFile errors", async () => {
mockResolveRelativePathInDir.mockResolvedValue(
"file:///dir/test/file.txt",
);
it("should wrap IDE readFile errors", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockRejectedValue(new Error("Read failed"));
@ -335,7 +149,7 @@ describe("multiEditImpl", () => {
});
describe("return value", () => {
it("should return correct structure", async () => {
it("should return structure for async completion", async () => {
mockResolveRelativePathInDir.mockResolvedValue(
"file:///dir/test/file.txt",
);

View file

@ -1,86 +1,32 @@
import {
inferResolvedUriFromRelativePath,
resolveRelativePathInDir,
} from "core/util/ideUtils";
import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation";
import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
import {
performFindAndReplace,
validateCreatingForMultiEdit,
validateSingleEdit,
} from "./findAndReplaceUtils";
import { validateSearchAndReplaceFilepath } from "./singleFindAndReplaceImpl";
export const multiEditImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
const { filepath, edits, editingFileContents } = args;
const { filepath, editingFileContents } = args;
const streamId = uuid();
// Validate arguments
if (!filepath) {
throw new Error("filepath is required");
}
if (!edits || !Array.isArray(edits) || edits.length === 0) {
throw new Error(
"edits array is required and must contain at least one edit",
);
}
// Validate each edit operation
for (let i = 0; i < edits.length; i++) {
const edit = edits[i];
validateSingleEdit(edit.old_string, edit.new_string, i);
}
// Check if this is creating a new file (first edit has empty old_string)
const isCreatingNewFile = validateCreatingForMultiEdit(edits);
const resolvedUri = await resolveRelativePathInDir(
const resolvedUri = await validateSearchAndReplaceFilepath(
filepath,
extras.ideMessenger.ide,
);
let newContent: string;
let fileUri: string;
if (isCreatingNewFile) {
if (resolvedUri) {
throw new Error(
`file ${filepath} already exists, cannot create new file`,
);
}
newContent = edits[0].new_string;
const dirs = await extras.ideMessenger.ide.getWorkspaceDirs();
fileUri = await inferResolvedUriFromRelativePath(
filepath,
extras.ideMessenger.ide,
dirs,
);
} else {
if (!resolvedUri) {
throw new Error(
`file ${filepath} does not exist. If you are trying to edit it, correct the filepath. If you are trying to create it, you must pass old_string=""`,
);
}
newContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
fileUri = resolvedUri;
for (let i = 0; i < edits.length; i++) {
const { old_string, new_string, replace_all } = edits[i];
newContent = performFindAndReplace(
newContent,
old_string,
new_string,
replace_all,
i,
);
}
}
const { edits } = validateMultiEdit(args);
// Apply the changes to the file
const currentContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
const fileUri = resolvedUri;
const newContent = executeMultiFindAndReplace(currentContent, edits);
const streamId = uuid();
void extras.dispatch(
applyForEditTool({
streamId,

View file

@ -1,3 +1,4 @@
import { ContinueErrorReason } from "core/util/errors";
import * as ideUtils from "core/util/ideUtils";
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
@ -45,6 +46,14 @@ describe("singleFindAndReplaceImpl", () => {
});
describe("argument validation", () => {
beforeEach(() => {
// For validation tests, make the file exist so we can test validation errors
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("content");
});
it("should throw error if filepath is missing", async () => {
const args = {
old_string: "test",
@ -53,7 +62,11 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("filepath is required");
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingFilepath,
}),
);
});
it("should throw error if old_string is missing", async () => {
@ -64,7 +77,11 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("old_string is required");
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error if new_string is missing", async () => {
@ -75,7 +92,11 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("new_string is required");
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should throw error if old_string and new_string are the same", async () => {
@ -87,7 +108,11 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("old_string and new_string must be different");
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
});
@ -103,7 +128,11 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("File nonexistent.txt does not exist");
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FileNotFound,
}),
);
});
it("should resolve relative file paths", async () => {
@ -148,7 +177,11 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow(`string not found in file: "not found"`);
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should replace single occurrence", async () => {
@ -188,8 +221,10 @@ describe("singleFindAndReplaceImpl", () => {
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow(
'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});

View file

@ -1,11 +1,31 @@
import { IDE } from "core";
import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
import {
performFindAndReplace,
validateSingleEdit,
} from "./findAndReplaceUtils";
export async function validateSearchAndReplaceFilepath(
filepath: any,
ide: IDE,
) {
if (!filepath || typeof filepath !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"filepath (string) is required",
);
}
const resolvedFilepath = await resolveRelativePathInDir(filepath, ide);
if (!resolvedFilepath) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${filepath} does not exist`,
);
}
return resolvedFilepath;
}
export const singleFindAndReplaceImpl: ClientToolImpl = async (
args,
@ -20,43 +40,34 @@ export const singleFindAndReplaceImpl: ClientToolImpl = async (
editingFileContents,
} = args;
const streamId = uuid();
// Validate arguments
if (!filepath) {
throw new Error("filepath is required");
}
validateSingleEdit(old_string, new_string);
// Resolve the file path
const resolvedFilepath = await resolveRelativePathInDir(
const resolvedUri = await validateSearchAndReplaceFilepath(
filepath,
extras.ideMessenger.ide,
);
if (!resolvedFilepath) {
throw new Error(`File ${filepath} does not exist`);
}
validateSingleEdit(old_string, new_string);
// Read the current file content
const originalContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedFilepath));
(await extras.ideMessenger.ide.readFile(resolvedUri));
// Perform the find and replace operation
const newContent = performFindAndReplace(
const newContent = executeFindAndReplace(
originalContent,
old_string,
new_string,
replace_all,
0,
);
// Apply the changes to the file
const streamId = uuid();
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: newContent,
filepath: resolvedFilepath,
filepath: resolvedUri,
isSearchAndReplace: true,
}),
);