From 462a2239bfcc58be10c4c5334ee8b8d924f2c62e Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 2 Nov 2024 11:01:41 -0700 Subject: [PATCH 01/13] prompt files v2 --- core/commands/index.ts | 2 +- core/config/load.ts | 42 +++++++------ core/config/promptFile.ts | 2 +- .../providers/PromptFilesContextProvider.ts | 55 +++++++++++++++++ core/context/providers/index.ts | 2 +- core/core.ts | 6 +- core/llm/llms/index.ts | 8 +-- .../{ => v1}/createNewPromptFile.ts | 4 +- .../{ => v1}/getContextProviderHelpers.ts | 0 core/promptFiles/{ => v1}/getPromptFiles.ts | 4 +- core/promptFiles/{ => v1}/handlebarUtils.ts | 0 core/promptFiles/{ => v1}/index.ts | 5 +- .../{ => v1}/renderTemplatedString.ts | 0 .../{ => v1}/slashCommandFromPromptFile.ts | 8 +-- .../promptFiles/{ => v1}/updateChatHistory.ts | 0 core/promptFiles/v2/createNewPromptFile.ts | 35 +++++++++++ core/promptFiles/v2/getPromptFiles.ts | 59 +++++++++++++++++++ core/promptFiles/v2/parse.ts | 27 +++++++++ core/promptFiles/v2/renderPromptFile.ts | 3 + extensions/vscode/package-lock.json | 4 +- gui/src/components/mainInput/MentionList.tsx | 19 +++++- gui/src/components/mainInput/getSuggestion.ts | 23 ++++---- 22 files changed, 252 insertions(+), 56 deletions(-) create mode 100644 core/context/providers/PromptFilesContextProvider.ts rename core/promptFiles/{ => v1}/createNewPromptFile.ts (96%) rename core/promptFiles/{ => v1}/getContextProviderHelpers.ts (100%) rename core/promptFiles/{ => v1}/getPromptFiles.ts (86%) rename core/promptFiles/{ => v1}/handlebarUtils.ts (100%) rename core/promptFiles/{ => v1}/index.ts (73%) rename core/promptFiles/{ => v1}/renderTemplatedString.ts (100%) rename core/promptFiles/{ => v1}/slashCommandFromPromptFile.ts (94%) rename core/promptFiles/{ => v1}/updateChatHistory.ts (100%) create mode 100644 core/promptFiles/v2/createNewPromptFile.ts create mode 100644 core/promptFiles/v2/getPromptFiles.ts create mode 100644 core/promptFiles/v2/parse.ts create mode 100644 core/promptFiles/v2/renderPromptFile.ts 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/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 ebbbd59ab..1cee2875f 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,7 +4,7 @@ import * as YAML from "yaml"; import type { 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"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; diff --git a/core/context/providers/PromptFilesContextProvider.ts b/core/context/providers/PromptFilesContextProvider.ts new file mode 100644 index 000000000..61314adae --- /dev/null +++ b/core/context/providers/PromptFilesContextProvider.ts @@ -0,0 +1,55 @@ +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 rendered = await renderPromptFileV2(rawContent); + return [ + { + content: rendered, + 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 8ce7c7a5d..dcf27f6eb 100644 --- a/core/core.ts +++ b/core/core.ts @@ -8,7 +8,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"; @@ -18,6 +17,7 @@ import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; 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"; @@ -245,11 +245,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 4a6b1d539..a3fa6c910 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"; const LLMs = [ Anthropic, @@ -84,7 +84,7 @@ const LLMs = [ Cerebras, Asksage, Nebius, - VertexAI + VertexAI, ]; 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 94% rename from core/promptFiles/slashCommandFromPromptFile.ts rename to core/promptFiles/v1/slashCommandFromPromptFile.ts index e81f13615..1bb99b9cc 100644 --- a/core/promptFiles/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,10 +1,10 @@ -import { SlashCommand } from ".."; -import { stripImages } from "../llm/images"; +import * as YAML from "yaml"; +import { 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]; 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..e334a5085 --- /dev/null +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -0,0 +1,35 @@ +import path from "path"; +import { IDE } from "../.."; +import { DEFAULT_PROMPTS_FOLDER_V2 } from "./getPromptFiles"; + +const 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 +# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files +temperature: 0.0 +version: 2 +--- +@README.md + +Please reference the above README.md file to understand the current project. +`; + +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 promptFilePath = path.join( + workspaceDirs[0], + promptPath ?? DEFAULT_PROMPTS_FOLDER_V2, + "new-prompt-file.prompt", + ); + + await ide.writeFile(promptFilePath, DEFAULT_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..1c952ba1b --- /dev/null +++ b/core/promptFiles/v2/parse.ts @@ -0,0 +1,27 @@ +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 parsePreamble( + path: string, + content: string, +): { [key: string]: any; name: string; description: string } { + let [preambleRaw, prompt] = content.split("\n---\n"); + if (prompt === undefined) { + // This means there is no preamble + preambleRaw = ""; + } + + 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..769c93d3e --- /dev/null +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -0,0 +1,3 @@ +export async function renderPromptFileV2(rawContent: string): Promise { + return rawContent; +} diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 760e977b6..44ade3c05 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.224", + "version": "0.9.225", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.224", + "version": "0.9.225", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index a84294a23..62dfdf1de 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -6,6 +6,7 @@ import { BookOpenIcon, CodeBracketIcon, CommandLineIcon, + DocumentTextIcon, ExclamationCircleIcon, ExclamationTriangleIcon, FolderIcon, @@ -21,6 +22,7 @@ import { import { Editor } from "@tiptap/react"; import { forwardRef, + useContext, useEffect, useImperativeHandle, useRef, @@ -36,6 +38,7 @@ import { vscListActiveForeground, vscQuickInputBackground, } from ".."; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { setDialogMessage, setShowDialog, @@ -61,6 +64,7 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { issue: ExclamationCircleIcon, trash: TrashIcon, web: GlobeAltIcon, + "prompt-files": DocumentTextIcon, "repo-map": FolderIcon, "/edit": PencilIcon, "/clear": TrashIcon, @@ -177,6 +181,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 +214,15 @@ 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); + }, + description: "Create a new .prompt file", + }); } setAllItems(items); @@ -375,7 +390,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/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) => { From bfb485b6935665893a57cfcdfbc17a85bc0b4fe7 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 5 Nov 2024 23:20:33 -0800 Subject: [PATCH 02/13] render prompt file v2 --- .../providers/PromptFilesContextProvider.ts | 2 +- core/promptFiles/v2/parse.ts | 16 ++++-- core/promptFiles/v2/renderPromptFile.ts | 54 ++++++++++++++++++- extensions/vscode/package-lock.json | 4 +- extensions/vscode/src/VsCodeIde.ts | 3 +- extensions/vscode/src/util/ideUtils.ts | 4 +- 6 files changed, 69 insertions(+), 14 deletions(-) diff --git a/core/context/providers/PromptFilesContextProvider.ts b/core/context/providers/PromptFilesContextProvider.ts index 61314adae..67a8a9e73 100644 --- a/core/context/providers/PromptFilesContextProvider.ts +++ b/core/context/providers/PromptFilesContextProvider.ts @@ -24,7 +24,7 @@ class PromptFilesContextProvider extends BaseContextProvider { ): Promise { const rawContent = await extras.ide.readFile(query); const preamble = parsePreamble(query, rawContent); - const rendered = await renderPromptFileV2(rawContent); + const rendered = await renderPromptFileV2(rawContent, extras); return [ { content: rendered, diff --git a/core/promptFiles/v2/parse.ts b/core/promptFiles/v2/parse.ts index 1c952ba1b..9f5ecf832 100644 --- a/core/promptFiles/v2/parse.ts +++ b/core/promptFiles/v2/parse.ts @@ -5,15 +5,21 @@ 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 } { - let [preambleRaw, prompt] = content.split("\n---\n"); - if (prompt === undefined) { - // This means there is no preamble - preambleRaw = ""; - } + const [preambleRaw, _] = getPreambleAndBody(content); const preamble = YAML.parse(preambleRaw) ?? {}; const name = extractName(preamble, path); diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 769c93d3e..04c08f245 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -1,3 +1,53 @@ -export async function renderPromptFileV2(rawContent: string): Promise { - return rawContent; +import { ContextProviderExtras } from "../.."; +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.map((item) => item.content).join("\n\n"); + } + + // Files + if (await extras.ide.fileExists(name)) { + const content = await extras.ide.readFile(name); + return `\`\`\`${name}\n${content}\n\`\`\``; + } + + // URLs + if (name.startsWith("http")) { + const response = await extras.fetch(name); + if (response.status !== 200) { + return `Error fetching ${name}: HTTP ${response.status}`; + } + return response.text(); + } + + return null; +} + +export async function renderPromptFileV2( + rawContent: string, + extras: ContextProviderExtras, +): Promise { + const [preamble, body] = getPreambleAndBody(rawContent); + + const attachmentPromises: Promise[] = []; + const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { + attachmentPromises.push(resolveAttachment(name, extras)); + return match; + }); + const attachments = (await Promise.all(attachmentPromises)).filter(Boolean); + + if (!attachments.length) { + return renderedBody; + } + + return attachments.join("\n\n") + "\n\n" + renderedBody; } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 44ade3c05..3751e3f97 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.225", + "version": "0.9.226", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.225", + "version": "0.9.226", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 43911c6f8..526dc1844 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/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 14ebd9ed2..d42aa65b0 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -136,9 +136,7 @@ export class VsCodeIdeUtils { ); } - private async resolveAbsFilepathInWorkspace( - filepath: string, - ): Promise { + async resolveAbsFilepathInWorkspace(filepath: string): Promise { // If the filepath is already absolute, return it as is if (this.path.isAbsolute(filepath)) { return filepath; From 82e6a4beca04b92f0da5d32c172f76483dee2619 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 5 Nov 2024 23:23:01 -0800 Subject: [PATCH 03/13] use URLContextProvider --- core/promptFiles/v2/renderPromptFile.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 04c08f245..51f94a602 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -1,4 +1,5 @@ import { ContextProviderExtras } from "../.."; +import URLContextProvider from "../../context/providers/URLContextProvider"; import { getPreambleAndBody } from "./parse"; async function resolveAttachment( @@ -22,11 +23,11 @@ async function resolveAttachment( // URLs if (name.startsWith("http")) { - const response = await extras.fetch(name); - if (response.status !== 200) { - return `Error fetching ${name}: HTTP ${response.status}`; - } - return response.text(); + const items = await new URLContextProvider({}).getContextItems( + name, + extras, + ); + return items.map((item) => item.content).join("\n\n"); } return null; From 94ee240dff2cb25d073a70c08f47b3e46ea707ff Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 5 Nov 2024 23:45:15 -0800 Subject: [PATCH 04/13] completions for prompt files --- extensions/vscode/package.json | 10 +++ extensions/vscode/src/activation/activate.ts | 2 + .../src/lang-server/promptFileCompletions.ts | 79 +++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 extensions/vscode/src/lang-server/promptFileCompletions.ts diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index c38d47b0d..aeb32f078 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -64,6 +64,16 @@ ".continuerc.json" ], "id": "jsonc" + }, + { + "id": "promptLanguage", + "extensions": [ + ".prompt" + ], + "aliases": [ + "Prompt Language" + ], + "configuration": "./prompt-file-language-configuration.json" } ], "configuration": { diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 864b07cc4..909cd449e 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -3,6 +3,7 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; +import { registerPromptFilesCompletionProvider } from "../lang-server/promptFileCompletions"; import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; import { setupInlineTips } from "./inlineTips"; @@ -14,6 +15,7 @@ export async function activateExtension(context: vscode.ExtensionContext) { // Register commands and providers registerQuickFixProvider(); + registerPromptFilesCompletionProvider(context); setupInlineTips(context); const vscodeExtension = new VsCodeExtension(context); diff --git a/extensions/vscode/src/lang-server/promptFileCompletions.ts b/extensions/vscode/src/lang-server/promptFileCompletions.ts new file mode 100644 index 000000000..4fade3c38 --- /dev/null +++ b/extensions/vscode/src/lang-server/promptFileCompletions.ts @@ -0,0 +1,79 @@ +import { getBasename, getLastNPathParts } from "core/util"; +import vscode from "vscode"; + +export function registerPromptFilesCompletionProvider( + context: vscode.ExtensionContext, +) { + let provider = vscode.languages.registerCompletionItemProvider( + "promptLanguage", + { + async provideCompletionItems( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + context: vscode.CompletionContext, + ) { + const linePrefix = document + .lineAt(position) + .text.substr(0, position.character); + + // Check if the last character typed is '@' + if (!linePrefix.endsWith("@")) { + return undefined; + } + + const files = await vscode.workspace.findFiles("**/*"); + + // Provide completion items + return [ + { + label: "terminal", + detail: "Contents of terminal", + sortText: "...", + }, + { + label: "tree", + detail: "File tree of workspace", + sortText: "...", + }, + { + label: "open", + detail: "All open files", + sortText: "...", + }, + { + label: "os", + detail: "Operating system information", + sortText: "...", + }, + { + label: "problems", + detail: "Problems in the current file", + sortText: "...", + }, + { + label: "currentFile", + detail: "Current file", + sortText: "...", + }, + { + label: "repo-map", + detail: "Map of files in your repo", + sortText: "...", + }, + ...files.map((file) => { + return { + label: getBasename(file.path), + detail: getLastNPathParts(file.path, 2), + insertText: file.path, + kind: vscode.CompletionItemKind.File, + }; + }), + ]; + }, + }, + "@", // Trigger completion when '@' is typed + ); + + context.subscriptions.push(provider); +} From 4cbf0592e40cd635942a541093bd4c9924415275 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 6 Nov 2024 11:28:21 -0800 Subject: [PATCH 05/13] better file search for prompt files --- extensions/vscode/src/activation/activate.ts | 2 - .../vscode/src/extension/VsCodeExtension.ts | 8 +++ .../src/lang-server/promptFileCompletions.ts | 38 ++++++++++--- .../src/quickEdit/QuickEditQuickPick.ts | 54 +++++-------------- extensions/vscode/src/util/FileSearch.ts | 42 +++++++++++++++ 5 files changed, 94 insertions(+), 50 deletions(-) create mode 100644 extensions/vscode/src/util/FileSearch.ts diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 909cd449e..864b07cc4 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -3,7 +3,6 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; -import { registerPromptFilesCompletionProvider } from "../lang-server/promptFileCompletions"; import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; import { setupInlineTips } from "./inlineTips"; @@ -15,7 +14,6 @@ export async function activateExtension(context: vscode.ExtensionContext) { // Register commands and providers registerQuickFixProvider(); - registerPromptFilesCompletionProvider(context); setupInlineTips(context); const vscodeExtension = new VsCodeExtension(context); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 2eda0c192..1ccdd9331 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 { registerPromptFilesCompletionProvider } 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,17 @@ export class VsCodeExtension { context.subscriptions.push(this.battery); context.subscriptions.push(monitorBatteryChanges(this.battery)); + // FileSearch + this.fileSearch = new FileSearch(this.ide); + registerPromptFilesCompletionProvider(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 index 4fade3c38..086dbbdc2 100644 --- a/extensions/vscode/src/lang-server/promptFileCompletions.ts +++ b/extensions/vscode/src/lang-server/promptFileCompletions.ts @@ -1,8 +1,12 @@ +import { IDE } from "core"; import { getBasename, getLastNPathParts } from "core/util"; import vscode from "vscode"; +import { FileSearch } from "../util/FileSearch"; export function registerPromptFilesCompletionProvider( context: vscode.ExtensionContext, + fileSearch: FileSearch, + ide: IDE, ) { let provider = vscode.languages.registerCompletionItemProvider( "promptLanguage", @@ -13,16 +17,27 @@ export function registerPromptFilesCompletionProvider( token: vscode.CancellationToken, context: vscode.CompletionContext, ) { - const linePrefix = document - .lineAt(position) - .text.substr(0, position.character); + const linePrefix = + document + .lineAt(position) + .text.substr(0, position.character) + .split(" ") + .pop() || ""; // Check if the last character typed is '@' - if (!linePrefix.endsWith("@")) { + if (!linePrefix.includes("@")) { return undefined; } - const files = await vscode.workspace.findFiles("**/*"); + const searchText = linePrefix.split("@").pop() || ""; + const files = fileSearch.search(searchText).map(({ filename }) => { + return filename; + }); + + if (files.length === 0) { + const openFiles = await ide.getOpenFiles(); + files.push(...openFiles); + } // Provide completion items return [ @@ -62,10 +77,17 @@ export function registerPromptFilesCompletionProvider( sortText: "...", }, ...files.map((file) => { + const workspaceFolder = vscode.workspace.getWorkspaceFolder( + vscode.Uri.file(file), + ); + const relativePath = workspaceFolder + ? vscode.workspace.asRelativePath(file) + : file; + return { - label: getBasename(file.path), - detail: getLastNPathParts(file.path, 2), - insertText: file.path, + label: getBasename(file), + detail: getLastNPathParts(file, 2), + insertText: relativePath, kind: vscode.CompletionItemKind.File, }; }), 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[]; + } +} From 46bb3a57a9dd10451ae59e5fd73ee3e041982377 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 6 Nov 2024 11:36:31 -0800 Subject: [PATCH 06/13] default prompt file --- core/promptFiles/v2/createNewPromptFile.ts | 15 +++++++++++++-- core/util/GlobalContext.ts | 1 + 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/v2/createNewPromptFile.ts index e334a5085..5813533ed 100644 --- a/core/promptFiles/v2/createNewPromptFile.ts +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -1,8 +1,9 @@ import path from "path"; import { IDE } from "../.."; +import { GlobalContext } from "../../util/GlobalContext"; import { DEFAULT_PROMPTS_FOLDER_V2 } from "./getPromptFiles"; -const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file +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 # To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files @@ -14,6 +15,11 @@ version: 2 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, @@ -30,6 +36,11 @@ export async function createNewPromptFileV2( "new-prompt-file.prompt", ); - await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE); + 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/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; }; /** From 863ddaf89614c9132ca897a157550446a9cae5fb Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 16:56:35 -0800 Subject: [PATCH 07/13] syntax highlighting for prompt files --- .../vscode/media/prompt.tmLanguage.json | 64 +++++++++++++++++++ extensions/vscode/package.json | 7 ++ 2 files changed, 71 insertions(+) create mode 100644 extensions/vscode/media/prompt.tmLanguage.json 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 aeb32f078..52029445b 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -76,6 +76,13 @@ "configuration": "./prompt-file-language-configuration.json" } ], + "grammars": [ + { + "language": "promptLanguage", + "scopeName": "source.prompt", + "path": "./media/prompt.tmLanguage.json" + } + ], "configuration": { "title": "Continue", "properties": { From ad1880c760943b4a8d5df3a41f0a486168e4ecfc Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 17:07:22 -0800 Subject: [PATCH 08/13] create multiple new prompt files at once --- core/promptFiles/v2/createNewPromptFile.ts | 34 ++++++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/v2/createNewPromptFile.ts index 5813533ed..aea2f917b 100644 --- a/core/promptFiles/v2/createNewPromptFile.ts +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -6,8 +6,28 @@ 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 -temperature: 0.0 +name: Example +description: Example prompt file version: 2 --- @README.md @@ -30,12 +50,20 @@ export async function createNewPromptFileV2( "No workspace directories found. Make sure you've opened a folder in your IDE.", ); } - const promptFilePath = path.join( + const baseDir = path.join( workspaceDirs[0], promptPath ?? DEFAULT_PROMPTS_FOLDER_V2, - "new-prompt-file.prompt", ); + // 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 From 4caa546b2c84720eaca79c6d35fac569cd6fcd4b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 17:14:20 -0800 Subject: [PATCH 09/13] change prompt file dropdown icon --- extensions/vscode/src/lang-server/promptFileCompletions.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extensions/vscode/src/lang-server/promptFileCompletions.ts b/extensions/vscode/src/lang-server/promptFileCompletions.ts index 086dbbdc2..12ab6f908 100644 --- a/extensions/vscode/src/lang-server/promptFileCompletions.ts +++ b/extensions/vscode/src/lang-server/promptFileCompletions.ts @@ -45,36 +45,43 @@ export function registerPromptFilesCompletionProvider( 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( From 4068900036fbedc9593a91de2c83e58a704fc13b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 17:23:35 -0800 Subject: [PATCH 10/13] include context items in dropdown for prompt files --- .../providers/PromptFilesContextProvider.ts | 5 ++-- core/promptFiles/v2/renderPromptFile.ts | 28 +++++++++---------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/core/context/providers/PromptFilesContextProvider.ts b/core/context/providers/PromptFilesContextProvider.ts index 67a8a9e73..bc9239f1d 100644 --- a/core/context/providers/PromptFilesContextProvider.ts +++ b/core/context/providers/PromptFilesContextProvider.ts @@ -24,10 +24,11 @@ class PromptFilesContextProvider extends BaseContextProvider { ): Promise { const rawContent = await extras.ide.readFile(query); const preamble = parsePreamble(query, rawContent); - const rendered = await renderPromptFileV2(rawContent, extras); + const [contextItems, body] = await renderPromptFileV2(rawContent, extras); return [ + ...contextItems, { - content: rendered, + content: body, name: preamble.name, description: preamble.description, }, diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 51f94a602..243c007dd 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -1,24 +1,25 @@ -import { ContextProviderExtras } from "../.."; +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 { +): Promise { // Context providers const contextProvider = extras.config.contextProviders?.find( (provider) => provider.description.title === name, ); if (contextProvider) { const items = await contextProvider.getContextItems("", extras); - return items.map((item) => item.content).join("\n\n"); + return items; } // Files if (await extras.ide.fileExists(name)) { - const content = await extras.ide.readFile(name); - return `\`\`\`${name}\n${content}\n\`\`\``; + const content = `\`\`\`${name}\n${await extras.ide.readFile(name)}\n\`\`\``; + return [{ name: getBasename(name), content, description: name }]; } // URLs @@ -27,28 +28,25 @@ async function resolveAttachment( name, extras, ); - return items.map((item) => item.content).join("\n\n"); + return items; } - return null; + return []; } export async function renderPromptFileV2( rawContent: string, extras: ContextProviderExtras, -): Promise { +): Promise<[ContextItem[], string]> { const [preamble, body] = getPreambleAndBody(rawContent); - const attachmentPromises: Promise[] = []; + const contextItemsPromises: Promise[] = []; const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { - attachmentPromises.push(resolveAttachment(name, extras)); + contextItemsPromises.push(resolveAttachment(name, extras)); return match; }); - const attachments = (await Promise.all(attachmentPromises)).filter(Boolean); - if (!attachments.length) { - return renderedBody; - } + const contextItems = (await Promise.all(contextItemsPromises)).flat(); - return attachments.join("\n\n") + "\n\n" + renderedBody; + return [contextItems, renderedBody]; } From bd612261f0e49885cd2c13fec4d710450e6ce359 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 18:34:23 -0800 Subject: [PATCH 11/13] remove the edit slash command --- core/commands/slash/index.ts | 6 +- core/config/default.ts | 16 ----- docs/docs/customize/slash-commands.md | 44 +++---------- docs/docs/reference.md | 6 +- .../constants/ServerConstants.kt | 8 --- .../mainInput/CodeBlockComponent.tsx | 63 +------------------ gui/src/components/mainInput/MentionList.tsx | 4 -- gui/src/components/mainInput/TipTapEditor.tsx | 32 ++-------- .../markdown/CodeSnippetPreview.tsx | 34 ++-------- gui/src/hooks/useChatHandler.ts | 15 +---- gui/src/redux/slices/stateSlice.ts | 32 +--------- 11 files changed, 26 insertions(+), 234 deletions(-) diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index f94c6ee05..18008e251 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -1,19 +1,15 @@ 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 OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; -import OnboardSlashCommand from "./onboard"; 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/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 391273943..a78a9689b 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -267,7 +267,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) @@ -281,10 +281,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/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 62dfdf1de..6416771d9 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -12,9 +12,7 @@ import { FolderIcon, FolderOpenIcon, GlobeAltIcon, - HashtagIcon, MagnifyingGlassIcon, - PencilIcon, PlusIcon, SparklesIcon, TrashIcon, @@ -66,9 +64,7 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { web: GlobeAltIcon, "prompt-files": DocumentTextIcon, "repo-map": FolderIcon, - "/edit": PencilIcon, "/clear": TrashIcon, - "/comment": HashtagIcon, "/share": ArrowUpOnSquareIcon, "/cmd": CommandLineIcon, }; diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 2ef4db920..631f59824 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -44,17 +44,12 @@ 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, isJetBrains, isMetaEquivalentKeyPressed, } from "../../util"; -import { - handleJetBrainsMetaKeyPress, - handleMetaKeyPress, -} from "./handleMetaKeyPress"; import { CodeBlockExtension } from "./CodeBlockExtension"; import { SlashCommand } from "./CommandsExtension"; import InputToolbar, { ToolbarOptions } from "./InputToolbar"; @@ -64,6 +59,10 @@ import { getContextProviderDropdownOptions, getSlashCommandDropdownOptions, } from "./getSuggestion"; +import { + handleJetBrainsMetaKeyPress, + handleMetaKeyPress, +} from "./handleMetaKeyPress"; import { ComboBoxItem } from "./types"; const InputBoxDiv = styled.div<{ border?: string }>` @@ -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, }); diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 2a7b6d970..5794b6781 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 c90c044dc..5cd469c87 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -57,13 +57,12 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const active = useSelector((store: RootState) => store.state.active); const activeRef = useRef(active); - const {saveSession} = useHistory(dispatch); + const { saveSession } = useHistory(dispatch); const [save, triggerSave] = useState(false); useEffect(() => { saveSession(false); }, [save]); - useEffect(() => { activeRef.current = active; @@ -219,9 +218,8 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const currentFilePath = await ideMessenger.ide.getCurrentFile(); if (typeof currentFilePath === "string") { - let currentFileContents = await ideMessenger.ide.readFile( - currentFilePath, - ); + let currentFileContents = + await ideMessenger.ide.readFile(currentFilePath); if (usingFreeTrial) { currentFileContents = currentFileContents .split("\n") @@ -294,13 +292,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, From 6888753b20462b2391407231b268ccc423ff440e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 18:41:34 -0800 Subject: [PATCH 12/13] close dropdown after making new prompt file --- gui/src/components/mainInput/MentionList.tsx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 6416771d9..49dcebbbc 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -216,6 +216,15 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { 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", }); From c6c6049a661145fb668c72035e7ecc45ebedcfcf Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 19:20:44 -0800 Subject: [PATCH 13/13] intellisense for prompt file frontmatter --- .../vscode/src/extension/VsCodeExtension.ts | 8 +- .../src/lang-server/promptFileCompletions.ts | 346 +++++++++++++----- 2 files changed, 260 insertions(+), 94 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 1ccdd9331..5534625d9 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -19,7 +19,7 @@ import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvide import { DiffManager } from "../diff/horizontal"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; -import { registerPromptFilesCompletionProvider } from "../lang-server/promptFileCompletions"; +import { registerAllPromptFilesCompletionProviders } from "../lang-server/promptFileCompletions"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { QuickEdit } from "../quickEdit/QuickEditQuickPick"; import { setupRemoteConfigSync } from "../stubs/activation"; @@ -211,7 +211,11 @@ export class VsCodeExtension { // FileSearch this.fileSearch = new FileSearch(this.ide); - registerPromptFilesCompletionProvider(context, this.fileSearch, this.ide); + registerAllPromptFilesCompletionProviders( + context, + this.fileSearch, + this.ide, + ); const quickEdit = new QuickEdit( this.verticalDiffManager, diff --git a/extensions/vscode/src/lang-server/promptFileCompletions.ts b/extensions/vscode/src/lang-server/promptFileCompletions.ts index 12ab6f908..da620f700 100644 --- a/extensions/vscode/src/lang-server/promptFileCompletions.ts +++ b/extensions/vscode/src/lang-server/promptFileCompletions.ts @@ -3,106 +3,268 @@ import { getBasename, getLastNPathParts } from "core/util"; import vscode from "vscode"; import { FileSearch } from "../util/FileSearch"; -export function registerPromptFilesCompletionProvider( +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", - { - 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 = fileSearch.search(searchText).map(({ filename }) => { - return filename; - }); - - if (files.length === 0) { - const openFiles = await 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, - }; - }), - ]; - }, - }, + 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); + } + } + }), + ); +}