From c4f17fae2dadceeb1476a71d9abd58848814bd64 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 26 Jun 2025 10:27:29 +0530 Subject: [PATCH 01/24] when no results were retrieved, use other tools - add the instruction prompt --- core/context/retrieval/retrieval.ts | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 3b8e98427..8e89af7ad 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -24,6 +24,8 @@ export async function retrieveContextItemsFromEmbeddings( // } const includeEmbeddings = !!extras.config.selectedModelByRole.embed; + console.log("debug1 running retrieval"); + // Get tags to retrieve for const workspaceDirs = await extras.ide.getWorkspaceDirs(); @@ -70,25 +72,22 @@ export async function retrieveContextItemsFromEmbeddings( }; const pipeline = new pipelineType(pipelineOptions); - const results = await pipeline.run({ - tags, - filterDirectory, - query: extras.fullInput, - includeEmbeddings, - }); + const results = [] as any[]; 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 []; } - return []; + return [ + { + ...INSTRUCTIONS_BASE_ITEM, + content: "No results were found. Try using other tools.", + }, + ]; } return [ From aace37c178e86ff1970ed88e659e810b2578bc73 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 26 Jun 2025 16:29:21 +0530 Subject: [PATCH 02/24] remove console log --- core/context/retrieval/retrieval.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 8e89af7ad..b53afa1e4 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -24,8 +24,6 @@ export async function retrieveContextItemsFromEmbeddings( // } const includeEmbeddings = !!extras.config.selectedModelByRole.embed; - console.log("debug1 running retrieval"); - // Get tags to retrieve for const workspaceDirs = await extras.ide.getWorkspaceDirs(); @@ -72,7 +70,12 @@ export async function retrieveContextItemsFromEmbeddings( }; const pipeline = new pipelineType(pipelineOptions); - const results = [] as any[]; + const results = await pipeline.run({ + tags, + filterDirectory, + query: extras.fullInput, + includeEmbeddings, + }); if (results.length === 0) { if (extras.config.disableIndexing) { From ed49258fd618d33d2a353eb22f2a81e5d3b92d02 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 1 Jul 2025 13:11:05 +0530 Subject: [PATCH 03/24] add isInAgentMode in retreival pipeline --- core/context/retrieval/retrieval.ts | 15 +++++++++------ core/core.ts | 2 ++ core/index.d.ts | 1 + core/protocol/core.ts | 1 + .../mainInput/AtMentionDropdown/index.tsx | 5 +++++ .../TipTapEditor/utils/renderPromptv1.ts | 1 + .../TipTapEditor/utils/resolveEditorContent.ts | 11 +++++++++++ gui/src/redux/thunks/edit.ts | 4 +++- gui/src/redux/thunks/streamResponse.ts | 3 ++- 9 files changed, 35 insertions(+), 8 deletions(-) diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index b53afa1e4..a03cf5b12 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -85,12 +85,15 @@ export async function retrieveContextItemsFromEmbeddings( ); return []; } - return [ - { - ...INSTRUCTIONS_BASE_ITEM, - content: "No results were found. Try using other tools.", - }, - ]; + if (extras.isInAgentMode) { + return [ + { + ...INSTRUCTIONS_BASE_ITEM, + content: "No results were found. Try using other tools.", + }, + ]; + } + return []; } return [ diff --git a/core/core.ts b/core/core.ts index 13edb15b2..6cb8d711a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1021,6 +1021,7 @@ export class Core { query: string; fullInput: string; selectedCode: RangeInFile[]; + isInAgentMode: boolean; }>, ) => { const { config } = await this.configHandler.loadConfig(); @@ -1068,6 +1069,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/index.d.ts b/core/index.d.ts index 39e7cb911..8686e7f4d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -186,6 +186,7 @@ export interface ContextProviderExtras { ide: IDE; selectedCode: RangeInFile[]; fetch: FetchFunction; + isInAgentMode: boolean; } export interface LoadSubmenuItemsArgs { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f2f44e3ee..a4dc25028 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -109,6 +109,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { query: string; fullInput: string; selectedCode: RangeInFile[]; + isInAgentMode: boolean; }, ContextItemWithId[], ]; 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/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 5dc031e56..d02ea43b6 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -68,6 +68,7 @@ export const streamResponseThunk = createAsyncThunk< defaultContextProviders, availableSlashCommands: state.config.config.slashCommands, dispatch, + getState, }); // symbols for both context items AND selected codeblocks @@ -77,7 +78,7 @@ export const streamResponseThunk = createAsyncThunk< .map((item) => item.uri!.value), ...selectedCode.map((rif) => rif.filepath), ]; - dispatch(updateFileSymbolsFromFiles(filesForSymbols)); + void dispatch(updateFileSymbolsFromFiles(filesForSymbols)); dispatch( updateHistoryItemAtIndex({ From c22402b6d9981f577b82b397aa06cb6c5e8dbc55 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 1 Jul 2025 13:36:17 +0530 Subject: [PATCH 04/24] fix type in tests --- core/context/providers/_context-providers.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 468aac6ec..056d01755 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -48,6 +48,7 @@ async function getContextProviderExtras( llm: config.modelsByRole.chat[0], reranker: config.selectedModelByRole.rerank, selectedCode: [], + isInAgentMode: true, }; } From 02689a752556a48d5ac2199b6213addcc23fc1a3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 1 Jul 2025 13:40:01 +0530 Subject: [PATCH 05/24] fix type --- extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts | 1 + 1 file changed, 1 insertion(+) 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, }); }) || [], ) From a94da7a9f1075ffeffa868e791cf076b8557c70c Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 4 Jul 2025 10:45:47 +0530 Subject: [PATCH 06/24] fix type error --- core/tools/implementations/codebaseTool.ts | 1 + 1 file changed, 1 insertion(+) 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 From a63fc267e97e83c61e422e991c87d50fa2fe8e53 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 4 Jul 2025 18:14:12 +0530 Subject: [PATCH 07/24] fix multiple configs present --- extensions/vscode/src/activation/activate.ts | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) 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) { From a50aecef37c024b27685214a1078d01a50c0d6ff Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 10:02:16 -0700 Subject: [PATCH 08/24] don't throw noisy error when reranker isn't properly configured --- .../context/retrieval/pipelines/RerankerRetrievalPipeline.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) 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); } } From a91a28160e88cf217d04ab8dd58f5e1ffc05694e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 10:12:52 -0700 Subject: [PATCH 09/24] fix typo --- core/indexing/LanceDbIndex.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 0a285b15d..facaba2f1 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -300,7 +300,7 @@ export class LanceDbIndex implements CodebaseIndex { const vector = JSON.parse(item.vector); const { uuid, startLine, endLine, contents } = item; - cachedItems.push({ + lanceRows.push({ path, uuid, startLine, From 7f00150114d5804ad70cd2b04fc2c20a03e4721a Mon Sep 17 00:00:00 2001 From: Emmanuel Ferdman Date: Fri, 4 Jul 2025 13:45:39 -0700 Subject: [PATCH 10/24] Move the CLA document Signed-off-by: Emmanuel Ferdman --- docs/{ => docs}/CLA.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename docs/{ => docs}/CLA.md (100%) 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 From 97131c24fe31c0af3ec26e3a3e93ad688be2c112 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 15:36:24 -0700 Subject: [PATCH 11/24] hotfix for read file tool --- core/llm/countTokens.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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; } From fb70b61ac44e20f20fd980cb414ddb2211cb58be Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 15:36:34 -0700 Subject: [PATCH 12/24] bump package.json --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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" From 4868cdf8855612f166c37aceb5ea5d160edd8dc1 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 19:07:49 -0700 Subject: [PATCH 13/24] refactor findSearchMatch --- core/edit/searchAndReplace/findSearchMatch.ts | 76 ++++++++++++++----- .../definitions/searchAndReplaceInFile.ts | 2 +- 2 files changed, 57 insertions(+), 21 deletions(-) diff --git a/core/edit/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts index 3b1b8acf8..727e0b0ba 100644 --- a/core/edit/searchAndReplace/findSearchMatch.ts +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -8,14 +8,61 @@ export interface SearchMatchResult { endIndex: number; } +/** + * Strategy function type for finding matches + */ +type MatchStrategy = ( + fileContent: string, + searchContent: string, +) => SearchMatchResult | null; + +/** + * Exact string matching strategy + */ +function exactMatch( + fileContent: string, + searchContent: string, +): SearchMatchResult | null { + const exactIndex = fileContent.indexOf(searchContent); + if (exactIndex !== -1) { + return { + startIndex: exactIndex, + endIndex: exactIndex + searchContent.length, + }; + } + return null; +} + +/** + * Trimmed content matching strategy + */ +function trimmedMatch( + fileContent: string, + searchContent: string, +): SearchMatchResult | null { + const trimmedSearchContent = searchContent.trim(); + const trimmedIndex = fileContent.indexOf(trimmedSearchContent); + if (trimmedIndex !== -1) { + return { + startIndex: trimmedIndex, + endIndex: trimmedIndex + trimmedSearchContent.length, + }; + } + return null; +} + +/** + * Ordered list of matching strategies to try + */ +const matchingStrategies: MatchStrategy[] = [exactMatch, trimmedMatch]; + /** * Find the exact match position for search content in file content. - * Uses simple exact matching with trimmed newlines for MVP. + * 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 exact string match first - * 3. Fallback to trimmed content match if exact match fails + * 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 @@ -25,7 +72,6 @@ export function findSearchMatch( fileContent: string, searchContent: string, ): SearchMatchResult | null { - // Strip leading/trailing newlines for basic matching strategy const trimmedSearchContent = searchContent.trim(); if (trimmedSearchContent === "") { @@ -33,22 +79,12 @@ export function findSearchMatch( return { startIndex: 0, endIndex: 0 }; } - // Try exact match first - const exactIndex = fileContent.indexOf(searchContent); - if (exactIndex !== -1) { - return { - startIndex: exactIndex, - endIndex: exactIndex + searchContent.length, - }; - } - - // Fallback: try trimmed content match - const trimmedIndex = fileContent.indexOf(trimmedSearchContent); - if (trimmedIndex !== -1) { - return { - startIndex: trimmedIndex, - endIndex: trimmedIndex + trimmedSearchContent.length, - }; + // Try each matching strategy in order + for (const strategy of matchingStrategies) { + const result = strategy(fileContent, searchContent); + if (result !== null) { + return result; + } } return null; 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"], From 932a5fbdc73c10011650cc96eb592ed0e5fb25ce Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Fri, 4 Jul 2025 19:14:55 -0700 Subject: [PATCH 14/24] =?UTF-8?q?rolling=20back=20edit=20logging=20tempora?= =?UTF-8?q?rily=20=E2=80=94=20issues=20with=20repo=20detection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/nextEdit/context/processNextEditData.ts | 34 ++++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) 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 = { From 13d5527f2a7827e11ad3441be2f81e4b3be290e5 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 19:27:53 -0700 Subject: [PATCH 15/24] whitespace ignored matching algorithm + tests --- .../searchAndReplace/findSearchMatch.test.ts | 666 ++++++++++++------ core/edit/searchAndReplace/findSearchMatch.ts | 63 +- 2 files changed, 509 insertions(+), 220 deletions(-) diff --git a/core/edit/searchAndReplace/findSearchMatch.test.ts b/core/edit/searchAndReplace/findSearchMatch.test.ts index 8d5c3682b..aa2e6f701 100644 --- a/core/edit/searchAndReplace/findSearchMatch.test.ts +++ b/core/edit/searchAndReplace/findSearchMatch.test.ts @@ -1,319 +1,548 @@ 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, }); + }); - 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, }); + }); - 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, }); + }); - 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, }); + }); - 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, }); }); +}); - 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 }); + }); - 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, }); + }); - 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, + }); + }); +}); + +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, }); }); - 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, }); }); - 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, }); + }); +}); - 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).toBeNull(); + }); + + it("should return null 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).toBeNull(); + }); - it("should return null for non-existent single line", () => { - const fileContent = `const a = 1; + 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;`; + const searchContent = `const d = 4;`; - 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() { + it("should return null for partial match", () => { + const fileContent = `function hello() { console.log("world"); }`; - const searchContent = `function hello() { + const searchContent = `function hello() { console.log("universe"); }`; - const result = findSearchMatch(fileContent, searchContent); + const result = findSearchMatch(fileContent, searchContent); - expect(result).toBeNull(); + expect(result).toBeNull(); + }); +}); + +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, }); }); - 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, }); + }); - 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, }); }); - 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, + }); + }); +}); + +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;" + + // 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;" + + // 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}" + + // 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'" + + // 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;" + + // 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, + }); + }); + + 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, + }); + }); + + 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 " }" + + // 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 whitespace-ignored match exists", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = `function goodbye() { + console.log("universe"); +}`; + + 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, + }); + }); +}); + +describe("Real-world scenarios", () => { + it("should match typical function replacement", () => { + const fileContent = `class Calculator { constructor() { this.result = 0; } @@ -328,41 +557,41 @@ 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, }); + }); - 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, }); + }); - it("should match comment block", () => { - const fileContent = `/** + it("should match comment block", () => { + const fileContent = `/** * This is a comment * that spans multiple lines */ @@ -370,17 +599,16 @@ 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, }); }); }); diff --git a/core/edit/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts index 727e0b0ba..465a41b6a 100644 --- a/core/edit/searchAndReplace/findSearchMatch.ts +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -51,10 +51,71 @@ function trimmedMatch( return null; } +/** + * Whitespace-ignored matching strategy + * Removes all whitespace from both content and search, then finds the match + */ +function whitespaceIgnoredMatch( + fileContent: string, + searchContent: string, +): SearchMatchResult | 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 */ -const matchingStrategies: MatchStrategy[] = [exactMatch, trimmedMatch]; +const matchingStrategies: MatchStrategy[] = [ + exactMatch, + trimmedMatch, + whitespaceIgnoredMatch, +]; /** * Find the exact match position for search content in file content. From b5df848e63114601a0f99a3d1b4017d7f03c6a42 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 20:04:53 -0700 Subject: [PATCH 16/24] add telemetry for match result --- .../searchAndReplace/findSearchMatch.test.ts | 27 ++++++++++++++ core/edit/searchAndReplace/findSearchMatch.ts | 36 +++++++++++-------- .../clientTools/searchReplaceImpl.test.ts | 10 ++++++ gui/src/util/clientTools/searchReplaceImpl.ts | 14 ++++++++ 4 files changed, 73 insertions(+), 14 deletions(-) diff --git a/core/edit/searchAndReplace/findSearchMatch.test.ts b/core/edit/searchAndReplace/findSearchMatch.test.ts index aa2e6f701..522c9f095 100644 --- a/core/edit/searchAndReplace/findSearchMatch.test.ts +++ b/core/edit/searchAndReplace/findSearchMatch.test.ts @@ -14,6 +14,7 @@ describe("Exact matches", () => { expect(result).toEqual({ startIndex: 0, endIndex: fileContent.length, + strategyName: "exactMatch", }); }); @@ -32,6 +33,7 @@ const b = 2;`; expect(result).toEqual({ startIndex: 13, // After "const a = 1;\n" endIndex: 13 + searchContent.length, + strategyName: "exactMatch", }); }); @@ -49,6 +51,7 @@ function hello() { expect(result).toEqual({ startIndex: 13, // After "const a = 1;\n" endIndex: fileContent.length, + strategyName: "exactMatch", }); }); @@ -63,6 +66,7 @@ const c = 3;`; expect(result).toEqual({ startIndex: 13, // After "const a = 1;\n" endIndex: 13 + searchContent.length, + strategyName: "exactMatch", }); }); @@ -80,6 +84,7 @@ const c = 3;`; expect(result).toEqual({ startIndex: 18, endIndex: 18 + searchContent.length, + strategyName: "exactMatch", }); }); }); @@ -98,6 +103,7 @@ describe("Trimmed matches", () => { expect(result).toEqual({ startIndex: 0, endIndex: fileContent.length, // Uses trimmed length + strategyName: "trimmedMatch", }); }); @@ -117,6 +123,7 @@ const b = 2;`; expect(result).toEqual({ startIndex: 12, endIndex: 12 + searchContent.length, + strategyName: "exactMatch", }); }); @@ -134,6 +141,7 @@ const c = 3;`; expect(result).toEqual({ startIndex: expectedStart, endIndex: expectedStart + trimmedSearchContent.length, + strategyName: "trimmedMatch", }); }); }); @@ -150,6 +158,7 @@ describe("Empty search content", () => { expect(result).toEqual({ startIndex: 0, endIndex: 0, + strategyName: "emptySearch", }); }); @@ -164,6 +173,7 @@ describe("Empty search content", () => { expect(result).toEqual({ startIndex: 0, endIndex: 0, + strategyName: "emptySearch", }); }); @@ -176,6 +186,7 @@ describe("Empty search content", () => { expect(result).toEqual({ startIndex: 0, endIndex: 0, + strategyName: "emptySearch", }); }); }); @@ -256,6 +267,7 @@ describe("Edge cases", () => { expect(result).toEqual({ startIndex: expectedStart, endIndex: expectedStart + searchContent.length, + strategyName: "exactMatch", }); }); @@ -271,6 +283,7 @@ const unicode = "πŸš€ Hello δΈ–η•Œ";`; expect(result).toEqual({ startIndex: expectedStart, endIndex: expectedStart + searchContent.length, + strategyName: "exactMatch", }); }); @@ -292,6 +305,7 @@ function test() { expect(result).toEqual({ startIndex: 0, endIndex: searchContent.length, + strategyName: "exactMatch", }); }); @@ -306,6 +320,7 @@ const a = 1;`; expect(result).toEqual({ startIndex: 0, endIndex: searchContent.length, + strategyName: "exactMatch", }); }); }); @@ -326,6 +341,7 @@ return x+y;`; 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( @@ -349,6 +365,7 @@ const c = 3;`; 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( @@ -374,6 +391,7 @@ const b = 2;`); 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( @@ -401,6 +419,7 @@ key3:'value3'`; 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( @@ -431,6 +450,7 @@ key3:'value3'`; 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( @@ -459,6 +479,7 @@ const x = 1;`; expect(result).toEqual({ startIndex: 0, endIndex: 10, + strategyName: "exactMatch", }); }); @@ -474,6 +495,7 @@ const x = 1;`; expect(result).toEqual({ startIndex: 0, endIndex: 0, + strategyName: "emptySearch", }); }); @@ -498,6 +520,7 @@ this.value=0; 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( @@ -536,6 +559,7 @@ const a = 1;`; expect(result).toEqual({ startIndex: 0, endIndex: 10, + strategyName: "exactMatch", }); }); }); @@ -568,6 +592,7 @@ describe("Real-world scenarios", () => { expect(result).toEqual({ startIndex: expectedStart, endIndex: expectedStart + searchContent.length, + strategyName: "exactMatch", }); }); @@ -587,6 +612,7 @@ function App() { expect(result).toEqual({ startIndex: expectedStart, endIndex: expectedStart + searchContent.length, + strategyName: "exactMatch", }); }); @@ -609,6 +635,7 @@ function test() { expect(result).toEqual({ startIndex: 0, endIndex: searchContent.length, + strategyName: "exactMatch", }); }); }); diff --git a/core/edit/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts index 465a41b6a..31ff64f0a 100644 --- a/core/edit/searchAndReplace/findSearchMatch.ts +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -1,20 +1,28 @@ /** - * 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 */ 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, -) => SearchMatchResult | null; +) => BasicMatchResult | null; /** * Exact string matching strategy @@ -22,7 +30,7 @@ type MatchStrategy = ( function exactMatch( fileContent: string, searchContent: string, -): SearchMatchResult | null { +): BasicMatchResult | null { const exactIndex = fileContent.indexOf(searchContent); if (exactIndex !== -1) { return { @@ -39,7 +47,7 @@ function exactMatch( function trimmedMatch( fileContent: string, searchContent: string, -): SearchMatchResult | null { +): BasicMatchResult | null { const trimmedSearchContent = searchContent.trim(); const trimmedIndex = fileContent.indexOf(trimmedSearchContent); if (trimmedIndex !== -1) { @@ -58,7 +66,7 @@ function trimmedMatch( function whitespaceIgnoredMatch( fileContent: string, searchContent: string, -): SearchMatchResult | null { +): BasicMatchResult | null { // Remove all whitespace (spaces, tabs, newlines, etc.) const strippedFileContent = fileContent.replace(/\s/g, ""); const strippedSearchContent = searchContent.replace(/\s/g, ""); @@ -109,12 +117,12 @@ function whitespaceIgnoredMatch( } /** - * Ordered list of matching strategies to try + * Ordered list of matching strategies to try with their names */ -const matchingStrategies: MatchStrategy[] = [ - exactMatch, - trimmedMatch, - whitespaceIgnoredMatch, +const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ + { strategy: exactMatch, name: "exactMatch" }, + { strategy: trimmedMatch, name: "trimmedMatch" }, + { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, ]; /** @@ -137,14 +145,14 @@ export function findSearchMatch( if (trimmedSearchContent === "") { // Empty search content matches the beginning of the file - return { startIndex: 0, endIndex: 0 }; + return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; } // Try each matching strategy in order - for (const strategy of matchingStrategies) { + for (const { strategy, name } of matchingStrategies) { const result = strategy(fileContent, searchContent); if (result !== null) { - return result; + return { ...result, strategyName: name }; } } diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts index 97dc50eb0..a31089d7c 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.test.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.test.ts @@ -99,6 +99,7 @@ describe("searchReplaceToolImpl", () => { mockFindSearchMatch.mockReturnValue({ startIndex, endIndex, + strategyName: "exactMatch", }); mockIdeMessenger.request.mockResolvedValue({ status: "success" }); @@ -173,10 +174,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 +242,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 +282,7 @@ keep this too`; mockFindSearchMatch.mockReturnValue({ startIndex: 6, endIndex: 11, + strategyName: "exactMatch", }); mockIdeMessenger.request.mockResolvedValue({ status: "success" }); @@ -344,6 +349,7 @@ keep this too`; .mockReturnValueOnce({ startIndex: 0, endIndex: 13, + strategyName: "exactMatch", }) .mockReturnValueOnce(null); // Second search fails @@ -393,6 +399,7 @@ keep this too`; mockFindSearchMatch.mockReturnValue({ startIndex: 0, endIndex: 7, + strategyName: "exactMatch", }); mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed")); @@ -423,6 +430,7 @@ keep this too`; mockFindSearchMatch.mockReturnValue({ startIndex: 0, // Empty search matches at beginning endIndex: 0, + strategyName: "exactMatch", }); mockIdeMessenger.request.mockResolvedValue({ status: "success" }); @@ -457,6 +465,7 @@ keep this too`; mockFindSearchMatch.mockReturnValue({ startIndex: 0, endIndex: originalContent.length, + strategyName: "exactMatch", }); mockIdeMessenger.request.mockResolvedValue({ status: "success" }); @@ -492,6 +501,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}`, From 5a598bf6cc987176f11b655e11dff1a69db214b0 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 21:57:08 -0700 Subject: [PATCH 17/24] don't expand edit tool codeblocks by default --- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 77fd2757f..17d306374 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -18,7 +18,7 @@ export function EditFile(props: EditToolCallProps) { return ( Date: Fri, 4 Jul 2025 22:19:47 -0700 Subject: [PATCH 18/24] make edit container collapsible --- .../CollapsibleContainer.tsx | 48 +++++++++++++++++++ .../StepContainerPreToolbar/index.tsx | 5 +- 2 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx new file mode 100644 index 000000000..1b029ddb6 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx @@ -0,0 +1,48 @@ +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import { useState } from "react"; + +interface CollapsibleContainerProps { + children: React.ReactNode; + maxHeight?: string; + className?: string; +} + +export function CollapsibleContainer({ + children, + maxHeight = "max-h-40", + className = "", +}: CollapsibleContainerProps) { + const [isExpanded, setIsExpanded] = useState(false); + + return ( +
+
+ {children} +
+ + {!isExpanded && ( +
+
setIsExpanded(true)} + className="flex h-full cursor-pointer items-end justify-center pb-2" + > + + + +
+
+ )} + + {isExpanded && ( +
setIsExpanded(false)} + className="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..0b564582f 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"; @@ -299,9 +300,7 @@ export function StepContainerPreToolbar({ - {isExpanded && ( -
{children}
- )} + {isExpanded && {children}} ); } From 76d73dbb915d44ac4928c23da0f8da1ccf5524de Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 22:24:52 -0700 Subject: [PATCH 19/24] hover color --- .../StepContainerPreToolbar/CollapsibleContainer.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx index 1b029ddb6..fbc5f1366 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx @@ -24,10 +24,10 @@ export function CollapsibleContainer({
setIsExpanded(true)} - className="flex h-full cursor-pointer items-end justify-center pb-2" + className="group flex h-full cursor-pointer items-end justify-center pb-2" > - +
@@ -36,10 +36,10 @@ export function CollapsibleContainer({ {isExpanded && (
setIsExpanded(false)} - className="mt-2 flex cursor-pointer justify-center" + className="group mt-2 flex cursor-pointer justify-center" > - +
)} From 923b7e79d30aefec77d7209cd3174fd06d76a08f Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 22:50:08 -0700 Subject: [PATCH 20/24] don't collapse code blocks in chat mode --- .../StepContainerPreToolbar/CollapsibleContainer.tsx | 7 +++++++ .../StepContainerPreToolbar/index.tsx | 9 +++++++-- gui/src/components/StyledMarkdownPreview/index.tsx | 2 ++ gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 1 + 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx index fbc5f1366..464c4b4cf 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/CollapsibleContainer.tsx @@ -5,15 +5,22 @@ 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 (
diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 0b564582f..1d252dbdb 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -33,6 +33,7 @@ export interface StepContainerPreToolbarProps { children: any; expanded?: boolean; disableManualApply?: boolean; + collapsible?: boolean; } export function StepContainerPreToolbar({ @@ -48,6 +49,7 @@ export function StepContainerPreToolbar({ children, expanded, disableManualApply, + collapsible, }: StepContainerPreToolbarProps) { const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((state) => state.session.history); @@ -299,8 +301,11 @@ export function StepContainerPreToolbar({ {renderActionButtons()}
- - {isExpanded && {children}} + {isExpanded && ( + + {children} + + )} ); } diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index 0f2d1af0d..b01e49256 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -127,6 +127,7 @@ interface StyledMarkdownPreviewProps { disableManualApply?: boolean; toolCallId?: string; expandCodeblocks?: boolean; + collapsible?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -305,6 +306,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( forceToolCallId={props.toolCallId} expanded={props.expandCodeblocks} disableManualApply={props.disableManualApply} + collapsible={props.collapsible} > diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 17d306374..27b093799 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -24,6 +24,7 @@ export function EditFile(props: EditToolCallProps) { source={src} toolCallId={props.toolCallId} itemIndex={props.historyIndex} + collapsible={true} /> ); } From 0a1c2db3225e10c353aa6e5a47b031430e8f5674 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 4 Jul 2025 23:13:48 -0700 Subject: [PATCH 21/24] fix jaro winkler --- .../searchAndReplace/findSearchMatch.test.ts | 189 +++++++++++++++--- core/edit/searchAndReplace/findSearchMatch.ts | 157 +++++++++++++++ 2 files changed, 315 insertions(+), 31 deletions(-) diff --git a/core/edit/searchAndReplace/findSearchMatch.test.ts b/core/edit/searchAndReplace/findSearchMatch.test.ts index 522c9f095..a39322e31 100644 --- a/core/edit/searchAndReplace/findSearchMatch.test.ts +++ b/core/edit/searchAndReplace/findSearchMatch.test.ts @@ -202,10 +202,10 @@ describe("No matches", () => { const result = findSearchMatch(fileContent, searchContent); - expect(result).toBeNull(); + expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch"); }); - it("should return null when trimmed search content is not found", () => { + it("should return only fuzzy result when trimmed search content is not found", () => { const fileContent = `function hello() { console.log("world"); }`; @@ -215,31 +215,7 @@ describe("No matches", () => { const result = findSearchMatch(fileContent, searchContent); - expect(result).toBeNull(); - }); - - 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;`; - - const result = findSearchMatch(fileContent, searchContent); - - expect(result).toBeNull(); - }); - - it("should return null for partial match", () => { - const fileContent = `function hello() { - console.log("world"); -}`; - const searchContent = `function hello() { - console.log("universe"); -}`; - - const result = findSearchMatch(fileContent, searchContent); - - expect(result).toBeNull(); + expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch"); }); }); @@ -534,13 +510,11 @@ this.value=0; }`); }); - it("should return null when no whitespace-ignored match exists", () => { + it("should return null when no close match exists", () => { const fileContent = `function hello() { console.log("world"); }`; - const searchContent = `function goodbye() { - console.log("universe"); -}`; + const searchContent = `this has nothing to do with the other option`; const result = findSearchMatch(fileContent, searchContent); @@ -638,4 +612,157 @@ function test() { 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 31ff64f0a..9597d5070 100644 --- a/core/edit/searchAndReplace/findSearchMatch.ts +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -116,6 +116,161 @@ function whitespaceIgnoredMatch( }; } +/** + * 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 */ @@ -123,6 +278,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ { strategy: exactMatch, name: "exactMatch" }, { strategy: trimmedMatch, name: "trimmedMatch" }, { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, + { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, ]; /** @@ -135,6 +291,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ * * @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( From 9a5c4c0b507752dbdabfb884cf8e73f67a8158c2 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Jul 2025 09:30:48 -0700 Subject: [PATCH 22/24] fix tests --- gui/src/util/clientTools/searchReplaceImpl.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts index a31089d7c..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(), }; }); From de2d0c187ffe460b3fe75849f787277b07a3fe18 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Jul 2025 09:53:53 -0700 Subject: [PATCH 23/24] parse incorrectly formatted vectors so we can salvage broken indexes --- core/indexing/LanceDbIndex.ts | 19 ++++++++++++++++++- gui/src/redux/slices/sessionSlice.ts | 1 - 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index facaba2f1..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,7 +314,7 @@ 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; lanceRows.push({ 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 ( From 1b58a968f8e044f421650f800c6f5d7b531bd7ca Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Jul 2025 09:56:27 -0700 Subject: [PATCH 24/24] more informative log for retrieval tool call parsing failures --- core/context/retrieval/pipelines/BaseRetrievalPipeline.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 []; }