feat: apply logic
This commit is contained in:
parent
525e5d448b
commit
bf7b62890e
11 changed files with 1095 additions and 88 deletions
|
|
@ -0,0 +1,143 @@
|
|||
import { SearchMatchResult } from "./findSearchMatch";
|
||||
import { generateSearchReplaceDiffLines } from "./generateSearchReplaceDiffLines";
|
||||
|
||||
describe("generateSearchReplaceDiffLines", () => {
|
||||
async function collectDiffLines(generator: AsyncGenerator<any>) {
|
||||
const lines = [];
|
||||
for await (const line of generator) {
|
||||
lines.push(line);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
it("should generate valid diff lines", async () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
|
||||
const searchMatch: SearchMatchResult = {
|
||||
startIndex: 13, // Start of "const b = 2;"
|
||||
endIndex: 25, // End of "const b = 2;"
|
||||
};
|
||||
|
||||
const replaceContent = "const b = 42;";
|
||||
|
||||
const diffLines = await collectDiffLines(
|
||||
generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent),
|
||||
);
|
||||
|
||||
// Verify we get valid diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify all lines have valid types
|
||||
diffLines.forEach((line) => {
|
||||
expect(["old", "new", "same"]).toContain(line.type);
|
||||
expect(typeof line.line).toBe("string");
|
||||
});
|
||||
|
||||
// Verify we have both old and new lines (indicating a change)
|
||||
const hasOldLines = diffLines.some((line) => line.type === "old");
|
||||
const hasNewLines = diffLines.some((line) => line.type === "new");
|
||||
expect(hasOldLines).toBe(true);
|
||||
expect(hasNewLines).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle empty replacement (deletion)", async () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
|
||||
const searchMatch: SearchMatchResult = {
|
||||
startIndex: 12, // Start of "\nconst b = 2;"
|
||||
endIndex: 25, // End of "const b = 2;"
|
||||
};
|
||||
|
||||
const replaceContent = "";
|
||||
|
||||
const diffLines = await collectDiffLines(
|
||||
generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent),
|
||||
);
|
||||
|
||||
// Should have old lines for the deleted content
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
const hasOldLines = diffLines.some((line) => line.type === "old");
|
||||
expect(hasOldLines).toBe(true);
|
||||
});
|
||||
it("should handle whole file replacement", async () => {
|
||||
const fileContent = `old content`;
|
||||
const searchMatch: SearchMatchResult = {
|
||||
startIndex: 0,
|
||||
endIndex: fileContent.length,
|
||||
};
|
||||
|
||||
const replaceContent = `completely new content`;
|
||||
const diffLines = await collectDiffLines(
|
||||
generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent),
|
||||
);
|
||||
|
||||
// Should have both old and new lines
|
||||
const hasOldLines = diffLines.some((line) => line.type === "old");
|
||||
const hasNewLines = diffLines.some((line) => line.type === "new");
|
||||
expect(hasOldLines).toBe(true);
|
||||
expect(hasNewLines).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle empty file with insertion", async () => {
|
||||
const fileContent = "";
|
||||
const searchMatch: SearchMatchResult = {
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
};
|
||||
|
||||
const replaceContent = `new content
|
||||
second line`;
|
||||
|
||||
const diffLines = await collectDiffLines(
|
||||
generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent),
|
||||
);
|
||||
|
||||
// Should have new lines for the inserted content
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
const hasNewLines = diffLines.some((line) => line.type === "new");
|
||||
expect(hasNewLines).toBe(true);
|
||||
|
||||
// Note: Empty file split by newlines gives [''] so there will be one "old" empty line
|
||||
// This is correct behavior from the diff algorithm's perspective
|
||||
});
|
||||
|
||||
it("should produce correct final content when applied", async () => {
|
||||
const fileContent = `line1
|
||||
line2
|
||||
line3`;
|
||||
|
||||
const searchMatch: SearchMatchResult = {
|
||||
startIndex: 6, // Start of "line2"
|
||||
endIndex: 11, // End of "line2"
|
||||
};
|
||||
|
||||
const replaceContent = "replaced";
|
||||
|
||||
// The expected final content
|
||||
const expectedContent =
|
||||
fileContent.substring(0, searchMatch.startIndex) +
|
||||
replaceContent +
|
||||
fileContent.substring(searchMatch.endIndex);
|
||||
|
||||
const diffLines = await collectDiffLines(
|
||||
generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent),
|
||||
);
|
||||
|
||||
// Reconstruct content from diff lines
|
||||
const newLines = diffLines
|
||||
.filter((line) => line.type === "new" || line.type === "same")
|
||||
.map((line) => line.line);
|
||||
|
||||
const reconstructedContent = newLines.join("\n");
|
||||
|
||||
// Should exactly match expected content, including line structure
|
||||
expect(reconstructedContent).toBe(expectedContent);
|
||||
|
||||
// Also verify we have the correct number of lines
|
||||
expect(newLines).toEqual(["line1", "replaced", "line3"]);
|
||||
});
|
||||
});
|
||||
39
core/edit/searchAndReplace/generateSearchReplaceDiffLines.ts
Normal file
39
core/edit/searchAndReplace/generateSearchReplaceDiffLines.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { DiffLine } from "../..";
|
||||
import { streamDiff } from "../../diff/streamDiff";
|
||||
import { SearchMatchResult } from "./findSearchMatch";
|
||||
|
||||
/**
|
||||
* Generates a stream of DiffLine objects for a search and replace operation.
|
||||
* Uses the existing streamDiff algorithm to calculate the actual differences.
|
||||
*
|
||||
* @param fileContent - The complete content of the file
|
||||
* @param searchMatch - The match result with start/end character positions
|
||||
* @param replaceContent - The content to replace the matched section with
|
||||
* @returns AsyncGenerator of DiffLine objects for streaming to VerticalDiffManager
|
||||
*/
|
||||
export async function* generateSearchReplaceDiffLines(
|
||||
fileContent: string,
|
||||
searchMatch: SearchMatchResult,
|
||||
replaceContent: string,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
// Apply the replacement to get the new file content
|
||||
const newFileContent =
|
||||
fileContent.substring(0, searchMatch.startIndex) +
|
||||
replaceContent +
|
||||
fileContent.substring(searchMatch.endIndex);
|
||||
|
||||
// Split into lines for the diff algorithm
|
||||
const oldLines = fileContent.split("\n");
|
||||
const newLines = newFileContent.split("\n");
|
||||
|
||||
// Create a simple async generator for the new lines
|
||||
// Don't use streamLines since we already have complete lines
|
||||
async function* newLinesGenerator() {
|
||||
for (const line of newLines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
// Stream the diff using existing infrastructure
|
||||
yield* streamDiff(oldLines, newLinesGenerator());
|
||||
}
|
||||
|
|
@ -1,4 +1,8 @@
|
|||
import { parseSearchReplaceBlock } from "./parseSearchReplaceBlock";
|
||||
import {
|
||||
parseAllSearchReplaceBlocks,
|
||||
parseSearchReplaceBlock,
|
||||
} from "./parseSearchReplaceBlock";
|
||||
|
||||
describe("parseSearchReplaceBlock", () => {
|
||||
describe("Complete blocks", () => {
|
||||
it("should parse a complete basic search/replace block", () => {
|
||||
|
|
@ -58,16 +62,28 @@ new content
|
|||
expect(result.replaceContent).toBe("new content");
|
||||
});
|
||||
|
||||
it("should handle empty replace content", () => {
|
||||
it("should handle empty replace content (deletion)", () => {
|
||||
const content = `------- SEARCH
|
||||
old content
|
||||
old content to delete
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("old content");
|
||||
expect(result.searchContent).toBe("old content to delete");
|
||||
expect(result.replaceContent).toBe("");
|
||||
});
|
||||
|
||||
it("should handle both empty search and replace content", () => {
|
||||
const content = `------- SEARCH
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("");
|
||||
expect(result.replaceContent).toBe("");
|
||||
});
|
||||
});
|
||||
|
|
@ -136,6 +152,7 @@ content
|
|||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
|
|
@ -195,3 +212,179 @@ content`;
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAllSearchReplaceBlocks", () => {
|
||||
it("should parse multiple complete blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
old code 1
|
||||
=======
|
||||
new code 1
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
old code 2
|
||||
=======
|
||||
new code 2
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("old code 1");
|
||||
expect(blocks[0].replaceContent).toBe("new code 1");
|
||||
expect(blocks[1].searchContent).toBe("old code 2");
|
||||
expect(blocks[1].replaceContent).toBe("new code 2");
|
||||
});
|
||||
|
||||
it("should handle blocks with different content", () => {
|
||||
const content = `------- SEARCH
|
||||
function old() {
|
||||
return 1;
|
||||
}
|
||||
=======
|
||||
function new() {
|
||||
return 2;
|
||||
}
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
const x = 'old';
|
||||
=======
|
||||
const x = 'new';
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe(`function old() {
|
||||
return 1;
|
||||
}`);
|
||||
expect(blocks[0].replaceContent).toBe(`function new() {
|
||||
return 2;
|
||||
}`);
|
||||
expect(blocks[1].searchContent).toBe(`const x = 'old';`);
|
||||
expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
|
||||
});
|
||||
|
||||
it("should handle deletion blocks (empty replace content)", () => {
|
||||
const content = `------- SEARCH
|
||||
code to keep
|
||||
=======
|
||||
modified code
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
code to delete
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("code to keep");
|
||||
expect(blocks[0].replaceContent).toBe("modified code");
|
||||
expect(blocks[1].searchContent).toBe("code to delete");
|
||||
expect(blocks[1].replaceContent).toBe(""); // Deletion
|
||||
});
|
||||
|
||||
it("should handle insertion blocks (empty search content)", () => {
|
||||
const content = `------- SEARCH
|
||||
existing code
|
||||
=======
|
||||
modified existing code
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
=======
|
||||
new code to insert
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("existing code");
|
||||
expect(blocks[0].replaceContent).toBe("modified existing code");
|
||||
expect(blocks[1].searchContent).toBe(""); // Insertion
|
||||
expect(blocks[1].replaceContent).toBe("new code to insert");
|
||||
});
|
||||
|
||||
it("should skip incomplete blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
incomplete block
|
||||
|
||||
------- SEARCH
|
||||
complete block
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(1);
|
||||
expect(blocks[0].searchContent).toBe("complete block");
|
||||
expect(blocks[0].replaceContent).toBe("replacement");
|
||||
});
|
||||
|
||||
it("should handle single block", () => {
|
||||
const content = `------- SEARCH
|
||||
single block
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(1);
|
||||
expect(blocks[0].searchContent).toBe("single block");
|
||||
expect(blocks[0].replaceContent).toBe("replacement");
|
||||
});
|
||||
|
||||
it("should return empty array when no complete blocks found", () => {
|
||||
const content = `------- SEARCH
|
||||
incomplete
|
||||
=======
|
||||
missing replace marker`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle blocks with extra content between them", () => {
|
||||
const content = `Some other content here
|
||||
|
||||
------- SEARCH
|
||||
block 1
|
||||
=======
|
||||
replacement 1
|
||||
+++++++ REPLACE
|
||||
|
||||
More content in between
|
||||
|
||||
------- SEARCH
|
||||
block 2
|
||||
=======
|
||||
replacement 2
|
||||
+++++++ REPLACE
|
||||
|
||||
Trailing content`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("block 1");
|
||||
expect(blocks[0].replaceContent).toBe("replacement 1");
|
||||
expect(blocks[1].searchContent).toBe("block 2");
|
||||
expect(blocks[1].replaceContent).toBe("replacement 2");
|
||||
});
|
||||
|
||||
it("should throw error for malformed blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
+++++++ REPLACE`; // Missing =======
|
||||
|
||||
expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// Search and replace block markers using flexible regex patterns
|
||||
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
|
||||
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
|
||||
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
|
||||
|
|
@ -30,6 +31,7 @@ export function parseSearchReplaceBlock(
|
|||
content: string,
|
||||
): SearchReplaceBlockResult {
|
||||
const lines = content.split("\n");
|
||||
|
||||
let currentSearchContent = "";
|
||||
let currentReplaceContent = "";
|
||||
let inSearch = false;
|
||||
|
|
@ -88,3 +90,53 @@ export function parseSearchReplaceBlock(
|
|||
replaceContent: currentReplaceContent.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses all complete search and replace blocks from content.
|
||||
*
|
||||
* @param content - The content containing multiple search/replace blocks
|
||||
* @returns Array of complete search/replace blocks found
|
||||
*/
|
||||
export function parseAllSearchReplaceBlocks(
|
||||
content: string,
|
||||
): SearchReplaceBlockResult[] {
|
||||
const blocks: SearchReplaceBlockResult[] = [];
|
||||
const lines = content.split("\n");
|
||||
|
||||
let currentBlockLines: string[] = [];
|
||||
let inBlock = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (SEARCH_BLOCK_START_REGEX.test(line)) {
|
||||
// Start of new block
|
||||
if (inBlock && currentBlockLines.length > 0) {
|
||||
// Process previous incomplete block if any
|
||||
const blockContent = currentBlockLines.join("\n");
|
||||
const result = parseSearchReplaceBlock(blockContent);
|
||||
if (result.isComplete) {
|
||||
blocks.push(result);
|
||||
}
|
||||
}
|
||||
currentBlockLines = [line];
|
||||
inBlock = true;
|
||||
} else if (inBlock) {
|
||||
currentBlockLines.push(line);
|
||||
|
||||
// Check if this line completes the current block
|
||||
if (REPLACE_BLOCK_END_REGEX.test(line)) {
|
||||
const blockContent = currentBlockLines.join("\n");
|
||||
const result = parseSearchReplaceBlock(blockContent);
|
||||
if (result.isComplete) {
|
||||
blocks.push(result);
|
||||
} else if (result.error) {
|
||||
// If there's an error, throw it immediately
|
||||
throw new Error(result.error);
|
||||
}
|
||||
currentBlockLines = [];
|
||||
inBlock = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import type {
|
||||
ContinueRcJson,
|
||||
DiffLine,
|
||||
FileStatsMap,
|
||||
FileType,
|
||||
IDE,
|
||||
|
|
@ -35,15 +34,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
saveFile: [{ filepath: string }, void];
|
||||
fileExists: [{ filepath: string }, boolean];
|
||||
readFile: [{ filepath: string }, string];
|
||||
diffLine: [
|
||||
{
|
||||
diffLine: DiffLine;
|
||||
filepath: string;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
},
|
||||
void,
|
||||
];
|
||||
getProblems: [{ filepath: string }, Problem[]];
|
||||
getOpenFiles: [undefined, string[]];
|
||||
getCurrentFile: [
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
streamId: string;
|
||||
filepath?: string;
|
||||
toolCallId?: string;
|
||||
searchContent?: string;
|
||||
isSearchReplace?: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,15 +7,9 @@ export interface SearchAndReplaceInFileArgs {
|
|||
}
|
||||
|
||||
/**
|
||||
* Critical requirements:
|
||||
1. SEARCH content must match the file section EXACTLY (character-for-character, including whitespace and indentation)
|
||||
2. Each SEARCH/REPLACE block replaces only the first matching occurrence
|
||||
3. For multiple changes, use multiple SEARCH/REPLACE blocks in file order
|
||||
4. Keep blocks concise - include only the lines that need to change plus minimal context for uniqueness
|
||||
5. To delete code, use an empty REPLACE section
|
||||
6. To move code, use two blocks (one to delete, one to insert at new location)
|
||||
* This tool is in an experimental state.
|
||||
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
|
||||
*/
|
||||
|
||||
export const searchAndReplaceInFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
|
|
@ -28,7 +22,7 @@ export const searchAndReplaceInFileTool: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.SearchAndReplaceInFile,
|
||||
description:
|
||||
"Use this tool to make precise modifications to existing files using SEARCH/REPLACE blocks. This tool is ideal for targeted changes to specific sections of a file.",
|
||||
"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.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "diff"],
|
||||
|
|
@ -47,7 +41,40 @@ export const searchAndReplaceInFileTool: Tool = {
|
|||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
\`\`\``,
|
||||
\`\`\`
|
||||
|
||||
Critical rules:
|
||||
1. SEARCH content must match the associated file section to find EXACTLY:
|
||||
* Match character-for-character including whitespace, indentation, line endings
|
||||
* Include all comments, docstrings, etc.
|
||||
2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
|
||||
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
|
||||
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
|
||||
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
|
||||
3. Keep SEARCH/REPLACE blocks concise:
|
||||
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
|
||||
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
|
||||
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
|
||||
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
|
||||
4. Special operations:
|
||||
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
|
||||
* To delete code: Use empty REPLACE section
|
||||
|
||||
Usage:
|
||||
\`\`\`
|
||||
------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
\`\`\`
|
||||
`,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { getUriPathBasename } from "core/util/uri";
|
|||
import * as vscode from "vscode";
|
||||
|
||||
import { ApplyAbortManager } from "core/edit/applyAbortManager";
|
||||
import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
|
||||
import { generateSearchReplaceDiffLines } from "core/edit/searchAndReplace/generateSearchReplaceDiffLines";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
|
@ -13,6 +15,9 @@ export interface ApplyToFileOptions {
|
|||
filepath?: string;
|
||||
text: string;
|
||||
toolCallId?: string;
|
||||
// NEW: Search/replace specific fields
|
||||
searchContent?: string;
|
||||
isSearchReplace?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -31,6 +36,8 @@ export class ApplyManager {
|
|||
filepath,
|
||||
text,
|
||||
toolCallId,
|
||||
searchContent,
|
||||
isSearchReplace,
|
||||
}: ApplyToFileOptions) {
|
||||
await this.webviewProtocol.request("updateApplyState", {
|
||||
streamId,
|
||||
|
|
@ -49,6 +56,19 @@ export class ApplyManager {
|
|||
return;
|
||||
}
|
||||
|
||||
// NEW: Handle search/replace mode
|
||||
if (isSearchReplace && searchContent !== undefined) {
|
||||
await this.handleSearchReplace(
|
||||
activeTextEditor,
|
||||
searchContent,
|
||||
text, // This is the replace content
|
||||
streamId,
|
||||
toolCallId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Existing logic for regular apply
|
||||
const hasExistingDocument = !!activeTextEditor.document.getText().trim();
|
||||
|
||||
if (hasExistingDocument) {
|
||||
|
|
@ -148,6 +168,40 @@ export class ApplyManager {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* NEW: Handle search and replace operations
|
||||
*/
|
||||
private async handleSearchReplace(
|
||||
editor: vscode.TextEditor,
|
||||
searchContent: string,
|
||||
replaceContent: string,
|
||||
streamId: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
const fileContent = editor.document.getText();
|
||||
|
||||
// Find the search content in the file
|
||||
const match = findSearchMatch(fileContent, searchContent);
|
||||
if (!match) {
|
||||
throw new Error(`Search content not found in file:\n${searchContent}`);
|
||||
}
|
||||
|
||||
// Generate diff lines using our search/replace diff generator
|
||||
const diffLinesGenerator = generateSearchReplaceDiffLines(
|
||||
fileContent,
|
||||
match,
|
||||
replaceContent,
|
||||
);
|
||||
|
||||
// Stream through existing VerticalDiffManager infrastructure
|
||||
await this.verticalDiffManager.streamDiffLines(
|
||||
diffLinesGenerator,
|
||||
true, // isInstantApply = true (deterministic, no LLM involved)
|
||||
streamId,
|
||||
toolCallId,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a prompt for applying code edits
|
||||
*/
|
||||
|
|
|
|||
531
gui/src/util/clientTools/searchReplaceImpl.test.ts
Normal file
531
gui/src/util/clientTools/searchReplaceImpl.test.ts
Normal file
|
|
@ -0,0 +1,531 @@
|
|||
import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
|
||||
import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
|
||||
import { resolveRelativePathInDir } from "core/util/ideUtils";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ClientToolExtras } from "./callClientTool";
|
||||
import { searchReplaceToolImpl } from "./searchReplaceImpl";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("core/edit/searchAndReplace/findSearchMatch");
|
||||
vi.mock("core/edit/searchAndReplace/parseSearchReplaceBlock");
|
||||
vi.mock("core/util/ideUtils");
|
||||
|
||||
const mockFindSearchMatch = vi.mocked(findSearchMatch);
|
||||
const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks);
|
||||
const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir);
|
||||
|
||||
describe("searchReplaceToolImpl", () => {
|
||||
let mockExtras: ClientToolExtras;
|
||||
let mockIdeMessenger: any;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset all mocks
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Create mock IDE messenger
|
||||
mockIdeMessenger = {
|
||||
ide: {
|
||||
readFile: vi.fn(),
|
||||
},
|
||||
request: vi.fn(),
|
||||
};
|
||||
|
||||
// Create mock extras
|
||||
mockExtras = {
|
||||
streamId: "test-stream-id",
|
||||
ideMessenger: mockIdeMessenger,
|
||||
getState: vi.fn(),
|
||||
dispatch: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("basic validation", () => {
|
||||
it("should throw error when no streamId is provided", async () => {
|
||||
const extrasWithoutStreamId = {
|
||||
...mockExtras,
|
||||
streamId: undefined,
|
||||
};
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "some diff" },
|
||||
"tool-call-id",
|
||||
extrasWithoutStreamId,
|
||||
),
|
||||
).rejects.toThrow("Invalid apply state - no streamId available");
|
||||
});
|
||||
|
||||
it("should throw error when file does not exist", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue(undefined);
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "nonexistent.txt", diff: "some diff" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("File nonexistent.txt does not exist");
|
||||
});
|
||||
|
||||
it("should throw error when no search/replace blocks found", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([]);
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "invalid diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("No complete search/replace blocks found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("single block replacement", () => {
|
||||
it("should successfully apply single search/replace block", async () => {
|
||||
const originalContent = `function hello() {
|
||||
console.log("Hello");
|
||||
return "world";
|
||||
}`;
|
||||
|
||||
const expectedFinalContent = `function hello() {
|
||||
console.log("Hi there!");
|
||||
return "world";
|
||||
}`;
|
||||
|
||||
// Setup mocks
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: 'console.log("Hello");',
|
||||
replaceContent: 'console.log("Hi there!");',
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
|
||||
// Calculate correct positions for 'console.log("Hello");' in the original content
|
||||
const searchText = 'console.log("Hello");';
|
||||
const startIndex = originalContent.indexOf(searchText);
|
||||
const endIndex = startIndex + searchText.length;
|
||||
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex,
|
||||
endIndex,
|
||||
});
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
const result = await searchReplaceToolImpl(
|
||||
{ filepath: "test.js", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
respondImmediately: false,
|
||||
output: undefined,
|
||||
});
|
||||
|
||||
// Verify applyToFile was called with correct parameters
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: expectedFinalContent,
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.js",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("multiple block replacement", () => {
|
||||
it("should successfully apply multiple search/replace blocks sequentially", async () => {
|
||||
const originalContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
|
||||
const expectedFinalContent = `const a = 100;
|
||||
const b = 200;
|
||||
const c = 3;`;
|
||||
|
||||
// Setup mocks
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "const a = 1;",
|
||||
replaceContent: "const a = 100;",
|
||||
},
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "const b = 2;",
|
||||
replaceContent: "const b = 200;",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
|
||||
// Calculate positions for sequential replacements
|
||||
const firstSearchText = "const a = 1;";
|
||||
const secondSearchText = "const b = 2;";
|
||||
|
||||
const firstStartIndex = originalContent.indexOf(firstSearchText);
|
||||
const firstEndIndex = firstStartIndex + firstSearchText.length;
|
||||
|
||||
// After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;"
|
||||
const contentAfterFirstReplacement =
|
||||
originalContent.substring(0, firstStartIndex) +
|
||||
"const a = 100;" +
|
||||
originalContent.substring(firstEndIndex);
|
||||
|
||||
const secondStartIndex =
|
||||
contentAfterFirstReplacement.indexOf(secondSearchText);
|
||||
const secondEndIndex = secondStartIndex + secondSearchText.length;
|
||||
|
||||
// Mock sequential search matches
|
||||
mockFindSearchMatch
|
||||
.mockReturnValueOnce({
|
||||
startIndex: firstStartIndex,
|
||||
endIndex: firstEndIndex,
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
startIndex: secondStartIndex,
|
||||
endIndex: secondEndIndex,
|
||||
});
|
||||
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
const result = await searchReplaceToolImpl(
|
||||
{ filepath: "test.js", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
respondImmediately: false,
|
||||
output: undefined,
|
||||
});
|
||||
|
||||
// Verify findSearchMatch was called twice with updated content
|
||||
expect(mockFindSearchMatch).toHaveBeenCalledTimes(2);
|
||||
expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
originalContent,
|
||||
"const a = 1;",
|
||||
);
|
||||
expect(mockFindSearchMatch).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
contentAfterFirstReplacement,
|
||||
"const b = 2;",
|
||||
);
|
||||
// Verify final applyToFile call
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: expectedFinalContent,
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.js",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("deletion scenarios", () => {
|
||||
it("should handle empty replacement (deletion)", async () => {
|
||||
const originalContent = `keep this
|
||||
remove this line
|
||||
keep this too`;
|
||||
|
||||
const expectedFinalContent = `keep this
|
||||
|
||||
keep this too`;
|
||||
|
||||
// Setup mocks
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "remove this line",
|
||||
replaceContent: "",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex: 10, // Position of "remove this line"
|
||||
endIndex: 26, // End of "remove this line"
|
||||
});
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
const result = await searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
respondImmediately: false,
|
||||
output: undefined,
|
||||
});
|
||||
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: expectedFinalContent,
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.txt",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle undefined replaceContent as empty string", async () => {
|
||||
const originalContent = "line1\nline2\nline3";
|
||||
const expectedFinalContent = "line1\n\nline3";
|
||||
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "line2",
|
||||
replaceContent: undefined, // undefined should be treated as empty string
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex: 6,
|
||||
endIndex: 11,
|
||||
});
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
await searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: expectedFinalContent,
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.txt",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should throw error when search content is not found", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "nonexistent content",
|
||||
replaceContent: "replacement",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue("some file content");
|
||||
mockFindSearchMatch.mockReturnValue(null); // Search content not found
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"Search content not found in block 1:\nnonexistent content",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when search content is not found in second block", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "found content",
|
||||
replaceContent: "replacement1",
|
||||
},
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "missing content",
|
||||
replaceContent: "replacement2",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(
|
||||
"found content and other stuff",
|
||||
);
|
||||
|
||||
// First search succeeds, second fails
|
||||
mockFindSearchMatch
|
||||
.mockReturnValueOnce({
|
||||
startIndex: 0,
|
||||
endIndex: 13,
|
||||
})
|
||||
.mockReturnValueOnce(null); // Second search fails
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"Search content not found in block 2:\nmissing content",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle file read errors", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "content",
|
||||
replaceContent: "replacement",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockRejectedValue(
|
||||
new Error("File read error"),
|
||||
);
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Failed to apply search and replace: File read error");
|
||||
});
|
||||
|
||||
it("should handle applyToFile errors", async () => {
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "content",
|
||||
replaceContent: "replacement",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue("content");
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex: 0,
|
||||
endIndex: 7,
|
||||
});
|
||||
mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed"));
|
||||
|
||||
await expect(
|
||||
searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Failed to apply search and replace: Apply failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases", () => {
|
||||
it("should handle empty search content", async () => {
|
||||
const originalContent = "existing content";
|
||||
const expectedFinalContent = "new contentexisting content";
|
||||
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "",
|
||||
replaceContent: "new content",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex: 0, // Empty search matches at beginning
|
||||
endIndex: 0,
|
||||
});
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
await searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: expectedFinalContent,
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.txt",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle whole file replacement", async () => {
|
||||
const originalContent = "old file content";
|
||||
const expectedFinalContent = "completely new content";
|
||||
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: originalContent,
|
||||
replaceContent: "completely new content",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex: 0,
|
||||
endIndex: originalContent.length,
|
||||
});
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
await searchReplaceToolImpl(
|
||||
{ filepath: "test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: expectedFinalContent,
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.txt",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("dependency integration", () => {
|
||||
it("should call all dependencies with correct parameters", async () => {
|
||||
const originalContent = "test content";
|
||||
|
||||
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
|
||||
mockParseAllSearchReplaceBlocks.mockReturnValue([
|
||||
{
|
||||
isComplete: true,
|
||||
searchContent: "test",
|
||||
replaceContent: "updated",
|
||||
},
|
||||
]);
|
||||
mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent);
|
||||
mockFindSearchMatch.mockReturnValue({
|
||||
startIndex: 0,
|
||||
endIndex: 4,
|
||||
});
|
||||
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
|
||||
|
||||
await searchReplaceToolImpl(
|
||||
{ filepath: "relative/test.txt", diff: "mock diff content" },
|
||||
"tool-call-id",
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
// Verify all dependencies were called correctly
|
||||
expect(mockResolveRelativePathInDir).toHaveBeenCalledWith(
|
||||
"relative/test.txt",
|
||||
mockIdeMessenger.ide,
|
||||
);
|
||||
expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledWith(
|
||||
"mock diff content",
|
||||
);
|
||||
expect(mockIdeMessenger.ide.readFile).toHaveBeenCalledWith(
|
||||
"/resolved/path/test.txt",
|
||||
);
|
||||
expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test");
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
|
||||
text: "updated content",
|
||||
streamId: "test-stream-id",
|
||||
filepath: "/resolved/path/test.txt",
|
||||
toolCallId: "tool-call-id",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import { ContextItem } from "core";
|
||||
import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
|
||||
import { parseSearchReplaceBlock } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
|
||||
import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
|
||||
import { resolveRelativePathInDir } from "core/util/ideUtils";
|
||||
import { ClientToolImpl } from "./callClientTool";
|
||||
|
||||
|
|
@ -11,6 +10,11 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
|
|||
) => {
|
||||
const { filepath, diff } = args;
|
||||
|
||||
// Check if we have a streamId from a pre-existing apply state
|
||||
if (!extras.streamId) {
|
||||
throw new Error("Invalid apply state - no streamId available");
|
||||
}
|
||||
|
||||
// Resolve the file path
|
||||
const resolvedFilepath = await resolveRelativePathInDir(
|
||||
filepath,
|
||||
|
|
@ -20,66 +24,53 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
|
|||
throw new Error(`File ${filepath} does not exist`);
|
||||
}
|
||||
|
||||
// Parse the search/replace block from the diff content
|
||||
const parseResult = parseSearchReplaceBlock(diff);
|
||||
// Parse all search/replace blocks from the diff content
|
||||
const blocks = parseAllSearchReplaceBlocks(diff);
|
||||
|
||||
if (parseResult.error) {
|
||||
throw new Error(`Parse error: ${parseResult.error}`);
|
||||
if (blocks.length === 0) {
|
||||
throw new Error("No complete search/replace blocks found");
|
||||
}
|
||||
|
||||
if (!parseResult.isComplete) {
|
||||
throw new Error("Incomplete search/replace block");
|
||||
}
|
||||
|
||||
const { searchContent, replaceContent } = parseResult;
|
||||
|
||||
try {
|
||||
// Read the current file content
|
||||
const fileContent =
|
||||
const originalContent =
|
||||
await extras.ideMessenger.ide.readFile(resolvedFilepath);
|
||||
let currentContent = originalContent;
|
||||
|
||||
// Find the search match
|
||||
const match = findSearchMatch(fileContent, searchContent || "");
|
||||
// Apply all replacements sequentially to build the final content
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
const block = blocks[i];
|
||||
const { searchContent, replaceContent } = block;
|
||||
|
||||
if (!match) {
|
||||
throw new Error(`Search content not found in file:\n${searchContent}`);
|
||||
// Find the search content in the current state of the file
|
||||
const match = findSearchMatch(currentContent, searchContent || "");
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`Search content not found in block ${i + 1}:\n${searchContent}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Apply the replacement
|
||||
currentContent =
|
||||
currentContent.substring(0, match.startIndex) +
|
||||
(replaceContent || "") +
|
||||
currentContent.substring(match.endIndex);
|
||||
}
|
||||
|
||||
// Apply the replacement
|
||||
const newContent =
|
||||
fileContent.substring(0, match.startIndex) +
|
||||
(replaceContent || "") +
|
||||
fileContent.substring(match.endIndex);
|
||||
|
||||
// Write the updated file
|
||||
await extras.ideMessenger.request("writeFile", {
|
||||
path: resolvedFilepath,
|
||||
contents: newContent,
|
||||
// Single applyToFile call with all accumulated changes
|
||||
// Use regular apply mode (not search/replace mode) to leverage existing diff logic
|
||||
await extras.ideMessenger.request("applyToFile", {
|
||||
text: currentContent,
|
||||
streamId: extras.streamId,
|
||||
filepath: resolvedFilepath,
|
||||
toolCallId,
|
||||
// Don't use search/replace mode since we're providing the complete final content
|
||||
});
|
||||
|
||||
// Create context item showing the change
|
||||
const contextItem: ContextItem = {
|
||||
name: `Modified ${filepath}`,
|
||||
description: `Applied search and replace to ${filepath}`,
|
||||
content: `Search and replace operation completed successfully.
|
||||
|
||||
Search content:
|
||||
\`\`\`
|
||||
${searchContent}
|
||||
\`\`\`
|
||||
|
||||
Replace content:
|
||||
\`\`\`
|
||||
${replaceContent}
|
||||
\`\`\`
|
||||
|
||||
File: ${filepath}`,
|
||||
editing: true,
|
||||
};
|
||||
|
||||
// Return success - applyToFile will handle the completion state
|
||||
return {
|
||||
respondImmediately: true,
|
||||
output: [contextItem],
|
||||
respondImmediately: false, // Let apply state handle completion
|
||||
output: undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
gui\src\components\mainInput\TutorialCard.tsx
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
gui\src\components\modelSelection\ModelSelect.tsx
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
gui\src\components\modelSelection\platform\AssistantSelect.tsx
|
||||
|
||||
???
|
||||
Loading…
Add table
Reference in a new issue