diff --git a/core/commands/index.ts b/core/commands/index.ts index fd075c6ff..94b57c2b9 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,6 +1,6 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; import { stripImages } from "../llm/images"; -import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; +import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import SlashCommands from "./slash"; export function slashFromCustomCommand( diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index 472684a7e..544673901 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -1,8 +1,6 @@ import GenerateTerminalCommand from "./cmd"; -import CommentSlashCommand from "./comment"; import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; -import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; import MultiFileEditSlashCommand from "./multifileEdit"; import OnboardSlashCommand from "./onboard"; @@ -13,8 +11,6 @@ export default [ DraftIssueCommand, ShareSlashCommand, GenerateTerminalCommand, - EditSlashCommand, - CommentSlashCommand, HttpSlashCommand, CommitMessageCommand, ReviewMessageCommand, diff --git a/core/config/default.ts b/core/config/default.ts index 814552e75..54f601b53 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -67,14 +67,6 @@ export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [ ]; export const defaultSlashCommandsVscode: SlashCommandDescription[] = [ - { - name: "edit", - description: "Edit selected code", - }, - { - name: "comment", - description: "Write comments for the selected code", - }, { name: "share", description: "Export the current chat session to markdown", @@ -90,14 +82,6 @@ export const defaultSlashCommandsVscode: SlashCommandDescription[] = [ ]; export const defaultSlashCommandsJetBrains = [ - { - name: "edit", - description: "Edit selected code", - }, - { - name: "comment", - description: "Write comments for the selected code", - }, { name: "share", description: "Export the current chat session to markdown", diff --git a/core/config/load.ts b/core/config/load.ts index 2064dd61d..d9d020d2d 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,16 +1,9 @@ +import { execSync } from "child_process"; import * as JSONC from "comment-json"; import * as fs from "fs"; +import os from "os"; import path from "path"; import * as tar from "tar"; -import { - slashCommandFromDescription, - slashFromCustomCommand, -} from "../commands/index.js"; -import CustomContextProviderClass from "../context/providers/CustomContextProvider"; -import FileContextProvider from "../context/providers/FileContextProvider"; -import { contextProviderClassFromName } from "../context/providers/index"; -import { AllRerankers } from "../context/rerankers/index"; -import { LLMReranker } from "../context/rerankers/llm"; import { BrowserSerializedContinueConfig, Config, @@ -30,18 +23,25 @@ import { SerializedContinueConfig, SlashCommand, } from ".."; -import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider"; -import { allEmbeddingsProviders } from "../indexing/embeddings"; -import { BaseLLM } from "../llm"; -import CustomLLMClass from "../llm/llms/CustomLLM"; -import FreeTrial from "../llm/llms/FreeTrial"; -import { llmFromDescription } from "../llm/llms"; -import os from "os"; -import { execSync } from "child_process"; +import { + slashCommandFromDescription, + slashFromCustomCommand, +} from "../commands/index.js"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; -import { fetchwithRequestOptions } from "../util/fetchWithOptions"; +import CustomContextProviderClass from "../context/providers/CustomContextProvider"; +import FileContextProvider from "../context/providers/FileContextProvider"; +import { contextProviderClassFromName } from "../context/providers/index"; +import { AllRerankers } from "../context/rerankers/index"; +import { LLMReranker } from "../context/rerankers/llm"; +import { allEmbeddingsProviders } from "../indexing/embeddings"; +import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import { BaseLLM } from "../llm"; +import { llmFromDescription } from "../llm/llms"; +import CustomLLMClass from "../llm/llms/CustomLLM"; +import FreeTrial from "../llm/llms/FreeTrial"; import { copyOf } from "../util"; +import { fetchwithRequestOptions } from "../util/fetchWithOptions"; import mergeJson from "../util/merge"; import { DEFAULT_CONFIG_TS_CONTENTS, @@ -65,8 +65,9 @@ import { getPromptFiles, slashCommandFromPromptFile, } from "./promptFile.js"; -import { validateConfig, ConfigValidationError } from "./validation.js"; +import { ConfigValidationError, validateConfig } from "./validation.js"; +import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; import { GlobalContext } from "../util/GlobalContext"; export interface ConfigResult { @@ -187,6 +188,7 @@ async function serializedToIntermediateConfig( const promptFolder = initial.experimental?.promptPath; if (loadPromptFiles) { + // v1 prompt files let promptFiles: { path: string; content: string }[] = []; promptFiles = ( await Promise.all( @@ -238,6 +240,7 @@ async function intermediateToFinalConfig( uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, + loadPromptFiles: boolean = true, allowFreeTrial: boolean = true, ): Promise { // Auto-detect models @@ -389,6 +392,7 @@ async function intermediateToFinalConfig( const DEFAULT_CONTEXT_PROVIDERS = [ new FileContextProvider({}), new CodebaseContextProvider(codebaseContextParams), + ...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []), ]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 728090fcc..44646ec95 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,7 +4,7 @@ import * as YAML from "yaml"; import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; -import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; +import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import { getBasename } from "../util/index"; import { BaseContextProvider } from "../context"; diff --git a/core/context/providers/PromptFilesContextProvider.ts b/core/context/providers/PromptFilesContextProvider.ts new file mode 100644 index 000000000..bc9239f1d --- /dev/null +++ b/core/context/providers/PromptFilesContextProvider.ts @@ -0,0 +1,56 @@ +import { BaseContextProvider } from ".."; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../"; +import { getAllPromptFilesV2 } from "../../promptFiles/v2/getPromptFiles"; +import { parsePreamble } from "../../promptFiles/v2/parse"; +import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile"; + +class PromptFilesContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "prompt-files", + displayTitle: "Prompt Files", + description: ".prompt files", + type: "submenu", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const rawContent = await extras.ide.readFile(query); + const preamble = parsePreamble(query, rawContent); + const [contextItems, body] = await renderPromptFileV2(rawContent, extras); + return [ + ...contextItems, + { + content: body, + name: preamble.name, + description: preamble.description, + }, + ]; + } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const promptFiles = await getAllPromptFilesV2( + args.ide, + args.config.experimental?.promptPath, + ); + return promptFiles.map((file) => { + const preamble = parsePreamble(file.path, file.content); + return { + id: file.path, + title: preamble.name, + description: preamble.description, + }; + }); + } +} + +export default PromptFilesContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index fc56f6de9..ec1d7c6ad 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -4,6 +4,7 @@ import CodeContextProvider from "./CodeContextProvider"; import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; import CurrentFileContextProvider from "./CurrentFileContextProvider"; import DatabaseContextProvider from "./DatabaseContextProvider"; +import DebugLocalsProvider from "./DebugLocalsProvider"; import DiffContextProvider from "./DiffContextProvider"; import DiscordContextProvider from "./DiscordContextProvider"; import DocsContextProvider from "./DocsContextProvider"; @@ -15,7 +16,6 @@ import GoogleContextProvider from "./GoogleContextProvider"; import GreptileContextProvider from "./GreptileContextProvider"; import HttpContextProvider from "./HttpContextProvider"; import JiraIssuesContextProvider from "./JiraIssuesContextProvider/"; -import DebugLocalsProvider from "./DebugLocalsProvider"; import OSContextProvider from "./OSContextProvider"; import OpenFilesContextProvider from "./OpenFilesContextProvider"; import PostgresContextProvider from "./PostgresContextProvider"; diff --git a/core/core.ts b/core/core.ts index e57af155b..87eeb52da 100644 --- a/core/core.ts +++ b/core/core.ts @@ -10,7 +10,6 @@ import { setupLocalConfigAfterFreeTrial, setupQuickstartConfig, } from "./config/onboarding"; -import { createNewPromptFile } from "./config/promptFile"; import { addModel, addOpenAIKey, deleteModel } from "./config/util"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; @@ -21,6 +20,7 @@ import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; +import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext"; import { ChatDescriber } from "./util/chatDescriber"; @@ -248,11 +248,11 @@ export class Core { }); on("config/newPromptFile", async (msg) => { - void createNewPromptFile( + await createNewPromptFileV2( this.ide, (await this.config()).experimental?.promptPath, ); - void this.configHandler.reloadConfig(); + await this.configHandler.reloadConfig(); }); on("config/reload", (msg) => { diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 64882b09b..17ff45725 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -5,9 +5,10 @@ import { LLMOptions, ModelDescription, } from "../.."; -import { renderTemplatedString } from "../../promptFiles/renderTemplatedString"; +import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; +import Asksage from "./Asksage"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; import BedrockImport from "./BedrockImport"; @@ -40,11 +41,10 @@ import SageMaker from "./SageMaker"; import SambaNova from "./SambaNova"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; +import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import ContinueProxy from "./stubs/ContinueProxy"; -import VertexAI from "./VertexAI"; -import Asksage from "./Asksage"; import xAI from "./xAI"; const LLMs = [ @@ -86,7 +86,7 @@ const LLMs = [ Asksage, Nebius, VertexAI, - xAI + xAI, ]; export async function llmFromDescription( diff --git a/core/promptFiles/createNewPromptFile.ts b/core/promptFiles/v1/createNewPromptFile.ts similarity index 96% rename from core/promptFiles/createNewPromptFile.ts rename to core/promptFiles/v1/createNewPromptFile.ts index d686e0d72..e6386056c 100644 --- a/core/promptFiles/createNewPromptFile.ts +++ b/core/promptFiles/v1/createNewPromptFile.ts @@ -1,6 +1,6 @@ import path from "path"; -import { IDE } from ".."; -import { DEFAULT_PROMPTS_FOLDER } from "./"; +import { DEFAULT_PROMPTS_FOLDER } from "."; +import { IDE } from "../.."; const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file # It is used to define and reuse prompts within Continue diff --git a/core/promptFiles/getContextProviderHelpers.ts b/core/promptFiles/v1/getContextProviderHelpers.ts similarity index 100% rename from core/promptFiles/getContextProviderHelpers.ts rename to core/promptFiles/v1/getContextProviderHelpers.ts diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/v1/getPromptFiles.ts similarity index 86% rename from core/promptFiles/getPromptFiles.ts rename to core/promptFiles/v1/getPromptFiles.ts index 2ab9dc893..b9bb5d823 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/v1/getPromptFiles.ts @@ -1,5 +1,5 @@ -import { IDE } from ".."; -import { walkDir } from "../indexing/walkDir"; +import { IDE } from "../.."; +import { walkDir } from "../../indexing/walkDir"; export async function getPromptFiles( ide: IDE, diff --git a/core/promptFiles/handlebarUtils.ts b/core/promptFiles/v1/handlebarUtils.ts similarity index 100% rename from core/promptFiles/handlebarUtils.ts rename to core/promptFiles/v1/handlebarUtils.ts diff --git a/core/promptFiles/index.ts b/core/promptFiles/v1/index.ts similarity index 73% rename from core/promptFiles/index.ts rename to core/promptFiles/v1/index.ts index c3afdec76..2eed3a15d 100644 --- a/core/promptFiles/index.ts +++ b/core/promptFiles/v1/index.ts @@ -1,8 +1,7 @@ -import { IDE } from ".."; -import { getPromptFiles } from "./getPromptFiles"; import { createNewPromptFile } from "./createNewPromptFile"; +import { getPromptFiles } from "./getPromptFiles"; import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; -export { getPromptFiles, createNewPromptFile, slashCommandFromPromptFile }; +export { createNewPromptFile, getPromptFiles, slashCommandFromPromptFile }; diff --git a/core/promptFiles/renderTemplatedString.ts b/core/promptFiles/v1/renderTemplatedString.ts similarity index 100% rename from core/promptFiles/renderTemplatedString.ts rename to core/promptFiles/v1/renderTemplatedString.ts diff --git a/core/promptFiles/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts similarity index 90% rename from core/promptFiles/slashCommandFromPromptFile.ts rename to core/promptFiles/v1/slashCommandFromPromptFile.ts index af865078e..a272c2872 100644 --- a/core/promptFiles/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,10 +1,10 @@ -import { ContinueSDK, SlashCommand } from ".."; -import { stripImages } from "../llm/images"; +import * as YAML from "yaml"; +import { ContinueSDK, SlashCommand } from "../.."; +import { stripImages } from "../../llm/images"; +import { getBasename } from "../../util/index"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; import { updateChatHistory } from "./updateChatHistory"; -import * as YAML from "yaml"; -import { getBasename } from "../util/index"; export function extractName(preamble: { name?: string }, path: string): string { return preamble.name ?? getBasename(path).split(".prompt")[0]; @@ -37,7 +37,10 @@ export function extractUserInput(input: string, commandName: string): string { return input; } -export async function getDefaultVariables(context: ContinueSDK, userInput: string): Promise> { +export async function getDefaultVariables( + context: ContinueSDK, + userInput: string, +): Promise> { const currentFile = await context.ide.getCurrentFile(); const vars: Record = { input: userInput }; if (currentFile) { diff --git a/core/promptFiles/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts similarity index 100% rename from core/promptFiles/updateChatHistory.ts rename to core/promptFiles/v1/updateChatHistory.ts diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/v2/createNewPromptFile.ts new file mode 100644 index 000000000..aea2f917b --- /dev/null +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -0,0 +1,74 @@ +import path from "path"; +import { IDE } from "../.."; +import { GlobalContext } from "../../util/GlobalContext"; +import { DEFAULT_PROMPTS_FOLDER_V2 } from "./getPromptFiles"; + +const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file +# It is used to define and reuse prompts within Continue +# Continue will automatically create a context provider for each prompt in the .prompts folder + +# A prompt file consists of two parts: +# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options +# 2. Everything below the "---" is the prompt body + +# If you don't want to set any options, you don't need to include the "---" + +# In the body, you can reference: +# 1. Files, using either absolute or relative (based on the workspace root) paths + # e.g. @README.md + # e.g. @src/test/test.py + # e.g. @/Users/me/Desktop/my-project/src/test/test.py +# 2. URLs + # e.g. https://example.com +# 3. Some context providers, like + # e.g. @currentFile + # e.g. @os + # e.g. @repo-map + +# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files +name: Example +description: Example prompt file +version: 2 +--- +@README.md + +Please reference the above README.md file to understand the current project. +`; + +const DEFAULT_PROMPT_FILE = `version: 2 +--- + +`; + +export async function createNewPromptFileV2( + ide: IDE, + promptPath: string | undefined, +): Promise { + const workspaceDirs = await ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + throw new Error( + "No workspace directories found. Make sure you've opened a folder in your IDE.", + ); + } + const baseDir = path.join( + workspaceDirs[0], + promptPath ?? DEFAULT_PROMPTS_FOLDER_V2, + ); + + // Find the first available filename + let counter = 0; + let promptFilePath: string; + do { + const suffix = counter === 0 ? "" : `-${counter}`; + promptFilePath = path.join(baseDir, `new-prompt-file${suffix}.prompt`); + counter++; + } while (await ide.fileExists(promptFilePath)); + + const PROMPT_FILE = + new GlobalContext().get("hasAlreadyCreatedAPromptFile") === true + ? DEFAULT_PROMPT_FILE + : FIRST_TIME_DEFAULT_PROMPT_FILE; + + await ide.writeFile(promptFilePath, PROMPT_FILE); + await ide.openFile(promptFilePath); +} diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts new file mode 100644 index 000000000..ae02013a3 --- /dev/null +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -0,0 +1,59 @@ +import path from "path"; +import { IDE } from "../.."; +import { walkDir } from "../../indexing/walkDir"; +import { readAllGlobalPromptFiles } from "../../util/paths"; + +async function getPromptFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const paths = await walkDir(dir, ide, { ignoreFiles: [] }); + const results = paths.map(async (path) => { + const content = await ide.readFile(path); // make a try catch + return { path, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export const DEFAULT_PROMPTS_FOLDER_V2 = ".prompts"; + +export async function getAllPromptFilesV2( + ide: IDE, + overridePromptFolder?: string, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let promptFiles: { path: string; content: string }[] = []; + promptFiles = ( + await Promise.all( + workspaceDirs.map((dir) => + getPromptFilesFromDir( + ide, + path.join(dir, overridePromptFolder ?? DEFAULT_PROMPTS_FOLDER_V2), + ), + ), + ) + ) + .flat() + .filter(({ path }) => path.endsWith(".prompt")); + + // Also read from ~/.continue/.prompts + promptFiles.push(...readAllGlobalPromptFiles()); + + return await Promise.all( + promptFiles.map(async (file) => { + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/promptFiles/v2/parse.ts b/core/promptFiles/v2/parse.ts new file mode 100644 index 000000000..9f5ecf832 --- /dev/null +++ b/core/promptFiles/v2/parse.ts @@ -0,0 +1,33 @@ +import * as YAML from "yaml"; +import { getBasename } from "../../util"; + +export function extractName(preamble: { name?: string }, path: string): string { + return preamble.name ?? getBasename(path).split(".prompt")[0]; +} + +export function getPreambleAndBody(content: string): [string, string] { + let [preamble, body] = content.split("\n---\n"); + if (body === undefined) { + // This means there is no preamble + body = preamble; + preamble = ""; + } + return [preamble, body]; +} + +export function parsePreamble( + path: string, + content: string, +): { [key: string]: any; name: string; description: string } { + const [preambleRaw, _] = getPreambleAndBody(content); + + const preamble = YAML.parse(preambleRaw) ?? {}; + const name = extractName(preamble, path); + const description = preamble.description ?? name; + + return { + ...preamble, + name, + description, + }; +} diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts new file mode 100644 index 000000000..243c007dd --- /dev/null +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -0,0 +1,52 @@ +import { ContextItem, ContextProviderExtras } from "../.."; +import URLContextProvider from "../../context/providers/URLContextProvider"; +import { getBasename } from "../../util"; +import { getPreambleAndBody } from "./parse"; + +async function resolveAttachment( + name: string, + extras: ContextProviderExtras, +): Promise { + // Context providers + const contextProvider = extras.config.contextProviders?.find( + (provider) => provider.description.title === name, + ); + if (contextProvider) { + const items = await contextProvider.getContextItems("", extras); + return items; + } + + // Files + if (await extras.ide.fileExists(name)) { + const content = `\`\`\`${name}\n${await extras.ide.readFile(name)}\n\`\`\``; + return [{ name: getBasename(name), content, description: name }]; + } + + // URLs + if (name.startsWith("http")) { + const items = await new URLContextProvider({}).getContextItems( + name, + extras, + ); + return items; + } + + return []; +} + +export async function renderPromptFileV2( + rawContent: string, + extras: ContextProviderExtras, +): Promise<[ContextItem[], string]> { + const [preamble, body] = getPreambleAndBody(rawContent); + + const contextItemsPromises: Promise[] = []; + const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { + contextItemsPromises.push(resolveAttachment(name, extras)); + return match; + }); + + const contextItems = (await Promise.all(contextItemsPromises)).flat(); + + return [contextItems, renderedBody]; +} diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index f48e848a9..097dac5d1 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -14,6 +14,7 @@ export type GlobalContextType = { */ curEmbeddingsProviderId: EmbeddingsProvider["id"]; hasDismissedConfigTsNoticeJetBrains: boolean; + hasAlreadyCreatedAPromptFile: boolean; }; /** diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.md index 7c1d05ed9..96988e858 100644 --- a/docs/docs/customize/slash-commands.md +++ b/docs/docs/customize/slash-commands.md @@ -12,37 +12,7 @@ Slash commands are shortcuts that can be activated by typing '/' and selecting f To use any of the built-in slash commands, open `config.json` and add it to the `slashCommands` list. -### `/Edit` - -Select code with `ctrl/cmd + L` (VS Code) or `ctrl/cmd + J` (JetBrains), and then type `/Edit`, followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "edit", - "description": "Edit highlighted code" - } - ] -} -``` - -### `/Comment` - -Comment works just like `/Edit`, except it will automatically prompt the LLM to comment the code. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "comment", - "description": "Write comments for the highlighted code" - } - ] -} -``` - -### `/Share` +### `/share` Generate a shareable markdown transcript of your current chat history. @@ -60,7 +30,7 @@ Generate a shareable markdown transcript of your current chat history. Use the `outputDir` parameter to specify where you want to the markdown file to be saved. -### `/Cmd` +### `/cmd` Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal. @@ -75,7 +45,7 @@ Generate a shell command from natural language and (only in VS Code) automatical } ``` -### `/Commit` +### `/commit` Shows the LLM your current git diff and asks it to generate a commit message. @@ -90,7 +60,7 @@ Shows the LLM your current git diff and asks it to generate a commit message. } ``` -### `/Http` +### `/http` Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference. @@ -106,7 +76,7 @@ Write a custom slash command at your own HTTP endpoint. Set 'url' in the params } ``` -### `/Issue` +### `/issue` Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for. @@ -122,9 +92,9 @@ Describe the issue you'd like to generate, and Continue will turn into a well-fo } ``` -### `/Onboard` +### `/onboard` -The Onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. +The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. ```json title="config.json" { diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 367f32d54..09dd150a6 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -268,7 +268,7 @@ Custom commands initiated by typing "/" in the sidebar. Commands include predefi **Properties:** -- `name`: The command name. Options include "issue", "share", "cmd", "edit", "comment", "http", "commit", and "review". +- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". - `description`: Brief description of the command. - `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. - `params`: Additional parameters to configure command behavior (command-specific - see code for command) @@ -282,10 +282,6 @@ Example: "name": "commit", "description": "Generate a commit message" }, - { - "name": "comment", - "description": "Write comments for the selected code" - }, { "name": "share", "description": "Export this session as markdown" diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt index cdcb58c18..5135dc87a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt @@ -48,14 +48,6 @@ const val DEFAULT_CONFIG = } ], "slashCommands": [ - { - "name": "edit", - "description": "Edit selected code" - }, - { - "name": "comment", - "description": "Write comments for the selected code" - }, { "name": "share", "description": "Export the current chat session to markdown" diff --git a/extensions/vscode/media/prompt.tmLanguage.json b/extensions/vscode/media/prompt.tmLanguage.json new file mode 100644 index 000000000..c1022d882 --- /dev/null +++ b/extensions/vscode/media/prompt.tmLanguage.json @@ -0,0 +1,64 @@ +{ + "name": "Prompt", + "scopeName": "source.prompt", + "patterns": [ + { + "include": "#at-references" + }, + { + "include": "#strings" + }, + { + "include": "#comments" + } + ], + "repository": { + "at-references": { + "patterns": [ + { + "name": "entity.name.type.prompt", + "match": "@\\S+" + } + ] + }, + "strings": { + "patterns": [ + { + "name": "string.quoted.double.prompt", + "begin": "\"", + "end": "\"", + "patterns": [ + { + "name": "constant.character.escape.prompt", + "match": "\\\\." + } + ] + }, + { + "name": "string.quoted.single.prompt", + "begin": "'", + "end": "'", + "patterns": [ + { + "name": "constant.character.escape.prompt", + "match": "\\\\." + } + ] + } + ] + }, + "comments": { + "patterns": [ + { + "name": "comment.line.double-slash.prompt", + "match": "//.*$" + }, + { + "name": "comment.block.prompt", + "begin": "/\\*", + "end": "\\*/" + } + ] + } + } +} diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index d3cc6debd..50c295b98 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -64,6 +64,23 @@ ".continuerc.json" ], "id": "jsonc" + }, + { + "id": "promptLanguage", + "extensions": [ + ".prompt" + ], + "aliases": [ + "Prompt Language" + ], + "configuration": "./prompt-file-language-configuration.json" + } + ], + "grammars": [ + { + "language": "promptLanguage", + "scopeName": "source.prompt", + "path": "./media/prompt.tmLanguage.json" } ], "configuration": { diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index caf365805..eabb2fec8 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -49,7 +49,8 @@ class VsCodeIde implements IDE { return Promise.resolve(this.ideUtils.path.sep); } async fileExists(filepath: string): Promise { - return vscode.workspace.fs.stat(uriFromFilePath(filepath)).then( + const absPath = await this.ideUtils.resolveAbsFilepathInWorkspace(filepath); + return vscode.workspace.fs.stat(uriFromFilePath(absPath)).then( () => true, () => false, ); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index ca6313640..faee3cc06 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -19,6 +19,7 @@ import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvide import { DiffManager } from "../diff/horizontal"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; +import { registerAllPromptFilesCompletionProviders } from "../lang-server/promptFileCompletions"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { QuickEdit } from "../quickEdit/QuickEditQuickPick"; import { setupRemoteConfigSync } from "../stubs/activation"; @@ -28,6 +29,7 @@ import { } from "../stubs/WorkOsAuthProvider"; import { arePathsEqual } from "../util/arePathsEqual"; import { Battery } from "../util/battery"; +import { FileSearch } from "../util/FileSearch"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { VsCodeIde } from "../VsCodeIde"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -49,6 +51,7 @@ export class VsCodeExtension { private core: Core; private battery: Battery; private workOsAuthProvider: WorkOsAuthProvider; + private fileSearch: FileSearch; constructor(context: vscode.ExtensionContext) { // Register auth provider @@ -206,12 +209,21 @@ export class VsCodeExtension { context.subscriptions.push(this.battery); context.subscriptions.push(monitorBatteryChanges(this.battery)); + // FileSearch + this.fileSearch = new FileSearch(this.ide); + registerAllPromptFilesCompletionProviders( + context, + this.fileSearch, + this.ide, + ); + const quickEdit = new QuickEdit( this.verticalDiffManager, this.configHandler, this.sidebar.webviewProtocol, this.ide, context, + this.fileSearch, ); // Commands diff --git a/extensions/vscode/src/lang-server/promptFileCompletions.ts b/extensions/vscode/src/lang-server/promptFileCompletions.ts new file mode 100644 index 000000000..da620f700 --- /dev/null +++ b/extensions/vscode/src/lang-server/promptFileCompletions.ts @@ -0,0 +1,270 @@ +import { IDE } from "core"; +import { getBasename, getLastNPathParts } from "core/util"; +import vscode from "vscode"; +import { FileSearch } from "../util/FileSearch"; + +class PromptFilesCompletionItemProvider + implements vscode.CompletionItemProvider +{ + constructor( + private fileSearch: FileSearch, + private ide: IDE, + ) {} + async provideCompletionItems( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + context: vscode.CompletionContext, + ) { + const linePrefix = + document + .lineAt(position) + .text.substr(0, position.character) + .split(" ") + .pop() || ""; + + // Check if the last character typed is '@' + if (!linePrefix.includes("@")) { + return undefined; + } + + const searchText = linePrefix.split("@").pop() || ""; + const files = this.fileSearch.search(searchText).map(({ filename }) => { + return filename; + }); + + if (files.length === 0) { + const openFiles = await this.ide.getOpenFiles(); + files.push(...openFiles); + } + + // Provide completion items + return [ + { + label: "terminal", + detail: "Contents of terminal", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + { + label: "tree", + detail: "File tree of workspace", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + { + label: "open", + detail: "All open files", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + { + label: "os", + detail: "Operating system information", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + { + label: "problems", + detail: "Problems in the current file", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + { + label: "currentFile", + detail: "Current file", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + { + label: "repo-map", + detail: "Map of files in your repo", + sortText: "...", + kind: vscode.CompletionItemKind.Field, + }, + ...files.map((file) => { + const workspaceFolder = vscode.workspace.getWorkspaceFolder( + vscode.Uri.file(file), + ); + const relativePath = workspaceFolder + ? vscode.workspace.asRelativePath(file) + : file; + + return { + label: getBasename(file), + detail: getLastNPathParts(file, 2), + insertText: relativePath, + kind: vscode.CompletionItemKind.File, + }; + }), + ]; + } +} + +function registerPromptFilesCompletionProvider( + context: vscode.ExtensionContext, + fileSearch: FileSearch, + ide: IDE, +) { + let provider = vscode.languages.registerCompletionItemProvider( + "promptLanguage", + new PromptFilesCompletionItemProvider(fileSearch, ide), + "@", // Trigger completion when '@' is typed + ); + + context.subscriptions.push(provider); +} + +class YamlKeysCompletionItemProvider implements vscode.CompletionItemProvider { + private yamlKeys: { key: string; description: string }[] = [ + { + key: "name", + description: "The name of the prompt template", + }, + { + key: "description", + description: "A description of what this prompt template does", + }, + { + key: "version", + description: ".prompt file version. Either 1 (legacy) or 2", + }, + ]; + + async provideCompletionItems( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + context: vscode.CompletionContext, + ) { + const lineText = document.lineAt(position).text; + const textBeforeCursor = lineText.substring(0, position.character); + + // 1. Check if the cursor is in YAML section (before --- delimiter) + const beforeDelimiter = isCursorBeforeDelimiter(document, position); + + if (!beforeDelimiter) { + return undefined; + } + + // 2. Check if there is no colon before the cursor on this line + if (textBeforeCursor.includes(":")) { + return undefined; + } + + // 3. Provide completion items for YAML keys + const completionItems = this.yamlKeys.map((key) => { + const item = new vscode.CompletionItem( + key.key, + vscode.CompletionItemKind.Property, + ); + item.documentation = new vscode.MarkdownString(key.description); + item.insertText = key + ": "; + return item; + }); + + return completionItems; + } +} + +// Helper function to determine if the cursor is before the '---' delimiter +function isCursorBeforeDelimiter( + document: vscode.TextDocument, + position: vscode.Position, +): boolean { + const delimiter = "---"; + for (let i = 0; i < document.lineCount; i++) { + const lineText = document.lineAt(i).text.trim(); + if (lineText === delimiter) { + // Cursor is before the delimiter + return position.line < i; + } + } + // Delimiter not found; assume entire document is YAML + return true; +} + +function registerYamlKeysCompletionProvider(context: vscode.ExtensionContext) { + const provider = vscode.languages.registerCompletionItemProvider( + "promptLanguage", + new YamlKeysCompletionItemProvider(), + ...Array.from("abcdefghijklmnopqrstuvwxyz"), // Trigger on all lowercase letters + ); + + context.subscriptions.push(provider); +} + +// Helper function to determine if the position is within the YAML header +function isPositionInYamlHeader( + document: vscode.TextDocument, + position: vscode.Position, +): boolean { + const delimiter = "---"; + for (let i = 0; i < document.lineCount; i++) { + const lineText = document.lineAt(i).text.trim(); + if (lineText === delimiter) { + // Cursor is before the delimiter + return position.line < i; + } + } + // Delimiter not found; assume entire document is YAML + return true; +} + +export function registerAllPromptFilesCompletionProviders( + context: vscode.ExtensionContext, + fileSearch: FileSearch, + ide: IDE, +) { + registerPromptFilesCompletionProvider(context, fileSearch, ide); + registerYamlKeysCompletionProvider(context); + + context.subscriptions.push( + vscode.workspace.onDidChangeTextDocument((event) => { + const editor = vscode.window.activeTextEditor; + if (!editor || event.document !== editor.document) { + return; + } + + const languageId = editor.document.languageId; + if (languageId !== "promptLanguage") { + return; + } + + for (const change of event.contentChanges) { + // Get position after the change by applying the change length + const isDeletion = change.text.length <= 0; + const lines = change.text.split("\n"); + const positionAfterChange = isDeletion + ? change.range.start + : new vscode.Position( + change.range.start.line + lines.length - 1, + lines.length === 1 + ? change.range.start.character + change.text.length + : lines[lines.length - 1].length, + ); + + // Use the updated document state + const line = event.document.lineAt(positionAfterChange.line); + + // Check if we're in the YAML header using current document state + const inYamlHeader = isPositionInYamlHeader( + event.document, + positionAfterChange, + ); + // Check if we're at the first character of the line + const atLineStart = positionAfterChange.character === 0; + // Check if the current line is empty (excluding whitespace) + const lineIsEmpty = line.text.trim() === ""; + + if (inYamlHeader && atLineStart && lineIsEmpty) { + // Delay slightly to ensure the editor updates before triggering suggestions + setTimeout(() => { + // Trigger suggestions + vscode.commands.executeCommand("editor.action.triggerSuggest"); + }, 50); + } + } + }), + ); +} diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 2ec7aa515..e4274230e 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,6 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { IDE } from "core"; -import { walkDir } from "core/indexing/walkDir"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { VerticalDiffManager } from "../diff/vertical/manager"; @@ -13,9 +12,8 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; import { ConfigHandler } from "core/config/ConfigHandler"; // @ts-ignore import { getModelByRole } from "core/config/util"; -// @ts-ignore -import MiniSearch from "minisearch"; import { logDevData } from "core/util/devdata"; +import { FileSearch } from "../util/FileSearch"; /** * Used to track what action to take after a user interacts @@ -43,8 +41,6 @@ export type QuickEditShowParams = { range?: vscode.Range; }; -type FileMiniSearchResult = { filename: string }; - const FILE_SEARCH_CHAR = "@"; /** @@ -89,15 +85,6 @@ export class QuickEdit { private range?: vscode.Range; private initialPrompt?: string; - private miniSearch = new MiniSearch({ - fields: ["filename"], - storeFields: ["filename"], - searchOptions: { - prefix: true, - fuzzy: 2, - }, - }); - private previousInput?: string; /** @@ -123,9 +110,8 @@ export class QuickEdit { private readonly webviewProtocol: VsCodeWebviewProtocol, private readonly ide: IDE, private readonly context: vscode.ExtensionContext, - ) { - this.initializeFileSearchState(); - } + private readonly fileSearch: FileSearch, + ) {} /** * Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt. @@ -238,7 +224,13 @@ export class QuickEdit { break; } let model = await this.getCurModelTitle(); - logDevData('quickEdit', {prompt, path, label, diffs: this.verticalDiffManager.logDiffs, model}); + logDevData("quickEdit", { + prompt, + path, + label, + diffs: this.verticalDiffManager.logDiffs, + model, + }); quickPick.dispose(); }); } @@ -252,23 +244,6 @@ export class QuickEdit { this.openAcceptRejectMenu(prompt, path); }; - private async initializeFileSearchState() { - const workspaceDirs = await this.ide.getWorkspaceDirs(); - - const results = await Promise.all( - workspaceDirs.map((dir) => { - return walkDir(dir, this.ide); - }), - ); - - const filenames = results.flat().map((file) => ({ - id: file, - filename: vscode.workspace.asRelativePath(file), - })); - - this.miniSearch.addAll(filenames); - } - private setActiveEditorAndPrevInput(editor: vscode.TextEditor) { const existingHandler = this.verticalDiffManager.getHandlerForFile( editor.document.uri.fsPath ?? "", @@ -321,8 +296,9 @@ export class QuickEdit { return isSelectionEmpty ? `Edit ${fileName}` - : `Edit ${fileName}:${start.line}${end.line > start.line ? `-${end.line}` : "" - }`; + : `Edit ${fileName}:${start.line}${ + end.line > start.line ? `-${end.line}` : "" + }`; }; private async _streamEditWithInputAndContext( @@ -465,9 +441,7 @@ export class QuickEdit { // search character to the end of the string const searchQuery = value.substring(lastAtIndex + 1); - const searchResults = this.miniSearch.search( - searchQuery, - ) as unknown as FileMiniSearchResult[]; + const searchResults = this.fileSearch.search(searchQuery); if (searchResults.length > 0) { quickPick.items = searchResults diff --git a/extensions/vscode/src/util/FileSearch.ts b/extensions/vscode/src/util/FileSearch.ts new file mode 100644 index 000000000..cc02f3128 --- /dev/null +++ b/extensions/vscode/src/util/FileSearch.ts @@ -0,0 +1,42 @@ +import { IDE } from "core"; +import { walkDir } from "core/indexing/walkDir"; +// @ts-ignore +import MiniSearch from "minisearch"; +import * as vscode from "vscode"; + +type FileMiniSearchResult = { filename: string }; + +export class FileSearch { + constructor(private readonly ide: IDE) { + this.initializeFileSearchState(); + } + + private miniSearch = new MiniSearch({ + fields: ["filename"], + storeFields: ["filename"], + searchOptions: { + prefix: true, + fuzzy: 2, + }, + }); + private async initializeFileSearchState() { + const workspaceDirs = await this.ide.getWorkspaceDirs(); + + const results = await Promise.all( + workspaceDirs.map((dir) => { + return walkDir(dir, this.ide); + }), + ); + + const filenames = results.flat().map((file) => ({ + id: file, + filename: vscode.workspace.asRelativePath(file), + })); + + this.miniSearch.addAll(filenames); + } + + public search(query: string): FileMiniSearchResult[] { + return this.miniSearch.search(query) as unknown as FileMiniSearchResult[]; + } +} diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 3c0ba951f..217fcc293 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -2,7 +2,6 @@ import { NodeViewWrapper } from "@tiptap/react"; import { ContextItemWithId } from "core"; import { useDispatch, useSelector } from "react-redux"; import { vscBadgeBackground } from ".."; -import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; @@ -26,71 +25,13 @@ export const CodeBlockComponent = ({ item.id === contextItems[0]?.id ? "#d0d" : selected - ? vscBadgeBackground - : undefined + ? vscBadgeBackground + : undefined } item={item} onDelete={() => { deleteNode(); }} - onEdit={async () => { - dispatch(setEditingContextItemAtIndex({ item })); - if (item.id === contextItems[0]?.id) { - // Find and delete the /edit command - let index = 0; - for (const el of editor.getJSON().content) { - if (el.type === "slashcommand") { - if (el.attrs.id === "/edit") { - editor - .chain() - .deleteRange({ from: index, to: index + 2 }) - .focus("end") - .run(); - break; - } - } - index += 1; - } - - updateAttributes({ - item: { - ...item, - editing: false, - }, - }); - } else { - let index = 0; - for (const el of editor.getJSON().content) { - if (el.type === "codeBlock") { - index += 2; - } else { - break; - } - } - editor - .chain() - .focus("end") - .insertContent([ - { - type: "slashcommand", - attrs: { id: "/edit", label: "/edit" }, - }, - { type: "text", text: " " }, - ]) - .run(); - - updateAttributes({ - item: { - ...item, - editing: true, - }, - }); - - await new Promise((resolve) => setTimeout(resolve, 100)); - editor.commands.focus("end"); - } - }} - editing={item.id === contextItems[0]?.id} /> ); diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index a84294a23..49dcebbbc 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -6,14 +6,13 @@ import { BookOpenIcon, CodeBracketIcon, CommandLineIcon, + DocumentTextIcon, ExclamationCircleIcon, ExclamationTriangleIcon, FolderIcon, FolderOpenIcon, GlobeAltIcon, - HashtagIcon, MagnifyingGlassIcon, - PencilIcon, PlusIcon, SparklesIcon, TrashIcon, @@ -21,6 +20,7 @@ import { import { Editor } from "@tiptap/react"; import { forwardRef, + useContext, useEffect, useImperativeHandle, useRef, @@ -36,6 +36,7 @@ import { vscListActiveForeground, vscQuickInputBackground, } from ".."; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { setDialogMessage, setShowDialog, @@ -61,10 +62,9 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { issue: ExclamationCircleIcon, trash: TrashIcon, web: GlobeAltIcon, + "prompt-files": DocumentTextIcon, "repo-map": FolderIcon, - "/edit": PencilIcon, "/clear": TrashIcon, - "/comment": HashtagIcon, "/share": ArrowUpOnSquareIcon, "/cmd": CommandLineIcon, }; @@ -177,6 +177,8 @@ interface MentionListProps { const MentionList = forwardRef((props: MentionListProps, ref) => { const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( @@ -208,6 +210,24 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { }, description: "Add a new documentation source", }); + } else if (subMenuTitle === ".prompt files") { + items.push({ + title: "New .prompt file", + type: "action", + action: () => { + ideMessenger.request("config/newPromptFile", undefined); + const { tr } = props.editor.view.state; + const text = tr.doc.textBetween(0, tr.selection.from); + const start = text.lastIndexOf("@"); + if (start !== -1) { + props.editor.view.dispatch( + tr.delete(start, tr.selection.from).scrollIntoView(), + ); + } + props.onClose(); // Escape the mention list after creating a new prompt file + }, + description: "Create a new .prompt file", + }); } setAllItems(items); @@ -375,7 +395,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { onClick={() => selectItem(index)} onMouseEnter={() => setSelectedIndex(index)} > - +
{showFileIconForItem(item) && ( { opacity: index !== selectedIndex ? 0 : 1, minWidth: "30px", }} - className="whitespace-nowrap overflow-hidden overflow-ellipsis ml-2 flex items-center" + className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap" > {item.description} {item.type === "contextProvider" && diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 7ee758e75..c2646415e 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -44,7 +44,6 @@ import useUpdatingRef from "../../hooks/useUpdatingRef"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectUseActiveFile } from "../../redux/selectors"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; -import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import { getFontSize, @@ -508,29 +507,6 @@ function TipTapEditor(props: TipTapEditorProps) { if (!codeBlock) { return; } - - // Search for slashcommand type - for (const p of json.content) { - if ( - p.type !== "paragraph" || - !p.content || - typeof p.content === "string" - ) { - continue; - } - for (const node of p.content) { - if ( - node.type === "slashcommand" && - ["/edit", "/comment"].includes(node.attrs.label) - ) { - // Update context items - dispatch( - setEditingContextItemAtIndex({ item: codeBlock.attrs.item }), - ); - return; - } - } - } }, editable: !active || props.isMainInput, }); diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index 196fe09a2..7711562ae 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -189,18 +189,17 @@ export function getSlashCommandDropdownOptions( const items = async ({ query }: { query: string }) => { const options = [ ...availableSlashCommandsRef.current, - { - title: "Build a custom prompt", - description: "Build a custom prompt", - type: "action", - id: "createPromptFile", - label: "Create Prompt File", - action: () => { - console.log("I", ideMessenger.request); - ideMessenger.request("config/newPromptFile", undefined); - }, - name: "Create Prompt File", - }, + // { + // title: "Build a custom prompt", + // description: "Build a custom prompt", + // type: "action", + // id: "createPromptFile", + // label: "Create Prompt File", + // action: () => { + // ideMessenger.request("config/newPromptFile", undefined); + // }, + // name: "Create Prompt File", + // }, ]; return ( options.filter((slashCommand) => { diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 3c783c59a..b635179a2 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -1,7 +1,6 @@ import { ChevronDownIcon, ChevronUpIcon, - PencilIcon, XMarkIcon, } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; @@ -36,7 +35,7 @@ const PreviewMarkdownHeader = styled.div` padding: 2px 6px; border-bottom: 0.5px solid ${lightGray}; word-break: break-all; - font-size: ${getFontSize() - 2}px; + font-size: ${getFontSize() - 3}px; display: flex; align-items: center; `; @@ -44,17 +43,9 @@ const PreviewMarkdownHeader = styled.div` interface CodeSnippetPreviewProps { item: ContextItemWithId; onDelete?: () => void; - onEdit?: () => void; borderColor?: string; - editing?: boolean; } -const StyledHeaderButtonWithText = styled(ButtonWithTooltip)<{ - color?: string; -}>` - ${(props) => props.color && `background-color: ${props.color};`} -`; - const MAX_PREVIEW_HEIGHT = 300; // Pre-compile the regular expression outside of the function @@ -83,7 +74,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { borderColor={props.borderColor} > { if (props.item.id.providerTitle === "file") { ideMessenger.post("showFile", { @@ -108,23 +99,10 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { }} >
- + {props.item.name}
- {props.onEdit && ( - { - e.stopPropagation(); - e.preventDefault(); - props.onEdit?.(); - }} - {...(props.editing && { color: "#f0f4" })} - > - - - )} { @@ -132,14 +110,14 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { props.onDelete?.(); }} > - +
@@ -153,7 +131,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { {(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && ( {collapsed ? ( diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index f961e62c1..ba0a7e26d 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -64,7 +64,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { saveSession(false); }, [save]); - useEffect(() => { activeRef.current = active; }, [active]); @@ -219,7 +218,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const currentFile = await ideMessenger.ide.getCurrentFile(); if (currentFile) { - let currentFileContents = currentFile.contents + let currentFileContents = currentFile.contents; if (usingFreeTrial) { currentFileContents = currentFile.contents .split("\n") @@ -292,13 +291,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { params: {}, }); - // For edit and comment slash commands, including the selected code in the context from store and for other commands, including the selected context alone - if (slashCommand.name === "edit" || slashCommand.name === "comment") { - updatedContextItems = [...contextItems]; - } else { - updatedContextItems = [...selectedContextItems]; - } - await _streamSlashCommand( messages, slashCommand, diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index c22d4bb1b..0e41fd26e 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -1,7 +1,6 @@ import { PayloadAction, createSlice } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/react"; import { - ChatHistory, ChatHistoryItem, ChatMessage, ContextItemId, @@ -10,12 +9,11 @@ import { PromptLog, } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; +import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; import { createSelector } from "reselect"; -import { v4 } from "uuid"; +import { v4 as uuidv4, v4 } from "uuid"; import { RootState } from "../store"; -import { v4 as uuidv4 } from "uuid"; -import { ConfigValidationError } from "core/config/validation"; export const memoizedContextItemsSelector = createSelector( [(state: RootState) => state.state.history], @@ -57,14 +55,6 @@ const initialState: State = { configError: undefined, config: { slashCommands: [ - { - name: "edit", - description: "Edit selected code", - }, - { - name: "comment", - description: "Write comments for the selected code", - }, { name: "share", description: "Export the current chat session to markdown", @@ -151,23 +141,6 @@ export const stateSlice = createSlice({ state.history[index].contextItems = contextItems; } }, - setEditingContextItemAtIndex: ( - state, - { - payload: { index, item }, - }: PayloadAction<{ index?: number; item: ContextItemWithId }>, - ) => { - if (index === undefined) { - const isFirstContextItem = - state.contextItems[0]?.id.itemId === item.id.itemId; - - state.contextItems = isFirstContextItem - ? [] - : [{ ...item, editing: true }]; - return; - } - // TODO - }, addContextItems: (state, action: PayloadAction) => { state.contextItems = state.contextItems.concat(action.payload); }, @@ -462,7 +435,6 @@ export const { addPromptCompletionPair, setTTSActive, setActive, - setEditingContextItemAtIndex, initNewActiveMessage, setMessageAtIndex, clearLastResponse,