diff --git a/.continue/rules/continue-pun.md b/.continue/rules/continue-pun.md new file mode 100644 index 000000000..502e1cfbc --- /dev/null +++ b/.continue/rules/continue-pun.md @@ -0,0 +1,9 @@ +--- +name: Add Continue pun easter eggs +description: Adds an easter egg whenever the "continue" keyword +pattern: "continue" +--- + +Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase + +Do not add a comment if the use of "continue" is not in a code continue statement diff --git a/.continue/rules/css-units.md b/.continue/rules/css-units.md new file mode 100644 index 000000000..a270a383d --- /dev/null +++ b/.continue/rules/css-units.md @@ -0,0 +1,5 @@ +--- +globs: "gui/**/*.tsx" +--- + +You should try to use the `rem` CSS unit whenever possible for scalability instead of `px`. diff --git a/.continue/rules/edit-aggregator-singleton-rule.md b/.continue/rules/edit-aggregator-singleton-rule.md new file mode 100644 index 000000000..05ad0917b --- /dev/null +++ b/.continue/rules/edit-aggregator-singleton-rule.md @@ -0,0 +1,8 @@ +--- +patterns: ["EditAggregator", "processEdit"] +glob: "**/*.tsx" +name: "Enforce EditAggregator Singleton" +description: "Ensure that EditAggregator is used as a singleton in the codebase." +--- + +When you encounter usage of EditAggregator, be sure that this is compatible with the singleton nature of the EditAggregator class. If you are creating a new instance of EditAggregator, you should instead use the existing singleton. Refer to the `aggregateEdits.ts` to examine how the singleton pattern is used. Do not create a new instance of EditAggregator. diff --git a/.github/workflows/cla.yaml b/.github/workflows/cla.yaml index 1c170855c..5d5ce3933 100644 --- a/.github/workflows/cla.yaml +++ b/.github/workflows/cla.yaml @@ -26,5 +26,6 @@ jobs: path-to-signatures: "signatures/version1/cla.json" path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md" branch: cla-signatures - allowlist: dependabot[bot] + # Bots and CLAs signed outside of GitHub + allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline signed-commit-message: "CLA signed in $pullRequestNo" diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 8ea3d2ebb..920ed808b 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -167,20 +167,8 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Build and check config-yaml - run: | - cd ../../packages/config-yaml - npm i - npx tsc --noEmit - # Tests are currently failing, commenting out for now - # npm test - npm run build + - name: Build packages (Unix) + run: ./scripts/build-packages.sh # npm install core - name: Install core node_modules diff --git a/.vscode/launch.json b/.vscode/launch.json index 294429bcb..346714e94 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -19,6 +19,7 @@ "pauseForSourceMap": false, "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", + "postDebugTask": "Terminate All Tasks", "env": { // "CONTROL_PLANE_ENV": "local", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" @@ -73,32 +74,6 @@ "sourceMaps": true // "preLaunchTask": "gui:dev" }, - // Has to be run after starting the server (separately or using the compound configuration) - { - "name": "Run tests", - "type": "extensionHost", - "request": "launch", - "cwd": "${workspaceFolder}/extensions/vscode", - "runtimeExecutable": "${execPath}", - "args": [ - // Pass a directory to run tests in - "${workspaceFolder}/extensions/vscode/manual-testing-sandbox", - "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode", - "--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner" - ], - "outFiles": [ - // Allows setting breakpoints in test suites across the /src folder - "${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js", - // Allows setting breakpoints in mocha test runner file - "${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js" - ], - "internalConsoleOptions": "openOnSessionStart", - "preLaunchTask": "vscode-extension:tests:build", - "env": { - // Avoid timing out when stopping on breakpoints during debugging in VSCode - "MOCHA_TIMEOUT": "0" - } - }, { "name": "[Core] Jest Test Debugger, Current Open File", "type": "node", diff --git a/.vscode/tasks.json b/.vscode/tasks.json index d3a4a623d..0ea873978 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -109,39 +109,6 @@ "cwd": "${workspaceFolder}/extensions/vscode" } }, - // - // Compile and bundle tests - { - "label": "vscode-extension:tests:build", - "dependsOn": [ - // Build the extension - "vscode-extension:build", - // To detect compile errors - this type checks both the extension and the tests - "tsc:watch", - "vscode-extension:tests:esbuild" - ] - }, - { - "label": "vscode-extension:tests:esbuild", - "type": "npm", - "script": "build-test", - "path": "extensions/vscode", - "problemMatcher": [ - { - "pattern": [ - { - "regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$", - "file": 1, - "line": 2, - "column": 3, - "severity": 4, - "message": 5 - } - ] - } - ] - }, - // // Install or update all dependencies for all projects in the monrepo { "label": "install-all-dependencies", @@ -256,6 +223,19 @@ ], "type": "shell", "problemMatcher": [] + }, + { + "label": "Terminate All Tasks", + "command": "${input:terminate}", + "type": "shell" + } + ], + "inputs": [ + { + "id": "terminate", + "type": "command", + "command": "workbench.action.tasks.terminate", + "args": "terminateAll" } ] } diff --git a/binary/package-lock.json b/binary/package-lock.json index 11eaadc8a..51e6f5cf9 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -144,6 +144,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 82b169677..1fdbd3e86 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -6,12 +6,36 @@ import { } from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { + /** + * The display name of the language + */ name: string; + /** + * Keywords that show up at the top-level of files. We often use these as stop words or soft breaks + */ topLevelKeywords: string[]; + /** + * The character that prefixes a single line comment + * We use this to format snippets from other files as large comment blocks + */ singleLineComment?: string; + /** + * Semi-colon or other end of line indicator that may be used as a stop char + * or other parsing + */ endOfLine: string[]; + /** + * Strings that indicate we should filter out a line from completion + * Primarily currently used for .ipynb files + */ lineFilters?: LineFilter[]; + /** + * Similar to line filters, but characters. I think. + */ charFilters?: CharacterFilter[]; + /** + * Function that allows cusotmization of whether to use a multi-line completion on a per-language and completion basis + */ useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } @@ -23,6 +47,14 @@ export const Typescript = { endOfLine: [";"], }; +// JavaScript +export const JavaScript = { + name: "JavaScript", + topLevelKeywords: ["function", "class", "module", "export", "import"], + singleLineComment: "//", + endOfLine: [";"], +}; + // Python export const Python = { name: "Python", @@ -336,7 +368,7 @@ export const Markdown: AutocompleteLanguageInfo = { export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, - js: Typescript, + js: JavaScript, tsx: Typescript, json: Json, jsx: Typescript, diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 72e061fed..f521d292a 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -70,4 +70,20 @@ export class ContextRetrievalService { helper.treePath, ); } + + /** + * Initialize the import definitions cache for a file. + * This is normally done automatically when the active text editor changes, + * but needs to be called manually when using context fetching outside the normal flow. + */ + public async initializeForFile(filepath: string): Promise { + try { + await (this.importDefinitionsService as any).cache.initKey(filepath); + } catch (e) { + console.warn( + `Failed to initialize import definitions cache for ${filepath}:`, + e, + ); + } + } } diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index bf0284cb2..3504a069d 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -132,6 +132,14 @@ export function postprocessCompletion({ completion = "\n" + completion; } + if ( + (llm.model.includes("gemini") || llm.model.includes("gemma")) && + completion.endsWith("<|file_separator|>") + ) { + // "<|file_separator|>" is 18 characters long + completion = completion.slice(0, -18); + } + // If prefix ends with space and so does completion, then remove the space from completion if (prefix.endsWith(" ") && completion.startsWith(" ")) { diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 9194bccc8..702356198 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -209,3 +209,47 @@ export const getAllSnippets = async ({ recentlyOpenedFileSnippets, }; }; + +export const getAllSnippetsWithoutRace = async ({ + helper, + ide, + getDefinitionsFromLsp, + contextRetrievalService, +}: { + helper: HelperVars; + ide: IDE; + getDefinitionsFromLsp: GetLspDefinitionsFunction; + contextRetrievalService: ContextRetrievalService; +}): Promise => { + const recentlyEditedRangeSnippets = + getSnippetsFromRecentlyEditedRanges(helper); + + const [ + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + diffSnippets, + clipboardSnippets, + recentlyOpenedFileSnippets, + ] = await Promise.all([ + contextRetrievalService.getRootPathSnippets(helper), + contextRetrievalService.getSnippetsFromImportDefinitions(helper), + IDE_SNIPPETS_ENABLED + ? getIdeSnippets(helper, ide, getDefinitionsFromLsp) + : [], + [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, + getClipboardSnippets(ide), + getSnippetsFromRecentlyOpenedFiles(helper, ide), + ]); + + return { + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + recentlyEditedRangeSnippets, + diffSnippets, + clipboardSnippets, + recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, + recentlyOpenedFileSnippets, + }; +}; diff --git a/core/codeRenderer/CodeRenderer.ts b/core/codeRenderer/CodeRenderer.ts new file mode 100644 index 000000000..3d4084f7a --- /dev/null +++ b/core/codeRenderer/CodeRenderer.ts @@ -0,0 +1,272 @@ +/** + * CodeRenderer is a class that, when given a code string, + * highlights the code string using shiki and + * returns a svg representation of it. + * We could technically just call shiki's methods to do a + * one-liner syntax highlighting code, but + * a separate class for this is useful because + * we rarely ever need syntax highlighting outside of + * creating a render of it. + */ +import { JSDOM } from "jsdom"; +import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki"; +import { escapeForSVG, kebabOfStr } from "../util/text"; + +interface CodeRendererOptions { + themesDir?: string; + theme?: string; +} + +interface HTMLOptions { + theme?: string; + customCSS?: string; + containerClass?: string; +} + +interface ConversionOptions extends HTMLOptions { + transparent?: boolean; + imageType: "svg"; +} + +interface Dimensions { + width: number; + height: number; +} + +type DataUri = PngUri | SvgUri; +type PngUri = string; +type SvgUri = string; + +export class CodeRenderer { + private static instance: CodeRenderer; + private currentTheme: string = "dark-plus"; + private editorBackground: string = "#000000"; + private editorForeground: string = "#FFFFFF"; + + private constructor() {} + + static getInstance(): CodeRenderer { + if (!CodeRenderer.instance) { + CodeRenderer.instance = new CodeRenderer(); + } + return CodeRenderer.instance; + } + + public async setTheme(themeName: string): Promise { + if ( + this.themeExists(kebabOfStr(themeName)) || + themeName === "Default Dark Modern" + ) { + this.currentTheme = + themeName === "Default Dark Modern" + ? "dark-plus" + : kebabOfStr(themeName); + + const highlighter = await getSingletonHighlighter({ + themes: [this.currentTheme], + }); + + const th = highlighter.getTheme(this.currentTheme); + this.editorBackground = th.bg; + this.editorForeground = th.fg; + } else { + this.currentTheme = "dark-plus"; + } + } + + async init(): Promise {} + + async close(): Promise {} + + themeExists(themeNameKebab: string): themeNameKebab is BundledTheme { + const themeArray: BundledTheme[] = [ + "andromeeda", + "aurora-x", + "ayu-dark", + "catppuccin-frappe", + "catppuccin-latte", + "catppuccin-macchiato", + "catppuccin-mocha", + "dark-plus", + "dracula", + "dracula-soft", + "everforest-dark", + "everforest-light", + "github-dark", + "github-dark-default", + "github-dark-dimmed", + "github-dark-high-contrast", + "github-light", + "github-light-default", + "github-light-high-contrast", + "gruvbox-dark-hard", + "gruvbox-dark-medium", + "gruvbox-dark-soft", + "gruvbox-light-hard", + "gruvbox-light-medium", + "gruvbox-light-soft", + "houston", + "kanagawa-dragon", + "kanagawa-lotus", + "kanagawa-wave", + "laserwave", + "light-plus", + "material-theme", + "material-theme-darker", + "material-theme-lighter", + "material-theme-ocean", + "material-theme-palenight", + "min-dark", + "min-light", + "monokai", + "night-owl", + "nord", + "one-dark-pro", + "one-light", + "plastic", + "poimandres", + "red", + "rose-pine", + "rose-pine-dawn", + "rose-pine-moon", + "slack-dark", + "slack-ochin", + "snazzy-light", + "solarized-dark", + "solarized-light", + "synthwave-84", + "tokyo-night", + "vesper", + "vitesse-black", + "vitesse-dark", + "vitesse-light", + ]; + + return themeArray.includes(themeNameKebab as BundledTheme); + } + + async highlightCode( + code: string, + language: string = "javascript", + ): Promise { + return await codeToHtml(code, { + lang: language, + theme: this.currentTheme, + }); + } + + async convertToSVG( + code: string, + language: string = "javascript", + fontSize: number, + fontFamily: string, + dimensions: Dimensions, + lineHeight: number, + options: ConversionOptions, + ): Promise { + const highlightedCodeHtml = await this.highlightCode(code, language); + + const guts = this.convertShikiHtmlToSvgGut( + highlightedCodeHtml, + fontSize, + fontFamily, + lineHeight, + ); + const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); + + const svg = ` + + + ${guts} + +`; + + return Buffer.from(svg, "utf8"); + } + + convertShikiHtmlToSvgGut( + shikiHtml: string, + fontSize: number, + fontFamily: string, + lineHeight: number, + ): string { + const dom = new JSDOM(shikiHtml); + const document = dom.window.document; + + const lines = Array.from(document.querySelectorAll(".line")); + const svgLines = lines.map((line, index) => { + const spans = Array.from(line.childNodes) + .map((node) => { + if (node.nodeType === 3) { + return `${escapeForSVG(node.textContent ?? "")}`; + } + + const el = node as HTMLElement; + const style = el.getAttribute("style") || ""; + const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/); + const fill = colorMatch ? ` fill="${colorMatch[1]}"` : ""; + const content = el.textContent || ""; + return `${escapeForSVG(content)}`; + }) + .join(""); + + const y = (index + 1) * lineHeight; + return `${spans}`; + }); + + return ` + ${svgLines.join("\n")} + `.trim(); + } + + getBackgroundColor(shikiHtml: string): string { + const dom = new JSDOM(shikiHtml); + const document = dom.window.document; + + const preElement = document.querySelector("pre"); + let backgroundColor = "#333333"; // Default white background + if (preElement) { + const style = preElement.getAttribute("style") || ""; + const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/); + if (bgColorMatch) { + backgroundColor = bgColorMatch[1]; + } + } + + return backgroundColor; + } + + async getDataUri( + code: string, + language: string = "javascript", + fontSize: number, + fontFamily: string, + dimensions: Dimensions, + lineHeight: number, + options: ConversionOptions, + ): Promise { + switch (options.imageType) { + // case "png": + // const pngBuffer = await this.convertToPNG( + // code, + // language, + // fontSize, + // dimensions, + // lineHeight, + // options, + // ); + // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`; + case "svg": + const svgBuffer = await this.convertToSVG( + code, + language, + fontSize, + fontFamily, + dimensions, + lineHeight, + options, + ); + return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; + } + } +} diff --git a/core/commands/index.ts b/core/commands/index.ts deleted file mode 100644 index d87a3536f..000000000 --- a/core/commands/index.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; -import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; -import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; -import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile"; -import { renderChatMessage } from "../util/messageContent"; - -import SlashCommands from "./slash"; - -export function slashFromCustomCommand( - customCommand: CustomCommand, -): SlashCommand { - const commandName = customCommand.name.startsWith("/") - ? customCommand.name.substring(1) - : customCommand.name; - return { - name: commandName, - description: customCommand.description ?? "", - prompt: customCommand.prompt, - run: async function* ({ - input, - llm, - history, - ide, - completionOptions, - config, - selectedCode, - fetch, - abortController, - }) { - // Render prompt template - let renderedPrompt: string; - if (customCommand.prompt.includes("{{{ input }}}")) { - renderedPrompt = await renderTemplatedString( - customCommand.prompt, - ide.readFile.bind(ide), - { input }, - ); - } else { - const renderedPromptFile = await renderPromptFileV2( - customCommand.prompt, - { - config, - llm, - ide, - selectedCode, - fetch, - fullInput: input, - embeddingsProvider: config.modelsByRole.embed[0], - reranker: config.modelsByRole.rerank[0], - }, - ); - - renderedPrompt = renderedPromptFile[1]; - } - - // Replaces slash command messages with the rendered prompt - // which INCLUDES the input - const messages = replaceSlashCommandWithPromptInChatHistory( - history, - commandName, - renderedPrompt, - undefined, - ); - - for await (const chunk of llm.streamChat( - messages, - abortController.signal, - completionOptions, - )) { - yield renderChatMessage(chunk); - } - }, - }; -} - -export function slashCommandFromDescription( - desc: SlashCommandDescription, -): SlashCommand | undefined { - const cmd = SlashCommands.find((cmd) => cmd.name === desc.name); - if (!cmd) { - return undefined; - } - return { - ...cmd, - params: desc.params, - description: desc.description ?? cmd.description, - }; -} diff --git a/core/commands/slash/cmd.ts b/core/commands/slash/built-in-legacy/cmd.ts similarity index 91% rename from core/commands/slash/cmd.ts rename to core/commands/slash/built-in-legacy/cmd.ts index 7b93d2fa3..5cd96e365 100644 --- a/core/commands/slash/cmd.ts +++ b/core/commands/slash/built-in-legacy/cmd.ts @@ -1,6 +1,6 @@ -import { streamLines } from "../../diff/util.js"; -import { SlashCommand } from "../../index.js"; -import { removeQuotesAndEscapes } from "../../util/index.js"; +import { streamLines } from "../../../diff/util.js"; +import { SlashCommand } from "../../../index.js"; +import { removeQuotesAndEscapes } from "../../../util/index.js"; function commandIsPotentiallyDangerous(command: string) { return ( diff --git a/core/commands/slash/commit.ts b/core/commands/slash/built-in-legacy/commit.ts similarity index 89% rename from core/commands/slash/commit.ts rename to core/commands/slash/built-in-legacy/commit.ts index 55499b583..1f7e71343 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/built-in-legacy/commit.ts @@ -1,5 +1,5 @@ -import { SlashCommand } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { SlashCommand } from "../../../index.js"; +import { renderChatMessage } from "../../../util/messageContent.js"; const CommitMessageCommand: SlashCommand = { name: "commit", diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/built-in-legacy/draftIssue.ts similarity index 91% rename from core/commands/slash/draftIssue.ts rename to core/commands/slash/built-in-legacy/draftIssue.ts index fba5d4cd3..9a1c5bdf9 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/built-in-legacy/draftIssue.ts @@ -1,6 +1,6 @@ -import { ChatMessage, SlashCommand } from "../../index.js"; -import { removeQuotesAndEscapes } from "../../util/index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { ChatMessage, SlashCommand } from "../../../index.js"; +import { removeQuotesAndEscapes } from "../../../util/index.js"; +import { renderChatMessage } from "../../../util/messageContent.js"; const PROMPT = ( input: string, diff --git a/core/commands/slash/http.ts b/core/commands/slash/built-in-legacy/http.ts similarity index 87% rename from core/commands/slash/http.ts rename to core/commands/slash/built-in-legacy/http.ts index e92c7c3f1..3141dcc11 100644 --- a/core/commands/slash/http.ts +++ b/core/commands/slash/built-in-legacy/http.ts @@ -1,6 +1,6 @@ import { streamResponse } from "@continuedev/fetch"; -import { SlashCommand } from "../../index.js"; -import { removeQuotesAndEscapes } from "../../util/index.js"; +import { SlashCommand } from "../../../index.js"; +import { removeQuotesAndEscapes } from "../../../util/index.js"; const HttpSlashCommand: SlashCommand = { name: "http", diff --git a/core/commands/slash/built-in-legacy/index.ts b/core/commands/slash/built-in-legacy/index.ts new file mode 100644 index 000000000..3e57f67a6 --- /dev/null +++ b/core/commands/slash/built-in-legacy/index.ts @@ -0,0 +1,37 @@ +import { + SlashCommand, + SlashCommandDescription, + SlashCommandWithSource, +} from "../../.."; +import GenerateTerminalCommand from "./cmd"; +import CommitMessageCommand from "./commit"; +import DraftIssueCommand from "./draftIssue"; +import HttpSlashCommand from "./http"; +import OnboardSlashCommand from "./onboard"; +import ReviewMessageCommand from "./review"; +import ShareSlashCommand from "./share"; + +const LegacyBuiltInSlashCommands: SlashCommand[] = [ + DraftIssueCommand, + ShareSlashCommand, + GenerateTerminalCommand, + HttpSlashCommand, + CommitMessageCommand, + ReviewMessageCommand, + OnboardSlashCommand, +]; + +export function getLegacyBuiltInSlashCommandFromDescription( + desc: SlashCommandDescription, +): SlashCommandWithSource | undefined { + const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name); + if (!cmd) { + return undefined; + } + return { + ...cmd, + params: desc.params, + description: desc.description ?? cmd.description, + source: "built-in-legacy", + }; +} diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/built-in-legacy/onboard.ts similarity index 96% rename from core/commands/slash/onboard.ts rename to core/commands/slash/built-in-legacy/onboard.ts index 545b75cc2..969ebc0c4 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/built-in-legacy/onboard.ts @@ -1,17 +1,17 @@ import ignore from "ignore"; -import type { FileType, IDE, SlashCommand } from "../.."; +import type { FileType, IDE, SlashCommand } from "../../.."; import { DEFAULT_IGNORE, getGlobalContinueIgArray, gitIgArrayFromFile, -} from "../../indexing/ignore"; -import { renderChatMessage } from "../../util/messageContent"; +} from "../../../indexing/ignore"; +import { renderChatMessage } from "../../../util/messageContent"; import { findUriInDirs, getUriPathBasename, joinPathsToUri, -} from "../../util/uri"; +} from "../../../util/uri"; const LANGUAGE_DEP_MGMT_FILENAMES = [ "package.json", // JavaScript (Node.js) diff --git a/core/commands/slash/review.ts b/core/commands/slash/built-in-legacy/review.ts similarity index 93% rename from core/commands/slash/review.ts rename to core/commands/slash/built-in-legacy/review.ts index 6190f5499..37c280b34 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/built-in-legacy/review.ts @@ -1,5 +1,5 @@ -import { ChatMessage, SlashCommand } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { ChatMessage, SlashCommand } from "../../../index.js"; +import { renderChatMessage } from "../../../util/messageContent.js"; const prompt = ` Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: diff --git a/core/commands/slash/share.ts b/core/commands/slash/built-in-legacy/share.ts similarity index 92% rename from core/commands/slash/share.ts rename to core/commands/slash/built-in-legacy/share.ts index 01d5bea96..daddf8dff 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/built-in-legacy/share.ts @@ -3,10 +3,10 @@ import { homedir } from "node:os"; import { fileURLToPath, pathToFileURL } from "node:url"; import path from "path"; -import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; -import { SlashCommand } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; -import { getContinueGlobalPath } from "../../util/paths.js"; +import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js"; +import { SlashCommand } from "../../../index.js"; +import { renderChatMessage } from "../../../util/messageContent.js"; +import { getContinueGlobalPath } from "../../../util/paths.js"; // If useful elsewhere, helper funcs should move to core/util/index.ts or similar function getOffsetDatetime(date: Date): Date { diff --git a/core/commands/slash/customSlashCommand.ts b/core/commands/slash/customSlashCommand.ts new file mode 100644 index 000000000..c27a41f4c --- /dev/null +++ b/core/commands/slash/customSlashCommand.ts @@ -0,0 +1,15 @@ +import { CustomCommand, SlashCommandWithSource } from "../.."; + +export function convertCustomCommandToSlashCommand( + customCommand: CustomCommand, +): SlashCommandWithSource { + const commandName = customCommand.name.startsWith("/") + ? customCommand.name.substring(1) + : customCommand.name; + return { + name: commandName, + description: customCommand.description ?? "", + prompt: customCommand.prompt, + source: "json-custom-command", + }; +} diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts deleted file mode 100644 index 18008e251..000000000 --- a/core/commands/slash/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import GenerateTerminalCommand from "./cmd"; -import CommitMessageCommand from "./commit"; -import DraftIssueCommand from "./draftIssue"; -import HttpSlashCommand from "./http"; -import OnboardSlashCommand from "./onboard"; -import ReviewMessageCommand from "./review"; -import ShareSlashCommand from "./share"; - -export default [ - DraftIssueCommand, - ShareSlashCommand, - GenerateTerminalCommand, - HttpSlashCommand, - CommitMessageCommand, - ReviewMessageCommand, - OnboardSlashCommand, -]; diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts deleted file mode 100644 index 89af5c5c2..000000000 --- a/core/commands/slash/mcp.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; - -import { PromptMessage } from "@modelcontextprotocol/sdk/types.js"; -import { ChatMessage, SlashCommand } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; -export function constructMcpSlashCommand( - client: Client, - name: string, - description?: string, - args?: string[], -): SlashCommand { - return { - name, - description: description ?? "MCP Prompt", - params: {}, - run: async function* (context) { - const argsObject: { [key: string]: string } = {}; - const userInput = context.input.split(" ").slice(1).join(" "); - if (args) { - args.forEach((arg, i) => { - argsObject[arg] = ""; // userInput - }); - } - - const result = await client.getPrompt({ name, arguments: argsObject }); - const mcpMessages: PromptMessage[] = result.messages; - const messages: ChatMessage[] = mcpMessages.map((msg) => { - if (msg.content.type !== "text") { - throw new Error( - "Continue currently only supports text prompts through MCP", - ); - } - return { - content: msg.content.text, - role: msg.role, - }; - }); - - if (messages.length === 0) { - yield "The MCP prompt returned no messages"; - return; - } - - if (userInput) { - const lastMessage = messages.at(-1); - if (!lastMessage || lastMessage.role !== "user") { - messages.push({ - role: "user", - content: userInput, - }); - } else { - let newContent = renderChatMessage(lastMessage); - if (newContent) { - newContent += "\n\n"; - } - newContent += userInput; - lastMessage.content = newContent; - } - } - - for await (const chunk of context.llm.streamChat( - messages, - context.abortController.signal, - context.completionOptions, - )) { - yield renderChatMessage(chunk); - } - }, - }; -} diff --git a/core/commands/slash/mcpSlashCommand.ts b/core/commands/slash/mcpSlashCommand.ts new file mode 100644 index 000000000..d9c1278ff --- /dev/null +++ b/core/commands/slash/mcpSlashCommand.ts @@ -0,0 +1,34 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; + +import { SlashCommandWithSource } from "../../index.js"; + +export function constructMcpSlashCommand( + client: Client, + name: string, + description?: string, + args?: string[], +): SlashCommandWithSource { + return { + name, + description: description ?? "MCP Prompt", + source: "mcp-prompt", + params: {}, + }; +} + +export function stringifyMcpPrompt( + prompt: Awaited>, +): string { + const { messages } = prompt; + let stringified = ""; + for (const message of messages) { + if (message.content.type === "text") { + stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`; + } else { + console.warn( + `MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`, + ); + } + } + return stringified; +} diff --git a/core/commands/slash/promptBlockSlashCommand.ts b/core/commands/slash/promptBlockSlashCommand.ts new file mode 100644 index 000000000..00530b8bd --- /dev/null +++ b/core/commands/slash/promptBlockSlashCommand.ts @@ -0,0 +1,13 @@ +import { Prompt } from "@continuedev/config-yaml"; +import { SlashCommandWithSource } from "../.."; + +export function convertPromptBlockToSlashCommand( + prompt: Prompt, +): SlashCommandWithSource { + return { + name: prompt.name, + description: prompt.description ?? "", + prompt: prompt.prompt, + source: "yaml-prompt-block", + }; +} diff --git a/core/commands/slash/promptFileSlashCommand.ts b/core/commands/slash/promptFileSlashCommand.ts new file mode 100644 index 000000000..e076086c0 --- /dev/null +++ b/core/commands/slash/promptFileSlashCommand.ts @@ -0,0 +1,21 @@ +import { SlashCommandWithSource } from "../.."; +import { parsePromptFile } from "../../promptFiles/parsePromptFile"; + +export function slashCommandFromPromptFile( + path: string, + content: string, +): SlashCommandWithSource | null { + const { name, description, systemMessage, prompt, version } = parsePromptFile( + path, + content, + ); + + return { + name, + description, + prompt, + source: version === 1 ? "prompt-file-v1" : "prompt-file-v2", + promptFile: path, + overrideSystemMessage: systemMessage, + }; +} diff --git a/core/commands/util.ts b/core/commands/util.ts index 3785b4f52..ce234919f 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -16,7 +16,7 @@ export function rifWithContentsToContextItem( return { content: rif.contents, name: `${basename} ${rangeStr}`, - description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI + description: `${relativePathOrBasename} ${rangeStr}`, id: { providerTitle: "code", itemId: uuidv4(), diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.vitest.ts similarity index 89% rename from core/config/ConfigHandler.test.ts rename to core/config/ConfigHandler.vitest.ts index 4b4be0762..5af9d6bb8 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.vitest.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import path from "node:path"; +import { describe, expect, test } from "vitest"; import { testConfigHandler } from "../test/fixtures"; import { TEST_DIR } from "../test/testDir"; import { getConfigTsPath } from "../util/paths"; @@ -24,7 +25,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { ); }); - test.skip("should add a system message from config.ts", async () => { + test("should add a system message from config.ts", async () => { const configTs = `export function modifyConfig(config: Config): Config { config.systemMessage = "SYSTEM"; return config; @@ -39,7 +40,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { expect(config.systemMessage).toBe("SYSTEM"); }); - test.skip("should acknowledge override from .continuerc.json", async () => { + test("should acknowledge override from .continuerc.json", async () => { fs.writeFileSync( path.join(TEST_DIR, ".continuerc.json"), JSON.stringify({ systemMessage: "SYSTEM2" }), diff --git a/core/config/load.ts b/core/config/load.ts index fe0c4de61..a084bbd38 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -30,14 +30,12 @@ import { ModelDescription, RerankerDescription, SerializedContinueConfig, - SlashCommand, + SlashCommandWithSource, } from ".."; -import { - slashCommandFromDescription, - slashFromCustomCommand, -} from "../commands/index"; +import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy"; +import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand"; +import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand"; import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; -import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import FileContextProvider from "../context/providers/FileContextProvider"; @@ -48,8 +46,7 @@ import { LLMClasses, llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import { LLMReranker } from "../llm/llms/llm"; import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider"; -import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; -import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; +import { getAllPromptFiles } from "../promptFiles/getPromptFiles"; import { copyOf } from "../util"; import { GlobalContext } from "../util/GlobalContext"; import mergeJson from "../util/merge"; @@ -65,7 +62,8 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { baseToolDefinitions } from "../tools"; +import { getToolsForIde } from "../tools"; +import { resolveRelativePathInDir } from "../util/ideUtils"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; import { getModelByRole, @@ -174,15 +172,15 @@ async function serializedToIntermediateConfig( ide: IDE, ): Promise { // DEPRECATED - load custom slash commands - const slashCommands: SlashCommand[] = []; + const slashCommands: SlashCommandWithSource[] = []; for (const command of initial.slashCommands || []) { - const newCommand = slashCommandFromDescription(command); + const newCommand = getLegacyBuiltInSlashCommandFromDescription(command); if (newCommand) { slashCommands.push(newCommand); } } for (const command of initial.customCommands || []) { - slashCommands.push(slashFromCustomCommand(command)); + slashCommands.push(convertCustomCommandToSlashCommand(command)); } // DEPRECATED - load slash commands from v1 prompt files @@ -194,7 +192,7 @@ async function serializedToIntermediateConfig( ); for (const file of promptFiles) { - const slashCommand = slashCommandFromPromptFileV1(file.path, file.content); + const slashCommand = slashCommandFromPromptFile(file.path, file.content); if (slashCommand) { slashCommands.push(slashCommand); } @@ -254,7 +252,10 @@ async function intermediateToFinalConfig({ loadPromptFiles?: boolean; }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { const errors: ConfigValidationError[] = []; - + const workspaceDirs = await ide.getWorkspaceDirs(); + const getUriFromPath = (path: string) => { + return resolveRelativePathInDir(path, ide, workspaceDirs); + }; // Auto-detect models let models: BaseLLM[] = []; await Promise.all( @@ -263,6 +264,7 @@ async function intermediateToFinalConfig({ const llm = await llmFromDescription( desc, ide.readFile.bind(ide), + getUriFromPath, uniqueId, ideSettings, llmLogger, @@ -284,6 +286,7 @@ async function intermediateToFinalConfig({ title: modelName, }, ide.readFile.bind(ide), + getUriFromPath, uniqueId, ideSettings, llmLogger, @@ -360,6 +363,7 @@ async function intermediateToFinalConfig({ const llm = await llmFromDescription( desc, ide.readFile.bind(ide), + getUriFromPath, uniqueId, ideSettings, llmLogger, @@ -393,13 +397,7 @@ async function intermediateToFinalConfig({ | undefined )?.params || {}; - const DEFAULT_CONTEXT_PROVIDERS = [ - new FileContextProvider({}), - // Add codebase provider if indexing is enabled - ...(!config.disableIndexing - ? [new CodebaseContextProvider(codebaseContextParams)] - : []), - ]; + const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( ({ description: { title } }) => title, @@ -527,9 +525,9 @@ async function intermediateToFinalConfig({ const continueConfig: ContinueConfig = { ...config, contextProviders, - tools: [...baseToolDefinitions], + tools: await getToolsForIde(ide), mcpServerStatuses: [], - slashCommands: config.slashCommands ?? [], + slashCommands: [], modelsByRole: { chat: models, edit: models, @@ -551,6 +549,17 @@ async function intermediateToFinalConfig({ rules: [], }; + for (const cmd of config.slashCommands ?? []) { + if ("source" in cmd) { + continueConfig.slashCommands.push(cmd); + } else { + continueConfig.slashCommands.push({ + ...cmd, + source: "config-ts-slash-command", + }); + } + } + if (config.systemMessage) { continueConfig.rules.unshift({ rule: config.systemMessage, @@ -651,9 +660,10 @@ async function finalToBrowserConfig( return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, completionOptions: final.completionOptions, - slashCommands: final.slashCommands?.map( - ({ run, ...slashCommandDescription }) => slashCommandDescription, - ), + slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({ + ...rest, + isLegacy: !!run, + })), contextProviders: final.contextProviders?.map((c) => c.description), disableIndexing: final.disableIndexing, disableSessionTitles: final.disableSessionTitles, @@ -975,7 +985,6 @@ async function loadContinueConfigFromJson( export { finalToBrowserConfig, - intermediateToFinalConfig, loadContinueConfigFromJson, type BrowserSerializedContinueConfig, }; diff --git a/core/config/loadLocalAssistants.test.ts b/core/config/loadLocalAssistants.vitest.ts similarity index 99% rename from core/config/loadLocalAssistants.test.ts rename to core/config/loadLocalAssistants.vitest.ts index 2865a5b34..a366316d4 100644 --- a/core/config/loadLocalAssistants.test.ts +++ b/core/config/loadLocalAssistants.vitest.ts @@ -1,3 +1,4 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { walkDirCache } from "../indexing/walkDir"; import { testIde } from "../test/fixtures"; import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir"; diff --git a/core/config/markdown/loadCodebaseRules.ts b/core/config/markdown/loadCodebaseRules.ts index b0d8cac6d..a239f56f1 100644 --- a/core/config/markdown/loadCodebaseRules.ts +++ b/core/config/markdown/loadCodebaseRules.ts @@ -33,7 +33,7 @@ export async function loadCodebaseRules(ide: IDE): Promise<{ const content = await ide.readFile(filePath); const rule = markdownToRule(content, { uriType: "file", filePath }); - rules.push({ ...rule, source: "rules-block" }); + rules.push({ ...rule, source: "rules-block", ruleFile: filePath }); } catch (e) { errors.push({ fatal: false, diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index dd506f75c..e3d32e237 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -33,7 +33,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ uriType: "file", filePath: file.path, }); - rules.push({ ...rule, source: "rules-block" }); + rules.push({ ...rule, source: "rules-block", ruleFile: file.path }); } catch (e) { errors.push({ fatal: false, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 7685546c9..bd142a895 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -16,9 +16,9 @@ import { ILLMLogger, RuleWithSource, SerializedContinueConfig, + SlashCommandDescWithSource, Tool, } from "../../"; -import { constructMcpSlashCommand } from "../../commands/slash/mcp"; import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; import MCPContextProvider from "../../context/providers/MCPContextProvider"; import RulesContextProvider from "../../context/providers/RulesContextProvider"; @@ -190,14 +190,15 @@ export default async function doLoadConfig(options: { })); newConfig.tools.push(...serverTools); - const serverSlashCommands = server.prompts.map((prompt) => - constructMcpSlashCommand( - server.client, - prompt.name, - prompt.description, - prompt.arguments?.map((a: any) => a.name), - ), - ); + const serverSlashCommands: SlashCommandDescWithSource[] = + server.prompts.map((prompt) => ({ + name: prompt.name, + description: prompt.description ?? "MCP Prompt", + source: "mcp-prompt", + isLegacy: false, + mcpServerName: server.name, // Used in client to retrieve prompt + mcpArgs: prompt.arguments, + })); newConfig.slashCommands.push(...serverSlashCommands); const submenuItems = server.resources @@ -229,6 +230,8 @@ export default async function doLoadConfig(options: { newConfig.tools.push( ...getConfigDependentToolDefinitions({ rules: newConfig.rules, + enableExperimentalTools: + newConfig.experimental?.enableExperimentalTools ?? false, }), ); diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 439925188..5d7053cf8 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -19,6 +19,10 @@ export const sharedConfigSchema = z readResponseTTS: z.boolean(), promptPath: z.string(), useCurrentFileAsContext: z.boolean(), + logEditingData: z.boolean(), + optInNextEditFeature: z.boolean(), + enableExperimentalTools: z.boolean(), + codebaseToolCallingOnly: z.boolean(), // `ui` in `ContinueConfig` showSessionTabs: z.boolean(), @@ -157,6 +161,12 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental = { ...configCopy.experimental, }; + + if (sharedConfig.enableExperimentalTools !== undefined) { + configCopy.experimental.enableExperimentalTools = + sharedConfig.enableExperimentalTools; + } + if (sharedConfig.promptPath !== undefined) { configCopy.experimental.promptPath = sharedConfig.promptPath; } @@ -171,6 +181,17 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.useCurrentFileAsContext = sharedConfig.useCurrentFileAsContext; } + if (sharedConfig.logEditingData !== undefined) { + configCopy.experimental.logEditingData = sharedConfig.logEditingData; + } + if (sharedConfig.optInNextEditFeature !== undefined) { + configCopy.experimental.optInNextEditFeature = + sharedConfig.optInNextEditFeature; + } + if (sharedConfig.codebaseToolCallingOnly !== undefined) { + configCopy.experimental.codebaseToolCallingOnly = + sharedConfig.codebaseToolCallingOnly; + } return configCopy; } diff --git a/core/config/usesFreeTrialApiKey.test.ts b/core/config/usesFreeTrialApiKey.test.ts deleted file mode 100644 index 8e8727084..000000000 --- a/core/config/usesFreeTrialApiKey.test.ts +++ /dev/null @@ -1,344 +0,0 @@ -import { jest } from "@jest/globals"; -import { BrowserSerializedContinueConfig } from ".."; - -// Create the mock before importing anything else -const mockDecodeSecretLocation = jest.fn(); - -// Mock the module -jest.unstable_mockModule("@continuedev/config-yaml", () => ({ - SecretType: { - User: "user", - Organization: "organization", - FreeTrial: "free_trial", - }, - decodeSecretLocation: mockDecodeSecretLocation, -})); - -// Import after mocking -const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey"); -const { SecretType } = await import("@continuedev/config-yaml"); - -beforeEach(() => { - mockDecodeSecretLocation.mockReset(); -}); - -test("usesFreeTrialApiKey should return false when config is null", () => { - const result = usesFreeTrialApiKey(null); - expect(result).toBe(false); -}); - -test("usesFreeTrialApiKey should return false when config is undefined", () => { - const result = usesFreeTrialApiKey(undefined as any); - expect(result).toBe(false); -}); - -test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - underlyingProviderName: "test", - }, - { - title: "Model 2", - provider: "test", - model: "test-model-2", - underlyingProviderName: "test", - }, - ], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); -}); - -test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "user:testuser/api-key", - underlyingProviderName: "test", - }, - ], - edit: [ - { - title: "Model 2", - provider: "test", - model: "test-model-2", - apiKeyLocation: "organization:testorg/api-key", - underlyingProviderName: "test", - }, - ], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation - .mockReturnValueOnce({ - secretType: SecretType.User, - userSlug: "testuser", - secretName: "api-key", - }) - .mockReturnValueOnce({ - secretType: SecretType.Organization, - orgSlug: "testorg", - secretName: "api-key", - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); -}); - -test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "user:testuser/api-key", - underlyingProviderName: "test", - }, - { - title: "Free Trial Model", - provider: "test", - model: "free-trial-model", - apiKeyLocation: "free_trial:owner/package/api-key", - underlyingProviderName: "test", - }, - ], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation - .mockReturnValueOnce({ - secretType: SecretType.User, - userSlug: "testuser", - secretName: "api-key", - }) - .mockReturnValueOnce({ - secretType: SecretType.FreeTrial, - blockSlug: { ownerSlug: "owner", packageSlug: "package" }, - secretName: "api-key", - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(true); - expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); -}); - -test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "user:testuser/api-key", - underlyingProviderName: "test", - }, - ], - edit: [ - { - title: "Free Trial Edit Model", - provider: "test", - model: "free-trial-edit-model", - apiKeyLocation: "free_trial:owner/package/api-key", - underlyingProviderName: "test", - }, - ], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation - .mockReturnValueOnce({ - secretType: SecretType.User, - userSlug: "testuser", - secretName: "api-key", - }) - .mockReturnValueOnce({ - secretType: SecretType.FreeTrial, - blockSlug: { ownerSlug: "owner", packageSlug: "package" }, - secretName: "api-key", - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(true); -}); - -test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => { - const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {}); - - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [ - { - title: "Model 1", - provider: "test", - model: "test-model", - apiKeyLocation: "invalid-secret-location", - underlyingProviderName: "test", - }, - ], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - mockDecodeSecretLocation.mockImplementation(() => { - throw new Error("Invalid secret location format"); - }); - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(consoleSpy).toHaveBeenCalledWith( - "Error checking for free trial API key:", - expect.any(Error), - ); - - consoleSpy.mockRestore(); -}); - -test("usesFreeTrialApiKey should handle empty modelsByRole object", () => { - const config: BrowserSerializedContinueConfig = { - modelsByRole: { - chat: [], - edit: [], - apply: [], - summarize: [], - autocomplete: [], - rerank: [], - embed: [], - }, - selectedModelByRole: { - chat: null, - edit: null, - apply: null, - summarize: null, - autocomplete: null, - rerank: null, - embed: null, - }, - contextProviders: [], - slashCommands: [], - tools: [], - mcpServerStatuses: [], - usePlatform: false, - rules: [], - }; - - const result = usesFreeTrialApiKey(config); - expect(result).toBe(false); - expect(mockDecodeSecretLocation).not.toHaveBeenCalled(); -}); diff --git a/core/config/usesFreeTrialApiKey.vitest.ts b/core/config/usesFreeTrialApiKey.vitest.ts new file mode 100644 index 000000000..b92dd90a2 --- /dev/null +++ b/core/config/usesFreeTrialApiKey.vitest.ts @@ -0,0 +1,348 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { BrowserSerializedContinueConfig } from ".."; + +// Create the mock before importing anything else +const mockDecodeSecretLocation = vi.fn(); + +// Mock the module +vi.mock("@continuedev/config-yaml", () => ({ + SecretType: { + User: "user", + Organization: "organization", + FreeTrial: "free_trial", + }, + decodeSecretLocation: mockDecodeSecretLocation, +})); + +describe("usesFreeTrialApiKey", () => { + let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey; + let SecretType: typeof import("@continuedev/config-yaml").SecretType; + + beforeEach(async () => { + mockDecodeSecretLocation.mockReset(); + usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey")) + .usesFreeTrialApiKey; + SecretType = (await import("@continuedev/config-yaml")).SecretType; + }); + + test("usesFreeTrialApiKey should return false when config is null", () => { + const result = usesFreeTrialApiKey(null); + expect(result).toBe(false); + }); + + test("usesFreeTrialApiKey should return false when config is undefined", () => { + const result = usesFreeTrialApiKey(undefined as any); + expect(result).toBe(false); + }); + + test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + underlyingProviderName: "test", + }, + { + title: "Model 2", + provider: "test", + model: "test-model-2", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + }); + + test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + ], + edit: [ + { + title: "Model 2", + provider: "test", + model: "test-model-2", + apiKeyLocation: "organization:testorg/api-key", + underlyingProviderName: "test", + }, + ], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.Organization, + orgSlug: "testorg", + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); + }); + + test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + { + title: "Free Trial Model", + provider: "test", + model: "free-trial-model", + apiKeyLocation: "free_trial:owner/package/api-key", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.FreeTrial, + blockSlug: { ownerSlug: "owner", packageSlug: "package" }, + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(true); + expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); + }); + + test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + ], + edit: [ + { + title: "Free Trial Edit Model", + provider: "test", + model: "free-trial-edit-model", + apiKeyLocation: "free_trial:owner/package/api-key", + underlyingProviderName: "test", + }, + ], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.FreeTrial, + blockSlug: { ownerSlug: "owner", packageSlug: "package" }, + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(true); + }); + + test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => { + const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "invalid-secret-location", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation.mockImplementation(() => { + throw new Error("Invalid secret location format"); + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(consoleSpy).toHaveBeenCalledWith( + "Error checking for free trial API key:", + expect.any(Error), + ); + + consoleSpy.mockRestore(); + }); + + test("usesFreeTrialApiKey should handle empty modelsByRole object", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(mockDecodeSecretLocation).not.toHaveBeenCalled(); + }); +}); diff --git a/core/config/util.ts b/core/config/util.ts index 9128fc0b5..a53027a76 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -10,7 +10,7 @@ import { JSONModelDescription, PromptTemplate, } from "../"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; diff --git a/core/config/util.test.ts b/core/config/util.vitest.ts similarity index 96% rename from core/config/util.test.ts rename to core/config/util.vitest.ts index e7de79e1b..5ea63c879 100644 --- a/core/config/util.test.ts +++ b/core/config/util.vitest.ts @@ -1,3 +1,4 @@ +import { describe, expect, it } from "vitest"; import { PromptTemplate } from ".."; import { serializePromptTemplates } from "./util"; diff --git a/core/config/workspace/workspaceBlocks.test.ts b/core/config/workspace/workspaceBlocks.vitest.ts similarity index 98% rename from core/config/workspace/workspaceBlocks.test.ts rename to core/config/workspace/workspaceBlocks.vitest.ts index 532444196..281a4d785 100644 --- a/core/config/workspace/workspaceBlocks.test.ts +++ b/core/config/workspace/workspaceBlocks.vitest.ts @@ -1,5 +1,5 @@ import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml"; -import { describe, expect, test } from "@jest/globals"; +import { describe, expect, test } from "vitest"; import { findAvailableFilename, getFileContent } from "./workspaceBlocks"; describe("getFileContent", () => { diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index ba17eae78..f1546e255 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -25,19 +25,18 @@ import { ILLMLogger, RuleWithSource, } from "../.."; -import { slashFromCustomCommand } from "../../commands"; import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; -import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import FileContextProvider from "../../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../../context/providers/index"; import { ControlPlaneClient } from "../../control-plane/client"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; -import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; -import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; +import { getAllPromptFiles } from "../../promptFiles/getPromptFiles"; import { GlobalContext } from "../../util/GlobalContext"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; +import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; +import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; import { getControlPlaneEnvSync } from "../../control-plane/env"; import { getToolsForIde } from "../../tools"; import { getCleanUriPath } from "../../util/uri"; @@ -263,7 +262,7 @@ async function configYamlToContinueConfig(options: { promptFiles.forEach((file) => { try { - const slashCommand = slashCommandFromPromptFileV1( + const slashCommand = slashCommandFromPromptFile( file.path, file.content, ); @@ -286,7 +285,7 @@ async function configYamlToContinueConfig(options: { config.prompts?.forEach((prompt) => { try { - const slashCommand = slashFromCustomCommand(prompt); + const slashCommand = convertPromptBlockToSlashCommand(prompt); continueConfig.slashCommands?.push(slashCommand); } catch (e) { localErrors.push({ @@ -385,13 +384,7 @@ async function configYamlToContinueConfig(options: { } // Context providers - const codebaseContextParams: IContextProvider[] = - (config.context || []).find((cp) => cp.provider === "codebase")?.params || - {}; - const DEFAULT_CONTEXT_PROVIDERS = [ - new FileContextProvider({}), - new CodebaseContextProvider(codebaseContextParams), - ]; + const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( ({ description: { title } }) => title, diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.vitest.ts similarity index 94% rename from core/context/mcp/MCPConnection.test.ts rename to core/context/mcp/MCPConnection.vitest.ts index f8f146f07..7736ebec9 100644 --- a/core/context/mcp/MCPConnection.test.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -1,10 +1,10 @@ -import { jest } from "@jest/globals"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import MCPConnection from "./MCPConnection"; describe("MCPConnection", () => { beforeEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe("constructor", () => { @@ -131,10 +131,10 @@ describe("MCPConnection", () => { it("should connect successfully", async () => { const conn = new MCPConnection(options); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockResolvedValue(undefined); - const mockGetServerCapabilities = jest + const mockGetServerCapabilities = vi .spyOn(Client.prototype, "getServerCapabilities") .mockReturnValue({ resources: {}, @@ -142,12 +142,12 @@ describe("MCPConnection", () => { prompts: {}, }); - const mockListResources = jest + const mockListResources = vi .spyOn(Client.prototype, "listResources") .mockResolvedValue({ resources: [{ name: "test-resource", uri: "test-uri" }], }); - const mockListTools = jest + const mockListTools = vi .spyOn(Client.prototype, "listTools") .mockResolvedValue({ tools: [ @@ -159,7 +159,7 @@ describe("MCPConnection", () => { }, ], }); - const mockListPrompts = jest + const mockListPrompts = vi .spyOn(Client.prototype, "listPrompts") .mockResolvedValue({ prompts: [{ name: "test-prompt" }] }); @@ -175,7 +175,7 @@ describe("MCPConnection", () => { it("should handle custom connection timeout", async () => { const conn = new MCPConnection({ ...options, timeout: 1500 }); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockImplementation( () => new Promise((resolve) => setTimeout(resolve, 1000)), @@ -190,7 +190,7 @@ describe("MCPConnection", () => { it("should handle connection timeout", async () => { const conn = new MCPConnection({ ...options, timeout: 1 }); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockImplementation( () => new Promise((resolve) => setTimeout(resolve, 100)), @@ -208,7 +208,7 @@ describe("MCPConnection", () => { const conn = new MCPConnection(options); conn.status = "connected"; - const mockConnect = jest.spyOn(Client.prototype, "connect"); + const mockConnect = vi.spyOn(Client.prototype, "connect"); const abortController = new AbortController(); await conn.connectClient(false, abortController.signal); @@ -219,7 +219,7 @@ describe("MCPConnection", () => { it("should handle transport errors", async () => { const conn = new MCPConnection(options); - const mockConnect = jest + const mockConnect = vi .spyOn(Client.prototype, "connect") .mockRejectedValue(new Error("spawn test-cmd ENOENT")); @@ -233,7 +233,7 @@ describe("MCPConnection", () => { it.skip("should include stderr output in error message when stdio command fails", async () => { // Clear any existing mocks to ensure we get real behavior - jest.restoreAllMocks(); + vi.restoreAllMocks(); // Use a command that will definitely fail and produce stderr output const failingOptions = { diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index d0d7c0991..7eafa1564 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -161,4 +161,21 @@ export class MCPManagerSingleton { client: connection.client, })); } + + async getPrompt( + serverName: string, + promptName: string, + args: Record = {}, + ) { + const connection = this.connections.get(serverName); + if (!connection) { + throw new Error( + `Error getting prompt: MCP Connection ${serverName} not found`, + ); + } + return await connection.client.getPrompt({ + name: promptName, + arguments: args, + }); + } } diff --git a/core/context/mcp/MCPManagerSingleton.test.ts b/core/context/mcp/MCPManagerSingleton.vitest.ts similarity index 91% rename from core/context/mcp/MCPManagerSingleton.test.ts rename to core/context/mcp/MCPManagerSingleton.vitest.ts index 49e2389d6..f361c13a1 100644 --- a/core/context/mcp/MCPManagerSingleton.test.ts +++ b/core/context/mcp/MCPManagerSingleton.vitest.ts @@ -1,3 +1,4 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; import { MCPOptions } from "../.."; import MCPConnection from "./MCPConnection"; import { MCPManagerSingleton } from "./MCPManagerSingleton"; @@ -18,8 +19,8 @@ class TestMCPConnection extends MCPConnection { } as any; this.abortController = new AbortController(); - this.connectClient = jest.fn().mockResolvedValue(undefined); - this.getStatus = jest + this.connectClient = vi.fn().mockResolvedValue(undefined); + this.getStatus = vi .fn() .mockReturnValue({ status: "connected", errors: [] }); } @@ -54,13 +55,12 @@ describe("MCPManagerSingleton", () => { id: string, options: MCPOptions, ): MCPConnection { - if (!this.connections.has(id)) { - const connection = new TestMCPConnection(options); - this.connections.set(id, connection); - return connection; - } else { + if (this.connections.has(id)) { return this.connections.get(id)!; } + const connection = new TestMCPConnection(options); + this.connections.set(id, connection); + return connection; }; }); @@ -103,7 +103,7 @@ describe("MCPManagerSingleton", () => { "test-id", testOptions, ) as TestMCPConnection; - const closeSpy = jest.spyOn(connection.client, "close"); + const closeSpy = vi.spyOn(connection.client, "close"); await manager.removeConnection("test-id"); @@ -133,8 +133,8 @@ describe("MCPManagerSingleton", () => { "test-id", testOptions, ) as TestMCPConnection; - const abortSpy = jest.spyOn(connection.abortController, "abort"); - const closeSpy = jest.spyOn(connection.client, "close"); + const abortSpy = vi.spyOn(connection.abortController, "abort"); + const closeSpy = vi.spyOn(connection.client, "close"); // Remove it by setting empty server list manager.setConnections([], false); @@ -192,7 +192,7 @@ describe("MCPManagerSingleton", () => { }); it("should call onConnectionsRefreshed if defined", async () => { - const mockCallback = jest.fn(); + const mockCallback = vi.fn(); manager.onConnectionsRefreshed = mockCallback; manager.createConnection("test-id", testOptions); @@ -209,7 +209,7 @@ describe("MCPManagerSingleton", () => { testOptions, ) as TestMCPConnection; const mockStatus = { status: "connected", errors: [] }; - connection.getStatus = jest.fn().mockReturnValue(mockStatus); + connection.getStatus = vi.fn().mockReturnValue(mockStatus); const statuses = manager.getStatuses(); expect(statuses).toHaveLength(1); diff --git a/core/context/providers/TerminalContextProvider.ts b/core/context/providers/TerminalContextProvider.ts index 88577c946..d0f6e12b3 100644 --- a/core/context/providers/TerminalContextProvider.ts +++ b/core/context/providers/TerminalContextProvider.ts @@ -21,7 +21,9 @@ class TerminalContextProvider extends BaseContextProvider { return [ { description: "The contents of the terminal", - content: `Current terminal contents:\n\n${content}`, + content: `Current terminal contents:\n\n${ + content || "The terminal is empty." + }`, name: "Terminal", }, ]; diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.vitest.ts similarity index 90% rename from core/context/providers/_context-providers.test.ts rename to core/context/providers/_context-providers.vitest.ts index 468aac6ec..7ae55d32e 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.vitest.ts @@ -1,5 +1,6 @@ import fetch from "node-fetch"; +import { afterAll, describe, expect, test } from "vitest"; import { contextProviderClassFromName } from "."; import { ContextProviderExtras, @@ -8,7 +9,7 @@ import { } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { LLMLogger } from "../../llm/logger"; -import { TEST_DIR } from "../../test/testDir"; +import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir"; import FileSystemIde from "../../util/filesystem"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ @@ -25,6 +26,7 @@ const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ async function getContextProviderExtras( fullInput: string, ): Promise { + setUpTestDir(); const ide = new FileSystemIde(TEST_DIR); const ideSettingsPromise = ide.getIdeSettings(); const llmLogger = new LLMLogger(); @@ -52,6 +54,10 @@ async function getContextProviderExtras( } describe.skip("Should successfully run all context providers", () => { + afterAll(() => { + tearDownTestDir(); + }); + const extrasPromise = getContextProviderExtras("Test"); CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => { diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index d9fa14bd3..910b16c14 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,7 +1,9 @@ import { BaseContextProvider } from "../"; import { ContextProviderName } from "../../"; +import { Telemetry } from "../../util/posthog"; import ClipboardContextProvider from "./ClipboardContextProvider"; +import CodebaseContextProvider from "./CodebaseContextProvider"; import CodeContextProvider from "./CodeContextProvider"; import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; import CurrentFileContextProvider from "./CurrentFileContextProvider"; @@ -56,6 +58,7 @@ export const Providers: (typeof BaseContextProvider)[] = [ JiraIssuesContextProvider, PostgresContextProvider, DatabaseContextProvider, + CodebaseContextProvider, CodeContextProvider, CurrentFileContextProvider, URLContextProvider, @@ -73,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [ export function contextProviderClassFromName( name: ContextProviderName, ): typeof BaseContextProvider | undefined { - return Providers.find((cls) => cls.description.title === name); + const provider = Providers.find((cls) => cls.description.title === name); + + void Telemetry.capture("context_provider_load", { + providerName: name, + found: !!provider, // also capture those which user expected to be present + }); + + return provider; } diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index b8e196cff..d13da2145 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,14 +1,40 @@ // @ts-ignore import nlp from "wink-nlp-utils"; -import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; +import { + BranchAndDir, + Chunk, + ContextItem, + ContinueConfig, + IDE, + ILLM, + Tool, + ToolExtras, +} from "../../../"; import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache"; import { chunkDocument } from "../../../indexing/chunk/chunk"; import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { BuiltInToolNames } from "../../../tools/builtIn"; +import { callBuiltInTool } from "../../../tools/callTool"; +import { globSearchTool } from "../../../tools/definitions/globSearch"; +import { grepSearchTool } from "../../../tools/definitions/grepSearch"; +import { lsTool } from "../../../tools/definitions/lsTool"; +import { readFileTool } from "../../../tools/definitions/readFile"; +import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap"; +import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory"; const DEFAULT_CHUNK_SIZE = 384; +const AVAILABLE_TOOLS: Tool[] = [ + globSearchTool, + grepSearchTool, + lsTool, + readFileTool, + viewRepoMapTool, + viewSubdirectoryTool, +]; + export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; @@ -155,4 +181,105 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { run(args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } + + protected async retrieveWithTools(input: string): Promise { + const toolSelectionPrompt = `Given the following user input: "${input}" + +Available tools: +${AVAILABLE_TOOLS.map((tool) => { + const requiredParams = tool.function.parameters?.required || []; + const properties = tool.function.parameters?.properties || {}; + const paramDescriptions = requiredParams + .map( + (param: any) => `${param}: ${properties[param]?.description || "string"}`, + ) + .join(", "); + + return `- ${tool.function.name}: ${tool.function.description} + Required arguments: ${paramDescriptions || "none"}`; +}).join("\n")} + +Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else: +{ + "tools": [ + { + "name": "", + "args": { "": "" } + } + ] +}`; + + // Get LLM response for tool selection + const toolSelectionResponse = await this.options.llm.chat( + [{ role: "user", content: toolSelectionPrompt }], + new AbortController().signal, + ); + + let toolCalls: { name: string; args: any }[] = []; + try { + const responseContent = + typeof toolSelectionResponse.content === "string" + ? toolSelectionResponse.content + : toolSelectionResponse.content + .map((part) => (part.type === "text" ? part.text : "")) + .join(""); + const parsed = JSON.parse(responseContent); + toolCalls = parsed.tools || []; + console.log("retrieveWithTools", toolCalls); + } catch (e) { + console.log("Failed to parse tool selection response", e); + return []; + } + + // Execute tools and collect results + const allContextItems: ContextItem[] = []; + + const toolExtras: ToolExtras = { + ide: this.options.ide, + llm: this.options.llm, + fetch: fetch, + tool: grepSearchTool, + config: this.options.config, + }; + + for (const toolCall of toolCalls) { + const tool = AVAILABLE_TOOLS.find( + (t) => t.function.name === toolCall.name, + )!; + + const args = toolCall.args; + if (toolCall.name === BuiltInToolNames.GrepSearch) { + args.splitByFile = true; + } + + toolExtras.tool = tool; + const contextItems = await callBuiltInTool( + toolCall.name, + args, + toolExtras, + ); + allContextItems.push(...contextItems); + } + + const chunks: Chunk[] = []; + + // Transform ContextItem[] to Chunk[] + for (let i = 0; i < allContextItems.length; i++) { + const contextItem = allContextItems[i]; + const filepath = contextItem.uri?.value || contextItem.name || "unknown"; + const cleanedFilepath = filepath.replace(/^file:\/\/\//, ""); + + chunks.push({ + content: contextItem.content, + startLine: -1, + endLine: -1, + digest: `file:///${cleanedFilepath}`, + filepath: `file:///${cleanedFilepath}`, + index: i, + }); + } + + console.log("retrieveWithTools chunks", chunks); + return chunks; + } } diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index ca88c479e..f98a48c41 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -64,12 +64,22 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { console.error("Error retrieving repo map chunks:", error); } - retrievalResults.push( - ...recentlyEditedFilesChunks, - ...ftsChunks, - ...embeddingsChunks, - ...repoMapChunks, - ); + if (this.options.config.experimental?.codebaseToolCallingOnly) { + let toolBasedChunks: Chunk[] = []; + try { + toolBasedChunks = await this.retrieveWithTools(input); + } catch (error) { + console.error("Error retrieving tool based chunks:", error); + } + retrievalResults.push(...toolBasedChunks); + } else { + retrievalResults.push( + ...recentlyEditedFilesChunks, + ...ftsChunks, + ...embeddingsChunks, + ...repoMapChunks, + ); + } if (filterDirectory) { // Backup if the individual retrieval methods don't listen diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 28de3d096..8a9d053fd 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -58,12 +58,22 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { console.error("Error retrieving repo map chunks:", error); } - retrievalResults.push( - ...recentlyEditedFilesChunks, - ...ftsChunks, - ...embeddingsChunks, - ...repoMapChunks, - ); + if (config.experimental?.codebaseToolCallingOnly) { + let toolBasedChunks: Chunk[] = []; + try { + toolBasedChunks = await this.retrieveWithTools(input); + } catch (error) { + console.error("Error retrieving tool based chunks:", error); + } + retrievalResults.push(...toolBasedChunks); + } else { + retrievalResults.push( + ...recentlyEditedFilesChunks, + ...ftsChunks, + ...embeddingsChunks, + ...repoMapChunks, + ); + } if (filterDirectory) { // Backup if the individual retrieval methods don't listen @@ -107,7 +117,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); results.sort( - (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], + (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!], ); results = results.slice(-this.options.nFinal); return results; diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 3b8e98427..31dc8750b 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -108,7 +108,11 @@ export async function retrieveContextItemsFromEmbeddings( } return { - name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`, + // Don't show line numbers for tool calls where startLine = -1 + name: + r.startLine === -1 + ? baseName + : `${baseName} (${r.startLine + 1}-${r.endLine + 1})`, description: last2Parts, content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``, uri: { diff --git a/core/context/retrieval/utils.test.ts b/core/context/retrieval/utils.vitest.ts similarity index 98% rename from core/context/retrieval/utils.test.ts rename to core/context/retrieval/utils.vitest.ts index 4b8d9d3fe..133e30c8e 100644 --- a/core/context/retrieval/utils.test.ts +++ b/core/context/retrieval/utils.vitest.ts @@ -1,6 +1,6 @@ // Generated by Continue +import { describe, expect, it } from "vitest"; import { Chunk } from "../../index"; - import { deduplicateChunks } from "./util"; describe("deduplicateChunks", () => { diff --git a/core/core.ts b/core/core.ts index 5e8d4d060..7708463ad 100644 --- a/core/core.ts +++ b/core/core.ts @@ -10,7 +10,6 @@ import { import { ConfigHandler } from "./config/ConfigHandler"; import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; import { addModel, deleteModel } from "./config/util"; -import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; @@ -21,7 +20,8 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { countTokens } from "./llm/countTokens"; import Ollama from "./llm/llms/Ollama"; -import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; +import { EditAggregator } from "./nextEdit/context/aggregateEdits"; +import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; import { callTool } from "./tools/callTool"; import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; @@ -38,18 +38,20 @@ import { TTS } from "./util/tts"; import { CompleteOnboardingPayload, + ContextItemId, ContextItemWithId, IdeSettings, ModelDescription, + Position, RangeInFile, ToolCall, type ContextItem, - type ContextItemId, type IDE, } from "."; import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; +import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand"; import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; import { setupLocalConfig, @@ -66,6 +68,8 @@ import { walkDirCache } from "./indexing/walkDir"; import { LLMLogger } from "./llm/logger"; import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants"; import { llmStreamChat } from "./llm/streamChat"; +import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting"; +import { processSmallEdit } from "./nextEdit/context/processSmallEdit"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -381,6 +385,19 @@ export class Core { on("mcp/reloadServer", async (msg) => { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); + on("mcp/getPrompt", async (msg) => { + const { serverName, promptName, args } = msg.data; + const prompt = await MCPManagerSingleton.getInstance().getPrompt( + serverName, + promptName, + args, + ); + const stringifiedPrompt = stringifyMcpPrompt(prompt); + return { + prompt: stringifiedPrompt, + description: prompt.description, + }; + }); // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); @@ -541,7 +558,6 @@ export class Core { : undefined, input: data.input, language: data.language, - onlyOneInsertion: false, overridePrompt: undefined, abortController, }); @@ -702,6 +718,52 @@ export class Core { } }); + on("files/smallEdit", async ({ data }) => { + const EDIT_AGGREGATION_OPTIONS = { + deltaT: 1.0, + deltaL: 5, + maxEdits: 500, + maxDuration: 120.0, + contextSize: 5, + }; + + EditAggregator.getInstance( + EDIT_AGGREGATION_OPTIONS, + ( + beforeAfterdiff: BeforeAfterDiff, + cursorPosBeforeEdit: Position, + cursorPosAfterPrevEdit: Position, + ) => { + void processSmallEdit( + beforeAfterdiff, + cursorPosBeforeEdit, + cursorPosAfterPrevEdit, + data.configHandler, + data.getDefsFromLspFunction, + this.ide, + ); + }, + ); + + const workspaceDir = + data.actions.length > 0 ? data.actions[0].workspaceDir : undefined; + + // Store the latest context data + const instance = EditAggregator.getInstance(); + (instance as any).latestContextData = { + configHandler: data.configHandler, + getDefsFromLspFunction: data.getDefsFromLspFunction, + recentlyEditedRanges: data.recentlyEditedRanges, + recentlyVisitedRanges: data.recentlyVisitedRanges, + workspaceDir: workspaceDir, + }; + + // queueMicrotask prevents blocking the UI thread during typing + queueMicrotask(() => { + void EditAggregator.getInstance().processEdits(data.actions); + }); + }); + // Docs, etc. indexing on("indexing/reindex", async (msg) => { if (msg.data.type === "docs") { @@ -809,7 +871,7 @@ export class Core { this.messenger.send("toolCallPartialOutput", params); }; - return await callTool(tool, toolCall, { + const result = await callTool(tool, toolCall, { config, ide: this.ide, llm: config.selectedModelByRole.chat, @@ -820,6 +882,8 @@ export class Core { onPartialOutput, codeBaseIndexer: this.codeBaseIndexer, }); + + return result; } private async isItemTooBig(item: ContextItemWithId) { @@ -1031,18 +1095,15 @@ export class Core { // user doesn't need these in their config.json for the shortcuts to work // option+enter new CurrentFileContextProvider({}), - // cmd+enter - new CodebaseContextProvider({}), ].find((provider) => provider.description.title === name); if (!provider) { return []; } try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: uuidv4(), - }; + void Telemetry.capture("context_provider_get_context_items", { + name: provider.description.title, + }); const items = await provider.getContextItems(query, { config, @@ -1064,10 +1125,14 @@ export class Core { true, ); - return items.map((item) => ({ - ...item, - id, - })); + return items.map((item) => { + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: uuidv4(), + }; + + return { ...item, id }; + }); } catch (e) { let knownError = false; diff --git a/core/core_temp.ts b/core/core_temp.ts deleted file mode 100644 index e69de29bb..000000000 diff --git a/core/edit/searchAndReplace/findSearchMatch.test.ts b/core/edit/searchAndReplace/findSearchMatch.test.ts new file mode 100644 index 000000000..8d5c3682b --- /dev/null +++ b/core/edit/searchAndReplace/findSearchMatch.test.ts @@ -0,0 +1,386 @@ +import { findSearchMatch } from "./findSearchMatch"; + +describe("findSearchMatch", () => { + describe("Exact matches", () => { + it("should find exact match at the beginning of file", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = `function hello() { + console.log("world"); +}`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: fileContent.length, + }); + }); + + it("should find exact match in the middle of file", () => { + const fileContent = `const a = 1; +function hello() { + console.log("world"); +} +const b = 2;`; + const searchContent = `function hello() { + console.log("world"); +}`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 13, // After "const a = 1;\n" + endIndex: 13 + searchContent.length, + }); + }); + + it("should find exact match at the end of file", () => { + const fileContent = `const a = 1; +function hello() { + console.log("world"); +}`; + const searchContent = `function hello() { + console.log("world"); +}`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 13, // After "const a = 1;\n" + endIndex: fileContent.length, + }); + }); + + it("should find exact match with single line", () => { + const fileContent = `const a = 1; +const b = 2; +const c = 3;`; + const searchContent = `const b = 2;`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 13, // After "const a = 1;\n" + endIndex: 13 + searchContent.length, + }); + }); + + it("should find exact match with whitespace preserved", () => { + const fileContent = `function test() { + const x = 1; + const y = 2; +}`; + const searchContent = ` const x = 1; + const y = 2;`; + + const result = findSearchMatch(fileContent, searchContent); + + // The actual indexOf result is 18, not 17 + expect(result).toEqual({ + startIndex: 18, + endIndex: 18 + searchContent.length, + }); + }); + }); + + describe("Trimmed matches", () => { + it("should find trimmed match when exact match fails due to leading newlines", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = `\n\nfunction hello() { + console.log("world"); +}\n\n`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: fileContent.length, // Uses trimmed length + }); + }); + + it("should find trimmed match when exact match fails due to trailing newlines", () => { + const fileContent = `const a = 1; +function hello() { + return "world"; +} +const b = 2;`; + const searchContent = `\nfunction hello() { + return "world"; +}\n`; + + const result = findSearchMatch(fileContent, searchContent); + + // The function finds the exact match first (at index 12), not the trimmed match + expect(result).toEqual({ + startIndex: 12, + endIndex: 12 + searchContent.length, + }); + }); + + it("should find trimmed match for single line with extra whitespace", () => { + const fileContent = `const a = 1; +const b = 2; +const c = 3;`; + const searchContent = `\n const b = 2; \n`; + + const result = findSearchMatch(fileContent, searchContent); + + const trimmedSearchContent = searchContent.trim(); + const expectedStart = fileContent.indexOf(trimmedSearchContent); + + expect(result).toEqual({ + startIndex: expectedStart, + endIndex: expectedStart + trimmedSearchContent.length, + }); + }); + }); + + describe("Empty search content", () => { + it("should match at beginning for empty search content", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = ""; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + }); + }); + + it("should match at beginning for whitespace-only search content", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = "\n\n \t \n"; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + }); + }); + + it("should match at beginning for empty file and empty search", () => { + const fileContent = ""; + const searchContent = ""; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: 0, + }); + }); + }); + + describe("No matches", () => { + it("should return null when search content is not found", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = `function goodbye() { + console.log("world"); +}`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should return null when trimmed search content is not found", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = `\n\nfunction goodbye() { + console.log("world"); +}\n\n`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should return null for non-existent single line", () => { + const fileContent = `const a = 1; +const b = 2; +const c = 3;`; + const searchContent = `const d = 4;`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should return null for partial match", () => { + const fileContent = `function hello() { + console.log("world"); +}`; + const searchContent = `function hello() { + console.log("universe"); +}`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + }); + + describe("Edge cases", () => { + it("should handle empty file with non-empty search", () => { + const fileContent = ""; + const searchContent = "function hello() {}"; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toBeNull(); + }); + + it("should handle very large content", () => { + const repeatedLine = "const x = 1;\n"; + const fileContent = + repeatedLine.repeat(1000) + + "const target = 2;\n" + + repeatedLine.repeat(1000); + const searchContent = "const target = 2;"; + + const result = findSearchMatch(fileContent, searchContent); + + const expectedStart = repeatedLine.length * 1000; + expect(result).toEqual({ + startIndex: expectedStart, + endIndex: expectedStart + searchContent.length, + }); + }); + + it("should handle special characters and symbols", () => { + const fileContent = `const regex = /[a-zA-Z]+/g; +const symbols = !@#$%^&*(); +const unicode = "🚀 Hello 世界";`; + const searchContent = `const symbols = !@#$%^&*();`; + + const result = findSearchMatch(fileContent, searchContent); + + const expectedStart = fileContent.indexOf(searchContent); + expect(result).toEqual({ + startIndex: expectedStart, + endIndex: expectedStart + searchContent.length, + }); + }); + + it("should prefer exact match over trimmed match", () => { + const fileContent = `function test() { + const x = 1; +} + +function test() { + const x = 1; +}`; + const searchContent = `function test() { + const x = 1; +}`; + + const result = findSearchMatch(fileContent, searchContent); + + // Should find the first exact match, not a trimmed version + expect(result).toEqual({ + startIndex: 0, + endIndex: searchContent.length, + }); + }); + + it("should handle multiple occurrences and return first match", () => { + const fileContent = `const a = 1; +const b = 2; +const a = 1;`; + const searchContent = `const a = 1;`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: searchContent.length, + }); + }); + }); + + describe("Real-world scenarios", () => { + it("should match typical function replacement", () => { + const fileContent = `class Calculator { + constructor() { + this.result = 0; + } + + reset() { + this.result = 0; + return this; + } + + add(value) { + this.result += value; + return this; + } +}`; + const searchContent = ` reset() { + this.result = 0; + return this; + }`; + + const result = findSearchMatch(fileContent, searchContent); + + const expectedStart = fileContent.indexOf(searchContent); + expect(result).toEqual({ + startIndex: expectedStart, + endIndex: expectedStart + searchContent.length, + }); + }); + + it("should match import statement", () => { + const fileContent = `import React from 'react'; +import { useState, useEffect } from 'react'; +import './App.css'; + +function App() { + return
Hello World
; +}`; + const searchContent = `import { useState, useEffect } from 'react';`; + + const result = findSearchMatch(fileContent, searchContent); + + const expectedStart = fileContent.indexOf(searchContent); + expect(result).toEqual({ + startIndex: expectedStart, + endIndex: expectedStart + searchContent.length, + }); + }); + + it("should match comment block", () => { + const fileContent = `/** + * This is a comment + * that spans multiple lines + */ +function test() { + // Single line comment + return true; +}`; + const searchContent = `/** + * This is a comment + * that spans multiple lines + */`; + + const result = findSearchMatch(fileContent, searchContent); + + expect(result).toEqual({ + startIndex: 0, + endIndex: searchContent.length, + }); + }); + }); +}); diff --git a/core/edit/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts new file mode 100644 index 000000000..3b1b8acf8 --- /dev/null +++ b/core/edit/searchAndReplace/findSearchMatch.ts @@ -0,0 +1,55 @@ +/** + * Represents a match result with start and end character positions + */ +export interface SearchMatchResult { + /** The starting character index of the match in the file content */ + startIndex: number; + /** The ending character index of the match in the file content */ + endIndex: number; +} + +/** + * Find the exact match position for search content in file content. + * Uses simple exact matching with trimmed newlines for MVP. + * + * Matching Strategy: + * 1. If search content is empty, matches at the beginning of file (position 0) + * 2. Try exact string match first + * 3. Fallback to trimmed content match if exact match fails + * + * @param fileContent - The complete content of the file to search in + * @param searchContent - The content to search for + * @returns Match result with character positions, or null if no match found + */ +export function findSearchMatch( + fileContent: string, + searchContent: string, +): SearchMatchResult | null { + // Strip leading/trailing newlines for basic matching strategy + const trimmedSearchContent = searchContent.trim(); + + if (trimmedSearchContent === "") { + // Empty search content matches the beginning of the file + return { startIndex: 0, endIndex: 0 }; + } + + // Try exact match first + const exactIndex = fileContent.indexOf(searchContent); + if (exactIndex !== -1) { + return { + startIndex: exactIndex, + endIndex: exactIndex + searchContent.length, + }; + } + + // Fallback: try trimmed content match + const trimmedIndex = fileContent.indexOf(trimmedSearchContent); + if (trimmedIndex !== -1) { + return { + startIndex: trimmedIndex, + endIndex: trimmedIndex + trimmedSearchContent.length, + }; + } + + return null; +} diff --git a/core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts b/core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts new file mode 100644 index 000000000..1fd6ab38c --- /dev/null +++ b/core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts @@ -0,0 +1,390 @@ +import { + parseAllSearchReplaceBlocks, + parseSearchReplaceBlock, +} from "./parseSearchReplaceBlock"; + +describe("parseSearchReplaceBlock", () => { + describe("Complete blocks", () => { + it("should parse a complete basic search/replace block", () => { + const content = `------- SEARCH +reset() { +this.result = 0; +return this; +} +======= +// Resets the calculator result to 0 and returns the instance for method chaining +reset() { +this.result = 0; +return this; +} ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(true); + expect(result.searchContent).toBe(`reset() { +this.result = 0; +return this; +}`); + expect(result.replaceContent) + .toBe(`// Resets the calculator result to 0 and returns the instance for method chaining +reset() { +this.result = 0; +return this; +}`); + expect(result.error).toBeUndefined(); + }); + + it("should handle different marker lengths", () => { + const content = `------- SEARCH +old content +========= +new content ++++++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(true); + expect(result.searchContent).toBe("old content"); + expect(result.replaceContent).toBe("new content"); + }); + + it("should handle empty search content", () => { + const content = `------- SEARCH +======= +new content ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(true); + expect(result.searchContent).toBe(""); + expect(result.replaceContent).toBe("new content"); + }); + + it("should handle empty replace content (deletion)", () => { + const content = `------- SEARCH +old content to delete +======= ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(true); + expect(result.searchContent).toBe("old content to delete"); + expect(result.replaceContent).toBe(""); + }); + + it("should handle both empty search and replace content", () => { + const content = `------- SEARCH +======= ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(true); + expect(result.searchContent).toBe(""); + expect(result.replaceContent).toBe(""); + }); + }); + + describe("Incomplete blocks", () => { + it("should handle incomplete search block", () => { + const content = `------- SEARCH +some content`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(false); + expect(result.searchContent).toBe("some content"); + expect(result.replaceContent).toBe(""); + expect(result.error).toBeUndefined(); + }); + + it("should handle incomplete replace block", () => { + const content = `------- SEARCH +old content +======= +new content`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(false); + expect(result.searchContent).toBe("old content"); + expect(result.replaceContent).toBe("new content"); + expect(result.error).toBeUndefined(); + }); + }); + + describe("Error cases", () => { + it("should error on search end without start", () => { + const content = `======= +some content ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(false); + expect(result.error).toBe( + "Found search block end marker without matching start marker", + ); + }); + + it("should error on replace end without replace start", () => { + const content = `+++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + + expect(result.isComplete).toBe(false); + expect(result.error).toBe( + "Found replace block end marker without matching replace start marker", + ); + }); + }); + + describe("Regex pattern validation", () => { + it("should match various search start patterns", () => { + const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"]; + + patterns.forEach((pattern) => { + const content = `${pattern} +content +======= +replacement ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + expect(result.isComplete).toBe(true); + }); + }); + + it("should match various search end patterns", () => { + const patterns = ["===", "=======", "=============="]; + + patterns.forEach((pattern) => { + const content = `------- SEARCH +content +${pattern} +replacement ++++++++ REPLACE`; + + const result = parseSearchReplaceBlock(content); + expect(result.isComplete).toBe(true); + }); + }); + + it("should match various replace end patterns", () => { + const patterns = [ + "+++ REPLACE", + "+++++++ REPLACE", + "+++++++++++ REPLACE", + ]; + + patterns.forEach((pattern) => { + const content = `------- SEARCH +content +======= +replacement +${pattern}`; + + const result = parseSearchReplaceBlock(content); + expect(result.isComplete).toBe(true); + }); + }); + + it("should not match invalid patterns", () => { + const invalidPatterns = [ + "-- SEARCH", // Too few dashes + "SEARCH", // No markers + "== SEARCH", // Wrong markers + "=== REPLACE", // Wrong end marker + "++++ SEARCH", // Wrong markers for search + ]; + + invalidPatterns.forEach((pattern) => { + const content = `${pattern} +content`; + + const result = parseSearchReplaceBlock(content); + expect(result.isComplete).toBe(false); + expect(result.searchContent).toBe(""); // Should not enter search mode + }); + }); + }); +}); + +describe("parseAllSearchReplaceBlocks", () => { + it("should parse multiple complete blocks", () => { + const content = `------- SEARCH +old code 1 +======= +new code 1 ++++++++ REPLACE + +------- SEARCH +old code 2 +======= +new code 2 ++++++++ REPLACE`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(2); + expect(blocks[0].searchContent).toBe("old code 1"); + expect(blocks[0].replaceContent).toBe("new code 1"); + expect(blocks[1].searchContent).toBe("old code 2"); + expect(blocks[1].replaceContent).toBe("new code 2"); + }); + + it("should handle blocks with different content", () => { + const content = `------- SEARCH +function old() { + return 1; +} +======= +function new() { + return 2; +} ++++++++ REPLACE + +------- SEARCH +const x = 'old'; +======= +const x = 'new'; ++++++++ REPLACE`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(2); + expect(blocks[0].searchContent).toBe(`function old() { + return 1; +}`); + expect(blocks[0].replaceContent).toBe(`function new() { + return 2; +}`); + expect(blocks[1].searchContent).toBe(`const x = 'old';`); + expect(blocks[1].replaceContent).toBe(`const x = 'new';`); + }); + + it("should handle deletion blocks (empty replace content)", () => { + const content = `------- SEARCH +code to keep +======= +modified code ++++++++ REPLACE + +------- SEARCH +code to delete +======= ++++++++ REPLACE`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(2); + expect(blocks[0].searchContent).toBe("code to keep"); + expect(blocks[0].replaceContent).toBe("modified code"); + expect(blocks[1].searchContent).toBe("code to delete"); + expect(blocks[1].replaceContent).toBe(""); // Deletion + }); + + it("should handle insertion blocks (empty search content)", () => { + const content = `------- SEARCH +existing code +======= +modified existing code ++++++++ REPLACE + +------- SEARCH +======= +new code to insert ++++++++ REPLACE`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(2); + expect(blocks[0].searchContent).toBe("existing code"); + expect(blocks[0].replaceContent).toBe("modified existing code"); + expect(blocks[1].searchContent).toBe(""); // Insertion + expect(blocks[1].replaceContent).toBe("new code to insert"); + }); + + it("should skip incomplete blocks", () => { + const content = `------- SEARCH +incomplete block + +------- SEARCH +complete block +======= +replacement ++++++++ REPLACE`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(1); + expect(blocks[0].searchContent).toBe("complete block"); + expect(blocks[0].replaceContent).toBe("replacement"); + }); + + it("should handle single block", () => { + const content = `------- SEARCH +single block +======= +replacement ++++++++ REPLACE`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(1); + expect(blocks[0].searchContent).toBe("single block"); + expect(blocks[0].replaceContent).toBe("replacement"); + }); + + it("should return empty array when no complete blocks found", () => { + const content = `------- SEARCH +incomplete +======= +missing replace marker`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(0); + }); + + it("should handle blocks with extra content between them", () => { + const content = `Some other content here + +------- SEARCH +block 1 +======= +replacement 1 ++++++++ REPLACE + +More content in between + +------- SEARCH +block 2 +======= +replacement 2 ++++++++ REPLACE + +Trailing content`; + + const blocks = parseAllSearchReplaceBlocks(content); + + expect(blocks).toHaveLength(2); + expect(blocks[0].searchContent).toBe("block 1"); + expect(blocks[0].replaceContent).toBe("replacement 1"); + expect(blocks[1].searchContent).toBe("block 2"); + expect(blocks[1].replaceContent).toBe("replacement 2"); + }); + + it("should throw error for malformed blocks", () => { + const content = `------- SEARCH +content ++++++++ REPLACE`; // Missing ======= + + expect(() => parseAllSearchReplaceBlocks(content)).toThrow( + "Found replace block end marker without matching replace start marker", + ); + }); +}); diff --git a/core/edit/searchAndReplace/parseSearchReplaceBlock.ts b/core/edit/searchAndReplace/parseSearchReplaceBlock.ts new file mode 100644 index 000000000..64fa901a2 --- /dev/null +++ b/core/edit/searchAndReplace/parseSearchReplaceBlock.ts @@ -0,0 +1,147 @@ +// Search and replace block markers using flexible regex patterns +const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; +const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; +const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; + +export interface SearchReplaceBlockResult { + /** Whether a complete search/replace block has been parsed */ + isComplete: boolean; + /** The content to search for in the file */ + searchContent?: string; + /** The content to replace the search content with */ + replaceContent?: string; + /** Error message if parsing failed */ + error?: string; +} + +/** + * Parses a search and replace block from content. + * + * Expected format: + * ------- SEARCH + * [content to find] + * ======= + * [content to replace with] + * +++++++ REPLACE + * + * @param content - The content to parse + * @returns ParseResult with completion status and extracted content + */ +export function parseSearchReplaceBlock( + content: string, +): SearchReplaceBlockResult { + const lines = content.split("\n"); + + let currentSearchContent = ""; + let currentReplaceContent = ""; + let inSearch = false; + let inReplace = false; + + for (const line of lines) { + if (SEARCH_BLOCK_START_REGEX.test(line)) { + inSearch = true; + inReplace = false; + currentSearchContent = ""; + currentReplaceContent = ""; + continue; + } + + if (SEARCH_BLOCK_END_REGEX.test(line)) { + if (!inSearch) { + return { + isComplete: false, + error: "Found search block end marker without matching start marker", + }; + } + inSearch = false; + inReplace = true; + continue; + } + + if (REPLACE_BLOCK_END_REGEX.test(line)) { + if (!inReplace) { + return { + isComplete: false, + error: + "Found replace block end marker without matching replace start marker", + }; + } + + // Complete block found + return { + isComplete: true, + searchContent: currentSearchContent.trim(), + replaceContent: currentReplaceContent.trim(), + }; + } + + // Accumulate content + if (inSearch) { + currentSearchContent += line + "\n"; + } else if (inReplace) { + currentReplaceContent += line + "\n"; + } + } + + // Block is not yet complete + return { + isComplete: false, + searchContent: currentSearchContent.trim(), + replaceContent: currentReplaceContent.trim(), + }; +} + +/** + * Parses all complete search and replace blocks from content. + * + * @param content - The content containing multiple search/replace blocks + * @returns Array of complete search/replace blocks found + * @throws Error if any malformed blocks are encountered + */ +export function parseAllSearchReplaceBlocks( + content: string, +): SearchReplaceBlockResult[] { + const blocks: SearchReplaceBlockResult[] = []; + const lines = content.split("\n"); + + let currentBlockLines: string[] = []; + let inBlock = false; + + for (const line of lines) { + if (SEARCH_BLOCK_START_REGEX.test(line)) { + // Start of new block + if (inBlock && currentBlockLines.length > 0) { + // Process previous incomplete block if any + const blockContent = currentBlockLines.join("\n"); + const result = parseSearchReplaceBlock(blockContent); + if (result.isComplete) { + blocks.push(result); + } else if (result.error) { + // Fail fast on any parsing error + throw new Error(result.error); + } + // If incomplete but no error, it's just a partial block - continue processing + } + currentBlockLines = [line]; + inBlock = true; + } else if (inBlock) { + currentBlockLines.push(line); + + // Check if this line completes the current block + if (REPLACE_BLOCK_END_REGEX.test(line)) { + const blockContent = currentBlockLines.join("\n"); + const result = parseSearchReplaceBlock(blockContent); + if (result.isComplete) { + blocks.push(result); + } else if (result.error) { + // Fail fast on any parsing error + throw new Error(result.error); + } + currentBlockLines = []; + inBlock = false; + } + } + } + + return blocks; +} diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index f64448f36..7cf1af2f7 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -66,7 +66,6 @@ export async function* streamDiffLines({ abortController, input, language, - onlyOneInsertion, overridePrompt, rulesToInclude, }: { @@ -77,7 +76,6 @@ export async function* streamDiffLines({ abortController: AbortController; input: string; language: string | undefined; - onlyOneInsertion: boolean; overridePrompt: ChatMessage[] | undefined; rulesToInclude: RuleWithSource[] | undefined; }): AsyncGenerator { @@ -112,7 +110,7 @@ export async function* streamDiffLines({ // If any rules are present this will result in using chat instead of legacy completion const systemMessage = rulesToInclude ? getSystemMessageWithRules({ - rules: rulesToInclude, + availableRules: rulesToInclude, userMessage: typeof prompt === "string" ? ({ @@ -125,7 +123,7 @@ export async function* streamDiffLines({ ) as UserChatMessage | ToolResultChatMessage | undefined), baseSystemMessage: undefined, contextItems: [], - }) + }).systemMessage : undefined; if (systemMessage) { @@ -182,13 +180,7 @@ export async function* streamDiffLines({ diffLines = addIndentation(diffLines, indentation); } - let seenGreen = false; for await (const diffLine of diffLines) { yield diffLine; - if (diffLine.type === "new") { - seenGreen = true; - } else if (onlyOneInsertion && seenGreen && diffLine.type === "same") { - break; - } } } diff --git a/core/index.d.ts b/core/index.d.ts index 4aea44fd4..c6dabcb02 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -57,6 +57,7 @@ export interface IndexingProgressUpdate { | "disabled" | "cancelled"; debugInfo?: string; + warnings?: string[]; } // This is more or less a V2 of IndexingProgressUpdate for docs etc. @@ -443,6 +444,7 @@ interface ToolCallState { status: ToolStatus; parsedArgs: any; output?: ContextItem[]; + tool?: Tool; } interface Reasoning { @@ -838,15 +840,44 @@ export interface ContinueSDK { abortController: AbortController; } -export interface SlashCommand { +/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */ +export interface SlashCommandDescription { name: string; description: string; prompt?: string; params?: { [key: string]: any }; - promptFile?: string; +} + +export interface SlashCommand extends SlashCommandDescription { run: (sdk: ContinueSDK) => AsyncGenerator; } +export interface SlashCommandWithSource extends SlashCommandDescription { + run?: (sdk: ContinueSDK) => AsyncGenerator; // Optional - only needed for legacy + source: SlashCommandSource; + promptFile?: string; + overrideSystemMessage?: string; +} + +export type SlashCommandSource = + | "built-in-legacy" + | "built-in" + | "json-custom-command" + | "config-ts-slash-command" + | "yaml-prompt-block" + | "mcp-prompt" + | "prompt-file-v1" + | "prompt-file-v2" + | "invokable-rule"; + +export interface SlashCommandDescWithSource extends SlashCommandDescription { + isLegacy: boolean; // Maps to if slashcommand.run exists + source: SlashCommandSource; + promptFile?: string; + mcpServerName?: string; + mcpArgs?: MCPPromptArgs; +} + // Config export type StepName = @@ -947,8 +978,6 @@ export interface ContextProviderWithParams { params: { [key: string]: any }; } -export type SlashCommandDescription = Omit; - export interface CustomCommand { name: string; prompt: string; @@ -1009,6 +1038,7 @@ interface ToolChoice { export interface ConfigDependentToolParams { rules: RuleWithSource[]; + enableExperimentalTools: boolean; } export type GetTool = (params: ConfigDependentToolParams) => Tool; @@ -1172,14 +1202,16 @@ export type MCPConnectionStatus = | "error" | "not-connected"; +export type MCPPromptArgs = { + name: string; + description?: string; + required?: boolean; +}[]; + export interface MCPPrompt { name: string; description?: string; - arguments?: { - name: string; - description?: string; - required?: boolean; - }[]; + arguments?: MCPPromptArgs; } // Leaving here to ideate on @@ -1228,6 +1260,7 @@ export interface ContinueUIConfig { codeWrap?: boolean; showSessionTabs?: boolean; autoAcceptEditToolDiffs?: boolean; + logEditingData?: boolean; } export interface ContextMenuConfig { @@ -1291,6 +1324,14 @@ export interface ShowFilePayload { filepath: string; } +export interface ApplyToFilePayload { + streamId: string; + filepath?: string; + text: string; + toolCallId?: string; + isSearchAndReplace?: boolean; +} + export interface RangeInFileWithContents { filepath: string; range: { @@ -1300,6 +1341,16 @@ export interface RangeInFileWithContents { contents: string; } +export interface RangeInFileWithNextEditInfo { + filepath: string; + range: Range; + fileContents: string; + editText: string; + afterCursorPos: Position; + beforeCursorPos: Position; + workspaceDir: string; +} + export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; /** @@ -1336,6 +1387,7 @@ export interface ExperimentalConfig { modelRoles?: ExperimentalModelRoles; defaultContext?: DefaultContextProvider[]; promptPath?: string; + enableExperimentalTools?: boolean; /** * Quick actions are a way to add custom commands to the Code Lens of @@ -1360,6 +1412,22 @@ export interface ExperimentalConfig { * If enabled, will add the current file as context. */ useCurrentFileAsContext?: boolean; + + /** + * If enabled, will save data on the user's editing processes + */ + logEditingData?: boolean; + + /** + * If enabled, will enable next edit in place of autocomplete + */ + optInNextEditFeature?: boolean; + + /** + * If enabled, @codebase will only use tool calling + * instead of embeddings, FTS, recently edited files, etc. + */ + codebaseToolCallingOnly?: boolean; } export interface AnalyticsConfig { @@ -1444,7 +1512,7 @@ export interface Config { /** Request options that will be applied to all models and context providers */ requestOptions?: RequestOptions; /** The list of slash commands that will be available in the sidebar */ - slashCommands?: SlashCommand[]; + slashCommands?: (SlashCommand | SlashCommandWithSource)[]; /** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders. * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title ', Continue will call `getContextItems(query)`. */ @@ -1481,7 +1549,7 @@ export interface ContinueConfig { // systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; - slashCommands: SlashCommand[]; + slashCommands: SlashCommandWithSource[]; contextProviders: IContextProvider[]; disableSessionTitles?: boolean; disableIndexing?: boolean; @@ -1504,7 +1572,7 @@ export interface BrowserSerializedContinueConfig { // systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; - slashCommands: SlashCommandDescription[]; + slashCommands: SlashCommandDescWithSource[]; contextProviders: ContextProviderDescription[]; disableIndexing?: boolean; disableSessionTitles?: boolean; diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index bf79b093e..d04eca7ee 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -35,7 +35,8 @@ type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; - artifactId = "codeSnippets"; + static artifactId = "codeSnippets"; + artifactId: string = CodeSnippetsCodebaseIndex.artifactId; constructor(private readonly ide: IDE) {} @@ -220,7 +221,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Compute for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; - let snippets: SnippetChunk[] = []; try { snippets = await this.getSnippetsInFile( diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index d2de0c512..e867399fd 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -48,6 +48,16 @@ export class CodebaseIndexer { private codebaseIndexingState: IndexingProgressUpdate; private readonly pauseToken: PauseToken; + private getUserFriendlyIndexName(artifactId: string): string { + if (artifactId === FullTextSearchCodebaseIndex.artifactId) + return "Full text search"; + if (artifactId === CodeSnippetsCodebaseIndex.artifactId) + return "Code snippets"; + if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking"; + if (artifactId.startsWith("vectordb")) return "Embedding"; + return artifactId; // fallback to original + } + // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on, // e.g. a `SQLITE_BUSY` error. errorsRegexesToClearIndexesOn = [ @@ -314,6 +324,7 @@ export class CodebaseIndexer { status: "loading", }; const beginTime = Date.now(); + let collectedWarnings: string[] = []; for (const directory of dirs) { const dirBasename = getUriPathBasename(directory); @@ -344,45 +355,52 @@ export class CodebaseIndexer { const repoName = await this.ide.getRepoName(directory); let nextLogThreshold = 0; - try { - for await (const updateDesc of this.indexFiles( - directory, - directoryFiles, - branch, - repoName, - )) { - // Handle pausing in this loop because it's the only one really taking time - if (abortSignal.aborted) { - yield { - progress: 0, - desc: "Indexing cancelled", - status: "cancelled", - }; - return; - } - if (this.pauseToken.paused) { - yield* this.yieldUpdateAndPause(); - } - yield updateDesc; - if (updateDesc.progress >= nextLogThreshold) { - // log progress every 2.5% - nextLogThreshold += 0.025; - this.logProgress( - beginTime, - Math.floor(directoryFiles.length * updateDesc.progress), - updateDesc.progress, - ); - } + for await (const updateDesc of this.indexFiles( + directory, + directoryFiles, + branch, + repoName, + )) { + // Handle pausing in this loop because it's the only one really taking time + if (abortSignal.aborted) { + yield { + progress: 0, + desc: "Indexing cancelled", + status: "cancelled", + }; + return; + } + if (this.pauseToken.paused) { + yield* this.yieldUpdateAndPause(); + } + + // Collect warnings from indexFiles + if (updateDesc.warnings && updateDesc.warnings.length > 0) { + collectedWarnings = [...updateDesc.warnings]; + } + + yield updateDesc; + if (updateDesc.progress >= nextLogThreshold) { + // log progress every 2.5% + nextLogThreshold += 0.025; + this.logProgress( + beginTime, + Math.floor(directoryFiles.length * updateDesc.progress), + updateDesc.progress, + ); } - } catch (err) { - yield this.handleErrorAndGetProgressUpdate(err); - return; } } + + // Final completion message with preserved warnings yield { progress: 1, - desc: "Indexing Complete", + desc: + collectedWarnings.length > 0 + ? `Indexing completed with ${collectedWarnings.length} warning(s)` + : "Indexing Complete", status: "done", + warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined, }; this.logProgress(beginTime, 0, 1); } @@ -490,6 +508,8 @@ export class CodebaseIndexer { const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; + const warnings: string[] = []; + for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { directory, @@ -500,45 +520,101 @@ export class CodebaseIndexer { progress: progress, desc: `Planning changes for ${codebaseIndex.artifactId} index...`, status: "indexing", + warnings: warnings.length > 0 ? [...warnings] : undefined, }; - const [results, lastUpdated, markComplete] = - await getComputeDeleteAddRemove( - tag, - { ...stats }, - (filepath) => this.ide.readFile(filepath), - repoName, - ); - const totalOps = this.totalIndexOps(results); - let completedOps = 0; - // Don't update if nothing to update. Some of the indices might do unnecessary setup work - if (totalOps > 0) { - for (const subResult of this.batchRefreshIndexResults(results)) { - for await (const { desc } of codebaseIndex.update( + try { + const [results, lastUpdated, markComplete] = + await getComputeDeleteAddRemove( tag, - subResult, - markComplete, + { ...stats }, + (filepath) => this.ide.readFile(filepath), repoName, - )) { - yield { - progress, - desc, - status: "indexing", - }; - } - completedOps += - subResult.compute.length + - subResult.del.length + - subResult.addTag.length + - subResult.removeTag.length; - progress = - (completedIndexCount + completedOps / totalOps) * - (1 / indexesToBuild.length); - } - } + ); + const totalOps = this.totalIndexOps(results); + let completedOps = 0; - await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); - completedIndexCount += 1; + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (totalOps > 0) { + for (const subResult of this.batchRefreshIndexResults(results)) { + try { + for await (const { desc } of codebaseIndex.update( + tag, + subResult, + markComplete, + repoName, + )) { + yield { + progress, + desc, + status: "indexing", + warnings: warnings.length > 0 ? [...warnings] : undefined, + }; + } + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); + } catch (err) { + // Collect non-fatal errors as warnings and continue + const warningMsg = + err instanceof Error ? err.message : String(err); + const friendlyName = this.getUserFriendlyIndexName( + codebaseIndex.artifactId, + ); + warnings.push(`${friendlyName}: ${warningMsg}`); + console.warn(`${friendlyName}: ${warningMsg}`, err); + + // Complete this batch and continue with next + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); + } + } + } + + await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); + completedIndexCount += 1; + } catch (err) { + // Handle errors during planning phase + const cause = getRootCause(err as Error); + if (cause instanceof LLMError) { + // LLM errors are critical, re-throw them + throw cause; + } + + // Collect planning errors as warnings and continue to next index + const errorMsg = err instanceof Error ? err.message : String(err); + const friendlyName = this.getUserFriendlyIndexName( + codebaseIndex.artifactId, + ); + warnings.push(`${friendlyName}: ${errorMsg}`); + console.warn( + `Warning during ${codebaseIndex.artifactId} planning:`, + err, + ); + completedIndexCount += 1; + progress = completedIndexCount * (1 / indexesToBuild.length); + } + } + + // Final update with any collected warnings + if (warnings.length > 0) { + yield { + progress: 1, + desc: `Indexing completed with ${warnings.length} warning(s)`, + status: "done", + warnings: [...warnings], + }; } } diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 1bac74e4a..8016d04d3 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -55,7 +55,6 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.compute.length; i++) { const item = results.compute[i]; - // Insert chunks const chunks = await db.all( "SELECT * FROM chunks WHERE path = ? AND cacheKey = ?", @@ -68,7 +67,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { [item.path, chunk.content], ); await db.run( - `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) + `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET path = excluded.path, diff --git a/core/indexing/README.md b/core/indexing/README.md index 2a7375f00..94bf196aa 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -20,10 +20,10 @@ The indexing process does the following: All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used. -`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file +`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 -`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex` -`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. +`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex` +`LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. ## Known problems diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 6bd285520..7ea3d444e 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -981,17 +981,11 @@ export default class DocsService { // Otherwise sync the index based on config changes const oldConfigDocs = oldConfig?.docs || []; const newConfigDocs = newConfig.docs || []; - const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // Anything found in sqlite but not in new config should be deleted - const deletedDocs = currentlyIndexedDocs.filter( - (doc) => !newConfigStartUrls.includes(doc.startUrl), - ); - // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed // TODO if only favicon and title change, only update, don't embed // Otherwise anything found in new config that isn't in sqlite should be added/indexed @@ -1038,10 +1032,6 @@ export default class DocsService { ...changedDocs.map((doc) => this.indexAndAdd(doc, true)), ...addedDocs.map((doc) => this.indexAndAdd(doc)), ]); - - for (const doc of deletedDocs) { - await this.deleteIndexes(doc.startUrl); - } } catch (e) { console.error("Error syncing docs index on config update", e); } finally { diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index dd65cc2d9..a13ffe8dc 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -187,7 +187,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("gemini") || lower.includes("grok") || lower.includes("moonshot") || - lower.includes("mercury") + lower.includes("mercury") || + /^o\d/.test(lower) ) { return undefined; } diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts new file mode 100644 index 000000000..c5cbf08fe --- /dev/null +++ b/core/llm/autodetect.vitest.ts @@ -0,0 +1,190 @@ +import { expect, test } from "vitest"; +import { autodetectTemplateType } from "./autodetect"; + +test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => { + expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b"); + expect(autodetectTemplateType("CodeLlama-70B")).toBe("codellama-70b"); + expect(autodetectTemplateType("codellama-70b-instruct")).toBe( + "codellama-70b", + ); + expect(autodetectTemplateType("CodeLlama-70B-Python")).toBe("codellama-70b"); +}); + +test("autodetectTemplateType returns undefined for models that don't need templates", () => { + expect(autodetectTemplateType("gpt-4")).toBe(undefined); + expect(autodetectTemplateType("gpt-3.5-turbo")).toBe(undefined); + expect(autodetectTemplateType("GPT-4")).toBe(undefined); + expect(autodetectTemplateType("command-r")).toBe(undefined); + expect(autodetectTemplateType("aya-23")).toBe(undefined); + expect(autodetectTemplateType("chat-bison")).toBe(undefined); + expect(autodetectTemplateType("pplx-70b")).toBe(undefined); + expect(autodetectTemplateType("gemini-pro")).toBe(undefined); + expect(autodetectTemplateType("grok-beta")).toBe(undefined); + expect(autodetectTemplateType("moonshot-v1")).toBe(undefined); + expect(autodetectTemplateType("mercury-chat")).toBe(undefined); + expect(autodetectTemplateType("mercury-chat")).toBe(undefined); + expect(autodetectTemplateType("o3-mini")).toBe(undefined); + expect(autodetectTemplateType("o4")).toBe(undefined); + expect(autodetectTemplateType("claude-sonnet-4-20250514")).toBe("none"); + expect(autodetectTemplateType("claude-3-7-sonnet-latest")).toBe("none"); +}); + +test("autodetectTemplateType returns 'llama3' for Llama 3 models", () => { + expect(autodetectTemplateType("llama3")).toBe("llama3"); + expect(autodetectTemplateType("llama-3")).toBe("llama3"); + expect(autodetectTemplateType("Llama3-8B")).toBe("llama3"); + expect(autodetectTemplateType("llama-3:70b")).toBe("llama3"); +}); + +test("autodetectTemplateType returns 'llava' for LLaVA models", () => { + expect(autodetectTemplateType("llava")).toBe("llava"); + expect(autodetectTemplateType("LLaVA")).toBe("llava"); + expect(autodetectTemplateType("llava-1.5")).toBe("llava"); + expect(autodetectTemplateType("llava-v1.6")).toBe("llava"); +}); + +test("autodetectTemplateType returns 'zephyr' for TinyLlama models", () => { + expect(autodetectTemplateType("tinyllama")).toBe("zephyr"); + expect(autodetectTemplateType("TinyLlama")).toBe("zephyr"); + expect(autodetectTemplateType("tinyllama-1.1b")).toBe("zephyr"); +}); + +test("autodetectTemplateType returns 'xwin-coder' for XWin models", () => { + expect(autodetectTemplateType("xwin")).toBe("xwin-coder"); + expect(autodetectTemplateType("XWin")).toBe("xwin-coder"); + expect(autodetectTemplateType("xwin-coder")).toBe("xwin-coder"); +}); + +test("autodetectTemplateType returns 'chatml' for Dolphin models", () => { + expect(autodetectTemplateType("dolphin")).toBe("chatml"); + expect(autodetectTemplateType("Dolphin")).toBe("chatml"); + expect(autodetectTemplateType("dolphin-2.1")).toBe("chatml"); +}); + +test("autodetectTemplateType returns 'gemma' for Gemma models", () => { + expect(autodetectTemplateType("gemma")).toBe("gemma"); + expect(autodetectTemplateType("Gemma")).toBe("gemma"); + expect(autodetectTemplateType("gemma-7b")).toBe("gemma"); +}); + +test("autodetectTemplateType returns 'phi2' for Phi-2 models", () => { + expect(autodetectTemplateType("phi2")).toBe("phi2"); + expect(autodetectTemplateType("Phi2")).toBe("phi2"); + expect(autodetectTemplateType("microsoft-phi2")).toBe("phi2"); +}); + +test("autodetectTemplateType returns 'phind' for Phind models", () => { + expect(autodetectTemplateType("phind")).toBe("phind"); + expect(autodetectTemplateType("Phind")).toBe("phind"); + expect(autodetectTemplateType("phind-codellama")).toBe("phind"); +}); + +test("autodetectTemplateType returns 'llama2' for general Llama models", () => { + expect(autodetectTemplateType("llama")).toBe("llama2"); + expect(autodetectTemplateType("Llama")).toBe("llama2"); + expect(autodetectTemplateType("llama2")).toBe("llama2"); + expect(autodetectTemplateType("llama-2")).toBe("llama2"); + expect(autodetectTemplateType("codellama")).toBe("llama2"); +}); + +test("autodetectTemplateType returns 'zephyr' for Zephyr models", () => { + expect(autodetectTemplateType("zephyr")).toBe("zephyr"); + expect(autodetectTemplateType("Zephyr")).toBe("zephyr"); + expect(autodetectTemplateType("zephyr-7b")).toBe("zephyr"); +}); + +test("autodetectTemplateType returns 'none' for Claude models", () => { + expect(autodetectTemplateType("claude")).toBe("none"); + expect(autodetectTemplateType("Claude")).toBe("none"); + expect(autodetectTemplateType("claude-3")).toBe("none"); + expect(autodetectTemplateType("claude-3-opus")).toBe("none"); +}); + +test("autodetectTemplateType returns 'none' for Codestral models", () => { + expect(autodetectTemplateType("codestral")).toBe("none"); + expect(autodetectTemplateType("Codestral")).toBe("none"); + expect(autodetectTemplateType("codestral-22b")).toBe("none"); +}); + +test("autodetectTemplateType returns 'alpaca' for Alpaca and Wizard models", () => { + expect(autodetectTemplateType("alpaca")).toBe("alpaca"); + expect(autodetectTemplateType("Alpaca")).toBe("alpaca"); + expect(autodetectTemplateType("wizard")).toBe("alpaca"); + expect(autodetectTemplateType("Wizard")).toBe("alpaca"); + expect(autodetectTemplateType("wizardlm")).toBe("alpaca"); +}); + +test("autodetectTemplateType returns 'llama2' for Mistral and Mixtral models", () => { + expect(autodetectTemplateType("mistral")).toBe("llama2"); + expect(autodetectTemplateType("Mistral")).toBe("llama2"); + expect(autodetectTemplateType("mixtral")).toBe("llama2"); + expect(autodetectTemplateType("Mixtral")).toBe("llama2"); + expect(autodetectTemplateType("mistral-7b")).toBe("llama2"); +}); + +test("autodetectTemplateType returns 'deepseek' for DeepSeek models", () => { + expect(autodetectTemplateType("deepseek")).toBe("deepseek"); + expect(autodetectTemplateType("DeepSeek")).toBe("deepseek"); + expect(autodetectTemplateType("deepseek-coder")).toBe("deepseek"); +}); + +test("autodetectTemplateType returns 'openchat' for Ninja and OpenChat models", () => { + expect(autodetectTemplateType("ninja")).toBe("openchat"); + expect(autodetectTemplateType("Ninja")).toBe("openchat"); + expect(autodetectTemplateType("openchat")).toBe("openchat"); + expect(autodetectTemplateType("OpenChat")).toBe("openchat"); +}); + +test("autodetectTemplateType returns 'neural-chat' for Neural Chat models", () => { + expect(autodetectTemplateType("neural-chat")).toBe("neural-chat"); + expect(autodetectTemplateType("Neural-Chat")).toBe("neural-chat"); + expect(autodetectTemplateType("intel-neural-chat")).toBe("neural-chat"); +}); + +test("autodetectTemplateType returns 'granite' for Granite models", () => { + expect(autodetectTemplateType("granite")).toBe("granite"); + expect(autodetectTemplateType("granite2:8b")).toBe("granite"); + expect(autodetectTemplateType("Granite")).toBe("granite"); + expect(autodetectTemplateType("granite-code")).toBe("granite"); +}); + +test("autodetectTemplateType returns chatml for other models", () => { + expect(autodetectTemplateType("unknown-model")).toBe("chatml"); + expect(autodetectTemplateType("random-ai")).toBe("chatml"); + expect(autodetectTemplateType("")).toBe("chatml"); +}); + +test("autodetectTemplateType handles case sensitivity correctly", () => { + expect(autodetectTemplateType("LLAMA3")).toBe("llama3"); + expect(autodetectTemplateType("gpt-4")).toBe(undefined); + expect(autodetectTemplateType("GPT-4")).toBe(undefined); + expect(autodetectTemplateType("CLAUDE")).toBe("none"); +}); + +test("autodetectTemplateType follows correct precedence order", () => { + // CodeLlama 70B should be detected before general llama + expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b"); + + // Llama3 should be detected before general llama + expect(autodetectTemplateType("llama3")).toBe("llama3"); + + // General llama should be detected after specific cases + expect(autodetectTemplateType("llama2")).toBe("llama2"); + + // TinyLlama should be detected as zephyr, not llama + expect(autodetectTemplateType("tinyllama")).toBe("zephyr"); +}); + +test("autodetectTemplateType handles edge cases with special characters", () => { + expect(autodetectTemplateType("llama-3-8b-instruct")).toBe("llama3"); + expect(autodetectTemplateType("gpt-4-turbo-preview")).toBe(undefined); + expect(autodetectTemplateType("claude-3-opus-20240229")).toBe("none"); + expect(autodetectTemplateType("mistral-7b-instruct-v0.1")).toBe("llama2"); +}); + +test("autodetectTemplateType handles models with mixed keywords", () => { + // Should match the first applicable pattern + expect(autodetectTemplateType("llama3-chat")).toBe("llama3"); // llama3 comes before general patterns + expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined + expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2 +}); diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts deleted file mode 100644 index 49115cb6f..000000000 --- a/core/llm/constructMessages.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { - ChatHistoryItem, - ChatMessage, - ContextItemWithId, - RuleWithSource, - TextMessagePart, - ToolResultChatMessage, - UserChatMessage, -} from "../"; -import { findLast } from "../util/findLast"; -import { normalizeToMessageParts } from "../util/messageContent"; -import { isUserOrToolMsg } from "./messages"; -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -import { RulePolicies } from "./rules/types"; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; - -const EDIT_MESSAGE = `\ - Always include the language and file name in the info string when you write code blocks. - If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' - - When addressing code modification requests, present a concise code snippet that - emphasizes only the necessary changes and uses abbreviated placeholders for - unmodified sections. For example: - - \`\`\`language /path/to/file - // ... existing code ... - - {{ modified code here }} - - // ... existing code ... - - {{ another modification }} - - // ... rest of code ... - \`\`\` - - In existing files, you should always restate the function or class that the snippet belongs to: - - \`\`\`language /path/to/file - // ... existing code ... - - function exampleFunction() { - // ... existing code ... - - {{ modified code here }} - - // ... rest of function ... - } - - // ... rest of code ... - \`\`\` - - Since users have access to their complete file, they prefer reading only the - relevant modifications. It's perfectly acceptable to omit unmodified portions - at the beginning, middle, or end of files using these "lazy" comments. Only - provide the complete file when explicitly requested. Include a concise explanation - of changes unless the user specifically asks for code only. -`; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ - - You are in chat mode. - - If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. - -${EDIT_MESSAGE} -`; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ - - You are in agent mode. - -${EDIT_MESSAGE} -`; - -/** - * Helper function to get the context items for a user message - */ -function getUserContextItems( - userMsg: UserChatMessage | ToolResultChatMessage | undefined, - history: ChatHistoryItem[], -): ContextItemWithId[] { - if (!userMsg) return []; - - // Find the history item that contains the userMsg - const historyItem = history.find((item) => { - // Check if the message ID matches - if ("id" in userMsg && "id" in item.message) { - return (item.message as any).id === (userMsg as any).id; - } - // Fallback to content comparison - return ( - item.message.content === userMsg.content && - item.message.role === userMsg.role - ); - }); - - return historyItem?.contextItems || []; -} - -export function constructMessages( - messageMode: string, - history: ChatHistoryItem[], - baseChatOrAgentSystemMessage: string | undefined, - rules: RuleWithSource[], - rulePolicies?: RulePolicies, -): ChatMessage[] { - const filteredHistory = history.filter( - (item) => item.message.role !== "system", - ); - const msgs: ChatMessage[] = []; - - for (let i = 0; i < filteredHistory.length; i++) { - const historyItem = filteredHistory[i]; - - if (messageMode === "chat") { - const toolMessage: ToolResultChatMessage = - historyItem.message as ToolResultChatMessage; - if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { - // remove all tool calls from the history - continue; - } - } - - if (historyItem.message.role === "user") { - // Gather context items for user messages - let content = normalizeToMessageParts(historyItem.message); - - const ctxItems = historyItem.contextItems - .map((ctxItem) => { - return { - type: "text", - text: `${ctxItem.content}\n`, - } as TextMessagePart; - }) - .filter((part) => !!part.text.trim()); - - content = [...ctxItems, ...content]; - msgs.push({ - ...historyItem.message, - content, - }); - } else { - msgs.push(historyItem.message); - } - } - - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as - | UserChatMessage - | ToolResultChatMessage - | undefined; - - // Get context items for the last user message - const lastUserContextItems = getUserContextItems( - lastUserMsg, - filteredHistory, - ); - const systemMessage = getSystemMessageWithRules({ - baseSystemMessage: baseChatOrAgentSystemMessage, - rules, - userMessage: lastUserMsg, - contextItems: lastUserContextItems, - rulePolicies, - }); - - if (systemMessage.trim()) { - msgs.unshift({ - role: "system", - content: systemMessage, - }); - } - - // Remove the "id" from all of the messages - return msgs.map((msg) => { - const { id, ...rest } = msg as any; - return rest; - }); -} diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts new file mode 100644 index 000000000..c2f82bac4 --- /dev/null +++ b/core/llm/defaultSystemMessages.ts @@ -0,0 +1,68 @@ +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; + +export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ + Always include the language and file name in the info string when you write code blocks. + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' +`; + +export const EDIT_CODE_INSTRUCTIONS = `\ + When addressing code modification requests, present a concise code snippet that + emphasizes only the necessary changes and uses abbreviated placeholders for + unmodified sections. For example: + + \`\`\`language /path/to/file + // ... existing code ... + + {{ modified code here }} + + // ... existing code ... + + {{ another modification }} + + // ... rest of code ... + \`\`\` + + In existing files, you should always restate the function or class that the snippet belongs to: + + \`\`\`language /path/to/file + // ... existing code ... + + function exampleFunction() { + // ... existing code ... + + {{ modified code here }} + + // ... rest of function ... + } + + // ... rest of code ... + \`\`\` + + Since users have access to their complete file, they prefer reading only the + relevant modifications. It's perfectly acceptable to omit unmodified portions + at the beginning, middle, or end of files using these "lazy" comments. Only + provide the complete file when explicitly requested. Include a concise explanation + of changes unless the user specifically asks for code only. +`; + +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ + + You are in chat mode. + + If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. + If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. + +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +${EDIT_CODE_INSTRUCTIONS} +`; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ + + You are in agent mode. + +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +`; diff --git a/core/llm/index.ts b/core/llm/index.ts index 78f5c4ff6..47fdf8011 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -384,6 +384,50 @@ export abstract class BaseLLM implements ILLM { } } + private async parseError(resp: any): Promise { + let text = await resp.text(); + + if (resp.status === 404 && !resp.url.includes("/v1")) { + const parsedError = JSON.parse(text); + const errorMessageRaw = parsedError?.error ?? parsedError?.message; + const error = + typeof errorMessageRaw === "string" + ? errorMessageRaw.replace(/"/g, "'") + : undefined; + let model = error?.match(/model '(.*)' not found/)?.[1]; + if (model && resp.url.match("127.0.0.1:11434")) { + text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + return new LLMError(text, this); // No need to add HTTP status details + } else if (text.includes("/api/chat")) { + text = + "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; + } else { + text = + "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; + } + } else if (resp.status === 404 && resp.url.includes("api.openai.com")) { + text = + "You may need to add pre-paid credits before using the OpenAI API."; + } else if ( + resp.status === 401 && + (resp.url.includes("api.mistral.ai") || + resp.url.includes("codestral.mistral.ai")) + ) { + if (resp.url.includes("codestral.mistral.ai")) { + return new Error( + "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.", + ); + } else { + return new Error( + "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.", + ); + } + } + return new Error( + `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`, + ); + } + fetch(url: RequestInfo | URL, init?: RequestInit): Promise { // Custom Node.js fetch const customFetch = async (input: URL | RequestInfo, init: any) => { @@ -399,44 +443,9 @@ export abstract class BaseLLM implements ILLM { if (resp.status === 499) { return resp; // client side cancellation } - let text = await resp.text(); - if (resp.status === 404 && !resp.url.includes("/v1")) { - const error = JSON.parse(text)?.error?.replace(/"/g, "'"); - let model = error?.match(/model '(.*)' not found/)?.[1]; - if (model && resp.url.match("127.0.0.1:11434")) { - text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; - throw new LLMError(text, this); // No need to add HTTP status details - } else if (text.includes("/api/chat")) { - text = - "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; - } else { - text = - "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; - } - } else if ( - resp.status === 404 && - resp.url.includes("api.openai.com") - ) { - text = - "You may need to add pre-paid credits before using the OpenAI API."; - } else if ( - resp.status === 401 && - (resp.url.includes("api.mistral.ai") || - resp.url.includes("codestral.mistral.ai")) - ) { - if (resp.url.includes("codestral.mistral.ai")) { - throw new Error( - "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.", - ); - } else { - throw new Error( - "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.", - ); - } - } - throw new Error( - `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`, - ); + + const error = await this.parseError(resp); + throw error; } return resp; @@ -492,28 +501,32 @@ export abstract class BaseLLM implements ILLM { const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : []; let formatted = ""; for (const msg of msgsCopy) { - let contentToShow = ""; - if (msg.role === "tool") { - contentToShow = msg.content; - } else if (msg.role === "assistant" && msg.toolCalls) { - contentToShow = msg.toolCalls - ?.map( - (toolCall) => - `${toolCall.function?.name}(${toolCall.function?.arguments})`, - ) - .join("\n"); - } else if ("content" in msg) { - if (Array.isArray(msg.content)) { - msg.content = renderChatMessage(msg); - } - contentToShow = msg.content; - } - - formatted += `<${msg.role}>\n${contentToShow}\n\n`; + formatted += this._formatChatMessage(msg); } return formatted; } + private _formatChatMessage(msg: ChatMessage): string { + let contentToShow = ""; + if (msg.role === "tool") { + contentToShow = msg.content; + } else if (msg.role === "assistant" && msg.toolCalls) { + contentToShow = msg.toolCalls + ?.map( + (toolCall) => + `${toolCall.function?.name}(${toolCall.function?.arguments})`, + ) + .join("\n"); + } else if ("content" in msg) { + if (Array.isArray(msg.content)) { + msg.content = renderChatMessage(msg); + } + contentToShow = msg.content; + } + + return `<${msg.role}>\n${contentToShow}\n\n`; + } + protected async *_streamFim( prefix: string, suffix: string, @@ -569,11 +582,12 @@ export abstract class BaseLLM implements ILLM { const result = fromChatCompletionChunk(chunk); if (result) { const content = renderChatMessage(result); + const formattedContent = this._formatChatMessage(result); interaction?.logItem({ kind: "chunk", - chunk: content, + chunk: formattedContent, }); - completion += content; + completion += formattedContent; yield content; } } @@ -932,7 +946,7 @@ export abstract class BaseLLM implements ILLM { ); const msg = fromChatResponse(response); yield msg; - completion = renderChatMessage(msg); + completion = this._formatChatMessage(msg); } else { // Stream true const stream = this.openaiAdapter.chatCompletionStream( @@ -945,7 +959,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of stream) { const result = fromChatCompletionChunk(chunk); if (result) { - completion += result.content; + completion += this._formatChatMessage(result); interaction?.logItem({ kind: "message", message: result, @@ -961,7 +975,7 @@ export abstract class BaseLLM implements ILLM { completionOptions, )) { if (chunk.role === "assistant") { - completion += chunk.content; + completion += this._formatChatMessage(chunk); } else if (chunk.role === "thinking") { thinking += chunk.content; } diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index a3088f409..69b4ab7a8 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -1,12 +1,10 @@ -import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; -import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; -import Bedrock from "./Bedrock.js"; import { ChatMessage, Chunk, CompletionOptions, UserChatMessage, } from "../../index.js"; +import Bedrock from "./Bedrock.js"; // Mock AWS SDK jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ @@ -317,96 +315,266 @@ describe("Bedrock", () => { }); }); - it("should convert text messages correctly", () => { - const message: ChatMessage = { - role: "user", - content: "Hello", - } as UserChatMessage; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [{ text: "Hello" }], - }); + it("should convert simple user and assistant messages correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" } as UserChatMessage, + { role: "assistant", content: "Hi there" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Hello" }] }, + { role: "assistant", content: [{ text: "Hi there" }] }, + ]); }); - it("should convert tool responses correctly", () => { - const message: ChatMessage = { - role: "tool", - content: "Tool result", - toolCallId: "tool-1", - }; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [ - { - toolResult: { - toolUseId: "tool-1", - content: [{ text: "Tool result" }], - }, - }, - ], - }); - }); - - it("should convert tool calls correctly", () => { - const message: ChatMessage = { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-1", - type: "function" as const, - function: { - name: "test_tool", - arguments: '{"arg":"value"}', - }, - }, - ], - }; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "assistant", - content: [ - { - toolUse: { - toolUseId: "tool-1", - name: "test_tool", - input: { arg: "value" }, - }, - }, - ], - }); - }); - - it("should handle multimodal content correctly", () => { - const message: ChatMessage = { - role: "user", - content: [ - { type: "text", text: "Look at this image:" }, - { - type: "imageUrl", - imageUrl: { - url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", - }, - }, - ], - } as UserChatMessage; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [ - { text: "Look at this image:" }, - { - image: { - format: "jpeg", - source: { - bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), + it("should handle tool responses correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Use a tool" } as UserChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg":"value"}', }, }, - }, - ], + ], + }, + { + role: "tool", + content: "Tool result", + toolCallId: "tool-1", + }, + ]; + + const availableTools = new Set(["test_tool"]); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Use a tool" }] }, + { + role: "assistant", + content: [ + { + toolUse: { + toolUseId: "tool-1", + name: "test_tool", + input: { arg: "value" }, + }, + }, + ], + }, + { + role: "user", + content: [ + { + toolResult: { + toolUseId: "tool-1", + content: [{ text: "Tool result" }], + }, + }, + ], + }, + ]); + }); + + it("should handle tool calls with unavailable tools as text", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Use a tool" } as UserChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-1", + type: "function", + function: { + name: "unavailable_tool", + arguments: '{"arg":"value"}', + }, + }, + ], + }, + ]; + + // Empty set means no tools are available + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Use a tool" }] }, + { + role: "assistant", + content: [ + { + text: expect.stringContaining("Assistant tool call:"), + }, + ], + }, + ]); + }); + + it("should handle thinking messages correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Think about this" } as UserChatMessage, + { role: "thinking", content: "I am thinking about the solution" }, + { role: "assistant", content: "Here's my answer" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Think about this" }] }, + { + role: "assistant", + content: [ + { + reasoningContent: { + reasoningText: { + text: "I am thinking about the solution", + signature: undefined, + }, + }, + }, + { text: "Here's my answer" }, + ], + }, + ]); + }); + + it("should handle redacted thinking messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Think about this" } as UserChatMessage, + { + role: "thinking", + content: "", + redactedThinking: "redacted-content-bytes", + }, + { role: "assistant", content: "Here's my answer" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Think about this" }] }, + { + role: "assistant", + content: [ + { + reasoningContent: { + redactedContent: expect.any(Uint8Array), + }, + }, + { text: "Here's my answer" }, + ], + }, + ]); + + // Check that the Uint8Array contains the expected bytes + const redactedContent = + converted[1].content?.[0].reasoningContent?.redactedContent; + expect(redactedContent).toBeInstanceOf(Uint8Array); + expect(Buffer.from(redactedContent!).toString()).toBe( + "redacted-content-bytes", + ); + }); + + it("should convert multimodal content correctly", () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: [ + { type: "text", text: "Look at this image:" }, + { + type: "imageUrl", + imageUrl: { + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", + }, + }, + ], + } as UserChatMessage, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { + role: "user", + content: [ + { text: "Look at this image:" }, + { + image: { + format: "jpeg", + source: { + bytes: expect.any(Uint8Array), + }, + }, + }, + ], + }, + ]); + + // Check that the image bytes were processed correctly + const imageBytes = converted[0].content?.[1].image?.source?.bytes; + expect(imageBytes).toBeInstanceOf(Uint8Array); + expect(Buffer.from(imageBytes!).toString("base64")).toBe( + "/9j/4AAQSkZJRg==", + ); + }); + + it("should add cache points for prompt caching when needed", () => { + // Create a test instance with caching behavior enabled + const bedrockWithCaching = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", }); + + // Set caching behavior + bedrockWithCaching.cacheBehavior = { + cacheConversation: true, + cacheSystemMessage: true, + }; + + const messages: ChatMessage[] = [ + { role: "system", content: "You are a helpful assistant" }, + { role: "user", content: "First message" } as UserChatMessage, + { role: "assistant", content: "First response" }, + { role: "user", content: "Second message" } as UserChatMessage, + ]; + + const availableTools = new Set(); + const converted = bedrockWithCaching["_convertMessages"]( + messages, + availableTools, + ); + + // The last two user messages should have cache points + // But we're not testing the system message here since it's handled separately + expect(converted.length).toBe(3); + expect(converted[0].role).toBe("user"); + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( + true, + ); + expect(converted[1].role).toBe("assistant"); + expect(converted[2].role).toBe("user"); + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( + true, + ); + + // Verify that text content includes a cache ID suffix + const userMessageText = converted[0].content?.[0].text; + expect(userMessageText).toMatch(/First message.+/); }); }); }); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 371713905..1c1c61ed3 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,8 +1,10 @@ import { BedrockRuntimeClient, ContentBlock, + ConversationRole, ConverseStreamCommand, ConverseStreamCommandOutput, + ImageFormat, InvokeModelCommand, Message, ToolConfiguration, @@ -14,6 +16,7 @@ import { Chunk, CompletionOptions, LLMOptions, + MessageContent, } from "../../index.js"; import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; @@ -289,8 +292,8 @@ class Bedrock extends BaseLLM { const systemMessage = stripImages( messages.find((m) => m.role === "system")?.content ?? "", ); - const convertedMessages = this._convertMessages(messages); + // Prompt and system message caching settings const shouldCacheSystemMessage = (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || this.completionOptions.promptCaching; @@ -298,9 +301,7 @@ class Bedrock extends BaseLLM { shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching; - const shouldCacheToolsConfig = this.completionOptions.promptCaching; - // Add header for prompt caching if (enablePromptCaching) { this.requestOptions.headers = { ...this.requestOptions.headers, @@ -308,30 +309,37 @@ class Bedrock extends BaseLLM { }; } + // First get tools const supportsTools = (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false; - let toolConfig = - supportsTools && options.tools - ? ({ - tools: options.tools.map((tool) => ({ - toolSpec: { - name: tool.function.name, - description: tool.function.description, - inputSchema: { - json: tool.function.parameters, - }, - }, - })), - } as ToolConfiguration) - : undefined; - - if (toolConfig?.tools && shouldCacheToolsConfig) { - toolConfig.tools.push({ cachePoint: { type: "default" } }); + let toolConfig: undefined | ToolConfiguration = undefined; + const availableTools = new Set(); + if (supportsTools && options.tools && options.tools.length > 0) { + toolConfig = { + tools: options.tools.map((tool) => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters, + }, + }, + })), + } as ToolConfiguration; + const shouldCacheToolsConfig = this.completionOptions.promptCaching; + if (shouldCacheToolsConfig) { + toolConfig.tools!.push({ cachePoint: { type: "default" } }); + } + options.tools.forEach((tool) => { + availableTools.add(tool.function.name); + }); } + const convertedMessages = this._convertMessages(messages, availableTools); + return { modelId: options.model, system: systemMessage @@ -368,167 +376,236 @@ class Bedrock extends BaseLLM { }; } - private _convertMessage( - message: ChatMessage, - addCaching: boolean = false, - ): Message | null { - // Handle system messages explicitly - if (message.role === "system") { - return null; - } + /* + Converts the messages to the format expected by the Bedrock API. + + */ + private _convertMessages( + messages: ChatMessage[], + availableTools: Set, + ): Message[] { + let currentRole: "user" | "assistant" = "user"; + let currentBlocks: ContentBlock[] = []; - const cachePoint = addCaching - ? { cachePoint: { type: "default" } } - : undefined; - - // Tool response handling - if (message.role === "tool") { - return { - role: "user", - content: [ - { - toolResult: { - toolUseId: message.toolCallId, - content: [ - { - text: message.content || "", - }, - ], - }, - }, - ], - }; - } - - // Tool calls handling - if (message.role === "assistant" && message.toolCalls) { - return { - role: "assistant", - content: message.toolCalls.map((toolCall) => ({ - toolUse: { - toolUseId: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - }, - })), - }; - } - - if (message.role === "thinking") { - if (message.redactedThinking) { - const content: ContentBlock.ReasoningContentMember = { - reasoningContent: { - redactedContent: new Uint8Array( - Buffer.from(message.redactedThinking), - ), - }, - }; - return { - role: "assistant", - content: [content], - }; - } else { - const content: ContentBlock.ReasoningContentMember = { - reasoningContent: { - reasoningText: { - text: (message.content as string) || "", - signature: message.signature, - }, - }, - }; - return { - role: "assistant", - content: [content], - }; + const converted: Message[] = []; + const pushCurrentMessage = () => { + if (currentBlocks.length === 0 && converted.length > 1) { + throw new Error( + `Bedrock: no content in ${currentRole} message before conversational turn change`, + ); } - } - - // Standard text message - if (typeof message.content === "string") { - if (addCaching) { - message.content += getSecureID(); + if (currentBlocks.length > 0) { + converted.push({ + role: currentRole, + content: currentBlocks, + }); } - const content: any[] = [{ text: message.content }]; - if (addCaching) { - content.push({ cachePoint: { type: "default" } }); - } - return { - role: message.role, - content, - }; - } + currentBlocks = []; + }; - // Improved multimodal content handling - if (Array.isArray(message.content)) { - const content: any[] = []; + const nonSystemMessages = messages.filter((m) => m.role !== "system"); + const hasAddedToolCallIds = new Set(); - // Process all parts first - message.content.forEach((part) => { - if (part.type === "text") { - if (addCaching) { - part.text += getSecureID(); + for (let idx = 0; idx < nonSystemMessages.length; idx++) { + const message = nonSystemMessages[idx]; + + if (message.role === "user" || message.role === "tool") { + // Detect conversational turn change + if (currentRole !== ConversationRole.USER) { + pushCurrentMessage(); + currentRole = ConversationRole.USER; + } + + // USER messages: + // Non-empty user message content is converted to "text" and "image" blocks + // If ANY user message part is cached, we add a single cache point block when we push the message + if (message.role === "user") { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { + currentBlocks.push( + ...this._convertMessageContentToBlocks(trimmedContent), + ); } - content.push({ text: part.text }); + } + // TOOL messages: + // Tool messages are represented by "toolResult" blocks + // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig) + // If it doesn't, we convert it to a text block + else if (message.role === "tool") { + const trimmedContent = message.content.trim() || "No tool output"; + if (hasAddedToolCallIds.has(message.toolCallId)) { + currentBlocks.push({ + toolResult: { + toolUseId: message.toolCallId, + content: [ + { + text: trimmedContent, + }, + ], + }, + }); + } else { + currentBlocks.push({ + text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`, + }); + } + } + } else if (message.role === "assistant" || message.role === "thinking") { + // Detect conversational turn change + if (currentRole !== ConversationRole.ASSISTANT) { + pushCurrentMessage(); + currentRole = ConversationRole.ASSISTANT; + } + + // ASSISTANT messages: + // Non-empty assistant message content is converted to "text" and "image" blocks + if (message.role === "assistant") { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { + currentBlocks.push( + ...this._convertMessageContentToBlocks(trimmedContent), + ); + } + // TOOL CALLS: + // Tool calls are represented by "toolUse" blocks + // Each tool call must have an id and a function name + // The function name must match one of the available tools + // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools) + if (message.toolCalls) { + for (const toolCall of message.toolCalls) { + if (toolCall.id && toolCall.function?.name) { + if (availableTools.has(toolCall.function.name)) { + currentBlocks.push({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function.name, + input: safeParseToolCallArgs(toolCall), + }, + }); + hasAddedToolCallIds.add(toolCall.id); + } else { + const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; + currentBlocks.push({ + text: toolCallText, + }); + } + } else { + console.warn( + `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, + ); + continue; + } + } + } + } else if (message.role === "thinking") { + // THINKING: + // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content + if (message.redactedThinking) { + const block: ContentBlock.ReasoningContentMember = { + reasoningContent: { + redactedContent: new Uint8Array( + Buffer.from(message.redactedThinking), + ), + }, + }; + currentBlocks.push(block); + } else { + const block: ContentBlock.ReasoningContentMember = { + reasoningContent: { + reasoningText: { + text: (message.content as string) || "", + signature: message.signature, + }, + }, + }; + currentBlocks.push(block); + } + } + } + } + if (currentBlocks.length > 0) { + pushCurrentMessage(); + } + + // If caching is enabled, we add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + if (this.cacheBehavior?.cacheConversation) { + this._addCachingToLastTwoUserMessages(converted); + } + + return converted; + } + + private _addCachingToLastTwoUserMessages(converted: Message[]) { + let numCached = 0; + for (let i = converted.length - 1; i >= 0; i--) { + const message = converted[i]; + if (message.role === "user") { + message.content?.forEach((block) => { + if (block.text) { + block.text += getSecureID(); + } + }); + message.content?.push({ cachePoint: { type: "default" } }); + numCached++; + } + if (numCached === 2) { + break; + } + } + } + + // Converts Continue message content (string/parts) to Bedrock ContentBlock format. + // Unsupported/problematic image formats are skipped with a warning. + private _convertMessageContentToBlocks( + content: MessageContent, + ): ContentBlock[] { + const blocks: ContentBlock[] = []; + if (typeof content === "string") { + blocks.push({ text: content }); + } else { + for (const part of content) { + if (part.type === "text") { + blocks.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { try { const [mimeType, base64Data] = part.imageUrl.url.split(","); const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; - content.push({ - image: { - format, - source: { - bytes: Buffer.from(base64Data, "base64"), + if ( + format === ImageFormat.JPEG || + format === ImageFormat.PNG || + format === ImageFormat.WEBP || + format === ImageFormat.GIF + ) { + blocks.push({ + image: { + format, + source: { + bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), + }, }, - }, - }); + }); + } else { + console.warn( + `Bedrock: skipping unsupported image part format: ${format}`, + part, + ); + } } catch (error) { - console.warn(`Failed to process image: ${error}`); + console.warn("Bedrock: failed to process image part", error, part); } } - }); - - // Add cache point as a separate block at the end if needed - if (addCaching && content.length > 0) { - content.push({ cachePoint: { type: "default" } }); } - - return { - role: message.role, - content, - } as Message; } - return null; - } - - private _convertMessages(messages: ChatMessage[]): any[] { - const filteredmessages = messages.filter( - (m) => m.role !== "system" && !!m.content, - ); - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1) - .slice(-2); - - const converted = filteredmessages - .map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); - - try { - return this._convertMessage(message, addCaching); - } catch (error) { - console.error(`Failed to convert message: ${error}`); - return null; - } - }) - .filter(Boolean); - - return converted; + return blocks; } private async _getCredentials() { diff --git a/core/llm/llms/LlamaStack.ts b/core/llm/llms/LlamaStack.ts new file mode 100644 index 000000000..c246bdbdf --- /dev/null +++ b/core/llm/llms/LlamaStack.ts @@ -0,0 +1,57 @@ +import { streamSse } from "@continuedev/fetch"; +import { CompletionOptions, LLMOptions } from "../../index.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; + +import OpenAI from "./OpenAI.js"; + +class LlamaStack extends OpenAI { + static providerName = "llamastack"; + static defaultOptions: Partial = { + apiBase: "http://localhost:8321/v1/openai/v1/", + model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; + maxStopWords: number | undefined = 16; + + supportsFim(): boolean { + return true; + } + + async *_streamFim( + prefix: string, + suffix: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + prompt: prefix, + suffix, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].text; + } + } +} + +export default LlamaStack; diff --git a/core/llm/llms/Test.ts b/core/llm/llms/Test.ts index 202046cc6..814659b9b 100644 --- a/core/llm/llms/Test.ts +++ b/core/llm/llms/Test.ts @@ -2,6 +2,7 @@ import { ChatMessage, CompletionOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE"; +const NEXT_EDIT_COMPLETION: string = "<|editable_region_start|>\nHELLO\n"; class TestLLM extends BaseLLM { static providerName = "test"; @@ -24,7 +25,15 @@ class TestLLM extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - yield this.findResponse(prompt) || `PROMPT: ${prompt}`; + if ( + prompt === "NEXT_EDIT" || + prompt === + "<|im_start|>user\nNEXT_EDIT<|im_end|>\n<|im_start|>assistant\n" + ) { + yield NEXT_EDIT_COMPLETION; + } else { + yield this.findResponse(prompt) || `PROMPT: ${prompt}`; + } } protected async *_streamChat( diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index a003ce0cf..e45828c40 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -1,3 +1,4 @@ +import Handlebars from "handlebars"; import { BaseCompletionOptions, IdeSettings, @@ -6,10 +7,9 @@ import { JSONModelDescription, LLMOptions, } from "../.."; -import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; +import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; import { BaseLLM } from "../index"; - import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; import Azure from "./Azure"; @@ -33,6 +33,7 @@ import Inception from "./Inception"; import Kindo from "./Kindo"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; +import LlamaStack from "./LlamaStack"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; import MockLLM from "./Mock"; @@ -62,7 +63,6 @@ import Vllm from "./Vllm"; import Voyage from "./Voyage"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; - export const LLMClasses = [ Anthropic, Cohere, @@ -116,11 +116,13 @@ export const LLMClasses = [ Relace, Inception, Voyage, + LlamaStack, ]; export async function llmFromDescription( desc: JSONModelDescription, readFile: (filepath: string) => Promise, + getUriFromPath: (path: string) => Promise, uniqueId: string, ideSettings: IdeSettings, llmLogger: ILLMLogger, @@ -142,9 +144,12 @@ export async function llmFromDescription( baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; baseChatSystemMessage += "\n\n"; baseChatSystemMessage += await renderTemplatedString( + Handlebars, desc.systemMessage, - readFile, {}, + [], + readFile, + getUriFromPath, ); } diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index c005a5f92..f017f24fd 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -327,27 +327,36 @@ export const getApplicableRules = ( export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, - rules, + availableRules, contextItems, rulePolicies = {}, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; - rules: RuleWithSource[]; + availableRules: RuleWithSource[]; contextItems: ContextItemWithId[]; rulePolicies?: RulePolicies; -}) => { - const applicableRules = getApplicableRules( +}): { + systemMessage: string; + appliedRules: RuleWithSource[]; +} => { + const appliedRules = getApplicableRules( userMessage, - rules, + availableRules, contextItems, rulePolicies, ); let systemMessage = baseSystemMessage ?? ""; - for (const rule of applicableRules) { - systemMessage += `\n\n${rule.rule}`; + for (const rule of appliedRules) { + if (systemMessage) { + systemMessage += "\n\n"; + } + systemMessage += rule.rule; } - return systemMessage; + return { + systemMessage, + appliedRules, + }; }; diff --git a/core/llm/stream.ts b/core/llm/stream.ts deleted file mode 100644 index 5902ec114..000000000 --- a/core/llm/stream.ts +++ /dev/null @@ -1,114 +0,0 @@ -export async function* toAsyncIterable( - nodeReadable: NodeJS.ReadableStream, -): AsyncGenerator { - for await (const chunk of nodeReadable) { - // @ts-ignore - yield chunk as Uint8Array; - } -} - -export async function* streamResponse( - response: Response, -): AsyncGenerator { - if (response.status !== 200) { - throw new Error(await response.text()); - } - - if (!response.body) { - throw new Error("No response body returned."); - } - - // Get the major version of Node.js - const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10); - - if (nodeMajorVersion >= 20) { - // Use the new API for Node 20 and above - const stream = (ReadableStream as any).from(response.body); - for await (const chunk of stream.pipeThrough( - new TextDecoderStream("utf-8"), - )) { - yield chunk; - } - } else { - // Fallback for Node versions below 20 - // Streaming with this method doesn't work as version 20+ does - const decoder = new TextDecoder("utf-8"); - const nodeStream = response.body as unknown as NodeJS.ReadableStream; - for await (const chunk of toAsyncIterable(nodeStream)) { - yield decoder.decode(chunk, { stream: true }); - } - } -} - -function parseDataLine(line: string): any { - const json = line.startsWith("data: ") - ? line.slice("data: ".length) - : line.slice("data:".length); - - try { - const data = JSON.parse(json); - if (data.error) { - throw new Error(`Error streaming response: ${data.error}`); - } - - return data; - } catch (e) { - throw new Error(`Malformed JSON sent from server: ${json}`); - } -} - -function parseSseLine(line: string): { done: boolean; data: any } { - if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { - return { done: true, data: undefined }; - } - if (line.startsWith("data:")) { - return { done: false, data: parseDataLine(line) }; - } - if (line.startsWith(": ping")) { - return { done: true, data: undefined }; - } - return { done: false, data: undefined }; -} - -export async function* streamSse(response: Response): AsyncGenerator { - let buffer = ""; - for await (const value of streamResponse(response)) { - buffer += value; - - let position: number; - while ((position = buffer.indexOf("\n")) >= 0) { - const line = buffer.slice(0, position); - buffer = buffer.slice(position + 1); - - const { done, data } = parseSseLine(line); - if (done) { - break; - } - if (data) { - yield data; - } - } - } - - if (buffer.length > 0) { - const { done, data } = parseSseLine(buffer); - if (!done && data) { - yield data; - } - } -} - -export async function* streamJSON(response: Response): AsyncGenerator { - let buffer = ""; - for await (const value of streamResponse(response)) { - buffer += value; - - let position; - while ((position = buffer.indexOf("\n")) >= 0) { - const line = buffer.slice(0, position); - const data = JSON.parse(line); - yield data; - buffer = buffer.slice(position + 1); - } - } -} diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 3f52a0192..00efc8c2d 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -59,6 +59,12 @@ export async function* llmStreamChat( }, true, ); + if (!slashCommand.run) { + console.error( + `Slash command ${command.name} (${command.source}) has no run function`, + ); + throw new Error(`Slash command not found`); + } const gen = slashCommand.run({ input, diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 5f6ffbce8..b578569cb 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -22,6 +22,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "gpt-4", "o3", "gemini", + "claude-opus-4", ].some((part) => model.toLowerCase().startsWith(part)); }, anthropic: (model) => { @@ -32,6 +33,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "claude-3-7", "claude-3.7", "claude-sonnet-4", + "claude-opus-4", ].some((part) => model.toLowerCase().startsWith(part)) ) { return true; @@ -86,15 +88,14 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = ); }, bedrock: (model) => { - // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 if ( - model.toLowerCase().includes("sonnet") && [ - "claude-3-5", - "claude-3.5", - "claude-3-7", - "claude-3.7", + "claude-3-5-sonnet", + "claude-3.5-sonnet", + "claude-3-7-sonnet", + "claude-3.7-sonnet", "claude-sonnet-4", + "claude-opus-4", ].some((part) => model.toLowerCase().includes(part)) ) { return true; @@ -179,7 +180,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, deepseek: (model) => { - if (model !== "deepseek-reasoner") { + // https://api-docs.deepseek.com/quick_start/pricing + // https://api-docs.deepseek.com/guides/function_calling + if (model === "deepseek-reasoner" || model === "deepseek-chat") { return true; } diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 316dc61e9..df4168b28 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,17 +1,14 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; -import { IDE, ILLM } from "../index.js"; +import { ChatMessage, IDE, ILLM } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; -import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js"; import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; -import { postprocessCompletion } from "../autocomplete/postprocessing/index.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; -import { getAllSnippets } from "../autocomplete/snippets/index.js"; -import { renderPrompt } from "../autocomplete/templating/index.js"; +import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js"; @@ -21,6 +18,14 @@ import { AutocompleteInput, AutocompleteOutcome, } from "../autocomplete/util/types.js"; +import { replaceEscapedCharacters } from "../util/text.js"; +import { + Prompt, + renderDefaultSystemPrompt, + renderDefaultUserPrompt, + renderPrompt, +} from "./templating/NextEditPromptEngine.js"; +// import { renderPrompt } from "./templating/NextEditPromptEngine.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -33,6 +38,8 @@ const ERRORS_TO_IGNORE = [ ]; export class NextEditProvider { + private static instance: NextEditProvider | null = null; + private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); @@ -40,16 +47,54 @@ export class NextEditProvider { private completionStreamer: CompletionStreamer; private loggingService = new AutocompleteLoggingService(); private contextRetrievalService: ContextRetrievalService; + private endpointType: "default" | "fineTuned"; + private diffContext: string = ""; - constructor( + private constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly _injectedGetLlm: () => Promise, private readonly _onError: (e: any) => void, private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, + endpointType: "default" | "fineTuned", ) { this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); this.contextRetrievalService = new ContextRetrievalService(this.ide); + this.endpointType = endpointType; + } + + public static initialize( + configHandler: ConfigHandler, + ide: IDE, + injectedGetLlm: () => Promise, + onError: (e: any) => void, + getDefinitionsFromLsp: GetLspDefinitionsFunction, + endpointType: "default" | "fineTuned", + ): NextEditProvider { + if (!NextEditProvider.instance) { + NextEditProvider.instance = new NextEditProvider( + configHandler, + ide, + injectedGetLlm, + onError, + getDefinitionsFromLsp, + endpointType, + ); + } + return NextEditProvider.instance; + } + + public static getInstance(): NextEditProvider { + if (!NextEditProvider.instance) { + throw new Error( + "NextEditProvider has not been initialized. Call initialize() first.", + ); + } + return NextEditProvider.instance; + } + + public addDiffToContext(diff: string): void { + this.diffContext = diff; } private async _prepareLlm(): Promise { @@ -174,7 +219,7 @@ export class NextEditProvider { } const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippets({ + getAllSnippetsWithoutRace({ helper, ide: this.ide, getDefinitionsFromLsp: this.getDefinitionsFromLsp, @@ -183,100 +228,241 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const { prompt, prefix, suffix, completionOptions } = renderPrompt({ - snippetPayload, - workspaceDirs, - helper, - }); + // TODO: Toggle between the default endpoint and the finetuned endpoint. + const prompts: Prompt[] = []; - // Completion - let completion: string | undefined = ""; - - const cache = await autocompleteCache; - const cachedCompletion = helper.options.useCache - ? await cache.get(helper.prunedPrefix) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; + if (this.endpointType === "default") { + prompts.push(renderDefaultSystemPrompt()); + prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); } else { - const multiline = - !helper.options.transform || shouldCompleteMultiline(helper); + prompts.push( + // await renderFineTunedUserPrompt(snippetPayload, this.ide, helper), + // await renderFineTunedBasicUserPrompt( + // snippetPayload, + // this.ide, + // helper, + // this.diffContext, + // ), + renderPrompt(helper, this.diffContext), + ); + } - const completionStream = - this.completionStreamer.streamCompletionWithFilters( - token, - llm, - prefix, - suffix, - prompt, - multiline, - completionOptions, - helper, - ); - - for await (const update of completionStream) { - completion += update; - } - - // Don't postprocess if aborted - if (token.aborted) { + if (this.endpointType === "default") { + const msg: ChatMessage = await llm.chat(prompts, token); + if (typeof msg.content === "string") { + const nextCompletion = JSON.parse(msg.content).newCode; + const outcomeNext: AutocompleteOutcome = { + time: Date.now() - startTime, + completion: nextCompletion, + prefix: "", + suffix: "", + prompt: "", + modelProvider: llm.underlyingProviderName, + modelName: llm.model, + completionOptions: null, + cacheHit: false, + filepath: helper.filepath, + numLines: nextCompletion.split("\n").length, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + ...helper.options, + }; + return outcomeNext; + } else { return undefined; } + // const body = { + // model: defaultModel, + // messages: prompts, + // // max_tokens: 15000, + // // stop: ["<|editable_region_end|>"], + // }; + // + // const resp = await fetch(defaultEndpoint, { + // method: "POST", + // headers: { + // Authorization: `Bearer ${mercuryToken} `, + // "Content-Type": "application/json", + // }, + // body: JSON.stringify(body), + // }); + // + // const respJson = await resp.json(); - const processedCompletion = helper.options.transform - ? postprocessCompletion({ - completion, - prefix: helper.prunedPrefix, - suffix: helper.prunedSuffix, - llm, - }) - : completion; + // TODO: Do some zod schema validation here if needed. + } else { + // const testController = new AbortController(); + // const msg: ChatMessage = await llm.chat(prompts, testController.signal); + // const testToken = testController.signal; + const msg: ChatMessage = await llm.chat(prompts, token); + if (typeof msg.content === "string") { + // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined + const nextCompletion = replaceEscapedCharacters( + msg.content.split("<|editable_region_start|>\n")[1], + ).replace(/\n$/, ""); - completion = processedCompletion; + // const diffLines = myersDiff(helper.fileContents, nextCompletion); + + // const diff = getRenderableDiff(diffLines); + const outcomeNext: AutocompleteOutcome = { + time: Date.now() - startTime, + completion: nextCompletion, + prefix: "", + suffix: "", + prompt: "", + modelProvider: llm.underlyingProviderName, + modelName: llm.model, + completionOptions: null, + cacheHit: false, + filepath: helper.filepath, + numLines: nextCompletion.split("\n").length, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + ...helper.options, + }; + return outcomeNext; + } else { + return undefined; + } + // const body = { + // model: fineTunedModel, + // messages: prompts, + // max_tokens: 15000, + // stop: ["<|editable_region_end|>"], + // }; + // + // const resp = await fetch(fineTunedEndpoint, { + // method: "POST", + // headers: { + // Authorization: `Bearer ${mercuryToken} `, + // "Content-Type": "application/json", + // }, + // body: JSON.stringify(body), + // }); + // + // const respJson = await resp.json(); + // + // const nextCompletion = respJson.choices[0].message.content + // .split("<|editable_region_start|>\n")[1] + // .split("<|editable_region_end|>")[0] + // .slice(1) + // .slice(0, -1) + // .replaceAll("\\n", "\n") + // .replaceAll('\\"', '"'); + // + // const outcomeNext: AutocompleteOutcome = { + // time: Date.now() - startTime, + // completion: nextCompletion, + // prefix: "", + // suffix: "", + // prompt: "", + // modelProvider: llm.underlyingProviderName, + // modelName: llm.model, + // completionOptions: null, + // cacheHit: false, + // filepath: helper.filepath, + // numLines: nextCompletion.split("\n").length, + // completionId: helper.input.completionId, + // gitRepo: await this.ide.getRepoName(helper.filepath), + // uniqueId: await this.ide.getUniqueId(), + // timestamp: Date.now(), + // ...helper.options, + // }; + // return outcomeNext; } - if (!completion) { - return undefined; - } + // // Completion + // let completion: string | undefined = ""; - const outcome: AutocompleteOutcome = { - time: Date.now() - startTime, - completion, - prefix, - suffix, - prompt, - modelProvider: llm.underlyingProviderName, - modelName: llm.model, - completionOptions, - cacheHit, - filepath: helper.filepath, - numLines: completion.split("\n").length, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - ...helper.options, - }; + // const cache = await autocompleteCache; + // const cachedCompletion = helper.options.useCache + // ? await cache.get(helper.prunedPrefix) + // : undefined; + // let cacheHit = false; + // if (cachedCompletion) { + // // Cache + // cacheHit = true; + // completion = cachedCompletion; + // } else { + // const multiline = + // !helper.options.transform || shouldCompleteMultiline(helper); - ////////// + // const completionStream = + // this.completionStreamer.streamCompletionWithFilters( + // token, + // llm, + // prefix, + // suffix, + // prompt, + // multiline, + // completionOptions, + // helper, + // ); - // Save to cache - if (!outcome.cacheHit && helper.options.useCache) { - (await this.autocompleteCache) - .put(outcome.prefix, outcome.completion) - .catch((e) => console.warn(`Failed to save to cache: ${e.message}`)); - } + // for await (const update of completionStream) { + // completion += update; + // } - // When using the JetBrains extension, Mark as displayed - const ideType = (await this.ide.getIdeInfo()).ideType; - if (ideType === "jetbrains") { - this.markDisplayed(input.completionId, outcome); - } + // // Don't postprocess if aborted + // if (token.aborted) { + // return undefined; + // } - return outcome; + // const processedCompletion = helper.options.transform + // ? postprocessCompletion({ + // completion, + // prefix: helper.prunedPrefix, + // suffix: helper.prunedSuffix, + // llm, + // }) + // : completion; + + // completion = processedCompletion; + // } + + // if (!completion) { + // return undefined; + // } + + // const outcome: AutocompleteOutcome = { + // time: Date.now() - startTime, + // completion, + // prefix, + // suffix, + // prompt, + // modelProvider: llm.underlyingProviderName, + // modelName: llm.model, + // completionOptions, + // cacheHit, + // filepath: helper.filepath, + // numLines: completion.split("\n").length, + // completionId: helper.input.completionId, + // gitRepo: await this.ide.getRepoName(helper.filepath), + // uniqueId: await this.ide.getUniqueId(), + // timestamp: Date.now(), + // ...helper.options, + // }; + + // ////////// + + // // Save to cache + // if (!outcome.cacheHit && helper.options.useCache) { + // (await this.autocompleteCache) + // .put(outcome.prefix, outcome.completion) + // .catch((e) => console.warn(`Failed to save to cache: ${e.message}`)); + // } + + // // When using the JetBrains extension, Mark as displayed + // const ideType = (await this.ide.getIdeInfo()).ideType; + // if (ideType === "jetbrains") { + // this.markDisplayed(input.completionId, outcome); + // } + + // return outcome; } catch (e: any) { this.onError(e); } finally { diff --git a/core/nextEdit/README.md b/core/nextEdit/README.md new file mode 100644 index 000000000..2c78f484f --- /dev/null +++ b/core/nextEdit/README.md @@ -0,0 +1,29 @@ +# Next Edit Prediction + +## What is it? + +## How is it different from autocomplete? + +## Where are we right now? + +- Users can decide to switch between autocomplete and next edit. +- Next edit triggers at the same time autocomplete is triggered, via vscode's inline completion provider. +- The following happens after the trigger: + - User's current cursor position is captured. + - We define an editable range, ±5 lines from the current cursor position. + - User's most recent edit is captured as a unified diff. (this is currently buggy) + - This is sent to the model, which returns a new editable range with next edit predictions. + - We display this new editable range in a SVG decoration. + - User can either tab to accept or esc to reject. + - On accept, the old editable range will be replaced by the new editable region. The cursor will be moved to the last line containing some change. + - On reject, nothing happens. + +## What needs to be worked on? + +- User edit captures. +- Find a better way to trigger next edit (this links back to the diff capture problem). + - We can see that next edit triggers as soon as the user accepts a change. This is because autocomplete runs the same way. + - I think autocomplete has some filter logic that doesn't display the ghost text under some conditions, which I am guessing are the following: + - The model does not have any more completions to create. + - The prediction at the cursor location has been cached. +- JetBrains integration. diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 317a3dcf7..6c1e86fbc 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -1 +1,6 @@ export const IS_NEXT_EDIT_ACTIVE = false; +export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5; +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|>"; +export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts new file mode 100644 index 000000000..4443b1d9e --- /dev/null +++ b/core/nextEdit/context/aggregateEdits.ts @@ -0,0 +1,575 @@ +import { Position, RangeInFileWithNextEditInfo } from "../.."; +import { + BeforeAfterDiff, + DiffFormatType, + createBeforeAfterDiff, + createDiff, +} from "./diffFormatting"; + +interface ClusterState { + beforeState: string; // stores content of cluster before edit + startRange: { minLine: number; maxLine: number }; + currentRange: { minLine: number; maxLine: number }; + edits: RangeInFileWithNextEditInfo[]; // store small edits that form the cluster + firstTimestamp: number; + lastTimestamp: number; + lastLine: number; + firstEditBeforeCursor: { line: number; character: number }; // cursor position before the first edit in the cluster + lastEditAfterCursor: { line: number; character: number }; // cursor position after the last edit in the previous cluster +} + +interface FileState { + activeClusters: ClusterState[]; // Stores active clusters for the file + currentContent: string; // Stores the current content of the file + priorComparisons: string[]; // Stores prior comparisons for the file (not currently used, but kept for future use) + processingQueue: Array<() => Promise>; // Stores a queue of small edits to be processed into clusters + isProcessing: boolean; +} + +export interface EditClusterConfig { + deltaT: number; // Time threshold in seconds; if exceeded, a new cluster is created + deltaL: number; // Line threshold; if the user jumps more than this many lines, a new cluster is created + maxEdits: number; // Maximum number of edits in a cluster + maxDuration: number; // Maximum total duration of an edit in seconds + contextSize: number; // Number of previous edits to store; not currently used but kept for future use + contextLines: number; // Used for computations involving deltaL +} + +export class EditAggregator { + private fileStates: Map = new Map(); + public config: EditClusterConfig; + private previousEditFinalCursorPosition: Position; + private lastProcessedFilePath: string | null = null; + public onComparisonFinalized: ( + diff: BeforeAfterDiff, + beforeCursorPos: Position, + afterPrevEditCursorPos: Position, + ) => void; + + private static _instance: EditAggregator | null = null; + + public static getInstance( + config?: Partial, + onComparisonFinalized?: ( + diff: BeforeAfterDiff, + beforeCursorPos: Position, + afterPrevEditCursorPos: Position, + ) => void, + ): EditAggregator { + // Create instance if it doesn't exist + if (!EditAggregator._instance) { + EditAggregator._instance = new EditAggregator( + config, + onComparisonFinalized, + ); + } + // Update instance if new parameters are provided + else if (config || onComparisonFinalized) { + if (config) { + EditAggregator._instance.config = { + deltaT: config.deltaT ?? EditAggregator._instance.config.deltaT, + deltaL: config.deltaL ?? EditAggregator._instance.config.deltaL, + maxEdits: config.maxEdits ?? EditAggregator._instance.config.maxEdits, + maxDuration: + config.maxDuration ?? EditAggregator._instance.config.maxDuration, + contextSize: + config.contextSize ?? EditAggregator._instance.config.contextSize, + contextLines: + config.contextLines ?? EditAggregator._instance.config.contextLines, + }; + } + + if (onComparisonFinalized) { + EditAggregator._instance.onComparisonFinalized = onComparisonFinalized; + } + } + + return EditAggregator._instance; + } + + constructor( + config: Partial = {}, + onComparisonFinalized: ( + diff: BeforeAfterDiff, + beforeCursorPos: Position, + afterPrevEditCursorPos: Position, + ) => void = () => {}, + ) { + this.config = { + deltaT: config.deltaT ?? 1.0, + deltaL: config.deltaL ?? 5, + maxEdits: config.maxEdits ?? 500, + maxDuration: config.maxDuration ?? 100.0, + contextSize: config.contextSize ?? 5, + contextLines: config.contextLines ?? 3, + }; + this.onComparisonFinalized = onComparisonFinalized; + this.previousEditFinalCursorPosition = { line: 0, character: 0 }; + } + + async processEdit( + edit: RangeInFileWithNextEditInfo, + timestamp: number = Date.now(), + ): Promise { + const filePath = edit.filepath; + + // If we're switching to a different file, finalize all clusters from the previous file + if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) { + await this.finalizeClustersForFile(this.lastProcessedFilePath); + } + + // Update the last processed file path + this.lastProcessedFilePath = filePath; + + if (!this.fileStates.has(filePath)) { + this.fileStates.set(filePath, { + activeClusters: [], + currentContent: edit.fileContents, + priorComparisons: [], + processingQueue: [], + isProcessing: false, + }); + } + + const fileState = this.fileStates.get(filePath)!; + const task = async () => { + await this._processEditInternal(edit, timestamp, fileState); + }; + + fileState.processingQueue.push(task); + + if (!fileState.isProcessing) { + void this._processQueue(filePath); + } + } + + private async _processQueue(filePath: string): Promise { + const fileState = this.fileStates.get(filePath); + if (!fileState) return; + + fileState.isProcessing = true; + + // Process chunks of (5) edits instead of one at a time + while (fileState.processingQueue.length > 0) { + const tasks = fileState.processingQueue.splice(0, 5); + if (tasks.length > 0) { + try { + await Promise.all(tasks.map((task) => task())); + } catch (error) { + console.error(`Error processing edits in ${filePath}:`, error); + } + + // Yield to the event loop to prevent blocking + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } + + fileState.isProcessing = false; + } + + private async _processEditInternal( + edit: RangeInFileWithNextEditInfo, + timestamp: number, + fileState: FileState, + ): Promise { + const filePath = edit.filepath; + + const editLine = edit.range.start.line; + const currentFileLines = fileState.currentContent.split("\n"); + + const clustersToFinalize = this.identifyClustersToFinalize( + fileState, + edit, + timestamp, + false, + ); + + for (const cluster of clustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + + let suitableCluster = this.findSuitableCluster( + fileState, + editLine, + timestamp, + ); + + // Check if adding this edit would exceed deltaL lines for the cluster + if (suitableCluster) { + const potentialMinLine = Math.min( + suitableCluster.currentRange.minLine, + Math.max(0, editLine - this.config.contextLines), + ); + const potentialMaxLine = Math.max( + suitableCluster.currentRange.maxLine, + Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + ); + const potentialLineSpan = potentialMaxLine - potentialMinLine + 1; + + if (potentialLineSpan > this.config.deltaL * 2) { + // Auto-finalize the current cluster before creating a new one + await this.finalizeCluster(filePath, suitableCluster, fileState); + suitableCluster = null; + } + } + + // initialize a cluster + if (!suitableCluster) { + suitableCluster = { + beforeState: fileState.currentContent, + startRange: { + minLine: Math.max(0, editLine - this.config.contextLines), + maxLine: Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + }, + currentRange: { + minLine: Math.max(0, editLine - this.config.contextLines), + maxLine: Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + }, + edits: [], + firstTimestamp: timestamp, + lastTimestamp: timestamp, + lastLine: editLine, + firstEditBeforeCursor: edit.beforeCursorPos, + lastEditAfterCursor: edit.afterCursorPos, + }; + fileState.activeClusters.push(suitableCluster); + } + + suitableCluster.edits.push(edit); + suitableCluster.lastTimestamp = timestamp; + suitableCluster.lastLine = editLine; + suitableCluster.lastEditAfterCursor = edit.afterCursorPos; + + const isWhitespaceOnly = this.isWhitespaceOnlyEdit( + edit, + fileState.currentContent, + ); + + if (!isWhitespaceOnly) { + suitableCluster.currentRange.minLine = Math.min( + suitableCluster.currentRange.minLine, + Math.max(0, editLine - this.config.contextLines), + ); + suitableCluster.currentRange.maxLine = Math.max( + suitableCluster.currentRange.maxLine, + Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + ); + } + + fileState.currentContent = edit.fileContents; + + const isStructuralEdit = + edit.editText.includes("\n") || + edit.range.start.line !== edit.range.end.line; + + if (isStructuralEdit) { + const additionalClustersToFinalize = fileState.activeClusters.filter( + (c) => + c !== suitableCluster && this.clustersOverlap(c, suitableCluster), + ); + + for (const cluster of additionalClustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + } + } + + private isWhitespaceOnlyEdit( + edit: RangeInFileWithNextEditInfo, + currentContent: string, + ): boolean { + const lines = currentContent.split("\n"); + const line = edit.range.start.line; + + if (line >= lines.length) return false; + + if (edit.range.start.line === edit.range.end.line) { + const beforeEdit = lines[line]; + const afterEdit = + beforeEdit.substring(0, edit.range.start.character) + + edit.editText + + beforeEdit.substring(edit.range.end.character); + + return beforeEdit.trim() === afterEdit.trim(); + } + + return false; + } + + private clustersOverlap( + cluster1: ClusterState, + cluster2: ClusterState, + ): boolean { + return ( + cluster1.currentRange.minLine <= + cluster2.currentRange.maxLine + this.config.deltaL && + cluster1.currentRange.maxLine >= + cluster2.currentRange.minLine - this.config.deltaL + ); + } + + async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise { + const timestamp = Date.now(); + + // Only process the last edit during rapid typing + if (this.getProcessingQueueSize() > 50) { + if (edits.length > 0) { + await this.processEdit(edits[edits.length - 1], timestamp); + } + return; + } + + for (const edit of edits) { + await this.processEdit(edit, timestamp); + } + } + + /** + * Finalizes all clusters for a specific file + */ + private async finalizeClustersForFile(filePath: string): Promise { + const fileState = this.fileStates.get(filePath); + if (!fileState) return; + + // Create a copy of the clusters to finalize to avoid modifying array during iteration + const clustersToFinalize = [...fileState.activeClusters]; + + for (const cluster of clustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + } + + async finalizeAllClusters(): Promise { + const filePromises: Promise[] = []; + + this.fileStates.forEach((fileState, filePath) => { + const filePromise = this.finalizeClustersForFile(filePath); + filePromises.push(filePromise); + }); + + await Promise.all(filePromises); + } + + private findSuitableCluster( + fileState: FileState, + editLine: number, + timestamp: number, + ): ClusterState | null { + const activeClusters = [...fileState.activeClusters]; + + for (const cluster of activeClusters) { + // If we're outside the line range but within the time window, + // we should finalize the current cluster + const isOutsideLineRange = + editLine < cluster.currentRange.minLine - this.config.deltaL || + editLine > cluster.currentRange.maxLine + this.config.deltaL; + + const isWithinTimeWindow = + (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; + + // If user quickly jumped far away, finalize this cluster before continuing + if (isOutsideLineRange && isWithinTimeWindow) { + void this.finalizeCluster( + cluster.edits[0].filepath, + cluster, + fileState, + ); + } + } + + // Now look for a suitable cluster for the new edit + for (const cluster of fileState.activeClusters) { + const isOnSameLine = editLine === cluster.lastLine; + const isWithinTimeWindow = + (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; + const isWithinLineRange = + editLine >= cluster.currentRange.minLine - this.config.deltaL && + editLine <= cluster.currentRange.maxLine + this.config.deltaL; + const isWithinEditLimit = cluster.edits.length < this.config.maxEdits; + const isWithinDurationLimit = + (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration; + + if ( + (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) && + isWithinEditLimit && + isWithinDurationLimit + ) { + return cluster; + } + } + return null; + } + + private identifyClustersToFinalize( + fileState: FileState, + edit: RangeInFileWithNextEditInfo, + timestamp: number, + isStructuralEdit: boolean, + ): ClusterState[] { + const clustersToFinalize: ClusterState[] = []; + const editLine = edit.range.start.line; + + fileState.activeClusters.forEach((cluster) => { + const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000; + + const isOnDifferentLineByNumber = cluster.lastLine !== editLine; + + const isOnDifferentLineByNewline = edit.editText.includes("\n"); + + // Use different time thresholds for different types of line change detection + const shouldFinalizeByLineNumber = + isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT; + + const shouldFinalizeByNewline = + isOnDifferentLineByNewline && + timeSinceLastEdit > this.config.deltaT * 1.5; + + // Finalize if we moved to a different line AND the time gap exceeds the respective threshold + const shouldFinalizeByTime = + shouldFinalizeByLineNumber || shouldFinalizeByNewline; + const shouldFinalizeByCount = + cluster.edits.length >= this.config.maxEdits; + const shouldFinalizeByDuration = + (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration; + + // For structural edits, use the combined line detection + const isOnDifferentLine = + isOnDifferentLineByNumber || isOnDifferentLineByNewline; + const shouldFinalizeByStructuralEdit = + isStructuralEdit && isOnDifferentLine; + + if ( + shouldFinalizeByTime || + shouldFinalizeByCount || + shouldFinalizeByDuration || + shouldFinalizeByStructuralEdit + ) { + clustersToFinalize.push(cluster); + } + }); + + return clustersToFinalize; + } + + private async finalizeCluster( + filePath: string, + cluster: ClusterState, + fileState: FileState, + ): Promise { + const beforeContent = cluster.beforeState; + const afterContent = fileState.currentContent; + + // Skip whitespace-only diffs + const isWhitespaceOnlyDiff = + beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, ""); + + if (isWhitespaceOnlyDiff) { + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + return; + } + + const diff = createDiff( + beforeContent, + afterContent, + filePath, + DiffFormatType.Unified, + ); // Used for checks, not for final output + + // Skip diffs with too many changed lines + const changedLineCount = this.countChangedLines(diff); + if (changedLineCount > this.config.deltaL * 2) { + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + return; + } + + fileState.priorComparisons.push(diff); + if (fileState.priorComparisons.length > this.config.contextSize) { + fileState.priorComparisons.shift(); + } + + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + + // Give format-agnostic diff to the callback + const fullFileVersionsDiff = createBeforeAfterDiff( + beforeContent, + afterContent, + filePath, + ); + + // Store this cluster's final cursor position for future reference + this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor; + + this.onComparisonFinalized( + fullFileVersionsDiff, + cluster.firstEditBeforeCursor, + this.previousEditFinalCursorPosition, + ); + } + + private countChangedLines(diff: string): number { + let count = 0; + let addedLines = new Set(); + let removedLines = new Set(); + + // Parse the diff lines + const lines = diff.split("\n"); + for (const line of lines) { + if ( + line.startsWith("+++ ") || + line.startsWith("--- ") || + line.startsWith("@@") + ) { + continue; // Skip header lines + } + + if (line.startsWith("+")) { + addedLines.add(count); + count++; + } else if (line.startsWith("-")) { + removedLines.add(count); + count++; + } + } + + return Math.max(addedLines.size, removedLines.size); + } + + getActiveClusterCount(): number { + let count = 0; + this.fileStates.forEach((fileState) => { + count += fileState.activeClusters.length; + }); + return count; + } + + getProcessingQueueSize(): number { + let count = 0; + this.fileStates.forEach((fileState) => { + count += fileState.processingQueue.length; + }); + return count; + } + + resetState(): void { + this.fileStates.clear(); + this.lastProcessedFilePath = null; + } +} diff --git a/core/nextEdit/context/autocompleteContextFetching.ts b/core/nextEdit/context/autocompleteContextFetching.ts new file mode 100644 index 000000000..8b57a4a17 --- /dev/null +++ b/core/nextEdit/context/autocompleteContextFetching.ts @@ -0,0 +1,140 @@ +import { Position } from "../.."; +import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService"; +import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets"; +import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types"; +import { renderPrompt } from "../../autocomplete/templating"; +import { GetLspDefinitionsFunction } from "../../autocomplete/types"; +import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { + AutocompleteInput, + RecentlyEditedRange, +} from "../../autocomplete/util/types"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { IDE, ILLM } from "../../index"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters"; + +/** + * Gets the formatted autocomplete context string that would be used for autocomplete at the given position. + * This function mimics the context generation pipeline from the autocomplete system without triggering + * an actual completion. + * + * @param filepath - The file path where context is being requested + * @param pos - The position in the file where context is being requested + * @param ide - The IDE interface for file system operations + * @param configHandler - The config handler to load user configuration + * @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed) + * @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model) + * @param recentlyEditedRanges - Recently edited ranges (defaults to empty array) + * @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete) + * @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config) + * @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state) + * @returns Promise that resolves to the formatted context string + */ +export const getAutocompleteContext = async ( + filepath: string, + pos: Position, + ide: IDE, + configHandler: ConfigHandler, + getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [], + recentlyEditedRanges: RecentlyEditedRange[], + recentlyVisitedRanges: AutocompleteCodeSnippet[], + maxPromptTokens: number, + manuallyPassFileContents: string, + autocompleteModel?: ILLM | string, + // eslint-disable-next-line max-params +): Promise => { + if (!recentlyEditedRanges) recentlyEditedRanges = []; + if (!recentlyVisitedRanges) recentlyVisitedRanges = []; + + const input: AutocompleteInput = { + isUntitledFile: false, + completionId: `context-fetch-${Date.now()}`, + filepath, + pos, + recentlyVisitedRanges, + recentlyEditedRanges, + manuallyPassFileContents, + }; + + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("No config available"); + } + + // Use provided autocomplete model or fall back to configured autocomplete model + let finalModel: ILLM; + let modelNameForTemplating: string; + + if (autocompleteModel) { + if (typeof autocompleteModel === "string") { + // Try to find the model in config first + const foundModel = config.modelsByRole.autocomplete.find( + (m) => m.title === autocompleteModel, + ); + if (foundModel) { + finalModel = foundModel; + modelNameForTemplating = foundModel.model; + } else { + // Model not found in config, but we can still use it for template selection + const configuredModel = config.selectedModelByRole.autocomplete; + if (!configuredModel) { + throw new Error( + "No autocomplete model configured and provided model not found in config", + ); + } + finalModel = configuredModel; + modelNameForTemplating = autocompleteModel; // Use the provided string for template selection + } + } else { + finalModel = autocompleteModel; + modelNameForTemplating = autocompleteModel.model; + } + } else { + const configuredModel = config.selectedModelByRole.autocomplete; + if (!configuredModel) { + throw new Error("No autocomplete model configured and no model provided"); + } + finalModel = configuredModel; + modelNameForTemplating = configuredModel.model; + } + + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config.tabAutocompleteOptions, + ...finalModel.autocompleteOptions, + ...(maxPromptTokens && { maxPromptTokens }), + }; + + if (finalModel.promptTemplates?.autocomplete) { + options.template = finalModel.promptTemplates.autocomplete as string; + } + + const helper = await HelperVars.create( + input, + options, + modelNameForTemplating, + ide, + ); + + const contextRetrievalService = new ContextRetrievalService(ide); + + await contextRetrievalService.initializeForFile(filepath); + + const [snippetPayload, workspaceDirs] = await Promise.all([ + getAllSnippetsWithoutRace({ + helper, + ide: ide, + getDefinitionsFromLsp: getDefinitionsFromLsp, + contextRetrievalService: contextRetrievalService, + }), + ide.getWorkspaceDirs(), + ]); + + const { prompt, prefix, suffix, completionOptions } = renderPrompt({ + snippetPayload, + workspaceDirs, + helper, + }); + + return prefix; +}; diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts new file mode 100644 index 000000000..6d892dee7 --- /dev/null +++ b/core/nextEdit/context/diffFormatting.ts @@ -0,0 +1,82 @@ +import { createPatch } from "diff"; + +export enum DiffFormatType { + Unified = "unified", + RawBeforeAfter = "beforeAfter", + TokenLineDiff = "linediff", +} + +export type BeforeAfterDiff = { + filePath: string; + beforeContent: string; + afterContent: string; +}; + +export const createDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, + diffType: DiffFormatType, +) => { + switch (diffType) { + case DiffFormatType.Unified: + return createUnifiedDiff(beforeContent, afterContent, filePath); + case DiffFormatType.TokenLineDiff: + return createTokenLineDiff(beforeContent, afterContent, filePath); + } + return ""; +}; + +const createUnifiedDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, +) => { + const normalizedBefore = beforeContent.endsWith("\n") + ? beforeContent + : beforeContent + "\n"; + const normalizedAfter = afterContent.endsWith("\n") + ? afterContent + : afterContent + "\n"; + + const patch = createPatch( + filePath, + normalizedBefore, + normalizedAfter, + "before", + "after", + { context: 3 }, + ); + + return patch; +}; + +export const createBeforeAfterDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, +) => { + const normalizedBefore = beforeContent.endsWith("\n") + ? beforeContent + : beforeContent + "\n"; + const normalizedAfter = afterContent.endsWith("\n") + ? afterContent + : afterContent + "\n"; + + const result: BeforeAfterDiff = { + filePath: filePath, + beforeContent: normalizedBefore, + afterContent: normalizedAfter, + }; + + return result; +}; + +const createTokenLineDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, +) => { + // TODO: Implement token line diff + return ""; +}; diff --git a/core/nextEdit/context/prevEditLruCache.ts b/core/nextEdit/context/prevEditLruCache.ts new file mode 100644 index 000000000..31feb782a --- /dev/null +++ b/core/nextEdit/context/prevEditLruCache.ts @@ -0,0 +1,30 @@ +import QuickLRU from "quick-lru"; + +export interface prevEdit { + unidiff: string; + fileUri: string; + workspaceUri: string; + timestamp: number; +} +const maxPrevEdits = 5; + +export const prevEditLruCache = new QuickLRU({ + maxSize: maxPrevEdits, +}); + +export const setPrevEdit = (edit: prevEdit): void => { + const uniqueSuffix = Math.random().toString(36).substring(2, 8); + const key = `${edit.fileUri}:${edit.timestamp}:${uniqueSuffix}`; + prevEditLruCache.set(key, edit); +}; + +export const getPrevEditsDescending = (): prevEdit[] => { + const edits: prevEdit[] = []; + for (const [_, edit] of prevEditLruCache.entriesDescending()) { + if (edits.length >= maxPrevEdits) { + break; + } + edits.push(edit); + } + return edits; +}; diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts new file mode 100644 index 000000000..206b17b80 --- /dev/null +++ b/core/nextEdit/context/processNextEditData.ts @@ -0,0 +1,142 @@ +import { IDE, Position } from "../.."; +import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types"; +import { GetLspDefinitionsFunction } from "../../autocomplete/types"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { DataLogger } from "../../data/log"; +import { RecentlyEditedRange } from "../types"; +import { getAutocompleteContext } from "./autocompleteContextFetching"; +import { createDiff, DiffFormatType } from "./diffFormatting"; +import { + getPrevEditsDescending, + prevEdit, + prevEditLruCache, + setPrevEdit, +} from "./prevEditLruCache"; + +const randomNumberBetween = (min: number, max: number) => { + min = Math.ceil(min); // Ensure min is an integer + max = Math.floor(max); // Ensure max is an integer + return Math.floor(Math.random() * (max - min + 1)) + min; +}; + +interface ProcessNextEditDataParams { + filePath: string; + beforeContent: string; + afterContent: string; + cursorPosBeforeEdit: Position; + cursorPosAfterPrevEdit: Position; + ide: IDE; + configHandler: ConfigHandler; + getDefinitionsFromLsp: GetLspDefinitionsFunction; + recentlyEditedRanges: RecentlyEditedRange[]; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + workspaceDir: string; + modelNameOrInstance?: string | undefined; +} + +interface filenameAndDiff { + filename: string; + diff: string; +} + +export const processNextEditData = async ({ + filePath, + beforeContent, + afterContent, + cursorPosBeforeEdit, + cursorPosAfterPrevEdit, + ide, + configHandler, + getDefinitionsFromLsp, + recentlyEditedRanges, + recentlyVisitedRanges, + workspaceDir, + modelNameOrInstance, +}: ProcessNextEditDataParams) => { + // To switch to the user's autocomplete model, uncomment the following lines + // const { config } = await configHandler.loadConfig(); + // const autocompleteModel = + // (modelNameOrInstance || config?.selectedModelByRole.autocomplete) ?? + // undefined; + + const modelName = "Codestral"; + const maxPromptTokens = randomNumberBetween(500, 12000); + + const autocompleteContext = await getAutocompleteContext( + filePath, + cursorPosBeforeEdit, + ide, + configHandler, + getDefinitionsFromLsp, + recentlyEditedRanges, + recentlyVisitedRanges, + maxPromptTokens, + beforeContent, + modelName, + ); + + // console.log( + // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified), + // ); + + let filenamesAndDiffs: filenameAndDiff[] = []; + + const timestamp = Date.now(); + let prevEdits: prevEdit[] = getPrevEditsDescending(); // edits from most to least recent + if (prevEdits.length > 0) { + // if last edit was 10+ minutes ago or the workspace changed, forget previous edits + if ( + timestamp - prevEdits[0].timestamp >= 1000 * 60 * 10 || + workspaceDir !== prevEdits[0].workspaceUri + ) { + prevEditLruCache.clear(); + prevEdits = []; + } + + // extract filenames and diffs for logging + filenamesAndDiffs = prevEdits.map( + (edit) => + ({ + // filename relative to workspace dir + filename: edit.fileUri + .replace(edit.workspaceUri, "") + .replace(/^[/\\]/, ""), + + // diff without the first 4 lines (the file header) + diff: edit.unidiff.split("\n").slice(4).join("\n"), + }) as filenameAndDiff, + ); + } + + if (filenamesAndDiffs.length > 0) { + // if there are previous edits, log + void DataLogger.getInstance().logDevData({ + name: "nextEditWithHistory", + data: { + previousEdits: filenamesAndDiffs, + fileURI: filePath, + workspaceDirURI: workspaceDir, + beforeContent, + afterContent, + beforeCursorPos: cursorPosBeforeEdit, + afterCursorPos: cursorPosAfterPrevEdit, + context: autocompleteContext, + }, + }); + } + + // add current edit to history + const thisEdit: prevEdit = { + unidiff: createDiff( + beforeContent, + afterContent, + filePath, + DiffFormatType.Unified, + ), + fileUri: filePath, + workspaceUri: workspaceDir, + timestamp: timestamp, + }; + + setPrevEdit(thisEdit); +}; diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts new file mode 100644 index 000000000..18ed9d544 --- /dev/null +++ b/core/nextEdit/context/processSmallEdit.ts @@ -0,0 +1,48 @@ +import { IDE, Position } from "../.."; +import { GetLspDefinitionsFunction } from "../../autocomplete/types"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { NextEditProvider } from "../NextEditProvider"; +import { EditAggregator } from "./aggregateEdits"; +import { BeforeAfterDiff, createDiff, DiffFormatType } from "./diffFormatting"; +import { processNextEditData } from "./processNextEditData"; + +export const processSmallEdit = async ( + beforeAfterdiff: BeforeAfterDiff, + cursorPosBeforeEdit: Position, + cursorPosAfterPrevEdit: Position, + configHandler: ConfigHandler, + getDefsFromLspFunction: GetLspDefinitionsFunction, + ide: IDE, +) => { + NextEditProvider.getInstance().addDiffToContext( + createDiff( + beforeAfterdiff.beforeContent, + beforeAfterdiff.afterContent, + beforeAfterdiff.filePath, + DiffFormatType.Unified, + ), + ); + + // Get the current context data from the most recent message + const currentData = (EditAggregator.getInstance() as any) + .latestContextData || { + configHandler: configHandler, + getDefsFromLspFunction: getDefsFromLspFunction, + recentlyEditedRanges: [], + recentlyVisitedRanges: [], + }; + + void processNextEditData({ + filePath: beforeAfterdiff.filePath, + beforeContent: beforeAfterdiff.beforeContent, + afterContent: beforeAfterdiff.afterContent, + cursorPosBeforeEdit: cursorPosBeforeEdit, + cursorPosAfterPrevEdit: cursorPosAfterPrevEdit, + ide: ide, + configHandler: currentData.configHandler, + getDefinitionsFromLsp: currentData.getDefsFromLspFunction, + recentlyEditedRanges: currentData.recentlyEditedRanges, + recentlyVisitedRanges: currentData.recentlyVisitedRanges, + workspaceDir: currentData.workspaceDir, + }); +}; diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts new file mode 100644 index 000000000..bca4a6d08 --- /dev/null +++ b/core/nextEdit/diff/diff.ts @@ -0,0 +1,194 @@ +import { DiffLine } from "../.."; + +/** + * Given a diff of two editable regions, get the offset position at the last new line inside the editable region. + * @param diffLines Result of myersDiff. + * @param lineContentAtCursorPos Content of the line at cursor position. + * @param lineOffsetAtCursorPos Offset of the line at cursor position compared to the start of the editable region. + * @returns Offset position at last new line inside the editable region. + */ +export function getOffsetPositionAtLastNewLine( + diffLines: DiffLine[], + lineContentAtCursorPos: string, + lineOffsetAtCursorPos: number, +): { + line: number; + character: number; +} { + let lastNewLineContent = ""; + let lineOffset = -1; + let currentResultLine = 0; + let hasChanges = false; + + // Build the string while tracking line numbers in the result + diffLines.reduce((acc, curr, i) => { + // Add the current line to our result + acc += curr.line; + + // Add newline if not the last line + if (i < diffLines.length - 1) { + acc += "\n"; + } + + // If this is a "new" or "same" line, it will be part of the result + if (curr.type === "new" || curr.type === "same") { + if (curr.type === "new") { + // If it's a new line, update our tracking + lastNewLineContent = curr.line; + lineOffset = currentResultLine; + hasChanges = true; + } + // Increment our position in the result + currentResultLine++; + } + + return acc; + }, ""); + + // If nothing has changed, return the original position + if (!hasChanges) { + lineOffset = lineOffsetAtCursorPos; + lastNewLineContent = lineContentAtCursorPos; + } + // Calculate the character position for the end of the last relevant line + const endOfCharPos = lastNewLineContent.length; + return { + line: lineOffset, + character: endOfCharPos, + }; +} + +export function getRenderableDiffWithGutterAnnotations( + diffLines: DiffLine[], + lineContentAtCursorPos: string, + lineOffsetAtCursorPos: number, +): { + offset: { + line: number; + character: number; + }; +} { + let lastNewLineContent = ""; + let lineOffset = -1; + let currentResultLine = 0; + let hasChanges = false; + + // Build the string while tracking line numbers in the result + diffLines.reduce((acc, curr, i) => { + // Add the current line to our result + acc += curr.line; + + // Add newline if not the last line + if (i < diffLines.length - 1) { + acc += "\n"; + } + + // If this is a "new" or "same" line, it will be part of the result + if (curr.type === "new" || curr.type === "same") { + if (curr.type === "new") { + // If it's a new line, update our tracking + lastNewLineContent = curr.line; + lineOffset = currentResultLine; + hasChanges = true; + } + // Increment our position in the result + currentResultLine++; + } + + return acc; + }, ""); + + // If nothing has changed, return the original position + if (!hasChanges) { + lineOffset = lineOffsetAtCursorPos; + lastNewLineContent = lineContentAtCursorPos; + } + // Calculate the character position for the end of the last relevant line + const endOfCharPos = lastNewLineContent.length; + return { + offset: { + line: lineOffset, + character: endOfCharPos, + }, + }; +} + +/** + * Check if the diff is indeed a FIM. + * @param oldEditRange Original string content. + * @param newEditRange New string content. + * @param cursorPosition The position of the cursor in the old string. + * @returns boolean indicating if the change is purely additive (FIM) + * @returns string of FIM text content. + */ +export function checkFim( + oldEditRange: string, + newEditRange: string, + cursorPosition: { line: number; character: number }, +): + | { + isFim: true; + fimText: string; + } + | { + isFim: false; + fimText: null; + } { + // Find the common prefix. + let prefixLength = 0; + while ( + prefixLength < oldEditRange.length && + prefixLength < newEditRange.length && + oldEditRange[prefixLength] === newEditRange[prefixLength] + ) { + prefixLength++; + } + + // Find the common suffix + let oldSuffixPos = oldEditRange.length - 1; + let newSuffixPos = newEditRange.length - 1; + + while ( + oldSuffixPos >= prefixLength && + newSuffixPos >= prefixLength && + oldEditRange[oldSuffixPos] === newEditRange[newSuffixPos] + ) { + oldSuffixPos--; + newSuffixPos--; + } + + // The old text is purely preserved if: + // 1. The prefix ends before or at the cursor. + // 2. The suffix starts after or at the cursor. + // 3. There's no gap between prefix and suffix in the old text. + + const suffixStartInOld = oldSuffixPos + 1; + const suffixStartInNew = newSuffixPos + 1; + + // Convert cursor position to an offset in the string. + // For simplicity, we need to calculate the cursor's position in the string. + // This requires knowledge of line endings in the oldEditRange. + const lines = oldEditRange.substring(0, prefixLength).split("\n"); + const cursorOffset = + lines.length > 1 + ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + + cursorPosition.character + : cursorPosition.character; + + // Check if the cursor is positioned between the prefix and suffix. + const cursorBetweenPrefixAndSuffix = + prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld; + + // Check if the old text is completely preserved (no deletion). + const noTextDeleted = suffixStartInOld - prefixLength <= 0; + + const isFim = cursorBetweenPrefixAndSuffix && noTextDeleted; + + if (isFim) { + // Extract the content between prefix and suffix in the new string. + const fimText = newEditRange.substring(prefixLength, suffixStartInNew); + return { isFim, fimText }; + } else { + return { isFim, fimText: null }; + } +} diff --git a/core/nextEdit/diff/diff.vitest.ts b/core/nextEdit/diff/diff.vitest.ts new file mode 100644 index 000000000..fa161d49c --- /dev/null +++ b/core/nextEdit/diff/diff.vitest.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; +import { checkFim } from "./diff"; + +describe("checkFim", () => { + const testCases = [ + { + name: "simple insertion at cursor", + oldEditRange: ["function test() {", " ", "}"].join("\n"), + newEditRange: ["function test() {", " console.log('hello');", "}"].join( + "\n", + ), + cursorPosition: { line: 1, character: 2 }, + expected: { + isFim: true, + fimText: "console.log('hello');", + }, + }, + { + name: "not a FIM because insertion starts before { and new suffix is different from {}", + oldEditRange: ["function test() {}"].join("\n"), + newEditRange: ["function test() {console.log('test');}"].join("\n"), + cursorPosition: { line: 0, character: 16 }, + expected: { + isFim: false, + fimText: null, + }, + }, + { + name: "insertion with cursor at beginning", + oldEditRange: ["function test() {}"].join("\n"), + newEditRange: ["function test() {console.log('test');}"].join("\n"), + cursorPosition: { line: 0, character: 17 }, + expected: { + isFim: true, + fimText: "console.log('test');", + }, + }, + { + name: "not a FIM because text was deleted", + oldEditRange: ["function test() {", " return 42;", "}"].join("\n"), + newEditRange: ["function test() {", " console.log('hello');", "}"].join( + "\n", + ), + cursorPosition: { line: 1, character: 2 }, + expected: { + isFim: false, + fimText: null, + }, + }, + { + name: "not a FIM because text was changed before cursor", + oldEditRange: ["let x = 1;"].join("\n"), + newEditRange: ["const x = 1; // initialized x"].join("\n"), + cursorPosition: { line: 0, character: 8 }, + expected: { + isFim: false, + fimText: null, + }, + }, + { + name: "multi-line insertion at cursor", + oldEditRange: [ + "function process() {", + " ", + " return result;", + "}", + ].join("\n"), + newEditRange: [ + "function process() {", + " const data = fetchData();", + " const result = processData(data);", + " return result;", + "}", + ].join("\n"), + cursorPosition: { line: 1, character: 2 }, + expected: { + isFim: true, + fimText: + "const data = fetchData();\n const result = processData(data);", + }, + }, + ]; + + testCases.forEach( + ({ name, oldEditRange, newEditRange, cursorPosition, expected }) => { + it(name, () => { + const result = checkFim(oldEditRange, newEditRange, cursorPosition); + expect(result).toEqual(expected); + }); + }, + ); +}); diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts new file mode 100644 index 000000000..6d9319fd3 --- /dev/null +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -0,0 +1,343 @@ +import Handlebars from "handlebars"; +import { Position } from "../.."; +import { SnippetPayload } from "../../autocomplete/snippets"; +import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { + EDITABLE_REGION_END_TOKEN, + EDITABLE_REGION_START_TOKEN, + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + USER_CURSOR_IS_HERE_TOKEN, +} from "../constants"; + +export type Prompt = SystemPrompt | UserPrompt; + +interface SystemPrompt { + role: "system"; + content: string; +} + +interface UserPrompt { + role: "user"; + content: string; +} + +export interface NextEditTemplate { + template: string; +} + +export interface TemplateVars { + userEdits: string; + languageShorthand: string; + userExcerpts: string; +} + +type TemplateRenderer = (vars: TemplateVars) => string; + +type NextEditModelName = "mercury-coder-nextedit" | "this field is not used"; + +const NEXT_EDIT_MODEL_TEMPLATES: Record = { + "mercury-coder-nextedit": { + template: + "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", + }, + "this field is not used": { + template: "NEXT_EDIT", + }, +}; + +function templateRendererOfModel( + modelName: NextEditModelName, +): TemplateRenderer { + let template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; + if (!template) { + throw new Error(`Model ${modelName} is not supported for next edit.`); + } + + const compiledTemplate = Handlebars.compile(template.template); + + return (vars: TemplateVars): string => { + return compiledTemplate(vars); + }; +} + +export function renderPrompt( + helper: HelperVars, + userEdits: string, +): UserPrompt { + let modelName = helper.modelName as NextEditModelName; + + if (modelName === "this field is not used") { + return { + role: "user", + content: "NEXT_EDIT", + }; + } + + // Validate that the modelName is actually a supported model. + if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) { + // Check if modelName includes any known model name as substring. + const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) => + modelName.includes(key), + ); + + if (matchingModel) { + modelName = matchingModel as NextEditModelName; + } else { + throw new Error( + `${helper.modelName} is not yet supported for next edit.`, + ); + } + } + + const renderer = templateRendererOfModel(modelName); + const editedCodeWithTokens = insertTokens( + helper.fileContents.split("\n"), + helper.pos, + ); + + const tv: TemplateVars = { + userEdits, + languageShorthand: helper.lang.name, + userExcerpts: editedCodeWithTokens, + }; + + return { + role: "user", + content: renderer(tv), + }; +} + +export function renderDefaultSystemPrompt(): SystemPrompt { + return { + role: "system", + content: [ + /* Identity forming */ + "You are an expert polyglot developer who is overseeing a junior developer write code in some language.", + "You are psychic as well, so you are an expert at reading minds just from what the junior has done.", + "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.", + /* Action crash course */ + "An action is a change in code state that preserves the well-formedness of the code.", + "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.", + /* Input description */ + // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.', + // "language is the language the code is written in.", + // "originalCode is the code state before the junior has taken some edit action.", + // "editedCode is the code state after the junior has taken some edit action.", + // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.", + // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.", + 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.', + "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.", + "recentlyEditedRange is the code that the junior has recently edited.", + "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.", + "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.", + "The junior might want to add new code, delete existing code, or replace different parts of code.", + "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.", + /* Output description */ + 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.', + /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/ + /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */ + "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.", + // "actionType is the type of action the junior has taken.", + "newCode is what the full code looks like after applying your nextEditContent.", + // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.", + "Given the above definition of an action, you should prioritize fixing the following:", + "- Patterns and repetition in code.", + "- Static errors that the compiler of the language may return.", + "- The junior's code style.", + "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.", + "If the junior has added some code, there's a good chance that the next edit will also be additions.", + "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.", + "Careful of language intricacies.", + // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.", + "Do not reply in markdown.", + "Do not hallucinate.", + ].join(" "), + }; +} + +export function renderDefaultUserPrompt( + // originalCode: string, + // editedCode: string, + snippets: SnippetPayload, + helper: HelperVars, +): UserPrompt { + const userEdit = { + language: helper.lang, + rootPathSnippets: snippets.rootPathSnippets, + importDefinitionSnippets: snippets.importDefinitionSnippets, + ideSnippets: snippets.ideSnippets, + recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets, + diffSnippets: snippets.diffSnippets, + clipboardSnippets: snippets.clipboardSnippets, + recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets, + }; + + return { + role: "user", + content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`, + }; +} + +// export async function renderFineTunedUserPrompt( +// snippets: SnippetPayload, +// ide: IDE, +// helper: HelperVars, +// ): Promise { +// const ideInfo = await ide.getIdeInfo(); +// switch (ideInfo.ideType) { +// case "vscode": +// const editedCodeWithPins = insertTokens( +// helper.fileContents.split("\n"), +// helper.pos, +// ); + +// return { +// role: "user", +// content: renderStringTemplate( +// mercuryCoderTemplate, +// snippets.diffSnippets.join("\n"), +// helper.lang.name, +// editedCodeWithPins, +// ), +// }; + +// case "jetbrains": +// return { +// role: "user", +// content: "", +// }; +// } +// } + +// export async function renderDefaultBasicUserPrompt( +// snippets: SnippetPayload, +// ide: IDE, +// helper: HelperVars, +// ): Promise { +// const ideInfo = await ide.getIdeInfo(); +// switch (ideInfo.ideType) { +// case "vscode": +// const editedCodeWithPins = insertTokens( +// helper.fileContents.split("\n"), +// helper.pos, +// ); + +// return { +// role: "user", +// content: renderStringTemplate( +// mercuryCoderTemplate, +// JSON.stringify(snippets), +// helper.lang.name, +// editedCodeWithPins, +// ), +// }; + +// case "jetbrains": +// return { +// role: "user", +// content: "", +// }; +// } +// } + +// export async function renderFineTunedBasicUserPrompt( +// snippets: SnippetPayload, +// ide: IDE, +// helper: HelperVars, +// diffContext: string, +// ): Promise { +// const ideInfo = await ide.getIdeInfo(); +// switch (ideInfo.ideType) { +// case "vscode": +// const lines = helper.fileContents.split("\n"); +// const editedCodeWithPins = insertTokens(lines, helper.pos); + +// return { +// role: "user", +// content: renderStringTemplate( +// mercuryCoderTemplate, +// diffContext, +// helper.lang.name, +// editedCodeWithPins, +// ), +// }; + +// case "jetbrains": +// return { +// role: "user", +// content: "", +// }; +// } +// } + +function insertTokens(lines: string[], cursorPos: Position) { + const a = insertCursorToken(lines, cursorPos); + const b = insertEditableRegionTokensWithStaticRange(a, cursorPos); + return b.join("\n"); +} + +function insertCursorToken(lines: string[], cursorPos: Position) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure character position is within bounds or at the end of the line. + const lineLength = lines[cursorPos.line].length; + const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); + + lines[cursorPos.line] = + lines[cursorPos.line].slice(0, charPos) + + USER_CURSOR_IS_HERE_TOKEN + + lines[cursorPos.line].slice(charPos); + + return lines; +} + +function insertEditableRegionTokensWithStaticRange( + lines: string[], + cursorPos: Position, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure editable regions are within bounds. + const editableRegionStart = Math.max( + cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEnd = Math.min( + cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + lines.length - 1, // Line numbers should be zero-indexed. + ); + + const instrumentedLines = [ + ...lines.slice(0, editableRegionStart), + EDITABLE_REGION_START_TOKEN, + ...lines.slice(editableRegionStart, editableRegionEnd + 1), + EDITABLE_REGION_END_TOKEN, + ...lines.slice(editableRegionEnd + 1), + ]; + + return instrumentedLines; +} + +function insertEditableRegionTokensWithAst( + lines: string[], + cursorPos: Position, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure character position is within bounds or at the end of the line. + const lineLength = lines[cursorPos.line].length; + const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); + + (lines[cursorPos.line] = + lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN), + lines[cursorPos.line].slice(charPos); + + return lines; +} diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts new file mode 100644 index 000000000..5fdd293a9 --- /dev/null +++ b/core/nextEdit/types.ts @@ -0,0 +1,45 @@ +import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../"; +import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; + +export type RecentlyEditedRange = RangeInFile & { + timestamp: number; + lines: string[]; + symbols: Set; +}; + +export interface AutocompleteInput { + isUntitledFile: boolean; + completionId: string; + filepath: string; + pos: Position; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + // Used for notebook files + manuallyPassFileContents?: string; + // Used for VS Code git commit input box + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + injectDetails?: string; +} + +export interface NextEditOutcome extends TabAutocompleteOptions { + accepted?: boolean; + time: number; + prefix: string; + suffix: string; + prompt: string; + completion: string; + modelProvider: string; + modelName: string; + completionOptions: any; + cacheHit: boolean; + numLines: number; + filepath: string; + gitRepo?: string; + completionId: string; + uniqueId: string; + timestamp: number; +} diff --git a/core/package-lock.json b/core/package-lock.json index 6fed1b052..a5b9cea03 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -105,6 +105,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" @@ -166,12 +167,12 @@ }, "../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.0.42", + "version": "1.0.44", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.11", + "@continuedev/fetch": "^1.0.15", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", @@ -4751,6 +4752,80 @@ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", "peer": true }, + "node_modules/@shikijs/core": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.6.0.tgz", + "integrity": "sha512-9By7Xb3olEX0o6UeJyPLI1PE1scC4d3wcVepvtv2xbuN9/IThYN4Wcwh24rcFeASzPam11MCq8yQpwwzCgSBRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.5" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.6.0.tgz", + "integrity": "sha512-7YnLhZG/TU05IHMG14QaLvTW/9WiK8SEYafceccHUSXs2Qr5vJibUwsDfXDLmRi0zHdzsxrGKpSX6hnqe0k8nA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^4.3.3" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.6.0.tgz", + "integrity": "sha512-nmOhIZ9yT3Grd+2plmW/d8+vZ2pcQmo/UnVwXMUXAKTXdi+LK0S08Ancrz5tQQPkxvjBalpMW2aKvwXfelauvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, + "node_modules/@shikijs/langs": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.6.0.tgz", + "integrity": "sha512-IdZkQJaLBu1LCYCwkr30hNuSDfllOT8RWYVZK1tD2J03DkiagYKRxj/pDSl8Didml3xxuyzUjgtioInwEQM/TA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0" + } + }, + "node_modules/@shikijs/themes": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.6.0.tgz", + "integrity": "sha512-Fq2j4nWr1DF4drvmhqKq8x5vVQ27VncF8XZMBuHuQMZvUSS3NBgpqfwz/FoGe36+W6PvniZ1yDlg2d4kmYDU6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0" + } + }, + "node_modules/@shikijs/types": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.6.0.tgz", + "integrity": "sha512-cLWFiToxYu0aAzJqhXTQsFiJRTFDAGl93IrMSBNaGSzs7ixkLfdG6pH11HipuWFGW5vyx4X47W8HDQ7eSrmBUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", + "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "dev": true, + "license": "MIT" + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -5481,6 +5556,16 @@ "@types/node": "*" } }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -5552,6 +5637,16 @@ "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==" }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/mozilla-readability": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@types/mozilla-readability/-/mozilla-readability-0.2.1.tgz", @@ -5688,6 +5783,13 @@ "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==" }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/uuid": { "version": "9.0.8", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", @@ -7205,6 +7307,17 @@ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chai": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz", @@ -7261,6 +7374,28 @@ "node": ">=10" } }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/check-error": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", @@ -7486,6 +7621,17 @@ "node": ">= 0.8" } }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/command-line-args": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", @@ -8025,6 +8171,16 @@ "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", @@ -8042,6 +8198,20 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/devtools-protocol": { "version": "0.0.1312386", "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz", @@ -10588,6 +10758,44 @@ "node": ">= 0.4" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", + "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", @@ -10613,6 +10821,17 @@ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/htmlparser2": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz", @@ -13009,6 +13228,28 @@ "node": ">= 0.4" } }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz", + "integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/media-typer": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", @@ -13042,6 +13283,100 @@ "node": ">= 8" } }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -13884,6 +14219,25 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/oniguruma-parser": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz", + "integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/oniguruma-to-es": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.3.tgz", + "integrity": "sha512-rPiZhzC3wXwE59YQMRDodUwwT9FZ9nNBwQQfsd1wfdtlKEyCdRV0avrTcSZ5xlIvGRVPd/cx6ZN45ECmS39xvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "oniguruma-parser": "^0.12.1", + "regex": "^6.0.1", + "regex-recursion": "^6.0.2" + } + }, "node_modules/onnx-proto": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz", @@ -14881,6 +15235,17 @@ "node": ">= 6" } }, + "node_modules/property-information": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", + "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/protobufjs": { "version": "6.11.4", "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.4.tgz", @@ -15285,6 +15650,33 @@ "@babel/runtime": "^7.8.4" } }, + "node_modules/regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz", + "integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, "node_modules/regexp.prototype.flags": { "version": "1.5.3", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.3.tgz", @@ -15856,6 +16248,23 @@ "node": ">=8" } }, + "node_modules/shiki": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.6.0.tgz", + "integrity": "sha512-tKn/Y0MGBTffQoklaATXmTqDU02zx8NYBGQ+F6gy87/YjKbizcLd+Cybh/0ZtOBX9r1NEnAy/GTRDKtOsc1L9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "3.6.0", + "@shikijs/engine-javascript": "3.6.0", + "@shikijs/engine-oniguruma": "3.6.0", + "@shikijs/langs": "3.6.0", + "@shikijs/themes": "3.6.0", + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -16136,6 +16545,17 @@ "source-map": "^0.6.0" } }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/split": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", @@ -16457,6 +16877,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -16947,6 +17382,17 @@ "tree-sitter-wasms": "^0.1.11" } }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/triple-beam": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz", @@ -17375,6 +17821,79 @@ "imurmurhash": "^0.1.4" } }, + "node_modules/unist-util-is": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz", + "integrity": "sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", + "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.1.tgz", + "integrity": "sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/universal-user-agent": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", @@ -17534,6 +18053,36 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.2.tgz", + "integrity": "sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/vite": { "version": "6.3.5", "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", @@ -18345,6 +18894,17 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } } diff --git a/core/package.json b/core/package.json index df74064a8..fd1be11e0 100644 --- a/core/package.json +++ b/core/package.json @@ -41,6 +41,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/createNewPromptFile.ts similarity index 94% rename from core/promptFiles/v2/createNewPromptFile.ts rename to core/promptFiles/createNewPromptFile.ts index 02ff786d1..d77967631 100644 --- a/core/promptFiles/v2/createNewPromptFile.ts +++ b/core/promptFiles/createNewPromptFile.ts @@ -1,6 +1,6 @@ -import { IDE } from "../.."; -import { GlobalContext } from "../../util/GlobalContext"; -import { joinPathsToUri } from "../../util/uri"; +import { IDE } from ".."; +import { GlobalContext } from "../util/GlobalContext"; +import { joinPathsToUri } from "../util/uri"; const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file # It is used to define and reuse prompts within Continue diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts new file mode 100644 index 000000000..8ca4f1966 --- /dev/null +++ b/core/promptFiles/getPromptFiles.ts @@ -0,0 +1,152 @@ +import { DEFAULT_PROMPTS_FOLDER_V1 } from "."; +import { IDE } from ".."; +import { walkDir } from "../indexing/walkDir"; +import { readAllGlobalPromptFiles } from "../util/paths"; +import { joinPathsToUri } from "../util/uri"; + +// The hardcoded init prompt content +const INIT_PROMPT_CONTENT = `name: Init +description: Initialize Codebase +--- +You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project. + +## Step 1: Check Required Tools +First, verify that you have access to the necessary tools: +- builtin_file_glob_search: To discover project files +- builtin_read_file: To analyze file contents +- builtin_ls: To explore directory structure +- builtin_create_new_file: To generate the CONTINUE.md file + +If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. + +## Step 2: Project Analysis +Analyze the project structure and key files to understand: +- The programming languages and frameworks used +- The overall architecture and organization +- Key components and their responsibilities +- Important configuration files +- Build/deployment system + +## Step 3: Generate CONTINUE.md +Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections: + +1. **Project Overview** + - Brief description of the project's purpose + - Key technologies used + - High-level architecture + +2. **Getting Started** + - Prerequisites (required software, dependencies) + - Installation instructions + - Basic usage examples + - Running tests + +3. **Project Structure** + - Overview of main directories and their purpose + - Key files and their roles + - Important configuration files + +4. **Development Workflow** + - Coding standards or conventions + - Testing approach + - Build and deployment process + - Contribution guidelines + +5. **Key Concepts** + - Domain-specific terminology + - Core abstractions + - Design patterns used + +6. **Common Tasks** + - Step-by-step guides for frequent development tasks + - Examples of common operations + +7. **Troubleshooting** + - Common issues and their solutions + - Debugging tips + +8. **References** + - Links to relevant documentation + - Important resources + +Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. + +## Step 4: Finalize +After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to: +1. Review and edit the file as needed +2. Commit it to their repository to share with their team +3. Explain that Continue will automatically load this file into context when working with the project + +Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`; + +export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; + +export async function getPromptFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const uris = await walkDir(dir, ide, { + source: "get dir prompt files", + }); + const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const results = promptFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export async function getAllPromptFiles( + ide: IDE, + overridePromptFolder?: string, + checkV1DefaultFolder: boolean = false, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let promptFiles: { path: string; content: string }[] = []; + + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; + if (checkV1DefaultFolder) { + dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); + } + if (overridePromptFolder) { + dirsToCheck = [overridePromptFolder]; + } + + const fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + + promptFiles = ( + await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) + ).flat(); + + // Also read from ~/.continue/.prompts + promptFiles.push(...readAllGlobalPromptFiles()); + + // Add hardcoded init prompt + promptFiles.push({ + path: "builtin:/init.prompt", + content: INIT_PROMPT_CONTENT, + }); + + return await Promise.all( + promptFiles.map(async (file) => { + if (file.path.startsWith("builtin:")) { + return file; + } + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/promptFiles/index.ts b/core/promptFiles/index.ts new file mode 100644 index 000000000..ee5fb6b84 --- /dev/null +++ b/core/promptFiles/index.ts @@ -0,0 +1,19 @@ +import { ContextProviderName } from ".."; + +export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; +export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; + +export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [ + "file", + "clipboard", + "repo-map", + "currentFile", + "os", + "problems", + "codebase", + "tree", + "open", + "debugger", + "terminal", + "diff", +]; diff --git a/core/promptFiles/v2/parsePromptFileV1V2.ts b/core/promptFiles/parsePromptFile.ts similarity index 84% rename from core/promptFiles/v2/parsePromptFileV1V2.ts rename to core/promptFiles/parsePromptFile.ts index a883c5e7b..4b6cf6917 100644 --- a/core/promptFiles/v2/parsePromptFileV1V2.ts +++ b/core/promptFiles/parsePromptFile.ts @@ -1,8 +1,8 @@ import * as YAML from "yaml"; -import { getLastNPathParts } from "../../util/uri"; +import { getLastNPathParts } from "../util/uri"; -export function parsePromptFileV1V2(path: string, content: string) { +export function parsePromptFile(path: string, content: string) { let [preambleRaw, prompt] = content.split("\n---\n"); if (prompt === undefined) { prompt = preambleRaw; diff --git a/core/promptFiles/v1/getContextProviderHelpers.ts b/core/promptFiles/v1/getContextProviderHelpers.ts deleted file mode 100644 index 30b51bf8b..000000000 --- a/core/promptFiles/v1/getContextProviderHelpers.ts +++ /dev/null @@ -1,38 +0,0 @@ -import Handlebars from "handlebars"; -import { ContextItem, ContinueSDK, IContextProvider } from "../.."; - -function createContextItem(item: ContextItem, provider: IContextProvider) { - return { - ...item, - id: { - itemId: item.description, - providerTitle: provider.description.title, - }, - }; -} - -export function getContextProviderHelpers( - context: ContinueSDK, -): Array<[string, Handlebars.HelperDelegate]> | undefined { - return context.config.contextProviders?.map((provider: IContextProvider) => [ - provider.description.title, - async (helperContext: any) => { - const items = await provider.getContextItems(helperContext, { - config: context.config, - embeddingsProvider: context.config.selectedModelByRole.embed, - fetch: context.fetch, - fullInput: context.input, - ide: context.ide, - llm: context.llm, - reranker: context.config.selectedModelByRole.rerank, - selectedCode: context.selectedCode, - }); - - items.forEach((item) => - context.addContextItem(createContextItem(item, provider)), - ); - - return items.map((item) => item.content).join("\n\n"); - }, - ]); -} diff --git a/core/promptFiles/v1/handlebarUtils.ts b/core/promptFiles/v1/handlebarUtils.ts deleted file mode 100644 index ffb719590..000000000 --- a/core/promptFiles/v1/handlebarUtils.ts +++ /dev/null @@ -1,117 +0,0 @@ -import Handlebars from "handlebars"; -import { v4 as uuidv4 } from "uuid"; - -function convertToLetter(num: number): string { - let result = ""; - while (num > 0) { - const remainder = (num - 1) % 26; - result = String.fromCharCode(97 + remainder) + result; - num = Math.floor((num - 1) / 26); - } - return result; -} - -/** - * We replace filepaths with alphabetic characters to handle - * escaping issues. - */ -const replaceFilepaths = ( - value: string, - ctxProviderNames: string[], -): [string, { [key: string]: string }] => { - const ast = Handlebars.parse(value); - - const keysToFilepath: { [key: string]: string } = {}; - - let keyIndex = 1; - - for (const i in ast.body) { - const node = ast.body[i] as any; - - if (node.type === "MustacheStatement") { - const originalNodeVal = node.path.original; - const isFilepath = !ctxProviderNames.includes(originalNodeVal); - - if (isFilepath) { - const letter = convertToLetter(keyIndex); - - keysToFilepath[letter] = originalNodeVal; - - value = value.replace( - new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), - `{{${letter}}}`, - ); - - keyIndex++; - } - } - } - - return [value, keysToFilepath]; -}; - -export function registerHelpers( - helpers: Array<[string, Handlebars.HelperDelegate]>, -): { - [key: string]: Promise; -} { - const promises: { [key: string]: Promise } = {}; - - for (const [name, helper] of helpers) { - Handlebars.registerHelper(name, (...args) => { - const id = uuidv4(); - promises[id] = helper(...args); - return `__${id}__`; - }); - } - - return promises; -} - -export async function prepareTemplateAndData( - template: string, - readFile: (filepath: string) => Promise, - inputData: Record, - ctxProviderNames: string[], -): Promise<[string, any]> { - const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames); - - const data: any = { ...inputData }; - - for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) { - data[replacedName] = - inputData[originalCtxProviderName] ?? originalCtxProviderName; - - // If it's not a context provider, assume it's a filepath. - if (!ctxProviderNames.includes(originalCtxProviderName)) { - const fileContents = await readFile(vars[replacedName]); - - if (fileContents) { - data[replacedName] = fileContents; - } - } - } - - return [newTemplate, data]; -} - -export function compileAndRenderTemplate( - template: string, - data: Record, -): string { - const templateFn = Handlebars.compile(template); - return templateFn(data); -} - -export async function resolveHelperPromises( - renderedString: string, - promises: { [key: string]: Promise }, -): Promise { - await Promise.all(Object.values(promises)); - - for (const id in promises) { - renderedString = renderedString.replace(`__${id}__`, await promises[id]); - } - - return renderedString; -} diff --git a/core/promptFiles/v1/index.ts b/core/promptFiles/v1/index.ts deleted file mode 100644 index 1d6726b3e..000000000 --- a/core/promptFiles/v1/index.ts +++ /dev/null @@ -1 +0,0 @@ -export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts deleted file mode 100644 index 8e1478648..000000000 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { ContinueSDK, SlashCommand } from "../.."; -import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; -import { renderChatMessage } from "../../util/messageContent"; -import { getLastNPathParts } from "../../util/uri"; -import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; -import { renderPromptFileV2 } from "../v2/renderPromptFile"; - -import { getContextProviderHelpers } from "./getContextProviderHelpers"; -import { renderTemplatedString } from "./renderTemplatedString"; -import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory"; - -export function extractName(preamble: { name?: string }, path: string): string { - return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; -} - -async function renderPromptV1( - prompt: string, - context: ContinueSDK, - userInput: string, -) { - const helpers = getContextProviderHelpers(context); - - const inputData: Record = { - input: userInput, - }; - - // A few context providers that don't need to be in config.json to work in .prompt files - if (helpers?.find((helper) => helper[0] === "diff")) { - const diffs = await getDiffsFromCache(context.ide); - inputData.diff = diffs.join("\n"); - } - if (helpers?.find((helper) => helper[0] === "currentFile")) { - const currentFile = await context.ide.getCurrentFile(); - if (currentFile) { - inputData.currentFile = currentFile.path; - } - } - - return renderTemplatedString( - prompt, - context.ide.readFile.bind(context.ide), - inputData, - helpers, - ); -} - -export function slashCommandFromPromptFileV1( - path: string, - content: string, -): SlashCommand | null { - const { name, description, systemMessage, prompt } = parsePromptFileV1V2( - path, - content, - ); - - return { - name, - description, - prompt, - promptFile: path, - run: async function* (context) { - const [_, renderedPrompt] = await renderPromptFileV2(prompt, { - config: context.config, - fullInput: context.input, - embeddingsProvider: context.config.modelsByRole.embed[0], - reranker: context.config.modelsByRole.rerank[0], - llm: context.llm, - ide: context.ide, - selectedCode: context.selectedCode, - fetch: context.fetch, - }); - - const messages = replaceSlashCommandWithPromptInChatHistory( - context.history, - name, - renderedPrompt, - systemMessage, - ); - - for await (const chunk of context.llm.streamChat( - messages, - context.abortController.signal, - context.completionOptions, - )) { - yield renderChatMessage(chunk); - } - }, - }; -} diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts deleted file mode 100644 index 70b3ce1bd..000000000 --- a/core/promptFiles/v1/updateChatHistory.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { ChatMessage } from "../.."; - -export function replaceSlashCommandWithPromptInChatHistory( - history: ChatMessage[], - commandName: string, - renderedPrompt: string, - systemMessageOverride?: string, -): ChatMessage[] { - const messages = [...history]; - - for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; - if (role !== "user") { - continue; - } - - if (Array.isArray(content)) { - if ( - content.some( - (part) => - part.type === "text" && part.text?.startsWith(`/${commandName}`), - ) - ) { - messages[i] = updateArrayContent( - messages[i], - commandName, - renderedPrompt, - ); - break; - } - } else if ( - typeof content === "string" && - content.startsWith(`/${commandName}`) - ) { - messages[i] = { ...messages[i], content: renderedPrompt }; - break; - } - } - - if (systemMessageOverride) { - if (messages[0]?.role === "system") { - messages[0].content = systemMessageOverride; - } else { - messages.unshift({ role: "system", content: systemMessageOverride }); - } - } - - return messages; -} - -function updateArrayContent( - message: any, - commandName: string, - renderedPrompt: string, -) { - return { - ...message, - content: message.content.map((part: any) => - part.text?.startsWith(`/${commandName}`) - ? { ...part, text: renderedPrompt } - : part, - ), - }; -} diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts deleted file mode 100644 index 069fe1114..000000000 --- a/core/promptFiles/v2/getPromptFiles.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { IDE } from "../.."; -import { walkDir } from "../../indexing/walkDir"; -import { readAllGlobalPromptFiles } from "../../util/paths"; -import { joinPathsToUri } from "../../util/uri"; -import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1"; - -export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; -export async function getPromptFilesFromDir( - ide: IDE, - dir: string, -): Promise<{ path: string; content: string }[]> { - try { - const exists = await ide.fileExists(dir); - - if (!exists) { - return []; - } - - const uris = await walkDir(dir, ide, { - source: "get dir prompt files", - }); - const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); - const results = promptFilePaths.map(async (uri) => { - const content = await ide.readFile(uri); // make a try catch - return { path: uri, content }; - }); - return Promise.all(results); - } catch (e) { - console.error(e); - return []; - } -} - -export async function getAllPromptFiles( - ide: IDE, - overridePromptFolder?: string, - checkV1DefaultFolder: boolean = false, -): Promise<{ path: string; content: string }[]> { - const workspaceDirs = await ide.getWorkspaceDirs(); - let promptFiles: { path: string; content: string }[] = []; - - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; - if (checkV1DefaultFolder) { - dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); - } - if (overridePromptFolder) { - dirsToCheck = [overridePromptFolder]; - } - - const fullDirs = workspaceDirs - .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) - .flat(); - - promptFiles = ( - await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) - ).flat(); - - // Also read from ~/.continue/.prompts - promptFiles.push(...readAllGlobalPromptFiles()); - - return await Promise.all( - promptFiles.map(async (file) => { - const content = await ide.readFile(file.path); - return { path: file.path, content }; - }), - ); -} diff --git a/core/promptFiles/v2/parse.ts b/core/promptFiles/v2/parse.ts deleted file mode 100644 index ec543cbdc..000000000 --- a/core/promptFiles/v2/parse.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as YAML from "yaml"; - -import { getLastNPathParts } from "../../util/uri"; - -export function extractName(preamble: { name?: string }, path: string): string { - return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; -} - -export function getPreambleAndBody(content: string): [string, string] { - let [preamble, body] = content.split("\n---\n"); - if (body === undefined) { - // This means there is no preamble - body = preamble; - preamble = ""; - } - return [preamble, body]; -} - -export function parsePreamble( - path: string, - content: string, -): { [key: string]: any; name: string; description: string } { - const [preambleRaw, _] = getPreambleAndBody(content); - - const preamble = YAML.parse(preambleRaw) ?? {}; - const name = extractName(preamble, path); - const description = preamble.description ?? name; - - return { - ...preamble, - name, - description, - }; -} diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts deleted file mode 100644 index 4d1330eb3..000000000 --- a/core/promptFiles/v2/renderPromptFile.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { ContextItem, ContextProviderExtras } from "../.."; -import { contextProviderClassFromName } from "../../context/providers"; -import { getUrlContextItems } from "../../context/providers/URLContextProvider"; -import { resolveRelativePathInDir } from "../../util/ideUtils"; -import { getUriPathBasename } from "../../util/uri"; - -import { getPreambleAndBody } from "./parse"; - -async function resolveAttachment( - name: string, - extras: ContextProviderExtras, -): Promise { - // Context providers - const contextProvider = extras.config.contextProviders?.find( - (provider) => provider.description.title === name, - ); - if (contextProvider) { - const items = await contextProvider.getContextItems("", extras); - return items; - } else { - // Just instantiate it here - const providerClass = contextProviderClassFromName(name) as any; - if (providerClass) { - const providerInstance = new providerClass({}); - return providerInstance.getContextItems("", extras); - } - } - - // Files - const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide); - if (resolvedFileUri) { - let subItems: ContextItem[] = []; - if (name.endsWith(".prompt")) { - // Recurse - const [items, _] = await renderPromptFileV2( - await extras.ide.readFile(resolvedFileUri), - extras, - ); - subItems.push(...items); - } - - const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``; - return [ - ...subItems, - { - name: getUriPathBasename(resolvedFileUri), - content, - description: resolvedFileUri, - }, - ]; - } - - // URLs - if (name.startsWith("http")) { - const items = getUrlContextItems(name, extras.fetch); - return items; - } - - return []; -} - -export async function renderPromptFileV2( - rawContent: string, - extras: ContextProviderExtras, -): Promise<[ContextItem[], string]> { - const [_, body] = getPreambleAndBody(rawContent); - - const contextItemsPromises: Promise[] = []; - const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { - contextItemsPromises.push(resolveAttachment(name, extras)); - return match; - }); - - const contextItems = (await Promise.all(contextItemsPromises)).flat(); - const renderedPrompt = [ - ...contextItems.map((item) => item.content), - renderedBody, - extras.fullInput, - ] - .join("\n\n") - .trim(); - - return [contextItems, renderedPrompt]; -} diff --git a/core/promptFiles/v2/renderPromptFile.vitest.ts b/core/promptFiles/v2/renderPromptFile.vitest.ts deleted file mode 100644 index 1d72bc85a..000000000 --- a/core/promptFiles/v2/renderPromptFile.vitest.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { ContextProviderExtras, ILLM, RangeInFile } from "../.."; -import { testConfigHandler, testIde } from "../../test/fixtures"; -import { - addToTestDir, - setUpTestDir, - tearDownTestDir, -} from "../../test/testDir"; -import { renderPromptFileV2 } from "./renderPromptFile"; - -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock( - import("../../context/providers/URLContextProvider"), - async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - getUrlContextItems: vi.fn().mockResolvedValue([ - { - description: "https://example.com", - content: "Example Content", - name: "Example site", - uri: { - type: "url", - value: "https://example.com", - }, - }, - ]), - }; - }, -); - -describe("renderPromptFileV2", () => { - let extras: ContextProviderExtras; - const mockGetContextItems = vi.fn().mockResolvedValue([ - { - name: "custom", - content: "Custom provider content", - description: "Custom provider", - }, - ]); - beforeEach(async () => { - const { config } = await testConfigHandler.loadConfig(); - - // Setup mock extras - extras = { - config: { - ...config!, - contextProviders: [ - { - description: { - type: "normal", - title: "CustomProvider", - displayTitle: "Custom Provider", - description: "A custom context provider", - }, - loadSubmenuItems: vi.fn().mockResolvedValue([]), - getContextItems: mockGetContextItems, - }, - ], - }, - fullInput: "User input", - embeddingsProvider: null, - reranker: null, - llm: {} as ILLM, - ide: testIde, - selectedCode: [] as RangeInFile[], - fetch: vi.fn(), - }; - - // Clear all mocks - vi.clearAllMocks(); - setUpTestDir(); - }); - - afterEach(() => { - tearDownTestDir(); - }); - - it("should render a prompt file with no attachments", async () => { - const rawContent = "Simple prompt with no attachments"; - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(contextItems).toHaveLength(0); - expect(renderedPrompt).toBe( - "Simple prompt with no attachments\n\nUser input", - ); - }); - - it("should handle URL attachments", async () => { - const rawContent = "Content with URL @https://example.com"; - - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(contextItems).toHaveLength(1); - expect(renderedPrompt).toContain("Example Content"); - }); - - it("should resolve file attachments", async () => { - const rawContent = "Content with file attachment @test.txt"; - - addToTestDir([["test.txt", "File content"]]); - - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(contextItems).toHaveLength(1); - expect(renderedPrompt).toContain("```test.txt\nFile content\n```"); - expect(renderedPrompt).toContain("Content with file attachment @test.txt"); - }); - - it("should handle nested prompt files", async () => { - const rawContent = "Main prompt with nested @nested.prompt"; - addToTestDir([ - ["nested.prompt", "Nested prompt content with @CustomProvider"], - ]); - - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(renderedPrompt).toContain("Custom provider content"); - }); - - it("should handle custom context providers", async () => { - const rawContent = "Content with custom provider @CustomProvider"; - - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(contextItems).toHaveLength(1); - expect(renderedPrompt).toContain("Custom provider content"); - expect(mockGetContextItems).toHaveBeenCalled(); - }); - - it("should handle multiple attachments", async () => { - const rawContent = "Content with @file1.txt and @file2.txt"; - addToTestDir([ - ["file1.txt", "Content 1"], - ["file2.txt", "Content 2"], - ]); - - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(contextItems).toHaveLength(2); - expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```"); - expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```"); - }); - - it("should handle failed attachment resolutions gracefully", async () => { - const rawContent = "Content with @nonexistent"; - - const [contextItems, renderedPrompt] = await renderPromptFileV2( - rawContent, - extras, - ); - - expect(contextItems).toHaveLength(0); - expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input"); - }); -}); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index dfc0d87d6..b6cb8e9b0 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -5,7 +5,10 @@ import { ModelRole, } from "@continuedev/config-yaml"; -import { AutocompleteInput } from "../autocomplete/util/types"; +import { + AutocompleteInput, + RecentlyEditedRange, +} from "../autocomplete/util/types"; import { SharedConfigSchema } from "../config/sharedConfig"; import { GlobalContextModelSelections } from "../util/GlobalContext"; @@ -25,14 +28,18 @@ import { ModelDescription, PromptLog, RangeInFile, + RangeInFileWithNextEditInfo, SerializedContinueConfig, Session, SessionMetadata, SiteIndexingConfig, - SlashCommandDescription, + SlashCommandDescWithSource, StreamDiffLinesPayload, ToolCall, } from "../"; +import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; +import { GetLspDefinitionsFunction } from "../autocomplete/types"; +import { ConfigHandler } from "../config/ConfigHandler"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; import { FreeTrialStatus } from "../control-plane/client"; @@ -118,6 +125,17 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + "mcp/getPrompt": [ + { + serverName: string; + promptName: string; + args?: Record; + }, + { + prompt: string; + description: string | undefined; + }, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; @@ -141,7 +159,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; legacySlashCommandData?: { - command: SlashCommandDescription; + command: SlashCommandDescWithSource; input: string; contextItems: ContextItemWithId[]; historyIndex: number; @@ -182,6 +200,16 @@ export type ToCoreFromIdeOrWebviewProtocol = { "files/created": [{ uris?: string[] }, void]; "files/deleted": [{ uris?: string[] }, void]; "files/closed": [{ uris?: string[] }, void]; + "files/smallEdit": [ + { + actions: RangeInFileWithNextEditInfo[]; + configHandler: ConfigHandler; + getDefsFromLspFunction: GetLspDefinitionsFunction; + recentlyEditedRanges: RecentlyEditedRange[]; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + }, + void, + ]; // Docs etc. Indexing. TODO move codebase to this "indexing/reindex": [{ type: string; id: string }, void]; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 4fa8f4bc4..ba4cf4f88 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,6 +1,5 @@ import type { ContinueRcJson, - DiffLine, FileStatsMap, FileType, IDE, @@ -35,15 +34,6 @@ export type ToIdeFromWebviewOrCoreProtocol = { saveFile: [{ filepath: string }, void]; fileExists: [{ filepath: string }, boolean]; readFile: [{ filepath: string }, string]; - diffLine: [ - { - diffLine: DiffLine; - filepath: string; - startLine: number; - endLine: number; - }, - void, - ]; getProblems: [{ filepath: string }, Problem[]]; getOpenFiles: [undefined, string[]]; getCurrentFile: [ diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 074e3837f..55532eac0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,6 +4,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { AcceptOrRejectDiffPayload, ApplyState, + ApplyToFilePayload, HighlightedCodePayload, MessageContent, RangeInFileWithContents, @@ -13,15 +14,7 @@ import { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; - applyToFile: [ - { - text: string; - streamId: string; - filepath?: string; - toolCallId?: string; - }, - void, - ]; + applyToFile: [ApplyToFilePayload, void]; overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [ShowFilePayload, void]; @@ -84,4 +77,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { updateApplyState: [ApplyState, void]; exitEditMode: [undefined, void]; focusEdit: [undefined, void]; + generateRule: [undefined, void]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 105636d2f..6b29ce472 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -27,6 +27,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/updateSharedConfig", "config/updateSelectedModel", "mcp/reloadServer", + "mcp/getPrompt", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 5a2408a0c..c5c5da16c 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,23 +1,28 @@ export enum BuiltInToolNames { - ReadFile = "builtin_read_file", - EditExistingFile = "builtin_edit_existing_file", - ReadCurrentlyOpenFile = "builtin_read_currently_open_file", - CreateNewFile = "builtin_create_new_file", - RunTerminalCommand = "builtin_run_terminal_command", - GrepSearch = "builtin_grep_search", - FileGlobSearch = "builtin_file_glob_search", - SearchWeb = "builtin_search_web", - ViewDiff = "builtin_view_diff", - LSTool = "builtin_ls", - CreateRuleBlock = "builtin_create_rule_block", - RequestRule = "builtin_request_rule", - FetchUrlContent = "builtin_fetch_url_content", + ReadFile = "read_file", + EditExistingFile = "edit_existing_file", + SearchAndReplaceInFile = "search_and_replace_in_file", + ReadCurrentlyOpenFile = "read_currently_open_file", + CreateNewFile = "create_new_file", + RunTerminalCommand = "run_terminal_command", + GrepSearch = "grep_search", + FileGlobSearch = "file_glob_search", + SearchWeb = "search_web", + ViewDiff = "view_diff", + LSTool = "ls", + CreateRuleBlock = "create_rule_block", + RequestRule = "request_rule", + FetchUrlContent = "fetch_url_content", + CodebaseTool = "codebase", // excluded from allTools for now - ViewRepoMap = "builtin_view_repo_map", - ViewSubdirectory = "builtin_view_subdirectory", + ViewRepoMap = "view_repo_map", + ViewSubdirectory = "view_subdirectory", } export const BUILT_IN_GROUP_NAME = "Built-In"; -export const CLIENT_TOOLS_IMPLS = [BuiltInToolNames.EditExistingFile]; +export const CLIENT_TOOLS_IMPLS = [ + BuiltInToolNames.EditExistingFile, + BuiltInToolNames.SearchAndReplaceInFile, +]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 40dd7abe2..f24210511 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -3,6 +3,7 @@ import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; +import { codebaseToolImpl } from "./implementations/codebaseTool"; import { createNewFileImpl } from "./implementations/createNewFile"; import { createRuleBlockImpl } from "./implementations/createRuleBlock"; import { fetchUrlContentImpl } from "./implementations/fetchUrlContent"; @@ -15,6 +16,8 @@ import { requestRuleImpl } from "./implementations/requestRule"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; +import { viewRepoMapImpl } from "./implementations/viewRepoMap"; +import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory"; import { safeParseToolCallArgs } from "./parseArgs"; async function callHttpTool( @@ -134,7 +137,7 @@ async function callToolFromUri( } } -async function callBuiltInTool( +export async function callBuiltInTool( functionName: string, args: any, extras: ToolExtras, @@ -164,6 +167,12 @@ async function callBuiltInTool( return await createRuleBlockImpl(args, extras); case BuiltInToolNames.RequestRule: return await requestRuleImpl(args, extras); + case BuiltInToolNames.CodebaseTool: + return await codebaseToolImpl(args, extras); + case BuiltInToolNames.ViewRepoMap: + return await viewRepoMapImpl(args, extras); + case BuiltInToolNames.ViewSubdirectory: + return await viewSubdirectoryImpl(args, extras); default: throw new Error(`Tool "${functionName}" not found`); } diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts new file mode 100644 index 000000000..fffe51e02 --- /dev/null +++ b/core/tools/definitions/codebaseTool.ts @@ -0,0 +1,29 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const codebaseTool: Tool = { + type: "function", + displayTitle: "Codebase Search", + wouldLikeTo: "search the codebase for: {{{ query }}}", + isCurrently: "searching the codebase for: {{{ query }}}", + hasAlready: "searched the codebase for: {{{ query }}}", + readonly: true, + isInstant: false, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.CodebaseTool, + description: + "Use this tool to semantically search through the codebase and retrieve relevant code snippets based on a natural language query. This helps find relevant code context for understanding or working with the codebase.", + parameters: { + type: "object", + required: ["query"], + properties: { + query: { + type: "string", + description: + "Natural language description of what you're looking for in the codebase (e.g., 'authentication logic', 'database connection setup', 'error handling')", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 9596122a3..92aecb158 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -13,7 +13,7 @@ export const createRuleBlock: Tool = { function: { name: BuiltInToolNames.CreateRuleBlock, description: - 'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.', + 'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)', parameters: { type: "object", required: ["name", "rule", "description"], @@ -30,7 +30,8 @@ export const createRuleBlock: Tool = { }, description: { type: "string", - description: "Short description of the rule", + description: + "Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.", }, globs: { type: "string", @@ -42,6 +43,11 @@ export const createRuleBlock: Tool = { description: "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)", }, + alwaysApply: { + type: "boolean", + description: + "Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.", + }, }, }, }, diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 6c6ad6fd9..235833d1f 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,4 +1,5 @@ import { Tool } from "../.."; +import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export interface EditToolArgs { @@ -17,8 +18,7 @@ export const editFileTool: Tool = { isInstant: false, function: { name: BuiltInToolNames.EditExistingFile, - description: - "Use this tool to edit an existing file. If you don't know the contents of the file, read it first.", + description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}`, parameters: { type: "object", required: ["filepath", "changes"], diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index b3cbcac5b..42e8afd2d 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -13,7 +13,7 @@ export const globSearchTool: Tool = { function: { name: BuiltInToolNames.FileGlobSearch, description: - "Search for files in the project. Output may be truncated; use targeted patterns", + "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns", parameters: { type: "object", required: ["pattern"], diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts new file mode 100644 index 000000000..a861fbb1c --- /dev/null +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -0,0 +1,82 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export interface SearchAndReplaceInFileArgs { + filepath: string; + diff: string; +} + +/** + * This tool is in an experimental state. + * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 + */ +export const searchAndReplaceInFileTool: Tool = { + type: "function", + displayTitle: "Edit File", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + isInstant: false, + function: { + name: BuiltInToolNames.SearchAndReplaceInFile, + description: + "Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.", + parameters: { + type: "object", + required: ["filepath", "diff"], + 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: +\`\`\` +------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE +\`\`\` + +Critical rules: +1. SEARCH content must match the associated file section to find EXACTLY: + * Match character-for-character including whitespace, indentation, line endings + * Include all comments, docstrings, etc. +2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. + * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. + * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. + * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. +3. Keep SEARCH/REPLACE blocks concise: + * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. + * Include just the changing lines, and a few surrounding lines if needed for uniqueness. + * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. + * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. +4. Special operations: + * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) + * To delete code: Use empty REPLACE section + +Usage: +\`\`\` +------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE + +------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE + \`\`\` +`, + }, + }, + }, + }, +}; diff --git a/core/tools/implementations/codebaseTool.ts b/core/tools/implementations/codebaseTool.ts new file mode 100644 index 000000000..46b06a8c6 --- /dev/null +++ b/core/tools/implementations/codebaseTool.ts @@ -0,0 +1,61 @@ +import { ToolImpl } from "."; +import { RangeInFile } from "../.."; +import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval"; + +export const codebaseToolImpl: ToolImpl = async (args, extras) => { + if (!args.query || args.query.trim() === "") { + return [ + { + name: "Error", + description: "Codebase search error", + content: "Query parameter is required and cannot be empty.", + }, + ]; + } + + try { + const contextExtras = { + config: extras.config, + fullInput: args.query, + embeddingsProvider: extras.config.selectedModelByRole.embed, + reranker: extras.config.selectedModelByRole.rerank, + llm: extras.llm, + ide: extras.ide, + selectedCode: [] as RangeInFile[], + fetch: extras.fetch, + }; + + // Use the existing retrieval function to get context items + const results = await retrieveContextItemsFromEmbeddings( + contextExtras, + undefined, + undefined, + ); + + // If no results found, return helpful message + if (results.length === 0) { + return [ + { + name: "No Results", + description: "Codebase search", + content: `No relevant code found for query: "${args.query}". This could mean: +- The codebase hasn't been indexed yet +- No code matches the search criteria +- Embeddings provider is not configured + +Try re-indexing the codebase or using a more specific query.`, + }, + ]; + } + + return results; + } catch (error) { + return [ + { + name: "Error", + description: "Codebase search error", + content: `Failed to search codebase: ${error instanceof Error ? error.message : String(error)}`, + }, + ]; + } +}; diff --git a/core/tools/implementations/createRuleBlock.test.ts b/core/tools/implementations/createRuleBlock.test.ts index 261f8eeb9..4808037b4 100644 --- a/core/tools/implementations/createRuleBlock.test.ts +++ b/core/tools/implementations/createRuleBlock.test.ts @@ -36,6 +36,7 @@ test("createRuleBlockImpl should create a rule with glob pattern", async () => { const { frontmatter, markdown } = parseMarkdownRule(fileContent); expect(frontmatter).toEqual({ + alwaysApply: true, description: "Always use interfaces", globs: "**/*.{ts,tsx}", }); @@ -72,6 +73,7 @@ test("createRuleBlockImpl should create a rule with description pattern", async const { frontmatter, markdown } = parseMarkdownRule(fileContent); expect(frontmatter).toEqual({ + alwaysApply: true, description: "This is a detailed explanation of the rule", }); @@ -94,6 +96,7 @@ test("createRuleBlockImpl should include both globs and description in frontmatt const { frontmatter, markdown } = parseMarkdownRule(fileContent); expect(frontmatter).toEqual({ + alwaysApply: false, description: "This rule enforces our team standards", globs: "**/*.js", }); @@ -116,6 +119,7 @@ test("createRuleBlockImpl should create a rule with alwaysApply set to false", a const { frontmatter } = parseMarkdownRule(fileContent); expect(frontmatter).toEqual({ + alwaysApply: false, description: "Optional rule", }); }); diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index 06921f770..e433c233d 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -5,29 +5,18 @@ import { createRuleFilePath } from "../../config/markdown/utils"; export type CreateRuleBlockArgs = Pick< Required, - "rule" | "description" | "alwaysApply" | "name" + "rule" | "name" > & - Pick; + Pick; export const createRuleBlockImpl: ToolImpl = async ( - args: CreateRuleBlockArgs, + { name, rule, ...otherArgs }: CreateRuleBlockArgs, extras, ) => { - // Create options object with the fields that createRuleMarkdown expects - const options: any = { - description: args.description, - globs: args.globs, - }; - - // Add regex if provided - if (args.regex) { - options.regex = args.regex; - } - - const fileContent = createRuleMarkdown(args.name, args.rule, options); + const fileContent = createRuleMarkdown(name, rule, otherArgs); const [localContinueDir] = await extras.ide.getWorkspaceDirs(); - const ruleFilePath = createRuleFilePath(localContinueDir, args.name); + const ruleFilePath = createRuleFilePath(localContinueDir, name); await extras.ide.writeFile(ruleFilePath, fileContent); await extras.ide.openFile(ruleFilePath); @@ -35,7 +24,7 @@ export const createRuleBlockImpl: ToolImpl = async ( return [ { name: "New Rule Block", - description: args.description || "", + description: otherArgs.description || "", uri: { type: "file", value: ruleFilePath, diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index 149b68a75..b13839669 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -5,6 +5,41 @@ import { formatGrepSearchResults } from "../../util/grepSearch"; const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now +function splitGrepResultsByFile(content: string): ContextItem[] { + const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)]; + + if (matches.length === 0) { + return []; + } + + const contextItems: ContextItem[] = []; + + for (let i = 0; i < matches.length; i++) { + const match = matches[i]; + const filepath = match[1]; + const startIndex = match.index!; + const endIndex = + i < matches.length - 1 ? matches[i + 1].index! : content.length; + + // Extract grepped content for this file + const fileContent = content + .substring(startIndex, endIndex) + .replace(/^\.\/[^\n]+\n/, "") // remove the line with file path + .trim(); + + if (fileContent) { + contextItems.push({ + name: `Search results in ${filepath}`, + description: `Grep search results from ${filepath}`, + content: fileContent, + uri: { type: "file", value: filepath }, + }); + } + } + + return contextItems; +} + export const grepSearchImpl: ToolImpl = async (args, extras) => { const results = await extras.ide.getSearchResults( args.query, @@ -26,13 +61,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { ); } - const contextItems: ContextItem[] = [ - { - name: "Search results", - description: "Results from grep search", - content: formatted, - }, - ]; + let contextItems: ContextItem[] = []; + + const splitByFile: boolean = args.splitByFile || false; + if (splitByFile) { + contextItems = splitGrepResultsByFile(formatted); + } else { + contextItems = [ + { + name: "Search results", + description: "Results from grep search", + content: formatted, + }, + ]; + } + if (truncationReasons.length > 0) { contextItems.push({ name: "Search truncation warning", diff --git a/core/tools/implementations/readCurrentlyOpenFile.ts b/core/tools/implementations/readCurrentlyOpenFile.ts index a55aee2bd..bf3b2c713 100644 --- a/core/tools/implementations/readCurrentlyOpenFile.ts +++ b/core/tools/implementations/readCurrentlyOpenFile.ts @@ -1,28 +1,41 @@ import { getUriDescription } from "../../util/uri"; import { ToolImpl } from "."; +import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { const result = await extras.ide.getCurrentFile(); - if (!result) { - return []; - } + if (result) { + await throwIfFileExceedsHalfOfContext( + result.path, + result.contents, + extras.config.selectedModelByRole.chat, + ); - const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( - result.path, - await extras.ide.getWorkspaceDirs(), - ); + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + result.path, + await extras.ide.getWorkspaceDirs(), + ); - return [ - { - name: `Current file: ${baseName}`, - description: last2Parts, - content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``, - uri: { - type: "file", - value: result.path, + return [ + { + name: `Current file: ${baseName}`, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``, + uri: { + type: "file", + value: result.path, + }, }, - }, - ]; + ]; + } else { + return [ + { + name: `No Current File`, + description: "", + content: "There are no files currently open.", + }, + ]; + } }; diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index c08713997..4736d0b4c 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -2,6 +2,7 @@ import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getUriPathBasename } from "../../util/uri"; import { ToolImpl } from "."; +import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; export const readFileImpl: ToolImpl = async (args, extras) => { const firstUriMatch = await resolveRelativePathInDir( @@ -12,6 +13,13 @@ export const readFileImpl: ToolImpl = async (args, extras) => { throw new Error(`Could not find file ${args.filepath}`); } const content = await extras.ide.readFile(firstUriMatch); + + await throwIfFileExceedsHalfOfContext( + args.filepath, + content, + extras.config.selectedModelByRole.chat, + ); + return [ { name: getUriPathBasename(args.filepath), diff --git a/core/tools/implementations/readFileLimit.ts b/core/tools/implementations/readFileLimit.ts new file mode 100644 index 000000000..e2af14d56 --- /dev/null +++ b/core/tools/implementations/readFileLimit.ts @@ -0,0 +1,18 @@ +import { ILLM } from "../.."; +import { countTokensAsync } from "../../llm/countTokens"; + +export async function throwIfFileExceedsHalfOfContext( + filepath: string, + content: string, + model: ILLM | null, +) { + if (model) { + const tokens = await countTokensAsync(content, model.title); + const tokenLimit = model.contextLength / 2; + if (tokens > tokenLimit) { + throw new Error( + `File ${filepath} is too large (${tokens} tokens vs ${tokenLimit} token limit). Try another approach`, + ); + } + } +} diff --git a/core/tools/index.ts b/core/tools/index.ts index daf40c7e0..198438eb1 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { ConfigDependentToolParams, IDE, Tool } from ".."; +import { codebaseTool } from "./definitions/codebaseTool"; import { createNewFileTool } from "./definitions/createNewFile"; import { createRuleBlock } from "./definitions/createRuleBlock"; import { editFileTool } from "./definitions/editFile"; @@ -10,15 +11,19 @@ import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; import { readFileTool } from "./definitions/readFile"; import { requestRuleTool } from "./definitions/requestRule"; import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; +import { searchAndReplaceInFileTool } from "./definitions/searchAndReplaceInFile"; import { searchWebTool } from "./definitions/searchWeb"; import { viewDiffTool } from "./definitions/viewDiff"; +import { viewRepoMapTool } from "./definitions/viewRepoMap"; +import { viewSubdirectoryTool } from "./definitions/viewSubdirectory"; + +// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads. // missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 -export const localOnlyToolDefinitions = [grepSearchTool]; +const getLocalOnlyToolDefinitions = () => [grepSearchTool]; -export const baseToolDefinitions = [ +const getBaseToolDefinitions = () => [ readFileTool, - editFileTool, createNewFileTool, runTerminalCommandTool, globSearchTool, @@ -28,16 +33,23 @@ export const baseToolDefinitions = [ lsTool, createRuleBlock, fetchUrlContentTool, - // replacing with ls tool for now - // viewSubdirectoryTool, - // viewRepoMapTool, ]; export const getConfigDependentToolDefinitions = ( params: ConfigDependentToolParams, -): Tool[] => [requestRuleTool(params)]; +): Tool[] => [ + requestRuleTool(params), + ...(params.enableExperimentalTools + ? [ + searchAndReplaceInFileTool, + viewRepoMapTool, + viewSubdirectoryTool, + codebaseTool, + ] + : [editFileTool]), +]; -export const getToolsForIde = async (ide: IDE) => +export const getToolsForIde = async (ide: IDE): Promise => (await ide.isWorkspaceRemote()) - ? baseToolDefinitions - : [...baseToolDefinitions, ...localOnlyToolDefinitions]; + ? getBaseToolDefinitions() + : [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()]; diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index 36d75e020..86ee26cb1 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -4,7 +4,7 @@ export function safeParseToolCallArgs( toolCall: ToolCallDelta, ): Record { try { - return JSON.parse(toolCall.function?.arguments ?? "{}"); + return JSON.parse(toolCall.function?.arguments?.trim() || "{}"); } catch (e) { console.error( `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`, diff --git a/core/util/findLast.ts b/core/util/findLast.ts index 9e99fd473..256d6e09d 100644 --- a/core/util/findLast.ts +++ b/core/util/findLast.ts @@ -1,6 +1,6 @@ -export function findLastIndex( - arr: any[], - criterion: (item: any) => boolean, +export function findLastIndex( + arr: T[], + criterion: (item: T) => boolean, ): number { let lastIndex = -1; diff --git a/core/util/handlebars/handlebarUtils.ts b/core/util/handlebars/handlebarUtils.ts new file mode 100644 index 000000000..9314fd353 --- /dev/null +++ b/core/util/handlebars/handlebarUtils.ts @@ -0,0 +1,111 @@ +import { v4 as uuidv4 } from "uuid"; + +export type HandlebarsType = typeof import("handlebars"); + +function convertToLetter(num: number): string { + let result = ""; + while (num > 0) { + const remainder = (num - 1) % 26; + result = String.fromCharCode(97 + remainder) + result; + num = Math.floor((num - 1) / 26); + } + return result; +} + +export function registerHelpers( + handlebars: HandlebarsType, + helpers: Array<[string, Handlebars.HelperDelegate]>, +): { + [key: string]: Promise; +} { + const promises: { [key: string]: Promise } = {}; + + for (const [name, helper] of helpers) { + handlebars.registerHelper(name, (...args) => { + const id = uuidv4(); + promises[id] = helper(...args); + return `__${id}__`; + }); + } + + return promises; +} + +export async function prepareTemplatedFilepaths( + handlebars: HandlebarsType, + template: string, + inputData: Record, + ctxProviderNames: string[], + readFile: (filepath: string) => Promise, + getUriFromPath: (path: string) => Promise, +) { + // First, replace filepaths with letters to avoid escaping issues + const ast = handlebars.parse(template); + + const filepathLetters: Map = new Map(); + const requiredContextProviders: Set = new Set(); + let withLetterKeys = template; + + let letterIndex = 1; + + for (const i in ast.body) { + const node = ast.body[i] as any; + + if (node.type === "MustacheStatement") { + const originalNodeVal = node.path.original; + if (originalNodeVal.toLowerCase() === "input") { + continue; + } + const isFilepath = !ctxProviderNames.includes(originalNodeVal); + + if (isFilepath) { + const letter = convertToLetter(letterIndex); + + filepathLetters.set(letter, originalNodeVal); + + withLetterKeys = withLetterKeys.replace( + new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), + `{{${letter}}}`, + ); + + letterIndex++; + } else { + requiredContextProviders.add(originalNodeVal); + } + } + } + + // Then, resolve the filepaths to their actual content and add to template data + // Fallback to simple error string if file read fails + const templateData = { ...inputData }; + + for (const [letter, filepath] of filepathLetters.entries()) { + try { + const uri = await getUriFromPath(filepath); + if (uri) { + const fileContents = await readFile(uri); + templateData[letter] = fileContents; + } else { + throw new Error(`File not found: ${filepath}`); + } + } catch (e) { + console.error(`Error reading file in prompt file ${filepath}:`, e); + templateData[letter] = `[Error reading file "${filepath}"]`; + } + } + + return { withLetterKeys, templateData, requiredContextProviders }; +} + +export async function resolveHelperPromises( + renderedString: string, + promises: { [key: string]: Promise }, +): Promise { + await Promise.all(Object.values(promises)); + + for (const id in promises) { + renderedString = renderedString.replace(`__${id}__`, await promises[id]); + } + + return renderedString; +} diff --git a/core/promptFiles/v1/renderTemplatedString.ts b/core/util/handlebars/renderTemplatedString.ts similarity index 51% rename from core/promptFiles/v1/renderTemplatedString.ts rename to core/util/handlebars/renderTemplatedString.ts index bcc645ace..20927e814 100644 --- a/core/promptFiles/v1/renderTemplatedString.ts +++ b/core/util/handlebars/renderTemplatedString.ts @@ -1,30 +1,35 @@ import { - compileAndRenderTemplate, - prepareTemplateAndData, + prepareTemplatedFilepaths, registerHelpers, resolveHelperPromises, + type HandlebarsType, } from "./handlebarUtils"; export async function renderTemplatedString( + handlebars: HandlebarsType, template: string, - readFile: (filepath: string) => Promise, inputData: Record, - availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, + availableHelpers: Array<[string, Handlebars.HelperDelegate]>, + readFile: (filepath: string) => Promise, + getUriFromPath: (path: string) => Promise, ): Promise { const helperPromises = availableHelpers - ? registerHelpers(availableHelpers) + ? registerHelpers(handlebars, availableHelpers) : {}; const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? []; - const [newTemplate, data] = await prepareTemplateAndData( + const { withLetterKeys, templateData } = await prepareTemplatedFilepaths( + handlebars, template, - readFile, inputData, ctxProviderNames, + readFile, + getUriFromPath, ); - let renderedString = compileAndRenderTemplate(newTemplate, data); + const templateFn = handlebars.compile(withLetterKeys); + const renderedString = templateFn(templateData); return resolveHelperPromises(renderedString, helperPromises); } diff --git a/core/util/text.ts b/core/util/text.ts index e4870dfa0..9e948f415 100644 --- a/core/util/text.ts +++ b/core/util/text.ts @@ -4,3 +4,40 @@ export const capitalizeFirstLetter = (val: string) => { } return val[0].toUpperCase() + val.slice(1); }; + +export function replaceEscapedCharacters(str: string): string { + return str.replaceAll(/\\(n|t|r|\\|"|')/g, (match, p1) => { + switch (p1) { + case "n": + return "\n"; + case "t": + return "\t"; + case "r": + return "\r"; + case "\\": + return "\\"; + case '"': + return '"'; + case "'": + return "'"; + default: + return match; // NOTE: Handle unexpected escapes better than this. + } + }); +} + +export function escapeForSVG(text: string): string { + return text + .replace(/&/g, "&") // must be first + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +export function kebabOfStr(str: string): string { + return str + .replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase + .replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens + .toLowerCase(); +} diff --git a/core/util/uri.ts b/core/util/uri.ts index e180a0a69..d3c1659b5 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -188,6 +188,7 @@ export function getUriDescription(uri: string, dirUriCandidates: string[]) { dirUriCandidates, ); const baseName = getUriPathBasename(uri); + const extension = getFileExtensionFromBasename(baseName); const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2); return { uri, @@ -195,5 +196,6 @@ export function getUriDescription(uri: string, dirUriCandidates: string[]) { foundInDir, last2Parts, baseName, + extension, }; } diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md index 5847b99a5..9253b45d3 100644 --- a/docs/docs/agent/how-it-works.md +++ b/docs/docs/agent/how-it-works.md @@ -28,14 +28,12 @@ In [Chat mode](../chat/how-to-use-it.md), tools are **not** included in the requ Continue includes several built-in tools which provide the model access to IDE functionality: -- **Read file** (`builtin_read_file`): read the contents of a file within the project -- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file -- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model -- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project -- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. -- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root -- **Search web** (`builtin_search_web`): Perform a web search to get top results -- **View diff** (`builtin_view_diff`): View the current working git diff -- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map) -- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project -- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation +- **Read file** (`read_file`): read the contents of a file within the project +- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file +- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model +- **Exact search** (`exact_search`): perform a `ripgrep` search within the project +- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. +- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root +- **Search web** (`search_web`): Perform a web search to get top results +- **View diff** (`view_diff`): View the current working git diff +- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation diff --git a/docs/docs/customize/deep-dives/rules.mdx b/docs/docs/customize/deep-dives/rules.mdx index 92a006b5e..610878f0c 100644 --- a/docs/docs/customize/deep-dives/rules.mdx +++ b/docs/docs/customize/deep-dives/rules.mdx @@ -48,7 +48,7 @@ Rules can be added locally using the "Add Rules" button while viewing the Local ![add local rules button](/img/add-local-rules.png) :::info Automatically create local rule blocks -When in Agent mode, you can prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled. +When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled. For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation. ::: diff --git a/docs/docs/customize/model-providers/more/llamastack.mdx b/docs/docs/customize/model-providers/more/llamastack.mdx new file mode 100644 index 000000000..4f21e9911 --- /dev/null +++ b/docs/docs/customize/model-providers/more/llamastack.mdx @@ -0,0 +1,113 @@ +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +# Llama Stack + +[Llama Stack](https://llama-stack.readthedocs.io/en/latest/index.html) is an open-source library that standardizes the core building blocks that simplify AI application development. It codifies best practices across the Llama ecosystem. More specifically, it provides + +- **Unified API layer** for Inference, RAG, Agents, Tools, Safety, Evals, and Telemetry. +- **Plugin architecture** to support the rich ecosystem of different API implementations in various environments, including local development, on-premises, cloud, and mobile. +- **Prepackaged verified distributions** which offer a one-stop solution for developers to get started quickly and reliably in any environment. +- **Multiple developer interfaces** like CLI and SDKs for Python, Typescript, iOS, and Android. +- **Standalone applications** as examples for how to build production-grade AI applications with Llama Stack. + +To try Llama Stack locally, run: + +```shell +curl -LsSf https://github.com/meta-llama/llama-stack/raw/main/install.sh | bash +``` + +Learn more about how to get started with llama stack in this [guide](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html) + +## Chat model + +We recommend configuring **Llama 4 Maverick** as your chat model. + + + + ```yaml title="config.yaml" + models: + - name: Llama4 Maverick + provider: llamastack + model: meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8 + apiBase: http:///v1/openai/v1/ + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Llama4 Maverick", + "provider": "llamastack", + "model": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", + "apiBase": "http:///v1/openai/v1/" + } + ] + } + ``` + + + +## Autocomplete model + +We recommend configuring **CodeLlama 7B** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - name: CodeLlama 7B + provider: llamastack + model: codellama:7b + apiBase: http:///v1/openai/v1/ + roles: + - autocomplete + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": { + "title": "CodeLlama 7B", + "provider": "llamastack", + "model": "codellama:7b", + "apiBase": "http:///v1/openai/v1/" + } + } + ``` + + + +## Embeddings model + +By default, Llama Stack uses **all-MiniLM-L6-v2** as the embeddings model. + + + + ```yaml title="config.yaml" + models: + - name: all-MiniLM-L6-v2 + provider: llamastack + model: all-MiniLM-L6-v2 + apiBase: http:///v1/openai/v1/ + roles: + - embed + ``` + + + ```json title="config.json" + { + "embeddingsProvider": { + "provider": "llamastack", + "model": "all-MiniLM-L6-v2", + "apiBase": "http:///v1/openai/v1/" + } + } + ``` + + + +## Reranking model + +Llama Stack currently did not support Reranking API yet. \ No newline at end of file diff --git a/docs/docs/customize/model-providers/top-level/bedrock.mdx b/docs/docs/customize/model-providers/top-level/bedrock.mdx index eb2646d46..a314d0899 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.mdx +++ b/docs/docs/customize/model-providers/top-level/bedrock.mdx @@ -200,9 +200,10 @@ To setup Bedrock using custom imported models, add the following to your config - name: AWS Bedrock deepseek-coder-6.7b-instruct provider: bedrockimport model: deepseek-coder-6.7b-instruct - modelArn: arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX - region: us-west-2 - profile: bedrock + env: + region: us-west-2 + profile: bedrock + modelArn: arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX ``` diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index 2331eb2b3..9757bc430 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -9,6 +9,7 @@ This file is for contribution guidelines specific to the JetBrains extension. Se - [Environment Setup](#environment-setup) - [IDE Installation](#ide-installation) - [IDE configuration](#ide-configuration) + - [Recommended plugins](#recommended-plugins) - [Node.js Requirements](#nodejs-requirements) - [Install all dependencies](#install-all-dependencies) - [Misc](#misc) @@ -27,6 +28,7 @@ This file is for contribution guidelines specific to the JetBrains extension. Se - [Setup](#setup) - [Running the tests](#running-the-tests) - [Identifying selectors](#identifying-selectors) + - [Rebuilding the extension](#rebuilding-the-extension) ## Architecture Overview @@ -50,6 +52,13 @@ notes below). - Enable code formatting on save: `Settings | Tools | Actions on Save | Reformat code` +#### Recommended plugins + +- [Thread Access Info](https://plugins.jetbrains.com/plugin/16815-thread-access-info) - adds an extra debug panel + showing possible thread access violation (according to Intellij Platform SDK guidelines) +- [File Expander](https://plugins.jetbrains.com/plugin/11940-file-expander) - allows you to easily preview archives as + directories (like `build/distributions/continue-*.zip`) + ### Node.js Requirements This project requires Node.js version 20.19.0 (LTS) or higher. You have two options for installation: @@ -184,7 +193,7 @@ Run a single test While the `runIdeForUiTests` task is running, you can visit the following URL to view the UI hierarchy of the running IDE: -http://127.0.0.1:8082/ + #### Rebuilding the extension diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index a1b27e801..fb85ded90 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -11,13 +11,14 @@ fun Sync.prepareSandbox() { val remoteRobotVersion = "0.11.23" plugins { - id("java") // Java support - alias(libs.plugins.kotlin) // Kotlin support - alias(libs.plugins.gradleIntelliJPlugin) // Gradle IntelliJ Plugin - alias(libs.plugins.changelog) // Gradle Changelog Plugin - alias(libs.plugins.qodana) // Gradle Qodana Plugin - alias(libs.plugins.kover) // Gradle Kover Plugin + id("java") + kotlin("jvm") version "1.9.0" + id("org.jetbrains.intellij") version "1.15.0" + id("org.jetbrains.changelog") version "2.1.2" + id("org.jetbrains.qodana") version "0.1.13" + id("org.jetbrains.kotlinx.kover") version "0.7.3" kotlin("plugin.serialization") version "1.8.0" + id("io.sentry.jvm.gradle") version "5.8.0" } group = properties("pluginGroup").get() @@ -33,7 +34,6 @@ repositories { // Dependencies are managed with Gradle version catalog - read more: // https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog dependencies { - // implementation(libs.annotations) implementation("com.squareup.okhttp3:okhttp:4.12.0") { exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib") } @@ -46,7 +46,7 @@ dependencies { testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2") testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0") - implementation("com.automation-remarks:video-recorder-junit5:2.0") + testImplementation("com.automation-remarks:video-recorder-junit5:2.0") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3") @@ -192,11 +192,8 @@ tasks { } runIde { - // Open the `manual-testing-sandbox` directory and the specific file on start - args = listOf( - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox", - "${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt" - ).map { file(it).absolutePath } + val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox" + args = listOf(dir, "$dir/test.kt") } test { diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 4248e25a9..6ed879f4b 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.26 +pluginVersion=1.0.27 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/gradle/libs.versions.toml b/extensions/intellij/gradle/libs.versions.toml deleted file mode 100644 index 4e9387593..000000000 --- a/extensions/intellij/gradle/libs.versions.toml +++ /dev/null @@ -1,20 +0,0 @@ -[versions] -# libraries -annotations = "24.0.1" - -# plugins -kotlin = "1.9.0" -changelog = "2.1.2" -gradleIntelliJPlugin = "1.15.0" -qodana = "0.1.13" -kover = "0.7.3" - -[libraries] -annotations = { group = "org.jetbrains", name = "annotations", version.ref = "annotations" } - -[plugins] -changelog = { id = "org.jetbrains.changelog", version.ref = "changelog" } -gradleIntelliJPlugin = { id = "org.jetbrains.intellij", version.ref = "gradleIntelliJPlugin" } -kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } -kover = { id = "org.jetbrains.kotlinx.kover", version.ref = "kover" } -qodana = { id = "org.jetbrains.qodana", version.ref = "qodana" } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/Icons.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/Icons.kt new file mode 100644 index 000000000..e047127a1 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/Icons.kt @@ -0,0 +1,10 @@ +package com.github.continuedev.continueintellijextension + +import com.intellij.openapi.util.IconLoader + +object Icons { + @JvmField + val Continue = IconLoader.getIcon("/icons/continue.svg", javaClass) + @JvmField + val Close = IconLoader.getIcon("/icons/close.svg", javaClass) +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/MyBundle.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/MyBundle.kt deleted file mode 100644 index fa1e59dbb..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/MyBundle.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.github.continuedev.continueintellijextension - -import com.intellij.DynamicBundle -import org.jetbrains.annotations.NonNls -import org.jetbrains.annotations.PropertyKey - -@NonNls -private const val BUNDLE = "messages.MyBundle" - -object MyBundle : DynamicBundle(BUNDLE) { - - @JvmStatic - fun message( - @PropertyKey(resourceBundle = BUNDLE) key: String, - vararg params: Any - ) = - getMessage(key, *params) - - @Suppress("unused") - @JvmStatic - fun messagePointer( - @PropertyKey(resourceBundle = BUNDLE) key: String, - vararg params: Any - ) = - getLazyMessage(key, *params) -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt index 8c046c342..43ae74881 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -5,7 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinueExtensi import com.intellij.openapi.actionSystem.ActionPromoter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import org.jetbrains.annotations.NotNull class ContinueActionPromote : ActionPromoter { @@ -13,7 +13,7 @@ class ContinueActionPromote : ActionPromoter { override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? { // For autocomplete actions if (actions.any { it is AcceptAutocompleteAction }) { - val settings = ServiceManager.getService(ContinueExtensionSettings::class.java) + val settings = service() if (settings.continueState.showIDECompletionSideBySide) { return actions.filterIsInstance() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt index 1bd31c463..654b96483 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt @@ -1,7 +1,7 @@ package com.github.continuedev.continueintellijextension.actions import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowManager @@ -28,12 +28,5 @@ fun focusContinueInput(project: Project?) { continuePluginService.ideProtocolClient?.sendHighlightedCode() } -fun getPluginService(project: Project?): ContinuePluginService? { - if (project == null) { - return null - } - return ServiceManager.getService( - project, - ContinuePluginService::class.java - ) -} \ No newline at end of file +fun getPluginService(project: Project?): ContinuePluginService? = + project?.service() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt index e8d3d0788..7fee29ee3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt @@ -1,9 +1,7 @@ package com.github.continuedev.continueintellijextension.activities import com.intellij.openapi.Disposable -import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service -import com.intellij.openapi.project.Project /** * The service is a parent disposable that represents the entire plugin lifecycle @@ -18,15 +16,4 @@ class ContinuePluginDisposable : Disposable { override fun dispose() { } - companion object { - - fun getInstance(): ContinuePluginDisposable { - return ApplicationManager.getApplication().getService(ContinuePluginDisposable::class.java) - } - - fun getInstance(project: Project): ContinuePluginDisposable { - return project.getService(ContinuePluginDisposable::class.java) - } - - } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index d4a9d2201..3aaeef5ed 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -14,7 +14,6 @@ import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.keymap.KeymapManager @@ -122,14 +121,10 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { private fun initializePlugin(project: Project) { val coroutineScope = CoroutineScope(Dispatchers.IO) - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) + val continuePluginService = project.service() coroutineScope.launch { - val settings = - ServiceManager.getService(ContinueExtensionSettings::class.java) + val settings = service() if (!settings.continueState.shownWelcomeDialog) { settings.continueState.shownWelcomeDialog = true // Open tutorial file @@ -270,7 +265,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { EditorFactory.getInstance().eventMulticaster.addSelectionListener( listener, - ContinuePluginDisposable.getInstance(project) + project.service() ) val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 17397f1c8..f4c3fd67f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -7,7 +7,6 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.application.* import com.intellij.openapi.components.Service -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.InlayProperties @@ -64,8 +63,7 @@ class AutocompleteService(private val project: Project) { var lastChangeWasPartialAccept = false fun triggerCompletion(editor: Editor) { - val settings = - ServiceManager.getService(ContinueExtensionSettings::class.java) + val settings = service() if (!settings.continueState.enableTabAutocomplete) { return } @@ -183,7 +181,7 @@ class AutocompleteService(private val project: Project) { } if (isInjectedFile(editor)) return // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled - if (shouldSkipRender(ServiceManager.getService(ContinueExtensionSettings::class.java))) { + if (shouldSkipRender()) { return } @@ -230,9 +228,10 @@ class AutocompleteService(private val project: Project) { } } - private fun shouldSkipRender(settings: ContinueExtensionSettings) = - !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() - + private fun shouldSkipRender(): Boolean { + val settings = service() + return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() + } private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt index 9eba3ce5d..b19baf669 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.autocomplete +import com.github.continuedev.continueintellijextension.Icons import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.intellij.openapi.Disposable @@ -26,7 +27,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), private val animatedIcon = AnimatedIcon.Default() init { - Disposer.register(ContinuePluginDisposable.getInstance(project), this) + Disposer.register(project.service(), this) updateIcon() } @@ -50,7 +51,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), } override fun getIcon(): Icon = if (isLoading) animatedIcon else - IconLoader.getIcon("/icons/continue.svg", javaClass) + Icons.Continue fun setLoading(loading: Boolean) { isLoading = loading 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 66ebac070..0d8e071e4 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 @@ -41,11 +41,12 @@ class MessageTypes { "getTerminalContents", "showToast", "openUrl", - + "isWorkspaceRemote", + // These only come from the GUI for now but should be here to prevent confusion "toggleDevTools", "showTutorial", - + // These are jetbrains only and only come from the GUI for now // But again including for consistency "copyText", @@ -92,6 +93,7 @@ class MessageTypes { "config/updateSharedConfig", "config/updateSelectedModel", "mcp/reloadServer", + "mcp/getPrompt", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index 8cb05dc31..28b648d4a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -10,6 +10,7 @@ import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import kotlinx.coroutines.suspendCancellableCoroutine @@ -44,6 +45,12 @@ class ApplyToFileHandler( return } + // Handle search/replace mode + if (params.isSearchReplace == true) { + handleSearchReplace(editorUtils) + return + } + // Get the LLM configuration for applying edits val llm = fetchApplyLLMConfig() ?: run { ide.showToast(ToastType.ERROR, "Failed to fetch model configuration") @@ -54,6 +61,40 @@ class ApplyToFileHandler( setupAndStreamDiffs(editorUtils, llm) } + /** + * Handle search and replace operations + * + * For search/replace, we always get a full file rewrite of the contents. + * We just need to generate diff lines between the current content and new content, + * then stream them through the existing infrastructure. + */ + private fun handleSearchReplace(editorUtils: EditorUtils) { + // Clear all diff blocks before running the diff stream + diffStreamService.reject(editorUtils.editor) + + // Get current file content and the new content (full rewrite) + val currentContent = editorUtils.getDocumentText() + val newContent = params.text + + // Work with the entire document + val startLine = 0 + val endLine = editorUtils.getLineCount() - 1 + // Create and register the diff stream handler + val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine) + diffStreamService.register(diffStreamHandler, editorUtils.editor) + + // Stream the diffs between current and new content + // For search/replace, we pass the new content as "input" and current as "highlighted" + diffStreamHandler.streamDiffLinesToEditor( + input = newContent, // The new content (full rewrite) + prefix = "", // No prefix since we're rewriting the whole file + highlighted = currentContent, // Current file content + suffix = "", // No suffix since we're rewriting the whole file + modelTitle = null, // No model needed for search/replace instant apply + includeRulesInSystemMessage = false // No LLM involved, just diff generation + ) + } + private fun notifyStreamStarted() { sendApplyStateUpdate(ApplyStateStatus.STREAMING) } @@ -61,10 +102,8 @@ class ApplyToFileHandler( private fun notifyStreamClosed(numDiffs: Int? = 0) { sendApplyStateUpdate(ApplyStateStatus.CLOSED, numDiffs) } - private fun sendApplyStateUpdate( - status: ApplyStateStatus, - numDiffs: Int? = null + status: ApplyStateStatus, numDiffs: Int? = null ) { val payload = ApplyState( streamId = params.streamId, @@ -82,16 +121,11 @@ class ApplyToFileHandler( return try { suspendCancellableCoroutine { continuation -> continuePluginService.coreMessenger?.request( - "config/getSerializedProfileInfo", - null, - null + "config/getSerializedProfileInfo", null, null ) { response -> try { val selectedModels = response.castNestedOrNull>( - "content", - "result", - "config", - "selectedModelByRole" + "content", "result", "config", "selectedModelByRole" ) // If "apply" role model is not found, try "chat" role @@ -143,9 +177,7 @@ class ApplyToFileHandler( } private fun createDiffStreamHandler( - editor: Editor, - startLine: Int, - endLine: Int + editor: Editor, startLine: Int, endLine: Int ): DiffStreamHandler { return DiffStreamHandler( project, @@ -164,28 +196,19 @@ class ApplyToFileHandler( * Factory method to create and execute a new handler for a single apply-to-file operation */ suspend fun apply( - project: Project, - continuePluginService: ContinuePluginService, - ide: IDE, - params: ApplyToFileParams + project: Project, continuePluginService: ContinuePluginService, ide: IDE, params: ApplyToFileParams ) { - val editorUtils = if (EditorUtils.editorFileExist(params.filepath)) - EditorUtils.getOrOpenEditor(project, params.filepath) - else - EditorUtils.getEditorByCreateFile(project, params.filepath) + val editorUtils = + if (EditorUtils.editorFileExist(params.filepath)) EditorUtils.getOrOpenEditor(project, params.filepath) + else EditorUtils.getEditorByCreateFile(project, params.filepath) - val diffStreamService = project.getService(DiffStreamService::class.java) + val diffStreamService = project.service() val handler = ApplyToFileHandler( - project, - continuePluginService, - ide, - params, - editorUtils, - diffStreamService + project, continuePluginService, ide, params, editorUtils, diffStreamService ) handler.handleApplyToFile() } } -} \ No newline at end of file +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index ac65237c6..d419e2f7c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -43,7 +43,9 @@ class CoreMessenger( val message = gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data)) responseListeners[id] = onResponse - write(message) + coroutineScope.launch(Dispatchers.IO) { + write(message) + } } private fun handleMessage(json: String) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt index 417fbb8d4..c0eeec508 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt @@ -9,7 +9,7 @@ import com.intellij.diff.contents.DiffContent import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project @@ -18,7 +18,6 @@ import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import java.awt.Toolkit import java.io.File -import java.net.URI import java.nio.file.Paths import javax.swing.Action import javax.swing.JComponent @@ -89,11 +88,7 @@ class DiffManager(private val project: Project) : DumbAware { FileDocumentManager.getInstance().saveDocument(document) // Notify server of acceptance - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) - continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex) + project.service().ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex) // Clean up state cleanUpFile(file) @@ -102,10 +97,7 @@ class DiffManager(private val project: Project) : DumbAware { fun rejectDiff(file2: String?) { val file = (file2 ?: lastFile2) ?: return val diffInfo = diffInfoMap[file] ?: return - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) + val continuePluginService = project.service() continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex) continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex) continuePluginService.coreMessenger?.request("cancelApply", null, null) {} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt index 0ee4c2bd0..3a01f05fc 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -166,6 +166,9 @@ class GetTheme { val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?: editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor + // Use editor background with slight tint for code blocks + val textCodeBlockBackground = slightChange(editorBackground, 3) ?: editorBackground + // These should match the keys in GUI's theme.ts val theme = mapOf( "background" to background, @@ -197,6 +200,7 @@ class GetTheme { "warning" to warningColor, "error" to errorColor, "link" to link, + "textCodeBlockBackground" to textCodeBlockBackground, "accent" to accentColor, "find-match" to findMatchBackground, "find-match-selected" to findMatchSelectedBackground, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index ddbb5f738..08a5e8d18 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.activities.showTutorial import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.protocol.* import com.github.continuedev.continueintellijextension.services.* import com.github.continuedev.continueintellijextension.utils.* @@ -46,7 +47,7 @@ class IdeProtocolClient( init { // Setup config.json / config.ts save listeners VirtualFileManager.getInstance().addAsyncFileListener( - AsyncFileSaveListener(continuePluginService), ContinuePluginDisposable.getInstance(project) + AsyncFileSaveListener(continuePluginService), project.service() ) } @@ -67,8 +68,7 @@ class IdeProtocolClient( } "jetbrains/isOSREnabled" -> { - val isOSREnabled = - ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = service().continueState.enableOSR respond(isOSREnabled) } @@ -202,6 +202,11 @@ class IdeProtocolClient( respond(contents) } + "isWorkspaceRemote" -> { + val isRemote = ide.isWorkspaceRemote() + respond(isRemote) + } + "saveFile" -> { val params = Gson().fromJson( dataElement.toString(), @@ -463,8 +468,10 @@ class IdeProtocolClient( println("Unknown message type: $messageType") } } - } catch (error: Exception) { - ide.showToast(ToastType.ERROR, " Error handling message of type $messageType: $error") + } catch (exception: Exception) { + val exceptionMessage = "Error handling message of type $messageType: $exception" + service().report(exception, exceptionMessage) + ide.showToast(ToastType.ERROR, exceptionMessage) } } } @@ -473,7 +480,7 @@ class IdeProtocolClient( val editor = EditorUtils.getEditor(project) val rif = editor?.getHighlightedRIF() ?: return - val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents( + val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents( filepath = rif.filepath, range = rif.range, contents = rif.contents diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 9ceca69f3..2dfc3e3e1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -1,9 +1,9 @@ package com.github.continuedev.continueintellijextension.`continue` import com.github.continuedev.continueintellijextension.* -import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath import com.github.continuedev.continueintellijextension.constants.ContinueConstants -import com.github.continuedev.continueintellijextension.`continue`.GitService +import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.* @@ -11,7 +11,6 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.ide.BrowserUtil -import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity import com.intellij.notification.NotificationAction @@ -19,6 +18,7 @@ import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.extensions.PluginId @@ -38,9 +38,7 @@ import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.InputStreamReader -import java.net.URI import java.nio.charset.Charset -import java.nio.file.Paths class IntelliJIDE( private val project: Project, @@ -297,23 +295,26 @@ class IntelliJIDE( continuePluginService.diffManager?.showDiff(filepath, newContents, stepIndex) } - override suspend fun getOpenFiles(): List { - val fileEditorManager = FileEditorManager.getInstance(project) - return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList() - } - - override suspend fun getCurrentFile(): Map? { - val fileEditorManager = FileEditorManager.getInstance(project) - val editor = fileEditorManager.selectedTextEditor - val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } - return virtualFile?.toUriOrNull()?.let { - mapOf( - "path" to it, - "contents" to editor.document.text, - "isUntitled" to false - ) + override suspend fun getOpenFiles(): List = + withContext(Dispatchers.EDT) { + FileEditorManager.getInstance(project).openFiles + .mapNotNull { it.toUriOrNull() } + .toList() + } + + override suspend fun getCurrentFile(): Map? = + withContext(Dispatchers.EDT) { + val fileEditorManager = FileEditorManager.getInstance(project) + val document = fileEditorManager.selectedTextEditor?.document + val virtualFile = document?.let { FileDocumentManager.getInstance().getFile(it) } + virtualFile?.toUriOrNull()?.let { + mapOf( + "path" to it, + "contents" to document.text, + "isUntitled" to false + ) + } } - } override suspend fun getPinnedFiles(): List { // Returning open files for now as per existing code @@ -344,11 +345,10 @@ class IntelliJIDE( command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout return results.split("\n") - } catch (e: Exception) { - showToast( - ToastType.ERROR, - "Error executing ripgrep: ${e.message}" - ) + } catch (exception: Exception) { + val message = "Error executing ripgrep: ${exception.message}" + service().report(exception, message) + showToast(ToastType.ERROR, message) return emptyList() } } else { @@ -386,11 +386,10 @@ class IntelliJIDE( command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout - } catch (e: Exception) { - showToast( - ToastType.ERROR, - "Error executing ripgrep: ${e.message}" - ) + } catch (exception: Exception) { + val message = "Error executing ripgrep: ${exception.message}" + service().report(exception, message) + showToast(ToastType.ERROR, message) return "Error: Unable to execute ripgrep command." } } else { @@ -530,10 +529,9 @@ class IntelliJIDE( } val deferred = CompletableDeferred() - val icon = IconLoader.getIcon("/icons/continue.svg", javaClass) val notification = NotificationGroupManager.getInstance().getNotificationGroup("Continue") - .createNotification(message, notificationType).setIcon(icon) + .createNotification(message, notificationType).setIcon(Icons.Continue) val buttonTexts = otherParams.filterIsInstance().toTypedArray() buttonTexts.forEach { buttonText -> diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 67e49a87f..52abfe00c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -7,7 +7,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.undo.UndoManager -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.RangeHighlighter @@ -42,7 +42,6 @@ class DiffStreamHandler( private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false private val unfinishedHighlighters: MutableList = mutableListOf() - private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) @@ -62,10 +61,10 @@ class DiffStreamHandler( numDiffs = diffBlocks.size, filepath = virtualFile?.url, fileContent = "not implemented", - toolCallId = toolCallId?.toString() + toolCallId = toolCallId ) - continuePluginService.sendToWebview("updateApplyState", payload) + project.service().sendToWebview("updateApplyState", payload) } fun acceptAll() { @@ -96,13 +95,13 @@ class DiffStreamHandler( prefix: String, highlighted: String, suffix: String, - modelTitle: String, + modelTitle: String?, includeRulesInSystemMessage: Boolean ) { isRunning = true sendUpdate(ApplyStateStatus.STREAMING) - continuePluginService.coreMessenger?.request( + project.service().coreMessenger?.request( "streamDiffLines", StreamDiffLinesPayload( input = input, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt index 391c0423d..204994f6b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt @@ -46,6 +46,13 @@ class EditorUtils(val editor: Editor) { return editor.document.lineCount } + /** + * Gets the full text content of the document + */ + fun getDocumentText(): String { + return editor.document.text + } + /** * Inserts text at the specified position in the document */ @@ -62,7 +69,6 @@ class EditorUtils(val editor: Editor) { insertTextAtPos(0, text) } - /** * Scrolls the editor to make the specified line visible */ @@ -165,7 +171,6 @@ class EditorUtils(val editor: Editor) { } } } - val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null return EditorUtils(editor) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt index ee0499067..f5e8b81ee 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.editor +import com.github.continuedev.continueintellijextension.Icons import com.github.continuedev.continueintellijextension.`continue`.GetTheme import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService @@ -357,8 +358,7 @@ class CustomPanel( } private fun createCloseButton(): JComponent { - val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) - return JLabel(closeIcon).apply { + return JLabel(Icons.Close).apply { background = Color(0, 0, 0, 0) border = JBUI.Borders.empty(2, 6, 2, 0) toolTipText = "`esc` to cancel" diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt new file mode 100644 index 000000000..b1fdae571 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt @@ -0,0 +1,50 @@ +package com.github.continuedev.continueintellijextension.error + +import com.intellij.ide.plugins.PluginManagerCore +import com.intellij.openapi.application.ApplicationInfo +import com.intellij.openapi.components.Service +import com.intellij.openapi.diagnostic.Attachment +import com.intellij.openapi.diagnostic.Logger +import com.intellij.openapi.extensions.PluginId +import com.intellij.ui.jcef.JBCefApp +import io.sentry.Hint +import io.sentry.Sentry +import io.sentry.SentryEvent +import io.sentry.protocol.Message + +private typealias SentryAttachment = io.sentry.Attachment + +@Service +class ContinueErrorService { + private val log = Logger.getInstance(ContinueErrorService::class.java) + + init { + Sentry.init { config -> + config.dsn = SENTRY_DSN + config.isSendDefaultPii = false + config.setTag("ide_version", ApplicationInfo.getInstance().build.asString()) + config.setTag("jcef_supported", JBCefApp.isSupported().toString()) + config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version) + } + } + + fun report( + throwable: Throwable, + message: String? = null, + attachments: List? = null + ) { + val sentryEvent = SentryEvent() + sentryEvent.throwable = throwable + sentryEvent.message = Message().apply { this.message = message } + val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) }) + Sentry.captureEvent(sentryEvent, hint) + log.warn("Problem sent to Sentry: $message", throwable) + } + + private companion object { + private const val PLUGIN_ID = "com.github.continuedev.continueintellijextension" + private const val SENTRY_DSN = + "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016" + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt new file mode 100644 index 000000000..3f30c17a8 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt @@ -0,0 +1,39 @@ +package com.github.continuedev.continueintellijextension.error + +import com.intellij.diagnostic.IdeaReportingEvent +import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.ErrorReportSubmitter +import com.intellij.openapi.diagnostic.IdeaLoggingEvent +import com.intellij.openapi.diagnostic.SubmittedReportInfo +import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus +import com.intellij.util.Consumer +import java.awt.Component + +class ContinueErrorSubmitter : ErrorReportSubmitter() { + + override fun getReportActionText() = + "Report to Continue" + + override fun submit( + events: Array, + additionalInfo: String?, + parentComponent: Component, + consumer: Consumer + ): Boolean { + try { + val event = events.filterIsInstance() + .firstOrNull() ?: return false + service().report( + throwable = event.data.throwable, + message = additionalInfo ?: event.data.message, + attachments = event.data.allAttachments + ) + } catch (_: Exception) { + consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED)) + return false + } + consumer.consume(SubmittedReportInfo(SubmissionStatus.NEW_ISSUE)) + return true + } + +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/VirtualFileListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/VirtualFileListener.kt deleted file mode 100644 index e69de29bb..000000000 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index a2a751f2b..7ed69f6eb 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -8,10 +8,10 @@ data class ApplyToFileParams( val text: String, val streamId: String, val filepath: String?, - val toolCallId: String? + val toolCallId: String?, + val isSearchReplace: Boolean? = null ) data class InsertAtCursorParams( val text: String ) - diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 908bf3f8d..4e4117985 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -111,7 +111,7 @@ open class ContinueExtensionSettings : PersistentStateComponent() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 43a468cf7..7fd13e177 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -9,30 +9,21 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser +import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* import com.intellij.ui.jcef.JBCefClient.Properties -import com.intellij.util.application import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter class ContinueBrowser(val project: Project, url: String) { - private fun registerAppSchemeHandler() { - CefApp.getInstance().registerSchemeHandlerFactory( - "http", - "continue", - CustomSchemeHandlerFactory() - ) - } val browser: JBCefBrowser - val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java) - init { - val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = service().continueState.enableOSR this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { // To avoid using System.setProperty to affect other plugins, @@ -43,7 +34,7 @@ class ContinueBrowser(val project: Project, url: String) { } registerAppSchemeHandler() - Disposer.register(ContinuePluginDisposable.getInstance(project), browser) + Disposer.register(project.service(), browser) // Listen for events sent from browser val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!) @@ -60,7 +51,7 @@ class ContinueBrowser(val project: Project, url: String) { } if (PASS_THROUGH_TO_CORE.contains(messageType)) { - continuePluginService.coreMessenger?.request(messageType, data, messageId, respond) + project.service().coreMessenger?.request(messageType, data, messageId, respond) return@addHandler null } @@ -75,7 +66,7 @@ class ContinueBrowser(val project: Project, url: String) { } if (msg != null) { - continuePluginService.ideProtocolClient?.handleMessage(msg, respondToWebview) + project.service().ideProtocolClient?.handleMessage(msg, respondToWebview) } null @@ -99,7 +90,7 @@ class ContinueBrowser(val project: Project, url: String) { // Load the url only after the protocolClient is initialized, // otherwise some messages will be lost, which are some configurations when the page is loaded. // Moreover, we should add LoadHandler before loading the url. - continuePluginService.onProtocolClientInitialized { + project.service().onProtocolClientInitialized { browser.loadURL(url) } @@ -138,6 +129,14 @@ class ContinueBrowser(val project: Project, url: String) { } } + private fun registerAppSchemeHandler() { + CefApp.getInstance().registerSchemeHandlerFactory( + "http", + "continue", + CustomSchemeHandlerFactory() + ) + } + private fun buildJavaScript(jsonData: String): String { return """window.postMessage($jsonData, "*");""" } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index d0d44655c..492356ed3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -3,13 +3,13 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory -import javax.swing.* +import javax.swing.JComponent const val JS_QUERY_POOL_SIZE = "200" @@ -52,9 +52,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl val browser = ContinueBrowser(project, url) - val continuePluginService = - ServiceManager.getService(project, ContinuePluginService::class.java) - continuePluginService.continuePluginWindow = this + project.service().continuePluginWindow = this browser } diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 92005ffdc..aa9a81989 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -19,7 +19,7 @@ - @@ -36,11 +36,7 @@ displayType="BALLOON"/> - - - messages.MyBundle - - + + + diff --git a/extensions/intellij/src/main/resources/messages/MyBundle.properties b/extensions/intellij/src/main/resources/messages/MyBundle.properties deleted file mode 100644 index 2e041d8b9..000000000 --- a/extensions/intellij/src/main/resources/messages/MyBundle.properties +++ /dev/null @@ -1,3 +0,0 @@ -projectService=Project service: {0} -randomLabel=The random number is: {0} -shuffle=Shuffle diff --git a/extensions/intellij/src/main/resources/tool-window-icon.svg b/extensions/intellij/src/main/resources/tool-window-icon.svg deleted file mode 100644 index ab3f4d8bb..000000000 --- a/extensions/intellij/src/main/resources/tool-window-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/extensions/intellij/src/main/resources/tool-window-icon_dark.svg b/extensions/intellij/src/main/resources/tool-window-icon_dark.svg deleted file mode 100644 index 441f5ab4b..000000000 --- a/extensions/intellij/src/main/resources/tool-window-icon_dark.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/extensions/vscode/.vscodeignore b/extensions/vscode/.vscodeignore index 387be8ba5..f2179a2c5 100644 --- a/extensions/vscode/.vscodeignore +++ b/extensions/vscode/.vscodeignore @@ -18,7 +18,6 @@ node_modules/** manual-testing-sandbox esbuild.js -esbuild.test.mjs importMetaUrl.js scripts e2e diff --git a/extensions/vscode/e2e/README.md b/extensions/vscode/e2e/README.md index ac0cc22ea..02e8ef06d 100644 --- a/extensions/vscode/e2e/README.md +++ b/extensions/vscode/e2e/README.md @@ -31,3 +31,11 @@ All e2e tests are separated (by folder) into - Is your `data-testid` or selector actually just wrong? - Are you inconsistently getting different behaviors? You can try adding a `TestUtils.waitForTimeout` between two events if you think it's caused by a race condition. Note that this may lead to flake down the road. - Alternatively, you can add a `TestUtils.waitForSuccess` + +### How is it connecting to the LLM? + +- This depends on the model provider written inside the `test-continue/config.json` and `test-continue/config.yaml`. If the model provider is `mock`, it will use `MockLLM`, and if it uses `test`, it will use `TestLLM`. + +### Quirks + +- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`. \ No newline at end of file diff --git a/extensions/vscode/e2e/TestUtils.ts b/extensions/vscode/e2e/TestUtils.ts index 5b62edaa7..3c27e3621 100644 --- a/extensions/vscode/e2e/TestUtils.ts +++ b/extensions/vscode/e2e/TestUtils.ts @@ -1,9 +1,26 @@ import { expect } from "chai"; import { Key } from "vscode-extension-tester"; +import { access, constants } from 'fs/promises'; +import * as path from "path"; import { DEFAULT_TIMEOUT } from "./constants"; export class TestUtils { + public static CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? ""; + + public static getGlobalContextFilePath(): string { + return path.join(TestUtils.CONTINUE_GLOBAL_DIR, "index", "globalContext.json"); + } + + public static async fileExists(path: string): Promise { + try { + await access(path, constants.F_OK); + return true; + } catch { + return false; + } + } + /** * In many cases it might be more useful to use existing Selenium * utilities. For example: diff --git a/extensions/vscode/e2e/actions/NextEdit.actions.ts b/extensions/vscode/e2e/actions/NextEdit.actions.ts new file mode 100644 index 000000000..4432a278c --- /dev/null +++ b/extensions/vscode/e2e/actions/NextEdit.actions.ts @@ -0,0 +1,60 @@ +import { expect } from "chai"; +import { TextEditor, VSBrowser, Workbench } from "vscode-extension-tester"; + +import { DEFAULT_TIMEOUT } from "../constants"; +import { NextEditSelectors } from "../selectors/NextEdit.selectors"; +import { TestUtils } from "../TestUtils"; + +export class NextEditActions { + /** + * Test accepting a Next Edit suggestion with Tab. + */ + public static async acceptNextEditSuggestion(editor: TextEditor) { + const hasDecoration = await NextEditActions.forceNextEdit(editor); + expect(hasDecoration).to.be.true; + + await new Workbench().executeCommand("Continue: Accept Next Edit Suggestion"); + + // Check if HELLO is written into the editor. + const editorText = await editor.getTextAtLine(1); + + return editorText === "HELLO"; + } + + /** + * Test rejecting a Next Edit suggestion with Esc. + */ + public static async rejectNextEditSuggestion(editor: TextEditor) { + const hasDecoration = await NextEditActions.forceNextEdit(editor); + expect(hasDecoration).to.be.true; + + await new Workbench().executeCommand("Continue: Hide Next Edit Suggestion"); + + // Check if the editor text didn't change. + const editorText = await editor.getText(); + + return editorText === "def main():\n "; + } + + /** + * Force a Next Edit suggestion using command. + */ + public static async forceNextEdit(editor: TextEditor): Promise { + await editor.setText("def main():\n "); + await editor.moveCursor(2, 4); + + await new Workbench().executeCommand("Continue: Force Next Edit"); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL); + + const svgDecoration = await TestUtils.waitForSuccess( + () => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver), + DEFAULT_TIMEOUT.XL + ); + + return svgDecoration !== null; + } + + public static async reload(): Promise { + await new Workbench().executeCommand('workbench.action.reloadWindow'); + } +} diff --git a/extensions/vscode/e2e/constants.ts b/extensions/vscode/e2e/constants.ts index e11f7e0db..d2fb8f422 100644 --- a/extensions/vscode/e2e/constants.ts +++ b/extensions/vscode/e2e/constants.ts @@ -5,4 +5,5 @@ export const DEFAULT_TIMEOUT = { SM: BASELINE * 0.5, MD: BASELINE, XL: BASELINE * 5, + XXL: BASELINE * 7, }; diff --git a/extensions/vscode/e2e/selectors/NextEdit.selectors.ts b/extensions/vscode/e2e/selectors/NextEdit.selectors.ts new file mode 100644 index 000000000..3fb6f0083 --- /dev/null +++ b/extensions/vscode/e2e/selectors/NextEdit.selectors.ts @@ -0,0 +1,19 @@ +import { By, WebDriver } from "vscode-extension-tester"; + +export class NextEditSelectors { + /** + * Get the SVG decoration element if present (for next edit). + */ + public static async getSvgDecoration(driver: WebDriver) { + try { + const decorations = await driver.findElement( + // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") + By.css("[class*='TextEditorDecorationType']") + ); + return decorations ?? null; + } catch (error) { + console.error("Error finding SVG decoration:", error); + return null; + } + } +} \ No newline at end of file diff --git a/extensions/vscode/e2e/test-continue-yaml/config.yaml b/extensions/vscode/e2e/test-continue-yaml/config.yaml index 9dfe3ed0e..31d2c4985 100644 --- a/extensions/vscode/e2e/test-continue-yaml/config.yaml +++ b/extensions/vscode/e2e/test-continue-yaml/config.yaml @@ -37,7 +37,7 @@ models: - id: test_id type: function function: - name: builtin_view_diff + name: view_diff - REPEAT_LAST_MSG roles: - chat diff --git a/extensions/vscode/e2e/test-continue/config.json b/extensions/vscode/e2e/test-continue/config.json index e6b610f6a..fbe78fa0a 100644 --- a/extensions/vscode/e2e/test-continue/config.json +++ b/extensions/vscode/e2e/test-continue/config.json @@ -36,7 +36,7 @@ "id": "test_id", "type": "function", "function": { - "name": "builtin_view_diff" + "name": "view_diff" } } ] diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index b05302226..a709266ec 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -304,7 +304,7 @@ describe("GUI Test", () => { }).timeout(DEFAULT_TIMEOUT.MD * 100); it("should call tool after approval", async () => { - await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2); + await GUIActions.toggleToolPolicy(view, "view_diff", 2); const [messageInput] = await GUISelectors.getMessageInputFields(view); await messageInput.sendKeys("Hello"); @@ -325,7 +325,7 @@ describe("GUI Test", () => { }).timeout(DEFAULT_TIMEOUT.XL); it("should cancel tool", async () => { - await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2); + await GUIActions.toggleToolPolicy(view, "view_diff", 2); const [messageInput] = await GUISelectors.getMessageInputFields(view); await messageInput.sendKeys("Hello"); diff --git a/extensions/vscode/e2e/tests/NextEdit.test.ts b/extensions/vscode/e2e/tests/NextEdit.test.ts new file mode 100644 index 000000000..2541feb0b --- /dev/null +++ b/extensions/vscode/e2e/tests/NextEdit.test.ts @@ -0,0 +1,120 @@ +import { expect } from "chai"; +import * as fs from "fs/promises"; +import { EditorView, TextEditor } from "vscode-extension-tester"; + +import { GlobalActions } from "../actions/Global.actions"; +import { NextEditActions } from "../actions/NextEdit.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { TestUtils } from "../TestUtils"; + +describe("Next Edit", () => { + let editor: TextEditor; + + before(async function () { + // this.timeout(DEFAULT_TIMEOUT.XL); + + const globalContextPath = TestUtils.getGlobalContextFilePath(); + + // Update config.json to add optInNextEditFeature. + // globalContext.json does not exist in CI before this test runs. + if (await TestUtils.fileExists(globalContextPath)) { + const globalContext = await fs.readFile(globalContextPath, "utf8"); + const sharedConfig = JSON.parse(globalContext).sharedConfig; + + const sharedConfigWithNextEditEnabled = { + ...sharedConfig, + "optInNextEditFeature": true + }; + + const globalContextWithNextEditEnabled = { + ...JSON.parse(globalContext), + "sharedConfig": sharedConfigWithNextEditEnabled + }; + + await fs.writeFile(globalContextPath, JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8"); + } else { + await fs.writeFile( + globalContextPath, + JSON.stringify( + { + sharedConfig: { + optInNextEditFeature: true + }, + selectedModelsByProfileId: { + local: { + chat: "TEST LLM", + edit: "TEST LLM", + apply: "TEST LLM", + embed: "Transformers.js (Built-In)", + autocomplete: "TEST LLM", + rerank: null, + summarize: null + } + } + }, + null, + 2, + ), + ); + } + + await NextEditActions.reload(); + }).timeout(DEFAULT_TIMEOUT.XL); + + beforeEach(async function () { + // this.timeout(DEFAULT_TIMEOUT.XL); + + await GlobalActions.openTestWorkspace(); + ({ editor } = await GlobalActions.createAndOpenNewTextFile()); + }).timeout(DEFAULT_TIMEOUT.XL); + + afterEach(async function () { + // this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.clearText(); + await new EditorView().closeAllEditors(); + }).timeout(DEFAULT_TIMEOUT.XL); + + after(async function () { + // this.timeout(DEFAULT_TIMEOUT.XL); + + // Update config.json to delete optInNextEditFeature. + const globalContext = await fs.readFile(TestUtils.getGlobalContextFilePath(), "utf8"); + const sharedConfig = JSON.parse(globalContext).sharedConfig; + + const sharedConfigWithoutNextEdit = { ...sharedConfig }; + delete sharedConfigWithoutNextEdit.optInNextEditFeature; + + const globalContextWithNextEditEnabled = { + ...JSON.parse(globalContext), + "sharedConfig": sharedConfigWithoutNextEdit + }; + + await fs.writeFile(TestUtils.getGlobalContextFilePath(), JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8"); + await NextEditActions.reload(); + }).timeout(DEFAULT_TIMEOUT.XL); + + // it("Should enable Next Edit feature in settings", async () => { + // expect(false).to.be.true; + // }).timeout(DEFAULT_TIMEOUT.XL); + + // it("Should check that autocomplete is disabled when next edit is enabled", async () => { + // expect(false).to.be.true; + // }).timeout(DEFAULT_TIMEOUT.XL); + + it("Should force a Next Edit", async () => { + const hasDecoration = await NextEditActions.forceNextEdit(editor); + expect(hasDecoration).to.be.true; + }).timeout(DEFAULT_TIMEOUT.XXL); + + it("Should accept Next Edit suggestion with Tab", async () => { + const accepted = await NextEditActions.acceptNextEditSuggestion(editor); + expect(accepted).to.be.true; + }).timeout(DEFAULT_TIMEOUT.XXL); + + it("Should reject Next Edit suggestion with Esc", async () => { + const rejected = await NextEditActions.rejectNextEditSuggestion(editor); + expect(rejected).to.be.true; + }).timeout(DEFAULT_TIMEOUT.XXL); + +}); \ No newline at end of file diff --git a/extensions/vscode/esbuild.test.mjs b/extensions/vscode/esbuild.test.mjs deleted file mode 100644 index 3d6ca8b94..000000000 --- a/extensions/vscode/esbuild.test.mjs +++ /dev/null @@ -1,67 +0,0 @@ -import * as esbuild from "esbuild"; -import glob from "glob"; - -/** - * Bundles tests into multiple files, runTestOnVSCodeHost is then run using node runTestOnVSCodeHost.js - * It downloads vscode, starts it and passes test file to run - mochaRunner.js - * mochaRunner.js then runs tests using Mocha class - */ - -console.log("Bundling tests..."); - -// Bundles script to run tests on VSCode host + mocha runner that will be invoked from within VSCode host -await esbuild.build({ - entryPoints: [ - // Runs mocha runner on VSCode host using runTests from @vscode/test-electron - "src/test/runner/runTestOnVSCodeHost.ts", - - // Runs the bundled tests using Mocha class - "src/test/runner/mochaRunner.ts", - ], - bundle: true, - outdir: "out", - - external: [ - "vscode", - - // Its important to externalize mocha, otherwise mocha seems to be not initialized properly when running tests - // Example warning by esbuild when mocha is not externalized: - // [WARNING] "./reporters/parallel-buffered" should be marked as external for use with "require.resolve" [require-resolve-not-external] - "mocha", - ], - format: "cjs", - platform: "node", - sourcemap: true, - loader: { - // eslint-disable-next-line @typescript-eslint/naming-convention - ".node": "file", - }, -}); - -/** - * Note: Bundling is done to work around import issues, for example with fkill that does not provide cjs module. - * Rather than figuring out a combination of tsconfig.json that would work, I decided to bundle tests instead. - */ -await esbuild.build({ - // Tests can be added anywhere in src folder - entryPoints: glob.sync("src/**/*.test.ts"), - bundle: true, - outdir: "out", - external: [ - "vscode", - - // Its important to externalize mocha, otherwise mocha seems to be not initialized properly when running tests - "mocha", - ], - format: "cjs", - platform: "node", - sourcemap: true, - loader: { - // eslint-disable-next-line @typescript-eslint/naming-convention - ".node": "file", - }, - // To allow import.meta.path for transformers.js - // https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483 - inject: ["./scripts/importMetaUrl.js"], - define: { "import.meta.url": "importMetaUrl" }, -}); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 7e3e3ff06..0f87e013c 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,22 +1,19 @@ { "name": "continue", - "version": "1.1.52", + "version": "1.1.55", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.52", + "version": "1.1.55", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", "@continuedev/fetch": "^1.0.10", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", - "@types/node-fetch": "^2.6.11", - "@types/uuid": "^9.0.8", "@vscode/ripgrep": "^1.15.9", - "@vscode/test-electron": "^2.3.9", "axios": "^1.2.5", "core": "file:../../core", "cors": "^2.8.5", @@ -38,6 +35,7 @@ "jsdom": "^24.0.0", "lru-cache": "^11.0.2", "minisearch": "^7.0.0", + "mocha": "^11.7.1", "monaco-editor": "^0.45.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", "ncp": "^2.0.0", @@ -70,11 +68,12 @@ "@types/cors": "^2.8.17", "@types/express": "^4.17.21", "@types/follow-redirects": "^1.14.4", - "@types/glob": "^8.0.0", - "@types/mocha": "^10.0.6", + "@types/mocha": "^10.0.10", "@types/node": "16.x", + "@types/node-fetch": "^2.6.12", "@types/react-dom": "^18.2.4", "@types/request": "^2.48.8", + "@types/uuid": "^10.0.0", "@types/vscode": "1.70", "@types/ws": "^8.5.4", "@typescript-eslint/eslint-plugin": "^5.45.0", @@ -84,9 +83,7 @@ "esbuild": "0.17.19", "esbuild-visualizer": "^0.6.0", "eslint": "^8.28.0", - "glob": "^8.0.3", "json-schema-to-typescript": "^12.0.0", - "mocha": "^10.4.0", "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", @@ -199,6 +196,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" @@ -2448,16 +2446,6 @@ "@types/node": "*" } }, - "node_modules/@types/glob": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/@types/glob/-/glob-8.1.0.tgz", - "integrity": "sha512-IO+MJPVhoqz+28h1qLAcBEH2+xHMK6MTyHJc7MTnnYb6wsoLR29POVGJ7LycmVXIqyy/4/2ShP5sUwTXuOwb/w==", - "dev": true, - "dependencies": { - "@types/minimatch": "^5.1.2", - "@types/node": "*" - } - }, "node_modules/@types/hast": { "version": "2.3.10", "resolved": "https://registry.npmjs.org/@types/hast/-/hast-2.3.10.tgz", @@ -2542,10 +2530,11 @@ "dev": true }, "node_modules/@types/mocha": { - "version": "10.0.9", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.9.tgz", - "integrity": "sha512-sicdRoWtYevwxjOHNMPTl3vSfJM6oyW8o1wXeI7uww6b6xHg8eBznQDNSGBCDJmsE8UMxP05JgZRtsKbTqt//Q==", - "dev": true + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz", + "integrity": "sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q==", + "dev": true, + "license": "MIT" }, "node_modules/@types/ms": { "version": "0.7.34", @@ -2558,9 +2547,11 @@ "integrity": "sha512-ia7V9a2FnhUFfetng4/sRPBMTwHZUkPFY736rb1cg9AgG7MZdR97q7/nLR9om+sq5f1la9C857E0l/nrI0RiFQ==" }, "node_modules/@types/node-fetch": { - "version": "2.6.11", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz", - "integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==", + "version": "2.6.12", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.12.tgz", + "integrity": "sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA==", + "dev": true, + "license": "MIT", "dependencies": { "@types/node": "*", "form-data": "^4.0.0" @@ -2717,9 +2708,11 @@ "integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==" }, "node_modules/@types/uuid": { - "version": "9.0.8", - "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", - "integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==" + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "dev": true, + "license": "MIT" }, "node_modules/@types/vscode": { "version": "1.70.0", @@ -3088,136 +3081,6 @@ "yauzl": "^2.9.2" } }, - "node_modules/@vscode/test-electron": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.4.1.tgz", - "integrity": "sha512-Gc6EdaLANdktQ1t+zozoBVRynfIsMKMc94Svu1QreOBC8y76x4tvaK32TljrLi1LI2+PK58sDVbL7ALdqf3VRQ==", - "dependencies": { - "http-proxy-agent": "^7.0.2", - "https-proxy-agent": "^7.0.5", - "jszip": "^3.10.1", - "ora": "^7.0.1", - "semver": "^7.6.2" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@vscode/test-electron/node_modules/chalk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", - "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/@vscode/test-electron/node_modules/cli-cursor": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", - "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", - "dependencies": { - "restore-cursor": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vscode/test-electron/node_modules/is-interactive": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", - "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vscode/test-electron/node_modules/is-unicode-supported": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", - "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vscode/test-electron/node_modules/log-symbols": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-5.1.0.tgz", - "integrity": "sha512-l0x2DvrW294C9uDCoQe1VSU4gf529FkSZ6leBl4TiqZH/e+0R7hSfHQBNut2mNygDgHwvYHfFLn6Oxb3VWj2rA==", - "dependencies": { - "chalk": "^5.0.0", - "is-unicode-supported": "^1.1.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vscode/test-electron/node_modules/ora": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/ora/-/ora-7.0.1.tgz", - "integrity": "sha512-0TUxTiFJWv+JnjWm4o9yvuskpEJLXTcng8MJuKd+SzAzp2o+OP3HWqNhB4OdJRt1Vsd9/mR0oyaEYlOnL7XIRw==", - "dependencies": { - "chalk": "^5.3.0", - "cli-cursor": "^4.0.0", - "cli-spinners": "^2.9.0", - "is-interactive": "^2.0.0", - "is-unicode-supported": "^1.3.0", - "log-symbols": "^5.1.0", - "stdin-discarder": "^0.1.0", - "string-width": "^6.1.0", - "strip-ansi": "^7.1.0" - }, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vscode/test-electron/node_modules/restore-cursor": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", - "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", - "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vscode/test-electron/node_modules/string-width": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-6.1.0.tgz", - "integrity": "sha512-k01swCJAgQmuADB0YIc+7TuatfNvTBVOoaUWJjTB9R4VJzR5vNWzf5t42ESVZFPS8xTySF7CAdV4t/aaIm3UnQ==", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^10.2.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/@vscode/vsce": { "version": "2.32.0", "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-2.32.0.tgz", @@ -3594,15 +3457,6 @@ "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ansi-colors": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", - "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -3741,8 +3595,7 @@ "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, "node_modules/array-back": { "version": "3.1.0", @@ -4038,8 +3891,7 @@ "node_modules/browser-stdout": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", - "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", - "dev": true + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==" }, "node_modules/buffer": { "version": "5.7.1", @@ -4307,7 +4159,6 @@ "version": "6.3.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, "engines": { "node": ">=10" }, @@ -5156,7 +5007,8 @@ "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true }, "node_modules/cors": { "version": "2.8.5", @@ -5329,7 +5181,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", - "dev": true, "engines": { "node": ">=10" }, @@ -5935,7 +5786,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, "engines": { "node": ">=10" }, @@ -6630,7 +6480,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" @@ -6665,7 +6514,6 @@ "version": "5.0.2", "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", - "dev": true, "bin": { "flat": "cli.js" } @@ -7278,7 +7126,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", - "dev": true, "bin": { "he": "bin/he" } @@ -7550,7 +7397,8 @@ "node_modules/immediate": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", - "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==" + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "dev": true }, "node_modules/immer": { "version": "9.0.21", @@ -7955,7 +7803,8 @@ "node_modules/isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true }, "node_modules/isexe": { "version": "2.0.0", @@ -8061,7 +7910,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, "dependencies": { "argparse": "^2.0.1" }, @@ -8301,6 +8149,7 @@ "version": "3.10.1", "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "dev": true, "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", @@ -8391,6 +8240,7 @@ "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dev": true, "dependencies": { "immediate": "~3.0.5" } @@ -8441,7 +8291,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, "dependencies": { "p-locate": "^5.0.0" }, @@ -9436,30 +9285,30 @@ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" }, "node_modules/mocha": { - "version": "10.8.2", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.8.2.tgz", - "integrity": "sha512-VZlYo/WE8t1tstuRmqgeyBgCbJc/lEdopaa+axcKzTBJ+UIdlAB9XnmvTCAH4pwR4ElNInaedhEBmZD8iCSVEg==", - "dev": true, + "version": "11.7.1", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.1.tgz", + "integrity": "sha512-5EK+Cty6KheMS/YLPPMJC64g5V61gIR25KsRItHw6x4hEKT6Njp1n9LOlH4gpevuwMVS66SXaBBpg+RWZkza4A==", + "license": "MIT", "dependencies": { - "ansi-colors": "^4.1.3", "browser-stdout": "^1.3.1", - "chokidar": "^3.5.3", + "chokidar": "^4.0.1", "debug": "^4.3.5", - "diff": "^5.2.0", + "diff": "^7.0.0", "escape-string-regexp": "^4.0.0", "find-up": "^5.0.0", - "glob": "^8.1.0", + "glob": "^10.4.5", "he": "^1.2.0", "js-yaml": "^4.1.0", "log-symbols": "^4.1.0", - "minimatch": "^5.1.6", + "minimatch": "^9.0.5", "ms": "^2.1.3", + "picocolors": "^1.1.1", "serialize-javascript": "^6.0.2", "strip-json-comments": "^3.1.1", "supports-color": "^8.1.1", - "workerpool": "^6.5.1", - "yargs": "^16.2.0", - "yargs-parser": "^20.2.9", + "workerpool": "^9.2.0", + "yargs": "^17.7.2", + "yargs-parser": "^21.1.1", "yargs-unparser": "^2.0.0" }, "bin": { @@ -9467,76 +9316,94 @@ "mocha": "bin/mocha.js" }, "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/mocha/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/mocha/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "dev": true, + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" } }, - "node_modules/mocha/node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", - "dev": true, + "node_modules/mocha/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "license": "MIT", "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/mocha/node_modules/diff": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz", - "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==", - "dev": true, - "engines": { - "node": ">=0.3.1" + "node_modules/mocha/node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/mocha/node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", - "dev": true, + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", "dependencies": { "brace-expansion": "^2.0.1" }, "engines": { - "node": ">=10" + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/mocha/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, + "node_modules/mocha/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mocha/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" } }, "node_modules/mocha/node_modules/supports-color": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -9547,39 +9414,13 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/mocha/node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, + "node_modules/mocha/node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/mocha/node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", - "dev": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" + "node": ">=12" } }, "node_modules/monaco-editor": { @@ -10422,7 +10263,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, "dependencies": { "yocto-queue": "^0.1.0" }, @@ -10437,7 +10277,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, "dependencies": { "p-limit": "^3.0.2" }, @@ -10559,7 +10398,8 @@ "node_modules/pako": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", - "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true }, "node_modules/parent-module": { "version": "1.0.1", @@ -10639,7 +10479,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, "engines": { "node": ">=8" } @@ -11159,7 +10998,8 @@ "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true }, "node_modules/promise-inflight": { "version": "1.0.1", @@ -11363,7 +11203,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "dev": true, "dependencies": { "safe-buffer": "^5.1.0" } @@ -11572,6 +11411,7 @@ "version": "2.3.8", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -11585,7 +11425,8 @@ "node_modules/readable-stream/node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true }, "node_modules/readdirp": { "version": "3.6.0", @@ -12124,7 +11965,6 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", - "dev": true, "dependencies": { "randombytes": "^2.1.0" } @@ -12168,7 +12008,8 @@ "node_modules/setimmediate": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==" + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "dev": true }, "node_modules/setprototypeof": { "version": "1.2.0", @@ -12499,66 +12340,6 @@ "integrity": "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==", "license": "MIT" }, - "node_modules/stdin-discarder": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.1.0.tgz", - "integrity": "sha512-xhV7w8S+bUwlPTb4bAOUQhv8/cSS5offJuX8GQGq32ONF0ZtDWKfkdomM3HMRA+LhX6um/FZ0COqlwsjD53LeQ==", - "dependencies": { - "bl": "^5.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/stdin-discarder/node_modules/bl": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-5.1.0.tgz", - "integrity": "sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ==", - "dependencies": { - "buffer": "^6.0.3", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/stdin-discarder/node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, - "node_modules/stdin-discarder/node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/stoppable": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", @@ -12711,7 +12492,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, "engines": { "node": ">=8" }, @@ -16685,10 +16465,10 @@ } }, "node_modules/workerpool": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.5.1.tgz", - "integrity": "sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==", - "dev": true + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-9.3.3.tgz", + "integrity": "sha512-slxCaKbYjEdFT/o2rH9xS1hf4uRDch1w7Uo+apxhZ+sf/1d9e0ZVkn42kPNGP2dgjIx6YFvSevj0zHvbWe2jdw==", + "license": "Apache-2.0" }, "node_modules/wrap-ansi": { "version": "6.2.0", @@ -16891,7 +16671,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", - "dev": true, "dependencies": { "camelcase": "^6.0.0", "decamelize": "^4.0.0", @@ -16906,7 +16685,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", - "dev": true, "engines": { "node": ">=8" } @@ -16954,7 +16732,6 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, "engines": { "node": ">=10" }, diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index f37fe5139..9e8716811 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.52", + "version": "1.1.55", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -334,6 +334,27 @@ "category": "Continue", "title": "Enter Enterprise License Key", "group": "Continue" + }, + { + "command": "continue.nextEditWindow.hideNextEditSuggestion", + "category": "Continue", + "title": "Hide Next Edit Suggestion" + }, + { + "command": "continue.nextEditWindow.acceptNextEditSuggestion", + "category": "Continue", + "title": "Accept Next Edit Suggestion" + }, + { + "command": "continue.forceNextEdit", + "category": "Continue", + "title": "Continue: Force Next Edit" + }, + { + "command": "continue.generateRule", + "category": "Continue", + "title": "Generate Rule", + "group": "Continue" } ], "keybindings": [ @@ -426,6 +447,16 @@ "command": "continue.applyCodeFromChat", "mac": "alt+a", "key": "alt+a" + }, + { + "command": "continue.nextEditWindow.hideNextEditSuggestion", + "key": "escape", + "when": "editorTextFocus && nextEditWindowActive" + }, + { + "command": "continue.nextEditWindow.acceptNextEditSuggestion", + "key": "tab", + "when": "editorTextFocus && nextEditWindowActive" } ], "submenus": [ @@ -453,6 +484,9 @@ }, { "command": "continue.enterEnterpriseLicenseKey" + }, + { + "command": "continue.generateRule" } ], "editor/context": [ @@ -622,10 +656,8 @@ "rebuild": "electron-rebuild -v 19.1.8 node-pty", "lint": "eslint src --ext ts", "lint:fix": "eslint . --ext ts --fix", - "build-test": "npm run esbuild && node esbuild.test.mjs", - "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "test": "vitest run", "vitest": "vitest run", - "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", "package": "node scripts/package.js", @@ -646,6 +678,7 @@ "e2e:test": "extest run-tests ${TEST_FILE:-'./e2e/_output/tests/*.test.js'} --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage", "e2e:clean": "rm -rf ./e2e/_output ./e2e/storage", "e2e:all": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", + "e2e:all-non-mac": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", "e2e:recompile-extension": "npm run package && npm run e2e:compile && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", "e2e:rebuild-gui": "rm -rf gui && cp -r ../../gui/dist gui && npm run package && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", "e2e:quick": "npm run e2e:compile && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean", @@ -661,11 +694,12 @@ "@types/cors": "^2.8.17", "@types/express": "^4.17.21", "@types/follow-redirects": "^1.14.4", - "@types/glob": "^8.0.0", - "@types/mocha": "^10.0.6", + "@types/mocha": "^10.0.10", "@types/node": "16.x", + "@types/node-fetch": "^2.6.12", "@types/react-dom": "^18.2.4", "@types/request": "^2.48.8", + "@types/uuid": "^10.0.0", "@types/vscode": "1.70", "@types/ws": "^8.5.4", "@typescript-eslint/eslint-plugin": "^5.45.0", @@ -675,9 +709,7 @@ "esbuild": "0.17.19", "esbuild-visualizer": "^0.6.0", "eslint": "^8.28.0", - "glob": "^8.0.3", "json-schema-to-typescript": "^12.0.0", - "mocha": "^10.4.0", "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", @@ -689,10 +721,7 @@ "@continuedev/fetch": "^1.0.10", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", - "@types/node-fetch": "^2.6.11", - "@types/uuid": "^9.0.8", "@vscode/ripgrep": "^1.15.9", - "@vscode/test-electron": "^2.3.9", "axios": "^1.2.5", "core": "file:../../core", "cors": "^2.8.5", @@ -714,6 +743,7 @@ "jsdom": "^24.0.0", "lru-cache": "^11.0.2", "minisearch": "^7.0.0", + "mocha": "^11.7.1", "monaco-editor": "^0.45.0", "monaco-vscode-textmate-theme-converter": "^0.1.7", "ncp": "^2.0.0", diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts new file mode 100644 index 000000000..25cd64acc --- /dev/null +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -0,0 +1,699 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { EXTENSION_NAME } from "core/control-plane/env"; +// @ts-ignore +import * as vscode from "vscode"; + +import { DiffLine } from "core"; +import { CodeRenderer } from "core/codeRenderer/CodeRenderer"; +import { + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "core/nextEdit/constants"; +import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; +import { getThemeString } from "../util/getTheme"; + +export interface TextApplier { + applyText( + editor: vscode.TextEditor, + text: string, + position: vscode.Position, + finalCursorPos: vscode.Position | null, + ): Promise; +} + +const SVG_CONFIG = { + stroke: "#999998", + strokeWidth: 1, + textColor: "#999998", + filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))", + radius: 3, + leftMargin: 40, + defaultText: "", + lineSpacing: 1.2, // Line spacing multiplier + cursorOffset: 4, // Spaces to offset from cursor + + get fontSize() { + return Math.ceil( + vscode.workspace.getConfiguration("editor").get("fontSize") ?? 14, + ); + }, + get fontFamily() { + return ( + vscode.workspace.getConfiguration("editor").get("fontFamily") || + "helvetica" + ); + }, + get paddingX() { + return Math.ceil(this.getEstimatedTextWidth(" ")); + }, + get paddingY() { + return Math.ceil(this.fontSize * 0.3); + }, + get lineHeight() { + return Math.ceil(this.fontSize * this.lineSpacing); + }, + getEstimatedTextWidth(text: string): number { + return text.length * this.fontSize * 0.6; + }, + getTipWidth(text: string): number { + // Find the longest line + const lines = text.split("\n"); + const longestLine = lines.reduce( + (longest, line) => (line.length > longest.length ? line : longest), + "", + ); + + return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2; + }, + getTipHeight(text: string): number { + // Count the number of lines + const lineCount = text.split("\n").length; + return this.lineHeight * lineCount + this.paddingY * 2; + }, +} as const; + +// Command ID - can be used in package.json +export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND = + "continue.nextEditWindow.hideNextEditSuggestion"; +export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND = + "continue.nextEditWindow.acceptNextEditSuggestion"; + +export class NextEditWindowManager { + private static instance: NextEditWindowManager | undefined; + + private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"]; + private theme: string; + private fontSize: number; + private fontFamily: string; + private codeRenderer: CodeRenderer; + + // Current active decoration + private currentDecoration: vscode.TextEditorDecorationType | null = null; + // Track which editor has the active decoration + private activeEditor: vscode.TextEditor | null = null; + // Store the current tooltip text for accepting + private currentTooltipText: string | null = null; + + // Disposables + private disposables: vscode.Disposable[] = []; + + private textApplier: TextApplier | null = null; + + private finalCursorPos: vscode.Position | null = null; + + private context: vscode.ExtensionContext | null = null; + + public static getInstance(): NextEditWindowManager { + if (!NextEditWindowManager.instance) { + NextEditWindowManager.instance = new NextEditWindowManager(); + } + return NextEditWindowManager.instance; + } + + public static isInstantiated(): boolean { + return !!NextEditWindowManager.instance; + } + + public static clearInstance(): void { + if (NextEditWindowManager.instance) { + NextEditWindowManager.instance.dispose(); + NextEditWindowManager.instance = undefined; + } + } + + private constructor() { + this.theme = getThemeString(); + + console.log( + "Next Edit Theme initialized:", + this.theme + ? `Theme exists: ${JSON.stringify(this.theme)}` + : "Theme is undefined", + ); + this.setupListeners(); + this.codeRenderer = CodeRenderer.getInstance(); + + const editorConfig = vscode.workspace.getConfiguration("editor"); + this.fontSize = editorConfig.get("fontSize") ?? 14; + this.fontFamily = editorConfig.get("fontFamily") ?? "monospace"; + } + + public static async reserveTabAndEsc() { + await vscode.commands.executeCommand( + "setContext", + "nextEditWindowActive", + true, + ); + } + + public static async freeTabAndEsc() { + await vscode.commands.executeCommand( + "setContext", + "nextEditWindowActive", + false, + ); + } + + /** + * An async setup function to help us initialize the NextEditWindowManager. + * This is necessary because we need some setup to be done asynchronously, + * and constructors in TypeScript cannot be async. + * Plus, it's generally not recommended to pass arguments to getInstance() of a singleton. + * @param context The extension context. + * @param textApplier Callback that lets us use external deps such as llms if needed. + */ + public async setupNextEditWindowManager( + context: vscode.ExtensionContext, + textApplier?: TextApplier, + ) { + this.context = context; + + // Set nextEditWindowActive to false to free esc and tab, + // letting them return to their original behaviors. + await NextEditWindowManager.freeTabAndEsc(); + + // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. + this.registerCommandSafely( + HIDE_NEXT_EDIT_SUGGESTION_COMMAND, + async () => await this.hideAllNextEditWindows(), + ); + this.registerCommandSafely( + ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, + async () => await this.acceptNextEdit(), + ); + + // Add this class to context disposables. + context.subscriptions.push(this); + + if (textApplier) { + this.textApplier = textApplier; + } + + await this.codeRenderer.setTheme(this.theme); + } + + /** + * Registers our two custom commands to the extension context. + * @param commandId Custom commands to help set up next edit. + * @param callback Function to run on command execution. + */ + private registerCommandSafely( + commandId: + | "continue.nextEditWindow.hideNextEditSuggestion" + | "continue.nextEditWindow.acceptNextEditSuggestion", + callback: () => Promise, + ) { + if (!this.context) { + console.log("Extension context is not yet set."); + return; + } + + try { + const command = vscode.commands.registerCommand(commandId, callback); + this.context.subscriptions.push(command); + } catch (error) { + console.log( + `Command ${commandId} already has an associated callback, skipping registration`, + ); + } + } + + /** + * Show a tooltip with the given text at the current cursor position. + * @param editor The active text editor. + * @param text Text to display in the tooltip. + */ + public async showNextEditWindow( + editor: vscode.TextEditor, + currCursorPos: vscode.Position, + editableRegionStartLine: number, + newEditRangeSlice: string, + diffLines: DiffLine[], + ) { + if (!newEditRangeSlice || !this.shouldRenderTip(editor.document.uri)) { + return; + } + + // Clear any existing decorations first (very important to prevent overlapping). + await this.hideAllNextEditWindows(); + + // Store the current tooltip text for accepting later. + this.currentTooltipText = newEditRangeSlice; + + // How far away is the current line from the start of the editable region? + const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; + + // How long is the line at the current cursor position? + const lineContentAtCursorPos = + newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; + + const offset = getOffsetPositionAtLastNewLine( + diffLines, + lineContentAtCursorPos, + lineOffsetAtCursorPos, + ); + + // Calculate the actual line number in the editor by adding the startPos offset + // to the line number from the diff calculation. + this.finalCursorPos = new vscode.Position( + editableRegionStartLine + offset.line, + offset.character, + ); + + // Create and apply decoration with the text. + await this.renderTooltip(editor, currCursorPos, newEditRangeSlice); + + // Reserve tab and esc to either accept or reject the displayed next edit contents. + await NextEditWindowManager.reserveTabAndEsc(); + } + + /** + * Hide all tooltips in all editors. + */ + public async hideAllNextEditWindows() { + if (this.currentDecoration) { + vscode.window.visibleTextEditors.forEach((editor) => { + editor.setDecorations(this.currentDecoration!, []); + }); + + // If we know which editor had the decoration, clear it specifically. + // This is a bit redundant but ensures we don't leave any decorations behind. + if (this.activeEditor) { + this.activeEditor.setDecorations(this.currentDecoration, []); + this.activeEditor = null; + } + + // This prevents memory leaks. + this.currentDecoration.dispose(); + this.currentDecoration = null; + + this.disposables.forEach((d) => d.dispose()); + this.disposables = []; + + // Clear the current tooltip text. + this.currentTooltipText = null; + } + + await NextEditWindowManager.freeTabAndEsc(); + } + + /** + * Accept the current next edit suggestion by inserting it at cursor position. + */ + private async acceptNextEdit() { + if (!this.activeEditor || !this.currentTooltipText) { + return; + } + + const editor = this.activeEditor; + const text = this.currentTooltipText; + const position = editor.selection.active; + + let success = false; + if (this.textApplier) { + success = await this.textApplier.applyText( + editor, + text, + position, + this.finalCursorPos, + ); + } else { + // Define the editable region. + const editableRegionStartLine = Math.max( + 0, + position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + ); + const editableRegionEndLine = Math.min( + editor.document.lineCount - 1, + position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + ); + const startPos = new vscode.Position(editableRegionStartLine, 0); + const endPosChar = editor.document.lineAt(editableRegionEndLine).text + .length; + + const endPos = new vscode.Position(editableRegionEndLine, endPosChar); + const editRange = new vscode.Range(startPos, endPos); + + success = await editor.edit((editBuilder) => { + editBuilder.replace(editRange, text); + }); + + // Disable inline suggestions temporarily. + // This prevents the race condition between vscode's inline completion provider + // and the next edit window manager's cursor repositioning logic. + await vscode.workspace + .getConfiguration() + .update("editor.inlineSuggest.enabled", false, true); + } + + if (success) { + // Move cursor to the final position if available. + if (this.finalCursorPos) { + editor.selection = new vscode.Selection( + this.finalCursorPos, + this.finalCursorPos, + ); + + // Reenable inline suggestions after we move the cursor. + await vscode.workspace + .getConfiguration() + .update("editor.inlineSuggest.enabled", true, true); + + await this.hideAllNextEditWindows(); + } + } + } + + /** + * Dispose of the NextEditWindowManager. + */ + public dispose() { + // Dispose current decoration. + if (this.currentDecoration) { + this.currentDecoration.dispose(); + this.currentDecoration = null; + } + + // Dispose all other disposables. + this.disposables.forEach((d) => d.dispose()); + this.disposables = []; + } + + /** + * Setup listeners for theme, font, and cursor position changes. + */ + private setupListeners() { + // Theme change listener. + vscode.workspace.onDidChangeConfiguration((e) => { + if ( + e.affectsConfiguration("workbench.colorTheme") || + e.affectsConfiguration("editor.fontSize") || + e.affectsConfiguration("editor.fontFamily") || + e.affectsConfiguration("window.autoDetectColorScheme") || + e.affectsConfiguration("window.autoDetectHighContrast") || + e.affectsConfiguration("workbench.preferredDarkColorTheme") || + e.affectsConfiguration("workbench.preferredLightColorTheme") || + e.affectsConfiguration("workbench.preferredHighContrastColorTheme") || + e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme") + ) { + this.theme = getThemeString(); + this.codeRenderer.setTheme(this.theme); + console.log( + "Theme updated:", + this.theme ? "Theme exists" : "Theme is undefined", + ); + const editorConfig = vscode.workspace.getConfiguration("editor"); + this.fontSize = editorConfig.get("fontSize") ?? 14; + this.fontFamily = editorConfig.get("fontFamily") ?? "monospace"; + } + }); + + // Listen for active color theme changes. + vscode.window.onDidChangeActiveColorTheme(() => { + this.theme = getThemeString(); + this.codeRenderer.setTheme(this.theme); + console.log( + "Active theme changed:", + this.theme ? "Theme exists" : "Theme is undefined", + ); + }); + + // Listen for editor changes to clean up decorations when editor closes. + vscode.window.onDidChangeVisibleTextEditors(async () => { + // If our active editor is no longer visible, clear decorations. + if ( + this.activeEditor && + !vscode.window.visibleTextEditors.includes(this.activeEditor) + ) { + await this.hideAllNextEditWindows(); + } + }); + + // Listen for selection changes to hide tooltip when cursor moves. + vscode.window.onDidChangeTextEditorSelection(async (e) => { + // If the selection changed in our active editor, hide the tooltip. + if (this.activeEditor && e.textEditor === this.activeEditor) { + await this.hideAllNextEditWindows(); + } + }); + } + + private shouldRenderTip(uri: vscode.Uri): boolean { + const isAllowedUri = + !this.excludedURIPrefixes.some((prefix) => + uri.toString().startsWith(prefix), + ) && uri.scheme !== "comment"; + + const isEnabled = + !!vscode.workspace + .getConfiguration(EXTENSION_NAME) + .get("showInlineTip") === true; + + return isAllowedUri && isEnabled; + } + + /** + * Create a render of the given code, supporting multiple lines. + */ + private async createCodeRender( + text: string, + ): Promise< + | { uri: vscode.Uri; dimensions: { width: number; height: number } } + | undefined + > { + try { + const tipWidth = SVG_CONFIG.getTipWidth(text); + const tipHeight = SVG_CONFIG.getTipHeight(text); + const dimensions = { + width: tipWidth, + height: tipHeight, + }; + + const uri = await this.codeRenderer.getDataUri( + text, + "typescript", + this.fontSize, + this.fontFamily, + dimensions, + SVG_CONFIG.lineHeight, + { + imageType: "svg", + }, + ); + + return { + uri: vscode.Uri.parse(uri), + dimensions, + }; + } catch (error) { + console.error("Error creating SVG tooltip:", error); + return undefined; + } + } + + /** + * Create a decoration type with the code render. + * @param code: The code to render. + * @returns The decoration. + */ + private async createCodeRenderDecoration( + code: string, + ): Promise { + const uriAndDimensions = await this.createCodeRender(code); + if (!uriAndDimensions) { + return undefined; + } + + const { uri, dimensions } = uriAndDimensions; + const tipWidth = dimensions.width; + const tipHeight = dimensions.height; + + return vscode.window.createTextEditorDecorationType({ + after: { + contentIconPath: uri, + // border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; + // border-radius: ${SVG_CONFIG.radius}px; + // filter: ${SVG_CONFIG.filter}`, + // width: `${tipWidth}px`, + // height: `${tipHeight}px`, + // border: `transparent; position: absolute; z-index: 1000; + // box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, + // inset 0 0 0 ${tipHeight}px ${backgroundColour}; + // border-radius: ${SVG_CONFIG.radius}px; + // filter: ${SVG_CONFIG.filter}; + // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, + border: `transparent; position: absolute; z-index: 1000; + box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px; + filter: ${SVG_CONFIG.filter}; + border-radius: ${SVG_CONFIG.radius}px; + margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, + // border: `solid 1px white; position: absolute; z-index: 1000; + // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; + // margin-top: 0em;`, + // border: `solid 1px white; position: absolute; z-index: 1000; + // margin: 0em; padding: 0em; + // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; + // margin-top: 0em;`, + width: `${tipWidth}px`, + height: `${tipHeight}px`, + // textDecoration: `none; transform: translateY(-100%);`, + }, + // Set a negative margin to make the decoration float if it starts to displace text. + // Also use absolute positioning. + rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed, + }); + } + + private buildHideTooltipHoverMsg() { + const hoverMarkdown = new vscode.MarkdownString( + `[Reject (Esc)](command:${HIDE_NEXT_EDIT_SUGGESTION_COMMAND}) | [Accept (Tab)](command:${ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND})`, + ); + + hoverMarkdown.isTrusted = true; + hoverMarkdown.supportHtml = true; + return hoverMarkdown; + } + + private isValidRange( + editor: vscode.TextEditor, + range: vscode.Range, + ): boolean { + const doc = editor.document; + + // Check if line numbers are valid. + if (range.start.line < 0 || range.start.line >= doc.lineCount) { + console.log( + "Invalid start line:", + range.start.line, + "doc lines:", + doc.lineCount, + ); + return false; + } + + if (range.end.line < 0 || range.end.line >= doc.lineCount) { + console.log( + "Invalid end line:", + range.end.line, + "doc lines:", + doc.lineCount, + ); + return false; + } + + // Check if character positions are valid. + const startLine = doc.lineAt(range.start.line); + const endLine = doc.lineAt(range.end.line); + + if ( + range.start.character < 0 || + range.start.character > startLine.text.length + ) { + console.log( + "Invalid start character:", + range.start.character, + "line length:", + startLine.text.length, + ); + return false; + } + + if (range.end.character < 0 || range.end.character > endLine.text.length) { + console.log( + "Invalid end character:", + range.end.character, + "line length:", + endLine.text.length, + ); + return false; + } + + return true; + } + + /** + * Calculate a position to the right of the cursor with the specified offset. + */ + private getDecorationOffsetPosition( + editor: vscode.TextEditor, + position: vscode.Position, + ): vscode.Position { + // Create a position that's offset spaces to the right of the cursor. + + const line = editor.document.lineAt(position.line); + const offsetChar = Math.min( + position.character + SVG_CONFIG.cursorOffset, + line.text.length, + ); + return new vscode.Position(position.line, offsetChar); + } + + /** + * Render a tooltip with the given text at the specified position. + */ + private async renderTooltip( + editor: vscode.TextEditor, + position: vscode.Position, + text: string, + ) { + console.log("renderTooltip"); + // Capture document version to detect changes. + const docVersion = editor.document.version; + + // Create a new decoration with the text. + const decoration = await this.createCodeRenderDecoration(text); + if (!decoration) { + console.error("Failed to create decoration for text:", text); + return; + } + + // Check if document changed during async operation. + if (editor.document.version !== docVersion) { + console.log("Document changed during decoration creation, aborting"); + decoration.dispose(); + return; + } + + // Store the decoration and editor. + await this.hideAllNextEditWindows(); + this.currentDecoration = decoration; + this.activeEditor = editor; + + // Calculate how far off to the right of the cursor the decoration should be. + const decorationOffsetPosition = this.getDecorationOffsetPosition( + editor, + position, + ); + const range = new vscode.Range( + decorationOffsetPosition, + decorationOffsetPosition, + ); + + // Validate the range before applying. + if (!this.isValidRange(editor, range)) { + console.error("Invalid range detected, skipping decoration"); + return; + } + + // Apply the decoration at the calculated position. + editor.setDecorations(this.currentDecoration, [ + { + range: new vscode.Range( + decorationOffsetPosition, + decorationOffsetPosition, + ), + hoverMessage: [this.buildHideTooltipHoverMsg()], + }, + ]); + } +} + +export default async function setupNextEditWindowManager( + context: vscode.ExtensionContext, + textApplier?: TextApplier, +) { + await NextEditWindowManager.getInstance().setupNextEditWindowManager( + context, + textApplier, + ); +} diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index fb446e174..1ac84c368 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -3,18 +3,14 @@ import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ApplyToFilePayload } from "core"; +import { myersDiff } from "core/diff/myers"; +import { generateLines } from "core/diff/util"; import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -export interface ApplyToFileOptions { - streamId: string; - filepath?: string; - text: string; - toolCallId?: string; -} - /** * Handles applying text/code to files including diff generation and streaming */ @@ -31,7 +27,8 @@ export class ApplyManager { filepath, text, toolCallId, - }: ApplyToFileOptions) { + isSearchAndReplace, + }: ApplyToFilePayload) { await this.webviewProtocol.request("updateApplyState", { streamId, status: "streaming", @@ -45,19 +42,34 @@ export class ApplyManager { const { activeTextEditor } = vscode.window; if (!activeTextEditor) { - vscode.window.showErrorMessage("No active editor to apply edits to"); + void vscode.window.showErrorMessage("No active editor to apply edits to"); return; } const hasExistingDocument = !!activeTextEditor.document.getText().trim(); if (hasExistingDocument) { - await this.handleExistingDocument( - activeTextEditor, - text, - streamId, - toolCallId, - ); + // Currently `isSearchAndReplace` will always provide a full file rewrite + // as the contents of `text`, so we can just instantly apply + if (isSearchAndReplace) { + const diffLinesGenerator = generateLines( + myersDiff(activeTextEditor.document.getText(), text), + ); + + await this.verticalDiffManager.streamDiffLines( + diffLinesGenerator, + true, + streamId, + toolCallId, + ); + } else { + await this.handleExistingDocument( + activeTextEditor, + text, + streamId, + toolCallId, + ); + } } else { await this.handleEmptyDocument( activeTextEditor, @@ -104,14 +116,14 @@ export class ApplyManager { ) { const { config } = await this.configHandler.loadConfig(); if (!config) { - vscode.window.showErrorMessage("Config not loaded"); + void vscode.window.showErrorMessage("Config not loaded"); return; } const llm = config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; if (!llm) { - vscode.window.showErrorMessage( + void vscode.window.showErrorMessage( `No model with roles "apply" or "chat" found in config.`, ); return; @@ -165,7 +177,7 @@ export class ApplyManager { ) { const { config } = await this.configHandler.loadConfig(); if (!config) { - vscode.window.showErrorMessage("Config not loaded"); + void vscode.window.showErrorMessage("Config not loaded"); return; } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 963dcedeb..24bd86fa0 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,8 +5,8 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; -import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; -import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +// import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; +// import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -15,6 +15,14 @@ import { handleLLMError } from "../util/errorHandling"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { myersDiff } from "core/diff/myers"; +import { + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "core/nextEdit/constants"; +import { checkFim } from "core/nextEdit/diff/diff"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditWindowManager } from "../activation/NextEditWindowManager"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; @@ -54,9 +62,19 @@ export class ContinueCompletionProvider } private completionProvider: CompletionProvider; - private nextEditProvider: NextEditProvider | undefined; - private recentlyVisitedRanges: RecentlyVisitedRangesService; - private recentlyEditedTracker: RecentlyEditedTracker; + private nextEditProvider: NextEditProvider; + public recentlyVisitedRanges: RecentlyVisitedRangesService; + public recentlyEditedTracker: RecentlyEditedTracker; + + private isNextEditActive: boolean = false; + + public activateNextEdit() { + this.isNextEditActive = true; + } + + public deactivateNextEdit() { + this.isNextEditActive = false; + } constructor( private readonly configHandler: ConfigHandler, @@ -79,16 +97,16 @@ export class ContinueCompletionProvider this.onError.bind(this), getDefinitionsFromLsp, ); - // NOTE: Only turn it on locally when testing (for review purposes). - if (IS_NEXT_EDIT_ACTIVE) { - this.nextEditProvider = new NextEditProvider( - this.configHandler, - this.ide, - getAutocompleteModel, - this.onError.bind(this), - getDefinitionsFromLsp, - ); - } + + this.nextEditProvider = NextEditProvider.initialize( + this.configHandler, + this.ide, + getAutocompleteModel, + this.onError.bind(this), + getDefinitionsFromLsp, + "fineTuned", + ); + this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } @@ -148,6 +166,10 @@ export class ContinueCompletionProvider line: position.line, character: position.character, }; + // const pos = { + // line: 0, + // character: 0, + // }; let manuallyPassFileContents: string | undefined = undefined; if (document.uri.scheme === "vscode-notebook-cell") { const notebook = vscode.workspace.notebookDocuments.find((notebook) => @@ -208,31 +230,22 @@ export class ContinueCompletionProvider }; setupStatusBar(undefined, true); - const outcome = - await this.completionProvider.provideInlineCompletionItems( - input, - signal, - wasManuallyTriggered, - ); + + const outcome = this.isNextEditActive + ? await this.nextEditProvider.provideInlineCompletionItems( + input, + signal, + ) + : await this.completionProvider.provideInlineCompletionItems( + input, + signal, + wasManuallyTriggered, + ); if (!outcome || !outcome.completion) { return null; } - // NOTE: This is a very rudimentary check to see if we can call the next edit service. - // In the future we will have to figure out how to call this more gracefully. - if (this.nextEditProvider) { - const nextEditOutcome = - await this.nextEditProvider?.provideInlineCompletionItems( - input, - signal, - ); - - if (nextEditOutcome && nextEditOutcome.completion) { - outcome.completion = nextEditOutcome.completion; - } - } - // VS Code displays dependent on selectedCompletionInfo (their docstring below) // We should first always make sure we have a valid completion, but if it goes wrong we // want telemetry to be correct @@ -265,7 +278,10 @@ export class ContinueCompletionProvider // Construct the range/text to show const startPos = selectedCompletionInfo?.range.start ?? position; + // const startPos = new vscode.Position(0, 0); + // const endPos = new vscode.Position(0, 5); let range = new vscode.Range(startPos, startPos); + // let range = new vscode.Range(startPos, endPos); let completionText = outcome.completion; const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; @@ -308,7 +324,81 @@ export class ContinueCompletionProvider ); (completionItem as any).completeBracketPairs = true; - return [completionItem]; + + if (this.isNextEditActive) { + const editor = vscode.window.activeTextEditor; + if (!editor) { + return undefined; + } + + // Check the diff between old and new editable region. + const newEditRangeSlice = completionText; + + // We don't need to show the next edit window if the predicted edits is empty. + if (newEditRangeSlice === "") { + return undefined; + } + + // Get the contents of the old (current) editable region. + const currCursorPos = editor.selection.active; + const editableRegionStartLine = Math.max( + currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEndLine = Math.min( + currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + editor.document.lineCount - 1, + ); + const oldEditRangeSlice = editor.document + .getText() + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + // We don't need to show the next edit window if the predicted edits are identical to the previous version. + if (oldEditRangeSlice === newEditRangeSlice) { + return undefined; + } + + // If the diff is a FIM, render a ghost text. + const { isFim, fimText } = checkFim( + oldEditRangeSlice, + newEditRangeSlice, + currCursorPos, + ); + if (isFim) { + const completionItem = new vscode.InlineCompletionItem( + fimText, + new vscode.Range( + new vscode.Position(currCursorPos.line, currCursorPos.character), + new vscode.Position(currCursorPos.line, currCursorPos.character), + ), + { + title: "Log Autocomplete Outcome", + command: "continue.logAutocompleteOutcome", + arguments: [input.completionId, this.completionProvider], + }, + ); + return [completionItem]; + } + + // Else, render a next edit window. + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + + if (NextEditWindowManager.isInstantiated()) { + await NextEditWindowManager.getInstance().showNextEditWindow( + editor, + currCursorPos, + editableRegionStartLine, + completionText, + diffLines, + ); + } + + return undefined; + } else { + return [completionItem]; + } } finally { stopStatusBarLoading(); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 82d045a01..e5320b6b8 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -142,14 +142,12 @@ const getCommandsMap: ( * * @param promptName - The key for the prompt in the context menu configuration. * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. * @param [range] - Optional. The range to edit if provided. * @returns */ async function streamInlineEdit( promptName: keyof ContextMenuConfig, fallbackPrompt: string, - onlyOneInsertion?: boolean, range?: vscode.Range, ) { const { config } = await configHandler.loadConfig(); @@ -170,7 +168,6 @@ const getCommandsMap: ( input: config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, llm, - onlyOneInsertion, range, rulesToInclude: config.rules, }); @@ -243,7 +240,7 @@ const getCommandsMap: ( ) => { captureCommandTelemetry("customQuickActionStreamInlineEdit"); - streamInlineEdit("docstring", prompt, false, range); + streamInlineEdit("docstring", prompt, range); }, "continue.codebaseForceReIndex": async () => { core.invoke("index/forceReIndex", undefined); @@ -344,6 +341,11 @@ const getCommandsMap: ( editDecorationManager.clear(); void sidebar.webviewProtocol?.request("exitEditMode", undefined); }, + "continue.generateRule": async () => { + captureCommandTelemetry("generateRule"); + focusGUI(); + void sidebar.webviewProtocol?.request("generateRule", undefined); + }, "continue.writeCommentsForCode": async () => { captureCommandTelemetry("writeCommentsForCode"); @@ -355,10 +357,9 @@ const getCommandsMap: ( "continue.writeDocstringForCode": async () => { captureCommandTelemetry("writeDocstringForCode"); - streamInlineEdit( + void streamInlineEdit( "docstring", "Write a docstring for this code. Do not change anything about the code itself.", - true, ); }, "continue.fixCode": async () => { @@ -779,6 +780,18 @@ const getCommandsMap: ( ); } }, + "continue.forceNextEdit": async () => { + captureCommandTelemetry("forceNextEdit"); + + // This is basically the same logic as forceAutocomplete. + // I'm writing a new command KV pair here in case we diverge in features. + + await vscode.commands.executeCommand("editor.action.inlineSuggest.hide"); + + await vscode.commands.executeCommand( + "editor.action.inlineSuggest.trigger", + ); + }, }; }; diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts index b78ea966c..f350e12b4 100644 --- a/extensions/vscode/src/diff/processDiff.ts +++ b/extensions/vscode/src/diff/processDiff.ts @@ -1,5 +1,7 @@ import { Core } from "core/core"; +import { DataLogger } from "core/data/log"; import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; +import { editOutcomeTracker } from "../extension/EditOutcomeTracker"; import { VsCodeIde } from "../VsCodeIde"; import { VerticalDiffManager } from "./vertical/manager"; @@ -27,6 +29,11 @@ export async function processDiff( await ide.openFile(newOrCurrentUri); + // If streamId is not provided, try to get it from the VerticalDiffManager + if (!streamId) { + streamId = verticalDiffManager.getStreamIdForFile(newOrCurrentUri); + } + // Clear vertical diffs depending on action verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); if (action === "reject") { @@ -37,6 +44,13 @@ export async function processDiff( if (streamId) { const fileContent = await ide.readFile(newOrCurrentUri); + // Record the edit outcome before updating the apply state + await editOutcomeTracker.recordEditOutcome( + streamId, + action === "accept", + DataLogger.getInstance(), + ); + await sidebar.webviewProtocol.request("updateApplyState", { fileContent, filepath: newOrCurrentUri, diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 15b3e79d4..68c3436e8 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -9,8 +9,8 @@ import { indexDecorationType, } from "./decorations"; -import type { VerticalDiffCodeLens } from "./manager"; import type { ApplyState, DiffLine } from "core"; +import type { VerticalDiffCodeLens } from "./manager"; export interface VerticalDiffHandlerOptions { input?: string; @@ -20,10 +20,12 @@ export interface VerticalDiffHandlerOptions { numDiffs?: ApplyState["numDiffs"], fileContent?: ApplyState["fileContent"], ) => void; + streamId?: string; } export class VerticalDiffHandler implements vscode.Disposable { public insertedInCurrentBlock = 0; + public streamId?: string; disposables: vscode.Disposable[] = []; private currentLineIndex: number; private cancelled = false; @@ -50,6 +52,7 @@ export class VerticalDiffHandler implements vscode.Disposable { public options: VerticalDiffHandlerOptions, ) { this.currentLineIndex = startLine; + this.streamId = options.streamId; this.removedLineDecorations = new RemovedLineDecorationManager(this.editor); this.addedLineDecorations = new AddedLineDecorationManager(this.editor); @@ -330,10 +333,7 @@ export class VerticalDiffHandler implements vscode.Disposable { // Then, we insert our diff lines await this.editor.edit((editBuilder) => { editBuilder.replace(this.range, replaceContent), - { - undoStopAfter: false, - undoStopBefore: false, - }; + { undoStopAfter: false, undoStopBefore: false }; }); // Lastly, we apply decorations @@ -446,10 +446,7 @@ export class VerticalDiffHandler implements vscode.Disposable { editBuilder.insert(new vscode.Position(index, 0), `${text}\n`); } }, - { - undoStopAfter: false, - undoStopBefore: false, - }, + { undoStopAfter: false, undoStopBefore: false }, ); } @@ -467,10 +464,7 @@ export class VerticalDiffHandler implements vscode.Disposable { new vscode.Range(startLine, startLine.translate(numLines)), ); }, - { - undoStopAfter: false, - undoStopBefore: false, - }, + { undoStopAfter: false, undoStopBefore: false }, ); } @@ -486,10 +480,7 @@ export class VerticalDiffHandler implements vscode.Disposable { ); } }, - { - undoStopAfter: false, - undoStopBefore: false, - }, + { undoStopAfter: false, undoStopBefore: false }, ); } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index aca644c3a..efa4725da 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,4 +1,4 @@ -import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core"; +import { ChatMessage, DiffLine, IDE, ILLM, RuleWithSource } from "core"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; @@ -11,6 +11,9 @@ import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; import { ApplyAbortManager } from "core/edit/applyAbortManager"; +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; +import { stripImages } from "core/util/messageContent"; +import { editOutcomeTracker } from "../../extension/EditOutcomeTracker"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -23,7 +26,6 @@ export class VerticalDiffManager { public refreshCodeLens: () => void = () => {}; private fileUriToHandler: Map = new Map(); - fileUriToCodeLens: Map = new Map(); private userChangeListener: vscode.Disposable | undefined; @@ -33,6 +35,7 @@ export class VerticalDiffManager { constructor( private readonly webviewProtocol: VsCodeWebviewProtocol, private readonly editDecorationManager: EditDecorationManager, + private readonly ide: IDE, ) { this.userChangeListener = undefined; } @@ -69,6 +72,10 @@ export class VerticalDiffManager { return this.fileUriToHandler.get(fileUri); } + getStreamIdForFile(fileUri: string): string | undefined { + return this.fileUriToHandler.get(fileUri)?.streamId; + } + // Creates a listener for document changes by user. private enableDocumentChangeListener(): vscode.Disposable | undefined { if (this.userChangeListener) { @@ -229,6 +236,7 @@ export class VerticalDiffManager { filepath: fileUri, toolCallId, }), + streamId, }, ); @@ -279,7 +287,6 @@ export class VerticalDiffManager { input, llm, streamId, - onlyOneInsertion, quickEdit, range, newCode, @@ -289,14 +296,17 @@ export class VerticalDiffManager { input: string; llm: ILLM; streamId?: string; - onlyOneInsertion?: boolean; quickEdit?: string; range?: vscode.Range; newCode?: string; toolCallId?: string; rulesToInclude: undefined | RuleWithSource[]; }): Promise { - vscode.commands.executeCommand("setContext", "continue.diffVisible", true); + void vscode.commands.executeCommand( + "setContext", + "continue.diffVisible", + true, + ); let editor = vscode.window.activeTextEditor; @@ -373,6 +383,7 @@ export class VerticalDiffManager { filepath: fileUri, toolCallId, }), + streamId, }, ); @@ -430,7 +441,7 @@ export class VerticalDiffManager { ); } - vscode.commands.executeCommand( + void vscode.commands.executeCommand( "setContext", "continue.streamingDiff", true, @@ -453,7 +464,6 @@ export class VerticalDiffManager { rulesToInclude, input, language: getMarkdownLanguageTagForFile(fileUri), - onlyOneInsertion: !!onlyOneInsertion, overridePrompt, abortController, }); @@ -472,10 +482,18 @@ export class VerticalDiffManager { this.enableDocumentChangeListener(); if (abortController.signal.aborted) { - vscode.commands.executeCommand("continue.rejectDiff"); + void vscode.commands.executeCommand("continue.rejectDiff"); } - return `${prefix}${streamedLines.join("\n")}${suffix}`; + const fileAfterEdit = `${prefix}${streamedLines.join("\n")}${suffix}`; + await this.trackEditInteraction({ + model: llm, + filepath: fileUri, + prompt: input, + fileAfterEdit, + }); + + return fileAfterEdit; } catch (e) { this.disableDocumentChangeListener(); const handled = await handleLLMError(e); @@ -487,11 +505,46 @@ export class VerticalDiffManager { throw new Error(message); } } finally { - vscode.commands.executeCommand( + void vscode.commands.executeCommand( "setContext", "continue.streamingDiff", false, ); } } + + async trackEditInteraction({ + model, + filepath, + prompt, + fileAfterEdit, + }: { + model: ILLM; + filepath: string; + prompt: string; + fileAfterEdit: string | undefined; + }) { + // Get previous code content for outcome tracking + const previousCode = await this.ide.readFile(filepath); + const newCode = fileAfterEdit ?? ""; + const previousCodeLines = previousCode.split("\n").length; + const newCodeLines = newCode.split("\n").length; + const lineChange = newCodeLines - previousCodeLines; + + // Store pending edit data for outcome tracking + editOutcomeTracker.trackEditInteraction({ + streamId: EDIT_MODE_STREAM_ID, + timestamp: new Date().toISOString(), + modelProvider: model.underlyingProviderName, + modelTitle: model.title ?? "", + prompt: stripImages(prompt), + completion: newCode, + previousCode, + newCode, + filepath: filepath, + previousCodeLines, + newCodeLines, + lineChange, + }); + } } diff --git a/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts b/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts index 1c0a76251..75a6410f4 100644 --- a/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts +++ b/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts @@ -1,3 +1,5 @@ +import * as path from "path"; + import * as vscode from "vscode"; export class ConfigYamlDocumentLinkProvider @@ -11,11 +13,35 @@ export class ConfigYamlDocumentLinkProvider const links: vscode.DocumentLink[] = []; for (let lineIndex = 0; lineIndex < document.lineCount; lineIndex++) { + if (token.isCancellationRequested) { + return []; + } const line = document.lineAt(lineIndex); const match = this.usesPattern.exec(line.text); if (match) { - const slug = match[1].trim(); + let slug = match[1].trim(); + // Remove any leading comment symbols (#) + slug = slug.replace(/^\s*(#\s*)+/, ""); + + // Check for surrounding quotes + const quoteMatch = slug.match(/^(['"])(.*)\1/); + if (quoteMatch) { + // If quoted, remove the quotes but keep everything inside (including #) + slug = quoteMatch[2].trim(); + } else { + // If not quoted, remove any trailing comment + slug = slug.replace(/\s*#.*$/, "").trim(); + } + + if (slug === "") { + continue; // Skip empty slugs + } + + if (/^(https?:\/\/|file:\/\/)/.test(slug)) { + // VS Code already handles external links, so skip them + continue; + } const startPos = line.text.indexOf(slug); const range = new vscode.Range( lineIndex, @@ -24,10 +50,17 @@ export class ConfigYamlDocumentLinkProvider startPos + slug.length, ); - const link = new vscode.DocumentLink( - range, - vscode.Uri.parse(`https://hub.continue.dev/${slug}`), - ); + let linkUri: vscode.Uri; + if (slug.startsWith("./") || slug.startsWith("../")) { + const currentFilePath = document.uri.fsPath; + const parentPath = path.dirname(currentFilePath); + const resolvedPath = path.resolve(parentPath, slug); + linkUri = vscode.Uri.file(resolvedPath); + } else { + linkUri = vscode.Uri.parse(`https://hub.continue.dev/${slug}`); + } + + const link = new vscode.DocumentLink(range, linkUri); links.push(link); } } diff --git a/extensions/vscode/src/extension/EditOutcomeTracker.ts b/extensions/vscode/src/extension/EditOutcomeTracker.ts new file mode 100644 index 000000000..c69dbac72 --- /dev/null +++ b/extensions/vscode/src/extension/EditOutcomeTracker.ts @@ -0,0 +1,96 @@ +/** + * Tracks pending edit interactions until they are accepted or rejected, + * then emits editOutcome events with the final result. + */ +export interface PendingEditData { + streamId: string; + timestamp: string; + modelProvider: string; + modelTitle: string; + prompt: string; + completion: string; + previousCode: string; + newCode: string; + filepath: string; + previousCodeLines: number; + newCodeLines: number; + lineChange: number; +} + +class EditOutcomeTracker { + private static instance: EditOutcomeTracker; + private pendingEdits: Map = new Map(); + + private constructor() {} + + public static getInstance(): EditOutcomeTracker { + if (!EditOutcomeTracker.instance) { + EditOutcomeTracker.instance = new EditOutcomeTracker(); + } + return EditOutcomeTracker.instance; + } + + /** + * Store a pending edit interaction for later outcome tracking + */ + public trackEditInteraction(data: PendingEditData): void { + this.pendingEdits.set(data.streamId, data); + } + + /** + * Record the outcome of an edit interaction and emit the editOutcome event + */ + public async recordEditOutcome( + streamId: string, + accepted: boolean, + dataLogger: any, + ): Promise { + const pendingEdit = this.pendingEdits.get(streamId); + if (!pendingEdit) { + console.warn(`No pending edit found for streamId: ${streamId}`); + return; + } + + // Emit the editOutcome event + await dataLogger.logDevData({ + name: "editOutcome", + data: { + modelProvider: pendingEdit.modelProvider, + modelTitle: pendingEdit.modelTitle, + prompt: pendingEdit.prompt, + completion: pendingEdit.completion, + previousCode: pendingEdit.previousCode, + newCode: pendingEdit.newCode, + previousCodeLines: pendingEdit.previousCodeLines, + newCodeLines: pendingEdit.newCodeLines, + lineChange: pendingEdit.lineChange, + accepted, + }, + }); + + // Clean up the pending edit + this.pendingEdits.delete(streamId); + } + + /** + * Clean up pending edits that might have been abandoned + */ + public cleanupOldPendingEdits(maxAgeMs: number = 30 * 60 * 1000): void { + const now = Date.now(); + for (const [streamId, edit] of this.pendingEdits.entries()) { + const editTime = new Date(edit.timestamp).getTime(); + if (now - editTime > maxAgeMs) { + this.pendingEdits.delete(streamId); + } + } + } + + /** + * Get count of pending edits (for debugging/monitoring) + */ + public getPendingEditCount(): number { + return this.pendingEdits.size; + } +} + +export const editOutcomeTracker = EditOutcomeTracker.getInstance(); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 20bde355d..0bc47f90d 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -36,12 +36,17 @@ import { } from "../stubs/WorkOsAuthProvider"; import { Battery } from "../util/battery"; import { FileSearch } from "../util/FileSearch"; +import { VsCodeIdeUtils } from "../util/ideUtils"; import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; -import { VsCodeIdeUtils } from "../util/ideUtils"; +import setupNextEditWindowManager, { + NextEditWindowManager, +} from "../activation/NextEditWindowManager"; +import { getDefinitionsFromLsp } from "../autocomplete/lsp"; +import { handleTextDocumentChange } from "../util/editLoggingUtils"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; export class VsCodeExtension { @@ -62,11 +67,12 @@ export class VsCodeExtension { private workOsAuthProvider: WorkOsAuthProvider; private fileSearch: FileSearch; private uriHandler = new UriEventHandler(); + private completionProvider: ContinueCompletionProvider; constructor(context: vscode.ExtensionContext) { // Register auth provider this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler); - this.workOsAuthProvider.refreshSessions(); + void this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); this.editDecorationManager = new EditDecorationManager(context); @@ -124,25 +130,28 @@ export class VsCodeExtension { configHandlerPromise, this.workOsAuthProvider, this.editDecorationManager, + context, + this, ); this.core = new Core(inProcessMessenger, this.ide); this.configHandler = this.core.configHandler; resolveConfigHandler?.(this.configHandler); - this.configHandler.loadConfig(); + void this.configHandler.loadConfig(); this.verticalDiffManager = new VerticalDiffManager( this.sidebar.webviewProtocol, this.editDecorationManager, + this.ide, ); resolveVerticalDiffManager?.(this.verticalDiffManager); - setupRemoteConfigSync( + void setupRemoteConfigSync( this.configHandler.reloadConfig.bind(this.configHandler), ); - this.configHandler.loadConfig().then(({ config }) => { + void this.configHandler.loadConfig().then(({ config }) => { const { verticalDiffCodeLens } = registerAllCodeLensProviders( context, this.verticalDiffManager.fileUriToCodeLens, @@ -155,6 +164,18 @@ export class VsCodeExtension { this.configHandler.onConfigUpdate( async ({ config: newConfig, configLoadInterrupted }) => { + if (newConfig?.experimental?.optInNextEditFeature) { + // Set up next edit window manager only for Continue team members + await setupNextEditWindowManager(context); + + this.activateNextEdit(); + await NextEditWindowManager.freeTabAndEsc(); + } else { + NextEditWindowManager.clearInstance(); + this.deactivateNextEdit(); + await NextEditWindowManager.freeTabAndEsc(); + } + if (configLoadInterrupted) { // Show error in status bar setupStatusBar(undefined, undefined, true); @@ -178,14 +199,15 @@ export class VsCodeExtension { setupStatusBar( enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled, ); + this.completionProvider = new ContinueCompletionProvider( + this.configHandler, + this.ide, + this.sidebar.webviewProtocol, + ); context.subscriptions.push( vscode.languages.registerInlineCompletionItemProvider( [{ pattern: "**" }], - new ContinueCompletionProvider( - this.configHandler, - this.ide, - this.sidebar.webviewProtocol, - ), + this.completionProvider, ), ); @@ -280,7 +302,19 @@ export class VsCodeExtension { if (stats.size === 0) { return; } - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); + }); + + vscode.workspace.onDidChangeTextDocument(async (event) => { + const editInfo = await handleTextDocumentChange( + event, + this.configHandler, + this.ide, + this.completionProvider, + getDefinitionsFromLsp, + ); + + if (editInfo) this.core.invoke("files/smallEdit", editInfo); }); vscode.workspace.onDidSaveTextDocument(async (event) => { @@ -311,7 +345,7 @@ export class VsCodeExtension { vscode.authentication.onDidChangeSessions(async (e) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); if (e.provider.id === env.AUTH_TYPE) { - vscode.commands.executeCommand( + void vscode.commands.executeCommand( "setContext", "continue.isSignedInToControlPlane", true, @@ -322,7 +356,7 @@ export class VsCodeExtension { sessionInfo, }); } else { - vscode.commands.executeCommand( + void vscode.commands.executeCommand( "setContext", "continue.isSignedInToControlPlane", false, @@ -335,7 +369,7 @@ export class VsCodeExtension { }); // Refresh index when branch is changed - this.ide.getWorkspaceDirs().then((dirs) => + void this.ide.getWorkspaceDirs().then((dirs) => dirs.forEach(async (dir) => { const repo = await this.ide.getRepo(dir); if (repo) { @@ -410,4 +444,12 @@ export class VsCodeExtension { registerCustomContextProvider(contextProvider: IContextProvider) { this.configHandler.registerCustomContextProvider(contextProvider); } + + public activateNextEdit() { + this.completionProvider.activateNextEdit(); + } + + public deactivateNextEdit() { + this.completionProvider.deactivateNextEdit(); + } } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 5aff7056e..430c4fff1 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -30,6 +30,7 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { VsCodeExtension } from "./VsCodeExtension"; type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & ToWebviewFromCoreProtocol; @@ -82,6 +83,8 @@ export class VsCodeMessenger { private readonly configHandlerPromise: Promise, private readonly workOsAuthProvider: WorkOsAuthProvider, private readonly editDecorationManager: EditDecorationManager, + private readonly context: vscode.ExtensionContext, + private readonly vsCodeExtension: VsCodeExtension, ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { diff --git a/extensions/vscode/src/test/runner/mochaRunner.ts b/extensions/vscode/src/test/runner/mochaRunner.ts deleted file mode 100644 index 1056ed6b7..000000000 --- a/extensions/vscode/src/test/runner/mochaRunner.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as path from "node:path"; - -import * as glob from "glob"; -import Mocha from "mocha"; - -export function run() { - // Avoid timing out when stopping on breakpoints during debugging in VSCode - const timeoutOption = process.env.MOCHA_TIMEOUT - ? Number.parseInt(process.env.MOCHA_TIMEOUT) - : // : undefined; - 30_000; - - // Create the mocha test - const mocha = new Mocha({ - ui: "tdd", - color: true, - timeout: timeoutOption, - }); - - // See esbuild.test.mjs for more details - // Assumes this file is in out/test/runner/mochaRunner.js - const compiledTestSuitesDirectory = path.resolve(__dirname); - - glob - .sync("**/**.test.js", { cwd: compiledTestSuitesDirectory }) - .forEach((file) => { - mocha.addFile(path.resolve(compiledTestSuitesDirectory, file)); - }); - - console.log( - `Testing files in ${compiledTestSuitesDirectory}: ${mocha.files}`, - ); - - return new Promise((resolve, reject) => { - try { - // Run the mocha test - mocha.run((failures) => { - if (failures > 0) { - reject(new Error(`${failures} tests failed.`)); - } else { - resolve(); - } - }); - } catch (err) { - console.error(err); - reject(err); - } - }); -} diff --git a/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts b/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts deleted file mode 100644 index f6174e087..000000000 --- a/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts +++ /dev/null @@ -1,127 +0,0 @@ -import fs from "node:fs"; -import * as path from "node:path"; - -import { runTests } from "@vscode/test-electron"; -import { defaultConfig } from "core/config/default"; - -export const testWorkspacePath = path.resolve( - __dirname, - "..", - "src", - "test", - "fixtures", - "test-workspace", -); - -const continueGlobalDir = path.resolve( - __dirname, - "..", - "src", - "test", - "fixtures", - ".continue", -); - -function setupTestWorkspace() { - if (fs.existsSync(testWorkspacePath)) { - fs.rmSync(testWorkspacePath, { recursive: true }); - } - fs.mkdirSync(testWorkspacePath, { - recursive: true, - }); - - fs.writeFileSync( - path.join(testWorkspacePath, "test.py"), - "print('Hello World!')", - ); - fs.writeFileSync( - path.join(testWorkspacePath, "index.js"), - "console.log('Hello World!')", - ); - fs.writeFileSync( - path.join(testWorkspacePath, "test.py"), - "print('Hello World!')", - ); - fs.mkdirSync(path.join(testWorkspacePath, "test-folder")); - fs.writeFileSync( - path.join(testWorkspacePath, "test-folder", "test.js"), - "console.log('Hello World!')", - ); -} - -function setupContinueGlobalDir() { - if (fs.existsSync(continueGlobalDir)) { - fs.rmSync(continueGlobalDir, { recursive: true }); - } - fs.mkdirSync(continueGlobalDir, { - recursive: true, - }); - fs.writeFileSync( - path.join(continueGlobalDir, "config.json"), - JSON.stringify({ - ...defaultConfig, - models: [ - { - title: "Test Model", - provider: "openai", - model: "gpt-3.5-turbo", - apiKey: "API_KEY", - }, - ], - }), - ); -} - -function cleanupTestWorkspace() { - if (fs.existsSync(testWorkspacePath)) { - fs.rmSync(testWorkspacePath, { recursive: true }); - } -} - -function cleanupContinueGlobalDir() { - if (fs.existsSync(continueGlobalDir)) { - fs.rmSync(continueGlobalDir, { recursive: true }); - } -} - -async function main() { - try { - // The folder containing the Extension Manifest package.json - // Passed to `--extensionDevelopmentPath` - - // Assumes this file is in out/runTestOnVSCodeHost.js - const extensionDevelopmentPath = path.resolve(__dirname, "../"); - console.log("extensionDevelopmentPath", extensionDevelopmentPath); - - // The path to test runner - // Passed to --extensionTestsPath - const extensionTestsPath = path.resolve( - extensionDevelopmentPath, - "out/mochaRunner", - ); - - const extensionTestsEnv = { - NODE_ENV: "test", - CONTINUE_GLOBAL_DIR: continueGlobalDir, - }; - - setupTestWorkspace(); - setupContinueGlobalDir(); - - // Download VS Code, unzip it and run the integration test - await runTests({ - extensionDevelopmentPath, - extensionTestsPath, - extensionTestsEnv, - launchArgs: [testWorkspacePath], - }); - } catch (err) { - console.error("Failed to run tests", err); - process.exit(1); - } finally { - cleanupTestWorkspace(); - cleanupContinueGlobalDir(); - } -} - -main(); diff --git a/extensions/vscode/src/test/test-suites/ideUtils.test.ts b/extensions/vscode/src/test/test-suites/ideUtils.test.ts deleted file mode 100644 index 37ba5cc33..000000000 --- a/extensions/vscode/src/test/test-suites/ideUtils.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import assert from "node:assert"; -import path from "node:path"; - -import { describe, test } from "mocha"; -import * as vscode from "vscode"; - -import { VsCodeIdeUtils } from "../../util/ideUtils"; -import { testWorkspacePath } from "../runner/runTestOnVSCodeHost"; - -const util = require("node:util"); -const asyncExec = util.promisify(require("node:child_process").exec); - -/* - TODO check uri => path assumptions, will only work in some environments. -*/ -describe("IDE Utils", () => { - const utils = new VsCodeIdeUtils(); - const testPyPath = path.join(testWorkspacePath, "test.py"); - const testJsPath = path.join(testWorkspacePath, "test-folder", "test.js"); - - test("getWorkspaceDirectories", async () => { - const [dir] = utils.getWorkspaceDirectories(); - assert(dir.toString().endsWith("test-workspace")); - }); - - test("fileExists", async () => { - const exists2 = await utils.fileExists( - vscode.Uri.file(path.join(testWorkspacePath, "test.py")), - ); - assert(exists2); - }); - - test("getOpenFiles", async () => { - let openFiles = utils.getOpenFiles(); - assert(openFiles.length === 0); - // await utils.openFile(testPyPath); - let document = await vscode.workspace.openTextDocument(testPyPath); - await vscode.window.showTextDocument(document, { - preview: false, - }); - openFiles = utils.getOpenFiles(); - assert(openFiles.length === 1); - assert(openFiles[0].fsPath === testPyPath); - - document = await vscode.workspace.openTextDocument(testJsPath); - await vscode.window.showTextDocument(document, { - preview: false, - }); - openFiles = utils.getOpenFiles(); - assert(openFiles.length === 2); - assert(openFiles.find((f) => f.fsPath === testPyPath)); - assert(openFiles.find((f) => f.fsPath === testJsPath)); - }); - - test("getUniqueId", async () => { - const uniqueId = utils.getUniqueId(); - assert(uniqueId.length === 64); - const regex = /^[a-z0-9]+$/; - assert(regex.test(uniqueId)); - }); - - test.skip("getTerminalContents", async () => { - await new Promise((resolve) => setTimeout(resolve, 1000)); - const terminal = vscode.window.createTerminal(); - await new Promise((resolve) => setTimeout(resolve, 1000)); - terminal.show(); - await new Promise((resolve) => setTimeout(resolve, 1000)); - terminal.sendText("echo abcdefg", true); - const contents = await utils.getTerminalContents(1); - console.log("TERMINAL CONTENTS: ", contents); - assert(contents.includes("abcdefg")); - terminal.dispose(); - }); - - test("noDiff", async () => { - const noDiff = await utils.getDiff(false); - assert(noDiff.length === 0); - }); - - test.skip("getBranch", async () => { - const uri = vscode.Uri.file(testWorkspacePath); - const branch = await utils.getBranch(uri); - assert(typeof branch === "string"); - const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", { - cwd: __dirname, - }); - assert(branch === stdout?.trim()); - }); -}); diff --git a/extensions/vscode/src/util/editLoggingUtils.ts b/extensions/vscode/src/util/editLoggingUtils.ts new file mode 100644 index 000000000..90992db2e --- /dev/null +++ b/extensions/vscode/src/util/editLoggingUtils.ts @@ -0,0 +1,91 @@ +import { IDE, Position, Range, RangeInFileWithNextEditInfo } from "core"; +import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types"; +import { GetLspDefinitionsFunction } from "core/autocomplete/types"; +import { ConfigHandler } from "core/config/ConfigHandler"; +import { RecentlyEditedRange } from "core/nextEdit/types"; +import * as vscode from "vscode"; +import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; + +export const getBeforeCursorPos = (range: Range, activePos: Position) => { + // whichever side of the range isn't active is the before position + if ( + range.start.line === activePos.line && + range.start.character === activePos.character + ) { + return range.end as Position; + } else { + return range.start as Position; + } +}; + +const getWorkspaceDirInfo = async ( + event: vscode.TextDocumentChangeEvent, + ide: IDE, +) => { + // gets the workspace dir uri and checks if it's the open-source continue repo + const workspaceFolder = vscode.workspace.getWorkspaceFolder( + event.document.uri, + ); + if (!workspaceFolder) { + return false; + } + const workspaceDirUri = workspaceFolder.uri.toString(); + const repoName = await ide.getRepoName(workspaceDirUri); + return { + workspaceDirUri: workspaceDirUri, + isContinueRepo: repoName === "continuedev/continue", + }; +}; + +export const handleTextDocumentChange = async ( + event: vscode.TextDocumentChangeEvent, + configHandler: ConfigHandler, + ide: IDE, + completionProvider: ContinueCompletionProvider, + getDefinitionsFromLsp: GetLspDefinitionsFunction, +) => { + const changes = event.contentChanges; + const editor = vscode.window.activeTextEditor; + const { config } = await configHandler.loadConfig(); + + if (!config?.experimental?.logEditingData) return; + if (!editor) return; + if (event.contentChanges.length === 0) return; + + // Ensure that loggin will only happen in the open-source continue repo + const workspaceDirInfo = await getWorkspaceDirInfo(event, ide); + if (!workspaceDirInfo) return; + // if (!workspaceDirInfo.isContinueRepo) return; + + const activeCursorPos = editor.selection.active; + const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({ + filepath: event.document.uri.toString(), + range: { + start: change.range.start as Position, + end: change.range.end as Position, + }, + fileContents: event.document.getText(), + editText: change.text, + beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos), + afterCursorPos: activeCursorPos as Position, + workspaceDir: workspaceDirInfo.workspaceDirUri, + })); + + let recentlyEditedRanges: RecentlyEditedRange[] = []; + let recentlyVisitedRanges: AutocompleteCodeSnippet[] = []; + + if (completionProvider) { + recentlyEditedRanges = + await completionProvider.recentlyEditedTracker.getRecentlyEditedRanges(); + recentlyVisitedRanges = + completionProvider.recentlyVisitedRanges.getSnippets(); + } + + return { + actions: editActions, + configHandler: configHandler, + getDefsFromLspFunction: getDefinitionsFromLsp, + recentlyEditedRanges, + recentlyVisitedRanges, + }; +}; diff --git a/extensions/vscode/src/util/getTheme.ts b/extensions/vscode/src/util/getTheme.ts index e47dbccfe..a927c36c1 100644 --- a/extensions/vscode/src/util/getTheme.ts +++ b/extensions/vscode/src/util/getTheme.ts @@ -45,6 +45,14 @@ function parseThemeString(themeString: string | undefined): any { return JSON.parse(themeString ?? "{}"); } +export function getThemeString(): string { + const workbenchConfig = vscode.workspace.getConfiguration(); + const themeString = + workbenchConfig.get("workbench.colorTheme") ?? + "Default Dark Modern"; + return themeString; +} + export function getTheme() { let currentTheme: string | undefined = undefined; // Get color theme from settings diff --git a/gui/package-lock.json b/gui/package-lock.json index 873415983..8c53ca7ce 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -31,12 +31,12 @@ "dompurify": "^3.0.6", "downshift": "^7.6.0", "escape-carriage": "^1.3.1", + "handlebars": "^4.7.8", "lodash": "^4.17.21", "lowlight": "^3.3.0", "minisearch": "^7.0.2", "mustache": "^4.2.0", "posthog-js": "^1.130.1", - "prismjs": "^1.29.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-error-boundary": "^4.0.11", @@ -205,6 +205,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" @@ -6304,6 +6305,36 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", "dev": true }, + "node_modules/handlebars": { + "version": "4.7.8", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz", + "integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.5", + "neo-async": "^2.6.2", + "source-map": "^0.6.1", + "wordwrap": "^1.0.0" + }, + "bin": { + "handlebars": "bin/handlebars" + }, + "engines": { + "node": ">=0.4.7" + }, + "optionalDependencies": { + "uglify-js": "^3.1.4" + } + }, + "node_modules/handlebars/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/has-bigints": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", @@ -8778,6 +8809,15 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/minipass": { "version": "7.1.2", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", @@ -8850,6 +8890,12 @@ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "license": "MIT" + }, "node_modules/node-releases": { "version": "2.0.18", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", @@ -12157,6 +12203,19 @@ "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==" }, + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "license": "BSD-2-Clause", + "optional": true, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, "node_modules/unbox-primitive": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", @@ -13753,6 +13812,12 @@ "node": ">=0.10.0" } }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "license": "MIT" + }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", diff --git a/gui/package.json b/gui/package.json index eb4a5a4d0..f98c4499f 100644 --- a/gui/package.json +++ b/gui/package.json @@ -40,12 +40,12 @@ "dompurify": "^3.0.6", "downshift": "^7.6.0", "escape-carriage": "^1.3.1", + "handlebars": "^4.7.8", "lodash": "^4.17.21", "lowlight": "^3.3.0", "minisearch": "^7.0.2", "mustache": "^4.2.0", "posthog-js": "^1.130.1", - "prismjs": "^1.29.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-error-boundary": "^4.0.11", diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index a19b56068..252d19332 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -2,6 +2,9 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../redux/slices/sessionSlice"; import { getMetaKeyLabel } from "../util"; import { ToolTip } from "./gui/Tooltip"; @@ -20,8 +23,21 @@ export default function AcceptRejectAllButtons({ (state) => state.status === "done", ); const ideMessenger = useContext(IdeMessengerContext); - + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, + ); + const dispatch = useAppDispatch(); async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { + if ( + status === "rejectDiff" && + currentToolCallApplyState?.status === "done" + ) { + dispatch( + cancelToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); + } for (const { filepath = "", streamId } of pendingApplyStates) { ideMessenger.post(status, { filepath, diff --git a/gui/src/components/ConversationStarters/ConversationStarterCard.tsx b/gui/src/components/ConversationStarters/ConversationStarterCard.tsx index 29ff81833..64705d99b 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCard.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCard.tsx @@ -1,9 +1,9 @@ import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; -import { SlashCommandDescription } from "core"; +import { SlashCommandDescWithSource } from "core"; interface ConversationStarterCardProps { - command: SlashCommandDescription; - onClick: (command: SlashCommandDescription) => void; + command: SlashCommandDescWithSource; + onClick: (command: SlashCommandDescWithSource) => void; } export function ConversationStarterCard({ diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 776c0721b..696b00527 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -1,4 +1,4 @@ -import { SlashCommandDescription } from "core"; +import { SlashCommandDescWithSource } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -23,8 +23,12 @@ export function ConversationStarterCards() { isCommandBookmarked(command.name), ); - function onClick(command: SlashCommandDescription) { - mainEditor?.commands.insertPrompt(command); + function onClick(command: SlashCommandDescWithSource) { + mainEditor?.commands.insertPrompt({ + description: command.description, + title: command.name, + content: command.prompt, + }); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/ConversationStarters/__tests__/utils.test.ts b/gui/src/components/ConversationStarters/__tests__/utils.test.ts index 3e7050985..86de0f83e 100644 --- a/gui/src/components/ConversationStarters/__tests__/utils.test.ts +++ b/gui/src/components/ConversationStarters/__tests__/utils.test.ts @@ -1,27 +1,35 @@ -import { SlashCommandDescription } from "core"; +import { SlashCommandDescWithSource } from "core"; import { sortCommandsByBookmarkStatus } from "../utils"; describe("sortCommandsByBookmarkStatus", () => { - const mockCommands: SlashCommandDescription[] = [ + const mockCommands: SlashCommandDescWithSource[] = [ { name: "command1", description: "First command", prompt: "This is command 1", + source: "built-in", + isLegacy: false, }, { name: "command2", description: "Second command", prompt: "This is command 2", + source: "built-in", + isLegacy: false, }, { name: "command3", description: "Third command", prompt: "This is command 3", + source: "built-in", + isLegacy: false, }, { name: "command4", description: "Fourth command", prompt: "This is command 4", + source: "built-in", + isLegacy: false, }, ]; diff --git a/gui/src/components/ConversationStarters/utils.ts b/gui/src/components/ConversationStarters/utils.ts index 1f9ef09ae..e10b79237 100644 --- a/gui/src/components/ConversationStarters/utils.ts +++ b/gui/src/components/ConversationStarters/utils.ts @@ -1,4 +1,4 @@ -import { SlashCommandDescription } from "core"; +import { SlashCommandDescWithSource } from "core"; import {} from "core/config/default"; /** @@ -8,9 +8,9 @@ import {} from "core/config/default"; * @returns A new sorted array with bookmarked commands first */ export function sortCommandsByBookmarkStatus( - commands: SlashCommandDescription[], + commands: SlashCommandDescWithSource[], bookmarkedCommands: string[], -): SlashCommandDescription[] { +): SlashCommandDescWithSource[] { return [...commands].sort((a, b) => { const aIsBookmarked = bookmarkedCommands.includes(a.name); const bIsBookmarked = bookmarkedCommands.includes(b.name); diff --git a/gui/src/components/FeedbackButtons.tsx b/gui/src/components/FeedbackButtons.tsx index 6ad0992df..009666859 100644 --- a/gui/src/components/FeedbackButtons.tsx +++ b/gui/src/components/FeedbackButtons.tsx @@ -12,7 +12,7 @@ export interface FeedbackButtonsProps { item: ChatHistoryItem; } -export default function FeedbackButtons({ item }: FeedbackButtonsProps) { +export function FeedbackButtons({ item }: FeedbackButtonsProps) { const [feedback, setFeedback] = useState(undefined); const ideMessenger = useContext(IdeMessengerContext); const sessionId = useAppSelector((store) => store.session.id); @@ -41,7 +41,7 @@ export default function FeedbackButtons({ item }: FeedbackButtonsProps) { onClick={() => sendFeedback(true)} > sendFeedback(false)} > diff --git a/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx b/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx new file mode 100644 index 000000000..28831b15d --- /dev/null +++ b/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx @@ -0,0 +1,300 @@ +import { + createRuleMarkdown, + getRuleType, + RuleType, + RuleTypeDescriptions, +} from "@continuedev/config-yaml"; +import { InformationCircleIcon } from "@heroicons/react/24/outline"; +import { createRuleFilePath } from "core/config/markdown/utils"; +import { CreateRuleBlockArgs } from "core/tools/implementations/createRuleBlock"; +import { useContext, useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import Spinner from "../gui/Spinner"; +import { ToolTip } from "../gui/Tooltip"; +import { Button } from "../ui"; +import { useRuleGeneration } from "./useRuleGeneration"; + +interface GenerationScreenProps { + inputPrompt: string; + onBack: () => void; + onSuccess: () => void; + isManualMode?: boolean; +} + +export function GenerationScreen({ + inputPrompt, + onBack, + onSuccess, + isManualMode = false, +}: GenerationScreenProps) { + const ideMessenger = useContext(IdeMessengerContext); + + const { register, watch, setValue, reset } = useForm({ + defaultValues: { + name: "", + description: "", + globs: "", + alwaysApply: undefined, + rule: "", + }, + }); + + const formData = watch(); + + // Track rule type separately from form data + const [selectedRuleType, setSelectedRuleType] = useState( + RuleType.Always, + ); + const [formError, setFormError] = useState(null); + + // Use the generation hook with the input prompt + const { generateRule, isGenerating, error } = useRuleGeneration( + inputPrompt, + (args) => { + // Streaming causes a lot of jank, so wait until done generating + if (!isGenerating) { + reset(args); + handleRuleTypeChange(getRuleType(args)); + } + }, + ); + + // Start generation once when component mounts (only if not in manual mode) + useEffect(() => { + if (!isManualMode) { + void generateRule(); + } + }, [isManualMode]); + + const handleRuleTypeChange = (newRuleType: RuleType) => { + setSelectedRuleType(newRuleType); + + // Update alwaysApply based on rule type + const alwaysApply = newRuleType === RuleType.Always; + setValue("alwaysApply", alwaysApply); + + // Don't clear optional fields - preserve their state + // Users can manually clear them if needed + }; + + const handleContinue = async () => { + // Clear any previous errors + setFormError(null); + + if (!formData.name) { + setFormError("Rule name is required"); + return; + } + + if (!formData.rule) { + setFormError("Rule content is required"); + return; + } + + try { + const options: any = { + alwaysApply: formData.alwaysApply, + }; + + if (formData.description) { + options.description = formData.description; + } + + if (formData.globs) { + options.globs = formData.globs; + } + + const fileContent = createRuleMarkdown( + formData.name, + formData.rule, + options, + ); + + const workspaceDirs = await ideMessenger.request( + "getWorkspaceDirs", + undefined, + ); + + if (workspaceDirs.status !== "success") { + setFormError("Failed to get workspace directory"); + return; + } + + const localContinueDir = workspaceDirs.content[0]; + const ruleFilePath = createRuleFilePath(localContinueDir, formData.name); + + await ideMessenger.request("writeFile", { + path: ruleFilePath, + contents: fileContent, + }); + ideMessenger.post("openFile", { path: ruleFilePath }); + + onSuccess(); + } catch (err) { + const errorMessage = + err instanceof Error ? err.message : "Unknown error occurred"; + setFormError(`Failed to create rule file: ${errorMessage}`); + } + }; + + const showNameSpinner = isGenerating && !formData.name && !isManualMode; + const tooltipId = "rule-type-tooltip"; + + return ( +
+
+
+

Your rule

+

+ Review and edit your generated rule below +

+
+
+
+ {/* Rule metadata form */} +
+ {/* Rule Name - Always visible */} +
+ +
+ + {showNameSpinner && ( +
+ +
+ )} +
+
+ + {/* Rule Type Selector - Always visible */} +
+
+ + + +
+
+ +
+
+ + {/* Description (for Agent Requested only) */} +
+ +