From 604ec09ef12f780ca7047f6a226a0715ac682d3b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 19 Sep 2025 17:35:21 -0700 Subject: [PATCH] WIP: perform search and replace with fallbacks --- .../findAndReplaceUtils.test.ts | 2 +- .../searchAndReplace}/findAndReplaceUtils.ts | 5 +- core/edit/searchAndReplace/findSearchMatch.ts | 53 +++++++++++++- core/edit/searchAndReplace/performReplace.ts | 70 +++++++++++++++++++ .../gui/ToolCallDiv/FindAndReplace.test.tsx | 2 +- .../pages/gui/ToolCallDiv/FindAndReplace.tsx | 8 +-- .../util/clientTools/multiEditImpl.test.ts | 2 +- gui/src/util/clientTools/multiEditImpl.ts | 10 +-- .../clientTools/singleFindAndReplaceImpl.ts | 8 +-- 9 files changed, 140 insertions(+), 20 deletions(-) rename {gui/src/util/clientTools => core/edit/searchAndReplace}/findAndReplaceUtils.test.ts (99%) rename {gui/src/util/clientTools => core/edit/searchAndReplace}/findAndReplaceUtils.ts (96%) diff --git a/gui/src/util/clientTools/findAndReplaceUtils.test.ts b/core/edit/searchAndReplace/findAndReplaceUtils.test.ts similarity index 99% rename from gui/src/util/clientTools/findAndReplaceUtils.test.ts rename to core/edit/searchAndReplace/findAndReplaceUtils.test.ts index c898439b3..0ed8cfe65 100644 --- a/gui/src/util/clientTools/findAndReplaceUtils.test.ts +++ b/core/edit/searchAndReplace/findAndReplaceUtils.test.ts @@ -1,5 +1,5 @@ -import { EditOperation } from "core/tools/definitions/multiEdit"; import { describe, expect, it } from "vitest"; +import { EditOperation } from "../../tools/definitions/multiEdit"; import { EMPTY_NON_FIRST_EDIT_MESSAGE, FOUND_MULTIPLE_FIND_STRINGS_ERROR, diff --git a/gui/src/util/clientTools/findAndReplaceUtils.ts b/core/edit/searchAndReplace/findAndReplaceUtils.ts similarity index 96% rename from gui/src/util/clientTools/findAndReplaceUtils.ts rename to core/edit/searchAndReplace/findAndReplaceUtils.ts index 0404259a1..5b99e7f83 100644 --- a/gui/src/util/clientTools/findAndReplaceUtils.ts +++ b/core/edit/searchAndReplace/findAndReplaceUtils.ts @@ -1,5 +1,5 @@ -import { EditOperation } from "core/tools/definitions/multiEdit"; -import { ContinueError, ContinueErrorReason } from "core/util/errors"; +import { EditOperation } from "../../tools/definitions/multiEdit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; @@ -89,6 +89,7 @@ export function validateSingleEdit( export const EMPTY_NON_FIRST_EDIT_MESSAGE = "contains empty old_string. Only the first edit can contain an empty old_string, which is only used for file creation."; + export function validateCreatingForMultiEdit(edits: EditOperation[]) { const isCreating = edits[0].old_string === ""; if (edits.length > 1) { diff --git a/core/edit/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts index 29704e967..f857c7d42 100644 --- a/core/edit/searchAndReplace/findSearchMatch.ts +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -4,7 +4,7 @@ interface BasicMatchResult { /** The starting character index of the match in the file content */ startIndex: number; - /** The ending character index of the match in the file content */ + /** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/ endIndex: number; } @@ -124,7 +124,7 @@ function whitespaceIgnoredMatch( /** * Calculate the Jaro similarity between two strings - * TODO Re + * TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match */ function jaroSimilarity(s1: string, s2: string): number { if (s1 === s2) return 1.0; @@ -322,3 +322,52 @@ export function findSearchMatch( return null; } + +/** + * Find all matches for search content in file content. + * Uses the same matching strategies as findSearchMatch, applied iteratively. + * + * @param fileContent - The complete content of the file to search in + * @param searchContent - The content to search for + * @returns Array of match results with character positions, empty array if no matches found + */ +export function findSearchMatches( + fileContent: string, + searchContent: string, +): SearchMatchResult[] { + const matches: SearchMatchResult[] = []; + let remainingContent = fileContent; + let currentOffset = 0; + + while (remainingContent.length > 0) { + const match = findSearchMatch(remainingContent, searchContent); + + if (match === null) { + break; + } + + // Adjust match positions to account for the current offset + const adjustedMatch: SearchMatchResult = { + startIndex: match.startIndex + currentOffset, + endIndex: match.endIndex + currentOffset, + strategyName: match.strategyName, + }; + + // Prevent infinite loops by ensuring we're making progress + // If the new match starts at or before the last match's start position, break + if ( + matches.length > 0 && + adjustedMatch.startIndex <= matches[matches.length - 1].startIndex + ) { + break; + } + + matches.push(adjustedMatch); + + // Update offset and truncate content after the current match + currentOffset = adjustedMatch.endIndex; + remainingContent = fileContent.slice(currentOffset); + } + + return matches; +} diff --git a/core/edit/searchAndReplace/performReplace.ts b/core/edit/searchAndReplace/performReplace.ts index e69de29bb..5a80c6215 100644 --- a/core/edit/searchAndReplace/performReplace.ts +++ b/core/edit/searchAndReplace/performReplace.ts @@ -0,0 +1,70 @@ +import { EditOperation } from "../../tools/definitions/multiEdit"; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; +import { findSearchMatch, findSearchMatches } from "./findSearchMatch"; + +export function executeFindAndReplace( + fileContent: string, + oldString: string, + newString: string, + editIndex = 0, +): string { + const match = findSearchMatch(fileContent, oldString); + if (!match) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceOldStringNotFound, + `Edit at index ${editIndex}: string not found in file: "${oldString}"`, + ); + } + return ( + fileContent.substring(0, match.startIndex) + + newString + + fileContent.substring(match.endIndex) + ); +} + +export function executeMultiFindAndReplace( + fileContent: string, + edits: EditOperation[], +): string { + let result = fileContent; + + // Apply edits in reverse order by startIndex to avoid position shifts + // affecting subsequent edits + for (let editIndex = 0; editIndex < edits.length; editIndex++) { + const edit = edits[editIndex]; + const matches = findSearchMatches(result, edit.old_string); + if (matches.length === 0) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceOldStringNotFound, + `Edit at index ${editIndex}: string not found in file: "${edit.old_string}"`, + ); + } + if (edit.replace_all) { + // Apply replacements in reverse order to maintain correct positions + for (let i = matches.length - 1; i >= 0; i--) { + const match = matches[i]; + result = + result.substring(0, match.startIndex) + + edit.new_string + + result.substring(match.endIndex); + } + } else { + // For single replacement, check for multiple matches first + if (matches.length > 1) { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMultipleOccurrences, + `Edit at index ${editIndex}: String "${edit.old_string}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, + ); + } + + // Apply single replacement + const match = matches[0]; + result = + result.substring(0, match.startIndex) + + edit.new_string + + result.substring(match.endIndex); + } + } + + return result; +} diff --git a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx index 966cb075b..e394e6e1a 100644 --- a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.test.tsx @@ -43,8 +43,8 @@ vi.mock("react", async () => { }); // Import mocked modules +import { performFindAndReplace } from "core/edit/searchAndReplace/findAndReplaceUtils"; import { useAppSelector } from "../../../redux/hooks"; -import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils"; const mockPost = vi.fn(); const mockUseAppSelector = useAppSelector as any; diff --git a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx index d69517740..94b18c565 100644 --- a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx @@ -1,5 +1,9 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; +import { + performFindAndReplace, + trimEmptyLines, +} from "core/edit/searchAndReplace/findAndReplaceUtils"; import { EditOperation } from "core/tools/definitions/multiEdit"; import { renderContextItems } from "core/util/messageContent"; import { getLastNPathParts, getUriPathBasename } from "core/util/uri"; @@ -13,10 +17,6 @@ import { selectApplyStateByToolCallId, selectToolCallById, } from "../../../redux/selectors/selectToolCalls"; -import { - performFindAndReplace, - trimEmptyLines, -} from "../../../util/clientTools/findAndReplaceUtils"; import { cn } from "../../../util/cn"; import { getStatusIcon } from "./utils"; diff --git a/gui/src/util/clientTools/multiEditImpl.test.ts b/gui/src/util/clientTools/multiEditImpl.test.ts index 7c262cb82..da3c5106d 100644 --- a/gui/src/util/clientTools/multiEditImpl.test.ts +++ b/gui/src/util/clientTools/multiEditImpl.test.ts @@ -1,8 +1,8 @@ +import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "core/edit/searchAndReplace/findAndReplaceUtils"; import * as ideUtils from "core/util/ideUtils"; import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolExtras } from "./callClientTool"; -import { FOUND_MULTIPLE_FIND_STRINGS_ERROR } from "./findAndReplaceUtils"; import { multiEditImpl } from "./multiEditImpl"; vi.mock("uuid", () => ({ diff --git a/gui/src/util/clientTools/multiEditImpl.ts b/gui/src/util/clientTools/multiEditImpl.ts index 1a9f7dbd5..a091030c0 100644 --- a/gui/src/util/clientTools/multiEditImpl.ts +++ b/gui/src/util/clientTools/multiEditImpl.ts @@ -1,3 +1,8 @@ +import { + performFindAndReplace, + validateCreatingForMultiEdit, + validateSingleEdit, +} from "core/edit/searchAndReplace/findAndReplaceUtils"; import { ContinueError, ContinueErrorReason } from "core/util/errors"; import { inferResolvedUriFromRelativePath, @@ -6,11 +11,6 @@ import { import { v4 as uuid } from "uuid"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; -import { - performFindAndReplace, - validateCreatingForMultiEdit, - validateSingleEdit, -} from "./findAndReplaceUtils"; export const multiEditImpl: ClientToolImpl = async ( args, diff --git a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts index b8137c9f5..670210803 100644 --- a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts +++ b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts @@ -1,12 +1,12 @@ +import { + performFindAndReplace, + validateSingleEdit, +} from "core/edit/searchAndReplace/findAndReplaceUtils"; import { ContinueError, ContinueErrorReason } from "core/util/errors"; import { resolveRelativePathInDir } from "core/util/ideUtils"; import { v4 as uuid } from "uuid"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; -import { - performFindAndReplace, - validateSingleEdit, -} from "./findAndReplaceUtils"; export const singleFindAndReplaceImpl: ClientToolImpl = async ( args,