Changesets · Branches · Tags · Compare
| Changeset | 9517700465b5a7fe03a9f13b9de9ae24f348b6e23cbd991e0056008ae60d7f3e |
|---|---|
| Author | Patrick Erichsen <patrick.a.erichsen@gmail.com> · 2025-06-26 16:02 -07:00 |
| Committer | Patrick Erichsen <patrick.a.erichsen@gmail.com> · 2025-06-26 16:02 -07:00 |
| Parents | 6c0ea8c4e384 |
11 files changed
added core/edit/searchAndReplace/generateSearchReplaceDiffLines.test.ts +143 −0
| @@ -0,0 +1,143 @@ | ||
| 1 | +import { SearchMatchResult } from "./findSearchMatch"; | |
| 2 | +import { generateSearchReplaceDiffLines } from "./generateSearchReplaceDiffLines"; | |
| 3 | + | |
| 4 | +describe("generateSearchReplaceDiffLines", () => { | |
| 5 | + async function collectDiffLines(generator: AsyncGenerator<any>) { | |
| 6 | + const lines = []; | |
| 7 | + for await (const line of generator) { | |
| 8 | + lines.push(line); | |
| 9 | + } | |
| 10 | + return lines; | |
| 11 | + } | |
| 12 | + | |
| 13 | + it("should generate valid diff lines", async () => { | |
| 14 | + const fileContent = `const a = 1; | |
| 15 | +const b = 2; | |
| 16 | +const c = 3;`; | |
| 17 | + | |
| 18 | + const searchMatch: SearchMatchResult = { | |
| 19 | + startIndex: 13, // Start of "const b = 2;" | |
| 20 | + endIndex: 25, // End of "const b = 2;" | |
| 21 | + }; | |
| 22 | + | |
| 23 | + const replaceContent = "const b = 42;"; | |
| 24 | + | |
| 25 | + const diffLines = await collectDiffLines( | |
| 26 | + generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent), | |
| 27 | + ); | |
| 28 | + | |
| 29 | + // Verify we get valid diff lines | |
| 30 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 31 | + | |
| 32 | + // Verify all lines have valid types | |
| 33 | + diffLines.forEach((line) => { | |
| 34 | + expect(["old", "new", "same"]).toContain(line.type); | |
| 35 | + expect(typeof line.line).toBe("string"); | |
| 36 | + }); | |
| 37 | + | |
| 38 | + // Verify we have both old and new lines (indicating a change) | |
| 39 | + const hasOldLines = diffLines.some((line) => line.type === "old"); | |
| 40 | + const hasNewLines = diffLines.some((line) => line.type === "new"); | |
| 41 | + expect(hasOldLines).toBe(true); | |
| 42 | + expect(hasNewLines).toBe(true); | |
| 43 | + }); | |
| 44 | + | |
| 45 | + it("should handle empty replacement (deletion)", async () => { | |
| 46 | + const fileContent = `const a = 1; | |
| 47 | +const b = 2; | |
| 48 | +const c = 3;`; | |
| 49 | + | |
| 50 | + const searchMatch: SearchMatchResult = { | |
| 51 | + startIndex: 12, // Start of "\nconst b = 2;" | |
| 52 | + endIndex: 25, // End of "const b = 2;" | |
| 53 | + }; | |
| 54 | + | |
| 55 | + const replaceContent = ""; | |
| 56 | + | |
| 57 | + const diffLines = await collectDiffLines( | |
| 58 | + generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent), | |
| 59 | + ); | |
| 60 | + | |
| 61 | + // Should have old lines for the deleted content | |
| 62 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 63 | + const hasOldLines = diffLines.some((line) => line.type === "old"); | |
| 64 | + expect(hasOldLines).toBe(true); | |
| 65 | + }); | |
| 66 | + it("should handle whole file replacement", async () => { | |
| 67 | + const fileContent = `old content`; | |
| 68 | + const searchMatch: SearchMatchResult = { | |
| 69 | + startIndex: 0, | |
| 70 | + endIndex: fileContent.length, | |
| 71 | + }; | |
| 72 | + | |
| 73 | + const replaceContent = `completely new content`; | |
| 74 | + const diffLines = await collectDiffLines( | |
| 75 | + generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent), | |
| 76 | + ); | |
| 77 | + | |
| 78 | + // Should have both old and new lines | |
| 79 | + const hasOldLines = diffLines.some((line) => line.type === "old"); | |
| 80 | + const hasNewLines = diffLines.some((line) => line.type === "new"); | |
| 81 | + expect(hasOldLines).toBe(true); | |
| 82 | + expect(hasNewLines).toBe(true); | |
| 83 | + }); | |
| 84 | + | |
| 85 | + it("should handle empty file with insertion", async () => { | |
| 86 | + const fileContent = ""; | |
| 87 | + const searchMatch: SearchMatchResult = { | |
| 88 | + startIndex: 0, | |
| 89 | + endIndex: 0, | |
| 90 | + }; | |
| 91 | + | |
| 92 | + const replaceContent = `new content | |
| 93 | +second line`; | |
| 94 | + | |
| 95 | + const diffLines = await collectDiffLines( | |
| 96 | + generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent), | |
| 97 | + ); | |
| 98 | + | |
| 99 | + // Should have new lines for the inserted content | |
| 100 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 101 | + const hasNewLines = diffLines.some((line) => line.type === "new"); | |
| 102 | + expect(hasNewLines).toBe(true); | |
| 103 | + | |
| 104 | + // Note: Empty file split by newlines gives [''] so there will be one "old" empty line | |
| 105 | + // This is correct behavior from the diff algorithm's perspective | |
| 106 | + }); | |
| 107 | + | |
| 108 | + it("should produce correct final content when applied", async () => { | |
| 109 | + const fileContent = `line1 | |
| 110 | +line2 | |
| 111 | +line3`; | |
| 112 | + | |
| 113 | + const searchMatch: SearchMatchResult = { | |
| 114 | + startIndex: 6, // Start of "line2" | |
| 115 | + endIndex: 11, // End of "line2" | |
| 116 | + }; | |
| 117 | + | |
| 118 | + const replaceContent = "replaced"; | |
| 119 | + | |
| 120 | + // The expected final content | |
| 121 | + const expectedContent = | |
| 122 | + fileContent.substring(0, searchMatch.startIndex) + | |
| 123 | + replaceContent + | |
| 124 | + fileContent.substring(searchMatch.endIndex); | |
| 125 | + | |
| 126 | + const diffLines = await collectDiffLines( | |
| 127 | + generateSearchReplaceDiffLines(fileContent, searchMatch, replaceContent), | |
| 128 | + ); | |
| 129 | + | |
| 130 | + // Reconstruct content from diff lines | |
| 131 | + const newLines = diffLines | |
| 132 | + .filter((line) => line.type === "new" || line.type === "same") | |
| 133 | + .map((line) => line.line); | |
| 134 | + | |
| 135 | + const reconstructedContent = newLines.join("\n"); | |
| 136 | + | |
| 137 | + // Should exactly match expected content, including line structure | |
| 138 | + expect(reconstructedContent).toBe(expectedContent); | |
| 139 | + | |
| 140 | + // Also verify we have the correct number of lines | |
| 141 | + expect(newLines).toEqual(["line1", "replaced", "line3"]); | |
| 142 | + }); | |
| 143 | +}); |
added core/edit/searchAndReplace/generateSearchReplaceDiffLines.ts +39 −0
| @@ -0,0 +1,39 @@ | ||
| 1 | +import { DiffLine } from "../.."; | |
| 2 | +import { streamDiff } from "../../diff/streamDiff"; | |
| 3 | +import { SearchMatchResult } from "./findSearchMatch"; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Generates a stream of DiffLine objects for a search and replace operation. | |
| 7 | + * Uses the existing streamDiff algorithm to calculate the actual differences. | |
| 8 | + * | |
| 9 | + * @param fileContent - The complete content of the file | |
| 10 | + * @param searchMatch - The match result with start/end character positions | |
| 11 | + * @param replaceContent - The content to replace the matched section with | |
| 12 | + * @returns AsyncGenerator of DiffLine objects for streaming to VerticalDiffManager | |
| 13 | + */ | |
| 14 | +export async function* generateSearchReplaceDiffLines( | |
| 15 | + fileContent: string, | |
| 16 | + searchMatch: SearchMatchResult, | |
| 17 | + replaceContent: string, | |
| 18 | +): AsyncGenerator<DiffLine> { | |
| 19 | + // Apply the replacement to get the new file content | |
| 20 | + const newFileContent = | |
| 21 | + fileContent.substring(0, searchMatch.startIndex) + | |
| 22 | + replaceContent + | |
| 23 | + fileContent.substring(searchMatch.endIndex); | |
| 24 | + | |
| 25 | + // Split into lines for the diff algorithm | |
| 26 | + const oldLines = fileContent.split("\n"); | |
| 27 | + const newLines = newFileContent.split("\n"); | |
| 28 | + | |
| 29 | + // Create a simple async generator for the new lines | |
| 30 | + // Don't use streamLines since we already have complete lines | |
| 31 | + async function* newLinesGenerator() { | |
| 32 | + for (const line of newLines) { | |
| 33 | + yield line; | |
| 34 | + } | |
| 35 | + } | |
| 36 | + | |
| 37 | + // Stream the diff using existing infrastructure | |
| 38 | + yield* streamDiff(oldLines, newLinesGenerator()); | |
| 39 | +} |
modified core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts +197 −4
| @@ -1,4 +1,8 @@ | ||
| 1 | -import { parseSearchReplaceBlock } from "./parseSearchReplaceBlock"; | |
| 1 | +import { | |
| 2 | + parseAllSearchReplaceBlocks, | |
| 3 | + parseSearchReplaceBlock, | |
| 4 | +} from "./parseSearchReplaceBlock"; | |
| 5 | + | |
| 2 | 6 | describe("parseSearchReplaceBlock", () => { |
| 3 | 7 | describe("Complete blocks", () => { |
| 4 | 8 | it("should parse a complete basic search/replace block", () => { |
| @@ -58,16 +62,28 @@ | ||
| 58 | 62 | expect(result.replaceContent).toBe("new content"); |
| 59 | 63 | }); |
| 60 | 64 | |
| 61 | - it("should handle empty replace content", () => { | |
| 65 | + it("should handle empty replace content (deletion)", () => { | |
| 62 | 66 | const content = `------- SEARCH |
| 63 | -old content | |
| 67 | +old content to delete | |
| 64 | 68 | ======= |
| 65 | 69 | +++++++ REPLACE`; |
| 66 | 70 | |
| 67 | 71 | const result = parseSearchReplaceBlock(content); |
| 68 | 72 | |
| 69 | 73 | expect(result.isComplete).toBe(true); |
| 70 | - expect(result.searchContent).toBe("old content"); | |
| 74 | + expect(result.searchContent).toBe("old content to delete"); | |
| 75 | + expect(result.replaceContent).toBe(""); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + it("should handle both empty search and replace content", () => { | |
| 79 | + const content = `------- SEARCH | |
| 80 | +======= | |
| 81 | ++++++++ REPLACE`; | |
| 82 | + | |
| 83 | + const result = parseSearchReplaceBlock(content); | |
| 84 | + | |
| 85 | + expect(result.isComplete).toBe(true); | |
| 86 | + expect(result.searchContent).toBe(""); | |
| 71 | 87 | expect(result.replaceContent).toBe(""); |
| 72 | 88 | }); |
| 73 | 89 | }); |
| @@ -136,6 +152,7 @@ | ||
| 136 | 152 | ======= |
| 137 | 153 | replacement |
| 138 | 154 | +++++++ REPLACE`; |
| 155 | + | |
| 139 | 156 | const result = parseSearchReplaceBlock(content); |
| 140 | 157 | expect(result.isComplete).toBe(true); |
| 141 | 158 | }); |
| @@ -195,3 +212,179 @@ | ||
| 195 | 212 | }); |
| 196 | 213 | }); |
| 197 | 214 | }); |
| 215 | + | |
| 216 | +describe("parseAllSearchReplaceBlocks", () => { | |
| 217 | + it("should parse multiple complete blocks", () => { | |
| 218 | + const content = `------- SEARCH | |
| 219 | +old code 1 | |
| 220 | +======= | |
| 221 | +new code 1 | |
| 222 | ++++++++ REPLACE | |
| 223 | + | |
| 224 | +------- SEARCH | |
| 225 | +old code 2 | |
| 226 | +======= | |
| 227 | +new code 2 | |
| 228 | ++++++++ REPLACE`; | |
| 229 | + | |
| 230 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 231 | + | |
| 232 | + expect(blocks).toHaveLength(2); | |
| 233 | + expect(blocks[0].searchContent).toBe("old code 1"); | |
| 234 | + expect(blocks[0].replaceContent).toBe("new code 1"); | |
| 235 | + expect(blocks[1].searchContent).toBe("old code 2"); | |
| 236 | + expect(blocks[1].replaceContent).toBe("new code 2"); | |
| 237 | + }); | |
| 238 | + | |
| 239 | + it("should handle blocks with different content", () => { | |
| 240 | + const content = `------- SEARCH | |
| 241 | +function old() { | |
| 242 | + return 1; | |
| 243 | +} | |
| 244 | +======= | |
| 245 | +function new() { | |
| 246 | + return 2; | |
| 247 | +} | |
| 248 | ++++++++ REPLACE | |
| 249 | + | |
| 250 | +------- SEARCH | |
| 251 | +const x = 'old'; | |
| 252 | +======= | |
| 253 | +const x = 'new'; | |
| 254 | ++++++++ REPLACE`; | |
| 255 | + | |
| 256 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 257 | + | |
| 258 | + expect(blocks).toHaveLength(2); | |
| 259 | + expect(blocks[0].searchContent).toBe(`function old() { | |
| 260 | + return 1; | |
| 261 | +}`); | |
| 262 | + expect(blocks[0].replaceContent).toBe(`function new() { | |
| 263 | + return 2; | |
| 264 | +}`); | |
| 265 | + expect(blocks[1].searchContent).toBe(`const x = 'old';`); | |
| 266 | + expect(blocks[1].replaceContent).toBe(`const x = 'new';`); | |
| 267 | + }); | |
| 268 | + | |
| 269 | + it("should handle deletion blocks (empty replace content)", () => { | |
| 270 | + const content = `------- SEARCH | |
| 271 | +code to keep | |
| 272 | +======= | |
| 273 | +modified code | |
| 274 | ++++++++ REPLACE | |
| 275 | + | |
| 276 | +------- SEARCH | |
| 277 | +code to delete | |
| 278 | +======= | |
| 279 | ++++++++ REPLACE`; | |
| 280 | + | |
| 281 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 282 | + | |
| 283 | + expect(blocks).toHaveLength(2); | |
| 284 | + expect(blocks[0].searchContent).toBe("code to keep"); | |
| 285 | + expect(blocks[0].replaceContent).toBe("modified code"); | |
| 286 | + expect(blocks[1].searchContent).toBe("code to delete"); | |
| 287 | + expect(blocks[1].replaceContent).toBe(""); // Deletion | |
| 288 | + }); | |
| 289 | + | |
| 290 | + it("should handle insertion blocks (empty search content)", () => { | |
| 291 | + const content = `------- SEARCH | |
| 292 | +existing code | |
| 293 | +======= | |
| 294 | +modified existing code | |
| 295 | ++++++++ REPLACE | |
| 296 | + | |
| 297 | +------- SEARCH | |
| 298 | +======= | |
| 299 | +new code to insert | |
| 300 | ++++++++ REPLACE`; | |
| 301 | + | |
| 302 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 303 | + | |
| 304 | + expect(blocks).toHaveLength(2); | |
| 305 | + expect(blocks[0].searchContent).toBe("existing code"); | |
| 306 | + expect(blocks[0].replaceContent).toBe("modified existing code"); | |
| 307 | + expect(blocks[1].searchContent).toBe(""); // Insertion | |
| 308 | + expect(blocks[1].replaceContent).toBe("new code to insert"); | |
| 309 | + }); | |
| 310 | + | |
| 311 | + it("should skip incomplete blocks", () => { | |
| 312 | + const content = `------- SEARCH | |
| 313 | +incomplete block | |
| 314 | + | |
| 315 | +------- SEARCH | |
| 316 | +complete block | |
| 317 | +======= | |
| 318 | +replacement | |
| 319 | ++++++++ REPLACE`; | |
| 320 | + | |
| 321 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 322 | + | |
| 323 | + expect(blocks).toHaveLength(1); | |
| 324 | + expect(blocks[0].searchContent).toBe("complete block"); | |
| 325 | + expect(blocks[0].replaceContent).toBe("replacement"); | |
| 326 | + }); | |
| 327 | + | |
| 328 | + it("should handle single block", () => { | |
| 329 | + const content = `------- SEARCH | |
| 330 | +single block | |
| 331 | +======= | |
| 332 | +replacement | |
| 333 | ++++++++ REPLACE`; | |
| 334 | + | |
| 335 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 336 | + | |
| 337 | + expect(blocks).toHaveLength(1); | |
| 338 | + expect(blocks[0].searchContent).toBe("single block"); | |
| 339 | + expect(blocks[0].replaceContent).toBe("replacement"); | |
| 340 | + }); | |
| 341 | + | |
| 342 | + it("should return empty array when no complete blocks found", () => { | |
| 343 | + const content = `------- SEARCH | |
| 344 | +incomplete | |
| 345 | +======= | |
| 346 | +missing replace marker`; | |
| 347 | + | |
| 348 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 349 | + | |
| 350 | + expect(blocks).toHaveLength(0); | |
| 351 | + }); | |
| 352 | + | |
| 353 | + it("should handle blocks with extra content between them", () => { | |
| 354 | + const content = `Some other content here | |
| 355 | + | |
| 356 | +------- SEARCH | |
| 357 | +block 1 | |
| 358 | +======= | |
| 359 | +replacement 1 | |
| 360 | ++++++++ REPLACE | |
| 361 | + | |
| 362 | +More content in between | |
| 363 | + | |
| 364 | +------- SEARCH | |
| 365 | +block 2 | |
| 366 | +======= | |
| 367 | +replacement 2 | |
| 368 | ++++++++ REPLACE | |
| 369 | + | |
| 370 | +Trailing content`; | |
| 371 | + | |
| 372 | + const blocks = parseAllSearchReplaceBlocks(content); | |
| 373 | + | |
| 374 | + expect(blocks).toHaveLength(2); | |
| 375 | + expect(blocks[0].searchContent).toBe("block 1"); | |
| 376 | + expect(blocks[0].replaceContent).toBe("replacement 1"); | |
| 377 | + expect(blocks[1].searchContent).toBe("block 2"); | |
| 378 | + expect(blocks[1].replaceContent).toBe("replacement 2"); | |
| 379 | + }); | |
| 380 | + | |
| 381 | + it("should throw error for malformed blocks", () => { | |
| 382 | + const content = `------- SEARCH | |
| 383 | +content | |
| 384 | ++++++++ REPLACE`; // Missing ======= | |
| 385 | + | |
| 386 | + expect(() => parseAllSearchReplaceBlocks(content)).toThrow( | |
| 387 | + "Found replace block end marker without matching replace start marker", | |
| 388 | + ); | |
| 389 | + }); | |
| 390 | +}); |
modified core/edit/searchAndReplace/parseSearchReplaceBlock.ts +52 −0
| @@ -1,3 +1,4 @@ | ||
| 1 | +// Search and replace block markers using flexible regex patterns | |
| 1 | 2 | const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; |
| 2 | 3 | const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; |
| 3 | 4 | const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; |
| @@ -30,6 +31,7 @@ | ||
| 30 | 31 | content: string, |
| 31 | 32 | ): SearchReplaceBlockResult { |
| 32 | 33 | const lines = content.split("\n"); |
| 34 | + | |
| 33 | 35 | let currentSearchContent = ""; |
| 34 | 36 | let currentReplaceContent = ""; |
| 35 | 37 | let inSearch = false; |
| @@ -88,3 +90,53 @@ | ||
| 88 | 90 | replaceContent: currentReplaceContent.trim(), |
| 89 | 91 | }; |
| 90 | 92 | } |
| 93 | + | |
| 94 | +/** | |
| 95 | + * Parses all complete search and replace blocks from content. | |
| 96 | + * | |
| 97 | + * @param content - The content containing multiple search/replace blocks | |
| 98 | + * @returns Array of complete search/replace blocks found | |
| 99 | + */ | |
| 100 | +export function parseAllSearchReplaceBlocks( | |
| 101 | + content: string, | |
| 102 | +): SearchReplaceBlockResult[] { | |
| 103 | + const blocks: SearchReplaceBlockResult[] = []; | |
| 104 | + const lines = content.split("\n"); | |
| 105 | + | |
| 106 | + let currentBlockLines: string[] = []; | |
| 107 | + let inBlock = false; | |
| 108 | + | |
| 109 | + for (const line of lines) { | |
| 110 | + if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 111 | + // Start of new block | |
| 112 | + if (inBlock && currentBlockLines.length > 0) { | |
| 113 | + // Process previous incomplete block if any | |
| 114 | + const blockContent = currentBlockLines.join("\n"); | |
| 115 | + const result = parseSearchReplaceBlock(blockContent); | |
| 116 | + if (result.isComplete) { | |
| 117 | + blocks.push(result); | |
| 118 | + } | |
| 119 | + } | |
| 120 | + currentBlockLines = [line]; | |
| 121 | + inBlock = true; | |
| 122 | + } else if (inBlock) { | |
| 123 | + currentBlockLines.push(line); | |
| 124 | + | |
| 125 | + // Check if this line completes the current block | |
| 126 | + if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 127 | + const blockContent = currentBlockLines.join("\n"); | |
| 128 | + const result = parseSearchReplaceBlock(blockContent); | |
| 129 | + if (result.isComplete) { | |
| 130 | + blocks.push(result); | |
| 131 | + } else if (result.error) { | |
| 132 | + // If there's an error, throw it immediately | |
| 133 | + throw new Error(result.error); | |
| 134 | + } | |
| 135 | + currentBlockLines = []; | |
| 136 | + inBlock = false; | |
| 137 | + } | |
| 138 | + } | |
| 139 | + } | |
| 140 | + | |
| 141 | + return blocks; | |
| 142 | +} |
modified core/protocol/ide.ts +0 −10
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | import type { |
| 2 | 2 | ContinueRcJson, |
| 3 | - DiffLine, | |
| 4 | 3 | FileStatsMap, |
| 5 | 4 | FileType, |
| 6 | 5 | IDE, |
| @@ -35,15 +34,6 @@ | ||
| 35 | 34 | saveFile: [{ filepath: string }, void]; |
| 36 | 35 | fileExists: [{ filepath: string }, boolean]; |
| 37 | 36 | readFile: [{ filepath: string }, string]; |
| 38 | - diffLine: [ | |
| 39 | - { | |
| 40 | - diffLine: DiffLine; | |
| 41 | - filepath: string; | |
| 42 | - startLine: number; | |
| 43 | - endLine: number; | |
| 44 | - }, | |
| 45 | - void, | |
| 46 | - ]; | |
| 47 | 37 | getProblems: [{ filepath: string }, Problem[]]; |
| 48 | 38 | getOpenFiles: [undefined, string[]]; |
| 49 | 39 | getCurrentFile: [ |
modified core/protocol/ideWebview.ts +2 −0
| @@ -19,6 +19,8 @@ | ||
| 19 | 19 | streamId: string; |
| 20 | 20 | filepath?: string; |
| 21 | 21 | toolCallId?: string; |
| 22 | + searchContent?: string; | |
| 23 | + isSearchReplace?: boolean; | |
| 22 | 24 | }, |
| 23 | 25 | void, |
| 24 | 26 | ]; |
modified core/tools/definitions/searchAndReplaceInFile.ts +37 −10
| @@ -7,15 +7,9 @@ | ||
| 7 | 7 | } |
| 8 | 8 | |
| 9 | 9 | /** |
| 10 | - * Critical requirements: | |
| 11 | -1. SEARCH content must match the file section EXACTLY (character-for-character, including whitespace and indentation) | |
| 12 | -2. Each SEARCH/REPLACE block replaces only the first matching occurrence | |
| 13 | -3. For multiple changes, use multiple SEARCH/REPLACE blocks in file order | |
| 14 | -4. Keep blocks concise - include only the lines that need to change plus minimal context for uniqueness | |
| 15 | -5. To delete code, use an empty REPLACE section | |
| 16 | -6. To move code, use two blocks (one to delete, one to insert at new location) | |
| 10 | + * This tool is in an experimental state. | |
| 11 | + * 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 | |
| 17 | 12 | */ |
| 18 | - | |
| 19 | 13 | export const searchAndReplaceInFileTool: Tool = { |
| 20 | 14 | type: "function", |
| 21 | 15 | displayTitle: "Edit File", |
| @@ -28,7 +22,7 @@ | ||
| 28 | 22 | function: { |
| 29 | 23 | name: BuiltInToolNames.SearchAndReplaceInFile, |
| 30 | 24 | description: |
| 31 | - "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.", | |
| 25 | + "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.", | |
| 32 | 26 | parameters: { |
| 33 | 27 | type: "object", |
| 34 | 28 | required: ["filepath", "diff"], |
| @@ -47,7 +41,40 @@ | ||
| 47 | 41 | ======= |
| 48 | 42 | [new content to replace with] |
| 49 | 43 | +++++++ REPLACE |
| 50 | -\`\`\``, | |
| 44 | +\`\`\` | |
| 45 | + | |
| 46 | +Critical rules: | |
| 47 | +1. SEARCH content must match the associated file section to find EXACTLY: | |
| 48 | + * Match character-for-character including whitespace, indentation, line endings | |
| 49 | + * Include all comments, docstrings, etc. | |
| 50 | +2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. | |
| 51 | + * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. | |
| 52 | + * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. | |
| 53 | + * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. | |
| 54 | +3. Keep SEARCH/REPLACE blocks concise: | |
| 55 | + * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. | |
| 56 | + * Include just the changing lines, and a few surrounding lines if needed for uniqueness. | |
| 57 | + * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. | |
| 58 | + * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. | |
| 59 | +4. Special operations: | |
| 60 | + * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) | |
| 61 | + * To delete code: Use empty REPLACE section | |
| 62 | + | |
| 63 | +Usage: | |
| 64 | +\`\`\` | |
| 65 | +------- SEARCH | |
| 66 | +[exact content to find] | |
| 67 | +======= | |
| 68 | +[new content to replace with] | |
| 69 | ++++++++ REPLACE | |
| 70 | + | |
| 71 | +------- SEARCH | |
| 72 | +[exact content to find] | |
| 73 | +======= | |
| 74 | +[new content to replace with] | |
| 75 | ++++++++ REPLACE | |
| 76 | + \`\`\` | |
| 77 | +`, | |
| 51 | 78 | }, |
| 52 | 79 | }, |
| 53 | 80 | }, |
modified extensions/vscode/src/apply/ApplyManager.ts +54 −0
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | import * as vscode from "vscode"; |
| 5 | 5 | |
| 6 | 6 | import { ApplyAbortManager } from "core/edit/applyAbortManager"; |
| 7 | +import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; | |
| 8 | +import { generateSearchReplaceDiffLines } from "core/edit/searchAndReplace/generateSearchReplaceDiffLines"; | |
| 7 | 9 | import { VerticalDiffManager } from "../diff/vertical/manager"; |
| 8 | 10 | import { VsCodeIde } from "../VsCodeIde"; |
| 9 | 11 | import { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| @@ -13,6 +15,9 @@ | ||
| 13 | 15 | filepath?: string; |
| 14 | 16 | text: string; |
| 15 | 17 | toolCallId?: string; |
| 18 | + // NEW: Search/replace specific fields | |
| 19 | + searchContent?: string; | |
| 20 | + isSearchReplace?: boolean; | |
| 16 | 21 | } |
| 17 | 22 | |
| 18 | 23 | /** |
| @@ -31,6 +36,8 @@ | ||
| 31 | 36 | filepath, |
| 32 | 37 | text, |
| 33 | 38 | toolCallId, |
| 39 | + searchContent, | |
| 40 | + isSearchReplace, | |
| 34 | 41 | }: ApplyToFileOptions) { |
| 35 | 42 | await this.webviewProtocol.request("updateApplyState", { |
| 36 | 43 | streamId, |
| @@ -49,6 +56,19 @@ | ||
| 49 | 56 | return; |
| 50 | 57 | } |
| 51 | 58 | |
| 59 | + // NEW: Handle search/replace mode | |
| 60 | + if (isSearchReplace && searchContent !== undefined) { | |
| 61 | + await this.handleSearchReplace( | |
| 62 | + activeTextEditor, | |
| 63 | + searchContent, | |
| 64 | + text, // This is the replace content | |
| 65 | + streamId, | |
| 66 | + toolCallId, | |
| 67 | + ); | |
| 68 | + return; | |
| 69 | + } | |
| 70 | + | |
| 71 | + // Existing logic for regular apply | |
| 52 | 72 | const hasExistingDocument = !!activeTextEditor.document.getText().trim(); |
| 53 | 73 | |
| 54 | 74 | if (hasExistingDocument) { |
| @@ -148,6 +168,40 @@ | ||
| 148 | 168 | } |
| 149 | 169 | } |
| 150 | 170 | |
| 171 | + /** | |
| 172 | + * NEW: Handle search and replace operations | |
| 173 | + */ | |
| 174 | + private async handleSearchReplace( | |
| 175 | + editor: vscode.TextEditor, | |
| 176 | + searchContent: string, | |
| 177 | + replaceContent: string, | |
| 178 | + streamId: string, | |
| 179 | + toolCallId?: string, | |
| 180 | + ) { | |
| 181 | + const fileContent = editor.document.getText(); | |
| 182 | + | |
| 183 | + // Find the search content in the file | |
| 184 | + const match = findSearchMatch(fileContent, searchContent); | |
| 185 | + if (!match) { | |
| 186 | + throw new Error(`Search content not found in file:\n${searchContent}`); | |
| 187 | + } | |
| 188 | + | |
| 189 | + // Generate diff lines using our search/replace diff generator | |
| 190 | + const diffLinesGenerator = generateSearchReplaceDiffLines( | |
| 191 | + fileContent, | |
| 192 | + match, | |
| 193 | + replaceContent, | |
| 194 | + ); | |
| 195 | + | |
| 196 | + // Stream through existing VerticalDiffManager infrastructure | |
| 197 | + await this.verticalDiffManager.streamDiffLines( | |
| 198 | + diffLinesGenerator, | |
| 199 | + true, // isInstantApply = true (deterministic, no LLM involved) | |
| 200 | + streamId, | |
| 201 | + toolCallId, | |
| 202 | + ); | |
| 203 | + } | |
| 204 | + | |
| 151 | 205 | /** |
| 152 | 206 | * Creates a prompt for applying code edits |
| 153 | 207 | */ |
added gui/src/util/clientTools/searchReplaceImpl.test.ts +531 −0
| @@ -0,0 +1,531 @@ | ||
| 1 | +import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; | |
| 2 | +import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; | |
| 3 | +import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 4 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 5 | +import { ClientToolExtras } from "./callClientTool"; | |
| 6 | +import { searchReplaceToolImpl } from "./searchReplaceImpl"; | |
| 7 | + | |
| 8 | +// Mock the dependencies | |
| 9 | +vi.mock("core/edit/searchAndReplace/findSearchMatch"); | |
| 10 | +vi.mock("core/edit/searchAndReplace/parseSearchReplaceBlock"); | |
| 11 | +vi.mock("core/util/ideUtils"); | |
| 12 | + | |
| 13 | +const mockFindSearchMatch = vi.mocked(findSearchMatch); | |
| 14 | +const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks); | |
| 15 | +const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir); | |
| 16 | + | |
| 17 | +describe("searchReplaceToolImpl", () => { | |
| 18 | + let mockExtras: ClientToolExtras; | |
| 19 | + let mockIdeMessenger: any; | |
| 20 | + | |
| 21 | + beforeEach(() => { | |
| 22 | + // Reset all mocks | |
| 23 | + vi.clearAllMocks(); | |
| 24 | + | |
| 25 | + // Create mock IDE messenger | |
| 26 | + mockIdeMessenger = { | |
| 27 | + ide: { | |
| 28 | + readFile: vi.fn(), | |
| 29 | + }, | |
| 30 | + request: vi.fn(), | |
| 31 | + }; | |
| 32 | + | |
| 33 | + // Create mock extras | |
| 34 | + mockExtras = { | |
| 35 | + streamId: "test-stream-id", | |
| 36 | + ideMessenger: mockIdeMessenger, | |
| 37 | + getState: vi.fn(), | |
| 38 | + dispatch: vi.fn(), | |
| 39 | + }; | |
| 40 | + }); | |
| 41 | + | |
| 42 | + describe("basic validation", () => { | |
| 43 | + it("should throw error when no streamId is provided", async () => { | |
| 44 | + const extrasWithoutStreamId = { | |
| 45 | + ...mockExtras, | |
| 46 | + streamId: undefined, | |
| 47 | + }; | |
| 48 | + | |
| 49 | + await expect( | |
| 50 | + searchReplaceToolImpl( | |
| 51 | + { filepath: "test.txt", diff: "some diff" }, | |
| 52 | + "tool-call-id", | |
| 53 | + extrasWithoutStreamId, | |
| 54 | + ), | |
| 55 | + ).rejects.toThrow("Invalid apply state - no streamId available"); | |
| 56 | + }); | |
| 57 | + | |
| 58 | + it("should throw error when file does not exist", async () => { | |
| 59 | + mockResolveRelativePathInDir.mockResolvedValue(undefined); | |
| 60 | + | |
| 61 | + await expect( | |
| 62 | + searchReplaceToolImpl( | |
| 63 | + { filepath: "nonexistent.txt", diff: "some diff" }, | |
| 64 | + "tool-call-id", | |
| 65 | + mockExtras, | |
| 66 | + ), | |
| 67 | + ).rejects.toThrow("File nonexistent.txt does not exist"); | |
| 68 | + }); | |
| 69 | + | |
| 70 | + it("should throw error when no search/replace blocks found", async () => { | |
| 71 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 72 | + mockParseAllSearchReplaceBlocks.mockReturnValue([]); | |
| 73 | + | |
| 74 | + await expect( | |
| 75 | + searchReplaceToolImpl( | |
| 76 | + { filepath: "test.txt", diff: "invalid diff content" }, | |
| 77 | + "tool-call-id", | |
| 78 | + mockExtras, | |
| 79 | + ), | |
| 80 | + ).rejects.toThrow("No complete search/replace blocks found"); | |
| 81 | + }); | |
| 82 | + }); | |
| 83 | + | |
| 84 | + describe("single block replacement", () => { | |
| 85 | + it("should successfully apply single search/replace block", async () => { | |
| 86 | + const originalContent = `function hello() { | |
| 87 | + console.log("Hello"); | |
| 88 | + return "world"; | |
| 89 | +}`; | |
| 90 | + | |
| 91 | + const expectedFinalContent = `function hello() { | |
| 92 | + console.log("Hi there!"); | |
| 93 | + return "world"; | |
| 94 | +}`; | |
| 95 | + | |
| 96 | + // Setup mocks | |
| 97 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); | |
| 98 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 99 | + { | |
| 100 | + isComplete: true, | |
| 101 | + searchContent: 'console.log("Hello");', | |
| 102 | + replaceContent: 'console.log("Hi there!");', | |
| 103 | + }, | |
| 104 | + ]); | |
| 105 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 106 | + | |
| 107 | + // Calculate correct positions for 'console.log("Hello");' in the original content | |
| 108 | + const searchText = 'console.log("Hello");'; | |
| 109 | + const startIndex = originalContent.indexOf(searchText); | |
| 110 | + const endIndex = startIndex + searchText.length; | |
| 111 | + | |
| 112 | + mockFindSearchMatch.mockReturnValue({ | |
| 113 | + startIndex, | |
| 114 | + endIndex, | |
| 115 | + }); | |
| 116 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 117 | + | |
| 118 | + const result = await searchReplaceToolImpl( | |
| 119 | + { filepath: "test.js", diff: "mock diff content" }, | |
| 120 | + "tool-call-id", | |
| 121 | + mockExtras, | |
| 122 | + ); | |
| 123 | + | |
| 124 | + // Verify the result | |
| 125 | + expect(result).toEqual({ | |
| 126 | + respondImmediately: false, | |
| 127 | + output: undefined, | |
| 128 | + }); | |
| 129 | + | |
| 130 | + // Verify applyToFile was called with correct parameters | |
| 131 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 132 | + text: expectedFinalContent, | |
| 133 | + streamId: "test-stream-id", | |
| 134 | + filepath: "/resolved/path/test.js", | |
| 135 | + toolCallId: "tool-call-id", | |
| 136 | + }); | |
| 137 | + }); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + describe("multiple block replacement", () => { | |
| 141 | + it("should successfully apply multiple search/replace blocks sequentially", async () => { | |
| 142 | + const originalContent = `const a = 1; | |
| 143 | +const b = 2; | |
| 144 | +const c = 3;`; | |
| 145 | + | |
| 146 | + const expectedFinalContent = `const a = 100; | |
| 147 | +const b = 200; | |
| 148 | +const c = 3;`; | |
| 149 | + | |
| 150 | + // Setup mocks | |
| 151 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); | |
| 152 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 153 | + { | |
| 154 | + isComplete: true, | |
| 155 | + searchContent: "const a = 1;", | |
| 156 | + replaceContent: "const a = 100;", | |
| 157 | + }, | |
| 158 | + { | |
| 159 | + isComplete: true, | |
| 160 | + searchContent: "const b = 2;", | |
| 161 | + replaceContent: "const b = 200;", | |
| 162 | + }, | |
| 163 | + ]); | |
| 164 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 165 | + | |
| 166 | + // Calculate positions for sequential replacements | |
| 167 | + const firstSearchText = "const a = 1;"; | |
| 168 | + const secondSearchText = "const b = 2;"; | |
| 169 | + | |
| 170 | + const firstStartIndex = originalContent.indexOf(firstSearchText); | |
| 171 | + const firstEndIndex = firstStartIndex + firstSearchText.length; | |
| 172 | + | |
| 173 | + // After first replacement: "const a = 100;\nconst b = 2;\nconst c = 3;" | |
| 174 | + const contentAfterFirstReplacement = | |
| 175 | + originalContent.substring(0, firstStartIndex) + | |
| 176 | + "const a = 100;" + | |
| 177 | + originalContent.substring(firstEndIndex); | |
| 178 | + | |
| 179 | + const secondStartIndex = | |
| 180 | + contentAfterFirstReplacement.indexOf(secondSearchText); | |
| 181 | + const secondEndIndex = secondStartIndex + secondSearchText.length; | |
| 182 | + | |
| 183 | + // Mock sequential search matches | |
| 184 | + mockFindSearchMatch | |
| 185 | + .mockReturnValueOnce({ | |
| 186 | + startIndex: firstStartIndex, | |
| 187 | + endIndex: firstEndIndex, | |
| 188 | + }) | |
| 189 | + .mockReturnValueOnce({ | |
| 190 | + startIndex: secondStartIndex, | |
| 191 | + endIndex: secondEndIndex, | |
| 192 | + }); | |
| 193 | + | |
| 194 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 195 | + | |
| 196 | + const result = await searchReplaceToolImpl( | |
| 197 | + { filepath: "test.js", diff: "mock diff content" }, | |
| 198 | + "tool-call-id", | |
| 199 | + mockExtras, | |
| 200 | + ); | |
| 201 | + | |
| 202 | + // Verify the result | |
| 203 | + expect(result).toEqual({ | |
| 204 | + respondImmediately: false, | |
| 205 | + output: undefined, | |
| 206 | + }); | |
| 207 | + | |
| 208 | + // Verify findSearchMatch was called twice with updated content | |
| 209 | + expect(mockFindSearchMatch).toHaveBeenCalledTimes(2); | |
| 210 | + expect(mockFindSearchMatch).toHaveBeenNthCalledWith( | |
| 211 | + 1, | |
| 212 | + originalContent, | |
| 213 | + "const a = 1;", | |
| 214 | + ); | |
| 215 | + expect(mockFindSearchMatch).toHaveBeenNthCalledWith( | |
| 216 | + 2, | |
| 217 | + contentAfterFirstReplacement, | |
| 218 | + "const b = 2;", | |
| 219 | + ); | |
| 220 | + // Verify final applyToFile call | |
| 221 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 222 | + text: expectedFinalContent, | |
| 223 | + streamId: "test-stream-id", | |
| 224 | + filepath: "/resolved/path/test.js", | |
| 225 | + toolCallId: "tool-call-id", | |
| 226 | + }); | |
| 227 | + }); | |
| 228 | + }); | |
| 229 | + | |
| 230 | + describe("deletion scenarios", () => { | |
| 231 | + it("should handle empty replacement (deletion)", async () => { | |
| 232 | + const originalContent = `keep this | |
| 233 | +remove this line | |
| 234 | +keep this too`; | |
| 235 | + | |
| 236 | + const expectedFinalContent = `keep this | |
| 237 | + | |
| 238 | +keep this too`; | |
| 239 | + | |
| 240 | + // Setup mocks | |
| 241 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 242 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 243 | + { | |
| 244 | + isComplete: true, | |
| 245 | + searchContent: "remove this line", | |
| 246 | + replaceContent: "", | |
| 247 | + }, | |
| 248 | + ]); | |
| 249 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 250 | + mockFindSearchMatch.mockReturnValue({ | |
| 251 | + startIndex: 10, // Position of "remove this line" | |
| 252 | + endIndex: 26, // End of "remove this line" | |
| 253 | + }); | |
| 254 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 255 | + | |
| 256 | + const result = await searchReplaceToolImpl( | |
| 257 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 258 | + "tool-call-id", | |
| 259 | + mockExtras, | |
| 260 | + ); | |
| 261 | + | |
| 262 | + expect(result).toEqual({ | |
| 263 | + respondImmediately: false, | |
| 264 | + output: undefined, | |
| 265 | + }); | |
| 266 | + | |
| 267 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 268 | + text: expectedFinalContent, | |
| 269 | + streamId: "test-stream-id", | |
| 270 | + filepath: "/resolved/path/test.txt", | |
| 271 | + toolCallId: "tool-call-id", | |
| 272 | + }); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + it("should handle undefined replaceContent as empty string", async () => { | |
| 276 | + const originalContent = "line1\nline2\nline3"; | |
| 277 | + const expectedFinalContent = "line1\n\nline3"; | |
| 278 | + | |
| 279 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 280 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 281 | + { | |
| 282 | + isComplete: true, | |
| 283 | + searchContent: "line2", | |
| 284 | + replaceContent: undefined, // undefined should be treated as empty string | |
| 285 | + }, | |
| 286 | + ]); | |
| 287 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 288 | + mockFindSearchMatch.mockReturnValue({ | |
| 289 | + startIndex: 6, | |
| 290 | + endIndex: 11, | |
| 291 | + }); | |
| 292 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 293 | + | |
| 294 | + await searchReplaceToolImpl( | |
| 295 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 296 | + "tool-call-id", | |
| 297 | + mockExtras, | |
| 298 | + ); | |
| 299 | + | |
| 300 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 301 | + text: expectedFinalContent, | |
| 302 | + streamId: "test-stream-id", | |
| 303 | + filepath: "/resolved/path/test.txt", | |
| 304 | + toolCallId: "tool-call-id", | |
| 305 | + }); | |
| 306 | + }); | |
| 307 | + }); | |
| 308 | + | |
| 309 | + describe("error handling", () => { | |
| 310 | + it("should throw error when search content is not found", async () => { | |
| 311 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 312 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 313 | + { | |
| 314 | + isComplete: true, | |
| 315 | + searchContent: "nonexistent content", | |
| 316 | + replaceContent: "replacement", | |
| 317 | + }, | |
| 318 | + ]); | |
| 319 | + mockIdeMessenger.ide.readFile.mockResolvedValue("some file content"); | |
| 320 | + mockFindSearchMatch.mockReturnValue(null); // Search content not found | |
| 321 | + | |
| 322 | + await expect( | |
| 323 | + searchReplaceToolImpl( | |
| 324 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 325 | + "tool-call-id", | |
| 326 | + mockExtras, | |
| 327 | + ), | |
| 328 | + ).rejects.toThrow( | |
| 329 | + "Search content not found in block 1:\nnonexistent content", | |
| 330 | + ); | |
| 331 | + }); | |
| 332 | + | |
| 333 | + it("should throw error when search content is not found in second block", async () => { | |
| 334 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 335 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 336 | + { | |
| 337 | + isComplete: true, | |
| 338 | + searchContent: "found content", | |
| 339 | + replaceContent: "replacement1", | |
| 340 | + }, | |
| 341 | + { | |
| 342 | + isComplete: true, | |
| 343 | + searchContent: "missing content", | |
| 344 | + replaceContent: "replacement2", | |
| 345 | + }, | |
| 346 | + ]); | |
| 347 | + mockIdeMessenger.ide.readFile.mockResolvedValue( | |
| 348 | + "found content and other stuff", | |
| 349 | + ); | |
| 350 | + | |
| 351 | + // First search succeeds, second fails | |
| 352 | + mockFindSearchMatch | |
| 353 | + .mockReturnValueOnce({ | |
| 354 | + startIndex: 0, | |
| 355 | + endIndex: 13, | |
| 356 | + }) | |
| 357 | + .mockReturnValueOnce(null); // Second search fails | |
| 358 | + | |
| 359 | + await expect( | |
| 360 | + searchReplaceToolImpl( | |
| 361 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 362 | + "tool-call-id", | |
| 363 | + mockExtras, | |
| 364 | + ), | |
| 365 | + ).rejects.toThrow( | |
| 366 | + "Search content not found in block 2:\nmissing content", | |
| 367 | + ); | |
| 368 | + }); | |
| 369 | + | |
| 370 | + it("should handle file read errors", async () => { | |
| 371 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 372 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 373 | + { | |
| 374 | + isComplete: true, | |
| 375 | + searchContent: "content", | |
| 376 | + replaceContent: "replacement", | |
| 377 | + }, | |
| 378 | + ]); | |
| 379 | + mockIdeMessenger.ide.readFile.mockRejectedValue( | |
| 380 | + new Error("File read error"), | |
| 381 | + ); | |
| 382 | + | |
| 383 | + await expect( | |
| 384 | + searchReplaceToolImpl( | |
| 385 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 386 | + "tool-call-id", | |
| 387 | + mockExtras, | |
| 388 | + ), | |
| 389 | + ).rejects.toThrow("Failed to apply search and replace: File read error"); | |
| 390 | + }); | |
| 391 | + | |
| 392 | + it("should handle applyToFile errors", async () => { | |
| 393 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 394 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 395 | + { | |
| 396 | + isComplete: true, | |
| 397 | + searchContent: "content", | |
| 398 | + replaceContent: "replacement", | |
| 399 | + }, | |
| 400 | + ]); | |
| 401 | + mockIdeMessenger.ide.readFile.mockResolvedValue("content"); | |
| 402 | + mockFindSearchMatch.mockReturnValue({ | |
| 403 | + startIndex: 0, | |
| 404 | + endIndex: 7, | |
| 405 | + }); | |
| 406 | + mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed")); | |
| 407 | + | |
| 408 | + await expect( | |
| 409 | + searchReplaceToolImpl( | |
| 410 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 411 | + "tool-call-id", | |
| 412 | + mockExtras, | |
| 413 | + ), | |
| 414 | + ).rejects.toThrow("Failed to apply search and replace: Apply failed"); | |
| 415 | + }); | |
| 416 | + }); | |
| 417 | + | |
| 418 | + describe("edge cases", () => { | |
| 419 | + it("should handle empty search content", async () => { | |
| 420 | + const originalContent = "existing content"; | |
| 421 | + const expectedFinalContent = "new contentexisting content"; | |
| 422 | + | |
| 423 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 424 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 425 | + { | |
| 426 | + isComplete: true, | |
| 427 | + searchContent: "", | |
| 428 | + replaceContent: "new content", | |
| 429 | + }, | |
| 430 | + ]); | |
| 431 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 432 | + mockFindSearchMatch.mockReturnValue({ | |
| 433 | + startIndex: 0, // Empty search matches at beginning | |
| 434 | + endIndex: 0, | |
| 435 | + }); | |
| 436 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 437 | + | |
| 438 | + await searchReplaceToolImpl( | |
| 439 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 440 | + "tool-call-id", | |
| 441 | + mockExtras, | |
| 442 | + ); | |
| 443 | + | |
| 444 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 445 | + text: expectedFinalContent, | |
| 446 | + streamId: "test-stream-id", | |
| 447 | + filepath: "/resolved/path/test.txt", | |
| 448 | + toolCallId: "tool-call-id", | |
| 449 | + }); | |
| 450 | + }); | |
| 451 | + | |
| 452 | + it("should handle whole file replacement", async () => { | |
| 453 | + const originalContent = "old file content"; | |
| 454 | + const expectedFinalContent = "completely new content"; | |
| 455 | + | |
| 456 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 457 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 458 | + { | |
| 459 | + isComplete: true, | |
| 460 | + searchContent: originalContent, | |
| 461 | + replaceContent: "completely new content", | |
| 462 | + }, | |
| 463 | + ]); | |
| 464 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 465 | + mockFindSearchMatch.mockReturnValue({ | |
| 466 | + startIndex: 0, | |
| 467 | + endIndex: originalContent.length, | |
| 468 | + }); | |
| 469 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 470 | + | |
| 471 | + await searchReplaceToolImpl( | |
| 472 | + { filepath: "test.txt", diff: "mock diff content" }, | |
| 473 | + "tool-call-id", | |
| 474 | + mockExtras, | |
| 475 | + ); | |
| 476 | + | |
| 477 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 478 | + text: expectedFinalContent, | |
| 479 | + streamId: "test-stream-id", | |
| 480 | + filepath: "/resolved/path/test.txt", | |
| 481 | + toolCallId: "tool-call-id", | |
| 482 | + }); | |
| 483 | + }); | |
| 484 | + }); | |
| 485 | + | |
| 486 | + describe("dependency integration", () => { | |
| 487 | + it("should call all dependencies with correct parameters", async () => { | |
| 488 | + const originalContent = "test content"; | |
| 489 | + | |
| 490 | + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 491 | + mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 492 | + { | |
| 493 | + isComplete: true, | |
| 494 | + searchContent: "test", | |
| 495 | + replaceContent: "updated", | |
| 496 | + }, | |
| 497 | + ]); | |
| 498 | + mockIdeMessenger.ide.readFile.mockResolvedValue(originalContent); | |
| 499 | + mockFindSearchMatch.mockReturnValue({ | |
| 500 | + startIndex: 0, | |
| 501 | + endIndex: 4, | |
| 502 | + }); | |
| 503 | + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); | |
| 504 | + | |
| 505 | + await searchReplaceToolImpl( | |
| 506 | + { filepath: "relative/test.txt", diff: "mock diff content" }, | |
| 507 | + "tool-call-id", | |
| 508 | + mockExtras, | |
| 509 | + ); | |
| 510 | + | |
| 511 | + // Verify all dependencies were called correctly | |
| 512 | + expect(mockResolveRelativePathInDir).toHaveBeenCalledWith( | |
| 513 | + "relative/test.txt", | |
| 514 | + mockIdeMessenger.ide, | |
| 515 | + ); | |
| 516 | + expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledWith( | |
| 517 | + "mock diff content", | |
| 518 | + ); | |
| 519 | + expect(mockIdeMessenger.ide.readFile).toHaveBeenCalledWith( | |
| 520 | + "/resolved/path/test.txt", | |
| 521 | + ); | |
| 522 | + expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test"); | |
| 523 | + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { | |
| 524 | + text: "updated content", | |
| 525 | + streamId: "test-stream-id", | |
| 526 | + filepath: "/resolved/path/test.txt", | |
| 527 | + toolCallId: "tool-call-id", | |
| 528 | + }); | |
| 529 | + }); | |
| 530 | + }); | |
| 531 | +}); |
modified gui/src/util/clientTools/searchReplaceImpl.ts +42 −51
| @@ -1,6 +1,5 @@ | ||
| 1 | -import { ContextItem } from "core"; | |
| 2 | 1 | import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; |
| 3 | -import { parseSearchReplaceBlock } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; | |
| 2 | +import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; | |
| 4 | 3 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 5 | 4 | import { ClientToolImpl } from "./callClientTool"; |
| 6 | 5 | |
| @@ -11,6 +10,11 @@ | ||
| 11 | 10 | ) => { |
| 12 | 11 | const { filepath, diff } = args; |
| 13 | 12 | |
| 13 | + // Check if we have a streamId from a pre-existing apply state | |
| 14 | + if (!extras.streamId) { | |
| 15 | + throw new Error("Invalid apply state - no streamId available"); | |
| 16 | + } | |
| 17 | + | |
| 14 | 18 | // Resolve the file path |
| 15 | 19 | const resolvedFilepath = await resolveRelativePathInDir( |
| 16 | 20 | filepath, |
| @@ -20,66 +24,53 @@ | ||
| 20 | 24 | throw new Error(`File ${filepath} does not exist`); |
| 21 | 25 | } |
| 22 | 26 | |
| 23 | - // Parse the search/replace block from the diff content | |
| 24 | - const parseResult = parseSearchReplaceBlock(diff); | |
| 25 | - | |
| 26 | - if (parseResult.error) { | |
| 27 | - throw new Error(`Parse error: ${parseResult.error}`); | |
| 28 | - } | |
| 27 | + // Parse all search/replace blocks from the diff content | |
| 28 | + const blocks = parseAllSearchReplaceBlocks(diff); | |
| 29 | 29 | |
| 30 | - if (!parseResult.isComplete) { | |
| 31 | - throw new Error("Incomplete search/replace block"); | |
| 30 | + if (blocks.length === 0) { | |
| 31 | + throw new Error("No complete search/replace blocks found"); | |
| 32 | 32 | } |
| 33 | 33 | |
| 34 | - const { searchContent, replaceContent } = parseResult; | |
| 35 | - | |
| 36 | 34 | try { |
| 37 | 35 | // Read the current file content |
| 38 | - const fileContent = | |
| 36 | + const originalContent = | |
| 39 | 37 | await extras.ideMessenger.ide.readFile(resolvedFilepath); |
| 40 | - | |
| 41 | - // Find the search match | |
| 42 | - const match = findSearchMatch(fileContent, searchContent || ""); | |
| 43 | - | |
| 44 | - if (!match) { | |
| 45 | - throw new Error(`Search content not found in file:\n${searchContent}`); | |
| 38 | + let currentContent = originalContent; | |
| 39 | + | |
| 40 | + // Apply all replacements sequentially to build the final content | |
| 41 | + for (let i = 0; i < blocks.length; i++) { | |
| 42 | + const block = blocks[i]; | |
| 43 | + const { searchContent, replaceContent } = block; | |
| 44 | + | |
| 45 | + // Find the search content in the current state of the file | |
| 46 | + const match = findSearchMatch(currentContent, searchContent || ""); | |
| 47 | + if (!match) { | |
| 48 | + throw new Error( | |
| 49 | + `Search content not found in block ${i + 1}:\n${searchContent}`, | |
| 50 | + ); | |
| 51 | + } | |
| 52 | + | |
| 53 | + // Apply the replacement | |
| 54 | + currentContent = | |
| 55 | + currentContent.substring(0, match.startIndex) + | |
| 56 | + (replaceContent || "") + | |
| 57 | + currentContent.substring(match.endIndex); | |
| 46 | 58 | } |
| 47 | 59 | |
| 48 | - // Apply the replacement | |
| 49 | - const newContent = | |
| 50 | - fileContent.substring(0, match.startIndex) + | |
| 51 | - (replaceContent || "") + | |
| 52 | - fileContent.substring(match.endIndex); | |
| 53 | - | |
| 54 | - // Write the updated file | |
| 55 | - await extras.ideMessenger.request("writeFile", { | |
| 56 | - path: resolvedFilepath, | |
| 57 | - contents: newContent, | |
| 60 | + // Single applyToFile call with all accumulated changes | |
| 61 | + // Use regular apply mode (not search/replace mode) to leverage existing diff logic | |
| 62 | + await extras.ideMessenger.request("applyToFile", { | |
| 63 | + text: currentContent, | |
| 64 | + streamId: extras.streamId, | |
| 65 | + filepath: resolvedFilepath, | |
| 66 | + toolCallId, | |
| 67 | + // Don't use search/replace mode since we're providing the complete final content | |
| 58 | 68 | }); |
| 59 | 69 | |
| 60 | - // Create context item showing the change | |
| 61 | - const contextItem: ContextItem = { | |
| 62 | - name: `Modified ${filepath}`, | |
| 63 | - description: `Applied search and replace to ${filepath}`, | |
| 64 | - content: `Search and replace operation completed successfully. | |
| 65 | - | |
| 66 | -Search content: | |
| 67 | -\`\`\` | |
| 68 | -${searchContent} | |
| 69 | -\`\`\` | |
| 70 | - | |
| 71 | -Replace content: | |
| 72 | -\`\`\` | |
| 73 | -${replaceContent} | |
| 74 | -\`\`\` | |
| 75 | - | |
| 76 | -File: ${filepath}`, | |
| 77 | - editing: true, | |
| 78 | - }; | |
| 79 | - | |
| 70 | + // Return success - applyToFile will handle the completion state | |
| 80 | 71 | return { |
| 81 | - respondImmediately: true, | |
| 82 | - output: [contextItem], | |
| 72 | + respondImmediately: false, // Let apply state handle completion | |
| 73 | + output: undefined, | |
| 83 | 74 | }; |
| 84 | 75 | } catch (error) { |
| 85 | 76 | throw new Error( |
deleted keycaps-todo.md +0 −15
| @@ -1,15 +0,0 @@ | ||
| 1 | -gui\src\components\mainInput\TutorialCard.tsx | |
| 2 | - | |
| 3 | - | |
| 4 | - | |
| 5 | - | |
| 6 | - | |
| 7 | -gui\src\components\modelSelection\ModelSelect.tsx | |
| 8 | - | |
| 9 | - | |
| 10 | - | |
| 11 | - | |
| 12 | - | |
| 13 | -gui\src\components\modelSelection\platform\AssistantSelect.tsx | |
| 14 | - | |
| 15 | -??? |