Changesets · Branches · Tags · Compare
| Changeset | 9b7370a63b4d5b0f3fd04c265fcf2a6f7d7a8e4f76dd6d5ccda43346c4ec039c |
|---|---|
| Author | Kai Wu <wukaixingxp@gmail.com> · 2025-06-30 09:42 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-06-30 09:42 -07:00 |
| Parents | 6a75d4a25a1b, 483c37bb84f4 |
93 files changed
modified .vscode/launch.json +0 −26
| @@ -73,32 +73,6 @@ | ||
| 73 | 73 | "sourceMaps": true |
| 74 | 74 | // "preLaunchTask": "gui:dev" |
| 75 | 75 | }, |
| 76 | - // Has to be run after starting the server (separately or using the compound configuration) | |
| 77 | - { | |
| 78 | - "name": "Run tests", | |
| 79 | - "type": "extensionHost", | |
| 80 | - "request": "launch", | |
| 81 | - "cwd": "${workspaceFolder}/extensions/vscode", | |
| 82 | - "runtimeExecutable": "${execPath}", | |
| 83 | - "args": [ | |
| 84 | - // Pass a directory to run tests in | |
| 85 | - "${workspaceFolder}/extensions/vscode/manual-testing-sandbox", | |
| 86 | - "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode", | |
| 87 | - "--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner" | |
| 88 | - ], | |
| 89 | - "outFiles": [ | |
| 90 | - // Allows setting breakpoints in test suites across the /src folder | |
| 91 | - "${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js", | |
| 92 | - // Allows setting breakpoints in mocha test runner file | |
| 93 | - "${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js" | |
| 94 | - ], | |
| 95 | - "internalConsoleOptions": "openOnSessionStart", | |
| 96 | - "preLaunchTask": "vscode-extension:tests:build", | |
| 97 | - "env": { | |
| 98 | - // Avoid timing out when stopping on breakpoints during debugging in VSCode | |
| 99 | - "MOCHA_TIMEOUT": "0" | |
| 100 | - } | |
| 101 | - }, | |
| 102 | 76 | { |
| 103 | 77 | "name": "[Core] Jest Test Debugger, Current Open File", |
| 104 | 78 | "type": "node", |
modified .vscode/tasks.json +0 −33
| @@ -109,39 +109,6 @@ | ||
| 109 | 109 | "cwd": "${workspaceFolder}/extensions/vscode" |
| 110 | 110 | } |
| 111 | 111 | }, |
| 112 | - // | |
| 113 | - // Compile and bundle tests | |
| 114 | - { | |
| 115 | - "label": "vscode-extension:tests:build", | |
| 116 | - "dependsOn": [ | |
| 117 | - // Build the extension | |
| 118 | - "vscode-extension:build", | |
| 119 | - // To detect compile errors - this type checks both the extension and the tests | |
| 120 | - "tsc:watch", | |
| 121 | - "vscode-extension:tests:esbuild" | |
| 122 | - ] | |
| 123 | - }, | |
| 124 | - { | |
| 125 | - "label": "vscode-extension:tests:esbuild", | |
| 126 | - "type": "npm", | |
| 127 | - "script": "build-test", | |
| 128 | - "path": "extensions/vscode", | |
| 129 | - "problemMatcher": [ | |
| 130 | - { | |
| 131 | - "pattern": [ | |
| 132 | - { | |
| 133 | - "regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$", | |
| 134 | - "file": 1, | |
| 135 | - "line": 2, | |
| 136 | - "column": 3, | |
| 137 | - "severity": 4, | |
| 138 | - "message": 5 | |
| 139 | - } | |
| 140 | - ] | |
| 141 | - } | |
| 142 | - ] | |
| 143 | - }, | |
| 144 | - // | |
| 145 | 112 | // Install or update all dependencies for all projects in the monrepo |
| 146 | 113 | { |
| 147 | 114 | "label": "install-all-dependencies", |
deleted core/commands/index.ts +0 −88
| @@ -1,88 +0,0 @@ | ||
| 1 | -import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; | |
| 2 | -import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; | |
| 3 | -import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; | |
| 4 | -import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile"; | |
| 5 | -import { renderChatMessage } from "../util/messageContent"; | |
| 6 | - | |
| 7 | -import SlashCommands from "./slash"; | |
| 8 | - | |
| 9 | -export function slashFromCustomCommand( | |
| 10 | - customCommand: CustomCommand, | |
| 11 | -): SlashCommand { | |
| 12 | - const commandName = customCommand.name.startsWith("/") | |
| 13 | - ? customCommand.name.substring(1) | |
| 14 | - : customCommand.name; | |
| 15 | - return { | |
| 16 | - name: commandName, | |
| 17 | - description: customCommand.description ?? "", | |
| 18 | - prompt: customCommand.prompt, | |
| 19 | - run: async function* ({ | |
| 20 | - input, | |
| 21 | - llm, | |
| 22 | - history, | |
| 23 | - ide, | |
| 24 | - completionOptions, | |
| 25 | - config, | |
| 26 | - selectedCode, | |
| 27 | - fetch, | |
| 28 | - abortController, | |
| 29 | - }) { | |
| 30 | - // Render prompt template | |
| 31 | - let renderedPrompt: string; | |
| 32 | - if (customCommand.prompt.includes("{{{ input }}}")) { | |
| 33 | - renderedPrompt = await renderTemplatedString( | |
| 34 | - customCommand.prompt, | |
| 35 | - ide.readFile.bind(ide), | |
| 36 | - { input }, | |
| 37 | - ); | |
| 38 | - } else { | |
| 39 | - const renderedPromptFile = await renderPromptFileV2( | |
| 40 | - customCommand.prompt, | |
| 41 | - { | |
| 42 | - config, | |
| 43 | - llm, | |
| 44 | - ide, | |
| 45 | - selectedCode, | |
| 46 | - fetch, | |
| 47 | - fullInput: input, | |
| 48 | - embeddingsProvider: config.modelsByRole.embed[0], | |
| 49 | - reranker: config.modelsByRole.rerank[0], | |
| 50 | - }, | |
| 51 | - ); | |
| 52 | - | |
| 53 | - renderedPrompt = renderedPromptFile[1]; | |
| 54 | - } | |
| 55 | - | |
| 56 | - // Replaces slash command messages with the rendered prompt | |
| 57 | - // which INCLUDES the input | |
| 58 | - const messages = replaceSlashCommandWithPromptInChatHistory( | |
| 59 | - history, | |
| 60 | - commandName, | |
| 61 | - renderedPrompt, | |
| 62 | - undefined, | |
| 63 | - ); | |
| 64 | - | |
| 65 | - for await (const chunk of llm.streamChat( | |
| 66 | - messages, | |
| 67 | - abortController.signal, | |
| 68 | - completionOptions, | |
| 69 | - )) { | |
| 70 | - yield renderChatMessage(chunk); | |
| 71 | - } | |
| 72 | - }, | |
| 73 | - }; | |
| 74 | -} | |
| 75 | - | |
| 76 | -export function slashCommandFromDescription( | |
| 77 | - desc: SlashCommandDescription, | |
| 78 | -): SlashCommand | undefined { | |
| 79 | - const cmd = SlashCommands.find((cmd) => cmd.name === desc.name); | |
| 80 | - if (!cmd) { | |
| 81 | - return undefined; | |
| 82 | - } | |
| 83 | - return { | |
| 84 | - ...cmd, | |
| 85 | - params: desc.params, | |
| 86 | - description: desc.description ?? cmd.description, | |
| 87 | - }; | |
| 88 | -} |
added core/commands/slash/built-in-legacy/cmd.ts +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +import { streamLines } from "../../../diff/util.js"; | |
| 2 | +import { SlashCommand } from "../../../index.js"; | |
| 3 | +import { removeQuotesAndEscapes } from "../../../util/index.js"; | |
| 4 | + | |
| 5 | +function commandIsPotentiallyDangerous(command: string) { | |
| 6 | + return ( | |
| 7 | + command.includes("rm -rf") || | |
| 8 | + command.includes("sudo") || | |
| 9 | + command.includes("cd / ") | |
| 10 | + ); | |
| 11 | +} | |
| 12 | + | |
| 13 | +const GenerateTerminalCommand: SlashCommand = { | |
| 14 | + name: "cmd", | |
| 15 | + description: "Generate a shell command", | |
| 16 | + run: async function* ({ ide, llm, input }) { | |
| 17 | + if (input.trim() === "") { | |
| 18 | + yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'."; | |
| 19 | + return; | |
| 20 | + } | |
| 21 | + | |
| 22 | + const gen = llm.streamComplete( | |
| 23 | + `The user has made a request to run a shell command. Their description of what it should do is: | |
| 24 | + | |
| 25 | +"${input}" | |
| 26 | + | |
| 27 | +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, | |
| 28 | + new AbortController().signal, | |
| 29 | + ); | |
| 30 | + | |
| 31 | + const lines = streamLines(gen); | |
| 32 | + let cmd = ""; | |
| 33 | + for await (const line of lines) { | |
| 34 | + console.log(line); | |
| 35 | + if (line.startsWith("```") && line.endsWith("```")) { | |
| 36 | + cmd = line.split(" ").slice(1).join(" ").slice(0, -3); | |
| 37 | + break; | |
| 38 | + } | |
| 39 | + | |
| 40 | + if ( | |
| 41 | + line.startsWith(">") || | |
| 42 | + line.startsWith("``") || | |
| 43 | + line.startsWith("\\begin{") || | |
| 44 | + line.trim() === "" | |
| 45 | + ) { | |
| 46 | + continue; | |
| 47 | + } | |
| 48 | + | |
| 49 | + cmd = removeQuotesAndEscapes(line.trim()); | |
| 50 | + break; | |
| 51 | + } | |
| 52 | + | |
| 53 | + yield `Generated shell command: ${cmd}`; | |
| 54 | + if (commandIsPotentiallyDangerous(cmd)) { | |
| 55 | + yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal."; | |
| 56 | + } else { | |
| 57 | + await ide.runCommand(cmd); | |
| 58 | + } | |
| 59 | + }, | |
| 60 | +}; | |
| 61 | + | |
| 62 | +export default GenerateTerminalCommand; |
added core/commands/slash/built-in-legacy/commit.ts +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +import { SlashCommand } from "../../../index.js"; | |
| 2 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 3 | + | |
| 4 | +const CommitMessageCommand: SlashCommand = { | |
| 5 | + name: "commit", | |
| 6 | + description: "Generate a commit message for current changes", | |
| 7 | + run: async function* ({ ide, llm, params, abortController }) { | |
| 8 | + const includeUnstaged = params?.includeUnstaged ?? false; | |
| 9 | + const diff = await ide.getDiff(includeUnstaged); | |
| 10 | + | |
| 11 | + if (diff.length === 0) { | |
| 12 | + yield "No changes detected. Make sure you are in a git repository with current changes."; | |
| 13 | + return; | |
| 14 | + } | |
| 15 | + | |
| 16 | + const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; | |
| 17 | + for await (const chunk of llm.streamChat( | |
| 18 | + [{ role: "user", content: prompt }], | |
| 19 | + abortController.signal, | |
| 20 | + )) { | |
| 21 | + yield renderChatMessage(chunk); | |
| 22 | + } | |
| 23 | + }, | |
| 24 | +}; | |
| 25 | + | |
| 26 | +export default CommitMessageCommand; |
added core/commands/slash/built-in-legacy/draftIssue.ts +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +import { ChatMessage, SlashCommand } from "../../../index.js"; | |
| 2 | +import { removeQuotesAndEscapes } from "../../../util/index.js"; | |
| 3 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 4 | + | |
| 5 | +const PROMPT = ( | |
| 6 | + input: string, | |
| 7 | + title: string, | |
| 8 | +) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules: | |
| 9 | +- Be descriptive but do not make up details | |
| 10 | +- If the the user request includes any code snippets that are relevant, reference them in code blocks | |
| 11 | +- Describe step by step how to reproduce the problem | |
| 12 | +- Describe the ideal solution to the problem | |
| 13 | +- Describe the expected behavior after the issue has been resolved | |
| 14 | +- This issue will be read by a team member | |
| 15 | +- Use markdown formatting, but you do not need to surround the entire body with triple backticks | |
| 16 | +{additional_instructions} | |
| 17 | + | |
| 18 | +Here is the user request: '${input}' | |
| 19 | + | |
| 20 | +Title: ${title} | |
| 21 | + | |
| 22 | +Body:\n\n`; | |
| 23 | + | |
| 24 | +const DraftIssueCommand: SlashCommand = { | |
| 25 | + name: "issue", | |
| 26 | + description: "Draft a GitHub issue", | |
| 27 | + run: async function* ({ input, llm, history, params, abortController }) { | |
| 28 | + if (params?.repositoryUrl === undefined) { | |
| 29 | + yield "This command requires a repository URL to be set in the config file."; | |
| 30 | + return; | |
| 31 | + } | |
| 32 | + let title = await llm.complete( | |
| 33 | + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, | |
| 34 | + new AbortController().signal, | |
| 35 | + { maxTokens: 30 }, | |
| 36 | + ); | |
| 37 | + | |
| 38 | + title = `${removeQuotesAndEscapes(title.trim())}\n\n`; | |
| 39 | + yield title; | |
| 40 | + | |
| 41 | + let body = ""; | |
| 42 | + const messages: ChatMessage[] = [ | |
| 43 | + ...history.filter((msg) => msg.role !== "system"), | |
| 44 | + { role: "user", content: PROMPT(input, title) }, | |
| 45 | + ]; | |
| 46 | + | |
| 47 | + for await (const chunk of llm.streamChat( | |
| 48 | + messages, | |
| 49 | + abortController.signal, | |
| 50 | + )) { | |
| 51 | + body += chunk.content; | |
| 52 | + yield renderChatMessage(chunk); | |
| 53 | + } | |
| 54 | + | |
| 55 | + const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( | |
| 56 | + title, | |
| 57 | + )}&body=${encodeURIComponent(body)}`; | |
| 58 | + yield `\n\n[Link to draft of issue](${url})`; | |
| 59 | + }, | |
| 60 | +}; | |
| 61 | + | |
| 62 | +export default DraftIssueCommand; |
added core/commands/slash/built-in-legacy/http.ts +33 −0
| @@ -0,0 +1,33 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 2 | +import { SlashCommand } from "../../../index.js"; | |
| 3 | +import { removeQuotesAndEscapes } from "../../../util/index.js"; | |
| 4 | + | |
| 5 | +const HttpSlashCommand: SlashCommand = { | |
| 6 | + name: "http", | |
| 7 | + description: "Call an HTTP endpoint to serve response", | |
| 8 | + run: async function* ({ ide, llm, input, params, fetch }) { | |
| 9 | + const url = params?.url; | |
| 10 | + if (!url) { | |
| 11 | + throw new Error("URL is not defined in params"); | |
| 12 | + } | |
| 13 | + const response = await fetch(url, { | |
| 14 | + method: "POST", | |
| 15 | + headers: { | |
| 16 | + "Content-Type": "application/json", | |
| 17 | + }, | |
| 18 | + body: JSON.stringify({ | |
| 19 | + input: removeQuotesAndEscapes(input), | |
| 20 | + }), | |
| 21 | + }); | |
| 22 | + | |
| 23 | + // Stream the response | |
| 24 | + if (response.body === null) { | |
| 25 | + throw new Error("Response body is null"); | |
| 26 | + } | |
| 27 | + for await (const chunk of streamResponse(response)) { | |
| 28 | + yield chunk; | |
| 29 | + } | |
| 30 | + }, | |
| 31 | +}; | |
| 32 | + | |
| 33 | +export default HttpSlashCommand; |
added core/commands/slash/built-in-legacy/index.ts +37 −0
| @@ -0,0 +1,37 @@ | ||
| 1 | +import { | |
| 2 | + SlashCommand, | |
| 3 | + SlashCommandDescription, | |
| 4 | + SlashCommandWithSource, | |
| 5 | +} from "../../.."; | |
| 6 | +import GenerateTerminalCommand from "./cmd"; | |
| 7 | +import CommitMessageCommand from "./commit"; | |
| 8 | +import DraftIssueCommand from "./draftIssue"; | |
| 9 | +import HttpSlashCommand from "./http"; | |
| 10 | +import OnboardSlashCommand from "./onboard"; | |
| 11 | +import ReviewMessageCommand from "./review"; | |
| 12 | +import ShareSlashCommand from "./share"; | |
| 13 | + | |
| 14 | +const LegacyBuiltInSlashCommands: SlashCommand[] = [ | |
| 15 | + DraftIssueCommand, | |
| 16 | + ShareSlashCommand, | |
| 17 | + GenerateTerminalCommand, | |
| 18 | + HttpSlashCommand, | |
| 19 | + CommitMessageCommand, | |
| 20 | + ReviewMessageCommand, | |
| 21 | + OnboardSlashCommand, | |
| 22 | +]; | |
| 23 | + | |
| 24 | +export function getLegacyBuiltInSlashCommandFromDescription( | |
| 25 | + desc: SlashCommandDescription, | |
| 26 | +): SlashCommandWithSource | undefined { | |
| 27 | + const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name); | |
| 28 | + if (!cmd) { | |
| 29 | + return undefined; | |
| 30 | + } | |
| 31 | + return { | |
| 32 | + ...cmd, | |
| 33 | + params: desc.params, | |
| 34 | + description: desc.description ?? cmd.description, | |
| 35 | + source: "built-in-legacy", | |
| 36 | + }; | |
| 37 | +} |
added core/commands/slash/built-in-legacy/onboard.ts +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +import ignore from "ignore"; | |
| 2 | + | |
| 3 | +import type { FileType, IDE, SlashCommand } from "../../.."; | |
| 4 | +import { | |
| 5 | + DEFAULT_IGNORE, | |
| 6 | + getGlobalContinueIgArray, | |
| 7 | + gitIgArrayFromFile, | |
| 8 | +} from "../../../indexing/ignore"; | |
| 9 | +import { renderChatMessage } from "../../../util/messageContent"; | |
| 10 | +import { | |
| 11 | + findUriInDirs, | |
| 12 | + getUriPathBasename, | |
| 13 | + joinPathsToUri, | |
| 14 | +} from "../../../util/uri"; | |
| 15 | + | |
| 16 | +const LANGUAGE_DEP_MGMT_FILENAMES = [ | |
| 17 | + "package.json", // JavaScript (Node.js) | |
| 18 | + "requirements.txt", // Python | |
| 19 | + "Gemfile", // Ruby | |
| 20 | + "pom.xml", // Java (Maven) | |
| 21 | + "build.gradle", // Java (Gradle) | |
| 22 | + "composer.json", // PHP | |
| 23 | + "Cargo.toml", // Rust | |
| 24 | + "go.mod", // Go | |
| 25 | + "packages.config", // C# (.NET) | |
| 26 | + "*.csproj", // C# (.NET Core) | |
| 27 | + "pubspec.yaml", // Dart | |
| 28 | + "Project.toml", // Julia | |
| 29 | + "mix.exs", // Elixir | |
| 30 | + "rebar.config", // Erlang | |
| 31 | + "shard.yml", // Crystal | |
| 32 | + "Package.swift", // Swift | |
| 33 | + "dependencies.gradle", // Kotlin (when using Gradle) | |
| 34 | + "Podfile", // Objective-C/Swift (CocoaPods) | |
| 35 | + "*.cabal", // Haskell | |
| 36 | + "dub.json", // D | |
| 37 | +]; | |
| 38 | + | |
| 39 | +const MAX_EXPLORE_DEPTH = 2; | |
| 40 | + | |
| 41 | +const OnboardSlashCommand: SlashCommand = { | |
| 42 | + name: "onboard", | |
| 43 | + description: "Familiarize yourself with the codebase", | |
| 44 | + run: async function* ({ llm, ide, abortController }) { | |
| 45 | + const [workspaceDir] = await ide.getWorkspaceDirs(); | |
| 46 | + | |
| 47 | + const context = await gatherProjectContext(workspaceDir, ide); | |
| 48 | + const prompt = createOnboardingPrompt(context); | |
| 49 | + | |
| 50 | + for await (const chunk of llm.streamChat( | |
| 51 | + [{ role: "user", content: prompt }], | |
| 52 | + abortController.signal, | |
| 53 | + )) { | |
| 54 | + yield renderChatMessage(chunk); | |
| 55 | + } | |
| 56 | + }, | |
| 57 | +}; | |
| 58 | + | |
| 59 | +async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { | |
| 60 | + const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); | |
| 61 | + const entries = await ide.listDir(dir); | |
| 62 | + | |
| 63 | + const ignoreUri = joinPathsToUri(dir, ".gitignore"); | |
| 64 | + const fileExists = await ide.fileExists(ignoreUri); | |
| 65 | + | |
| 66 | + if (fileExists) { | |
| 67 | + const gitIgnore = await ide.readFile(ignoreUri); | |
| 68 | + const igPatterns = gitIgArrayFromFile(gitIgnore); | |
| 69 | + | |
| 70 | + ig.add(igPatterns); | |
| 71 | + } | |
| 72 | + | |
| 73 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 74 | + | |
| 75 | + const withRelativePaths = entries | |
| 76 | + .filter( | |
| 77 | + (entry) => | |
| 78 | + entry[1] === (1 as FileType.File) || | |
| 79 | + entry[1] === (2 as FileType.Directory), | |
| 80 | + ) | |
| 81 | + .map((entry) => { | |
| 82 | + const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs); | |
| 83 | + return { | |
| 84 | + uri: entry[0], | |
| 85 | + type: entry[1], | |
| 86 | + basename: getUriPathBasename(entry[0]), | |
| 87 | + relativePath: | |
| 88 | + relativePathOrBasename + | |
| 89 | + (entry[1] === (2 as FileType.Directory) ? "/" : ""), | |
| 90 | + }; | |
| 91 | + }); | |
| 92 | + | |
| 93 | + return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath)); | |
| 94 | +} | |
| 95 | + | |
| 96 | +async function gatherProjectContext( | |
| 97 | + workspaceDir: string, | |
| 98 | + ide: IDE, | |
| 99 | +): Promise<string> { | |
| 100 | + let context = ""; | |
| 101 | + async function exploreDirectory(dir: string, currentDepth: number = 0) { | |
| 102 | + if (currentDepth > MAX_EXPLORE_DEPTH) { | |
| 103 | + return; | |
| 104 | + } | |
| 105 | + | |
| 106 | + const entries = await getEntriesFilteredByIgnore(dir, ide); | |
| 107 | + | |
| 108 | + for (const entry of entries) { | |
| 109 | + if (entry.type === (2 as FileType.Directory)) { | |
| 110 | + context += `\nFolder: ${entry.relativePath}\n`; | |
| 111 | + await exploreDirectory(entry.uri, currentDepth + 1); | |
| 112 | + } else { | |
| 113 | + if (entry.basename.toLowerCase() === "readme.md") { | |
| 114 | + const content = await ide.readFile(entry.uri); | |
| 115 | + context += `README for ${entry.relativePath}:\n${content}\n\n`; | |
| 116 | + } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) { | |
| 117 | + const content = await ide.readFile(entry.uri); | |
| 118 | + context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`; | |
| 119 | + } | |
| 120 | + } | |
| 121 | + } | |
| 122 | + } | |
| 123 | + | |
| 124 | + await exploreDirectory(workspaceDir); | |
| 125 | + | |
| 126 | + return context; | |
| 127 | +} | |
| 128 | + | |
| 129 | +function createOnboardingPrompt(context: string): string { | |
| 130 | + return ` | |
| 131 | + As a helpful AI assistant, your task is to onboard a new developer to this project. | |
| 132 | + Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview: | |
| 133 | + | |
| 134 | + ${context} | |
| 135 | + | |
| 136 | + Please provide an overview of the project with the following guidelines: | |
| 137 | + - Determine the most important folders in the project, at most 10 | |
| 138 | + - Go through each important folder step-by-step: | |
| 139 | + - Explain what each folder does in isolation by summarzing the README or package.json file, if available | |
| 140 | + - Mention the most popular or common packages used in that folder and their roles. | |
| 141 | + - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture: | |
| 142 | + - How different parts of the codebase fit together. | |
| 143 | + - The overall project architecture or design patterns evident from the folder structure and dependencies. | |
| 144 | + - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown. | |
| 145 | + | |
| 146 | + Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. | |
| 147 | + | |
| 148 | + Here is an example of a valid response: | |
| 149 | + | |
| 150 | + ## Important folders | |
| 151 | + | |
| 152 | + ### /folder1 | |
| 153 | + - Description: Contains the main application logic. | |
| 154 | + - Key packages: Express.js for routing, Mongoose for database operations. | |
| 155 | + | |
| 156 | + #### /folder1/folder2 | |
| 157 | + | |
| 158 | + ## Project Architecture | |
| 159 | + - The frontend is built using React and Redux for state management. | |
| 160 | + - The backend is a Node.js application using Express.js for routing and Mongoose for database operations. | |
| 161 | + - The application follows a Model-View-Controller (MVC) architecture. | |
| 162 | + | |
| 163 | + ## Additional Insights | |
| 164 | + - The project is using a monorepo structure. | |
| 165 | + - The project uses TypeScript for type checking. | |
| 166 | + `; | |
| 167 | +} | |
| 168 | + | |
| 169 | +export default OnboardSlashCommand; |
added core/commands/slash/built-in-legacy/review.ts +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +import { ChatMessage, SlashCommand } from "../../../index.js"; | |
| 2 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 3 | + | |
| 4 | +const prompt = ` | |
| 5 | + Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: | |
| 6 | + | |
| 7 | + Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements. | |
| 8 | + Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts. | |
| 9 | + Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly. | |
| 10 | + Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability. | |
| 11 | + Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`; | |
| 12 | + | |
| 13 | +function getLastUserHistory(history: ChatMessage[]): string { | |
| 14 | + const lastUserHistory = history | |
| 15 | + .reverse() | |
| 16 | + .find((message) => message.role === "user"); | |
| 17 | + | |
| 18 | + if (!lastUserHistory) { | |
| 19 | + return ""; | |
| 20 | + } | |
| 21 | + | |
| 22 | + if (Array.isArray(lastUserHistory.content)) { | |
| 23 | + return lastUserHistory.content.reduce( | |
| 24 | + (acc: string, current: { type: string; text?: string }) => { | |
| 25 | + return current.type === "text" && current.text | |
| 26 | + ? acc + current.text | |
| 27 | + : acc; | |
| 28 | + }, | |
| 29 | + "", | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + | |
| 33 | + return typeof lastUserHistory.content === "string" | |
| 34 | + ? lastUserHistory.content | |
| 35 | + : ""; | |
| 36 | +} | |
| 37 | + | |
| 38 | +const ReviewMessageCommand: SlashCommand = { | |
| 39 | + name: "review", | |
| 40 | + description: "Review code and give feedback", | |
| 41 | + run: async function* ({ llm, history, abortController }) { | |
| 42 | + const reviewText = getLastUserHistory(history).replace("\\review", ""); | |
| 43 | + | |
| 44 | + const content = `${prompt} \r\n ${reviewText}`; | |
| 45 | + | |
| 46 | + for await (const chunk of llm.streamChat( | |
| 47 | + [{ role: "user", content: content }], | |
| 48 | + abortController.signal, | |
| 49 | + )) { | |
| 50 | + yield renderChatMessage(chunk); | |
| 51 | + } | |
| 52 | + }, | |
| 53 | +}; | |
| 54 | + | |
| 55 | +export default ReviewMessageCommand; |
added core/commands/slash/built-in-legacy/share.ts +101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import { homedir } from "node:os"; | |
| 3 | +import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 4 | +import path from "path"; | |
| 5 | + | |
| 6 | +import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js"; | |
| 7 | +import { SlashCommand } from "../../../index.js"; | |
| 8 | +import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 9 | +import { getContinueGlobalPath } from "../../../util/paths.js"; | |
| 10 | + | |
| 11 | +// If useful elsewhere, helper funcs should move to core/util/index.ts or similar | |
| 12 | +function getOffsetDatetime(date: Date): Date { | |
| 13 | + const offset = date.getTimezoneOffset(); | |
| 14 | + const offsetHours = Math.floor(offset / 60); | |
| 15 | + const offsetMinutes = offset % 60; | |
| 16 | + date.setHours(date.getHours() - offsetHours); | |
| 17 | + date.setMinutes(date.getMinutes() - offsetMinutes); | |
| 18 | + | |
| 19 | + return date; | |
| 20 | +} | |
| 21 | + | |
| 22 | +function asBasicISOString(date: Date): string { | |
| 23 | + const isoString = date.toISOString(); | |
| 24 | + | |
| 25 | + return isoString.replace(/[-:]|(\.\d+Z)/g, ""); | |
| 26 | +} | |
| 27 | + | |
| 28 | +function reformatCodeBlocks(msgText: string): string { | |
| 29 | + const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; | |
| 30 | + msgText = msgText.replace( | |
| 31 | + codeBlockFenceRegex, | |
| 32 | + (match, metadata, filename, extension) => { | |
| 33 | + const lang = languageForFilepath(filename); | |
| 34 | + return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; | |
| 35 | + }, | |
| 36 | + ); | |
| 37 | + // Appease the markdown linter | |
| 38 | + return msgText.replace(/```\n```/g, "```\n\n```"); | |
| 39 | +} | |
| 40 | + | |
| 41 | +const ShareSlashCommand: SlashCommand = { | |
| 42 | + name: "share", | |
| 43 | + description: "Export the current chat session to markdown", | |
| 44 | + run: async function* ({ ide, history, params }) { | |
| 45 | + const now = new Date(); | |
| 46 | + | |
| 47 | + let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; | |
| 48 | + | |
| 49 | + // As currently implemented, the /share command is by definition the last | |
| 50 | + // message in the chat history, this will omit it | |
| 51 | + for (const msg of history.slice(0, history.length - 1)) { | |
| 52 | + let msgText = msg.content; | |
| 53 | + msgText = renderChatMessage(msg); | |
| 54 | + | |
| 55 | + if (msg.role === "user" && msgText.search("```") > -1) { | |
| 56 | + msgText = reformatCodeBlocks(msgText); | |
| 57 | + } | |
| 58 | + | |
| 59 | + // format messages as blockquotes | |
| 60 | + msgText = msgText.replace(/^/gm, "> "); | |
| 61 | + | |
| 62 | + content += `\n\n#### ${ | |
| 63 | + msg.role === "user" ? "_User_" : "_Assistant_" | |
| 64 | + }\n\n${msgText}`; | |
| 65 | + } | |
| 66 | + | |
| 67 | + let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); | |
| 68 | + | |
| 69 | + if (outputDir.startsWith("~")) { | |
| 70 | + outputDir = outputDir.replace(/^~/, homedir); | |
| 71 | + } else if ( | |
| 72 | + outputDir.startsWith("./") || | |
| 73 | + outputDir.startsWith(".\\") || | |
| 74 | + outputDir === "." | |
| 75 | + ) { | |
| 76 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 77 | + // Although the most common situation is to have one directory open in a | |
| 78 | + // workspace it's also possible to have just a file open without an | |
| 79 | + // associated directory or to use multi-root workspaces in which multiple | |
| 80 | + // folders are included. We default to using the first item in the list, if | |
| 81 | + // it exists. | |
| 82 | + const workspaceDirectory = workspaceDirs?.[0] || ""; | |
| 83 | + outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); | |
| 84 | + } | |
| 85 | + | |
| 86 | + if (!fs.existsSync(outputDir)) { | |
| 87 | + fs.mkdirSync(outputDir, { recursive: true }); | |
| 88 | + } | |
| 89 | + | |
| 90 | + const dtString = asBasicISOString(getOffsetDatetime(now)); | |
| 91 | + const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? | |
| 92 | + | |
| 93 | + const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ | |
| 94 | + await ide.writeFile(fileUrl, content); | |
| 95 | + await ide.openFile(fileUrl); | |
| 96 | + | |
| 97 | + yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; | |
| 98 | + }, | |
| 99 | +}; | |
| 100 | + | |
| 101 | +export default ShareSlashCommand; |
deleted core/commands/slash/cmd.ts +0 −62
| @@ -1,62 +0,0 @@ | ||
| 1 | -import { streamLines } from "../../diff/util.js"; | |
| 2 | -import { SlashCommand } from "../../index.js"; | |
| 3 | -import { removeQuotesAndEscapes } from "../../util/index.js"; | |
| 4 | - | |
| 5 | -function commandIsPotentiallyDangerous(command: string) { | |
| 6 | - return ( | |
| 7 | - command.includes("rm -rf") || | |
| 8 | - command.includes("sudo") || | |
| 9 | - command.includes("cd / ") | |
| 10 | - ); | |
| 11 | -} | |
| 12 | - | |
| 13 | -const GenerateTerminalCommand: SlashCommand = { | |
| 14 | - name: "cmd", | |
| 15 | - description: "Generate a shell command", | |
| 16 | - run: async function* ({ ide, llm, input }) { | |
| 17 | - if (input.trim() === "") { | |
| 18 | - yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'."; | |
| 19 | - return; | |
| 20 | - } | |
| 21 | - | |
| 22 | - const gen = llm.streamComplete( | |
| 23 | - `The user has made a request to run a shell command. Their description of what it should do is: | |
| 24 | - | |
| 25 | -"${input}" | |
| 26 | - | |
| 27 | -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, | |
| 28 | - new AbortController().signal, | |
| 29 | - ); | |
| 30 | - | |
| 31 | - const lines = streamLines(gen); | |
| 32 | - let cmd = ""; | |
| 33 | - for await (const line of lines) { | |
| 34 | - console.log(line); | |
| 35 | - if (line.startsWith("```") && line.endsWith("```")) { | |
| 36 | - cmd = line.split(" ").slice(1).join(" ").slice(0, -3); | |
| 37 | - break; | |
| 38 | - } | |
| 39 | - | |
| 40 | - if ( | |
| 41 | - line.startsWith(">") || | |
| 42 | - line.startsWith("``") || | |
| 43 | - line.startsWith("\\begin{") || | |
| 44 | - line.trim() === "" | |
| 45 | - ) { | |
| 46 | - continue; | |
| 47 | - } | |
| 48 | - | |
| 49 | - cmd = removeQuotesAndEscapes(line.trim()); | |
| 50 | - break; | |
| 51 | - } | |
| 52 | - | |
| 53 | - yield `Generated shell command: ${cmd}`; | |
| 54 | - if (commandIsPotentiallyDangerous(cmd)) { | |
| 55 | - yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal."; | |
| 56 | - } else { | |
| 57 | - await ide.runCommand(cmd); | |
| 58 | - } | |
| 59 | - }, | |
| 60 | -}; | |
| 61 | - | |
| 62 | -export default GenerateTerminalCommand; |
deleted core/commands/slash/commit.ts +0 −26
| @@ -1,26 +0,0 @@ | ||
| 1 | -import { SlashCommand } from "../../index.js"; | |
| 2 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 3 | - | |
| 4 | -const CommitMessageCommand: SlashCommand = { | |
| 5 | - name: "commit", | |
| 6 | - description: "Generate a commit message for current changes", | |
| 7 | - run: async function* ({ ide, llm, params, abortController }) { | |
| 8 | - const includeUnstaged = params?.includeUnstaged ?? false; | |
| 9 | - const diff = await ide.getDiff(includeUnstaged); | |
| 10 | - | |
| 11 | - if (diff.length === 0) { | |
| 12 | - yield "No changes detected. Make sure you are in a git repository with current changes."; | |
| 13 | - return; | |
| 14 | - } | |
| 15 | - | |
| 16 | - const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; | |
| 17 | - for await (const chunk of llm.streamChat( | |
| 18 | - [{ role: "user", content: prompt }], | |
| 19 | - abortController.signal, | |
| 20 | - )) { | |
| 21 | - yield renderChatMessage(chunk); | |
| 22 | - } | |
| 23 | - }, | |
| 24 | -}; | |
| 25 | - | |
| 26 | -export default CommitMessageCommand; |
added core/commands/slash/customSlashCommand.ts +15 −0
| @@ -0,0 +1,15 @@ | ||
| 1 | +import { CustomCommand, SlashCommandWithSource } from "../.."; | |
| 2 | + | |
| 3 | +export function convertCustomCommandToSlashCommand( | |
| 4 | + customCommand: CustomCommand, | |
| 5 | +): SlashCommandWithSource { | |
| 6 | + const commandName = customCommand.name.startsWith("/") | |
| 7 | + ? customCommand.name.substring(1) | |
| 8 | + : customCommand.name; | |
| 9 | + return { | |
| 10 | + name: commandName, | |
| 11 | + description: customCommand.description ?? "", | |
| 12 | + prompt: customCommand.prompt, | |
| 13 | + source: "json-custom-command", | |
| 14 | + }; | |
| 15 | +} |
deleted core/commands/slash/draftIssue.ts +0 −62
| @@ -1,62 +0,0 @@ | ||
| 1 | -import { ChatMessage, SlashCommand } from "../../index.js"; | |
| 2 | -import { removeQuotesAndEscapes } from "../../util/index.js"; | |
| 3 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 4 | - | |
| 5 | -const PROMPT = ( | |
| 6 | - input: string, | |
| 7 | - title: string, | |
| 8 | -) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules: | |
| 9 | -- Be descriptive but do not make up details | |
| 10 | -- If the the user request includes any code snippets that are relevant, reference them in code blocks | |
| 11 | -- Describe step by step how to reproduce the problem | |
| 12 | -- Describe the ideal solution to the problem | |
| 13 | -- Describe the expected behavior after the issue has been resolved | |
| 14 | -- This issue will be read by a team member | |
| 15 | -- Use markdown formatting, but you do not need to surround the entire body with triple backticks | |
| 16 | -{additional_instructions} | |
| 17 | - | |
| 18 | -Here is the user request: '${input}' | |
| 19 | - | |
| 20 | -Title: ${title} | |
| 21 | - | |
| 22 | -Body:\n\n`; | |
| 23 | - | |
| 24 | -const DraftIssueCommand: SlashCommand = { | |
| 25 | - name: "issue", | |
| 26 | - description: "Draft a GitHub issue", | |
| 27 | - run: async function* ({ input, llm, history, params, abortController }) { | |
| 28 | - if (params?.repositoryUrl === undefined) { | |
| 29 | - yield "This command requires a repository URL to be set in the config file."; | |
| 30 | - return; | |
| 31 | - } | |
| 32 | - let title = await llm.complete( | |
| 33 | - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, | |
| 34 | - new AbortController().signal, | |
| 35 | - { maxTokens: 30 }, | |
| 36 | - ); | |
| 37 | - | |
| 38 | - title = `${removeQuotesAndEscapes(title.trim())}\n\n`; | |
| 39 | - yield title; | |
| 40 | - | |
| 41 | - let body = ""; | |
| 42 | - const messages: ChatMessage[] = [ | |
| 43 | - ...history.filter((msg) => msg.role !== "system"), | |
| 44 | - { role: "user", content: PROMPT(input, title) }, | |
| 45 | - ]; | |
| 46 | - | |
| 47 | - for await (const chunk of llm.streamChat( | |
| 48 | - messages, | |
| 49 | - abortController.signal, | |
| 50 | - )) { | |
| 51 | - body += chunk.content; | |
| 52 | - yield renderChatMessage(chunk); | |
| 53 | - } | |
| 54 | - | |
| 55 | - const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( | |
| 56 | - title, | |
| 57 | - )}&body=${encodeURIComponent(body)}`; | |
| 58 | - yield `\n\n[Link to draft of issue](${url})`; | |
| 59 | - }, | |
| 60 | -}; | |
| 61 | - | |
| 62 | -export default DraftIssueCommand; |
deleted core/commands/slash/http.ts +0 −33
| @@ -1,33 +0,0 @@ | ||
| 1 | -import { streamResponse } from "@continuedev/fetch"; | |
| 2 | -import { SlashCommand } from "../../index.js"; | |
| 3 | -import { removeQuotesAndEscapes } from "../../util/index.js"; | |
| 4 | - | |
| 5 | -const HttpSlashCommand: SlashCommand = { | |
| 6 | - name: "http", | |
| 7 | - description: "Call an HTTP endpoint to serve response", | |
| 8 | - run: async function* ({ ide, llm, input, params, fetch }) { | |
| 9 | - const url = params?.url; | |
| 10 | - if (!url) { | |
| 11 | - throw new Error("URL is not defined in params"); | |
| 12 | - } | |
| 13 | - const response = await fetch(url, { | |
| 14 | - method: "POST", | |
| 15 | - headers: { | |
| 16 | - "Content-Type": "application/json", | |
| 17 | - }, | |
| 18 | - body: JSON.stringify({ | |
| 19 | - input: removeQuotesAndEscapes(input), | |
| 20 | - }), | |
| 21 | - }); | |
| 22 | - | |
| 23 | - // Stream the response | |
| 24 | - if (response.body === null) { | |
| 25 | - throw new Error("Response body is null"); | |
| 26 | - } | |
| 27 | - for await (const chunk of streamResponse(response)) { | |
| 28 | - yield chunk; | |
| 29 | - } | |
| 30 | - }, | |
| 31 | -}; | |
| 32 | - | |
| 33 | -export default HttpSlashCommand; |
deleted core/commands/slash/index.ts +0 −17
| @@ -1,17 +0,0 @@ | ||
| 1 | -import GenerateTerminalCommand from "./cmd"; | |
| 2 | -import CommitMessageCommand from "./commit"; | |
| 3 | -import DraftIssueCommand from "./draftIssue"; | |
| 4 | -import HttpSlashCommand from "./http"; | |
| 5 | -import OnboardSlashCommand from "./onboard"; | |
| 6 | -import ReviewMessageCommand from "./review"; | |
| 7 | -import ShareSlashCommand from "./share"; | |
| 8 | - | |
| 9 | -export default [ | |
| 10 | - DraftIssueCommand, | |
| 11 | - ShareSlashCommand, | |
| 12 | - GenerateTerminalCommand, | |
| 13 | - HttpSlashCommand, | |
| 14 | - CommitMessageCommand, | |
| 15 | - ReviewMessageCommand, | |
| 16 | - OnboardSlashCommand, | |
| 17 | -]; |
deleted core/commands/slash/mcp.ts +0 −70
| @@ -1,70 +0,0 @@ | ||
| 1 | -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | |
| 2 | - | |
| 3 | -import { PromptMessage } from "@modelcontextprotocol/sdk/types.js"; | |
| 4 | -import { ChatMessage, SlashCommand } from "../../index.js"; | |
| 5 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 6 | -export function constructMcpSlashCommand( | |
| 7 | - client: Client, | |
| 8 | - name: string, | |
| 9 | - description?: string, | |
| 10 | - args?: string[], | |
| 11 | -): SlashCommand { | |
| 12 | - return { | |
| 13 | - name, | |
| 14 | - description: description ?? "MCP Prompt", | |
| 15 | - params: {}, | |
| 16 | - run: async function* (context) { | |
| 17 | - const argsObject: { [key: string]: string } = {}; | |
| 18 | - const userInput = context.input.split(" ").slice(1).join(" "); | |
| 19 | - if (args) { | |
| 20 | - args.forEach((arg, i) => { | |
| 21 | - argsObject[arg] = ""; // userInput | |
| 22 | - }); | |
| 23 | - } | |
| 24 | - | |
| 25 | - const result = await client.getPrompt({ name, arguments: argsObject }); | |
| 26 | - const mcpMessages: PromptMessage[] = result.messages; | |
| 27 | - const messages: ChatMessage[] = mcpMessages.map((msg) => { | |
| 28 | - if (msg.content.type !== "text") { | |
| 29 | - throw new Error( | |
| 30 | - "Continue currently only supports text prompts through MCP", | |
| 31 | - ); | |
| 32 | - } | |
| 33 | - return { | |
| 34 | - content: msg.content.text, | |
| 35 | - role: msg.role, | |
| 36 | - }; | |
| 37 | - }); | |
| 38 | - | |
| 39 | - if (messages.length === 0) { | |
| 40 | - yield "The MCP prompt returned no messages"; | |
| 41 | - return; | |
| 42 | - } | |
| 43 | - | |
| 44 | - if (userInput) { | |
| 45 | - const lastMessage = messages.at(-1); | |
| 46 | - if (!lastMessage || lastMessage.role !== "user") { | |
| 47 | - messages.push({ | |
| 48 | - role: "user", | |
| 49 | - content: userInput, | |
| 50 | - }); | |
| 51 | - } else { | |
| 52 | - let newContent = renderChatMessage(lastMessage); | |
| 53 | - if (newContent) { | |
| 54 | - newContent += "\n\n"; | |
| 55 | - } | |
| 56 | - newContent += userInput; | |
| 57 | - lastMessage.content = newContent; | |
| 58 | - } | |
| 59 | - } | |
| 60 | - | |
| 61 | - for await (const chunk of context.llm.streamChat( | |
| 62 | - messages, | |
| 63 | - context.abortController.signal, | |
| 64 | - context.completionOptions, | |
| 65 | - )) { | |
| 66 | - yield renderChatMessage(chunk); | |
| 67 | - } | |
| 68 | - }, | |
| 69 | - }; | |
| 70 | -} |
added core/commands/slash/mcpSlashCommand.ts +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | |
| 2 | + | |
| 3 | +import { SlashCommandWithSource } from "../../index.js"; | |
| 4 | + | |
| 5 | +export function constructMcpSlashCommand( | |
| 6 | + client: Client, | |
| 7 | + name: string, | |
| 8 | + description?: string, | |
| 9 | + args?: string[], | |
| 10 | +): SlashCommandWithSource { | |
| 11 | + return { | |
| 12 | + name, | |
| 13 | + description: description ?? "MCP Prompt", | |
| 14 | + source: "mcp-prompt", | |
| 15 | + params: {}, | |
| 16 | + }; | |
| 17 | +} | |
| 18 | + | |
| 19 | +export function stringifyMcpPrompt( | |
| 20 | + prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>, | |
| 21 | +): string { | |
| 22 | + const { messages } = prompt; | |
| 23 | + let stringified = ""; | |
| 24 | + for (const message of messages) { | |
| 25 | + if (message.content.type === "text") { | |
| 26 | + stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`; | |
| 27 | + } else { | |
| 28 | + console.warn( | |
| 29 | + `MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`, | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + } | |
| 33 | + return stringified; | |
| 34 | +} |
deleted core/commands/slash/onboard.ts +0 −169
| @@ -1,169 +0,0 @@ | ||
| 1 | -import ignore from "ignore"; | |
| 2 | - | |
| 3 | -import type { FileType, IDE, SlashCommand } from "../.."; | |
| 4 | -import { | |
| 5 | - DEFAULT_IGNORE, | |
| 6 | - getGlobalContinueIgArray, | |
| 7 | - gitIgArrayFromFile, | |
| 8 | -} from "../../indexing/ignore"; | |
| 9 | -import { renderChatMessage } from "../../util/messageContent"; | |
| 10 | -import { | |
| 11 | - findUriInDirs, | |
| 12 | - getUriPathBasename, | |
| 13 | - joinPathsToUri, | |
| 14 | -} from "../../util/uri"; | |
| 15 | - | |
| 16 | -const LANGUAGE_DEP_MGMT_FILENAMES = [ | |
| 17 | - "package.json", // JavaScript (Node.js) | |
| 18 | - "requirements.txt", // Python | |
| 19 | - "Gemfile", // Ruby | |
| 20 | - "pom.xml", // Java (Maven) | |
| 21 | - "build.gradle", // Java (Gradle) | |
| 22 | - "composer.json", // PHP | |
| 23 | - "Cargo.toml", // Rust | |
| 24 | - "go.mod", // Go | |
| 25 | - "packages.config", // C# (.NET) | |
| 26 | - "*.csproj", // C# (.NET Core) | |
| 27 | - "pubspec.yaml", // Dart | |
| 28 | - "Project.toml", // Julia | |
| 29 | - "mix.exs", // Elixir | |
| 30 | - "rebar.config", // Erlang | |
| 31 | - "shard.yml", // Crystal | |
| 32 | - "Package.swift", // Swift | |
| 33 | - "dependencies.gradle", // Kotlin (when using Gradle) | |
| 34 | - "Podfile", // Objective-C/Swift (CocoaPods) | |
| 35 | - "*.cabal", // Haskell | |
| 36 | - "dub.json", // D | |
| 37 | -]; | |
| 38 | - | |
| 39 | -const MAX_EXPLORE_DEPTH = 2; | |
| 40 | - | |
| 41 | -const OnboardSlashCommand: SlashCommand = { | |
| 42 | - name: "onboard", | |
| 43 | - description: "Familiarize yourself with the codebase", | |
| 44 | - run: async function* ({ llm, ide, abortController }) { | |
| 45 | - const [workspaceDir] = await ide.getWorkspaceDirs(); | |
| 46 | - | |
| 47 | - const context = await gatherProjectContext(workspaceDir, ide); | |
| 48 | - const prompt = createOnboardingPrompt(context); | |
| 49 | - | |
| 50 | - for await (const chunk of llm.streamChat( | |
| 51 | - [{ role: "user", content: prompt }], | |
| 52 | - abortController.signal, | |
| 53 | - )) { | |
| 54 | - yield renderChatMessage(chunk); | |
| 55 | - } | |
| 56 | - }, | |
| 57 | -}; | |
| 58 | - | |
| 59 | -async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { | |
| 60 | - const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); | |
| 61 | - const entries = await ide.listDir(dir); | |
| 62 | - | |
| 63 | - const ignoreUri = joinPathsToUri(dir, ".gitignore"); | |
| 64 | - const fileExists = await ide.fileExists(ignoreUri); | |
| 65 | - | |
| 66 | - if (fileExists) { | |
| 67 | - const gitIgnore = await ide.readFile(ignoreUri); | |
| 68 | - const igPatterns = gitIgArrayFromFile(gitIgnore); | |
| 69 | - | |
| 70 | - ig.add(igPatterns); | |
| 71 | - } | |
| 72 | - | |
| 73 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 74 | - | |
| 75 | - const withRelativePaths = entries | |
| 76 | - .filter( | |
| 77 | - (entry) => | |
| 78 | - entry[1] === (1 as FileType.File) || | |
| 79 | - entry[1] === (2 as FileType.Directory), | |
| 80 | - ) | |
| 81 | - .map((entry) => { | |
| 82 | - const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs); | |
| 83 | - return { | |
| 84 | - uri: entry[0], | |
| 85 | - type: entry[1], | |
| 86 | - basename: getUriPathBasename(entry[0]), | |
| 87 | - relativePath: | |
| 88 | - relativePathOrBasename + | |
| 89 | - (entry[1] === (2 as FileType.Directory) ? "/" : ""), | |
| 90 | - }; | |
| 91 | - }); | |
| 92 | - | |
| 93 | - return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath)); | |
| 94 | -} | |
| 95 | - | |
| 96 | -async function gatherProjectContext( | |
| 97 | - workspaceDir: string, | |
| 98 | - ide: IDE, | |
| 99 | -): Promise<string> { | |
| 100 | - let context = ""; | |
| 101 | - async function exploreDirectory(dir: string, currentDepth: number = 0) { | |
| 102 | - if (currentDepth > MAX_EXPLORE_DEPTH) { | |
| 103 | - return; | |
| 104 | - } | |
| 105 | - | |
| 106 | - const entries = await getEntriesFilteredByIgnore(dir, ide); | |
| 107 | - | |
| 108 | - for (const entry of entries) { | |
| 109 | - if (entry.type === (2 as FileType.Directory)) { | |
| 110 | - context += `\nFolder: ${entry.relativePath}\n`; | |
| 111 | - await exploreDirectory(entry.uri, currentDepth + 1); | |
| 112 | - } else { | |
| 113 | - if (entry.basename.toLowerCase() === "readme.md") { | |
| 114 | - const content = await ide.readFile(entry.uri); | |
| 115 | - context += `README for ${entry.relativePath}:\n${content}\n\n`; | |
| 116 | - } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) { | |
| 117 | - const content = await ide.readFile(entry.uri); | |
| 118 | - context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`; | |
| 119 | - } | |
| 120 | - } | |
| 121 | - } | |
| 122 | - } | |
| 123 | - | |
| 124 | - await exploreDirectory(workspaceDir); | |
| 125 | - | |
| 126 | - return context; | |
| 127 | -} | |
| 128 | - | |
| 129 | -function createOnboardingPrompt(context: string): string { | |
| 130 | - return ` | |
| 131 | - As a helpful AI assistant, your task is to onboard a new developer to this project. | |
| 132 | - Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview: | |
| 133 | - | |
| 134 | - ${context} | |
| 135 | - | |
| 136 | - Please provide an overview of the project with the following guidelines: | |
| 137 | - - Determine the most important folders in the project, at most 10 | |
| 138 | - - Go through each important folder step-by-step: | |
| 139 | - - Explain what each folder does in isolation by summarzing the README or package.json file, if available | |
| 140 | - - Mention the most popular or common packages used in that folder and their roles. | |
| 141 | - - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture: | |
| 142 | - - How different parts of the codebase fit together. | |
| 143 | - - The overall project architecture or design patterns evident from the folder structure and dependencies. | |
| 144 | - - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown. | |
| 145 | - | |
| 146 | - Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. | |
| 147 | - | |
| 148 | - Here is an example of a valid response: | |
| 149 | - | |
| 150 | - ## Important folders | |
| 151 | - | |
| 152 | - ### /folder1 | |
| 153 | - - Description: Contains the main application logic. | |
| 154 | - - Key packages: Express.js for routing, Mongoose for database operations. | |
| 155 | - | |
| 156 | - #### /folder1/folder2 | |
| 157 | - | |
| 158 | - ## Project Architecture | |
| 159 | - - The frontend is built using React and Redux for state management. | |
| 160 | - - The backend is a Node.js application using Express.js for routing and Mongoose for database operations. | |
| 161 | - - The application follows a Model-View-Controller (MVC) architecture. | |
| 162 | - | |
| 163 | - ## Additional Insights | |
| 164 | - - The project is using a monorepo structure. | |
| 165 | - - The project uses TypeScript for type checking. | |
| 166 | - `; | |
| 167 | -} | |
| 168 | - | |
| 169 | -export default OnboardSlashCommand; |
added core/commands/slash/promptBlockSlashCommand.ts +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +import { Prompt } from "@continuedev/config-yaml"; | |
| 2 | +import { SlashCommandWithSource } from "../.."; | |
| 3 | + | |
| 4 | +export function convertPromptBlockToSlashCommand( | |
| 5 | + prompt: Prompt, | |
| 6 | +): SlashCommandWithSource { | |
| 7 | + return { | |
| 8 | + name: prompt.name, | |
| 9 | + description: prompt.description ?? "", | |
| 10 | + prompt: prompt.prompt, | |
| 11 | + source: "yaml-prompt-block", | |
| 12 | + }; | |
| 13 | +} |
added core/commands/slash/promptFileSlashCommand.ts +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +import { SlashCommandWithSource } from "../.."; | |
| 2 | +import { parsePromptFile } from "../../promptFiles/parsePromptFile"; | |
| 3 | + | |
| 4 | +export function slashCommandFromPromptFile( | |
| 5 | + path: string, | |
| 6 | + content: string, | |
| 7 | +): SlashCommandWithSource | null { | |
| 8 | + const { name, description, systemMessage, prompt, version } = parsePromptFile( | |
| 9 | + path, | |
| 10 | + content, | |
| 11 | + ); | |
| 12 | + | |
| 13 | + return { | |
| 14 | + name, | |
| 15 | + description, | |
| 16 | + prompt, | |
| 17 | + source: version === 1 ? "prompt-file-v1" : "prompt-file-v2", | |
| 18 | + promptFile: path, | |
| 19 | + overrideSystemMessage: systemMessage, | |
| 20 | + }; | |
| 21 | +} |
deleted core/commands/slash/review.ts +0 −55
| @@ -1,55 +0,0 @@ | ||
| 1 | -import { ChatMessage, SlashCommand } from "../../index.js"; | |
| 2 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 3 | - | |
| 4 | -const prompt = ` | |
| 5 | - Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: | |
| 6 | - | |
| 7 | - Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements. | |
| 8 | - Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts. | |
| 9 | - Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly. | |
| 10 | - Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability. | |
| 11 | - Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`; | |
| 12 | - | |
| 13 | -function getLastUserHistory(history: ChatMessage[]): string { | |
| 14 | - const lastUserHistory = history | |
| 15 | - .reverse() | |
| 16 | - .find((message) => message.role === "user"); | |
| 17 | - | |
| 18 | - if (!lastUserHistory) { | |
| 19 | - return ""; | |
| 20 | - } | |
| 21 | - | |
| 22 | - if (Array.isArray(lastUserHistory.content)) { | |
| 23 | - return lastUserHistory.content.reduce( | |
| 24 | - (acc: string, current: { type: string; text?: string }) => { | |
| 25 | - return current.type === "text" && current.text | |
| 26 | - ? acc + current.text | |
| 27 | - : acc; | |
| 28 | - }, | |
| 29 | - "", | |
| 30 | - ); | |
| 31 | - } | |
| 32 | - | |
| 33 | - return typeof lastUserHistory.content === "string" | |
| 34 | - ? lastUserHistory.content | |
| 35 | - : ""; | |
| 36 | -} | |
| 37 | - | |
| 38 | -const ReviewMessageCommand: SlashCommand = { | |
| 39 | - name: "review", | |
| 40 | - description: "Review code and give feedback", | |
| 41 | - run: async function* ({ llm, history, abortController }) { | |
| 42 | - const reviewText = getLastUserHistory(history).replace("\\review", ""); | |
| 43 | - | |
| 44 | - const content = `${prompt} \r\n ${reviewText}`; | |
| 45 | - | |
| 46 | - for await (const chunk of llm.streamChat( | |
| 47 | - [{ role: "user", content: content }], | |
| 48 | - abortController.signal, | |
| 49 | - )) { | |
| 50 | - yield renderChatMessage(chunk); | |
| 51 | - } | |
| 52 | - }, | |
| 53 | -}; | |
| 54 | - | |
| 55 | -export default ReviewMessageCommand; |
deleted core/commands/slash/share.ts +0 −101
| @@ -1,101 +0,0 @@ | ||
| 1 | -import fs from "fs"; | |
| 2 | -import { homedir } from "node:os"; | |
| 3 | -import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 4 | -import path from "path"; | |
| 5 | - | |
| 6 | -import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; | |
| 7 | -import { SlashCommand } from "../../index.js"; | |
| 8 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 9 | -import { getContinueGlobalPath } from "../../util/paths.js"; | |
| 10 | - | |
| 11 | -// If useful elsewhere, helper funcs should move to core/util/index.ts or similar | |
| 12 | -function getOffsetDatetime(date: Date): Date { | |
| 13 | - const offset = date.getTimezoneOffset(); | |
| 14 | - const offsetHours = Math.floor(offset / 60); | |
| 15 | - const offsetMinutes = offset % 60; | |
| 16 | - date.setHours(date.getHours() - offsetHours); | |
| 17 | - date.setMinutes(date.getMinutes() - offsetMinutes); | |
| 18 | - | |
| 19 | - return date; | |
| 20 | -} | |
| 21 | - | |
| 22 | -function asBasicISOString(date: Date): string { | |
| 23 | - const isoString = date.toISOString(); | |
| 24 | - | |
| 25 | - return isoString.replace(/[-:]|(\.\d+Z)/g, ""); | |
| 26 | -} | |
| 27 | - | |
| 28 | -function reformatCodeBlocks(msgText: string): string { | |
| 29 | - const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; | |
| 30 | - msgText = msgText.replace( | |
| 31 | - codeBlockFenceRegex, | |
| 32 | - (match, metadata, filename, extension) => { | |
| 33 | - const lang = languageForFilepath(filename); | |
| 34 | - return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; | |
| 35 | - }, | |
| 36 | - ); | |
| 37 | - // Appease the markdown linter | |
| 38 | - return msgText.replace(/```\n```/g, "```\n\n```"); | |
| 39 | -} | |
| 40 | - | |
| 41 | -const ShareSlashCommand: SlashCommand = { | |
| 42 | - name: "share", | |
| 43 | - description: "Export the current chat session to markdown", | |
| 44 | - run: async function* ({ ide, history, params }) { | |
| 45 | - const now = new Date(); | |
| 46 | - | |
| 47 | - let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; | |
| 48 | - | |
| 49 | - // As currently implemented, the /share command is by definition the last | |
| 50 | - // message in the chat history, this will omit it | |
| 51 | - for (const msg of history.slice(0, history.length - 1)) { | |
| 52 | - let msgText = msg.content; | |
| 53 | - msgText = renderChatMessage(msg); | |
| 54 | - | |
| 55 | - if (msg.role === "user" && msgText.search("```") > -1) { | |
| 56 | - msgText = reformatCodeBlocks(msgText); | |
| 57 | - } | |
| 58 | - | |
| 59 | - // format messages as blockquotes | |
| 60 | - msgText = msgText.replace(/^/gm, "> "); | |
| 61 | - | |
| 62 | - content += `\n\n#### ${ | |
| 63 | - msg.role === "user" ? "_User_" : "_Assistant_" | |
| 64 | - }\n\n${msgText}`; | |
| 65 | - } | |
| 66 | - | |
| 67 | - let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); | |
| 68 | - | |
| 69 | - if (outputDir.startsWith("~")) { | |
| 70 | - outputDir = outputDir.replace(/^~/, homedir); | |
| 71 | - } else if ( | |
| 72 | - outputDir.startsWith("./") || | |
| 73 | - outputDir.startsWith(".\\") || | |
| 74 | - outputDir === "." | |
| 75 | - ) { | |
| 76 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 77 | - // Although the most common situation is to have one directory open in a | |
| 78 | - // workspace it's also possible to have just a file open without an | |
| 79 | - // associated directory or to use multi-root workspaces in which multiple | |
| 80 | - // folders are included. We default to using the first item in the list, if | |
| 81 | - // it exists. | |
| 82 | - const workspaceDirectory = workspaceDirs?.[0] || ""; | |
| 83 | - outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); | |
| 84 | - } | |
| 85 | - | |
| 86 | - if (!fs.existsSync(outputDir)) { | |
| 87 | - fs.mkdirSync(outputDir, { recursive: true }); | |
| 88 | - } | |
| 89 | - | |
| 90 | - const dtString = asBasicISOString(getOffsetDatetime(now)); | |
| 91 | - const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? | |
| 92 | - | |
| 93 | - const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ | |
| 94 | - await ide.writeFile(fileUrl, content); | |
| 95 | - await ide.openFile(fileUrl); | |
| 96 | - | |
| 97 | - yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; | |
| 98 | - }, | |
| 99 | -}; | |
| 100 | - | |
| 101 | -export default ShareSlashCommand; |
modified core/commands/util.ts +1 −1
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | return { |
| 17 | 17 | content: rif.contents, |
| 18 | 18 | name: `${basename} ${rangeStr}`, |
| 19 | - description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI | |
| 19 | + description: `${relativePathOrBasename} ${rangeStr}`, | |
| 20 | 20 | id: { |
| 21 | 21 | providerTitle: "code", |
| 22 | 22 | itemId: uuidv4(), |
modified core/config/load.ts +33 −17
| @@ -30,12 +30,11 @@ | ||
| 30 | 30 | ModelDescription, |
| 31 | 31 | RerankerDescription, |
| 32 | 32 | SerializedContinueConfig, |
| 33 | - SlashCommand, | |
| 33 | + SlashCommandWithSource, | |
| 34 | 34 | } from ".."; |
| 35 | -import { | |
| 36 | - slashCommandFromDescription, | |
| 37 | - slashFromCustomCommand, | |
| 38 | -} from "../commands/index"; | |
| 35 | +import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy"; | |
| 36 | +import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand"; | |
| 37 | +import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand"; | |
| 39 | 38 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 40 | 39 | import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; |
| 41 | 40 | import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; |
| @@ -48,8 +47,7 @@ | ||
| 48 | 47 | import CustomLLMClass from "../llm/llms/CustomLLM"; |
| 49 | 48 | import { LLMReranker } from "../llm/llms/llm"; |
| 50 | 49 | import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider"; |
| 51 | -import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; | |
| 52 | -import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; | |
| 50 | +import { getAllPromptFiles } from "../promptFiles/getPromptFiles"; | |
| 53 | 51 | import { copyOf } from "../util"; |
| 54 | 52 | import { GlobalContext } from "../util/GlobalContext"; |
| 55 | 53 | import mergeJson from "../util/merge"; |
| @@ -66,6 +64,7 @@ | ||
| 66 | 64 | import { localPathToUri } from "../util/pathToUri"; |
| 67 | 65 | |
| 68 | 66 | import { baseToolDefinitions } from "../tools"; |
| 67 | +import { resolveRelativePathInDir } from "../util/ideUtils"; | |
| 69 | 68 | import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; |
| 70 | 69 | import { |
| 71 | 70 | getModelByRole, |
| @@ -174,15 +173,15 @@ | ||
| 174 | 173 | ide: IDE, |
| 175 | 174 | ): Promise<Config> { |
| 176 | 175 | // DEPRECATED - load custom slash commands |
| 177 | - const slashCommands: SlashCommand[] = []; | |
| 176 | + const slashCommands: SlashCommandWithSource[] = []; | |
| 178 | 177 | for (const command of initial.slashCommands || []) { |
| 179 | - const newCommand = slashCommandFromDescription(command); | |
| 178 | + const newCommand = getLegacyBuiltInSlashCommandFromDescription(command); | |
| 180 | 179 | if (newCommand) { |
| 181 | 180 | slashCommands.push(newCommand); |
| 182 | 181 | } |
| 183 | 182 | } |
| 184 | 183 | for (const command of initial.customCommands || []) { |
| 185 | - slashCommands.push(slashFromCustomCommand(command)); | |
| 184 | + slashCommands.push(convertCustomCommandToSlashCommand(command)); | |
| 186 | 185 | } |
| 187 | 186 | |
| 188 | 187 | // DEPRECATED - load slash commands from v1 prompt files |
| @@ -194,7 +193,7 @@ | ||
| 194 | 193 | ); |
| 195 | 194 | |
| 196 | 195 | for (const file of promptFiles) { |
| 197 | - const slashCommand = slashCommandFromPromptFileV1(file.path, file.content); | |
| 196 | + const slashCommand = slashCommandFromPromptFile(file.path, file.content); | |
| 198 | 197 | if (slashCommand) { |
| 199 | 198 | slashCommands.push(slashCommand); |
| 200 | 199 | } |
| @@ -254,7 +253,10 @@ | ||
| 254 | 253 | loadPromptFiles?: boolean; |
| 255 | 254 | }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { |
| 256 | 255 | const errors: ConfigValidationError[] = []; |
| 257 | - | |
| 256 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 257 | + const getUriFromPath = (path: string) => { | |
| 258 | + return resolveRelativePathInDir(path, ide, workspaceDirs); | |
| 259 | + }; | |
| 258 | 260 | // Auto-detect models |
| 259 | 261 | let models: BaseLLM[] = []; |
| 260 | 262 | await Promise.all( |
| @@ -263,6 +265,7 @@ | ||
| 263 | 265 | const llm = await llmFromDescription( |
| 264 | 266 | desc, |
| 265 | 267 | ide.readFile.bind(ide), |
| 268 | + getUriFromPath, | |
| 266 | 269 | uniqueId, |
| 267 | 270 | ideSettings, |
| 268 | 271 | llmLogger, |
| @@ -284,6 +287,7 @@ | ||
| 284 | 287 | title: modelName, |
| 285 | 288 | }, |
| 286 | 289 | ide.readFile.bind(ide), |
| 290 | + getUriFromPath, | |
| 287 | 291 | uniqueId, |
| 288 | 292 | ideSettings, |
| 289 | 293 | llmLogger, |
| @@ -360,6 +364,7 @@ | ||
| 360 | 364 | const llm = await llmFromDescription( |
| 361 | 365 | desc, |
| 362 | 366 | ide.readFile.bind(ide), |
| 367 | + getUriFromPath, | |
| 363 | 368 | uniqueId, |
| 364 | 369 | ideSettings, |
| 365 | 370 | llmLogger, |
| @@ -529,7 +534,7 @@ | ||
| 529 | 534 | contextProviders, |
| 530 | 535 | tools: [...baseToolDefinitions], |
| 531 | 536 | mcpServerStatuses: [], |
| 532 | - slashCommands: config.slashCommands ?? [], | |
| 537 | + slashCommands: [], | |
| 533 | 538 | modelsByRole: { |
| 534 | 539 | chat: models, |
| 535 | 540 | edit: models, |
| @@ -551,6 +556,17 @@ | ||
| 551 | 556 | rules: [], |
| 552 | 557 | }; |
| 553 | 558 | |
| 559 | + for (const cmd of config.slashCommands ?? []) { | |
| 560 | + if ("source" in cmd) { | |
| 561 | + continueConfig.slashCommands.push(cmd); | |
| 562 | + } else { | |
| 563 | + continueConfig.slashCommands.push({ | |
| 564 | + ...cmd, | |
| 565 | + source: "config-ts-slash-command", | |
| 566 | + }); | |
| 567 | + } | |
| 568 | + } | |
| 569 | + | |
| 554 | 570 | if (config.systemMessage) { |
| 555 | 571 | continueConfig.rules.unshift({ |
| 556 | 572 | rule: config.systemMessage, |
| @@ -651,9 +667,10 @@ | ||
| 651 | 667 | return { |
| 652 | 668 | allowAnonymousTelemetry: final.allowAnonymousTelemetry, |
| 653 | 669 | completionOptions: final.completionOptions, |
| 654 | - slashCommands: final.slashCommands?.map( | |
| 655 | - ({ run, ...slashCommandDescription }) => slashCommandDescription, | |
| 656 | - ), | |
| 670 | + slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({ | |
| 671 | + ...rest, | |
| 672 | + isLegacy: !!run, | |
| 673 | + })), | |
| 657 | 674 | contextProviders: final.contextProviders?.map((c) => c.description), |
| 658 | 675 | disableIndexing: final.disableIndexing, |
| 659 | 676 | disableSessionTitles: final.disableSessionTitles, |
| @@ -975,7 +992,6 @@ | ||
| 975 | 992 | |
| 976 | 993 | export { |
| 977 | 994 | finalToBrowserConfig, |
| 978 | - intermediateToFinalConfig, | |
| 979 | 995 | loadContinueConfigFromJson, |
| 980 | 996 | type BrowserSerializedContinueConfig, |
| 981 | 997 | }; |
modified core/config/profile/doLoadConfig.ts +10 −9
| @@ -16,9 +16,9 @@ | ||
| 16 | 16 | ILLMLogger, |
| 17 | 17 | RuleWithSource, |
| 18 | 18 | SerializedContinueConfig, |
| 19 | + SlashCommandDescWithSource, | |
| 19 | 20 | Tool, |
| 20 | 21 | } from "../../"; |
| 21 | -import { constructMcpSlashCommand } from "../../commands/slash/mcp"; | |
| 22 | 22 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 23 | 23 | import MCPContextProvider from "../../context/providers/MCPContextProvider"; |
| 24 | 24 | import RulesContextProvider from "../../context/providers/RulesContextProvider"; |
| @@ -190,14 +190,15 @@ | ||
| 190 | 190 | })); |
| 191 | 191 | newConfig.tools.push(...serverTools); |
| 192 | 192 | |
| 193 | - const serverSlashCommands = server.prompts.map((prompt) => | |
| 194 | - constructMcpSlashCommand( | |
| 195 | - server.client, | |
| 196 | - prompt.name, | |
| 197 | - prompt.description, | |
| 198 | - prompt.arguments?.map((a: any) => a.name), | |
| 199 | - ), | |
| 200 | - ); | |
| 193 | + const serverSlashCommands: SlashCommandDescWithSource[] = | |
| 194 | + server.prompts.map((prompt) => ({ | |
| 195 | + name: prompt.name, | |
| 196 | + description: prompt.description ?? "MCP Prompt", | |
| 197 | + source: "mcp-prompt", | |
| 198 | + isLegacy: false, | |
| 199 | + mcpServerName: server.name, // Used in client to retrieve prompt | |
| 200 | + mcpArgs: prompt.arguments, | |
| 201 | + })); | |
| 201 | 202 | newConfig.slashCommands.push(...serverSlashCommands); |
| 202 | 203 | |
| 203 | 204 | const submenuItems = server.resources |
modified core/config/yaml/loadYaml.ts +5 −5
| @@ -25,7 +25,6 @@ | ||
| 25 | 25 | ILLMLogger, |
| 26 | 26 | RuleWithSource, |
| 27 | 27 | } from "../.."; |
| 28 | -import { slashFromCustomCommand } from "../../commands"; | |
| 29 | 28 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 30 | 29 | import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; |
| 31 | 30 | import DocsContextProvider from "../../context/providers/DocsContextProvider"; |
| @@ -33,11 +32,12 @@ | ||
| 33 | 32 | import { contextProviderClassFromName } from "../../context/providers/index"; |
| 34 | 33 | import { ControlPlaneClient } from "../../control-plane/client"; |
| 35 | 34 | import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; |
| 36 | -import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; | |
| 37 | -import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; | |
| 35 | +import { getAllPromptFiles } from "../../promptFiles/getPromptFiles"; | |
| 38 | 36 | import { GlobalContext } from "../../util/GlobalContext"; |
| 39 | 37 | import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; |
| 40 | 38 | |
| 39 | +import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; | |
| 40 | +import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; | |
| 41 | 41 | import { getControlPlaneEnvSync } from "../../control-plane/env"; |
| 42 | 42 | import { getToolsForIde } from "../../tools"; |
| 43 | 43 | import { getCleanUriPath } from "../../util/uri"; |
| @@ -263,7 +263,7 @@ | ||
| 263 | 263 | |
| 264 | 264 | promptFiles.forEach((file) => { |
| 265 | 265 | try { |
| 266 | - const slashCommand = slashCommandFromPromptFileV1( | |
| 266 | + const slashCommand = slashCommandFromPromptFile( | |
| 267 | 267 | file.path, |
| 268 | 268 | file.content, |
| 269 | 269 | ); |
| @@ -286,7 +286,7 @@ | ||
| 286 | 286 | |
| 287 | 287 | config.prompts?.forEach((prompt) => { |
| 288 | 288 | try { |
| 289 | - const slashCommand = slashFromCustomCommand(prompt); | |
| 289 | + const slashCommand = convertPromptBlockToSlashCommand(prompt); | |
| 290 | 290 | continueConfig.slashCommands?.push(slashCommand); |
| 291 | 291 | } catch (e) { |
| 292 | 292 | localErrors.push({ |
modified core/context/mcp/MCPManagerSingleton.ts +17 −0
| @@ -161,4 +161,21 @@ | ||
| 161 | 161 | client: connection.client, |
| 162 | 162 | })); |
| 163 | 163 | } |
| 164 | + | |
| 165 | + async getPrompt( | |
| 166 | + serverName: string, | |
| 167 | + promptName: string, | |
| 168 | + args: Record<string, string> = {}, | |
| 169 | + ) { | |
| 170 | + const connection = this.connections.get(serverName); | |
| 171 | + if (!connection) { | |
| 172 | + throw new Error( | |
| 173 | + `Error getting prompt: MCP Connection ${serverName} not found`, | |
| 174 | + ); | |
| 175 | + } | |
| 176 | + return await connection.client.getPrompt({ | |
| 177 | + name: promptName, | |
| 178 | + arguments: args, | |
| 179 | + }); | |
| 180 | + } | |
| 164 | 181 | } |
modified core/context/providers/TerminalContextProvider.ts +3 −1
| @@ -21,7 +21,9 @@ | ||
| 21 | 21 | return [ |
| 22 | 22 | { |
| 23 | 23 | description: "The contents of the terminal", |
| 24 | - content: `Current terminal contents:\n\n${content}`, | |
| 24 | + content: `Current terminal contents:\n\n${ | |
| 25 | + content || "The terminal is empty." | |
| 26 | + }`, | |
| 25 | 27 | name: "Terminal", |
| 26 | 28 | }, |
| 27 | 29 | ]; |
modified core/core.ts +15 −1
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | import DocsService from "./indexing/docs/DocsService"; |
| 22 | 22 | import { countTokens } from "./llm/countTokens"; |
| 23 | 23 | import Ollama from "./llm/llms/Ollama"; |
| 24 | -import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; | |
| 24 | +import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; | |
| 25 | 25 | import { callTool } from "./tools/callTool"; |
| 26 | 26 | import { ChatDescriber } from "./util/chatDescriber"; |
| 27 | 27 | import { clipboardCache } from "./util/clipboardCache"; |
| @@ -50,6 +50,7 @@ | ||
| 50 | 50 | |
| 51 | 51 | import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; |
| 52 | 52 | import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; |
| 53 | +import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand"; | |
| 53 | 54 | import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; |
| 54 | 55 | import { |
| 55 | 56 | setupLocalConfig, |
| @@ -381,6 +382,19 @@ | ||
| 381 | 382 | on("mcp/reloadServer", async (msg) => { |
| 382 | 383 | await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); |
| 383 | 384 | }); |
| 385 | + on("mcp/getPrompt", async (msg) => { | |
| 386 | + const { serverName, promptName, args } = msg.data; | |
| 387 | + const prompt = await MCPManagerSingleton.getInstance().getPrompt( | |
| 388 | + serverName, | |
| 389 | + promptName, | |
| 390 | + args, | |
| 391 | + ); | |
| 392 | + const stringifiedPrompt = stringifyMcpPrompt(prompt); | |
| 393 | + return { | |
| 394 | + prompt: stringifiedPrompt, | |
| 395 | + description: prompt.description, | |
| 396 | + }; | |
| 397 | + }); | |
| 384 | 398 | // Context providers |
| 385 | 399 | on("context/addDocs", async (msg) => { |
| 386 | 400 | void this.docsService.indexAndAdd(msg.data); |
modified core/index.d.ts +41 −12
| @@ -838,15 +838,44 @@ | ||
| 838 | 838 | abortController: AbortController; |
| 839 | 839 | } |
| 840 | 840 | |
| 841 | -export interface SlashCommand { | |
| 841 | +/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */ | |
| 842 | +export interface SlashCommandDescription { | |
| 842 | 843 | name: string; |
| 843 | 844 | description: string; |
| 844 | 845 | prompt?: string; |
| 845 | 846 | params?: { [key: string]: any }; |
| 846 | - promptFile?: string; | |
| 847 | +} | |
| 848 | + | |
| 849 | +export interface SlashCommand extends SlashCommandDescription { | |
| 847 | 850 | run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; |
| 848 | 851 | } |
| 849 | 852 | |
| 853 | +export interface SlashCommandWithSource extends SlashCommandDescription { | |
| 854 | + run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy | |
| 855 | + source: SlashCommandSource; | |
| 856 | + promptFile?: string; | |
| 857 | + overrideSystemMessage?: string; | |
| 858 | +} | |
| 859 | + | |
| 860 | +export type SlashCommandSource = | |
| 861 | + | "built-in-legacy" | |
| 862 | + | "built-in" | |
| 863 | + | "json-custom-command" | |
| 864 | + | "config-ts-slash-command" | |
| 865 | + | "yaml-prompt-block" | |
| 866 | + | "mcp-prompt" | |
| 867 | + | "prompt-file-v1" | |
| 868 | + | "prompt-file-v2" | |
| 869 | + | "invokable-rule"; | |
| 870 | + | |
| 871 | +export interface SlashCommandDescWithSource extends SlashCommandDescription { | |
| 872 | + isLegacy: boolean; // Maps to if slashcommand.run exists | |
| 873 | + source: SlashCommandSource; | |
| 874 | + promptFile?: string; | |
| 875 | + mcpServerName?: string; | |
| 876 | + mcpArgs?: MCPPromptArgs; | |
| 877 | +} | |
| 878 | + | |
| 850 | 879 | // Config |
| 851 | 880 | |
| 852 | 881 | export type StepName = |
| @@ -947,8 +976,6 @@ | ||
| 947 | 976 | params: { [key: string]: any }; |
| 948 | 977 | } |
| 949 | 978 | |
| 950 | -export type SlashCommandDescription = Omit<SlashCommand, "run">; | |
| 951 | - | |
| 952 | 979 | export interface CustomCommand { |
| 953 | 980 | name: string; |
| 954 | 981 | prompt: string; |
| @@ -1172,14 +1199,16 @@ | ||
| 1172 | 1199 | | "error" |
| 1173 | 1200 | | "not-connected"; |
| 1174 | 1201 | |
| 1202 | +export type MCPPromptArgs = { | |
| 1203 | + name: string; | |
| 1204 | + description?: string; | |
| 1205 | + required?: boolean; | |
| 1206 | +}[]; | |
| 1207 | + | |
| 1175 | 1208 | export interface MCPPrompt { |
| 1176 | 1209 | name: string; |
| 1177 | 1210 | description?: string; |
| 1178 | - arguments?: { | |
| 1179 | - name: string; | |
| 1180 | - description?: string; | |
| 1181 | - required?: boolean; | |
| 1182 | - }[]; | |
| 1211 | + arguments?: MCPPromptArgs; | |
| 1183 | 1212 | } |
| 1184 | 1213 | |
| 1185 | 1214 | // Leaving here to ideate on |
| @@ -1444,7 +1473,7 @@ | ||
| 1444 | 1473 | /** Request options that will be applied to all models and context providers */ |
| 1445 | 1474 | requestOptions?: RequestOptions; |
| 1446 | 1475 | /** The list of slash commands that will be available in the sidebar */ |
| 1447 | - slashCommands?: SlashCommand[]; | |
| 1476 | + slashCommands?: (SlashCommand | SlashCommandWithSource)[]; | |
| 1448 | 1477 | /** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders. |
| 1449 | 1478 | * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`. |
| 1450 | 1479 | */ |
| @@ -1481,7 +1510,7 @@ | ||
| 1481 | 1510 | // systemMessage?: string; |
| 1482 | 1511 | completionOptions?: BaseCompletionOptions; |
| 1483 | 1512 | requestOptions?: RequestOptions; |
| 1484 | - slashCommands: SlashCommand[]; | |
| 1513 | + slashCommands: SlashCommandWithSource[]; | |
| 1485 | 1514 | contextProviders: IContextProvider[]; |
| 1486 | 1515 | disableSessionTitles?: boolean; |
| 1487 | 1516 | disableIndexing?: boolean; |
| @@ -1504,7 +1533,7 @@ | ||
| 1504 | 1533 | // systemMessage?: string; |
| 1505 | 1534 | completionOptions?: BaseCompletionOptions; |
| 1506 | 1535 | requestOptions?: RequestOptions; |
| 1507 | - slashCommands: SlashCommandDescription[]; | |
| 1536 | + slashCommands: SlashCommandDescWithSource[]; | |
| 1508 | 1537 | contextProviders: ContextProviderDescription[]; |
| 1509 | 1538 | disableIndexing?: boolean; |
| 1510 | 1539 | disableSessionTitles?: boolean; |
modified core/llm/llms/index.ts +7 −3
| @@ -1,3 +1,4 @@ | ||
| 1 | +import Handlebars from "handlebars"; | |
| 1 | 2 | import { |
| 2 | 3 | BaseCompletionOptions, |
| 3 | 4 | IdeSettings, |
| @@ -6,10 +7,9 @@ | ||
| 6 | 7 | JSONModelDescription, |
| 7 | 8 | LLMOptions, |
| 8 | 9 | } from "../.."; |
| 9 | -import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; | |
| 10 | +import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; | |
| 10 | 11 | import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; |
| 11 | 12 | import { BaseLLM } from "../index"; |
| 12 | - | |
| 13 | 13 | import Anthropic from "./Anthropic"; |
| 14 | 14 | import Asksage from "./Asksage"; |
| 15 | 15 | import Azure from "./Azure"; |
| @@ -122,6 +122,7 @@ | ||
| 122 | 122 | export async function llmFromDescription( |
| 123 | 123 | desc: JSONModelDescription, |
| 124 | 124 | readFile: (filepath: string) => Promise<string>, |
| 125 | + getUriFromPath: (path: string) => Promise<string | undefined>, | |
| 125 | 126 | uniqueId: string, |
| 126 | 127 | ideSettings: IdeSettings, |
| 127 | 128 | llmLogger: ILLMLogger, |
| @@ -143,9 +144,12 @@ | ||
| 143 | 144 | baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; |
| 144 | 145 | baseChatSystemMessage += "\n\n"; |
| 145 | 146 | baseChatSystemMessage += await renderTemplatedString( |
| 147 | + Handlebars, | |
| 146 | 148 | desc.systemMessage, |
| 147 | - readFile, | |
| 148 | 149 | {}, |
| 150 | + [], | |
| 151 | + readFile, | |
| 152 | + getUriFromPath, | |
| 149 | 153 | ); |
| 150 | 154 | } |
| 151 | 155 |
modified core/llm/streamChat.ts +6 −0
| @@ -59,6 +59,12 @@ | ||
| 59 | 59 | }, |
| 60 | 60 | true, |
| 61 | 61 | ); |
| 62 | + if (!slashCommand.run) { | |
| 63 | + console.error( | |
| 64 | + `Slash command ${command.name} (${command.source}) has no run function`, | |
| 65 | + ); | |
| 66 | + throw new Error(`Slash command not found`); | |
| 67 | + } | |
| 62 | 68 | |
| 63 | 69 | const gen = slashCommand.run({ |
| 64 | 70 | input, |
added core/promptFiles/createNewPromptFile.ts +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +import { IDE } from ".."; | |
| 2 | +import { GlobalContext } from "../util/GlobalContext"; | |
| 3 | +import { joinPathsToUri } from "../util/uri"; | |
| 4 | + | |
| 5 | +const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file | |
| 6 | +# It is used to define and reuse prompts within Continue | |
| 7 | +# Each .prompt file can be accessed by typing "@prompts" in the Chat input | |
| 8 | + | |
| 9 | +# A prompt file consists of two parts: | |
| 10 | +# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options | |
| 11 | +# 2. Everything below the "---" is the prompt body | |
| 12 | + | |
| 13 | +# If you do not want to set any options, you do not need to include the "---" | |
| 14 | + | |
| 15 | +# In the body, you can reference: | |
| 16 | +# 1. Files, using either absolute or relative paths (based on the workspace root) | |
| 17 | + # @README.md | |
| 18 | + # @src/test/test.py | |
| 19 | + # @/Users/me/Desktop/my-project/src/test/test.py | |
| 20 | +# 2. URLs, for example | |
| 21 | + # @https://example.com | |
| 22 | +# 3. Context providers, for example | |
| 23 | + # @currentFile | |
| 24 | + # @os | |
| 25 | + # @repo-map | |
| 26 | + | |
| 27 | +# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files | |
| 28 | +name: Example | |
| 29 | +description: Example prompt file | |
| 30 | +--- | |
| 31 | + | |
| 32 | +Here is information about the current repo: | |
| 33 | + | |
| 34 | +@README.md`; | |
| 35 | + | |
| 36 | +const DEFAULT_PROMPT_FILE = ""; | |
| 37 | + | |
| 38 | +export async function createNewPromptFileV2( | |
| 39 | + ide: IDE, | |
| 40 | + promptPath: string | undefined, | |
| 41 | +): Promise<void> { | |
| 42 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 43 | + if (workspaceDirs.length === 0) { | |
| 44 | + throw new Error( | |
| 45 | + "No workspace directories found. Make sure you've opened a folder in your IDE.", | |
| 46 | + ); | |
| 47 | + } | |
| 48 | + | |
| 49 | + const baseDirUri = joinPathsToUri( | |
| 50 | + workspaceDirs[0], | |
| 51 | + promptPath ?? ".continue/prompts", | |
| 52 | + ); | |
| 53 | + | |
| 54 | + // Find the first available filename | |
| 55 | + let counter = 0; | |
| 56 | + let promptFileUri: string; | |
| 57 | + do { | |
| 58 | + const suffix = counter === 0 ? "" : `-${counter}`; | |
| 59 | + promptFileUri = joinPathsToUri( | |
| 60 | + baseDirUri, | |
| 61 | + `new-prompt-file${suffix}.prompt`, | |
| 62 | + ); | |
| 63 | + counter++; | |
| 64 | + } while (await ide.fileExists(promptFileUri)); | |
| 65 | + | |
| 66 | + const globalContext = new GlobalContext(); | |
| 67 | + const PROMPT_FILE = | |
| 68 | + globalContext.get("hasAlreadyCreatedAPromptFile") === true | |
| 69 | + ? DEFAULT_PROMPT_FILE | |
| 70 | + : FIRST_TIME_DEFAULT_PROMPT_FILE; | |
| 71 | + | |
| 72 | + globalContext.update("hasAlreadyCreatedAPromptFile", true); | |
| 73 | + | |
| 74 | + await ide.writeFile(promptFileUri, PROMPT_FILE); | |
| 75 | + await ide.openFile(promptFileUri); | |
| 76 | +} |
added core/promptFiles/getPromptFiles.ts +66 −0
| @@ -0,0 +1,66 @@ | ||
| 1 | +import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from "."; | |
| 2 | +import { IDE } from ".."; | |
| 3 | +import { walkDir } from "../indexing/walkDir"; | |
| 4 | +import { readAllGlobalPromptFiles } from "../util/paths"; | |
| 5 | +import { joinPathsToUri } from "../util/uri"; | |
| 6 | + | |
| 7 | +export async function getPromptFilesFromDir( | |
| 8 | + ide: IDE, | |
| 9 | + dir: string, | |
| 10 | +): Promise<{ path: string; content: string }[]> { | |
| 11 | + try { | |
| 12 | + const exists = await ide.fileExists(dir); | |
| 13 | + | |
| 14 | + if (!exists) { | |
| 15 | + return []; | |
| 16 | + } | |
| 17 | + | |
| 18 | + const uris = await walkDir(dir, ide, { | |
| 19 | + source: "get dir prompt files", | |
| 20 | + }); | |
| 21 | + const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); | |
| 22 | + const results = promptFilePaths.map(async (uri) => { | |
| 23 | + const content = await ide.readFile(uri); // make a try catch | |
| 24 | + return { path: uri, content }; | |
| 25 | + }); | |
| 26 | + return Promise.all(results); | |
| 27 | + } catch (e) { | |
| 28 | + console.error(e); | |
| 29 | + return []; | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +export async function getAllPromptFiles( | |
| 34 | + ide: IDE, | |
| 35 | + overridePromptFolder?: string, | |
| 36 | + checkV1DefaultFolder: boolean = false, | |
| 37 | +): Promise<{ path: string; content: string }[]> { | |
| 38 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 39 | + let promptFiles: { path: string; content: string }[] = []; | |
| 40 | + | |
| 41 | + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; | |
| 42 | + if (checkV1DefaultFolder) { | |
| 43 | + dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); | |
| 44 | + } | |
| 45 | + if (overridePromptFolder) { | |
| 46 | + dirsToCheck = [overridePromptFolder]; | |
| 47 | + } | |
| 48 | + | |
| 49 | + const fullDirs = workspaceDirs | |
| 50 | + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) | |
| 51 | + .flat(); | |
| 52 | + | |
| 53 | + promptFiles = ( | |
| 54 | + await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) | |
| 55 | + ).flat(); | |
| 56 | + | |
| 57 | + // Also read from ~/.continue/.prompts | |
| 58 | + promptFiles.push(...readAllGlobalPromptFiles()); | |
| 59 | + | |
| 60 | + return await Promise.all( | |
| 61 | + promptFiles.map(async (file) => { | |
| 62 | + const content = await ide.readFile(file.path); | |
| 63 | + return { path: file.path, content }; | |
| 64 | + }), | |
| 65 | + ); | |
| 66 | +} |
added core/promptFiles/index.ts +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +import { ContextProviderName } from ".."; | |
| 2 | + | |
| 3 | +export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; | |
| 4 | +export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; | |
| 5 | + | |
| 6 | +export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [ | |
| 7 | + "file", | |
| 8 | + "clipboard", | |
| 9 | + "repo-map", | |
| 10 | + "currentFile", | |
| 11 | + "os", | |
| 12 | + "problems", | |
| 13 | + "codebase", | |
| 14 | + "tree", | |
| 15 | + "open", | |
| 16 | + "debugger", | |
| 17 | + "terminal", | |
| 18 | + "diff", | |
| 19 | +]; |
added core/promptFiles/parsePromptFile.ts +24 −0
| @@ -0,0 +1,24 @@ | ||
| 1 | +import * as YAML from "yaml"; | |
| 2 | + | |
| 3 | +import { getLastNPathParts } from "../util/uri"; | |
| 4 | + | |
| 5 | +export function parsePromptFile(path: string, content: string) { | |
| 6 | + let [preambleRaw, prompt] = content.split("\n---\n"); | |
| 7 | + if (prompt === undefined) { | |
| 8 | + prompt = preambleRaw; | |
| 9 | + preambleRaw = ""; | |
| 10 | + } | |
| 11 | + | |
| 12 | + const preamble = YAML.parse(preambleRaw) ?? {}; | |
| 13 | + const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 14 | + const description = preamble.description ?? name; | |
| 15 | + const version = preamble.version ?? 2; | |
| 16 | + | |
| 17 | + let systemMessage: string | undefined = undefined; | |
| 18 | + if (prompt.includes("<system>")) { | |
| 19 | + systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim(); | |
| 20 | + prompt = prompt.split("</system>")[1].trim(); | |
| 21 | + } | |
| 22 | + | |
| 23 | + return { name, description, systemMessage, prompt, version }; | |
| 24 | +} |
deleted core/promptFiles/v1/getContextProviderHelpers.ts +0 −38
| @@ -1,38 +0,0 @@ | ||
| 1 | -import Handlebars from "handlebars"; | |
| 2 | -import { ContextItem, ContinueSDK, IContextProvider } from "../.."; | |
| 3 | - | |
| 4 | -function createContextItem(item: ContextItem, provider: IContextProvider) { | |
| 5 | - return { | |
| 6 | - ...item, | |
| 7 | - id: { | |
| 8 | - itemId: item.description, | |
| 9 | - providerTitle: provider.description.title, | |
| 10 | - }, | |
| 11 | - }; | |
| 12 | -} | |
| 13 | - | |
| 14 | -export function getContextProviderHelpers( | |
| 15 | - context: ContinueSDK, | |
| 16 | -): Array<[string, Handlebars.HelperDelegate]> | undefined { | |
| 17 | - return context.config.contextProviders?.map((provider: IContextProvider) => [ | |
| 18 | - provider.description.title, | |
| 19 | - async (helperContext: any) => { | |
| 20 | - const items = await provider.getContextItems(helperContext, { | |
| 21 | - config: context.config, | |
| 22 | - embeddingsProvider: context.config.selectedModelByRole.embed, | |
| 23 | - fetch: context.fetch, | |
| 24 | - fullInput: context.input, | |
| 25 | - ide: context.ide, | |
| 26 | - llm: context.llm, | |
| 27 | - reranker: context.config.selectedModelByRole.rerank, | |
| 28 | - selectedCode: context.selectedCode, | |
| 29 | - }); | |
| 30 | - | |
| 31 | - items.forEach((item) => | |
| 32 | - context.addContextItem(createContextItem(item, provider)), | |
| 33 | - ); | |
| 34 | - | |
| 35 | - return items.map((item) => item.content).join("\n\n"); | |
| 36 | - }, | |
| 37 | - ]); | |
| 38 | -} |
deleted core/promptFiles/v1/handlebarUtils.ts +0 −117
| @@ -1,117 +0,0 @@ | ||
| 1 | -import Handlebars from "handlebars"; | |
| 2 | -import { v4 as uuidv4 } from "uuid"; | |
| 3 | - | |
| 4 | -function convertToLetter(num: number): string { | |
| 5 | - let result = ""; | |
| 6 | - while (num > 0) { | |
| 7 | - const remainder = (num - 1) % 26; | |
| 8 | - result = String.fromCharCode(97 + remainder) + result; | |
| 9 | - num = Math.floor((num - 1) / 26); | |
| 10 | - } | |
| 11 | - return result; | |
| 12 | -} | |
| 13 | - | |
| 14 | -/** | |
| 15 | - * We replace filepaths with alphabetic characters to handle | |
| 16 | - * escaping issues. | |
| 17 | - */ | |
| 18 | -const replaceFilepaths = ( | |
| 19 | - value: string, | |
| 20 | - ctxProviderNames: string[], | |
| 21 | -): [string, { [key: string]: string }] => { | |
| 22 | - const ast = Handlebars.parse(value); | |
| 23 | - | |
| 24 | - const keysToFilepath: { [key: string]: string } = {}; | |
| 25 | - | |
| 26 | - let keyIndex = 1; | |
| 27 | - | |
| 28 | - for (const i in ast.body) { | |
| 29 | - const node = ast.body[i] as any; | |
| 30 | - | |
| 31 | - if (node.type === "MustacheStatement") { | |
| 32 | - const originalNodeVal = node.path.original; | |
| 33 | - const isFilepath = !ctxProviderNames.includes(originalNodeVal); | |
| 34 | - | |
| 35 | - if (isFilepath) { | |
| 36 | - const letter = convertToLetter(keyIndex); | |
| 37 | - | |
| 38 | - keysToFilepath[letter] = originalNodeVal; | |
| 39 | - | |
| 40 | - value = value.replace( | |
| 41 | - new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), | |
| 42 | - `{{${letter}}}`, | |
| 43 | - ); | |
| 44 | - | |
| 45 | - keyIndex++; | |
| 46 | - } | |
| 47 | - } | |
| 48 | - } | |
| 49 | - | |
| 50 | - return [value, keysToFilepath]; | |
| 51 | -}; | |
| 52 | - | |
| 53 | -export function registerHelpers( | |
| 54 | - helpers: Array<[string, Handlebars.HelperDelegate]>, | |
| 55 | -): { | |
| 56 | - [key: string]: Promise<string>; | |
| 57 | -} { | |
| 58 | - const promises: { [key: string]: Promise<string> } = {}; | |
| 59 | - | |
| 60 | - for (const [name, helper] of helpers) { | |
| 61 | - Handlebars.registerHelper(name, (...args) => { | |
| 62 | - const id = uuidv4(); | |
| 63 | - promises[id] = helper(...args); | |
| 64 | - return `__${id}__`; | |
| 65 | - }); | |
| 66 | - } | |
| 67 | - | |
| 68 | - return promises; | |
| 69 | -} | |
| 70 | - | |
| 71 | -export async function prepareTemplateAndData( | |
| 72 | - template: string, | |
| 73 | - readFile: (filepath: string) => Promise<string>, | |
| 74 | - inputData: Record<string, string>, | |
| 75 | - ctxProviderNames: string[], | |
| 76 | -): Promise<[string, any]> { | |
| 77 | - const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames); | |
| 78 | - | |
| 79 | - const data: any = { ...inputData }; | |
| 80 | - | |
| 81 | - for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) { | |
| 82 | - data[replacedName] = | |
| 83 | - inputData[originalCtxProviderName] ?? originalCtxProviderName; | |
| 84 | - | |
| 85 | - // If it's not a context provider, assume it's a filepath. | |
| 86 | - if (!ctxProviderNames.includes(originalCtxProviderName)) { | |
| 87 | - const fileContents = await readFile(vars[replacedName]); | |
| 88 | - | |
| 89 | - if (fileContents) { | |
| 90 | - data[replacedName] = fileContents; | |
| 91 | - } | |
| 92 | - } | |
| 93 | - } | |
| 94 | - | |
| 95 | - return [newTemplate, data]; | |
| 96 | -} | |
| 97 | - | |
| 98 | -export function compileAndRenderTemplate( | |
| 99 | - template: string, | |
| 100 | - data: Record<string, string>, | |
| 101 | -): string { | |
| 102 | - const templateFn = Handlebars.compile(template); | |
| 103 | - return templateFn(data); | |
| 104 | -} | |
| 105 | - | |
| 106 | -export async function resolveHelperPromises( | |
| 107 | - renderedString: string, | |
| 108 | - promises: { [key: string]: Promise<string> }, | |
| 109 | -): Promise<string> { | |
| 110 | - await Promise.all(Object.values(promises)); | |
| 111 | - | |
| 112 | - for (const id in promises) { | |
| 113 | - renderedString = renderedString.replace(`__${id}__`, await promises[id]); | |
| 114 | - } | |
| 115 | - | |
| 116 | - return renderedString; | |
| 117 | -} |
deleted core/promptFiles/v1/index.ts +0 −1
| @@ -1,1 +0,0 @@ | ||
| 1 | -export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; |
deleted core/promptFiles/v1/renderTemplatedString.ts +0 −30
| @@ -1,30 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - compileAndRenderTemplate, | |
| 3 | - prepareTemplateAndData, | |
| 4 | - registerHelpers, | |
| 5 | - resolveHelperPromises, | |
| 6 | -} from "./handlebarUtils"; | |
| 7 | - | |
| 8 | -export async function renderTemplatedString( | |
| 9 | - template: string, | |
| 10 | - readFile: (filepath: string) => Promise<string>, | |
| 11 | - inputData: Record<string, string>, | |
| 12 | - availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, | |
| 13 | -): Promise<string> { | |
| 14 | - const helperPromises = availableHelpers | |
| 15 | - ? registerHelpers(availableHelpers) | |
| 16 | - : {}; | |
| 17 | - | |
| 18 | - const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? []; | |
| 19 | - | |
| 20 | - const [newTemplate, data] = await prepareTemplateAndData( | |
| 21 | - template, | |
| 22 | - readFile, | |
| 23 | - inputData, | |
| 24 | - ctxProviderNames, | |
| 25 | - ); | |
| 26 | - | |
| 27 | - let renderedString = compileAndRenderTemplate(newTemplate, data); | |
| 28 | - | |
| 29 | - return resolveHelperPromises(renderedString, helperPromises); | |
| 30 | -} |
deleted core/promptFiles/v1/slashCommandFromPromptFile.ts +0 −89
| @@ -1,89 +0,0 @@ | ||
| 1 | -import { ContinueSDK, SlashCommand } from "../.."; | |
| 2 | -import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; | |
| 3 | -import { renderChatMessage } from "../../util/messageContent"; | |
| 4 | -import { getLastNPathParts } from "../../util/uri"; | |
| 5 | -import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; | |
| 6 | -import { renderPromptFileV2 } from "../v2/renderPromptFile"; | |
| 7 | - | |
| 8 | -import { getContextProviderHelpers } from "./getContextProviderHelpers"; | |
| 9 | -import { renderTemplatedString } from "./renderTemplatedString"; | |
| 10 | -import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory"; | |
| 11 | - | |
| 12 | -export function extractName(preamble: { name?: string }, path: string): string { | |
| 13 | - return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 14 | -} | |
| 15 | - | |
| 16 | -async function renderPromptV1( | |
| 17 | - prompt: string, | |
| 18 | - context: ContinueSDK, | |
| 19 | - userInput: string, | |
| 20 | -) { | |
| 21 | - const helpers = getContextProviderHelpers(context); | |
| 22 | - | |
| 23 | - const inputData: Record<string, string> = { | |
| 24 | - input: userInput, | |
| 25 | - }; | |
| 26 | - | |
| 27 | - // A few context providers that don't need to be in config.json to work in .prompt files | |
| 28 | - if (helpers?.find((helper) => helper[0] === "diff")) { | |
| 29 | - const diffs = await getDiffsFromCache(context.ide); | |
| 30 | - inputData.diff = diffs.join("\n"); | |
| 31 | - } | |
| 32 | - if (helpers?.find((helper) => helper[0] === "currentFile")) { | |
| 33 | - const currentFile = await context.ide.getCurrentFile(); | |
| 34 | - if (currentFile) { | |
| 35 | - inputData.currentFile = currentFile.path; | |
| 36 | - } | |
| 37 | - } | |
| 38 | - | |
| 39 | - return renderTemplatedString( | |
| 40 | - prompt, | |
| 41 | - context.ide.readFile.bind(context.ide), | |
| 42 | - inputData, | |
| 43 | - helpers, | |
| 44 | - ); | |
| 45 | -} | |
| 46 | - | |
| 47 | -export function slashCommandFromPromptFileV1( | |
| 48 | - path: string, | |
| 49 | - content: string, | |
| 50 | -): SlashCommand | null { | |
| 51 | - const { name, description, systemMessage, prompt } = parsePromptFileV1V2( | |
| 52 | - path, | |
| 53 | - content, | |
| 54 | - ); | |
| 55 | - | |
| 56 | - return { | |
| 57 | - name, | |
| 58 | - description, | |
| 59 | - prompt, | |
| 60 | - promptFile: path, | |
| 61 | - run: async function* (context) { | |
| 62 | - const [_, renderedPrompt] = await renderPromptFileV2(prompt, { | |
| 63 | - config: context.config, | |
| 64 | - fullInput: context.input, | |
| 65 | - embeddingsProvider: context.config.modelsByRole.embed[0], | |
| 66 | - reranker: context.config.modelsByRole.rerank[0], | |
| 67 | - llm: context.llm, | |
| 68 | - ide: context.ide, | |
| 69 | - selectedCode: context.selectedCode, | |
| 70 | - fetch: context.fetch, | |
| 71 | - }); | |
| 72 | - | |
| 73 | - const messages = replaceSlashCommandWithPromptInChatHistory( | |
| 74 | - context.history, | |
| 75 | - name, | |
| 76 | - renderedPrompt, | |
| 77 | - systemMessage, | |
| 78 | - ); | |
| 79 | - | |
| 80 | - for await (const chunk of context.llm.streamChat( | |
| 81 | - messages, | |
| 82 | - context.abortController.signal, | |
| 83 | - context.completionOptions, | |
| 84 | - )) { | |
| 85 | - yield renderChatMessage(chunk); | |
| 86 | - } | |
| 87 | - }, | |
| 88 | - }; | |
| 89 | -} |
deleted core/promptFiles/v1/updateChatHistory.ts +0 −64
| @@ -1,64 +0,0 @@ | ||
| 1 | -import { ChatMessage } from "../.."; | |
| 2 | - | |
| 3 | -export function replaceSlashCommandWithPromptInChatHistory( | |
| 4 | - history: ChatMessage[], | |
| 5 | - commandName: string, | |
| 6 | - renderedPrompt: string, | |
| 7 | - systemMessageOverride?: string, | |
| 8 | -): ChatMessage[] { | |
| 9 | - const messages = [...history]; | |
| 10 | - | |
| 11 | - for (let i = messages.length - 1; i >= 0; i--) { | |
| 12 | - const { role, content } = messages[i]; | |
| 13 | - if (role !== "user") { | |
| 14 | - continue; | |
| 15 | - } | |
| 16 | - | |
| 17 | - if (Array.isArray(content)) { | |
| 18 | - if ( | |
| 19 | - content.some( | |
| 20 | - (part) => | |
| 21 | - part.type === "text" && part.text?.startsWith(`/${commandName}`), | |
| 22 | - ) | |
| 23 | - ) { | |
| 24 | - messages[i] = updateArrayContent( | |
| 25 | - messages[i], | |
| 26 | - commandName, | |
| 27 | - renderedPrompt, | |
| 28 | - ); | |
| 29 | - break; | |
| 30 | - } | |
| 31 | - } else if ( | |
| 32 | - typeof content === "string" && | |
| 33 | - content.startsWith(`/${commandName}`) | |
| 34 | - ) { | |
| 35 | - messages[i] = { ...messages[i], content: renderedPrompt }; | |
| 36 | - break; | |
| 37 | - } | |
| 38 | - } | |
| 39 | - | |
| 40 | - if (systemMessageOverride) { | |
| 41 | - if (messages[0]?.role === "system") { | |
| 42 | - messages[0].content = systemMessageOverride; | |
| 43 | - } else { | |
| 44 | - messages.unshift({ role: "system", content: systemMessageOverride }); | |
| 45 | - } | |
| 46 | - } | |
| 47 | - | |
| 48 | - return messages; | |
| 49 | -} | |
| 50 | - | |
| 51 | -function updateArrayContent( | |
| 52 | - message: any, | |
| 53 | - commandName: string, | |
| 54 | - renderedPrompt: string, | |
| 55 | -) { | |
| 56 | - return { | |
| 57 | - ...message, | |
| 58 | - content: message.content.map((part: any) => | |
| 59 | - part.text?.startsWith(`/${commandName}`) | |
| 60 | - ? { ...part, text: renderedPrompt } | |
| 61 | - : part, | |
| 62 | - ), | |
| 63 | - }; | |
| 64 | -} |
deleted core/promptFiles/v2/createNewPromptFile.ts +0 −76
| @@ -1,76 +0,0 @@ | ||
| 1 | -import { IDE } from "../.."; | |
| 2 | -import { GlobalContext } from "../../util/GlobalContext"; | |
| 3 | -import { joinPathsToUri } from "../../util/uri"; | |
| 4 | - | |
| 5 | -const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file | |
| 6 | -# It is used to define and reuse prompts within Continue | |
| 7 | -# Each .prompt file can be accessed by typing "@prompts" in the Chat input | |
| 8 | - | |
| 9 | -# A prompt file consists of two parts: | |
| 10 | -# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options | |
| 11 | -# 2. Everything below the "---" is the prompt body | |
| 12 | - | |
| 13 | -# If you do not want to set any options, you do not need to include the "---" | |
| 14 | - | |
| 15 | -# In the body, you can reference: | |
| 16 | -# 1. Files, using either absolute or relative paths (based on the workspace root) | |
| 17 | - # @README.md | |
| 18 | - # @src/test/test.py | |
| 19 | - # @/Users/me/Desktop/my-project/src/test/test.py | |
| 20 | -# 2. URLs, for example | |
| 21 | - # @https://example.com | |
| 22 | -# 3. Context providers, for example | |
| 23 | - # @currentFile | |
| 24 | - # @os | |
| 25 | - # @repo-map | |
| 26 | - | |
| 27 | -# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files | |
| 28 | -name: Example | |
| 29 | -description: Example prompt file | |
| 30 | ---- | |
| 31 | - | |
| 32 | -Here is information about the current repo: | |
| 33 | - | |
| 34 | -@README.md`; | |
| 35 | - | |
| 36 | -const DEFAULT_PROMPT_FILE = ""; | |
| 37 | - | |
| 38 | -export async function createNewPromptFileV2( | |
| 39 | - ide: IDE, | |
| 40 | - promptPath: string | undefined, | |
| 41 | -): Promise<void> { | |
| 42 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 43 | - if (workspaceDirs.length === 0) { | |
| 44 | - throw new Error( | |
| 45 | - "No workspace directories found. Make sure you've opened a folder in your IDE.", | |
| 46 | - ); | |
| 47 | - } | |
| 48 | - | |
| 49 | - const baseDirUri = joinPathsToUri( | |
| 50 | - workspaceDirs[0], | |
| 51 | - promptPath ?? ".continue/prompts", | |
| 52 | - ); | |
| 53 | - | |
| 54 | - // Find the first available filename | |
| 55 | - let counter = 0; | |
| 56 | - let promptFileUri: string; | |
| 57 | - do { | |
| 58 | - const suffix = counter === 0 ? "" : `-${counter}`; | |
| 59 | - promptFileUri = joinPathsToUri( | |
| 60 | - baseDirUri, | |
| 61 | - `new-prompt-file${suffix}.prompt`, | |
| 62 | - ); | |
| 63 | - counter++; | |
| 64 | - } while (await ide.fileExists(promptFileUri)); | |
| 65 | - | |
| 66 | - const globalContext = new GlobalContext(); | |
| 67 | - const PROMPT_FILE = | |
| 68 | - globalContext.get("hasAlreadyCreatedAPromptFile") === true | |
| 69 | - ? DEFAULT_PROMPT_FILE | |
| 70 | - : FIRST_TIME_DEFAULT_PROMPT_FILE; | |
| 71 | - | |
| 72 | - globalContext.update("hasAlreadyCreatedAPromptFile", true); | |
| 73 | - | |
| 74 | - await ide.writeFile(promptFileUri, PROMPT_FILE); | |
| 75 | - await ide.openFile(promptFileUri); | |
| 76 | -} |
deleted core/promptFiles/v2/getPromptFiles.ts +0 −67
| @@ -1,67 +0,0 @@ | ||
| 1 | -import { IDE } from "../.."; | |
| 2 | -import { walkDir } from "../../indexing/walkDir"; | |
| 3 | -import { readAllGlobalPromptFiles } from "../../util/paths"; | |
| 4 | -import { joinPathsToUri } from "../../util/uri"; | |
| 5 | -import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1"; | |
| 6 | - | |
| 7 | -export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; | |
| 8 | -export async function getPromptFilesFromDir( | |
| 9 | - ide: IDE, | |
| 10 | - dir: string, | |
| 11 | -): Promise<{ path: string; content: string }[]> { | |
| 12 | - try { | |
| 13 | - const exists = await ide.fileExists(dir); | |
| 14 | - | |
| 15 | - if (!exists) { | |
| 16 | - return []; | |
| 17 | - } | |
| 18 | - | |
| 19 | - const uris = await walkDir(dir, ide, { | |
| 20 | - source: "get dir prompt files", | |
| 21 | - }); | |
| 22 | - const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); | |
| 23 | - const results = promptFilePaths.map(async (uri) => { | |
| 24 | - const content = await ide.readFile(uri); // make a try catch | |
| 25 | - return { path: uri, content }; | |
| 26 | - }); | |
| 27 | - return Promise.all(results); | |
| 28 | - } catch (e) { | |
| 29 | - console.error(e); | |
| 30 | - return []; | |
| 31 | - } | |
| 32 | -} | |
| 33 | - | |
| 34 | -export async function getAllPromptFiles( | |
| 35 | - ide: IDE, | |
| 36 | - overridePromptFolder?: string, | |
| 37 | - checkV1DefaultFolder: boolean = false, | |
| 38 | -): Promise<{ path: string; content: string }[]> { | |
| 39 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 40 | - let promptFiles: { path: string; content: string }[] = []; | |
| 41 | - | |
| 42 | - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; | |
| 43 | - if (checkV1DefaultFolder) { | |
| 44 | - dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); | |
| 45 | - } | |
| 46 | - if (overridePromptFolder) { | |
| 47 | - dirsToCheck = [overridePromptFolder]; | |
| 48 | - } | |
| 49 | - | |
| 50 | - const fullDirs = workspaceDirs | |
| 51 | - .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) | |
| 52 | - .flat(); | |
| 53 | - | |
| 54 | - promptFiles = ( | |
| 55 | - await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) | |
| 56 | - ).flat(); | |
| 57 | - | |
| 58 | - // Also read from ~/.continue/.prompts | |
| 59 | - promptFiles.push(...readAllGlobalPromptFiles()); | |
| 60 | - | |
| 61 | - return await Promise.all( | |
| 62 | - promptFiles.map(async (file) => { | |
| 63 | - const content = await ide.readFile(file.path); | |
| 64 | - return { path: file.path, content }; | |
| 65 | - }), | |
| 66 | - ); | |
| 67 | -} |
deleted core/promptFiles/v2/parse.ts +0 −34
| @@ -1,34 +0,0 @@ | ||
| 1 | -import * as YAML from "yaml"; | |
| 2 | - | |
| 3 | -import { getLastNPathParts } from "../../util/uri"; | |
| 4 | - | |
| 5 | -export function extractName(preamble: { name?: string }, path: string): string { | |
| 6 | - return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 7 | -} | |
| 8 | - | |
| 9 | -export function getPreambleAndBody(content: string): [string, string] { | |
| 10 | - let [preamble, body] = content.split("\n---\n"); | |
| 11 | - if (body === undefined) { | |
| 12 | - // This means there is no preamble | |
| 13 | - body = preamble; | |
| 14 | - preamble = ""; | |
| 15 | - } | |
| 16 | - return [preamble, body]; | |
| 17 | -} | |
| 18 | - | |
| 19 | -export function parsePreamble( | |
| 20 | - path: string, | |
| 21 | - content: string, | |
| 22 | -): { [key: string]: any; name: string; description: string } { | |
| 23 | - const [preambleRaw, _] = getPreambleAndBody(content); | |
| 24 | - | |
| 25 | - const preamble = YAML.parse(preambleRaw) ?? {}; | |
| 26 | - const name = extractName(preamble, path); | |
| 27 | - const description = preamble.description ?? name; | |
| 28 | - | |
| 29 | - return { | |
| 30 | - ...preamble, | |
| 31 | - name, | |
| 32 | - description, | |
| 33 | - }; | |
| 34 | -} |
deleted core/promptFiles/v2/parsePromptFileV1V2.ts +0 −24
| @@ -1,24 +0,0 @@ | ||
| 1 | -import * as YAML from "yaml"; | |
| 2 | - | |
| 3 | -import { getLastNPathParts } from "../../util/uri"; | |
| 4 | - | |
| 5 | -export function parsePromptFileV1V2(path: string, content: string) { | |
| 6 | - let [preambleRaw, prompt] = content.split("\n---\n"); | |
| 7 | - if (prompt === undefined) { | |
| 8 | - prompt = preambleRaw; | |
| 9 | - preambleRaw = ""; | |
| 10 | - } | |
| 11 | - | |
| 12 | - const preamble = YAML.parse(preambleRaw) ?? {}; | |
| 13 | - const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; | |
| 14 | - const description = preamble.description ?? name; | |
| 15 | - const version = preamble.version ?? 2; | |
| 16 | - | |
| 17 | - let systemMessage: string | undefined = undefined; | |
| 18 | - if (prompt.includes("<system>")) { | |
| 19 | - systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim(); | |
| 20 | - prompt = prompt.split("</system>")[1].trim(); | |
| 21 | - } | |
| 22 | - | |
| 23 | - return { name, description, systemMessage, prompt, version }; | |
| 24 | -} |
deleted core/promptFiles/v2/renderPromptFile.ts +0 −84
| @@ -1,84 +0,0 @@ | ||
| 1 | -import { ContextItem, ContextProviderExtras } from "../.."; | |
| 2 | -import { contextProviderClassFromName } from "../../context/providers"; | |
| 3 | -import { getUrlContextItems } from "../../context/providers/URLContextProvider"; | |
| 4 | -import { resolveRelativePathInDir } from "../../util/ideUtils"; | |
| 5 | -import { getUriPathBasename } from "../../util/uri"; | |
| 6 | - | |
| 7 | -import { getPreambleAndBody } from "./parse"; | |
| 8 | - | |
| 9 | -async function resolveAttachment( | |
| 10 | - name: string, | |
| 11 | - extras: ContextProviderExtras, | |
| 12 | -): Promise<ContextItem[]> { | |
| 13 | - // Context providers | |
| 14 | - const contextProvider = extras.config.contextProviders?.find( | |
| 15 | - (provider) => provider.description.title === name, | |
| 16 | - ); | |
| 17 | - if (contextProvider) { | |
| 18 | - const items = await contextProvider.getContextItems("", extras); | |
| 19 | - return items; | |
| 20 | - } else { | |
| 21 | - // Just instantiate it here | |
| 22 | - const providerClass = contextProviderClassFromName(name) as any; | |
| 23 | - if (providerClass) { | |
| 24 | - const providerInstance = new providerClass({}); | |
| 25 | - return providerInstance.getContextItems("", extras); | |
| 26 | - } | |
| 27 | - } | |
| 28 | - | |
| 29 | - // Files | |
| 30 | - const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide); | |
| 31 | - if (resolvedFileUri) { | |
| 32 | - let subItems: ContextItem[] = []; | |
| 33 | - if (name.endsWith(".prompt")) { | |
| 34 | - // Recurse | |
| 35 | - const [items, _] = await renderPromptFileV2( | |
| 36 | - await extras.ide.readFile(resolvedFileUri), | |
| 37 | - extras, | |
| 38 | - ); | |
| 39 | - subItems.push(...items); | |
| 40 | - } | |
| 41 | - | |
| 42 | - const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``; | |
| 43 | - return [ | |
| 44 | - ...subItems, | |
| 45 | - { | |
| 46 | - name: getUriPathBasename(resolvedFileUri), | |
| 47 | - content, | |
| 48 | - description: resolvedFileUri, | |
| 49 | - }, | |
| 50 | - ]; | |
| 51 | - } | |
| 52 | - | |
| 53 | - // URLs | |
| 54 | - if (name.startsWith("http")) { | |
| 55 | - const items = getUrlContextItems(name, extras.fetch); | |
| 56 | - return items; | |
| 57 | - } | |
| 58 | - | |
| 59 | - return []; | |
| 60 | -} | |
| 61 | - | |
| 62 | -export async function renderPromptFileV2( | |
| 63 | - rawContent: string, | |
| 64 | - extras: ContextProviderExtras, | |
| 65 | -): Promise<[ContextItem[], string]> { | |
| 66 | - const [_, body] = getPreambleAndBody(rawContent); | |
| 67 | - | |
| 68 | - const contextItemsPromises: Promise<ContextItem[]>[] = []; | |
| 69 | - const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { | |
| 70 | - contextItemsPromises.push(resolveAttachment(name, extras)); | |
| 71 | - return match; | |
| 72 | - }); | |
| 73 | - | |
| 74 | - const contextItems = (await Promise.all(contextItemsPromises)).flat(); | |
| 75 | - const renderedPrompt = [ | |
| 76 | - ...contextItems.map((item) => item.content), | |
| 77 | - renderedBody, | |
| 78 | - extras.fullInput, | |
| 79 | - ] | |
| 80 | - .join("\n\n") | |
| 81 | - .trim(); | |
| 82 | - | |
| 83 | - return [contextItems, renderedPrompt]; | |
| 84 | -} |
deleted core/promptFiles/v2/renderPromptFile.vitest.ts +0 −175
| @@ -1,175 +0,0 @@ | ||
| 1 | -import { ContextProviderExtras, ILLM, RangeInFile } from "../.."; | |
| 2 | -import { testConfigHandler, testIde } from "../../test/fixtures"; | |
| 3 | -import { | |
| 4 | - addToTestDir, | |
| 5 | - setUpTestDir, | |
| 6 | - tearDownTestDir, | |
| 7 | -} from "../../test/testDir"; | |
| 8 | -import { renderPromptFileV2 } from "./renderPromptFile"; | |
| 9 | - | |
| 10 | -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 11 | - | |
| 12 | -vi.mock( | |
| 13 | - import("../../context/providers/URLContextProvider"), | |
| 14 | - async (importOriginal) => { | |
| 15 | - const actual = await importOriginal(); | |
| 16 | - return { | |
| 17 | - ...actual, | |
| 18 | - getUrlContextItems: vi.fn().mockResolvedValue([ | |
| 19 | - { | |
| 20 | - description: "https://example.com", | |
| 21 | - content: "Example Content", | |
| 22 | - name: "Example site", | |
| 23 | - uri: { | |
| 24 | - type: "url", | |
| 25 | - value: "https://example.com", | |
| 26 | - }, | |
| 27 | - }, | |
| 28 | - ]), | |
| 29 | - }; | |
| 30 | - }, | |
| 31 | -); | |
| 32 | - | |
| 33 | -describe("renderPromptFileV2", () => { | |
| 34 | - let extras: ContextProviderExtras; | |
| 35 | - const mockGetContextItems = vi.fn().mockResolvedValue([ | |
| 36 | - { | |
| 37 | - name: "custom", | |
| 38 | - content: "Custom provider content", | |
| 39 | - description: "Custom provider", | |
| 40 | - }, | |
| 41 | - ]); | |
| 42 | - beforeEach(async () => { | |
| 43 | - const { config } = await testConfigHandler.loadConfig(); | |
| 44 | - | |
| 45 | - // Setup mock extras | |
| 46 | - extras = { | |
| 47 | - config: { | |
| 48 | - ...config!, | |
| 49 | - contextProviders: [ | |
| 50 | - { | |
| 51 | - description: { | |
| 52 | - type: "normal", | |
| 53 | - title: "CustomProvider", | |
| 54 | - displayTitle: "Custom Provider", | |
| 55 | - description: "A custom context provider", | |
| 56 | - }, | |
| 57 | - loadSubmenuItems: vi.fn().mockResolvedValue([]), | |
| 58 | - getContextItems: mockGetContextItems, | |
| 59 | - }, | |
| 60 | - ], | |
| 61 | - }, | |
| 62 | - fullInput: "User input", | |
| 63 | - embeddingsProvider: null, | |
| 64 | - reranker: null, | |
| 65 | - llm: {} as ILLM, | |
| 66 | - ide: testIde, | |
| 67 | - selectedCode: [] as RangeInFile[], | |
| 68 | - fetch: vi.fn(), | |
| 69 | - }; | |
| 70 | - | |
| 71 | - // Clear all mocks | |
| 72 | - vi.clearAllMocks(); | |
| 73 | - setUpTestDir(); | |
| 74 | - }); | |
| 75 | - | |
| 76 | - afterEach(() => { | |
| 77 | - tearDownTestDir(); | |
| 78 | - }); | |
| 79 | - | |
| 80 | - it("should render a prompt file with no attachments", async () => { | |
| 81 | - const rawContent = "Simple prompt with no attachments"; | |
| 82 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 83 | - rawContent, | |
| 84 | - extras, | |
| 85 | - ); | |
| 86 | - | |
| 87 | - expect(contextItems).toHaveLength(0); | |
| 88 | - expect(renderedPrompt).toBe( | |
| 89 | - "Simple prompt with no attachments\n\nUser input", | |
| 90 | - ); | |
| 91 | - }); | |
| 92 | - | |
| 93 | - it("should handle URL attachments", async () => { | |
| 94 | - const rawContent = "Content with URL @https://example.com"; | |
| 95 | - | |
| 96 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 97 | - rawContent, | |
| 98 | - extras, | |
| 99 | - ); | |
| 100 | - | |
| 101 | - expect(contextItems).toHaveLength(1); | |
| 102 | - expect(renderedPrompt).toContain("Example Content"); | |
| 103 | - }); | |
| 104 | - | |
| 105 | - it("should resolve file attachments", async () => { | |
| 106 | - const rawContent = "Content with file attachment @test.txt"; | |
| 107 | - | |
| 108 | - addToTestDir([["test.txt", "File content"]]); | |
| 109 | - | |
| 110 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 111 | - rawContent, | |
| 112 | - extras, | |
| 113 | - ); | |
| 114 | - | |
| 115 | - expect(contextItems).toHaveLength(1); | |
| 116 | - expect(renderedPrompt).toContain("```test.txt\nFile content\n```"); | |
| 117 | - expect(renderedPrompt).toContain("Content with file attachment @test.txt"); | |
| 118 | - }); | |
| 119 | - | |
| 120 | - it("should handle nested prompt files", async () => { | |
| 121 | - const rawContent = "Main prompt with nested @nested.prompt"; | |
| 122 | - addToTestDir([ | |
| 123 | - ["nested.prompt", "Nested prompt content with @CustomProvider"], | |
| 124 | - ]); | |
| 125 | - | |
| 126 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 127 | - rawContent, | |
| 128 | - extras, | |
| 129 | - ); | |
| 130 | - | |
| 131 | - expect(renderedPrompt).toContain("Custom provider content"); | |
| 132 | - }); | |
| 133 | - | |
| 134 | - it("should handle custom context providers", async () => { | |
| 135 | - const rawContent = "Content with custom provider @CustomProvider"; | |
| 136 | - | |
| 137 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 138 | - rawContent, | |
| 139 | - extras, | |
| 140 | - ); | |
| 141 | - | |
| 142 | - expect(contextItems).toHaveLength(1); | |
| 143 | - expect(renderedPrompt).toContain("Custom provider content"); | |
| 144 | - expect(mockGetContextItems).toHaveBeenCalled(); | |
| 145 | - }); | |
| 146 | - | |
| 147 | - it("should handle multiple attachments", async () => { | |
| 148 | - const rawContent = "Content with @file1.txt and @file2.txt"; | |
| 149 | - addToTestDir([ | |
| 150 | - ["file1.txt", "Content 1"], | |
| 151 | - ["file2.txt", "Content 2"], | |
| 152 | - ]); | |
| 153 | - | |
| 154 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 155 | - rawContent, | |
| 156 | - extras, | |
| 157 | - ); | |
| 158 | - | |
| 159 | - expect(contextItems).toHaveLength(2); | |
| 160 | - expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```"); | |
| 161 | - expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```"); | |
| 162 | - }); | |
| 163 | - | |
| 164 | - it("should handle failed attachment resolutions gracefully", async () => { | |
| 165 | - const rawContent = "Content with @nonexistent"; | |
| 166 | - | |
| 167 | - const [contextItems, renderedPrompt] = await renderPromptFileV2( | |
| 168 | - rawContent, | |
| 169 | - extras, | |
| 170 | - ); | |
| 171 | - | |
| 172 | - expect(contextItems).toHaveLength(0); | |
| 173 | - expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input"); | |
| 174 | - }); | |
| 175 | -}); |
modified core/protocol/core.ts +13 −2
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | Session, |
| 30 | 30 | SessionMetadata, |
| 31 | 31 | SiteIndexingConfig, |
| 32 | - SlashCommandDescription, | |
| 32 | + SlashCommandDescWithSource, | |
| 33 | 33 | StreamDiffLinesPayload, |
| 34 | 34 | ToolCall, |
| 35 | 35 | } from "../"; |
| @@ -118,6 +118,17 @@ | ||
| 118 | 118 | }, |
| 119 | 119 | void, |
| 120 | 120 | ]; |
| 121 | + "mcp/getPrompt": [ | |
| 122 | + { | |
| 123 | + serverName: string; | |
| 124 | + promptName: string; | |
| 125 | + args?: Record<string, string>; | |
| 126 | + }, | |
| 127 | + { | |
| 128 | + prompt: string; | |
| 129 | + description: string | undefined; | |
| 130 | + }, | |
| 131 | + ]; | |
| 121 | 132 | "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; |
| 122 | 133 | "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; |
| 123 | 134 | "autocomplete/complete": [AutocompleteInput, string[]]; |
| @@ -141,7 +152,7 @@ | ||
| 141 | 152 | completionOptions: LLMFullCompletionOptions; |
| 142 | 153 | title: string; |
| 143 | 154 | legacySlashCommandData?: { |
| 144 | - command: SlashCommandDescription; | |
| 155 | + command: SlashCommandDescWithSource; | |
| 145 | 156 | input: string; |
| 146 | 157 | contextItems: ContextItemWithId[]; |
| 147 | 158 | historyIndex: number; |
modified core/protocol/passThrough.ts +1 −0
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | "config/updateSharedConfig", |
| 28 | 28 | "config/updateSelectedModel", |
| 29 | 29 | "mcp/reloadServer", |
| 30 | + "mcp/getPrompt", | |
| 30 | 31 | "context/getContextItems", |
| 31 | 32 | "context/getSymbolsForFiles", |
| 32 | 33 | "context/loadSubmenuItems", |
modified core/tools/parseArgs.ts +1 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | toolCall: ToolCallDelta, |
| 5 | 5 | ): Record<string, any> { |
| 6 | 6 | try { |
| 7 | - return JSON.parse(toolCall.function?.arguments ?? "{}"); | |
| 7 | + return JSON.parse(toolCall.function?.arguments?.trim() || "{}"); | |
| 8 | 8 | } catch (e) { |
| 9 | 9 | console.error( |
| 10 | 10 | `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`, |
added core/util/handlebars/handlebarUtils.ts +111 −0
| @@ -0,0 +1,111 @@ | ||
| 1 | +import { v4 as uuidv4 } from "uuid"; | |
| 2 | + | |
| 3 | +export type HandlebarsType = typeof import("handlebars"); | |
| 4 | + | |
| 5 | +function convertToLetter(num: number): string { | |
| 6 | + let result = ""; | |
| 7 | + while (num > 0) { | |
| 8 | + const remainder = (num - 1) % 26; | |
| 9 | + result = String.fromCharCode(97 + remainder) + result; | |
| 10 | + num = Math.floor((num - 1) / 26); | |
| 11 | + } | |
| 12 | + return result; | |
| 13 | +} | |
| 14 | + | |
| 15 | +export function registerHelpers( | |
| 16 | + handlebars: HandlebarsType, | |
| 17 | + helpers: Array<[string, Handlebars.HelperDelegate]>, | |
| 18 | +): { | |
| 19 | + [key: string]: Promise<string>; | |
| 20 | +} { | |
| 21 | + const promises: { [key: string]: Promise<string> } = {}; | |
| 22 | + | |
| 23 | + for (const [name, helper] of helpers) { | |
| 24 | + handlebars.registerHelper(name, (...args) => { | |
| 25 | + const id = uuidv4(); | |
| 26 | + promises[id] = helper(...args); | |
| 27 | + return `__${id}__`; | |
| 28 | + }); | |
| 29 | + } | |
| 30 | + | |
| 31 | + return promises; | |
| 32 | +} | |
| 33 | + | |
| 34 | +export async function prepareTemplatedFilepaths( | |
| 35 | + handlebars: HandlebarsType, | |
| 36 | + template: string, | |
| 37 | + inputData: Record<string, string>, | |
| 38 | + ctxProviderNames: string[], | |
| 39 | + readFile: (filepath: string) => Promise<string>, | |
| 40 | + getUriFromPath: (path: string) => Promise<string | undefined>, | |
| 41 | +) { | |
| 42 | + // First, replace filepaths with letters to avoid escaping issues | |
| 43 | + const ast = handlebars.parse(template); | |
| 44 | + | |
| 45 | + const filepathLetters: Map<string, string> = new Map(); | |
| 46 | + const requiredContextProviders: Set<string> = new Set(); | |
| 47 | + let withLetterKeys = template; | |
| 48 | + | |
| 49 | + let letterIndex = 1; | |
| 50 | + | |
| 51 | + for (const i in ast.body) { | |
| 52 | + const node = ast.body[i] as any; | |
| 53 | + | |
| 54 | + if (node.type === "MustacheStatement") { | |
| 55 | + const originalNodeVal = node.path.original; | |
| 56 | + if (originalNodeVal.toLowerCase() === "input") { | |
| 57 | + continue; | |
| 58 | + } | |
| 59 | + const isFilepath = !ctxProviderNames.includes(originalNodeVal); | |
| 60 | + | |
| 61 | + if (isFilepath) { | |
| 62 | + const letter = convertToLetter(letterIndex); | |
| 63 | + | |
| 64 | + filepathLetters.set(letter, originalNodeVal); | |
| 65 | + | |
| 66 | + withLetterKeys = withLetterKeys.replace( | |
| 67 | + new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), | |
| 68 | + `{{${letter}}}`, | |
| 69 | + ); | |
| 70 | + | |
| 71 | + letterIndex++; | |
| 72 | + } else { | |
| 73 | + requiredContextProviders.add(originalNodeVal); | |
| 74 | + } | |
| 75 | + } | |
| 76 | + } | |
| 77 | + | |
| 78 | + // Then, resolve the filepaths to their actual content and add to template data | |
| 79 | + // Fallback to simple error string if file read fails | |
| 80 | + const templateData = { ...inputData }; | |
| 81 | + | |
| 82 | + for (const [letter, filepath] of filepathLetters.entries()) { | |
| 83 | + try { | |
| 84 | + const uri = await getUriFromPath(filepath); | |
| 85 | + if (uri) { | |
| 86 | + const fileContents = await readFile(uri); | |
| 87 | + templateData[letter] = fileContents; | |
| 88 | + } else { | |
| 89 | + throw new Error(`File not found: ${filepath}`); | |
| 90 | + } | |
| 91 | + } catch (e) { | |
| 92 | + console.error(`Error reading file in prompt file ${filepath}:`, e); | |
| 93 | + templateData[letter] = `[Error reading file "${filepath}"]`; | |
| 94 | + } | |
| 95 | + } | |
| 96 | + | |
| 97 | + return { withLetterKeys, templateData, requiredContextProviders }; | |
| 98 | +} | |
| 99 | + | |
| 100 | +export async function resolveHelperPromises( | |
| 101 | + renderedString: string, | |
| 102 | + promises: { [key: string]: Promise<string> }, | |
| 103 | +): Promise<string> { | |
| 104 | + await Promise.all(Object.values(promises)); | |
| 105 | + | |
| 106 | + for (const id in promises) { | |
| 107 | + renderedString = renderedString.replace(`__${id}__`, await promises[id]); | |
| 108 | + } | |
| 109 | + | |
| 110 | + return renderedString; | |
| 111 | +} |
added core/util/handlebars/renderTemplatedString.ts +35 −0
| @@ -0,0 +1,35 @@ | ||
| 1 | +import { | |
| 2 | + prepareTemplatedFilepaths, | |
| 3 | + registerHelpers, | |
| 4 | + resolveHelperPromises, | |
| 5 | + type HandlebarsType, | |
| 6 | +} from "./handlebarUtils"; | |
| 7 | + | |
| 8 | +export async function renderTemplatedString( | |
| 9 | + handlebars: HandlebarsType, | |
| 10 | + template: string, | |
| 11 | + inputData: Record<string, string>, | |
| 12 | + availableHelpers: Array<[string, Handlebars.HelperDelegate]>, | |
| 13 | + readFile: (filepath: string) => Promise<string>, | |
| 14 | + getUriFromPath: (path: string) => Promise<string | undefined>, | |
| 15 | +): Promise<string> { | |
| 16 | + const helperPromises = availableHelpers | |
| 17 | + ? registerHelpers(handlebars, availableHelpers) | |
| 18 | + : {}; | |
| 19 | + | |
| 20 | + const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? []; | |
| 21 | + | |
| 22 | + const { withLetterKeys, templateData } = await prepareTemplatedFilepaths( | |
| 23 | + handlebars, | |
| 24 | + template, | |
| 25 | + inputData, | |
| 26 | + ctxProviderNames, | |
| 27 | + readFile, | |
| 28 | + getUriFromPath, | |
| 29 | + ); | |
| 30 | + | |
| 31 | + const templateFn = handlebars.compile(withLetterKeys); | |
| 32 | + const renderedString = templateFn(templateData); | |
| 33 | + | |
| 34 | + return resolveHelperPromises(renderedString, helperPromises); | |
| 35 | +} |
modified core/util/uri.ts +2 −0
| @@ -188,6 +188,7 @@ | ||
| 188 | 188 | dirUriCandidates, |
| 189 | 189 | ); |
| 190 | 190 | const baseName = getUriPathBasename(uri); |
| 191 | + const extension = getFileExtensionFromBasename(baseName); | |
| 191 | 192 | const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2); |
| 192 | 193 | return { |
| 193 | 194 | uri, |
| @@ -195,5 +196,6 @@ | ||
| 195 | 196 | foundInDir, |
| 196 | 197 | last2Parts, |
| 197 | 198 | baseName, |
| 199 | + extension, | |
| 198 | 200 | }; |
| 199 | 201 | } |
modified extensions/intellij/CONTRIBUTING.md +3 −1
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | - [Setup](#setup) |
| 28 | 28 | - [Running the tests](#running-the-tests) |
| 29 | 29 | - [Identifying selectors](#identifying-selectors) |
| 30 | + - [Rebuilding the extension](#rebuilding-the-extension) | |
| 30 | 31 | |
| 31 | 32 | ## Architecture Overview |
| 32 | 33 | |
| @@ -49,6 +50,7 @@ | ||
| 49 | 50 | ### IDE configuration |
| 50 | 51 | |
| 51 | 52 | - Enable code formatting on save: `Settings | Tools | Actions on Save | Reformat code` |
| 53 | +- We recommend installing the [Thread Access Info](https://plugins.jetbrains.com/plugin/16815-thread-access-info) plugin | |
| 52 | 54 | |
| 53 | 55 | ### Node.js Requirements |
| 54 | 56 | |
| @@ -184,7 +186,7 @@ | ||
| 184 | 186 | While the `runIdeForUiTests` task is running, you can visit the following URL |
| 185 | 187 | to view the UI hierarchy of the running IDE: |
| 186 | 188 | |
| 187 | -http://127.0.0.1:8082/ | |
| 189 | +<http://127.0.0.1:8082/> | |
| 188 | 190 | |
| 189 | 191 | #### Rebuilding the extension |
| 190 | 192 |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +1 −0
| @@ -92,6 +92,7 @@ | ||
| 92 | 92 | "config/updateSharedConfig", |
| 93 | 93 | "config/updateSelectedModel", |
| 94 | 94 | "mcp/reloadServer", |
| 95 | + "mcp/getPrompt", | |
| 95 | 96 | "context/getContextItems", |
| 96 | 97 | "context/getSymbolsForFiles", |
| 97 | 98 | "context/loadSubmenuItems", |
modified extensions/vscode/.vscodeignore +0 −1
| @@ -18,7 +18,6 @@ | ||
| 18 | 18 | |
| 19 | 19 | manual-testing-sandbox |
| 20 | 20 | esbuild.js |
| 21 | -esbuild.test.mjs | |
| 22 | 21 | importMetaUrl.js |
| 23 | 22 | scripts |
| 24 | 23 | e2e |
deleted extensions/vscode/esbuild.test.mjs +0 −67
| @@ -1,67 +0,0 @@ | ||
| 1 | -import * as esbuild from "esbuild"; | |
| 2 | -import glob from "glob"; | |
| 3 | - | |
| 4 | -/** | |
| 5 | - * Bundles tests into multiple files, runTestOnVSCodeHost is then run using node runTestOnVSCodeHost.js | |
| 6 | - * It downloads vscode, starts it and passes test file to run - mochaRunner.js | |
| 7 | - * mochaRunner.js then runs tests using Mocha class | |
| 8 | - */ | |
| 9 | - | |
| 10 | -console.log("Bundling tests..."); | |
| 11 | - | |
| 12 | -// Bundles script to run tests on VSCode host + mocha runner that will be invoked from within VSCode host | |
| 13 | -await esbuild.build({ | |
| 14 | - entryPoints: [ | |
| 15 | - // Runs mocha runner on VSCode host using runTests from @vscode/test-electron | |
| 16 | - "src/test/runner/runTestOnVSCodeHost.ts", | |
| 17 | - | |
| 18 | - // Runs the bundled tests using Mocha class | |
| 19 | - "src/test/runner/mochaRunner.ts", | |
| 20 | - ], | |
| 21 | - bundle: true, | |
| 22 | - outdir: "out", | |
| 23 | - | |
| 24 | - external: [ | |
| 25 | - "vscode", | |
| 26 | - | |
| 27 | - // Its important to externalize mocha, otherwise mocha seems to be not initialized properly when running tests | |
| 28 | - // Example warning by esbuild when mocha is not externalized: | |
| 29 | - // [WARNING] "./reporters/parallel-buffered" should be marked as external for use with "require.resolve" [require-resolve-not-external] | |
| 30 | - "mocha", | |
| 31 | - ], | |
| 32 | - format: "cjs", | |
| 33 | - platform: "node", | |
| 34 | - sourcemap: true, | |
| 35 | - loader: { | |
| 36 | - // eslint-disable-next-line @typescript-eslint/naming-convention | |
| 37 | - ".node": "file", | |
| 38 | - }, | |
| 39 | -}); | |
| 40 | - | |
| 41 | -/** | |
| 42 | - * Note: Bundling is done to work around import issues, for example with fkill that does not provide cjs module. | |
| 43 | - * Rather than figuring out a combination of tsconfig.json that would work, I decided to bundle tests instead. | |
| 44 | - */ | |
| 45 | -await esbuild.build({ | |
| 46 | - // Tests can be added anywhere in src folder | |
| 47 | - entryPoints: glob.sync("src/**/*.test.ts"), | |
| 48 | - bundle: true, | |
| 49 | - outdir: "out", | |
| 50 | - external: [ | |
| 51 | - "vscode", | |
| 52 | - | |
| 53 | - // Its important to externalize mocha, otherwise mocha seems to be not initialized properly when running tests | |
| 54 | - "mocha", | |
| 55 | - ], | |
| 56 | - format: "cjs", | |
| 57 | - platform: "node", | |
| 58 | - sourcemap: true, | |
| 59 | - loader: { | |
| 60 | - // eslint-disable-next-line @typescript-eslint/naming-convention | |
| 61 | - ".node": "file", | |
| 62 | - }, | |
| 63 | - // To allow import.meta.path for transformers.js | |
| 64 | - // https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483 | |
| 65 | - inject: ["./scripts/importMetaUrl.js"], | |
| 66 | - define: { "import.meta.url": "importMetaUrl" }, | |
| 67 | -}); |
modified extensions/vscode/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/vscode/package.json +5 −10
| @@ -622,10 +622,8 @@ | ||
| 622 | 622 | "rebuild": "electron-rebuild -v 19.1.8 node-pty", |
| 623 | 623 | "lint": "eslint src --ext ts", |
| 624 | 624 | "lint:fix": "eslint . --ext ts --fix", |
| 625 | - "build-test": "npm run esbuild && node esbuild.test.mjs", | |
| 626 | - "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", | |
| 625 | + "test": "vitest run", | |
| 627 | 626 | "vitest": "vitest run", |
| 628 | - "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", | |
| 629 | 627 | "write-build-timestamp": "node scripts/write-build-timestamp.js", |
| 630 | 628 | "prepackage": "node scripts/prepackage.js", |
| 631 | 629 | "package": "node scripts/package.js", |
| @@ -661,11 +659,12 @@ | ||
| 661 | 659 | "@types/cors": "^2.8.17", |
| 662 | 660 | "@types/express": "^4.17.21", |
| 663 | 661 | "@types/follow-redirects": "^1.14.4", |
| 664 | - "@types/glob": "^8.0.0", | |
| 665 | - "@types/mocha": "^10.0.6", | |
| 662 | + "@types/mocha": "^10.0.10", | |
| 666 | 663 | "@types/node": "16.x", |
| 664 | + "@types/node-fetch": "^2.6.12", | |
| 667 | 665 | "@types/react-dom": "^18.2.4", |
| 668 | 666 | "@types/request": "^2.48.8", |
| 667 | + "@types/uuid": "^10.0.0", | |
| 669 | 668 | "@types/vscode": "1.70", |
| 670 | 669 | "@types/ws": "^8.5.4", |
| 671 | 670 | "@typescript-eslint/eslint-plugin": "^5.45.0", |
| @@ -675,9 +674,7 @@ | ||
| 675 | 674 | "esbuild": "0.17.19", |
| 676 | 675 | "esbuild-visualizer": "^0.6.0", |
| 677 | 676 | "eslint": "^8.28.0", |
| 678 | - "glob": "^8.0.3", | |
| 679 | 677 | "json-schema-to-typescript": "^12.0.0", |
| 680 | - "mocha": "^10.4.0", | |
| 681 | 678 | "ovsx": "^0.8.3", |
| 682 | 679 | "rimraf": "^5.0.5", |
| 683 | 680 | "typescript": "^5.6.3", |
| @@ -689,10 +686,7 @@ | ||
| 689 | 686 | "@continuedev/fetch": "^1.0.10", |
| 690 | 687 | "@electron/rebuild": "^3.2.10", |
| 691 | 688 | "@reduxjs/toolkit": "^1.9.3", |
| 692 | - "@types/node-fetch": "^2.6.11", | |
| 693 | - "@types/uuid": "^9.0.8", | |
| 694 | 689 | "@vscode/ripgrep": "^1.15.9", |
| 695 | - "@vscode/test-electron": "^2.3.9", | |
| 696 | 690 | "axios": "^1.2.5", |
| 697 | 691 | "core": "file:../../core", |
| 698 | 692 | "cors": "^2.8.5", |
| @@ -714,6 +708,7 @@ | ||
| 714 | 708 | "jsdom": "^24.0.0", |
| 715 | 709 | "lru-cache": "^11.0.2", |
| 716 | 710 | "minisearch": "^7.0.0", |
| 711 | + "mocha": "^11.7.1", | |
| 717 | 712 | "monaco-editor": "^0.45.0", |
| 718 | 713 | "monaco-vscode-textmate-theme-converter": "^0.1.7", |
| 719 | 714 | "ncp": "^2.0.0", |
deleted extensions/vscode/src/test/runner/mochaRunner.ts +0 −49
| @@ -1,49 +0,0 @@ | ||
| 1 | -import * as path from "node:path"; | |
| 2 | - | |
| 3 | -import * as glob from "glob"; | |
| 4 | -import Mocha from "mocha"; | |
| 5 | - | |
| 6 | -export function run() { | |
| 7 | - // Avoid timing out when stopping on breakpoints during debugging in VSCode | |
| 8 | - const timeoutOption = process.env.MOCHA_TIMEOUT | |
| 9 | - ? Number.parseInt(process.env.MOCHA_TIMEOUT) | |
| 10 | - : // : undefined; | |
| 11 | - 30_000; | |
| 12 | - | |
| 13 | - // Create the mocha test | |
| 14 | - const mocha = new Mocha({ | |
| 15 | - ui: "tdd", | |
| 16 | - color: true, | |
| 17 | - timeout: timeoutOption, | |
| 18 | - }); | |
| 19 | - | |
| 20 | - // See esbuild.test.mjs for more details | |
| 21 | - // Assumes this file is in out/test/runner/mochaRunner.js | |
| 22 | - const compiledTestSuitesDirectory = path.resolve(__dirname); | |
| 23 | - | |
| 24 | - glob | |
| 25 | - .sync("**/**.test.js", { cwd: compiledTestSuitesDirectory }) | |
| 26 | - .forEach((file) => { | |
| 27 | - mocha.addFile(path.resolve(compiledTestSuitesDirectory, file)); | |
| 28 | - }); | |
| 29 | - | |
| 30 | - console.log( | |
| 31 | - `Testing files in ${compiledTestSuitesDirectory}: ${mocha.files}`, | |
| 32 | - ); | |
| 33 | - | |
| 34 | - return new Promise<void>((resolve, reject) => { | |
| 35 | - try { | |
| 36 | - // Run the mocha test | |
| 37 | - mocha.run((failures) => { | |
| 38 | - if (failures > 0) { | |
| 39 | - reject(new Error(`${failures} tests failed.`)); | |
| 40 | - } else { | |
| 41 | - resolve(); | |
| 42 | - } | |
| 43 | - }); | |
| 44 | - } catch (err) { | |
| 45 | - console.error(err); | |
| 46 | - reject(err); | |
| 47 | - } | |
| 48 | - }); | |
| 49 | -} |
deleted extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts +0 −127
| @@ -1,127 +0,0 @@ | ||
| 1 | -import fs from "node:fs"; | |
| 2 | -import * as path from "node:path"; | |
| 3 | - | |
| 4 | -import { runTests } from "@vscode/test-electron"; | |
| 5 | -import { defaultConfig } from "core/config/default"; | |
| 6 | - | |
| 7 | -export const testWorkspacePath = path.resolve( | |
| 8 | - __dirname, | |
| 9 | - "..", | |
| 10 | - "src", | |
| 11 | - "test", | |
| 12 | - "fixtures", | |
| 13 | - "test-workspace", | |
| 14 | -); | |
| 15 | - | |
| 16 | -const continueGlobalDir = path.resolve( | |
| 17 | - __dirname, | |
| 18 | - "..", | |
| 19 | - "src", | |
| 20 | - "test", | |
| 21 | - "fixtures", | |
| 22 | - ".continue", | |
| 23 | -); | |
| 24 | - | |
| 25 | -function setupTestWorkspace() { | |
| 26 | - if (fs.existsSync(testWorkspacePath)) { | |
| 27 | - fs.rmSync(testWorkspacePath, { recursive: true }); | |
| 28 | - } | |
| 29 | - fs.mkdirSync(testWorkspacePath, { | |
| 30 | - recursive: true, | |
| 31 | - }); | |
| 32 | - | |
| 33 | - fs.writeFileSync( | |
| 34 | - path.join(testWorkspacePath, "test.py"), | |
| 35 | - "print('Hello World!')", | |
| 36 | - ); | |
| 37 | - fs.writeFileSync( | |
| 38 | - path.join(testWorkspacePath, "index.js"), | |
| 39 | - "console.log('Hello World!')", | |
| 40 | - ); | |
| 41 | - fs.writeFileSync( | |
| 42 | - path.join(testWorkspacePath, "test.py"), | |
| 43 | - "print('Hello World!')", | |
| 44 | - ); | |
| 45 | - fs.mkdirSync(path.join(testWorkspacePath, "test-folder")); | |
| 46 | - fs.writeFileSync( | |
| 47 | - path.join(testWorkspacePath, "test-folder", "test.js"), | |
| 48 | - "console.log('Hello World!')", | |
| 49 | - ); | |
| 50 | -} | |
| 51 | - | |
| 52 | -function setupContinueGlobalDir() { | |
| 53 | - if (fs.existsSync(continueGlobalDir)) { | |
| 54 | - fs.rmSync(continueGlobalDir, { recursive: true }); | |
| 55 | - } | |
| 56 | - fs.mkdirSync(continueGlobalDir, { | |
| 57 | - recursive: true, | |
| 58 | - }); | |
| 59 | - fs.writeFileSync( | |
| 60 | - path.join(continueGlobalDir, "config.json"), | |
| 61 | - JSON.stringify({ | |
| 62 | - ...defaultConfig, | |
| 63 | - models: [ | |
| 64 | - { | |
| 65 | - title: "Test Model", | |
| 66 | - provider: "openai", | |
| 67 | - model: "gpt-3.5-turbo", | |
| 68 | - apiKey: "API_KEY", | |
| 69 | - }, | |
| 70 | - ], | |
| 71 | - }), | |
| 72 | - ); | |
| 73 | -} | |
| 74 | - | |
| 75 | -function cleanupTestWorkspace() { | |
| 76 | - if (fs.existsSync(testWorkspacePath)) { | |
| 77 | - fs.rmSync(testWorkspacePath, { recursive: true }); | |
| 78 | - } | |
| 79 | -} | |
| 80 | - | |
| 81 | -function cleanupContinueGlobalDir() { | |
| 82 | - if (fs.existsSync(continueGlobalDir)) { | |
| 83 | - fs.rmSync(continueGlobalDir, { recursive: true }); | |
| 84 | - } | |
| 85 | -} | |
| 86 | - | |
| 87 | -async function main() { | |
| 88 | - try { | |
| 89 | - // The folder containing the Extension Manifest package.json | |
| 90 | - // Passed to `--extensionDevelopmentPath` | |
| 91 | - | |
| 92 | - // Assumes this file is in out/runTestOnVSCodeHost.js | |
| 93 | - const extensionDevelopmentPath = path.resolve(__dirname, "../"); | |
| 94 | - console.log("extensionDevelopmentPath", extensionDevelopmentPath); | |
| 95 | - | |
| 96 | - // The path to test runner | |
| 97 | - // Passed to --extensionTestsPath | |
| 98 | - const extensionTestsPath = path.resolve( | |
| 99 | - extensionDevelopmentPath, | |
| 100 | - "out/mochaRunner", | |
| 101 | - ); | |
| 102 | - | |
| 103 | - const extensionTestsEnv = { | |
| 104 | - NODE_ENV: "test", | |
| 105 | - CONTINUE_GLOBAL_DIR: continueGlobalDir, | |
| 106 | - }; | |
| 107 | - | |
| 108 | - setupTestWorkspace(); | |
| 109 | - setupContinueGlobalDir(); | |
| 110 | - | |
| 111 | - // Download VS Code, unzip it and run the integration test | |
| 112 | - await runTests({ | |
| 113 | - extensionDevelopmentPath, | |
| 114 | - extensionTestsPath, | |
| 115 | - extensionTestsEnv, | |
| 116 | - launchArgs: [testWorkspacePath], | |
| 117 | - }); | |
| 118 | - } catch (err) { | |
| 119 | - console.error("Failed to run tests", err); | |
| 120 | - process.exit(1); | |
| 121 | - } finally { | |
| 122 | - cleanupTestWorkspace(); | |
| 123 | - cleanupContinueGlobalDir(); | |
| 124 | - } | |
| 125 | -} | |
| 126 | - | |
| 127 | -main(); |
deleted extensions/vscode/src/test/test-suites/ideUtils.test.ts +0 −89
| @@ -1,89 +0,0 @@ | ||
| 1 | -import assert from "node:assert"; | |
| 2 | -import path from "node:path"; | |
| 3 | - | |
| 4 | -import { describe, test } from "mocha"; | |
| 5 | -import * as vscode from "vscode"; | |
| 6 | - | |
| 7 | -import { VsCodeIdeUtils } from "../../util/ideUtils"; | |
| 8 | -import { testWorkspacePath } from "../runner/runTestOnVSCodeHost"; | |
| 9 | - | |
| 10 | -const util = require("node:util"); | |
| 11 | -const asyncExec = util.promisify(require("node:child_process").exec); | |
| 12 | - | |
| 13 | -/* | |
| 14 | - TODO check uri => path assumptions, will only work in some environments. | |
| 15 | -*/ | |
| 16 | -describe("IDE Utils", () => { | |
| 17 | - const utils = new VsCodeIdeUtils(); | |
| 18 | - const testPyPath = path.join(testWorkspacePath, "test.py"); | |
| 19 | - const testJsPath = path.join(testWorkspacePath, "test-folder", "test.js"); | |
| 20 | - | |
| 21 | - test("getWorkspaceDirectories", async () => { | |
| 22 | - const [dir] = utils.getWorkspaceDirectories(); | |
| 23 | - assert(dir.toString().endsWith("test-workspace")); | |
| 24 | - }); | |
| 25 | - | |
| 26 | - test("fileExists", async () => { | |
| 27 | - const exists2 = await utils.fileExists( | |
| 28 | - vscode.Uri.file(path.join(testWorkspacePath, "test.py")), | |
| 29 | - ); | |
| 30 | - assert(exists2); | |
| 31 | - }); | |
| 32 | - | |
| 33 | - test("getOpenFiles", async () => { | |
| 34 | - let openFiles = utils.getOpenFiles(); | |
| 35 | - assert(openFiles.length === 0); | |
| 36 | - // await utils.openFile(testPyPath); | |
| 37 | - let document = await vscode.workspace.openTextDocument(testPyPath); | |
| 38 | - await vscode.window.showTextDocument(document, { | |
| 39 | - preview: false, | |
| 40 | - }); | |
| 41 | - openFiles = utils.getOpenFiles(); | |
| 42 | - assert(openFiles.length === 1); | |
| 43 | - assert(openFiles[0].fsPath === testPyPath); | |
| 44 | - | |
| 45 | - document = await vscode.workspace.openTextDocument(testJsPath); | |
| 46 | - await vscode.window.showTextDocument(document, { | |
| 47 | - preview: false, | |
| 48 | - }); | |
| 49 | - openFiles = utils.getOpenFiles(); | |
| 50 | - assert(openFiles.length === 2); | |
| 51 | - assert(openFiles.find((f) => f.fsPath === testPyPath)); | |
| 52 | - assert(openFiles.find((f) => f.fsPath === testJsPath)); | |
| 53 | - }); | |
| 54 | - | |
| 55 | - test("getUniqueId", async () => { | |
| 56 | - const uniqueId = utils.getUniqueId(); | |
| 57 | - assert(uniqueId.length === 64); | |
| 58 | - const regex = /^[a-z0-9]+$/; | |
| 59 | - assert(regex.test(uniqueId)); | |
| 60 | - }); | |
| 61 | - | |
| 62 | - test.skip("getTerminalContents", async () => { | |
| 63 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 64 | - const terminal = vscode.window.createTerminal(); | |
| 65 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 66 | - terminal.show(); | |
| 67 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 68 | - terminal.sendText("echo abcdefg", true); | |
| 69 | - const contents = await utils.getTerminalContents(1); | |
| 70 | - console.log("TERMINAL CONTENTS: ", contents); | |
| 71 | - assert(contents.includes("abcdefg")); | |
| 72 | - terminal.dispose(); | |
| 73 | - }); | |
| 74 | - | |
| 75 | - test("noDiff", async () => { | |
| 76 | - const noDiff = await utils.getDiff(false); | |
| 77 | - assert(noDiff.length === 0); | |
| 78 | - }); | |
| 79 | - | |
| 80 | - test.skip("getBranch", async () => { | |
| 81 | - const uri = vscode.Uri.file(testWorkspacePath); | |
| 82 | - const branch = await utils.getBranch(uri); | |
| 83 | - assert(typeof branch === "string"); | |
| 84 | - const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", { | |
| 85 | - cwd: __dirname, | |
| 86 | - }); | |
| 87 | - assert(branch === stdout?.trim()); | |
| 88 | - }); | |
| 89 | -}); |
modified gui/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified gui/package.json +1 −0
| @@ -40,6 +40,7 @@ | ||
| 40 | 40 | "dompurify": "^3.0.6", |
| 41 | 41 | "downshift": "^7.6.0", |
| 42 | 42 | "escape-carriage": "^1.3.1", |
| 43 | + "handlebars": "^4.7.8", | |
| 43 | 44 | "lodash": "^4.17.21", |
| 44 | 45 | "lowlight": "^3.3.0", |
| 45 | 46 | "minisearch": "^7.0.2", |
modified gui/src/components/ConversationStarters/ConversationStarterCard.tsx +3 −3
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; |
| 2 | -import { SlashCommandDescription } from "core"; | |
| 2 | +import { SlashCommandDescWithSource } from "core"; | |
| 3 | 3 | |
| 4 | 4 | interface ConversationStarterCardProps { |
| 5 | - command: SlashCommandDescription; | |
| 6 | - onClick: (command: SlashCommandDescription) => void; | |
| 5 | + command: SlashCommandDescWithSource; | |
| 6 | + onClick: (command: SlashCommandDescWithSource) => void; | |
| 7 | 7 | } |
| 8 | 8 | |
| 9 | 9 | export function ConversationStarterCard({ |
modified gui/src/components/ConversationStarters/ConversationStarterCards.tsx +7 −3
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import { useState } from "react"; |
| 3 | 3 | import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; |
| 4 | 4 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| @@ -23,8 +23,12 @@ | ||
| 23 | 23 | isCommandBookmarked(command.name), |
| 24 | 24 | ); |
| 25 | 25 | |
| 26 | - function onClick(command: SlashCommandDescription) { | |
| 27 | - mainEditor?.commands.insertPrompt(command); | |
| 26 | + function onClick(command: SlashCommandDescWithSource) { | |
| 27 | + mainEditor?.commands.insertPrompt({ | |
| 28 | + description: command.description, | |
| 29 | + title: command.name, | |
| 30 | + content: command.prompt, | |
| 31 | + }); | |
| 28 | 32 | } |
| 29 | 33 | |
| 30 | 34 | if (bookmarkedSlashCommands.length === 0) { |
modified gui/src/components/ConversationStarters/__tests__/utils.test.ts +10 −2
| @@ -1,27 +1,35 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import { sortCommandsByBookmarkStatus } from "../utils"; |
| 3 | 3 | |
| 4 | 4 | describe("sortCommandsByBookmarkStatus", () => { |
| 5 | - const mockCommands: SlashCommandDescription[] = [ | |
| 5 | + const mockCommands: SlashCommandDescWithSource[] = [ | |
| 6 | 6 | { |
| 7 | 7 | name: "command1", |
| 8 | 8 | description: "First command", |
| 9 | 9 | prompt: "This is command 1", |
| 10 | + source: "built-in", | |
| 11 | + isLegacy: false, | |
| 10 | 12 | }, |
| 11 | 13 | { |
| 12 | 14 | name: "command2", |
| 13 | 15 | description: "Second command", |
| 14 | 16 | prompt: "This is command 2", |
| 17 | + source: "built-in", | |
| 18 | + isLegacy: false, | |
| 15 | 19 | }, |
| 16 | 20 | { |
| 17 | 21 | name: "command3", |
| 18 | 22 | description: "Third command", |
| 19 | 23 | prompt: "This is command 3", |
| 24 | + source: "built-in", | |
| 25 | + isLegacy: false, | |
| 20 | 26 | }, |
| 21 | 27 | { |
| 22 | 28 | name: "command4", |
| 23 | 29 | description: "Fourth command", |
| 24 | 30 | prompt: "This is command 4", |
| 31 | + source: "built-in", | |
| 32 | + isLegacy: false, | |
| 25 | 33 | }, |
| 26 | 34 | ]; |
| 27 | 35 |
modified gui/src/components/ConversationStarters/utils.ts +3 −3
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import {} from "core/config/default"; |
| 3 | 3 | |
| 4 | 4 | /** |
| @@ -8,9 +8,9 @@ | ||
| 8 | 8 | * @returns A new sorted array with bookmarked commands first |
| 9 | 9 | */ |
| 10 | 10 | export function sortCommandsByBookmarkStatus( |
| 11 | - commands: SlashCommandDescription[], | |
| 11 | + commands: SlashCommandDescWithSource[], | |
| 12 | 12 | bookmarkedCommands: string[], |
| 13 | -): SlashCommandDescription[] { | |
| 13 | +): SlashCommandDescWithSource[] { | |
| 14 | 14 | return [...commands].sort((a, b) => { |
| 15 | 15 | const aIsBookmarked = bookmarkedCommands.includes(a.name); |
| 16 | 16 | const bIsBookmarked = bookmarkedCommands.includes(b.name); |
modified gui/src/components/console/ResultGroup.tsx +5 −1
| @@ -10,7 +10,11 @@ | ||
| 10 | 10 | return ( |
| 11 | 11 | <> |
| 12 | 12 | {group.map((result, i) => ( |
| 13 | - <Result key={i} result={result} prevResult={group[i - 1]}></Result> | |
| 13 | + <Result | |
| 14 | + key={`${result.timestamp}-${i}`} | |
| 15 | + result={result} | |
| 16 | + prevResult={group[i - 1]} | |
| 17 | + ></Result> | |
| 14 | 18 | ))} |
| 15 | 19 | </> |
| 16 | 20 | ); |
modified gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +17 −10
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | PencilIcon, |
| 5 | 5 | } from "@heroicons/react/24/outline"; |
| 6 | 6 | import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid"; |
| 7 | -import { SlashCommandDescription } from "core"; | |
| 7 | +import { SlashCommandDescWithSource } from "core"; | |
| 8 | 8 | import { useContext, useMemo } from "react"; |
| 9 | 9 | import { useAuth } from "../../../../context/Auth"; |
| 10 | 10 | import { IdeMessengerContext } from "../../../../context/IdeMessenger"; |
| @@ -15,10 +15,12 @@ | ||
| 15 | 15 | import { useLump } from "../LumpContext"; |
| 16 | 16 | import { ExploreBlocksButton } from "./ExploreBlocksButton"; |
| 17 | 17 | |
| 18 | -type PromptWithSlug = SlashCommandDescription & { slug?: string }; | |
| 18 | +interface PromptCommandWithSlug extends SlashCommandDescWithSource { | |
| 19 | + slug?: string; | |
| 20 | +} | |
| 19 | 21 | |
| 20 | 22 | interface PromptRowProps { |
| 21 | - prompt: PromptWithSlug; | |
| 23 | + prompt: PromptCommandWithSlug; | |
| 22 | 24 | isBookmarked: boolean; |
| 23 | 25 | setIsBookmarked: (isBookmarked: boolean) => void; |
| 24 | 26 | onEdit?: () => void; |
| @@ -38,7 +40,11 @@ | ||
| 38 | 40 | |
| 39 | 41 | const handlePromptClick = (e: React.MouseEvent) => { |
| 40 | 42 | e.stopPropagation(); |
| 41 | - mainEditor?.commands.insertPrompt(prompt); | |
| 43 | + mainEditor?.commands.insertPrompt({ | |
| 44 | + title: prompt.name, | |
| 45 | + description: prompt.description, | |
| 46 | + content: prompt.prompt, | |
| 47 | + }); | |
| 42 | 48 | hideLump(); |
| 43 | 49 | }; |
| 44 | 50 | |
| @@ -102,7 +108,7 @@ | ||
| 102 | 108 | (state) => state.config.config.slashCommands ?? [], |
| 103 | 109 | ); |
| 104 | 110 | |
| 105 | - const handleEdit = (prompt: PromptWithSlug) => { | |
| 111 | + const handleEdit = (prompt: PromptCommandWithSlug) => { | |
| 106 | 112 | if (prompt.promptFile) { |
| 107 | 113 | ideMessenger.post("openFile", { |
| 108 | 114 | path: prompt.promptFile, |
| @@ -120,23 +126,24 @@ | ||
| 120 | 126 | }; |
| 121 | 127 | |
| 122 | 128 | const sortedCommands = useMemo(() => { |
| 123 | - const promptsWithSlug: PromptWithSlug[] = structuredClone(slashCommands); | |
| 129 | + const promptsWithSlug: PromptCommandWithSlug[] = | |
| 130 | + structuredClone(slashCommands); | |
| 124 | 131 | // get the slugs from rawYaml |
| 125 | 132 | if (selectedProfile?.rawYaml) { |
| 126 | 133 | const parsed = parseConfigYaml(selectedProfile.rawYaml); |
| 127 | 134 | const parsedPrompts = parsed.prompts ?? []; |
| 128 | 135 | |
| 129 | 136 | let index = 0; |
| 130 | - for (const prompt of promptsWithSlug) { | |
| 137 | + for (const commandWithSlug of promptsWithSlug) { | |
| 131 | 138 | // skip for local prompt files |
| 132 | - if (prompt.promptFile) continue; | |
| 139 | + if (commandWithSlug.promptFile) continue; | |
| 133 | 140 | |
| 134 | 141 | const yamlPrompt = parsedPrompts[index]; |
| 135 | 142 | if (yamlPrompt) { |
| 136 | 143 | if ("uses" in yamlPrompt) { |
| 137 | - prompt.slug = yamlPrompt.uses; | |
| 144 | + commandWithSlug.slug = yamlPrompt.uses; | |
| 138 | 145 | } else { |
| 139 | - prompt.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; | |
| 146 | + commandWithSlug.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; | |
| 140 | 147 | } |
| 141 | 148 | } |
| 142 | 149 | index = index + 1; |
modified gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts +12 −9
| @@ -1,8 +1,9 @@ | ||
| 1 | 1 | import { mergeAttributes, Node } from "@tiptap/core"; |
| 2 | 2 | import { Node as ProseMirrorNode } from "@tiptap/pm/model"; |
| 3 | 3 | import { ReactNodeViewRenderer } from "@tiptap/react"; |
| 4 | -import { ContextItemWithId, SlashCommandDescription } from "core"; | |
| 4 | +import { ContextItemWithId } from "core"; | |
| 5 | 5 | import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat"; |
| 6 | +import { ComboBoxItem } from "../../../types"; | |
| 6 | 7 | import { PromptBlockPreview } from "./PromptBlockPreview"; |
| 7 | 8 | |
| 8 | 9 | export interface PromptBlockOptions { |
| @@ -20,7 +21,9 @@ | ||
| 20 | 21 | /** |
| 21 | 22 | * Insert a prompt block into the editor |
| 22 | 23 | */ |
| 23 | - insertPrompt: (item: SlashCommandDescription) => ReturnType; | |
| 24 | + insertPrompt: ( | |
| 25 | + item: Pick<ComboBoxItem, "title" | "content" | "description">, | |
| 26 | + ) => ReturnType; | |
| 24 | 27 | |
| 25 | 28 | /** |
| 26 | 29 | * Clear all prompt blocks from the editor |
| @@ -76,15 +79,15 @@ | ||
| 76 | 79 | addCommands() { |
| 77 | 80 | return { |
| 78 | 81 | insertPrompt: |
| 79 | - (prompt: SlashCommandDescription) => | |
| 82 | + (item) => | |
| 80 | 83 | ({ chain }) => { |
| 81 | - const item: ContextItemWithId = { | |
| 82 | - content: prompt.prompt ?? "", | |
| 83 | - name: prompt.name, | |
| 84 | - description: prompt.description, | |
| 84 | + const contextItem: ContextItemWithId = { | |
| 85 | + content: item.content ?? "", | |
| 86 | + name: item.title, | |
| 87 | + description: item.description, | |
| 85 | 88 | id: { |
| 86 | 89 | providerTitle: "prompt", |
| 87 | - itemId: prompt.name, | |
| 90 | + itemId: item.title, | |
| 88 | 91 | }, |
| 89 | 92 | }; |
| 90 | 93 | |
| @@ -93,7 +96,7 @@ | ||
| 93 | 96 | .insertContentAt(0, { |
| 94 | 97 | type: this.name, |
| 95 | 98 | attrs: { |
| 96 | - item, | |
| 99 | + item: contextItem, | |
| 97 | 100 | inputId: MAIN_EDITOR_INPUT_ID, |
| 98 | 101 | }, |
| 99 | 102 | }) |
modified gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts +1 −5
| @@ -22,11 +22,7 @@ | ||
| 22 | 22 | // First delete the slash character and any text after it |
| 23 | 23 | editor.chain().focus().deleteRange(range).run(); |
| 24 | 24 | |
| 25 | - editor.commands.insertPrompt({ | |
| 26 | - name: props.title, | |
| 27 | - description: props.description, | |
| 28 | - prompt: props.content, | |
| 29 | - }); | |
| 25 | + editor.commands.insertPrompt(props); | |
| 30 | 26 | }, |
| 31 | 27 | }, |
| 32 | 28 | }; |
added gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.test.ts +536 −0
| @@ -0,0 +1,536 @@ | ||
| 1 | +import { JSONContent } from "@tiptap/react"; | |
| 2 | +import { ContextItemWithId } from "core"; | |
| 3 | +import { expect, test, vi } from "vitest"; | |
| 4 | +import { processEditorContent } from "./processEditorContent"; | |
| 5 | + | |
| 6 | +describe("processEditorContent", () => { | |
| 7 | + // Create some reusable test data | |
| 8 | + const createContextItem = ( | |
| 9 | + content: string, | |
| 10 | + description: string, | |
| 11 | + fileUri?: string, | |
| 12 | + editing?: boolean, | |
| 13 | + ): ContextItemWithId => ({ | |
| 14 | + id: { providerTitle: "test", itemId: "test-id" }, | |
| 15 | + content, | |
| 16 | + description, | |
| 17 | + name: "Test Item", | |
| 18 | + editing, | |
| 19 | + uri: fileUri ? { type: "file", value: fileUri } : undefined, | |
| 20 | + }); | |
| 21 | + | |
| 22 | + test("processEditorContent should return empty arrays when content is empty", () => { | |
| 23 | + // Empty editor state | |
| 24 | + const emptyEditorState: JSONContent = { | |
| 25 | + type: "doc", | |
| 26 | + content: [], | |
| 27 | + }; | |
| 28 | + | |
| 29 | + const result = processEditorContent(emptyEditorState); | |
| 30 | + | |
| 31 | + expect(result.parts).toEqual([]); | |
| 32 | + expect(result.contextRequests).toEqual([]); | |
| 33 | + expect(result.selectedCode).toEqual([]); | |
| 34 | + expect(result.slashCommandName).toBeUndefined(); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + test("processEditorContent should process text paragraphs", () => { | |
| 38 | + const editorState: JSONContent = { | |
| 39 | + type: "doc", | |
| 40 | + content: [ | |
| 41 | + { | |
| 42 | + type: "paragraph", | |
| 43 | + content: [ | |
| 44 | + { | |
| 45 | + type: "text", | |
| 46 | + text: "Hello world", | |
| 47 | + }, | |
| 48 | + ], | |
| 49 | + }, | |
| 50 | + { | |
| 51 | + type: "paragraph", | |
| 52 | + content: [ | |
| 53 | + { | |
| 54 | + type: "text", | |
| 55 | + text: "This is another paragraph", | |
| 56 | + }, | |
| 57 | + ], | |
| 58 | + }, | |
| 59 | + ], | |
| 60 | + }; | |
| 61 | + | |
| 62 | + const result = processEditorContent(editorState); | |
| 63 | + | |
| 64 | + expect(result.parts).toEqual([ | |
| 65 | + { | |
| 66 | + type: "text", | |
| 67 | + text: "Hello world\nThis is another paragraph", | |
| 68 | + }, | |
| 69 | + ]); | |
| 70 | + expect(result.contextRequests).toEqual([]); | |
| 71 | + expect(result.selectedCode).toEqual([]); | |
| 72 | + }); | |
| 73 | + | |
| 74 | + test("processEditorContent should detect slash commands", () => { | |
| 75 | + const editorState: JSONContent = { | |
| 76 | + type: "doc", | |
| 77 | + content: [ | |
| 78 | + { | |
| 79 | + type: "prompt-block", | |
| 80 | + attrs: { | |
| 81 | + item: { | |
| 82 | + name: "test-command", | |
| 83 | + }, | |
| 84 | + }, | |
| 85 | + }, | |
| 86 | + { | |
| 87 | + type: "paragraph", | |
| 88 | + content: [ | |
| 89 | + { | |
| 90 | + type: "text", | |
| 91 | + text: "Some text after the prompt", | |
| 92 | + }, | |
| 93 | + ], | |
| 94 | + }, | |
| 95 | + ], | |
| 96 | + }; | |
| 97 | + | |
| 98 | + const result = processEditorContent(editorState); | |
| 99 | + | |
| 100 | + expect(result.slashCommandName).toBe("test-command"); | |
| 101 | + expect(result.parts).toEqual([ | |
| 102 | + { | |
| 103 | + type: "text", | |
| 104 | + text: "Some text after the prompt", | |
| 105 | + }, | |
| 106 | + ]); | |
| 107 | + }); | |
| 108 | + | |
| 109 | + test("processEditorContent should handle mentions and collect context requests", () => { | |
| 110 | + const editorState: JSONContent = { | |
| 111 | + type: "doc", | |
| 112 | + content: [ | |
| 113 | + { | |
| 114 | + type: "paragraph", | |
| 115 | + content: [ | |
| 116 | + { | |
| 117 | + type: "text", | |
| 118 | + text: "Hello ", | |
| 119 | + }, | |
| 120 | + { | |
| 121 | + type: "mention", | |
| 122 | + attrs: { | |
| 123 | + id: "fileSearch", | |
| 124 | + label: "@fileSearch", | |
| 125 | + itemType: "contextProvider", | |
| 126 | + }, | |
| 127 | + }, | |
| 128 | + { | |
| 129 | + type: "text", | |
| 130 | + text: " and also ", | |
| 131 | + }, | |
| 132 | + { | |
| 133 | + type: "mention", | |
| 134 | + attrs: { | |
| 135 | + id: "github", | |
| 136 | + label: "@github", | |
| 137 | + itemType: "contextProvider", | |
| 138 | + }, | |
| 139 | + }, | |
| 140 | + ], | |
| 141 | + }, | |
| 142 | + ], | |
| 143 | + }; | |
| 144 | + | |
| 145 | + const result = processEditorContent(editorState); | |
| 146 | + | |
| 147 | + expect(result.parts).toEqual([ | |
| 148 | + { | |
| 149 | + type: "text", | |
| 150 | + text: "Hello @fileSearch and also @github", | |
| 151 | + }, | |
| 152 | + ]); | |
| 153 | + expect(result.contextRequests).toEqual([ | |
| 154 | + { provider: "fileSearch" }, | |
| 155 | + { provider: "github" }, | |
| 156 | + ]); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + test("processEditorContent should handle code blocks", () => { | |
| 160 | + const codeItem = createContextItem( | |
| 161 | + "function test() {\n return 'hello';\n}", | |
| 162 | + "a description", | |
| 163 | + "file:///example.js", | |
| 164 | + ); | |
| 165 | + | |
| 166 | + const editorState: JSONContent = { | |
| 167 | + type: "doc", | |
| 168 | + content: [ | |
| 169 | + { | |
| 170 | + type: "paragraph", | |
| 171 | + content: [ | |
| 172 | + { | |
| 173 | + type: "text", | |
| 174 | + text: "Check this code:", | |
| 175 | + }, | |
| 176 | + ], | |
| 177 | + }, | |
| 178 | + { | |
| 179 | + type: "code-block", | |
| 180 | + attrs: { | |
| 181 | + item: codeItem, | |
| 182 | + }, | |
| 183 | + }, | |
| 184 | + ], | |
| 185 | + }; | |
| 186 | + | |
| 187 | + const result = processEditorContent(editorState); | |
| 188 | + | |
| 189 | + expect(result.parts).toEqual([ | |
| 190 | + { | |
| 191 | + type: "text", | |
| 192 | + text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n", | |
| 193 | + }, | |
| 194 | + ]); | |
| 195 | + expect(result.selectedCode).toHaveLength(1); | |
| 196 | + expect(result.selectedCode[0].filepath).toBe("file:///example.js"); | |
| 197 | + }); | |
| 198 | + | |
| 199 | + test("processEditorContent should not include editing code blocks in the text", () => { | |
| 200 | + const editingCodeItem = createContextItem( | |
| 201 | + "function test() {\n return 'hello';\n}", | |
| 202 | + "a description", | |
| 203 | + "file:///editing.js", | |
| 204 | + true, // Set editing to true | |
| 205 | + ); | |
| 206 | + | |
| 207 | + const editorState: JSONContent = { | |
| 208 | + type: "doc", | |
| 209 | + content: [ | |
| 210 | + { | |
| 211 | + type: "paragraph", | |
| 212 | + content: [ | |
| 213 | + { | |
| 214 | + type: "text", | |
| 215 | + text: "Edit this code:", | |
| 216 | + }, | |
| 217 | + ], | |
| 218 | + }, | |
| 219 | + { | |
| 220 | + type: "code-block", | |
| 221 | + attrs: { | |
| 222 | + item: editingCodeItem, | |
| 223 | + }, | |
| 224 | + }, | |
| 225 | + ], | |
| 226 | + }; | |
| 227 | + | |
| 228 | + const result = processEditorContent(editorState); | |
| 229 | + | |
| 230 | + // The code block should not be included in parts because it's marked as editing | |
| 231 | + expect(result.parts).toEqual([ | |
| 232 | + { | |
| 233 | + type: "text", | |
| 234 | + text: "Edit this code:", | |
| 235 | + }, | |
| 236 | + ]); | |
| 237 | + | |
| 238 | + // But it should still be in selectedCode | |
| 239 | + expect(result.selectedCode).toHaveLength(1); | |
| 240 | + expect(result.selectedCode[0].filepath).toBe("file:///editing.js"); | |
| 241 | + }); | |
| 242 | + | |
| 243 | + test("processEditorContent should handle images", () => { | |
| 244 | + const editorState: JSONContent = { | |
| 245 | + type: "doc", | |
| 246 | + content: [ | |
| 247 | + { | |
| 248 | + type: "paragraph", | |
| 249 | + content: [ | |
| 250 | + { | |
| 251 | + type: "text", | |
| 252 | + text: "Here's an image:", | |
| 253 | + }, | |
| 254 | + ], | |
| 255 | + }, | |
| 256 | + { | |
| 257 | + type: "image", | |
| 258 | + attrs: { | |
| 259 | + src: "https://example.com/image.png", | |
| 260 | + }, | |
| 261 | + }, | |
| 262 | + ], | |
| 263 | + }; | |
| 264 | + | |
| 265 | + const result = processEditorContent(editorState); | |
| 266 | + | |
| 267 | + expect(result.parts).toEqual([ | |
| 268 | + { | |
| 269 | + type: "text", | |
| 270 | + text: "Here's an image:", | |
| 271 | + }, | |
| 272 | + { | |
| 273 | + type: "imageUrl", | |
| 274 | + imageUrl: { url: "https://example.com/image.png" }, | |
| 275 | + }, | |
| 276 | + ]); | |
| 277 | + }); | |
| 278 | + | |
| 279 | + test("processEditorContent should handle complex content with multiple elements", () => { | |
| 280 | + const codeItem = createContextItem( | |
| 281 | + "const x = 42;", | |
| 282 | + "a description", | |
| 283 | + "file:///script.ts", | |
| 284 | + ); | |
| 285 | + | |
| 286 | + const editorState: JSONContent = { | |
| 287 | + type: "doc", | |
| 288 | + content: [ | |
| 289 | + { | |
| 290 | + type: "prompt-block", | |
| 291 | + attrs: { | |
| 292 | + item: { | |
| 293 | + name: "explain", | |
| 294 | + }, | |
| 295 | + }, | |
| 296 | + }, | |
| 297 | + { | |
| 298 | + type: "paragraph", | |
| 299 | + content: [ | |
| 300 | + { | |
| 301 | + type: "text", | |
| 302 | + text: "Please explain this code and also check ", | |
| 303 | + }, | |
| 304 | + { | |
| 305 | + type: "mention", | |
| 306 | + attrs: { | |
| 307 | + id: "related", | |
| 308 | + label: "@related", | |
| 309 | + itemType: "similarFiles", | |
| 310 | + }, | |
| 311 | + }, | |
| 312 | + ], | |
| 313 | + }, | |
| 314 | + { | |
| 315 | + type: "code-block", | |
| 316 | + attrs: { | |
| 317 | + item: codeItem, | |
| 318 | + }, | |
| 319 | + }, | |
| 320 | + { | |
| 321 | + type: "paragraph", | |
| 322 | + content: [ | |
| 323 | + { | |
| 324 | + type: "text", | |
| 325 | + text: "What does this constant do?", | |
| 326 | + }, | |
| 327 | + ], | |
| 328 | + }, | |
| 329 | + { | |
| 330 | + type: "image", | |
| 331 | + attrs: { | |
| 332 | + src: "https://example.com/diagram.png", | |
| 333 | + }, | |
| 334 | + }, | |
| 335 | + ], | |
| 336 | + }; | |
| 337 | + | |
| 338 | + const result = processEditorContent(editorState); | |
| 339 | + | |
| 340 | + expect(result.slashCommandName).toBe("explain"); | |
| 341 | + expect(result.contextRequests).toEqual([{ provider: "similarFiles" }]); | |
| 342 | + expect(result.selectedCode).toHaveLength(1); | |
| 343 | + expect(result.selectedCode[0].filepath).toBe("file:///script.ts"); | |
| 344 | + | |
| 345 | + // `\n\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`; | |
| 346 | + | |
| 347 | + expect(result.parts).toEqual([ | |
| 348 | + { | |
| 349 | + type: "text", | |
| 350 | + text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?", | |
| 351 | + }, | |
| 352 | + { | |
| 353 | + type: "imageUrl", | |
| 354 | + imageUrl: { url: "https://example.com/diagram.png" }, | |
| 355 | + }, | |
| 356 | + ]); | |
| 357 | + }); | |
| 358 | + | |
| 359 | + test("processEditorContent should merge consecutive text parts", () => { | |
| 360 | + const editorState: JSONContent = { | |
| 361 | + type: "doc", | |
| 362 | + content: [ | |
| 363 | + { | |
| 364 | + type: "paragraph", | |
| 365 | + content: [ | |
| 366 | + { | |
| 367 | + type: "text", | |
| 368 | + text: "First paragraph", | |
| 369 | + }, | |
| 370 | + ], | |
| 371 | + }, | |
| 372 | + { | |
| 373 | + type: "paragraph", | |
| 374 | + content: [ | |
| 375 | + { | |
| 376 | + type: "text", | |
| 377 | + text: "Second paragraph", | |
| 378 | + }, | |
| 379 | + ], | |
| 380 | + }, | |
| 381 | + { | |
| 382 | + type: "image", | |
| 383 | + attrs: { | |
| 384 | + src: "https://example.com/image.png", | |
| 385 | + }, | |
| 386 | + }, | |
| 387 | + { | |
| 388 | + type: "paragraph", | |
| 389 | + content: [ | |
| 390 | + { | |
| 391 | + type: "text", | |
| 392 | + text: "Third paragraph", | |
| 393 | + }, | |
| 394 | + ], | |
| 395 | + }, | |
| 396 | + ], | |
| 397 | + }; | |
| 398 | + | |
| 399 | + const result = processEditorContent(editorState); | |
| 400 | + | |
| 401 | + // First two paragraphs should be merged, but the third should be separate | |
| 402 | + // because there's an image in between | |
| 403 | + expect(result.parts).toEqual([ | |
| 404 | + { | |
| 405 | + type: "text", | |
| 406 | + text: "First paragraph\nSecond paragraph", | |
| 407 | + }, | |
| 408 | + { | |
| 409 | + type: "imageUrl", | |
| 410 | + imageUrl: { url: "https://example.com/image.png" }, | |
| 411 | + }, | |
| 412 | + { | |
| 413 | + type: "text", | |
| 414 | + text: "Third paragraph", | |
| 415 | + }, | |
| 416 | + ]); | |
| 417 | + }); | |
| 418 | + | |
| 419 | + test("processEditorContent should handle unexpected content types gracefully", () => { | |
| 420 | + // Testing with an unknown node type | |
| 421 | + const editorState: JSONContent = { | |
| 422 | + type: "doc", | |
| 423 | + content: [ | |
| 424 | + { | |
| 425 | + type: "paragraph", | |
| 426 | + content: [ | |
| 427 | + { | |
| 428 | + type: "text", | |
| 429 | + text: "Normal text", | |
| 430 | + }, | |
| 431 | + ], | |
| 432 | + }, | |
| 433 | + { | |
| 434 | + type: "unknown-type", // This type doesn't exist | |
| 435 | + content: [ | |
| 436 | + { | |
| 437 | + type: "text", | |
| 438 | + text: "This should be ignored", | |
| 439 | + }, | |
| 440 | + ], | |
| 441 | + }, | |
| 442 | + ], | |
| 443 | + }; | |
| 444 | + | |
| 445 | + // Spy on console.warn to verify it's called | |
| 446 | + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | |
| 447 | + | |
| 448 | + const result = processEditorContent(editorState); | |
| 449 | + | |
| 450 | + // Only the normal paragraph should be processed | |
| 451 | + expect(result.parts).toEqual([ | |
| 452 | + { | |
| 453 | + type: "text", | |
| 454 | + text: "Normal text", | |
| 455 | + }, | |
| 456 | + ]); | |
| 457 | + | |
| 458 | + // Console.warn should be called for the unknown type | |
| 459 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 460 | + "Unexpected content type", | |
| 461 | + "unknown-type", | |
| 462 | + ); | |
| 463 | + | |
| 464 | + warnSpy.mockRestore(); | |
| 465 | + }); | |
| 466 | + | |
| 467 | + test("processEditorContent should handle missing attrs in code blocks", () => { | |
| 468 | + // Testing with a code block that has no item attribute | |
| 469 | + const editorState: JSONContent = { | |
| 470 | + type: "doc", | |
| 471 | + content: [ | |
| 472 | + { | |
| 473 | + type: "code-block", | |
| 474 | + // Missing attrs property | |
| 475 | + }, | |
| 476 | + ], | |
| 477 | + }; | |
| 478 | + | |
| 479 | + // Spy on console.warn to verify it's called | |
| 480 | + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | |
| 481 | + | |
| 482 | + const result = processEditorContent(editorState); | |
| 483 | + | |
| 484 | + // No parts should be created | |
| 485 | + expect(result.parts).toEqual([]); | |
| 486 | + expect(result.selectedCode).toEqual([]); | |
| 487 | + | |
| 488 | + // Console.warn should be called for the missing item attribute | |
| 489 | + expect(warnSpy).toHaveBeenCalledWith("codeBlock has no item attribute"); | |
| 490 | + | |
| 491 | + warnSpy.mockRestore(); | |
| 492 | + }); | |
| 493 | + | |
| 494 | + test("processEditorContent should handle paragraphs with unexpected child types", () => { | |
| 495 | + // Testing with a paragraph that has an unknown child type | |
| 496 | + const editorState: JSONContent = { | |
| 497 | + type: "doc", | |
| 498 | + content: [ | |
| 499 | + { | |
| 500 | + type: "paragraph", | |
| 501 | + content: [ | |
| 502 | + { | |
| 503 | + type: "text", | |
| 504 | + text: "Normal text ", | |
| 505 | + }, | |
| 506 | + { | |
| 507 | + type: "unknown-child", // This type doesn't exist | |
| 508 | + text: "This should be ignored", | |
| 509 | + }, | |
| 510 | + ], | |
| 511 | + }, | |
| 512 | + ], | |
| 513 | + }; | |
| 514 | + | |
| 515 | + // Spy on console.warn to verify it's called | |
| 516 | + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | |
| 517 | + | |
| 518 | + const result = processEditorContent(editorState); | |
| 519 | + | |
| 520 | + // Only the normal text should be processed | |
| 521 | + expect(result.parts).toEqual([ | |
| 522 | + { | |
| 523 | + type: "text", | |
| 524 | + text: "Normal text ", | |
| 525 | + }, | |
| 526 | + ]); | |
| 527 | + | |
| 528 | + // Console.warn should be called for the unknown child type | |
| 529 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 530 | + "Unexpected child type", | |
| 531 | + "unknown-child", | |
| 532 | + ); | |
| 533 | + | |
| 534 | + warnSpy.mockRestore(); | |
| 535 | + }); | |
| 536 | +}); |
added gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +119 −0
| @@ -0,0 +1,119 @@ | ||
| 1 | +import Image from "@tiptap/extension-image"; | |
| 2 | +import { Paragraph } from "@tiptap/extension-paragraph"; | |
| 3 | +import { Text } from "@tiptap/extension-text"; | |
| 4 | +import { JSONContent } from "@tiptap/react"; | |
| 5 | +import { | |
| 6 | + ContextItemWithId, | |
| 7 | + MessagePart, | |
| 8 | + RangeInFile, | |
| 9 | + TextMessagePart, | |
| 10 | +} from "core"; | |
| 11 | +import { ctxItemToRifWithContents } from "core/commands/util"; | |
| 12 | +import { getUriDescription } from "core/util/uri"; | |
| 13 | +import { CodeBlock, Mention, PromptBlock } from "../extensions"; | |
| 14 | +import { GetContextRequest } from "./types"; | |
| 15 | + | |
| 16 | +interface MentionAttrs { | |
| 17 | + label: string; | |
| 18 | + id: string; | |
| 19 | + itemType?: string; | |
| 20 | + query?: string; | |
| 21 | +} | |
| 22 | + | |
| 23 | +function resolvePromptBlock(p: JSONContent): string | undefined { | |
| 24 | + return p.attrs?.item.name; | |
| 25 | +} | |
| 26 | + | |
| 27 | +function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] { | |
| 28 | + const contextRequests: GetContextRequest[] = []; | |
| 29 | + | |
| 30 | + const text = (p.content || []) | |
| 31 | + .map((child) => { | |
| 32 | + switch (child.type) { | |
| 33 | + case Text.name: | |
| 34 | + return child.text; | |
| 35 | + case Mention.name: | |
| 36 | + const attrs = child.attrs as MentionAttrs; | |
| 37 | + contextRequests.push({ | |
| 38 | + provider: | |
| 39 | + attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!, | |
| 40 | + }); | |
| 41 | + return child.attrs?.renderInlineAs ?? child.attrs?.label; | |
| 42 | + | |
| 43 | + default: | |
| 44 | + console.warn("Unexpected child type", child.type); | |
| 45 | + return ""; | |
| 46 | + } | |
| 47 | + }) | |
| 48 | + .join("") | |
| 49 | + .trimStart(); | |
| 50 | + | |
| 51 | + return [text, contextRequests]; | |
| 52 | +} | |
| 53 | + | |
| 54 | +export function processEditorContent(editorState: JSONContent) { | |
| 55 | + const contextRequests: GetContextRequest[] = []; | |
| 56 | + const selectedCode: RangeInFile[] = []; | |
| 57 | + let slashCommandName: string | undefined; | |
| 58 | + | |
| 59 | + const parts: MessagePart[] = []; | |
| 60 | + for (const p of editorState?.content || []) { | |
| 61 | + switch (p.type) { | |
| 62 | + case PromptBlock.name: | |
| 63 | + slashCommandName = resolvePromptBlock(p); | |
| 64 | + break; | |
| 65 | + case Paragraph.name: | |
| 66 | + const [text, ctxItems] = resolveParagraph(p); | |
| 67 | + | |
| 68 | + contextRequests.push(...ctxItems); | |
| 69 | + | |
| 70 | + if (text) { | |
| 71 | + // Merge with previous text part if possible | |
| 72 | + if (parts[parts.length - 1]?.type === "text") { | |
| 73 | + (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; | |
| 74 | + } else { | |
| 75 | + parts.push({ type: "text", text }); | |
| 76 | + } | |
| 77 | + } | |
| 78 | + break; | |
| 79 | + case CodeBlock.name: | |
| 80 | + if (!p.attrs?.item) { | |
| 81 | + console.warn("codeBlock has no item attribute"); | |
| 82 | + break; | |
| 83 | + } | |
| 84 | + | |
| 85 | + const contextItem = p.attrs.item as ContextItemWithId; | |
| 86 | + const rif = ctxItemToRifWithContents(contextItem, true); | |
| 87 | + selectedCode.push(rif); | |
| 88 | + | |
| 89 | + // If editing, only include in selectedCode | |
| 90 | + if (contextItem.editing) { | |
| 91 | + break; | |
| 92 | + } | |
| 93 | + | |
| 94 | + const { extension, relativePathOrBasename } = getUriDescription( | |
| 95 | + rif.filepath, | |
| 96 | + window.workspacePaths ?? [], | |
| 97 | + ); | |
| 98 | + const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`; | |
| 99 | + | |
| 100 | + if (parts[parts.length - 1]?.type === "text") { | |
| 101 | + (parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText; | |
| 102 | + } else { | |
| 103 | + parts.push({ type: "text", text: codeText }); | |
| 104 | + } | |
| 105 | + break; | |
| 106 | + case Image.name: | |
| 107 | + parts.push({ | |
| 108 | + type: "imageUrl", | |
| 109 | + imageUrl: { url: p.attrs?.src }, | |
| 110 | + }); | |
| 111 | + break; | |
| 112 | + default: { | |
| 113 | + console.warn("Unexpected content type", p.type); | |
| 114 | + } | |
| 115 | + } | |
| 116 | + } | |
| 117 | + | |
| 118 | + return { parts, contextRequests, selectedCode, slashCommandName }; | |
| 119 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderMcpPrompt.ts +32 −0
| @@ -0,0 +1,32 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 3 | + | |
| 4 | +export async function renderMcpPrompt( | |
| 5 | + command: SlashCommandDescWithSource, | |
| 6 | + ideMessenger: IIdeMessenger, | |
| 7 | + userInput?: string, | |
| 8 | +) { | |
| 9 | + // TODO add support for mcp prompt args using command.mcpArgs | |
| 10 | + const args: { [key: string]: string } = {}; | |
| 11 | + if (command.mcpArgs) { | |
| 12 | + command.mcpArgs.forEach((arg, i) => { | |
| 13 | + args[arg.name] = ""; | |
| 14 | + }); | |
| 15 | + } | |
| 16 | + const response = await ideMessenger.request("mcp/getPrompt", { | |
| 17 | + serverName: command.mcpServerName!, | |
| 18 | + promptName: command.name, | |
| 19 | + args: args, | |
| 20 | + }); | |
| 21 | + if (response.status === "success") { | |
| 22 | + let renderedPrompt = response.content.prompt; | |
| 23 | + if (userInput) { | |
| 24 | + renderedPrompt += `\n\n${userInput}`; | |
| 25 | + } | |
| 26 | + return renderedPrompt; | |
| 27 | + } else { | |
| 28 | + throw new Error( | |
| 29 | + `Failed to get MCP prompt for slash command ${command.name}`, | |
| 30 | + ); | |
| 31 | + } | |
| 32 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.test.ts +128 −0
| @@ -0,0 +1,128 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { beforeEach, describe, it, vi } from "vitest"; | |
| 3 | +import { | |
| 4 | + MockIdeMessenger, | |
| 5 | + MockResponseHandler, | |
| 6 | +} from "../../../../context/MockIdeMessenger"; | |
| 7 | +import { getRenderedV1Prompt } from "./renderPromptv1"; | |
| 8 | + | |
| 9 | +function getTestPromptV1Command(body: string): SlashCommandDescWithSource { | |
| 10 | + return { | |
| 11 | + prompt: body, | |
| 12 | + name: "test-prompt-name", | |
| 13 | + description: "test-prompt-description", | |
| 14 | + isLegacy: false, | |
| 15 | + source: "prompt-file-v1", | |
| 16 | + }; | |
| 17 | +} | |
| 18 | +describe("get rendered v1 prompt file", () => { | |
| 19 | + const ideMessenger = new MockIdeMessenger(); | |
| 20 | + const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? ""; | |
| 21 | + const customGetContextItems: MockResponseHandler< | |
| 22 | + "context/getContextItems" | |
| 23 | + > = async ({ name }) => { | |
| 24 | + if (name === "diff") { | |
| 25 | + return [ | |
| 26 | + { | |
| 27 | + id: { | |
| 28 | + itemId: "id", | |
| 29 | + providerTitle: "diff", | |
| 30 | + }, | |
| 31 | + name: "name", | |
| 32 | + description: "description", | |
| 33 | + content: "Diff provider content", | |
| 34 | + }, | |
| 35 | + ]; | |
| 36 | + } | |
| 37 | + return []; | |
| 38 | + }; | |
| 39 | + beforeEach(async () => { | |
| 40 | + vi.clearAllMocks(); | |
| 41 | + ideMessenger.resetMocks(); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + it("should render a prompt file with no attachments or templated input", async () => { | |
| 45 | + const rawContent = "Simple prompt with no attachments"; | |
| 46 | + const command = getTestPromptV1Command(rawContent); | |
| 47 | + const rendered = await getRenderedV1Prompt( | |
| 48 | + ideMessenger, | |
| 49 | + command, | |
| 50 | + "User input", | |
| 51 | + [], | |
| 52 | + ); | |
| 53 | + expect(rendered).toBe("Simple prompt with no attachments\n\nUser input"); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + it("should render a prompt file templated input", async () => { | |
| 57 | + const rawContent = "{{{ input }}} Simple prompt with no attachments"; | |
| 58 | + const command = getTestPromptV1Command(rawContent); | |
| 59 | + const rendered = await getRenderedV1Prompt( | |
| 60 | + ideMessenger, | |
| 61 | + command, | |
| 62 | + "User input", | |
| 63 | + [], | |
| 64 | + ); | |
| 65 | + expect(rendered).toBe("User input Simple prompt with no attachments"); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + it("Should handle file attachments", async () => { | |
| 69 | + ideMessenger.responses["readFile"] = "Test file content"; | |
| 70 | + const rawContent = "Content with URL {{{ testFile.txt }}}"; | |
| 71 | + const command = getTestPromptV1Command(rawContent); | |
| 72 | + const rendered = await getRenderedV1Prompt( | |
| 73 | + ideMessenger, | |
| 74 | + command, | |
| 75 | + "User input", | |
| 76 | + [], | |
| 77 | + ); | |
| 78 | + expect(rendered).toBe("Content with URL Test file content\n\nUser input"); | |
| 79 | + }); | |
| 80 | + | |
| 81 | + it("should handle supported providers", async () => { | |
| 82 | + ideMessenger.responseHandlers["context/getContextItems"] = | |
| 83 | + customGetContextItems; | |
| 84 | + const rawContent = "Tell me about {{{ diff }}} please"; | |
| 85 | + const command = getTestPromptV1Command(rawContent); | |
| 86 | + const rendered = await getRenderedV1Prompt( | |
| 87 | + ideMessenger, | |
| 88 | + command, | |
| 89 | + "User input", | |
| 90 | + [], | |
| 91 | + ); | |
| 92 | + expect(rendered).toBe( | |
| 93 | + "Tell me about Diff provider content please\n\nUser input", | |
| 94 | + ); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("should render file read errors within prompt", async () => { | |
| 98 | + ideMessenger.responses["fileExists"] = false; | |
| 99 | + const rawContent = "Content with provider {{{ nonexistent }}}"; | |
| 100 | + const command = getTestPromptV1Command(rawContent); | |
| 101 | + const rendered = await getRenderedV1Prompt( | |
| 102 | + ideMessenger, | |
| 103 | + command, | |
| 104 | + "User input", | |
| 105 | + [], | |
| 106 | + ); | |
| 107 | + expect(rendered).toBe( | |
| 108 | + `Content with provider [Error reading file "nonexistent"]\n\nUser input`, | |
| 109 | + ); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + it("should handle multiple attachments", async () => { | |
| 113 | + ideMessenger.responseHandlers["context/getContextItems"] = | |
| 114 | + customGetContextItems; | |
| 115 | + ideMessenger.responses["readFile"] = "Test file content"; | |
| 116 | + const rawContent = "Content with {{{ diff }}} and {{{ file.txt }}}"; | |
| 117 | + const command = getTestPromptV1Command(rawContent); | |
| 118 | + const rendered = await getRenderedV1Prompt( | |
| 119 | + ideMessenger, | |
| 120 | + command, | |
| 121 | + "User input", | |
| 122 | + [], | |
| 123 | + ); | |
| 124 | + expect(rendered).toBe( | |
| 125 | + "Content with Diff provider content and Test file content\n\nUser input", | |
| 126 | + ); | |
| 127 | + }); | |
| 128 | +}); |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts +58 −0
| @@ -0,0 +1,58 @@ | ||
| 1 | +import { | |
| 2 | + ContextProviderName, | |
| 3 | + RangeInFile, | |
| 4 | + SlashCommandDescWithSource, | |
| 5 | +} from "core"; | |
| 6 | +import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles"; | |
| 7 | +import { renderTemplatedString } from "core/util/handlebars/renderTemplatedString"; | |
| 8 | +import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 9 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 10 | + | |
| 11 | +export async function getRenderedV1Prompt( | |
| 12 | + ideMessenger: IIdeMessenger, | |
| 13 | + command: SlashCommandDescWithSource, | |
| 14 | + userInput: string, | |
| 15 | + selectedCode: RangeInFile[], | |
| 16 | +): Promise<string> { | |
| 17 | + if (!command.prompt) { | |
| 18 | + return ""; | |
| 19 | + } | |
| 20 | + const handleBarHelpers = SUPPORTED_PROMPT_CONTEXT_PROVIDERS.map( | |
| 21 | + (name: ContextProviderName): [string, Handlebars.HelperDelegate] => [ | |
| 22 | + name, | |
| 23 | + async (helperContext: any) => { | |
| 24 | + const response = await ideMessenger.request("context/getContextItems", { | |
| 25 | + fullInput: userInput, | |
| 26 | + name, | |
| 27 | + query: "", | |
| 28 | + selectedCode, | |
| 29 | + }); | |
| 30 | + if (response.status === "success") { | |
| 31 | + return response.content.map((item) => item.content).join("\n\n"); | |
| 32 | + } else { | |
| 33 | + throw new Error( | |
| 34 | + `Failed to get context items from provider "${name}": ${response.error}`, | |
| 35 | + ); | |
| 36 | + } | |
| 37 | + }, | |
| 38 | + ], | |
| 39 | + ); | |
| 40 | + const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); | |
| 41 | + const getUriFromPath = (path: string) => { | |
| 42 | + return resolveRelativePathInDir(path, ideMessenger.ide, workspaceDirs); | |
| 43 | + }; | |
| 44 | + const handlebars = await import("handlebars"); | |
| 45 | + let rendered = await renderTemplatedString( | |
| 46 | + handlebars, | |
| 47 | + command.prompt, | |
| 48 | + { input: userInput }, | |
| 49 | + handleBarHelpers, | |
| 50 | + ideMessenger.ide.readFile.bind(ideMessenger.ide), | |
| 51 | + getUriFromPath, | |
| 52 | + ); | |
| 53 | + // For prompt file append the input if it isn't rendered | |
| 54 | + if (!rendered.includes(userInput)) { | |
| 55 | + rendered = rendered + `\n\n${userInput}`; | |
| 56 | + } | |
| 57 | + return rendered.trim(); | |
| 58 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.test.ts +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | +import { MockIdeMessenger } from "../../../../context/MockIdeMessenger"; | |
| 4 | +import { getPromptV2ContextRequests } from "./renderPromptv2"; | |
| 5 | + | |
| 6 | +function getTestPromptV2Command(body: string): SlashCommandDescWithSource { | |
| 7 | + return { | |
| 8 | + prompt: body, | |
| 9 | + name: "test-prompt-name", | |
| 10 | + description: "test-prompt-description", | |
| 11 | + isLegacy: false, | |
| 12 | + source: "prompt-file-v2", | |
| 13 | + }; | |
| 14 | +} | |
| 15 | +describe("getPromptV2ContextRequests", () => { | |
| 16 | + const ideMessenger = new MockIdeMessenger(); | |
| 17 | + const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? ""; | |
| 18 | + beforeEach(async () => { | |
| 19 | + vi.clearAllMocks(); | |
| 20 | + ideMessenger.resetMocks(); | |
| 21 | + }); | |
| 22 | + | |
| 23 | + it("should render a prompt file with no attachments", async () => { | |
| 24 | + const rawContent = "Simple prompt with no attachments"; | |
| 25 | + const command = getTestPromptV2Command(rawContent); | |
| 26 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 27 | + expect(requests).toHaveLength(0); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should handle URL attachments", async () => { | |
| 31 | + const rawContent = "Content with URL @https://example.com"; | |
| 32 | + const command = getTestPromptV2Command(rawContent); | |
| 33 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 34 | + expect(requests).toHaveLength(1); | |
| 35 | + expect(requests[0].provider).toBe("url"); | |
| 36 | + expect(requests[0].query).toBe("https://example.com"); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + it("should resolve file attachments", async () => { | |
| 40 | + const rawContent = "Content with file attachment @test.txt"; | |
| 41 | + const command = getTestPromptV2Command(rawContent); | |
| 42 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 43 | + | |
| 44 | + expect(requests).toHaveLength(1); | |
| 45 | + expect(requests[0].provider).toBe("file"); | |
| 46 | + expect(requests[0].query).toBe(`${firstDir}/test.txt`); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + it("should handle nested prompt files", async () => { | |
| 50 | + ideMessenger.responses["readFile"] = "Contents @myfile.txt"; | |
| 51 | + const rawContent = "Main prompt with nested @test.prompt"; | |
| 52 | + const command = getTestPromptV2Command(rawContent); | |
| 53 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 54 | + expect(requests).toHaveLength(2); | |
| 55 | + expect(requests[0].provider).toBe("file"); | |
| 56 | + expect(requests[0].query).toBe(`${firstDir}/myfile.txt`); | |
| 57 | + expect(requests[1].provider).toBe("file"); | |
| 58 | + expect(requests[1].query).toBe(`${firstDir}/test.prompt`); | |
| 59 | + }); | |
| 60 | + | |
| 61 | + it("should ignore unsupported providers", async () => { | |
| 62 | + ideMessenger.responses["fileExists"] = false; | |
| 63 | + const rawContent = "Content with custom provider @unsupported"; | |
| 64 | + const command = getTestPromptV2Command(rawContent); | |
| 65 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 66 | + expect(requests).toHaveLength(0); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("should handle multiple attachments", async () => { | |
| 70 | + const rawContent = "Content with @file1.txt and @file2.txt"; | |
| 71 | + const command = getTestPromptV2Command(rawContent); | |
| 72 | + const requests = await getPromptV2ContextRequests(ideMessenger, command); | |
| 73 | + | |
| 74 | + expect(requests).toHaveLength(2); | |
| 75 | + expect(requests[0].provider).toBe("file"); | |
| 76 | + expect(requests[0].query).toBe(`${firstDir}/file1.txt`); | |
| 77 | + expect(requests[1].provider).toBe("file"); | |
| 78 | + expect(requests[1].query).toBe(`${firstDir}/file2.txt`); | |
| 79 | + }); | |
| 80 | +}); |
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts +69 −0
| @@ -0,0 +1,69 @@ | ||
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | +import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles"; | |
| 3 | +import { resolveRelativePathInDir } from "core/util/ideUtils"; | |
| 4 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 5 | +import { GetContextRequest } from "./types"; | |
| 6 | + | |
| 7 | +export async function getPromptV2ContextRequests( | |
| 8 | + ideMessenger: IIdeMessenger, | |
| 9 | + command: SlashCommandDescWithSource, | |
| 10 | +): Promise<GetContextRequest[]> { | |
| 11 | + if (!command.prompt) { | |
| 12 | + return []; | |
| 13 | + } | |
| 14 | + const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); | |
| 15 | + const visitedFiles = new Set<string>(); | |
| 16 | + if (command.promptFile) { | |
| 17 | + visitedFiles.add(command.promptFile); | |
| 18 | + } | |
| 19 | + | |
| 20 | + const contextRequests: GetContextRequest[] = []; | |
| 21 | + | |
| 22 | + async function addContextRequestsRecursive(promptBody: string) { | |
| 23 | + // Files | |
| 24 | + const templateMatches = promptBody.matchAll(/@([^\s]+)/g); | |
| 25 | + for (const match of templateMatches) { | |
| 26 | + const name = match[1]; | |
| 27 | + | |
| 28 | + if (SUPPORTED_PROMPT_CONTEXT_PROVIDERS.includes(name)) { | |
| 29 | + contextRequests.push({ | |
| 30 | + provider: name, | |
| 31 | + }); | |
| 32 | + continue; | |
| 33 | + } | |
| 34 | + | |
| 35 | + // URLs | |
| 36 | + if (name.startsWith("http")) { | |
| 37 | + contextRequests.push({ | |
| 38 | + provider: "url", | |
| 39 | + query: name, | |
| 40 | + }); | |
| 41 | + continue; | |
| 42 | + } | |
| 43 | + | |
| 44 | + // Files | |
| 45 | + const resolvedFileUri = await resolveRelativePathInDir( | |
| 46 | + match[1], | |
| 47 | + ideMessenger.ide, | |
| 48 | + workspaceDirs, | |
| 49 | + ); | |
| 50 | + if (resolvedFileUri) { | |
| 51 | + const contents = await ideMessenger.ide.readFile(resolvedFileUri); | |
| 52 | + if (name.endsWith(".prompt")) { | |
| 53 | + if (visitedFiles.has(resolvedFileUri)) { | |
| 54 | + return []; | |
| 55 | + } | |
| 56 | + visitedFiles.add(resolvedFileUri); | |
| 57 | + // As well as any context providers it references | |
| 58 | + await addContextRequestsRecursive(contents); | |
| 59 | + } | |
| 60 | + contextRequests.push({ | |
| 61 | + provider: "file", | |
| 62 | + query: resolvedFileUri, | |
| 63 | + }); | |
| 64 | + } | |
| 65 | + } | |
| 66 | + } | |
| 67 | + await addContextRequestsRecursive(command.prompt); | |
| 68 | + return contextRequests; | |
| 69 | +} |
added gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts +145 −0
| @@ -0,0 +1,145 @@ | ||
| 1 | +import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core"; | |
| 2 | +import { stripImages } from "core/util/messageContent"; | |
| 3 | +import { IIdeMessenger } from "../../../../context/IdeMessenger"; | |
| 4 | +import { renderMcpPrompt } from "./renderMcpPrompt"; | |
| 5 | +import { getRenderedV1Prompt } from "./renderPromptv1"; | |
| 6 | +import { getPromptV2ContextRequests } from "./renderPromptv2"; | |
| 7 | +import { GetContextRequest } from "./types"; | |
| 8 | + | |
| 9 | +/* | |
| 10 | +Slash commands can come from many sources. Render based on the source. | |
| 11 | +*/ | |
| 12 | +export async function renderSlashCommandPrompt( | |
| 13 | + ideMessenger: IIdeMessenger, | |
| 14 | + commandName: string | undefined, | |
| 15 | + parts: MessagePart[], | |
| 16 | + availableSlashCommands: SlashCommandDescWithSource[], | |
| 17 | + selectedCode: RangeInFile[], | |
| 18 | +): Promise<{ | |
| 19 | + slashedParts: MessagePart[]; | |
| 20 | + legacyCommandWithInput?: { | |
| 21 | + command: SlashCommandDescWithSource; | |
| 22 | + input: string; | |
| 23 | + }; | |
| 24 | + contextRequests: GetContextRequest[]; | |
| 25 | +}> { | |
| 26 | + const NO_COMMAND = { | |
| 27 | + slashedParts: parts, | |
| 28 | + legacyCommandWithInput: undefined, | |
| 29 | + contextRequests: [], | |
| 30 | + }; | |
| 31 | + if (!commandName) { | |
| 32 | + return NO_COMMAND; | |
| 33 | + } | |
| 34 | + const command = availableSlashCommands.find((c) => c.name === commandName); | |
| 35 | + if (!command) { | |
| 36 | + return NO_COMMAND; | |
| 37 | + } | |
| 38 | + | |
| 39 | + const nonTextParts = parts.filter((part) => part.type !== "text"); | |
| 40 | + const textParts = parts.filter((part) => part.type === "text"); | |
| 41 | + const slashedParts: MessagePart[] = [...nonTextParts]; | |
| 42 | + | |
| 43 | + const userInput = stripImages(textParts).trimStart(); | |
| 44 | + | |
| 45 | + const legacyCommandWithInput = command.isLegacy | |
| 46 | + ? { | |
| 47 | + command, | |
| 48 | + input: userInput, | |
| 49 | + } | |
| 50 | + : undefined; | |
| 51 | + | |
| 52 | + const contextRequests: GetContextRequest[] = []; | |
| 53 | + | |
| 54 | + switch (command.source) { | |
| 55 | + case "built-in-legacy": | |
| 56 | + case "config-ts-slash-command": | |
| 57 | + /** | |
| 58 | + * For legacy slash commands, we simply insert the text "/{name}" in front of the message | |
| 59 | + * And then parsing for this is done in core | |
| 60 | + */ | |
| 61 | + slashedParts.push({ | |
| 62 | + type: "text", | |
| 63 | + text: `/${command.name}${command.prompt ? " " + command.prompt : ""}${userInput ? " " + userInput : ""}`, | |
| 64 | + }); | |
| 65 | + break; | |
| 66 | + case "mcp-prompt": | |
| 67 | + const renderedMcpPrompt = await renderMcpPrompt( | |
| 68 | + command, | |
| 69 | + ideMessenger, | |
| 70 | + userInput, | |
| 71 | + ); | |
| 72 | + slashedParts.push({ | |
| 73 | + type: "text", | |
| 74 | + text: renderedMcpPrompt, | |
| 75 | + }); | |
| 76 | + break; | |
| 77 | + case "prompt-file-v1": | |
| 78 | + case "prompt-file-v2": | |
| 79 | + case "yaml-prompt-block": | |
| 80 | + case "invokable-rule": | |
| 81 | + if (!command.prompt) { | |
| 82 | + console.warn(`Invalid/empty prompt from slash command ${command.name}`); | |
| 83 | + break; | |
| 84 | + } | |
| 85 | + let renderedPrompt: string; | |
| 86 | + if ( | |
| 87 | + command.source === "prompt-file-v1" || | |
| 88 | + command.prompt.includes("{{{ input }}}") | |
| 89 | + ) { | |
| 90 | + renderedPrompt = await getRenderedV1Prompt( | |
| 91 | + ideMessenger, | |
| 92 | + command, | |
| 93 | + userInput, | |
| 94 | + selectedCode, | |
| 95 | + ); | |
| 96 | + } else { | |
| 97 | + const promptFileCtxRequests = await getPromptV2ContextRequests( | |
| 98 | + ideMessenger, | |
| 99 | + command, | |
| 100 | + ); | |
| 101 | + contextRequests.push(...promptFileCtxRequests); | |
| 102 | + renderedPrompt = [command.prompt, userInput].join("\n\n").trim(); | |
| 103 | + } | |
| 104 | + | |
| 105 | + if (renderedPrompt) { | |
| 106 | + slashedParts.push({ | |
| 107 | + type: "text", | |
| 108 | + text: renderedPrompt, // Includes user input | |
| 109 | + }); | |
| 110 | + } else { | |
| 111 | + console.warn( | |
| 112 | + `Invalid/empty prompt + input from slash command ${command.name}`, | |
| 113 | + ); | |
| 114 | + } | |
| 115 | + | |
| 116 | + break; | |
| 117 | + case "built-in": | |
| 118 | + case "json-custom-command": | |
| 119 | + if (!command.prompt) { | |
| 120 | + console.warn(`Slash command ${command.name} is missing prompt`); | |
| 121 | + break; | |
| 122 | + } | |
| 123 | + let rendered = command.prompt; | |
| 124 | + if (userInput) { | |
| 125 | + rendered += `\n\n${userInput}`; | |
| 126 | + } | |
| 127 | + if (rendered) { | |
| 128 | + slashedParts.push({ | |
| 129 | + type: "text", | |
| 130 | + text: rendered, | |
| 131 | + }); | |
| 132 | + } else { | |
| 133 | + console.warn( | |
| 134 | + `Invalid/empty prompt + input from slash command ${command.name}`, | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + default: | |
| 138 | + break; | |
| 139 | + } | |
| 140 | + return { | |
| 141 | + slashedParts, | |
| 142 | + legacyCommandWithInput, | |
| 143 | + contextRequests, | |
| 144 | + }; | |
| 145 | +} |
modified gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +112 −226
| @@ -1,7 +1,4 @@ | ||
| 1 | 1 | import { Dispatch } from "@reduxjs/toolkit"; |
| 2 | -import Image from "@tiptap/extension-image"; | |
| 3 | -import { Paragraph } from "@tiptap/extension-paragraph"; | |
| 4 | -import { Text } from "@tiptap/extension-text"; | |
| 5 | 2 | import { JSONContent } from "@tiptap/react"; |
| 6 | 3 | import { |
| 7 | 4 | ContextItemWithId, |
| @@ -10,44 +7,35 @@ | ||
| 10 | 7 | MessageContent, |
| 11 | 8 | MessagePart, |
| 12 | 9 | RangeInFile, |
| 13 | - SlashCommandDescription, | |
| 14 | - TextMessagePart, | |
| 10 | + SlashCommandDescWithSource, | |
| 15 | 11 | } from "core"; |
| 16 | -import { ctxItemToRifWithContents } from "core/commands/util"; | |
| 17 | -import { renderChatMessage, stripImages } from "core/util/messageContent"; | |
| 18 | -import { getUriFileExtension } from "core/util/uri"; | |
| 12 | +import { stripImages } from "core/util/messageContent"; | |
| 19 | 13 | import { IIdeMessenger } from "../../../../context/IdeMessenger"; |
| 20 | 14 | import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; |
| 21 | -import { CodeBlock, Mention, PromptBlock } from "../extensions"; | |
| 22 | - | |
| 23 | -interface MentionAttrs { | |
| 24 | - label: string; | |
| 25 | - id: string; | |
| 26 | - itemType?: string; | |
| 27 | - query?: string; | |
| 28 | -} | |
| 15 | +import { processEditorContent } from "./processEditorContent"; | |
| 16 | +import { renderSlashCommandPrompt } from "./renderSlashCommand"; | |
| 17 | +import { GetContextRequest } from "./types"; | |
| 29 | 18 | |
| 30 | 19 | interface ResolveEditorContentInput { |
| 31 | 20 | editorState: JSONContent; |
| 32 | 21 | modifiers: InputModifiers; |
| 33 | 22 | ideMessenger: IIdeMessenger; |
| 34 | 23 | defaultContextProviders: DefaultContextProvider[]; |
| 35 | - availableSlashCommands: SlashCommandDescription[]; | |
| 24 | + availableSlashCommands: SlashCommandDescWithSource[]; | |
| 36 | 25 | dispatch: Dispatch; |
| 37 | 26 | } |
| 38 | 27 | |
| 39 | -type ResolveEditorContentOutput = [ | |
| 40 | - ContextItemWithId[], | |
| 41 | - RangeInFile[], | |
| 42 | - MessageContent, | |
| 43 | - ( | |
| 28 | +interface ResolveEditorContentOutput { | |
| 29 | + selectedContextItems: ContextItemWithId[]; | |
| 30 | + selectedCode: RangeInFile[]; | |
| 31 | + content: MessageContent; | |
| 32 | + legacyCommandWithInput: | |
| 44 | 33 | | { |
| 45 | - command: SlashCommandDescription; | |
| 34 | + command: SlashCommandDescWithSource; | |
| 46 | 35 | input: string; |
| 47 | 36 | } |
| 48 | - | undefined | |
| 49 | - ), | |
| 50 | -]; | |
| 37 | + | undefined; | |
| 38 | +} | |
| 51 | 39 | |
| 52 | 40 | /** |
| 53 | 41 | * This function converts the input from the editor to a string, resolving any context items |
| @@ -61,26 +49,43 @@ | ||
| 61 | 49 | availableSlashCommands, |
| 62 | 50 | dispatch, |
| 63 | 51 | }: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> { |
| 64 | - const { parts, contextItemAttrs, selectedCode, slashCommandName } = | |
| 65 | - processEditorContent(editorState); | |
| 66 | - | |
| 67 | - const slashCommandWithInput = processSlashCommand( | |
| 52 | + const { | |
| 53 | + parts, | |
| 54 | + contextRequests: editorContextRequests, | |
| 55 | + selectedCode, | |
| 56 | + slashCommandName, | |
| 57 | + } = processEditorContent(editorState); | |
| 58 | + | |
| 59 | + const { | |
| 60 | + slashedParts, | |
| 61 | + contextRequests: slashContextRequests, | |
| 62 | + legacyCommandWithInput, | |
| 63 | + } = await renderSlashCommandPrompt( | |
| 64 | + ideMessenger, | |
| 68 | 65 | slashCommandName, |
| 69 | - availableSlashCommands, | |
| 70 | 66 | parts, |
| 67 | + availableSlashCommands, | |
| 68 | + selectedCode, | |
| 71 | 69 | ); |
| 72 | 70 | |
| 73 | - const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput; | |
| 71 | + const contextRequests = [...editorContextRequests, ...slashContextRequests]; | |
| 72 | + | |
| 73 | + const shouldGatherContext = | |
| 74 | + defaultContextProviders.length > 0 || | |
| 75 | + modifiers.useCodebase || | |
| 76 | + !modifiers.noContext || | |
| 77 | + contextRequests.length > 0; | |
| 78 | + | |
| 74 | 79 | if (shouldGatherContext) { |
| 75 | 80 | dispatch(setIsGatheringContext(true)); |
| 76 | 81 | } |
| 77 | 82 | |
| 78 | - const contextItems = await gatherContextItems({ | |
| 79 | - contextItemAttrs, | |
| 83 | + const selectedContextItems = await gatherContextItems({ | |
| 84 | + contextRequests, | |
| 80 | 85 | modifiers, |
| 81 | 86 | ideMessenger, |
| 82 | 87 | defaultContextProviders, |
| 83 | - parts, | |
| 88 | + parts: slashedParts, | |
| 84 | 89 | selectedCode, |
| 85 | 90 | }); |
| 86 | 91 | |
| @@ -88,140 +93,11 @@ | ||
| 88 | 93 | dispatch(setIsGatheringContext(false)); |
| 89 | 94 | } |
| 90 | 95 | |
| 91 | - return [contextItems, selectedCode, parts, slashCommandWithInput]; | |
| 92 | -} | |
| 93 | - | |
| 94 | -/** | |
| 95 | - * Processes editor content and extracts parts, context items, code, and slash commands | |
| 96 | - */ | |
| 97 | -function processEditorContent(editorState: JSONContent) { | |
| 98 | - const contextItemAttrs: MentionAttrs[] = []; | |
| 99 | - const selectedCode: RangeInFile[] = []; | |
| 100 | - let slashCommandName: string | undefined; | |
| 101 | - | |
| 102 | - const parts = (editorState?.content || []).reduce<MessagePart[]>( | |
| 103 | - (parts, p) => { | |
| 104 | - switch (p.type) { | |
| 105 | - case PromptBlock.name: { | |
| 106 | - slashCommandName = resvolePromptBlock(p); | |
| 107 | - } | |
| 108 | - | |
| 109 | - case Paragraph.name: { | |
| 110 | - const [text, ctxItems] = resolveParagraph(p); | |
| 111 | - | |
| 112 | - contextItemAttrs.push(...ctxItems); | |
| 113 | - | |
| 114 | - if (!text) return parts; | |
| 115 | - | |
| 116 | - // Merge with previous text part if possible | |
| 117 | - if (parts[parts.length - 1]?.type === "text") { | |
| 118 | - (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; | |
| 119 | - return parts; | |
| 120 | - } | |
| 121 | - | |
| 122 | - return [...parts, { type: "text", text }]; | |
| 123 | - } | |
| 124 | - | |
| 125 | - case CodeBlock.name: { | |
| 126 | - if (!p.attrs?.item) { | |
| 127 | - console.warn("codeBlock has no item attribute"); | |
| 128 | - return parts; | |
| 129 | - } | |
| 130 | - | |
| 131 | - const contextItem = p.attrs.item as ContextItemWithId; | |
| 132 | - const rif = ctxItemToRifWithContents(contextItem, true); | |
| 133 | - selectedCode.push(rif); | |
| 134 | - | |
| 135 | - // If editing, only include in selectedCode | |
| 136 | - if (contextItem.editing) { | |
| 137 | - return parts; | |
| 138 | - } | |
| 139 | - | |
| 140 | - const fileExtension = getUriFileExtension(rif.filepath); | |
| 141 | - const codeText = [ | |
| 142 | - "\n\n```", | |
| 143 | - fileExtension, | |
| 144 | - " ", | |
| 145 | - contextItem.description, | |
| 146 | - "\n", | |
| 147 | - contextItem.content, | |
| 148 | - "\n```", | |
| 149 | - ].join(""); | |
| 150 | - | |
| 151 | - if (parts[parts.length - 1]?.type === "text") { | |
| 152 | - (parts[parts.length - 1] as TextMessagePart).text += | |
| 153 | - "\n" + codeText; | |
| 154 | - return parts; | |
| 155 | - } | |
| 156 | - | |
| 157 | - return [...parts, { type: "text", text: codeText }]; | |
| 158 | - } | |
| 159 | - | |
| 160 | - case Image.name: { | |
| 161 | - return [ | |
| 162 | - ...parts, | |
| 163 | - { | |
| 164 | - type: "imageUrl", | |
| 165 | - imageUrl: { url: p.attrs?.src }, | |
| 166 | - }, | |
| 167 | - ]; | |
| 168 | - } | |
| 169 | - | |
| 170 | - default: { | |
| 171 | - console.warn("Unexpected content type", p.type); | |
| 172 | - return parts; | |
| 173 | - } | |
| 174 | - } | |
| 175 | - }, | |
| 176 | - [], | |
| 177 | - ); | |
| 178 | - | |
| 179 | - return { parts, contextItemAttrs, selectedCode, slashCommandName }; | |
| 180 | -} | |
| 181 | - | |
| 182 | -/** | |
| 183 | - * Processes slash commands and prepares the command with input | |
| 184 | - */ | |
| 185 | -function processSlashCommand( | |
| 186 | - slashCommandName: string | undefined, | |
| 187 | - availableSlashCommands: SlashCommandDescription[], | |
| 188 | - parts: MessagePart[], | |
| 189 | -): { command: SlashCommandDescription; input: string } | undefined { | |
| 190 | - if (!slashCommandName) return; | |
| 191 | - | |
| 192 | - const command = availableSlashCommands.find( | |
| 193 | - (c) => c.name === slashCommandName, | |
| 194 | - ); | |
| 195 | - | |
| 196 | - if (!command) return; | |
| 197 | - | |
| 198 | - const lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); | |
| 199 | - const lastTextPart = parts[lastTextIndex] as TextMessagePart; | |
| 200 | - | |
| 201 | - const originalPrompt = command.prompt ? " " + command.prompt : ""; | |
| 202 | - | |
| 203 | - let input: string; | |
| 204 | - | |
| 205 | - /** | |
| 206 | - * Although we no longer render slash command <span /> tags from the editor, | |
| 207 | - * we are inserting a slash command style text back into the text here. | |
| 208 | - * This is a a hack, but there's a number of assumptions in `core` that there | |
| 209 | - * is slash command text at the beginning of the text in order to process slash commands. | |
| 210 | - */ | |
| 211 | - if (lastTextPart) { | |
| 212 | - input = renderChatMessage({ | |
| 213 | - role: "user", | |
| 214 | - content: lastTextPart.text, | |
| 215 | - }).trimStart(); | |
| 216 | - lastTextPart.text = `/${command.name}${originalPrompt} ${lastTextPart.text}`; | |
| 217 | - } else { | |
| 218 | - input = ""; | |
| 219 | - parts.push({ type: "text", text: `/${command.name}${originalPrompt}` }); | |
| 220 | - } | |
| 221 | - | |
| 222 | 96 | return { |
| 223 | - command, | |
| 224 | - input, | |
| 97 | + selectedContextItems, | |
| 98 | + selectedCode, | |
| 99 | + content: slashedParts, | |
| 100 | + legacyCommandWithInput, | |
| 225 | 101 | }; |
| 226 | 102 | } |
| 227 | 103 | |
| @@ -229,26 +105,44 @@ | ||
| 229 | 105 | * Gathers context items from various sources |
| 230 | 106 | */ |
| 231 | 107 | async function gatherContextItems({ |
| 232 | - contextItemAttrs, | |
| 108 | + contextRequests, | |
| 233 | 109 | modifiers, |
| 234 | 110 | ideMessenger, |
| 235 | 111 | defaultContextProviders, |
| 236 | 112 | parts, |
| 237 | 113 | selectedCode, |
| 238 | 114 | }: { |
| 239 | - contextItemAttrs: MentionAttrs[]; | |
| 115 | + contextRequests: GetContextRequest[]; | |
| 240 | 116 | modifiers: InputModifiers; |
| 241 | 117 | ideMessenger: IIdeMessenger; |
| 242 | 118 | defaultContextProviders: DefaultContextProvider[]; |
| 243 | 119 | parts: MessagePart[]; |
| 244 | 120 | selectedCode: RangeInFile[]; |
| 245 | 121 | }): Promise<ContextItemWithId[]> { |
| 122 | + const defaultRequests: GetContextRequest[] = defaultContextProviders.map( | |
| 123 | + (def) => ({ | |
| 124 | + provider: def.name, | |
| 125 | + query: def.query, | |
| 126 | + }), | |
| 127 | + ); | |
| 128 | + const withDefaults = [...contextRequests, ...defaultRequests]; | |
| 129 | + const deduplicatedInputs = withDefaults.reduce<GetContextRequest[]>( | |
| 130 | + (acc, item) => { | |
| 131 | + if ( | |
| 132 | + !acc.some((i) => i.provider === item.provider && i.query === item.query) | |
| 133 | + ) { | |
| 134 | + acc.push(item); | |
| 135 | + } | |
| 136 | + return acc; | |
| 137 | + }, | |
| 138 | + [], | |
| 139 | + ); | |
| 246 | 140 | let contextItems: ContextItemWithId[] = []; |
| 247 | 141 | |
| 248 | 142 | // Process context item attributes |
| 249 | - for (const item of contextItemAttrs) { | |
| 143 | + for (const item of deduplicatedInputs) { | |
| 250 | 144 | const result = await ideMessenger.request("context/getContextItems", { |
| 251 | - name: item.itemType === "contextProvider" ? item.id : item.itemType!, | |
| 145 | + name: item.provider, | |
| 252 | 146 | query: item.query ?? "", |
| 253 | 147 | fullInput: stripImages(parts), |
| 254 | 148 | selectedCode, |
| @@ -259,7 +153,10 @@ | ||
| 259 | 153 | } |
| 260 | 154 | |
| 261 | 155 | // cmd+enter to use codebase |
| 262 | - if (modifiers.useCodebase) { | |
| 156 | + if ( | |
| 157 | + modifiers.useCodebase && | |
| 158 | + !deduplicatedInputs.some((item) => item.provider === "codebase") | |
| 159 | + ) { | |
| 263 | 160 | const result = await ideMessenger.request("context/getContextItems", { |
| 264 | 161 | name: "codebase", |
| 265 | 162 | query: "", |
| @@ -272,62 +169,51 @@ | ||
| 272 | 169 | } |
| 273 | 170 | } |
| 274 | 171 | |
| 275 | - // Include default context providers | |
| 276 | - const defaultContextItems = await Promise.all( | |
| 277 | - defaultContextProviders.map(async (provider) => { | |
| 278 | - const result = await ideMessenger.request("context/getContextItems", { | |
| 279 | - name: provider.name, | |
| 280 | - query: provider.query ?? "", | |
| 281 | - fullInput: stripImages(parts), | |
| 282 | - selectedCode, | |
| 283 | - }); | |
| 284 | - if (result.status === "success") { | |
| 285 | - return result.content; | |
| 286 | - } else { | |
| 287 | - return []; | |
| 172 | + // noContext modifier adds currently open file if it's not already present | |
| 173 | + if ( | |
| 174 | + !modifiers.noContext && | |
| 175 | + !deduplicatedInputs.some((item) => item.provider === "currentFile") | |
| 176 | + ) { | |
| 177 | + const currentFileResponse = await ideMessenger.request( | |
| 178 | + "context/getContextItems", | |
| 179 | + { | |
| 180 | + name: "currentFile", | |
| 181 | + query: "non-mention-usage", | |
| 182 | + fullInput: "", | |
| 183 | + selectedCode: [], | |
| 184 | + }, | |
| 185 | + ); | |
| 186 | + if (currentFileResponse.status === "success") { | |
| 187 | + const currentFile = currentFileResponse.content[0]; | |
| 188 | + if (currentFile.uri?.value) { | |
| 189 | + currentFile.id = { | |
| 190 | + providerTitle: "file", | |
| 191 | + itemId: currentFile.uri.value, | |
| 192 | + }; | |
| 193 | + contextItems.unshift(currentFile); | |
| 288 | 194 | } |
| 289 | - }), | |
| 290 | - ); | |
| 291 | - contextItems.push(...defaultContextItems.flat()); | |
| 292 | - | |
| 293 | - return contextItems; | |
| 294 | -} | |
| 295 | - | |
| 296 | -function findLastIndex<T>( | |
| 297 | - array: T[], | |
| 298 | - predicate: (value: T, index: number, obj: T[]) => boolean, | |
| 299 | -): number { | |
| 300 | - for (let i = array.length - 1; i >= 0; i--) { | |
| 301 | - if (predicate(array[i], i, array)) { | |
| 302 | - return i; | |
| 303 | 195 | } |
| 304 | 196 | } |
| 305 | - return -1; // if no element satisfies the predicate | |
| 306 | -} | |
| 307 | - | |
| 308 | -function resvolePromptBlock(p: JSONContent): string | undefined { | |
| 309 | - return p.attrs?.item.name; | |
| 310 | -} | |
| 311 | 197 | |
| 312 | -function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] { | |
| 313 | - const contextItems: MentionAttrs[] = []; | |
| 314 | - | |
| 315 | - const text = (p.content || []) | |
| 316 | - .map((child) => { | |
| 317 | - switch (child.type) { | |
| 318 | - case Text.name: | |
| 319 | - return child.text; | |
| 320 | - case Mention.name: | |
| 321 | - contextItems.push(child.attrs as MentionAttrs); | |
| 322 | - return child.attrs?.renderInlineAs ?? child.attrs?.label; | |
| 323 | - | |
| 324 | - default: | |
| 325 | - console.warn("Unexpected child type", child.type); | |
| 326 | - return ""; | |
| 198 | + // Deduplicates based on either providerTitle + itemId or uri type + value | |
| 199 | + const deduplicatedOutputs = contextItems.reduce<ContextItemWithId[]>( | |
| 200 | + (acc, item) => { | |
| 201 | + if ( | |
| 202 | + !acc.some( | |
| 203 | + (i) => | |
| 204 | + (i.id.providerTitle === item.id.providerTitle && | |
| 205 | + i.id.itemId === item.id.itemId) || | |
| 206 | + (i.uri && | |
| 207 | + item.uri && | |
| 208 | + i.uri.type === item.uri.type && | |
| 209 | + i.uri.value === item.uri.value), | |
| 210 | + ) | |
| 211 | + ) { | |
| 212 | + acc.push(item); | |
| 327 | 213 | } |
| 328 | - }) | |
| 329 | - .join("") | |
| 330 | - .trimStart(); | |
| 331 | - | |
| 332 | - return [text, contextItems]; | |
| 214 | + return acc; | |
| 215 | + }, | |
| 216 | + [], | |
| 217 | + ); | |
| 218 | + return deduplicatedOutputs; | |
| 333 | 219 | } |
added gui/src/components/mainInput/TipTapEditor/utils/types.ts +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +export interface GetContextRequest { | |
| 2 | + provider: string; | |
| 3 | + query?: string; | |
| 4 | +} |
modified gui/src/context/MockIdeMessenger.ts +23 −1
| @@ -18,6 +18,14 @@ | ||
| 18 | 18 | [K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1]; |
| 19 | 19 | }>; |
| 20 | 20 | |
| 21 | +export type MockResponseHandler<T extends keyof FromWebviewProtocol> = ( | |
| 22 | + input: FromWebviewProtocol[T][0], | |
| 23 | +) => Promise<FromWebviewProtocol[T][1]>; | |
| 24 | + | |
| 25 | +type MockResponseHandlers = Partial<{ | |
| 26 | + [K in keyof FromWebviewProtocol]: MockResponseHandler<K>; | |
| 27 | +}>; | |
| 28 | + | |
| 21 | 29 | const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { |
| 22 | 30 | fileExists: true, |
| 23 | 31 | getCurrentFile: { |
| @@ -66,6 +74,7 @@ | ||
| 66 | 74 | "chatDescriber/describe": "Session summary", |
| 67 | 75 | applyToFile: undefined, |
| 68 | 76 | acceptDiff: undefined, |
| 77 | + readFile: "File contents", | |
| 69 | 78 | }; |
| 70 | 79 | |
| 71 | 80 | const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [ |
| @@ -119,6 +128,7 @@ | ||
| 119 | 128 | } |
| 120 | 129 | |
| 121 | 130 | responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES }; |
| 131 | + responseHandlers: MockResponseHandlers = {}; | |
| 122 | 132 | chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE; |
| 123 | 133 | chatStreamDelay: number = 0; |
| 124 | 134 | setChatResponseText(text: string): void { |
| @@ -164,6 +174,14 @@ | ||
| 164 | 174 | messageType: T, |
| 165 | 175 | data: FromWebviewProtocol[T][0], |
| 166 | 176 | ): Promise<WebviewSingleProtocolMessage<T>> { |
| 177 | + if (this.responseHandlers[messageType]) { | |
| 178 | + const content = await this.responseHandlers[messageType](data); | |
| 179 | + return { | |
| 180 | + status: "success", | |
| 181 | + content, | |
| 182 | + done: true, | |
| 183 | + }; | |
| 184 | + } | |
| 167 | 185 | if (messageType in this.responses) { |
| 168 | 186 | const content = this.responses[messageType]; |
| 169 | 187 | return { |
| @@ -173,7 +191,10 @@ | ||
| 173 | 191 | }; |
| 174 | 192 | } |
| 175 | 193 | console.error(messageType); |
| 176 | - throw new Error("MockIdeMessenger: No response defined for " + messageType); | |
| 194 | + throw new Error( | |
| 195 | + "MockIdeMessenger: No response handler or response defined for " + | |
| 196 | + messageType, | |
| 197 | + ); | |
| 177 | 198 | } |
| 178 | 199 | |
| 179 | 200 | respond<T extends keyof ToWebviewProtocol>( |
| @@ -195,6 +216,7 @@ | ||
| 195 | 216 | |
| 196 | 217 | resetMocks(): void { |
| 197 | 218 | this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES }; |
| 219 | + this.responseHandlers = {}; | |
| 198 | 220 | this.chatResponse = DEFAULT_CHAT_RESPONSE; |
| 199 | 221 | this.chatStreamDelay = 0; |
| 200 | 222 | } |
modified gui/src/hooks/useBookmarkedSlashCommands.ts +2 −2
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { SlashCommandDescription } from "core"; | |
| 1 | +import { SlashCommandDescWithSource } from "core"; | |
| 2 | 2 | import { usePostHog } from "posthog-js/react"; |
| 3 | 3 | |
| 4 | 4 | import { useAppDispatch, useAppSelector } from "../redux/hooks"; |
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | return bookmarkedCommands.includes(commandName); |
| 18 | 18 | }; |
| 19 | 19 | |
| 20 | - const toggleBookmark = (command: SlashCommandDescription) => { | |
| 20 | + const toggleBookmark = (command: SlashCommandDescWithSource) => { | |
| 21 | 21 | const isBookmarked = isCommandBookmarked(command.name); |
| 22 | 22 | |
| 23 | 23 | posthog.capture("toggle_bookmarked_slash_command", { |
modified gui/src/redux/slices/configSlice.ts +1 −10
| @@ -10,16 +10,7 @@ | ||
| 10 | 10 | }; |
| 11 | 11 | |
| 12 | 12 | export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { |
| 13 | - slashCommands: [ | |
| 14 | - { | |
| 15 | - name: "share", | |
| 16 | - description: "Export the current chat session to markdown", | |
| 17 | - }, | |
| 18 | - { | |
| 19 | - name: "cmd", | |
| 20 | - description: "Generate a shell command", | |
| 21 | - }, | |
| 22 | - ], | |
| 13 | + slashCommands: [], | |
| 23 | 14 | contextProviders: [], |
| 24 | 15 | tools: [], |
| 25 | 16 | mcpServerStatuses: [], |
modified gui/src/redux/slices/profilesSlice.ts +2 −2
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { createSlice, PayloadAction } from "@reduxjs/toolkit"; |
| 2 | -import { SlashCommandDescription } from "core"; | |
| 2 | +import { SlashCommandDescWithSource } from "core"; | |
| 3 | 3 | import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager"; |
| 4 | 4 | |
| 5 | 5 | const DEFAULT_SLASH_COMMANDS_BOOKMARKS_COUNT = 5; |
| @@ -81,7 +81,7 @@ | ||
| 81 | 81 | state, |
| 82 | 82 | action: PayloadAction<{ |
| 83 | 83 | profileId: string; |
| 84 | - defaultSlashCommands?: SlashCommandDescription[]; | |
| 84 | + defaultSlashCommands?: SlashCommandDescWithSource[]; | |
| 85 | 85 | }>, |
| 86 | 86 | ) => { |
| 87 | 87 | const { profileId, defaultSlashCommands = [] } = action.payload; |
modified gui/src/redux/thunks/edit.ts +14 −15
| @@ -34,27 +34,26 @@ | ||
| 34 | 34 | }, |
| 35 | 35 | ThunkApiType |
| 36 | 36 | >( |
| 37 | - "chat/streamResponse", | |
| 37 | + "edit/streamResponse", | |
| 38 | 38 | async ({ editorState, codeToEdit }, { dispatch, extra }) => { |
| 39 | 39 | await dispatch( |
| 40 | 40 | streamThunkWrapper(async () => { |
| 41 | 41 | dispatch(setActive()); |
| 42 | - const [contextItems, __, userInstructions, _] = | |
| 43 | - await resolveEditorContent({ | |
| 44 | - editorState, | |
| 45 | - modifiers: { | |
| 46 | - noContext: true, | |
| 47 | - useCodebase: false, | |
| 48 | - }, | |
| 49 | - ideMessenger: extra.ideMessenger, | |
| 50 | - defaultContextProviders: [], | |
| 51 | - availableSlashCommands: [], | |
| 52 | - dispatch, | |
| 53 | - }); | |
| 42 | + const { selectedContextItems, content } = await resolveEditorContent({ | |
| 43 | + editorState, | |
| 44 | + modifiers: { | |
| 45 | + noContext: true, | |
| 46 | + useCodebase: false, | |
| 47 | + }, | |
| 48 | + ideMessenger: extra.ideMessenger, | |
| 49 | + defaultContextProviders: [], | |
| 50 | + availableSlashCommands: [], | |
| 51 | + dispatch, | |
| 52 | + }); | |
| 54 | 53 | |
| 55 | 54 | const prompt = [ |
| 56 | - ...contextItems.map((item) => item.content), | |
| 57 | - stripImages(userInstructions), | |
| 55 | + ...selectedContextItems.map((item) => item.content), | |
| 56 | + stripImages(content), | |
| 58 | 57 | ].join("\n\n"); |
| 59 | 58 | |
| 60 | 59 | const response = await extra.ideMessenger.request("edit/sendPrompt", { |
deleted gui/src/redux/thunks/gatherContext.ts +0 −124
| @@ -1,124 +0,0 @@ | ||
| 1 | -import { createAsyncThunk } from "@reduxjs/toolkit"; | |
| 2 | -import { JSONContent } from "@tiptap/core"; | |
| 3 | -import { | |
| 4 | - ContextItemWithId, | |
| 5 | - InputModifiers, | |
| 6 | - MessageContent, | |
| 7 | - RangeInFile, | |
| 8 | - SlashCommandDescription, | |
| 9 | -} from "core"; | |
| 10 | -import * as URI from "uri-js"; | |
| 11 | -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; | |
| 12 | -import { selectSelectedChatModel } from "../slices/configSlice"; | |
| 13 | -import { ThunkApiType } from "../store"; | |
| 14 | - | |
| 15 | -export const gatherContext = createAsyncThunk< | |
| 16 | - { | |
| 17 | - selectedContextItems: ContextItemWithId[]; | |
| 18 | - selectedCode: RangeInFile[]; | |
| 19 | - content: MessageContent; | |
| 20 | - slashCommandWithInput: | |
| 21 | - | { | |
| 22 | - command: SlashCommandDescription; | |
| 23 | - input: string; | |
| 24 | - } | |
| 25 | - | undefined; | |
| 26 | - }, | |
| 27 | - { | |
| 28 | - editorState: JSONContent; | |
| 29 | - modifiers: InputModifiers; | |
| 30 | - promptPreamble?: string; | |
| 31 | - }, | |
| 32 | - ThunkApiType | |
| 33 | ->( | |
| 34 | - "chat/gatherContext", | |
| 35 | - async ( | |
| 36 | - { modifiers, editorState, promptPreamble }, | |
| 37 | - { dispatch, extra, getState }, | |
| 38 | - ) => { | |
| 39 | - const state = getState(); | |
| 40 | - const selectedChatModel = selectSelectedChatModel(state); | |
| 41 | - | |
| 42 | - const defaultContextProviders = | |
| 43 | - state.config.config.experimental?.defaultContext ?? []; | |
| 44 | - | |
| 45 | - if (!selectedChatModel) { | |
| 46 | - console.error( | |
| 47 | - "gatherContext thunk: Cannot gather context, no model selected", | |
| 48 | - ); | |
| 49 | - throw new Error("No chat model selected"); | |
| 50 | - } | |
| 51 | - | |
| 52 | - // Resolve context providers and construct new history | |
| 53 | - let [selectedContextItems, selectedCode, content, slashCommandWithInput] = | |
| 54 | - await resolveEditorContent({ | |
| 55 | - editorState, | |
| 56 | - modifiers, | |
| 57 | - ideMessenger: extra.ideMessenger, | |
| 58 | - defaultContextProviders, | |
| 59 | - availableSlashCommands: state.config.config.slashCommands, | |
| 60 | - dispatch, | |
| 61 | - }); | |
| 62 | - | |
| 63 | - // Automatically use currently open file | |
| 64 | - if (!modifiers.noContext) { | |
| 65 | - const usingFreeTrial = false; // TODO no longer tracking free trial count, need to hook up to hub | |
| 66 | - | |
| 67 | - const currentFileResponse = await extra.ideMessenger.request( | |
| 68 | - "context/getContextItems", | |
| 69 | - { | |
| 70 | - name: "currentFile", | |
| 71 | - query: "non-mention-usage", | |
| 72 | - fullInput: "", | |
| 73 | - selectedCode: [], | |
| 74 | - }, | |
| 75 | - ); | |
| 76 | - if (currentFileResponse.status === "success") { | |
| 77 | - const items = currentFileResponse.content; | |
| 78 | - if (items.length > 0) { | |
| 79 | - const currentFile = items[0]; | |
| 80 | - const uri = currentFile.uri?.value; | |
| 81 | - | |
| 82 | - // don't add the file if it's already in the context items | |
| 83 | - if ( | |
| 84 | - uri && | |
| 85 | - !selectedContextItems.find( | |
| 86 | - (item) => item.uri?.value && URI.equal(item.uri.value, uri), | |
| 87 | - ) | |
| 88 | - ) { | |
| 89 | - // Limit to 1000 lines if using free trial | |
| 90 | - if (usingFreeTrial) { | |
| 91 | - currentFile.content = currentFile.content | |
| 92 | - .split("\n") | |
| 93 | - .slice(0, 1000) | |
| 94 | - .join("\n"); | |
| 95 | - if (!currentFile.content.endsWith("```")) { | |
| 96 | - currentFile.content += "\n```"; | |
| 97 | - } | |
| 98 | - } | |
| 99 | - currentFile.id = { | |
| 100 | - providerTitle: "file", | |
| 101 | - itemId: uri, | |
| 102 | - }; | |
| 103 | - selectedContextItems.unshift(currentFile); | |
| 104 | - } | |
| 105 | - } | |
| 106 | - } | |
| 107 | - } | |
| 108 | - | |
| 109 | - if (promptPreamble) { | |
| 110 | - if (typeof content === "string") { | |
| 111 | - content = promptPreamble + content; | |
| 112 | - } else if (content[0].type === "text") { | |
| 113 | - content[0].text = promptPreamble + content[0].text; | |
| 114 | - } | |
| 115 | - } | |
| 116 | - | |
| 117 | - return { | |
| 118 | - selectedContextItems, | |
| 119 | - selectedCode, | |
| 120 | - content, | |
| 121 | - slashCommandWithInput, | |
| 122 | - }; | |
| 123 | - }, | |
| 124 | -); |
modified gui/src/redux/thunks/streamResponse.ts +27 −20
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; |
| 6 | 6 | import posthog from "posthog-js"; |
| 7 | 7 | import { v4 as uuidv4 } from "uuid"; |
| 8 | +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; | |
| 8 | 9 | import { getBaseSystemMessage } from "../../util"; |
| 9 | 10 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 10 | 11 | import { |
| @@ -13,7 +14,6 @@ | ||
| 13 | 14 | updateHistoryItemAtIndex, |
| 14 | 15 | } from "../slices/sessionSlice"; |
| 15 | 16 | import { ThunkApiType } from "../store"; |
| 16 | -import { gatherContext } from "./gatherContext"; | |
| 17 | 17 | import { resetStateForNewMessage } from "./resetStateForNewMessage"; |
| 18 | 18 | import { streamNormalInput } from "./streamNormalInput"; |
| 19 | 19 | import { streamThunkWrapper } from "./streamThunkWrapper"; |
| @@ -25,15 +25,11 @@ | ||
| 25 | 25 | editorState: JSONContent; |
| 26 | 26 | modifiers: InputModifiers; |
| 27 | 27 | index?: number; |
| 28 | - promptPreamble?: string; | |
| 29 | 28 | }, |
| 30 | 29 | ThunkApiType |
| 31 | 30 | >( |
| 32 | 31 | "chat/streamResponse", |
| 33 | - async ( | |
| 34 | - { editorState, modifiers, index, promptPreamble }, | |
| 35 | - { dispatch, extra, getState }, | |
| 36 | - ) => { | |
| 32 | + async ({ editorState, modifiers, index }, { dispatch, extra, getState }) => { | |
| 37 | 33 | await dispatch( |
| 38 | 34 | streamThunkWrapper(async () => { |
| 39 | 35 | const state = getState(); |
| @@ -49,19 +45,30 @@ | ||
| 49 | 45 | ); |
| 50 | 46 | resetStateForNewMessage(); |
| 51 | 47 | |
| 52 | - const result = await dispatch( | |
| 53 | - gatherContext({ | |
| 54 | - editorState, | |
| 55 | - modifiers, | |
| 56 | - promptPreamble, | |
| 57 | - }), | |
| 58 | - ); | |
| 48 | + const defaultContextProviders = | |
| 49 | + state.config.config.experimental?.defaultContext ?? []; | |
| 50 | + | |
| 51 | + if (!selectedChatModel) { | |
| 52 | + console.error( | |
| 53 | + "gatherContext thunk: Cannot gather context, no model selected", | |
| 54 | + ); | |
| 55 | + throw new Error("No chat model selected"); | |
| 56 | + } | |
| 57 | + | |
| 58 | + // Resolve context providers and construct new history | |
| 59 | 59 | const { |
| 60 | 60 | selectedContextItems, |
| 61 | 61 | selectedCode, |
| 62 | 62 | content, |
| 63 | - slashCommandWithInput, | |
| 64 | - } = unwrapResult(result); | |
| 63 | + legacyCommandWithInput, | |
| 64 | + } = await resolveEditorContent({ | |
| 65 | + editorState, | |
| 66 | + modifiers, | |
| 67 | + ideMessenger: extra.ideMessenger, | |
| 68 | + defaultContextProviders, | |
| 69 | + availableSlashCommands: state.config.config.slashCommands, | |
| 70 | + dispatch, | |
| 71 | + }); | |
| 65 | 72 | |
| 66 | 73 | // symbols for both context items AND selected codeblocks |
| 67 | 74 | const filesForSymbols = [ |
| @@ -133,9 +140,9 @@ | ||
| 133 | 140 | }); |
| 134 | 141 | posthog.capture("userInput", {}); |
| 135 | 142 | |
| 136 | - if (slashCommandWithInput) { | |
| 143 | + if (legacyCommandWithInput) { | |
| 137 | 144 | posthog.capture("step run", { |
| 138 | - step_name: slashCommandWithInput.command.name, | |
| 145 | + step_name: legacyCommandWithInput.command.name, | |
| 139 | 146 | params: {}, |
| 140 | 147 | }); |
| 141 | 148 | } |
| @@ -144,12 +151,12 @@ | ||
| 144 | 151 | await dispatch( |
| 145 | 152 | streamNormalInput({ |
| 146 | 153 | messages, |
| 147 | - legacySlashCommandData: slashCommandWithInput | |
| 154 | + legacySlashCommandData: legacyCommandWithInput | |
| 148 | 155 | ? { |
| 149 | - command: slashCommandWithInput.command, | |
| 156 | + command: legacyCommandWithInput.command, | |
| 150 | 157 | contextItems: selectedContextItems, |
| 151 | 158 | historyIndex: inputIndex, |
| 152 | - input: slashCommandWithInput.input, | |
| 159 | + input: legacyCommandWithInput.input, | |
| 153 | 160 | selectedCode, |
| 154 | 161 | } |
| 155 | 162 | : undefined, |
modified packages/openai-adapters/src/util/parseArgs.ts +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | errorId?: string, |
| 4 | 4 | ): Record<string, any> { |
| 5 | 5 | try { |
| 6 | - return JSON.parse(args ?? "{}"); | |
| 6 | + return JSON.parse(args?.trim() || "{}"); | |
| 7 | 7 | } catch (e) { |
| 8 | 8 | const identifier = errorId ? `Call: ${errorId}\nArgs:${args}\n` : ""; |
| 9 | 9 | console.error( |