From 4f8e907d05052d19acf93955ca4c070ece0e4ba8 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:54:32 -0700 Subject: [PATCH] Improved code linking (#1500) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * allow setting apiBase for bedrock provider * ⚡️ better linking * ✨ new prompt file action * ⚡️ strip from GPT-4 completion --- core/autocomplete/completionProvider.ts | 2 + core/autocomplete/lineStream.ts | 16 ++++ core/config/load.ts | 11 ++- core/config/promptFile.ts | 57 ++++++++++++ core/core.ts | 7 ++ core/llm/llms/Bedrock.ts | 4 +- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 1 + .../toolWindow/ContinueBrowser.kt | 1 + extensions/vscode/src/ideProtocol.ts | 15 ++-- gui/src/components/mainInput/TipTapEditor.tsx | 1 + gui/src/components/mainInput/getSuggestion.ts | 21 ++++- gui/src/components/markdown/LinkableCode.tsx | 87 +++++++++++++++---- 13 files changed, 192 insertions(+), 32 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 3590a2383..873515bf5 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -38,6 +38,7 @@ import { AutocompleteLanguageInfo } from "./languages.js"; import { avoidPathLine, noTopLevelKeywordsMidline, + skipPrefixes, stopAtLines, stopAtRepeatingLines, stopAtSimilarLine, @@ -407,6 +408,7 @@ export async function getTabCompletion( lineGenerator = stopAtLines(lineGenerator, fullStop); lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); + lineGenerator = skipPrefixes(lineGenerator); lineGenerator = noTopLevelKeywordsMidline( lineGenerator, lang.topLevelKeywords, diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 3f552e5f5..14d4c4ab7 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -121,6 +121,22 @@ export async function* stopAtLines( } } +const PREFIXES_TO_SKIP = [""]; +export async function* skipPrefixes(lines: LineStream): LineStream { + let isFirstLine = true; + for await (const line of lines) { + if (isFirstLine) { + const match = PREFIXES_TO_SKIP.find((prefix) => line.startsWith(prefix)); + if (match) { + yield line.slice(match.length); + continue; + } + isFirstLine = false; + } + yield line; + } +} + const LINES_TO_SKIP = [""]; export async function* skipLines(stream: LineStream): LineStream { diff --git a/core/config/load.ts b/core/config/load.ts index 8dd708b7e..0745614d7 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -54,7 +54,11 @@ import { defaultSlashCommandsJetBrains, defaultSlashCommandsVscode, } from "./default.js"; -import { getPromptFiles, slashCommandFromPromptFile } from "./promptFile.js"; +import { + DEFAULT_PROMPTS_FOLDER, + getPromptFiles, + slashCommandFromPromptFile, +} from "./promptFile.js"; const { execSync } = require("child_process"); function resolveSerializedConfig(filepath: string): SerializedContinueConfig { @@ -171,7 +175,10 @@ async function serializedToIntermediateConfig( promptFiles = ( await Promise.all( workspaceDirs.map((dir) => - getPromptFiles(ide, path.join(dir, promptFolder ?? ".prompts")), + getPromptFiles( + ide, + path.join(dir, promptFolder ?? DEFAULT_PROMPTS_FOLDER), + ), ), ) ) diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 9fa66c892..e537dd4d5 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -1,9 +1,12 @@ +import path from "path"; import * as YAML from "yaml"; import type { IDE, SlashCommand } from ".."; import { stripImages } from "../llm/countTokens.js"; import { renderTemplatedString } from "../llm/llms/index.js"; import { getBasename } from "../util/index.js"; +export const DEFAULT_PROMPTS_FOLDER = ".prompts"; + export async function getPromptFiles( ide: IDE, dir: string, @@ -21,6 +24,60 @@ export async function 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 slash command for each prompt in the .prompts folder +# To learn more, see the full .prompt file reference: https://docs.continue.dev/walkthroughs/prompt-files +temperature: 0.0 +--- +{{{ diff }}} + +Give me feedback on the above changes. For each file, you should output a markdown section including the following: +- If you found any problems, an h3 like "❌ " +- If you didn't find any problems, an h3 like "✅ " +- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it +- If you didn't find any problems, you don't need to add anything else + +Here is an example. The example is surrounded in backticks, but your response should not be: + +\`\`\` +### ✅ + +### ❌ + + +\`\`\` + +You should look primarily for the following types of issues, and only mention other problems if they are highly pressing. + +- console.logs that have been left after debugging +- repeated code +- algorithmic errors that could fail under edge cases +- something that could be refactored + +Make sure to review ALL files that were changed, do not skip any. +`; + +export async function createNewPromptFile( + 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, + "new-prompt-file.prompt", + ); + + await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE); + await ide.openFile(promptFilePath); +} + export function slashCommandFromPromptFile( path: string, content: string, diff --git a/core/core.ts b/core/core.ts index 8aa577251..5bc049255 100644 --- a/core/core.ts +++ b/core/core.ts @@ -14,6 +14,7 @@ import { setupLocalMode, setupOptimizedExistingUserMode, } from "./config/onboarding.js"; +import { createNewPromptFile } from "./config/promptFile"; import { addModel, addOpenAIKey, deleteModel } from "./config/util.js"; import { ContinueServerClient } from "./continueServer/stubs/client.js"; import { indexDocs } from "./indexing/docs/index.js"; @@ -190,6 +191,12 @@ export class Core { deleteModel(msg.data.title); this.configHandler.reloadConfig(); }); + on("config/newPromptFile", async (msg) => { + createNewPromptFile( + this.ide, + (await this.config()).experimental?.promptPath, + ); + }); on("config/reload", (msg) => { this.configHandler.reloadConfig(); return this.configHandler.getSerializedConfig(); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 2f7af46a4..c9ddce736 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -24,7 +24,9 @@ class Bedrock extends BaseLLM { constructor(options: LLMOptions) { super(options); - this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; + if (!options.apiBase) { + this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; + } } protected async *_streamComplete( diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 977e4edcd..995c6a961 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -45,6 +45,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { { model: SerializedContinueConfig["models"][number] }, void, ]; + "config/newPromptFile": [undefined, void]; "config/ideSettingsUpdate": [IdeSettings, void]; "config/getBrowserSerialized": [undefined, BrowserSerializedContinueConfig]; "config/deleteModel": [{ title: string }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 441659823..9e22bda32 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -16,6 +16,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "devdata/log", "config/addOpenAiKey", "config/addModel", + "config/newPromptFile", "config/ideSettingsUpdate", "config/getBrowserSerialized", "config/deleteModel", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 159e8471f..e230658fa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -48,6 +48,7 @@ class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false "config/ideSettingsUpdate", "config/getBrowserSerialized", "config/deleteModel", + "config/newPromptFile", "config/reload", "context/getContextItems", "context/loadSubmenuItems", diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index a9181e8cd..80f3e5e8a 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -365,15 +365,12 @@ class VsCodeIde implements IDE { new vscode.Position(startLine, 0), new vscode.Position(endLine, 0), ); - openEditorAndRevealRange(filepath, range).then(() => { - // TODO: Highlight lines - // this.ideUtils.highlightCode( - // { - // filepath, - // range, - // }, - // "#fff1" - // ); + openEditorAndRevealRange(filepath, range).then((editor) => { + // Select the lines + editor.selection = new vscode.Selection( + new vscode.Position(startLine, 0), + new vscode.Position(endLine, 0), + ); }); } diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 19dea7770..04e3f8c62 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -374,6 +374,7 @@ function TipTapEditor(props: TipTapEditorProps) { availableSlashCommandsRef, onClose, onOpen, + ideMessenger, ), renderText: (props) => { return props.node.attrs.label; diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index 5e7dd605b..7fb953b10 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -161,10 +161,26 @@ export function getCommandSuggestion( availableSlashCommandsRef: MutableRefObject, onClose: () => void, onOpen: () => void, + ideMessenger: IIdeMessenger, ) { const items = async ({ query }) => { + 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", + }, + ]; return ( - availableSlashCommandsRef.current?.filter((slashCommand) => { + options.filter((slashCommand) => { const sc = slashCommand.title.substring(1).toLowerCase(); const iv = query.toLowerCase(); return sc.startsWith(iv); @@ -175,7 +191,8 @@ export function getCommandSuggestion( id: provider.title, title: provider.title, label: provider.title, - type: "slashCommand" as ComboBoxItemType, + type: (provider.type ?? "slashCommand") as ComboBoxItemType, + action: provider.action, })); }; return getSuggestion(items, undefined, onClose, onOpen); diff --git a/gui/src/components/markdown/LinkableCode.tsx b/gui/src/components/markdown/LinkableCode.tsx index 8f323a003..24c85426d 100644 --- a/gui/src/components/markdown/LinkableCode.tsx +++ b/gui/src/components/markdown/LinkableCode.tsx @@ -1,3 +1,4 @@ +import { RangeInFile } from "core"; import { useContext, useEffect, useState } from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; @@ -24,14 +25,13 @@ function LinkableCode(props: any) { const [linkingDone, setLinkingDone] = useState(false); const [isLink, setIsLink] = useState(false); - const [filepath, setFilepath] = useState(""); - const [line, setLine] = useState(0); + const [rif, setRif] = useState(undefined); useEffect(() => { if (linkingDone) return; setLinkingDone(true); - // Get filename from props.children + // Get content of the code tag let content: string | undefined = undefined; if (typeof props.children === "string") { content = props.children; @@ -44,7 +44,7 @@ function LinkableCode(props: any) { } if (!content) return; - // Check if this is a real file + // Match filepath with context items const contextItemFileMatch = contextItems.find( (item) => ["file", "codebase", "folder"].includes(item.id.providerTitle) && @@ -58,38 +58,89 @@ function LinkableCode(props: any) { .split(" (")[1] .split(")")[0] .split("-"); - setFilepath(contextItemFileMatch.description.split(" (")[0]); - setLine(parseInt(startLine)); + const filepath = contextItemFileMatch.description.split(" (")[0]; + setRif({ + filepath, + range: { + start: { + line: 0, + character: 0, + }, + end: { + line: 0, + character: 0, + }, + }, + }); + return; } else { - setFilepath(contextItemFileMatch.description.split(" (")[0]); - setLine(0); + // If no line number, just open the file + setRif({ + filepath: contextItemFileMatch.description.split(" (")[0], + range: { + start: { + line: 0, + character: 0, + }, + end: { + line: 0, + character: 0, + }, + }, + }); + return; } } - if (content.length > 6) { + // Try to match the content with a line in a file + if (content.length > 8) { const contextItemContentMatch = contextItems.find( (item) => ["file", "codebase", "folder"].includes(item.id.providerTitle) && item.content.includes(content), ); if (contextItemContentMatch) { + const line = contextItemContentMatch.content + .split("\n") + .slice(1) // code block fence + .findIndex((line) => line.includes(content)); + + const [filepath, rest] = + contextItemContentMatch.description.split(" ("); + const [startLine, endLine] = rest.split(")")[0]?.split("-") || [ + "0", + "0", + ]; + const start = parseInt(startLine); + const end = parseInt(endLine); + setIsLink(true); - setFilepath(contextItemContentMatch.description.split(" (")[0]); - setLine( - contextItemContentMatch.content - .split("\n") - .findIndex((line) => line.includes(content)) + 1, - ); + setRif({ + filepath, + range: { + start: { + line: start + line, + character: 0, + }, + end: { + line: start + line + 1, + character: 0, + }, + }, + }); + + console.log("MATCH: ", content, contextItemContentMatch, line); } } }, [linkingDone, contextItems]); const onClick = () => { if (!isLink) return; + if (!rif) return; ideMessenger.post("showLines", { - filepath, - startLine: line, - endLine: line + 1, + filepath: rif.filepath, + startLine: rif.range.start.line, + endLine: rif.range.end.line, }); };