| 1 | import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; |
| 2 | import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; |
| 3 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 4 | import posthog from "posthog-js"; |
| 5 | import { v4 as uuid } from "uuid"; |
| 6 | import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; |
| 7 | import { ClientToolImpl } from "./callClientTool"; |
| 8 | |
| 9 | export const searchReplaceToolImpl: ClientToolImpl = async ( |
| 10 | args, |
| 11 | toolCallId, |
| 12 | extras, |
| 13 | ) => { |
| 14 | const { filepath, diffs, editingFileContents } = args; |
| 15 | |
| 16 | const state = extras.getState(); |
| 17 | const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; |
| 18 | |
| 19 | const streamId = uuid(); |
| 20 | |
| 21 | // Resolve the file path |
| 22 | const resolvedFilepath = await resolveRelativePathInDir( |
| 23 | filepath, |
| 24 | extras.ideMessenger.ide, |
| 25 | ); |
| 26 | if (!resolvedFilepath) { |
| 27 | throw new Error(`File ${filepath} does not exist`); |
| 28 | } |
| 29 | |
| 30 | // Parse all search/replace blocks from all diff strings |
| 31 | const allBlocks = []; |
| 32 | for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) { |
| 33 | const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]); |
| 34 | if (blocks.length === 0) { |
| 35 | throw new Error( |
| 36 | `No complete search/replace blocks found in diff ${diffIndex + 1}`, |
| 37 | ); |
| 38 | } |
| 39 | allBlocks.push(...blocks); |
| 40 | } |
| 41 | |
| 42 | if (allBlocks.length === 0) { |
| 43 | throw new Error("No complete search/replace blocks found in any diffs"); |
| 44 | } |
| 45 | |
| 46 | try { |
| 47 | // Read the current file content |
| 48 | const originalContent = |
| 49 | editingFileContents ?? |
| 50 | (await extras.ideMessenger.ide.readFile(resolvedFilepath)); |
| 51 | let currentContent = originalContent; |
| 52 | |
| 53 | // Apply all replacements sequentially to build the final content |
| 54 | for (let i = 0; i < allBlocks.length; i++) { |
| 55 | const block = allBlocks[i]; |
| 56 | const { searchContent, replaceContent } = block; |
| 57 | |
| 58 | // Find the search content in the current state of the file |
| 59 | const match = findSearchMatch(currentContent, searchContent || ""); |
| 60 | |
| 61 | // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` |
| 62 | // directly rather than using `CustomPostHogProvider` |
| 63 | if (allowAnonymousTelemetry) { |
| 64 | // Capture telemetry for tool calls |
| 65 | posthog.capture("find_replace_match_result", { |
| 66 | matchStrategy: match?.strategyName ?? "noMatch", |
| 67 | }); |
| 68 | } |
| 69 | |
| 70 | if (!match) { |
| 71 | throw new Error( |
| 72 | `Search content not found in block ${i + 1}:\n${searchContent}`, |
| 73 | ); |
| 74 | } |
| 75 | |
| 76 | // Apply the replacement |
| 77 | currentContent = |
| 78 | currentContent.substring(0, match.startIndex) + |
| 79 | (replaceContent || "") + |
| 80 | currentContent.substring(match.endIndex); |
| 81 | } |
| 82 | |
| 83 | // Single applyToFile call with all accumulated changes |
| 84 | // This works becaues of our logic in `applyCodeBlock` that determines |
| 85 | // that the full file rewrite here can be applied instantly, so the diff |
| 86 | // lines are generated with meyers diff and streamed instantaneously |
| 87 | void extras.dispatch( |
| 88 | applyForEditTool({ |
| 89 | streamId, |
| 90 | toolCallId, |
| 91 | text: currentContent, |
| 92 | filepath: resolvedFilepath, |
| 93 | isSearchAndReplace: true, |
| 94 | }), |
| 95 | ); |
| 96 | |
| 97 | // Return success - applyToFile will handle the completion state |
| 98 | return { |
| 99 | respondImmediately: false, // Let apply state handle completion |
| 100 | output: undefined, |
| 101 | }; |
| 102 | } catch (error) { |
| 103 | throw new Error( |
| 104 | `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`, |
| 105 | ); |
| 106 | } |
| 107 | }; |