diff --git a/.changes/unreleased/Added-20241108-113942.yaml b/.changes/unreleased/Added-20241108-113942.yaml new file mode 100644 index 000000000..987643345 --- /dev/null +++ b/.changes/unreleased/Added-20241108-113942.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: OpenAI predicted outputs support +time: 2024-11-08T11:39:42.277047-08:00 diff --git a/.changes/unreleased/Added-20241108-114100.yaml b/.changes/unreleased/Added-20241108-114100.yaml new file mode 100644 index 000000000..af7cb5444 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114100.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improve codebase retrieval with BM25 +time: 2024-11-08T11:41:00.002716-08:00 diff --git a/.changes/unreleased/Added-20241108-114423.yaml b/.changes/unreleased/Added-20241108-114423.yaml new file mode 100644 index 000000000..fc3a6eaf7 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114423.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Grok from xAI +time: 2024-11-08T11:44:23.761084-08:00 diff --git a/.changes/unreleased/Added-20241108-114437.yaml b/.changes/unreleased/Added-20241108-114437.yaml new file mode 100644 index 000000000..fab18b954 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114437.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Chat enhancements including sticking input to bottom +time: 2024-11-08T11:44:37.408176-08:00 diff --git a/.changes/unreleased/Added-20241108-114450.yaml b/.changes/unreleased/Added-20241108-114450.yaml new file mode 100644 index 000000000..14644f3e9 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114450.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New UI for cmd+I in sidebar +time: 2024-11-08T11:44:50.682952-08:00 diff --git a/.changes/unreleased/Added-20241108-114612.yaml b/.changes/unreleased/Added-20241108-114612.yaml new file mode 100644 index 000000000..68d8b27d1 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114612.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Nebius LLM provider +time: 2024-11-08T11:46:12.94828-08:00 diff --git a/.changes/unreleased/Added-20241108-114622.yaml b/.changes/unreleased/Added-20241108-114622.yaml new file mode 100644 index 000000000..e91ddb398 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114622.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Ask Sage LLM provider +time: 2024-11-08T11:46:22.626907-08:00 diff --git a/.changes/unreleased/Added-20241108-114649.yaml b/.changes/unreleased/Added-20241108-114649.yaml new file mode 100644 index 000000000..0e7a0c9d0 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114649.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improved reference for config.json +time: 2024-11-08T11:46:49.648545-08:00 diff --git a/.changes/unreleased/Added-20241108-114753.yaml b/.changes/unreleased/Added-20241108-114753.yaml new file mode 100644 index 000000000..8cb7f1805 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114753.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New @web context provider +time: 2024-11-08T11:47:53.447346-08:00 diff --git a/.changes/unreleased/Added-20241108-114813.yaml b/.changes/unreleased/Added-20241108-114813.yaml new file mode 100644 index 000000000..cd5ba1067 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114813.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Updates for llama3.2 +time: 2024-11-08T11:48:13.830692-08:00 diff --git a/.changes/unreleased/Changed-20241108-114549.yaml b/.changes/unreleased/Changed-20241108-114549.yaml new file mode 100644 index 000000000..d340736b6 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114549.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Improved @docs crawler +time: 2024-11-08T11:45:49.381554-08:00 diff --git a/.changes/unreleased/Changed-20241108-114850.yaml b/.changes/unreleased/Changed-20241108-114850.yaml new file mode 100644 index 000000000..ab6c2a037 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114850.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Many improvements to make autocomplete more eager +time: 2024-11-08T11:48:50.486502-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114322.yaml b/.changes/unreleased/Fixed-20241108-114322.yaml new file mode 100644 index 000000000..e896eac4d --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114322.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: OSR-related fixes for non-Mac users +time: 2024-11-08T11:43:22.623155-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114707.yaml b/.changes/unreleased/Fixed-20241108-114707.yaml new file mode 100644 index 000000000..95c70c844 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114707.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: Fixes for inline edit in JetBrains +time: 2024-11-08T11:47:07.953304-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114905.yaml b/.changes/unreleased/Fixed-20241108-114905.yaml new file mode 100644 index 000000000..eb590eeb4 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114905.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Brought back the Apply button for all code blocks +time: 2024-11-08T11:49:05.021499-08:00 diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index f94c6ee05..472684a7e 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -4,9 +4,10 @@ import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; +import MultiFileEditSlashCommand from "./multifileEdit"; +import OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; -import OnboardSlashCommand from "./onboard"; export default [ DraftIssueCommand, @@ -18,4 +19,5 @@ export default [ CommitMessageCommand, ReviewMessageCommand, OnboardSlashCommand, + MultiFileEditSlashCommand, ]; diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts new file mode 100644 index 000000000..ffda6b703 --- /dev/null +++ b/core/commands/slash/multifileEdit.ts @@ -0,0 +1,108 @@ +import { SlashCommand } from "../.."; +import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util"; +import { VsCodeIde } from "../../../extensions/vscode/src/VsCodeIde"; +import { stripImages } from "../../llm/images"; + +const MultiFileEditSlashCommand: SlashCommand = { + name: "multifile-edit", + description: "Edit multiple files in the codebase at once", + run: async function* ({ llm, contextItems, selectedCode, input, ide }) { + const selectedCodeStr = ( + await Promise.all( + selectedCode.map(async (item) => { + // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` + const [filepath, rangeStr] = item.filepath.split(" "); + const fullPath = getFullyQualifiedPath(ide as VsCodeIde, filepath); + + if (!fullPath) { + return ""; + } + + const codeStr = await ide.readRangeInFile(fullPath, item.range); + + // Include the filepath so the model can map it correctly with codeblock outputs + return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``; + }), + ) + ).join("\n"); + + const fileContextItemsStr = contextItems + .filter((item) => item.uri?.type === "file") + .map((item) => item.content) + .join("\n"); + + const filesToEditStr = fileContextItemsStr + "\n" + selectedCodeStr; + + const additionalContextStr = contextItems + .filter((item) => item.uri?.type !== "file") + .map((item) => `${item.description}: ${item.content}`) + .join("\n"); + + const content = createPrompt(filesToEditStr, additionalContextStr, input); + + for await (const chunk of llm.streamChat([{ role: "user", content }])) { + yield stripImages(chunk.content); + } + }, +}; + +function createPrompt( + filesToEditStr: string, + additionalContextStr: string, + input: string, +): string { + return ` +You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: + +1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" +2. When providing instructions, if a user needs to interact with a CLI, walk them through each step +2. Perform file edits in a logical, sequential ordering +3. For each file edit, provide a brief explanation of the changes +4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. + a. When creating new files, also inlcude the filname in the language specifier of the code block. +6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits + +Remember to be concise and focus on the code changes and their impact. + +Here's an example of how your response should be structured: + + +I'll make the following changes to implement feature X: + +1. First, I'll modify file1.js to add a new function: +\`\`\`javascript /path/to/file1.js +// Entire content of file1.js or changes to be made +\`\`\` + +2. Next, let's create a new test file: +\`\`\`javascript /path/to/file1.test.js +# Entire content of file2.py or changes to be made +\`\`\` + +Summary: +- [Sequential overview of the most important 3-5 edits] + + +Now, let's make the changes based on the engineer's request: + + +${input} + + +Here are the files to base your edits on: + + +${filesToEditStr} + + +And here is any additional context the engineer has provided: + + +${additionalContextStr} + + +Please provide the multi-file edit details based on the engineer's request. + `; +} + +export default MultiFileEditSlashCommand; diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts deleted file mode 100644 index 9c52bd6b6..000000000 --- a/core/context/retrieval/fullTextSearch.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BranchAndDir, Chunk } from "../../index.js"; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js"; - -export async function retrieveFts( - query: string, - n: number, - tags: BranchAndDir[], - filterDirectory: string | undefined, -): Promise { - const ftsIndex = new FullTextSearchCodebaseIndex(); - - let ftsResults: Chunk[] = []; - try { - if (query.trim() !== "") { - ftsResults = await ftsIndex.retrieve( - tags, - query - .trim() - .split(" ") - .map((element) => `"${element}"`) - .join(" OR "), - n, - filterDirectory, - undefined, - ); - } - return ftsResults; - } catch (e) { - console.warn("Error retrieving from FTS:", e); - return []; - } -} diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 9495f1608..89323d9b2 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,14 +1,11 @@ -import { - BranchAndDir, - Chunk, - ContinueConfig, - IDE, - ILLM, -} from "../../../index.js"; -import { chunkDocument } from "../../../indexing/chunk/chunk.js"; -import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js"; -import { retrieveFts } from "../fullTextSearch.js"; -import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js"; +// @ts-ignore +import nlp from "wink-nlp-utils"; + +import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; +import { chunkDocument } from "../../../indexing/chunk/chunk"; +import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; +import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; export interface RetrievalPipelineOptions { llm: ILLM; @@ -23,11 +20,18 @@ export interface RetrievalPipelineOptions { includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model } +export interface RetrievalPipelineRunArguments { + query: string; + tags: BranchAndDir[]; + filterDirectory?: string; +} + export interface IRetrievalPipeline { - run(options: RetrievalPipelineOptions): Promise; + run(args: RetrievalPipelineRunArguments): Promise; } export default class BaseRetrievalPipeline implements IRetrievalPipeline { + private ftsIndex = new FullTextSearchCodebaseIndex(); private lanceDbIndex: LanceDbIndex; constructor(protected readonly options: RetrievalPipelineOptions) { @@ -38,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } + private getCleanedTrigrams( + query: RetrievalPipelineRunArguments["query"], + ): string[] { + let text = nlp.string.removeExtraSpaces(query); + text = nlp.string.stem(text); + + let tokens = nlp.string + .tokenize(text, true) + .filter((token: any) => token.tag === "word") + .map((token: any) => token.value); + + tokens = nlp.tokens.removeWords(tokens); + tokens = nlp.tokens.setOfWords(tokens); + + const cleanedTokens = [...tokens].join(" "); + const trigrams = nlp.string.ngram(cleanedTokens, 3); + + return trigrams; + } + + protected async retrieveFts( + args: RetrievalPipelineRunArguments, + n: number, + ): Promise { + try { + if (args.query.trim() === "") { + return []; + } + + const tokens = this.getCleanedTrigrams(args.query).join(" OR "); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); + } catch (e) { + console.warn("Error retrieving from FTS:", e); + return []; + } + } + protected async retrieveAndChunkRecentlyEditedFiles( n: number, ): Promise { @@ -75,15 +122,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return chunks.slice(0, n); } - protected async retrieveFts(input: string, n: number): Promise { - return retrieveFts( - input, - n, - this.options.tags, - this.options.filterDirectory, - ); - } - protected async retrieveEmbeddings( input: string, n: number, @@ -96,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } - run(): Promise { + run(args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } } diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 6caef72dd..052a1fce6 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -1,10 +1,13 @@ -import { Chunk } from "../../../index.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../../"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { - async run(): Promise { + async run(args: RetrievalPipelineRunArguments): Promise { const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, @@ -15,7 +18,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, ftsNFinal); + const ftsChunks = await this.retrieveFts(args, ftsNFinal); const embeddingsChunks = includeEmbeddings ? await this.retrieveEmbeddings(input, embeddingsNFinal) diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 375f1b17b..6f28a4a89 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -1,17 +1,22 @@ -import { Chunk } from "../../../index.js"; -import { RETRIEVAL_PARAMS } from "../../../util/parameters.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../.."; +import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { - private async _retrieveInitial(): Promise { + private async _retrieveInitial( + args: RetrievalPipelineRunArguments, + ): Promise { const { input, nRetrieve, filterDirectory, includeEmbeddings } = this.options; let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, nRetrieve); + const ftsChunks = await this.retrieveFts(args, nRetrieve); const embeddingsChunks = includeEmbeddings ? await this.retrieveEmbeddings(input, nRetrieve) : []; @@ -104,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { return results; } - async run(): Promise { - const intialResults = await this._retrieveInitial(); - const rankedResults = await this._rerank(this.options.input, intialResults); + async run(args: RetrievalPipelineRunArguments): Promise { + let results = await this._retrieveInitial(args); + results = await this._rerank(args.query, results); // // // Expand top reranked results // const expanded = await this._expandRankedResults(results); @@ -120,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // TODO: stitch together results - return rankedResults; + return results; } } diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index a40e163a0..8aae10a41 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -93,7 +93,11 @@ export async function retrieveContextItemsFromEmbeddings( }; const pipeline = new pipelineType(pipelineOptions); - const results = await pipeline.run(); + const results = await pipeline.run({ + tags, + filterDirectory, + query: extras.fullInput, + }); if (results.length === 0) { throw new Error( diff --git a/core/core.ts b/core/core.ts index d7bd1846f..fb794d29c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,3 +1,5 @@ +import ignore from "ignore"; +import path from "path"; import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import { CompletionProvider } from "./autocomplete/CompletionProvider"; @@ -17,6 +19,7 @@ import { ControlPlaneClient } from "./control-plane/client"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext"; @@ -398,6 +401,7 @@ export class Core { }); break; } + // @ts-ignore yield { content: next.value.content }; next = await gen.next(); } @@ -704,8 +708,13 @@ export class Core { return { url }; }); - on("didChangeActiveTextEditor", ({ data: { filepath } }) => { - recentlyEditedFilesCache.set(filepath, filepath); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { + const ignoreInstance = ignore().add(defaultIgnoreFile); + let rootDirectory = await this.ide.getWorkspaceDirs(); + const relativeFilePath = path.relative(rootDirectory[0], filepath); + if (!ignoreInstance.ignores(relativeFilePath)) { + recentlyEditedFilesCache.set(filepath, filepath); + } }); } diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index f49f3f911..ca47f010d 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -8,7 +8,7 @@ import { } from "../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; -import { ChatMessage, DiffLine, ILLM } from "../index.js"; +import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; import { Telemetry } from "../util/posthog.js"; @@ -89,10 +89,17 @@ export async function* streamDiffLines( ); const inept = modelIsInept(llm.model); + const prediction: Prediction = { + type: "content", + content: highlighted, + }; + const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true }) - : llm.streamChat(prompt); + ? llm.streamComplete(prompt, { raw: true, prediction }) + : llm.streamChat(prompt, { + prediction, + }); let lines = streamLines(completion); diff --git a/core/index.d.ts b/core/index.d.ts index 8866142d8..4bd546214 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -780,6 +780,14 @@ export interface CustomCommand { description: string; } +interface Prediction { + type: "content" + content: string | { + type: "text" + text: string + }[] +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -794,6 +802,7 @@ interface BaseCompletionOptions { keepAlive?: number; raw?: boolean; stream?: boolean; + prediction?: Prediction; } export interface ModelCapability { @@ -825,6 +834,7 @@ export type EmbeddingsProviderName = | "ollama" | "openai" | "cohere" + | "lmstudio" | "free-trial" | "gemini" | "continue-proxy" diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 27face898..82e4e822f 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,6 +1,7 @@ import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; import { getBasename } from "../util/index"; import { RETRIEVAL_PARAMS } from "../util/parameters"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { @@ -10,10 +11,20 @@ import { type CodebaseIndex, } from "./types"; +export interface RetrieveConfig { + tags: BranchAndDir[]; + text: string; + n: number; + directory?: string; + filterPaths?: string[]; + bm25Threshold?: number; +} + export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; static artifactId = "sqliteFts"; artifactId: string = FullTextSearchCodebaseIndex.artifactId; + pathWeightMultiplier = 10.0; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( @@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { desc: `Indexing ${getBasename(item.path)}`, status: "indexing", }; - markComplete([item], IndexResultType.Compute); + await markComplete([item], IndexResultType.Compute); } // Add tag for (const item of results.addTag) { - markComplete([item], IndexResultType.AddTag); + await markComplete([item], IndexResultType.AddTag); } // Remove tag for (const item of results.removeTag) { - markComplete([item], IndexResultType.RemoveTag); + await markComplete([item], IndexResultType.RemoveTag); } // Delete @@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { await db.run("DELETE FROM fts WHERE path = ?", [item.path]); - markComplete([item], IndexResultType.Delete); + await markComplete([item], IndexResultType.Delete); } } - async retrieve( - tags: BranchAndDir[], - text: string, - n: number, - directory: string | undefined, - filterPaths: string[] | undefined, - bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold, - ): Promise { + async retrieve(config: RetrieveConfig): Promise { const db = await SqliteDb.get(); - // Notice that the "chunks" artifactId is used because of linking between tables - const tagStrings = tags.map((tag) => { - return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }); - }); + const query = this.buildRetrieveQuery(config); + const parameters = this.getRetrieveQueryParameters(config); - const query = `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank - FROM fts - JOIN fts_metadata ON fts.rowid = fts_metadata.id - JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId - WHERE fts MATCH '${text.replace( - /\?/g, - "", - )}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")}) - ${ - filterPaths - ? `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})` - : "" - } - ORDER BY rank - LIMIT ?`; + let results = await db.all(query, parameters); - let results = await db.all(query, [ - ...tagStrings, - ...(filterPaths || []), - Math.ceil(n), - ]); - - results = results.filter((result) => result.rank <= bm25Threshold); + results = results.filter( + (result) => + result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold), + ); const chunks = await db.all( `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`, results.map((result) => result.chunkId), ); - return chunks.map((chunk) => { - return { - filepath: chunk.path, - index: chunk.index, - startLine: chunk.startLine, - endLine: chunk.endLine, - content: chunk.content, - digest: chunk.cacheKey, - }; - }); + return chunks.map((chunk) => ({ + filepath: chunk.path, + index: chunk.index, + startLine: chunk.startLine, + endLine: chunk.endLine, + content: chunk.content, + digest: chunk.cacheKey, + })); + } + + private buildTagFilter(tags: BranchAndDir[]): string { + const tagStrings = this.convertTags(tags); + + return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`; + } + + private buildPathFilter(filterPaths: string[] | undefined): string { + if (!filterPaths || filterPaths.length === 0) { + return ""; + } + return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`; + } + + private buildRetrieveQuery(config: RetrieveConfig): string { + return ` + SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank + FROM fts + JOIN fts_metadata ON fts.rowid = fts_metadata.id + JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId + WHERE fts MATCH ? + ${this.buildTagFilter(config.tags)} + ${this.buildPathFilter(config.filterPaths)} + ORDER BY bm25(fts, ${this.pathWeightMultiplier}) + LIMIT ? + `; + } + + private getRetrieveQueryParameters(config: RetrieveConfig) { + const { text, tags, filterPaths, n } = config; + const tagStrings = this.convertTags(tags); + + return [ + text.replace(/\?/g, ""), + ...tagStrings, + ...(filterPaths || []), + Math.ceil(n), + ]; + } + + private convertTags(tags: BranchAndDir[]): string[] { + // Notice that the "chunks" artifactId is used because of linking between tables + return tags.map((tag) => + tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }), + ); } } diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts new file mode 100644 index 000000000..f5ec128d3 --- /dev/null +++ b/core/indexing/embeddings/LMStudio.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "lmstudio"; + + static defaultOptions: Partial | undefined = { + apiBase: "http://localhost:1234/v1", + model: "nomic-ai/nomic-embed-text-v1.5-GGUF", + }; +} + +export default LMStudioEmbeddingsProvider; \ No newline at end of file diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 7b62340e1..b0508d3fd 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -17,6 +17,7 @@ import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; +import LMStudioEmbeddingsProvider from "./LMStudio.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] @@ -42,5 +43,6 @@ export const allEmbeddingsProviders: Record< mistral: MistralEmbeddingsProvider, nebius: NebiusEmbeddingsProvider, vertexai: VertexEmbeddingsProvider, - watsonx: WatsonxEmbeddingsProvider + watsonx: WatsonxEmbeddingsProvider, + lmstudio: LMStudioEmbeddingsProvider }; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index b626a9698..168e0afff 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,7 +95,14 @@ class OpenAI extends BaseLLM { ); } - protected _convertArgs(options: any, messages: ChatMessage[]) { + private supportsPrediction(model: string): boolean { + return [ + "gpt-4o-mini", + "gpt-4o" + ].includes(model); + } + + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); const finalOptions: any = { messages: messages.map(this._convertMessage), @@ -135,6 +142,18 @@ class OpenAI extends BaseLLM { ); } + if (options.prediction && this.supportsPrediction(options.model)) { + if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + finalOptions.presence_penalty = undefined; + } + if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + finalOptions.frequency_penalty = undefined; + } + finalOptions.max_completion_tokens = undefined; + + finalOptions.prediction = options.prediction; + } + return finalOptions; } diff --git a/core/package-lock.json b/core/package-lock.json index 9e3937c64..f218b1904 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -64,6 +64,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" @@ -14850,6 +14851,69 @@ "node": ">=4" } }, + "node_modules/wink-distance": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz", + "integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==", + "dependencies": { + "wink-helpers": "^2.0.0", + "wink-jaro-distance": "^2.0.0" + } + }, + "node_modules/wink-eng-lite-web-model": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz", + "integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/wink-helpers": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz", + "integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg==" + }, + "node_modules/wink-jaro-distance": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz", + "integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA==" + }, + "node_modules/wink-nlp": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz", + "integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A==" + }, + "node_modules/wink-nlp-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz", + "integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==", + "dependencies": { + "wink-distance": "^2.0.1", + "wink-eng-lite-web-model": "^1.4.3", + "wink-helpers": "^2.0.0", + "wink-nlp": "^1.12.0", + "wink-porter2-stemmer": "^2.0.1", + "wink-tokenizer": "^5.2.3" + } + }, + "node_modules/wink-porter2-stemmer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz", + "integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ==" + }, + "node_modules/wink-tokenizer": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz", + "integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==", + "dependencies": { + "emoji-regex": "^9.0.0" + } + }, + "node_modules/wink-tokenizer/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/core/package.json b/core/package.json index ed489d1f2..952a9503d 100644 --- a/core/package.json +++ b/core/package.json @@ -95,6 +95,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 0526fb499..6fb101c03 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -1,8 +1,9 @@ -import type { RangeInFileWithContents } from "../commands/util.js"; -import type { ContextSubmenuItem, MessageContent } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; +import type { RangeInFileWithContents } from "../commands/util.js"; +import type { ContextSubmenuItem, MessageContent } from "../index.js"; + export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { onLoad: [ undefined, @@ -17,8 +18,13 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; // We pass the `curSelectedModel` because we currently cannot access the // default model title in the GUI from JB - applyToCurrentFile: [ - { text: string; streamId: string; curSelectedModelTitle: string }, + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath: string; + }, void, ]; showTutorial: [undefined, void]; @@ -59,7 +65,6 @@ export interface ApplyState { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; - setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f570b9e87..1c0f5e962 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -60,4 +60,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", + "getWebviewHistoryLength" ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index eccb1e97e..ef2daacf0 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -16,4 +16,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { void, ]; setTTSActive: [boolean, void]; + getWebviewHistoryLength: [undefined, number]; }; diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 0ed9f63d2..1fab1c6b9 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -27,7 +27,7 @@ export class MessageIde implements IDE { messageType: T, callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], ) => void, - ) {} + ) { } pathSep(): Promise { return this.request("pathSep", undefined); diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index 3e7c04644..5be83b2e7 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -14,7 +14,7 @@ Actions are shortcuts for common use cases. For example, you might want to revie ### Slash commands -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. +The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. ![slash-commands](/img/slash-commands.png) @@ -48,7 +48,7 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use `cmd/ctrl+L` to select it in the Continue sidebar. +Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. @@ -76,10 +76,10 @@ Right click actions let you highlight a desired region of code, right click, and #### Debug action -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use `cmd/ctrl+shift+R` to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. +The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. #### Quick fixes -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut `cmd/ctrl+.` will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use `cmd/ctrl+.` again and Continue will attempt to help solve the problem. +Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. ![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/autocomplete/context-selection.md b/docs/docs/autocomplete/context-selection.md index e85e3d4bd..f237a3625 100644 --- a/docs/docs/autocomplete/context-selection.md +++ b/docs/docs/autocomplete/context-selection.md @@ -13,7 +13,7 @@ We will always include the code from your file prior to and after the cursor pos ### Definitions from the Language Server Protocol -Similar to how you can use `cmd/ctrl + click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. +Similar to how you can use cmd/ctrl + `click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. ### Imported files diff --git a/docs/docs/autocomplete/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index 92a3db76e..5fd127ce5 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -14,12 +14,12 @@ Autocomplete provides inline code suggestions as you type. To enable it, simply ### Accepting a full suggestion -Accept a full suggestion by pressing `Tab` +Accept a full suggestion by pressing Tab ### Rejecting a full suggestion -Reject a full suggestion with `Esc` +Reject a full suggestion with Esc ### Partially accepting a suggestion -For more granular control, use `cmd/ctrl + →` to accept parts of the suggestion word-by-word. +For more granular control, use cmd/ctrl + → to accept parts of the suggestion word-by-word. diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index ebdb41185..072bc0128 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -11,11 +11,11 @@ Typing a question or instructions into the input box is the only required contex ## Highlighted code -The highlighted code you’ve selected by pressing `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. +The highlighted code you’ve selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. ## Active file -You can include the currently open file as context by pressing `cmd/ctrl + opt + enter` when you send your request. +You can include the currently open file as context by pressing cmd/ctrl + opt + enter when you send your request. ## Specific file diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md index b5e8aaece..84c81582e 100644 --- a/docs/docs/chat/how-it-works.md +++ b/docs/docs/chat/how-it-works.md @@ -7,7 +7,7 @@ sidebar_position: 4 Using any selected code sections, all context that you have selected with @, and your input instructions, we prompt the model to provide a response in the sidebar. If you are asking a follow-up, then all earlier session context is also included. No other additional context is provided to the model. -The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. +The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs). diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md index 509702b4f..112649aeb 100644 --- a/docs/docs/chat/how-to-use-it.md +++ b/docs/docs/chat/how-to-use-it.md @@ -20,7 +20,7 @@ You send it a question, and it replies with an answer. You tell it to solve a pr ## Highlight a code section to include as context -You select a code section with your mouse, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. +You select a code section with your mouse, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. ## Reference context with the @ symbol @@ -32,8 +32,8 @@ When the LLM replies with edits to a file, you can click the “Apply” button. ## Start a fresh session for a new task -Once you complete a task and want to start a new one, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. +Once you complete a task and want to start a new one, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. ## Switch between different models -If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’` +If you have configured multiple models, you can switch between models using the dropdown or by pressing cmd/ctrl + ’ diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 9e406416d..bb7e0f770 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -103,8 +103,8 @@ Follow these steps to ensure that everything is set up correctly: 2. Make sure you have downloaded Ollama. 3. Run `ollama run starcoder2:3b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl+, then search for this and check the box) +5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. +6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. ### Completions are slow @@ -122,8 +122,8 @@ Yes, in VS Code, if you don't want to be shown suggestions automatically you can 1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disable automatic suggestions 2. Open "Keyboard Shortcuts" (cmd/ctrl+k, cmd/ctrl+s) and search for `editor.action.inlineSuggest.trigger` 3. Click the "+" icon to add a new keybinding -4. Press the key combination you want to use to trigger suggestions (e.g. `ctrl+space`) -5. Now whenever you want to see a suggestion, you can press your key binding (e.g. `ctrl+space`) to trigger suggestions manually +4. Press the key combination you want to use to trigger suggestions (e.g. cmd/ctrl + space) +5. Now whenever you want to see a suggestion, you can press your key binding (e.g. cmd/ctrl + space) to trigger suggestions manually ### Is there a shortcut to accept one line at a time? @@ -137,7 +137,7 @@ Click the "Continue" button in the status panel at the bottom right of the scree Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". -You can also use the default shortcut to disable autocomplete directly: press `ctrl/cmd + K`, `ctrl/cmd + A`. This will turn off autocomplete without navigating through settings. +You can also use the default shortcut to disable autocomplete directly using a chord: press and hold ctrl/cmd + K (continue holding ctrl/cmd) and press ctrl/cmd + A. This will turn off autocomplete without navigating through settings. #### JetBrains diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index f106fea14..4da920943 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -75,7 +75,7 @@ Continue also supports a **global** `.continueignore` file that will be respecte If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. -If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window". +If you need to force a refresh of the index, reload the VS Code window with cmd/ctrl + shift + p + "Reload Window". ## Repository map diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1c70d729c..928e01543 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -35,7 +35,7 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use `cmd/ctrl + L` to select it in the Continue sidebar. +Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 7448ebd01..a901f811a 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -14,6 +14,19 @@ } ``` +### Embeddings model + +LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } +} +``` + ## Setting up a remote instance To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: diff --git a/docs/docs/customize/model-providers/more/nvidia.md b/docs/docs/customize/model-providers/more/nvidia.md index e59f131b7..049ff7754 100644 --- a/docs/docs/customize/model-providers/more/nvidia.md +++ b/docs/docs/customize/model-providers/more/nvidia.md @@ -37,13 +37,11 @@ We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings m ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "nvidia", - "model": "nvidia/nv-embedqa-mistral-7b-v2", - "apiKey": "[API_KEY]" - } - ] + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } } ``` diff --git a/docs/docs/customize/model-providers/more/textgenwebui.md b/docs/docs/customize/model-providers/more/textgenwebui.md index 9abf2b9e8..723079735 100644 --- a/docs/docs/customize/model-providers/more/textgenwebui.md +++ b/docs/docs/customize/model-providers/more/textgenwebui.md @@ -8,7 +8,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. { "title": "Text Generation WebUI", "provider": "text-gen-webui", - "apiBase": "http://localhost:5000", + "apiBase": "http://localhost:5000/v1", "model": "MODEL_NAME" } ] diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index 4bcc88785..882c5da79 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -13,6 +13,10 @@ In Continue, embeddings are generated during indexing and then used by [@Codebas `transformers.js` is used as a default embeddings model in VS Code. In JetBrains, there currently is no default. ::: +:::info[Free Trial] +The free trial supports embeddings (provider: `free-trial`) +::: + ## Recommended embedding models If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. @@ -77,3 +81,23 @@ See [here](../model-providers/top-level/gemini.md#embeddings-model) for instruct ### Vertex See [here](../model-providers/top-level/vertexai.md#embeddings-model) for instructions on how to use Vertex for embeddings. + +### Mistral + +See [here](../model-providers/top-level/mistral.md#embeddings-model) for instructions on how to use Mistral for embeddings. + +### NVIDIA + +See [here](../model-providers/more/nvidia.md#embeddings-model) for instructions on how to use NVIDIA for embeddings. + +### Bedrock + +See [here](../model-providers/top-level/bedrock.md#embeddings-model) for instructions on how to use Bedrock for embeddings. + +### WatsonX + +See [here](../model-providers/more/watsonx.md#embeddings-model) for instructions on how to use WatsonX for embeddings. + +### LMStudio + +See [here](../model-providers/more/lmstudio.md#embeddings-model) for instructions on how to use LMStudio for embeddings. diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 4dbed98d8..850c34b60 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -20,7 +20,7 @@ Edit is best used for small, quick changes such as: ## Highlight code and activate -Highlight the block of code you would like to modify, and press `cmd/ctrl + i` to activate the edit input. +Highlight the block of code you would like to modify, and press cmd/ctrl + i to activate the edit input. ## Describe code changes @@ -30,8 +30,8 @@ Describe the changes you would like the model to make to your highlighted code. Proposed changes appear as inline diffs within your highlighted text. -You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl + opt + y` (to accept) or `cmd/ctrl + opt + n` (to reject). +You can navigate through each proposed change, accepting or rejecting them using cmd/ctrl + opt + y (to accept) or cmd/ctrl + opt + n (to reject). -You can also accept or reject all changes at once using `cmd/ctrl + shift + enter` (to accept) or `cmd/ctrl + shift + delete` (to reject). +You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). -If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl + i` to re-prompt the model. +If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index a72a6e77a..8e7152d01 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -46,6 +46,6 @@ To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternativ ### Steps to Disable Telemetry via VS Code Settings 1. Open VS Code. -2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut `Ctrl + ,` on Windows/Linux or `Cmd + ,` on macOS). +2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). 3. In the search bar, type "Continue: Telemetry Enabled". 4. Uncheck the "Continue: Telemetry Enabled" checkbox. diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index d10d2c104..d4bbe69db 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -24,7 +24,7 @@ To solve many problems, the first step is reading the logs to find the relevant In order to view debug logs, which contain extra information, click the dropdown at the top that says "Default levels" and select "Verbose". ::: -1. `cmd+shift+p` (MacOS) / `ctrl+shift+p` (Windows) +1. cmd + shift + P for MacOS or ctrl + shift + P for Windows 2. Search for and then select "Developer: Toggle Developer Tools" 3. This will open the [Chrome DevTools window](https://developer.chrome.com/docs/devtools/) 4. Select the `Console` tab @@ -56,7 +56,7 @@ We are constantly making fixes and improvements to Continue, but the latest chan On JetBrains, the "pre-release" happens through their Early Access Program (EAP) channel. To download the latest EAP version, enable the EAP channel: -1. Open JetBrains settings (`cmd/ctrl + ,`) and go to "Plugins" +1. Open JetBrains settings (cmd/ctrl + ,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." 4. Add "[https://plugins.jetbrains.com/plugins/eap/list](https://plugins.jetbrains.com/plugins/eap/list)" to the list @@ -104,7 +104,7 @@ You may also set `requestOptions.caBundlePath` to an array of paths to multiple #### VS Code Proxy Settings -If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl+, to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. +If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl + , to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. #### code-server diff --git a/docs/src/css/custom.css b/docs/src/css/custom.css index 6002807cc..f0b798f64 100644 --- a/docs/src/css/custom.css +++ b/docs/src/css/custom.css @@ -47,6 +47,7 @@ kbd { display: inline-block; padding: 0.3em 0.4em; + margin: 0.1em .4em; font-family: var(--ifm-font-family-monospace); font-size: .8rem; font-weight: 500; diff --git a/extensions/intellij/CHANGELOG.md b/extensions/intellij/CHANGELOG.md index 0eb45541f..7745d5c91 100644 --- a/extensions/intellij/CHANGELOG.md +++ b/extensions/intellij/CHANGELOG.md @@ -8,6 +8,8 @@ and is generated by [Changie](https://github.com/miniscruff/changie). Pre-release Changes ### Fixed * Off-screen rendering to solve white flash on load and lack of changing cursor type +* OSR-related fixes for non-Mac users +* Fixes for inline edit in JetBrains ## 0.0.72 - 2024-10-04 ### Added diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 1295d0002..17c89ec85 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -632,7 +632,7 @@ class IdeProtocolClient( } } - "applyToCurrentFile" -> { + "applyToFile" -> { val msg = data as Map; val text = msg["text"] as String val curSelectedModelTitle = msg["curSelectedModelTitle"] as String diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 030da9bcc..88925e7f4 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -9,6 +9,21 @@ Pre-release Changes ### Added * New Edit mode in sidebar (cmd/ctrl+I) * Significantly faster and more accurate docs crawler by default +* OpenAI predicted outputs support +* Improve codebase retrieval with BM25 +* Support for Grok from xAI +* Chat enhancements including sticking input to bottom +* New UI for cmd+I in sidebar +* Support for Nebius LLM provider +* Support for Ask Sage LLM provider +* Improved reference for config.json +* New @web context provider +* Updates for llama3.2 +### Changed +* Improved @docs crawler +* Many improvements to make autocomplete more eager +### Fixed +* Brought back the Apply button for all code blocks ## 0.8.55 - 2024-10-25 ### Added diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f18bdbb6a..8dff320fd 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2717,13 +2717,18 @@ "openai", "cohere", "free-trial", + "continue-proxy", "gemini", "voyage", "nvidia", "bedrock", "sagemaker", "nebius", - "vertexai" + "vertexai", + "deepinfra", + "mistral", + "watsonx", + "lmstudio" ] }, "model": { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 44ade3c05..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.225", + "version": "0.9.227", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.225", + "version": "0.9.227", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -149,6 +149,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 43911c6f8..c36516018 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -384,7 +384,7 @@ class VsCodeIde implements IDE { } async openFile(path: string): Promise { - this.ideUtils.openFile(path); + await this.ideUtils.openFile(path); } async showLines( diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 06601187e..c33d71aea 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { ContextMenuConfig, IDE } from "core"; -import { CompletionProvider } from "core/autocomplete/CompletionProvider"; +import { ContextMenuConfig } from "core"; +import { CompletionProvider } from "core/autocomplete/completionProvider"; import { RangeInFileWithContents } from "core/commands/util"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; @@ -33,6 +33,7 @@ import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; +import { VsCodeIde } from "./VsCodeIde"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -177,18 +178,31 @@ async function addEntireFileToContext( function focusGUI() { const fullScreenTab = getFullScreenTab(); - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { + if (fullScreenTab) { // focus fullscreen fullScreenPanel?.reveal(); + } else { + // focus sidebar + vscode.commands.executeCommand("continue.continueGUIView.focus"); + // vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar"); + } +} + +function hideGUI() { + const fullScreenTab = getFullScreenTab(); + if (fullScreenTab) { + // focus fullscreen + fullScreenPanel?.dispose(); + } else { + // focus sidebar + vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); + // vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); } } // Copy everything over from extension.ts const commandsMap: ( - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, @@ -261,8 +275,10 @@ const commandsMap: ( if (fullPath instanceof vscode.Uri) { fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - fullPath = getFullyQualifiedPath(fullPath); + console.warn(`Unable to resolve filepath: ${newFilepath}`); } verticalDiffManager.clearForFilepath(fullPath, true); @@ -278,8 +294,10 @@ const commandsMap: ( if (fullPath instanceof vscode.Uri) { fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - fullPath = getFullyQualifiedPath(fullPath); + console.warn(`Unable to resolve filepath: ${newFilepath}`); } verticalDiffManager.clearForFilepath(fullPath, false); @@ -344,32 +362,37 @@ const commandsMap: ( core.invoke("context/indexDocs", { reIndex: true }); }, "continue.focusContinueInput": async () => { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - }, - "continue.focusContinueInputWithoutClear": async () => { - const fullScreenTab = getFullScreenTab(); - + const historyLength = await sidebar.webviewProtocol.request( + "getWebviewHistoryLength", + undefined, + ); const isContinueInputFocused = await sidebar.webviewProtocol.request( "isContinueInputFocused", undefined, ); if (isContinueInputFocused) { - // Handle closing the GUI only if we are focused on the input - if (fullScreenTab) { - fullScreenPanel?.dispose(); + if (historyLength === 0) { + hideGUI(); + } else { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); } } else { - // Handle opening the GUI otherwise - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { - // focus fullscreen - fullScreenPanel?.reveal(); - } + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", + undefined, + ); + + if (isContinueInputFocused) { + hideGUI(); + } else { + focusGUI(); sidebar.webviewProtocol?.request( "focusContinueInputWithoutClear", @@ -381,39 +404,40 @@ const commandsMap: ( }, "continue.edit": async () => { captureCommandTelemetry("edit"); - const fullScreenTab = getFullScreenTab(); - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { - // focus fullscreen - fullScreenPanel?.reveal(); - } + focusGUI(); const editor = vscode.window.activeTextEditor; if (!editor) { return; } - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), + const existingDiff = await verticalDiffManager.getHandlerForFile( + editor.document.fileName, ); + if (!existingDiff) { + // If there's a diff currently being applied, then we just toggle focus back to the input + editDecorationManager.setDecoration( + editor, + new vscode.Range(editor.selection.start, editor.selection.end), + ); - const highlightedCode = getCurrentlyHighlightedCode(true)!; - await sidebar.webviewProtocol?.request("startEditMode", { - highlightedCode, - }); + const highlightedCode = getCurrentlyHighlightedCode(true)!; + await sidebar.webviewProtocol?.request("startEditMode", { + highlightedCode, + }); - // Un-select the current selection - editor.selection = new vscode.Selection( - editor.selection.anchor, - editor.selection.anchor, - ); + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); - setTimeout(() => { + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + } else { sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); + } }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); @@ -564,15 +588,15 @@ const commandsMap: ( const fullScreenTab = getFullScreenTab(); if (fullScreenTab && fullScreenPanel) { - //Full screen open, but not focused - focus it + // Full screen open, but not focused - focus it fullScreenPanel.reveal(); return; } - //Full screen not open - open it + // Full screen not open - open it captureCommandTelemetry("openFullScreen"); - //create the full screen panel + // Create the full screen panel let panel = vscode.window.createWebviewPanel( "continue.continueGUIView", "Continue", @@ -583,7 +607,7 @@ const commandsMap: ( ); fullScreenPanel = panel; - //Add content to the panel + // Add content to the panel panel.webview.html = sidebar.getSidebarContent( extensionContext, panel, @@ -592,7 +616,7 @@ const commandsMap: ( true, ); - //When panel closes, reset the webview and focus + // When panel closes, reset the webview and focus panel.onDidDispose( () => { sidebar.resetWebviewProtocolWebview(); @@ -807,7 +831,7 @@ const commandsMap: ( export function registerAllCommands( context: vscode.ExtensionContext, - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index c6f3c2aa7..88ed3831f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -257,30 +257,6 @@ export class VerticalDiffManager { } } - /** - * Streams an edit to the current document based on user input and model output. - * - * @param input - The user's input or instruction for the edit. - * @param modelTitle - The title of the language model to be used. - * @param [onlyOneInsertion] - Optional flag to limit the edit to a single insertion. - * @param [quickEdit] - Optional string indicating if this is a quick edit. - * @param [range] - Optional range to use instead of the highlighted text. Note that the `quickEdit` - * property currently can't be passed with `range` since it assumes there is an - * active selection. - * - * This method performs the following steps: - * 1. Sets up the editor context for the diff. - * 2. Determines the range of text to be edited. - * 3. Clears any existing diff handlers for the file. - * 4. Creates a new vertical diff handler. - * 5. Prepares the context (prefix and suffix) for the language model. - * 6. Streams the diff lines from the language model. - * 7. Applies the changes to the document. - * 8. Sets up a listener for subsequent user edits. - * - * The method handles various edge cases, such as quick edits and existing diffs, - * and manages the lifecycle of diff handlers and document change listeners. - */ async streamEdit( input: string, modelTitle: string | undefined, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 483ff1603..d7ed63a5f 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -29,6 +29,7 @@ import { import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { getFullyQualifiedPath } from "../util/util"; /** * A shared messenger class between Core and Webview @@ -85,7 +86,11 @@ export class VsCodeMessenger { ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { - this.ide.openFile(msg.data.filepath); + const fullPath = getFullyQualifiedPath(this.ide, msg.data.filepath); + + if (fullPath) { + this.ide.openFile(fullPath); + } }); this.onWebview("vscode/openMoveRightMarkdown", (msg) => { @@ -153,9 +158,33 @@ export class VsCodeMessenger { await vscode.commands.executeCommand("continue.rejectDiff", filepath); }); - this.onWebview("applyToCurrentFile", async ({ data }) => { + this.onWebview("applyToFile", async ({ data }) => { + const fullPath = getFullyQualifiedPath(ide, data.filepath); + + if (!fullPath) { + return; + } + + const fileExists = await this.ide.fileExists(fullPath); + + // If it's a new file, no need to apply, just write directly + if (!fileExists) { + await this.ide.writeFile(fullPath, data.text); + await this.ide.openFile(fullPath); + + await webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "done", + }); + + return; + } + + await this.ide.openFile(fullPath); + // Get active text editor const editor = vscode.window.activeTextEditor; + if (!editor) { vscode.window.showErrorMessage("No active editor to apply edits to"); return; diff --git a/extensions/vscode/src/stubs/remoteConfig.ts b/extensions/vscode/src/stubs/remoteConfig.ts index 24c197bd8..eb3cba824 100644 --- a/extensions/vscode/src/stubs/remoteConfig.ts +++ b/extensions/vscode/src/stubs/remoteConfig.ts @@ -67,6 +67,18 @@ export class RemoteConfigSync { }; } + private canParse(url: string): boolean { + if ((URL as any).canParse) { + return (URL as any).canParse(url); + } + try { + new URL(url); + return true; + } catch (e) { + return false; + } + } + async setup() { if ( this.userToken === null || @@ -75,7 +87,7 @@ export class RemoteConfigSync { ) { return; } - if (!URL.canParse(this.remoteConfigServerUrl)) { + if (!this.canParse(this.remoteConfigServerUrl)) { vscode.window.showErrorMessage( "The value set for 'remoteConfigServerUrl' is not valid: ", this.remoteConfigServerUrl, @@ -92,6 +104,7 @@ export class RemoteConfigSync { private setInterval() { if (this.syncInterval !== undefined) { + // @ts-ignore clearInterval(this.syncInterval); } this.syncInterval = setInterval( diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 14ebd9ed2..6ebb9c1a1 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -136,9 +136,7 @@ export class VsCodeIdeUtils { ); } - private async resolveAbsFilepathInWorkspace( - filepath: string, - ): Promise { + async resolveAbsFilepathInWorkspace(filepath: string): Promise { // If the filepath is already absolute, return it as is if (this.path.isAbsolute(filepath)) { return filepath; @@ -158,7 +156,7 @@ export class VsCodeIdeUtils { async openFile(filepath: string, range?: vscode.Range) { // vscode has a builtin open/get open files - return openEditorAndRevealRange( + return await openEditorAndRevealRange( await this.resolveAbsFilepathInWorkspace(filepath), range, vscode.ViewColumn.One, diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 2d0ae72a7..9b5c11bfe 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -1,6 +1,7 @@ const os = require("node:os"); import path from "node:path"; import * as vscode from "vscode"; +import { VsCodeIde } from "../VsCodeIde"; function charIsEscapedAtIndex(index: number, str: string): boolean { if (index === 0) { @@ -123,15 +124,12 @@ export function getExtensionVersion(): string { return extension?.packageJSON.version || "0.1.0"; } -export function getFullyQualifiedPath(filepath?: string) { - if (filepath && !path.isAbsolute(filepath)) { - const workspaceFolders = vscode.workspace.workspaceFolders; - if (workspaceFolders && workspaceFolders.length > 0) { - return path.join(workspaceFolders[0].uri.fsPath, filepath); - } else { - vscode.window.showErrorMessage( - "Unable to resolve filepath: no workspace folder found", - ); - } +export function getFullyQualifiedPath(ide: VsCodeIde, filepath: string) { + if (ide.ideUtils.path.isAbsolute(filepath)) return filepath; + + const workspaceFolders = vscode.workspace.workspaceFolders; + + if (workspaceFolders && workspaceFolders.length > 0) { + return ide.ideUtils.path.join(workspaceFolders[0].uri.fsPath, filepath); } } diff --git a/gui/package-lock.json b/gui/package-lock.json index b0be81c6c..5c0221a2f 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -151,6 +151,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 0a4ceb5e3..7a04bf43a 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -18,6 +18,10 @@ export const VSC_INPUT_BORDER_FOCUS_VAR = "--vscode-focusBorder"; export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background"; export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground"; export const VSC_SIDEBAR_BORDER_VAR = "--vscode-sideBar-border"; +export const VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR = + "--vscode-diffEditor-removedLineBackground"; +export const VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR = + "--vscode-diffEditor-insertedLineBackground"; export const VSC_THEME_COLOR_VARS = [ VSC_INPUT_BACKGROUND_VAR, @@ -35,6 +39,8 @@ export const VSC_THEME_COLOR_VARS = [ VSC_BADGE_BACKGROUND_VAR, VSC_SIDEBAR_BORDER_VAR, VSC_BADGE_FOREGROUND_VAR, + VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, + VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, ]; export const defaultBorderRadius = "5px"; @@ -56,6 +62,8 @@ export const vscInputBorderFocus = `var(${VSC_INPUT_BORDER_FOCUS_VAR}, ${lightGr export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`; export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #fff)`; export const vscSidebarBorder = `var(${VSC_SIDEBAR_BORDER_VAR}, transparent)`; +export const vscDiffRemovedLineBackground = `var(${VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR}, #808080)`; +export const vscDiffInsertedLineBackground = `var(${VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR}, #28a745)`; if (typeof document !== "undefined") { for (const colorVar of VSC_THEME_COLOR_VARS) { @@ -101,20 +109,25 @@ export function parseColorForHex(colorVar: string): string { colorVar, ); if (value.startsWith("#")) { + console.log("OAIJFIOJOOJOIO", colorVar, value, value.slice(0, 7)); return value.slice(0, 7); } - // Parse rgb - const rgb = value - .slice(4, -1) + // Parse rgb/rgba + const rgbValues = value + .slice(value.startsWith("rgba") ? 5 : 4, -1) .split(",") + .map((x) => x.trim()) + .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) .map((x) => parseInt(x, 10)); + let hex = "#" + - rgb + rgbValues .map((x) => x.toString(16)) .map((x) => (x.length === 1 ? "0" + x : x)) .join(""); + return hex; } diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 2ef4db920..01ee8dea6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -248,8 +248,8 @@ function TipTapEditor(props: TipTapEditorProps) { const timer = setTimeout(() => { setHasDefaultModel( !!defaultModel && - defaultModel.apiKey !== undefined && - defaultModel.apiKey !== "", + defaultModel.apiKey !== undefined && + defaultModel.apiKey !== "", ); }, 3500); @@ -452,38 +452,38 @@ function TipTapEditor(props: TipTapEditorProps) { Text, props.availableContextProviders.length ? Mention.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }) : undefined, props.availableSlashCommands.length ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) : undefined, CodeBlockExtension, ], @@ -575,18 +575,10 @@ function TipTapEditor(props: TipTapEditorProps) { * with those key actions. */ const handleKeyDown = async (e: KeyboardEvent) => { - if (!editor || !editorFocusedRef.current) return; + if (!editorFocusedRef?.current) return; setActiveKey(e.key); - // Allow users to use the escape key to jump back to the editor - if (e.key === "Escape") { - e.stopPropagation(); - e.preventDefault(); - ideMessenger.post("focusEditor", undefined); - return; - } - // Handle meta key issues if (isMetaEquivalentKeyPressed(e)) { if (isJetBrains()) { @@ -655,7 +647,7 @@ function TipTapEditor(props: TipTapEditorProps) { return; } if (historyLength > 0) { - saveSession(); + await saveSession(); } setTimeout(() => { editor?.commands.blur(); @@ -684,12 +676,12 @@ function TipTapEditor(props: TipTapEditorProps) { if (!props.isMainInput) { return; } - saveSession(); + await saveSession(); setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor, props.isMainInput, saveSession], ); useWebviewListener( @@ -706,9 +698,8 @@ function TipTapEditor(props: TipTapEditorProps) { rif.filepath, await ideMessenger.ide.getWorkspaceDirs(), ); - const rangeStr = `(${rif.range.start.line + 1}-${ - rif.range.end.line + 1 - })`; + const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1 + })`; const item: ContextItemWithId = { content: rif.contents, name: `${basename} ${rangeStr}`, diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index b5380e26d..ac4c03bb2 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -131,7 +131,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { const defaultModel = useSelector(defaultModelSelector); const isTerminal = isTerminalCodeBlock(props.language, props.text); const [isCopied, setIsCopied] = useState(false); - const [isApplying, setIsApplying] = useState(false); const streamIdRef = useRef(null); if (streamIdRef.current === null) { @@ -149,10 +148,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { useWebviewListener( "applyCodeFromChat", async () => { - await ideMessenger.request("applyToCurrentFile", { + await ideMessenger.request("applyToFile", { curSelectedModelTitle: defaultModel.title, text: props.text, streamId: streamIdRef.current, + filepath: props.filepath, }); dispatch(incrementNextCodeBlockToApplyIndex({})); }, @@ -172,23 +172,26 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { } async function onClickApply() { - if (isApplying) return; - if (isTerminal) { await ideMessenger.ide.runCommand(getTerminalCommand(props.text)); - } else { - ideMessenger.post("applyToCurrentFile", { - curSelectedModelTitle: defaultModel.title, - text: props.text, - streamId: streamIdRef.current, - }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "streaming", - }), - ); + return; } + + if (!props.filepath) return; + + dispatch( + updateApplyState({ + streamId: streamIdRef.current, + status: "streaming", + }), + ); + + ideMessenger.post("applyToFile", { + curSelectedModelTitle: defaultModel.title, + text: props.text, + streamId: streamIdRef.current, + filepath: props.filepath, + }); } function onClickHeader() { @@ -227,7 +230,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { {!isJetBrains() && isTerminal && ( @@ -235,15 +237,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { )} - {isApplying ? ( - - ) : ( - - )} + ) { ); // IDE event listeners + const history = useSelector((store: RootState) => store.state.history); + useWebviewListener("getWebviewHistoryLength", async () => { + return history.length; + }, [history]); + useWebviewListener("setInactive", async () => { dispatch(setInactive()); }); diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index dbfb44f64..852cdf845 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -27,14 +27,13 @@ function IndexingProgressIndicator({ update }: IndexingProgressIndicatorProps) { return (
- {showProgress && {progressPercentage}%} + {showProgress && {progressPercentage.toFixed(0)}%} {Icon && (
)} diff --git a/gui/src/pages/edit.tsx b/gui/src/pages/edit.tsx index f05648875..9629d4d66 100644 --- a/gui/src/pages/edit.tsx +++ b/gui/src/pages/edit.tsx @@ -7,7 +7,14 @@ import { useContext, useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscForeground } from "../components"; +import { + defaultBorderRadius, + lightGray, + parseColorForHex, + VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, + VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, + vscForeground, +} from "../components"; import FileIcon from "../components/FileIcon"; import { NewSessionButton } from "../components/mainInput/NewSessionButton"; import resolveEditorContent from "../components/mainInput/resolveInput"; @@ -162,7 +169,7 @@ function Edit() { placeholder={ ["streaming", "accepting"].includes(editModeState.editStatus) ? "Enter instructions for edit" - : "Enter follow-up instructions" + : "Enter instructions for edit" } border={`1px solid #aa0`} availableContextProviders={availableContextProviders.filter( @@ -203,7 +210,9 @@ function Edit() {
{ ideMessenger.request("edit/acceptReject", { accept: false, @@ -217,7 +226,9 @@ function Edit() { { ideMessenger.request("edit/acceptReject", { accept: true, @@ -240,7 +251,7 @@ function Edit() { className="mr-auto flex items-center gap-2" > - Back to chat + Back to Chat
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6ca0cc167..27e9be2cd 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -136,7 +136,6 @@ export function Chat() { const { streamResponse } = useChatHandler(dispatch, ideMessenger); const onboardingCard = useOnboardingCard(); const { showTutorialCard, closeTutorialCard } = useTutorialCard(); - const sessionState = useSelector((state: RootState) => state.state); const defaultModel = useSelector(defaultModelSelector); const ttsActive = useSelector((state: RootState) => state.state.ttsActive); const active = useSelector((state: RootState) => state.state.active); @@ -148,7 +147,7 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); - const scrollToBottom = useCallback(() => { + const snapToBottom = useCallback(() => { if (!topGuiDivRef.current) return; const elem = topGuiDivRef.current; elem.scrollTop = elem.scrollHeight - elem.clientHeight; @@ -156,9 +155,26 @@ export function Chat() { setIsAtBottom(true); }, [topGuiDivRef, setIsAtBottom]); + const smoothScrollToBottom = useCallback(async () => { + if (!topGuiDivRef.current) return; + const elem = topGuiDivRef.current + elem.scrollTo({ + top: elem.scrollHeight - elem.clientHeight, + behavior: 'smooth' + }) + + setIsAtBottom(true); + }, [topGuiDivRef, setIsAtBottom]); + useEffect(() => { - if (active) scrollToBottom(); - }, [active, scrollToBottom]); + if (active) snapToBottom(); + }, [active, snapToBottom]); + + useEffect(() => { + setTimeout(() => { + smoothScrollToBottom(); + }, 250) + }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { // Cmd + Backspace to delete current step @@ -284,8 +300,8 @@ export function Chat() { } }, [ - sessionState.history, - sessionState.contextItems, + state.history, + state.contextItems, defaultModel, state, streamResponse, @@ -370,11 +386,11 @@ export function Chat() { : true : stepsOpen[index]! } - onToggle={() => {}} + onToggle={() => { }} > {}} + onUserInput={(input: string) => { }} item={item} - onReverse={() => {}} + onReverse={() => { }} onRetry={() => { streamResponse( state.history[index - 1].editorState, state.history[index - 1].modifiers ?? - defaultInputModifiers, + defaultInputModifiers, ideMessenger, index - 1, );