feat: multi edit and single search and replace tools
This commit is contained in:
parent
4b51607595
commit
d6ed405d0c
16 changed files with 1228 additions and 79 deletions
|
|
@ -62,7 +62,7 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { getToolsForIde } from "../tools";
|
||||
import { getBaseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
|
|
@ -526,7 +526,7 @@ async function intermediateToFinalConfig({
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
tools: await getToolsForIde(ide),
|
||||
tools: getBaseToolDefinitions(),
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: [],
|
||||
modelsByRole: {
|
||||
|
|
|
|||
|
|
@ -287,6 +287,8 @@ export default async function doLoadConfig(options: {
|
|||
enableExperimentalTools:
|
||||
newConfig.experimental?.enableExperimentalTools ?? false,
|
||||
isSignedIn,
|
||||
isRemote: await ide.isWorkspaceRemote(),
|
||||
modelName: newConfig.selectedModelByRole.chat?.model,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { getToolsForIde } from "../../tools";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
|
||||
|
|
@ -177,7 +177,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [],
|
||||
tools: await getToolsForIde(ide),
|
||||
tools: getBaseToolDefinitions(),
|
||||
mcpServerStatuses: [],
|
||||
contextProviders: [],
|
||||
modelsByRole: {
|
||||
|
|
|
|||
2
core/index.d.ts
vendored
2
core/index.d.ts
vendored
|
|
@ -1112,6 +1112,8 @@ export interface ConfigDependentToolParams {
|
|||
rules: RuleWithSource[];
|
||||
enableExperimentalTools: boolean;
|
||||
isSignedIn: boolean;
|
||||
isRemote: boolean;
|
||||
modelName: string | undefined;
|
||||
}
|
||||
|
||||
export type GetTool = (params: ConfigDependentToolParams) => Tool;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ export enum BuiltInToolNames {
|
|||
ReadFile = "read_file",
|
||||
EditExistingFile = "edit_existing_file",
|
||||
SearchAndReplaceInFile = "search_and_replace_in_file",
|
||||
SingleFindAndReplace = "single_find_and_replace",
|
||||
MultiEdit = "multi_edit",
|
||||
ReadCurrentlyOpenFile = "read_currently_open_file",
|
||||
CreateNewFile = "create_new_file",
|
||||
RunTerminalCommand = "run_terminal_command",
|
||||
|
|
@ -25,4 +27,6 @@ export const BUILT_IN_GROUP_NAME = "Built-In";
|
|||
export const CLIENT_TOOLS_IMPLS = [
|
||||
BuiltInToolNames.EditExistingFile,
|
||||
BuiltInToolNames.SearchAndReplaceInFile,
|
||||
BuiltInToolNames.SingleFindAndReplace,
|
||||
BuiltInToolNames.MultiEdit,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ export { fetchUrlContentTool } from "./fetchUrlContent";
|
|||
export { globSearchTool } from "./globSearch";
|
||||
export { grepSearchTool } from "./grepSearch";
|
||||
export { lsTool } from "./ls";
|
||||
export { multiEditTool } from "./multiEdit";
|
||||
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
|
||||
export { readFileTool } from "./readFile";
|
||||
export { requestRuleTool } from "./requestRule";
|
||||
export { runTerminalCommandTool } from "./runTerminalCommand";
|
||||
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
|
||||
export { searchWebTool } from "./searchWeb";
|
||||
export { singleFindAndReplaceTool } from "./singleFindAndReplace";
|
||||
export { viewDiffTool } from "./viewDiff";
|
||||
export { viewRepoMapTool } from "./viewRepoMap";
|
||||
export { viewSubdirectoryTool } from "./viewSubdirectory";
|
||||
|
|
|
|||
131
core/tools/definitions/multiEdit.ts
Normal file
131
core/tools/definitions/multiEdit.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditOperation {
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
export interface MultiEditArgs {
|
||||
filepath: string;
|
||||
edits: EditOperation[];
|
||||
}
|
||||
|
||||
export const multiEditTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Multi Edit",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.MultiEdit,
|
||||
description: `This is a tool for making multiple edits to a single file in one operation. It
|
||||
is built on top of the single find and replace tool and allows you to perform multiple
|
||||
find-and-replace operations efficiently. Prefer this tool over the single find and replace tool
|
||||
when you need to make multiple edits to the same file.
|
||||
|
||||
Before using this tool:
|
||||
|
||||
1. Use the read_file tool to understand the file's contents and context
|
||||
2. Verify the directory path is correct
|
||||
|
||||
To make multiple file edits, provide the following:
|
||||
|
||||
1. filepath: The path to the file to modify (relative to the root of the workspace)
|
||||
2. edits: An array of edit operations to perform, where each edit contains:
|
||||
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
|
||||
- new_string: The edited text to replace the old_string
|
||||
- replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
|
||||
|
||||
IMPORTANT:
|
||||
- All edits are applied in sequence, in the order they are provided
|
||||
- Each edit operates on the result of the previous edit
|
||||
- All edits must be valid for the operation to succeed - if any edit fails,
|
||||
none will be applied
|
||||
- This tool is ideal when you need to make several changes to different parts
|
||||
of the same file
|
||||
|
||||
CRITICAL REQUIREMENTS:
|
||||
|
||||
1. All edits follow the same requirements as the single find and replace tool
|
||||
2. The edits are atomic - either all succeed or none are applied
|
||||
3. Plan your edits carefully to avoid conflicts between sequential operations
|
||||
|
||||
WARNING:
|
||||
|
||||
- The tool will fail if edits.old_string doesn't match the file contents
|
||||
exactly (including whitespace)
|
||||
- The tool will fail if edits.old_string and edits.new_string are the same
|
||||
- Since edits are applied in sequence, ensure that earlier edits don't affect
|
||||
the text that later edits are trying to find
|
||||
|
||||
When making edits:
|
||||
|
||||
- Ensure all edits result in idiomatic, correct code
|
||||
- Do not leave the code in a broken state
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
|
||||
files unless asked.
|
||||
- Use replace_all for replacing and renaming strings across the file. This
|
||||
parameter is useful if you want to rename a variable for instance.
|
||||
|
||||
If you want to create a new file, use:
|
||||
- A new file path
|
||||
- First edit: empty old_string and the new file's contents as new_string
|
||||
- Subsequent edits: normal edit operations on the created content`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "edits"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path to the file to modify, relative to the root of the workspace",
|
||||
},
|
||||
edits: {
|
||||
type: "array",
|
||||
description:
|
||||
"Array of edit operations to perform sequentially on the file",
|
||||
items: {
|
||||
type: "object",
|
||||
required: ["old_string", "new_string"],
|
||||
properties: {
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description: "The text to replace it with",
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Replace all occurrences of old_string (default false)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To make multiple edits to a single file, use the ${BuiltInToolNames.MultiEdit} tool with a filepath (relative to the root of the workspace) and an array of edit operations.
|
||||
|
||||
For example, you could respond with:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/file.ts"],
|
||||
[
|
||||
"edits",
|
||||
`[
|
||||
{ "old_string": "const oldVar = 'value'", "new_string": "const newVar = 'updated'" },
|
||||
{ "old_string": "oldFunction()", "new_string": "newFunction()", "replace_all": true }
|
||||
]`,
|
||||
],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
};
|
||||
84
core/tools/definitions/singleFindAndReplace.ts
Normal file
84
core/tools/definitions/singleFindAndReplace.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface SingleFindAndReplaceArgs {
|
||||
filepath: string;
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
export const singleFindAndReplaceTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Find and Replace",
|
||||
wouldLikeTo: "find and replace in {{{ filepath }}}",
|
||||
isCurrently: "finding and replacing in {{{ filepath }}}",
|
||||
hasAlready: "found and replaced in {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SingleFindAndReplace,
|
||||
description: `Performs exact string replacements in files.
|
||||
|
||||
Usage:
|
||||
|
||||
- You must use your \`read_file\` tool at least once in the conversation before
|
||||
editing. This tool will error if you attempt an edit without reading the file.
|
||||
|
||||
- When editing text from read_file tool output, ensure you preserve the exact
|
||||
indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
|
||||
number prefix format is: spaces + line number + tab. Everything after that tab
|
||||
is the actual file content to match. Never include any part of the line number
|
||||
prefix in the old_string or new_string.
|
||||
|
||||
- ALWAYS prefer editing existing files in the codebase. NEVER write new files
|
||||
unless explicitly required.
|
||||
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
|
||||
files unless asked.
|
||||
|
||||
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
|
||||
a larger string with more surrounding context to make it unique or use
|
||||
\`replace_all\` to change every instance of \`old_string\`.
|
||||
|
||||
- Use \`replace_all\` for replacing and renaming strings across the file. This
|
||||
parameter is useful if you want to rename a variable for instance.`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "old_string", "new_string"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path to the file to modify, relative to the root of the workspace",
|
||||
},
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description:
|
||||
"The text to replace it with (must be different from old_string)",
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
description: "Replace all occurrences of old_string (default false)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To perform exact string replacements in files, use the ${BuiltInToolNames.SingleFindAndReplace} tool with a filepath (relative to the root of the workspace) and the strings to find and replace.
|
||||
|
||||
For example, you could respond with:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/file.ts"],
|
||||
["old_string", "const oldVariable = 'value'"],
|
||||
["new_string", "const newVariable = 'updated'"],
|
||||
["replace_all", "false"],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
};
|
||||
|
|
@ -1,12 +1,8 @@
|
|||
import { ConfigDependentToolParams, IDE, Tool } from "..";
|
||||
import { ConfigDependentToolParams, Tool } from "..";
|
||||
import * as toolDefinitions from "./definitions";
|
||||
|
||||
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
|
||||
|
||||
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
|
||||
const getLocalOnlyToolDefinitions = () => [toolDefinitions.grepSearchTool];
|
||||
|
||||
const getBaseToolDefinitions = () => [
|
||||
export const getBaseToolDefinitions = () => [
|
||||
toolDefinitions.readFileTool,
|
||||
toolDefinitions.createNewFileTool,
|
||||
toolDefinitions.runTerminalCommandTool,
|
||||
|
|
@ -20,24 +16,38 @@ const getBaseToolDefinitions = () => [
|
|||
|
||||
export const getConfigDependentToolDefinitions = (
|
||||
params: ConfigDependentToolParams,
|
||||
): Tool[] => [
|
||||
toolDefinitions.requestRuleTool(params),
|
||||
// Search and replace is now generally available
|
||||
toolDefinitions.searchAndReplaceInFileTool,
|
||||
// Keep edit file tool available for models that need it
|
||||
toolDefinitions.editFileTool,
|
||||
// Web search is only available for signed-in users
|
||||
...(params.isSignedIn ? [toolDefinitions.searchWebTool] : []),
|
||||
...(params.enableExperimentalTools
|
||||
? [
|
||||
toolDefinitions.viewRepoMapTool,
|
||||
toolDefinitions.viewSubdirectoryTool,
|
||||
toolDefinitions.codebaseTool,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
): Tool[] => {
|
||||
const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params;
|
||||
const tools: Tool[] = [];
|
||||
|
||||
export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>
|
||||
(await ide.isWorkspaceRemote())
|
||||
? getBaseToolDefinitions()
|
||||
: [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()];
|
||||
tools.push(toolDefinitions.requestRuleTool(params));
|
||||
|
||||
if (isSignedIn) {
|
||||
// Web search is only available for signed-in users
|
||||
tools.push(toolDefinitions.searchWebTool);
|
||||
}
|
||||
|
||||
if (enableExperimentalTools) {
|
||||
tools.push(
|
||||
toolDefinitions.viewRepoMapTool,
|
||||
toolDefinitions.viewSubdirectoryTool,
|
||||
toolDefinitions.codebaseTool,
|
||||
);
|
||||
}
|
||||
|
||||
// OLD SEARCH AND REPLACE IS CURRENTLY NOT USED
|
||||
// toolDefinitions.searchAndReplaceInFileTool
|
||||
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
|
||||
tools.push(toolDefinitions.multiEditTool);
|
||||
} else {
|
||||
tools.push(toolDefinitions.singleFindAndReplaceTool);
|
||||
tools.push(toolDefinitions.editFileTool);
|
||||
}
|
||||
|
||||
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
|
||||
if (!isRemote) {
|
||||
tools.push(toolDefinitions.grepSearchTool);
|
||||
}
|
||||
|
||||
return tools;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { test, expect } from "vitest";
|
||||
import { getConfigDependentToolDefinitions } from "./index";
|
||||
import { expect, test } from "vitest";
|
||||
import { BuiltInToolNames } from "./builtIn";
|
||||
import { getConfigDependentToolDefinitions } from "./index";
|
||||
|
||||
test("searchWeb tool is only available when user is signed in", () => {
|
||||
// Test with signed-in user
|
||||
|
|
@ -8,6 +8,8 @@ test("searchWeb tool is only available when user is signed in", () => {
|
|||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: true,
|
||||
isRemote: false,
|
||||
modelName: "",
|
||||
});
|
||||
|
||||
const searchWebToolSignedIn = signedInTools.find(
|
||||
|
|
@ -21,6 +23,8 @@ test("searchWeb tool is only available when user is signed in", () => {
|
|||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: false,
|
||||
isRemote: false,
|
||||
modelName: "",
|
||||
});
|
||||
|
||||
const searchWebToolNotSignedIn = notSignedInTools.find(
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { LLMFullCompletionOptions, ModelDescription, Tool } from "core";
|
||||
import { LLMFullCompletionOptions, Tool } from "core";
|
||||
import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
|
||||
import { ToCoreProtocol } from "core/protocol";
|
||||
import { BuiltInToolNames } from "core/tools/builtIn";
|
||||
import { selectActiveTools } from "../selectors/selectActiveTools";
|
||||
import { selectUseSystemMessageTools } from "../selectors/selectUseSystemMessageTools";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
|
|
@ -86,49 +85,6 @@ async function handleToolCallExecution(
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters tools based on the selected model's capabilities.
|
||||
* Returns either the edit file tool or search and replace tool, but not both.
|
||||
*/
|
||||
function filterToolsForModel(
|
||||
tools: Tool[],
|
||||
selectedModel: ModelDescription,
|
||||
): Tool[] {
|
||||
const editFileTool = tools.find(
|
||||
(tool) => tool.function.name === BuiltInToolNames.EditExistingFile,
|
||||
);
|
||||
const searchAndReplaceTool = tools.find(
|
||||
(tool) => tool.function.name === BuiltInToolNames.SearchAndReplaceInFile,
|
||||
);
|
||||
|
||||
// If we don't have both tools, return tools as-is
|
||||
if (!editFileTool || !searchAndReplaceTool) {
|
||||
return tools;
|
||||
}
|
||||
|
||||
// Determine which tool to use based on the model
|
||||
const shouldUseFindReplace = shouldUseFindReplaceEdits(selectedModel);
|
||||
|
||||
// Filter out the unwanted tool
|
||||
return tools.filter((tool) => {
|
||||
if (tool.function.name === BuiltInToolNames.EditExistingFile) {
|
||||
return !shouldUseFindReplace;
|
||||
}
|
||||
if (tool.function.name === BuiltInToolNames.SearchAndReplaceInFile) {
|
||||
return shouldUseFindReplace;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether to use search and replace tool instead of edit file
|
||||
* Right now we only know that this is reliable with Claude models
|
||||
*/
|
||||
function shouldUseFindReplaceEdits({ model }: ModelDescription): boolean {
|
||||
return model.includes("claude") || model.includes("gpt-5");
|
||||
}
|
||||
|
||||
export const streamNormalInput = createAsyncThunk<
|
||||
void,
|
||||
{
|
||||
|
|
@ -146,8 +102,8 @@ export const streamNormalInput = createAsyncThunk<
|
|||
}
|
||||
|
||||
// Get tools and filter them based on the selected model
|
||||
const allActiveTools = selectActiveTools(state);
|
||||
const activeTools = filterToolsForModel(allActiveTools, selectedChatModel);
|
||||
const activeTools = selectActiveTools(state);
|
||||
|
||||
const supportsNativeTools = modelSupportsNativeTools(selectedChatModel);
|
||||
|
||||
// Use the centralized selector to determine if system message tools should be used
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ import { BuiltInToolNames } from "core/tools/builtIn";
|
|||
import { IIdeMessenger } from "../../context/IdeMessenger";
|
||||
import { AppThunkDispatch, RootState } from "../../redux/store";
|
||||
import { editToolImpl } from "./editImpl";
|
||||
import { multiEditImpl } from "./multiEditImpl";
|
||||
import { searchReplaceToolImpl } from "./searchReplaceImpl";
|
||||
import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl";
|
||||
|
||||
export interface ClientToolExtras {
|
||||
getState: () => RootState;
|
||||
|
|
@ -40,6 +42,16 @@ export async function callClientTool(
|
|||
case BuiltInToolNames.SearchAndReplaceInFile:
|
||||
output = await searchReplaceToolImpl(parsedArgs, toolCall.id, extras);
|
||||
break;
|
||||
case BuiltInToolNames.SingleFindAndReplace:
|
||||
output = await singleFindAndReplaceImpl(
|
||||
parsedArgs,
|
||||
toolCall.id,
|
||||
extras,
|
||||
);
|
||||
break;
|
||||
case BuiltInToolNames.MultiEdit:
|
||||
output = await multiEditImpl(parsedArgs, toolCall.id, extras);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Invalid client tool name ${toolCall.function.name}`);
|
||||
}
|
||||
|
|
|
|||
390
gui/src/util/clientTools/multiEditImpl.test.ts
Normal file
390
gui/src/util/clientTools/multiEditImpl.test.ts
Normal file
|
|
@ -0,0 +1,390 @@
|
|||
import * as ideUtils from "core/util/ideUtils";
|
||||
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
|
||||
import { ClientToolExtras } from "./callClientTool";
|
||||
import { multiEditImpl } from "./multiEditImpl";
|
||||
|
||||
vi.mock("uuid", () => ({
|
||||
v4: vi.fn(() => "test-uuid"),
|
||||
}));
|
||||
|
||||
vi.mock("core/util/ideUtils", () => ({
|
||||
resolveRelativePathInDir: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("multiEditImpl", () => {
|
||||
let mockExtras: ClientToolExtras;
|
||||
let mockResolveRelativePathInDir: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir);
|
||||
|
||||
mockExtras = {
|
||||
getState: vi.fn(() => ({
|
||||
config: { config: { allowAnonymousTelemetry: false } },
|
||||
})) as any,
|
||||
dispatch: vi.fn() as any,
|
||||
ideMessenger: {
|
||||
ide: { readFile: vi.fn() },
|
||||
request: vi.fn(),
|
||||
} as any,
|
||||
};
|
||||
});
|
||||
|
||||
describe("argument validation", () => {
|
||||
it("should throw if filepath is missing", async () => {
|
||||
await expect(
|
||||
multiEditImpl({ edits: [] }, "id", mockExtras),
|
||||
).rejects.toThrow("filepath is required");
|
||||
});
|
||||
|
||||
it("should throw if edits array is empty", async () => {
|
||||
await expect(
|
||||
multiEditImpl({ filepath: "test.txt", edits: [] }, "id", mockExtras),
|
||||
).rejects.toThrow(
|
||||
"edits array is required and must contain at least one edit",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw if edit has invalid old_string", async () => {
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
edits: [{ old_string: null, new_string: "test" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Edit 1: old_string is required");
|
||||
});
|
||||
|
||||
it("should throw if edit has undefined new_string", async () => {
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
edits: [{ old_string: "test", new_string: undefined }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Edit 1: new_string is required");
|
||||
});
|
||||
|
||||
it("should throw if old_string equals new_string", async () => {
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
edits: [{ old_string: "same", new_string: "same" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Edit 1: old_string and new_string must be different");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sequential edits", () => {
|
||||
beforeEach(() => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
});
|
||||
|
||||
it("should apply single edit", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("Hello world");
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [{ old_string: "Hello", new_string: "Hi" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "Hi world",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should apply multiple edits sequentially", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("Hello world\nGoodbye world");
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [
|
||||
{ old_string: "Hello", new_string: "Hi" },
|
||||
{ old_string: "world", new_string: "universe", replace_all: true },
|
||||
],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "Hi universe\nGoodbye universe",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle edits that depend on previous edits", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("const x = 1;");
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [
|
||||
{ old_string: "const x", new_string: "let x" },
|
||||
{ old_string: "let x = 1;", new_string: "let x = 2;" },
|
||||
],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "let x = 2;",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw if string not found in edit sequence", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("Hello world");
|
||||
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [
|
||||
{ old_string: "Hello", new_string: "Hi" },
|
||||
{ old_string: "not found", new_string: "test" },
|
||||
],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow('Edit 2: String not found in file: "not found"');
|
||||
});
|
||||
|
||||
it("should throw if multiple occurrences without replace_all", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("test test test");
|
||||
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [{ old_string: "test", new_string: "replaced" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow('Edit 1: String "test" appears 3 times');
|
||||
});
|
||||
});
|
||||
|
||||
describe("file creation", () => {
|
||||
it("should create new file with empty old_string", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue(null);
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "new.txt",
|
||||
edits: [{ old_string: "", new_string: "New content\nLine 2" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "New content\nLine 2",
|
||||
filepath: "new.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should create and edit new file", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue(null);
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "new.txt",
|
||||
edits: [
|
||||
{ old_string: "", new_string: "Hello world" },
|
||||
{ old_string: "world", new_string: "universe" },
|
||||
],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "Hello universe",
|
||||
filepath: "new.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("replace_all functionality", () => {
|
||||
beforeEach(() => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
});
|
||||
|
||||
it("should replace all occurrences when specified", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("foo bar foo baz foo");
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [{ old_string: "foo", new_string: "qux", replace_all: true }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "qux bar qux baz qux",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle mixed replace_all settings", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockResolvedValue("x y x z x");
|
||||
|
||||
await multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [
|
||||
{ old_string: "x", new_string: "a", replace_all: true },
|
||||
{ old_string: "y", new_string: "b" },
|
||||
],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
|
||||
"applyToFile",
|
||||
{
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "id",
|
||||
text: "a b a z a",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should wrap readFile errors", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi
|
||||
.fn()
|
||||
.mockRejectedValue(new Error("Read failed"));
|
||||
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [{ old_string: "test", new_string: "new" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Failed to apply multi edit: Read failed");
|
||||
});
|
||||
|
||||
it("should wrap applyToFile errors", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test");
|
||||
mockExtras.ideMessenger.request = vi
|
||||
.fn()
|
||||
.mockRejectedValue(new Error("Write failed"));
|
||||
|
||||
await expect(
|
||||
multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [{ old_string: "test", new_string: "new" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Failed to apply multi edit: Write failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("return value", () => {
|
||||
it("should return correct structure", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test");
|
||||
|
||||
const result = await multiEditImpl(
|
||||
{
|
||||
filepath: "file.txt",
|
||||
edits: [{ old_string: "test", new_string: "new" }],
|
||||
},
|
||||
"id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
respondImmediately: false,
|
||||
output: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
138
gui/src/util/clientTools/multiEditImpl.ts
Normal file
138
gui/src/util/clientTools/multiEditImpl.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { resolveRelativePathInDir } from "core/util/ideUtils";
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { ClientToolImpl } from "./callClientTool";
|
||||
|
||||
interface EditOperation {
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
function validateEdits(edits: EditOperation[]): void {
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
const edit = edits[i];
|
||||
if (!edit.old_string && edit.old_string !== "") {
|
||||
throw new Error(`Edit ${i + 1}: old_string is required`);
|
||||
}
|
||||
if (edit.new_string === undefined) {
|
||||
throw new Error(`Edit ${i + 1}: new_string is required`);
|
||||
}
|
||||
if (edit.old_string === edit.new_string) {
|
||||
throw new Error(
|
||||
`Edit ${i + 1}: old_string and new_string must be different`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function applyEdit(
|
||||
content: string,
|
||||
edit: EditOperation,
|
||||
editIndex: number,
|
||||
isFirstEditOfNewFile: boolean,
|
||||
): string {
|
||||
const { old_string, new_string, replace_all = false } = edit;
|
||||
|
||||
// For new file creation, the first edit can have empty old_string
|
||||
if (isFirstEditOfNewFile && old_string === "") {
|
||||
return new_string;
|
||||
}
|
||||
|
||||
// Check if old_string exists in current content
|
||||
if (!content.includes(old_string)) {
|
||||
throw new Error(
|
||||
`Edit ${editIndex + 1}: String not found in file: "${old_string}"`,
|
||||
);
|
||||
}
|
||||
|
||||
if (replace_all) {
|
||||
// Replace all occurrences
|
||||
return content.split(old_string).join(new_string);
|
||||
} else {
|
||||
// Replace only the first occurrence, but check for uniqueness
|
||||
const occurrences = content.split(old_string).length - 1;
|
||||
if (occurrences > 1) {
|
||||
throw new Error(
|
||||
`Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} 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.`,
|
||||
);
|
||||
}
|
||||
return content.replace(old_string, new_string);
|
||||
}
|
||||
}
|
||||
|
||||
export const multiEditImpl: ClientToolImpl = async (
|
||||
args,
|
||||
toolCallId,
|
||||
extras,
|
||||
) => {
|
||||
const { filepath, edits } = args;
|
||||
|
||||
const streamId = uuid();
|
||||
|
||||
// Validate arguments
|
||||
if (!filepath) {
|
||||
throw new Error("filepath is required");
|
||||
}
|
||||
if (!edits || !Array.isArray(edits) || edits.length === 0) {
|
||||
throw new Error(
|
||||
"edits array is required and must contain at least one edit",
|
||||
);
|
||||
}
|
||||
|
||||
// Validate each edit operation
|
||||
validateEdits(edits);
|
||||
|
||||
// Check if this is creating a new file (first edit has empty old_string)
|
||||
const isCreatingNewFile = edits[0].old_string === "";
|
||||
|
||||
// Resolve the file path
|
||||
const resolvedFilepath = await resolveRelativePathInDir(
|
||||
filepath,
|
||||
extras.ideMessenger.ide,
|
||||
);
|
||||
|
||||
// For new files, resolvedFilepath might be null, so we construct the path
|
||||
const targetFilepath = resolvedFilepath || filepath;
|
||||
|
||||
if (!isCreatingNewFile) {
|
||||
// For existing files, check if file exists
|
||||
if (!resolvedFilepath) {
|
||||
throw new Error(`File ${filepath} does not exist`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Read current file content (or start with empty for new files)
|
||||
let currentContent = "";
|
||||
if (!isCreatingNewFile) {
|
||||
currentContent = await extras.ideMessenger.ide.readFile(targetFilepath);
|
||||
}
|
||||
|
||||
let newContent = currentContent;
|
||||
|
||||
// Apply all edits sequentially
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
const isFirstEditOfNewFile = i === 0 && isCreatingNewFile;
|
||||
newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile);
|
||||
}
|
||||
|
||||
// Apply the changes to the file
|
||||
await extras.ideMessenger.request("applyToFile", {
|
||||
streamId,
|
||||
toolCallId,
|
||||
text: newContent,
|
||||
filepath: targetFilepath,
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
|
||||
// Return success - applyToFile will handle the completion state
|
||||
return {
|
||||
respondImmediately: false, // Let apply state handle completion
|
||||
output: undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to apply multi edit: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
332
gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts
Normal file
332
gui/src/util/clientTools/singleFindAndReplaceImpl.test.ts
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
import { describe, it, expect, beforeEach, vi, Mock } from "vitest";
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl";
|
||||
import { ClientToolExtras } from "./callClientTool";
|
||||
import * as ideUtils from "core/util/ideUtils";
|
||||
|
||||
vi.mock("uuid", () => ({
|
||||
v4: vi.fn(() => "test-uuid"),
|
||||
}));
|
||||
|
||||
vi.mock("core/util/ideUtils", () => ({
|
||||
resolveRelativePathInDir: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("singleFindAndReplaceImpl", () => {
|
||||
let mockExtras: ClientToolExtras;
|
||||
let mockResolveRelativePathInDir: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir);
|
||||
|
||||
mockExtras = {
|
||||
getState: vi.fn(() => ({
|
||||
config: {
|
||||
config: {
|
||||
allowAnonymousTelemetry: false,
|
||||
},
|
||||
},
|
||||
})) as any,
|
||||
dispatch: vi.fn() as any,
|
||||
ideMessenger: {
|
||||
ide: {
|
||||
readFile: vi.fn(),
|
||||
},
|
||||
request: vi.fn(),
|
||||
} as any,
|
||||
};
|
||||
});
|
||||
|
||||
describe("argument validation", () => {
|
||||
it("should throw error if filepath is missing", async () => {
|
||||
const args = {
|
||||
old_string: "test",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("filepath is required");
|
||||
});
|
||||
|
||||
it("should throw error if old_string is missing", async () => {
|
||||
const args = {
|
||||
filepath: "test.txt",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("old_string is required");
|
||||
});
|
||||
|
||||
it("should throw error if new_string is missing", async () => {
|
||||
const args = {
|
||||
filepath: "test.txt",
|
||||
old_string: "test",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("new_string is required");
|
||||
});
|
||||
|
||||
it("should throw error if old_string and new_string are the same", async () => {
|
||||
const args = {
|
||||
filepath: "test.txt",
|
||||
old_string: "same",
|
||||
new_string: "same",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("old_string and new_string must be different");
|
||||
});
|
||||
});
|
||||
|
||||
describe("file resolution", () => {
|
||||
it("should throw error if file does not exist", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue(null);
|
||||
|
||||
const args = {
|
||||
filepath: "nonexistent.txt",
|
||||
old_string: "test",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("File nonexistent.txt does not exist");
|
||||
});
|
||||
|
||||
it("should resolve relative file paths", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/absolute/path/test.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test content");
|
||||
|
||||
const args = {
|
||||
filepath: "test.txt",
|
||||
old_string: "test",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(mockResolveRelativePathInDir).toHaveBeenCalledWith(
|
||||
"test.txt",
|
||||
mockExtras.ideMessenger.ide
|
||||
);
|
||||
expect(mockExtras.ideMessenger.ide.readFile).toHaveBeenCalledWith(
|
||||
"/absolute/path/test.txt"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("string replacement", () => {
|
||||
beforeEach(() => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
});
|
||||
|
||||
it("should throw error if old_string is not found in file", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("different content");
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "not found",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("String not found in file: not found");
|
||||
});
|
||||
|
||||
it("should replace single occurrence", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue(
|
||||
"Hello world\nThis is a test file\nGoodbye world"
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
};
|
||||
|
||||
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "tool-call-id",
|
||||
text: "Hi there\nThis is a test file\nGoodbye world",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error if old_string appears multiple times and replace_all is false", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue(
|
||||
"Hello world\nThis is a test file\nGoodbye world"
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "world",
|
||||
new_string: "universe",
|
||||
replace_all: false,
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow(
|
||||
'String "world" appears 2 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.'
|
||||
);
|
||||
});
|
||||
|
||||
it("should replace all occurrences when replace_all is true", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue(
|
||||
"Hello world\nThis is a test file\nGoodbye world"
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "world",
|
||||
new_string: "universe",
|
||||
replace_all: true,
|
||||
};
|
||||
|
||||
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "tool-call-id",
|
||||
text: "Hello universe\nThis is a test file\nGoodbye universe",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle empty new_string (deletion)", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue(
|
||||
"Hello world\nThis is a test file"
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "Hello ",
|
||||
new_string: "",
|
||||
};
|
||||
|
||||
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "tool-call-id",
|
||||
text: "world\nThis is a test file",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle special characters in strings", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue(
|
||||
'const regex = /[a-z]+/g;\nconst text = "Hello $world"'
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: '"Hello $world"',
|
||||
new_string: '"Hi $universe"',
|
||||
};
|
||||
|
||||
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "tool-call-id",
|
||||
text: 'const regex = /[a-z]+/g;\nconst text = "Hi $universe"',
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should preserve whitespace and indentation", async () => {
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue(
|
||||
"function test() {\n const value = 'old';\n return value;\n}"
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: " const value = 'old';",
|
||||
new_string: " const value = 'new';",
|
||||
};
|
||||
|
||||
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
streamId: "test-uuid",
|
||||
toolCallId: "tool-call-id",
|
||||
text: "function test() {\n const value = 'new';\n return value;\n}",
|
||||
filepath: "/test/file.txt",
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("return value", () => {
|
||||
it("should return correct response structure", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test content");
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "test",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
const result = await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
|
||||
|
||||
expect(result).toEqual({
|
||||
respondImmediately: false,
|
||||
output: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should wrap and rethrow errors from readFile", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockRejectedValue(
|
||||
new Error("Permission denied")
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "test",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("Failed to apply find and replace: Permission denied");
|
||||
});
|
||||
|
||||
it("should wrap and rethrow errors from applyToFile", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
|
||||
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test content");
|
||||
mockExtras.ideMessenger.request = vi.fn().mockRejectedValue(
|
||||
new Error("Write failed")
|
||||
);
|
||||
|
||||
const args = {
|
||||
filepath: "file.txt",
|
||||
old_string: "test",
|
||||
new_string: "replacement",
|
||||
};
|
||||
|
||||
await expect(
|
||||
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras)
|
||||
).rejects.toThrow("Failed to apply find and replace: Write failed");
|
||||
});
|
||||
});
|
||||
});
|
||||
82
gui/src/util/clientTools/singleFindAndReplaceImpl.ts
Normal file
82
gui/src/util/clientTools/singleFindAndReplaceImpl.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { resolveRelativePathInDir } from "core/util/ideUtils";
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { ClientToolImpl } from "./callClientTool";
|
||||
|
||||
export const singleFindAndReplaceImpl: ClientToolImpl = async (
|
||||
args,
|
||||
toolCallId,
|
||||
extras,
|
||||
) => {
|
||||
const { filepath, old_string, new_string, replace_all = false } = args;
|
||||
|
||||
const streamId = uuid();
|
||||
|
||||
// Validate arguments
|
||||
if (!filepath) {
|
||||
throw new Error("filepath is required");
|
||||
}
|
||||
if (!old_string) {
|
||||
throw new Error("old_string is required");
|
||||
}
|
||||
if (new_string === undefined) {
|
||||
throw new Error("new_string is required");
|
||||
}
|
||||
if (old_string === new_string) {
|
||||
throw new Error("old_string and new_string must be different");
|
||||
}
|
||||
|
||||
// Resolve the file path
|
||||
const resolvedFilepath = await resolveRelativePathInDir(
|
||||
filepath,
|
||||
extras.ideMessenger.ide,
|
||||
);
|
||||
if (!resolvedFilepath) {
|
||||
throw new Error(`File ${filepath} does not exist`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Read the current file content
|
||||
const originalContent =
|
||||
await extras.ideMessenger.ide.readFile(resolvedFilepath);
|
||||
|
||||
// Check if old_string exists in the file
|
||||
if (!originalContent.includes(old_string)) {
|
||||
throw new Error(`String not found in file: ${old_string}`);
|
||||
}
|
||||
|
||||
let newContent: string;
|
||||
|
||||
if (replace_all) {
|
||||
// Replace all occurrences
|
||||
newContent = originalContent.split(old_string).join(new_string);
|
||||
} else {
|
||||
// Replace only the first occurrence
|
||||
const occurrences = originalContent.split(old_string).length - 1;
|
||||
if (occurrences > 1) {
|
||||
throw new Error(
|
||||
`String "${old_string}" appears ${occurrences} 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.`,
|
||||
);
|
||||
}
|
||||
newContent = originalContent.replace(old_string, new_string);
|
||||
}
|
||||
|
||||
// Apply the changes to the file
|
||||
await extras.ideMessenger.request("applyToFile", {
|
||||
streamId,
|
||||
toolCallId,
|
||||
text: newContent,
|
||||
filepath: resolvedFilepath,
|
||||
isSearchAndReplace: true,
|
||||
});
|
||||
|
||||
// Return success - applyToFile will handle the completion state
|
||||
return {
|
||||
respondImmediately: false, // Let apply state handle completion
|
||||
output: undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to apply find and replace: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Reference in a new issue