From 4348067e83cacf43d8829083a46a25fbed1ac0e1 Mon Sep 17 00:00:00 2001 From: Pranjal Rana <129268721+PRANJALRANA11@users.noreply.github.com> Date: Thu, 31 Oct 2024 20:51:30 +0530 Subject: [PATCH 01/27] add check for ignore for recently edited file --- core/core.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index 8ce7c7a5d..db965dec1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,6 +29,7 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; +import { walkDir } from "./indexing/walkDir"; export class Core { // implements IMessenger @@ -704,8 +705,12 @@ export class Core { return { url }; }); - on("didChangeActiveTextEditor", ({ data: { filepath } }) => { - recentlyEditedFilesCache.set(filepath, filepath); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { + const dirs = await this.ide.getWorkspaceDirs(); + const paths = await walkDir(dirs[0], this.ide); + if (paths.includes(filepath)) { + recentlyEditedFilesCache.set(filepath, filepath); + } }); } From d9af61f4471b6aa7fe21554feb5926d143e5c4f9 Mon Sep 17 00:00:00 2001 From: Pranjal Rana <129268721+PRANJALRANA11@users.noreply.github.com> Date: Fri, 1 Nov 2024 12:16:55 +0530 Subject: [PATCH 02/27] Add memoization for the walk-dir --- core/core.ts | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/core/core.ts b/core/core.ts index db965dec1..11b5ddb01 100644 --- a/core/core.ts +++ b/core/core.ts @@ -704,16 +704,41 @@ export class Core { const url = await getAuthUrlForTokenPage(); return { url }; }); - on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const dirs = await this.ide.getWorkspaceDirs(); - const paths = await walkDir(dirs[0], this.ide); - if (paths.includes(filepath)) { + let dirs = await this.ide.getWorkspaceDirs(); + let memoizedFunction = await this.memoizedFunction(dirs); + if (memoizedFunction.includes(filepath)) { + console.log("yep running"); recentlyEditedFilesCache.set(filepath, filepath); } }); } + private memoize Promise>( + fn: T, + ): (...args: Parameters) => Promise> { + const cache = new Map>>(); + + return async function (...args: Parameters): Promise> { + const key = JSON.stringify(args); + if (cache.has(key)) { + return cache.get(key) as Promise>; + } + const result = await fn(...args); + cache.set(key, Promise.resolve(result)); + return result; + }; + } + + private async checkIgnoredFiles(dirs: string[]): Promise { + console.log("called"); + const paths = await walkDir(dirs[0], this.ide); + return paths; + } + + // Memoize the async checkIgnoredFiles function + memoizedFunction = this.memoize(this.checkIgnoredFiles.bind(this)); + private indexingCancellationController: AbortController | undefined; private async refreshCodebaseIndex(dirs: string[]) { From 6f4b0f18adbf0da8a74d5248de72b4dfee9cd2c7 Mon Sep 17 00:00:00 2001 From: Pranjal Rana <129268721+PRANJALRANA11@users.noreply.github.com> Date: Sat, 2 Nov 2024 10:46:39 +0530 Subject: [PATCH 03/27] fix rel-path for ignore --- core/core.ts | 38 ++++++++------------------------------ 1 file changed, 8 insertions(+), 30 deletions(-) diff --git a/core/core.ts b/core/core.ts index 11b5ddb01..a3f59ec8e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,7 +29,9 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import { walkDir } from "./indexing/walkDir"; +import ignore from "ignore"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; +import path from "path"; export class Core { // implements IMessenger @@ -704,41 +706,17 @@ export class Core { const url = await getAuthUrlForTokenPage(); return { url }; }); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - let dirs = await this.ide.getWorkspaceDirs(); - let memoizedFunction = await this.memoizedFunction(dirs); - if (memoizedFunction.includes(filepath)) { - console.log("yep running"); + const ignoreInstance = ignore().add(defaultIgnoreFile); + let rootDirectory = await this.ide.getWorkspaceDirs(); + const relativeFilePath = path.relative(rootDirectory[0], filepath); + if (!ignoreInstance.ignores(relativeFilePath)) { recentlyEditedFilesCache.set(filepath, filepath); } }); } - private memoize Promise>( - fn: T, - ): (...args: Parameters) => Promise> { - const cache = new Map>>(); - - return async function (...args: Parameters): Promise> { - const key = JSON.stringify(args); - if (cache.has(key)) { - return cache.get(key) as Promise>; - } - const result = await fn(...args); - cache.set(key, Promise.resolve(result)); - return result; - }; - } - - private async checkIgnoredFiles(dirs: string[]): Promise { - console.log("called"); - const paths = await walkDir(dirs[0], this.ide); - return paths; - } - - // Memoize the async checkIgnoredFiles function - memoizedFunction = this.memoize(this.checkIgnoredFiles.bind(this)); - private indexingCancellationController: AbortController | undefined; private async refreshCodebaseIndex(dirs: string[]) { From f88f28b8551e95e4eb346fafa68d6223f9017d5a Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 4 Nov 2024 21:55:08 -0800 Subject: [PATCH 04/27] feat: impl /multifile-edit --- core/commands/slash/index.ts | 4 +- core/commands/slash/multifileEdit.ts | 67 +++++++++++++++++++ core/protocol/ideWebview.ts | 14 ++-- .../continue/IdeProtocolClient.kt | 2 +- extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- extensions/vscode/src/VsCodeIde.ts | 2 +- .../vscode/src/diff/vertical/manager.ts | 24 ------- .../vscode/src/extension/VsCodeMessenger.ts | 33 ++++++++- extensions/vscode/src/util/ideUtils.ts | 6 +- extensions/vscode/src/util/util.ts | 20 +++--- .../components/markdown/CodeBlockToolbar.tsx | 29 ++++---- 12 files changed, 146 insertions(+), 61 deletions(-) create mode 100644 core/commands/slash/multifileEdit.ts diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index f94c6ee05..472684a7e 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -4,9 +4,10 @@ import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; +import MultiFileEditSlashCommand from "./multifileEdit"; +import OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; -import OnboardSlashCommand from "./onboard"; export default [ DraftIssueCommand, @@ -18,4 +19,5 @@ export default [ CommitMessageCommand, ReviewMessageCommand, OnboardSlashCommand, + MultiFileEditSlashCommand, ]; diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts new file mode 100644 index 000000000..d045e0a2f --- /dev/null +++ b/core/commands/slash/multifileEdit.ts @@ -0,0 +1,67 @@ +import { SlashCommand } from "../.."; +import { stripImages } from "../../llm/images"; + +const MultiFileEditSlashCommand: SlashCommand = { + name: "multifile-edit", + description: "Edit multiple files in the codebase at once", + run: async function* ({ llm, contextItems, input }) { + const filesToEditStr = contextItems.map((item) => item.content).join("\n"); + + const content = createPrompt(filesToEditStr, input); + + for await (const chunk of llm.streamChat([{ role: "user", content }])) { + yield stripImages(chunk.content); + } + }, +}; + +function createPrompt(filesToEditStr: string, input: string): string { + return ` +You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: + +1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" +2. When providing instructions, if a user needs to interact with a CLI, walk them through each step +2. Perform file edits in a logical, sequential ordering +3. For each file edit, provide a brief explanation of the changes +4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. + a. When creating new files, also inlcude the filname in the language specifier of the code block. +6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits + +Remember to be concise and focus on the code changes and their impact. + +Here's an example of how your response should be structured: + + +I'll make the following changes to implement feature X: + +1. First, I'll modify file1.js to add a new function: +\`\`\`javascript /path/to/file1.js +// Entire content of file1.js or changes to be made +\`\`\` + +2. Next, let's create a new test file: +\`\`\`javascript /path/to/file1.test.js +# Entire content of file2.py or changes to be made +\`\`\` + +Summary: +- [Sequential overview of the most important 3-5 edits] + + +Now, let's make the changes based on the engineer's request: + + +${input} + + +Here are the files to edit: + + +${filesToEditStr} + + +Please provide the multi-file edit details based on the engineer's request. + `; +} + +export default MultiFileEditSlashCommand; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 0526fb499..cce7c6cb0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -1,8 +1,9 @@ -import type { RangeInFileWithContents } from "../commands/util.js"; -import type { ContextSubmenuItem, MessageContent } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; +import type { RangeInFileWithContents } from "../commands/util.js"; +import type { ContextSubmenuItem, MessageContent } from "../index.js"; + export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { onLoad: [ undefined, @@ -17,8 +18,13 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; // We pass the `curSelectedModel` because we currently cannot access the // default model title in the GUI from JB - applyToCurrentFile: [ - { text: string; streamId: string; curSelectedModelTitle: string }, + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath: string; + }, void, ]; showTutorial: [undefined, void]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 1295d0002..17c89ec85 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -632,7 +632,7 @@ class IdeProtocolClient( } } - "applyToCurrentFile" -> { + "applyToFile" -> { val msg = data as Map; val text = msg["text"] as String val curSelectedModelTitle = msg["curSelectedModelTitle"] as String diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 44ade3c05..c39c6391c 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.227", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.225", + "version": "0.9.227", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index cc2a41fb6..231f856c1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.225", + "version": "0.9.227", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 43911c6f8..c36516018 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -384,7 +384,7 @@ class VsCodeIde implements IDE { } async openFile(path: string): Promise { - this.ideUtils.openFile(path); + await this.ideUtils.openFile(path); } async showLines( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index c6f3c2aa7..88ed3831f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -257,30 +257,6 @@ export class VerticalDiffManager { } } - /** - * Streams an edit to the current document based on user input and model output. - * - * @param input - The user's input or instruction for the edit. - * @param modelTitle - The title of the language model to be used. - * @param [onlyOneInsertion] - Optional flag to limit the edit to a single insertion. - * @param [quickEdit] - Optional string indicating if this is a quick edit. - * @param [range] - Optional range to use instead of the highlighted text. Note that the `quickEdit` - * property currently can't be passed with `range` since it assumes there is an - * active selection. - * - * This method performs the following steps: - * 1. Sets up the editor context for the diff. - * 2. Determines the range of text to be edited. - * 3. Clears any existing diff handlers for the file. - * 4. Creates a new vertical diff handler. - * 5. Prepares the context (prefix and suffix) for the language model. - * 6. Streams the diff lines from the language model. - * 7. Applies the changes to the document. - * 8. Sets up a listener for subsequent user edits. - * - * The method handles various edge cases, such as quick edits and existing diffs, - * and manages the lifecycle of diff handlers and document change listeners. - */ async streamEdit( input: string, modelTitle: string | undefined, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 483ff1603..954f30349 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -29,6 +29,7 @@ import { import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { getFullyQualifiedPath } from "../util/util"; /** * A shared messenger class between Core and Webview @@ -85,7 +86,11 @@ export class VsCodeMessenger { ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { - this.ide.openFile(msg.data.filepath); + const fullPath = getFullyQualifiedPath(msg.data.filepath); + + if (fullPath) { + this.ide.openFile(fullPath); + } }); this.onWebview("vscode/openMoveRightMarkdown", (msg) => { @@ -153,9 +158,33 @@ export class VsCodeMessenger { await vscode.commands.executeCommand("continue.rejectDiff", filepath); }); - this.onWebview("applyToCurrentFile", async ({ data }) => { + this.onWebview("applyToFile", async ({ data }) => { + const fullPath = getFullyQualifiedPath(data.filepath); + + if (!fullPath) { + return; + } + + const fileExists = await this.ide.fileExists(fullPath); + + // If it's a new file, no need to apply, just write directly + if (!fileExists) { + await this.ide.writeFile(fullPath, data.text); + await this.ide.openFile(fullPath); + + await webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "done", + }); + + return; + } + + await this.ide.openFile(fullPath); + // Get active text editor const editor = vscode.window.activeTextEditor; + if (!editor) { vscode.window.showErrorMessage("No active editor to apply edits to"); return; diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 14ebd9ed2..6ebb9c1a1 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; @@ -158,7 +156,7 @@ export class VsCodeIdeUtils { async openFile(filepath: string, range?: vscode.Range) { // vscode has a builtin open/get open files - return openEditorAndRevealRange( + return await openEditorAndRevealRange( await this.resolveAbsFilepathInWorkspace(filepath), range, vscode.ViewColumn.One, diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 2d0ae72a7..4ac832455 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -124,14 +124,16 @@ export function getExtensionVersion(): string { } export function getFullyQualifiedPath(filepath?: string) { - if (filepath && !path.isAbsolute(filepath)) { - const workspaceFolders = vscode.workspace.workspaceFolders; - if (workspaceFolders && workspaceFolders.length > 0) { - return path.join(workspaceFolders[0].uri.fsPath, filepath); - } else { - vscode.window.showErrorMessage( - "Unable to resolve filepath: no workspace folder found", - ); - } + if (!filepath) return; + if (path.isAbsolute(filepath)) return filepath; + + const workspaceFolders = vscode.workspace.workspaceFolders; + + if (workspaceFolders && workspaceFolders.length > 0) { + return path.join(workspaceFolders[0].uri.fsPath, filepath); + } else { + vscode.window.showErrorMessage( + "Unable to resolve filepath: no workspace folder found", + ); } } diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index b5380e26d..a01dd78d2 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -176,19 +176,24 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { if (isTerminal) { await ideMessenger.ide.runCommand(getTerminalCommand(props.text)); - } else { - ideMessenger.post("applyToCurrentFile", { - curSelectedModelTitle: defaultModel.title, - text: props.text, - streamId: streamIdRef.current, - }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "streaming", - }), - ); + return; } + + if (!props.filepath) return; + + dispatch( + updateApplyState({ + streamId: streamIdRef.current, + status: "streaming", + }), + ); + + ideMessenger.post("applyToFile", { + curSelectedModelTitle: defaultModel.title, + text: props.text, + streamId: streamIdRef.current, + filepath: props.filepath, + }); } function onClickHeader() { From 2593a4e3e619130ed214f20d5fa7e181ae76a297 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 5 Nov 2024 10:35:42 -0800 Subject: [PATCH 05/27] Update multifileEdit.ts --- core/commands/slash/multifileEdit.ts | 50 +++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index d045e0a2f..797f27bf2 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -1,13 +1,43 @@ import { SlashCommand } from "../.."; +import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util"; import { stripImages } from "../../llm/images"; const MultiFileEditSlashCommand: SlashCommand = { name: "multifile-edit", description: "Edit multiple files in the codebase at once", - run: async function* ({ llm, contextItems, input }) { - const filesToEditStr = contextItems.map((item) => item.content).join("\n"); + run: async function* ({ llm, contextItems, selectedCode, input, ide }) { + const selectedCodeStr = ( + await Promise.all( + selectedCode.map(async (item) => { + // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` + const [filepath, rangeStr] = item.filepath.split(" "); + const fullPath = getFullyQualifiedPath(filepath); - const content = createPrompt(filesToEditStr, input); + if (!fullPath) { + return ""; + } + + const codeStr = await ide.readRangeInFile(fullPath, item.range); + + // Include the filepath so the model can map it correctly with codeblock outputs + return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``; + }), + ) + ).join("\n"); + + const fileContextItemsStr = contextItems + .filter((item) => item.uri?.type === "file") + .map((item) => item.content) + .join("\n"); + + const filesToEditStr = fileContextItemsStr + "\n" + selectedCodeStr; + + const additionalContextStr = contextItems + .filter((item) => item.uri?.type !== "file") + .map((item) => `${item.description}: ${item.content}`) + .join("\n"); + + const content = createPrompt(filesToEditStr, additionalContextStr, input); for await (const chunk of llm.streamChat([{ role: "user", content }])) { yield stripImages(chunk.content); @@ -15,7 +45,11 @@ const MultiFileEditSlashCommand: SlashCommand = { }, }; -function createPrompt(filesToEditStr: string, input: string): string { +function createPrompt( + filesToEditStr: string, + additionalContextStr: string, + input: string, +): string { return ` You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: @@ -54,12 +88,18 @@ Now, let's make the changes based on the engineer's request: ${input} -Here are the files to edit: +Here are the files to base your edits on: ${filesToEditStr} +And here is any additional context the engineer has provided: + + +${additionalContextStr} + + Please provide the multi-file edit details based on the engineer's request. `; } From 17081dfa77caa704489cca82ad5b92bd08379f80 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 5 Nov 2024 21:25:58 -0800 Subject: [PATCH 06/27] update `getFullyQualifiedPath` to use ide --- core/commands/slash/multifileEdit.ts | 3 ++- extensions/vscode/src/commands.ts | 14 ++++++++++---- extensions/vscode/src/extension/VsCodeMessenger.ts | 4 ++-- extensions/vscode/src/util/util.ts | 12 ++++-------- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index 797f27bf2..ffda6b703 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -1,5 +1,6 @@ import { SlashCommand } from "../.."; import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util"; +import { VsCodeIde } from "../../../extensions/vscode/src/VsCodeIde"; import { stripImages } from "../../llm/images"; const MultiFileEditSlashCommand: SlashCommand = { @@ -11,7 +12,7 @@ const MultiFileEditSlashCommand: SlashCommand = { selectedCode.map(async (item) => { // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` const [filepath, rangeStr] = item.filepath.split(" "); - const fullPath = getFullyQualifiedPath(filepath); + const fullPath = getFullyQualifiedPath(ide as VsCodeIde, filepath); if (!fullPath) { return ""; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..41d047730 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -34,6 +34,7 @@ import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { VsCodeIde } from "./VsCodeIde"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -188,7 +189,7 @@ function focusGUI() { // Copy everything over from extension.ts const commandsMap: ( - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, @@ -261,8 +262,10 @@ const commandsMap: ( if (fullPath instanceof vscode.Uri) { fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - fullPath = getFullyQualifiedPath(fullPath); + console.warn(`Unable to resolve filepath: ${newFilepath}`); } verticalDiffManager.clearForFilepath(fullPath, true); @@ -278,8 +281,11 @@ const commandsMap: ( if (fullPath instanceof vscode.Uri) { fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - fullPath = getFullyQualifiedPath(fullPath); + console.warn(`Unable to resolve filepath: ${newFilepath}`); + return; } verticalDiffManager.clearForFilepath(fullPath, false); @@ -807,7 +813,7 @@ const commandsMap: ( export function registerAllCommands( context: vscode.ExtensionContext, - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 954f30349..d7ed63a5f 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -86,7 +86,7 @@ export class VsCodeMessenger { ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { - const fullPath = getFullyQualifiedPath(msg.data.filepath); + const fullPath = getFullyQualifiedPath(this.ide, msg.data.filepath); if (fullPath) { this.ide.openFile(fullPath); @@ -159,7 +159,7 @@ export class VsCodeMessenger { }); this.onWebview("applyToFile", async ({ data }) => { - const fullPath = getFullyQualifiedPath(data.filepath); + const fullPath = getFullyQualifiedPath(ide, data.filepath); if (!fullPath) { return; diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 4ac832455..9b5c11bfe 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -1,6 +1,7 @@ const os = require("node:os"); import path from "node:path"; import * as vscode from "vscode"; +import { VsCodeIde } from "../VsCodeIde"; function charIsEscapedAtIndex(index: number, str: string): boolean { if (index === 0) { @@ -123,17 +124,12 @@ export function getExtensionVersion(): string { return extension?.packageJSON.version || "0.1.0"; } -export function getFullyQualifiedPath(filepath?: string) { - if (!filepath) return; - if (path.isAbsolute(filepath)) return filepath; +export function getFullyQualifiedPath(ide: VsCodeIde, filepath: string) { + if (ide.ideUtils.path.isAbsolute(filepath)) return filepath; const workspaceFolders = vscode.workspace.workspaceFolders; if (workspaceFolders && workspaceFolders.length > 0) { - return path.join(workspaceFolders[0].uri.fsPath, filepath); - } else { - vscode.window.showErrorMessage( - "Unable to resolve filepath: no workspace folder found", - ); + return ide.ideUtils.path.join(workspaceFolders[0].uri.fsPath, filepath); } } From f9325b36baf4f2d1fbace6fc1133e8dae7c24176 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 09:05:56 -0800 Subject: [PATCH 07/27] hideGUI command and first take on cmd L and cmd shift L --- gui/src/components/mainInput/TipTapEditor.tsx | 103 +++++++++++------- 1 file changed, 65 insertions(+), 38 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index f801aa348..55ff9db39 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -245,8 +245,8 @@ function TipTapEditor(props: TipTapEditorProps) { const timer = setTimeout(() => { setHasDefaultModel( !!defaultModel && - defaultModel.apiKey !== undefined && - defaultModel.apiKey !== "", + defaultModel.apiKey !== undefined && + defaultModel.apiKey !== "", ); }, 3500); @@ -311,6 +311,10 @@ function TipTapEditor(props: TipTapEditorProps) { : "Ask a follow-up"; } + const hideGUI = useCallback(() => { + ideMessenger.post("hideGUI", undefined); + }, [ideMessenger]); + const editor: Editor = useEditor({ extensions: [ Document, @@ -397,6 +401,29 @@ function TipTapEditor(props: TipTapEditorProps) { return true; } }, + "Mod-L": () => { + if (!editorFocusedRef.current) { + if (historyLength === 0) { + hideGUI(); + } else { + saveSession(); + + setTimeout(() => { + editor?.commands.blur(); + editor?.commands.focus("end"); + }, 20); + } + return true; + } + return false; + }, + "Mod-Shift-L": () => { + if (!editorFocusedRef.current) { + hideGUI(); + return true; + } + return false; + }, "Shift-Enter": () => this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), @@ -449,38 +476,38 @@ function TipTapEditor(props: TipTapEditorProps) { Text, props.availableContextProviders.length ? Mention.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }) : undefined, props.availableSlashCommands.length ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) : undefined, CodeBlockExtension, ], @@ -573,6 +600,7 @@ function TipTapEditor(props: TipTapEditorProps) { if (isMetaEquivalentKeyPressed(e)) { const { key, code } = e; + const isWebEnv = isWebEnvironment(); const text = editor.state.doc.textBetween( editor.state.selection.from, @@ -705,7 +733,7 @@ function TipTapEditor(props: TipTapEditorProps) { return; } if (historyLength > 0) { - saveSession(); + await saveSession(); } setTimeout(() => { editor?.commands.blur(); @@ -734,12 +762,12 @@ function TipTapEditor(props: TipTapEditorProps) { if (!props.isMainInput) { return; } - saveSession(); + await saveSession(); setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor, props.isMainInput, saveSession], ); useWebviewListener( @@ -756,9 +784,8 @@ function TipTapEditor(props: TipTapEditorProps) { rif.filepath, await ideMessenger.ide.getWorkspaceDirs(), ); - const rangeStr = `(${rif.range.start.line + 1}-${ - rif.range.end.line + 1 - })`; + const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1 + })`; const item: ContextItemWithId = { content: rif.contents, name: `${basename} ${rangeStr}`, @@ -881,7 +908,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { From 9f1ea9a04c1de6d4088ec605ed791e8a1f9e65cd Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 09:06:36 -0800 Subject: [PATCH 08/27] hide GUI and cmd L first take p2 --- core/protocol/ide.ts | 1 + core/util/messageIde.ts | 6 +- extensions/vscode/src/commands.ts | 1122 ++++++++--------- .../vscode/src/extension/VsCodeMessenger.ts | 3 + 4 files changed, 564 insertions(+), 568 deletions(-) diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index eda6bebfb..6a9f177d0 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -89,6 +89,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; logoutOfControlPlane: [undefined, void]; pathSep: [undefined, string]; + hideGUI: [undefined, void]; }; export type ToWebviewOrCoreFromIdeProtocol = { diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 0ed9f63d2..15ecc019f 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -27,7 +27,7 @@ export class MessageIde implements IDE { messageType: T, callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], ) => void, - ) {} + ) { } pathSep(): Promise { return this.request("pathSep", undefined); @@ -200,4 +200,8 @@ export class MessageIde implements IDE { async getBranch(dir: string): Promise { return this.request("getBranch", { dir }); } + + async hideGUI(): Promise { + await this.request("hideGUI", undefined); + } } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..8dd057445 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -212,598 +212,586 @@ const commandsMap: ( core, editDecorationManager, ) => { - /** - * Streams an inline edit to the vertical diff manager. - * - * This function retrieves the configuration, determines the appropriate model title, - * increments the FTC count, and then streams an edit to the - * vertical diff manager. - * - * @param promptName - The key for the prompt in the context menu configuration. - * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. - * @param [range] - Optional. The range to edit if provided. - * @returns - */ - async function streamInlineEdit( - promptName: keyof ContextMenuConfig, - fallbackPrompt: string, - onlyOneInsertion?: boolean, - range?: vscode.Range, - ) { - const config = await configHandler.loadConfig(); + /** + * Streams an inline edit to the vertical diff manager. + * + * This function retrieves the configuration, determines the appropriate model title, + * increments the FTC count, and then streams an edit to the + * vertical diff manager. + * + * @param promptName - The key for the prompt in the context menu configuration. + * @param fallbackPrompt - The prompt to use if the configured prompt is not available. + * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. + * @param [range] - Optional. The range to edit if provided. + * @returns + */ + async function streamInlineEdit( + promptName: keyof ContextMenuConfig, + fallbackPrompt: string, + onlyOneInsertion?: boolean, + range?: vscode.Range, + ) { + const config = await configHandler.loadConfig(); - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ); - - const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - - sidebar.webviewProtocol.request("incrementFtc", undefined); - - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, - onlyOneInsertion, - undefined, - range, - ); - } - - return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("acceptDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else { - fullPath = getFullyQualifiedPath(fullPath); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else { - fullPath = getFullyQualifiedPath(fullPath); - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("acceptVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); - }, - "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("rejectVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); - }, - "continue.quickFix": async ( - range: vscode.Range, - diagnosticMessage: string, - ) => { - captureCommandTelemetry("quickFix"); - - const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - // Passthrough for telemetry purposes - "continue.defaultQuickAction": async (args: QuickEditShowParams) => { - captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); - }, - "continue.customQuickActionSendToChat": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionSendToChat"); - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - "continue.customQuickActionStreamInlineEdit": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionStreamInlineEdit"); - - streamInlineEdit("docstring", prompt, false, range); - }, - "continue.codebaseForceReIndex": async () => { - core.invoke("index/forceReIndex", undefined); - }, - "continue.rebuildCodebaseIndex": async () => { - core.invoke("index/forceReIndex", { shouldClearIndexes: true }); - }, - "continue.docsIndex": async () => { - core.invoke("context/indexDocs", { reIndex: false }); - }, - "continue.docsReIndex": async () => { - core.invoke("context/indexDocs", { reIndex: true }); - }, - "continue.focusContinueInput": async () => { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - }, - "continue.focusContinueInputWithoutClear": async () => { - const fullScreenTab = getFullScreenTab(); - - const isContinueInputFocused = await sidebar.webviewProtocol.request( - "isContinueInputFocused", + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", undefined, ); - if (isContinueInputFocused) { - // Handle closing the GUI only if we are focused on the input - if (fullScreenTab) { - fullScreenPanel?.dispose(); - } - } else { - // Handle opening the GUI otherwise - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); + const modelTitle = + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + + sidebar.webviewProtocol.request("incrementFtc", undefined); + + await verticalDiffManager.streamEdit( + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + modelTitle, + undefined, + onlyOneInsertion, + undefined, + range, + ); + } + + return { + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; } else { - // focus fullscreen - fullScreenPanel?.reveal(); + fullPath = getFullyQualifiedPath(fullPath); } - sidebar.webviewProtocol?.request( - "focusContinueInputWithoutClear", + verticalDiffManager.clearForFilepath(fullPath, true); + await diffManager.acceptDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else { + fullPath = getFullyQualifiedPath(fullPath); + } + + verticalDiffManager.clearForFilepath(fullPath, false); + await diffManager.rejectDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("acceptVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); + }, + "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("rejectVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); + }, + "continue.quickFix": async ( + range: vscode.Range, + diagnosticMessage: string, + ) => { + captureCommandTelemetry("quickFix"); + + const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); + + streamInlineEdit("docstring", prompt, false, range); + }, + "continue.codebaseForceReIndex": async () => { + core.invoke("index/forceReIndex", undefined); + }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", { reIndex: false }); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", { reIndex: true }); + }, + "continue.focusContinueInput": async () => { + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", undefined, ); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); - const fullScreenTab = getFullScreenTab(); - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { - // focus fullscreen - fullScreenPanel?.reveal(); - } - - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } - - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), - ); - - const highlightedCode = getCurrentlyHighlightedCode(true)!; - await sidebar.webviewProtocol?.request("startEditMode", { - highlightedCode, - }); - - // Un-select the current selection - editor.selection = new vscode.Selection( - editor.selection.anchor, - editor.selection.anchor, - ); - - setTimeout(() => { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); - }, - "continue.exitEditMode": async () => { - captureCommandTelemetry("exitEditMode"); - await sidebar.webviewProtocol?.request("exitEditMode", undefined); - }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - let linesOfCode = undefined; - if (args.range) { - linesOfCode = args.range.end.line - args.range.start.line; - } - captureCommandTelemetry("quickEdit", { - linesOfCode, - }); - quickEdit.show(args); - }, - "continue.writeCommentsForCode": async () => { - captureCommandTelemetry("writeCommentsForCode"); - - streamInlineEdit( - "comment", - "Write comments for this code. Do not change anything about the code itself.", - ); - }, - "continue.writeDocstringForCode": async () => { - captureCommandTelemetry("writeDocstringForCode"); - - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - ); - }, - "continue.fixCode": async () => { - captureCommandTelemetry("fixCode"); - - streamInlineEdit( - "fix", - "Fix this code. If it is already 100% correct, simply rewrite the code.", - ); - }, - "continue.optimizeCode": async () => { - captureCommandTelemetry("optimizeCode"); - streamInlineEdit("optimize", "Optimize this code"); - }, - "continue.fixGrammar": async () => { - captureCommandTelemetry("fixGrammar"); - streamInlineEdit( - "fixGrammar", - "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", - ); - }, - "continue.viewLogs": async () => { - captureCommandTelemetry("viewLogs"); - - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } - - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); - }, - "continue.debugTerminal": async () => { - captureCommandTelemetry("debugTerminal"); - - const terminalContents = await ide.getTerminalContents(); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - sidebar.webviewProtocol?.request("userInput", { - input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, - }); - }, - "continue.hideInlineTip": () => { - vscode.workspace - .getConfiguration(EXTENSION_NAME) - .update("showInlineTip", false, vscode.ConfigurationTarget.Global); - }, - - // Commands without keyboard shortcuts - "continue.addModel": () => { - captureCommandTelemetry("addModel"); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("addModel", undefined); - }, - "continue.openSettingsUI": () => { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("openSettings", undefined); - }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, - "continue.newSession": () => { - sidebar.webviewProtocol?.request("newSession", undefined); - }, - "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); - }, - "continue.focusContinueSessionId": async ( - sessionId: string | undefined, - ) => { - if (!sessionId) { - sessionId = await vscode.window.showInputBox({ - prompt: "Enter the Session ID", - }); - } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); - }, - "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); - }, - "continue.toggleFullScreen": () => { - focusGUI(); - - // Check if full screen is already open by checking open tabs - const fullScreenTab = getFullScreenTab(); - - if (fullScreenTab && fullScreenPanel) { - //Full screen open, but not focused - focus it - fullScreenPanel.reveal(); - return; - } - - //Full screen not open - open it - captureCommandTelemetry("openFullScreen"); - - //create the full screen panel - let panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - { - retainContextWhenHidden: true, - }, - ); - fullScreenPanel = panel; - - //Add content to the panel - panel.webview.html = sidebar.getSidebarContent( - extensionContext, - panel, - undefined, - undefined, - true, - ); - - //When panel closes, reset the webview and focus - panel.onDidDispose( - () => { - sidebar.resetWebviewProtocolWebview(); - vscode.commands.executeCommand("continue.focusContinueInput"); - }, - null, - extensionContext.subscriptions, - ); - - vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); - }, - "continue.openConfigJson": () => { - ide.openFile(getConfigJsonPath()); - }, - "continue.selectFilesAsContext": async ( - firstUri: vscode.Uri, - uris: vscode.Uri[], - ) => { - if (uris === undefined) { - throw new Error("No files were selected"); - } - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - for (const uri of uris) { - // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) - const isDirectory = await vscode.workspace.fs - .stat(uri) - ?.then((stat) => stat.type === vscode.FileType.Directory); - if (isDirectory) { - for await (const filepath of walkDirAsync(uri.fsPath, ide)) { - addEntireFileToContext( - uriFromFilePath(filepath), - false, - sidebar.webviewProtocol, - ); + if (isContinueInputFocused) { + // Handle closing the GUI only if we are focused on the input + const fullScreenTab = getFullScreenTab(); + if (fullScreenTab) { + fullScreenPanel?.dispose(); } } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); - } - } - }, - "continue.logAutocompleteOutcome": ( - completionId: string, - completionProvider: CompletionProvider, - ) => { - completionProvider.accept(completionId); - }, - "continue.toggleTabAutocompleteEnabled": () => { - captureCommandTelemetry("toggleTabAutocompleteEnabled"); + focusGUI(); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const enabled = config.get("enableTabAutocomplete"); - const pauseOnBattery = config.get( - "pauseTabAutocompleteOnBattery", - ); - if (!pauseOnBattery || battery.isACConnected()) { - config.update( - "enableTabAutocomplete", - !enabled, - vscode.ConfigurationTarget.Global, + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", + undefined, + ); + + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.hideGUI": async () => { + vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); + }, + "continue.edit": async () => { + captureCommandTelemetry("edit"); + focusGUI(); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + editDecorationManager.setDecoration( + editor, + new vscode.Range(editor.selection.start, editor.selection.end), ); - } else { - if (enabled) { - const paused = getStatusBarStatus() === StatusBarStatus.Paused; - if (paused) { - setupStatusBar(StatusBarStatus.Enabled); + + const highlightedCode = getCurrentlyHighlightedCode(true)!; + await sidebar.webviewProtocol?.request("startEditMode", { + highlightedCode, + }); + + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); + + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + }, + "continue.exitEditMode": async () => { + captureCommandTelemetry("exitEditMode"); + await sidebar.webviewProtocol?.request("exitEditMode", undefined); + }, + "continue.quickEdit": async (args: QuickEditShowParams) => { + let linesOfCode = undefined; + if (args.range) { + linesOfCode = args.range.end.line - args.range.start.line; + } + captureCommandTelemetry("quickEdit", { + linesOfCode, + }); + quickEdit.show(args); + }, + "continue.writeCommentsForCode": async () => { + captureCommandTelemetry("writeCommentsForCode"); + + streamInlineEdit( + "comment", + "Write comments for this code. Do not change anything about the code itself.", + ); + }, + "continue.writeDocstringForCode": async () => { + captureCommandTelemetry("writeDocstringForCode"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + ); + }, + "continue.fixCode": async () => { + captureCommandTelemetry("fixCode"); + + streamInlineEdit( + "fix", + "Fix this code. If it is already 100% correct, simply rewrite the code.", + ); + }, + "continue.optimizeCode": async () => { + captureCommandTelemetry("optimizeCode"); + streamInlineEdit("optimize", "Optimize this code"); + }, + "continue.fixGrammar": async () => { + captureCommandTelemetry("fixGrammar"); + streamInlineEdit( + "fixGrammar", + "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", + ); + }, + "continue.viewLogs": async () => { + captureCommandTelemetry("viewLogs"); + + // Open ~/.continue/continue.log + const logFile = path.join(os.homedir(), ".continue", "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFile)) { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, ""); + } + + const uri = vscode.Uri.file(logFile); + await vscode.window.showTextDocument(uri); + }, + "continue.debugTerminal": async () => { + captureCommandTelemetry("debugTerminal"); + + const terminalContents = await ide.getTerminalContents(); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, + }); + }, + "continue.hideInlineTip": () => { + vscode.workspace + .getConfiguration(EXTENSION_NAME) + .update("showInlineTip", false, vscode.ConfigurationTarget.Global); + }, + + // Commands without keyboard shortcuts + "continue.addModel": () => { + captureCommandTelemetry("addModel"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("addModel", undefined); + }, + "continue.openSettingsUI": () => { + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("openSettings", undefined); + }, + "continue.sendMainUserInput": (text: string) => { + sidebar.webviewProtocol?.request("userInput", { + input: text, + }); + }, + "continue.selectRange": (startLine: number, endLine: number) => { + if (!vscode.window.activeTextEditor) { + return; + } + vscode.window.activeTextEditor.selection = new vscode.Selection( + startLine, + 0, + endLine, + 0, + ); + }, + "continue.foldAndUnfold": ( + foldSelectionLines: number[], + unfoldSelectionLines: number[], + ) => { + vscode.commands.executeCommand("editor.unfold", { + selectionLines: unfoldSelectionLines, + }); + vscode.commands.executeCommand("editor.fold", { + selectionLines: foldSelectionLines, + }); + }, + "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); + ide.runCommand(text); + }, + "continue.newSession": () => { + sidebar.webviewProtocol?.request("newSession", undefined); + }, + "continue.viewHistory": () => { + sidebar.webviewProtocol?.request("viewHistory", undefined); + }, + "continue.focusContinueSessionId": async ( + sessionId: string | undefined, + ) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID", + }); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, + "continue.applyCodeFromChat": () => { + sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + }, + "continue.toggleFullScreen": () => { + focusGUI(); + + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); + + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } + + // Full screen not open - open it + captureCommandTelemetry("openFullScreen"); + + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + }, + ); + fullScreenPanel = panel; + + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); + + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); + + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, + "continue.selectFilesAsContext": async ( + firstUri: vscode.Uri, + uris: vscode.Uri[], + ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + for (const uri of uris) { + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); + } } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); + } + } + }, + "continue.logAutocompleteOutcome": ( + completionId: string, + completionProvider: CompletionProvider, + ) => { + completionProvider.accept(completionId); + }, + "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); + + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const enabled = config.get("enableTabAutocomplete"); + const pauseOnBattery = config.get( + "pauseTabAutocompleteOnBattery", + ); + if (!pauseOnBattery || battery.isACConnected()) { + config.update( + "enableTabAutocomplete", + !enabled, + vscode.ConfigurationTarget.Global, + ); + } else { + if (enabled) { + const paused = getStatusBarStatus() === StatusBarStatus.Paused; + if (paused) { + setupStatusBar(StatusBarStatus.Enabled); + } else { + config.update( + "enableTabAutocomplete", + false, + vscode.ConfigurationTarget.Global, + ); + } + } else { + setupStatusBar(StatusBarStatus.Paused); config.update( "enableTabAutocomplete", - false, + true, vscode.ConfigurationTarget.Global, ); } + } + }, + "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); + + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const quickPick = vscode.window.createQuickPick(); + const autocompleteModels = + (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + + let selected = new GlobalContext().get("selectedTabAutocompleteModel"); + if ( + !selected || + !autocompleteModels.some((model) => model.title === selected) + ) { + selected = autocompleteModels[0].title; + } + + // Toggle between Disabled, Paused, and Enabled + const pauseOnBattery = + config.get("pauseTabAutocompleteOnBattery") && + !battery.isACConnected(); + const currentStatus = getStatusBarStatus(); + + let targetStatus: StatusBarStatus | undefined; + if (pauseOnBattery) { + // Cycle from Disabled -> Paused -> Enabled + targetStatus = + currentStatus === StatusBarStatus.Paused + ? StatusBarStatus.Enabled + : currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Paused + : StatusBarStatus.Disabled; } else { - setupStatusBar(StatusBarStatus.Paused); - config.update( - "enableTabAutocomplete", - true, - vscode.ConfigurationTarget.Global, - ); - } - } - }, - "continue.openTabAutocompleteConfigMenu": async () => { - captureCommandTelemetry("openTabAutocompleteConfigMenu"); - - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; - - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0].title; - } - - // Toggle between Disabled, Paused, and Enabled - const pauseOnBattery = - config.get("pauseTabAutocompleteOnBattery") && - !battery.isACConnected(); - const currentStatus = getStatusBarStatus(); - - let targetStatus: StatusBarStatus | undefined; - if (pauseOnBattery) { - // Cycle from Disabled -> Paused -> Enabled - targetStatus = - currentStatus === StatusBarStatus.Paused - ? StatusBarStatus.Enabled - : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused + // Toggle between Disabled and Enabled + targetStatus = + currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Enabled : StatusBarStatus.Disabled; - } else { - // Toggle between Disabled and Enabled - targetStatus = - currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Enabled - : StatusBarStatus.Disabled; - } - quickPick.items = [ - { - label: "$(question) Open help center", - }, - { - label: "$(comment) Open chat (Cmd+L)", - }, - { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", - }, - { - label: quickPickStatusText(targetStatus), - }, - { - label: "$(gear) Configure autocomplete options", - }, - { - label: "$(feedback) Give feedback", - }, - { - kind: vscode.QuickPickItemKind.Separator, - label: "Switch model", - }, - ...autocompleteModels.map((model) => ({ - label: getAutocompleteStatusBarTitle(selected, model), - description: getAutocompleteStatusBarDescription(selected, model), - })), - ]; - quickPick.onDidAccept(() => { - const selectedOption = quickPick.selectedItems[0].label; - const targetStatus = - getStatusBarStatusFromQuickPickItemLabel(selectedOption); - - if (targetStatus !== undefined) { - setupStatusBar(targetStatus); - config.update( - "enableTabAutocomplete", - targetStatus === StatusBarStatus.Enabled, - vscode.ConfigurationTarget.Global, - ); - } else if ( - selectedOption === "$(gear) Configure autocomplete options" - ) { - ide.openFile(getConfigJsonPath()); - } else if ( - autocompleteModels.some((model) => model.title === selectedOption) - ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); - } else if (selectedOption === "$(feedback) Give feedback") { - vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { - vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { - vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); } - quickPick.dispose(); - }); - quickPick.show(); - }, - "continue.giveAutocompleteFeedback": async () => { - const feedback = await vscode.window.showInputBox({ - ignoreFocusOut: true, - prompt: - "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", - }); - if (feedback) { - const client = await continueServerClientPromise; - const completionsPath = getDevDataFilePath("autocomplete"); + quickPick.items = [ + { + label: "$(question) Open help center", + }, + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, + { + label: quickPickStatusText(targetStatus), + }, + { + label: "$(gear) Configure autocomplete options", + }, + { + label: "$(feedback) Give feedback", + }, + { + kind: vscode.QuickPickItemKind.Separator, + label: "Switch model", + }, + ...autocompleteModels.map((model) => ({ + label: getAutocompleteStatusBarTitle(selected, model), + description: getAutocompleteStatusBarDescription(selected, model), + })), + ]; + quickPick.onDidAccept(() => { + const selectedOption = quickPick.selectedItems[0].label; + const targetStatus = + getStatusBarStatusFromQuickPickItemLabel(selectedOption); - const lastLines = await readLastLines.read(completionsPath, 2); - client.sendFeedback(feedback, lastLines); - } - }, - "continue.navigateTo": (path: string) => { - sidebar.webviewProtocol?.request("navigateTo", { path }); - focusGUI(); - }, + if (targetStatus !== undefined) { + setupStatusBar(targetStatus); + config.update( + "enableTabAutocomplete", + targetStatus === StatusBarStatus.Enabled, + vscode.ConfigurationTarget.Global, + ); + } else if ( + selectedOption === "$(gear) Configure autocomplete options" + ) { + ide.openFile(getConfigJsonPath()); + } else if ( + autocompleteModels.some((model) => model.title === selectedOption) + ) { + new GlobalContext().update( + "selectedTabAutocompleteModel", + selectedOption, + ); + configHandler.reloadConfig(); + } else if (selectedOption === "$(feedback) Give feedback") { + vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if (selectedOption === "$(question) Open help center") { + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); + } + quickPick.dispose(); + }); + quickPick.show(); + }, + "continue.giveAutocompleteFeedback": async () => { + const feedback = await vscode.window.showInputBox({ + ignoreFocusOut: true, + prompt: + "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", + }); + if (feedback) { + const client = await continueServerClientPromise; + const completionsPath = getDevDataFilePath("autocomplete"); + + const lastLines = await readLastLines.read(completionsPath, 2); + client.sendFeedback(feedback, lastLines); + } + }, + "continue.navigateTo": (path: string) => { + sidebar.webviewProtocol?.request("navigateTo", { path }); + focusGUI(); + }, + }; }; -}; export function registerAllCommands( context: vscode.ExtensionContext, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 483ff1603..952a57e54 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -130,6 +130,9 @@ export class VsCodeMessenger { this.onWebview("toggleFullScreen", (msg) => { vscode.commands.executeCommand("continue.toggleFullScreen"); }); + this.onWebview("hideGUI", (msg) => { + vscode.commands.executeCommand("continue.hideGUI"); + }); // History this.onWebview("saveFile", async (msg) => { return await ide.saveFile(msg.data.filepath); From 219b2c1569cc7e0ad555d87cc3a1e1e6699ccc6f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 09:32:56 -0800 Subject: [PATCH 09/27] keyboard shortcuts --- gui/src/components/mainInput/TipTapEditor.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 55ff9db39..3bae41942 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -908,7 +908,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { From 2e5b5794e9b394405c127893100be21e008b45ad Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 6 Nov 2024 11:31:53 -0800 Subject: [PATCH 10/27] feat: use bm25 for fts --- core/autocomplete/retrieval.ts | 12 +- core/context/retrieval/fullTextSearch.ts | 32 ----- .../pipelines/BaseRetrievalPipeline.ts | 82 +++++++++--- .../pipelines/NoRerankerRetrievalPipeline.ts | 15 ++- .../pipelines/RerankerRetrievalPipeline.ts | 27 ++-- core/context/retrieval/retrieval.ts | 6 +- core/indexing/FullTextSearchCodebaseIndex.ts | 125 +++++++++++------- core/package-lock.json | 64 +++++++++ core/package.json | 1 + extensions/vscode/package-lock.json | 1 + gui/package-lock.json | 1 + 11 files changed, 239 insertions(+), 127 deletions(-) delete mode 100644 core/context/retrieval/fullTextSearch.ts diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 422b377bd..8cc92ddec 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -10,13 +10,11 @@ export async function fullTextRetrieve( const searchStrings = prefix.split("\n").slice(-3); const results: Chunk[] = []; searchStrings.forEach(async (searchString) => { - const chunks = await index.retrieve( - [indexTag], - searchString, - 3, - undefined, - undefined, - ); + const chunks = await index.retrieve({ + tags: [indexTag], + text: searchString, + n: 3, + }); results.push(...chunks); }); return results; diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts deleted file mode 100644 index 9c52bd6b6..000000000 --- a/core/context/retrieval/fullTextSearch.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BranchAndDir, Chunk } from "../../index.js"; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js"; - -export async function retrieveFts( - query: string, - n: number, - tags: BranchAndDir[], - filterDirectory: string | undefined, -): Promise { - const ftsIndex = new FullTextSearchCodebaseIndex(); - - let ftsResults: Chunk[] = []; - try { - if (query.trim() !== "") { - ftsResults = await ftsIndex.retrieve( - tags, - query - .trim() - .split(" ") - .map((element) => `"${element}"`) - .join(" OR "), - n, - filterDirectory, - undefined, - ); - } - return ftsResults; - } catch (e) { - console.warn("Error retrieving from FTS:", e); - return []; - } -} diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 9495f1608..89323d9b2 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,14 +1,11 @@ -import { - BranchAndDir, - Chunk, - ContinueConfig, - IDE, - ILLM, -} from "../../../index.js"; -import { chunkDocument } from "../../../indexing/chunk/chunk.js"; -import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js"; -import { retrieveFts } from "../fullTextSearch.js"; -import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js"; +// @ts-ignore +import nlp from "wink-nlp-utils"; + +import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; +import { chunkDocument } from "../../../indexing/chunk/chunk"; +import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; +import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; export interface RetrievalPipelineOptions { llm: ILLM; @@ -23,11 +20,18 @@ export interface RetrievalPipelineOptions { includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model } +export interface RetrievalPipelineRunArguments { + query: string; + tags: BranchAndDir[]; + filterDirectory?: string; +} + export interface IRetrievalPipeline { - run(options: RetrievalPipelineOptions): Promise; + run(args: RetrievalPipelineRunArguments): Promise; } export default class BaseRetrievalPipeline implements IRetrievalPipeline { + private ftsIndex = new FullTextSearchCodebaseIndex(); private lanceDbIndex: LanceDbIndex; constructor(protected readonly options: RetrievalPipelineOptions) { @@ -38,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } + private getCleanedTrigrams( + query: RetrievalPipelineRunArguments["query"], + ): string[] { + let text = nlp.string.removeExtraSpaces(query); + text = nlp.string.stem(text); + + let tokens = nlp.string + .tokenize(text, true) + .filter((token: any) => token.tag === "word") + .map((token: any) => token.value); + + tokens = nlp.tokens.removeWords(tokens); + tokens = nlp.tokens.setOfWords(tokens); + + const cleanedTokens = [...tokens].join(" "); + const trigrams = nlp.string.ngram(cleanedTokens, 3); + + return trigrams; + } + + protected async retrieveFts( + args: RetrievalPipelineRunArguments, + n: number, + ): Promise { + try { + if (args.query.trim() === "") { + return []; + } + + const tokens = this.getCleanedTrigrams(args.query).join(" OR "); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); + } catch (e) { + console.warn("Error retrieving from FTS:", e); + return []; + } + } + protected async retrieveAndChunkRecentlyEditedFiles( n: number, ): Promise { @@ -75,15 +122,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return chunks.slice(0, n); } - protected async retrieveFts(input: string, n: number): Promise { - return retrieveFts( - input, - n, - this.options.tags, - this.options.filterDirectory, - ); - } - protected async retrieveEmbeddings( input: string, n: number, @@ -96,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } - run(): Promise { + run(args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } } diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 6caef72dd..052a1fce6 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -1,10 +1,13 @@ -import { Chunk } from "../../../index.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../../"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { - async run(): Promise { + async run(args: RetrievalPipelineRunArguments): Promise { const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, @@ -15,7 +18,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, ftsNFinal); + const ftsChunks = await this.retrieveFts(args, ftsNFinal); const embeddingsChunks = includeEmbeddings ? await this.retrieveEmbeddings(input, embeddingsNFinal) diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 375f1b17b..6f28a4a89 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -1,17 +1,22 @@ -import { Chunk } from "../../../index.js"; -import { RETRIEVAL_PARAMS } from "../../../util/parameters.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../.."; +import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { - private async _retrieveInitial(): Promise { + private async _retrieveInitial( + args: RetrievalPipelineRunArguments, + ): Promise { const { input, nRetrieve, filterDirectory, includeEmbeddings } = this.options; let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, nRetrieve); + const ftsChunks = await this.retrieveFts(args, nRetrieve); const embeddingsChunks = includeEmbeddings ? await this.retrieveEmbeddings(input, nRetrieve) : []; @@ -104,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { return results; } - async run(): Promise { - const intialResults = await this._retrieveInitial(); - const rankedResults = await this._rerank(this.options.input, intialResults); + async run(args: RetrievalPipelineRunArguments): Promise { + let results = await this._retrieveInitial(args); + results = await this._rerank(args.query, results); // // // Expand top reranked results // const expanded = await this._expandRankedResults(results); @@ -120,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // TODO: stitch together results - return rankedResults; + return results; } } diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index a40e163a0..8aae10a41 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -93,7 +93,11 @@ export async function retrieveContextItemsFromEmbeddings( }; const pipeline = new pipelineType(pipelineOptions); - const results = await pipeline.run(); + const results = await pipeline.run({ + tags, + filterDirectory, + query: extras.fullInput, + }); if (results.length === 0) { throw new Error( diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 27face898..82e4e822f 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,6 +1,7 @@ import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; import { getBasename } from "../util/index"; import { RETRIEVAL_PARAMS } from "../util/parameters"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { @@ -10,10 +11,20 @@ import { type CodebaseIndex, } from "./types"; +export interface RetrieveConfig { + tags: BranchAndDir[]; + text: string; + n: number; + directory?: string; + filterPaths?: string[]; + bm25Threshold?: number; +} + export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; static artifactId = "sqliteFts"; artifactId: string = FullTextSearchCodebaseIndex.artifactId; + pathWeightMultiplier = 10.0; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( @@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { desc: `Indexing ${getBasename(item.path)}`, status: "indexing", }; - markComplete([item], IndexResultType.Compute); + await markComplete([item], IndexResultType.Compute); } // Add tag for (const item of results.addTag) { - markComplete([item], IndexResultType.AddTag); + await markComplete([item], IndexResultType.AddTag); } // Remove tag for (const item of results.removeTag) { - markComplete([item], IndexResultType.RemoveTag); + await markComplete([item], IndexResultType.RemoveTag); } // Delete @@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { await db.run("DELETE FROM fts WHERE path = ?", [item.path]); - markComplete([item], IndexResultType.Delete); + await markComplete([item], IndexResultType.Delete); } } - async retrieve( - tags: BranchAndDir[], - text: string, - n: number, - directory: string | undefined, - filterPaths: string[] | undefined, - bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold, - ): Promise { + async retrieve(config: RetrieveConfig): Promise { const db = await SqliteDb.get(); - // Notice that the "chunks" artifactId is used because of linking between tables - const tagStrings = tags.map((tag) => { - return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }); - }); + const query = this.buildRetrieveQuery(config); + const parameters = this.getRetrieveQueryParameters(config); - const query = `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank - FROM fts - JOIN fts_metadata ON fts.rowid = fts_metadata.id - JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId - WHERE fts MATCH '${text.replace( - /\?/g, - "", - )}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")}) - ${ - filterPaths - ? `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})` - : "" - } - ORDER BY rank - LIMIT ?`; + let results = await db.all(query, parameters); - let results = await db.all(query, [ - ...tagStrings, - ...(filterPaths || []), - Math.ceil(n), - ]); - - results = results.filter((result) => result.rank <= bm25Threshold); + results = results.filter( + (result) => + result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold), + ); const chunks = await db.all( `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`, results.map((result) => result.chunkId), ); - return chunks.map((chunk) => { - return { - filepath: chunk.path, - index: chunk.index, - startLine: chunk.startLine, - endLine: chunk.endLine, - content: chunk.content, - digest: chunk.cacheKey, - }; - }); + return chunks.map((chunk) => ({ + filepath: chunk.path, + index: chunk.index, + startLine: chunk.startLine, + endLine: chunk.endLine, + content: chunk.content, + digest: chunk.cacheKey, + })); + } + + private buildTagFilter(tags: BranchAndDir[]): string { + const tagStrings = this.convertTags(tags); + + return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`; + } + + private buildPathFilter(filterPaths: string[] | undefined): string { + if (!filterPaths || filterPaths.length === 0) { + return ""; + } + return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`; + } + + private buildRetrieveQuery(config: RetrieveConfig): string { + return ` + SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank + FROM fts + JOIN fts_metadata ON fts.rowid = fts_metadata.id + JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId + WHERE fts MATCH ? + ${this.buildTagFilter(config.tags)} + ${this.buildPathFilter(config.filterPaths)} + ORDER BY bm25(fts, ${this.pathWeightMultiplier}) + LIMIT ? + `; + } + + private getRetrieveQueryParameters(config: RetrieveConfig) { + const { text, tags, filterPaths, n } = config; + const tagStrings = this.convertTags(tags); + + return [ + text.replace(/\?/g, ""), + ...tagStrings, + ...(filterPaths || []), + Math.ceil(n), + ]; + } + + private convertTags(tags: BranchAndDir[]): string[] { + // Notice that the "chunks" artifactId is used because of linking between tables + return tags.map((tag) => + tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }), + ); } } diff --git a/core/package-lock.json b/core/package-lock.json index 9e3937c64..f218b1904 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -64,6 +64,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" @@ -14850,6 +14851,69 @@ "node": ">=4" } }, + "node_modules/wink-distance": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz", + "integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==", + "dependencies": { + "wink-helpers": "^2.0.0", + "wink-jaro-distance": "^2.0.0" + } + }, + "node_modules/wink-eng-lite-web-model": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz", + "integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/wink-helpers": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz", + "integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg==" + }, + "node_modules/wink-jaro-distance": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz", + "integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA==" + }, + "node_modules/wink-nlp": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz", + "integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A==" + }, + "node_modules/wink-nlp-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz", + "integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==", + "dependencies": { + "wink-distance": "^2.0.1", + "wink-eng-lite-web-model": "^1.4.3", + "wink-helpers": "^2.0.0", + "wink-nlp": "^1.12.0", + "wink-porter2-stemmer": "^2.0.1", + "wink-tokenizer": "^5.2.3" + } + }, + "node_modules/wink-porter2-stemmer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz", + "integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ==" + }, + "node_modules/wink-tokenizer": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz", + "integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==", + "dependencies": { + "emoji-regex": "^9.0.0" + } + }, + "node_modules/wink-tokenizer/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/core/package.json b/core/package.json index ed489d1f2..952a9503d 100644 --- a/core/package.json +++ b/core/package.json @@ -95,6 +95,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c39c6391c..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -149,6 +149,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/gui/package-lock.json b/gui/package-lock.json index b0be81c6c..5c0221a2f 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -151,6 +151,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" From ef2f20fac59fc86b211ff46fed84e504ec4e2f0c Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 6 Nov 2024 13:46:50 -0800 Subject: [PATCH 11/27] Update CodeBlockToolbar.tsx --- gui/src/components/markdown/CodeBlockToolbar.tsx | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index a01dd78d2..ac4c03bb2 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -131,7 +131,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { const defaultModel = useSelector(defaultModelSelector); const isTerminal = isTerminalCodeBlock(props.language, props.text); const [isCopied, setIsCopied] = useState(false); - const [isApplying, setIsApplying] = useState(false); const streamIdRef = useRef(null); if (streamIdRef.current === null) { @@ -149,10 +148,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { useWebviewListener( "applyCodeFromChat", async () => { - await ideMessenger.request("applyToCurrentFile", { + await ideMessenger.request("applyToFile", { curSelectedModelTitle: defaultModel.title, text: props.text, streamId: streamIdRef.current, + filepath: props.filepath, }); dispatch(incrementNextCodeBlockToApplyIndex({})); }, @@ -172,8 +172,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { } async function onClickApply() { - if (isApplying) return; - if (isTerminal) { await ideMessenger.ide.runCommand(getTerminalCommand(props.text)); return; @@ -232,7 +230,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { {!isJetBrains() && isTerminal && ( @@ -240,15 +237,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { )} - {isApplying ? ( - - ) : ( - - )} + Date: Wed, 6 Nov 2024 15:47:04 -0800 Subject: [PATCH 12/27] remove test copy --- gui/src/components/mainInput/TipTapEditor.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index dfaeaf607..98a5c11db 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -863,7 +863,6 @@ function TipTapEditor(props: TipTapEditorProps) { event.preventDefault(); }} > -

{`${editorFocusedRef.current}`}

{props.header}
From 9a85a891818f0f2d012e0d8a0a881fab180cb27b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 16:17:40 -0800 Subject: [PATCH 13/27] clean up --- core/protocol/ide.ts | 1 - gui/src/components/mainInput/TipTapEditor.tsx | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 6a9f177d0..eda6bebfb 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -89,7 +89,6 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; logoutOfControlPlane: [undefined, void]; pathSep: [undefined, string]; - hideGUI: [undefined, void]; }; export type ToWebviewOrCoreFromIdeProtocol = { diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 98a5c11db..01ee8dea6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -819,7 +819,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { From 38131a0e7fa205939c47d4d854aa15b39fcf8958 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 02:28:57 -0800 Subject: [PATCH 14/27] openai prediction take 1 --- core/index.d.ts | 1 + core/llm/llms/OpenAI.ts | 24 +++++++++++++++++++++++- extensions/vscode/config_schema.json | 5 +++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/core/index.d.ts b/core/index.d.ts index 5b0b892f6..d73385dbe 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -794,6 +794,7 @@ interface BaseCompletionOptions { keepAlive?: number; raw?: boolean; stream?: boolean; + predictionContent?: string; } export interface ModelCapability { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index b626a9698..110e1e8ff 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,7 +95,14 @@ class OpenAI extends BaseLLM { ); } - protected _convertArgs(options: any, messages: ChatMessage[]) { + private supportsPrediction(model: string): boolean { + return [ + "gpt-4o-mini", + "gpt-4o" + ].includes(model); + } + + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); const finalOptions: any = { messages: messages.map(this._convertMessage), @@ -135,6 +142,21 @@ class OpenAI extends BaseLLM { ); } + if (options.predictionContent && this.supportsPrediction(options.model)) { + if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + finalOptions.presence_penalty = undefined; + } + if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + finalOptions.frequency_penalty = undefined; + } + finalOptions.max_completion_tokens = undefined; + + finalOptions.prediction = { + "type": "content", + "content": options.predictionContent + }; + } + return finalOptions; } diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f18bdbb6a..3f4b90b19 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -65,6 +65,11 @@ "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" + }, + "predictionContent": { + "title": "Prediction", + "description": "(gpt-4o/gpt-4o-mini only) Prediction output which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.", + "type": "string" } } }, From b3b7b5b9cab7048d8f84b51d6eb56d8b7408d60c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 02:46:29 -0800 Subject: [PATCH 15/27] prediction full implementation --- core/index.d.ts | 10 +++++- core/llm/llms/OpenAI.ts | 7 ++-- extensions/vscode/config_schema.json | 50 ++++++++++++++++++++++++++-- 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index d73385dbe..ef8b7c128 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -780,6 +780,14 @@ export interface CustomCommand { description: string; } +interface Prediction { + type: "content" + content: string | { + type: "text" + text: string + }[] +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -794,7 +802,7 @@ interface BaseCompletionOptions { keepAlive?: number; raw?: boolean; stream?: boolean; - predictionContent?: string; + prediction?: Prediction; } export interface ModelCapability { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 110e1e8ff..168e0afff 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -142,7 +142,7 @@ class OpenAI extends BaseLLM { ); } - if (options.predictionContent && this.supportsPrediction(options.model)) { + if (options.prediction && this.supportsPrediction(options.model)) { if (finalOptions.presence_penalty) { // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } @@ -151,10 +151,7 @@ class OpenAI extends BaseLLM { } finalOptions.max_completion_tokens = undefined; - finalOptions.prediction = { - "type": "content", - "content": options.predictionContent - }; + finalOptions.prediction = options.prediction; } return finalOptions; diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 3f4b90b19..e3736a3bb 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -66,10 +66,56 @@ "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" }, - "predictionContent": { + "prediction": { "title": "Prediction", "description": "(gpt-4o/gpt-4o-mini only) Prediction output which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.", - "type": "string" + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "content" + ], + "description": "Currently only 'content' type supported" + }, + "content": { + "description": "Predicted output (usually contents of a file)", + "anyOf": [ + { + "type": "string", + "description": "Predicted output (usually contents of a file)" + }, + { + "type": "array", + "description": "Array of predicted output text items (usually pieces of a file)", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "description": "Currently only 'text' supported" + }, + "text": { + "type": "string", + "description": "Predicted output item text" + } + }, + "required": [ + "type", + "text" + ] + } + } + ] + } + }, + "required": [ + "type", + "content" + ] } } }, From 0e166fcf32ee637f5776c954432c720da9854ab3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 09:18:34 -0800 Subject: [PATCH 16/27] remove prediction from config_schema.json --- extensions/vscode/config_schema.json | 51 ---------------------------- 1 file changed, 51 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index e3736a3bb..f18bdbb6a 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -65,57 +65,6 @@ "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" - }, - "prediction": { - "title": "Prediction", - "description": "(gpt-4o/gpt-4o-mini only) Prediction output which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.", - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": [ - "content" - ], - "description": "Currently only 'content' type supported" - }, - "content": { - "description": "Predicted output (usually contents of a file)", - "anyOf": [ - { - "type": "string", - "description": "Predicted output (usually contents of a file)" - }, - { - "type": "array", - "description": "Array of predicted output text items (usually pieces of a file)", - "items": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": [ - "text" - ], - "description": "Currently only 'text' supported" - }, - "text": { - "type": "string", - "description": "Predicted output item text" - } - }, - "required": [ - "type", - "text" - ] - } - } - ] - } - }, - "required": [ - "type", - "content" - ] } } }, From 0f3bc0e5b5983daf1ce655aebf87fd0c6ba936e1 Mon Sep 17 00:00:00 2001 From: Sherman Boyd Date: Thu, 7 Nov 2024 12:41:04 -0800 Subject: [PATCH 17/27] Implemented fancy keys for all keyboard shortcut expressions. Added a margin to tag so it doesn't crowd text: especially parens --- docs/docs/actions/how-to-use-it.md | 8 ++++---- docs/docs/autocomplete/context-selection.md | 2 +- docs/docs/autocomplete/how-to-use-it.md | 6 +++--- docs/docs/chat/context-selection.md | 4 ++-- docs/docs/chat/how-it-works.md | 2 +- docs/docs/chat/how-to-use-it.md | 6 +++--- docs/docs/customize/deep-dives/autocomplete.md | 10 +++++----- docs/docs/customize/deep-dives/codebase.md | 2 +- docs/docs/customize/deep-dives/prompt-files.md | 2 +- docs/docs/edit/how-to-use-it.md | 8 ++++---- docs/docs/telemetry.md | 2 +- docs/docs/troubleshooting.md | 6 +++--- docs/src/css/custom.css | 1 + 13 files changed, 30 insertions(+), 29 deletions(-) diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index 3e7c04644..5be83b2e7 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -14,7 +14,7 @@ Actions are shortcuts for common use cases. For example, you might want to revie ### Slash commands -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. +The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. ![slash-commands](/img/slash-commands.png) @@ -48,7 +48,7 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use `cmd/ctrl+L` to select it in the Continue sidebar. +Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. @@ -76,10 +76,10 @@ Right click actions let you highlight a desired region of code, right click, and #### Debug action -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use `cmd/ctrl+shift+R` to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. +The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. #### Quick fixes -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut `cmd/ctrl+.` will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use `cmd/ctrl+.` again and Continue will attempt to help solve the problem. +Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. ![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/autocomplete/context-selection.md b/docs/docs/autocomplete/context-selection.md index e85e3d4bd..f237a3625 100644 --- a/docs/docs/autocomplete/context-selection.md +++ b/docs/docs/autocomplete/context-selection.md @@ -13,7 +13,7 @@ We will always include the code from your file prior to and after the cursor pos ### Definitions from the Language Server Protocol -Similar to how you can use `cmd/ctrl + click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. +Similar to how you can use cmd/ctrl + `click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. ### Imported files diff --git a/docs/docs/autocomplete/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index 92a3db76e..5fd127ce5 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -14,12 +14,12 @@ Autocomplete provides inline code suggestions as you type. To enable it, simply ### Accepting a full suggestion -Accept a full suggestion by pressing `Tab` +Accept a full suggestion by pressing Tab ### Rejecting a full suggestion -Reject a full suggestion with `Esc` +Reject a full suggestion with Esc ### Partially accepting a suggestion -For more granular control, use `cmd/ctrl + →` to accept parts of the suggestion word-by-word. +For more granular control, use cmd/ctrl + → to accept parts of the suggestion word-by-word. diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index ebdb41185..072bc0128 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -11,11 +11,11 @@ Typing a question or instructions into the input box is the only required contex ## Highlighted code -The highlighted code you’ve selected by pressing `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. +The highlighted code you’ve selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. ## Active file -You can include the currently open file as context by pressing `cmd/ctrl + opt + enter` when you send your request. +You can include the currently open file as context by pressing cmd/ctrl + opt + enter when you send your request. ## Specific file diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md index b5e8aaece..84c81582e 100644 --- a/docs/docs/chat/how-it-works.md +++ b/docs/docs/chat/how-it-works.md @@ -7,7 +7,7 @@ sidebar_position: 4 Using any selected code sections, all context that you have selected with @, and your input instructions, we prompt the model to provide a response in the sidebar. If you are asking a follow-up, then all earlier session context is also included. No other additional context is provided to the model. -The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. +The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs). diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md index 509702b4f..112649aeb 100644 --- a/docs/docs/chat/how-to-use-it.md +++ b/docs/docs/chat/how-to-use-it.md @@ -20,7 +20,7 @@ You send it a question, and it replies with an answer. You tell it to solve a pr ## Highlight a code section to include as context -You select a code section with your mouse, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. +You select a code section with your mouse, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. ## Reference context with the @ symbol @@ -32,8 +32,8 @@ When the LLM replies with edits to a file, you can click the “Apply” button. ## Start a fresh session for a new task -Once you complete a task and want to start a new one, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. +Once you complete a task and want to start a new one, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. ## Switch between different models -If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’` +If you have configured multiple models, you can switch between models using the dropdown or by pressing cmd/ctrl + ’ diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 9e406416d..bb7e0f770 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -103,8 +103,8 @@ Follow these steps to ensure that everything is set up correctly: 2. Make sure you have downloaded Ollama. 3. Run `ollama run starcoder2:3b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl+, then search for this and check the box) +5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. +6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. ### Completions are slow @@ -122,8 +122,8 @@ Yes, in VS Code, if you don't want to be shown suggestions automatically you can 1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disable automatic suggestions 2. Open "Keyboard Shortcuts" (cmd/ctrl+k, cmd/ctrl+s) and search for `editor.action.inlineSuggest.trigger` 3. Click the "+" icon to add a new keybinding -4. Press the key combination you want to use to trigger suggestions (e.g. `ctrl+space`) -5. Now whenever you want to see a suggestion, you can press your key binding (e.g. `ctrl+space`) to trigger suggestions manually +4. Press the key combination you want to use to trigger suggestions (e.g. cmd/ctrl + space) +5. Now whenever you want to see a suggestion, you can press your key binding (e.g. cmd/ctrl + space) to trigger suggestions manually ### Is there a shortcut to accept one line at a time? @@ -137,7 +137,7 @@ Click the "Continue" button in the status panel at the bottom right of the scree Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". -You can also use the default shortcut to disable autocomplete directly: press `ctrl/cmd + K`, `ctrl/cmd + A`. This will turn off autocomplete without navigating through settings. +You can also use the default shortcut to disable autocomplete directly using a chord: press and hold ctrl/cmd + K (continue holding ctrl/cmd) and press ctrl/cmd + A. This will turn off autocomplete without navigating through settings. #### JetBrains diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index f106fea14..4da920943 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -75,7 +75,7 @@ Continue also supports a **global** `.continueignore` file that will be respecte If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. -If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window". +If you need to force a refresh of the index, reload the VS Code window with cmd/ctrl + shift + p + "Reload Window". ## Repository map diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1c70d729c..928e01543 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -35,7 +35,7 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use `cmd/ctrl + L` to select it in the Continue sidebar. +Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 4dbed98d8..850c34b60 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -20,7 +20,7 @@ Edit is best used for small, quick changes such as: ## Highlight code and activate -Highlight the block of code you would like to modify, and press `cmd/ctrl + i` to activate the edit input. +Highlight the block of code you would like to modify, and press cmd/ctrl + i to activate the edit input. ## Describe code changes @@ -30,8 +30,8 @@ Describe the changes you would like the model to make to your highlighted code. Proposed changes appear as inline diffs within your highlighted text. -You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl + opt + y` (to accept) or `cmd/ctrl + opt + n` (to reject). +You can navigate through each proposed change, accepting or rejecting them using cmd/ctrl + opt + y (to accept) or cmd/ctrl + opt + n (to reject). -You can also accept or reject all changes at once using `cmd/ctrl + shift + enter` (to accept) or `cmd/ctrl + shift + delete` (to reject). +You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). -If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl + i` to re-prompt the model. +If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index a72a6e77a..8e7152d01 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -46,6 +46,6 @@ To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternativ ### Steps to Disable Telemetry via VS Code Settings 1. Open VS Code. -2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut `Ctrl + ,` on Windows/Linux or `Cmd + ,` on macOS). +2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). 3. In the search bar, type "Continue: Telemetry Enabled". 4. Uncheck the "Continue: Telemetry Enabled" checkbox. diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index d10d2c104..d4bbe69db 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -24,7 +24,7 @@ To solve many problems, the first step is reading the logs to find the relevant In order to view debug logs, which contain extra information, click the dropdown at the top that says "Default levels" and select "Verbose". ::: -1. `cmd+shift+p` (MacOS) / `ctrl+shift+p` (Windows) +1. cmd + shift + P for MacOS or ctrl + shift + P for Windows 2. Search for and then select "Developer: Toggle Developer Tools" 3. This will open the [Chrome DevTools window](https://developer.chrome.com/docs/devtools/) 4. Select the `Console` tab @@ -56,7 +56,7 @@ We are constantly making fixes and improvements to Continue, but the latest chan On JetBrains, the "pre-release" happens through their Early Access Program (EAP) channel. To download the latest EAP version, enable the EAP channel: -1. Open JetBrains settings (`cmd/ctrl + ,`) and go to "Plugins" +1. Open JetBrains settings (cmd/ctrl + ,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." 4. Add "[https://plugins.jetbrains.com/plugins/eap/list](https://plugins.jetbrains.com/plugins/eap/list)" to the list @@ -104,7 +104,7 @@ You may also set `requestOptions.caBundlePath` to an array of paths to multiple #### VS Code Proxy Settings -If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl+, to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. +If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl + , to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. #### code-server diff --git a/docs/src/css/custom.css b/docs/src/css/custom.css index 6002807cc..f0b798f64 100644 --- a/docs/src/css/custom.css +++ b/docs/src/css/custom.css @@ -47,6 +47,7 @@ kbd { display: inline-block; padding: 0.3em 0.4em; + margin: 0.1em .4em; font-family: var(--ifm-font-family-monospace); font-size: .8rem; font-weight: 500; From 885e7c138d725dfed88d9165df99f1f692c49fb8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 12:58:13 -0800 Subject: [PATCH 18/27] integer progress percentage --- .../More/IndexingProgress/IndexingProgressIndicator.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index dbfb44f64..852cdf845 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -27,14 +27,13 @@ function IndexingProgressIndicator({ update }: IndexingProgressIndicatorProps) { return (
- {showProgress && {progressPercentage}%} + {showProgress && {progressPercentage.toFixed(0)}%} {Icon && (
)} From 0fac5aad1f5640bb9d4eff9841cd0dcb884a3579 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 7 Nov 2024 15:13:23 -0800 Subject: [PATCH 19/27] predicted completions for Edit and Apply --- core/edit/streamDiffLines.ts | 18 ++++++++++-------- extensions/vscode/package-lock.json | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index dbab5841c..48466d0d3 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -8,12 +8,7 @@ import { } from "../autocomplete/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; -import { - ChatMessage, - DiffLine, - ILLM, - LLMFullCompletionOptions, -} from "../index.js"; +import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; import { Telemetry } from "../util/posthog.js"; @@ -94,10 +89,17 @@ export async function* streamDiffLines( ); const inept = modelIsInept(llm.model); + const prediction: Prediction = { + type: "content", + content: highlighted, + }; + const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true }) - : llm.streamChat(prompt); + ? llm.streamComplete(prompt, { raw: true, prediction }) + : llm.streamChat(prompt, { + prediction, + }); let lines = streamLines(completion); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3baee50b0..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -12599,4 +12599,4 @@ } } } -} \ No newline at end of file +} From 648d4bfa4b29491f52cf8026f6a77d51d3888b86 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 7 Nov 2024 20:59:17 -0800 Subject: [PATCH 20/27] address edit feedback --- extensions/vscode/src/commands.ts | 1077 +++++++++++++++-------------- gui/src/components/index.ts | 21 +- gui/src/pages/edit.tsx | 21 +- 3 files changed, 581 insertions(+), 538 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 11c280678..c33d71aea 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { ContextMenuConfig, IDE } from "core"; +import { ContextMenuConfig } from "core"; import { CompletionProvider } from "core/autocomplete/completionProvider"; import { RangeInFileWithContents } from "core/commands/util"; import { ConfigHandler } from "core/config/ConfigHandler"; @@ -33,8 +33,8 @@ import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; -import type { VsCodeWebviewProtocol } from "./webviewProtocol"; import { VsCodeIde } from "./VsCodeIde"; +import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -226,180 +226,196 @@ const commandsMap: ( core, editDecorationManager, ) => { - /** - * Streams an inline edit to the vertical diff manager. - * - * This function retrieves the configuration, determines the appropriate model title, - * increments the FTC count, and then streams an edit to the - * vertical diff manager. - * - * @param promptName - The key for the prompt in the context menu configuration. - * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. - * @param [range] - Optional. The range to edit if provided. - * @returns - */ - async function streamInlineEdit( - promptName: keyof ContextMenuConfig, - fallbackPrompt: string, - onlyOneInsertion?: boolean, - range?: vscode.Range, - ) { - const config = await configHandler.loadConfig(); + /** + * Streams an inline edit to the vertical diff manager. + * + * This function retrieves the configuration, determines the appropriate model title, + * increments the FTC count, and then streams an edit to the + * vertical diff manager. + * + * @param promptName - The key for the prompt in the context menu configuration. + * @param fallbackPrompt - The prompt to use if the configured prompt is not available. + * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. + * @param [range] - Optional. The range to edit if provided. + * @returns + */ + async function streamInlineEdit( + promptName: keyof ContextMenuConfig, + fallbackPrompt: string, + onlyOneInsertion?: boolean, + range?: vscode.Range, + ) { + const config = await configHandler.loadConfig(); - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + ); + + const modelTitle = + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + + sidebar.webviewProtocol.request("incrementFtc", undefined); + + await verticalDiffManager.streamEdit( + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + modelTitle, + undefined, + onlyOneInsertion, + undefined, + range, + ); + } + + return { + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + verticalDiffManager.clearForFilepath(fullPath, true); + await diffManager.acceptDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + verticalDiffManager.clearForFilepath(fullPath, false); + await diffManager.rejectDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("acceptVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); + }, + "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("rejectVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); + }, + "continue.quickFix": async ( + range: vscode.Range, + diagnosticMessage: string, + ) => { + captureCommandTelemetry("quickFix"); + + const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); + + streamInlineEdit("docstring", prompt, false, range); + }, + "continue.codebaseForceReIndex": async () => { + core.invoke("index/forceReIndex", undefined); + }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", { reIndex: false }); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", { reIndex: true }); + }, + "continue.focusContinueInput": async () => { + const historyLength = await sidebar.webviewProtocol.request( + "getWebviewHistoryLength", + undefined, + ); + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", undefined, ); - const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - - sidebar.webviewProtocol.request("incrementFtc", undefined); - - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, - onlyOneInsertion, - undefined, - range, - ); - } - - return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("acceptDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - return; - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("acceptVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); - }, - "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("rejectVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); - }, - "continue.quickFix": async ( - range: vscode.Range, - diagnosticMessage: string, - ) => { - captureCommandTelemetry("quickFix"); - - const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - // Passthrough for telemetry purposes - "continue.defaultQuickAction": async (args: QuickEditShowParams) => { - captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); - }, - "continue.customQuickActionSendToChat": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionSendToChat"); - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - "continue.customQuickActionStreamInlineEdit": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionStreamInlineEdit"); - - streamInlineEdit("docstring", prompt, false, range); - }, - "continue.codebaseForceReIndex": async () => { - core.invoke("index/forceReIndex", undefined); - }, - "continue.rebuildCodebaseIndex": async () => { - core.invoke("index/forceReIndex", { shouldClearIndexes: true }); - }, - "continue.docsIndex": async () => { - core.invoke("context/indexDocs", { reIndex: false }); - }, - "continue.docsReIndex": async () => { - core.invoke("context/indexDocs", { reIndex: true }); - }, - "continue.focusContinueInput": async () => { - const historyLength = await sidebar.webviewProtocol.request("getWebviewHistoryLength", undefined); - const isContinueInputFocused = await sidebar.webviewProtocol.request("isContinueInputFocused", undefined); - - if (isContinueInputFocused) { - if (historyLength === 0) { - hideGUI(); - } else { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - } - } else { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.focusContinueInputWithoutClear": async () => { - const isContinueInputFocused = await sidebar.webviewProtocol.request("isContinueInputFocused", undefined); - - if (isContinueInputFocused) { + if (isContinueInputFocused) { + if (historyLength === 0) { hideGUI(); } else { - focusGUI(); - - sidebar.webviewProtocol?.request("focusContinueInputWithoutClear", undefined); - - await addHighlightedCodeToContext(sidebar.webviewProtocol); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); } - }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); + } else { + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", + undefined, + ); + + if (isContinueInputFocused) { + hideGUI(); + } else { focusGUI(); - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", + undefined, + ); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.edit": async () => { + captureCommandTelemetry("edit"); + focusGUI(); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const existingDiff = await verticalDiffManager.getHandlerForFile( + editor.document.fileName, + ); + if (!existingDiff) { + // If there's a diff currently being applied, then we just toggle focus back to the input editDecorationManager.setDecoration( editor, new vscode.Range(editor.selection.start, editor.selection.end), @@ -419,396 +435,399 @@ const commandsMap: ( setTimeout(() => { sidebar.webviewProtocol?.request("focusContinueInput", undefined); }, 30); - }, - "continue.exitEditMode": async () => { - captureCommandTelemetry("exitEditMode"); - await sidebar.webviewProtocol?.request("exitEditMode", undefined); - }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - let linesOfCode = undefined; - if (args.range) { - linesOfCode = args.range.end.line - args.range.start.line; - } - captureCommandTelemetry("quickEdit", { - linesOfCode, + } else { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + } + }, + "continue.exitEditMode": async () => { + captureCommandTelemetry("exitEditMode"); + await sidebar.webviewProtocol?.request("exitEditMode", undefined); + }, + "continue.quickEdit": async (args: QuickEditShowParams) => { + let linesOfCode = undefined; + if (args.range) { + linesOfCode = args.range.end.line - args.range.start.line; + } + captureCommandTelemetry("quickEdit", { + linesOfCode, + }); + quickEdit.show(args); + }, + "continue.writeCommentsForCode": async () => { + captureCommandTelemetry("writeCommentsForCode"); + + streamInlineEdit( + "comment", + "Write comments for this code. Do not change anything about the code itself.", + ); + }, + "continue.writeDocstringForCode": async () => { + captureCommandTelemetry("writeDocstringForCode"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + ); + }, + "continue.fixCode": async () => { + captureCommandTelemetry("fixCode"); + + streamInlineEdit( + "fix", + "Fix this code. If it is already 100% correct, simply rewrite the code.", + ); + }, + "continue.optimizeCode": async () => { + captureCommandTelemetry("optimizeCode"); + streamInlineEdit("optimize", "Optimize this code"); + }, + "continue.fixGrammar": async () => { + captureCommandTelemetry("fixGrammar"); + streamInlineEdit( + "fixGrammar", + "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", + ); + }, + "continue.viewLogs": async () => { + captureCommandTelemetry("viewLogs"); + + // Open ~/.continue/continue.log + const logFile = path.join(os.homedir(), ".continue", "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFile)) { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, ""); + } + + const uri = vscode.Uri.file(logFile); + await vscode.window.showTextDocument(uri); + }, + "continue.debugTerminal": async () => { + captureCommandTelemetry("debugTerminal"); + + const terminalContents = await ide.getTerminalContents(); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, + }); + }, + "continue.hideInlineTip": () => { + vscode.workspace + .getConfiguration(EXTENSION_NAME) + .update("showInlineTip", false, vscode.ConfigurationTarget.Global); + }, + + // Commands without keyboard shortcuts + "continue.addModel": () => { + captureCommandTelemetry("addModel"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("addModel", undefined); + }, + "continue.openSettingsUI": () => { + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("openSettings", undefined); + }, + "continue.sendMainUserInput": (text: string) => { + sidebar.webviewProtocol?.request("userInput", { + input: text, + }); + }, + "continue.selectRange": (startLine: number, endLine: number) => { + if (!vscode.window.activeTextEditor) { + return; + } + vscode.window.activeTextEditor.selection = new vscode.Selection( + startLine, + 0, + endLine, + 0, + ); + }, + "continue.foldAndUnfold": ( + foldSelectionLines: number[], + unfoldSelectionLines: number[], + ) => { + vscode.commands.executeCommand("editor.unfold", { + selectionLines: unfoldSelectionLines, + }); + vscode.commands.executeCommand("editor.fold", { + selectionLines: foldSelectionLines, + }); + }, + "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); + ide.runCommand(text); + }, + "continue.newSession": () => { + sidebar.webviewProtocol?.request("newSession", undefined); + }, + "continue.viewHistory": () => { + sidebar.webviewProtocol?.request("viewHistory", undefined); + }, + "continue.focusContinueSessionId": async ( + sessionId: string | undefined, + ) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID", }); - quickEdit.show(args); - }, - "continue.writeCommentsForCode": async () => { - captureCommandTelemetry("writeCommentsForCode"); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, + "continue.applyCodeFromChat": () => { + sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + }, + "continue.toggleFullScreen": () => { + focusGUI(); - streamInlineEdit( - "comment", - "Write comments for this code. Do not change anything about the code itself.", - ); - }, - "continue.writeDocstringForCode": async () => { - captureCommandTelemetry("writeDocstringForCode"); + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - ); - }, - "continue.fixCode": async () => { - captureCommandTelemetry("fixCode"); + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } - streamInlineEdit( - "fix", - "Fix this code. If it is already 100% correct, simply rewrite the code.", - ); - }, - "continue.optimizeCode": async () => { - captureCommandTelemetry("optimizeCode"); - streamInlineEdit("optimize", "Optimize this code"); - }, - "continue.fixGrammar": async () => { - captureCommandTelemetry("fixGrammar"); - streamInlineEdit( - "fixGrammar", - "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", - ); - }, - "continue.viewLogs": async () => { - captureCommandTelemetry("viewLogs"); + // Full screen not open - open it + captureCommandTelemetry("openFullScreen"); - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + }, + ); + fullScreenPanel = panel; - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); - }, - "continue.debugTerminal": async () => { - captureCommandTelemetry("debugTerminal"); + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); - const terminalContents = await ide.getTerminalContents(); + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); - vscode.commands.executeCommand("continue.continueGUIView.focus"); + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, + "continue.selectFilesAsContext": async ( + firstUri: vscode.Uri, + uris: vscode.Uri[], + ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } - sidebar.webviewProtocol?.request("userInput", { - input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, - }); - }, - "continue.hideInlineTip": () => { - vscode.workspace - .getConfiguration(EXTENSION_NAME) - .update("showInlineTip", false, vscode.ConfigurationTarget.Global); - }, + vscode.commands.executeCommand("continue.continueGUIView.focus"); - // Commands without keyboard shortcuts - "continue.addModel": () => { - captureCommandTelemetry("addModel"); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("addModel", undefined); - }, - "continue.openSettingsUI": () => { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("openSettings", undefined); - }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, - "continue.newSession": () => { - sidebar.webviewProtocol?.request("newSession", undefined); - }, - "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); - }, - "continue.focusContinueSessionId": async ( - sessionId: string | undefined, - ) => { - if (!sessionId) { - sessionId = await vscode.window.showInputBox({ - prompt: "Enter the Session ID", - }); - } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); - }, - "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); - }, - "continue.toggleFullScreen": () => { - focusGUI(); - - // Check if full screen is already open by checking open tabs - const fullScreenTab = getFullScreenTab(); - - if (fullScreenTab && fullScreenPanel) { - // Full screen open, but not focused - focus it - fullScreenPanel.reveal(); - return; - } - - // Full screen not open - open it - captureCommandTelemetry("openFullScreen"); - - // Create the full screen panel - let panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - { - retainContextWhenHidden: true, - }, - ); - fullScreenPanel = panel; - - // Add content to the panel - panel.webview.html = sidebar.getSidebarContent( - extensionContext, - panel, - undefined, - undefined, - true, - ); - - // When panel closes, reset the webview and focus - panel.onDidDispose( - () => { - sidebar.resetWebviewProtocolWebview(); - vscode.commands.executeCommand("continue.focusContinueInput"); - }, - null, - extensionContext.subscriptions, - ); - - vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); - }, - "continue.openConfigJson": () => { - ide.openFile(getConfigJsonPath()); - }, - "continue.selectFilesAsContext": async ( - firstUri: vscode.Uri, - uris: vscode.Uri[], - ) => { - if (uris === undefined) { - throw new Error("No files were selected"); - } - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - for (const uri of uris) { - // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) - const isDirectory = await vscode.workspace.fs - .stat(uri) - ?.then((stat) => stat.type === vscode.FileType.Directory); - if (isDirectory) { - for await (const filepath of walkDirAsync(uri.fsPath, ide)) { - addEntireFileToContext( - uriFromFilePath(filepath), - false, - sidebar.webviewProtocol, - ); - } - } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); + for (const uri of uris) { + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); } + } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); } - }, - "continue.logAutocompleteOutcome": ( - completionId: string, - completionProvider: CompletionProvider, - ) => { - completionProvider.accept(completionId); - }, - "continue.toggleTabAutocompleteEnabled": () => { - captureCommandTelemetry("toggleTabAutocompleteEnabled"); + } + }, + "continue.logAutocompleteOutcome": ( + completionId: string, + completionProvider: CompletionProvider, + ) => { + completionProvider.accept(completionId); + }, + "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const enabled = config.get("enableTabAutocomplete"); - const pauseOnBattery = config.get( - "pauseTabAutocompleteOnBattery", + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const enabled = config.get("enableTabAutocomplete"); + const pauseOnBattery = config.get( + "pauseTabAutocompleteOnBattery", + ); + if (!pauseOnBattery || battery.isACConnected()) { + config.update( + "enableTabAutocomplete", + !enabled, + vscode.ConfigurationTarget.Global, ); - if (!pauseOnBattery || battery.isACConnected()) { + } else { + if (enabled) { + const paused = getStatusBarStatus() === StatusBarStatus.Paused; + if (paused) { + setupStatusBar(StatusBarStatus.Enabled); + } else { + config.update( + "enableTabAutocomplete", + false, + vscode.ConfigurationTarget.Global, + ); + } + } else { + setupStatusBar(StatusBarStatus.Paused); config.update( "enableTabAutocomplete", - !enabled, + true, vscode.ConfigurationTarget.Global, ); - } else { - if (enabled) { - const paused = getStatusBarStatus() === StatusBarStatus.Paused; - if (paused) { - setupStatusBar(StatusBarStatus.Enabled); - } else { - config.update( - "enableTabAutocomplete", - false, - vscode.ConfigurationTarget.Global, - ); - } - } else { - setupStatusBar(StatusBarStatus.Paused); - config.update( - "enableTabAutocomplete", - true, - vscode.ConfigurationTarget.Global, - ); - } } - }, - "continue.openTabAutocompleteConfigMenu": async () => { - captureCommandTelemetry("openTabAutocompleteConfigMenu"); + } + }, + "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const quickPick = vscode.window.createQuickPick(); + const autocompleteModels = + (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0].title; - } + let selected = new GlobalContext().get("selectedTabAutocompleteModel"); + if ( + !selected || + !autocompleteModels.some((model) => model.title === selected) + ) { + selected = autocompleteModels[0].title; + } - // Toggle between Disabled, Paused, and Enabled - const pauseOnBattery = - config.get("pauseTabAutocompleteOnBattery") && - !battery.isACConnected(); - const currentStatus = getStatusBarStatus(); + // Toggle between Disabled, Paused, and Enabled + const pauseOnBattery = + config.get("pauseTabAutocompleteOnBattery") && + !battery.isACConnected(); + const currentStatus = getStatusBarStatus(); - let targetStatus: StatusBarStatus | undefined; - if (pauseOnBattery) { - // Cycle from Disabled -> Paused -> Enabled - targetStatus = - currentStatus === StatusBarStatus.Paused - ? StatusBarStatus.Enabled - : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused - : StatusBarStatus.Disabled; - } else { - // Toggle between Disabled and Enabled - targetStatus = - currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Enabled + let targetStatus: StatusBarStatus | undefined; + if (pauseOnBattery) { + // Cycle from Disabled -> Paused -> Enabled + targetStatus = + currentStatus === StatusBarStatus.Paused + ? StatusBarStatus.Enabled + : currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Paused : StatusBarStatus.Disabled; - } - quickPick.items = [ - { - label: "$(question) Open help center", - }, - { - label: "$(comment) Open chat (Cmd+L)", - }, - { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", - }, - { - label: quickPickStatusText(targetStatus), - }, - { - label: "$(gear) Configure autocomplete options", - }, - { - label: "$(feedback) Give feedback", - }, - { - kind: vscode.QuickPickItemKind.Separator, - label: "Switch model", - }, - ...autocompleteModels.map((model) => ({ - label: getAutocompleteStatusBarTitle(selected, model), - description: getAutocompleteStatusBarDescription(selected, model), - })), - ]; - quickPick.onDidAccept(() => { - const selectedOption = quickPick.selectedItems[0].label; - const targetStatus = - getStatusBarStatusFromQuickPickItemLabel(selectedOption); + } else { + // Toggle between Disabled and Enabled + targetStatus = + currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Enabled + : StatusBarStatus.Disabled; + } + quickPick.items = [ + { + label: "$(question) Open help center", + }, + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, + { + label: quickPickStatusText(targetStatus), + }, + { + label: "$(gear) Configure autocomplete options", + }, + { + label: "$(feedback) Give feedback", + }, + { + kind: vscode.QuickPickItemKind.Separator, + label: "Switch model", + }, + ...autocompleteModels.map((model) => ({ + label: getAutocompleteStatusBarTitle(selected, model), + description: getAutocompleteStatusBarDescription(selected, model), + })), + ]; + quickPick.onDidAccept(() => { + const selectedOption = quickPick.selectedItems[0].label; + const targetStatus = + getStatusBarStatusFromQuickPickItemLabel(selectedOption); - if (targetStatus !== undefined) { - setupStatusBar(targetStatus); - config.update( - "enableTabAutocomplete", - targetStatus === StatusBarStatus.Enabled, - vscode.ConfigurationTarget.Global, - ); - } else if ( - selectedOption === "$(gear) Configure autocomplete options" - ) { - ide.openFile(getConfigJsonPath()); - } else if ( - autocompleteModels.some((model) => model.title === selectedOption) - ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); - } else if (selectedOption === "$(feedback) Give feedback") { - vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { - vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { - vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); - } - quickPick.dispose(); - }); - quickPick.show(); - }, - "continue.giveAutocompleteFeedback": async () => { - const feedback = await vscode.window.showInputBox({ - ignoreFocusOut: true, - prompt: - "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", - }); - if (feedback) { - const client = await continueServerClientPromise; - const completionsPath = getDevDataFilePath("autocomplete"); - - const lastLines = await readLastLines.read(completionsPath, 2); - client.sendFeedback(feedback, lastLines); + if (targetStatus !== undefined) { + setupStatusBar(targetStatus); + config.update( + "enableTabAutocomplete", + targetStatus === StatusBarStatus.Enabled, + vscode.ConfigurationTarget.Global, + ); + } else if ( + selectedOption === "$(gear) Configure autocomplete options" + ) { + ide.openFile(getConfigJsonPath()); + } else if ( + autocompleteModels.some((model) => model.title === selectedOption) + ) { + new GlobalContext().update( + "selectedTabAutocompleteModel", + selectedOption, + ); + configHandler.reloadConfig(); + } else if (selectedOption === "$(feedback) Give feedback") { + vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if (selectedOption === "$(question) Open help center") { + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); } - }, - "continue.navigateTo": (path: string) => { - sidebar.webviewProtocol?.request("navigateTo", { path }); - focusGUI(); - }, - }; + quickPick.dispose(); + }); + quickPick.show(); + }, + "continue.giveAutocompleteFeedback": async () => { + const feedback = await vscode.window.showInputBox({ + ignoreFocusOut: true, + prompt: + "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", + }); + if (feedback) { + const client = await continueServerClientPromise; + const completionsPath = getDevDataFilePath("autocomplete"); + + const lastLines = await readLastLines.read(completionsPath, 2); + client.sendFeedback(feedback, lastLines); + } + }, + "continue.navigateTo": (path: string) => { + sidebar.webviewProtocol?.request("navigateTo", { path }); + focusGUI(); + }, }; +}; export function registerAllCommands( context: vscode.ExtensionContext, diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 0a4ceb5e3..7a04bf43a 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -18,6 +18,10 @@ export const VSC_INPUT_BORDER_FOCUS_VAR = "--vscode-focusBorder"; export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background"; export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground"; export const VSC_SIDEBAR_BORDER_VAR = "--vscode-sideBar-border"; +export const VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR = + "--vscode-diffEditor-removedLineBackground"; +export const VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR = + "--vscode-diffEditor-insertedLineBackground"; export const VSC_THEME_COLOR_VARS = [ VSC_INPUT_BACKGROUND_VAR, @@ -35,6 +39,8 @@ export const VSC_THEME_COLOR_VARS = [ VSC_BADGE_BACKGROUND_VAR, VSC_SIDEBAR_BORDER_VAR, VSC_BADGE_FOREGROUND_VAR, + VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, + VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, ]; export const defaultBorderRadius = "5px"; @@ -56,6 +62,8 @@ export const vscInputBorderFocus = `var(${VSC_INPUT_BORDER_FOCUS_VAR}, ${lightGr export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`; export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #fff)`; export const vscSidebarBorder = `var(${VSC_SIDEBAR_BORDER_VAR}, transparent)`; +export const vscDiffRemovedLineBackground = `var(${VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR}, #808080)`; +export const vscDiffInsertedLineBackground = `var(${VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR}, #28a745)`; if (typeof document !== "undefined") { for (const colorVar of VSC_THEME_COLOR_VARS) { @@ -101,20 +109,25 @@ export function parseColorForHex(colorVar: string): string { colorVar, ); if (value.startsWith("#")) { + console.log("OAIJFIOJOOJOIO", colorVar, value, value.slice(0, 7)); return value.slice(0, 7); } - // Parse rgb - const rgb = value - .slice(4, -1) + // Parse rgb/rgba + const rgbValues = value + .slice(value.startsWith("rgba") ? 5 : 4, -1) .split(",") + .map((x) => x.trim()) + .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) .map((x) => parseInt(x, 10)); + let hex = "#" + - rgb + rgbValues .map((x) => x.toString(16)) .map((x) => (x.length === 1 ? "0" + x : x)) .join(""); + return hex; } diff --git a/gui/src/pages/edit.tsx b/gui/src/pages/edit.tsx index f05648875..9629d4d66 100644 --- a/gui/src/pages/edit.tsx +++ b/gui/src/pages/edit.tsx @@ -7,7 +7,14 @@ import { useContext, useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscForeground } from "../components"; +import { + defaultBorderRadius, + lightGray, + parseColorForHex, + VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, + VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, + vscForeground, +} from "../components"; import FileIcon from "../components/FileIcon"; import { NewSessionButton } from "../components/mainInput/NewSessionButton"; import resolveEditorContent from "../components/mainInput/resolveInput"; @@ -162,7 +169,7 @@ function Edit() { placeholder={ ["streaming", "accepting"].includes(editModeState.editStatus) ? "Enter instructions for edit" - : "Enter follow-up instructions" + : "Enter instructions for edit" } border={`1px solid #aa0`} availableContextProviders={availableContextProviders.filter( @@ -203,7 +210,9 @@ function Edit() {
{ ideMessenger.request("edit/acceptReject", { accept: false, @@ -217,7 +226,9 @@ function Edit() { { ideMessenger.request("edit/acceptReject", { accept: true, @@ -240,7 +251,7 @@ function Edit() { className="mr-auto flex items-center gap-2" > - Back to chat + Back to Chat
From 4683ce871cdceda3ade1b2d9110582c38ce7e75d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 09:09:46 -0800 Subject: [PATCH 21/27] lmstudio embeddings p1 --- core/index.d.ts | 1 + core/indexing/embeddings/LMStudio.ts | 13 +++++++++++++ .../customize/model-providers/more/textgenwebui.md | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 core/indexing/embeddings/LMStudio.ts diff --git a/core/index.d.ts b/core/index.d.ts index ef8b7c128..1c14820af 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -834,6 +834,7 @@ export type EmbeddingsProviderName = | "ollama" | "openai" | "cohere" + | "lmstudio" | "free-trial" | "gemini" | "continue-proxy" diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts new file mode 100644 index 000000000..af5e390fb --- /dev/null +++ b/core/indexing/embeddings/LMStudio.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "lmstudio"; + + static defaultOptions: Partial | undefined = { + apiBase: "http://localhost:1234/v1", + model: "BAAI/bge-en-icl", + }; +} + +export default LMStudioEmbeddingsProvider; \ No newline at end of file diff --git a/docs/docs/customize/model-providers/more/textgenwebui.md b/docs/docs/customize/model-providers/more/textgenwebui.md index 9abf2b9e8..723079735 100644 --- a/docs/docs/customize/model-providers/more/textgenwebui.md +++ b/docs/docs/customize/model-providers/more/textgenwebui.md @@ -8,7 +8,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. { "title": "Text Generation WebUI", "provider": "text-gen-webui", - "apiBase": "http://localhost:5000", + "apiBase": "http://localhost:5000/v1", "model": "MODEL_NAME" } ] From 400d608a287e681c9fecde9f51a7c9c68ee79374 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 10:46:49 -0800 Subject: [PATCH 22/27] docs and config schema --- core/indexing/embeddings/LMStudio.ts | 2 +- core/indexing/embeddings/index.ts | 4 +++- .../customize/model-providers/more/lmstudio.md | 15 +++++++++++++++ extensions/vscode/config_schema.json | 7 ++++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts index af5e390fb..f5ec128d3 100644 --- a/core/indexing/embeddings/LMStudio.ts +++ b/core/indexing/embeddings/LMStudio.ts @@ -6,7 +6,7 @@ class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { static defaultOptions: Partial | undefined = { apiBase: "http://localhost:1234/v1", - model: "BAAI/bge-en-icl", + model: "nomic-ai/nomic-embed-text-v1.5-GGUF", }; } diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 7b62340e1..b0508d3fd 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -17,6 +17,7 @@ import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; +import LMStudioEmbeddingsProvider from "./LMStudio.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] @@ -42,5 +43,6 @@ export const allEmbeddingsProviders: Record< mistral: MistralEmbeddingsProvider, nebius: NebiusEmbeddingsProvider, vertexai: VertexEmbeddingsProvider, - watsonx: WatsonxEmbeddingsProvider + watsonx: WatsonxEmbeddingsProvider, + lmstudio: LMStudioEmbeddingsProvider }; diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 7448ebd01..466ccaaed 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -14,6 +14,21 @@ } ``` +### Embeddings model + +LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) + +```json title="config.json" +{ + "embeddingsProvider": [ + { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } + ] +} +``` + ## Setting up a remote instance To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f18bdbb6a..8dff320fd 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2717,13 +2717,18 @@ "openai", "cohere", "free-trial", + "continue-proxy", "gemini", "voyage", "nvidia", "bedrock", "sagemaker", "nebius", - "vertexai" + "vertexai", + "deepinfra", + "mistral", + "watsonx", + "lmstudio" ] }, "model": { From d764dddf75b373315ab6fd31d07b057f15d8ca88 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 10:55:43 -0800 Subject: [PATCH 23/27] embeddings docs fixes --- .../model-providers/more/lmstudio.md | 10 ++++---- .../customize/model-providers/more/nvidia.md | 12 ++++------ docs/docs/customize/model-types/embeddings.md | 24 +++++++++++++++++++ 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 466ccaaed..a901f811a 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -20,12 +20,10 @@ LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "lmstudio", - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" - } - ] + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } } ``` diff --git a/docs/docs/customize/model-providers/more/nvidia.md b/docs/docs/customize/model-providers/more/nvidia.md index e59f131b7..049ff7754 100644 --- a/docs/docs/customize/model-providers/more/nvidia.md +++ b/docs/docs/customize/model-providers/more/nvidia.md @@ -37,13 +37,11 @@ We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings m ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "nvidia", - "model": "nvidia/nv-embedqa-mistral-7b-v2", - "apiKey": "[API_KEY]" - } - ] + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } } ``` diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index 4bcc88785..882c5da79 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -13,6 +13,10 @@ In Continue, embeddings are generated during indexing and then used by [@Codebas `transformers.js` is used as a default embeddings model in VS Code. In JetBrains, there currently is no default. ::: +:::info[Free Trial] +The free trial supports embeddings (provider: `free-trial`) +::: + ## Recommended embedding models If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. @@ -77,3 +81,23 @@ See [here](../model-providers/top-level/gemini.md#embeddings-model) for instruct ### Vertex See [here](../model-providers/top-level/vertexai.md#embeddings-model) for instructions on how to use Vertex for embeddings. + +### Mistral + +See [here](../model-providers/top-level/mistral.md#embeddings-model) for instructions on how to use Mistral for embeddings. + +### NVIDIA + +See [here](../model-providers/more/nvidia.md#embeddings-model) for instructions on how to use NVIDIA for embeddings. + +### Bedrock + +See [here](../model-providers/top-level/bedrock.md#embeddings-model) for instructions on how to use Bedrock for embeddings. + +### WatsonX + +See [here](../model-providers/more/watsonx.md#embeddings-model) for instructions on how to use WatsonX for embeddings. + +### LMStudio + +See [here](../model-providers/more/lmstudio.md#embeddings-model) for instructions on how to use LMStudio for embeddings. From 9ce9fcbd6fcd854f864c41e592599ad86faa039f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 11:16:48 -0800 Subject: [PATCH 24/27] smooth scroll to bottom on session id change --- gui/src/pages/gui/Chat.tsx | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6ca0cc167..27e9be2cd 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -136,7 +136,6 @@ export function Chat() { const { streamResponse } = useChatHandler(dispatch, ideMessenger); const onboardingCard = useOnboardingCard(); const { showTutorialCard, closeTutorialCard } = useTutorialCard(); - const sessionState = useSelector((state: RootState) => state.state); const defaultModel = useSelector(defaultModelSelector); const ttsActive = useSelector((state: RootState) => state.state.ttsActive); const active = useSelector((state: RootState) => state.state.active); @@ -148,7 +147,7 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); - const scrollToBottom = useCallback(() => { + const snapToBottom = useCallback(() => { if (!topGuiDivRef.current) return; const elem = topGuiDivRef.current; elem.scrollTop = elem.scrollHeight - elem.clientHeight; @@ -156,9 +155,26 @@ export function Chat() { setIsAtBottom(true); }, [topGuiDivRef, setIsAtBottom]); + const smoothScrollToBottom = useCallback(async () => { + if (!topGuiDivRef.current) return; + const elem = topGuiDivRef.current + elem.scrollTo({ + top: elem.scrollHeight - elem.clientHeight, + behavior: 'smooth' + }) + + setIsAtBottom(true); + }, [topGuiDivRef, setIsAtBottom]); + useEffect(() => { - if (active) scrollToBottom(); - }, [active, scrollToBottom]); + if (active) snapToBottom(); + }, [active, snapToBottom]); + + useEffect(() => { + setTimeout(() => { + smoothScrollToBottom(); + }, 250) + }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { // Cmd + Backspace to delete current step @@ -284,8 +300,8 @@ export function Chat() { } }, [ - sessionState.history, - sessionState.contextItems, + state.history, + state.contextItems, defaultModel, state, streamResponse, @@ -370,11 +386,11 @@ export function Chat() { : true : stepsOpen[index]! } - onToggle={() => {}} + onToggle={() => { }} > {}} + onUserInput={(input: string) => { }} item={item} - onReverse={() => {}} + onReverse={() => { }} onRetry={() => { streamResponse( state.history[index - 1].editorState, state.history[index - 1].modifiers ?? - defaultInputModifiers, + defaultInputModifiers, ideMessenger, index - 1, ); From 7e1e88158a1062fa30dc5d4dc8a7ae5484628a62 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 11:49:47 -0800 Subject: [PATCH 25/27] update changelog --- .changes/unreleased/Added-20241108-113942.yaml | 4 ++++ .changes/unreleased/Added-20241108-114100.yaml | 4 ++++ .changes/unreleased/Added-20241108-114423.yaml | 4 ++++ .changes/unreleased/Added-20241108-114437.yaml | 4 ++++ .changes/unreleased/Added-20241108-114450.yaml | 4 ++++ .changes/unreleased/Added-20241108-114612.yaml | 4 ++++ .changes/unreleased/Added-20241108-114622.yaml | 4 ++++ .changes/unreleased/Added-20241108-114649.yaml | 4 ++++ .changes/unreleased/Added-20241108-114753.yaml | 4 ++++ .changes/unreleased/Added-20241108-114813.yaml | 4 ++++ .changes/unreleased/Changed-20241108-114549.yaml | 4 ++++ .changes/unreleased/Changed-20241108-114850.yaml | 4 ++++ .changes/unreleased/Fixed-20241108-114322.yaml | 4 ++++ .changes/unreleased/Fixed-20241108-114707.yaml | 4 ++++ .changes/unreleased/Fixed-20241108-114905.yaml | 4 ++++ extensions/intellij/CHANGELOG.md | 2 ++ extensions/vscode/CHANGELOG.md | 15 +++++++++++++++ 17 files changed, 77 insertions(+) create mode 100644 .changes/unreleased/Added-20241108-113942.yaml create mode 100644 .changes/unreleased/Added-20241108-114100.yaml create mode 100644 .changes/unreleased/Added-20241108-114423.yaml create mode 100644 .changes/unreleased/Added-20241108-114437.yaml create mode 100644 .changes/unreleased/Added-20241108-114450.yaml create mode 100644 .changes/unreleased/Added-20241108-114612.yaml create mode 100644 .changes/unreleased/Added-20241108-114622.yaml create mode 100644 .changes/unreleased/Added-20241108-114649.yaml create mode 100644 .changes/unreleased/Added-20241108-114753.yaml create mode 100644 .changes/unreleased/Added-20241108-114813.yaml create mode 100644 .changes/unreleased/Changed-20241108-114549.yaml create mode 100644 .changes/unreleased/Changed-20241108-114850.yaml create mode 100644 .changes/unreleased/Fixed-20241108-114322.yaml create mode 100644 .changes/unreleased/Fixed-20241108-114707.yaml create mode 100644 .changes/unreleased/Fixed-20241108-114905.yaml diff --git a/.changes/unreleased/Added-20241108-113942.yaml b/.changes/unreleased/Added-20241108-113942.yaml new file mode 100644 index 000000000..987643345 --- /dev/null +++ b/.changes/unreleased/Added-20241108-113942.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: OpenAI predicted outputs support +time: 2024-11-08T11:39:42.277047-08:00 diff --git a/.changes/unreleased/Added-20241108-114100.yaml b/.changes/unreleased/Added-20241108-114100.yaml new file mode 100644 index 000000000..af7cb5444 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114100.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improve codebase retrieval with BM25 +time: 2024-11-08T11:41:00.002716-08:00 diff --git a/.changes/unreleased/Added-20241108-114423.yaml b/.changes/unreleased/Added-20241108-114423.yaml new file mode 100644 index 000000000..fc3a6eaf7 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114423.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Grok from xAI +time: 2024-11-08T11:44:23.761084-08:00 diff --git a/.changes/unreleased/Added-20241108-114437.yaml b/.changes/unreleased/Added-20241108-114437.yaml new file mode 100644 index 000000000..fab18b954 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114437.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Chat enhancements including sticking input to bottom +time: 2024-11-08T11:44:37.408176-08:00 diff --git a/.changes/unreleased/Added-20241108-114450.yaml b/.changes/unreleased/Added-20241108-114450.yaml new file mode 100644 index 000000000..14644f3e9 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114450.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New UI for cmd+I in sidebar +time: 2024-11-08T11:44:50.682952-08:00 diff --git a/.changes/unreleased/Added-20241108-114612.yaml b/.changes/unreleased/Added-20241108-114612.yaml new file mode 100644 index 000000000..68d8b27d1 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114612.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Nebius LLM provider +time: 2024-11-08T11:46:12.94828-08:00 diff --git a/.changes/unreleased/Added-20241108-114622.yaml b/.changes/unreleased/Added-20241108-114622.yaml new file mode 100644 index 000000000..e91ddb398 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114622.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Ask Sage LLM provider +time: 2024-11-08T11:46:22.626907-08:00 diff --git a/.changes/unreleased/Added-20241108-114649.yaml b/.changes/unreleased/Added-20241108-114649.yaml new file mode 100644 index 000000000..0e7a0c9d0 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114649.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improved reference for config.json +time: 2024-11-08T11:46:49.648545-08:00 diff --git a/.changes/unreleased/Added-20241108-114753.yaml b/.changes/unreleased/Added-20241108-114753.yaml new file mode 100644 index 000000000..8cb7f1805 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114753.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New @web context provider +time: 2024-11-08T11:47:53.447346-08:00 diff --git a/.changes/unreleased/Added-20241108-114813.yaml b/.changes/unreleased/Added-20241108-114813.yaml new file mode 100644 index 000000000..cd5ba1067 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114813.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Updates for llama3.2 +time: 2024-11-08T11:48:13.830692-08:00 diff --git a/.changes/unreleased/Changed-20241108-114549.yaml b/.changes/unreleased/Changed-20241108-114549.yaml new file mode 100644 index 000000000..d340736b6 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114549.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Improved @docs crawler +time: 2024-11-08T11:45:49.381554-08:00 diff --git a/.changes/unreleased/Changed-20241108-114850.yaml b/.changes/unreleased/Changed-20241108-114850.yaml new file mode 100644 index 000000000..ab6c2a037 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114850.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Many improvements to make autocomplete more eager +time: 2024-11-08T11:48:50.486502-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114322.yaml b/.changes/unreleased/Fixed-20241108-114322.yaml new file mode 100644 index 000000000..e896eac4d --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114322.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: OSR-related fixes for non-Mac users +time: 2024-11-08T11:43:22.623155-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114707.yaml b/.changes/unreleased/Fixed-20241108-114707.yaml new file mode 100644 index 000000000..95c70c844 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114707.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: Fixes for inline edit in JetBrains +time: 2024-11-08T11:47:07.953304-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114905.yaml b/.changes/unreleased/Fixed-20241108-114905.yaml new file mode 100644 index 000000000..eb590eeb4 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114905.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Brought back the Apply button for all code blocks +time: 2024-11-08T11:49:05.021499-08:00 diff --git a/extensions/intellij/CHANGELOG.md b/extensions/intellij/CHANGELOG.md index 0eb45541f..7745d5c91 100644 --- a/extensions/intellij/CHANGELOG.md +++ b/extensions/intellij/CHANGELOG.md @@ -8,6 +8,8 @@ and is generated by [Changie](https://github.com/miniscruff/changie). Pre-release Changes ### Fixed * Off-screen rendering to solve white flash on load and lack of changing cursor type +* OSR-related fixes for non-Mac users +* Fixes for inline edit in JetBrains ## 0.0.72 - 2024-10-04 ### Added diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 030da9bcc..88925e7f4 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -9,6 +9,21 @@ Pre-release Changes ### Added * New Edit mode in sidebar (cmd/ctrl+I) * Significantly faster and more accurate docs crawler by default +* OpenAI predicted outputs support +* Improve codebase retrieval with BM25 +* Support for Grok from xAI +* Chat enhancements including sticking input to bottom +* New UI for cmd+I in sidebar +* Support for Nebius LLM provider +* Support for Ask Sage LLM provider +* Improved reference for config.json +* New @web context provider +* Updates for llama3.2 +### Changed +* Improved @docs crawler +* Many improvements to make autocomplete more eager +### Fixed +* Brought back the Apply button for all code blocks ## 0.8.55 - 2024-10-25 ### Added From 7c0474fbf71e13b85eb23904844d5405f5251068 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 13:07:45 -0800 Subject: [PATCH 26/27] bump down package.json --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 231f856c1..c38d47b0d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.227", + "version": "0.9.226", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From f779bf0bfbd239b11e5de4aef24086d5b2855c2d Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 13:40:26 -0800 Subject: [PATCH 27/27] fix type errors --- core/core.ts | 7 ++++--- extensions/vscode/package.json | 2 +- extensions/vscode/src/stubs/remoteConfig.ts | 15 ++++++++++++++- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/core/core.ts b/core/core.ts index a3f59ec8e..c26b786ac 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,3 +1,5 @@ +import ignore from "ignore"; +import path from "path"; import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import { CompletionProvider } from "./autocomplete/completionProvider"; @@ -17,6 +19,7 @@ import { ControlPlaneClient } from "./control-plane/client"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext"; @@ -29,9 +32,6 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import ignore from "ignore"; -import { defaultIgnoreFile } from "./indexing/ignore.js"; -import path from "path"; export class Core { // implements IMessenger @@ -401,6 +401,7 @@ export class Core { }); break; } + // @ts-ignore yield { content: next.value.content }; next = await gen.next(); } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 231f856c1..c38d47b0d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.227", + "version": "0.9.226", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/stubs/remoteConfig.ts b/extensions/vscode/src/stubs/remoteConfig.ts index 24c197bd8..eb3cba824 100644 --- a/extensions/vscode/src/stubs/remoteConfig.ts +++ b/extensions/vscode/src/stubs/remoteConfig.ts @@ -67,6 +67,18 @@ export class RemoteConfigSync { }; } + private canParse(url: string): boolean { + if ((URL as any).canParse) { + return (URL as any).canParse(url); + } + try { + new URL(url); + return true; + } catch (e) { + return false; + } + } + async setup() { if ( this.userToken === null || @@ -75,7 +87,7 @@ export class RemoteConfigSync { ) { return; } - if (!URL.canParse(this.remoteConfigServerUrl)) { + if (!this.canParse(this.remoteConfigServerUrl)) { vscode.window.showErrorMessage( "The value set for 'remoteConfigServerUrl' is not valid: ", this.remoteConfigServerUrl, @@ -92,6 +104,7 @@ export class RemoteConfigSync { private setInterval() { if (this.syncInterval !== undefined) { + // @ts-ignore clearInterval(this.syncInterval); } this.syncInterval = setInterval(