Merge branch 'main' of github.com:continuedev/continue into jacob/con-3748

This commit is contained in:
Jacob Kim 2025-08-29 16:19:54 -07:00
commit b16a73b979
44 changed files with 337 additions and 3054 deletions

View file

@ -0,0 +1,55 @@
name: "Check LLM Changes"
description: "Check if LLM-related files have changed and set environment variable to control API tests"
outputs:
llm_changed:
description: "Whether LLM-related files have changed"
value: ${{ steps.check-changes.outputs.llm_changed }}
ignore_api_tests:
description: "Whether to ignore API tests based on file changes and other conditions"
value: ${{ steps.check-changes.outputs.ignore_api_tests }}
inputs:
is_fork:
description: "Whether this is a fork PR"
required: false
default: "false"
is_dependabot:
description: "Whether this is a dependabot PR"
required: false
default: "false"
runs:
using: "composite"
steps:
- name: Check if LLM-related files changed
id: check-changes
shell: bash
run: |
if [ "${{ github.event_name }}" = "push" ]; then
# For push events, compare against the previous commit
CHANGED_FILES=$(git diff --name-only HEAD~1...HEAD)
else
# For PR events, compare against the base branch
git fetch origin ${{ github.event.pull_request.base.ref }}
CHANGED_FILES=$(git diff --name-only origin/${{ github.event.pull_request.base.ref }}...HEAD)
fi
echo "Changed files:"
echo "$CHANGED_FILES"
# Check if any LLM-related files were changed
LLM_CHANGED=false
if echo "$CHANGED_FILES" | grep -E "(^core/llm/|^core/index\.ts|^core/package\.json|^core/jest\.config\.js|^packages/.*/(.*llm.*|.*openai.*|.*anthropic.*)|\.github/workflows/pr-checks\.yaml|\.github/actions/check-llm-changes/)" > /dev/null; then
LLM_CHANGED=true
fi
echo "LLM files changed: $LLM_CHANGED"
echo "llm_changed=$LLM_CHANGED" >> $GITHUB_OUTPUT
# Determine whether to ignore API tests
IGNORE_API_TESTS=false
if [ "${{ inputs.is_fork }}" = "true" ] || [ "${{ inputs.is_dependabot }}" = "true" ] || [ "$LLM_CHANGED" = "false" ]; then
IGNORE_API_TESTS=true
fi
echo "Ignore API tests: $IGNORE_API_TESTS"
echo "ignore_api_tests=$IGNORE_API_TESTS" >> $GITHUB_OUTPUT

View file

@ -44,6 +44,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0 # Needed for git diff to work
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -52,6 +54,13 @@ jobs:
component: core
include-root: true
- name: Check if LLM-related files changed
id: llm-changes
uses: ./.github/actions/check-llm-changes
with:
is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
- name: Type check and lint
run: |
cd core
@ -66,7 +75,7 @@ jobs:
npm test
npm run vitest
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@ -180,16 +189,25 @@ jobs:
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0 # Needed for git diff to work
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Check if LLM-related files changed
id: llm-changes
uses: ./.github/actions/check-llm-changes
with:
is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
- name: Test and check ${{ matrix.package }}
run: |
cd packages/${{ matrix.package }}
npm ci
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -155,9 +155,27 @@ describe("DocsCrawler", () => {
test(
`Default crawler common site: ${url}`,
async () => {
const { pages, crawler } = await runCrawl(url);
expect(pages.length).toBeGreaterThanOrEqual(1);
expect(crawler).toEqual("default");
// Retry logic to handle flaky network requests to TRIAL_PROXY_URL
let lastError;
const maxRetries = 3;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const { pages, crawler } = await runCrawl(url);
expect(pages.length).toBeGreaterThanOrEqual(1);
expect(crawler).toEqual("default");
return; // Test passed, exit retry loop
} catch (error) {
lastError = error;
if (attempt === maxRetries) {
throw error; // Final attempt failed, throw the error
}
// Wait before retrying (exponential backoff)
await new Promise((resolve) =>
setTimeout(resolve, 1000 * attempt),
);
}
}
},
TIMEOUT_MS,
);

18
core/llm/llms/TARS.ts Normal file
View file

@ -0,0 +1,18 @@
import { LLMOptions } from "../../index.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
class TARS extends OpenAI {
static providerName = "tars";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.router.tetrate.ai/v1",
model: "gpt-5-mini",
promptTemplates: {
edit: osModelsEditPrompt,
},
useLegacyCompletionsEndpoint: false,
};
}
export default TARS;

View file

@ -53,6 +53,7 @@ import SambaNova from "./SambaNova";
import Scaleway from "./Scaleway";
import SiliconFlow from "./SiliconFlow";
import ContinueProxy from "./stubs/ContinueProxy";
import TARS from "./TARS";
import TestLLM from "./Test";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
@ -116,6 +117,7 @@ export const LLMClasses = [
Inception,
Voyage,
LlamaStack,
TARS,
];
export async function llmFromDescription(

View file

@ -7,6 +7,9 @@ export interface ProcessedItem {
outcome: NextEditOutcome; // Result from the model
}
/**
* Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts
*/
/**
* This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain.
* I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background.

View file

@ -25,7 +25,7 @@ import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
import { NextEditLoggingService } from "./NextEditLoggingService.js";
import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
import {
ModelSpecificContext,
NextEditOutcome,
@ -71,7 +71,7 @@ export class NextEditProvider {
private previousCompletions: NextEditOutcome[] = [];
// Model-specific provider instance.
private modelProvider: BaseNextEditProvider | null = null;
private modelProvider: BaseNextEditModelProvider | null = null;
private constructor(
private readonly configHandler: ConfigHandler,

View file

@ -1,10 +1,10 @@
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
export class NextEditProviderFactory {
static createProvider(modelName: string): BaseNextEditProvider {
static createProvider(modelName: string): BaseNextEditModelProvider {
if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
return new MercuryCoderProvider();
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {

View file

@ -24,7 +24,7 @@ import { isWhitespaceOnlyDeletion } from "../utils.js";
* This and its children are responsible for pre/post processing of prompts and outcomes.
* Different next edit models have very different requirements.
*/
export abstract class BaseNextEditProvider {
export abstract class BaseNextEditModelProvider {
protected readonly modelName: string;
constructor(modelName: string) {

View file

@ -11,9 +11,9 @@ import {
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js";
export class InstinctProvider extends BaseNextEditProvider {
export class InstinctProvider extends BaseNextEditModelProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {

View file

@ -11,9 +11,9 @@ import {
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js";
export class MercuryCoderProvider extends BaseNextEditProvider {
export class MercuryCoderProvider extends BaseNextEditModelProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {

View file

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

View file

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

View file

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

View file

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

View file

@ -1,112 +0,0 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface SearchAndReplaceInFileArgs {
filepath: string;
diffs: string[];
}
// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE`;
const SEARCH_AND_REPLACE_RULES = `Critical rules:
1. SEARCH content must match the associated file section to find EXACTLY:
* Match character-for-character including whitespace, indentation, line endings
* Include all comments, docstrings, etc.
2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
4. Keep SEARCH/REPLACE blocks concise:
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
5. Splitting up tool calls:
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
6. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section
7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`;
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
\`\`\`
${SEARCH_AND_REPLACE_RULES}
Usage:
\`\`\`
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
\`\`\`
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`;
/**
* This tool is in an experimental state.
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
*/
export const searchAndReplaceInFileTool: Tool = {
type: "function",
displayTitle: "Edit File",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description: `The path of the file to modify, relative to the root of the workspace.`,
},
diffs: {
type: "array",
items: {
type: "string",
},
description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION,
},
},
},
},
systemMessageDescription: {
prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
Each block should follow this format:
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
${SEARCH_AND_REPLACE_RULES}
For example, you could respond with:`,
exampleArgs: [
["filepath", "path/to/file.ts"],
[
"diffs",
`[
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}",
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}"
]`,
],
],
},
defaultToolPolicy: "allowedWithPermission",
};

View file

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

View file

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

View file

@ -0,0 +1,44 @@
---
title: "Tetrate Agent Router Service"
---
The Tetrate Agent Router Service (TARS) provides a unified API gateway for accessing various AI models with fast inference capabilities. TARS acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
## Getting Started
1. Obtain an API key from the [Tetrate Agent Router Service portal](https://api.router.tetrate.ai/)
2. Configure Continue to use TARS as your model provider
## Configuration
Update your Continue configuration file (`~/.continue/config.json` or `~/.continue/config.yaml`) with your TARS API key:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: TARS GPT-5 Mini
provider: tars
model: gpt-5-mini
apiKey: <YOUR_TARS_API_KEY>
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "TARS GPT-5 Mini",
"provider": "tars",
"model": "gpt-5-mini",
"apiKey": "<YOUR_TARS_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
## Available Models
TARS supports routing to various models. Go to the [Tetrate Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.

View file

@ -266,8 +266,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
project.service<ContinuePluginDisposable>()
)
val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope)
continuePluginService.coreMessengerManager = coreMessengerManager
continuePluginService.coreMessenger = CoreMessenger(project, ideProtocolClient, coroutineScope)
}
}
}

View file

@ -5,11 +5,9 @@ import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueBinaryProcess
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.uuid
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import kotlinx.coroutines.CoroutineScope
@ -17,13 +15,14 @@ import kotlinx.coroutines.CoroutineScope
class CoreMessenger(
private val project: Project,
private val ideProtocolClient: IdeProtocolClient,
val coroutineScope: CoroutineScope,
private val onUnexpectedExit: () -> Unit
// todo: this scope is public only to cancel the coroutines on dispose in ContinuePluginService
// todo: scope is created in ContinuePluginStartupActivity; refactor this/clean this up/encapsulate
val coroutineScope: CoroutineScope
) {
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
private var process = startContinueProcess()
private val log = Logger.getInstance(CoreMessenger::class.java.simpleName)
private val process = startContinueProcess()
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
@ -34,14 +33,15 @@ class CoreMessenger(
private fun startContinueProcess(): ContinueProcessHandler {
val isTcp = System.getenv("USE_TCP")?.toBoolean() ?: false
val process = if (isTcp)
ContinueSocketProcess()
else
ContinueBinaryProcess(onUnexpectedExit)
return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
return ContinueProcessHandler(coroutineScope, ::readProcessMessage) {
if (isTcp)
ContinueSocketProcess()
else
ContinueBinaryProcess()
}
}
private fun handleMessage(json: String) {
private fun readProcessMessage(json: String) {
val responseMap = tryToParse(json) ?: return
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
@ -76,19 +76,16 @@ class CoreMessenger(
try {
gson.fromJson(json, Map::class.java)
} catch (_: JsonSyntaxException) {
log.warn("Invalid message JSON: $json") // example: NODE_ENV undefined
LOG.warn("Invalid message JSON: $json") // example: NODE_ENV undefined
null
}
fun restart() {
log.warn("Restarting Continue process")
responseListeners.clear()
process.close()
process = startContinueProcess()
process.restart()
}
fun close() {
log.warn("Closing Continue process")
process.close()
private companion object {
private val LOG = Logger.getInstance(CoreMessenger::class.java.simpleName)
}
}

View file

@ -1,33 +0,0 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.seconds
class CoreMessengerManager(
project: Project,
ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
) {
val coreMessenger = CoreMessenger(project, ideProtocolClient, coroutineScope, ::onUnexpectedExit)
private var backoffIntervalSeconds = 1
private val log = Logger.getInstance(CoreMessengerManager::class.java)
private fun onUnexpectedExit() {
coroutineScope.launch {
try {
delay(backoffIntervalSeconds.seconds)
backoffIntervalSeconds *= 2
log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds")
coreMessenger.restart()
} catch (e: Exception) {
service<ContinuePostHogService>().capture("jetbrains_core_start_error", mapOf("error" to e))
}
}
}
}

View file

@ -0,0 +1,25 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/**
* Starts at [initialDuration] and doubles on each call to [nextDuration] up to [maxDuration].
*/
class BackoffCalculator(
private val initialDuration: Duration = 1.seconds,
private val maxDuration: Duration = 30.seconds
) {
private var currentTime: Duration = initialDuration
init {
require(initialDuration > 0.seconds)
}
fun nextDuration(): Duration {
val delay = currentTime
val next = currentTime * 2.0
currentTime = if (next <= maxDuration) next else maxDuration
return delay
}
}

View file

@ -1,12 +1,9 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.github.continuedev.continueintellijextension.proxy.ProxySettings
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
import com.github.continuedev.continueintellijextension.utils.getOS
import com.intellij.openapi.components.service
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.io.File
@ -16,47 +13,27 @@ import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class ContinueBinaryProcess(
private val onUnexpectedExit: () -> Unit
) : ContinueProcess {
class ContinueBinaryProcess() : ContinueProcess {
private val process = startBinaryProcess()
private val process = start()
override val input: InputStream = process.inputStream
override val output: OutputStream = process.outputStream
override fun close() =
process.destroy()
private fun startBinaryProcess(): Process {
val path = getContinueBinaryPath()
runBlocking(Dispatchers.IO) {
setPermissions()
}
val builder = ProcessBuilder(path)
builder.environment() += ProxySettings.getSettings().toContinueEnvVars()
return builder
.directory(File(path).parentFile)
.start()
.apply { onExit().thenRun(onUnexpectedExit).thenRun(::reportErrorTelemetry) }
}
private fun reportErrorTelemetry() {
var err = process.errorStream?.bufferedReader()?.readText()?.trim()
if (err != null) {
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
val delimiter = "⚡ Done in"
val doneIndex = err.lastIndexOf(delimiter)
if (doneIndex != -1) {
err = err.substring(doneIndex + delimiter.length)
}
}
service<ContinueSentryService>().reportMessage("Core process exited with output: $err")
service<ContinuePostHogService>().capture("jetbrains_core_exit", mapOf("error" to err))
}
private companion object {
private fun start(): Process {
val path = getContinueBinaryPath()
setPermissions()
val builder = ProcessBuilder(path)
builder.environment() += ProxySettings.getSettings().toContinueEnvVars()
return builder
.directory(File(path).parentFile)
.start()
}
private fun setPermissions() {
val os = getOS()
when (os) {

View file

@ -1,49 +1,62 @@
package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
class ContinueProcessHandler(
parentScope: CoroutineScope,
private val process: ContinueProcess,
handleMessage: (String) -> (Unit)
private val parentScope: CoroutineScope,
private val readMessage: (String) -> (Unit),
private val createProcess: () -> ContinueProcess
) {
private val innerJob = Job()
private val scope = CoroutineScope(parentScope.coroutineContext + innerJob)
private val pendingWrites = Channel<String>(Channel.UNLIMITED)
private val writer = OutputStreamWriter(process.output)
private val reader = BufferedReader(InputStreamReader(process.input))
private val log = Logger.getInstance(ContinueProcessHandler::class.java)
private val backoff = BackoffCalculator()
private var processScope: CoroutineScope? = null
private var process: ContinueProcess? = null
init {
scope.launch(Dispatchers.IO) {
try {
while (isActive) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
log.debug("Handle: $line")
handleMessage(line)
} catch (e: Exception) {
service<ContinueSentryService>().report(e, "Error handling message: $line")
}
} else
delay(100)
}
} catch (e: IOException) {
service<ContinueSentryService>().report(e)
restart()
}
fun restart() {
LOG.warn("Starting Continue process")
processScope?.cancel()
process?.close()
val handler = CoroutineExceptionHandler { _, e ->
service<ContinueSentryService>().report(e)
service<ContinuePostHogService>().capture("jetbrains_core_exit", mapOf("error" to e))
val backoffDuration = backoff.nextDuration()
LOG.warn("Process failed! Restarting in $backoffDuration")
parentScope.launch {
delay(backoffDuration)
restart()
}
}
scope.launch(Dispatchers.IO) {
val job = SupervisorJob(parentScope.coroutineContext.job)
processScope = CoroutineScope(parentScope.coroutineContext + job + handler)
process = createProcess()
val reader = BufferedReader(InputStreamReader(process!!.input))
val writer = OutputStreamWriter(process!!.output)
processScope!!.launch(Dispatchers.IO) {
while (isActive) {
val line = reader.readLine()
if (line != null && line.isNotEmpty())
readMessage(line)
}
}
processScope!!.launch(Dispatchers.IO) {
for (message in pendingWrites) {
log.debug("Write: $message")
writer.write(message)
writer.write("\r\n")
writer.flush()
@ -54,12 +67,7 @@ class ContinueProcessHandler(
fun write(message: String) =
pendingWrites.trySend(message)
fun close() {
innerJob.cancel()
scope.launch(Dispatchers.IO) {
reader.close()
writer.close()
process.close()
}
private companion object {
private val LOG = Logger.getInstance(ContinueProcessHandler::class.java.simpleName)
}
}

View file

@ -28,7 +28,7 @@ class ProxyPoolingActivity : StartupActivity {
private fun onSettingsChanged(project: Project) {
log.warn("Proxy settings changed, restarting")
project.service<ContinuePluginService>().coreMessengerManager?.coreMessenger?.restart()
project.service<ContinuePluginService>().coreMessenger?.restart()
}
}

View file

@ -1,34 +1,28 @@
package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
import com.github.continuedev.continueintellijextension.`continue`.DiffManager
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager
import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
import com.github.continuedev.continueintellijextension.utils.uuid
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlin.properties.Delegates
@Service(Service.Level.PROJECT)
class ContinuePluginService(private val project: Project) : DumbAware {
private val coroutineScope = CoroutineScope(Dispatchers.Main)
class ContinuePluginService(private val project: Project) : Disposable, DumbAware {
var listener: (() -> Unit)? = null
var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ ->
synchronized(this) { listener?.also { listener = null }?.invoke() }
}
var coreMessengerManager: CoreMessengerManager? = null
val coreMessenger: CoreMessenger?
get() = coreMessengerManager?.coreMessenger
var coreMessenger: CoreMessenger? = null
var workspacePaths: Array<String>? = null
var windowId: String = uuid()
var diffManager: DiffManager? = null
@ -57,14 +51,6 @@ class ContinuePluginService(private val project: Project) : DumbAware {
}
}
fun dispose() {
coroutineScope.cancel()
coreMessenger?.coroutineScope?.let {
it.cancel()
coreMessenger?.close()
}
}
/**
* Add a listener for protocolClient initialization.
* Currently, only one needs to be processed. If there are more than one,
@ -83,4 +69,8 @@ class ContinuePluginService(private val project: Project) : DumbAware {
listener()
}
}
override fun dispose() {
coreMessenger?.coroutineScope?.cancel()
}
}

View file

@ -0,0 +1,20 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.`continue`.process.BackoffCalculator
import junit.framework.TestCase
import kotlin.time.Duration.Companion.seconds
class BackoffCalculatorTest : TestCase() {
fun `test backoff`() {
val backoff = BackoffCalculator(initialDuration = 1.seconds, maxDuration = 30.seconds)
assertEquals(1.seconds, backoff.nextDuration())
assertEquals(2.seconds, backoff.nextDuration())
assertEquals(4.seconds, backoff.nextDuration())
assertEquals(8.seconds, backoff.nextDuration())
assertEquals(16.seconds, backoff.nextDuration())
assertEquals(30.seconds, backoff.nextDuration())
assertEquals(30.seconds, backoff.nextDuration())
}
}

View file

@ -233,7 +233,8 @@
"morph",
"ovhcloud",
"venice",
"inception"
"inception",
"tars"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)",
@ -283,7 +284,8 @@
"### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard).",
"### OVHcloud AI Endpoints is a serverless inference API that provides access to a curated selection of models (e.g., Llama, Mistral, Qwen, Deepseek). It is designed with security and data privacy in mind and is compliant with GDPR. To get started, create an API key on the OVHcloud [AI Endpoints website](https://endpoints.ai.cloud.ovh.net/). For more information, including pricing, visit the OVHcloud [AI Endpoints product page](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/).",
"### Venice\n Venice.AI is a privacy-focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data.\nHosted models support the OpenAI API standard, providing seamless integration for users seeking privacy and flexibility.\nTo get started with the Venice API, either purchase a pro account, stake $VVV for daily inference allotments, or fund your account with USD.\nVisit the [API settings page](https://venice.ai/settings/api) or learn more at the [Venice API documentation](https://venice.ai/api).",
"### Inception\n Inception Labs offer a new generation of diffusion-based LLMs.\nVisit the [API settings page](https://platform.inceptionlabs.ai/) or learn more at the [Inception docs](https://platform.inceptionlabs.ai/docs)."
"### Inception\n Inception Labs offer a new generation of diffusion-based LLMs.\nVisit the [API settings page](https://platform.inceptionlabs.ai/) or learn more at the [Inception docs](https://platform.inceptionlabs.ai/docs).",
"### TARS\nTARS is an OpenAI-compatible proxy router. To get started, obtain an API key and configure the provider in your config.json."
],
"type": "string"
},

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View file

@ -998,4 +998,30 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
packages: [{ ...models.AUTODETECT }],
apiKeyUrl: "https://venice.ai/chat",
},
tars: {
title: "Tetrate Agent Router Service",
provider: "tars",
icon: "TetrateAgentRouterService.png",
description: "TARS API for fast inference with various models",
tags: [ModelProviderTags.RequiresApiKey],
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your Tetrate Agent Router Service API key",
required: true,
},
],
packages: [
{
...models.AUTODETECT,
params: {
...models.AUTODETECT.params,
title: "TARS",
},
},
],
apiKeyUrl: "https://api.router.tetrate.ai/",
},
};

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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