diff --git a/.vscode/launch.json b/.vscode/launch.json index ad855a194..c00f3a766 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,6 +5,18 @@ "version": "0.2.0", "compounds": [], "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Core Binary", + "skipFiles": ["/**"], + "program": "${workspaceFolder}/pkg/out/index.js", + "preLaunchTask": "pkg:esbuild", + "outFiles": ["${workspaceFolder}/pkg/out/**/*.js"], + "sourceMaps": true, + "smartStep": true, + "internalConsoleOptions": "openOnSessionStart" + }, { "type": "node", "request": "launch", diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c46520247..16c7f8614 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -136,6 +136,18 @@ } } ] + }, + // + // esbuild for the core binary + { + "label": "pkg:esbuild", + "type": "shell", + "command": "npm", + "args": ["run", "esbuild"], + "problemMatcher": [], + "options": { + "cwd": "pkg" + } } ] } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index f9f28704c..76300aa01 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -111,7 +111,8 @@ export async function constructAutocompletePrompt( line: number, character: number ) => Promise, - options: TabAutocompleteOptions + options: TabAutocompleteOptions, + modelName: string ): Promise<{ prefix: string; suffix: string; @@ -167,17 +168,17 @@ export async function constructAutocompletePrompt( .join("\n"); const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage - - countTokens(formattedSnippets, "gpt-4"); - let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens); + countTokens(formattedSnippets, modelName); + let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); if (formattedSnippets.length > 0) { prefix = formattedSnippets + "\n" + prefix; } const maxSuffixTokens = Math.min( - options.maxPromptTokens - countTokens(prefix, "gpt-4"), + options.maxPromptTokens - countTokens(prefix, modelName), options.maxSuffixPercentage * options.maxPromptTokens ); - let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens); + let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); return { prefix, suffix, useFim: true, completeMultiline }; } diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index ca0907674..0c95060f5 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -6,7 +6,6 @@ import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; import ShareSlashCommand from "./share"; import StackOverflowSlashCommand from "./stackOverflow"; -import VerticalEditSlashCommand from "./verticalEdit"; export default [ DraftIssueCommand, @@ -17,5 +16,4 @@ export default [ CommentSlashCommand, HttpSlashCommand, CommitMessageCommand, - VerticalEditSlashCommand, ]; diff --git a/core/config/default.ts b/core/config/default.ts index 7af901c99..d80e0ef7e 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -1,12 +1,17 @@ import { SerializedContinueConfig } from ".."; -const defaultConfig: SerializedContinueConfig = { +export const defaultConfig: SerializedContinueConfig = { models: [ { title: "GPT-4 Vision (Free Trial)", provider: "free-trial", model: "gpt-4-vision-preview", }, + { + title: "GPT-3.5-Turbo (Free Trial)", + provider: "free-trial", + model: "gpt-3.5-turbo", + }, { title: "Gemini Pro (Free Trial)", provider: "free-trial", @@ -29,7 +34,7 @@ const defaultConfig: SerializedContinueConfig = { }, { name: "share", - description: "Download and share this session", + description: "Export this session as markdown", }, { name: "cmd", @@ -56,4 +61,55 @@ const defaultConfig: SerializedContinueConfig = { ], }; -export default defaultConfig; +export const defaultConfigJetBrains: SerializedContinueConfig = { + models: [ + { + title: "GPT-4 Vision (Free Trial)", + provider: "free-trial", + model: "gpt-4-vision-preview", + }, + { + title: "GPT-3.5-Turbo (Free Trial)", + provider: "free-trial", + model: "gpt-3.5-turbo", + }, + { + title: "Gemini Pro (Free Trial)", + provider: "free-trial", + model: "gemini-pro", + }, + { + title: "Codellama 70b (Free Trial)", + provider: "free-trial", + model: "codellama-70b", + }, + ], + slashCommands: [ + { + name: "edit", + description: "Edit selected code", + }, + { + name: "comment", + description: "Write comments for the selected code", + }, + { + name: "share", + description: "Export this session as markdown", + }, + ], + customCommands: [ + { + name: "test", + prompt: + "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + description: "Write unit tests for highlighted code", + }, + ], + contextProviders: [ + { + name: "open", + params: {}, + }, + ], +}; diff --git a/core/config/handler.ts b/core/config/handler.ts new file mode 100644 index 000000000..341dfaf12 --- /dev/null +++ b/core/config/handler.ts @@ -0,0 +1,196 @@ +import { http, https } from "follow-redirects"; +import * as fs from "fs"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { HttpsProxyAgent } from "https-proxy-agent"; +import fetch from "node-fetch"; +import { ContinueConfig, ContinueRcJson, IDE, ILLM } from ".."; +import { Telemetry } from "../util/posthog"; +import { + BrowserSerializedContinueConfig, + finalToBrowserConfig, + loadFullConfigNode, +} from "./load"; +const tls = require("tls"); +export class ConfigHandler { + private savedConfig: ContinueConfig | undefined; + private savedBrowserConfig?: BrowserSerializedContinueConfig; + + private readonly ide: IDE; + constructor(ide: IDE) { + this.ide = ide; + try { + this.loadConfig(); + } catch (e) { + console.error("Failed to load config: ", e); + } + } + + reloadConfig() { + this.savedConfig = undefined; + this.savedBrowserConfig = undefined; + this.loadConfig(); + } + + async getSerializedConfig(): Promise { + if (!this.savedBrowserConfig) { + this.savedConfig = await this.loadConfig(); + this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig); + } + return this.savedBrowserConfig; + } + + async loadConfig(): Promise { + try { + if (this.savedConfig) { + return this.savedConfig; + } + + let workspaceConfigs: ContinueRcJson[] = []; + try { + workspaceConfigs = await this.ide.getWorkspaceConfigs(); + } catch (e) { + console.warn("Failed to load workspace configs"); + } + + const ideInfo = await this.ide.getIdeInfo(); + this.savedConfig = await loadFullConfigNode( + this.ide.readFile, + workspaceConfigs, + ideInfo.ideType + ); + this.savedConfig.allowAnonymousTelemetry = + this.savedConfig.allowAnonymousTelemetry && + (await this.ide.isTelemetryEnabled()); + + // Setup telemetry only after (and if) we know it is enabled + await Telemetry.setup( + this.savedConfig.allowAnonymousTelemetry ?? true, + await this.ide.getUniqueId() + ); + + return this.savedConfig; + } catch (e: any) { + console.error("Failed to loadConfig: ", e.message); + throw new Error("Failed to loadConfig: " + e.message); + } + } + + setupLlm(llm: ILLM): ILLM { + const TIMEOUT = 7200; // 7200 seconds = 2 hours + // Since we know this is happening in Node.js, we can add requestOptions through a custom agent + const ca = [...tls.rootCertificates]; + const customCerts = + typeof llm.requestOptions?.caBundlePath === "string" + ? [llm.requestOptions?.caBundlePath] + : llm.requestOptions?.caBundlePath; + if (customCerts) { + ca.push( + ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) + ); + } + + let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms + + const agentOptions = { + ca, + rejectUnauthorized: llm.requestOptions?.verifySsl, + timeout, + sessionTimeout: timeout, + keepAlive: true, + keepAliveMsecs: timeout, + }; + + const proxy = llm.requestOptions?.proxy; + + llm._fetch = async (input, init) => { + // Create agent + const protocol = new URL(input).protocol === "https:" ? https : http; + const agent = proxy + ? new URL(input).protocol === "https:" + ? new HttpsProxyAgent(proxy, agentOptions) + : new HttpProxyAgent(proxy, agentOptions) + : new protocol.Agent(agentOptions); + + const headers: { [key: string]: string } = + llm!.requestOptions?.headers || {}; + for (const [key, value] of Object.entries(init?.headers || {})) { + headers[key] = value as string; + } + + // Replace localhost with 127.0.0.1 + input = new URL(input); + if (input.hostname === "localhost") { + input.hostname = "127.0.0.1"; + } + + let updatedBody: string | undefined = undefined; + try { + if ( + llm.requestOptions?.extraBodyProperties && + typeof init.body === "string" + ) { + const parsedBody = JSON.parse(init.body); + updatedBody = JSON.stringify({ + ...parsedBody, + ...llm.requestOptions.extraBodyProperties, + }); + } + } catch (e) { + console.log("Unable to parse HTTP request body: ", e); + } + + const resp = await fetch(input, { + ...init, + body: updatedBody ?? init.body, + headers, + agent, + }); + + if (!resp.ok) { + let text = await resp.text(); + if (resp.status === 404 && !resp.url.includes("/v1")) { + if (text.includes("try pulling it first")) { + const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + } else if (text.includes("/api/chat")) { + text = + "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; + } else { + text = + "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; + } + } + throw new Error( + `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}` + ); + } + + return resp; + }; + + llm.writeLog = async (log: string) => { + // const outputChannel = vscode.window.createOutputChannel( + // "Continue - LLM Prompt/Completion" + // ); + // outputChannel.appendLine( + // "==========================================================================" + // ); + // outputChannel.appendLine( + // "==========================================================================" + // ); + // outputChannel.append(log); + }; + return llm; + } + + async llmFromTitle(title?: string): Promise { + const config = await this.loadConfig(); + const model = + config.models.find((m) => m.title === title) || config.models[0]; + if (!model) { + throw new Error("No model found"); + } + + return this.setupLlm(model); + } +} diff --git a/core/config/load.ts b/core/config/load.ts index e31d6da03..a978a3358 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,4 +1,5 @@ import * as fs from "fs"; +import path from "path"; import { BrowserSerializedContinueConfig, Config, @@ -9,11 +10,11 @@ import { CustomLLM, EmbeddingsProviderDescription, IContextProvider, + IdeType, ModelDescription, SerializedContinueConfig, SlashCommand, } from ".."; - import { slashCommandFromDescription, slashFromCustomCommand, @@ -36,6 +37,7 @@ import { getContinueDotEnv, migrate, } from "../util/paths"; +const { execSync } = require("child_process"); function resolveSerializedConfig(filepath: string): SerializedContinueConfig { let content = fs.readFileSync(filepath, "utf8"); @@ -59,9 +61,10 @@ function resolveSerializedConfig(filepath: string): SerializedContinueConfig { function loadSerializedConfig( workspaceConfigs: ContinueRcJson[], - remoteConfigServerUrl: URL | undefined + remoteConfigServerUrl: URL | undefined, + ideType: IdeType ): SerializedContinueConfig { - const configPath = getConfigJsonPath(); + const configPath = getConfigJsonPath(ideType); let config = resolveSerializedConfig(configPath); if (config.allowAnonymousTelemetry === undefined) { config.allowAnonymousTelemetry = true; @@ -320,53 +323,101 @@ function finalToBrowserConfig( }; } -async function buildConfigTs(browser: boolean) { +function getTarget() { + const os = + { + aix: "linux", + darwin: "darwin", + freebsd: "linux", + linux: "linux", + openbsd: "linux", + sunos: "linux", + win32: "win32", + }[process.platform as string] ?? "linux"; + const arch = { + arm: "arm64", + arm64: "arm64", + ia32: "x64", + loong64: "arm64", + mips: "arm64", + mipsel: "arm64", + ppc: "x64", + ppc64: "x64", + riscv64: "arm64", + s390: "x64", + s390x: "x64", + x64: "x64", + }[process.arch]; + + return `${os}-${arch}`; +} + +function escapeSpacesInPath(p: string): string { + return p.replace(/ /g, "\\ "); +} + +async function buildConfigTs() { if (!fs.existsSync(getConfigTsPath())) { return undefined; } try { - // Dynamic import esbuild so potentially disastrous errors can be caught - const esbuild = require("esbuild"); + if (process.env.IS_BINARY === "true") { + execSync( + escapeSpacesInPath(path.dirname(process.execPath)) + + `/esbuild${ + getTarget().startsWith("win32") ? ".exe" : "" + } ${escapeSpacesInPath( + getConfigTsPath() + )} --bundle --outfile=${escapeSpacesInPath( + getConfigJsPath() + )} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process` + ); + } else { + // Dynamic import esbuild so potentially disastrous errors can be caught + const esbuild = require("esbuild"); - await esbuild.build({ - entryPoints: [getConfigTsPath()], - bundle: true, - platform: browser ? "browser" : "node", - format: browser ? "esm" : "cjs", - outfile: getConfigJsPath(!browser), - external: ["fetch", "fs", "path", "os", "child_process"], - sourcemap: true, - }); + await esbuild.build({ + entryPoints: [getConfigTsPath()], + bundle: true, + platform: "node", + format: "cjs", + outfile: getConfigJsPath(), + external: ["fetch", "fs", "path", "os", "child_process"], + sourcemap: true, + }); + } } catch (e) { - throw new Error( + console.log( "Build error. Please check your ~/.continue/config.ts file: " + e ); return undefined; } - if (!fs.existsSync(getConfigJsPath(!browser))) { + if (!fs.existsSync(getConfigJsPath())) { return undefined; } - return fs.readFileSync(getConfigJsPath(!browser), "utf8"); + return fs.readFileSync(getConfigJsPath(), "utf8"); } async function loadFullConfigNode( readFile: (filepath: string) => Promise, workspaceConfigs: ContinueRcJson[], - remoteConfigServerUrl: URL | undefined + remoteConfigServerUrl: URL | undefined, + ideType: IdeType ): Promise { let serialized = loadSerializedConfig( workspaceConfigs, - remoteConfigServerUrl + remoteConfigServerUrl, + ideType ); let intermediate = serializedToIntermediateConfig(serialized); - const configJsContents = await buildConfigTs(false); + const configJsContents = await buildConfigTs(); if (configJsContents) { try { // Try config.ts first - const configJsPath = getConfigJsPath(true); + const configJsPath = getConfigJsPath(); const module = await require(configJsPath); delete require.cache[require.resolve(configJsPath)]; if (!module.modifyConfig) { diff --git a/core/config/types.ts b/core/config/types.ts index c3070041a..976dc3f89 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -15,7 +15,11 @@ declare global { }; colorThemeName?: string; workspacePaths?: string[]; - postIntellijMessage?: (type: string, data: any) => void; + postIntellijMessage?: ( + messageType: string, + data: any, + messageIde: string + ) => void; } } @@ -313,13 +317,24 @@ declare global { message: string; } + export type IdeType = "vscode" | "jetbrains"; + export interface IdeInfo { + ideType: IdeType; + name: string; + version: string; + remoteName: string; + } + export interface IDE { - getSerializedConfig(): Promise; + getIdeInfo(): Promise; getDiff(): Promise; + isTelemetryEnabled(): Promise; + getUniqueId(): Promise; getTerminalContents(): Promise; listWorkspaceContents(directory?: string): Promise; listFolders(): Promise; getWorkspaceDirs(): Promise; + getWorkspaceConfigs(): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; getContinueDir(): Promise; @@ -327,6 +342,7 @@ declare global { runCommand(command: string): Promise; saveFile(filepath: string): Promise; readFile(filepath: string): Promise; + readRangeInFile(filepath: string, range: Range): Promise; showLines( filepath: string, startLine: number, @@ -337,34 +353,13 @@ declare global { newContents: string, stepIndex: number ): Promise; - verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ): Promise; getOpenFiles(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; getProblems(filepath?: string | undefined): Promise; getBranch(dir: string): Promise; - - // Embeddings - /** - * Returns list of [tag, filepath, hash of contents] that need to be embedded - */ - getFilesToEmbed(providerId: string): Promise<[string, string, string][]>; - sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ): void; - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise; + getStats(directory: string): Promise<{ [path: string]: number }>; } // Slash Commands @@ -377,6 +372,8 @@ declare global { input: string; params?: { [key: string]: any } | undefined; contextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + config: ContinueConfig; } export interface SlashCommand { diff --git a/core/config/util.ts b/core/config/util.ts new file mode 100644 index 000000000..94ebda6b8 --- /dev/null +++ b/core/config/util.ts @@ -0,0 +1,38 @@ +import { readFileSync, writeFileSync } from "fs"; +import { ModelDescription } from ".."; +import { editConfigJson, getConfigJsonPath } from "../util/paths"; + +export function addModel(model: ModelDescription) { + const config = readFileSync(getConfigJsonPath(), "utf8"); + const configJson = JSON.parse(config); + configJson.models.push(model); + const newConfigString = JSON.stringify( + configJson, + (key, value) => { + return value === null ? undefined : value; + }, + 2 + ); + writeFileSync(getConfigJsonPath(), newConfigString); + return newConfigString; +} + +export function addOpenAIKey(key: string) { + editConfigJson((config) => { + config.models = config.models.map((m: ModelDescription) => { + if (m.provider === "free-trial") { + m.apiKey = key; + m.provider = "openai"; + } + return m; + }); + return config; + }); +} + +export function deleteModel(title: string) { + editConfigJson((config) => { + config.models = config.models.filter((m: any) => m.title !== title); + return config; + }); +} diff --git a/core/context/retrieval.ts b/core/context/retrieval.ts index 547977257..41de15304 100644 --- a/core/context/retrieval.ts +++ b/core/context/retrieval.ts @@ -1,5 +1,6 @@ import { Chunk, ContextItem, ContextProviderExtras, ILLM } from ".."; import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch"; +import { LanceDbIndex } from "../indexing/LanceDbIndex"; import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex"; import { IndexTag } from "../indexing/types"; import { llmCanGenerateInParallel } from "../llm/autodetect"; @@ -147,7 +148,11 @@ export async function retrieveContextItemsFromEmbeddings( console.warn("Error retrieving from FTS:", e); } - let vecResults = await extras.ide.retrieveChunks( + const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) => + extras.ide.readFile(path) + ); + let vecResults = await lanceDbIndex.retrieve( + tags, extras.fullInput, nRetrieve, filterDirectory diff --git a/core/ide/index.ts b/core/ide/index.ts deleted file mode 100644 index 255c26a8e..000000000 --- a/core/ide/index.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { Chunk, DiffLine, Problem } from ".."; -import { BrowserSerializedContinueConfig } from "../config/load"; -import { IDE } from "../index"; - -import { ideRequest } from "./messaging"; -async function r(messageType: string, options: any = {}) { - return await ideRequest(messageType, options); -} -export class ExtensionIde implements IDE { - async getSerializedConfig(): Promise { - return await r("getSerializedConfig"); - } - - async getDiff() { - return await r("getDiff"); - } - - async getTerminalContents() { - return await r("getTerminalContents"); - } - - async listWorkspaceContents(directory?: string): Promise { - return await r("listWorkspaceContents"); - } - - async getWorkspaceDirs(): Promise { - return await r("getWorkspaceDirs"); - } - - async showLines( - filepath: string, - startLine: number, - endLine: number - ): Promise { - return await r("showLines", { filepath, startLine, endLine }); - } - - async listFolders(): Promise { - return await r("listFolders"); - } - - _continueDir: string | null = null; - - async getContinueDir(): Promise { - if (this._continueDir) { - return this._continueDir; - } - const dir = await r("getContinueDir"); - this._continueDir = dir; - return dir; - } - - async writeFile(path: string, contents: string): Promise { - await r("writeFile", { path, contents }); - } - - async showVirtualFile(title: string, contents: string): Promise { - await r("showVirtualFile", { name: title, content: contents }); - } - - async openFile(path: string): Promise { - await r("openFile", { path }); - } - - async runCommand(command: string): Promise { - await r("runCommand", { command }); - } - - async saveFile(filepath: string): Promise { - await r("saveFile", { filepath }); - } - async readFile(filepath: string): Promise { - return await r("readFile", { filepath }); - } - async showDiff( - filepath: string, - newContents: string, - stepIndex: number - ): Promise { - await r("showDiff", { filepath, newContents, stepIndex }); - } - - async verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ) { - await r("diffLine", { filepath, startLine, endLine, diffLine }); - } - - getOpenFiles(): Promise { - return r("getOpenFiles"); - } - - getPinnedFiles(): Promise { - return r("getPinnedFiles"); - } - - getSearchResults(query: string): Promise { - return r("getSearchResults", { query }); - } - - getProblems(filepath?: string | undefined): Promise { - return r("getProblems", { filepath }); - } - - subprocess(command: string): Promise<[string, string]> { - return r("subprocess", { command }); - } - - getFilesToEmbed(providerId: string): Promise<[string, string, string][]> { - return r("getFilesToEmbed", { providerId }); - } - - sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) { - return r("sendChunkForFile", { chunk, embedding, tags }); - } - - async getBranch(dir: string): Promise { - return r("getBranch", { dir }); - } - - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - return r("retrieveChunks", { text, n, directory }); - } -} diff --git a/core/ide/messaging.ts b/core/ide/messaging.ts deleted file mode 100644 index 6b7cc639a..000000000 --- a/core/ide/messaging.ts +++ /dev/null @@ -1,142 +0,0 @@ -// import "vscode-webview"; -import { v4 as uuidv4 } from "uuid"; -import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from ".."; -interface vscode { - postMessage(message: any): vscode; -} - -declare const vscode: any; - -function _postToIde(type: string, data: any) { - if (typeof vscode === "undefined") { - if (localStorage.getItem("ide") === "jetbrains") { - if (window.postIntellijMessage === undefined) { - console.log( - "Unable to send message: postIntellijMessage is undefined. ", - type, - data - ); - throw new Error("postIntellijMessage is undefined"); - } - window.postIntellijMessage?.(type, data); - return; - } else { - console.log("Unable to send message: vscode is undefined. ", type, data); - return; - } - } - vscode.postMessage({ - type, - ...data, - }); -} - -export function postToIde(type: string, data: any, attempt: number = 0) { - try { - _postToIde(type, data); - } catch (error) { - if (attempt < 5) { - console.log(`Attempt ${attempt} failed. Retrying...`); - setTimeout( - () => postToIde(type, data, attempt + 1), - Math.pow(2, attempt) * 1000 - ); - } else { - console.error("Max attempts reached. Message could not be sent.", error); - } - } -} - -export async function ideRequest(type: string, message: any): Promise { - // message, messageId, and type are passed back and forth - const messageId = uuidv4(); - - return new Promise((resolve) => { - const handler = (event: any) => { - if (event.data.messageId === messageId) { - window.removeEventListener("message", handler); - resolve(event.data.message); - } - }; - window.addEventListener("message", handler); - - postToIde(type, { message, messageId }); - }); -} - -export async function* ideStreamRequest( - type: string, - message: any, - cancelToken?: AbortSignal -): AsyncGenerator { - const messageId = uuidv4(); - - postToIde(type, { message, messageId }); - - let buffer = ""; - let index = 0; - let done = false; - let returnVal = undefined; - - const handler = (event: any) => { - if (event.data.messageId === messageId) { - if (event.data.message.done) { - window.removeEventListener("message", handler); - done = true; - returnVal = event.data.message.data; - } else { - buffer += event.data.message.content || ""; - } - } - }; - window.addEventListener("message", handler); - - cancelToken?.addEventListener("abort", () => { - postToIde("abort", { messageId }); - }); - - while (!done) { - if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; - yield chunk; - } else { - yield undefined; - } - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; - yield chunk; - } - - return returnVal; -} - -export async function* llmStreamChat( - modelTitle: string, - cancelToken: AbortSignal | undefined, - messages: ChatMessage[], - options: LLMFullCompletionOptions = {} -): AsyncGenerator { - const gen = ideStreamRequest( - "llmStreamChat", - { - messages, - title: modelTitle, - completionOptions: options, - }, - cancelToken - ); - - let next = await gen.next(); - while (!next.done) { - if (next.value) { - yield { role: "user", content: next.value }; - } - next = await gen.next(); - } - return { prompt: next.value?.prompt, completion: next.value?.completion }; -} diff --git a/core/index.d.ts b/core/index.d.ts index dd68f20f2..a9e8af006 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -13,7 +13,11 @@ declare global { }; colorThemeName?: string; workspacePaths?: string[]; - postIntellijMessage?: (type: string, data: any) => void; + postIntellijMessage?: ( + messageType: string, + data: any, + messageIde: string + ) => void; } } @@ -311,13 +315,24 @@ export class Problem { message: string; } +export type IdeType = "vscode" | "jetbrains"; +export interface IdeInfo { + ideType: IdeType; + name: string; + version: string; + remoteName: string; +} + export interface IDE { - getSerializedConfig(): Promise; + getIdeInfo(): Promise; getDiff(): Promise; + isTelemetryEnabled(): Promise; + getUniqueId(): Promise; getTerminalContents(): Promise; listWorkspaceContents(directory?: string): Promise; listFolders(): Promise; getWorkspaceDirs(): Promise; + getWorkspaceConfigs(): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; getContinueDir(): Promise; @@ -325,6 +340,7 @@ export interface IDE { runCommand(command: string): Promise; saveFile(filepath: string): Promise; readFile(filepath: string): Promise; + readRangeInFile(filepath: string, range: Range): Promise; showLines( filepath: string, startLine: number, @@ -335,34 +351,13 @@ export interface IDE { newContents: string, stepIndex: number ): Promise; - verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ): Promise; getOpenFiles(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; getProblems(filepath?: string | undefined): Promise; getBranch(dir: string): Promise; - - // Embeddings - /** - * Returns list of [tag, filepath, hash of contents] that need to be embedded - */ - getFilesToEmbed(providerId: string): Promise<[string, string, string][]>; - sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ): void; - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise; + getStats(directory: string): Promise<{ [path: string]: number }>; } // Slash Commands @@ -375,6 +370,8 @@ export interface ContinueSDK { input: string; params?: { [key: string]: any } | undefined; contextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + config: ContinueConfig; } export interface SlashCommand { diff --git a/core/indexing/chunk/basic.ts b/core/indexing/chunk/basic.ts index 60bda5995..e0e506a90 100644 --- a/core/indexing/chunk/basic.ts +++ b/core/indexing/chunk/basic.ts @@ -11,7 +11,7 @@ export function* basicChunker( let currLine = 0; for (const line of contents.split("\n")) { - const lineTokens = countTokens(line, "gpt-4"); + const lineTokens = countTokens(line); if (chunkTokens + lineTokens > maxChunkSize - 5) { yield { content: chunkContent, startLine, endLine: currLine - 1 }; chunkContent = ""; diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index bfb33eb5c..0132bc08d 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -43,11 +43,11 @@ export async function* chunkDocument( contents, maxChunkSize )) { - if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) { + if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) { console.warn( `Chunk with more than ${maxChunkSize} tokens constructed: `, filepath, - countTokens(chunkWithoutId.content, "gpt-4") + countTokens(chunkWithoutId.content) ); continue; } diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index b9862c634..b7527d422 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -59,10 +59,7 @@ function collapseChildren( } code = code.slice(node.startIndex); let removedChild = false; - while ( - countTokens(code, "gpt-4") > maxChunkSize && - collapsedChildren.length > 0 - ) { + while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) { removedChild = true; // Remove children starting at the end - TODO: Add multiple chunks so no children are missing const childCode = collapsedChildren.pop()!; @@ -169,7 +166,7 @@ function* getSmartCollapsedChunks( // Keep entire text if not over size if ( (root || node.type in collapsedNodeConstructors) && - countTokens(node.text, "gpt-4") < maxChunkSize + countTokens(node.text) < maxChunkSize ) { yield { content: node.text, diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index 0e0901cf0..252d43f5e 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -57,7 +57,7 @@ export async function* markdownChunker( maxChunkSize: number, hLevel: number ): AsyncGenerator { - if (countTokens(content, "gpt-4") <= maxChunkSize) { + if (countTokens(content) <= maxChunkSize) { const header = findHeader(content.split("\n")); yield { content, @@ -122,8 +122,7 @@ export async function* markdownChunker( for (const section of sections) { for await (const chunk of markdownChunker( section.content, - maxChunkSize - - (section.header ? countTokens(section.header, "gpt-4") : 0), + maxChunkSize - (section.header ? countTokens(section.header) : 0), hLevel + 1 )) { yield { diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts index 4773e6f0b..e959b699f 100644 --- a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts +++ b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts @@ -1,37 +1,12 @@ -import { - PipelineType, - env, - pipeline, -} from "../../vendor/node_modules/@xenova/transformers"; - +import { Worker } from "worker_threads"; import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; -env.allowLocalModels = true; -env.allowRemoteModels = false; -if (typeof window === "undefined") { - // The embeddings provider should just never be called in the browser - env.localModelPath = `${__dirname}/../models`; -} - -class EmbeddingsPipeline { - static task: PipelineType = "feature-extraction"; - static model = "all-MiniLM-L6-v2"; - static instance: any | null = null; - - static async getInstance() { - if (this.instance === null) { - this.instance = await pipeline(this.task, this.model); - } - - return this.instance; - } -} - class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { static MaxGroupSize: number = 4; + static ModelName: string = "all-MiniLM-L2-v6"; constructor() { - super({ model: "all-MiniLM-L2-v6" }); + super({ model: TransformersJsEmbeddingsProvider.ModelName }); } get id(): string { @@ -39,33 +14,27 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { } async embed(chunks: string[]) { - let extractor = await EmbeddingsPipeline.getInstance(); + return new Promise((resolve, reject) => { + const worker = new Worker("./TransformersJsWorkerThread.js"); - if (!extractor) { - throw new Error("TransformerJS embeddings pipeline is not initialized"); - } + worker.postMessage(chunks); - if (chunks.length === 0) { - return []; - } - - let outputs = []; - for ( - let i = 0; - i < chunks.length; - i += TransformersJsEmbeddingsProvider.MaxGroupSize - ) { - let chunkGroup = chunks.slice( - i, - i + TransformersJsEmbeddingsProvider.MaxGroupSize - ); - let output = await extractor(chunkGroup, { - pooling: "mean", - normalize: true, + worker.on("message", (result) => { + if (result.error) { + reject(new Error(result.error)); + } else { + resolve(result); + } }); - outputs.push(...output.tolist()); - } - return outputs; + + worker.on("error", reject); + + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }) as any; } } diff --git a/core/indexing/embeddings/TransformersJsWorkerThread.js b/core/indexing/embeddings/TransformersJsWorkerThread.js new file mode 100644 index 000000000..775e16a05 --- /dev/null +++ b/core/indexing/embeddings/TransformersJsWorkerThread.js @@ -0,0 +1,58 @@ +import { + env, + pipeline, +} from "../../vendor/node_modules/@xenova/transformers/types/transformers"; +import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider"; +const { parentPort } = require("worker_threads"); + +env.allowLocalModels = true; +env.allowRemoteModels = false; +if (typeof window === "undefined") { + // The embeddings provider should just never be called in the browser + env.localModelPath = `${__dirname}/../models`; +} + +class EmbeddingsPipeline { + static task = "feature-extraction"; + static model = TransformersJsEmbeddingsProvider.ModelName; + static instance = null; + + static async getInstance() { + if (this.instance === null) { + this.instance = await pipeline(this.task, this.model); + } + + return this.instance; + } +} + +parentPort.on("message", async (chunks) => { + try { + const extractor = await EmbeddingsPipeline.getInstance(); + + if (!extractor) { + throw new Error("TransformerJS embeddings pipeline is not initialized"); + } + + let outputs = []; + for ( + let i = 0; + i < chunks.length; + i += TransformersJsEmbeddingsProvider.MaxGroupSize + ) { + let chunkGroup = chunks.slice( + i, + i + TransformersJsEmbeddingsProvider.MaxGroupSize + ); + let output = await extractor(chunkGroup, { + pooling: "mean", + normalize: true, + }); + outputs.push(...output.tolist()); + } + + parentPort.postMessage(outputs); + } catch (error) { + parentPort.postMessage({ error: error.message }); + } +}); diff --git a/core/indexing/indexCodebase.ts b/core/indexing/indexCodebase.ts new file mode 100644 index 000000000..32c85f2b9 --- /dev/null +++ b/core/indexing/indexCodebase.ts @@ -0,0 +1,94 @@ +import { IDE, IndexingProgressUpdate } from ".."; +import { ConfigHandler } from "../config/handler"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearch"; +import { LanceDbIndex } from "./LanceDbIndex"; +import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; +import { getComputeDeleteAddRemove } from "./refreshIndex"; +import { CodebaseIndex, IndexTag } from "./types"; + +export class CodebaseIndexer { + configHandler: ConfigHandler; + ide: IDE; + constructor(configHandler: ConfigHandler, ide: IDE) { + this.configHandler = configHandler; + this.ide = ide; + } + + private async getIndexesToBuild(): Promise { + const config = await this.configHandler.loadConfig(); + + const indexes = [ + new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first + new LanceDbIndex( + config.embeddingsProvider, + this.ide.readFile.bind(this.ide) + ), + new FullTextSearchCodebaseIndex(), + ]; + + return indexes; + } + + async *refresh( + workspaceDirs: string[] + ): AsyncGenerator { + const config = await this.configHandler.loadConfig(); + if (config.disableIndexing) { + return; + } + + const indexesToBuild = await this.getIndexesToBuild(); + + let completedDirs = 0; + + for (let directory of workspaceDirs) { + const stats = await this.ide.getStats(directory); + const branch = await this.ide.getBranch(directory); + let completedIndexes = 0; + + try { + for (let codebaseIndex of indexesToBuild) { + const tag: IndexTag = { + directory, + branch, + artifactId: codebaseIndex.artifactId, + }; + const [results, markComplete] = await getComputeDeleteAddRemove( + tag, + { ...stats }, + (filepath) => this.ide.readFile(filepath) + ); + + for await (let { progress, desc } of codebaseIndex.update( + tag, + results, + markComplete + )) { + yield { + progress: + (completedDirs + + (completedIndexes + progress) / indexesToBuild.length) / + workspaceDirs.length, + desc, + }; + } + completedIndexes++; + yield { + progress: + (completedDirs + completedIndexes / indexesToBuild.length) / + workspaceDirs.length, + desc: "Completed indexing " + codebaseIndex.artifactId, + }; + } + } catch (e) { + console.warn("Error refreshing index: ", e); + } + + completedDirs++; + yield { + progress: completedDirs / workspaceDirs.length, + desc: "Indexing Complete", + }; + } + } +} diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 6283ad782..fddbee08a 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,16 +1,29 @@ -import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken"; +import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; +// @ts-expect-error +import llamaTokenizer from "llama-tokenizer-js"; import { ChatMessage, MessageContent, MessagePart } from ".."; +import { autodetectTemplateType } from "./autodetect"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants"; -let encoding: Tiktoken | null = null; +interface Encoding { + encode: Tiktoken["encode"]; + decode: Tiktoken["decode"]; +} -function encodingForModel(modelName: string): Tiktoken { - if (encoding) { - return encoding; +let gptEncoding: Encoding | null = null; + +function encodingForModel(modelName: string): Encoding { + const modelType = autodetectTemplateType(modelName); + + if (!modelType || modelType === "none") { + if (!gptEncoding) { + gptEncoding = _encodingForModel("gpt-4"); + } + + return gptEncoding; } - encoding = _encodingForModel("gpt-4"); - return encoding; + return llamaTokenizer; } function countImageTokens(content: MessagePart): number { @@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number { } } -function countTokens(content: MessageContent, modelName: string): number { +function countTokens( + content: MessageContent, + // defaults to llama2 because the tokenizer tends to produce more tokens + modelName: string = "llama2" +): number { const encoding = encodingForModel(modelName); if (Array.isArray(content)) { return content.reduce((acc, part) => { @@ -72,21 +89,29 @@ function countChatMessageTokens( return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE; } -function pruneLinesFromTop(prompt: string, maxTokens: number): string { - let totalTokens = countTokens(prompt, "gpt-4"); +function pruneLinesFromTop( + prompt: string, + maxTokens: number, + modelName: string +): string { + let totalTokens = countTokens(prompt, modelName); const lines = prompt.split("\n"); while (totalTokens > maxTokens && lines.length > 0) { - totalTokens -= countTokens(lines.shift()!, "gpt-4"); + totalTokens -= countTokens(lines.shift()!, modelName); } return lines.join("\n"); } -function pruneLinesFromBottom(prompt: string, maxTokens: number): string { - let totalTokens = countTokens(prompt, "gpt-4"); +function pruneLinesFromBottom( + prompt: string, + maxTokens: number, + modelName: string +): string { + let totalTokens = countTokens(prompt, modelName); const lines = prompt.split("\n"); while (totalTokens > maxTokens && lines.length > 0) { - totalTokens -= countTokens(lines.pop()!, "gpt-4"); + totalTokens -= countTokens(lines.pop()!, modelName); } return lines.join("\n"); diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 054a636d8..60ec16432 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -25,40 +25,44 @@ class Ollama extends BaseLLM { method: "POST", headers: {}, body: JSON.stringify({ name: this._getModel() }), - }).then(async (response) => { - if (response.status !== 200) { - console.warn( - "Error calling Ollama /api/show endpoint: ", - await response.text() - ); - return; - } - const body = await response.json(); - if (body.parameters) { - const params = []; - for (let line of body.parameters.split("\n")) { - let parts = line.split(" "); - if (parts.length < 2) { - continue; - } - let key = parts[0]; - let value = parts[parts.length - 1]; - switch (key) { - case "num_ctx": - this.contextLength = parseInt(value); - break; - case "stop": - if (!this.completionOptions.stop) { - this.completionOptions.stop = []; - } - this.completionOptions.stop.push(value); - break; - default: - break; + }) + .then(async (response) => { + if (response.status !== 200) { + console.warn( + "Error calling Ollama /api/show endpoint: ", + await response.text() + ); + return; + } + const body = await response.json(); + if (body.parameters) { + const params = []; + for (let line of body.parameters.split("\n")) { + let parts = line.split(" "); + if (parts.length < 2) { + continue; + } + let key = parts[0]; + let value = parts[parts.length - 1]; + switch (key) { + case "num_ctx": + this.contextLength = parseInt(value); + break; + case "stop": + if (!this.completionOptions.stop) { + this.completionOptions.stop = []; + } + this.completionOptions.stop.push(value); + break; + default: + break; + } } } - } - }); + }) + .catch((e) => { + console.warn(`Error calling Ollama /api/show endpoint: ${e}`); + }); } private _getModel() { diff --git a/core/package-lock.json b/core/package-lock.json index 3ead17d84..36faa3471 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -15,9 +15,13 @@ "adf-to-md": "^1.1.0", "axios": "^1.6.7", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.13", "node-fetch": "^3.3.2", @@ -35,6 +39,7 @@ "web-tree-sitter": "^0.20.8" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", @@ -2046,6 +2051,15 @@ "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" }, + "node_modules/@types/follow-redirects": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz", + "integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", @@ -2251,15 +2265,14 @@ } }, "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "optional": true, + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", + "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", "dependencies": { - "debug": "4" + "debug": "^4.3.4" }, "engines": { - "node": ">= 6.0.0" + "node": ">= 14" } }, "node_modules/agentkeepalive": { @@ -2401,6 +2414,20 @@ "node": "^12.13.0 || ^14.15.0 || >=16.0.0" } }, + "node_modules/are-we-there-yet/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -2740,6 +2767,42 @@ "readable-stream": "^3.4.0" } }, + "node_modules/bl/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -2820,9 +2883,9 @@ } }, "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", "funding": [ { "type": "github", @@ -2837,9 +2900,10 @@ "url": "https://feross.org/support" } ], + "optional": true, "dependencies": { "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "ieee754": "^1.2.1" } }, "node_modules/buffer-from": { @@ -3201,6 +3265,14 @@ "node": ">=12.17" } }, + "node_modules/commander": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz", + "integrity": "sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==", + "engines": { + "node": ">=18" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -4928,30 +5000,27 @@ "optional": true }, "node_modules/http-proxy-agent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", - "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", - "optional": true, + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.1.tgz", + "integrity": "sha512-My1KCEPs6A0hb4qCVzYp8iEvA8j8YqcvXLZZH8C9OFuTYpYjHE7N2dtG3mRl1HMD4+VGXpF3XcDVcxGBT7yDZQ==", "dependencies": { - "@tootallnate/once": "1", - "agent-base": "6", - "debug": "4" + "agent-base": "^7.1.0", + "debug": "^4.3.4" }, "engines": { - "node": ">= 6" + "node": ">= 14" } }, "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "optional": true, + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz", + "integrity": "sha512-kCnwztfX0KZJSLOBrcL0emLeFako55NWMovvyPP2AjsghNk9RB1yjSI+jVumPHYZsNXegNoqupSW9IY3afSH8w==", "dependencies": { - "agent-base": "6", + "agent-base": "^7.0.2", "debug": "4" }, "engines": { - "node": ">= 6" + "node": ">= 14" } }, "node_modules/human-signals": { @@ -6212,6 +6281,11 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, + "node_modules/llama-tokenizer-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/llama-tokenizer-js/-/llama-tokenizer-js-1.1.3.tgz", + "integrity": "sha512-+BUgsLCXVQJkjiD/t7PdESLn+yXJIRX/BJfwzVVYfKZ9aN3gsP9xoadBZxKnCxGz2Slby+S7x41gUr2TKNaS4Q==" + }, "node_modules/llm-code-highlighter": { "version": "0.0.13", "resolved": "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.13.tgz", @@ -6358,6 +6432,45 @@ "node": ">= 10" } }, + "node_modules/make-fetch-happen/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/make-fetch-happen/node_modules/http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "optional": true, + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/make-fetch-happen/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/make-fetch-happen/node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -7339,6 +7452,19 @@ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" }, + "node_modules/prebuild-install/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/prebuild-install/node_modules/tar-fs": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", @@ -7559,16 +7685,19 @@ "dev": true }, "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "optional": true, "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" }, "engines": { - "node": ">= 6" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/regexp.prototype.flags": { @@ -7610,46 +7739,6 @@ "readable-stream": ">=4.0.0" } }, - "node_modules/replicate/node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "optional": true, - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, - "node_modules/replicate/node_modules/readable-stream": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", - "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", - "optional": true, - "dependencies": { - "abort-controller": "^3.0.0", - "buffer": "^6.0.3", - "events": "^3.3.0", - "process": "^0.11.10", - "string_decoder": "^1.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -8097,6 +8186,18 @@ "node": ">= 10" } }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", diff --git a/core/package.json b/core/package.json index 7b79ffe41..1f16c40bf 100644 --- a/core/package.json +++ b/core/package.json @@ -8,6 +8,7 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", @@ -24,11 +25,16 @@ "adf-to-md": "^1.1.0", "axios": "^1.6.7", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.13", + "llama-tokenizer-js": "^1.1.3", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", diff --git a/core/protocol.ts b/core/protocol.ts new file mode 100644 index 000000000..4247291e9 --- /dev/null +++ b/core/protocol.ts @@ -0,0 +1,98 @@ +import { + BrowserSerializedContinueConfig, + ChatMessage, + ContextItemWithId, + ContextSubmenuItem, + LLMFullCompletionOptions, + MessageContent, + PersistedSessionInfo, + RangeInFile, + SerializedContinueConfig, + SessionInfo, +} from "."; + +export type ProtocolGeneratorType = AsyncGenerator<{ + done?: boolean; + content: T; +}>; + +export type Protocol = { + // New + "update/modelChange": [string, void]; + // Special + ping: [string, string]; + abort: [undefined, void]; + + // History + "history/list": [undefined, SessionInfo[]]; + "history/delete": [{ id: string }, void]; + "history/load": [{ id: string }, PersistedSessionInfo]; + "history/save": [PersistedSessionInfo, void]; + "devdata/log": [{ tableName: string; data: any }, void]; + "config/addOpenAiKey": [string, void]; + "config/addModel": [ + { model: SerializedContinueConfig["models"][number] }, + void, + ]; + "config/getBrowserSerialized": [ + undefined, + Promise, + ]; + "config/deleteModel": [{ title: string }, void]; + "config/reload": [undefined, Promise]; + "context/getContextItems": [ + { + name: string; + query: string; + fullInput: string; + selectedCode: RangeInFile[]; + }, + Promise, + ]; + "context/loadSubmenuItems": [ + { title: string }, + Promise, + ]; + "context/addDocs": [{ title: string; url: string }, void]; + "autocomplete/complete": [ + { filepath: string; line: number; column: number }, + string[], + ]; + "command/run": [ + { + input: string; + history: ChatMessage[]; + modelTitle: string; + slashCommandName: string; + contextItems: ContextItemWithId[]; + params: any; + historyIndex: number; + selectedCode: RangeInFile[]; + }, + ProtocolGeneratorType, + ]; + "llm/complete": [ + { + prompt: string; + completionOptions: LLMFullCompletionOptions; + title: string; + }, + string, + ]; + "llm/streamComplete": [ + { + prompt: string; + completionOptions: LLMFullCompletionOptions; + title: string; + }, + ProtocolGeneratorType, + ]; + "llm/streamChat": [ + { + messages: ChatMessage[]; + completionOptions: LLMFullCompletionOptions; + title: string; + }, + ProtocolGeneratorType, + ]; +}; diff --git a/core/test/edit.test.ts b/core/test/edit.test.ts index 4682601d1..d4186915d 100644 --- a/core/test/edit.test.ts +++ b/core/test/edit.test.ts @@ -2,10 +2,10 @@ import * as dotenv from "dotenv"; import { ContinueSDK } from ".."; import EditSlashCommand, { getPromptParts } from "../commands/slash/edit"; import { contextItemToRangeInFileWithContents } from "../commands/util"; -import FileSystemIde from "../ide/filesystem"; import FreeTrial from "../llm/llms/FreeTrial"; import Ollama from "../llm/llms/Ollama"; import { dedentAndGetCommonWhitespace } from "../util"; +import FileSystemIde from "../util/filesystem"; jest.setTimeout(100_000); @@ -62,6 +62,8 @@ describe("/edit slash command", () => { history: [], input: "implement this function", contextItems: [TEST_CONTEXT_ITEM], + selectedCode: [], + config: {} as any, }; let total = ""; diff --git a/core/tsconfig.json b/core/tsconfig.json index 8adaca34f..91573d8a6 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -18,5 +18,5 @@ "noEmitOnError": false, "types": ["jest", "node"] }, - "include": ["./**/*.ts"] + "include": ["./**/*.ts", "indexing/embeddings/TransformersJsWorkerThread.js"] } diff --git a/core/util/devdata.ts b/core/util/devdata.ts new file mode 100644 index 000000000..bb98b2527 --- /dev/null +++ b/core/util/devdata.ts @@ -0,0 +1,8 @@ +import { writeFileSync } from "fs"; +import { getDevDataFilePath } from "./paths"; + +export function logDevData(tableName: string, data: any) { + const filepath: string = getDevDataFilePath(tableName); + const jsonLine = JSON.stringify(data); + writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); +} diff --git a/core/ide/filesystem.ts b/core/util/filesystem.ts similarity index 76% rename from core/ide/filesystem.ts rename to core/util/filesystem.ts index 910dd022a..edc883cec 100644 --- a/core/ide/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,12 +1,30 @@ import * as fs from "fs"; -import { DiffLine, IDE, Problem } from ".."; -import { BrowserSerializedContinueConfig } from "../config/load"; -import { Chunk } from "../index"; -import { getContinueGlobalPath } from "../util/paths"; +import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from ".."; +import { getContinueGlobalPath } from "./paths"; class FileSystemIde implements IDE { - async getSerializedConfig(): Promise { - throw new Error("Not implemented"); + getIdeInfo(): Promise { + return Promise.resolve({ + ideType: "vscode", + name: "na", + version: "0.1", + remoteName: "na", + }); + } + readRangeInFile(filepath: string, range: Range): Promise { + return Promise.resolve(""); + } + getStats(directory: string): Promise<{ [path: string]: number }> { + return Promise.resolve({}); + } + isTelemetryEnabled(): Promise { + return Promise.resolve(false); + } + getUniqueId(): Promise { + return Promise.resolve("NOT_UNIQUE"); + } + getWorkspaceConfigs(): Promise { + return Promise.resolve([]); } getDiff(): Promise { @@ -92,15 +110,6 @@ class FileSystemIde implements IDE { return Promise.resolve(""); } - async verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ) { - return Promise.resolve(); - } - getOpenFiles(): Promise { return Promise.resolve([]); } @@ -120,20 +129,6 @@ class FileSystemIde implements IDE { async subprocess(command: string): Promise<[string, string]> { return ["", ""]; } - - getFilesToEmbed(providerId: string): Promise<[string, string, string][]> { - return Promise.resolve([]); - } - - sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {} - - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - return Promise.resolve([]); - } } export default FileSystemIde; diff --git a/extensions/vscode/src/history.ts b/core/util/history.ts similarity index 95% rename from extensions/vscode/src/history.ts rename to core/util/history.ts index 87ed290d9..bab04c4f8 100644 --- a/extensions/vscode/src/history.ts +++ b/core/util/history.ts @@ -1,9 +1,9 @@ -import { PersistedSessionInfo, SessionInfo } from "core"; -import { getSessionFilePath, getSessionsListPath } from "core/util/paths"; import * as fs from "fs"; +import { PersistedSessionInfo, SessionInfo } from ".."; +import { getSessionFilePath, getSessionsListPath } from "./paths"; class HistoryManager { - list(): PersistedSessionInfo[] { + list(): SessionInfo[] { const filepath = getSessionsListPath(); if (!fs.existsSync(filepath)) { return []; diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts new file mode 100644 index 000000000..8534394c6 --- /dev/null +++ b/core/util/messageIde.ts @@ -0,0 +1,121 @@ +import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from ".."; + +export class MessageIde implements IDE { + constructor( + private readonly request: (messageType: string, data: any) => Promise + ) {} + getIdeInfo(): Promise { + return this.request("getIdeInfo", undefined); + } + + readRangeInFile(filepath: string, range: Range): Promise { + return this.request("readRangeInFile", { filepath, range }); + } + getStats(directory: string): Promise<{ [path: string]: number }> { + throw new Error("Method not implemented."); + } + isTelemetryEnabled(): Promise { + return this.request("isTelemetryEnabled", undefined); + } + + getUniqueId(): Promise { + return this.request("getUniqueId", undefined); + } + + getWorkspaceConfigs(): Promise { + return this.request("getWorkspaceConfigs", undefined); + } + + async getDiff() { + return await this.request("getDiff", undefined); + } + + async getTerminalContents() { + return await this.request("getTerminalContents", undefined); + } + + async listWorkspaceContents(directory?: string): Promise { + return await this.request("listWorkspaceContents", undefined); + } + + async getWorkspaceDirs(): Promise { + return await this.request("getWorkspaceDirs", undefined); + } + + async showLines( + filepath: string, + startLine: number, + endLine: number + ): Promise { + return await this.request("showLines", { filepath, startLine, endLine }); + } + + async listFolders(): Promise { + return await this.request("listFolders", undefined); + } + + _continueDir: string | null = null; + + async getContinueDir(): Promise { + if (this._continueDir) { + return this._continueDir; + } + const dir = await this.request("getContinueDir", undefined); + this._continueDir = dir; + return dir; + } + + async writeFile(path: string, contents: string): Promise { + await this.request("writeFile", { path, contents }); + } + + async showVirtualFile(title: string, contents: string): Promise { + await this.request("showVirtualFile", { name: title, content: contents }); + } + + async openFile(path: string): Promise { + await this.request("openFile", { path }); + } + + async runCommand(command: string): Promise { + await this.request("runCommand", { command }); + } + + async saveFile(filepath: string): Promise { + await this.request("saveFile", { filepath }); + } + async readFile(filepath: string): Promise { + return await this.request("readFile", { filepath }); + } + async showDiff( + filepath: string, + newContents: string, + stepIndex: number + ): Promise { + await this.request("showDiff", { filepath, newContents, stepIndex }); + } + + getOpenFiles(): Promise { + return this.request("getOpenFiles", undefined); + } + + getPinnedFiles(): Promise { + return this.request("getPinnedFiles", undefined); + } + + getSearchResults(query: string): Promise { + return this.request("getSearchResults", { query }); + } + + getProblems(filepath?: string | undefined): Promise { + return this.request("getProblems", { filepath }); + } + + subprocess(command: string): Promise<[string, string]> { + return this.request("subprocess", { command }); + } + + async getBranch(dir: string): Promise { + return this.request("getBranch", { dir }); + } +} diff --git a/core/util/messenger.ts b/core/util/messenger.ts new file mode 100644 index 000000000..9f12b9630 --- /dev/null +++ b/core/util/messenger.ts @@ -0,0 +1,5 @@ +export interface Message { + messageType: string; + messageId: string; + data: T; +} diff --git a/core/util/paths.ts b/core/util/paths.ts index 5bec526b8..8fe150d9c 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -2,8 +2,8 @@ import dotenv from "dotenv"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; -import { SerializedContinueConfig } from ".."; -import defaultConfig from "../config/default"; +import { IdeType, SerializedContinueConfig } from ".."; +import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; export function getContinueGlobalPath(): string { @@ -43,10 +43,14 @@ export function getSessionsListPath(): string { return filepath; } -export function getConfigJsonPath(): string { +export function getConfigJsonPath(ideType: IdeType = "vscode"): string { const p = path.join(getContinueGlobalPath(), "config.json"); if (!fs.existsSync(p)) { - fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2)); + if (ideType === "jetbrains") { + fs.writeFileSync(p, JSON.stringify(defaultConfigJetBrains, null, 2)); + } else { + fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2)); + } } return p; } @@ -87,13 +91,9 @@ export function getConfigTsPath(): string { return p; } -export function getConfigJsPath(node: boolean): string { +export function getConfigJsPath(): string { // Do not create automatically - return path.join( - getContinueGlobalPath(), - "out", - `config${node ? ".node" : ""}.js` - ); + return path.join(getContinueGlobalPath(), "out", "config.js"); } export function getTsConfigPath(): string { @@ -220,3 +220,7 @@ export function getContinueDotEnv(): { [key: string]: string } { return {}; } } + +export function getCoreLogsPath(): string { + return path.join(getContinueGlobalPath(), "core.log"); +} diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 99bd3905d..887fa2390 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -19,14 +19,18 @@ export class Telemetry { if (!allow) { Telemetry.client = undefined; } else { - if (!Telemetry.client) { - const { PostHog } = await import("posthog-node"); - Telemetry.client = new PostHog( - "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", - { - host: "https://app.posthog.com", - } - ); + try { + if (!Telemetry.client) { + const { PostHog } = await import("posthog-node"); + Telemetry.client = new PostHog( + "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", + { + host: "https://app.posthog.com", + } + ); + } + } catch (e) { + console.error(`Failed to setup telemetry: ${e}`); } } } diff --git a/core/commands/slash/verticalEdit.ts b/core/util/verticalEdit.ts similarity index 56% rename from core/commands/slash/verticalEdit.ts rename to core/util/verticalEdit.ts index 387f818a2..81b55628b 100644 --- a/core/commands/slash/verticalEdit.ts +++ b/core/util/verticalEdit.ts @@ -1,24 +1,16 @@ -import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../.."; +import { DiffLine, ILLM } from ".."; import { filterCodeBlockLines, filterEnglishLinesAtEnd, filterEnglishLinesAtStart, filterLeadingAndTrailingNewLineInsertion, fixCodeLlamaFirstLineIndentation, -} from "../../autocomplete/lineStream"; -import { streamDiff } from "../../diff/streamDiff"; -import { streamLines } from "../../diff/util"; -import { stripImages } from "../../llm/countTokens"; -import { gptEditPrompt } from "../../llm/templates/edit"; -import { - dedentAndGetCommonWhitespace, - getMarkdownLanguageTagForFile, - renderPromptTemplate, -} from "../../util"; -import { - RangeInFileWithContents, - contextItemToRangeInFileWithContents, -} from "../util"; +} from "../autocomplete/lineStream"; +import { streamDiff } from "../diff/streamDiff"; +import { streamLines } from "../diff/util"; +import { stripImages } from "../llm/countTokens"; +import { gptEditPrompt } from "../llm/templates/edit"; +import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util"; function constructPrompt( codeToEdit: string, @@ -87,38 +79,3 @@ export async function* streamDiffLines( yield diffLine; } } - -const VerticalEditSlashCommand: SlashCommand = { - name: "verticalEdit", - description: "Edit selected code with vertical diff", - run: async function* ({ ide, llm, input, contextItems }) { - const contextItemToEdit = contextItems.find( - (item: ContextItemWithId) => - item.editing && item.id.providerTitle === "code" - ); - - if (!contextItemToEdit) { - yield "Highlight the code that you want to edit first"; - return; - } - - const rif: RangeInFileWithContents = - contextItemToRangeInFileWithContents(contextItemToEdit); - const startLine = rif.range.start.line; - const endLine = rif.range.end.line; - const filepath = rif.filepath; - - const diffLineGenerator = streamDiffLines( - rif.contents, - llm, - input, - getMarkdownLanguageTagForFile(rif.filepath) - ); - - for await (const diffLine of diffLineGenerator) { - await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine); - } - }, -}; - -export default VerticalEditSlashCommand; diff --git a/core/vendor/package-lock.json b/core/vendor/package-lock.json index 64225d017..3f8229af6 100644 --- a/core/vendor/package-lock.json +++ b/core/vendor/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "vendor", "version": "1.0.0", - "license": "ISC", + "license": "Apache-2.0", "dependencies": { "@xenova/transformers": "^2.14.0" } diff --git a/core/vendor/package.json b/core/vendor/package.json index a7838e858..07cd4c0d6 100644 --- a/core/vendor/package.json +++ b/core/vendor/package.json @@ -7,7 +7,7 @@ "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", - "license": "ISC", + "license": "Apache-2.0", "dependencies": { "@xenova/transformers": "^2.14.0" } diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts new file mode 100644 index 000000000..bc61add77 --- /dev/null +++ b/core/web/webviewProtocol.ts @@ -0,0 +1,101 @@ +import { + ContextItemWithId, + ContinueRcJson, + DiffLine, + Problem, + Range, +} from ".."; +import { RangeInFileWithContents } from "../commands/util"; +import { Protocol } from "../protocol"; + +export type IdeProtocol = { + listWorkspaceContents: [undefined, string[]]; + getWorkspaceDirs: [undefined, string[]]; + listFolders: [undefined, string[]]; + writeFile: [{ path: string; contents: string }, void]; + showVirtualFile: [{ name: string; content: string }, void]; + getContinueDir: [undefined, string]; + openFile: [{ path: string }, void]; + runCommand: [{ command: string }, void]; + getSearchResults: [{ query: string }, string]; + subprocess: [{ command: string }, [string, string]]; + saveFile: [{ filepath: string }, void]; + readFile: [{ filepath: string }, string]; + showDiff: [ + { filepath: string; newContents: string; stepIndex: number }, + void, + ]; + diffLine: [ + { + diffLine: DiffLine; + filepath: string; + startLine: number; + endLine: number; + }, + void, + ]; + getProblems: [{ filepath: string }, Problem[]]; + getBranch: [{ dir: string }, string]; + getOpenFiles: [undefined, string[]]; + getPinnedFiles: [undefined, string[]]; + showLines: [{ filepath: string; startLine: number; endLine: number }, void]; + readRangeInFile: [{ filepath: string; range: Range }, string]; + getDiff: [undefined, string]; + getWorkspaceConfigs: [undefined, ContinueRcJson[]]; + getTerminalContents: [undefined, string]; + isTelemetryEnabled: [undefined, boolean]; + getUniqueId: [undefined, string]; +}; + +export type WebviewProtocol = Protocol & + IdeProtocol & { + onLoad: [ + undefined, + { + windowId: string; + serverUrl: string; + workspacePaths: string[]; + vscMachineId: string; + vscMediaUrl: string; + }, + ]; + + errorPopup: [{ message: string }, void]; + applyToCurrentFile: [{ text: string }, void]; + showTutorial: [undefined, void]; + showFile: [{ filepath: string }, void]; + openConfigJson: [undefined, void]; + + toggleDevTools: [undefined, void]; + reloadWindow: [undefined, void]; + focusEditor: [undefined, void]; + toggleFullScreen: [undefined, void]; + }; + +export type ReverseWebviewProtocol = { + setInactive: [undefined, void]; + configUpdate: [undefined, void]; + submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap + addContextItem: [ + { + historyIndex: number; + item: ContextItemWithId; + }, + void, + ]; + getDefaultModelTitle: [undefined, string]; + newSessionWithPrompt: [{ prompt: string }, void]; + userInput: [{ input: string }, void]; + focusContinueInput: [undefined, void]; + focusContinueInputWithoutClear: [undefined, void]; + focusContinueInputWithNewSession: [undefined, void]; + highlightedCode: [{ rangeInFileWithContents: RangeInFileWithContents }, void]; + addModel: [undefined, void]; + openSettings: [undefined, void]; + viewHistory: [undefined, void]; + indexProgress: [{ progress: number; desc: string }, void]; + newSession: [undefined, void]; + refreshSubmenuItems: [undefined, void]; + setTheme: [{ theme: any }, void]; + setColors: [{ [key: string]: string }, void]; +}; diff --git a/core/yarn.lock b/core/yarn.lock index 28e83a183..a0f4ee245 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -899,6 +899,13 @@ resolved "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz" integrity sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg== +"@types/follow-redirects@^1.14.4": + version "1.14.4" + resolved "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz" + integrity sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA== + dependencies: + "@types/node" "*" + "@types/graceful-fs@^4.1.3": version "4.1.9" resolved "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz" @@ -1685,6 +1692,11 @@ command-line-usage@^7.0.0, command-line-usage@7.0.1: table-layout "^3.0.0" typical "^7.1.1" +commander@^12.0.0: + version "12.0.0" + resolved "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz" + integrity sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA== + concat-map@0.0.1: version "0.0.1" resolved "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" @@ -2758,6 +2770,14 @@ http-proxy-agent@^4.0.1: agent-base "6" debug "4" +http-proxy-agent@^7.0.1: + version "7.0.1" + resolved "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.1.tgz" + integrity sha512-My1KCEPs6A0hb4qCVzYp8iEvA8j8YqcvXLZZH8C9OFuTYpYjHE7N2dtG3mRl1HMD4+VGXpF3XcDVcxGBT7yDZQ== + dependencies: + agent-base "^7.1.0" + debug "^4.3.4" + https-proxy-agent@^5.0.0: version "5.0.1" resolved "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz" @@ -2766,6 +2786,14 @@ https-proxy-agent@^5.0.0: agent-base "6" debug "4" +https-proxy-agent@^7.0.3: + version "7.0.3" + resolved "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz" + integrity sha512-kCnwztfX0KZJSLOBrcL0emLeFako55NWMovvyPP2AjsghNk9RB1yjSI+jVumPHYZsNXegNoqupSW9IY3afSH8w== + dependencies: + agent-base "^7.0.2" + debug "4" + human-signals@^2.1.0: version "2.1.0" resolved "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz" @@ -4320,7 +4348,25 @@ react-is@^18.0.0: resolved "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz" integrity sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w== -readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0: +readable-stream@^3.1.1: + version "3.6.2" + resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readable-stream@^3.4.0: + version "3.6.2" + resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readable-stream@^3.6.0: version "3.6.2" resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz" integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index 73ab23c38..9873b602d 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -1 +1,2 @@ -src/main/resources/webview \ No newline at end of file +src/main/resources/webview +src/main/resources/bin \ No newline at end of file diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 5c1ee1e69..034edeef4 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -79,6 +79,12 @@ koverReport { } tasks { + prepareSandbox { + from("../../pkg/bin") { + into("${intellij.pluginName.get()}/core/") + } + } + wrapper { gradleVersion = properties("gradleVersion").get() } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 627737abd..bd4b41270 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.27 +pluginVersion = 0.0.33 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index 0fca2a3e8..3e1aaa1d5 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -4,13 +4,11 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.ToolWindowManager import java.awt.Dimension -import java.awt.GridLayout import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener @@ -130,7 +128,7 @@ class QuickTextEntryAction : AnAction() { } continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput"))) + continuePluginService.sendToWebview("focusContinueInput", null) } } @@ -179,7 +177,7 @@ class FocusContinueInputWithoutClearAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithoutClear"))) + continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) continuePluginService.ideProtocolClient?.sendHighlightedCode() } @@ -202,7 +200,7 @@ class FocusContinueInputAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput"))) + continuePluginService.sendToWebview("focusContinueInput", null) continuePluginService.ideProtocolClient?.sendHighlightedCode() } @@ -225,7 +223,7 @@ class NewContinueSessionAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithNewSession"))) + continuePluginService.sendToWebview("focusContinueInputWithNewSession", null) } } @@ -239,6 +237,6 @@ class ViewHistoryAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "viewHistory"))) + continuePluginService.sendToWebview("viewHistory", null) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index dccb3fd0a..14e829b43 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -1,9 +1,7 @@ package com.github.continuedev.continueintellijextension.activities import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath -import com.github.continuedev.continueintellijextension.`continue`.startProxyServer -import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy -import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient +import com.github.continuedev.continueintellijextension.`continue`.* import com.github.continuedev.continueintellijextension.listeners.ContinuePluginSelectionListener import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService @@ -30,7 +28,9 @@ import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths import javax.swing.* - +import com.intellij.openapi.application.PathManager; +import com.intellij.ide.plugins.PluginManager +import com.intellij.openapi.extensions.PluginId class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) { private var panel: JPanel? = null @@ -78,6 +78,28 @@ class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) { } } +fun showTutorial(project: Project) { + ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` -> + if (`is` == null) { + throw IOException("Resource not found: continue_tutorial.py") + } + var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) + if (!System.getProperty("os.name").toLowerCase().contains("mac")) { + content = content.replace("⌘", "⌃") + } + val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString() + File(filepath).writeText(content) + val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath) + + + ApplicationManager.getApplication().invokeLater { + if (virtualFile != null) { + FileEditorManager.getInstance(project).openFile(virtualFile, true) + } + } + } +} + class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.IO) @@ -121,6 +143,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { ContinuePluginService::class.java ) + val theme = GetTheme().getTheme() + val defaultStrategy = DefaultTextSelectionStrategy() coroutineScope.launch { @@ -129,24 +153,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { if (!settings.continueState.shownWelcomeDialog) { settings.continueState.shownWelcomeDialog = true // Open continue_tutorial.py - ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` -> - if (`is` == null) { - throw IOException("Resource not found: continue_tutorial.py") - } - var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) - if (!System.getProperty("os.name").toLowerCase().contains("mac")) { - content = content.replace("⌘", "⌃") - } - val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString() - File(filepath).writeText(content) - val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath) - - if (virtualFile != null) { - ApplicationManager.getApplication().invokeLater { - FileEditorManager.getInstance(project).openFile(virtualFile, true) - } - } - } + showTutorial(project) // Show the welcome dialog // withContext(Dispatchers.Main) { @@ -156,17 +163,17 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // settings.continueState.shownWelcomeDialog = true } - GlobalScope.async(Dispatchers.IO) { - val ideProtocolClient = IdeProtocolClient( + val ideProtocolClient = IdeProtocolClient( continuePluginService, defaultStrategy, coroutineScope, project.basePath, project - ) + ) - continuePluginService.ideProtocolClient = ideProtocolClient + continuePluginService.ideProtocolClient = ideProtocolClient + GlobalScope.async(Dispatchers.IO) { val listener = ContinuePluginSelectionListener( ideProtocolClient, @@ -193,6 +200,34 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { } } + GlobalScope.async(Dispatchers.IO) { + val myPluginId = "com.github.continuedev.continueintellijextension" + val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) + + if (pluginDescriptor == null) { + throw Exception("Plugin not found") + } + val pluginPath = pluginDescriptor.pluginPath + val osName = System.getProperty("os.name").toLowerCase() + val os = when { + osName.contains("mac") || osName.contains("darwin") -> "darwin" + osName.contains("win") -> "win32" + osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux" + else -> "linux" + } + val osArch = System.getProperty("os.arch").toLowerCase() + val arch = when { + osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64" + osArch.contains("amd64") || osArch.contains("x86_64") -> "x64" + else -> "x64" + } + val target = "$os-$arch" + + val continueCorePath = Paths.get(pluginPath.toString(), "core", target, "pkg").toString() + + val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient); + continuePluginService.coreMessenger = coreMessenger + } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt new file mode 100644 index 000000000..8357c3cf4 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt @@ -0,0 +1,48 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity +import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.io.StreamUtil +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.vfs.VirtualFile +import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider +import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory +import com.jetbrains.jsonSchema.extension.SchemaType +import java.io.File +import java.io.IOException +import java.nio.charset.StandardCharsets +import java.nio.file.Paths + +class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory { + override fun getProviders(project: Project): MutableList { + return mutableListOf(ConfigJsonSchemaFileProvider()) + } +} + +class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider { + override fun isAvailable(file: VirtualFile): Boolean { + return file.name == "config.json" + } + + override fun getName(): String { + return "config.json" + } + + override fun getSchemaFile(): VirtualFile? { + ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("config_schema.json").use { `is` -> + if (`is` == null) { + throw IOException("Resource not found: config_schema.json") + } + val content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) + val filepath = Paths.get(getContinueGlobalPath(), "config_schema.json").toString() + File(filepath).writeText(content) + return LocalFileSystem.getInstance().findFileByPath(filepath) + } + } + + override fun getSchemaType(): SchemaType { + return SchemaType.embeddedSchema + } + +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt new file mode 100644 index 000000000..413713b72 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -0,0 +1,179 @@ +package com.github.continuedev.continueintellijextension.`continue` +import java.io.BufferedReader +import java.io.InputStreamReader +import java.io.OutputStreamWriter + +import java.io.* + +import com.google.gson.Gson +import java.nio.file.Files +import java.nio.file.Paths +import java.nio.file.attribute.PosixFilePermission + +class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) { + private val writer: OutputStreamWriter + private val reader: BufferedReader + private val process: Process + private val gson = Gson() + private val responseListeners = mutableMapOf Unit>() + private val ideProtocolClient = ideProtocolClient + + private fun write(message: String) { + writer.write(message + "\r\n") + writer.flush() + } + + private fun close() { + writer.close() + reader.close() + val exitCode = process.waitFor() + println("Subprocess exited with code: $exitCode") + } + + fun request(messageType: String, data: Any?, messageId: String?, onResponse: (String) -> Unit) { + val id = messageId ?: uuid() + val message = gson.toJson(mapOf( + "messageId" to id, + "messageType" to messageType, + "data" to data + )) + responseListeners[id] = onResponse + write(message) + } + + private fun handleMessage(json: String) { + val responseMap = gson.fromJson(json, Map::class.java) + val messageId = responseMap["messageId"].toString() + val messageType = responseMap["messageType"].toString() + val data = gson.toJson(responseMap["data"]) + + // IDE listeners + if (ideMessageTypes.contains(messageType)) { + ideProtocolClient.handleMessage(json) { data -> + val message = gson.toJson(mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to data + )) + write(message) + }; + } + + // Responses for messageId + responseListeners[messageId]?.let { listener -> + listener(data) + if (generatorTypes.contains(messageType)) { + val parsedData = gson.fromJson(data, Map::class.java) + val done = parsedData["done"] as Boolean? + if (done == true) { + responseListeners.remove(messageId) + } else {} + } else { + responseListeners.remove(messageId) + } + + } + } + + private val generatorTypes = listOf( + "llm/streamComplete", + "llm/streamChat", + "command/run" + ) + + private val ideMessageTypes = listOf( + "readRangeInFile", + "isTelemetryEnabled", + "getUniqueId", + "getWorkspaceConfigs", + "getDiff", + "getTerminalContents", + "listWorkspaceContents", + "getWorkspaceDirs", + "showLines", + "listFolders", + "getContinueDir", + "writeFile", + "showVirtualFile", + "openFile", + "runCommand", + "saveFile", + "readFile", + "showDiff", + "getOpenFiles", + "getPinnedFiles", + "getSearchResults", + "getProblems", + "subprocess", + "getBranch", + "getIdeInfo" + ) + + private fun setPermissions(destination: String) { + val osName = System.getProperty("os.name").toLowerCase() + if (osName.contains("mac") || osName.contains("darwin")) { + ProcessBuilder( + "xattr", + "-dr", + "com.apple.quarantine", + destination + ).start() + setFilePermissions(destination, "rwxr-xr-x") + } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { + setFilePermissions(destination, "rwxr-xr-x") + } + } + + private fun setFilePermissions(path: String, posixPermissions: String) { + val perms = HashSet() + if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ) + if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE) + if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE) + Files.setPosixFilePermissions(Paths.get(path), perms) + } + + init { + // Set proper permissions + setPermissions(continueCorePath) + + // Start the subprocess + val processBuilder = ProcessBuilder(continueCorePath) + process = processBuilder.start() + + val outputStream = process.outputStream + val inputStream = process.inputStream + + writer = OutputStreamWriter(outputStream) + reader = BufferedReader(InputStreamReader(inputStream)) + + process.onExit().thenRun { + val err = process.errorStream.bufferedReader().readText() + ideProtocolClient.showMessage("Core process exited with output: $err") + } + + Thread { + try { + while (true) { + val line = reader.readLine() + if (line != null && line.isNotEmpty()) { + handleMessage(line) + } else { + Thread.sleep(100) + } + } + } catch (e: IOException) { + e.printStackTrace() + } finally { + try { + reader.close() + writer.close() + outputStream.close() + inputStream.close() + process.destroy() + } catch (e: IOException) { + e.printStackTrace() + } + } + }.start() + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt new file mode 100644 index 000000000..20367c33b --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -0,0 +1,58 @@ +package com.github.continuedev.continueintellijextension.`continue` +import com.intellij.codeInsight.template.impl.TemplateColors +import com.intellij.openapi.editor.DefaultLanguageHighlighterColors +import com.intellij.openapi.editor.colors.EditorColors +import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.colors.EditorColorsScheme +import com.intellij.openapi.editor.colors.TextAttributesKey +import kotlin.math.max +import kotlin.math.min + + +class GetTheme { + fun getTheme(): Map { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + val defaultForeground = globalScheme.defaultForeground + val highlight = globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: defaultForeground + val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue) + val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue) + val highlightHex = String.format("#%02x%02x%02x", highlight.red, highlight.green, highlight.blue) + + val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt() + + val adjustedRed: Int + val adjustedGreen: Int + val adjustedBlue: Int + + val tint: Int = 20 + if (grayscale > 128) { // if closer to white + adjustedRed = max(0, defaultBackground.red - tint) + adjustedGreen = max(0, defaultBackground.green - tint) + adjustedBlue = max(0, defaultBackground.blue - tint) + } else { // if closer to black + adjustedRed = min(255, defaultBackground.red + tint) + adjustedGreen = min(255, defaultBackground.green + tint) + adjustedBlue = min(255, defaultBackground.blue + tint) + } + + val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue) + + return mapOf( + "--vscode-editor-foreground" to defaultForegroundHex, + "--vscode-sideBar-background" to defaultBackgroundHex, + "--vscode-input-background" to secondaryDarkHex, + "--vscode-editor-background" to defaultBackgroundHex, + "--vscode-button-background" to defaultBackgroundHex, + "--vscode-list-activeSelectionBackground" to defaultBackgroundHex, + "--vscode-focusBorder" to highlightHex, + "--vscode-quickInputList-focusForeground" to defaultForegroundHex, + "--vscode-quickInput-background" to secondaryDarkHex, + "--vscode-input-border" to "#80808080", + "--vscode-badge-background" to highlightHex, + "--vscode-badge-foreground" to defaultForegroundHex, + "--vscode-sideBar-border" to "#80808080" + ) + + } +} \ No newline at end of file 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 8a6f64ae4..0c0f049d4 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 @@ -1,28 +1,19 @@ package com.github.continuedev.continueintellijextension.`continue` -import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.* import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson import com.google.gson.GsonBuilder -import com.google.gson.JsonObject import com.google.gson.reflect.TypeToken -import com.intellij.execution.ExecutionManager -import com.intellij.execution.process.ProcessAdapter -import com.intellij.execution.process.ProcessEvent -import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.Disposable -import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project -import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory @@ -32,15 +23,10 @@ import com.intellij.openapi.wm.WindowManager import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.awt.RelativePoint import kotlinx.coroutines.* -import net.minidev.json.JSONObject -import org.jetbrains.annotations.NotNull import java.io.* import java.net.NetworkInterface import java.nio.charset.Charset -import java.nio.file.Files -import java.nio.file.Paths import java.util.* -import kotlin.coroutines.ContinuationInterceptor fun uuid(): String { @@ -103,7 +89,7 @@ class AsyncFileSaveListener : AsyncFileListener { } override fun prepareChange(events: MutableList): AsyncFileListener.ChangeApplier? { for (event in events) { - if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts")) { + if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) { return object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { val config = readConfigJson() @@ -137,35 +123,21 @@ class IdeProtocolClient ( private fun send(messageType: String, data: Any?, messageId: String? = null) { val id = messageId ?: uuid() - val message = IdeMessage( - messageType, - id, - data - ) - val json = Gson().toJson(message) - continuePluginService.dispatchCustomEvent(json) + continuePluginService.sendToWebview(messageType, data, id) } - fun handleWebsocketMessage(text: String) { + fun handleMessage(text: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val parsedMessage: Map = Gson().fromJson( text, object : TypeToken>() {}.type ) - val messageType = parsedMessage["type"] as? String + val messageType = parsedMessage["messageType"] as? String if (messageType == null) { println("Recieved message without type: $text") return@launch } - val data = parsedMessage["data"] as Map<*, *> - - fun respond(responseData: Any?) { - if (data["messageId"] == null) { - println("Recieved message without messageId: $text") - return - } - send(messageType, responseData ?: emptyMap(), data["messageId"] as String); - } + val data = parsedMessage["data"] val historyManager = HistoryManager() @@ -175,7 +147,7 @@ class IdeProtocolClient ( mapOf("uniqueId" to uniqueId()) ) - "ide" -> { + "getIdeInfo" -> { val applicationInfo = ApplicationInfo.getInstance() val ideName: String = applicationInfo.fullApplicationName val ideVersion = applicationInfo.fullVersion @@ -187,14 +159,19 @@ class IdeProtocolClient ( remoteName = "ssh" } respond(mapOf( + "ideType" to "jetbrains", "name" to ideName, "version" to ideVersion, "remoteName" to remoteName )) } + "getUniqueId" -> { + respond(uniqueId()) + } + "showDiff" -> { - val data = data["message"] as Map + val data = data as Map diffManager.showDiff( data["filepath"] as String, data["newContents"] as String, @@ -204,10 +181,31 @@ class IdeProtocolClient ( } "readFile" -> { - val msg = readFile((data["message"] as Map)["filepath"] as String) + val msg = readFile((data as Map)["filepath"] as String) respond(msg) } + "isTelemetryEnabled" -> { + respond(true) + } + + "readRangeInFile" -> { + val fullContents = readFile((data as Map)["filepath"] as String) + val range = data["range"] as Map + val start = range["start"] as Map + val end = range["end"] as Map + val startLine = start["line"] as Int + val startCharacter = start["character"] as Int + val endLine = end["line"] as Int + val endCharacter = end["character"] as Int + + val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length) + val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter) + val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n") + + respond(firstLine + "\n" + between + "\n" + lastLine) + } + "listWorkspaceContents" -> { respond(listDirectoryContents(null)) } @@ -216,6 +214,10 @@ class IdeProtocolClient ( respond(workspaceDirectories()) } + "getWorkspaceConfigs" -> { + respond(emptyList()) + } + "getTerminalContents" -> { respond( mapOf("contents" to "Terminal cannot be accessed in JetBrains IDE") @@ -229,10 +231,11 @@ class IdeProtocolClient ( } "saveFile" -> { - saveFile((data["message"] as Map)["filepath"] ?: throw Exception("No filepath provided")) + saveFile((data as Map)["filepath"] ?: throw Exception("No filepath provided")) respond(null) } "showVirtualFile" -> { + val data = data as Map showVirtualFile( data["name"] as String, data["contents"] as String @@ -242,10 +245,11 @@ class IdeProtocolClient ( "connected" -> {} "showMessage" -> { - showMessage(data["message"] as String) + showMessage(data as String) respond(null) } "setFileOpen" -> { + val data = data as Map setFileOpen( data["filepath"] as String, data["open"] as Boolean @@ -253,8 +257,27 @@ class IdeProtocolClient ( respond(null) } + "showLines" -> { + val data = data as Map + val filepath = data["filepath"] as String + val startLine = data["startLine"] as Int + val endLine = data["endLine"] as Int + highlightCode( + RangeInFile( + filepath, + Range( + Position(startLine, 0), + Position(endLine, 0) + ) + ), + data["color"] as String + ) + respond(null) + } + "highlightCode" -> { val gson = Gson() + val data = data as Map val json = gson.toJson(data["rangeInFile"]) val type = object : TypeToken() {}.type val rangeInFile = @@ -265,16 +288,6 @@ class IdeProtocolClient ( "setSuggestionsLocked" -> {} "getSessionId" -> {} - "highlightedCode" -> { - val rifWithContents = getHighlightedCode() - val rifs: MutableList = mutableListOf() - if (rifWithContents != null) { - val rif = RangeInFile(rifWithContents.filepath, rifWithContents.range) - rifs += rif - } - respond(mapOf("highlightedCode" to rifs)) - } - // NEW // "getDiff" -> { @@ -295,29 +308,6 @@ class IdeProtocolClient ( respond(output.toString()); } - "getSerializedConfig" -> { - val configPath = getConfigJsonPath() - var config = File(configPath).readText() - - migrate("camelCaseConfig") { - if (config.contains("_")) { - config = config - .replace(Regex("(_\\w)")) { it.value[1].uppercase() } - .replace("openai-aiohttp", "openai") - // Rewrite to config.json - File(configPath).writeText(config) - } - } - - migrate("renameFreeTrialProvider") { - config = config.replace("openai-free-trial", "free-trial"); - File(configPath).writeText(config) - } - - val mapType = object : TypeToken>() {}.type - val parsed: Map = Gson().fromJson(config, mapType) - respond(parsed) - } "getConfigJsUrl" -> { // Calculate a data URL for the config.js file val configJsPath = getConfigJsPath() @@ -326,7 +316,7 @@ class IdeProtocolClient ( respond(configJsDataUrl) } "writeFile" -> { - val msg = data["message"] as Map; + val msg = data as Map; val file = File(msg["path"]) file.writeText(msg["contents"] as String) respond(null); @@ -335,7 +325,7 @@ class IdeProtocolClient ( respond(getContinueGlobalPath()) } "openFile" -> { - setFileOpen((data["message"] as Map)["path"] as String) + setFileOpen((data as Map)["path"] as String) respond(null) } "runCommand" -> { @@ -343,7 +333,14 @@ class IdeProtocolClient ( // Running commands not yet supported in JetBrains } "errorPopup" -> { - showMessage(data["message"] as String) + val data = data as Map + val message = data["message"] as String + showMessage(message) + respond(null) + } + + "listFolders" -> { + respond(null) } // History @@ -351,15 +348,15 @@ class IdeProtocolClient ( respond(historyManager.list()); } "saveSession" -> { - historyManager.save(data["message"] as PersistedSessionInfo); + historyManager.save(data as PersistedSessionInfo); respond(null); } "deleteSession" -> { - historyManager.delete(data["message"] as String); + historyManager.delete(data as String); respond(null); } "loadSession" -> { - val session = historyManager.load(data["message"] as String) + val session = historyManager.load(data as String) respond(session) } "getSearchResults" -> { @@ -371,7 +368,12 @@ class IdeProtocolClient ( val openFiles = visibleFiles() respond(openFiles) } + "getPinnedFiles" -> { + val openFiles = visibleFiles() + respond(openFiles) + } "logDevData" -> { + val data = data as Map val filename = data["tableName"] as String val jsonLine = data["data"] val filepath = getDevDataFilepath(filename) @@ -379,6 +381,7 @@ class IdeProtocolClient ( File(filepath).appendText(contents) } "addModel" -> { + val data = data as Map val model = data["model"] as Map val updatedConfig = editConfigJson { val models = it["models"] as MutableList> @@ -392,7 +395,7 @@ class IdeProtocolClient ( "deleteModel" -> { val configJson = editConfigJson { config -> var models: MutableList> = config["models"] as MutableList> - + val data = data as Map val model = data["title"] as String models = models.filter { it["title"] != model }.toMutableList() config["models"] = models @@ -402,6 +405,7 @@ class IdeProtocolClient ( } "addOpenAIKey" -> { val updatedConfig = editConfigJson { config -> + val data = data as Map val key = data["key"] as String var models = config["models"] as MutableList> models = models.map { @@ -432,12 +436,8 @@ class IdeProtocolClient ( } fun configUpdate(config: Map) { - val data = mapOf( - "type" to "configUpdate", - "config" to config - ) - val json = Gson().toJson(data) - continuePluginService.dispatchCustomEvent(json) + continuePluginService.coreMessenger?.request("config/reload", null, null) { _ -> } + continuePluginService.sendToWebview("configUpdate", config) } private fun editConfigJson(callback: (config: MutableMap) -> Map): Map { @@ -581,20 +581,17 @@ class IdeProtocolClient ( // edit // )) - continuePluginService.dispatchCustomEvent( - Gson().toJson(mapOf( - "type" to "highlightedCode", + continuePluginService.sendToWebview( +"highlightedCode", + mapOf( "rangeInFileWithContents" to rif, "edit" to edit - ))) + ) + ) } fun sendMainUserInput(input: String) { - val data = mapOf( - "type" to "userInput", - "input" to input, - ) - continuePluginService.dispatchCustomEvent(Gson().toJson(data)) + continuePluginService.sendToWebview("userInput", mapOf("input" to input)) } fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) { @@ -712,7 +709,7 @@ class IdeProtocolClient ( return fileEditorManager.openFiles.toList().map { it.path } } - private fun showMessage(msg: String) { + fun showMessage(msg: String) { val statusBar = WindowManager.getInstance().getStatusBar(project) JBPopupFactory.getInstance() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt index 0bc9d70e6..4b3c3cdcd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt @@ -35,7 +35,7 @@ class CustomResourceHandler : CefResourceHandler, DumbAware { ): Boolean { val url = cefRequest.url return if (url != null) { - val pathToResource = url.replace("http://continue", "webview/") + val pathToResource = url.replace("http://continue", "webview/").replace("http://localhost:5173", "webview/") val newUrl = javaClass.classLoader.getResource(pathToResource) state = OpenedConnection(newUrl?.openConnection()) currentUrl = url diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index ddfdb9d52..bac9d3096 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -1,6 +1,8 @@ package com.github.continuedev.continueintellijextension.services +import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient +import com.github.continuedev.continueintellijextension.`continue`.uuid import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory import com.google.gson.Gson import com.intellij.openapi.Disposable @@ -20,7 +22,8 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware { var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null var ideProtocolClient: IdeProtocolClient? = null - var workspacePaths: Array? = null + var coreMessenger: CoreMessenger? = null + var worksapcePaths: Array? = null var windowId: String = UUID.randomUUID().toString() override fun dispose() { @@ -33,10 +36,19 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware { } } - fun dispatchCustomEvent( - data: String + fun sendToWebview( + messageType: String, + data: Any?, + messageId: String = uuid() ) { - val jsCode = buildJavaScript(data) + val jsonData = Gson().toJson( + mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to data + ) + ) + val jsCode = buildJavaScript(jsonData) try { continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 1f5104174..6ccd4a8f1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -1,10 +1,8 @@ package com.github.continuedev.continueintellijextension.toolWindow +import com.github.continuedev.continueintellijextension.activities.showTutorial import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath -import com.github.continuedev.continueintellijextension.`continue`.Position -import com.github.continuedev.continueintellijextension.`continue`.Range -import com.github.continuedev.continueintellijextension.`continue`.RangeInFile -import com.github.continuedev.continueintellijextension.`continue`.getMachineUniqueID +import com.github.continuedev.continueintellijextension.`continue`.* import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -55,12 +53,34 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { class ContinuePluginWindow(toolWindow: ToolWindow, project: Project) { + val PASS_THROUGH_TO_CORE = listOf( + "abort", + "getContinueDir", + "history/list", + "history/save", + "history/delete", + "history/load", + "devdata/log", + "config/addModel", + "config/deleteModel", + "config/addOpenAIKey", + "llm/streamComplete", + "llm/streamChat", + "llm/complete", + "command/run", + "context/loadSubmenuItems", + "context/getContextItems", + "context/addDocs", + "config/getBrowserSerialized", + ) + init { System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) + System.setProperty("ide.browser.jcef.osr.enabled", "false") } val webView: JBCefBrowser by lazy { - val browser = JBCefBrowser() + val browser = JBCefBrowser.createBuilder().setOffScreenRendering(false).build() browser.jbCefClient.setProperty( JBCefClient.Properties.JS_QUERY_POOL_SIZE, JS_QUERY_POOL_SIZE @@ -68,6 +88,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { registerAppSchemeHandler() browser.loadURL("http://continue/index.html") +// browser.loadHTML("") +// browser.loadURL("http://localhost:5173/index.html") Disposer.register(project, browser) val continuePluginService = ServiceManager.getService( @@ -81,58 +103,46 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { myJSQueryOpenInBrowser.addHandler { msg: String? -> val parser = JsonParser() val json: JsonObject = parser.parse(msg).asJsonObject - val type = json.get("type").asString - val data = json.get("data").asJsonObject + val messageType = json.get("messageType").asString + val data = json.get("data") + val messageId = json.get("messageId")?.asString val ide = continuePluginService.ideProtocolClient; - when (type) { + val respond = fun(data: Any?) { + val jsonData = mutableMapOf( + "messageId" to messageId, + "data" to data, + "messageType" to messageType + ) + val jsonString = Gson().toJson(jsonData) + continuePluginService.sendToWebview(messageType, data, messageId ?: uuid()) + } + + if (PASS_THROUGH_TO_CORE.contains(messageType)) { + continuePluginService.coreMessenger?.request(messageType, data, messageId, respond) + return@addHandler null + } + + when (messageType) { "onLoad" -> { GlobalScope.launch { // Set the colors to match Intellij theme - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - val defaultForeground = globalScheme.defaultForeground - val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue) - val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue) - - val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt() - - val adjustedRed: Int - val adjustedGreen: Int - val adjustedBlue: Int - - val tint: Int = 20 - if (grayscale > 128) { // if closer to white - adjustedRed = max(0, defaultBackground.red - tint) - adjustedGreen = max(0, defaultBackground.green - tint) - adjustedBlue = max(0, defaultBackground.blue - tint) - } else { // if closer to black - adjustedRed = min(255, defaultBackground.red + tint) - adjustedGreen = min(255, defaultBackground.green + tint) - adjustedBlue = min(255, defaultBackground.blue + tint) - } - - val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue) - - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-foreground\", \"$defaultForegroundHex\");") - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-sideBar-background\", \"$defaultBackgroundHex\");") - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-input-background\", \"$secondaryDarkHex\");") - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-background\", \"$defaultBackgroundHex\");") + val colors = GetTheme().getTheme(); + continuePluginService.sendToWebview("setColors", colors) val jsonData = mutableMapOf( - "type" to "onLoad", "windowId" to continuePluginService.windowId, "workspacePaths" to continuePluginService.workspacePaths, "vscMachineId" to getMachineUniqueID(), "vscMediaUrl" to "http://continue", ) - val jsonString = Gson().toJson(jsonData) - browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""") + respond(jsonData) } } "showLines" -> { + val data = data.asJsonObject ide?.highlightCode(RangeInFile( data.get("filepath").asString, Range(Position( @@ -145,10 +155,15 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { ),"#00ff0022") } + "showTutorial" -> { + showTutorial(project) + } "showVirtualFile" -> { + val data = data.asJsonObject ide?.showVirtualFile(data.get("name").asString, data.get("content").asString) } "showFile" -> { + val data = data.asJsonObject ide?.setFileOpen(data.get("filepath").asString) } "reloadWindow" -> {} @@ -156,6 +171,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { ide?.setFileOpen(getConfigJsonPath()) } "readRangeInFile" -> { + val data = data.asJsonObject ide?.readRangeInFile(RangeInFile( data.get("filepath").asString, Range(Position( @@ -172,7 +188,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { // IDE // else -> { if (msg != null) { - ide?.handleWebsocketMessage(msg) + ide?.handleMessage(msg, respond) } } } @@ -201,8 +217,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) { // Execute JavaScript - you might want to handle potential exceptions here - val script = """window.postIntellijMessage = function(type, data) { - const msg = JSON.stringify({type, data}); + val script = """window.postIntellijMessage = function(messageType, data, messageId) { + const msg = JSON.stringify({messageType, data, messageId}); ${myJSQueryOpenInBrowser.inject("msg")} }""".trimIndent() diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 003f681c5..61b6b34ff 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -6,6 +6,10 @@ com.intellij.modules.platform + + + + diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json new file mode 100644 index 000000000..b82858588 --- /dev/null +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -0,0 +1,1382 @@ +{ + "title": "config.json", + "$ref": "#/definitions/SerializedContinueConfig", + "definitions": { + "BaseCompletionOptions": { + "title": "BaseCompletionOptions", + "type": "object", + "properties": { + "temperature": { + "title": "Temperature", + "description": "The temperature of the completion.", + "type": "number" + }, + "topP": { + "title": "Top P", + "description": "The topP of the completion.", + "type": "number" + }, + "topK": { + "title": "Top K", + "description": "The topK of the completion.", + "type": "integer" + }, + "presencePenalty": { + "title": "Presence Penalty", + "description": "The presence penalty Aof the completion.", + "type": "number" + }, + "frequencePenalty": { + "title": "Frequency Penalty", + "description": "The frequency penalty of the completion.", + "type": "number" + }, + "mirostat": { + "title": "Mirostat", + "description": "Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). Only available for Ollama, LM Studio, and llama.cpp providers", + "type": "number" + }, + "stop": { + "title": "Stop", + "description": "The stop tokens of the completion.", + "type": "array", + "items": { + "type": "string" + } + }, + "maxTokens": { + "title": "Max Tokens", + "description": "The maximum number of tokens to generate.", + "default": 600, + "type": "integer" + } + } + }, + "RequestOptions": { + "title": "RequestOptions", + "type": "object", + "properties": { + "timeout": { + "title": "Timeout", + "description": "Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.", + "default": 7200, + "type": "integer" + }, + "verifySsl": { + "title": "Verify Ssl", + "description": "Whether to verify SSL certificates for requests.", + "type": "boolean" + }, + "caBundlePath": { + "title": "Ca Bundle Path", + "description": "Path to a custom CA bundle to use when making the HTTP request", + "anyOf": [ + { "type": "string" }, + { "type": "array", "items": { "type": "string" } } + ] + }, + "proxy": { + "title": "Proxy", + "description": "Proxy URL to use when making the HTTP request", + "type": "string" + }, + "headers": { + "title": "Headers", + "description": "Headers to use when making the HTTP request", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "extraBodyProperties": { + "title": "Extra Body Properties", + "description": "This object will be merged with the body when making the HTTP requests", + "type": "object" + } + } + }, + "ModelDescription": { + "title": "ModelDescription", + "type": "object", + "properties": { + "title": { + "title": "Title", + "description": "The title you wish to give your model.", + "type": "string" + }, + "provider": { + "title": "Provider", + "description": "The provider of the model. This is used to determine the type of model, and how to interact with it.", + "enum": [ + "openai", + "free-trial", + "anthropic", + "together", + "ollama", + "huggingface-tgi", + "huggingface-inference-api", + "llama.cpp", + "replicate", + "google-palm", + "lmstudio", + "llamafile", + "mistral", + "deepinfra", + "flowise" + ], + "markdownEnumDescriptions": [ + "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)", + "### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)", + "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)", + "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)", + "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)", + "### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)", + "### Huggingface Inference API\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfaceinferenceapi)", + "### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamacpp)", + "### Replicate\nReplicate is a hosted service that makes it easy to run ML models. To get started with Replicate:\n1. Obtain an API key from [here](https://replicate.com)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/replicatellm)", + "### Google PALM\nTo get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/googlepalmapi)", + "### LMStudio\nLMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/lmstudio)", + "### Llamafile\nTo get started with llamafiles, find and download a binary on their [GitHub repo](https://github.com/Mozilla-Ocho/llamafile#binary-instructions). Then run it with the following command:\n\n```shell\nchmod +x ./llamafile\n./llamafile\n```\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamafile)", + "### Mistral API\n\nTo get access to the Mistral API, obtain your API key from the [Mistral platform](https://docs.mistral.ai/)", + "### DeepInfra\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/deepinfra)" + ], + "type": "string" + }, + "model": { + "title": "Model", + "description": "The name of the model. Used to autodetect prompt template.", + "type": "string" + }, + "apiKey": { + "title": "Api Key", + "description": "OpenAI, Anthropic, Together, or other API key", + "type": "string" + }, + "apiBase": { + "title": "Api Base", + "description": "The base URL of the LLM API.", + "type": "string" + }, + "contextLength": { + "title": "Context Length", + "description": "The maximum context length of the LLM in tokens, as counted by countTokens.", + "default": 2048, + "type": "integer" + }, + "template": { + "title": "Template", + "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", + "enum": [ + "llama2", + "alpaca", + "zephyr", + "phind", + "anthropic", + "chatml", + "none", + "deepseek", + "openchat", + "xwin-coder", + "neural-chat", + "codellama-70b" + ], + "type": "string" + }, + "promptTemplates": { + "title": "Prompt Templates", + "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://continue.dev/docs/model-setup/configuration#customizing-the-edit-prompt) for an example.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "completionOptions": { + "title": "Completion Options", + "description": "Options for the completion endpoint. Read more about the completion options in the documentation.", + "default": { + "temperature": null, + "topP": null, + "topK": null, + "presencePenalty": null, + "frequencyPenalty": null, + "stop": null, + "maxTokens": 600 + }, + "allOf": [ + { + "$ref": "#/definitions/BaseCompletionOptions" + } + ] + }, + "systemMessage": { + "title": "System Message", + "description": "A system message that will always be followed by the LLM", + "type": "string" + }, + "requestOptions": { + "title": "Request Options", + "description": "Options for the HTTP request to the LLM.", + "default": { + "timeout": 7200, + "verifySsl": null, + "caBundlePath": null, + "proxy": null, + "headers": null, + "extraBodyProperties": null + }, + "allOf": [ + { + "$ref": "#/definitions/RequestOptions" + } + ] + }, + "apiType": { + "title": "Api Type", + "markdownDescription": "OpenAI API type, either `openai` or `azure`", + "enum": ["openai", "azure"] + }, + "apiVersion": { + "title": "Api Version", + "description": "Azure OpenAI API version (e.g. 2023-07-01-preview)", + "type": "string" + }, + "engine": { + "title": "Engine", + "description": "Azure OpenAI engine", + "type": "string" + } + }, + "required": ["title", "provider", "model"], + "allOf": [ + { + "if": { + "properties": { + "provider": { + "type": "str" + } + }, + "not": { + "required": ["provider"] + } + }, + "then": { + "properties": { + "model": { + "description": "Choose a provider first, then model options will be shown here." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "openai", + "anthropic", + "google-palm", + "huggingface-inference-api", + "replicate", + "together" + ] + } + }, + "required": ["provider"] + }, + "then": { + "required": ["apiKey"] + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["huggingface-tgi"] + } + } + }, + "then": { + "required": ["apiBase"] + }, + "required": ["provider"] + }, + { + "if": { + "properties": { + "provider": { + "enum": ["openai"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "engine": { + "type": "string" + }, + "apiType": { + "type": "string" + }, + "apiVersion": { + "type": "string" + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["openai"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "AUTODETECT" + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["replicate"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "codellama-7b", + "codellama-13b", + "codellama-34b", + "llama2-7b", + "llama2-13b" + ] + }, + { "type": "string" } + ] + }, + "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)." + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["free-trial"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "enum": [ + "gpt-3.5-turbo", + "gpt-4", + "phind-codellama-34b", + "gemini-pro", + "gpt-4-vision-preview", + "codellama-70b", + "AUTODETECT" + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["openai"] + }, + "apiType": { + "not": { + "const": "azure" + } + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-turbo-preview", + "gpt-4-vision-preview", + "mistral-7b", + "mistral-8x7b", + "llama2-7b", + "llama2-13b", + "codellama-7b", + "codellama-13b", + "codellama-34b", + "codellama-70b", + "phind-codellama-34b", + "wizardcoder-7b", + "wizardcoder-13b", + "wizardcoder-34b", + "zephyr-7b", + "codeup-13b", + "deepseek-7b", + "deepseek-33b", + "neural-chat-7b", + "deepseek-1b", + "stable-code-3b", + "starcoder-1b", + "starcoder-3b", + "mistral-tiny", + "mistral-small", + "mistral-medium", + "AUTODETECT" + ] + }, + { "type": "string" } + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["anthropic"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { "enum": ["claude-2", "claude-instant-1"] }, + { "type": "string" } + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["google-palm"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "enum": ["chat-bison-001", "gemini-pro"] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["together"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "mistral-7b", + "mistral-8x7b", + "llama2-7b", + "llama2-13b", + "codellama-7b", + "codellama-13b", + "codellama-34b", + "codellama-70b", + "phind-codellama-34b" + ] + }, + { "type": "string" } + ], + "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["deepinfra"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "huggingface-tgi", + "huggingface-inference-api", + "llama.cpp", + "text-gen-webui", + "llamafile" + ] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "mistral-7b", + "mistral-8x7b", + "llama2-7b", + "llama2-13b", + "codellama-7b", + "codellama-13b", + "codellama-34b", + "codellama-70b", + "phind-codellama-34b", + "wizardcoder-7b", + "wizardcoder-13b", + "wizardcoder-34b", + "zephyr-7b", + "codeup-13b", + "deepseek-7b", + "deepseek-33b", + "neural-chat-7b", + "deepseek-1b", + "stable-code-3b", + "starcoder-1b", + "starcoder-3b" + ] + }, + { "type": "string" } + ] + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["ollama"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "mistral-7b", + "llama2-7b", + "llama2-13b", + "codellama-7b", + "codellama-13b", + "codellama-34b", + "codellama-70b", + "phi-2", + "phind-codellama-34b", + "wizardcoder-7b", + "wizardcoder-13b", + "wizardcoder-34b", + "zephyr-7b", + "codeup-13b", + "deepseek-7b", + "deepseek-33b", + "neural-chat-7b", + "deepseek-1b", + "stable-code-3b", + "starcoder-1b", + "starcoder-3b", + "AUTODETECT" + ] + }, + { "type": "string" } + ], + "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)." + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["mistral"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "enum": ["mistral-tiny", "mistral-small", "mistral-medium"] + } + } + } + }, + { + "if": { + "properties": { + "apiType": { + "const": "azure" + } + }, + "required": ["apiType"] + }, + "then": { + "required": ["engine", "apiVersion", "apiBase"] + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["openai"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "useLegacyCompletionsEndpoint": { + "type": "boolean" + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "const": "llamafile" + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "llamafileCommand": { + "type": "string" + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["text-gen-webui"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "streamingUrl": { + "type": "string" + } + } + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["flowise"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "timeout": { + "title": "Timeout", + "description": "Set the timeout for each request to Flowise. If you are running a local version of Flowise it might takes a while to respond, you might want to set this to avoid timeouts.", + "default": 5000, + "type": "integer" + }, + "additionalHeaders": { + "description": "A list of additional headers", + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "title": "Key", + "description": "Header key", + "type": "string" + }, + "value": { + "title": "Value", + "description": "Header value", + "type": "string" + } + }, + "required": ["key", "value"] + } + }, + "additionalFlowiseConfiguration": { + "description": "A list of additional properties to be sent along `overrideConfig`", + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "title": "Key", + "description": "Configuration Property key", + "type": "string" + }, + "value": { + "title": "Value", + "description": "Configuration Property value" + } + }, + "required": ["key", "value"] + } + }, + "model": { + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-turbo-preview", + "gpt-4-vision-preview", + "mistral-7b", + "mistral-8x7b", + "llama2-7b", + "llama2-13b", + "codellama-7b", + "codellama-13b", + "codellama-34b", + "codellama-70b", + "phind-codellama-34b", + "wizardcoder-7b", + "wizardcoder-13b", + "wizardcoder-34b", + "zephyr-7b", + "codeup-13b", + "deepseek-7b", + "deepseek-33b", + "claude-2", + "chat-bison-001", + "gemini-pro", + "mistral-tiny", + "mistral-small", + "mistral-medium", + "deepseek-1b", + "stable-code-3b", + "starcoder-1b", + "starcoder-3b" + ] + }, + { "type": "string" } + ] + } + } + } + } + ] + }, + "ModelRoles": { + "title": "ModelRoles", + "type": "object", + "properties": { + "default": { + "title": "Default", + "description": "The default model. If other model roles are not set, they will fall back to default.", + "type": "string" + }, + "chat": { + "title": "Chat", + "description": "The model to use for chat. If not set, will fall back to default.", + "type": "string" + }, + "edit": { + "title": "Edit", + "description": "The model to use for editing. If not set, will fall back to default.", + "type": "string" + }, + "summarize": { + "title": "Summarize", + "description": "The model to use for summarization. If not set, will fall back to default.", + "type": "string" + } + }, + "required": ["default"] + }, + "SlashCommand": { + "title": "SlashCommand", + "type": "object", + "properties": { + "name": { + "title": "Name", + "anyOf": [ + { + "enum": [ + "issue", + "share", + "so", + "cmd", + "edit", + "comment", + "http", + "commit" + ], + "type": "string", + "markdownEnumDescriptions": [ + "Generate a link to a drafted GitHub issue", + "Export the current chat session to markdown", + "Reference StackOverflow to answer the question", + "Generate a terminal command and paste it into the terminal", + "Edit the highlighted code with given instructions", + "Add comments to the highlighted code", + "Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", + "Generate a commit message for the current changes" + ] + }, + { "type": "string" } + ] + }, + "description": { + "title": "Description", + "type": "string" + }, + "step": { + "title": "Step", + "description": "This property is no longer required and has no effect. To use a built-in slash command, instead set the 'name' property to one of the pre-configured options.", + "type": "string" + }, + "params": { + "title": "Params", + "default": {}, + "type": "object" + } + }, + "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": ["issue"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "repositoryUrl": { + "type": "string", + "description": "Enter the URL of the GitHub repository for which you want to generate the issue." + } + }, + "required": ["repositoryUrl"] + } + }, + "required": ["params"] + } + }, + { + "if": { + "properties": { + "name": { + "enum": ["edit"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "recap": { + "type": "boolean", + "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." + }, + "tokenLimit": { + "type": "integer", + "markdownDescription": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." + } + } + } + } + } + } + ], + "required": ["name", "description"] + }, + "CustomCommand": { + "title": "CustomCommand", + "type": "object", + "properties": { + "name": { + "title": "Name", + "type": "string" + }, + "prompt": { + "title": "Prompt", + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + } + }, + "required": ["name", "prompt", "description"] + }, + "ContextProviderWithParams": { + "title": "ContextProviderWithParams", + "type": "object", + "properties": { + "name": { + "title": "Name", + "anyOf": [ + { + "enum": [ + "diff", + "terminal", + "open", + "google", + "search", + "http", + "codebase", + "problems", + "folder", + "issue", + "docs", + "tree", + "highlights", + "outline" + ], + "markdownEnumDescriptions": [ + "Reference the contents of the current changes as given by `git diff`", + "Reference the contents of the terminal", + "Reference the contents of all open or pinned files.", + "Enter a search phrase and include the Google search results as context", + "Reference the results of a ripgrep search in your codebase", + "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", + "Use embeddings to automatically find relevant files from throughout the codebase", + "Reference all linting errors and warnings in the currently open file", + "Include important files from a folder in the prompt, as determined by similarity search", + "Reference GitHub issues from a repository", + "Retrieve important pages from a documentation website, as determined by similarity search", + "Index and retrieve the contents of any documentation site, using embeddings to find important snippets", + "Display a file tree of the current workspace", + "Include a repo map showing important code objects", + "Displays important snippets of code from the currently open files", + "Displays definition lines from the currently open files" + ], + "type": "string" + }, + { "type": "string" } + ] + }, + "params": { + "title": "Params", + "default": {}, + "type": "object" + } + }, + "allOf": [ + { + "if": { + "properties": { + "name": { + "enum": ["google"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "serperApiKey": { + "type": "string", + "description": "Your API key for https://serper.dev in order to get Google search results" + } + }, + "required": ["serperApiKey"] + } + }, + "required": ["params"] + } + }, + { + "if": { + "properties": { + "name": { + "enum": ["open"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "onlyPinned": { + "type": "boolean", + "description": "If set to true, only 'pinned' files will be included.", + "default": false + } + } + } + } + } + }, + { + "if": { + "properties": { + "name": { + "enum": ["issue"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "githubToken": { + "type": "string", + "description": "Your GitHub token to access the GitHub API. Required for private repositories." + }, + "repos": { + "type": "array", + "description": "A list of repositories to search for issues", + "items": { + "type": "object", + "properties": { + "owner": { + "type": "string", + "description": "The owner of the repository" + }, + "repo": { + "type": "string", + "description": "The name of the repository" + }, + "type": { + "type": "string", + "description": "The type of issues to search for", + "enum": ["open", "closed", "all"] + } + }, + "required": ["owner", "repo"] + } + } + }, + "required": ["repos"] + } + }, + "required": ["params"] + } + }, + { + "if": { + "properties": { + "name": { + "enum": ["http"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "url": { + "type": "string", + "description": "The HTTP endpoint of your context provider server." + } + }, + "required": ["url"] + } + }, + "required": ["params"] + } + }, + { + "if": { + "properties": { + "name": { + "enum": ["codebase", "folder"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "nRetrieve": { + "title": "N Retrieve", + "description": "Number of results to initially retrieve from vector database", + "default": 50, + "type": "integer" + }, + "nFinal": { + "title": "N Final", + "description": "Final number of results to use after re-ranking", + "default": 10, + "type": "integer" + }, + "useReranking": { + "title": "Use Reranking", + "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.", + "default": true, + "type": "boolean" + } + } + } + } + } + } + ], + "required": ["name"] + }, + "SerializedContinueConfig": { + "title": "config.json", + "type": "object", + "properties": { + "allowAnonymousTelemetry": { + "title": "Allow Anonymous Telemetry", + "markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data.", + "default": true, + "type": "boolean" + }, + "models": { + "title": "Models", + "default": [ + { + "title": "GPT-4 (trial)", + "provider": "free-trial", + "model": "gpt-4", + "apiKey": "" + } + ], + "type": "array", + "items": { + "$ref": "#/definitions/ModelDescription" + } + }, + "systemMessage": { + "title": "System Message", + "description": "A system message that will always be followed by the LLM", + "type": "string" + }, + "completionOptions": { + "title": "Completion Options", + "description": "Default options for completion. These will be overriden by any options set for a specific model.", + "default": { + "temperature": null, + "topP": null, + "topK": null, + "presencePenalty": null, + "frequencyPenalty": null, + "stop": null, + "maxTokens": 600 + }, + "allOf": [ + { + "$ref": "#/definitions/BaseCompletionOptions" + } + ] + }, + "slashCommands": { + "title": "Slash Commands", + "description": "An array of slash commands that let you map custom Steps to a shortcut.", + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/SlashCommand" + } + }, + "customCommands": { + "title": "Custom Commands", + "description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt.", + "default": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "This is an example custom command. Use /config to edit it and create more" + } + ], + "type": "array", + "items": { + "$ref": "#/definitions/CustomCommand" + } + }, + "contextProviders": { + "title": "Context Providers", + "description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", + "default": [], + "type": "array", + "items": { + "$ref": "#/definitions/ContextProviderWithParams" + } + }, + "userToken": { + "title": "User Token", + "description": "An optional token to identify the user.", + "type": "string" + }, + "dataServerUrl": { + "title": "Data Server Url", + "description": "The URL of the server where development data is sent. No data is sent unless a valid user token is provided.", + "default": "https://us-west1-autodebug.cloudfunctions.net", + "type": "string" + }, + "disableSummaries": { + "title": "Disable Summaries", + "markdownDescription": "If set to `true`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.", + "default": false, + "type": "boolean" + }, + "disableIndexing": { + "title": "Disable Indexing", + "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", + "default": false, + "type": "boolean" + }, + "disableSessionTitles": { + "title": "Disable Session Titles", + "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", + "default": false, + "type": "boolean" + }, + "embeddingsProvider": { + "title": "Embeddings Provider", + "description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser.", + "type": "object", + "properties": { + "provider": { + "enum": ["transformers.js", "ollama", "openai"] + }, + "model": { + "type": "string" + }, + "apiKey": { + "type": "string" + }, + "apiBase": { + "type": "string" + } + }, + "required": ["provider"], + "allOf": [ + { + "if": { + "properties": { + "provider": { + "enum": ["ollama"] + } + }, + "required": ["provider"] + }, + "then": { + "required": ["model"] + } + } + ] + }, + "tabAutocompleteModel": { + "title": "Tab Autocomplete Model", + "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using deepseek-coder:1.3b-base on a local Ollama instance.", + "default": { + "title": "Tab Autocomplete Model", + "provider": "ollama", + "model": "deepseek-coder:1.3b-base" + }, + "$ref": "#/definitions/ModelDescription" + }, + "tabAutocompleteOptions": { + "title": "TabAutocompleteOptions", + "type": "object", + "properties": { + "useCopyBuffer": { + "type": "boolean", + "description": "Determines whether the copy buffer will be considered when contructing the prompt." + }, + "useSuffix": { + "type": "boolean", + "description": "Determines whether to use the file suffix in the prompt." + }, + "maxPromptTokens": { + "type": "number", + "description": "The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context." + }, + "debounceDelay": { + "type": "number", + "description": "The delay in milliseconds before triggering autocomplete after a keystroke." + }, + "maxSuffixPercentage": { + "type": "number", + "description": "The maximum percentage of the prompt that can be dedicated to the suffix." + }, + "prefixPercentage": { + "type": "number", + "description": "The percentage of the input that should be dedicated to the prefix." + }, + "template": { + "type": "string", + "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." + }, + "disableMultiLineCompletions": { + "type": "boolean", + "description": "If set to true, Continue will only complete a single line at a time." + } + }, + "required": [] + } + } + } + } +} diff --git a/extensions/vscode/continue_tutorial.py b/extensions/vscode/continue_tutorial.py index b89fd009a..dff23a718 100644 --- a/extensions/vscode/continue_tutorial.py +++ b/extensions/vscode/continue_tutorial.py @@ -19,7 +19,7 @@ You can either - follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section" """ -# region —————————————————————————— Part 1: Ask a question about code [⌘ M] —————————————————————————— +# region —————————————————————————— Part 1: Ask a question about code [⌘ L] —————————————————————————— """Step 1: Highlight the function below""" @@ -34,14 +34,14 @@ def mysterious_function(x): return x -"""Step 2: Use the keyboard shortcut [⌘ M] to +"""Step 2: Use the keyboard shortcut [⌘ L] to select the code and toggle the Continue input box""" """Step 3: Ask a question and press Enter""" # endregion -# region ————————————————————————————————— Part 2: Edit code [⌘ ⇧ L] ————————————————————————————————— +# region ————————————————————————————————— Part 2: Edit code [⌘ I] ————————————————————————————————— """Step 1: Highlight this code""" @@ -60,7 +60,7 @@ def mysterious_function(x): return x -"""Step 2: Use the keyboard shortcut [⌘ ⇧ L] to edit""" +"""Step 2: Use the keyboard shortcut [⌘ I] to edit""" """Step 3: Type "" and press Enter""" diff --git a/extensions/vscode/media/welcome.md b/extensions/vscode/media/welcome.md index f43ed4b37..e7b3b6e52 100644 --- a/extensions/vscode/media/welcome.md +++ b/extensions/vscode/media/welcome.md @@ -8,11 +8,11 @@ Continue is currently in the left sidebar, but we recommend moving it to the rig ## 🔑 Most important shortcuts -Cmd/Ctrl + M = Select code +Cmd/Ctrl + L = Select code -Cmd/Ctrl + Shift + M = Select code for follow-up +Cmd/Ctrl + Shift + L = Select code for follow-up -Cmd/Ctrl + Shift + L = Quick edit +Cmd/Ctrl + I = Quick edit Cmd/Ctrl + Shift + R = Automatically debug terminal diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 179a5036b..83f90ce39 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -91,9 +91,13 @@ "adf-to-md": "^1.1.0", "axios": "^1.6.7", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.13", "node-fetch": "^3.3.2", @@ -111,6 +115,7 @@ "web-tree-sitter": "^0.20.8" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9d4ed7c31..bbfdaa734 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -195,13 +195,13 @@ "keybindings": [ { "command": "continue.focusContinueInput", - "mac": "cmd+m", - "key": "ctrl+m" + "mac": "cmd+l", + "key": "ctrl+l" }, { "command": "continue.focusContinueInputWithoutClear", - "mac": "cmd+shift+m", - "key": "ctrl+shift+m" + "mac": "cmd+shift+l", + "key": "ctrl+shift+l" }, { "command": "continue.acceptDiff", @@ -221,8 +221,8 @@ }, { "command": "continue.quickEdit", - "mac": "cmd+shift+l", - "key": "ctrl+shift+l" + "mac": "cmd+i", + "key": "ctrl+i" }, { "command": "continue.toggleAuxiliaryBar", diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 4db78c7cb..76af0d9a0 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -13,11 +13,22 @@ if (args[2] === "--target") { (async () => { console.log("[info] Packaging extension for target ", target); - // Copy config_schema.json to config.json in docs + // Copy config_schema.json to config.json in docs and intellij fs.copyFileSync( "config_schema.json", path.join("..", "..", "docs", "static", "schemas", "config.json") ); + fs.copyFileSync( + "config_schema.json", + path.join( + "..", + "intellij", + "src", + "main", + "resources", + "config_schema.json" + ) + ); // Modify and copy for .continuerc.json const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); schema.definitions.SerializedContinueConfig.properties.mergeBehavior = { @@ -77,11 +88,19 @@ if (args[2] === "--target") { }); }); + // Put back index.html if (fs.existsSync(indexHtmlPath)) { fs.rmSync(indexHtmlPath, {}); } fs.copyFileSync("tmp_index.html", indexHtmlPath); fs.unlinkSync("tmp_index.html"); + + // Copy over other misc. files + fs.copyFileSync( + "../extensions/vscode/gui/onigasm.wasm", + path.join(intellijExtensionWebviewPath, "onigasm.wasm") + ); + console.log("[info] Copied gui build to Intellij extension"); // Then copy over the dist folder to the VSCode extension // diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 41af5748f..69bf90124 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -2,27 +2,14 @@ import { getTsConfigPath, migrate } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as fs from "fs"; import path from "path"; -import { v4 } from "uuid"; import * as vscode from "vscode"; -import { registerAllCommands } from "../commands"; -import IdeProtocolClient from "../continueIdeClient"; -import { ContinueGUIWebviewViewProvider } from "../debugPanel"; +import { VsCodeExtension } from "../extension/vscodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; -import { registerAllCodeLensProviders } from "../lang-server/codeLens"; -import { - ContinueCompletionProvider, - setupStatusBar, -} from "../lang-server/completionProvider"; -import { vsCodeIndexCodebase } from "../util/indexCodebase"; import { RemoteConfigSync } from "../util/remoteConfig"; import { getExtensionVersion } from "../util/util"; import { getExtensionUri } from "../util/vscode"; import { setupInlineTips } from "./inlineTips"; -export let extensionContext: vscode.ExtensionContext | undefined = undefined; -export let ideProtocolClient: IdeProtocolClient; -export let windowId: string = v4(); - export async function showTutorial() { const tutorialPath = path.join( getExtensionUri().fsPath, @@ -48,7 +35,9 @@ async function openTutorialFirstTime(context: vscode.ExtensionContext) { } } -function showRefactorMigrationMessage() { +function showRefactorMigrationMessage( + extensionContext: vscode.ExtensionContext +) { // Only if the vscode setting continue.manuallyRunningSserver is true const manuallyRunningServer = vscode.workspace @@ -82,45 +71,13 @@ export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files getTsConfigPath(); - extensionContext = context; - // Register commands and providers - registerAllCodeLensProviders(context); - registerAllCommands(context); registerQuickFixProvider(); await openTutorialFirstTime(context); setupInlineTips(context); - showRefactorMigrationMessage(); - const config = vscode.workspace.getConfiguration("continue"); - const enabled = config.get("enableTabAutocomplete"); + showRefactorMigrationMessage(context); - // Register inline completion provider (odd versions are pre-release) - if (parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !== 0) { - setupStatusBar(enabled); - context.subscriptions.push( - vscode.languages.registerInlineCompletionItemProvider( - [{ pattern: "**" }], - new ContinueCompletionProvider() - ) - ); - } - - ideProtocolClient = new IdeProtocolClient(context); - - // Register Continue GUI as sidebar webview, and beginning a new session - const provider = new ContinueGUIWebviewViewProvider(); - - context.subscriptions.push( - vscode.window.registerWebviewViewProvider( - "continue.continueGUIView", - provider, - { - webviewOptions: { retainContextWhenHidden: true }, - } - ) - ); - - vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories()); + const vscodeExtension = new VsCodeExtension(context); migrate("showWelcome", () => { vscode.commands.executeCommand( @@ -131,25 +88,6 @@ export async function activateExtension(context: vscode.ExtensionContext) { ); }); - // (async () => { - // const defaultDocsPages = [ - // ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"], - // // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"], - // ]; - - // const config = await configHandler.loadConfig(new VsCodeIde()); - - // defaultDocsPages.forEach(async ([title, url]) => { - // for await (const update of indexDocs( - // title, - // new URL(url), - // config.embeddingsProvider - // )) { - // console.log(update.progress, update.desc); - // } - // }); - // })(); - // Load Continue configuration if (!context.globalState.get("hasBeenInstalled")) { context.globalState.update("hasBeenInstalled", true); diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts index 84039aaa2..001fb6c1a 100644 --- a/extensions/vscode/src/activation/inlineTips.ts +++ b/extensions/vscode/src/activation/inlineTips.ts @@ -3,7 +3,7 @@ import { getMetaKeyLabel } from "../util/util"; const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ after: { - contentText: `${getMetaKeyLabel()} M to select code, ${getMetaKeyLabel()} ⇧ L to edit`, + contentText: `${getMetaKeyLabel()} L to select code, ${getMetaKeyLabel()} I to edit`, color: "#888", margin: "0 0 0 6em", fontWeight: "bold", @@ -31,7 +31,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { const line = Math.max(0, selection.start.line - 1); const hoverMarkdown = new vscode.MarkdownString( - `Use ${getMetaKeyLabel()} M to select code, or ${getMetaKeyLabel()} ⇧ L to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.` + `Use ${getMetaKeyLabel()} L to select code, or ${getMetaKeyLabel()} I to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.` ); hoverMarkdown.isTrusted = true; hoverMarkdown.supportHtml = true; @@ -49,7 +49,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType( { after: { - contentText: `Use ${getMetaKeyLabel()} ⇧ L to generate code`, + contentText: `Use ${getMetaKeyLabel()} I to generate code`, color: "#888", margin: "2em 0 0 0", fontStyle: "italic", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index a8484c105..307d35dfb 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -3,19 +3,19 @@ import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; -import { extensionContext, ideProtocolClient } from "./activation/activate"; -import { debugPanelWebview, getSidebarContent } from "./debugPanel"; -import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal"; -import { - editorToVerticalDiffCodeLens, - streamEdit, - verticalPerLineDiffManager, -} from "./diff/verticalPerLine/manager"; -import { VsCodeIde } from "./ideProtocol"; +import { IDE } from "core"; +import { ConfigHandler } from "core/config/handler"; +import { logDevData } from "core/util/devdata"; +import { ContinueGUIWebviewViewProvider } from "./debugPanel"; +import { DiffManager } from "./diff/horizontal"; +import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import { AutocompleteOutcome } from "./lang-server/completionProvider"; -import { configHandler, llmFromTitle } from "./loadConfig"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; -function addHighlightedCodeToContext(edit: boolean) { +function addHighlightedCodeToContext( + edit: boolean, + webviewProtocol: VsCodeWebviewProtocol | undefined +) { const editor = vscode.window.activeTextEditor; if (editor) { const selection = editor.selection; @@ -37,22 +37,28 @@ function addHighlightedCodeToContext(edit: boolean) { }, }; - debugPanelWebview?.postMessage({ - type: "highlightedCode", + webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, - edit, }); } } -async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) { +async function addEntireFileToContext( + filepath: vscode.Uri, + edit: boolean, + webviewProtocol: VsCodeWebviewProtocol | undefined +) { // If a directory, add all files in the directory const stat = await vscode.workspace.fs.stat(filepath); if (stat.type === vscode.FileType.Directory) { const files = await vscode.workspace.fs.readDirectory(filepath); for (const [filename, type] of files) { if (type === vscode.FileType.File) { - addEntireFileToContext(vscode.Uri.joinPath(filepath, filename), edit); + addEntireFileToContext( + vscode.Uri.joinPath(filepath, filename), + edit, + webviewProtocol + ); } } return; @@ -75,79 +81,70 @@ async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) { }, }; - debugPanelWebview?.postMessage({ - type: "highlightedCode", + webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, - edit, }); } -function acceptRejectVerticalDiffBlock( - accept: boolean, - filepath?: string, - index?: number -) { - if (!filepath) { - const activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - return; - } - filepath = activeEditor.document.uri.fsPath; - } - - if (typeof index === "undefined") { - index = 0; - } - - let blocks = editorToVerticalDiffCodeLens.get(filepath); - const block = blocks?.[index]; - if (!blocks || !block) { - return; - } - - const handler = verticalPerLineDiffManager.getHandlerForFile(filepath); - if (!handler) { - return; - } - - // CodeLens object removed from editorToVerticalDiffCodeLens here - handler.acceptRejectBlock(accept, block.start, block.numGreen, block.numRed); -} - // Copy everything over from extension.ts -const commandsMap: { [command: string]: (...args: any) => any } = { - "continue.acceptDiff": acceptDiffCommand, - "continue.rejectDiff": rejectDiffCommand, +const commandsMap: ( + ide: IDE, + extensionContext: vscode.ExtensionContext, + sidebar: ContinueGUIWebviewViewProvider, + configHandler: ConfigHandler, + diffManager: DiffManager, + verticalDiffManager: VerticalPerLineDiffManager +) => { [command: string]: (...args: any) => any } = ( + ide, + extensionContext, + sidebar, + configHandler, + diffManager, + verticalDiffManager +) => ({ + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + if (newFilepath instanceof vscode.Uri) { + newFilepath = newFilepath.fsPath; + } + verticalDiffManager.clearForFilepath(newFilepath, true); + await diffManager.acceptDiff(newFilepath); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + if (newFilepath instanceof vscode.Uri) { + newFilepath = newFilepath.fsPath; + } + verticalDiffManager.clearForFilepath(newFilepath, false); + await diffManager.rejectDiff(newFilepath); + }, "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - acceptRejectVerticalDiffBlock(true, filepath, index); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); }, "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - acceptRejectVerticalDiffBlock(false, filepath, index); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); }, "continue.quickFix": async (message: string, code: string, edit: boolean) => { - debugPanelWebview?.postMessage({ - type: "newSessionWithPrompt", + sidebar.webviewProtocol?.request("newSessionWithPrompt", { prompt: `${ edit ? "/edit " : "" }${code}\n\nHow do I fix this problem in the above code?: ${message}`, }); + if (!edit) { vscode.commands.executeCommand("continue.continueGUIView.focus"); } }, "continue.focusContinueInput": async () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ - type: "focusContinueInput", - }); - addHighlightedCodeToContext(false); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + addHighlightedCodeToContext(false, sidebar.webviewProtocol); }, "continue.focusContinueInputWithoutClear": async () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ - type: "focusContinueInputWithoutClear", - }); - addHighlightedCodeToContext(true); + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", + undefined + ); + addHighlightedCodeToContext(true, sidebar.webviewProtocol); }, "continue.toggleAuxiliaryBar": () => { vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); @@ -167,7 +164,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { } if (text.length > 0) { - await streamEdit(text); + await verticalDiffManager.streamEdit(text); } else { // Pick context first const quickPickItems: Promise = configHandler @@ -201,7 +198,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { title: "Continue Quick Edit", }); if (text) { - const llm = await llmFromTitle(); + const llm = await configHandler.llmFromTitle(); const config = await configHandler.loadConfig(); const context = ( await Promise.all( @@ -216,7 +213,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { return provider.getContextItems("", { embeddingsProvider: config.embeddingsProvider, - ide: new VsCodeIde(), + ide, llm, fullInput: text || "", selectedCode: [], @@ -230,24 +227,24 @@ const commandsMap: { [command: string]: (...args: any) => any } = { "\n\n---\n\n" + text; - await streamEdit(text); + await verticalDiffManager.streamEdit(text); } } }, "continue.writeCommentsForCode": async () => { - await streamEdit("Write comments for this code"); + await verticalDiffManager.streamEdit("Write comments for this code"); }, "continue.writeDocstringForCode": async () => { - await streamEdit("Write a docstring for this code"); + await verticalDiffManager.streamEdit("Write a docstring for this code"); }, "continue.fixCode": async () => { - await streamEdit("Fix this code"); + await verticalDiffManager.streamEdit("Fix this code"); }, "continue.optimizeCode": async () => { - await streamEdit("Optimize this code"); + await verticalDiffManager.streamEdit("Optimize this code"); }, "continue.fixGrammar": async () => { - await streamEdit( + await verticalDiffManager.streamEdit( "If there are any grammar or spelling mistakes in this writing, fix them" ); }, @@ -264,10 +261,9 @@ const commandsMap: { [command: string]: (...args: any) => any } = { await vscode.window.showTextDocument(uri); }, "continue.debugTerminal": async () => { - const terminalContents = await ideProtocolClient.getTerminalContents(1); + const terminalContents = await ide.getTerminalContents(); vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ - type: "userInput", + sidebar.webviewProtocol?.request("userInput", { input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents}`, }); }, @@ -280,21 +276,17 @@ const commandsMap: { [command: string]: (...args: any) => any } = { // Commands without keyboard shortcuts "continue.addModel": () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ - type: "addModel", - }); + sidebar.webviewProtocol?.request("addModel", undefined); }, "continue.openSettingsUI": () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ - type: "openSettings", - }); + sidebar.webviewProtocol?.request("openSettings", undefined); }, "continue.sendMainUserInput": (text: string) => { - ideProtocolClient.sendMainUserInput(text); + sidebar.sendMainUserInput(text); }, "continue.shareSession": () => { - ideProtocolClient.sendMainUserInput("/share"); + sidebar.sendMainUserInput("/share"); }, "continue.selectRange": (startLine: number, endLine: number) => { if (!vscode.window.activeTextEditor) { @@ -319,17 +311,13 @@ const commandsMap: { [command: string]: (...args: any) => any } = { }); }, "continue.sendToTerminal": (text: string) => { - ideProtocolClient.runCommand(text); + ide.runCommand(text); }, "continue.newSession": () => { - debugPanelWebview?.postMessage({ - type: "newSession", - }); + sidebar.webviewProtocol?.request("newSession", undefined); }, "continue.viewHistory": () => { - debugPanelWebview?.postMessage({ - type: "viewHistory", - }); + sidebar.webviewProtocol?.request("viewHistory", undefined); }, "continue.toggleFullScreen": () => { // Check if full screen is already open by checking open tabs @@ -364,7 +352,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { return; } - // Close the sidebars + // Close the sidebar.webviews // vscode.commands.executeCommand("workbench.action.closeSidebar"); vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); // vscode.commands.executeCommand("workbench.action.toggleZenMode"); @@ -373,9 +361,12 @@ const commandsMap: { [command: string]: (...args: any) => any } = { "Continue", vscode.ViewColumn.One ); - panel.webview.html = getSidebarContent( + panel.webview.html = sidebar.getSidebarContent( extensionContext, panel, + ide, + configHandler, + verticalDiffManager, undefined, undefined, true @@ -388,7 +379,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { vscode.commands.executeCommand("continue.continueGUIView.focus"); for (const uri of uris) { - addEntireFileToContext(uri, false); + addEntireFileToContext(uri, false, sidebar.webviewProtocol); } }, "continue.updateAllReferences": (filepath: vscode.Uri) => { @@ -398,7 +389,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { return; } const position = editor.selection.active; - ideProtocolClient.sendMainUserInput( + sidebar.sendMainUserInput( `/references ${filepath.fsPath} ${position.line} ${position.character}` ); }, @@ -408,7 +399,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { ) => { clearTimeout(logRejectionTimeout); outcome.accepted = true; - ideProtocolClient.logDevData("autocomplete", outcome); + logDevData("autocomplete", outcome); }, "continue.toggleTabAutocompleteEnabled": () => { const config = vscode.workspace.getConfiguration("continue"); @@ -419,10 +410,27 @@ const commandsMap: { [command: string]: (...args: any) => any } = { vscode.ConfigurationTarget.Global ); }, -}; +}); -export function registerAllCommands(context: vscode.ExtensionContext) { - for (const [command, callback] of Object.entries(commandsMap)) { +export function registerAllCommands( + context: vscode.ExtensionContext, + ide: IDE, + extensionContext: vscode.ExtensionContext, + sidebar: ContinueGUIWebviewViewProvider, + configHandler: ConfigHandler, + diffManager: DiffManager, + verticalDiffManager: VerticalPerLineDiffManager +) { + for (const [command, callback] of Object.entries( + commandsMap( + ide, + extensionContext, + sidebar, + configHandler, + diffManager, + verticalDiffManager + ) + )) { context.subscriptions.push( vscode.commands.registerCommand(command, callback) ); diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index a4c189701..c6d083281 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -1,707 +1,118 @@ -import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core"; -import { indexDocs } from "core/indexing/docs"; -import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; -import { editConfigJson, getConfigJsonPath } from "core/util/paths"; -import { readFileSync, writeFileSync } from "fs"; -import { v4 as uuidv4 } from "uuid"; +import { FileEdit, IDE } from "core"; +import { ConfigHandler } from "core/config/handler"; import * as vscode from "vscode"; -import { - extensionContext, - ideProtocolClient, - showTutorial, - windowId, -} from "./activation/activate"; -import { streamEdit } from "./diff/verticalPerLine/manager"; -import historyManager from "./history"; -import { VsCodeIde } from "./ideProtocol"; -import { configHandler, llmFromTitle } from "./loadConfig"; +import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import { getTheme } from "./util/getTheme"; import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; -export let debugPanelWebview: vscode.Webview | undefined; +export class ContinueGUIWebviewViewProvider + implements vscode.WebviewViewProvider +{ + public static readonly viewType = "continue.continueGUIView"; + public webviewProtocol: VsCodeWebviewProtocol; -export async function webviewRequest( - messageType: string, - data: any = {} -): Promise { - return new Promise((resolve, reject) => { - if (!debugPanelWebview) { - resolve(undefined); + resolveWebviewView( + webviewView: vscode.WebviewView, + _context: vscode.WebviewViewResolveContext, + _token: vscode.CancellationToken + ): void | Thenable { + this._webview = webviewView.webview; + webviewView.webview.html = this.getSidebarContent( + this.extensionContext, + webviewView, + this.ide, + this.configHandler, + this.verticalDiffManager + ); + } + + private _webview?: vscode.Webview; + + get webview() { + return this._webview; + } + + sendMainUserInput(input: string) { + this.webview?.postMessage({ + type: "userInput", + input, + }); + } + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly windowId: string, + private readonly extensionContext: vscode.ExtensionContext, + private readonly verticalDiffManager: VerticalPerLineDiffManager + ) { + this.webviewProtocol = new VsCodeWebviewProtocol( + ide, + configHandler, + verticalDiffManager + ); + } + + getSidebarContent( + context: vscode.ExtensionContext | undefined, + panel: vscode.WebviewPanel | vscode.WebviewView, + ide: IDE, + configHandler: ConfigHandler, + verticalDiffManager: VerticalPerLineDiffManager, + page: string | undefined = undefined, + edits: FileEdit[] | undefined = undefined, + isFullScreen: boolean = false + ): string { + let extensionUri = getExtensionUri(); + let scriptUri: string; + let styleMainUri: string; + let vscMediaUrl: string = panel.webview + .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui")) + .toString(); + + const inDevelopmentMode = + context?.extensionMode === vscode.ExtensionMode.Development; + if (!inDevelopmentMode) { + scriptUri = panel.webview + .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js")) + .toString(); + styleMainUri = panel.webview + .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css")) + .toString(); + } else { + scriptUri = "http://localhost:5173/src/main.tsx"; + styleMainUri = "http://localhost:5173/src/index.css"; } - const listener = debugPanelWebview?.onDidReceiveMessage((data) => { - if (data.type === messageType) { - resolve(data); - listener?.dispose(); - } - }); - - debugPanelWebview?.postMessage({ type: messageType, data }); - - setTimeout(() => { - reject("Error communciating with Continue side panel: timed out"); - listener?.dispose(); - }, 500); - }); -} - -const abortedMessageIds: Set = new Set(); - -export function getSidebarContent( - context: vscode.ExtensionContext | undefined, - panel: vscode.WebviewPanel | vscode.WebviewView, - page: string | undefined = undefined, - edits: FileEdit[] | undefined = undefined, - isFullScreen: boolean = false -): string { - if (!isFullScreen) { - debugPanelWebview = panel.webview; - panel.onDidDispose(() => { - debugPanelWebview = undefined; - }); - } - - let extensionUri = getExtensionUri(); - let scriptUri: string; - let styleMainUri: string; - let vscMediaUrl: string = panel.webview - .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui")) - .toString(); - - const inDevelopmentMode = - context?.extensionMode === vscode.ExtensionMode.Development; - if (!inDevelopmentMode) { - scriptUri = panel.webview - .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js")) - .toString(); - styleMainUri = panel.webview - .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css")) - .toString(); - } else { - scriptUri = "http://localhost:5173/src/main.tsx"; - styleMainUri = "http://localhost:5173/src/index.css"; - } - - panel.webview.options = { - enableScripts: true, - localResourceRoots: [ - vscode.Uri.joinPath(extensionUri, "gui"), - vscode.Uri.joinPath(extensionUri, "assets"), - ], - enableCommandUris: true, - portMapping: [ - { - webviewPort: 65433, - extensionHostPort: 65433, - }, - ], - }; - - const nonce = getNonce(); - - panel.webview.onDidReceiveMessage(async (data) => { - const ide = new VsCodeIde(); - const respond = (message: any) => { - panel.webview.postMessage({ - type: data.type, - messageId: data.messageId, - message: message, - }); + panel.webview.options = { + enableScripts: true, + localResourceRoots: [ + vscode.Uri.joinPath(extensionUri, "gui"), + vscode.Uri.joinPath(extensionUri, "assets"), + ], + enableCommandUris: true, + portMapping: [ + { + webviewPort: 65433, + extensionHostPort: 65433, + }, + ], }; - try { - switch (data.type) { - case "abort": { - abortedMessageIds.add(data.messageId); - break; - } - case "showFile": { - ideProtocolClient.openFile(data.filepath); - break; - } - case "openConfigJson": { - ideProtocolClient.openFile(getConfigJsonPath()); - break; - } - case "readRangeInFile": { - vscode.workspace.openTextDocument(data.filepath).then((document) => { - let start = new vscode.Position(0, 0); - let end = new vscode.Position(5, 0); - let range = new vscode.Range(start, end); - let contents = document.getText(range); - panel.webview.postMessage({ - type: "readRangeInFile", - messageId: data.messageId, - contents, - }); - }); - break; - } - case "toggleDevTools": { - vscode.commands.executeCommand("workbench.action.toggleDevTools"); - vscode.commands.executeCommand("continue.viewLogs"); - break; - } - case "reloadWindow": { - vscode.commands.executeCommand("workbench.action.reloadWindow"); - break; - } - case "focusEditor": { - vscode.commands.executeCommand( - "workbench.action.focusActiveEditorGroup" - ); - break; - } - case "toggleFullScreen": { - vscode.commands.executeCommand("continue.toggleFullScreen"); - break; - } - case "withProgress": { - // This message allows withProgress to be used in the webview - if (data.done) { - // Will be caught in the listener created below - break; - } - let title = data.title; - vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title, - cancellable: false, - }, - async () => { - return new Promise((resolve, reject) => { - let listener = panel.webview.onDidReceiveMessage( - async (data) => { - if ( - data.type === "withProgress" && - data.done && - data.title === title - ) { - listener.dispose(); - resolve(); - } - } - ); - }); - } - ); + const nonce = getNonce(); - break; - } - - // IDE - case "getDiff": { - respond(await ide.getDiff()); - break; - } - case "getSerializedConfig": { - respond(await ide.getSerializedConfig()); - break; - } - case "getTerminalContents": { - respond(await ide.getTerminalContents()); - break; - } - case "listWorkspaceContents": { - respond(await ide.listWorkspaceContents()); - break; - } - case "getWorkspaceDirs": { - respond(await ide.getWorkspaceDirs()); - break; - } - case "listFolders": { - respond(await ide.listFolders()); - break; - } - case "writeFile": { - respond( - await ide.writeFile(data.message.path, data.message.contents) - ); - break; - } - case "showVirtualFile": { - respond( - await ide.showVirtualFile(data.message.name, data.message.content) - ); - break; - } - case "getContinueDir": { - respond(await ide.getContinueDir()); - break; - } - case "openFile": { - respond(await ide.openFile(data.message.path)); - break; - } - case "runCommand": { - respond(await ide.runCommand(data.message.command)); - break; - } - case "getSearchResults": { - respond(await ide.getSearchResults(data.message.query)); - break; - } - case "subprocess": { - respond(await ide.subprocess(data.message.command)); - break; - } - case "getFilesToEmbed": { - let filesToEmbed = await ide.getFilesToEmbed(data.message.providerId); - respond(filesToEmbed); - break; - } - case "sendChunkForFile": { - respond( - await ide.sendEmbeddingForChunk( - data.message.chunk, - data.message.embedding, - data.message.tags - ) - ); - break; - } - case "retrieveChunks": { - respond( - await ide.retrieveChunks( - data.message.text, - data.message.n, - data.message.directory - ) - ); - break; - } - // History - case "history": { - respond(historyManager.list()); - break; - } - case "saveSession": { - historyManager.save(data.message); - respond({}); - break; - } - case "deleteSession": { - historyManager.delete(data.message); - respond({}); - break; - } - case "loadSession": { - respond(historyManager.load(data.message)); - break; - } - case "saveFile": { - respond(await ide.saveFile(data.message.filepath)); - break; - } - case "readFile": { - respond(await ide.readFile(data.message.filepath)); - break; - } - case "showDiff": { - respond( - await ide.showDiff( - data.message.filepath, - data.message.newContents, - data.message.stepIndex - ) - ); - break; - } - case "diffLine": { - const { - diffLine, - filepath, - startLine, - endLine, - }: { - diffLine: DiffLine; - filepath: string; - startLine: number; - endLine: number; - } = data.message; - - respond( - await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine) - ); - break; - } - case "getProblems": { - respond(await ide.getProblems(data.message.filepath)); - break; - } - case "getBranch": { - const { dir } = data.message; - respond(await ide.getBranch(dir)); - break; - } - case "getOpenFiles": { - respond(await ide.getOpenFiles()); - break; - } - case "getPinnedFiles": { - respond(await ide.getPinnedFiles()); - break; - } - case "showLines": { - const { filepath, startLine, endLine } = data.message; - respond(await ide.showLines(filepath, startLine, endLine)); - break; - } - // Other - case "errorPopup": { - vscode.window - .showErrorMessage(data.message, "Show Logs") - .then((selection) => { - if (selection === "Show Logs") { - vscode.commands.executeCommand( - "workbench.action.toggleDevTools" - ); - } - }); - break; - } - case "logDevData": { - ideProtocolClient.logDevData(data.tableName, data.data); - break; - } - case "addModel": { - const model = data.model; - const config = readFileSync(getConfigJsonPath(), "utf8"); - const configJson = JSON.parse(config); - configJson.models.push(model); - const newConfigString = JSON.stringify( - configJson, - (key, value) => { - return value === null ? undefined : value; - }, - 2 - ); - writeFileSync(getConfigJsonPath(), newConfigString); - configHandler.reloadConfig(); - ideProtocolClient.openFile(getConfigJsonPath()); - - // Find the range where it was added and highlight - let lines = newConfigString.split("\n"); - let startLine; - let endLine; - for (let i = 0; i < lines.length; i++) { - let line = lines[i]; - - if (!startLine) { - if (line.trim() === `"title": "${data.model.title}",`) { - startLine = i - 1; - } - } else { - if (line.startsWith(" }")) { - endLine = i; - break; - } - } - } - - if (startLine && endLine) { - ideProtocolClient.highlightCode( - { - filepath: getConfigJsonPath(), - range: { - start: { character: 0, line: startLine }, - end: { character: 0, line: endLine }, - }, - }, - "#fff1" - ); - } - vscode.window.showInformationMessage( - "🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration." - ); - break; - } - case "deleteModel": { - const configJson = editConfigJson((config) => { - config.models = config.models.filter( - (m: any) => m.title !== data.title - ); - return config; - }); - configHandler.reloadConfig(); - break; - } - case "addOpenAIKey": { - const configJson = editConfigJson((config) => { - config.models = config.models.map((m: ModelDescription) => { - if (m.provider === "free-trial") { - m.apiKey = data.key; - m.provider = "openai"; - } - return m; - }); - return config; - }); - configHandler.reloadConfig(); - break; - } - case "llmStreamComplete": { - const model = await llmFromTitle(data.message.title); - const gen = model.streamComplete( - data.message.prompt, - data.message.completionOptions - ); - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(data.messageId)) { - abortedMessageIds.delete(data.messageId); - next = await gen.return({ completion: "", prompt: "" }); - break; - } - respond({ content: next.value }); - next = await gen.next(); - } - - respond({ done: true, data: next.value }); - break; - } - case "llmStreamChat": { - const model = await llmFromTitle(data.message.title); - const gen = model.streamChat( - data.message.messages, - data.message.completionOptions - ); - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(data.messageId)) { - abortedMessageIds.delete(data.messageId); - next = await gen.return({ completion: "", prompt: "" }); - break; - } - respond({ content: next.value.content }); - next = await gen.next(); - } - - respond({ done: true, data: next.value }); - break; - } - case "llmComplete": { - const model = await llmFromTitle(data.message.title); - const completion = await model.complete( - data.message.prompt, - data.message.completionOptions - ); - respond({ content: completion }); - break; - } - case "runNodeJsSlashCommand": { - const { - input, - history, - modelTitle, - slashCommandName, - contextItems, - params, - historyIndex, - } = data.message; - - const config = await configHandler.loadConfig(); - const llm = await llmFromTitle(modelTitle); - const slashCommand = config.slashCommands?.find( - (sc) => sc.name === slashCommandName - ); - if (!slashCommand) { - throw new Error(`Unknown slash command ${slashCommandName}`); - } - - for await (const update of slashCommand.run({ - input, - history, - llm, - contextItems, - params, - ide, - addContextItem: (item) => { - debugPanelWebview?.postMessage({ - type: "addContextItem", - message: { item, historyIndex }, - }); - }, - })) { - if (abortedMessageIds.has(data.messageId)) { - abortedMessageIds.delete(data.messageId); - break; - } - respond({ content: update }); - } - respond({ done: true }); - break; - } - case "loadSubmenuItems": { - const { title } = data.message; - const config = await configHandler.loadConfig(); - const provider = config.contextProviders?.find( - (p) => p.description.title === title - ); - if (!provider) { - vscode.window.showErrorMessage( - `Unknown provider ${title}. Existing providers: ${config.contextProviders - ?.map((p) => p.description.title) - .join(", ")}` - ); - respond({ items: [] }); - break; - } - - try { - const items = await provider.loadSubmenuItems({ ide }); - respond({ items }); - } catch (e) { - vscode.window.showErrorMessage( - `Error loading submenu items from ${title}: ${e}` - ); - respond({ items: [] }); - } - break; - } - case "getContextItems": { - const { name, query, fullInput, selectedCode } = data.message; - const config = await configHandler.loadConfig(); - const llm = await llmFromTitle(); - const provider = config.contextProviders?.find( - (p) => p.description.title === name - ); - if (!provider) { - vscode.window.showErrorMessage( - `Unknown provider ${name}. Existing providers: ${config.contextProviders - ?.map((p) => p.description.title) - .join(", ")}` - ); - respond({ items: [] }); - break; - } - - try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: uuidv4(), - }; - const items = await provider.getContextItems(query, { - llm, - embeddingsProvider: config.embeddingsProvider, - fullInput, - ide, - selectedCode, - }); - respond({ items: items.map((item) => ({ ...item, id })) }); - } catch (e) { - vscode.window.showErrorMessage( - `Error getting context items from ${name}: ${e}` - ); - respond({ items: [] }); - } - break; - } - case "addDocs": { - const { url, title } = data; - const embeddingsProvider = new TransformersJsEmbeddingsProvider(); - vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: `Indexing ${title}`, - cancellable: false, - }, - async (progress) => { - for await (const update of indexDocs( - title, - new URL(url), - embeddingsProvider - )) { - progress.report({ - increment: update.progress, - message: update.desc, - }); - } - - vscode.window.showInformationMessage( - `🎉 Successfully indexed ${title}` - ); - - debugPanelWebview?.postMessage({ - type: "refreshSubmenuItems", - }); - } - ); - break; - } - case "applyToCurrentFile": { - // Select the entire current file - const editor = vscode.window.activeTextEditor; - if (!editor) { - vscode.window.showErrorMessage( - "No active editor to apply edits to" - ); - break; - } - const document = editor.document; - - if (document.getText().trim() === "") { - editor.edit((editBuilder) => { - editBuilder.insert(document.positionAt(0), data.text); - }); - return; - } - - const start = new vscode.Position(0, 0); - const end = new vscode.Position( - document.lineCount - 1, - document.lineAt(document.lineCount - 1).text.length - ); - editor.selection = new vscode.Selection(start, end); - - streamEdit( - `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.` - ); - break; - } - case "showTutorial": { - showTutorial(); - break; - } - } - } catch (e: any) { - let message = `Continue error: ${e.message}`; - if (e.cause) { - if (e.cause.name === "ConnectTimeoutError") { - message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`; - } else if (e.cause.code === "ECONNREFUSED") { - message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`; - } else { - message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`; - } + const currentTheme = getTheme(); + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("workbench.colorTheme")) { + // Send new theme to GUI to update embedded Monaco themes + this.webviewProtocol?.request("setTheme", { theme: getTheme() }); } + }); - vscode.window - .showErrorMessage(message, "Show Logs", "Troubleshooting") - .then((selection) => { - if (selection === "Show Logs") { - vscode.commands.executeCommand("workbench.action.toggleDevTools"); - } else if (selection === "Troubleshooting") { - vscode.env.openExternal( - vscode.Uri.parse("https://continue.dev/docs/troubleshooting") - ); - } - }); - respond({ done: true, data: {} }); - } - }); + this.webviewProtocol.webview = panel.webview; - const currentTheme = getTheme(); - vscode.workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("workbench.colorTheme")) { - // Send new theme to GUI to update embedded Monaco themes - debugPanelWebview?.postMessage({ type: "setTheme", theme: getTheme() }); - } - }); - - return ` + return ` @@ -729,7 +140,7 @@ export function getSidebarContent( - + @@ -750,18 +161,5 @@ export function getSidebarContent( ${page ? `` : ""} `; -} - -export class ContinueGUIWebviewViewProvider - implements vscode.WebviewViewProvider -{ - public static readonly viewType = "continue.continueGUIView"; - - resolveWebviewView( - webviewView: vscode.WebviewView, - _context: vscode.WebviewViewResolveContext, - _token: vscode.CancellationToken - ): void | Thenable { - webviewView.webview.html = getSidebarContent(extensionContext, webviewView); } } diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index b782658af..b71abf9ba 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -3,11 +3,9 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; -import { extensionContext } from "../activation/activate"; -import { debugPanelWebview } from "../debugPanel"; import { getMetaKeyLabel, getPlatform } from "../util/util"; import { uriFromFilePath } from "../util/vscode"; -import { verticalPerLineDiffManager } from "./verticalPerLine/manager"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; interface DiffInfo { originalFilepath: string; @@ -32,7 +30,7 @@ export const DIFF_DIRECTORY = path .join(os.homedir(), ".continue", "diffs") .replace(/^C:/, "c:"); -class DiffManager { +export class DiffManager { // Create a temporary file in the global .continue directory which displays the updated version // Doing this because virtual files are read-only private diffs: Map = new Map(); @@ -50,7 +48,9 @@ class DiffManager { } } - constructor() { + webviewProtocol: VsCodeWebviewProtocol | undefined; + + constructor(private readonly extensionContext: vscode.ExtensionContext) { this.setupDirectory(); // Listen for file closes, and if it's a diff file, clean up @@ -115,7 +115,7 @@ class DiffManager { .update("codeLens", true, vscode.ConfigurationTarget.Global); if ( - extensionContext?.globalState.get( + this.extensionContext.globalState.get( "continue.showDiffInfoMessage" ) !== false ) { @@ -128,7 +128,7 @@ class DiffManager { .then((selection) => { if (selection === "Don't show again") { // Get the global state - extensionContext?.globalState.update( + this.extensionContext.globalState.update( "continue.showDiffInfoMessage", false ); @@ -289,7 +289,7 @@ class DiffManager { } // Stop the step at step_index in case it is still streaming - debugPanelWebview?.postMessage({ type: "setInactive" }); + this.webviewProtocol?.request("setInactive", undefined); vscode.workspace.textDocuments .find((doc) => doc.uri.fsPath === newFilepath) @@ -302,8 +302,6 @@ class DiffManager { } } -export const diffManager = new DiffManager(); - async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) { const devDataDir = devDataPath(); const suggestionsPath = path.join(devDataDir, "suggestions.json"); @@ -333,19 +331,3 @@ async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) { JSON.stringify(suggestions, null, 4) ); } - -export async function acceptDiffCommand(newFilepath?: string | vscode.Uri) { - if (newFilepath instanceof vscode.Uri) { - newFilepath = newFilepath.fsPath; - } - verticalPerLineDiffManager.clearForFilepath(newFilepath, true); - await diffManager.acceptDiff(newFilepath); -} - -export async function rejectDiffCommand(newFilepath?: string | vscode.Uri) { - if (newFilepath instanceof vscode.Uri) { - newFilepath = newFilepath.fsPath; - } - verticalPerLineDiffManager.clearForFilepath(newFilepath, false); - await diffManager.rejectDiff(newFilepath); -} diff --git a/extensions/vscode/src/diff/verticalPerLine/handler.ts b/extensions/vscode/src/diff/verticalPerLine/handler.ts index b6e60e3db..d6737b701 100644 --- a/extensions/vscode/src/diff/verticalPerLine/handler.ts +++ b/extensions/vscode/src/diff/verticalPerLine/handler.ts @@ -7,10 +7,7 @@ import { indexDecorationType, redDecorationType, } from "./decorations"; -import { - editorToVerticalDiffCodeLens, - verticalPerLineDiffManager, -} from "./manager"; +import { VerticalDiffCodeLens } from "./manager"; export class VerticalPerLineDiffHandler { private editor: vscode.TextEditor; @@ -33,6 +30,14 @@ export class VerticalPerLineDiffHandler { startLine: number, endLine: number, editor: vscode.TextEditor, + private readonly editorToVerticalDiffCodeLens: Map< + string, + VerticalDiffCodeLens[] + >, + private readonly clearForFilepath: ( + filepath: string | undefined, + accept: boolean + ) => void, input?: string ) { this.currentLineIndex = startLine; @@ -71,13 +76,13 @@ export class VerticalPerLineDiffHandler { } if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { - const blocks = editorToVerticalDiffCodeLens.get(this.filepath) || []; + const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || []; blocks.push({ start: this.currentLineIndex - this.insertedInCurrentBlock, numRed: this.deletionBuffer.length, numGreen: this.insertedInCurrentBlock, }); - editorToVerticalDiffCodeLens.set(this.filepath, blocks); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } if (this.deletionBuffer.length === 0) { @@ -188,7 +193,7 @@ export class VerticalPerLineDiffHandler { this.greenDecorationManager.clear(); this.clearIndexLineDecorations(); - editorToVerticalDiffCodeLens.delete(this.filepath); + this.editorToVerticalDiffCodeLens.delete(this.filepath); this.editor.edit((editBuilder) => { for (const range of rangesToDelete) { @@ -251,7 +256,7 @@ export class VerticalPerLineDiffHandler { // } // }); } catch (e) { - verticalPerLineDiffManager.clearForFilepath(this.filepath, false); + this.clearForFilepath(this.filepath, false); throw e; } } @@ -288,7 +293,7 @@ export class VerticalPerLineDiffHandler { // Shift the codelens objects const blocks = - editorToVerticalDiffCodeLens + this.editorToVerticalDiffCodeLens .get(this.filepath) ?.filter((x) => x.start !== startLine) .map((x) => { @@ -297,6 +302,6 @@ export class VerticalPerLineDiffHandler { } return x; }) || []; - editorToVerticalDiffCodeLens.set(this.filepath, blocks); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } } diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index f42d42e9a..e4dff637e 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -1,13 +1,23 @@ -import { streamDiffLines } from "core/commands/slash/verticalEdit"; +import { ConfigHandler } from "core/config/handler"; import { getMarkdownLanguageTagForFile } from "core/util"; +import { streamDiffLines } from "core/util/verticalEdit"; import * as vscode from "vscode"; -import { llmFromTitle } from "../../loadConfig"; import { VerticalPerLineDiffHandler } from "./handler"; -class VerticalPerLineDiffManager { +export interface VerticalDiffCodeLens { + start: number; + numRed: number; + numGreen: number; +} + +export class VerticalPerLineDiffManager { private filepathToEditorMap: Map = new Map(); + editorToVerticalDiffCodeLens: Map = new Map(); + + constructor(private readonly configHandler: ConfigHandler) {} + createVerticalPerLineDiffHandler( filepath: string, startLine: number, @@ -24,6 +34,8 @@ class VerticalPerLineDiffManager { startLine, endLine, editor, + this.editorToVerticalDiffCodeLens, + this.clearForFilepath, input ); this.filepathToEditorMap.set(filepath, handler); @@ -46,7 +58,9 @@ class VerticalPerLineDiffManager { const handler = new VerticalPerLineDiffHandler( startLine, endLine, - editor + editor, + this.editorToVerticalDiffCodeLens, + this.clearForFilepath ); this.filepathToEditorMap.set(filepath, handler); return handler; @@ -75,78 +89,113 @@ class VerticalPerLineDiffManager { this.filepathToEditorMap.delete(filepath); } } -} -export const verticalPerLineDiffManager = new VerticalPerLineDiffManager(); + acceptRejectVerticalDiffBlock( + accept: boolean, + filepath?: string, + index?: number + ) { + if (!filepath) { + const activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + return; + } + filepath = activeEditor.document.uri.fsPath; + } -export async function streamEdit(input: string) { - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; + if (typeof index === "undefined") { + index = 0; + } + + let blocks = this.editorToVerticalDiffCodeLens.get(filepath); + const block = blocks?.[index]; + if (!blocks || !block) { + return; + } + + const handler = this.getHandlerForFile(filepath); + if (!handler) { + return; + } + + // CodeLens object removed from editorToVerticalDiffCodeLens here + handler.acceptRejectBlock( + accept, + block.start, + block.numGreen, + block.numRed + ); } - const filepath = editor.document.uri.fsPath; - const startLine = editor.selection.start.line; - const endLine = editor.selection.end.line; + async streamEdit(input: string) { + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } - const existingHandler = - verticalPerLineDiffManager.getHandlerForFile(filepath); - existingHandler?.clear(false); - await new Promise((resolve) => { - setTimeout(resolve, 200); - }); - const diffHandler = - verticalPerLineDiffManager.createVerticalPerLineDiffHandler( + const filepath = editor.document.uri.fsPath; + const startLine = editor.selection.start.line; + const endLine = editor.selection.end.line; + + const existingHandler = this.getHandlerForFile(filepath); + existingHandler?.clear(false); + await new Promise((resolve) => { + setTimeout(resolve, 200); + }); + const diffHandler = this.createVerticalPerLineDiffHandler( filepath, existingHandler?.range.start.line ?? startLine, existingHandler?.range.end.line ?? endLine, input ); - if (!diffHandler) { - return; - } + if (!diffHandler) { + return; + } - const selectedRange = - existingHandler?.range ?? - new vscode.Range( - editor.selection.start.with(undefined, 0), - editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER) + const selectedRange = + existingHandler?.range ?? + new vscode.Range( + editor.selection.start.with(undefined, 0), + editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER) + ); + const rangeContent = editor.document.getText(selectedRange); + const llm = await this.configHandler.llmFromTitle(); + + // Unselect the range + editor.selection = new vscode.Selection( + editor.selection.active, + editor.selection.active ); - const rangeContent = editor.document.getText(selectedRange); - const llm = await llmFromTitle(); - // Unselect the range - editor.selection = new vscode.Selection( - editor.selection.active, - editor.selection.active - ); + vscode.commands.executeCommand( + "setContext", + "continue.streamingDiff", + true + ); - vscode.commands.executeCommand("setContext", "continue.streamingDiff", true); - - if (existingHandler?.input) { - if (existingHandler.input.startsWith("Original request: ")) { - existingHandler.input = existingHandler.input.substring( - "Original request: ".length + if (existingHandler?.input) { + if (existingHandler.input.startsWith("Original request: ")) { + existingHandler.input = existingHandler.input.substring( + "Original request: ".length + ); + } + input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`; + } + try { + await diffHandler.run( + streamDiffLines( + rangeContent, + llm, + input, + getMarkdownLanguageTagForFile(filepath) + ) + ); + } finally { + vscode.commands.executeCommand( + "setContext", + "continue.streamingDiff", + false ); } - input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`; } - - await diffHandler.run( - streamDiffLines( - rangeContent, - llm, - input, - getMarkdownLanguageTagForFile(filepath) - ) - ); } - -export interface VerticalDiffCodeLens { - start: number; - numRed: number; - numGreen: number; -} - -export const editorToVerticalDiffCodeLens: Map = - new Map(); diff --git a/extensions/vscode/src/extension/autocomplete.ts b/extensions/vscode/src/extension/autocomplete.ts new file mode 100644 index 000000000..e69de29bb diff --git a/extensions/vscode/src/extension/indexing.ts b/extensions/vscode/src/extension/indexing.ts new file mode 100644 index 000000000..e69de29bb diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts new file mode 100644 index 000000000..a83b7838b --- /dev/null +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -0,0 +1,182 @@ +import { ConfigHandler } from "core/config/handler"; +import { CodebaseIndexer } from "core/indexing/indexCodebase"; +import { v4 as uuidv4 } from "uuid"; +import * as vscode from "vscode"; +import { registerAllCommands } from "../commands"; +import { ContinueGUIWebviewViewProvider } from "../debugPanel"; +import { DiffManager } from "../diff/horizontal"; +import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; +import { VsCodeIde } from "../ideProtocol"; +import { registerAllCodeLensProviders } from "../lang-server/codeLens"; +import { + ContinueCompletionProvider, + setupStatusBar, +} from "../lang-server/completionProvider"; +import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; + +export class VsCodeExtension { + private configHandler: ConfigHandler; + private extensionContext: vscode.ExtensionContext; + private ide: VsCodeIde; + private tabAutocompleteModel: TabAutocompleteModel; + private sidebar: ContinueGUIWebviewViewProvider; + private windowId: string; + private indexer: CodebaseIndexer; + private diffManager: DiffManager; + private verticalDiffManager: VerticalPerLineDiffManager; + private webviewProtocol: VsCodeWebviewProtocol; + + constructor(context: vscode.ExtensionContext) { + this.diffManager = new DiffManager(context); + this.ide = new VsCodeIde(this.diffManager); + this.configHandler = new ConfigHandler(this.ide); + this.configHandler.reloadConfig(); + this.verticalDiffManager = new VerticalPerLineDiffManager( + this.configHandler + ); + this.extensionContext = context; + this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); + this.windowId = uuidv4(); + this.sidebar = new ContinueGUIWebviewViewProvider( + this.configHandler, + this.ide, + this.windowId, + this.extensionContext, + this.verticalDiffManager + ); + + // Sidebar + context.subscriptions.push( + vscode.window.registerWebviewViewProvider( + "continue.continueGUIView", + this.sidebar, + { + webviewOptions: { retainContextWhenHidden: true }, + } + ) + ); + this.webviewProtocol = this.sidebar.webviewProtocol; + + this.diffManager.webviewProtocol = this.webviewProtocol; + this.indexer = new CodebaseIndexer(this.configHandler, this.ide); + + // CodeLens + registerAllCodeLensProviders( + context, + this.diffManager, + this.verticalDiffManager.editorToVerticalDiffCodeLens + ); + + // Tab autocomplete + const config = vscode.workspace.getConfiguration("continue"); + const enabled = config.get("enableTabAutocomplete"); + + // Register inline completion provider (odd versions are pre-release) + if ( + parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !== + 0 + ) { + setupStatusBar(enabled); + context.subscriptions.push( + vscode.languages.registerInlineCompletionItemProvider( + [{ pattern: "**" }], + new ContinueCompletionProvider( + this.configHandler, + this.ide, + this.tabAutocompleteModel + ) + ) + ); + } + + // Commands + registerAllCommands( + context, + this.ide, + context, + this.sidebar, + this.configHandler, + this.diffManager, + this.verticalDiffManager + ); + + // Indexing + this.ide.getWorkspaceDirs().then((dirs) => this.refreshCodebaseIndex(dirs)); + + // Listen for file saving + vscode.workspace.onDidSaveTextDocument((event) => { + const filepath = event.uri.fsPath; + + if ( + filepath.endsWith(".continue/config.json") || + filepath.endsWith(".continue\\config.json") || + filepath.endsWith(".continue/config.ts") || + filepath.endsWith(".continue\\config.ts") || + filepath.endsWith(".continuerc.json") + ) { + this.configHandler.reloadConfig(); + this.tabAutocompleteModel.clearLlm(); + } else if ( + filepath.endsWith(".continueignore") || + filepath.endsWith(".gitignore") + ) { + // Update embeddings! (TODO) + } + }); + + // Refresh index when branch is changed + this.ide.getWorkspaceDirs().then((dirs) => + dirs.forEach(async (dir) => { + const repo = await this.ide.getRepo(vscode.Uri.file(dir)); + if (repo) { + repo.state.onDidChange(() => { + // args passed to this callback are always undefined, so keep track of previous branch + const currentBranch = repo?.state?.HEAD?.name; + if (currentBranch) { + if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) { + if ( + currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] + ) { + // Trigger refresh of index only in this directory + this.refreshCodebaseIndex([dir]); + } + } + + this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch; + } + }); + } + }) + ); + + // Register a content provider for the readonly virtual documents + const documentContentProvider = new (class + implements vscode.TextDocumentContentProvider + { + // emitter and its event + onDidChangeEmitter = new vscode.EventEmitter(); + onDidChange = this.onDidChangeEmitter.event; + + provideTextDocumentContent(uri: vscode.Uri): string { + return uri.query; + } + })(); + context.subscriptions.push( + vscode.workspace.registerTextDocumentContentProvider( + VsCodeExtension.continueVirtualDocumentScheme, + documentContentProvider + ) + ); + } + + static continueVirtualDocumentScheme = "continue"; + + private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {}; + + private async refreshCodebaseIndex(dirs: string[]) { + for await (const update of this.indexer.refresh(dirs)) { + this.webviewProtocol.request("indexProgress", update); + } + } +} diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index e7855934a..26ca8ed78 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -2,48 +2,105 @@ import { exec } from "child_process"; import { getContinueGlobalPath } from "core/util/paths"; import * as path from "path"; import * as vscode from "vscode"; -import { ideProtocolClient } from "./activation/activate"; import * as child_process from "child_process"; -import { Chunk, DiffLine, IDE, Problem } from "core"; -import { - BrowserSerializedContinueConfig, - finalToBrowserConfig, -} from "core/config/load"; -import { LanceDbIndex } from "core/indexing/LanceDbIndex"; -import { IndexTag } from "core/indexing/types"; -import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; -import { configHandler } from "./loadConfig"; +import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "core"; +import { DiffManager } from "./diff/horizontal"; +import { VsCodeIdeUtils } from "./util/ideUtils"; import { traverseDirectory } from "./util/traverseDirectory"; import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; class VsCodeIde implements IDE { - async getSerializedConfig(): Promise { - const config = await configHandler.loadConfig(); - return finalToBrowserConfig(config); + ideUtils: VsCodeIdeUtils; + + constructor(private readonly diffManager: DiffManager) { + this.ideUtils = new VsCodeIdeUtils(); + } + getIdeInfo(): Promise { + return Promise.resolve({ + ideType: "vscode", + name: vscode.env.appName, + version: vscode.version, + remoteName: vscode.env.remoteName || "local", + }); + } + readRangeInFile(filepath: string, range: Range): Promise { + return this.ideUtils.readRangeInFile( + filepath, + new vscode.Range( + new vscode.Position(range.start.line, range.start.character), + new vscode.Position(range.end.line, range.end.character) + ) + ); + } + + async getStats(directory: string): Promise<{ [path: string]: number }> { + const files = await this.listWorkspaceContents(directory); + const pathToLastModified: { [path: string]: number } = {}; + await Promise.all( + files.map(async (file) => { + let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file)); + pathToLastModified[file] = stat.mtime; + }) + ); + + return pathToLastModified; + } + + async getRepo(dir: vscode.Uri): Promise { + return this.ideUtils.getRepo(dir); + } + + async isTelemetryEnabled(): Promise { + return ( + (await vscode.workspace + .getConfiguration("continue") + .get("telemetryEnabled")) ?? true + ); + } + getUniqueId(): Promise { + return Promise.resolve(vscode.env.machineId); } async getDiff(): Promise { - return await ideProtocolClient.getDiff(); + return await this.ideUtils.getDiff(); } async getTerminalContents(): Promise { - return await ideProtocolClient.getTerminalContents(1); + return await this.ideUtils.getTerminalContents(1); } async listWorkspaceContents(directory?: string): Promise { if (directory) { - return await ideProtocolClient.getDirectoryContents(directory, true); + return await this.ideUtils.getDirectoryContents(directory, true); } else { const contents = await Promise.all( - ideProtocolClient + this.ideUtils .getWorkspaceDirectories() - .map((dir) => ideProtocolClient.getDirectoryContents(dir, true)) + .map((dir) => this.ideUtils.getDirectoryContents(dir, true)) ); return contents.flat(); } } + async getWorkspaceConfigs() { + const workspaceDirs = + vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || []; + const configs: ContinueRcJson[] = []; + for (const workspaceDir of workspaceDirs) { + const files = await vscode.workspace.fs.readDirectory(workspaceDir); + for (const [filename, type] of files) { + if (type === vscode.FileType.File && filename === ".continuerc.json") { + const contents = await this.ideUtils.readFile( + vscode.Uri.joinPath(workspaceDir, filename).fsPath + ); + configs.push(JSON.parse(contents)); + } + } + } + return configs; + } + async listFolders(): Promise { const allDirs: string[] = []; @@ -63,7 +120,7 @@ class VsCodeIde implements IDE { } async getWorkspaceDirs(): Promise { - return ideProtocolClient.getWorkspaceDirectories(); + return this.ideUtils.getWorkspaceDirectories(); } async getContinueDir(): Promise { @@ -78,11 +135,11 @@ class VsCodeIde implements IDE { } async showVirtualFile(title: string, contents: string): Promise { - ideProtocolClient.showVirtualFile(title, contents); + this.ideUtils.showVirtualFile(title, contents); } async openFile(path: string): Promise { - ideProtocolClient.openFile(path); + this.ideUtils.openFile(path); } async showLines( @@ -95,53 +152,44 @@ class VsCodeIde implements IDE { new vscode.Position(endLine, 0) ); openEditorAndRevealRange(filepath, range).then(() => { - ideProtocolClient.highlightCode( - { - filepath, - range, - }, - "#fff1" - ); + // TODO: Highlight lines + // this.ideUtils.highlightCode( + // { + // filepath, + // range, + // }, + // "#fff1" + // ); }); } async runCommand(command: string): Promise { - await ideProtocolClient.runCommand(command); + if (vscode.window.terminals.length) { + vscode.window.terminals[0].show(); + vscode.window.terminals[0].sendText(command, false); + } else { + const terminal = vscode.window.createTerminal(); + terminal.show(); + terminal.sendText(command, false); + } } async saveFile(filepath: string): Promise { - await ideProtocolClient.saveFile(filepath); + await this.ideUtils.saveFile(filepath); } async readFile(filepath: string): Promise { - return await ideProtocolClient.readFile(filepath); + return await this.ideUtils.readFile(filepath); } async showDiff( filepath: string, newContents: string, stepIndex: number ): Promise { - await ideProtocolClient.showDiff(filepath, newContents, stepIndex); - } - - async verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ) { - const diffHandler = - verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler( - filepath, - startLine, - endLine - ); - if (diffHandler) { - await diffHandler.handleDiffLine(diffLine); - } + await this.diffManager.writeDiff(filepath, newContents, stepIndex); } async getOpenFiles(): Promise { - return await ideProtocolClient.getOpenFiles(); + return await this.ideUtils.getOpenFiles(); } async getPinnedFiles(): Promise { @@ -227,48 +275,7 @@ class VsCodeIde implements IDE { } async getBranch(dir: string): Promise { - return ideProtocolClient.getBranch(vscode.Uri.file(dir)); - } - - async getFilesToEmbed( - providerId: string - ): Promise<[string, string, string][]> { - return []; - } - - async sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ) {} - - async retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - const embeddingsProvider = (await configHandler.loadConfig()) - .embeddingsProvider; - if (!embeddingsProvider) { - return []; - } - const lanceDbIndex = new LanceDbIndex(embeddingsProvider, (path) => - ideProtocolClient.readFile(path) - ); - - const tags = await Promise.all( - (await this.getWorkspaceDirs()).map(async (dir) => { - let branch = await ideProtocolClient.getBranch(vscode.Uri.file(dir)); - let tag: IndexTag = { - directory: dir, - branch, - artifactId: lanceDbIndex.artifactId, - }; - return tag; - }) - ); - let chunks = await lanceDbIndex.retrieve(tags, text, n, directory); - return chunks as any[]; + return this.ideUtils.getBranch(vscode.Uri.file(dir)); } } diff --git a/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts b/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts new file mode 100644 index 000000000..eab90c80e --- /dev/null +++ b/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts @@ -0,0 +1,31 @@ +import { IDE } from "core"; +import { AutocompleteSnippet } from "core/autocomplete/constructPrompt"; +import * as vscode from "vscode"; + +export class AutocompletePromptBuilder { + constructor(private readonly ide: IDE) {} + + async getDefinition( + uri: string, + line: number, + character: number + ): Promise { + const definitions = (await vscode.commands.executeCommand( + "vscode.executeDefinitionProvider", + vscode.Uri.parse(uri), + new vscode.Position(line, character) + )) as any; + + if (definitions[0]?.targetRange) { + return { + filepath: uri, + content: await this.ide.readRangeInFile( + definitions[0].targetUri.fsPath, + definitions[0].targetRange + ), + }; + } + + return undefined; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts index 04915b777..04df50e69 100644 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ b/extensions/vscode/src/lang-server/codeLens.ts @@ -1,19 +1,26 @@ import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; -import { DIFF_DIRECTORY, diffManager } from "../diff/horizontal"; -import { editorToVerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; +import { DIFF_DIRECTORY, DiffManager } from "../diff/horizontal"; +import { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions"; import { getMetaKeyLabel } from "../util/util"; import { getExtensionUri } from "../util/vscode"; class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { + constructor( + private readonly editorToVerticalDiffCodeLens: Map< + string, + VerticalDiffCodeLens[] + > + ) {} + public provideCodeLenses( document: vscode.TextDocument, _: vscode.CancellationToken ): vscode.CodeLens[] | Thenable { const filepath = document.uri.fsPath; - const blocks = editorToVerticalDiffCodeLens.get(filepath); + const blocks = this.editorToVerticalDiffCodeLens.get(filepath); if (!blocks) { return []; } @@ -28,12 +35,12 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { ); codeLenses.push( new vscode.CodeLens(range, { - title: "Accept ✅", + title: "Accept", command: "continue.acceptVerticalDiffBlock", arguments: [filepath, i], }), new vscode.CodeLens(range, { - title: "Reject ❌", + title: "Reject", command: "continue.rejectVerticalDiffBlock", arguments: [filepath, i], }) @@ -41,7 +48,7 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { if (codeLenses.length === 2) { codeLenses.push( new vscode.CodeLens(range, { - title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}⇧L to retry)`, + title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}I to retry)`, command: "", }) ); @@ -71,12 +78,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider { ); codeLenses.push( new vscode.CodeLens(range, { - title: "Accept ✅", + title: "Accept", command: "continue.acceptSuggestion", arguments: [suggestion], }), new vscode.CodeLens(range, { - title: "Reject ❌", + title: "Reject", command: "continue.rejectSuggestion", arguments: [suggestion], }) @@ -96,6 +103,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider { } class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { + diffManager: DiffManager; + + constructor(diffManager: DiffManager) { + this.diffManager = diffManager; + } + public provideCodeLenses( document: vscode.TextDocument, _: vscode.CancellationToken @@ -103,7 +116,7 @@ class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) { const codeLenses: vscode.CodeLens[] = []; let range = new vscode.Range(0, 0, 1, 0); - const diffInfo = diffManager.diffAtNewFilepath(document.uri.fsPath); + const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath); if (diffInfo) { range = diffInfo.range; } @@ -334,7 +347,11 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; -export function registerAllCodeLensProviders(context: vscode.ExtensionContext) { +export function registerAllCodeLensProviders( + context: vscode.ExtensionContext, + diffManager: DiffManager, + editorToVerticalDiffCodeLens: Map +) { if (verticalPerLineCodeLensProvider) { verticalPerLineCodeLensProvider.dispose(); } @@ -353,7 +370,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) { verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider( "*", - new VerticalPerLineCodeLensProvider() + new VerticalPerLineCodeLensProvider(editorToVerticalDiffCodeLens) ); suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", @@ -361,7 +378,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) { ); diffsCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", - new DiffViewerCodeLensProvider() + new DiffViewerCodeLensProvider(diffManager) ); configPyCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", diff --git a/extensions/vscode/src/lang-server/completionProvider.ts b/extensions/vscode/src/lang-server/completionProvider.ts index bf6d22ccc..2231b92d4 100644 --- a/extensions/vscode/src/lang-server/completionProvider.ts +++ b/extensions/vscode/src/lang-server/completionProvider.ts @@ -1,8 +1,7 @@ -import { TabAutocompleteOptions } from "core"; +import { IDE, TabAutocompleteOptions } from "core"; import { AutocompleteLruCache } from "core/autocomplete/cache"; import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; import { - AutocompleteSnippet, constructAutocompletePrompt, languageForFilepath, } from "core/autocomplete/constructPrompt"; @@ -12,13 +11,15 @@ import { } from "core/autocomplete/lineStream"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters"; import { getTemplateForModel } from "core/autocomplete/templates"; +import { ConfigHandler } from "core/config/handler"; import { streamLines } from "core/diff/util"; import OpenAI from "core/llm/llms/OpenAI"; +import { logDevData } from "core/util/devdata"; import Handlebars from "handlebars"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import { ideProtocolClient } from "../activation/activate"; -import { TabAutocompleteModel, configHandler } from "../loadConfig"; +import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { AutocompletePromptBuilder } from "./autocompletePromptBuilder"; const statusBarItemText = (enabled: boolean | undefined) => enabled ? "$(check) Continue" : "$(circle-slash) Continue"; @@ -70,30 +71,6 @@ export function setupStatusBar( }); } -async function getDefinition( - uri: string, - line: number, - character: number -): Promise { - const definitions = (await vscode.commands.executeCommand( - "vscode.executeDefinitionProvider", - vscode.Uri.parse(uri), - new vscode.Position(line, character) - )) as any; - - if (definitions[0]?.targetRange) { - return { - filepath: uri, - content: await ideProtocolClient.readRangeInFile( - definitions[0].targetUri.fsPath, - definitions[0].targetRange - ), - }; - } - - return undefined; -} - export interface AutocompleteOutcome { accepted?: boolean; time: number; @@ -234,158 +211,6 @@ class GeneratorReuseManager { } } -async function getTabCompletion( - document: vscode.TextDocument, - pos: vscode.Position, - token: vscode.CancellationToken, - options: TabAutocompleteOptions -): Promise { - const startTime = Date.now(); - - // Filter - const lang = languageForFilepath(document.fileName); - const line = document.lineAt(pos).text; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) { - return undefined; - } - } - - try { - // Model - const llm = await TabAutocompleteModel.get(); - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } - if (!llm) return; - - // Prompt - const fullPrefix = document.getText( - new vscode.Range(new vscode.Position(0, 0), pos) - ); - const fullSuffix = document.getText( - new vscode.Range( - pos, - new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER) - ) - ); - const lineBelowCursor = document.lineAt( - Math.min(pos.line + 1, document.lineCount - 1) - ).text; - const clipboardText = await vscode.env.clipboard.readText(); - const { prefix, suffix, completeMultiline } = - await constructAutocompletePrompt( - document.uri.toString(), - fullPrefix, - fullSuffix, - clipboardText, - lang, - getDefinition, - options - ); - - const { template, completionOptions } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - const compiledTemplate = Handlebars.compile(template); - const prompt = compiledTemplate({ prefix, suffix }); - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = await cache.get(prompt); - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - setupStatusBar(true, true); - - // Try to reuse pending requests if what the user typed matches start of completion - let stop = [ - ...(completionOptions?.stop || []), - "\n\n", - "```", - ...lang.stopWords, - ]; - if (options.disableMultiLineCompletions || !completeMultiline) { - stop.unshift("\n"); - } - let generator = GeneratorReuseManager.getGenerator(prefix, () => - llm.streamComplete(prompt, { - ...completionOptions, - temperature: 0, - raw: true, - stop, - }) - ); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.isCancellationRequested) { - stopStatusBarLoading(); - cancelled = true; - return undefined; - } - yield update; - } - }; - const gen2 = onlyWhitespaceAfterEndOfLine( - generatorWithCancellation(), - lang.endOfLine - ); - const lineGenerator = streamWithNewLines(streamLines(gen2)); - const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor); - for await (const update of finalGenerator) { - completion += update; - } - - if (cancelled) { - return undefined; - } - - // Don't return empty - if (completion.trim().length <= 0) { - return undefined; - } - - // Post-processing - completion = completion.trimEnd(); - } - - const time = Date.now() - startTime; - return { - time, - completion, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - }; - } catch (e: any) { - console.warn("Error generating autocompletion: ", e); - if (!ContinueCompletionProvider.errorsShown.has(e.message)) { - ContinueCompletionProvider.errorsShown.add(e.message); - vscode.window.showErrorMessage(e.message, "Documentation").then((val) => { - if (val === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) - ); - } - }); - } - return undefined; - } -} - export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { @@ -395,6 +220,174 @@ export class ContinueCompletionProvider public static errorsShown: Set = new Set(); + private readonly promptBuilder: AutocompletePromptBuilder; + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly tabAutocompleteModel: TabAutocompleteModel + ) { + this.promptBuilder = new AutocompletePromptBuilder(ide); + } + + async getTabCompletion( + document: vscode.TextDocument, + pos: vscode.Position, + token: vscode.CancellationToken, + options: TabAutocompleteOptions + ): Promise { + const startTime = Date.now(); + + // Filter + const lang = languageForFilepath(document.fileName); + const line = document.lineAt(pos).text; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) { + return undefined; + } + } + + try { + // Model + const llm = await this.tabAutocompleteModel.get(); + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } + if (!llm) return; + + // Prompt + const fullPrefix = document.getText( + new vscode.Range(new vscode.Position(0, 0), pos) + ); + const fullSuffix = document.getText( + new vscode.Range( + pos, + new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER) + ) + ); + const lineBelowCursor = document.lineAt( + Math.min(pos.line + 1, document.lineCount - 1) + ).text; + const clipboardText = await vscode.env.clipboard.readText(); + const { prefix, suffix, completeMultiline } = + await constructAutocompletePrompt( + document.uri.toString(), + fullPrefix, + fullSuffix, + clipboardText, + lang, + this.promptBuilder.getDefinition.bind(this.promptBuilder), + options, + llm.model + ); + + const { template, completionOptions } = options.template + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); + + const compiledTemplate = Handlebars.compile(template); + const prompt = compiledTemplate({ prefix, suffix }); + + // Completion + let completion = ""; + + const cache = await autocompleteCache; + const cachedCompletion = await cache.get(prompt); + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + setupStatusBar(true, true); + + // Try to reuse pending requests if what the user typed matches start of completion + let stop = [ + ...(completionOptions?.stop || []), + "\n\n", + "```", + ...lang.stopWords, + ]; + if (options.disableMultiLineCompletions || !completeMultiline) { + stop.unshift("\n"); + } + let generator = GeneratorReuseManager.getGenerator(prefix, () => + llm.streamComplete(prompt, { + ...completionOptions, + temperature: 0, + raw: true, + stop, + }) + ); + + // LLM + let cancelled = false; + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.isCancellationRequested) { + stopStatusBarLoading(); + cancelled = true; + return undefined; + } + yield update; + } + }; + const gen2 = onlyWhitespaceAfterEndOfLine( + generatorWithCancellation(), + lang.endOfLine + ); + const lineGenerator = streamWithNewLines(streamLines(gen2)); + const finalGenerator = stopAtSimilarLine( + lineGenerator, + lineBelowCursor + ); + for await (const update of finalGenerator) { + completion += update; + } + + if (cancelled) { + return undefined; + } + + // Don't return empty + if (completion.trim().length <= 0) { + return undefined; + } + + // Post-processing + completion = completion.trimEnd(); + } + + const time = Date.now() - startTime; + return { + time, + completion, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + }; + } catch (e: any) { + console.warn("Error generating autocompletion: ", e); + if (!ContinueCompletionProvider.errorsShown.has(e.message)) { + ContinueCompletionProvider.errorsShown.add(e.message); + vscode.window + .showErrorMessage(e.message, "Documentation") + .then((val) => { + if (val === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) + ); + } + }); + } + return undefined; + } + } + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -406,7 +399,7 @@ export class ContinueCompletionProvider const uuid = uuidv4(); ContinueCompletionProvider.lastUUID = uuid; - const config = await configHandler.loadConfig(); + const config = await this.configHandler.loadConfig(); const options = { ...config.tabAutocompleteOptions, ...DEFAULT_AUTOCOMPLETE_OPTS, @@ -438,7 +431,7 @@ export class ContinueCompletionProvider } try { - const outcome = await getTabCompletion( + const outcome = await this.getTabCompletion( document, position, token, @@ -460,7 +453,7 @@ export class ContinueCompletionProvider const logRejectionTimeout = setTimeout(() => { // Wait 10 seconds, then assume it wasn't accepted outcome.accepted = false; - ideProtocolClient.logDevData("autocomplete", outcome); + logDevData("autocomplete", outcome); }, 10_000); return [ diff --git a/extensions/vscode/src/loadConfig.ts b/extensions/vscode/src/loadConfig.ts deleted file mode 100644 index 6e5778d43..000000000 --- a/extensions/vscode/src/loadConfig.ts +++ /dev/null @@ -1,323 +0,0 @@ -import { ContinueConfig, ContinueRcJson, ILLM } from "core"; -import defaultConfig from "core/config/default"; -import { - finalToBrowserConfig, - intermediateToFinalConfig, - loadFullConfigNode, - serializedToIntermediateConfig, -} from "core/config/load"; -import Ollama from "core/llm/llms/Ollama"; -import { getConfigJsonPath } from "core/util/paths"; -import { Telemetry } from "core/util/posthog"; -import { http, https } from "follow-redirects"; -import * as fs from "fs"; -import { HttpProxyAgent } from "http-proxy-agent"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch from "node-fetch"; -import * as vscode from "vscode"; -import { ideProtocolClient } from "./activation/activate"; -import { debugPanelWebview, webviewRequest } from "./debugPanel"; -import { getUniqueId } from "./util/vscode"; -const tls = require("tls"); - -const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion" -); - -class VsCodeConfigHandler { - savedConfig: ContinueConfig | undefined; - - reloadConfig() { - this.savedConfig = undefined; - this.loadConfig(); - } - - private async _getWorkspaceConfigs() { - const workspaceDirs = - vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || []; - const configs: ContinueRcJson[] = []; - for (const workspaceDir of workspaceDirs) { - const files = await vscode.workspace.fs.readDirectory(workspaceDir); - for (const [filename, type] of files) { - if (type === vscode.FileType.File && filename === ".continuerc.json") { - const contents = await ideProtocolClient.readFile( - vscode.Uri.joinPath(workspaceDir, filename).fsPath - ); - configs.push(JSON.parse(contents)); - } - } - } - return configs; - } - - async loadConfig(): Promise { - try { - if (this.savedConfig) { - return this.savedConfig; - } - let workspaceConfigs: ContinueRcJson[] = []; - try { - workspaceConfigs = await this._getWorkspaceConfigs(); - } catch (e) { - console.warn("Failed to load workspace configs"); - } - - const remoteConfigServerUrl = vscode.workspace - .getConfiguration("continue") - .get("remoteConfigServerUrl", undefined); - - this.savedConfig = await loadFullConfigNode( - ideProtocolClient.readFile, - workspaceConfigs, - remoteConfigServerUrl ? new URL(remoteConfigServerUrl) : undefined - ); - this.savedConfig.allowAnonymousTelemetry = - this.savedConfig.allowAnonymousTelemetry && - vscode.workspace.getConfiguration("continue").get("telemetryEnabled"); - - // Update the sidebar panel - const browserConfig = finalToBrowserConfig(this.savedConfig); - debugPanelWebview?.postMessage({ type: "configUpdate", browserConfig }); - - // Setup telemetry only after (and if) we know it is enabled - await Telemetry.setup( - this.savedConfig.allowAnonymousTelemetry ?? true, - getUniqueId() - ); - - return this.savedConfig; - } catch (e) { - vscode.window - .showErrorMessage( - "Error loading config.json. Please check your config.json file: " + e, - "Open config.json" - ) - .then((selection) => { - if (selection === "Open config.json") { - vscode.workspace - .openTextDocument(getConfigJsonPath()) - .then((doc) => { - vscode.window.showTextDocument(doc); - }); - } - }); - return intermediateToFinalConfig( - serializedToIntermediateConfig(defaultConfig), - ideProtocolClient.readFile - ); - } - } -} - -export const configHandler = new VsCodeConfigHandler(); - -const TIMEOUT = 7200; // 7200 seconds = 2 hours - -function setupLlm(llm: ILLM): ILLM { - // Since we know this is happening in Node.js, we can add requestOptions through a custom agent - const ca = [...tls.rootCertificates]; - const customCerts = - typeof llm.requestOptions?.caBundlePath === "string" - ? [llm.requestOptions?.caBundlePath] - : llm.requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) - ); - } - - let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms - - const agentOptions = { - ca, - rejectUnauthorized: llm.requestOptions?.verifySsl, - timeout, - sessionTimeout: timeout, - keepAlive: true, - keepAliveMsecs: timeout, - }; - - const proxy = llm.requestOptions?.proxy; - - llm._fetch = async (input, init) => { - // Create agent - const protocol = new URL(input).protocol === "https:" ? https : http; - const agent = proxy - ? new URL(input).protocol === "https:" - ? new HttpsProxyAgent(proxy, agentOptions) - : new HttpProxyAgent(proxy, agentOptions) - : new protocol.Agent(agentOptions); - - const headers: { [key: string]: string } = - llm!.requestOptions?.headers || {}; - for (const [key, value] of Object.entries(init?.headers || {})) { - headers[key] = value as string; - } - - let updatedBody: string | undefined = undefined; - try { - if ( - llm.requestOptions?.extraBodyProperties && - typeof init.body === "string" - ) { - const parsedBody = JSON.parse(init.body); - updatedBody = JSON.stringify({ - ...parsedBody, - ...llm.requestOptions.extraBodyProperties, - }); - } - } catch (e) { - console.log("Unable to parse HTTP request body: ", e); - } - - const resp = await fetch(input, { - ...init, - body: updatedBody ?? init.body, - headers, - agent, - }); - - if (!resp.ok) { - let text = await resp.text(); - if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); - text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; - } else if (text.includes("/api/chat")) { - text = - "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; - } else { - text = - "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; - } - } - throw new Error( - `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}` - ); - } - - return resp; - }; - - llm.writeLog = async (log: string) => { - outputChannel.appendLine( - "==========================================================================" - ); - outputChannel.appendLine( - "==========================================================================" - ); - - outputChannel.append(log); - }; - return llm; -} - -export async function llmFromTitle(title?: string): Promise { - let config = await configHandler.loadConfig(); - - if (title === undefined) { - const resp = await webviewRequest("getDefaultModelTitle"); - if (resp?.defaultModelTitle) { - title = resp.defaultModelTitle; - } - } - - let llm = title - ? config.models.find((llm) => llm.title === title) - : config.models[0]; - if (!llm) { - // Try to reload config - configHandler.reloadConfig(); - config = await configHandler.loadConfig(); - llm = config.models.find((llm) => llm.title === title); - if (!llm) { - throw new Error(`Unknown model ${title}`); - } - } - - return setupLlm(llm); -} - -export class TabAutocompleteModel { - private static _llm: ILLM | undefined; - private static defaultTag: string = "deepseek-coder:1.3b-base"; - - private static shownOllamaWarning: boolean = false; - private static shownDeepseekWarning: boolean = false; - - static clearLlm() { - TabAutocompleteModel._llm = undefined; - } - - static async getDefaultTabAutocompleteModel() { - const llm = new Ollama({ - model: TabAutocompleteModel.defaultTag, - }); - - // Check that deepseek is already downloaded - try { - const models = await llm.listModels(); - if (!models.includes(TabAutocompleteModel.defaultTag)) { - // Raise warning and explain how to download - if (!TabAutocompleteModel.shownDeepseekWarning) { - vscode.window - .showWarningMessage( - `Your local Ollama instance doesn't yet have DeepSeek Coder. To download this model, run \`ollama run deepseek-coder:1.3b-base\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`, - "Documentation", - "Copy Command" - ) - .then((value) => { - if (value === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) - ); - } else if (value === "Copy Command") { - vscode.env.clipboard.writeText( - "ollama run deepseek-coder:1.3b-base" - ); - } - }); - TabAutocompleteModel.shownDeepseekWarning = true; - } - return undefined; - } - } catch (e) { - if (!TabAutocompleteModel.shownOllamaWarning) { - vscode.window - .showWarningMessage( - "Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs", - "Documentation" - ) - .then((value) => { - if (value === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) - ); - } - }); - TabAutocompleteModel.shownOllamaWarning = true; - } - return undefined; - } - - return llm; - } - - static async get() { - if (!TabAutocompleteModel._llm) { - const config = await configHandler.loadConfig(); - if (config.tabAutocompleteModel) { - TabAutocompleteModel._llm = setupLlm(config.tabAutocompleteModel); - } else { - TabAutocompleteModel._llm = - await TabAutocompleteModel.getDefaultTabAutocompleteModel(); - } - } - - return TabAutocompleteModel._llm; - } -} diff --git a/extensions/vscode/src/suggestions.ts b/extensions/vscode/src/suggestions.ts index b5be341dd..e13cb42b4 100644 --- a/extensions/vscode/src/suggestions.ts +++ b/extensions/vscode/src/suggestions.ts @@ -1,8 +1,5 @@ import * as vscode from "vscode"; -import { openEditorAndRevealRange } from "./util/vscode"; -import { translate } from "./util/vscode"; -import { registerAllCodeLensProviders } from "./lang-server/codeLens"; -import { extensionContext, ideProtocolClient } from "./activation/activate"; +import { openEditorAndRevealRange, translate } from "./util/vscode"; export interface SuggestionRanges { oldRange: vscode.Range; @@ -125,9 +122,9 @@ export function rerenderDecorations(editorUri: string) { vscode.TextEditorRevealType.Default ); - if (extensionContext) { - registerAllCodeLensProviders(extensionContext); - } + // if (extensionContext) { + // registerAllCodeLensProviders(extensionContext); + // } } export function suggestionDownCommand() { diff --git a/extensions/vscode/src/continueIdeClient.ts b/extensions/vscode/src/util/ideUtils.ts similarity index 74% rename from extensions/vscode/src/continueIdeClient.ts rename to extensions/vscode/src/util/ideUtils.ts index fb1ed2f00..49b04a44c 100644 --- a/extensions/vscode/src/continueIdeClient.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -1,104 +1,24 @@ import { FileEdit, RangeInFile } from "core"; -import { getDevDataFilePath } from "core/util/paths"; -import { writeFileSync } from "fs"; -import * as path from "path"; +import path from "path"; import * as vscode from "vscode"; -import { extensionContext } from "./activation/activate"; -import { debugPanelWebview, getSidebarContent } from "./debugPanel"; -import { diffManager } from "./diff/horizontal"; -import { TabAutocompleteModel, configHandler } from "./loadConfig"; +import { VsCodeExtension } from "../extension/vscodeExtension"; import { SuggestionRanges, acceptSuggestionCommand, editorSuggestionsLocked, rejectSuggestionCommand, showSuggestion as showSuggestionInEditor, -} from "./suggestions"; -import { vsCodeIndexCodebase } from "./util/indexCodebase"; -import { defaultIgnoreFile, traverseDirectory } from "./util/traverseDirectory"; +} from "../suggestions"; +import { defaultIgnoreFile, traverseDirectory } from "./traverseDirectory"; import { getUniqueId, openEditorAndRevealRange, uriFromFilePath, -} from "./util/vscode"; +} from "./vscode"; const util = require("util"); -const exec = util.promisify(require("child_process").exec); - -const continueVirtualDocumentScheme = "continue"; - -class IdeProtocolClient { - private static PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = - {}; - - constructor(context: vscode.ExtensionContext) { - // Listen for file saving - vscode.workspace.onDidSaveTextDocument((event) => { - const filepath = event.uri.fsPath; - - if ( - filepath.endsWith(".continue/config.json") || - filepath.endsWith(".continue\\config.json") || - filepath.endsWith(".continue/config.ts") || - filepath.endsWith(".continue\\config.ts") || - filepath.endsWith(".continuerc.json") - ) { - configHandler.reloadConfig(); - TabAutocompleteModel.clearLlm(); - } else if ( - filepath.endsWith(".continueignore") || - filepath.endsWith(".gitignore") - ) { - debugPanelWebview?.postMessage({ - type: "updateEmbeddings", - }); - } - }); - - // Refresh index when branch is changed - this.getWorkspaceDirectories().forEach(async (dir) => { - const repo = await this.getRepo(vscode.Uri.file(dir)); - if (repo) { - repo.state.onDidChange(() => { - // args passed to this callback are always undefined, so keep track of previous branch - const currentBranch = repo?.state?.HEAD?.name; - if (currentBranch) { - if (IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) { - if ( - currentBranch !== - IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] - ) { - // Trigger refresh of index only in this directory - vsCodeIndexCodebase([dir]); - } - } - - IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = - currentBranch; - } - }); - } - }); - - // Register a content provider for the readonly virtual documents - const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider - { - // emitter and its event - onDidChangeEmitter = new vscode.EventEmitter(); - onDidChange = this.onDidChangeEmitter.event; - - provideTextDocumentContent(uri: vscode.Uri): string { - return uri.query; - } - })(); - context.subscriptions.push( - vscode.workspace.registerTextDocumentContentProvider( - continueVirtualDocumentScheme, - documentContentProvider - ) - ); - } +const asyncExec = util.promisify(require("child_process").exec); +export class VsCodeIdeUtils { visibleMessages: Set = new Set(); async gotoDefinition( @@ -207,10 +127,6 @@ class IdeProtocolClient { ); } - async showDiff(filepath: string, replacement: string, step_index: number) { - await diffManager.writeDiff(filepath, replacement, step_index); - } - showMultiFileEdit(edits: FileEdit[]) { vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); const panel = vscode.window.createWebviewPanel( @@ -218,12 +134,13 @@ class IdeProtocolClient { "Continue", vscode.ViewColumn.One ); - panel.webview.html = getSidebarContent( - extensionContext, - panel, - "/monaco", - edits - ); + // panel.webview.html = this.sidebar.getSidebarContent( + // extensionContext, + // panel, + // this.ide, + // "/monaco", + // edits + // ); } openFile(filepath: string, range?: vscode.Range) { @@ -244,9 +161,9 @@ class IdeProtocolClient { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${continueVirtualDocumentScheme}:${encodeURIComponent( - name - )}?${encodeURIComponent(contents)}` + `${ + VsCodeExtension.continueVirtualDocumentScheme + }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}` ) ) .then((doc) => { @@ -480,7 +397,7 @@ class IdeProtocolClient { let repo = await this.getRepo(forDirectory); if (repo?.state?.HEAD?.name === undefined) { try { - const { stdout } = await exec("git rev-parse --abbrev-ref HEAD", { + const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", { cwd: forDirectory.fsPath, }); return stdout?.trim() || "NONE"; @@ -533,30 +450,4 @@ class IdeProtocolClient { }); return rangeInFiles; } - - async runCommand(command: string) { - if (vscode.window.terminals.length) { - vscode.window.terminals[0].show(); - vscode.window.terminals[0].sendText(command, false); - } else { - const terminal = vscode.window.createTerminal(); - terminal.show(); - terminal.sendText(command, false); - } - } - - sendMainUserInput(input: string) { - debugPanelWebview?.postMessage({ - type: "userInput", - input, - }); - } - - logDevData(tableName: string, data: any) { - const filepath: string = getDevDataFilePath(tableName); - const jsonLine = JSON.stringify(data); - writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); - } } - -export default IdeProtocolClient; diff --git a/extensions/vscode/src/util/indexCodebase.ts b/extensions/vscode/src/util/indexCodebase.ts deleted file mode 100644 index 50d541c1f..000000000 --- a/extensions/vscode/src/util/indexCodebase.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { FullTextSearchCodebaseIndex } from "core/indexing/FullTextSearch"; -import { LanceDbIndex } from "core/indexing/LanceDbIndex"; -import { ChunkCodebaseIndex } from "core/indexing/chunk/ChunkCodebaseIndex"; -import { getComputeDeleteAddRemove } from "core/indexing/refreshIndex"; -import { CodebaseIndex, IndexTag, LastModifiedMap } from "core/indexing/types"; -import * as vscode from "vscode"; -import { ideProtocolClient } from "../activation/activate"; -import { debugPanelWebview } from "../debugPanel"; -import { VsCodeIde } from "../ideProtocol"; -import { configHandler } from "../loadConfig"; - -const vscodeGetStats = async ( - directory: string | undefined -): Promise => { - const files = await new VsCodeIde().listWorkspaceContents(directory); - const pathToLastModified: { [path: string]: number } = {}; - await Promise.all( - files.map(async (file) => { - let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file)); - pathToLastModified[file] = stat.mtime; - }) - ); - - return pathToLastModified; -}; - -async function getIndexesToBuild(): Promise { - const ide = new VsCodeIde(); - const config = await configHandler.loadConfig(); - - const indexes = [ - new ChunkCodebaseIndex(ide.readFile), // Chunking must come first - new LanceDbIndex(config.embeddingsProvider, ide.readFile), - new FullTextSearchCodebaseIndex(), - ]; - - return indexes; -} - -export async function vsCodeIndexCodebase(workspaceDirs: string[]) { - const update = (progress: number, desc: string) => { - debugPanelWebview?.postMessage({ type: "indexProgress", progress, desc }); - }; - - const config = await configHandler.loadConfig(); - if (config.disableIndexing) { - return; - } - - const indexesToBuild = await getIndexesToBuild(); - - let completedDirs = 0; - - for (let directory of workspaceDirs) { - const stats = await vscodeGetStats(directory); - const branch = await ideProtocolClient.getBranch( - vscode.Uri.file(directory) - ); - let completedIndexes = 0; - - try { - for (let codebaseIndex of indexesToBuild) { - const tag: IndexTag = { - directory, - branch, - artifactId: codebaseIndex.artifactId, - }; - const [results, markComplete] = await getComputeDeleteAddRemove( - tag, - { ...stats }, - (filepath) => ideProtocolClient.readFile(filepath) - ); - - for await (let { progress, desc } of codebaseIndex.update( - tag, - results, - markComplete - )) { - update( - (completedDirs + - (completedIndexes + progress) / indexesToBuild.length) / - workspaceDirs.length, - desc - ); - } - completedIndexes++; - update( - (completedDirs + completedIndexes / indexesToBuild.length) / - workspaceDirs.length, - "Completed indexing " + codebaseIndex.artifactId - ); - } - } catch (e) { - console.warn("Error refreshing index: ", e); - } - - completedDirs++; - update(completedDirs / workspaceDirs.length, "Indexing Complete"); - } -} diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts new file mode 100644 index 000000000..a720cad51 --- /dev/null +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -0,0 +1,90 @@ +import { ILLM } from "core"; +import { ConfigHandler } from "core/config/handler"; +import Ollama from "core/llm/llms/Ollama"; +import * as vscode from "vscode"; + +export class TabAutocompleteModel { + private _llm: ILLM | undefined; + private defaultTag: string = "starcoder:3b"; + private defaultTagName: string = "Starcoder 3b"; + + private shownOllamaWarning: boolean = false; + private shownDeepseekWarning: boolean = false; + + private configHandler: ConfigHandler; + + constructor(configHandler: ConfigHandler) { + this.configHandler = configHandler; + } + + clearLlm() { + this._llm = undefined; + } + + async getDefaultTabAutocompleteModel() { + const llm = new Ollama({ + model: this.defaultTag, + }); + + try { + const models = await llm.listModels(); + if (!models.includes(this.defaultTag)) { + if (!this.shownDeepseekWarning) { + vscode.window + .showWarningMessage( + `Your local Ollama instance doesn't yet have ${this.defaultTagName}. To download this model, run \`ollama run ${this.defaultTag}\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`, + "Documentation", + "Copy Command" + ) + .then((value) => { + if (value === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) + ); + } else if (value === "Copy Command") { + vscode.env.clipboard.writeText(`ollama run ${this.defaultTag}`); + } + }); + this.shownDeepseekWarning = true; + } + return undefined; + } + } catch (e) { + if (!this.shownOllamaWarning) { + vscode.window + .showWarningMessage( + "Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs", + "Documentation" + ) + .then((value) => { + if (value === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) + ); + } + }); + this.shownOllamaWarning = true; + } + return undefined; + } + + return llm; + } + + async get() { + if (!this._llm) { + const config = await this.configHandler.loadConfig(); + if (config.tabAutocompleteModel) { + this._llm = this.configHandler.setupLlm(config.tabAutocompleteModel); + } else { + this._llm = await this.getDefaultTabAutocompleteModel(); + } + } + + return this._llm; + } +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts new file mode 100644 index 000000000..3476e5c0d --- /dev/null +++ b/extensions/vscode/src/webviewProtocol.ts @@ -0,0 +1,534 @@ +import { ContextItemId, IDE } from "core"; +import { ConfigHandler } from "core/config/handler"; +import { addModel, addOpenAIKey, deleteModel } from "core/config/util"; +import { indexDocs } from "core/indexing/docs"; +import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; +import { logDevData } from "core/util/devdata"; +import historyManager from "core/util/history"; +import { Message } from "core/util/messenger"; +import { getConfigJsonPath } from "core/util/paths"; +import { + ReverseWebviewProtocol, + WebviewProtocol, +} from "core/web/webviewProtocol"; +import { v4 as uuidv4 } from "uuid"; +import * as vscode from "vscode"; +import { showTutorial } from "./activation/activate"; +import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; + +export class VsCodeWebviewProtocol { + listeners = new Map any)[]>(); + abortedMessageIds: Set = new Set(); + + private send(messageType: string, data: any, messageId?: string): string { + const id = messageId || uuidv4(); + this.webview?.postMessage({ + messageType, + data, + messageId: id, + }); + return id; + } + + private on( + messageType: T, + handler: ( + message: Message + ) => Promise | WebviewProtocol[T][1] + ): void { + if (!this.listeners.has(messageType)) { + this.listeners.set(messageType, []); + } + this.listeners.get(messageType)?.push(handler); + } + + _webview?: vscode.Webview; + _webviewListener?: vscode.Disposable; + + get webview(): vscode.Webview | undefined { + return this._webview; + } + + set webview(webView: vscode.Webview) { + this._webview = webView; + this._webviewListener?.dispose(); + + this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => { + if (!msg.messageType || !msg.messageId) { + throw new Error("Invalid webview protocol msg: " + JSON.stringify(msg)); + } + + const respond = (message: any) => + this.send(msg.messageType, message, msg.messageId); + + const handlers = this.listeners.get(msg.messageType) || []; + for (const handler of handlers) { + try { + const response = await handler(msg); + if ( + response && + typeof response[Symbol.asyncIterator] === "function" + ) { + for await (const update of response) { + respond(update); + } + respond({ done: true }); + } else { + respond(response || {}); + } + } catch (e: any) { + console.error( + "Error handling webview message: " + + JSON.stringify({ msg }, null, 2) + ); + + let message = `Continue error: ${e.message}`; + if (e.cause) { + if (e.cause.name === "ConnectTimeoutError") { + message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`; + } else if (e.cause.code === "ECONNREFUSED") { + message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`; + } else { + message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`; + } + } + + vscode.window + .showErrorMessage(message, "Show Logs", "Troubleshooting") + .then((selection) => { + if (selection === "Show Logs") { + vscode.commands.executeCommand( + "workbench.action.toggleDevTools" + ); + } else if (selection === "Troubleshooting") { + vscode.env.openExternal( + vscode.Uri.parse("https://continue.dev/docs/troubleshooting") + ); + } + }); + } + } + }); + } + + constructor( + private readonly ide: IDE, + private readonly configHandler: ConfigHandler, + private readonly verticalDiffManager: VerticalPerLineDiffManager + ) { + this.on("abort", (msg) => { + this.abortedMessageIds.add(msg.messageId); + }); + this.on("showFile", (msg) => { + this.ide.openFile(msg.data.filepath); + }); + this.on("openConfigJson", (msg) => { + this.ide.openFile(getConfigJsonPath()); + }); + this.on("readRangeInFile", async (msg) => { + return await vscode.workspace + .openTextDocument(msg.data.filepath) + .then((document) => { + let start = new vscode.Position(0, 0); + let end = new vscode.Position(5, 0); + let range = new vscode.Range(start, end); + + let contents = document.getText(range); + return contents; + }); + }); + this.on("toggleDevTools", (msg) => { + vscode.commands.executeCommand("workbench.action.toggleDevTools"); + vscode.commands.executeCommand("continue.viewLogs"); + }); + this.on("reloadWindow", (msg) => { + vscode.commands.executeCommand("workbench.action.reloadWindow"); + }); + this.on("focusEditor", (msg) => { + vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup"); + }); + this.on("toggleFullScreen", (msg) => { + vscode.commands.executeCommand("continue.toggleFullScreen"); + }); + + // IDE + this.on("getDiff", async (msg) => { + return await ide.getDiff(); + }); + this.on("config/getBrowserSerialized", async (msg) => { + return await configHandler.getSerializedConfig(); + }); + this.on("getTerminalContents", async (msg) => { + return await ide.getTerminalContents(); + }); + this.on("listWorkspaceContents", async (msg) => { + return await ide.listWorkspaceContents(); + }); + this.on("getWorkspaceDirs", async (msg) => { + return await ide.getWorkspaceDirs(); + }); + this.on("listFolders", async (msg) => { + return await ide.listFolders(); + }); + this.on("writeFile", async (msg) => { + return await ide.writeFile(msg.data.path, msg.data.contents); + }); + this.on("showVirtualFile", async (msg) => { + return await ide.showVirtualFile(msg.data.name, msg.data.content); + }); + this.on("getContinueDir", async (msg) => { + return await ide.getContinueDir(); + }); + this.on("openFile", async (msg) => { + return await ide.openFile(msg.data.path); + }); + this.on("runCommand", async (msg) => { + await ide.runCommand(msg.data.command); + }); + this.on("getSearchResults", async (msg) => { + return await ide.getSearchResults(msg.data.query); + }); + this.on("subprocess", async (msg) => { + return await ide.subprocess(msg.data.command); + }); + // History + this.on("history/list", (msg) => { + return historyManager.list(); + }); + this.on("history/save", (msg) => { + historyManager.save(msg.data); + }); + this.on("history/delete", (msg) => { + historyManager.delete(msg.data.id); + }); + this.on("history/load", (msg) => { + return historyManager.load(msg.data.id); + }); + this.on("saveFile", async (msg) => { + return await ide.saveFile(msg.data.filepath); + }); + this.on("readFile", async (msg) => { + return await ide.readFile(msg.data.filepath); + }); + this.on("showDiff", async (msg) => { + return await ide.showDiff( + msg.data.filepath, + msg.data.newContents, + msg.data.stepIndex + ); + }); + + this.on("getProblems", async (msg) => { + return await ide.getProblems(msg.data.filepath); + }); + this.on("getBranch", async (msg) => { + const { dir } = msg.data; + return await ide.getBranch(dir); + }); + this.on("getOpenFiles", async (msg) => { + return await ide.getOpenFiles(); + }); + this.on("getPinnedFiles", async (msg) => { + return await ide.getPinnedFiles(); + }); + this.on("showLines", async (msg) => { + const { filepath, startLine, endLine } = msg.data; + return await ide.showLines(filepath, startLine, endLine); + }); + // Other + this.on("errorPopup", (msg) => { + vscode.window + .showErrorMessage(msg.data.message, "Show Logs") + .then((selection) => { + if (selection === "Show Logs") { + vscode.commands.executeCommand("workbench.action.toggleDevTools"); + } + }); + }); + this.on("devdata/log", (msg) => { + logDevData(msg.data.tableName, msg.data.data); + }); + this.on("config/addModel", (msg) => { + const model = msg.data.model; + const newConfigString = addModel(model); + this.configHandler.reloadConfig(); + this.ide.openFile(getConfigJsonPath()); + + // Find the range where it was added and highlight + let lines = newConfigString.split("\n"); + let startLine; + let endLine; + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + + if (!startLine) { + if (line.trim() === `"title": "${model.title}",`) { + startLine = i - 1; + } + } else { + if (line.startsWith(" }")) { + endLine = i; + break; + } + } + } + + if (startLine && endLine) { + this.ide.showLines( + getConfigJsonPath(), + startLine, + endLine + // "#fff1" + ); + } + vscode.window.showInformationMessage( + "🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration." + ); + }); + this.on("config/deleteModel", (msg) => { + deleteModel(msg.data.title); + this.configHandler.reloadConfig(); + }); + this.on("config/addOpenAiKey", async (msg) => { + addOpenAIKey(msg.data); + this.configHandler.reloadConfig(); + }); + + async function* llmStreamComplete( + protocol: VsCodeWebviewProtocol, + msg: Message + ) { + const model = await protocol.configHandler.llmFromTitle(msg.data.title); + const gen = model.streamComplete( + msg.data.prompt, + msg.data.completionOptions + ); + let next = await gen.next(); + while (!next.done) { + if (protocol.abortedMessageIds.has(msg.messageId)) { + protocol.abortedMessageIds.delete(msg.messageId); + next = await gen.return({ completion: "", prompt: "" }); + break; + } + yield { content: next.value }; + next = await gen.next(); + } + + return { done: true, content: next.value }; + } + this.on("llm/streamComplete", (msg) => llmStreamComplete(this, msg)); + + async function* llmStreamChat( + protocol: VsCodeWebviewProtocol, + msg: Message + ) { + const model = await protocol.configHandler.llmFromTitle(msg.data.title); + const gen = model.streamChat( + msg.data.messages, + msg.data.completionOptions + ); + let next = await gen.next(); + while (!next.done) { + if (protocol.abortedMessageIds.has(msg.messageId)) { + protocol.abortedMessageIds.delete(msg.messageId); + next = await gen.return({ completion: "", prompt: "" }); + break; + } + yield { content: next.value.content }; + next = await gen.next(); + } + + return { done: true, content: next.value }; + } + this.on("llm/streamChat", (msg) => llmStreamChat(this, msg)); + this.on("llm/complete", async (msg) => { + const model = await this.configHandler.llmFromTitle(msg.data.title); + const completion = await model.complete( + msg.data.prompt, + msg.data.completionOptions + ); + return completion; + }); + + async function* runNodeJsSlashCommand( + protocol: VsCodeWebviewProtocol, + msg: Message + ) { + const { + input, + history, + modelTitle, + slashCommandName, + contextItems, + params, + historyIndex, + selectedCode, + } = msg.data; + + const config = await protocol.configHandler.loadConfig(); + const llm = await protocol.configHandler.llmFromTitle(modelTitle); + const slashCommand = config.slashCommands?.find( + (sc) => sc.name === slashCommandName + ); + if (!slashCommand) { + throw new Error(`Unknown slash command ${slashCommandName}`); + } + + for await (const content of slashCommand.run({ + input, + history, + llm, + contextItems, + params, + ide, + addContextItem: (item) => { + protocol.request("addContextItem", { + item, + historyIndex, + }); + }, + selectedCode, + config, + })) { + if (content) { + yield { content }; + } + } + yield { done: true, content: "" }; + } + this.on("command/run", (msg) => runNodeJsSlashCommand(this, msg)); + + this.on("context/loadSubmenuItems", async (msg) => { + const { title } = msg.data; + const config = await this.configHandler.loadConfig(); + const provider = config.contextProviders?.find( + (p) => p.description.title === title + ); + if (!provider) { + vscode.window.showErrorMessage( + `Unknown provider ${title}. Existing providers: ${config.contextProviders + ?.map((p) => p.description.title) + .join(", ")}` + ); + return []; + } + + try { + const items = await provider.loadSubmenuItems({ ide }); + return items; + } catch (e) { + vscode.window.showErrorMessage( + `Error loading submenu items from ${title}: ${e}` + ); + return []; + } + }); + + this.on("context/getContextItems", async (msg) => { + const { name, query, fullInput, selectedCode } = msg.data; + const config = await this.configHandler.loadConfig(); + const llm = await this.configHandler.llmFromTitle(); + const provider = config.contextProviders?.find( + (p) => p.description.title === name + ); + if (!provider) { + vscode.window.showErrorMessage( + `Unknown provider ${name}. Existing providers: ${config.contextProviders + ?.map((p) => p.description.title) + .join(", ")}` + ); + return []; + } + + try { + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: uuidv4(), + }; + const items = await provider.getContextItems(query, { + llm, + embeddingsProvider: config.embeddingsProvider, + fullInput, + ide, + selectedCode, + }); + return items.map((item) => ({ ...item, id })); + } catch (e) { + vscode.window.showErrorMessage( + `Error getting context items from ${name}: ${e}` + ); + return []; + } + }); + this.on("context/addDocs", (msg) => { + const { url, title } = msg.data; + const embeddingsProvider = new TransformersJsEmbeddingsProvider(); + vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Indexing ${title}`, + cancellable: false, + }, + async (progress) => { + for await (const update of indexDocs( + title, + new URL(url), + embeddingsProvider + )) { + progress.report({ + increment: update.progress, + message: update.desc, + }); + } + + vscode.window.showInformationMessage( + `🎉 Successfully indexed ${title}` + ); + + this.request("refreshSubmenuItems", undefined); + } + ); + }); + this.on("applyToCurrentFile", (msg) => { + // Select the entire current file + const editor = vscode.window.activeTextEditor; + if (!editor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + const document = editor.document; + const start = new vscode.Position(0, 0); + const end = new vscode.Position( + document.lineCount - 1, + document.lineAt(document.lineCount - 1).text.length + ); + editor.selection = new vscode.Selection(start, end); + + this.verticalDiffManager.streamEdit( + `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.` + ); + }); + this.on("showTutorial", (msg) => { + showTutorial(); + }); + } + + public request( + messageType: T, + data: ReverseWebviewProtocol[T][0] + ): Promise { + const messageId = uuidv4(); + return new Promise((resolve) => { + if (!this.webview) { + resolve(undefined); + return; + } + + this.send(messageType, data, messageId); + const disposable = this.webview.onDidReceiveMessage((msg) => { + resolve(msg); + disposable?.dispose(); + }); + }); + } +} diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index d7fbcf227..f8cdbd088 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -2323,9 +2323,13 @@ core-util-is@1.0.2: adf-to-md "^1.1.0" axios "^1.6.7" cheerio "^1.0.0-rc.12" + commander "^12.0.0" dotenv "^16.3.1" fastest-levenshtein "^1.0.16" + follow-redirects "^1.15.5" handlebars "^4.7.8" + http-proxy-agent "^7.0.1" + https-proxy-agent "^7.0.3" js-tiktoken "^1.0.8" llm-code-highlighter "^0.0.13" node-fetch "^3.3.2" diff --git a/gui/package-lock.json b/gui/package-lock.json index 6d46c2ec7..32e9df2f2 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -79,9 +79,13 @@ "adf-to-md": "^1.1.0", "axios": "^1.6.7", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.13", "node-fetch": "^3.3.2", @@ -99,6 +103,7 @@ "web-tree-sitter": "^0.20.8" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", @@ -836,12 +841,12 @@ } }, "node_modules/@floating-ui/dom": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.1.tgz", - "integrity": "sha512-iA8qE43/H5iGozC3W0YSnVSW42Vh522yyM1gj+BqRwVsTNOyr231PsXDaV04yT39PsO0QL2QpbI/M0ZaLUQgRQ==", + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.3.tgz", + "integrity": "sha512-RnDthu3mzPlQ31Ss/BTwQ1zjzIhr3lk1gZB1OC56h/1vEtaXkESrOqL5fQVMfXpwGtRwX+YsZBdyHtJMQnkArw==", "dependencies": { - "@floating-ui/core": "^1.6.0", - "@floating-ui/utils": "^0.2.1" + "@floating-ui/core": "^1.0.0", + "@floating-ui/utils": "^0.2.0" } }, "node_modules/@floating-ui/utils": { @@ -904,9 +909,9 @@ } }, "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", - "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "engines": { "node": ">=6.0.0" } @@ -1113,13 +1118,13 @@ "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" }, "node_modules/@swc/core": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.4.0.tgz", - "integrity": "sha512-wc5DMI5BJftnK0Fyx9SNJKkA0+BZSJQx8430yutWmsILkHMBD3Yd9GhlMaxasab9RhgKqZp7Ht30hUYO5ZDvQg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.4.1.tgz", + "integrity": "sha512-3y+Y8js+e7BbM16iND+6Rcs3jdiL28q3iVtYsCviYSSpP2uUVKkp5sJnCY4pg8AaVvyN7CGQHO7gLEZQ5ByozQ==", "dev": true, "hasInstallScript": true, "dependencies": { - "@swc/counter": "^0.1.1", + "@swc/counter": "^0.1.2", "@swc/types": "^0.1.5" }, "engines": { @@ -1130,16 +1135,16 @@ "url": "https://opencollective.com/swc" }, "optionalDependencies": { - "@swc/core-darwin-arm64": "1.4.0", - "@swc/core-darwin-x64": "1.4.0", - "@swc/core-linux-arm-gnueabihf": "1.4.0", - "@swc/core-linux-arm64-gnu": "1.4.0", - "@swc/core-linux-arm64-musl": "1.4.0", - "@swc/core-linux-x64-gnu": "1.4.0", - "@swc/core-linux-x64-musl": "1.4.0", - "@swc/core-win32-arm64-msvc": "1.4.0", - "@swc/core-win32-ia32-msvc": "1.4.0", - "@swc/core-win32-x64-msvc": "1.4.0" + "@swc/core-darwin-arm64": "1.4.1", + "@swc/core-darwin-x64": "1.4.1", + "@swc/core-linux-arm-gnueabihf": "1.4.1", + "@swc/core-linux-arm64-gnu": "1.4.1", + "@swc/core-linux-arm64-musl": "1.4.1", + "@swc/core-linux-x64-gnu": "1.4.1", + "@swc/core-linux-x64-musl": "1.4.1", + "@swc/core-win32-arm64-msvc": "1.4.1", + "@swc/core-win32-ia32-msvc": "1.4.1", + "@swc/core-win32-x64-msvc": "1.4.1" }, "peerDependencies": { "@swc/helpers": "^0.5.0" @@ -1151,9 +1156,9 @@ } }, "node_modules/@swc/core-darwin-arm64": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.0.tgz", - "integrity": "sha512-UTJ/Vz+s7Pagef6HmufWt6Rs0aUu+EJF4Pzuwvr7JQQ5b1DZeAAUeUtkUTFx/PvCbM8Xfw4XdKBUZfrIKCfW8A==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.1.tgz", + "integrity": "sha512-ePyfx0348UbR4DOAW24TedeJbafnzha8liXFGuQ4bdXtEVXhLfPngprrxKrAddCuv42F9aTxydlF6+adD3FBhA==", "cpu": [ "arm64" ], @@ -1167,9 +1172,9 @@ } }, "node_modules/@swc/core-darwin-x64": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.4.0.tgz", - "integrity": "sha512-f8v58u2GsGak8EtZFN9guXqE0Ep10Suny6xriaW2d8FGqESPyNrnBzli3aqkSeQk5gGqu2zJ7WiiKp3XoUOidA==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.4.1.tgz", + "integrity": "sha512-eLf4JSe6VkCMdDowjM8XNC5rO+BrgfbluEzAVtKR8L2HacNYukieumN7EzpYCi0uF1BYwu1ku6tLyG2r0VcGxA==", "cpu": [ "x64" ], @@ -1183,9 +1188,9 @@ } }, "node_modules/@swc/core-linux-arm-gnueabihf": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.0.tgz", - "integrity": "sha512-q2KAkBzmPcTnRij/Y1fgHCKAGevUX/H4uUESrw1J5gmUg9Qip6onKV80lTumA1/aooGJ18LOsB31qdbwmZk9OA==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.1.tgz", + "integrity": "sha512-K8VtTLWMw+rkN/jDC9o/Q9SMmzdiHwYo2CfgkwVT29NsGccwmNhCQx6XoYiPKyKGIFKt4tdQnJHKUFzxUqQVtQ==", "cpu": [ "arm" ], @@ -1199,9 +1204,9 @@ } }, "node_modules/@swc/core-linux-arm64-gnu": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.0.tgz", - "integrity": "sha512-SknGu96W0mzHtLHWm+62fk5+Omp9fMPFO7AWyGFmz2tr8EgRRXtTSrBUnWhAbgcalnhen48GsvtMdxf1KNputg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.1.tgz", + "integrity": "sha512-0e8p4g0Bfkt8lkiWgcdiENH3RzkcqKtpRXIVNGOmVc0OBkvc2tpm2WTx/eoCnes2HpTT4CTtR3Zljj4knQ4Fvw==", "cpu": [ "arm64" ], @@ -1215,9 +1220,9 @@ } }, "node_modules/@swc/core-linux-arm64-musl": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.0.tgz", - "integrity": "sha512-/k3TDvpBRMDNskHooNN1KqwUhcwkfBlIYxRTnJvsfT2C7My4pffR+4KXmt0IKynlTTbCdlU/4jgX4801FSuliw==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.1.tgz", + "integrity": "sha512-b/vWGQo2n7lZVUnSQ7NBq3Qrj85GrAPPiRbpqaIGwOytiFSk8VULFihbEUwDe0rXgY4LDm8z8wkgADZcLnmdUA==", "cpu": [ "arm64" ], @@ -1231,9 +1236,9 @@ } }, "node_modules/@swc/core-linux-x64-gnu": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.0.tgz", - "integrity": "sha512-GYsTMvNt5+WTVlwwQzOOWsPMw6P/F41u5PGHWmfev8Nd4QJ1h3rWPySKk4mV42IJwH9MgQCVSl3ygwNqwl6kFg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.1.tgz", + "integrity": "sha512-AFMQlvkKEdNi1Vk2GFTxxJzbICttBsOQaXa98kFTeWTnFFIyiIj2w7Sk8XRTEJ/AjF8ia8JPKb1zddBWr9+bEQ==", "cpu": [ "x64" ], @@ -1247,9 +1252,9 @@ } }, "node_modules/@swc/core-linux-x64-musl": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.0.tgz", - "integrity": "sha512-jGVPdM/VwF7kK/uYRW5N6FwzKf/FnDjGIR3RPvQokjYJy7Auk+3Oj21C0Jev7sIT9RYnO/TrFEoEozKeD/z2Qw==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.1.tgz", + "integrity": "sha512-QX2MxIECX1gfvUVZY+jk528/oFkS9MAl76e3ZRvG2KC/aKlCQL0KSzcTSm13mOxkDKS30EaGRDRQWNukGpMeRg==", "cpu": [ "x64" ], @@ -1263,9 +1268,9 @@ } }, "node_modules/@swc/core-win32-arm64-msvc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.0.tgz", - "integrity": "sha512-biHYm1AronEKlt47O/H8sSOBM2BKXMmWT+ApvlxUw50m1RGNnVnE0bgY7tylFuuSiWyXsQPJbmUV708JqORXVg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.1.tgz", + "integrity": "sha512-OklkJYXXI/tntD2zaY8i3iZldpyDw5q+NAP3k9OlQ7wXXf37djRsHLV0NW4+ZNHBjE9xp2RsXJ0jlOJhfgGoFA==", "cpu": [ "arm64" ], @@ -1279,9 +1284,9 @@ } }, "node_modules/@swc/core-win32-ia32-msvc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.0.tgz", - "integrity": "sha512-TL5L2tFQb19kJwv6+elToGBj74QXCn9j+hZfwQatvZEJRA5rDK16eH6oAE751dGUArhnWlW3Vj65hViPvTuycw==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.1.tgz", + "integrity": "sha512-MBuc3/QfKX9FnLOU7iGN+6yHRTQaPQ9WskiC8s8JFiKQ+7I2p25tay2RplR9dIEEGgVAu6L7auv96LbNTh+FaA==", "cpu": [ "ia32" ], @@ -1295,9 +1300,9 @@ } }, "node_modules/@swc/core-win32-x64-msvc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.0.tgz", - "integrity": "sha512-e2xVezU7XZ2Stzn4i7TOQe2Kn84oYdG0M3A7XI7oTdcpsKCcKwgiMoroiAhqCv+iN20KNqhnWwJiUiTj/qN5AA==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.1.tgz", + "integrity": "sha512-lu4h4wFBb/bOK6N2MuZwg7TrEpwYXgpQf5R7ObNSXL65BwZ9BG8XRzD+dLJmALu8l5N08rP/TrpoKRoGT4WSxw==", "cpu": [ "x64" ], @@ -1805,9 +1810,9 @@ "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==" }, "node_modules/@types/node": { - "version": "20.11.16", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.16.tgz", - "integrity": "sha512-gKb0enTmRCzXSSUJDq6/sPcqrfCv2mkkG6Jt/clpn5eiCbKTY+SgZUxo+p8ZKMof5dCp9vHQUAB7wOUTod22wQ==", + "version": "20.11.17", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.17.tgz", + "integrity": "sha512-QmgQZGWu1Yw9TDyAP9ZzpFJKynYNeOvwMJmaxABfieQoVoiVOS6MN1WSpqpRcbeA5+RW82kraAVxCCJg+780Qw==", "dev": true, "dependencies": { "undici-types": "~5.26.4" @@ -2066,6 +2071,15 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, + "node_modules/bcp-47-match": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-1.0.3.tgz", + "integrity": "sha512-LggQ4YTdjWQSKELZF5JwchnBa1u0pIQSZf5lSdOHEdbVP55h0qICA/FUp3+W99q0xqxYa1ZQizTUH87gecII5w==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -2102,9 +2116,9 @@ } }, "node_modules/browserslist": { - "version": "4.22.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.3.tgz", - "integrity": "sha512-UAp55yfwNv0klWNapjs/ktHoguxuQNGnOzxYmfnXIS+8AsRDZkSDxg7R1AX3GKzn078SBI5dzwzj/Yx0Or0e3A==", + "version": "4.23.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", + "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", "funding": [ { "type": "opencollective", @@ -2120,8 +2134,8 @@ } ], "dependencies": { - "caniuse-lite": "^1.0.30001580", - "electron-to-chromium": "^1.4.648", + "caniuse-lite": "^1.0.30001587", + "electron-to-chromium": "^1.4.668", "node-releases": "^2.0.14", "update-browserslist-db": "^1.0.13" }, @@ -2150,9 +2164,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001585", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001585.tgz", - "integrity": "sha512-yr2BWR1yLXQ8fMpdS/4ZZXpseBgE7o4g41x3a6AJOqZuOi+iE/WdJYAuZ6Y95i4Ohd2Y+9MzIWRR+uGABH4s3Q==", + "version": "1.0.30001587", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001587.tgz", + "integrity": "sha512-HMFNotUmLXn71BQxg8cijvqxnIAofforZOwGsxyXJ0qugTdspUF4sPSJ2vhgprHCB996tIDzEq1ubumPDV8ULA==", "funding": [ { "type": "opencollective", @@ -2375,6 +2389,11 @@ "node": ">=4" } }, + "node_modules/css-selector-parser": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-1.4.1.tgz", + "integrity": "sha512-HYPSb7y/Z7BNDCOrakL4raGO2zltZkbeXyAd6Tg9obzix6QhzxCotdBl6VT0Dv4vZfJGVz3WL/xaEI9Ly3ul0g==" + }, "node_modules/css-to-react-native": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz", @@ -2478,6 +2497,18 @@ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", "dev": true }, + "node_modules/direction": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz", + "integrity": "sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==", + "bin": { + "direction": "cli.js" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/dlv": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", @@ -2516,9 +2547,9 @@ "dev": true }, "node_modules/electron-to-chromium": { - "version": "1.4.661", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.661.tgz", - "integrity": "sha512-AFg4wDHSOk5F+zA8aR+SVIOabu7m0e7BiJnigCvPXzIGy731XENw/lmNxTySpVFtkFEy+eyt4oHhh5FF3NjQNw==" + "version": "1.4.669", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.669.tgz", + "integrity": "sha512-E2SmpffFPrZhBSgf8ibqanRS2mpuk3FIRDzLDwt7WFpfgJMKDHJs0hmacyP0PS1cWsq0dVkwIIzlscNaterkPg==" }, "node_modules/emoji-regex": { "version": "9.2.2", @@ -2850,9 +2881,9 @@ } }, "node_modules/hasown": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", - "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz", + "integrity": "sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA==", "dev": true, "dependencies": { "function-bind": "^1.1.2" @@ -3066,6 +3097,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-has-property": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-1.0.4.tgz", + "integrity": "sha512-ghHup2voGfgFoHMGnaLHOjbYFACKrRh9KFttdCzMCbFoBMJXiNi2+XTrPP8+q6cDJM/RSqlCfVWrjp1H201rZg==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-is-element": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz", @@ -3087,6 +3127,129 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-select": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-4.0.2.tgz", + "integrity": "sha512-8EEG2//bN5rrzboPWD2HdS3ugLijNioS1pqOTIolXNf67xxShYw4SQEmVXd3imiBG+U2bC2nVTySr/iRAA7Cjg==", + "dependencies": { + "bcp-47-match": "^1.0.0", + "comma-separated-tokens": "^1.0.0", + "css-selector-parser": "^1.0.0", + "direction": "^1.0.0", + "hast-util-has-property": "^1.0.0", + "hast-util-is-element": "^1.0.0", + "hast-util-to-string": "^1.0.0", + "hast-util-whitespace": "^1.0.0", + "not": "^0.1.0", + "nth-check": "^2.0.0", + "property-information": "^5.0.0", + "space-separated-tokens": "^1.0.0", + "unist-util-visit": "^2.0.0", + "zwitch": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/@types/unist": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz", + "integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA==" + }, + "node_modules/hast-util-select/node_modules/comma-separated-tokens": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz", + "integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-select/node_modules/hast-util-is-element": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-1.1.0.tgz", + "integrity": "sha512-oUmNua0bFbdrD/ELDSSEadRVtWZOf3iF6Lbv81naqsIV99RnSCieTbWuWCY8BAeEfKJTKl0gRdokv+dELutHGQ==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/hast-util-whitespace": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-1.0.4.tgz", + "integrity": "sha512-I5GTdSfhYfAPNztx2xJRQpG8cuDSNt599/7YUn7Gx/WxNMsG+a835k97TDkFgk123cwjfwINaZknkKkphx/f2A==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/property-information": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz", + "integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==", + "dependencies": { + "xtend": "^4.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-select/node_modules/space-separated-tokens": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz", + "integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-select/node_modules/unist-util-is": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz", + "integrity": "sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/unist-util-visit": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-2.0.3.tgz", + "integrity": "sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q==", + "dependencies": { + "@types/unist": "^2.0.0", + "unist-util-is": "^4.0.0", + "unist-util-visit-parents": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/unist-util-visit-parents": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz", + "integrity": "sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg==", + "dependencies": { + "@types/unist": "^2.0.0", + "unist-util-is": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/zwitch": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-1.0.5.tgz", + "integrity": "sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/hast-util-to-jsx-runtime": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.0.tgz", @@ -3113,6 +3276,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-string": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-1.0.4.tgz", + "integrity": "sha512-eK0MxRX47AV2eZ+Lyr18DCpQgodvaS3fAQO2+b9Two9F5HEoRPhiUMNzoXArMJfZi2yieFzUBMRl3HNJ3Jus3w==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-to-text": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.0.tgz", @@ -3698,9 +3870,9 @@ } }, "node_modules/mdast-util-mdx-jsx": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.0.0.tgz", - "integrity": "sha512-XZuPPzQNBPAlaqsTTgRrcJnyFbSOBovSadFgbFu8SnuNgm+6Bdx1K+IWoitsmj6Lq6MNtI+ytOqwN70n//NaBA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.1.0.tgz", + "integrity": "sha512-A8AJHlR7/wPQ3+Jre1+1rq040fX9A4Q1jG8JxmSNp/PLPHg80A6475wxTp3KzHpApFH6yWxFotHrJQA3dXP6/w==", "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", @@ -4319,9 +4491,9 @@ "integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ==" }, "node_modules/monaco-editor": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.45.0.tgz", - "integrity": "sha512-mjv1G1ZzfEE3k9HZN0dQ2olMdwIfaeAAjFiwNprLfYNRSz7ctv9XuCT7gPtBGrMUeV1/iZzYKj17Khu1hxoHOA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.46.0.tgz", + "integrity": "sha512-ADwtLIIww+9FKybWscd7OCfm9odsFYHImBRI1v9AviGce55QY8raT+9ihH8jX/E/e6QVSGM+pKj4jSUSRmALNQ==", "peer": true }, "node_modules/ms": { @@ -4658,12 +4830,15 @@ } }, "node_modules/postcss-load-config/node_modules/lilconfig": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz", - "integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.0.tgz", + "integrity": "sha512-p3cz0JV5vw/XeouBU3Ldnp+ZkBjE+n8ydJ4mcwBrOiXXPqNlrzGBqWs9X4MWF7f+iKUBu794Y8Hh8yawiJbCjw==", "dev": true, "engines": { "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" } }, "node_modules/postcss-nested": { @@ -4704,18 +4879,18 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" }, "node_modules/posthog-js": { - "version": "1.105.4", - "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.105.4.tgz", - "integrity": "sha512-hazxQYi4nxSqktu0Hh1xCV+sJCpN8mp5E5Ei/cfEa2nsb13xQbzn81Lf3VIDA0xMU1mXxNRStntlY267eQVC/w==", + "version": "1.105.9", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.105.9.tgz", + "integrity": "sha512-i9DnfyXDktugF5E9x0ejihQ8Xdh1kdVnVh7GdL7+PvFtULGMoN/b4pDmWBCwmH+ciubmqTCImVuNrZYy8+eTbw==", "dependencies": { "fflate": "^0.4.8", "preact": "^10.19.3" } }, "node_modules/preact": { - "version": "10.19.3", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.19.3.tgz", - "integrity": "sha512-nHHTeFVBTHRGxJXKkKu5hT8C/YWBkPso4/Gad6xuj5dbptt9iF9NZr9pHbPhBrnT2klheu7mHTxTZ/LjwJiEiQ==", + "version": "10.19.4", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.19.4.tgz", + "integrity": "sha512-dwaX5jAh0Ga8uENBX1hSOujmKWgx9RtL80KaKUFLc6jb4vCEAc3EeZ0rnQO/FO4VgjfPMfoLFWnNG8bHuZ9VLw==", "funding": { "type": "opencollective", "url": "https://opencollective.com/preact" @@ -5471,11 +5646,11 @@ } }, "node_modules/react-tooltip": { - "version": "5.26.0", - "resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-5.26.0.tgz", - "integrity": "sha512-UBbwy3fo1KYDwRCOWwM6AEfQsk9shgVfNkXFqgwS33QHplzg7xao/7mX/6wd+lE6KSZzhUNTkB5TNk9SMaBV/A==", + "version": "5.26.2", + "resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-5.26.2.tgz", + "integrity": "sha512-C1qHiqWYn6l5c98kL/NKFyJSw5G11vUVJkgOPcKgn306c5iL5317LxMNn5Qg1GSSM7Qvtsd6KA5MvwfgxFF7Dg==", "dependencies": { - "@floating-ui/dom": "^1.0.0", + "@floating-ui/dom": "^1.6.1", "classnames": "^2.3.0" }, "peerDependencies": { @@ -5738,123 +5913,6 @@ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz", "integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA==" }, - "node_modules/rehype-wrap-all/node_modules/bcp-47-match": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-1.0.3.tgz", - "integrity": "sha512-LggQ4YTdjWQSKELZF5JwchnBa1u0pIQSZf5lSdOHEdbVP55h0qICA/FUp3+W99q0xqxYa1ZQizTUH87gecII5w==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/comma-separated-tokens": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz", - "integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/css-selector-parser": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-1.4.1.tgz", - "integrity": "sha512-HYPSb7y/Z7BNDCOrakL4raGO2zltZkbeXyAd6Tg9obzix6QhzxCotdBl6VT0Dv4vZfJGVz3WL/xaEI9Ly3ul0g==" - }, - "node_modules/rehype-wrap-all/node_modules/direction": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz", - "integrity": "sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==", - "bin": { - "direction": "cli.js" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-has-property": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-1.0.4.tgz", - "integrity": "sha512-ghHup2voGfgFoHMGnaLHOjbYFACKrRh9KFttdCzMCbFoBMJXiNi2+XTrPP8+q6cDJM/RSqlCfVWrjp1H201rZg==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-is-element": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-1.1.0.tgz", - "integrity": "sha512-oUmNua0bFbdrD/ELDSSEadRVtWZOf3iF6Lbv81naqsIV99RnSCieTbWuWCY8BAeEfKJTKl0gRdokv+dELutHGQ==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-select": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-4.0.2.tgz", - "integrity": "sha512-8EEG2//bN5rrzboPWD2HdS3ugLijNioS1pqOTIolXNf67xxShYw4SQEmVXd3imiBG+U2bC2nVTySr/iRAA7Cjg==", - "dependencies": { - "bcp-47-match": "^1.0.0", - "comma-separated-tokens": "^1.0.0", - "css-selector-parser": "^1.0.0", - "direction": "^1.0.0", - "hast-util-has-property": "^1.0.0", - "hast-util-is-element": "^1.0.0", - "hast-util-to-string": "^1.0.0", - "hast-util-whitespace": "^1.0.0", - "not": "^0.1.0", - "nth-check": "^2.0.0", - "property-information": "^5.0.0", - "space-separated-tokens": "^1.0.0", - "unist-util-visit": "^2.0.0", - "zwitch": "^1.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-to-string": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-1.0.4.tgz", - "integrity": "sha512-eK0MxRX47AV2eZ+Lyr18DCpQgodvaS3fAQO2+b9Two9F5HEoRPhiUMNzoXArMJfZi2yieFzUBMRl3HNJ3Jus3w==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-whitespace": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-1.0.4.tgz", - "integrity": "sha512-I5GTdSfhYfAPNztx2xJRQpG8cuDSNt599/7YUn7Gx/WxNMsG+a835k97TDkFgk123cwjfwINaZknkKkphx/f2A==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/property-information": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz", - "integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==", - "dependencies": { - "xtend": "^4.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/space-separated-tokens": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz", - "integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/rehype-wrap-all/node_modules/unist-util-is": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz", @@ -5891,15 +5949,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/rehype-wrap-all/node_modules/zwitch": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-1.0.5.tgz", - "integrity": "sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/remark-math": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz", diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index a8fb8de28..a8237e46d 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -2,7 +2,6 @@ import { Cog6ToothIcon, QuestionMarkCircleIcon, } from "@heroicons/react/24/outline"; -import { postToIde } from "core/ide/messaging"; import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; @@ -13,6 +12,7 @@ import { vscForeground, vscInputBackground, } from "."; +import { useWebviewListener } from "../hooks/useWebviewListener"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { setBottomMessage, @@ -21,6 +21,7 @@ import { } from "../redux/slices/uiStateSlice"; import { RootStore } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; +import { postToIde } from "../util/ide"; import HeaderButtonWithText from "./HeaderButtonWithText"; import TextDialog from "./dialogs"; import IndexingProgressBar from "./loaders/IndexingProgressBar"; @@ -146,30 +147,35 @@ const Layout = () => { }; }, [timeline]); - useEffect(() => { - const handler = (event: any) => { - if (event.data.type === "addModel") { - navigate("/models"); - } else if (event.data.type === "openSettings") { - // navigate("/settings"); - postToIde("openConfigJson", {}); - } else if (event.data.type === "viewHistory") { - // Toggle the history page / main page - if (location.pathname === "/history") { - navigate("/"); - } else { - navigate("/history"); - } - } else if (event.data.type === "indexProgress") { - setIndexingProgress(event.data.progress); - setIndexingTask(event.data.desc); + useWebviewListener( + "addModel", + async () => { + navigate("/models"); + }, + [navigate] + ); + + useWebviewListener("openSettings", async () => { + postToIde("openConfigJson", undefined); + }); + + useWebviewListener( + "viewHistory", + async () => { + // Toggle the history page / main page + if (location.pathname === "/history") { + navigate("/"); + } else { + navigate("/history"); } - }; - window.addEventListener("message", handler); - return () => { - window.removeEventListener("message", handler); - }; - }, [location, navigate]); + }, + [location, navigate] + ); + + useWebviewListener("indexProgress", async (data) => { + setIndexingProgress(data.progress); + setIndexingTask(data.desc); + }); const [indexingProgress, setIndexingProgress] = useState(1); const [indexingTask, setIndexingTask] = useState("Indexing Codebase"); @@ -259,7 +265,7 @@ const Layout = () => { { // navigate("/settings"); - postToIde("openConfigJson", {}); + postToIde("openConfigJson", undefined); }} text="Config" > diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 54a158078..5c70b19a6 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,4 +1,3 @@ -import { postToIde } from "core/ide/messaging"; import { usePostHog } from "posthog-js/react"; import React, { useContext, useLayoutEffect } from "react"; import { useDispatch } from "react-redux"; @@ -6,6 +5,7 @@ import styled from "styled-components"; import { Button, Input } from ".."; import { SubmenuContextProvidersContext } from "../../App"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { postToIde } from "../../util/ide"; const GridDiv = styled.div` display: grid; @@ -58,7 +58,7 @@ function AddDocsDialog() { disabled={!docsUrl || !urlValid} className="ml-auto" onClick={() => { - postToIde("addDocs", { url: docsUrl, title: docsTitle }); + postToIde("context/addDocs", { url: docsUrl, title: docsTitle }); setDocsTitle(""); setDocsUrl(""); dispatch(setShowDialog(false)); diff --git a/gui/src/components/dialogs/FTCDialog.tsx b/gui/src/components/dialogs/FTCDialog.tsx index e679dadca..8533905ea 100644 --- a/gui/src/components/dialogs/FTCDialog.tsx +++ b/gui/src/components/dialogs/FTCDialog.tsx @@ -5,7 +5,7 @@ import styled from "styled-components"; import { Button, Input } from ".."; import { setDefaultModel } from "../../redux/slices/stateSlice"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; -import { addOpenAIKey } from "../../util/ide"; +import { postToIde } from "../../util/ide"; const GridDiv = styled.div` display: grid; @@ -55,7 +55,7 @@ function FTCDialog() {