diff --git a/core/context/providers/_context-providers.vitest.ts b/core/context/providers/_context-providers.vitest.ts
index 7ae55d32e..f7096bf87 100644
--- a/core/context/providers/_context-providers.vitest.ts
+++ b/core/context/providers/_context-providers.vitest.ts
@@ -50,6 +50,7 @@ async function getContextProviderExtras(
llm: config.modelsByRole.chat[0],
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
+ isInAgentMode: true,
};
}
diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts
index d13da2145..5089678c1 100644
--- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts
+++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts
@@ -225,9 +225,11 @@ Determine which tools should be used to answer this query. You should feel free
.join("");
const parsed = JSON.parse(responseContent);
toolCalls = parsed.tools || [];
- console.log("retrieveWithTools", toolCalls);
} catch (e) {
- console.log("Failed to parse tool selection response", e);
+ console.log(
+ `Failed to parse tool selection response: ${toolSelectionResponse.content}\n\n`,
+ e,
+ );
return [];
}
diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts
index 8a9d053fd..ad966f89a 100644
--- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts
+++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts
@@ -122,10 +122,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
results = results.slice(-this.options.nFinal);
return results;
} catch (e) {
- void this.options.ide.showToast(
- "warning",
- `Failed to rerank retrieval results\n${e}`,
- );
+ console.warn(`Failed to rerank retrieval results\n${e}`);
return chunks.slice(-this.options.nFinal);
}
}
diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts
index 31dc8750b..4f29d2ef8 100644
--- a/core/context/retrieval/retrieval.ts
+++ b/core/context/retrieval/retrieval.ts
@@ -79,14 +79,19 @@ export async function retrieveContextItemsFromEmbeddings(
if (results.length === 0) {
if (extras.config.disableIndexing) {
- void extras.ide.showToast("warning", "No results found.");
- return [];
- } else {
void extras.ide.showToast(
"warning",
- "No results found. If you think this is an error, re-index your codebase.",
+ "No results found (Indexing disabled).",
);
- // TODO - add "re-index" option to warning message which clears and reindexes codebase
+ return [];
+ }
+ if (extras.isInAgentMode) {
+ return [
+ {
+ ...INSTRUCTIONS_BASE_ITEM,
+ content: "No results were found. Try using other tools.",
+ },
+ ];
}
return [];
}
diff --git a/core/core.ts b/core/core.ts
index 7708463ad..72931c5e8 100644
--- a/core/core.ts
+++ b/core/core.ts
@@ -1071,6 +1071,7 @@ export class Core {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
+ isInAgentMode: boolean;
}>,
) => {
const { config } = await this.configHandler.loadConfig();
@@ -1115,6 +1116,7 @@ export class Core {
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
+ isInAgentMode: msg.data.isInAgentMode,
});
void Telemetry.capture(
diff --git a/core/edit/searchAndReplace/findSearchMatch.test.ts b/core/edit/searchAndReplace/findSearchMatch.test.ts
index 8d5c3682b..a39322e31 100644
--- a/core/edit/searchAndReplace/findSearchMatch.test.ts
+++ b/core/edit/searchAndReplace/findSearchMatch.test.ts
@@ -1,319 +1,546 @@
import { findSearchMatch } from "./findSearchMatch";
-describe("findSearchMatch", () => {
- describe("Exact matches", () => {
- it("should find exact match at the beginning of file", () => {
- const fileContent = `function hello() {
+describe("Exact matches", () => {
+ it("should find exact match at the beginning of file", () => {
+ const fileContent = `function hello() {
console.log("world");
}`;
- const searchContent = `function hello() {
+ const searchContent = `function hello() {
console.log("world");
}`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 0,
- endIndex: fileContent.length,
- });
+ 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;
+ 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() {
+ const searchContent = `function hello() {
console.log("world");
}`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 13, // After "const a = 1;\n"
- endIndex: 13 + searchContent.length,
- });
+ 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;
+ it("should find exact match at the end of file", () => {
+ const fileContent = `const a = 1;
function hello() {
console.log("world");
}`;
- const searchContent = `function hello() {
+ const searchContent = `function hello() {
console.log("world");
}`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 13, // After "const a = 1;\n"
- endIndex: fileContent.length,
- });
+ 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;
+ 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 searchContent = `const b = 2;`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 13, // After "const a = 1;\n"
- endIndex: 13 + searchContent.length,
- });
+ 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() {
+ it("should find exact match with whitespace preserved", () => {
+ const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
- const searchContent = ` const x = 1;
+ const searchContent = ` const x = 1;
const y = 2;`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- // The actual indexOf result is 18, not 17
- expect(result).toEqual({
- startIndex: 18,
- endIndex: 18 + searchContent.length,
- });
+ // 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() {
+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() {
+ const searchContent = `\n\nfunction hello() {
console.log("world");
}\n\n`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 0,
- endIndex: fileContent.length, // Uses trimmed length
- });
+ 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;
+ 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() {
+ const searchContent = `\nfunction hello() {
return "world";
}\n`;
- const result = findSearchMatch(fileContent, searchContent);
+ 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,
- });
+ // 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;
+ 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 searchContent = `\n const b = 2; \n`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- const trimmedSearchContent = searchContent.trim();
- const expectedStart = fileContent.indexOf(trimmedSearchContent);
+ const trimmedSearchContent = searchContent.trim();
+ const expectedStart = fileContent.indexOf(trimmedSearchContent);
- expect(result).toEqual({
- startIndex: expectedStart,
- endIndex: expectedStart + trimmedSearchContent.length,
- });
+ 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",
});
});
- describe("Empty search content", () => {
- it("should match at beginning for empty search content", () => {
- const fileContent = `function hello() {
+ it("should match at beginning for whitespace-only search content", () => {
+ const fileContent = `function hello() {
console.log("world");
}`;
- const searchContent = "";
+ const searchContent = "\n\n \t \n";
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 0,
- endIndex: 0,
- });
- });
-
- 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,
- });
- });
-
- 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,
- });
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
});
});
- describe("No matches", () => {
- it("should return null when search content is not found", () => {
- const fileContent = `function hello() {
- console.log("world");
-}`;
- const searchContent = `function goodbye() {
- console.log("world");
-}`;
+ it("should match at beginning for empty file and empty search", () => {
+ const fileContent = "";
+ const searchContent = "";
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toBeNull();
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
});
+ });
+});
- it("should return null when trimmed search content is not found", () => {
- const fileContent = `function hello() {
+describe("No matches", () => {
+ it("should return null when search content is not found", () => {
+ const fileContent = `function hello() {
console.log("world");
}`;
- const searchContent = `\n\nfunction goodbye() {
+ const searchContent = `function goodbye() {
+ console.log("world");
+}`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
+ });
+
+ it("should return only fuzzy result when trimmed search content is not found", () => {
+ const fileContent = `function hello() {
+ console.log("world");
+}`;
+ const searchContent = `\n\nfunction goodbye() {
console.log("world");
}\n\n`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toBeNull();
- });
+ expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
+ });
+});
- it("should return null for non-existent single line", () => {
- const fileContent = `const a = 1;
-const b = 2;
-const c = 3;`;
- const searchContent = `const d = 4;`;
+describe("Edge cases", () => {
+ it("should handle empty file with non-empty search", () => {
+ const fileContent = "";
+ const searchContent = "function hello() {}";
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toBeNull();
- });
+ expect(result).toBeNull();
+ });
- it("should return null for partial match", () => {
- const fileContent = `function hello() {
- console.log("world");
-}`;
- const searchContent = `function hello() {
- console.log("universe");
-}`;
+ 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 result = findSearchMatch(fileContent, searchContent);
- expect(result).toBeNull();
+ const expectedStart = repeatedLine.length * 1000;
+ expect(result).toEqual({
+ startIndex: expectedStart,
+ endIndex: expectedStart + searchContent.length,
+ strategyName: "exactMatch",
});
});
- 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,
- });
- });
-
- it("should handle special characters and symbols", () => {
- const fileContent = `const regex = /[a-zA-Z]+/g;
+ 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 searchContent = `const symbols = !@#$%^&*();`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- const expectedStart = fileContent.indexOf(searchContent);
- expect(result).toEqual({
- startIndex: expectedStart,
- endIndex: expectedStart + searchContent.length,
- });
+ 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() {
+ 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 searchContent = `function test() {
const x = 1;
}`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- // Should find the first exact match, not a trimmed version
- expect(result).toEqual({
- startIndex: 0,
- endIndex: searchContent.length,
- });
- });
-
- 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,
- });
+ // Should find the first exact match, not a trimmed version
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: searchContent.length,
+ strategyName: "exactMatch",
});
});
- describe("Real-world scenarios", () => {
- it("should match typical function replacement", () => {
- const fileContent = `class Calculator {
+ 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;
}
@@ -328,41 +555,43 @@ const a = 1;`;
return this;
}
}`;
- const searchContent = ` reset() {
+ const searchContent = ` reset() {
this.result = 0;
return this;
}`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- const expectedStart = fileContent.indexOf(searchContent);
- expect(result).toEqual({
- startIndex: expectedStart,
- endIndex: expectedStart + searchContent.length,
- });
+ 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';
+ it("should match import statement", () => {
+ const fileContent = `import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function App() {
return
Hello World
;
}`;
- const searchContent = `import { useState, useEffect } from 'react';`;
+ const searchContent = `import { useState, useEffect } from 'react';`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- const expectedStart = fileContent.indexOf(searchContent);
- expect(result).toEqual({
- startIndex: expectedStart,
- endIndex: expectedStart + searchContent.length,
- });
+ const expectedStart = fileContent.indexOf(searchContent);
+ expect(result).toEqual({
+ startIndex: expectedStart,
+ endIndex: expectedStart + searchContent.length,
+ strategyName: "exactMatch",
});
+ });
- it("should match comment block", () => {
- const fileContent = `/**
+ it("should match comment block", () => {
+ const fileContent = `/**
* This is a comment
* that spans multiple lines
*/
@@ -370,16 +599,169 @@ function test() {
// Single line comment
return true;
}`;
- const searchContent = `/**
+ const searchContent = `/**
* This is a comment
* that spans multiple lines
*/`;
- const result = findSearchMatch(fileContent, searchContent);
+ const result = findSearchMatch(fileContent, searchContent);
- expect(result).toEqual({
- startIndex: 0,
- endIndex: searchContent.length,
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: searchContent.length,
+ strategyName: "exactMatch",
+ });
+ });
+
+ describe("Jaro-Winkler fuzzy matching", () => {
+ describe("Basic fuzzy matching", () => {
+ it("should find fuzzy match for similar strings", () => {
+ const fileContent = `function calculateSum(a, b) {
+ return a + b;
+}`;
+ const searchContent = `function calculateSum(x, y) {
+ return x + y;
+}`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ });
+
+ it("should find fuzzy match with minor typos", () => {
+ const fileContent = `const message = "Hello World";`;
+ const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ expect(result?.startIndex).toBe(0);
+ });
+
+ it("should find fuzzy match with different variable names", () => {
+ const fileContent = `let userAge = 25;
+let userName = "John";`;
+ const searchContent = `let age = 25;
+let name = "John";`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ });
+
+ it("should find fuzzy match for similar function signature", () => {
+ const fileContent = `function processUserData(userData) {
+ validateInput(userData);
+ return formatOutput(userData);
+}`;
+ const searchContent = `function processData(data) {
+ validateInput(data);
+ return formatOutput(data);
+}`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ });
+ });
+
+ describe("Multi-line fuzzy matching", () => {
+ it("should find fuzzy match for multi-line blocks", () => {
+ const fileContent = `class Calculator {
+ constructor() {
+ this.result = 0;
+ }
+
+ add(value) {
+ this.result += value;
+ return this;
+ }
+}`;
+ const searchContent = `class Calculator {
+ constructor() {
+ this.value = 0;
+ }
+
+ add(num) {
+ this.value += num;
+ return this;
+ }
+}`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ });
+
+ it("should find fuzzy match for partial blocks", () => {
+ const fileContent = `function processData(input) {
+ const validated = validateInput(input);
+ const processed = transformData(validated);
+ const result = formatOutput(processed);
+ return result;
+}`;
+ const searchContent = `const validated = validateInput(input);
+ const processed = transformData(validated);`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ });
+ });
+
+ describe("Edge cases with fuzzy matching", () => {
+ it("should handle empty search content with fuzzy matching enabled", () => {
+ const fileContent = `function test() {}`;
+ const searchContent = "";
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+
+ it("should handle empty file content with fuzzy matching enabled", () => {
+ const fileContent = "";
+ const searchContent = "function test() {}";
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toBeNull();
+ });
+
+ it("should prefer exact match over fuzzy match", () => {
+ const fileContent = `function test() { return true; }
+function test() { return false; }`;
+ const searchContent = `function test() { return true; }`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
+ expect(result?.startIndex).toBe(0);
+ });
+
+ it("should handle very short strings", () => {
+ const fileContent = `a b c`;
+ const searchContent = `a c`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ // Should not match due to low similarity
+ expect(result).toBeNull();
+ });
+
+ it("should handle special characters in fuzzy matching", () => {
+ const fileContent = `const regex = /[a-zA-Z]+/g;
+const symbols = !@#$%^&*();`;
+ const searchContent = `const regex = /[a-zA-Z0-9]+/g;
+const symbols = !@#$%^&*();`;
+
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).not.toBeNull();
});
});
});
diff --git a/core/edit/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts
index 3b1b8acf8..9597d5070 100644
--- a/core/edit/searchAndReplace/findSearchMatch.ts
+++ b/core/edit/searchAndReplace/findSearchMatch.ts
@@ -1,7 +1,7 @@
/**
- * Represents a match result with start and end character positions
+ * Represents a basic match result with start and end character positions
*/
-export interface SearchMatchResult {
+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 */
@@ -9,31 +9,28 @@ export interface SearchMatchResult {
}
/**
- * Find the exact match position for search content in file content.
- * Uses simple exact matching with trimmed newlines for MVP.
- *
- * Matching Strategy:
- * 1. If search content is empty, matches at the beginning of file (position 0)
- * 2. Try exact string match first
- * 3. Fallback to trimmed content match if exact match fails
- *
- * @param fileContent - The complete content of the file to search in
- * @param searchContent - The content to search for
- * @returns Match result with character positions, or null if no match found
+ * Represents a match result with start and end character positions
*/
-export function findSearchMatch(
+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,
-): SearchMatchResult | null {
- // Strip leading/trailing newlines for basic matching strategy
- const trimmedSearchContent = searchContent.trim();
+) => BasicMatchResult | null;
- if (trimmedSearchContent === "") {
- // Empty search content matches the beginning of the file
- return { startIndex: 0, endIndex: 0 };
- }
-
- // Try exact match first
+/**
+ * Exact string matching strategy
+ */
+function exactMatch(
+ fileContent: string,
+ searchContent: string,
+): BasicMatchResult | null {
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
@@ -41,8 +38,17 @@ export function findSearchMatch(
endIndex: exactIndex + searchContent.length,
};
}
+ return null;
+}
- // Fallback: try trimmed content match
+/**
+ * Trimmed content matching strategy
+ */
+function trimmedMatch(
+ fileContent: string,
+ searchContent: string,
+): BasicMatchResult | null {
+ const trimmedSearchContent = searchContent.trim();
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedIndex !== -1) {
return {
@@ -50,6 +56,262 @@ export function findSearchMatch(
endIndex: trimmedIndex + trimmedSearchContent.length,
};
}
+ return null;
+}
+
+/**
+ * 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,
+ };
+}
+
+/**
+ * Calculate the Jaro similarity between two strings
+ */
+function jaroSimilarity(s1: string, s2: string): number {
+ if (s1 === s2) return 1.0;
+ if (s1.length === 0 || s2.length === 0) return 0.0;
+
+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
+ if (matchDistance < 0) return 0.0;
+
+ const s1Matches = new Array(s1.length).fill(false);
+ const s2Matches = new Array(s2.length).fill(false);
+
+ let matches = 0;
+ let transpositions = 0;
+
+ // Find matches
+ for (let i = 0; i < s1.length; i++) {
+ const start = Math.max(0, i - matchDistance);
+ const end = Math.min(i + matchDistance + 1, s2.length);
+
+ for (let j = start; j < end; j++) {
+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
+ s1Matches[i] = true;
+ s2Matches[j] = true;
+ matches++;
+ break;
+ }
+ }
+
+ if (matches === 0) return 0.0;
+
+ // Count transpositions
+ let k = 0;
+ for (let i = 0; i < s1.length; i++) {
+ if (!s1Matches[i]) continue;
+ while (!s2Matches[k]) k++;
+ if (s1[i] !== s2[k]) transpositions++;
+ k++;
+ }
+
+ return (
+ (matches / s1.length +
+ matches / s2.length +
+ (matches - transpositions / 2) / matches) /
+ 3.0
+ );
+}
+
+/**
+ * Calculate the Jaro-Winkler similarity between two strings
+ */
+function jaroWinklerSimilarity(
+ s1: string,
+ s2: string,
+ prefixScale = 0.1,
+): number {
+ const jaroSim = jaroSimilarity(s1, s2);
+
+ if (jaroSim < 0.7) return jaroSim;
+
+ // Calculate common prefix length (up to 4 characters)
+ let prefixLength = 0;
+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
+
+ for (let i = 0; i < maxPrefix; i++) {
+ if (s1[i] === s2[i]) {
+ prefixLength++;
+ } else {
+ break;
+ }
+ }
+
+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
+}
+
+/**
+ * Find the best fuzzy match for search content in file content using Jaro-Winkler
+ */
+function findFuzzyMatch(
+ fileContent: string,
+ searchContent: string,
+ threshold: number = 0.9,
+): BasicMatchResult | null {
+ const searchLines = searchContent.split("\n");
+ const fileLines = fileContent.split("\n");
+
+ let bestMatch: BasicMatchResult | null = null;
+ let bestSimilarity = 0;
+
+ // Try matching the search content as a whole block
+ const searchBlock = searchContent.trim();
+ if (searchBlock.length > 5) {
+ // Require minimum length for meaningful matches
+ // Use sliding window approach for multi-line search
+ for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
+ const candidateLines = fileLines.slice(i, i + searchLines.length);
+ const candidateBlock = candidateLines.join("\n").trim();
+
+ if (candidateBlock.length < 5) continue; // Skip very short blocks
+
+ const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
+
+ if (similarity >= threshold && similarity > bestSimilarity) {
+ // Calculate character positions
+ const linesBeforeMatch = fileLines.slice(0, i);
+ const startIndex =
+ linesBeforeMatch.join("\n").length +
+ (linesBeforeMatch.length > 0 ? 1 : 0);
+ const endIndex = startIndex + candidateBlock.length;
+
+ bestMatch = {
+ startIndex,
+ endIndex,
+ };
+ bestSimilarity = similarity;
+ }
+ }
+ }
+
+ // Also try line-by-line matching for better granularity
+ for (
+ let searchLineIdx = 0;
+ searchLineIdx < searchLines.length;
+ searchLineIdx++
+ ) {
+ const searchLine = searchLines[searchLineIdx].trim();
+ if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
+
+ for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
+ const fileLine = fileLines[fileLineIdx].trim();
+ if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
+
+ const similarity = jaroWinklerSimilarity(searchLine, fileLine);
+
+ if (similarity >= threshold && similarity > bestSimilarity) {
+ // Calculate character positions for the line
+ const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
+ const startIndex =
+ linesBeforeMatch.join("\n").length +
+ (linesBeforeMatch.length > 0 ? 1 : 0);
+ const endIndex = startIndex + fileLines[fileLineIdx].length;
+
+ bestMatch = {
+ startIndex,
+ endIndex,
+ };
+ bestSimilarity = similarity;
+ }
+ }
+ }
+
+ return bestMatch;
+}
+
+/**
+ * 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" },
+ { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
+];
+
+/**
+ * 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 {
+ const trimmedSearchContent = searchContent.trim();
+
+ if (trimmedSearchContent === "") {
+ // Empty search content matches the beginning of the file
+ 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;
}
diff --git a/core/index.d.ts b/core/index.d.ts
index c6dabcb02..3d6f1602c 100644
--- a/core/index.d.ts
+++ b/core/index.d.ts
@@ -187,6 +187,7 @@ export interface ContextProviderExtras {
ide: IDE;
selectedCode: RangeInFile[];
fetch: FetchFunction;
+ isInAgentMode: boolean;
}
export interface LoadSubmenuItemsArgs {
diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts
index 0a285b15d..e01518629 100644
--- a/core/indexing/LanceDbIndex.ts
+++ b/core/indexing/LanceDbIndex.ts
@@ -234,6 +234,23 @@ export class LanceDbIndex implements CodebaseIndex {
return results;
}
+ /**
+ * Due to a bug in indexing, some indexes have vectors
+ * without the surrounding []. These would fail to parse
+ * but this allows such existing indexes to function properly
+ */
+ private parseVector(vector: string): number[] {
+ try {
+ return JSON.parse(vector);
+ } catch (err) {
+ try {
+ return JSON.parse(`[${vector}]`);
+ } catch (err2) {
+ throw new Error(`Failed to parse vector: ${vector}`, { cause: err2 });
+ }
+ }
+ }
+
async *update(
tag: IndexTag,
results: RefreshIndexResults,
@@ -297,10 +314,10 @@ export class LanceDbIndex implements CodebaseIndex {
const lanceRows: LanceDbRow[] = [];
for (const item of cachedItems) {
try {
- const vector = JSON.parse(item.vector);
+ const vector = this.parseVector(item.vector);
const { uuid, startLine, endLine, contents } = item;
- cachedItems.push({
+ lanceRows.push({
path,
uuid,
startLine,
diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts
index 9ca8d1fe8..2297813b4 100644
--- a/core/llm/countTokens.ts
+++ b/core/llm/countTokens.ts
@@ -60,7 +60,10 @@ function asyncEncoderForModel(modelName: string): AsyncEncoder {
const modelType = autodetectTemplateType(modelName);
if (!modelType || modelType === "none") {
- return gptAsyncEncoder;
+ // Right now there is a problem packaging js-tiktoken in workers. Until then falling back
+ // Cannot find package 'js-tiktoken' imported from /Users/nate/gh/continuedev/continue/extensions/vscode/out/tiktokenWorkerPool.mjs
+ // return gptAsyncEncoder;
+ return llamaAsyncEncoder;
}
return llamaAsyncEncoder;
}
diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts
index 206b17b80..cb514f1e6 100644
--- a/core/nextEdit/context/processNextEditData.ts
+++ b/core/nextEdit/context/processNextEditData.ts
@@ -2,7 +2,7 @@ import { IDE, Position } from "../..";
import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
import { ConfigHandler } from "../../config/ConfigHandler";
-import { DataLogger } from "../../data/log";
+// import { DataLogger } from "../../data/log";
import { RecentlyEditedRange } from "../types";
import { getAutocompleteContext } from "./autocompleteContextFetching";
import { createDiff, DiffFormatType } from "./diffFormatting";
@@ -108,22 +108,22 @@ export const processNextEditData = async ({
);
}
- if (filenamesAndDiffs.length > 0) {
- // if there are previous edits, log
- void DataLogger.getInstance().logDevData({
- name: "nextEditWithHistory",
- data: {
- previousEdits: filenamesAndDiffs,
- fileURI: filePath,
- workspaceDirURI: workspaceDir,
- beforeContent,
- afterContent,
- beforeCursorPos: cursorPosBeforeEdit,
- afterCursorPos: cursorPosAfterPrevEdit,
- context: autocompleteContext,
- },
- });
- }
+ // if (filenamesAndDiffs.length > 0) {
+ // // if there are previous edits, log
+ // void DataLogger.getInstance().logDevData({
+ // name: "nextEditWithHistory",
+ // data: {
+ // previousEdits: filenamesAndDiffs,
+ // fileURI: filePath,
+ // workspaceDirURI: workspaceDir,
+ // beforeContent,
+ // afterContent,
+ // beforeCursorPos: cursorPosBeforeEdit,
+ // afterCursorPos: cursorPosAfterPrevEdit,
+ // context: autocompleteContext,
+ // },
+ // });
+ // }
// add current edit to history
const thisEdit: prevEdit = {
diff --git a/core/protocol/core.ts b/core/protocol/core.ts
index b6cb8e9b0..f06d1db04 100644
--- a/core/protocol/core.ts
+++ b/core/protocol/core.ts
@@ -116,6 +116,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
+ isInAgentMode: boolean;
},
ContextItemWithId[],
];
diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts
index a861fbb1c..b654f9c32 100644
--- a/core/tools/definitions/searchAndReplaceInFile.ts
+++ b/core/tools/definitions/searchAndReplaceInFile.ts
@@ -22,7 +22,7 @@ export const searchAndReplaceInFileTool: Tool = {
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description:
- "Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
+ "Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
parameters: {
type: "object",
required: ["filepath", "diff"],
diff --git a/core/tools/implementations/codebaseTool.ts b/core/tools/implementations/codebaseTool.ts
index 46b06a8c6..fe4f77ace 100644
--- a/core/tools/implementations/codebaseTool.ts
+++ b/core/tools/implementations/codebaseTool.ts
@@ -23,6 +23,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => {
ide: extras.ide,
selectedCode: [] as RangeInFile[],
fetch: extras.fetch,
+ isInAgentMode: true, // always true in tool call
};
// Use the existing retrieval function to get context items
diff --git a/docs/CLA.md b/docs/docs/CLA.md
similarity index 100%
rename from docs/CLA.md
rename to docs/docs/CLA.md
diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json
index cc1c10e27..7d5c2a12a 100644
--- a/extensions/vscode/package.json
+++ b/extensions/vscode/package.json
@@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
- "version": "1.1.56",
+ "version": "1.1.57",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts
index d364dc7b0..21f7fcb3f 100644
--- a/extensions/vscode/src/activation/activate.ts
+++ b/extensions/vscode/src/activation/activate.ts
@@ -24,8 +24,8 @@ export async function activateExtension(context: vscode.ExtensionContext) {
// Load Continue configuration
if (!context.globalState.get("hasBeenInstalled")) {
- context.globalState.update("hasBeenInstalled", true);
- Telemetry.capture(
+ void context.globalState.update("hasBeenInstalled", true);
+ void Telemetry.capture(
"install",
{
extensionVersion: getExtensionVersion(),
@@ -38,21 +38,15 @@ export async function activateExtension(context: vscode.ExtensionContext) {
const yamlMatcher = ".continue/**/*.yaml";
const yamlConfig = vscode.workspace.getConfiguration("yaml");
- const existingSchemas = yamlConfig.get("schemas") || {};
- const newSchemas = Object.entries(existingSchemas).filter(
- ([_, value]) => Array.isArray(value) && value.includes(yamlMatcher), // remove old ones
- );
-
const newPath = path.join(
context.extension.extensionUri.fsPath,
"config-yaml-schema.json",
);
- newSchemas.push([newPath, [yamlMatcher]]);
try {
await yamlConfig.update(
"schemas",
- Object.fromEntries(newSchemas),
+ { [newPath]: [yamlMatcher] },
vscode.ConfigurationTarget.Global,
);
} catch (error) {
diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts
index f982c5c55..307db2a63 100644
--- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts
+++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts
@@ -48,6 +48,7 @@ export async function getContextProvidersString(
selectedCode: [],
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
+ isInAgentMode: false,
});
}) || [],
)
diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx
new file mode 100644
index 000000000..464c4b4cf
--- /dev/null
+++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx
@@ -0,0 +1,55 @@
+import { ChevronDownIcon } from "@heroicons/react/24/outline";
+import { useState } from "react";
+
+interface CollapsibleContainerProps {
+ children: React.ReactNode;
+ maxHeight?: string;
+ className?: string;
+ collapsible?: boolean;
+}
+
+export function CollapsibleContainer({
+ children,
+ maxHeight = "max-h-40",
+ className = "",
+ collapsible = false,
+}: CollapsibleContainerProps) {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ // If not collapsible, just render children without any collapsible behavior
+ if (!collapsible) {
+ return {children}
;
+ }
+
+ return (
+
+
+ {children}
+
+
+ {!isExpanded && (
+
+
setIsExpanded(true)}
+ className="group flex h-full cursor-pointer items-end justify-center pb-2"
+ >
+
+
+
+
+
+ )}
+
+ {isExpanded && (
+
setIsExpanded(false)}
+ className="group mt-2 flex cursor-pointer justify-center"
+ >
+
+
+
+
+ )}
+
+ );
+}
diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx
index 8ece216bb..1d252dbdb 100644
--- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx
+++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx
@@ -13,6 +13,7 @@ import { getFontSize } from "../../../util";
import Spinner from "../../gui/Spinner";
import { isTerminalCodeBlock } from "../utils";
import { ApplyActions } from "./ApplyActions";
+import { CollapsibleContainer } from "./CollapsibleContainer";
import { CopyButton } from "./CopyButton";
import { CreateFileButton } from "./CreateFileButton";
import { FileInfo } from "./FileInfo";
@@ -32,6 +33,7 @@ export interface StepContainerPreToolbarProps {
children: any;
expanded?: boolean;
disableManualApply?: boolean;
+ collapsible?: boolean;
}
export function StepContainerPreToolbar({
@@ -47,6 +49,7 @@ export function StepContainerPreToolbar({
children,
expanded,
disableManualApply,
+ collapsible,
}: StepContainerPreToolbarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((state) => state.session.history);
@@ -298,9 +301,10 @@ export function StepContainerPreToolbar({
{renderActionButtons()}
-
{isExpanded && (
- {children}
+
+ {children}
+
)}
);
diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx
index a28e90675..d838b6edb 100644
--- a/gui/src/components/StyledMarkdownPreview/index.tsx
+++ b/gui/src/components/StyledMarkdownPreview/index.tsx
@@ -128,6 +128,7 @@ interface StyledMarkdownPreviewProps {
disableManualApply?: boolean;
toolCallId?: string;
expandCodeblocks?: boolean;
+ collapsible?: boolean;
}
const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
@@ -306,6 +307,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
forceToolCallId={props.toolCallId}
expanded={props.expandCodeblocks}
disableManualApply={props.disableManualApply}
+ collapsible={props.collapsible}
>
diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx
index a4beaba29..ac0bcfdba 100644
--- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx
+++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx
@@ -25,6 +25,7 @@ import {
vscQuickInputBackground,
} from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { useAppSelector } from "../../../redux/hooks";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import FileIcon from "../../FileIcon";
@@ -159,6 +160,9 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
+ const isInAgentMode = useAppSelector(
+ (store) => store.session.mode === "agent",
+ );
const [selectedIndex, setSelectedIndex] = useState(0);
@@ -187,6 +191,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
query,
fullInput: "",
selectedCode,
+ isInAgentMode,
},
);
diff --git a/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts b/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts
index 3721ab213..5f18073ba 100644
--- a/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts
+++ b/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts
@@ -26,6 +26,7 @@ export async function getRenderedV1Prompt(
name,
query: "",
selectedCode,
+ isInAgentMode: false,
});
if (response.status === "success") {
return response.content.map((item) => item.content).join("\n\n");
diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts
index 85f6797b5..4528c459f 100644
--- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts
+++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts
@@ -12,6 +12,7 @@ import {
import { stripImages } from "core/util/messageContent";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
+import { RootState } from "../../../../redux/store";
import { processEditorContent } from "./processEditorContent";
import { renderSlashCommandPrompt } from "./renderSlashCommand";
import { GetContextRequest } from "./types";
@@ -23,6 +24,7 @@ interface ResolveEditorContentInput {
defaultContextProviders: DefaultContextProvider[];
availableSlashCommands: SlashCommandDescWithSource[];
dispatch: Dispatch;
+ getState: () => RootState;
}
interface ResolveEditorContentOutput {
@@ -48,6 +50,7 @@ export async function resolveEditorContent({
defaultContextProviders,
availableSlashCommands,
dispatch,
+ getState,
}: ResolveEditorContentInput): Promise {
const {
parts,
@@ -87,6 +90,7 @@ export async function resolveEditorContent({
defaultContextProviders,
parts: slashedParts,
selectedCode,
+ getState,
});
if (shouldGatherContext) {
@@ -111,6 +115,7 @@ async function gatherContextItems({
defaultContextProviders,
parts,
selectedCode,
+ getState,
}: {
contextRequests: GetContextRequest[];
modifiers: InputModifiers;
@@ -118,6 +123,7 @@ async function gatherContextItems({
defaultContextProviders: DefaultContextProvider[];
parts: MessagePart[];
selectedCode: RangeInFile[];
+ getState: () => RootState;
}): Promise {
const defaultRequests: GetContextRequest[] = defaultContextProviders.map(
(def) => ({
@@ -139,6 +145,8 @@ async function gatherContextItems({
);
let contextItems: ContextItemWithId[] = [];
+ const isInAgentMode = getState().session.mode === "agent";
+
// Process context item attributes
for (const item of deduplicatedInputs) {
const result = await ideMessenger.request("context/getContextItems", {
@@ -146,6 +154,7 @@ async function gatherContextItems({
query: item.query ?? "",
fullInput: stripImages(parts),
selectedCode,
+ isInAgentMode,
});
if (result.status === "success") {
contextItems.push(...result.content);
@@ -162,6 +171,7 @@ async function gatherContextItems({
query: "",
fullInput: stripImages(parts),
selectedCode,
+ isInAgentMode,
});
if (result.status === "success") {
@@ -181,6 +191,7 @@ async function gatherContextItems({
query: "non-mention-usage",
fullInput: "",
selectedCode: [],
+ isInAgentMode,
},
);
if (currentFileResponse.status === "success") {
diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx
index 77fd2757f..27b093799 100644
--- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx
+++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx
@@ -18,12 +18,13 @@ export function EditFile(props: EditToolCallProps) {
return (
);
}
diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts
index 6cd96dd8e..45d68b456 100644
--- a/gui/src/redux/slices/sessionSlice.ts
+++ b/gui/src/redux/slices/sessionSlice.ts
@@ -405,7 +405,6 @@ export const sessionSlice = createSlice({
}
} else if (message.role === "thinking" && message.signature) {
if (lastMessage.role === "thinking") {
- console.log("add signature", message.signature);
lastMessage.signature = message.signature;
}
} else if (
diff --git a/gui/src/redux/thunks/edit.ts b/gui/src/redux/thunks/edit.ts
index 73b65740e..059b285ce 100644
--- a/gui/src/redux/thunks/edit.ts
+++ b/gui/src/redux/thunks/edit.ts
@@ -35,10 +35,11 @@ export const streamEditThunk = createAsyncThunk<
ThunkApiType
>(
"edit/streamResponse",
- async ({ editorState, codeToEdit }, { dispatch, extra }) => {
+ async ({ editorState, codeToEdit }, { dispatch, extra, getState }) => {
await dispatch(
streamThunkWrapper(async () => {
dispatch(setActive());
+
const { selectedContextItems, content } = await resolveEditorContent({
editorState,
modifiers: {
@@ -49,6 +50,7 @@ export const streamEditThunk = createAsyncThunk<
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
+ getState,
});
const prompt = [
diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts
index 11763a462..ac7af1ec2 100644
--- a/gui/src/redux/thunks/streamResponse.ts
+++ b/gui/src/redux/thunks/streamResponse.ts
@@ -64,6 +64,7 @@ export const streamResponseThunk = createAsyncThunk<
defaultContextProviders,
availableSlashCommands: state.config.config.slashCommands,
dispatch,
+ getState,
});
// symbols for both context items AND selected codeblocks
diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts
index 97dc50eb0..b8db3f830 100644
--- a/gui/src/util/clientTools/searchReplaceImpl.test.ts
+++ b/gui/src/util/clientTools/searchReplaceImpl.test.ts
@@ -36,7 +36,13 @@ describe("searchReplaceToolImpl", () => {
// Create mock extras
mockExtras = {
ideMessenger: mockIdeMessenger,
- getState: vi.fn(),
+ getState: vi.fn(() => ({
+ config: {
+ config: {
+ allowAnonymousTelemetry: false,
+ },
+ },
+ })),
dispatch: vi.fn(),
};
});
@@ -99,6 +105,7 @@ describe("searchReplaceToolImpl", () => {
mockFindSearchMatch.mockReturnValue({
startIndex,
endIndex,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -173,10 +180,12 @@ const c = 3;`;
.mockReturnValueOnce({
startIndex: firstStartIndex,
endIndex: firstEndIndex,
+ strategyName: "exactMatch",
})
.mockReturnValueOnce({
startIndex: secondStartIndex,
endIndex: secondEndIndex,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -239,6 +248,7 @@ keep this too`;
mockFindSearchMatch.mockReturnValue({
startIndex: 10, // Position of "remove this line"
endIndex: 26, // End of "remove this line"
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -278,6 +288,7 @@ keep this too`;
mockFindSearchMatch.mockReturnValue({
startIndex: 6,
endIndex: 11,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -344,6 +355,7 @@ keep this too`;
.mockReturnValueOnce({
startIndex: 0,
endIndex: 13,
+ strategyName: "exactMatch",
})
.mockReturnValueOnce(null); // Second search fails
@@ -393,6 +405,7 @@ keep this too`;
mockFindSearchMatch.mockReturnValue({
startIndex: 0,
endIndex: 7,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed"));
@@ -423,6 +436,7 @@ keep this too`;
mockFindSearchMatch.mockReturnValue({
startIndex: 0, // Empty search matches at beginning
endIndex: 0,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -457,6 +471,7 @@ keep this too`;
mockFindSearchMatch.mockReturnValue({
startIndex: 0,
endIndex: originalContent.length,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -492,6 +507,7 @@ keep this too`;
mockFindSearchMatch.mockReturnValue({
startIndex: 0,
endIndex: 4,
+ strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts
index cbab201f3..9594b9480 100644
--- a/gui/src/util/clientTools/searchReplaceImpl.ts
+++ b/gui/src/util/clientTools/searchReplaceImpl.ts
@@ -1,6 +1,7 @@
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 { ClientToolImpl } from "./callClientTool";
@@ -11,6 +12,9 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
) => {
const { filepath, diff } = args;
+ const state = extras.getState();
+ const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
+
const streamId = uuid();
// Resolve the file path
@@ -42,6 +46,16 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
// 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}`,