diff --git a/.github/workflows/cla.yaml b/.github/workflows/cla.yaml index 5d5ce3933..225439ced 100644 --- a/.github/workflows/cla.yaml +++ b/.github/workflows/cla.yaml @@ -24,7 +24,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: path-to-signatures: "signatures/version1/cla.json" - path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md" + path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md" branch: cla-signatures # Bots and CLAs signed outside of GitHub allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline diff --git a/CLA.md b/CLA.md new file mode 100644 index 000000000..a23e12a1e --- /dev/null +++ b/CLA.md @@ -0,0 +1,48 @@ +# Individual Contributor License Agreement (v1.0, Continue) + +_Based on the Apache Software Foundation Individual CLA v 2.2._ + +By commenting **“I have read the CLA Document and I hereby sign the CLA”** +on a Pull Request, **you (“Contributor”) agree to the following terms** for any +past and future “Contributions” submitted to **Continue (the “Project”)**. + +--- + +## 1. Definitions + +- **“Contribution”** – any original work of authorship submitted to the Project + (code, documentation, designs, etc.). +- **“You” / “Your”** – the individual (or legal entity) posting the acceptance + comment. + +## 2. Copyright License + +You grant **Continue Dev, Inc.** and all recipients of software distributed by the +Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable +license to reproduce, prepare derivative works of, publicly display, publicly +perform, sublicense, and distribute Your Contributions and derivative works. + +## 3. Patent License + +You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual, +worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent +license to make, have made, use, sell, offer to sell, import, and otherwise +transfer Your Contributions alone or in combination with the Project. + +If any entity brings patent litigation alleging that the Project or a +Contribution infringes a patent, the patent licenses granted by You to that +entity under this CLA terminate. + +## 4. Representations + +1. You are legally entitled to grant the licenses above. +2. Each Contribution is either Your original creation or You have authority to + submit it under this CLA. +3. Your Contributions are provided **“AS IS”** without warranties of any kind. +4. You will notify the Project if any statement above becomes inaccurate. + +## 5. Miscellany + +This Agreement is governed by the laws of the **State of California**, USA, +excluding its conflict‑of‑laws rules. If any provision is held unenforceable, +the remaining provisions remain in force. diff --git a/core/codeRenderer/CodeRenderer.ts b/core/codeRenderer/CodeRenderer.ts index 576088ca2..057695405 100644 --- a/core/codeRenderer/CodeRenderer.ts +++ b/core/codeRenderer/CodeRenderer.ts @@ -9,9 +9,7 @@ * creating a render of it. */ import { - transformerMetaHighlight, transformerNotationDiff, - transformerNotationFocus, transformerNotationHighlight, } from "@shikijs/transformers"; import { JSDOM } from "jsdom"; @@ -21,6 +19,7 @@ import { getSingletonHighlighter, Highlighter, } from "shiki"; +import { DiffLine } from ".."; import { escapeForSVG, kebabOfStr } from "../util/text"; interface CodeRendererOptions { @@ -37,6 +36,10 @@ interface HTMLOptions { interface ConversionOptions extends HTMLOptions { transparent?: boolean; imageType: "svg"; + fontSize: number; + fontFamily: string; + dimensions: Dimensions; + lineHeight: number; } interface Dimensions { @@ -166,83 +169,102 @@ export class CodeRenderer { code: string, language: string = "javascript", currLineOffsetFromTop: number, + newDiffLines: DiffLine[], ): Promise { - const annotatedCode = code - .split("\n") - .map((line, i) => - i === currLineOffsetFromTop - ? line + " \/\/ \[\!code highlight\]" - : line, - ) - .join("\n"); + const lines = code.split("\n"); + const newDiffLineMap = new Set(); + + if (newDiffLines) { + newDiffLines.forEach((diffLine) => { + if (diffLine.type === "new") { + newDiffLineMap.add(diffLine.line); + } + }); + } + + const annotatedLines = []; + + // NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line. + // If you are transforming an empty line, make sure that + // the transformation is applied to a non-empty line first. + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Add highlight comment before target line. + if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) { + annotatedLines.push("// [!code highlight:1]"); + } + + // Handle diff lines + if (newDiffLineMap.has(line)) { + if (line.trim() === "") { + // For empty lines, add the magic comment on a separate line before. + annotatedLines.push("// [!code ++]"); + annotatedLines.push(line); // The empty line itself. + } else { + // For non-empty lines, append the magic comment. + annotatedLines.push(line + "// [!code ++]"); + } + newDiffLineMap.delete(line); + } else { + annotatedLines.push(line); + } + } + + const annotatedCode = annotatedLines.join("\n"); await this.highlighter!.loadLanguage(language as BundledLanguage); - return this.highlighter!.codeToHtml(annotatedCode, { lang: language, theme: this.currentTheme, - transformers: [ - // transformerColorizedBrackets(), - transformerMetaHighlight(), - transformerNotationHighlight(), - transformerNotationDiff(), - transformerNotationFocus(), - ], + transformers: [transformerNotationHighlight(), transformerNotationDiff()], }); } async convertToSVG( code: string, language: string = "javascript", - fontSize: number, - fontFamily: string, - dimensions: Dimensions, - lineHeight: number, options: ConversionOptions, currLineOffsetFromTop: number, + newDiffLines: DiffLine[], ): Promise { const strokeWidth = 1; const highlightedCodeHtml = await this.highlightCode( code, language, currLineOffsetFromTop, + newDiffLines, ); // console.log(highlightedCodeHtml); const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut( highlightedCodeHtml, - fontSize, - fontFamily, - lineHeight, - dimensions, + options, ); const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); - const svg = ` - - - - ${lineBackgrounds} - ${guts} - -`; - console.log(svg); + const svg = ` + + + + ${lineBackgrounds} + ${guts} + + `; + // console.log(svg); return Buffer.from(svg, "utf8"); } convertShikiHtmlToSvgGut( shikiHtml: string, - fontSize: number, - fontFamily: string, - lineHeight: number, - dimensions: Dimensions, + options: ConversionOptions, ): { guts: string; lineBackgrounds: string } { const dom = new JSDOM(shikiHtml); const document = dom.window.document; @@ -263,6 +285,7 @@ export class CodeRenderer { if (classes.includes("highlighted")) { fill = ` fill="${this.editorLineHighlight}"`; } + const content = el.textContent || ""; return `${escapeForSVG(content)}`; }) @@ -278,8 +301,8 @@ export class CodeRenderer { // The first step is to add lineHeight / 2 to move the axis down. // The second step is to add 'dominant-baseline="central"' to vertically center the text. // Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable! - const y = index * lineHeight + lineHeight / 2; - return `${spans}`; + const y = index * options.lineHeight + options.lineHeight / 2; + return `${spans}`; }); const lineBackgrounds = lines @@ -287,8 +310,11 @@ export class CodeRenderer { const classes = line?.getAttribute("class") || ""; const bgColor = classes.includes("highlighted") ? this.editorLineHighlight - : this.editorBackground; - const y = index * lineHeight; + : classes.includes("diff add") + ? "rgba(255, 255, 0, 0.2)" + : this.editorBackground; + + const y = index * options.lineHeight; const isFirst = index === 0; const isLast = index === lines.length - 1; const radius = 10; @@ -297,24 +323,24 @@ export class CodeRenderer { // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps. // Turning it off with 'shape-rendering="crispEdges"' solves the issue. return isFirst - ? `` + ? `` : isLast - ? `` - : ``; + ? `` + : ``; }) .join("\n"); @@ -344,12 +370,9 @@ export class CodeRenderer { async getDataUri( code: string, language: string = "javascript", - fontSize: number, - fontFamily: string, - dimensions: Dimensions, - lineHeight: number, options: ConversionOptions, currLineOffsetFromTop: number, + newDiffLines: DiffLine[], ): Promise { switch (options.imageType) { // case "png": @@ -366,12 +389,9 @@ export class CodeRenderer { const svgBuffer = await this.convertToSVG( code, language, - fontSize, - fontFamily, - dimensions, - lineHeight, options, currLineOffsetFromTop, + newDiffLines, ); return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; } diff --git a/core/core.ts b/core/core.ts index 56270f2cd..57ce98d97 100644 --- a/core/core.ts +++ b/core/core.ts @@ -495,6 +495,18 @@ export class Core { }); on("llm/listModels", this.handleListModels.bind(this)); + on("llm/compileChat", async (msg) => { + const { messages, options } = msg.data; + const model = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } + + return model.compileChatMessages(messages, options); + }); + // Provide messenger to utils so they can interact with GUI + state TTS.messenger = this.messenger; ChatDescriber.messenger = this.messenger; diff --git a/core/diff/myers.ts b/core/diff/myers.ts index 0b5d23730..b39ddccf3 100644 --- a/core/diff/myers.ts +++ b/core/diff/myers.ts @@ -1,6 +1,6 @@ -import { diffLines, type Change } from "diff"; +import { diffChars, diffLines, type Change } from "diff"; -import { DiffLine } from ".."; +import { DiffChar, DiffLine } from ".."; export function convertMyersChangeToDiffLines(change: Change): DiffLine[] { const type: DiffLine["type"] = change.added @@ -55,3 +55,157 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] { return ourFormat; } + +export function myersCharDiff( + oldContent: string, + newContent: string, +): DiffChar[] { + // Process the content character by character. + // We will handle newlines separately, + // because diffChars does not have an option to ignore eol newlines. + const theirFormat = diffChars(oldContent, newContent); + + // Track indices as we process the diff. + let oldIndex = 0; + let newIndex = 0; + let oldLineIndex = 0; + let newLineIndex = 0; + let oldCharIndexInLine = 0; + let newCharIndexInLine = 0; + + const result: DiffChar[] = []; + + for (const change of theirFormat) { + // Split the change value by newlines to handle them separately. + if (change.value.includes("\n")) { + const parts = change.value.split(/(\n)/g); // This keeps the newlines as separate entries. + + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (part === "") continue; + + if (part === "\n") { + // Handle newline. + if (change.added) { + result.push({ + type: "new", + char: part, + newIndex: newIndex, + newLineIndex: newLineIndex, + newCharIndexInLine: newCharIndexInLine, + }); + newIndex += part.length; + newLineIndex++; + newCharIndexInLine = 0; // Reset when moving to a new line. + } else if (change.removed) { + result.push({ + type: "old", + char: part, + oldIndex: oldIndex, + oldLineIndex: oldLineIndex, + oldCharIndexInLine: oldCharIndexInLine, + }); + oldIndex += part.length; + oldLineIndex++; + oldCharIndexInLine = 0; // Reset when moving to a new line. + } else { + result.push({ + type: "same", + char: part, + oldIndex: oldIndex, + newIndex: newIndex, + oldLineIndex: oldLineIndex, + newLineIndex: newLineIndex, + oldCharIndexInLine: oldCharIndexInLine, + newCharIndexInLine: newCharIndexInLine, + }); + oldIndex += part.length; + newIndex += part.length; + oldLineIndex++; + newLineIndex++; + oldCharIndexInLine = 0; + newCharIndexInLine = 0; + } + } else { + // Handle regular text. + if (change.added) { + result.push({ + type: "new", + char: part, + newIndex: newIndex, + newLineIndex: newLineIndex, + newCharIndexInLine: newCharIndexInLine, + }); + newIndex += part.length; + newCharIndexInLine += part.length; + } else if (change.removed) { + result.push({ + type: "old", + char: part, + oldIndex: oldIndex, + oldLineIndex: oldLineIndex, + oldCharIndexInLine: oldCharIndexInLine, + }); + oldIndex += part.length; + oldCharIndexInLine += part.length; + } else { + result.push({ + type: "same", + char: part, + oldIndex: oldIndex, + newIndex: newIndex, + oldLineIndex: oldLineIndex, + newLineIndex: newLineIndex, + oldCharIndexInLine: oldCharIndexInLine, + newCharIndexInLine: newCharIndexInLine, + }); + oldIndex += part.length; + newIndex += part.length; + oldCharIndexInLine += part.length; + newCharIndexInLine += part.length; + } + } + } + } else { + // No newlines, handle as a simple change. + if (change.added) { + result.push({ + type: "new", + char: change.value, + newIndex: newIndex, + newLineIndex: newLineIndex, + newCharIndexInLine: newCharIndexInLine, + }); + newIndex += change.value.length; + newCharIndexInLine += change.value.length; + } else if (change.removed) { + result.push({ + type: "old", + char: change.value, + oldIndex: oldIndex, + oldLineIndex: oldLineIndex, + oldCharIndexInLine: oldCharIndexInLine, + }); + oldIndex += change.value.length; + oldCharIndexInLine += change.value.length; + } else { + result.push({ + type: "same", + char: change.value, + oldIndex: oldIndex, + newIndex: newIndex, + oldLineIndex: oldLineIndex, + newLineIndex: newLineIndex, + oldCharIndexInLine: oldCharIndexInLine, + newCharIndexInLine: newCharIndexInLine, + }); + oldIndex += change.value.length; + newIndex += change.value.length; + oldCharIndexInLine += change.value.length; + newCharIndexInLine += change.value.length; + } + } + } + + return result; +} diff --git a/core/diff/myers.vitest.ts b/core/diff/myers.vitest.ts index a5902142a..6c2168bc0 100644 --- a/core/diff/myers.vitest.ts +++ b/core/diff/myers.vitest.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest"; import { dedent } from "../util"; -import { myersDiff } from "./myers"; +import { myersCharDiff, myersDiff } from "./myers"; describe("Test myers diff function", () => { test("should ...", () => { @@ -56,3 +56,589 @@ describe("Test myers diff function", () => { ]); }); }); + +describe("Test myersCharDiff function on the same line", () => { + test("should differentiate character changes", () => { + const oldContent = "hello world"; + const newContent = "hello earth"; + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "hello ", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "wo", + oldIndex: 6, + oldCharIndexInLine: 6, + oldLineIndex: 0, + }, + { + type: "new", + char: "ea", + newIndex: 6, + newCharIndexInLine: 6, + newLineIndex: 0, + }, + { + type: "same", + char: "r", + oldIndex: 8, + newIndex: 8, + oldCharIndexInLine: 8, + newCharIndexInLine: 8, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "ld", + oldIndex: 9, + oldCharIndexInLine: 9, + oldLineIndex: 0, + }, + { + type: "new", + char: "th", + newIndex: 9, + newCharIndexInLine: 9, + newLineIndex: 0, + }, + ]); + }); + + test("should handle insertions", () => { + const oldContent = "abc"; + const newContent = "abxyzc"; + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "ab", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "new", + char: "xyz", + newIndex: 2, + newCharIndexInLine: 2, + newLineIndex: 0, + }, + { + type: "same", + char: "c", + oldIndex: 2, + newIndex: 5, + oldCharIndexInLine: 2, + newCharIndexInLine: 5, + oldLineIndex: 0, + newLineIndex: 0, + }, + ]); + }); + + test("should handle deletions", () => { + const oldContent = "abxyzc"; + const newContent = "abc"; + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "ab", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "xyz", + oldIndex: 2, + oldCharIndexInLine: 2, + oldLineIndex: 0, + }, + { + type: "same", + char: "c", + oldIndex: 5, + newIndex: 2, + oldCharIndexInLine: 5, + newCharIndexInLine: 2, + oldLineIndex: 0, + newLineIndex: 0, + }, + ]); + }); + + test("should handle empty strings", () => { + const oldContent = ""; + const newContent = "abc"; + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "new", + char: "abc", + newIndex: 0, + newCharIndexInLine: 0, + newLineIndex: 0, + }, + ]); + }); + + test("should handle identical strings", () => { + const content = "no changes here"; + + const diffChars = myersCharDiff(content, content); + expect(diffChars).toEqual([ + { + type: "same", + char: "no changes here", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + ]); + }); + + test("should handle whitespace changes", () => { + const oldContent = "hello world"; + const newContent = "hello world"; + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "hello ", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "new", + char: " ", + newIndex: 6, + newCharIndexInLine: 6, + newLineIndex: 0, + }, + { + type: "same", + char: "world", + oldIndex: 6, + newIndex: 7, + oldCharIndexInLine: 6, + newCharIndexInLine: 7, + oldLineIndex: 0, + newLineIndex: 0, + }, + ]); + }); + + test("should handle complex changes", () => { + const oldContent = "The quick brown fox jumps over the lazy dog"; + const newContent = "The fast brown fox leaps over the sleeping dog"; + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "The ", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "quick", + oldIndex: 4, + oldCharIndexInLine: 4, + oldLineIndex: 0, + }, + { + type: "new", + char: "fast", + newIndex: 4, + newCharIndexInLine: 4, + newLineIndex: 0, + }, + { + type: "same", + char: " brown fox ", + oldIndex: 9, + newIndex: 8, + oldCharIndexInLine: 9, + newCharIndexInLine: 8, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "jum", + oldIndex: 20, + oldCharIndexInLine: 20, + oldLineIndex: 0, + }, + { + type: "new", + char: "lea", + newIndex: 19, + newCharIndexInLine: 19, + newLineIndex: 0, + }, + { + type: "same", + char: "ps over the ", + oldIndex: 23, + newIndex: 22, + oldCharIndexInLine: 23, + newCharIndexInLine: 22, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "new", + char: "s", + newIndex: 34, + newCharIndexInLine: 34, + newLineIndex: 0, + }, + { + type: "same", + char: "l", + oldIndex: 35, + newIndex: 35, + oldCharIndexInLine: 35, + newCharIndexInLine: 35, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "azy", + oldIndex: 36, + oldCharIndexInLine: 36, + oldLineIndex: 0, + }, + { + type: "new", + char: "eeping", + newIndex: 36, + newCharIndexInLine: 36, + newLineIndex: 0, + }, + { + type: "same", + char: " dog", + oldIndex: 39, + newIndex: 42, + oldCharIndexInLine: 39, + newCharIndexInLine: 42, + oldLineIndex: 0, + newLineIndex: 0, + }, + ]); + }); +}); + +describe("Test myersCharDiff function on different lines", () => { + test("should track line indices for multi-line changes", () => { + const oldContent = ["Line one", "Line two", "Line three"].join("\n"); + + const newContent = ["Line one", "Modified line", "Line three"].join("\n"); + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "Line one", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "same", + char: "\n", + oldIndex: 8, + newIndex: 8, + oldCharIndexInLine: 8, + newCharIndexInLine: 8, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "L", + oldIndex: 9, + oldCharIndexInLine: 0, + oldLineIndex: 1, + }, + { + type: "new", + char: "Mod", + newIndex: 9, + newCharIndexInLine: 0, + newLineIndex: 1, + }, + { + char: "i", + newCharIndexInLine: 3, + newIndex: 12, + newLineIndex: 1, + oldCharIndexInLine: 1, + oldIndex: 10, + oldLineIndex: 1, + type: "same", + }, + { + char: "n", + oldCharIndexInLine: 2, + oldIndex: 11, + oldLineIndex: 1, + type: "old", + }, + { + char: "fi", + newCharIndexInLine: 4, + newIndex: 13, + newLineIndex: 1, + type: "new", + }, + { + char: "e", + newCharIndexInLine: 6, + newIndex: 15, + newLineIndex: 1, + oldCharIndexInLine: 3, + oldIndex: 12, + oldLineIndex: 1, + type: "same", + }, + { + char: "d", + newCharIndexInLine: 7, + newIndex: 16, + newLineIndex: 1, + type: "new", + }, + { + char: " ", + newCharIndexInLine: 8, + newIndex: 17, + newLineIndex: 1, + oldCharIndexInLine: 4, + oldIndex: 13, + oldLineIndex: 1, + type: "same", + }, + { + type: "old", + char: "two", + oldCharIndexInLine: 5, + oldIndex: 14, + oldLineIndex: 1, + }, + { + type: "new", + char: "line", + newCharIndexInLine: 9, + newIndex: 18, + newLineIndex: 1, + }, + { + type: "same", + char: "\n", + oldIndex: 17, + oldCharIndexInLine: 8, + oldLineIndex: 1, + newIndex: 22, + newCharIndexInLine: 13, + newLineIndex: 1, + }, + { + type: "same", + char: "Line three", + oldIndex: 18, + newIndex: 23, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 2, + newLineIndex: 2, + }, + ]); + }); + + test("should track line indices when adding new lines", () => { + const oldContent = ["First line", "Last line"].join("\n"); + + const newContent = [ + "First line", + "Middle line", + "Another middle", + "Last line", + ].join("\n"); + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "First line", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "same", + char: "\n", + oldIndex: 10, + newIndex: 10, + oldCharIndexInLine: 10, + newCharIndexInLine: 10, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "new", + char: "Middle line", + newIndex: 11, + newCharIndexInLine: 0, + newLineIndex: 1, + }, + { + type: "new", + char: "\n", + newIndex: 22, + newCharIndexInLine: 11, + newLineIndex: 1, + }, + { + type: "new", + char: "Another middle", + newCharIndexInLine: 0, + newIndex: 23, + newLineIndex: 2, + }, + { + type: "new", + char: "\n", + newCharIndexInLine: 14, + newIndex: 37, + newLineIndex: 2, + }, + { + type: "same", + char: "Last line", + oldIndex: 11, + oldCharIndexInLine: 0, + oldLineIndex: 1, + newIndex: 38, + newCharIndexInLine: 0, + newLineIndex: 3, + }, + ]); + }); + + test("should track line indices when removing lines", () => { + const oldContent = [ + "Start", + "Line to remove", + "Another to remove", + "End", + ].join("\n"); + + const newContent = ["Start", "End"].join("\n"); + + const diffChars = myersCharDiff(oldContent, newContent); + expect(diffChars).toEqual([ + { + type: "same", + char: "Start", + oldIndex: 0, + newIndex: 0, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "same", + char: "\n", + oldIndex: 5, + newIndex: 5, + oldCharIndexInLine: 5, + newCharIndexInLine: 5, + oldLineIndex: 0, + newLineIndex: 0, + }, + { + type: "old", + char: "Line to remove", + oldIndex: 6, + oldCharIndexInLine: 0, + oldLineIndex: 1, + }, + { + type: "old", + char: "\n", + oldCharIndexInLine: 14, + oldIndex: 20, + oldLineIndex: 1, + }, + { + type: "old", + char: "Another to remove", + oldCharIndexInLine: 0, + oldIndex: 21, + oldLineIndex: 2, + }, + { + type: "old", + char: "\n", + oldCharIndexInLine: 17, + oldIndex: 38, + oldLineIndex: 2, + }, + { + type: "same", + char: "End", + oldIndex: 39, + newIndex: 6, + oldCharIndexInLine: 0, + newCharIndexInLine: 0, + oldLineIndex: 3, + newLineIndex: 1, + }, + ]); + }); +}); diff --git a/core/diff/streamDiff.ts b/core/diff/streamDiff.ts index 436da1c09..6f8911679 100644 --- a/core/diff/streamDiff.ts +++ b/core/diff/streamDiff.ts @@ -1,4 +1,4 @@ -import { DiffLine, DiffLineType } from "../index.js"; +import { DiffLine, DiffType } from "../index.js"; import { LineStream, matchLine } from "./util.js"; @@ -33,7 +33,7 @@ export async function* streamDiff( seenIndentationMistake = true; } - let type: DiffLineType; + let type: DiffType; const isNewLine = matchIndex === -1; diff --git a/core/diff/streamDiff.vitest.ts b/core/diff/streamDiff.vitest.ts index 57c6e77f1..dbd329db1 100644 --- a/core/diff/streamDiff.vitest.ts +++ b/core/diff/streamDiff.vitest.ts @@ -6,11 +6,11 @@ import { describe, expect, test } from "vitest"; // @ts-ignore no typings available import { changed, diff as myersDiff } from "myers-diff"; import { streamDiff } from "../diff/streamDiff.js"; -import { DiffLine, DiffLineType } from "../index.js"; +import { DiffLine, DiffType } from "../index.js"; import { generateLines } from "./util.js"; // "modification" is an extra type used to represent an "old" + "new" diff line -type MyersDiffTypes = Extract | "modification"; +type MyersDiffTypes = Extract | "modification"; const UNIFIED_DIFF_SYMBOLS = { same: "", diff --git a/core/index.d.ts b/core/index.d.ts index 094d5b69f..92ad04dfb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -122,6 +122,7 @@ export interface ILLM messages: ChatMessage[], signal: AbortSignal, options?: LLMFullCompletionOptions, + messageOptions?: MessageOption, ): AsyncGenerator; chat( @@ -130,6 +131,11 @@ export interface ILLM options?: LLMFullCompletionOptions, ): Promise; + compileChatMessages( + messages: ChatMessage[], + options: LLMFullCompletionOpeions, + ): CompiledChatMessagesReport; + embed(chunks: string[]): Promise; rerank(query: string, chunks: Chunk[]): Promise; @@ -666,13 +672,26 @@ export type CustomLLM = RequireAtLeastOne< // IDE -export type DiffLineType = "new" | "old" | "same"; +export type DiffType = "new" | "old" | "same"; -export interface DiffLine { - type: DiffLineType; +export interface DiffObject { + type: DiffType; +} + +export interface DiffLine extends DiffObject { line: string; } +interface DiffChar extends DiffObject { + char: string; + oldIndex?: number; // Character index assuming a flattened line string. + newIndex?: number; + oldCharIndexInLine?: number; // Character index assuming new lines reset the character index to 0. + newCharIndexInLine?: number; + oldLineIndex?: number; + newLineIndex?: number; +} + export interface Problem { filepath: string; range: Range; @@ -1669,3 +1688,24 @@ export interface CompleteOnboardingPayload { provider?: string; apiKey?: string; } + +export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned"; + +export interface CompiledMessagesResult { + compiledChatMessages: ChatMessage[]; + pruningStatus: PruningStatus; +} + +export interface MessageOption { + precompiled: boolean; +} + +export type WarningMessageLevel = "warning" | "fatal"; + +export type WarningCategory = "exceeded-context-length" | "deleted-last-input"; + +export interface WarningMessage { + message: string; + level: WarningMessageLevel; + category: WarningCategory; +} diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index f2a31209c..63822bea9 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -1,3 +1,5 @@ +/* eslint-disable max-lines-per-function */ +/* lint is not useful for test classes */ import { jest } from "@jest/globals"; import { execSync } from "node:child_process"; import fs from "node:fs"; @@ -14,8 +16,11 @@ import { } from "../test/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; +import { ConfigResult } from "@continuedev/config-yaml"; +import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js"; +import { ContinueConfig } from "../index.js"; import { localPathToUri } from "../util/pathToUri.js"; -import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; +import { CodebaseIndexer } from "./CodebaseIndexer.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; import { CodebaseIndex } from "./types.js"; @@ -57,6 +62,17 @@ class TestCodebaseIndexer extends CodebaseIndexer { protected async getIndexesToBuild(): Promise { return [new TestCodebaseIndex()]; } + + // Add public methods to test private methods + public testHasCodebaseContextProvider() { + return (this as any).hasCodebaseContextProvider(); + } + + public async testHandleConfigUpdate( + configResult: ConfigResult, + ) { + return (this as any).handleConfigUpdate({ config: configResult.config }); + } } // Create a mock messenger type that doesn't require actual protocol imports @@ -71,8 +87,6 @@ type MockMessengerType = { // These are more like integration tests, whereas we should separately test // the individual CodebaseIndex classes describe("CodebaseIndexer", () => { - const pauseToken = new PauseToken(false); - // Replace mockProgressReporter with mockMessenger const mockMessenger: MockMessengerType = { send: jest.fn(), @@ -82,13 +96,8 @@ describe("CodebaseIndexer", () => { onError: jest.fn(), }; - const codebaseIndexer = new TestCodebaseIndexer( - testConfigHandler, - testIde, - mockMessenger as any, - false, - ); - const testIndex = new TestCodebaseIndex(); + let codebaseIndexer: TestCodebaseIndexer; + let testIndex: TestCodebaseIndex; beforeAll(async () => { tearDownTestDir(); @@ -99,6 +108,15 @@ describe("CodebaseIndexer", () => { cwd: TEST_DIR_PATH, }); execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH }); + + codebaseIndexer = new TestCodebaseIndexer( + testConfigHandler, + testIde, + mockMessenger as any, + false, + ); + await codebaseIndexer.initPromise; + testIndex = new TestCodebaseIndex(); }); afterAll(async () => { @@ -161,6 +179,7 @@ describe("CodebaseIndexer", () => { } test("should index test folder without problem", async () => { + walkDirCache.invalidate(); addToTestDir([ ["test.ts", TEST_TS], ["py/main.py", TEST_PY], @@ -403,4 +422,270 @@ describe("CodebaseIndexer", () => { expect(codebaseIndexer.currentIndexingState).toEqual(testState); }); }); + + // New describe block for testing handleConfigUpdate functionality + describe("handleConfigUpdate functionality", () => { + let testIndexer: TestCodebaseIndexer; + let mockRefreshCodebaseIndex: jest.MockedFunction; + let mockGetWorkspaceDirs: jest.MockedFunction; + + beforeEach(() => { + testIndexer = new TestCodebaseIndexer( + testConfigHandler, + testIde, + mockMessenger as any, + false, + ); + + // Mock the refreshCodebaseIndex method to avoid actual indexing + mockRefreshCodebaseIndex = jest + .spyOn(testIndexer, "refreshCodebaseIndex") + .mockImplementation(async () => {}); + + // Mock getWorkspaceDirs to return test directories + mockGetWorkspaceDirs = jest + .spyOn(testIde, "getWorkspaceDirs") + .mockResolvedValue(["/test/workspace"]); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe("hasCodebaseContextProvider", () => { + test("should return true when codebase context provider is present", () => { + // Set up config with codebase context provider + (testIndexer as any).config = { + contextProviders: [ + { + description: { + title: CodebaseContextProvider.description.title, + }, + }, + ], + }; + + const result = testIndexer.testHasCodebaseContextProvider(); + expect(result).toBe(true); + }); + + test("should return false when no context providers are configured", () => { + (testIndexer as any).config = { + contextProviders: undefined, + }; + + const result = testIndexer.testHasCodebaseContextProvider(); + expect(result).toBe(false); + }); + + test("should return false when context providers exist but no codebase provider", () => { + (testIndexer as any).config = { + contextProviders: [ + { + description: { + title: "SomeOtherProvider", + }, + }, + ], + }; + + const result = testIndexer.testHasCodebaseContextProvider(); + expect(result).toBe(false); + }); + + test("should return false when context providers is empty array", () => { + (testIndexer as any).config = { + contextProviders: [], + }; + + const result = testIndexer.testHasCodebaseContextProvider(); + expect(result).toBe(false); + }); + }); + + describe("handleConfigUpdate", () => { + test("should return early when newConfig is null", async () => { + const configResult: ConfigResult = { + config: null as any, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // These get called once on init, so we want them to not get called again + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); + }); + + test("should return early when newConfig is undefined", async () => { + const configResult: ConfigResult = { + config: undefined as any, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // These get called once on init, so we want them to not get called again + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); + }); + + test("should return early when no codebase context provider is present", async () => { + const configResult: ConfigResult = { + config: { + contextProviders: [ + { + description: { + title: "SomeOtherProvider", + }, + }, + ], + selectedModelByRole: { + embed: { + model: "test-model", + provider: "test-provider", + }, + }, + } as unknown as ContinueConfig, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // These get called once on init, so we want them to not get called again + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); + }); + + test("should return early when no embed model is configured", async () => { + const configResult: ConfigResult = { + config: { + contextProviders: [ + { + description: { + title: CodebaseContextProvider.description.title, + }, + }, + ], + selectedModelByRole: { + embed: undefined, + }, + } as unknown as ContinueConfig, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // These get called once on init, so we want them to not get called again + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1); + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1); + }); + + test("should call refreshCodebaseIndex when all conditions are met", async () => { + const configResult: ConfigResult = { + config: { + contextProviders: [ + { + description: { + title: CodebaseContextProvider.description.title, + }, + }, + ], + selectedModelByRole: { + embed: { + model: "test-model", + provider: "test-provider", + }, + }, + } as unknown as ContinueConfig, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // These get called once on init, and we want them to get called again + expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2); + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2); + expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([ + "/test/workspace", + ]); + }); + + test("should set config property before checking conditions", async () => { + const testConfig = { + contextProviders: [ + { + description: { + title: CodebaseContextProvider.description.title, + }, + }, + ], + selectedModelByRole: { + embed: { + model: "test-model", + provider: "test-provider", + }, + }, + } as unknown as ContinueConfig; + + const configResult: ConfigResult = { + config: testConfig, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // Verify that the config was set + expect((testIndexer as any).config).toBe(testConfig); + // These get called once on init, and we want them to get called again + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2); + }); + + test("should handle multiple context providers correctly", async () => { + const configResult: ConfigResult = { + config: { + contextProviders: [ + { + description: { + title: "SomeOtherProvider", + }, + }, + { + description: { + title: CodebaseContextProvider.description.title, + }, + }, + { + description: { + title: "AnotherProvider", + }, + }, + ], + selectedModelByRole: { + embed: { + model: "test-model", + provider: "test-provider", + }, + }, + } as unknown as ContinueConfig, + errors: [], + configLoadInterrupted: false, + }; + + await testIndexer.testHandleConfigUpdate(configResult); + + // These get called once on init, and we want them to get called again + expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2); + expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([ + "/test/workspace", + ]); + }); + }); + }); }); diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 0bd9b1328..862f1bb24 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,7 +1,12 @@ import * as fs from "fs/promises"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; +import { + ContinueConfig, + IDE, + IndexingProgressUpdate, + IndexTag, +} from "../index.js"; import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import type { IMessenger } from "../protocol/messenger"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; @@ -9,11 +14,14 @@ import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { Telemetry } from "../util/posthog.js"; import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; +import { ConfigResult } from "@continuedev/config-yaml"; +import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js"; import { ContinueServerClient } from "../continueServer/stubs/client"; import { LLMError } from "../llm/index.js"; import { getRootCause } from "../util/errors.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; +import { embedModelsAreEqual } from "./docs/DocsService.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; import { LanceDbIndex } from "./LanceDbIndex.js"; import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js"; @@ -44,6 +52,10 @@ export class CodebaseIndexer { * - To make as few requests as possible to the embeddings providers */ filesPerBatch = 200; + // We normally allow this to run in the background, + // and only need to `await` it for tests. + public initPromise: Promise; + private config!: ContinueConfig; private indexingCancellationController: AbortController | undefined; private codebaseIndexingState: IndexingProgressUpdate; private readonly pauseToken: PauseToken; @@ -83,6 +95,17 @@ export class CodebaseIndexer { // Initialize pause token this.pauseToken = new PauseToken(initialPaused); + + this.initPromise = this.init(configHandler); + } + + // Initialization - load config and attach config listener + private async init(configHandler: ConfigHandler) { + const result = await configHandler.loadConfig(); + await this.handleConfigUpdate(result); + configHandler.onConfigUpdate( + this.handleConfigUpdate.bind(this) as (arg: any) => void, + ); } set paused(value: boolean) { @@ -192,7 +215,7 @@ export class CodebaseIndexer { workspaceDirs: string[], ): Promise { if (this.pauseToken.paused) { - // NOTE: by returning here, there is a chance that while paused a file is modified and + // FIXME: by returning here, there is a chance that while paused a file is modified and // then after unpausing the file is not reindexed return; } @@ -763,4 +786,49 @@ export class CodebaseIndexer { public get currentIndexingState(): IndexingProgressUpdate { return this.codebaseIndexingState; } + + private hasCodebaseContextProvider() { + return !!this.config.contextProviders?.some( + (provider) => + provider.description.title === + CodebaseContextProvider.description.title, + ); + } + + private isIndexingConfigSame( + config1: ContinueConfig | undefined, + config2: ContinueConfig, + ) { + return embedModelsAreEqual( + config1?.selectedModelByRole.embed, + config2.selectedModelByRole.embed, + ); + } + + private async handleConfigUpdate({ + config: newConfig, + }: ConfigResult) { + if (newConfig) { + const needsReindex = !this.isIndexingConfigSame(this.config, newConfig); + + this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in + + // No point in indexing if no codebase context provider + const hasCodebaseContextProvider = this.hasCodebaseContextProvider(); + if (!hasCodebaseContextProvider) { + return; + } + + // Skip codebase indexing if not supported + // No warning message here because would show on ANY config update + if (!this.config.selectedModelByRole.embed) { + return; + } + + if (needsReindex) { + const dirs = await this.ide.getWorkspaceDirs(); + await this.refreshCodebaseIndex(dirs); + } + } + } } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 1399dd957..22374f5dd 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -69,7 +69,7 @@ const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => { const globalContext = new GlobalContext(); const failedDocs = globalContext.get("failedDocs") ?? []; const newFailedDocs = failedDocs.filter( - (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d), + (d) => !docConfigsAreEqual(siteIndexingConfig, d), ); newFailedDocs.push(siteIndexingConfig); globalContext.update("failedDocs", newFailedDocs); @@ -81,7 +81,7 @@ const removeFromFailedGlobalContext = ( const globalContext = new GlobalContext(); const failedDocs = globalContext.get("failedDocs") ?? []; const newFailedDocs = failedDocs.filter( - (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d), + (d) => !docConfigsAreEqual(siteIndexingConfig, d), ); globalContext.update("failedDocs", newFailedDocs); }; @@ -89,32 +89,69 @@ const removeFromFailedGlobalContext = ( const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => { const globalContext = new GlobalContext(); const failedDocs = globalContext.get("failedDocs") ?? []; - return failedDocs.find((d) => - siteIndexingConfigsAreEqual(siteIndexingConfig, d), + return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d)); +}; + +export function embedModelsAreEqual( + llm1: ILLM | null | undefined, + llm2: ILLM | null | undefined, +): boolean { + return ( + llm1?.underlyingProviderName === llm2?.underlyingProviderName && + llm1?.title === llm2?.title && + llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize + ); +} + +const docConfigsAreEqual = ( + siteConfig1: SiteIndexingConfig, + siteConfig2: SiteIndexingConfig, +) => { + return ( + siteConfig1.faviconUrl === siteConfig2.faviconUrl && + siteConfig1.title === siteConfig2.title && + docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) + ); +}; + +const docConfigsAreEqualExceptTitleAndFavicon = ( + siteConfig1: SiteIndexingConfig, + siteConfig2: SiteIndexingConfig, +) => { + return ( + siteConfig1.startUrl === siteConfig2.startUrl && + siteConfig1.maxDepth === siteConfig2.maxDepth && + siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling ); }; const siteIndexingConfigsAreEqual = ( - config1: SiteIndexingConfig, - config2: SiteIndexingConfig, + siteConfig1: SiteIndexingConfig, + siteConfig2: SiteIndexingConfig, + contConfig1: ContinueConfig | undefined, + contConfig2: ContinueConfig, ) => { return ( - config1.startUrl === config2.startUrl && - config1.faviconUrl === config2.faviconUrl && - config1.title === config2.title && - config1.maxDepth === config2.maxDepth && - config1.useLocalCrawling === config2.useLocalCrawling + docConfigsAreEqual(siteConfig1, siteConfig2) && + embedModelsAreEqual( + contConfig1?.selectedModelByRole.embed, + contConfig2.selectedModelByRole.embed, + ) ); }; const siteIndexingConfigsAreEqualExceptTitleAndFavicon = ( - config1: SiteIndexingConfig, - config2: SiteIndexingConfig, + siteConfig1: SiteIndexingConfig, + siteConfig2: SiteIndexingConfig, + contConfig1: ContinueConfig | undefined, + contConfig2: ContinueConfig, ) => { return ( - config1.startUrl === config2.startUrl && - config1.maxDepth === config2.maxDepth && - config1.useLocalCrawling === config2.useLocalCrawling + docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) && + embedModelsAreEqual( + contConfig1?.selectedModelByRole.embed, + contConfig2.selectedModelByRole.embed, + ) ); }; @@ -1037,12 +1074,22 @@ export default class DocsService { ); // TODO: Changes to the docs config made while Continue isn't running won't be caught - if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) { + if ( + oldConfigDoc && + !siteIndexingConfigsAreEqual( + oldConfigDoc, + doc, + oldConfig, + newConfig, + ) + ) { // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing if ( siteIndexingConfigsAreEqualExceptTitleAndFavicon( oldConfigDoc, doc, + oldConfig, + newConfig, ) ) { await this.updateMetadataInSqlite(doc); @@ -1262,7 +1309,7 @@ export default class DocsService { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file const doesEquivalentDocExist = this.config.docs?.some((doc) => - siteIndexingConfigsAreEqual(doc, siteIndexingConfig), + docConfigsAreEqual(doc, siteIndexingConfig), ); if (!doesEquivalentDocExist) { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 606148c1c..add0b983b 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,6 +1,13 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js"; +import { + ChatMessage, + CompiledMessagesResult, + MessageContent, + MessagePart, + PruningStatus, + Tool, +} from "../index.js"; import { autodetectTemplateType } from "./autodetect.js"; import { addSpaceToAnyEmptyMessages, @@ -417,7 +424,7 @@ function compileChatMessages({ maxTokens: number; supportsImages: boolean; tools?: Tool[]; -}): ChatMessage[] { +}): CompiledMessagesResult { let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); // If images not supported, convert MessagePart[] to string @@ -446,14 +453,14 @@ function compileChatMessages({ msgsCopy.pop(); } - // Extract the tool sequence from the end of the message array - const toolSequence = extractToolSequence(msgsCopy); + // // Extract the tool sequence from the end of the message array + // const toolSequence = extractToolSequence(msgsCopy); - // Count tokens for all messages in the tool sequence - let lastMessagesTokens = 0; - for (const msg of toolSequence) { - lastMessagesTokens += countChatMessageTokens(modelName, msg); - } + // // Count tokens for all messages in the tool sequence + // let lastMessagesTokens = 0; + // for (const msg of toolSequence) { + // lastMessagesTokens += countChatMessageTokens(modelName, msg); + // } // System message let systemMsgTokens = 0; @@ -479,7 +486,7 @@ function compileChatMessages({ // Non-negotiable messages inputTokensAvailable -= toolTokens; inputTokensAvailable -= systemMsgTokens; - inputTokensAvailable -= lastMessagesTokens; + // inputTokensAvailable -= lastMessagesTokens; // Make sure there's enough context for the non-excludable items if (inputTokensAvailable < 0) { @@ -491,7 +498,6 @@ function compileChatMessages({ - counting safety buffer: ${countingSafetyBuffer} - tools: ~${toolTokens} - system message: ~${systemMsgTokens} - - last user or tool + tool call message tokens: ~${lastMessagesTokens} - max output tokens: ${maxTokens}`, ); } @@ -507,9 +513,12 @@ function compileChatMessages({ }; }); + let pruningStatus: PruningStatus = "not-pruned"; + while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { const message = historyWithTokens.shift()!; currentTotal -= message.tokens; + pruningStatus = "pruned"; // At this point make sure no latent tool response without corresponding call while (historyWithTokens[0]?.role === "tool") { @@ -518,15 +527,18 @@ function compileChatMessages({ } } + if (historyWithTokens.length === 0) { + pruningStatus = "deleted-last-input"; + } + // Now reassemble const reassembled: ChatMessage[] = []; if (systemMsg) { reassembled.push(systemMsg); } reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); - reassembled.push(...toolSequence); - return reassembled; + return { compiledChatMessages: reassembled, pruningStatus }; } export { diff --git a/core/llm/index.ts b/core/llm/index.ts index 8872281d6..9a727d1a4 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -20,6 +20,7 @@ import { ILLMLogger, LLMFullCompletionOptions, LLMOptions, + MessageOption, ModelCapability, ModelInstaller, PromptLog, @@ -867,6 +868,23 @@ export abstract class BaseLLM implements ILLM { return { role: "assistant" as const, content: completion }; } + compileChatMessages( + message: ChatMessage[], + options: LLMFullCompletionOptions, + ) { + let { completionOptions } = this._parseCompletionOptions(options); + completionOptions = this._modifyCompletionOptions(completionOptions); + + return compileChatMessages({ + modelName: completionOptions.model, + msgs: message, + contextLength: this.contextLength, + maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + tools: options.tools, + }); + } + protected modifyChatBody( body: ChatCompletionCreateParams, ): ChatCompletionCreateParams { @@ -891,6 +909,7 @@ export abstract class BaseLLM implements ILLM { _messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}, + messageOptions?: MessageOption, ): AsyncGenerator { let { completionOptions, logEnabled } = this._parseCompletionOptions(options); @@ -901,14 +920,21 @@ export abstract class BaseLLM implements ILLM { completionOptions = this._modifyCompletionOptions(completionOptions); - const messages = compileChatMessages({ - modelName: completionOptions.model, - msgs: _messages, - contextLength: this.contextLength, - maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, - supportsImages: this.supportsImages(), - tools: options.tools, - }); + let messages = _messages; + + // If not precompiled, compile the chat messages + if (!messageOptions || messageOptions.precompiled === false) { + const { compiledChatMessages } = compileChatMessages({ + modelName: completionOptions.model, + msgs: _messages, + contextLength: this.contextLength, + maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + tools: options.tools, + }); + + messages = compiledChatMessages; + } const prompt = this.templateMessages ? this.templateMessages(messages) diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 00efc8c2d..2692195e2 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -24,7 +24,12 @@ export async function* llmStreamChat( void TTS.kill(); } - const { legacySlashCommandData, completionOptions, messages } = msg.data; + const { + legacySlashCommandData, + completionOptions, + messages, + messageOptions, + } = msg.data; const model = config.selectedModelByRole.chat; @@ -117,6 +122,7 @@ export async function* llmStreamChat( messages, abortController.signal, completionOptions, + messageOptions, ); let next = await gen.next(); while (!next.done) { diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 6c1e86fbc..c4dd70f51 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -1,5 +1,5 @@ export const IS_NEXT_EDIT_ACTIVE = false; -export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5; +export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0; export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f06d1db04..2bbc75620 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,6 +15,7 @@ import { GlobalContextModelSelections } from "../util/GlobalContext"; import { BrowserSerializedContinueConfig, ChatMessage, + CompiledMessagesResult, CompleteOnboardingPayload, ContextItem, ContextItemWithId, @@ -25,6 +26,7 @@ import { FileSymbolMap, IdeSettings, LLMFullCompletionOptions, + MessageOption, ModelDescription, PromptLog, RangeInFile, @@ -159,6 +161,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { messages: ChatMessage[]; completionOptions: LLMFullCompletionOptions; title: string; + messageOptions?: MessageOption; legacySlashCommandData?: { command: SlashCommandDescWithSource; input: string; @@ -170,6 +173,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { AsyncGenerator, ]; streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator]; + "llm/compileChat": [ + { messages: ChatMessage[]; options: LLMFullCompletionOptions }, + CompiledMessagesResult, + ]; "chatDescriber/describe": [ { text: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 6b29ce472..f4ad6c04c 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -41,6 +41,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "llm/complete", "llm/streamChat", "llm/listModels", + "llm/compileChat", "streamDiffLines", "chatDescriber/describe", "stats/getTokensPerDay", diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index 60c8ae3aa..97b79ca4d 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -3,7 +3,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export interface SearchAndReplaceInFileArgs { filepath: string; - diff: string; + diffs: string[]; } // Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` @@ -25,19 +25,22 @@ export const searchAndReplaceInFileTool: Tool = { isInstant: false, function: { name: BuiltInToolNames.SearchAndReplaceInFile, - 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. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, + description: `Request to replace sections of content in an existing file using multiple 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. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, parameters: { type: "object", - required: ["filepath", "diff"], + required: ["filepath", "diffs"], properties: { filepath: { type: "string", description: "The path of the file to modify, relative to the root of the workspace.", }, - diff: { - type: "string", - description: `One or more SEARCH/REPLACE blocks following this exact format: + diffs: { + type: "array", + items: { + type: "string", + }, + description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: \`\`\` ------- SEARCH [exact content to find] @@ -54,16 +57,17 @@ Critical rules: * 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: +3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. +4. 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. Splitting up tool calls: +5. Splitting up tool calls: * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] -5. Special operations: +6. 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 @@ -81,7 +85,8 @@ Usage: [new content to replace with] +++++++ REPLACE \`\`\` -`, + +Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, }, }, }, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index c53b4bc6e..ae2ae6165 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -107,6 +107,7 @@ class MessageTypes { "llm/complete", "llm/streamChat", "llm/listModels", + "llm/compileChat", "streamDiffLines", "chatDescriber/describe", "stats/getTokensPerDay", diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt index d153deda5..e668bd4b1 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt @@ -16,6 +16,7 @@ import com.intellij.remoterobot.utils.waitFor import com.intellij.remoterobot.utils.waitForIgnoringError import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.awt.event.KeyEvent.VK_I @@ -37,6 +38,7 @@ class InlineEdit { fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() @Test + @Disabled("Failing in CI, seems like the timeout just needs to be increased") @Video fun submitInlineEdit(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { welcomeFrame { diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index f35ede049..58d03239d 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -3,8 +3,9 @@ import { EXTENSION_NAME } from "core/control-plane/env"; // @ts-ignore import * as vscode from "vscode"; -import { DiffLine } from "core"; +import { DiffChar, DiffLine } from "core"; import { CodeRenderer } from "core/codeRenderer/CodeRenderer"; +import { myersCharDiff } from "core/diff/myers"; import { NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, @@ -295,14 +296,19 @@ export class NextEditWindowManager { ); // Create and apply decoration with the text. - await this.renderTooltip( + await this.renderWindow( editor, currCursorPos, oldEditRangeSlice, newEditRangeSlice, editableRegionStartLine, + diffLines, ); + const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); + + this.renderDeletes(editor, editableRegionStartLine, diffChars); + // Reserve tab and esc to either accept or reject the displayed next edit contents. await NextEditWindowManager.reserveTabAndEsc(); } @@ -531,6 +537,7 @@ export class NextEditWindowManager { private async createCodeRender( text: string, currLineOffsetFromTop: number, + newDiffLines: DiffLine[], ): Promise< | { uri: vscode.Uri; dimensions: { width: number; height: number } } | undefined @@ -546,14 +553,15 @@ export class NextEditWindowManager { const uri = await this.codeRenderer.getDataUri( text, "typescript", - this.fontSize, - this.fontFamily, - dimensions, - SVG_CONFIG.lineHeight, { imageType: "svg", + fontSize: this.fontSize, + fontFamily: this.fontFamily, + dimensions: dimensions, + lineHeight: SVG_CONFIG.lineHeight, }, currLineOffsetFromTop, + newDiffLines, ); return { @@ -576,11 +584,13 @@ export class NextEditWindowManager { predictedCode: string, position: vscode.Position, editableRegionStartLine: number, + newDiffLines: DiffLine[], ): Promise { const currLineOffsetFromTop = position.line - editableRegionStartLine; const uriAndDimensions = await this.createCodeRender( predictedCode, currLineOffsetFromTop, + newDiffLines, ); if (!uriAndDimensions) { return undefined; @@ -598,12 +608,12 @@ export class NextEditWindowManager { SVG_CONFIG.getTipWidth(originalCode) - SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]); - console.log(marginLeft); - console.log(SVG_CONFIG.getTipWidth(originalCode)); - console.log( - SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]), - ); - console.log(originalCode.split("\n")[currLineOffsetFromTop]); + // console.log(marginLeft); + // console.log(SVG_CONFIG.getTipWidth(originalCode)); + // console.log( + // SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]), + // ); + // console.log(originalCode.split("\n")[currLineOffsetFromTop]); return vscode.window.createTextEditorDecorationType({ before: { contentIconPath: uri, @@ -703,16 +713,16 @@ export class NextEditWindowManager { } /** - * Render a tooltip with the given text at the specified position. + * Render a window with the given text at the specified position. */ - private async renderTooltip( + private async renderWindow( editor: vscode.TextEditor, position: vscode.Position, originalCode: string, predictedCode: string, editableRegionStartLine: number, + newDiffLines: DiffLine[], ) { - console.log("renderTooltip"); // Capture document version to detect changes. const docVersion = editor.document.version; @@ -722,6 +732,7 @@ export class NextEditWindowManager { predictedCode, position, editableRegionStartLine, + newDiffLines, ); if (!decoration) { console.error("Failed to create decoration for text:", predictedCode); @@ -737,7 +748,8 @@ export class NextEditWindowManager { // Store the decoration and editor. await this.hideAllNextEditWindows(); - this.currentDecoration = decoration; + this.currentDecoration = decoration; // TODO: This might be redundant. + this.disposables.push(decoration); this.activeEditor = editor; // Calculate how far off to the right of the cursor the decoration should be. @@ -773,6 +785,66 @@ export class NextEditWindowManager { this.mostRecentCompletionId, ); } + + private renderDeletes( + editor: vscode.TextEditor, + editableRegionStartLine: number, + // oldEditRangeSlice: string, + // newEditRangeSlice: string, + oldDiffChars: DiffChar[], + ) { + const charsToDelete: vscode.DecorationOptions[] = []; + + // const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); + + oldDiffChars.forEach((diff) => { + // TODO: This check if technically redundant. + if (diff.type === "old") { + charsToDelete.push({ + range: new vscode.Range( + new vscode.Position( + editableRegionStartLine + diff.oldLineIndex!, + diff.oldCharIndexInLine!, + ), + new vscode.Position( + editableRegionStartLine + diff.oldLineIndex!, + diff.oldCharIndexInLine! + diff.char.length, + ), + ), + }); + } + }); + + const deleteDecorationType = vscode.window.createTextEditorDecorationType({ + backgroundColor: "rgba(255, 0, 0, 0.5)", + textDecoration: "line-through", + }); + + editor.setDecorations(deleteDecorationType, charsToDelete); + this.disposables.push(deleteDecorationType); + } + + async getExactCharacterWidth(): Promise { + // For VS Code extensions, you can sometimes access the editor's text metrics + const activeEditor = vscode.window.activeTextEditor; + if (activeEditor) { + // VS Code has internal methods to measure text, but they're not all exposed + // in the public API. You might need to use reflection or known properties. + + // Example accessing through reflection (this is pseudocode) + const editorInstance = activeEditor as any; + if (editorInstance._modelData && editorInstance._modelData.viewModel) { + const viewModel = editorInstance._modelData.viewModel; + return ( + viewModel.getLineWidth(0) / + activeEditor.document.lineAt(0).text.length + ); + } + } + + // If all else fails, return a reasonable default + return SVG_CONFIG.fontSize * 0.6; + } } export default async function setupNextEditWindowManager( diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index 5763cb394..c552ea690 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -161,17 +161,14 @@ export function AssistantAndOrgListbox() { refreshProfiles()} > { - e.stopPropagation(); - await refreshProfiles(); - }} > state.session.history[props.index + 1], ); + const warningMessage = useAppSelector( + (state) => state.session.warningMessage, + ); const uiConfig = useAppSelector(selectUIConfig); const isNextMsgAssistantOrThinking = diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index c731b761b..d95a0a118 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -10,6 +10,9 @@ import { GradientBorder } from "./GradientBorder"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; +import WarningMessageBox from "./WarningMessageBox"; +import EditConfigAction from "./WarningMessageBox/Actions/EditConfigAction"; +import NewSessionAction from "./WarningMessageBox/Actions/NewSessionAction"; interface ContinueInputBoxProps { isLastUserInput: boolean; @@ -40,6 +43,9 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ function ContinueInputBox(props: ContinueInputBoxProps) { const isStreaming = useAppSelector((state) => state.session.isStreaming); + const warningMessage = useAppSelector( + (state) => state.session.warningMessage, + ); const availableSlashCommands = useAppSelector( selectSlashCommandComboBoxInputs, ); @@ -119,6 +125,19 @@ function ContinueInputBox(props: ContinueInputBoxProps) { /> )} + {props.isLastUserInput && + warningMessage && + (warningMessage.category === "exceeded-context-length" ? ( + + ) : ( + + ))} ); } diff --git a/gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx b/gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx new file mode 100644 index 000000000..6ff98bf61 --- /dev/null +++ b/gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx @@ -0,0 +1,15 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +export default function EditConfigAction() { + const ideMessenger = useContext(IdeMessengerContext); + return ( + + ideMessenger.post("config/openProfile", { profileId: undefined }) + } + className="hover:underline" + > + Open configuration file + + ); +} diff --git a/gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx b/gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx new file mode 100644 index 000000000..2f397e7a2 --- /dev/null +++ b/gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx @@ -0,0 +1,10 @@ +import { useAppDispatch } from "../../../../redux/hooks"; +import { newSession } from "../../../../redux/slices/sessionSlice"; +export default function NewSessionAction() { + const dispatch = useAppDispatch(); + return ( + dispatch(newSession())} className="hover:underline"> + Start a new session + + ); +} diff --git a/gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx b/gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx new file mode 100644 index 000000000..dbcbf21a9 --- /dev/null +++ b/gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx @@ -0,0 +1,41 @@ +import { ReactNode, useEffect, useRef, useState } from "react"; +export default function ExpendableBox({ children }: { children: ReactNode }) { + const [isExpended, setIsExpended] = useState(false); + const [showTrigger, setShowTrigger] = useState(true); + const expendableDivRef = useRef(null); + const toggleExpendable = () => { + setIsExpended((pre) => !pre); + }; + + useEffect(() => { + if (expendableDivRef.current) { + expendableDivRef.current.style.maxHeight = isExpended ? "600px" : "0px"; + } + + if (isExpended) { + setShowTrigger(false); + } else { + setTimeout(() => setShowTrigger(true), 200); + } + }, [isExpended]); + + return ( +
+
+ +
+ {children} +
+
+ ); +} diff --git a/gui/src/components/mainInput/WarningMessageBox/index.tsx b/gui/src/components/mainInput/WarningMessageBox/index.tsx new file mode 100644 index 000000000..2b14a3457 --- /dev/null +++ b/gui/src/components/mainInput/WarningMessageBox/index.tsx @@ -0,0 +1,55 @@ +import { WarningMessage } from "core"; +import { ReactElement } from "react"; +import ExpendableBox from "./ExpendableBox"; + +function MessageBox({ + warningMessage, + actions, +}: { + warningMessage: WarningMessage; + actions?: (() => ReactElement)[]; +}) { + const warningMessageTextColor = + warningMessage.level === "fatal" ? "text-error" : "text-warning"; + const warningMessageBorderColor = + warningMessage.level === "fatal" ? "border-error" : "border-warning"; + return ( +
+

+ Warning: + {`${warningMessage.message}`} +

+ {actions && ( +
+

{`Recommended Action${actions.length > 1 ? "s" : ""}:`}

+
    + {actions.map((action, ind) => { + return
  • {action()}
  • ; + })} +
+
+ )} +
+ ); +} + +export default function WarningMessageBox({ + warningMessage, + actions, +}: { + warningMessage: WarningMessage; + actions?: (() => ReactElement)[]; +}) { + if (warningMessage.category === "exceeded-context-length") { + return ( + + } + /> + ); + } + return ; +} diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index 9cc5034ab..e6f144b6d 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -84,6 +84,10 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, ], }, + "llm/compileChat": { + compiledChatMessages: [], + pruningStatus: "not-pruned", + }, }; const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [ diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 383f18241..7f2fea420 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -113,6 +113,9 @@ export function Chat() { const jetbrains = useMemo(() => { return isJetBrains(); }, []); + const warningMessage = useAppSelector( + (state) => state.session.warningMessage, + ); useAutoScroll(stepsDivRef, history); diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 8effdd6e2..378483d71 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -36,7 +36,7 @@ function FunctionSpecificToolCallDiv({ return ( diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 8ada08e53..4c77ecafa 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -89,7 +89,6 @@ export function SimpleToolCallUI({ ) : null} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx index c1b1ec0c7..13294ceef 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx @@ -4,13 +4,11 @@ import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPrev interface ArgsToggleIconProps { isShowing: boolean; setIsShowing: (val: boolean) => void; - toolCallId: string; } export const ArgsToggleIcon = ({ isShowing, setIsShowing, - toolCallId, }: ArgsToggleIconProps) => { return ( -
+
@@ -50,7 +50,6 @@ export function ToolCallDisplay({ ) : null}
diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx index c633b0514..4a88fd7cb 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx @@ -53,7 +53,7 @@ export function ToolCallStatusMessage({ return (
{`Continue ${intro} ${message}`} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index c976a7ddd..ae2839926 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -6,7 +6,7 @@ import { useAppSelector } from "../../../redux/hooks"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; import { GroupedToolCallHeader } from "./GroupedToolCallHeader"; import { SimpleToolCallUI } from "./SimpleToolCallUI"; -import { ToolCallDisplay } from "./ToolCall"; +import { ToolCallDisplay } from "./ToolCallDisplay"; import { getStatusIcon, toolCallIcons } from "./utils"; interface ToolCallDivProps { @@ -103,10 +103,7 @@ export function ToolCallDiv({ } return toolCallStates.map((toolCallState) => ( -
+
{renderToolCall(toolCallState)}
)); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index fc87804a8..ddecb6c19 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,8 +21,9 @@ import { SessionMetadata, ThinkingChatMessage, Tool, - ToolCallState, ToolCallDelta, + ToolCallState, + WarningMessage, } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; @@ -223,6 +224,7 @@ type SessionState = { }; newestToolbarPreviewForInput: Record; hasReasoningEnabled?: boolean; + warningMessage?: WarningMessage; }; const initialState: SessionState = { @@ -424,6 +426,7 @@ export const sessionSlice = createSlice({ deleteMessage: (state, action: PayloadAction) => { // Deletes the current assistant message and the previous user message state.history.splice(action.payload - 1, 2); + state.warningMessage = undefined; }, updateHistoryItemAtIndex: ( state, @@ -889,6 +892,12 @@ export const sessionSlice = createSlice({ state.newestToolbarPreviewForInput[payload.inputId] = payload.contextItemId; }, + setWarningMessage: ( + state, + action: PayloadAction, + ) => { + state.warningMessage = action.payload; + }, }, selectors: { selectIsGatheringContext: (state) => { @@ -972,6 +981,7 @@ export const { setNewestToolbarPreviewForInput, setIsInEdit, setHasReasoningEnabled, + setWarningMessage, } = sessionSlice.actions; export const { selectIsGatheringContext } = sessionSlice.selectors; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 0c1992a48..3f56f4bbd 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -13,6 +13,7 @@ import { setAppliedRulesAtIndex, setInactive, setToolGenerated, + setWarningMessage, streamUpdate, } from "../slices/sessionSlice"; import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; @@ -183,6 +184,41 @@ export const streamNormalInput = createAsyncThunk< ); dispatch(setActive()); + // Remove the warning message before each compileChat call + dispatch(setWarningMessage(undefined)); + const precompiledRes = await extra.ideMessenger.request("llm/compileChat", { + messages, + options: completionOptions, + }); + + if (precompiledRes.status === "error") { + throw new Error(precompiledRes.error); + } + + const { compiledChatMessages, pruningStatus } = precompiledRes.content; + + switch (pruningStatus) { + case "pruned": + dispatch( + setWarningMessage({ + message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`, + level: "warning", + category: "exceeded-context-length", + }), + ); + break; + case "deleted-last-input": + dispatch( + setWarningMessage({ + message: + "The provided context items are too large. Please trim the context item to fit the model's context length or increase the model's context length by editing the configuration.", + level: "fatal", + category: "deleted-last-input", + }), + ); + dispatch(setInactive()); + return; + } // Send request and stream response const streamAborter = state.session.streamAborter; @@ -190,8 +226,9 @@ export const streamNormalInput = createAsyncThunk< { completionOptions, title: selectedChatModel.title, - messages: messages, + messages: compiledChatMessages, legacySlashCommandData, + messageOptions: { precompiled: true }, }, streamAborter.signal, ); @@ -235,9 +272,7 @@ export const streamNormalInput = createAsyncThunk< console.error("Failed to send dev data interaction log", e); } } - - await handleToolCallExecution(dispatch, getState); - dispatch(setInactive()); + await handleToolCallExecution(dispatch, getState); }, ); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 58a63f598..ed16b5a5a 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -2,80 +2,32 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; import { renderContextItems } from "core/util/messageContent"; import { + ChatHistoryItemWithMessageId, resetNextCodeBlockToApplyIndex, streamUpdate, } from "../slices/sessionSlice"; -import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; +import { ThunkApiType } from "../store"; import { findToolCallById } from "../util"; import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; -/** - * Finds the assistant message that contains the specified tool call. - */ -function findAssistantMessageWithToolCall( - history: RootState["session"]["history"], - toolCallId: string, -) { - return history.find( - (item) => - item.message.role === "assistant" && - item.toolCallStates?.some((tc) => tc.toolCallId === toolCallId), - ); -} - -/** - * Checks if all parallel tool calls in an assistant message are complete. - */ -function areAllToolCallsComplete( - toolCallStates: NonNullable< - ReturnType - >["toolCallStates"], -): boolean { - if (!toolCallStates) return false; - - const completedToolCalls = toolCallStates.filter( - (tc) => tc.status === "done", - ); - - return completedToolCalls.length === toolCallStates.length; -} - /** * Determines if we should continue streaming based on tool call completion status. */ -function shouldContinueStreaming( - assistantMessage: ReturnType, +function areAllToolsDoneStreaming( + assistantMessage: ChatHistoryItemWithMessageId | undefined, ): boolean { + // This might occur because of race conditions, if so, the tools are completed if (!assistantMessage?.toolCallStates) { - return false; // No assistant message found - don't stream - } - - const totalToolCalls = assistantMessage.toolCallStates.length; - - // Single tool call - always continue streaming - if (totalToolCalls === 1) { return true; } - // Multiple tool calls - only continue if all are complete - return areAllToolCallsComplete(assistantMessage.toolCallStates); -} + // Only continue if all tool calls are complete + const completedToolCalls = assistantMessage.toolCallStates.filter( + (tc) => tc.status === "done", + ); -/** - * Creates and dispatches a tool message for the completed tool call. - */ -function createAndDispatchToolMessage( - dispatch: AppThunkDispatch, - toolCallId: string, - toolOutput: any[], -): void { - const newMessage: ChatMessage = { - role: "tool", - content: renderContextItems(toolOutput), - toolCallId, - }; - dispatch(streamUpdate([newMessage])); + return completedToolCalls.length === assistantMessage.toolCallStates.length; } export const streamResponseAfterToolCall = createAsyncThunk< @@ -104,16 +56,22 @@ export const streamResponseAfterToolCall = createAsyncThunk< await new Promise((resolve) => setTimeout(resolve, 0)); // Create and dispatch the tool message - createAndDispatchToolMessage(dispatch, toolCallId, toolOutput); + const newMessage: ChatMessage = { + role: "tool", + content: renderContextItems(toolOutput), + toolCallId, + }; + dispatch(streamUpdate([newMessage])); // Check if we should continue streaming based on tool call completion const history = getState().session.history; - const assistantMessage = findAssistantMessageWithToolCall( - history, - toolCallId, + const assistantMessage = history.find( + (item) => + item.message.role === "assistant" && + item.toolCallStates?.some((tc) => tc.toolCallId === toolCallId), ); - if (shouldContinueStreaming(assistantMessage)) { + if (areAllToolsDoneStreaming(assistantMessage)) { unwrapResult(await dispatch(streamNormalInput({}))); } }), diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts index b8db3f830..a8eb74d77 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.test.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.test.ts @@ -53,24 +53,61 @@ describe("searchReplaceToolImpl", () => { await expect( searchReplaceToolImpl( - { filepath: "nonexistent.txt", diff: "some diff" }, + { filepath: "nonexistent.txt", diffs: ["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 () => { + it("should throw error when no search/replace blocks found in first diff", async () => { mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); mockParseAllSearchReplaceBlocks.mockReturnValue([]); await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "invalid diff content" }, + { filepath: "test.txt", diffs: ["invalid diff content"] }, "tool-call-id", mockExtras, ), - ).rejects.toThrow("No complete search/replace blocks found"); + ).rejects.toThrow("No complete search/replace blocks found in diff 1"); + }); + + it("should throw error when no search/replace blocks found in second diff", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); + mockParseAllSearchReplaceBlocks + .mockReturnValueOnce([ + { + isComplete: true, + searchContent: "valid content", + replaceContent: "replacement", + }, + ]) + .mockReturnValueOnce([]); + + await expect( + searchReplaceToolImpl( + { + filepath: "test.txt", + diffs: ["valid diff", "invalid diff content"], + }, + "tool-call-id", + mockExtras, + ), + ).rejects.toThrow("No complete search/replace blocks found in diff 2"); + }); + + it("should throw error when all diffs are empty", async () => { + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); + mockParseAllSearchReplaceBlocks.mockReturnValue([]); + + await expect( + searchReplaceToolImpl( + { filepath: "test.txt", diffs: [] }, + "tool-call-id", + mockExtras, + ), + ).rejects.toThrow("No complete search/replace blocks found in any diffs"); }); }); @@ -110,7 +147,65 @@ describe("searchReplaceToolImpl", () => { mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( - { filepath: "test.js", diff: "mock diff content" }, + { filepath: "test.js", diffs: ["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", + isSearchAndReplace: true, + }); + }); + }); + + describe("single diff scenarios", () => { + it("should successfully apply single diff with 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, + strategyName: "exactMatch", + }); + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); + + const result = await searchReplaceToolImpl( + { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -191,7 +286,7 @@ const c = 3;`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( - { filepath: "test.js", diff: "mock diff content" }, + { filepath: "test.js", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -225,6 +320,101 @@ const c = 3;`; }); }); + describe("multiple diff scenarios", () => { + it("should successfully apply multiple diffs each with single search/replace block", 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 - each diff returns one block + mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.js"); + mockParseAllSearchReplaceBlocks + .mockReturnValueOnce([ + { + isComplete: true, + searchContent: "const a = 1;", + replaceContent: "const a = 100;", + }, + ]) + .mockReturnValueOnce([ + { + 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, + strategyName: "exactMatch", + }) + .mockReturnValueOnce({ + startIndex: secondStartIndex, + endIndex: secondEndIndex, + strategyName: "exactMatch", + }); + + mockIdeMessenger.request.mockResolvedValue({ status: "success" }); + + const result = await searchReplaceToolImpl( + { filepath: "test.js", diffs: ["first diff", "second diff"] }, + "tool-call-id", + mockExtras, + ); + + // Verify the result + expect(result).toEqual({ + respondImmediately: false, + output: undefined, + }); + + // Verify parseAllSearchReplaceBlocks was called for each diff + expect(mockParseAllSearchReplaceBlocks).toHaveBeenCalledTimes(2); + expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith( + 1, + "first diff", + ); + expect(mockParseAllSearchReplaceBlocks).toHaveBeenNthCalledWith( + 2, + "second diff", + ); + + // Verify final applyToFile call + expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", { + text: expectedFinalContent, + streamId: "test-stream-id", + filepath: "/resolved/path/test.js", + toolCallId: "tool-call-id", + isSearchAndReplace: true, + }); + }); + }); + describe("deletion scenarios", () => { it("should handle empty replacement (deletion)", async () => { const originalContent = `keep this @@ -253,7 +443,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); const result = await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -293,7 +483,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -323,7 +513,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -361,7 +551,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -385,7 +575,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -411,7 +601,7 @@ keep this too`; await expect( searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ), @@ -441,7 +631,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -476,7 +666,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "test.txt", diff: "mock diff content" }, + { filepath: "test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); @@ -512,7 +702,7 @@ keep this too`; mockIdeMessenger.request.mockResolvedValue({ status: "success" }); await searchReplaceToolImpl( - { filepath: "relative/test.txt", diff: "mock diff content" }, + { filepath: "relative/test.txt", diffs: ["mock diff content"] }, "tool-call-id", mockExtras, ); diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts index 9594b9480..1fcf649e5 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.ts @@ -10,7 +10,7 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( toolCallId, extras, ) => { - const { filepath, diff } = args; + const { filepath, diffs } = args; const state = extras.getState(); const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; @@ -26,11 +26,20 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( throw new Error(`File ${filepath} does not exist`); } - // Parse all search/replace blocks from the diff content - const blocks = parseAllSearchReplaceBlocks(diff); + // Parse all search/replace blocks from all diff strings + const allBlocks = []; + for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) { + const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]); + if (blocks.length === 0) { + throw new Error( + `No complete search/replace blocks found in diff ${diffIndex + 1}`, + ); + } + allBlocks.push(...blocks); + } - if (blocks.length === 0) { - throw new Error("No complete search/replace blocks found"); + if (allBlocks.length === 0) { + throw new Error("No complete search/replace blocks found in any diffs"); } try { @@ -40,8 +49,8 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( let currentContent = originalContent; // Apply all replacements sequentially to build the final content - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; + for (let i = 0; i < allBlocks.length; i++) { + const block = allBlocks[i]; const { searchContent, replaceContent } = block; // Find the search content in the current state of the file