diff --git a/.changes/unreleased/Added-20241102-002724.yaml b/.changes/unreleased/Added-20241102-002724.yaml new file mode 100644 index 000000000..3426d6546 --- /dev/null +++ b/.changes/unreleased/Added-20241102-002724.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New Edit mode in sidebar (cmd/ctrl+I) +time: 2024-11-02T00:27:24.40964-07:00 diff --git a/.changes/unreleased/Added-20241102-002744.yaml b/.changes/unreleased/Added-20241102-002744.yaml new file mode 100644 index 000000000..b7d894747 --- /dev/null +++ b/.changes/unreleased/Added-20241102-002744.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Significantly faster and more accurate docs crawler by default +time: 2024-11-02T00:27:44.408045-07:00 diff --git a/.github/workflows/auto-assign.yaml b/.github/workflows/auto-assign.yaml index 284dc7f25..3108307e5 100644 --- a/.github/workflows/auto-assign.yaml +++ b/.github/workflows/auto-assign.yaml @@ -16,3 +16,9 @@ jobs: repo-token: ${{ secrets.CI_GITHUB_TOKEN }} assignees: sestinj,Patrick-Erichsen numOfAssignee: 1 + - name: "Add default labels" + uses: actions-ecosystem/action-add-labels@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + labels: | + "needs-triage" diff --git a/.prettierrc b/.prettierrc index 46664808a..7b5484dd7 100644 --- a/.prettierrc +++ b/.prettierrc @@ -2,5 +2,8 @@ "tabWidth": 2, "useTabs": false, "trailingComma": "all", + "semi": true, + "singleQuote": false, + "bracketSpacing": true, "plugins": ["prettier-plugin-tailwindcss"] } diff --git a/.prompts/test.prompt b/.prompts/test.prompt deleted file mode 100644 index e2f5d8662..000000000 --- a/.prompts/test.prompt +++ /dev/null @@ -1,19 +0,0 @@ -temperature: 0.5 -maxTokens: 4096 -name: jest -description: Write Jest unit tests ---- - -You are an expert programmer - - -{{{ input }}} - -Write unit tests for the above selected code, following each of these instructions: -- Use `jest` -- Properly set up and tear down -- Include important edge cases -- The tests should be complete and sophisticated -- Give the tests just as chat output, don't edit any file -- Don't explain how to set up `jest` -- Write a single code block, making sure to label with the language being used (e.g. "```typscript") \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index b302a1157..b77c6d9b0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -14,11 +14,26 @@ } }, "search.exclude": { - "**/core/vendor/**": true, - "**/gui/dist": true, - "**/extensions/vscode/gui/**": true, - "**/extensions/vscode/out/**": true, - "**/extensions/intellij/build/**": true + "**/package-lock.json": true, + "binary/bin/**": true, + "binary/build/**": true, + "binary/out/**": true, + "binary/tmp/**": true, + "core/llm/llamaTokenizer.js": true, + "core/llm/llamaTokenizer.mjs": true, + "core/vendor/**": true, + "docs/.docusaurus/**": true, + "extensions/intellij/build/**": true, + "extensions/vscode/bin/**": true, + "extensions/vscode/build/**": true, + "extensions/vscode/gui/**": true, + "extensions/vscode/models/all-MiniLM-L6-v2/**": true, + "extensions/vscode/out/**": true, + "extensions/vscode/tag-qry/**": true, + "extensions/vscode/textmate-syntaxes/**": true, + "extensions/vscode/tree-sitter/**": true, + "gui/dist/**": true + // "sync/**": true }, "eslint.workingDirectories": ["./core"] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 1beef2615..8331b5380 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -5,11 +5,11 @@ { "label": "vscode-extension:build", "dependsOn": [ - // To detect compile errors and output extensions.js + // To detect compile errors "vscode-extension:tsc", // To build the React app that is used in the extension "vscode-extension:continue-ui:build", - // To bundle the code the same way we do for publishing + // // To bundle the code the same way we do for publishing "vscode-extension:esbuild", // Start the React app that is used in the extension "gui:dev" @@ -21,10 +21,7 @@ }, { "label": "vscode-extension:esbuild", - "dependsOn": [ - "vscode-extension:continue-ui:build", - "vscode-extension:tsc" - ], + "dependsOn": ["vscode-extension:continue-ui:build"], "type": "npm", "script": "esbuild-watch", "path": "extensions/vscode", @@ -44,7 +41,7 @@ "background": { "activeOnStart": true, "beginsPattern": ">", - "endsPattern": ">" + "endsPattern": "VS Code Extension esbuild complete" } } ] diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 422b377bd..8cc92ddec 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -10,13 +10,11 @@ export async function fullTextRetrieve( const searchStrings = prefix.split("\n").slice(-3); const results: Chunk[] = []; searchStrings.forEach(async (searchString) => { - const chunks = await index.retrieve( - [indexTag], - searchString, - 3, - undefined, - undefined, - ); + const chunks = await index.retrieve({ + tags: [indexTag], + text: searchString, + n: 3, + }); results.push(...chunks); }); return results; diff --git a/core/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/config/default.ts b/core/config/default.ts index 634c8c599..814552e75 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -6,7 +6,7 @@ import { } from "../"; export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = { - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", provider: "anthropic", apiKey: "", title: "Claude 3.5 Sonnet", @@ -23,7 +23,7 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [ { title: "Claude 3.5 Sonnet (Free Trial)", provider: "free-trial", - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", systemMessage: "You are an expert software developer. You give helpful and concise responses.", }, diff --git a/core/config/types.ts b/core/config/types.ts index 22f1e9128..ca8ee9bec 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -648,6 +648,7 @@ declare global { | "gemma-7b-it" | "gemma2-9b-it" // Anthropic + | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" | "claude-3-sonnet-20240229" diff --git a/core/context/providers/DiffContextProvider.ts b/core/context/providers/DiffContextProvider.ts index ae0eb42b8..f2c95083f 100644 --- a/core/context/providers/DiffContextProvider.ts +++ b/core/context/providers/DiffContextProvider.ts @@ -17,7 +17,7 @@ class DiffContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const diff = await extras.ide.getDiff(false); + const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true); return [ { description: "The current git diff", diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts index 6c9320f8f..d747f76f1 100644 --- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts +++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts @@ -156,12 +156,17 @@ export class JiraClient { }, ); - if (response.status !== 200) { + if (response.status === 500) { + const text = await response.text(); console.warn( - "Unable to get jira tickets. Response code from API is", - response.status, + "Unable to get Jira tickets. You may need to set 'apiVersion': 2 in your config.json. See full documentation here: https://docs.continue.dev/customize/context-providers#jira-datacenter-support\n\n", + text, ); return Promise.resolve([]); + } else if (response.status !== 200) { + const text = await response.text(); + console.warn("Unable to get Jira tickets: ", text); + return Promise.resolve([]); } const data = (await response.json()) as any; diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts index 61f38b98b..2d3f9ab12 100644 --- a/core/context/rerankers/tei.ts +++ b/core/context/rerankers/tei.ts @@ -15,6 +15,7 @@ export class HuggingFaceTEIReranker implements Reranker { apiBase?: string; truncate?: boolean; truncation_direction?: string; + apiKey?: string; }, ) {} @@ -24,9 +25,17 @@ export class HuggingFaceTEIReranker implements Reranker { apiBase += "/"; } + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.params.apiKey) { + headers["Authorization"] = `Bearer ${this.params.apiKey}`; + } + const resp = await fetch(new URL("rerank", apiBase), { method: "POST", - headers: { "Content-Type": "application/json" }, + headers, body: JSON.stringify({ query: query, return_text: false, 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 5117cd22c..3781f4d81 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,6 +29,9 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; +import ignore from "ignore"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; +import path from "path"; export class Core { // implements IMessenger @@ -704,8 +707,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/index.d.ts b/core/index.d.ts index c896c361b..5b0b892f6 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -48,9 +48,9 @@ export interface IndexingProgressUpdate { export type PromptTemplate = | string | (( - history: ChatMessage[], - otherData: Record, - ) => string | ChatMessage[]); + history: ChatMessage[], + otherData: Record, + ) => string | ChatMessage[]); export interface ILLM extends LLMOptions { get providerName(): ModelProvider; @@ -646,7 +646,8 @@ type ModelProvider = | "cerebras" | "askSage" | "vertexai" - | "nebius"; + | "nebius" + | "xAI"; export type ModelName = | "AUTODETECT" @@ -696,6 +697,8 @@ export type ModelName = | "llama3.2-3b" | "llama3.2-11b" | "llama3.2-90b" + // xAI + | "grok-beta" // Other Open-source | "phi2" | "phind-codellama-34b" @@ -710,6 +713,7 @@ export type ModelName = | "gemma-7b-it" | "gemma2-9b-it" // Anthropic + | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" | "claude-3-sonnet-20240229" @@ -1053,9 +1057,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ 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/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 19300cd0b..d0851f95b 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -1,18 +1,11 @@ -import { Octokit } from "@octokit/rest"; -import * as cheerio from "cheerio"; -import * as fs from "fs"; -import fetch from "node-fetch"; import { URL } from "node:url"; -import { Handler, HTTPResponse, Page } from "puppeteer"; -import { - editConfigJson, - getChromiumPath, - getContinueUtilsPath, -} from "../../util/paths"; // @ts-ignore // @prettier-ignore -import PCR from "puppeteer-chromium-resolver"; import { ContinueConfig, IDE } from "../.."; +import CheerioCrawler from "./crawlers/CheerioCrawler"; +import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler"; +import { DefaultCrawler } from "./crawlers/DefaultCrawler"; +import GitHubCrawler from "./crawlers/GitHubCrawler"; export type PageData = { url: string; @@ -42,10 +35,23 @@ class DocsCrawler { async *crawl( startUrl: URL, maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL, - ): AsyncGenerator { + ): AsyncGenerator { if (startUrl.host === this.GITHUB_HOST) { yield* new GitHubCrawler(startUrl).crawl(); - } else if (this.shouldUseChromium()) { + return; + } + + try { + const pageData = await new DefaultCrawler(startUrl).crawl(); + if (pageData.length > 0) { + yield* pageData; + return; + } + } catch (e) { + console.error("Default crawler failed, trying backup: ", e); + } + + if (this.shouldUseChromium()) { yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); } else { let didCrawlSinglePage = false; @@ -83,471 +89,6 @@ class DocsCrawler { } } -class GitHubCrawler { - private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); - private octokit = new Octokit({ auth: undefined }); - - constructor(private readonly startUrl: URL) {} - - async *crawl(): AsyncGenerator { - console.debug( - `[${ - (this.constructor as any).name - }] Crawling GitHub repo: ${this.startUrl.toString()}`, - ); - const urlStr = this.startUrl.toString(); - const [_, owner, repo] = this.startUrl.pathname.split("/"); - const branch = await this.getGithubRepoDefaultBranch(owner, repo); - const paths = await this.getGitHubRepoPaths(owner, repo, branch); - - for await (const path of paths) { - const content = await this.getGithubRepoFileContent(path, owner, repo); - yield { path, url: urlStr, content: content ?? "" }; - } - } - - private async getGithubRepoDefaultBranch( - owner: string, - repo: string, - ): Promise { - const repoInfo = await this.octokit.repos.get({ owner, repo }); - return repoInfo.data.default_branch; - } - - private async getGitHubRepoPaths( - owner: string, - repo: string, - branch: string, - ) { - const tree = await this.octokit.request( - "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", - { - owner, - repo, - tree_sha: branch, - headers: { "X-GitHub-Api-Version": "2022-11-28" }, - recursive: "true", - }, - ); - - return tree.data.tree - .filter( - (file: any) => - file.type === "blob" && this.markdownRegex.test(file.path ?? ""), - ) - .map((file: any) => file.path); - } - - private async getGithubRepoFileContent( - path: string, - owner: string, - repo: string, - ) { - try { - const response = await this.octokit.repos.getContent({ - owner, - repo, - path, - headers: { Accept: "application/vnd.github.raw+json" }, - }); - return response.data as unknown as string; - } catch (error) { - console.debug("Error fetching file contents:", error); - return null; - } - } -} - -class CheerioCrawler { - private readonly IGNORE_PATHS_ENDING_IN = [ - "favicon.ico", - "robots.txt", - ".rst.txt", - "genindex", - "py-modindex", - "search.html", - "search", - "genindex.html", - "changelog", - "changelog.html", - ]; - - constructor( - private readonly startUrl: URL, - private readonly maxRequestsPerCrawl: number, - ) {} - - async *crawl(): AsyncGenerator { - yield* this.crawlPage(this.startUrl); - } - - private async *crawlPage( - url: URL, - maxDepth: number = 3, - ): AsyncGenerator { - console.log( - `[${ - (this.constructor as any).name - }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, - ); - - const { baseUrl, basePath } = this.splitUrl(url); - - let paths: { path: string; depth: number }[] = [ - { path: basePath, depth: 0 }, - ]; - - let index = 0; - - while (index < paths.length) { - const batch = paths.slice(index, index + 50); - - try { - const promises = batch.map(({ path, depth }) => - this.getLinksFromUrl(baseUrl, path).then((links) => ({ - links, - path, - depth, - })), - ); - - const results = await Promise.all(promises); - for (const { - links: { html, links: linksArray }, - path, - depth, - } of results) { - if (html !== "" && depth <= maxDepth) { - yield { url: url.toString(), path, content: html }; - } - - if (depth < maxDepth) { - for (let link of linksArray) { - if (!paths.some((p) => p.path === link)) { - paths.push({ path: link, depth: depth + 1 }); - } - } - } - } - } catch (e) { - console.debug("Error while crawling page: ", e); - } - - index += batch.length; - } - - console.log("Crawl completed"); - } - - private async getLinksFromUrl(url: string, path: string) { - const baseUrl = new URL(url); - const location = new URL(path, url); - let response; - - try { - response = await fetch(location.toString()); - } catch (error: unknown) { - if ( - error instanceof Error && - error.message.includes("maximum redirect") - ) { - console.error( - `[${ - (this.constructor as any).name - }] Maximum redirect reached for: ${location.toString()}`, - ); - return { html: "", links: [] }; - } - console.error(error); - return { html: "", links: [] }; - } - if (!response.ok) { - return { html: "", links: [] }; - } - const html = await response.text(); - let links: string[] = []; - - if (url.includes("github.com")) { - return { html, links }; - } - - const $ = cheerio.load(html); - - $("a").each((_: any, element: any) => { - const href = $(element).attr("href"); - if (!href) { - return; - } - - const parsedUrl = new URL(href, location); - if (parsedUrl.hostname === baseUrl.hostname) { - links.push(parsedUrl.pathname); - } - }); - - links = [...new Set(links)].filter((link) => { - return ( - !link.includes("#") && - !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) - ); - }); - return { html, links }; - } - - private splitUrl(url: URL) { - const baseUrl = new URL('/', url).href; - const basePath = url.pathname; - return { baseUrl, basePath }; - } -} - -class ChromiumCrawler { - private readonly LINK_GROUP_SIZE = 2; - private curCrawlCount = 0; - - constructor( - private readonly startUrl: URL, - private readonly maxRequestsPerCrawl: number, - ) {} - - static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { - editConfigJson((config) => ({ - ...config, - experimental: { - ...config.experimental, - useChromiumForDocsCrawling, - }, - })); - } - - async *crawl(): AsyncGenerator { - console.debug( - `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, - ); - - const stats = await PCR(ChromiumInstaller.PCR_CONFIG); - const browser = await stats.puppeteer.launch({ - args: [ - "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", - ], - executablePath: stats.executablePath, - }); - const page = await browser.newPage(); - - try { - yield* this.crawlSitePages(page, this.startUrl); - } catch (e) { - console.debug("Error getting links: ", e); - console.debug( - "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", - ); - - ChromiumCrawler.setUseChromiumForDocsCrawling(false); - } finally { - await browser.close(); - } - } - - /** - * We need to handle redirects manually, otherwise there are race conditions. - * - * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 - */ - private async gotoPageAndHandleRedirects(page: Page, url: string) { - const MAX_PAGE_WAIT_MS = 5000; - - await page.goto(url, { - timeout: 0, - waitUntil: "networkidle2", - }); - - let responseEventOccurred = false; - const responseHandler: Handler = (event) => - (responseEventOccurred = true); - - const responseWatcher = new Promise(function (resolve, reject) { - setTimeout(() => { - if (!responseEventOccurred) { - resolve(); - } else { - setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); - } - }, 500); - }); - - page.on("response", responseHandler); - - await Promise.race([responseWatcher, page.waitForNavigation()]); - } - - private async *crawlSitePages( - page: Page, - curUrl: URL, - visitedLinks: Set = new Set(), - ): AsyncGenerator { - const urlStr = curUrl.toString(); - - if (visitedLinks.has(urlStr)) { - return; - } - - await this.gotoPageAndHandleRedirects(page, urlStr); - - const htmlContent = await page.content(); - const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); - this.curCrawlCount++; - - visitedLinks.add(urlStr); - - yield { - path: curUrl.pathname, - url: urlStr, - content: htmlContent, - }; - - for (const linkGroup of linkGroups) { - let enqueuedLinkCount = this.curCrawlCount; - - for (const link of linkGroup) { - enqueuedLinkCount++; - console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); - if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { - yield* this.crawlSitePages(page, new URL(link), visitedLinks); - } - } - } - } - - private stripHashFromUrl(urlStr: string) { - try { - let url = new URL(urlStr); - url.hash = ""; - return url; - } catch (err) { - return null; - } - } - - private isValidHostAndPath(newUrl: URL, curUrl: URL) { - return ( - newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host - ); - } - - private async getLinksFromPage(page: Page, curUrl: URL) { - const links = await page.$$eval("a", (links) => links.map((a) => a.href)); - - const cleanedLinks = links - .map(this.stripHashFromUrl) - .filter( - (newUrl) => - newUrl !== null && - this.isValidHostAndPath(newUrl, curUrl) && - newUrl !== curUrl, - ) - .map((newUrl) => (newUrl as URL).href); - - const dedupedLinks = Array.from(new Set(cleanedLinks)); - - return dedupedLinks; - } - - private async getLinkGroupsFromPage(page: Page, curUrl: URL) { - const links = await this.getLinksFromPage(page, curUrl); - - const groups = links.reduce((acc, link, i) => { - const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); - - if (!acc[groupIndex]) { - acc.push([]); - } - - acc[groupIndex].push(link); - - return acc; - }, [] as string[][]); - - return groups; - } -} - -class ChromiumInstaller { - static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; - - constructor( - private readonly ide: IDE, - private readonly config: ContinueConfig, - ) { - if (this.shouldInstallOnStartup()) { - console.log("Installing Chromium"); - void this.install(); - } - } - - isInstalled() { - return fs.existsSync(getChromiumPath()); - } - - shouldInstallOnStartup() { - return ( - !this.isInstalled() && - this.config.experimental?.useChromiumForDocsCrawling - ); - } - - shouldProposeUseChromiumOnCrawlFailure() { - const { experimental } = this.config; - - return ( - experimental?.useChromiumForDocsCrawling === undefined || - experimental.useChromiumForDocsCrawling - ); - } - - async proposeAndAttemptInstall(site: string) { - const userAcceptedInstall = await this.proposeInstall(site); - - if (userAcceptedInstall) { - const didInstall = await this.install(); - return didInstall; - } - } - - async install() { - try { - await PCR(ChromiumInstaller.PCR_CONFIG); - - ChromiumCrawler.setUseChromiumForDocsCrawling(true); - - return true; - } catch (error) { - console.debug("Error installing Chromium : ", error); - console.debug( - "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", - ); - - ChromiumCrawler.setUseChromiumForDocsCrawling(false); - - await this.ide.showToast("error", "Failed to install Chromium"); - - return false; - } - } - - private async proposeInstall(site: string) { - const msg = - `Unable to crawl documentation site: ${site}\n` + - "We recommend installing Chromium. " + - "Download progress can be viewed in the developer console."; - - const actionMsg = "Install Chromium"; - - const res = await this.ide.showToast("warning", msg, actionMsg); - - return res === actionMsg; - } -} - export default DocsCrawler; export { CheerioCrawler, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index d6c3b684c..0224dc3a0 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -404,12 +404,15 @@ export default class DocsService { async getFavicon(startUrl: string) { const db = await this.getOrCreateSqliteDb(); - const { favicon } = await db.get( + const result = await db.get( `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, startUrl, ); - return favicon; + if (!result) { + return; + } + return result.favicon; } private async init(configHandler: ConfigHandler) { diff --git a/core/indexing/docs/crawlers/CheerioCrawler.ts b/core/indexing/docs/crawlers/CheerioCrawler.ts new file mode 100644 index 000000000..df3eaf1bd --- /dev/null +++ b/core/indexing/docs/crawlers/CheerioCrawler.ts @@ -0,0 +1,146 @@ +import * as cheerio from "cheerio"; +import { URL } from "node:url"; +import { PageData } from "../DocsCrawler"; + +export default class CheerioCrawler { + private readonly IGNORE_PATHS_ENDING_IN = [ + "favicon.ico", + "robots.txt", + ".rst.txt", + "genindex", + "py-modindex", + "search.html", + "search", + "genindex.html", + "changelog", + "changelog.html", + ]; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + ) {} + + async *crawl(): AsyncGenerator { + yield* this.crawlPage(this.startUrl); + } + + private async *crawlPage( + url: URL, + maxDepth: number = 3, + ): AsyncGenerator { + console.log( + `[${ + (this.constructor as any).name + }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, + ); + + const { baseUrl, basePath } = this.splitUrl(url); + + let paths: { path: string; depth: number }[] = [ + { path: basePath, depth: 0 }, + ]; + + let index = 0; + + while (index < paths.length) { + const batch = paths.slice(index, index + 50); + + try { + const promises = batch.map(({ path, depth }) => + this.getLinksFromUrl(baseUrl, path).then((links) => ({ + links, + path, + depth, + })), + ); + + const results = await Promise.all(promises); + for (const { + links: { html, links: linksArray }, + path, + depth, + } of results) { + if (html !== "" && depth <= maxDepth) { + yield { url: url.toString(), path, content: html }; + } + + if (depth < maxDepth) { + for (let link of linksArray) { + if (!paths.some((p) => p.path === link)) { + paths.push({ path: link, depth: depth + 1 }); + } + } + } + } + } catch (e) { + console.debug("Error while crawling page: ", e); + } + + index += batch.length; + } + + console.log("Crawl completed"); + } + + private async getLinksFromUrl(url: string, path: string) { + const baseUrl = new URL(url); + const location = new URL(path, url); + let response; + + try { + response = await fetch(location.toString()); + } catch (error: unknown) { + if ( + error instanceof Error && + error.message.includes("maximum redirect") + ) { + console.error( + `[${ + (this.constructor as any).name + }] Maximum redirect reached for: ${location.toString()}`, + ); + return { html: "", links: [] }; + } + console.error(error); + return { html: "", links: [] }; + } + if (!response.ok) { + return { html: "", links: [] }; + } + const html = await response.text(); + let links: string[] = []; + + if (url.includes("github.com")) { + return { html, links }; + } + + const $ = cheerio.load(html); + + $("a").each((_: any, element: any) => { + const href = $(element).attr("href"); + if (!href) { + return; + } + + const parsedUrl = new URL(href, location); + if (parsedUrl.hostname === baseUrl.hostname) { + links.push(parsedUrl.pathname); + } + }); + + links = [...new Set(links)].filter((link) => { + return ( + !link.includes("#") && + !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) + ); + }); + return { html, links }; + } + + private splitUrl(url: URL) { + const baseUrl = new URL("/", url).href; + const basePath = url.pathname; + return { baseUrl, basePath }; + } +} diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts new file mode 100644 index 000000000..1b4dbab01 --- /dev/null +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -0,0 +1,260 @@ +import * as fs from "fs"; +import { URL } from "node:url"; +import { Handler, HTTPResponse, Page } from "puppeteer"; +import { + editConfigJson, + getChromiumPath, + getContinueUtilsPath, +} from "../../../util/paths"; +// @ts-ignore +// @prettier-ignore +import PCR from "puppeteer-chromium-resolver"; +import { ContinueConfig, IDE } from "../../.."; +import { PageData } from "../DocsCrawler"; + +export class ChromiumCrawler { + private readonly LINK_GROUP_SIZE = 2; + private curCrawlCount = 0; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + ) {} + + static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { + editConfigJson((config) => ({ + ...config, + experimental: { + ...config.experimental, + useChromiumForDocsCrawling, + }, + })); + } + + async *crawl(): AsyncGenerator { + console.debug( + `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, + ); + + const stats = await PCR(ChromiumInstaller.PCR_CONFIG); + const browser = await stats.puppeteer.launch({ + args: [ + "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", + ], + executablePath: stats.executablePath, + }); + const page = await browser.newPage(); + + try { + yield* this.crawlSitePages(page, this.startUrl); + } catch (e) { + console.debug("Error getting links: ", e); + console.debug( + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + } finally { + await browser.close(); + } + } + + /** + * We need to handle redirects manually, otherwise there are race conditions. + * + * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 + */ + private async gotoPageAndHandleRedirects(page: Page, url: string) { + const MAX_PAGE_WAIT_MS = 5000; + + await page.goto(url, { + timeout: 0, + waitUntil: "networkidle2", + }); + + let responseEventOccurred = false; + const responseHandler: Handler = (event) => + (responseEventOccurred = true); + + const responseWatcher = new Promise(function (resolve, reject) { + setTimeout(() => { + if (!responseEventOccurred) { + resolve(); + } else { + setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); + } + }, 500); + }); + + page.on("response", responseHandler); + + await Promise.race([responseWatcher, page.waitForNavigation()]); + } + + private async *crawlSitePages( + page: Page, + curUrl: URL, + visitedLinks: Set = new Set(), + ): AsyncGenerator { + const urlStr = curUrl.toString(); + + if (visitedLinks.has(urlStr)) { + return; + } + + await this.gotoPageAndHandleRedirects(page, urlStr); + + const htmlContent = await page.content(); + const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); + this.curCrawlCount++; + + visitedLinks.add(urlStr); + + yield { + path: curUrl.pathname, + url: urlStr, + content: htmlContent, + }; + + for (const linkGroup of linkGroups) { + let enqueuedLinkCount = this.curCrawlCount; + + for (const link of linkGroup) { + enqueuedLinkCount++; + console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); + if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { + yield* this.crawlSitePages(page, new URL(link), visitedLinks); + } + } + } + } + + private stripHashFromUrl(urlStr: string) { + try { + let url = new URL(urlStr); + url.hash = ""; + return url; + } catch (err) { + return null; + } + } + + private isValidHostAndPath(newUrl: URL, curUrl: URL) { + return ( + newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host + ); + } + + private async getLinksFromPage(page: Page, curUrl: URL) { + const links = await page.$$eval("a", (links) => links.map((a) => a.href)); + + const cleanedLinks = links + .map(this.stripHashFromUrl) + .filter( + (newUrl) => + newUrl !== null && + this.isValidHostAndPath(newUrl, curUrl) && + newUrl !== curUrl, + ) + .map((newUrl) => (newUrl as URL).href); + + const dedupedLinks = Array.from(new Set(cleanedLinks)); + + return dedupedLinks; + } + + private async getLinkGroupsFromPage(page: Page, curUrl: URL) { + const links = await this.getLinksFromPage(page, curUrl); + + const groups = links.reduce((acc, link, i) => { + const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); + + if (!acc[groupIndex]) { + acc.push([]); + } + + acc[groupIndex].push(link); + + return acc; + }, [] as string[][]); + + return groups; + } +} + +export class ChromiumInstaller { + static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; + + constructor( + private readonly ide: IDE, + private readonly config: ContinueConfig, + ) { + if (this.shouldInstallOnStartup()) { + console.log("Installing Chromium"); + void this.install(); + } + } + + isInstalled() { + return fs.existsSync(getChromiumPath()); + } + + shouldInstallOnStartup() { + return ( + !this.isInstalled() && + this.config.experimental?.useChromiumForDocsCrawling + ); + } + + shouldProposeUseChromiumOnCrawlFailure() { + const { experimental } = this.config; + + return ( + experimental?.useChromiumForDocsCrawling === undefined || + experimental.useChromiumForDocsCrawling + ); + } + + async proposeAndAttemptInstall(site: string) { + const userAcceptedInstall = await this.proposeInstall(site); + + if (userAcceptedInstall) { + const didInstall = await this.install(); + return didInstall; + } + } + + async install() { + try { + await PCR(ChromiumInstaller.PCR_CONFIG); + + ChromiumCrawler.setUseChromiumForDocsCrawling(true); + + return true; + } catch (error) { + console.debug("Error installing Chromium : ", error); + console.debug( + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + + await this.ide.showToast("error", "Failed to install Chromium"); + + return false; + } + } + + private async proposeInstall(site: string) { + const msg = + `Unable to crawl documentation site: ${site}\n` + + "We recommend installing Chromium. " + + "Download progress can be viewed in the developer console."; + + const actionMsg = "Install Chromium"; + + const res = await this.ide.showToast("warning", msg, actionMsg); + + return res === actionMsg; + } +} diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts new file mode 100644 index 000000000..64a65c8fd --- /dev/null +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -0,0 +1,25 @@ +import { URL } from "node:url"; +import { getHeaders } from "../../../continueServer/stubs/headers"; +import { TRIAL_PROXY_URL } from "../../../control-plane/client"; +import { PageData } from "../DocsCrawler"; + +export class DefaultCrawler { + constructor(private readonly startUrl: URL) {} + + async crawl(): Promise { + const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ startUrl: this.startUrl.toString() }), + }); + if (!resp.ok) { + const text = await resp.text(); + throw new Error(`Failed to crawl site: ${text}`); + } + const json = (await resp.json()) as PageData[]; + return json; + } +} diff --git a/core/indexing/docs/crawlers/GitHubCrawler.ts b/core/indexing/docs/crawlers/GitHubCrawler.ts new file mode 100644 index 000000000..41362cf72 --- /dev/null +++ b/core/indexing/docs/crawlers/GitHubCrawler.ts @@ -0,0 +1,80 @@ +import { Octokit } from "@octokit/rest"; +import { URL } from "node:url"; +import { PageData } from "../DocsCrawler"; + +class GitHubCrawler { + private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); + private octokit = new Octokit({ auth: undefined }); + + constructor(private readonly startUrl: URL) {} + + async *crawl(): AsyncGenerator { + console.debug( + `[${ + (this.constructor as any).name + }] Crawling GitHub repo: ${this.startUrl.toString()}`, + ); + const urlStr = this.startUrl.toString(); + const [_, owner, repo] = this.startUrl.pathname.split("/"); + const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); + + for await (const path of paths) { + const content = await this.getGithubRepoFileContent(path, owner, repo); + yield { path, url: urlStr, content: content ?? "" }; + } + } + + private async getGithubRepoDefaultBranch( + owner: string, + repo: string, + ): Promise { + const repoInfo = await this.octokit.repos.get({ owner, repo }); + return repoInfo.data.default_branch; + } + + private async getGitHubRepoPaths( + owner: string, + repo: string, + branch: string, + ) { + const tree = await this.octokit.request( + "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", + { + owner, + repo, + tree_sha: branch, + headers: { "X-GitHub-Api-Version": "2022-11-28" }, + recursive: "true", + }, + ); + + return tree.data.tree + .filter( + (file: any) => + file.type === "blob" && this.markdownRegex.test(file.path ?? ""), + ) + .map((file: any) => file.path); + } + + private async getGithubRepoFileContent( + path: string, + owner: string, + repo: string, + ) { + try { + const response = await this.octokit.repos.getContent({ + owner, + repo, + path, + headers: { Accept: "application/vnd.github.raw+json" }, + }); + return response.data as unknown as string; + } catch (error) { + console.debug("Error fetching file contents:", error); + return null; + } + } +} + +export default GitHubCrawler; diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 83b439d42..48b777b21 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -299,30 +299,32 @@ const preIndexedDocs: Record< rootUrl: "https://docs.godotengine.org/en/latest/", faviconUrl: "https://godotengine.org/favicon.ico", }, - "https://docs.amplify.aws/react/": { + "https://docs.amplify.aws/react/start/": { title: "AWS Amplify (Gen 2)", startUrl: "https://docs.amplify.aws/react/start/", rootUrl: "https://docs.amplify.aws/react/", - faviconUrl: "https://docs.amplify.aws/favicon.ico" + faviconUrl: "https://docs.amplify.aws/favicon.ico", }, "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": { title: "AWS SDK for JavaScript v3", startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", - faviconUrl: "https://docs.aws.amazon.com/favicon.ico" + faviconUrl: "https://docs.aws.amazon.com/favicon.ico", }, "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": { title: "AWS CDK v2", - startUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html", + startUrl: + "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html", rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/", - faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png" + faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png", }, "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": { title: "AWS CLI commands", - startUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html", + startUrl: + "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html", rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/", - faviconUrl: "https://docs.aws.amazon.com/favicon.ico" - } + faviconUrl: "https://docs.aws.amazon.com/favicon.ico", + }, }; export default preIndexedDocs; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index c6b1874c3..64e0634a5 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -146,7 +146,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("command") || lower.includes("chat-bison") || lower.includes("pplx") || - lower.includes("gemini") + lower.includes("gemini") || + lower.includes("grok") ) { return undefined; } diff --git a/core/llm/index.ts b/core/llm/index.ts index c3680aae7..4d3f2fd6e 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -501,15 +501,20 @@ export abstract class BaseLLM implements ILLM { } let completion = ""; - for await (const chunk of this._streamComplete(prompt, completionOptions)) { - completion += chunk; - yield chunk; - } + try { + for await (const chunk of this._streamComplete( + prompt, + completionOptions, + )) { + completion += chunk; + yield chunk; + } + } finally { + this._logTokensGenerated(completionOptions.model, prompt, completion); - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (log && this.writeLog) { - await this.writeLog(`Completion:\n\n${completion}\n\n`); + if (log && this.writeLog) { + await this.writeLog(`Completion:\n\n${completion}\n\n`); + } } return { diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 2ad990e98..eaedde8de 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -11,16 +11,17 @@ import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { static providerName: ModelProvider = "anthropic"; static defaultOptions: Partial = { - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", contextLength: 200_000, completionOptions: { - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", maxTokens: 4096, }, apiBase: "https://api.anthropic.com/v1/", }; - public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI + public convertArgs(options: CompletionOptions) { + // should be public for use within VertexAI const finalOptions = { top_k: options.topK, top_p: options.topP, @@ -34,53 +35,61 @@ class Anthropic extends BaseLLM { return finalOptions; } - public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI - const filteredmessages = msgs.filter((m) => m.role !== "system") - const lastTwoUserMsgIndices = filteredmessages + public convertMessages(msgs: ChatMessage[]): any[] { + // should be public for use within VertexAI + const filteredmessages = msgs.filter((m) => m.role !== "system"); + const lastTwoUserMsgIndices = filteredmessages .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1).slice(-2); + .filter((index) => index !== -1) + .slice(-2); const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching + const addCaching = + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(filteredMsgIdx); - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [{ - type: "text", - text: message.content, - ...(addCaching? { cache_control: { type: "ephemeral" } } : {}) - }] - }; - return chatMessage; - } - - return { + if (typeof message.content === "string") { + var chatMessage = { ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), + content: [ + { + type: "text", + text: message.content, + ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), + }, + ], }; - }); + return chatMessage; + } + + return { + ...message, + content: message.content.map((part, contentIdx) => { + if (part.type === "text") { + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...(addCaching && contentIdx == message.content.length - 1 + ? { cache_control: { type: "ephemeral" } } + : {}), + }; + return newpart; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; + }); return messages; } @@ -98,7 +107,8 @@ class Anthropic extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const shouldCacheSystemMessage = + !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; const systemMessage: string = stripImages( messages.filter((m) => m.role === "system")[0]?.content, ); diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index e3dcdfef7..46d46046c 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -164,7 +164,7 @@ class FreeTrial extends BaseLLM { async listModels(): Promise { return [ "codestral-latest", - "claude-3-5-sonnet-20240620", + "claude-3-5-sonnet-latest", "llama3.1-405b", "llama3.1-70b", "gpt-4o", diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 4a6b1d539..64882b09b 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -45,6 +45,7 @@ import WatsonX from "./WatsonX"; import ContinueProxy from "./stubs/ContinueProxy"; import VertexAI from "./VertexAI"; import Asksage from "./Asksage"; +import xAI from "./xAI"; const LLMs = [ Anthropic, @@ -84,7 +85,8 @@ const LLMs = [ Cerebras, Asksage, Nebius, - VertexAI + VertexAI, + xAI ]; export async function llmFromDescription( diff --git a/core/llm/llms/xAI.ts b/core/llm/llms/xAI.ts new file mode 100644 index 000000000..aa33ee70d --- /dev/null +++ b/core/llm/llms/xAI.ts @@ -0,0 +1,20 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; + +import OpenAI from "./OpenAI.js"; + +class xAI extends OpenAI { + static providerName: ModelProvider = "xAI"; + static defaultOptions: Partial = { + apiBase: "https://api.x.ai/v1/", + }; + + private static MODEL_IDS: { [name: string]: string } = { + "grok-beta": "grok-beta", // Future names might not line up + }; + + protected _convertModelName(model: string) { + return xAI.MODEL_IDS[model] || this.model; + } +} + +export default xAI; 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 b5d18e1e8..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 } 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]; @@ -35,8 +41,23 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { setGitHubAuthToken: [{ token: string }, void]; acceptDiff: [{ filepath: string }, void]; rejectDiff: [{ filepath: string }, void]; + "edit/sendPrompt": [ + { prompt: MessageContent; range: RangeInFileWithContents }, + void, + ]; + "edit/acceptReject": [ + { accept: boolean; onlyFirst: boolean; filepath: string }, + void, + ]; + "edit/escape": [undefined, void]; }; +export interface EditModeArgs { + highlightedCode: RangeInFileWithContents; +} + +export type EditStatus = "not-started" | "streaming" | "accepting" | "done"; + export interface ApplyState { streamId: string; status: "streaming" | "done" | "closed"; @@ -44,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[] }, @@ -82,4 +102,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { openOnboardingCard: [undefined, void]; applyCodeFromChat: [undefined, void]; updateApplyState: [ApplyState, void]; + startEditMode: [EditModeArgs, void]; + setEditStatus: [{ status: EditStatus }, void]; + exitEditMode: [undefined, void]; }; 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/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 6e9dbcf22..bf968ad12 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -25,7 +25,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz { "title": "Claude 3.5 Sonnet", "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "apiKey": "[ANTHROPIC_API_KEY]" } ] diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index 96604ca70..58612106d 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -6,7 +6,7 @@ toc_max_heading_level: 5 # @Docs -The [`@Docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. +The [`@Docs` context provider](customize/context-providers.md#docs) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. ## Enabling the `@Docs` context provider diff --git a/docs/docs/customize/model-providers/top-level/anthropic.md b/docs/docs/customize/model-providers/top-level/anthropic.md index c4bb24a4c..9333a8e84 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.md +++ b/docs/docs/customize/model-providers/top-level/anthropic.md @@ -19,7 +19,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. { "title": "Claude 3.5 Sonnet", "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "apiKey": "[API_KEY]" } ] @@ -61,7 +61,7 @@ To enable caching of the system message and the turn-by-turn conversation, updat }, "title": "Anthropic", "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "apiKey": "[API_KEY]" } ] diff --git a/docs/docs/customize/model-providers/top-level/xAI.md b/docs/docs/customize/model-providers/top-level/xAI.md new file mode 100644 index 000000000..fbdfa83ad --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/xAI.md @@ -0,0 +1,53 @@ +--- +title: xAI +slug: ../xai +--- + +:::info + +You can get an API key from the [xAI console](https://console.x.ai/) + +::: + +## Chat model + +We recommend configuring **grok-beta** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Legacy Completions + +To force usage of `chat/completions` instead of `completions` endpoint you can set + +```json +"useLegacyCompletionsEndpoint": false +``` diff --git a/docs/docs/customize/model-types/reranking.md b/docs/docs/customize/model-types/reranking.md index 4aceade4a..a87918cb2 100644 --- a/docs/docs/customize/model-types/reranking.md +++ b/docs/docs/customize/model-types/reranking.md @@ -72,6 +72,7 @@ The `"modelTitle"` field must match one of the models in your "models" array in "name": "huggingface-tei", "params": { "apiBase": "http://localhost:8080", + "apiKey": "", "truncate": true, "truncation_direction": "Right" } diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 19e8f386e..391273943 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -421,7 +421,7 @@ Several experimental config parameters are available, as described below: - `fix`: Prompt for fixing code. - `optimize`: Prompt for optimizing code. - `fixGrammar`: Prompt for fixing grammar or spelling. -- `useChromiumForDocsCrawling`: Use chromium to crawl docs instead of default lighter-weight tool that can't render sites. Downloads and installs Chromium to `~/.continue/.utils`. +- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. Example diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index 9873b602d..13ca3bab9 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -1,2 +1,5 @@ src/main/resources/webview -src/main/resources/bin \ No newline at end of file +!src/main/resources/webview/index.html +src/main/resources/bin +src/main/resources/config_schema.json +src/main/resources/continue_rc_schema.json \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt index 5a1b8af0e..cdcb58c18 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt @@ -14,7 +14,7 @@ const val DEFAULT_CONFIG = { "models": [ { - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "provider": "anthropic", "apiKey": "", "title": "Claude 3.5 Sonnet" 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 index e4e21b957..2056d216e 100644 --- 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 @@ -22,7 +22,7 @@ class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory { class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider { override fun isAvailable(file: VirtualFile): Boolean { - return file.path.endsWith(".continue/config.json") + return file.path.endsWith("/.continue/config.json") } override fun getName(): String { 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/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index f73ba509c..5db34ff29 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -2,10 +2,12 @@ package com.github.continuedev.continueintellijextension.services import com.github.continuedev.continueintellijextension.constants.getConfigJsPath import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath +import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.util.SystemInfo import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.messages.Topic import kotlinx.serialization.Serializable @@ -28,6 +30,7 @@ class ContinueSettingsComponent : DumbAware { val userToken: JTextField = JTextField() val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete") val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta") + val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering") val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip") init { @@ -56,6 +59,8 @@ class ContinueSettingsComponent : DumbAware { constraints.gridy++ panel.add(enableContinueTeamsBeta, constraints) constraints.gridy++ + panel.add(enableOSR, constraints) + constraints.gridy++ panel.add(displayEditorTooltip, constraints) constraints.gridy++ @@ -87,6 +92,7 @@ open class ContinueExtensionSettings : PersistentStateComponent= minBuildNumber +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 03d4f4715..7891a02dc 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath import com.github.continuedev.continueintellijextension.`continue`.* import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson import com.google.gson.JsonObject @@ -78,7 +79,8 @@ class ContinueBrowser(val project: Project, url: String) { val browser: JBCefBrowser init { - this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(shouldRenderOffScreen()).build() + val enableOSR = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(enableOSR).build() browser.jbCefClient.setProperty( @@ -274,34 +276,4 @@ class ContinueBrowser(val project: Project, url: String) { return """window.postMessage($jsonData, "*");""" } - /** - * This function checks if the pluginSinceBuild is greater than or equal to 233, which corresponds - * to IntelliJ platform version 2023.3 and later. - * - * Setting `setOffScreenRendering` to `false` causes a number of issues such as a white screen flash when loading - * the GUI and the inability to set `cursor: pointer`. However, setting `setOffScreenRendering` to `true` on - * platform versions prior to 2023.3.4 causes larger issues such as an inability to type input for certain langauges, - * e.g. Korean. - * - * References: - * 1. https://youtrack.jetbrains.com/issue/IDEA-347828/JCEF-white-flash-when-tool-window-show#focus=Comments-27-9334070.0-0 - * This issue mentions that white screen flash problems were resolved in platformVersion 2023.3.4. - * 2. https://www.jetbrains.com/idea/download/other.html - * This documentation shows mappings from platformVersion to branchNumber. - * - * We use the branchNumber (e.g., 233) instead of the full version number (e.g., 2023.3.4) because - * it's a simple integer without dot notation, making it easier to compare. - */ - private fun shouldRenderOffScreen(): Boolean { - // With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality - // in the browser. Disabling OSR for all non-Mac users for now. - if (!SystemInfo.isMac) { - return false - } - - val minBuildNumber = 233 - val applicationInfo = ApplicationInfo.getInstance() - val currentBuildNumber = applicationInfo.build.baselineVersion - return currentBuildNumber >= minBuildNumber - } } diff --git a/extensions/intellij/src/main/resources/icons/continue.svg b/extensions/intellij/src/main/resources/icons/continue.svg deleted file mode 100644 index ab3f4d8bb..000000000 --- a/extensions/intellij/src/main/resources/icons/continue.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/extensions/vscode/.continuerc.json b/extensions/vscode/.continuerc.json deleted file mode 100644 index 2533f4d69..000000000 --- a/extensions/vscode/.continuerc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "customCommands": [] -} diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index d9ea895e4..e0a5e65fc 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -10,8 +10,10 @@ exe bin assets -gui/* +gui/** !gui/onigasm.wasm .devcontainer -.github \ No newline at end of file +.github + +continue_rc_schema.json \ No newline at end of file diff --git a/extensions/vscode/.prompts/review.prompt b/extensions/vscode/.prompts/review.prompt deleted file mode 100644 index 85bbcad6e..000000000 --- a/extensions/vscode/.prompts/review.prompt +++ /dev/null @@ -1,28 +0,0 @@ -temperature: 0.0 ---- -{{{ diff }}} - -Give me feedback on the above changes. For each file, you should output a markdown section including the following: -- If you found any problems, an h3 like "❌ " -- If you didn't find any problems, an h3 like "✅ " -- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it -- If you didn't find any problems, you don't need to add anything else - -Here is an example. The example is surrounded in backticks, but your response should not be: - -``` -### ✅ - -### ❌ - - -``` - -You should look primarily for the following types of issues, and only mention other problems if they are highly pressing. - -- console.logs that have been left after debugging -- repeated code -- algorithmic errors that could fail under edge cases -- something that could be refactored - -Make sure to review ALL files that were changed, do not skip any. \ No newline at end of file diff --git a/extensions/vscode/.prompts/test.prompt b/extensions/vscode/.prompts/test.prompt deleted file mode 100644 index 369fe07dc..000000000 --- a/extensions/vscode/.prompts/test.prompt +++ /dev/null @@ -1,17 +0,0 @@ -temperature: 0.5 -maxTokens: 4096 ---- - -You are an expert programmer - - -{{{ input }}} - -Write unit tests for the above selected code, following each of these instructions: -- Use `jest` -- Properly set up and tear down -- Include important edge cases -- The tests should be complete and sophisticated -- Give the tests just as chat output, don't edit any file -- Don't explain how to set up `jest` -- Write a single code block, making sure to label with the language being used (e.g. "```typscript") \ No newline at end of file diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 18e606865..030da9bcc 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -5,6 +5,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). +Pre-release Changes +### Added +* New Edit mode in sidebar (cmd/ctrl+I) +* Significantly faster and more accurate docs crawler by default + ## 0.8.55 - 2024-10-25 ### Added * Web context provider diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f69ce7e5c..f18bdbb6a 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -201,7 +201,8 @@ "cerebras", "askSage", "nebius", - "vertexai" + "vertexai", + "xAI" ], "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://docs.continue.dev/reference/Model%20Providers/openai)", @@ -236,7 +237,8 @@ "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", - "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)" + "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)", + "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)" ], "type": "string" }, @@ -471,7 +473,8 @@ "together", "cloudflare", "sambanova", - "nebius" + "nebius", + "xAI" ] } }, @@ -655,6 +658,37 @@ } } }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "xAI" + ] + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "grok-beta", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] + } + } + } + }, { "if": { "properties": { @@ -719,7 +753,7 @@ "llama3.1-405b", "gpt-3.5-turbo", "gemini-pro", - "claude-3-5-sonnet-20240620", + "claude-3-5-sonnet-latest", "claude-3-haiku-20240307", "AUTODETECT" ] @@ -834,7 +868,7 @@ "enum": [ "claude-2", "claude-instant-1", - "claude-3-5-sonnet-20240620", + "claude-3-5-sonnet-latest", "claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307", @@ -1301,7 +1335,10 @@ ] }, "then": { - "required": ["deployment", "apiBase"] + "required": [ + "deployment", + "apiBase" + ] } }, { @@ -1491,6 +1528,7 @@ "deepseek-33b", "claude-2", "claude-instant-1", + "claude-3-5-sonnet-latest", "claude-3-5-sonnet-20240620", "claude-3-opus-20240229", "claude-3-sonnet-20240229", @@ -2962,6 +3000,9 @@ "type": "string", "default": "http://localhost:8080" }, + "apiKey": { + "type": "string" + }, "truncate": { "type": "boolean", "description": "Whether to truncate long sequences to the maximum allowed context length.", @@ -3279,6 +3320,11 @@ "default": "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing." } } + }, + "useChromiumForDocsCrawling": { + "type": "boolean", + "description": "Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.", + "default": false } } } diff --git a/extensions/vscode/gui/continue-dev-square.png b/extensions/vscode/gui/continue-dev-square.png deleted file mode 100644 index e4b625568..000000000 Binary files a/extensions/vscode/gui/continue-dev-square.png and /dev/null differ diff --git a/extensions/vscode/gui/continue.gif b/extensions/vscode/gui/continue.gif deleted file mode 100644 index daed66637..000000000 Binary files a/extensions/vscode/gui/continue.gif and /dev/null differ diff --git a/extensions/vscode/gui/index.html b/extensions/vscode/gui/index.html deleted file mode 100644 index c8053de74..000000000 --- a/extensions/vscode/gui/index.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - Continue - - - - -
- - - diff --git a/extensions/vscode/gui/logos/anthropic.png b/extensions/vscode/gui/logos/anthropic.png deleted file mode 100644 index 9adf1b71b..000000000 Binary files a/extensions/vscode/gui/logos/anthropic.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/google-palm.png b/extensions/vscode/gui/logos/google-palm.png deleted file mode 100644 index 0f9dc3451..000000000 Binary files a/extensions/vscode/gui/logos/google-palm.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/hf.png b/extensions/vscode/gui/logos/hf.png deleted file mode 100644 index 49e2841dd..000000000 Binary files a/extensions/vscode/gui/logos/hf.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/llamacpp.png b/extensions/vscode/gui/logos/llamacpp.png deleted file mode 100644 index 119087b0e..000000000 Binary files a/extensions/vscode/gui/logos/llamacpp.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/lmstudio.png b/extensions/vscode/gui/logos/lmstudio.png deleted file mode 100644 index b2b73591f..000000000 Binary files a/extensions/vscode/gui/logos/lmstudio.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/meta.png b/extensions/vscode/gui/logos/meta.png deleted file mode 100644 index 84a15698e..000000000 Binary files a/extensions/vscode/gui/logos/meta.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/mistral.png b/extensions/vscode/gui/logos/mistral.png deleted file mode 100644 index 0f535f84e..000000000 Binary files a/extensions/vscode/gui/logos/mistral.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/ollama.png b/extensions/vscode/gui/logos/ollama.png deleted file mode 100644 index 56ef23f4a..000000000 Binary files a/extensions/vscode/gui/logos/ollama.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/openai.png b/extensions/vscode/gui/logos/openai.png deleted file mode 100644 index e24b90113..000000000 Binary files a/extensions/vscode/gui/logos/openai.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/replicate.png b/extensions/vscode/gui/logos/replicate.png deleted file mode 100644 index f71504f59..000000000 Binary files a/extensions/vscode/gui/logos/replicate.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/together.png b/extensions/vscode/gui/logos/together.png deleted file mode 100644 index e989afdde..000000000 Binary files a/extensions/vscode/gui/logos/together.png and /dev/null differ diff --git a/extensions/vscode/gui/logos/wizardlm.png b/extensions/vscode/gui/logos/wizardlm.png deleted file mode 100644 index a420cf038..000000000 Binary files a/extensions/vscode/gui/logos/wizardlm.png and /dev/null differ diff --git a/extensions/vscode/gui/play_button.png b/extensions/vscode/gui/play_button.png deleted file mode 100644 index af3793758..000000000 Binary files a/extensions/vscode/gui/play_button.png and /dev/null differ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ab1d53f6e..3baee50b0 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.223", + "version": "0.9.227", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.223", + "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" @@ -12598,4 +12599,4 @@ } } } -} +} \ No newline at end of file diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 88a6e1bc8..231f856c1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.223", + "version": "0.9.227", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -182,6 +182,18 @@ "title": "Debug Terminal", "group": "Continue" }, + { + "command": "continue.edit", + "category": "Continue", + "title": "Edit code with natural language", + "group": "Continue" + }, + { + "command": "continue.exitEditMode", + "category": "Continue", + "title": "Exit Edit Mode", + "group": "Continue" + }, { "command": "continue.toggleFullScreen", "category": "Continue", @@ -339,9 +351,20 @@ }, { "command": "continue.quickEdit", + "mac": "cmd+shift+i", + "key": "ctrl+shift+i" + }, + { + "command": "continue.edit", "mac": "cmd+i", "key": "ctrl+i" }, + { + "command": "continue.exitEditMode", + "mac": "escape", + "key": "escape", + "when": "continue.inEditMode && editorFocus" + }, { "command": "continue.debugTerminal", "mac": "cmd+shift+r", diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index f3d2c09db..7e367bfaa 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -30,4 +30,5 @@ const esbuildConfig = { } else { await esbuild.build(esbuildConfig); } -})(); + console.log("VS Code Extension esbuild complete"); // Used in task endpattern to signal completion +})(); \ No newline at end of file diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index fc4e1e020..7d62fefa4 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -18,8 +18,8 @@ function copyConfigSchema() { enum: ["merge", "overwrite"], default: "merge", title: "Merge behavior", - markdownDescription: - "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.", + markdownDescription: "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.", + "x-intellij-html-description": "

If set to merge, .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to overwrite, then every top-level property of .continuerc.json will overwrite that property from config.json.

" }; fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); 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 2a93e9154..11c280678 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { ContextMenuConfig, IDE } 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"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -27,11 +28,13 @@ import { import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; import { DiffManager } from "./diff/horizontal"; import { VerticalDiffManager } from "./diff/vertical/manager"; +import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { VsCodeIde } from "./VsCodeIde"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -88,20 +91,20 @@ function addCodeToContextFromRange( }); } -async function addHighlightedCodeToContext( - webviewProtocol: VsCodeWebviewProtocol | undefined, -) { +function getCurrentlyHighlightedCode( + allowEmpty?: boolean, +): RangeInFileWithContents | null { const editor = vscode.window.activeTextEditor; if (editor) { const selection = editor.selection; - if (selection.isEmpty) { - return; + if (selection.isEmpty && !allowEmpty) { + return null; } // adjust starting position to include indentation const start = new vscode.Position(selection.start.line, 0); const range = new vscode.Range(start, selection.end); const contents = editor.document.getText(range); - const rangeInFileWithContents = { + return { filepath: editor.document.uri.fsPath, contents, range: { @@ -115,7 +118,15 @@ async function addHighlightedCodeToContext( }, }, }; + } + return null; +} +async function addHighlightedCodeToContext( + webviewProtocol: VsCodeWebviewProtocol | undefined, +) { + const rangeInFileWithContents = getCurrentlyHighlightedCode(); + if (rangeInFileWithContents) { webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, }); @@ -167,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, @@ -188,6 +212,7 @@ const commandsMap: ( battery: Battery, quickEdit: QuickEdit, core: Core, + editDecorationManager: EditDecorationManager, ) => { [command: string]: (...args: any) => any } = ( ide, extensionContext, @@ -199,549 +224,595 @@ const commandsMap: ( battery, quickEdit, core, + editDecorationManager, ) => { - /** - * Streams an inline edit to the vertical diff manager. - * - * This function retrieves the configuration, determines the appropriate model title, - * increments the FTC count, and then streams an edit to the - * vertical diff manager. - * - * @param promptName - The key for the prompt in the context menu configuration. - * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. - * @param [range] - Optional. The range to edit if provided. - * @returns - */ - async function streamInlineEdit( - promptName: keyof ContextMenuConfig, - fallbackPrompt: string, - onlyOneInsertion?: boolean, - range?: vscode.Range, - ) { - const config = await configHandler.loadConfig(); + /** + * Streams an inline edit to the vertical diff manager. + * + * This function retrieves the configuration, determines the appropriate model title, + * increments the FTC count, and then streams an edit to the + * vertical diff manager. + * + * @param promptName - The key for the prompt in the context menu configuration. + * @param fallbackPrompt - The prompt to use if the configured prompt is not available. + * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. + * @param [range] - Optional. The range to edit if provided. + * @returns + */ + async function streamInlineEdit( + promptName: keyof ContextMenuConfig, + fallbackPrompt: string, + onlyOneInsertion?: boolean, + range?: vscode.Range, + ) { + const config = await configHandler.loadConfig(); - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ); - - const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - - sidebar.webviewProtocol.request("incrementFtc", undefined); - - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, - onlyOneInsertion, - undefined, - range, - ); - } - - return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("acceptDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else { - fullPath = getFullyQualifiedPath(fullPath); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else { - fullPath = getFullyQualifiedPath(fullPath); - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - }, - "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("acceptVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); - }, - "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("rejectVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); - }, - "continue.quickFix": async ( - range: vscode.Range, - diagnosticMessage: string, - ) => { - captureCommandTelemetry("quickFix"); - - const prompt = `How do I fix the following problem in the above code?: ${diagnosticMessage}`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - // Passthrough for telemetry purposes - "continue.defaultQuickAction": async (args: QuickEditShowParams) => { - captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); - }, - "continue.customQuickActionSendToChat": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionSendToChat"); - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - "continue.customQuickActionStreamInlineEdit": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionStreamInlineEdit"); - - streamInlineEdit("docstring", prompt, false, range); - }, - "continue.codebaseForceReIndex": async () => { - core.invoke("index/forceReIndex", undefined); - }, - "continue.rebuildCodebaseIndex": async () => { - core.invoke("index/forceReIndex", { shouldClearIndexes: true }); - }, - "continue.docsIndex": async () => { - core.invoke("context/indexDocs", { reIndex: false }); - }, - "continue.docsReIndex": async () => { - core.invoke("context/indexDocs", { reIndex: true }); - }, - "continue.focusContinueInput": async () => { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - }, - "continue.focusContinueInputWithoutClear": async () => { - const fullScreenTab = getFullScreenTab(); - - const isContinueInputFocused = await sidebar.webviewProtocol.request( - "isContinueInputFocused", + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", undefined, ); - if (isContinueInputFocused) { - // Handle closing the GUI only if we are focused on the input - if (fullScreenTab) { - fullScreenPanel?.dispose(); - } - } else { - // Handle opening the GUI otherwise - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); + const modelTitle = + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + + sidebar.webviewProtocol.request("incrementFtc", undefined); + + await verticalDiffManager.streamEdit( + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + modelTitle, + undefined, + onlyOneInsertion, + undefined, + range, + ); + } + + return { + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - // focus fullscreen - fullScreenPanel?.reveal(); + console.warn(`Unable to resolve filepath: ${newFilepath}`); } - sidebar.webviewProtocol?.request( - "focusContinueInputWithoutClear", - undefined, - ); - - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - captureCommandTelemetry("quickEdit"); - quickEdit.show(args); - }, - "continue.writeCommentsForCode": async () => { - captureCommandTelemetry("writeCommentsForCode"); - - streamInlineEdit( - "comment", - "Write comments for this code. Do not change anything about the code itself.", - ); - }, - "continue.writeDocstringForCode": async () => { - captureCommandTelemetry("writeDocstringForCode"); - - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - ); - }, - "continue.fixCode": async () => { - captureCommandTelemetry("fixCode"); - - streamInlineEdit( - "fix", - "Fix this code. If it is already 100% correct, simply rewrite the code.", - ); - }, - "continue.optimizeCode": async () => { - captureCommandTelemetry("optimizeCode"); - streamInlineEdit("optimize", "Optimize this code"); - }, - "continue.fixGrammar": async () => { - captureCommandTelemetry("fixGrammar"); - streamInlineEdit( - "fixGrammar", - "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", - ); - }, - "continue.viewLogs": async () => { - captureCommandTelemetry("viewLogs"); - - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } - - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); - }, - "continue.debugTerminal": async () => { - captureCommandTelemetry("debugTerminal"); - - const terminalContents = await ide.getTerminalContents(); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - sidebar.webviewProtocol?.request("userInput", { - input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, - }); - }, - "continue.hideInlineTip": () => { - vscode.workspace - .getConfiguration(EXTENSION_NAME) - .update("showInlineTip", false, vscode.ConfigurationTarget.Global); - }, - - // Commands without keyboard shortcuts - "continue.addModel": () => { - captureCommandTelemetry("addModel"); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("addModel", undefined); - }, - "continue.openSettingsUI": () => { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("openSettings", undefined); - }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, - "continue.newSession": () => { - sidebar.webviewProtocol?.request("newSession", undefined); - }, - "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); - }, - "continue.focusContinueSessionId": async (sessionId: string | undefined) => { - if (!sessionId) { - sessionId = await vscode.window.showInputBox({ - prompt: "Enter the Session ID" + verticalDiffManager.clearForFilepath(fullPath, true); + await diffManager.acceptDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", }); - } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); - }, - "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); - }, - "continue.toggleFullScreen": () => { - focusGUI(); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); - // Check if full screen is already open by checking open tabs - const fullScreenTab = getFullScreenTab(); + let fullPath = newFilepath; - if (fullScreenTab && fullScreenPanel) { - //Full screen open, but not focused - focus it - fullScreenPanel.reveal(); - return; - } + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + return; + } - //Full screen not open - open it - captureCommandTelemetry("openFullScreen"); + verticalDiffManager.clearForFilepath(fullPath, false); + await diffManager.rejectDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("acceptVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); + }, + "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("rejectVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); + }, + "continue.quickFix": async ( + range: vscode.Range, + diagnosticMessage: string, + ) => { + captureCommandTelemetry("quickFix"); - //create the full screen panel - let panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - { - retainContextWhenHidden: true, - }, - ); - fullScreenPanel = panel; + const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; - //Add content to the panel - panel.webview.html = sidebar.getSidebarContent( - extensionContext, - panel, - undefined, - undefined, - true, - ); + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - //When panel closes, reset the webview and focus - panel.onDidDispose( - () => { - sidebar.resetWebviewProtocolWebview(); - vscode.commands.executeCommand("continue.focusContinueInput"); - }, - null, - extensionContext.subscriptions, - ); + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); - vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); - }, - "continue.openConfigJson": () => { - ide.openFile(getConfigJsonPath()); - }, - "continue.selectFilesAsContext": async ( - firstUri: vscode.Uri, - uris: vscode.Uri[], - ) => { - if (uris === undefined) { - throw new Error("No files were selected"); - } + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - vscode.commands.executeCommand("continue.continueGUIView.focus"); + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); - for (const uri of uris) { - // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) - const isDirectory = await vscode.workspace.fs - .stat(uri) - ?.then((stat) => stat.type === vscode.FileType.Directory); - if (isDirectory) { - for await (const filepath of walkDirAsync(uri.fsPath, ide)) { - addEntireFileToContext( - uriFromFilePath(filepath), - false, - sidebar.webviewProtocol, - ); + streamInlineEdit("docstring", prompt, false, range); + }, + "continue.codebaseForceReIndex": async () => { + core.invoke("index/forceReIndex", undefined); + }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", { reIndex: false }); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", { reIndex: true }); + }, + "continue.focusContinueInput": async () => { + const historyLength = await sidebar.webviewProtocol.request("getWebviewHistoryLength", undefined); + const isContinueInputFocused = await sidebar.webviewProtocol.request("isContinueInputFocused", undefined); + + if (isContinueInputFocused) { + if (historyLength === 0) { + hideGUI(); + } else { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); } } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); } - } - }, - "continue.logAutocompleteOutcome": ( - completionId: string, - completionProvider: CompletionProvider, - ) => { - completionProvider.accept(completionId); - }, - "continue.toggleTabAutocompleteEnabled": () => { - captureCommandTelemetry("toggleTabAutocompleteEnabled"); + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request("isContinueInputFocused", undefined); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const enabled = config.get("enableTabAutocomplete"); - const pauseOnBattery = config.get( - "pauseTabAutocompleteOnBattery", - ); - if (!pauseOnBattery || battery.isACConnected()) { - config.update( - "enableTabAutocomplete", - !enabled, - vscode.ConfigurationTarget.Global, + if (isContinueInputFocused) { + hideGUI(); + } else { + focusGUI(); + + sidebar.webviewProtocol?.request("focusContinueInputWithoutClear", undefined); + + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.edit": async () => { + captureCommandTelemetry("edit"); + focusGUI(); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + editDecorationManager.setDecoration( + editor, + new vscode.Range(editor.selection.start, editor.selection.end), ); - } else { - if (enabled) { - const paused = getStatusBarStatus() === StatusBarStatus.Paused; - if (paused) { - setupStatusBar(StatusBarStatus.Enabled); + + const highlightedCode = getCurrentlyHighlightedCode(true)!; + await sidebar.webviewProtocol?.request("startEditMode", { + highlightedCode, + }); + + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); + + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + }, + "continue.exitEditMode": async () => { + captureCommandTelemetry("exitEditMode"); + await sidebar.webviewProtocol?.request("exitEditMode", undefined); + }, + "continue.quickEdit": async (args: QuickEditShowParams) => { + let linesOfCode = undefined; + if (args.range) { + linesOfCode = args.range.end.line - args.range.start.line; + } + captureCommandTelemetry("quickEdit", { + linesOfCode, + }); + quickEdit.show(args); + }, + "continue.writeCommentsForCode": async () => { + captureCommandTelemetry("writeCommentsForCode"); + + streamInlineEdit( + "comment", + "Write comments for this code. Do not change anything about the code itself.", + ); + }, + "continue.writeDocstringForCode": async () => { + captureCommandTelemetry("writeDocstringForCode"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + ); + }, + "continue.fixCode": async () => { + captureCommandTelemetry("fixCode"); + + streamInlineEdit( + "fix", + "Fix this code. If it is already 100% correct, simply rewrite the code.", + ); + }, + "continue.optimizeCode": async () => { + captureCommandTelemetry("optimizeCode"); + streamInlineEdit("optimize", "Optimize this code"); + }, + "continue.fixGrammar": async () => { + captureCommandTelemetry("fixGrammar"); + streamInlineEdit( + "fixGrammar", + "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", + ); + }, + "continue.viewLogs": async () => { + captureCommandTelemetry("viewLogs"); + + // Open ~/.continue/continue.log + const logFile = path.join(os.homedir(), ".continue", "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFile)) { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, ""); + } + + const uri = vscode.Uri.file(logFile); + await vscode.window.showTextDocument(uri); + }, + "continue.debugTerminal": async () => { + captureCommandTelemetry("debugTerminal"); + + const terminalContents = await ide.getTerminalContents(); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, + }); + }, + "continue.hideInlineTip": () => { + vscode.workspace + .getConfiguration(EXTENSION_NAME) + .update("showInlineTip", false, vscode.ConfigurationTarget.Global); + }, + + // Commands without keyboard shortcuts + "continue.addModel": () => { + captureCommandTelemetry("addModel"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("addModel", undefined); + }, + "continue.openSettingsUI": () => { + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("openSettings", undefined); + }, + "continue.sendMainUserInput": (text: string) => { + sidebar.webviewProtocol?.request("userInput", { + input: text, + }); + }, + "continue.selectRange": (startLine: number, endLine: number) => { + if (!vscode.window.activeTextEditor) { + return; + } + vscode.window.activeTextEditor.selection = new vscode.Selection( + startLine, + 0, + endLine, + 0, + ); + }, + "continue.foldAndUnfold": ( + foldSelectionLines: number[], + unfoldSelectionLines: number[], + ) => { + vscode.commands.executeCommand("editor.unfold", { + selectionLines: unfoldSelectionLines, + }); + vscode.commands.executeCommand("editor.fold", { + selectionLines: foldSelectionLines, + }); + }, + "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); + ide.runCommand(text); + }, + "continue.newSession": () => { + sidebar.webviewProtocol?.request("newSession", undefined); + }, + "continue.viewHistory": () => { + sidebar.webviewProtocol?.request("viewHistory", undefined); + }, + "continue.focusContinueSessionId": async ( + sessionId: string | undefined, + ) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID", + }); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, + "continue.applyCodeFromChat": () => { + sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + }, + "continue.toggleFullScreen": () => { + focusGUI(); + + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); + + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } + + // Full screen not open - open it + captureCommandTelemetry("openFullScreen"); + + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + }, + ); + fullScreenPanel = panel; + + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); + + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); + + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, + "continue.selectFilesAsContext": async ( + firstUri: vscode.Uri, + uris: vscode.Uri[], + ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + for (const uri of uris) { + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); + } } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); + } + } + }, + "continue.logAutocompleteOutcome": ( + completionId: string, + completionProvider: CompletionProvider, + ) => { + completionProvider.accept(completionId); + }, + "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); + + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const enabled = config.get("enableTabAutocomplete"); + const pauseOnBattery = config.get( + "pauseTabAutocompleteOnBattery", + ); + if (!pauseOnBattery || battery.isACConnected()) { + config.update( + "enableTabAutocomplete", + !enabled, + vscode.ConfigurationTarget.Global, + ); + } else { + if (enabled) { + const paused = getStatusBarStatus() === StatusBarStatus.Paused; + if (paused) { + setupStatusBar(StatusBarStatus.Enabled); + } else { + config.update( + "enableTabAutocomplete", + false, + vscode.ConfigurationTarget.Global, + ); + } + } else { + setupStatusBar(StatusBarStatus.Paused); config.update( "enableTabAutocomplete", - false, + true, vscode.ConfigurationTarget.Global, ); } + } + }, + "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); + + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const quickPick = vscode.window.createQuickPick(); + const autocompleteModels = + (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + + let selected = new GlobalContext().get("selectedTabAutocompleteModel"); + if ( + !selected || + !autocompleteModels.some((model) => model.title === selected) + ) { + selected = autocompleteModels[0].title; + } + + // Toggle between Disabled, Paused, and Enabled + const pauseOnBattery = + config.get("pauseTabAutocompleteOnBattery") && + !battery.isACConnected(); + const currentStatus = getStatusBarStatus(); + + let targetStatus: StatusBarStatus | undefined; + if (pauseOnBattery) { + // Cycle from Disabled -> Paused -> Enabled + targetStatus = + currentStatus === StatusBarStatus.Paused + ? StatusBarStatus.Enabled + : currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Paused + : StatusBarStatus.Disabled; } else { - setupStatusBar(StatusBarStatus.Paused); - config.update( - "enableTabAutocomplete", - true, - vscode.ConfigurationTarget.Global, - ); - } - } - }, - "continue.openTabAutocompleteConfigMenu": async () => { - captureCommandTelemetry("openTabAutocompleteConfigMenu"); - - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; - - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0].title; - } - - // Toggle between Disabled, Paused, and Enabled - const pauseOnBattery = - config.get("pauseTabAutocompleteOnBattery") && - !battery.isACConnected(); - const currentStatus = getStatusBarStatus(); - - let targetStatus: StatusBarStatus | undefined; - if (pauseOnBattery) { - // Cycle from Disabled -> Paused -> Enabled - targetStatus = - currentStatus === StatusBarStatus.Paused - ? StatusBarStatus.Enabled - : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused + // Toggle between Disabled and Enabled + targetStatus = + currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Enabled : StatusBarStatus.Disabled; - } else { - // Toggle between Disabled and Enabled - targetStatus = - currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Enabled - : StatusBarStatus.Disabled; - } - quickPick.items = [ - { - label: "$(question) Open help center", - }, - { - label: "$(comment) Open chat (Cmd+L)", - }, - { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", - }, - { - label: quickPickStatusText(targetStatus), - }, - { - label: "$(gear) Configure autocomplete options", - }, - { - label: "$(feedback) Give feedback", - }, - { - kind: vscode.QuickPickItemKind.Separator, - label: "Switch model", - }, - ...autocompleteModels.map((model) => ({ - label: getAutocompleteStatusBarTitle(selected, model), - description: getAutocompleteStatusBarDescription(selected, model), - })), - ]; - quickPick.onDidAccept(() => { - const selectedOption = quickPick.selectedItems[0].label; - const targetStatus = - getStatusBarStatusFromQuickPickItemLabel(selectedOption); - - if (targetStatus !== undefined) { - setupStatusBar(targetStatus); - config.update( - "enableTabAutocomplete", - targetStatus === StatusBarStatus.Enabled, - vscode.ConfigurationTarget.Global, - ); - } else if ( - selectedOption === "$(gear) Configure autocomplete options" - ) { - ide.openFile(getConfigJsonPath()); - } else if ( - autocompleteModels.some((model) => model.title === selectedOption) - ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); - } else if (selectedOption === "$(feedback) Give feedback") { - vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { - vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { - vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); } - quickPick.dispose(); - }); - quickPick.show(); - }, - "continue.giveAutocompleteFeedback": async () => { - const feedback = await vscode.window.showInputBox({ - ignoreFocusOut: true, - prompt: - "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", - }); - if (feedback) { - const client = await continueServerClientPromise; - const completionsPath = getDevDataFilePath("autocomplete"); + quickPick.items = [ + { + label: "$(question) Open help center", + }, + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, + { + label: quickPickStatusText(targetStatus), + }, + { + label: "$(gear) Configure autocomplete options", + }, + { + label: "$(feedback) Give feedback", + }, + { + kind: vscode.QuickPickItemKind.Separator, + label: "Switch model", + }, + ...autocompleteModels.map((model) => ({ + label: getAutocompleteStatusBarTitle(selected, model), + description: getAutocompleteStatusBarDescription(selected, model), + })), + ]; + quickPick.onDidAccept(() => { + const selectedOption = quickPick.selectedItems[0].label; + const targetStatus = + getStatusBarStatusFromQuickPickItemLabel(selectedOption); - const lastLines = await readLastLines.read(completionsPath, 2); - client.sendFeedback(feedback, lastLines); - } - }, - "continue.navigateTo": (path: string) => { - sidebar.webviewProtocol?.request("navigateTo", { path }); - focusGUI(); - }, + if (targetStatus !== undefined) { + setupStatusBar(targetStatus); + config.update( + "enableTabAutocomplete", + targetStatus === StatusBarStatus.Enabled, + vscode.ConfigurationTarget.Global, + ); + } else if ( + selectedOption === "$(gear) Configure autocomplete options" + ) { + ide.openFile(getConfigJsonPath()); + } else if ( + autocompleteModels.some((model) => model.title === selectedOption) + ) { + new GlobalContext().update( + "selectedTabAutocompleteModel", + selectedOption, + ); + configHandler.reloadConfig(); + } else if (selectedOption === "$(feedback) Give feedback") { + vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if (selectedOption === "$(question) Open help center") { + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); + } + quickPick.dispose(); + }); + quickPick.show(); + }, + "continue.giveAutocompleteFeedback": async () => { + const feedback = await vscode.window.showInputBox({ + ignoreFocusOut: true, + prompt: + "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", + }); + if (feedback) { + const client = await continueServerClientPromise; + const completionsPath = getDevDataFilePath("autocomplete"); + + const lastLines = await readLastLines.read(completionsPath, 2); + client.sendFeedback(feedback, lastLines); + } + }, + "continue.navigateTo": (path: string) => { + sidebar.webviewProtocol?.request("navigateTo", { path }); + focusGUI(); + }, + }; }; -}; export function registerAllCommands( context: vscode.ExtensionContext, - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, @@ -751,6 +822,7 @@ export function registerAllCommands( battery: Battery, quickEdit: QuickEdit, core: Core, + editDecorationManager: EditDecorationManager, ) { for (const [command, callback] of Object.entries( commandsMap( @@ -764,6 +836,7 @@ export function registerAllCommands( battery, quickEdit, core, + editDecorationManager, ), )) { context.subscriptions.push( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 5a6f8a96d..88ed3831f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,9 +1,10 @@ +import { DiffLine } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; +import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; -import { DiffLine } from "core"; -import { streamDiffLines } from "core/edit/streamDiffLines"; import * as vscode from "vscode"; +import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; @@ -27,6 +28,7 @@ export class VerticalDiffManager { constructor( private readonly configHandler: ConfigHandler, private readonly webviewProtocol: VsCodeWebviewProtocol, + private readonly editDecorationManager: EditDecorationManager, ) { this.userChangeListener = undefined; } @@ -240,7 +242,7 @@ export class VerticalDiffManager { try { this.logDiffs = await diffHandler.run(diffStream); - + // enable a listener for user edits to file while diff is open this.enableDocumentChangeListener(); } catch (e) { @@ -255,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, @@ -411,6 +389,8 @@ export class VerticalDiffManager { true, ); + this.editDecorationManager.clear(); + try { this.logDiffs = await diffHandler.run( streamDiffLines( diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 2261f938e..ca6313640 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -19,6 +19,7 @@ import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvide import { DiffManager } from "../diff/horizontal"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; +import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { QuickEdit } from "../quickEdit/QuickEditQuickPick"; import { setupRemoteConfigSync } from "../stubs/activation"; import { @@ -42,6 +43,7 @@ export class VsCodeExtension { private sidebar: ContinueGUIWebviewViewProvider; private windowId: string; private diffManager: DiffManager; + private editDecorationManager: EditDecorationManager; private verticalDiffManager: VerticalDiffManager; webviewProtocolPromise: Promise; private core: Core; @@ -54,6 +56,8 @@ export class VsCodeExtension { this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); + this.editDecorationManager = new EditDecorationManager(context); + let resolveWebviewProtocol: any = undefined; this.webviewProtocolPromise = new Promise( (resolve) => { @@ -110,6 +114,7 @@ export class VsCodeExtension { verticalDiffManagerPromise, configHandlerPromise, this.workOsAuthProvider, + this.editDecorationManager, ); this.core = new Core(inProcessMessenger, this.ide, async (log: string) => { @@ -128,6 +133,7 @@ export class VsCodeExtension { this.verticalDiffManager = new VerticalDiffManager( this.configHandler, this.sidebar.webviewProtocol, + this.editDecorationManager, ); resolveVerticalDiffManager?.(this.verticalDiffManager); this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); @@ -221,6 +227,7 @@ export class VsCodeExtension { this.battery, quickEdit, this.core, + this.editDecorationManager, ); // Disabled due to performance issues diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 6ba5f1279..d7ed63a5f 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,6 +1,7 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; +import { stripImages } from "core/llm/images"; import { FromCoreProtocol, FromWebviewProtocol, @@ -20,6 +21,7 @@ import * as fs from "node:fs"; import * as path from "node:path"; import * as vscode from "vscode"; import { VerticalDiffManager } from "../diff/vertical/manager"; +import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, @@ -27,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 @@ -79,10 +82,15 @@ export class VsCodeMessenger { private readonly verticalDiffManagerPromise: Promise, private readonly configHandlerPromise: Promise, private readonly workOsAuthProvider: WorkOsAuthProvider, + private readonly editDecorationManager: EditDecorationManager, ) { /** 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) => { @@ -150,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; @@ -160,7 +192,9 @@ export class VsCodeMessenger { // If document is empty, insert at 0,0 and finish if (!editor.document.getText().trim()) { - editor.edit(builder => builder.insert(new vscode.Position(0, 0), data.text)); + editor.edit((builder) => + builder.insert(new vscode.Position(0, 0), data.text), + ); await webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "done", @@ -175,7 +209,9 @@ export class VsCodeMessenger { let llm = getModelByRole(config, "applyCodeBlock"); if (!llm) { - llm = config.models.find((model) => model.title === data.curSelectedModelTitle); + llm = config.models.find( + (model) => model.title === data.curSelectedModelTitle, + ); if (!llm) { vscode.window.showErrorMessage( @@ -263,6 +299,57 @@ export class VsCodeMessenger { ); }); }); + this.onWebview("edit/sendPrompt", async (msg) => { + const prompt = msg.data.prompt; + const { start, end } = msg.data.range.range; + const verticalDiffManager = await verticalDiffManagerPromise; + const modelTitle = await this.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + ); + await verticalDiffManager.streamEdit( + stripImages(prompt), + modelTitle, + "edit", + undefined, + undefined, + new vscode.Range( + new vscode.Position(start.line, start.character), + new vscode.Position(end.line, end.character), + ), + ); + + this.webviewProtocol.request("setEditStatus", { + status: "accepting", + }); + }); + this.onWebview("edit/acceptReject", async (msg) => { + const { onlyFirst, accept, filepath } = msg.data; + if (accept && onlyFirst) { + // Accept first + vscode.commands.executeCommand( + "continue.acceptVerticalDiffBlock", + filepath, + 0, + ); + } else if (accept) { + vscode.commands.executeCommand("continue.acceptDiff", filepath); + // Accept all + } else if (onlyFirst) { + // Reject first + vscode.commands.executeCommand( + "continue.rejectVerticalDiffBlock", + filepath, + 0, + ); + } else { + // Reject all + vscode.commands.executeCommand("continue.rejectDiff", filepath); + } + }); + this.onWebview("edit/escape", async (msg) => { + this.editDecorationManager.clear(); + }); /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => { diff --git a/extensions/vscode/src/quickEdit/EditDecorationManager.ts b/extensions/vscode/src/quickEdit/EditDecorationManager.ts new file mode 100644 index 000000000..8b856d18f --- /dev/null +++ b/extensions/vscode/src/quickEdit/EditDecorationManager.ts @@ -0,0 +1,44 @@ +import vscode from "vscode"; +class EditDecorationManager { + private _lastEditor: vscode.TextEditor | undefined; + private decorationType: vscode.TextEditorDecorationType; + + constructor(context: vscode.ExtensionContext) { + this.decorationType = vscode.window.createTextEditorDecorationType({ + backgroundColor: "rgba(255, 255, 0, 0.1)", + borderWidth: "0 0 0 1px", + borderColor: "rgba(255, 255, 0)", + borderStyle: "solid", + isWholeLine: true, + cursor: "pointer", + // gutterIconPath: context.asAbsolutePath("media/gutterIcon.png"), + gutterIconSize: "contain", + }); + } + + private updateInEditMode(inEditMode: boolean) { + vscode.commands.executeCommand( + "setContext", + "continue.inEditMode", + inEditMode, + ); + } + + setDecoration(editor: vscode.TextEditor, range: vscode.Range) { + if (this._lastEditor) { + this._lastEditor.setDecorations(this.decorationType, []); + } + editor.setDecorations(this.decorationType, [range]); + this._lastEditor = editor; + this.updateInEditMode(true); + } + + clear() { + if (this._lastEditor) { + this._lastEditor.setDecorations(this.decorationType, []); + this._lastEditor = undefined; + this.updateInEditMode(false); + } + } +} +export default EditDecorationManager; 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/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index 9b86c7751..4d3484040 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -2,17 +2,12 @@ import type { ILLM } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import Ollama from "core/llm/llms/Ollama"; import { GlobalContext } from "core/util/GlobalContext"; -import * as vscode from "vscode"; export class TabAutocompleteModel { private _llm: ILLM | undefined; private defaultTag = "starcoder2:3b"; - private defaultTagName = "Starcoder2 3b"; private globalContext: GlobalContext = new GlobalContext(); - private shownOllamaWarning = false; - private shownDeepseekWarning = false; - constructor(private configHandler: ConfigHandler) {} clearLlm() { @@ -27,49 +22,9 @@ export class TabAutocompleteModel { 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://docs.continue.dev/features/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", - "Download Ollama", - "Documentation", - ) - .then((value) => { - if (value === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://docs.continue.dev/features/tab-autocomplete", - ), - ); - } else if (value === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai")); - } - }); - this.shownOllamaWarning = true; - } return undefined; } 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 ef9f8cda9..5c0221a2f 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -37,7 +37,7 @@ "react-dom": "^18.2.0", "react-error-boundary": "^4.0.11", "react-hook-form": "^7.47.0", - "react-intersection-observer": "^9.10.3", + "react-intersection-observer": "^9.13.1", "react-markdown": "^9.0.1", "react-redux": "^8.0.5", "react-remark": "^2.1.0", @@ -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/package.json b/gui/package.json index dae097902..ef77ac910 100644 --- a/gui/package.json +++ b/gui/package.json @@ -45,7 +45,7 @@ "react-dom": "^18.2.0", "react-error-boundary": "^4.0.11", "react-hook-form": "^7.47.0", - "react-intersection-observer": "^9.10.3", + "react-intersection-observer": "^9.13.1", "react-markdown": "^9.0.1", "react-redux": "^8.0.5", "react-remark": "^2.1.0", diff --git a/gui/public/logos/xAI.png b/gui/public/logos/xAI.png new file mode 100644 index 000000000..95bdec71a Binary files /dev/null and b/gui/public/logos/xAI.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index b384936c5..ca807a876 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -7,8 +7,10 @@ import useSetup from "./hooks/useSetup"; import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders"; import { useVscTheme } from "./hooks/useVscTheme"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; +import ConfigErrorPage from "./pages/config-error"; +import Edit from "./pages/edit"; import ErrorPage from "./pages/error"; -import GUI from "./pages/gui"; +import Chat from "./pages/gui"; import History from "./pages/history"; import MigrationPage from "./pages/migration"; import MonacoPage from "./pages/monaco"; @@ -16,7 +18,6 @@ import MorePage from "./pages/More"; import SettingsPage from "./pages/settings"; import Stats from "./pages/stats"; import { ROUTES } from "./util/navigation"; -import ConfigErrorPage from "./pages/config-error"; const router = createMemoryRouter([ { @@ -26,11 +27,15 @@ const router = createMemoryRouter([ children: [ { path: "/index.html", - element: , + element: , }, { path: "/", - element: , + element: , + }, + { + path: "/edit", + element: , }, { path: "/history", diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index a165ee1a8..27b4f5202 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -7,6 +7,11 @@ import { IdeMessengerContext } from "../context/IdeMessenger"; import { LastSessionProvider } from "../context/LastSessionContext"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useConfigError } from "../redux/hooks"; +import { + setEditDone, + setEditStatus, + startEditMode, +} from "../redux/slices/editModeState"; import { setShowDialog, updateApplyState } from "../redux/slices/uiStateSlice"; import { RootState } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; @@ -174,6 +179,24 @@ const Layout = () => { [], ); + useWebviewListener( + "startEditMode", + async (args) => { + dispatch(startEditMode(args)); + navigate("/edit"); + }, + [navigate], + ); + + useWebviewListener("setEditStatus", async ({ status }) => { + dispatch(setEditStatus(status)); + }); + + useWebviewListener("exitEditMode", async () => { + dispatch(setEditDone()); + navigate("/"); + }); + useEffect(() => { if ( isNewUserOnboarding() && diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 94652bc7d..c90d6c9c7 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -1,5 +1,4 @@ import { - ArrowPathIcon, BarsArrowDownIcon, HandThumbDownIcon, HandThumbUpIcon, @@ -14,7 +13,7 @@ import { vscBackground, vscInputBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import useUIConfig from "../../hooks/useUIConfig"; import { RootState } from "../../redux/store"; -import { getFontSize } from "../../util"; +import { getFontSize, getMetaKeyLabel } from "../../util"; import ButtonWithTooltip from "../ButtonWithTooltip"; import { CopyButton } from "../markdown/CopyButton"; import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; @@ -50,7 +49,7 @@ function StepContainer(props: StepContainerProps) { const isUserInput = props.item.message.role === "user"; const uiConfig = useUIConfig(); - const shouldRenderActions = !props.isLast || (props.isLast && !active); + const shouldRenderActions = !active || !props.isLast; useEffect(() => { if (!active) { @@ -84,7 +83,11 @@ function StepContainer(props: StepContainerProps) { }; return ( -
+
- - {shouldRenderActions && ( -
- {truncatedEarly && ( - - - - )} - - {props.index !== 1 && ( - - - - )} - - - +
+ {truncatedEarly && ( sendFeedback(true)} + text="Continue generation" + onClick={props.onContinueGeneration} > - + + )} + {props.index !== 1 && ( sendFeedback(false)} + onClick={props.onDelete} > - + -
- )} + )} + + + + sendFeedback(true)} + > + + + + sendFeedback(false)} + > + + +
); } diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 40127037f..4a9ea0dfd 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,5 +1,6 @@ -import { JSONContent } from "@tiptap/react"; +import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; +import { useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; @@ -9,12 +10,15 @@ import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice"; import { RootState } from "../../redux/store"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; -import { useState, useRef, useEffect } from "react"; interface ContinueInputBoxProps { isLastUserInput: boolean; isMainInput?: boolean; - onEnter: (editorState: JSONContent, modifiers: InputModifiers) => void; + onEnter: ( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) => void; editorState?: JSONContent; contextItems?: ContextItemWithId[]; hidden?: boolean; @@ -105,8 +109,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) { }, [isGatheringContextStore]); return ( -
-
+
+
{ + props.onEnter(...args); + if (props.isMainInput) { + args[2].commands.clearContent(true); + } + }} isMainInput={props.isMainInput ?? false} availableContextProviders={availableContextProviders ?? []} availableSlashCommands={availableSlashCommands} + historyKey="chat" />
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index deddde65e..6701e092e 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,8 +1,4 @@ -import { - AtSymbolIcon, - PhotoIcon, - SlashIcon, -} from "@heroicons/react/24/outline"; +import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { useRef } from "react"; @@ -11,8 +7,6 @@ import styled from "styled-components"; import { defaultBorderRadius, lightGray, - vscBadgeBackground, - vscBadgeForeground, vscForeground, vscInputBackground, } from ".."; @@ -24,8 +18,8 @@ import { getMetaKeyLabel, isMetaEquivalentKeyPressed, } from "../../util"; -import ModelSelect from "../modelSelection/ModelSelect"; import { ToolTip } from "../gui/Tooltip"; +import ModelSelect from "../modelSelection/ModelSelect"; const StyledDiv = styled.div<{ isHidden: boolean }>` padding: 4px 0; @@ -69,6 +63,14 @@ const EnterButton = styled.button` } `; +export interface ToolbarOptions { + hideUseCodebase?: boolean; + hideImageUpload?: boolean; + hideAddContext?: boolean; + enterText?: string; + hideSelectModel?: boolean; +} + interface InputToolbarProps { onEnter?: (modifiers: InputModifiers) => void; onAddContextItem?: () => void; @@ -77,6 +79,7 @@ interface InputToolbarProps { onImageFileSelected?: (file: File) => void; hidden?: boolean; activeKey: string | null; + toolbarOptions?: ToolbarOptions; disabled?: boolean; } @@ -105,69 +108,73 @@ function InputToolbar(props: InputToolbarProps) {
- {supportsImages && ( - <> - { - for (const file of e.target.files) { - props.onImageFileSelected(file); - } - }} - /> - - { - fileInputRef.current?.click(); + {props.toolbarOptions?.hideImageUpload || + (supportsImages && ( + <> + { + for (const file of e.target.files) { + props.onImageFileSelected(file); + } }} /> - - - )} + + { + fileInputRef.current?.click(); + }} + /> + + + ))} + {props.toolbarOptions?.hideAddContext || ( + + - - - - - Add context (files, docs, urls, etc.) - - -
-
- -
-
- {props.activeKey === "Alt" ? ( - - {`${getAltKeyLabel()}⏎ - ${useActiveFile ? "No active file" : "Active file"}`} - - ) : ( - - props.onEnter({ - useCodebase: true, - noContext: !useActiveFile, - }) - } - > - - {getMetaKeyLabel()}⏎ @codebase - - - Submit with the codebase as context ({getMetaKeyLabel()}⏎) + + Add context (files, docs, urls, etc.) )}
+
+ +
+ {props.toolbarOptions?.hideUseCodebase || ( +
+ {props.activeKey === "Alt" ? ( + + {`${getAltKeyLabel()}⏎ + ${useActiveFile ? "No active file" : "Active file"}`} + + ) : ( + + props.onEnter({ + useCodebase: true, + noContext: !useActiveFile, + }) + } + > + + {getMetaKeyLabel()}⏎ @codebase + + + Submit with the codebase as context ({getMetaKeyLabel()}⏎) + + + )} +
+ )} { @@ -178,7 +185,9 @@ function InputToolbar(props: InputToolbarProps) { }} disabled={props.disabled} > - ⏎ Enter + + ⏎ {props.toolbarOptions?.enterText ?? "Enter"} + ⏎
diff --git a/gui/src/components/mainInput/NewSessionButton.tsx b/gui/src/components/mainInput/NewSessionButton.tsx new file mode 100644 index 000000000..04193450c --- /dev/null +++ b/gui/src/components/mainInput/NewSessionButton.tsx @@ -0,0 +1,23 @@ +import styled from "styled-components"; +import { defaultBorderRadius, lightGray, vscForeground } from ".."; +import { getFontSize } from "../../util"; + +export const NewSessionButton = styled.div` + width: fit-content; + margin-right: auto; + margin-left: 6px; + margin-top: 2px; + margin-bottom: 8px; + font-size: ${getFontSize() - 2}px; + + border-radius: ${defaultBorderRadius}; + padding: 2px 6px; + color: ${lightGray}; + + &:hover { + background-color: ${lightGray}33; + color: ${vscForeground}; + } + + cursor: pointer; +`; diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 2c17a1f17..01ee8dea6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -50,12 +50,14 @@ import { getFontSize, isJetBrains, isMetaEquivalentKeyPressed, - isWebEnvironment, } from "../../util"; -import { handleMetaKeyPressJetBrains } from "../../util/handleMetaKeyPressJetBrains"; +import { + handleJetBrainsMetaKeyPress, + handleMetaKeyPress, +} from "./handleMetaKeyPress"; import { CodeBlockExtension } from "./CodeBlockExtension"; import { SlashCommand } from "./CommandsExtension"; -import InputToolbar from "./InputToolbar"; +import InputToolbar, { ToolbarOptions } from "./InputToolbar"; import { Mention } from "./MentionExtension"; import "./TipTapEditor.css"; import { @@ -64,20 +66,21 @@ import { } from "./getSuggestion"; import { ComboBoxItem } from "./types"; -const InputBoxDiv = styled.div` +const InputBoxDiv = styled.div<{ border?: string }>` resize: none; - padding: 8px 12px; padding-bottom: 4px; font-family: inherit; border-radius: ${defaultBorderRadius}; margin: 0; height: auto; - width: calc(100% - 24px); + width: 100%; background-color: ${vscInputBackground}; color: ${vscForeground}; - border: 0.5px solid ${vscInputBorder}; + border: ${(props) => + props.border ? props.border : `0.5px solid ${vscInputBorder}`}; outline: none; font-size: ${getFontSize()}px; + &:focus { outline: none; @@ -92,6 +95,11 @@ const InputBoxDiv = styled.div` flex-direction: column; `; +const PaddingDiv = styled.div` + padding: 8px 12px; + padding-bottom: 4px; +`; + const HoverDiv = styled.div` position: absolute; width: 100%; @@ -141,8 +149,17 @@ interface TipTapEditorProps { availableContextProviders: ContextProviderDescription[]; availableSlashCommands: ComboBoxItem[]; isMainInput: boolean; - onEnter: (editorState: JSONContent, modifiers: InputModifiers) => void; + onEnter: ( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) => void; editorState?: JSONContent; + toolbarOptions?: ToolbarOptions; + border?: string; + placeholder?: string; + header?: React.ReactNode; + historyKey: string; } function TipTapEditor(props: TipTapEditorProps) { @@ -231,8 +248,8 @@ function TipTapEditor(props: TipTapEditorProps) { const timer = setTimeout(() => { setHasDefaultModel( !!defaultModel && - defaultModel.apiKey !== undefined && - defaultModel.apiKey !== "", + defaultModel.apiKey !== undefined && + defaultModel.apiKey !== "", ); }, 3500); @@ -285,7 +302,7 @@ function TipTapEditor(props: TipTapEditorProps) { (store: RootState) => store.state.mainEditorContent, ); - const { prevRef, nextRef, addRef } = useInputHistory(); + const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); function getPlaceholder() { if (!hasDefaultModel) { @@ -337,7 +354,11 @@ function TipTapEditor(props: TipTapEditorProps) { }, }), Placeholder.configure({ - placeholder: getPlaceholder, + placeholder: + props.placeholder ?? + (historyLengthRef.current === 0 + ? "Ask anything, '/' for slash commands, '@' to add context" + : "Ask a follow-up"), }), Paragraph.extend({ addKeyboardShortcuts() { @@ -429,37 +450,41 @@ function TipTapEditor(props: TipTapEditorProps) { }, }), Text, - 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}`; - }, - }), - SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }), + 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}`; + }, + }) + : undefined, + props.availableSlashCommands.length + ? SlashCommand.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) + : undefined, CodeBlockExtension, ], editorProps: { @@ -539,86 +564,28 @@ function TipTapEditor(props: TipTapEditorProps) { /** * This handles various issues with meta key actions - * - In JetBrains, when using "off screen rendering", there is a bug where using the meta key to + * - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to * highlight code using arrow keys is not working * - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect * the actual notebook cells, even when performing them in our GUI + * + * Currently keydown events for a number of keys are not registering if the + * meta/shift key is pressed, for example "x", "c", "v", "z", etc. + * Until this is resolved we can't turn on OSR for non-Mac users due to issues + * with those key actions. */ const handleKeyDown = async (e: KeyboardEvent) => { - if (!editor || !editorFocusedRef.current) return; + if (!editorFocusedRef?.current) return; setActiveKey(e.key); + // Handle meta key issues if (isMetaEquivalentKeyPressed(e)) { - const { key, code } = e; - const isWebEnv = isWebEnvironment(); - const text = editor.state.doc.textBetween( - editor.state.selection.from, - editor.state.selection.to, - ); - if (isJetBrains()) { - if (code === "KeyJ") { - e.stopPropagation(); - e.preventDefault(); - setIgnoreHighlightedCode(true); - setTimeout(() => { - setIgnoreHighlightedCode(false); - }, 100); - } - - if (isMetaEquivalentKeyPressed(e)) { - e.stopPropagation(); - e.preventDefault(); - handleMetaKeyPressJetBrains(e, text, editor.commands.setContent); - } - } else { - if (code === "KeyL") { - e.stopPropagation(); - e.preventDefault(); - setIgnoreHighlightedCode(true); - setTimeout(() => { - setIgnoreHighlightedCode(false); - }, 100); - return; - } - - switch (key) { - case "x": - e.stopPropagation(); - e.preventDefault(); - if (isWebEnv) { - await navigator.clipboard.writeText(text); - editor.commands.deleteSelection(); - } else { - document.execCommand("cut"); - } - break; - case "c": - e.stopPropagation(); - e.preventDefault(); - if (isWebEnv) { - await navigator.clipboard.writeText(text); - } else { - document.execCommand("copy"); - } - break; - case "v": - e.stopPropagation(); - e.preventDefault(); - if (isWebEnv) { - const clipboardText = await navigator.clipboard.readText(); - editor.commands.insertContent(clipboardText); - } else { - document.execCommand("paste"); - } - break; - } + handleJetBrainsMetaKeyPress(e, editor); } - } else if (e.key === "Escape") { - e.stopPropagation(); - e.preventDefault(); - ideMessenger.post("focusEditor", undefined); + + await handleMetaKeyPress(e, editor); } }; @@ -639,20 +606,16 @@ function TipTapEditor(props: TipTapEditorProps) { return; } - props.onEnter(json, modifiers); + props.onEnter(json, modifiers, editor); if (props.isMainInput) { const content = editor.state.toJSON().doc; addRef.current(content); - editor.commands.clearContent(true); } }, [props.onEnter, editor, props.isMainInput], ); - // This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview - const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false); - // Re-focus main input after done generating useEffect(() => { if (editor && !active && props.isMainInput && document.hasFocus()) { @@ -684,7 +647,7 @@ function TipTapEditor(props: TipTapEditorProps) { return; } if (historyLength > 0) { - saveSession(); + await saveSession(); } setTimeout(() => { editor?.commands.blur(); @@ -713,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( @@ -727,71 +690,67 @@ function TipTapEditor(props: TipTapEditorProps) { if (!props.isMainInput || !editor) { return; } - if (!ignoreHighlightedCode) { - const rif: RangeInFile & { contents: string } = - data.rangeInFileWithContents; - const basename = getBasename(rif.filepath); - const relativePath = getRelativePath( - rif.filepath, - await ideMessenger.ide.getWorkspaceDirs(), - ); - const rangeStr = `(${rif.range.start.line + 1}-${ - rif.range.end.line + 1 + + const rif: RangeInFile & { contents: string } = + data.rangeInFileWithContents; + const basename = getBasename(rif.filepath); + const relativePath = getRelativePath( + rif.filepath, + await ideMessenger.ide.getWorkspaceDirs(), + ); + const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1 })`; - const item: ContextItemWithId = { - content: rif.contents, - name: `${basename} ${rangeStr}`, - // Description is passed on to the LLM to give more context on file path - description: `${relativePath} ${rangeStr}`, - id: { - providerTitle: "code", - itemId: v4(), - }, - uri: { - type: "file", - value: rif.filepath, - }, - }; + const item: ContextItemWithId = { + content: rif.contents, + name: `${basename} ${rangeStr}`, + // Description is passed on to the LLM to give more context on file path + description: `${relativePath} ${rangeStr}`, + id: { + providerTitle: "code", + itemId: v4(), + }, + uri: { + type: "file", + value: rif.filepath, + }, + }; - let index = 0; - for (const el of editor.getJSON().content) { - if (el.type === "codeBlock") { - index += 2; - } else { - break; - } + let index = 0; + for (const el of editor.getJSON().content) { + if (el.type === "codeBlock") { + index += 2; + } else { + break; } - editor - .chain() - .insertContentAt(index, { - type: "codeBlock", - attrs: { - item, - }, - }) - .run(); - - if (data.prompt) { - editor.commands.focus("end"); - editor.commands.insertContent(data.prompt); - } - - if (data.shouldRun) { - onEnterRef.current({ useCodebase: false, noContext: true }); - } - - setTimeout(() => { - editor.commands.blur(); - editor.commands.focus("end"); - }, 20); } - setIgnoreHighlightedCode(false); + editor + .chain() + .insertContentAt(index, { + type: "codeBlock", + attrs: { + item, + }, + }) + .run(); + + if (data.prompt) { + editor.commands.focus("end"); + editor.commands.insertContent(data.prompt); + } + + if (data.shouldRun) { + onEnterRef.current({ useCodebase: false, noContext: true }); + } + + setTimeout(() => { + editor.commands.blur(); + editor.commands.focus("end"); + }, 20); }, [ editor, props.isMainInput, historyLength, - ignoreHighlightedCode, props.isMainInput, onEnterRef.current, ], @@ -859,6 +818,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( - { - event.stopPropagation(); - }} - /> -
+ + {["accepting", "streaming"].includes(editModeState.editStatus) && ( +
+ { + ideMessenger.request("edit/acceptReject", { + accept: false, + onlyFirst: false, + filepath: editModeState.highlightedCode.filepath, + }); + dispatch(setEditDone()); + }} + > + {getMetaKeyLabel()}⇧⌫ Reject all + + { + ideMessenger.request("edit/acceptReject", { + accept: true, + onlyFirst: false, + filepath: editModeState.highlightedCode.filepath, + }); + dispatch(setEditDone()); + }} + > + {getMetaKeyLabel()}⇧⏎ Accept all + +
+ )} + +
+ { + dispatch(setEditDone()); + }} + className="mr-auto flex items-center gap-2" + > + + Back to chat + +
+ + + ); +} +export default Edit; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 243657462..6ca0cc167 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -23,13 +23,13 @@ import { defaultBorderRadius, lightGray, vscBackground, - vscForeground, } from "../../components"; import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; import StepContainer from "../../components/gui/StepContainer"; import TimelineItem from "../../components/gui/TimelineItem"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { defaultInputModifiers } from "../../components/mainInput/inputModifiers"; +import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import { TutorialCard } from "../../components/mainInput/TutorialCard"; import { OnboardingCard, @@ -66,7 +66,6 @@ const TopGuiDiv = styled.div<{ showScrollbar?: boolean; }>` overflow-y: auto; - height: 100%; scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; &::-webkit-scrollbar { @@ -75,6 +74,7 @@ const TopGuiDiv = styled.div<{ `; const StopButton = styled.div` + background-color: ${vscBackground}; width: fit-content; margin-right: auto; margin-left: auto; @@ -84,15 +84,20 @@ const StopButton = styled.div` padding: 4px 8px; color: ${lightGray}; cursor: pointer; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08); + box-shadow: + 0 4px 6px rgba(0, 0, 0, 0.1), + 0 1px 3px rgba(0, 0, 0, 0.08); transition: box-shadow 0.3s ease; &:hover { - box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1); + box-shadow: + 0 6px 8px rgba(0, 0, 0, 0.15), + 0 3px 6px rgba(0, 0, 0, 0.1); } `; const StepsDiv = styled.div` + margin-top: 8px; position: relative; background-color: transparent; @@ -105,26 +110,6 @@ const StepsDiv = styled.div` } `; -const NewSessionButton = styled.div` - width: fit-content; - margin-right: auto; - margin-left: 6px; - margin-top: 2px; - margin-bottom: 8px; - font-size: ${getFontSize() - 2}px; - - border-radius: ${defaultBorderRadius}; - padding: 2px 6px; - color: ${lightGray}; - - &:hover { - background-color: ${lightGray}33; - color: ${vscForeground}; - } - - cursor: pointer; -`; - function fallbackRender({ error, resetErrorBoundary }: any) { // Call resetErrorBoundary() to reset the error boundary and retry the render. @@ -163,16 +148,17 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); - useEffect(() => { - if (!active || !topGuiDivRef.current) return; - - const scrollAreaElement = topGuiDivRef.current; - - scrollAreaElement.scrollTop = - scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; + const scrollToBottom = useCallback(() => { + if (!topGuiDivRef.current) return; + const elem = topGuiDivRef.current; + elem.scrollTop = elem.scrollHeight - elem.clientHeight; setIsAtBottom(true); - }, [active]); + }, [topGuiDivRef, setIsAtBottom]); + + useEffect(() => { + if (active) scrollToBottom(); + }, [active, scrollToBottom]); useEffect(() => { // Cmd + Backspace to delete current step @@ -234,7 +220,7 @@ export function Chat() { if (currentCount === 300) { dispatch( setDialogMessage( -
+
👋 Thanks for using Continue. We are always trying to improve and love hearing from users. If you're interested in speaking, enter your name and email. We won't use this information for @@ -250,7 +236,7 @@ export function Chat() { }); dispatch( setDialogMessage( -
+
Thanks! We'll be in touch soon.
, ), @@ -327,11 +313,12 @@ export function Chat() { return ( <> 0 ? "h-full" : ""}`} ref={topGuiDivRef} onScroll={handleScroll} showScrollbar={state.config.ui?.showChatScrollbar || false} > -
+
{state.history.map((item, index: number) => ( @@ -431,30 +418,64 @@ export function Chat() { ))} +
+ + -