diff --git a/.continueignore b/.continueignore index fcbe84fa0..7e0d0c115 100644 --- a/.continueignore +++ b/.continueignore @@ -1,4 +1,7 @@ **/*.run.xml -archive/**/* -extensions/vscode/models/**/* -docs/docs/languages \ No newline at end of file +docs/docs/languages +.changes/ +.idea/ +.vscode/ +.archive/ +**/*.scm \ No newline at end of file diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 25194cbec..6c9e23ef9 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -12,8 +12,23 @@ defaults: working-directory: ./extensions/intellij jobs: + check_release_name: + runs-on: ubuntu-latest + outputs: + should_run: ${{ steps.check.outputs.should_run }} + steps: + - id: check + run: | + if [[ "${{ github.event.release.name }}" == *-jetbrains ]]; then + echo "should_run=true" >> $GITHUB_OUTPUT + else + echo "should_run=false" >> $GITHUB_OUTPUT + fi + # Prepare and publish the plugin to JetBrains Marketplace repository release: + needs: check_release_name + if: needs.check_release_name.outputs.should_run == 'true' name: Publish Plugin runs-on: ubuntu-latest permissions: diff --git a/.prettierignore b/.prettierignore index b497624cc..5d9bf3359 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1 +1,2 @@ -extensions/vscode/continue_rc_schema.json \ No newline at end of file +extensions/vscode/continue_rc_schema.json +**/.continueignore \ No newline at end of file diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index 87549e155..5db4ff52f 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -73,7 +73,11 @@ describe("Test Suite", () => { ); } - const ide = new FileSystemIde(); + const testDir = path.join(__dirname, "..", ".test"); + if (!fs.existsSync(testDir)) { + fs.mkdirSync(testDir); + } + const ide = new FileSystemIde(testDir); const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide); // Wait for core to set itself up diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index de235aca5..ef73d9b58 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -4,7 +4,7 @@ import OpenAI from "openai"; import path from "path"; import { v4 as uuidv4 } from "uuid"; import { RangeInFileWithContents } from "../commands/util.js"; -import { ConfigHandler } from "../config/handler.js"; +import { IConfigHandler } from "../config/IConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; import { @@ -145,7 +145,7 @@ export class CompletionProvider { private static lastUUID: string | undefined = undefined; constructor( - private readonly configHandler: ConfigHandler, + private readonly configHandler: IConfigHandler, private readonly ide: IDE, private readonly getLlm: () => Promise, private readonly _onError: (e: any) => void, diff --git a/core/config/handler.ts b/core/config/ConfigHandler.ts similarity index 91% rename from core/config/handler.ts rename to core/config/ConfigHandler.ts index bc340b994..1d9a8c958 100644 --- a/core/config/handler.ts +++ b/core/config/ConfigHandler.ts @@ -8,9 +8,10 @@ import { ILLM, } from "../index.js"; import { Telemetry } from "../util/posthog.js"; +import { IConfigHandler } from "./IConfigHandler.js"; import { finalToBrowserConfig, loadFullConfigNode } from "./load.js"; -export class ConfigHandler { +export class ConfigHandler implements IConfigHandler { private savedConfig: ContinueConfig | undefined; private savedBrowserConfig?: BrowserSerializedContinueConfig; private additionalContextProviders: IContextProvider[] = []; @@ -35,8 +36,8 @@ export class ConfigHandler { this.reloadConfig(); } - private updateListeners: (() => void)[] = []; - onConfigUpdate(listener: () => void) { + private updateListeners: ((newConfig: ContinueConfig) => void)[] = []; + onConfigUpdate(listener: (newConfig: ContinueConfig) => void) { this.updateListeners.push(listener); } @@ -45,10 +46,10 @@ export class ConfigHandler { this.savedBrowserConfig = undefined; this._pendingConfigPromise = undefined; - await this.loadConfig(); + const newConfig = await this.loadConfig(); for (const listener of this.updateListeners) { - listener(); + listener(newConfig); } } diff --git a/core/config/IConfigHandler.ts b/core/config/IConfigHandler.ts new file mode 100644 index 000000000..8177e7e03 --- /dev/null +++ b/core/config/IConfigHandler.ts @@ -0,0 +1,17 @@ +import { + BrowserSerializedContinueConfig, + ContinueConfig, + IContextProvider, + IdeSettings, + ILLM, +} from "../index.js"; + +export interface IConfigHandler { + updateIdeSettings(ideSettings: IdeSettings): void; + onConfigUpdate(listener: (newConfig: ContinueConfig) => void): void; + reloadConfig(): Promise; + getSerializedConfig(): Promise; + loadConfig(): Promise; + llmFromTitle(title?: string): Promise; + registerCustomContextProvider(contextProvider: IContextProvider): void; +} diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts index 504037497..3e22db302 100644 --- a/core/context/retrieval/fullTextSearch.ts +++ b/core/context/retrieval/fullTextSearch.ts @@ -1,5 +1,6 @@ import { BranchAndDir, Chunk } from "../../index.js"; import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch.js"; + export async function retrieveFts( query: string, n: number, diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts new file mode 100644 index 000000000..b993aea07 --- /dev/null +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -0,0 +1,59 @@ +import { + BranchAndDir, + Chunk, + EmbeddingsProvider, + IDE, + Reranker, +} from "../../.."; +import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { retrieveFts } from "../fullTextSearch"; + +export interface RetrievalPipelineOptions { + ide: IDE; + embeddingsProvider: EmbeddingsProvider; + reranker: Reranker | undefined; + + input: string; + nRetrieve: number; + nFinal: number; + tags: BranchAndDir[]; + filterDirectory?: string; +} + +export interface IRetrievalPipeline { + run(options: RetrievalPipelineOptions): Promise; +} + +export default class BaseRetrievalPipeline implements IRetrievalPipeline { + private lanceDbIndex: LanceDbIndex; + constructor(protected readonly options: RetrievalPipelineOptions) { + this.lanceDbIndex = new LanceDbIndex(options.embeddingsProvider, (path) => + options.ide.readFile(path), + ); + } + + 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, + ): Promise { + return this.lanceDbIndex.retrieve( + input, + n, + this.options.tags, + this.options.filterDirectory, + ); + } + + run(): Promise { + throw new Error("Not implemented"); + } +} diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts new file mode 100644 index 000000000..7ad1819d5 --- /dev/null +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -0,0 +1,26 @@ +import { Chunk } from "../../.."; +import { deduplicateChunks } from "../util"; +import BaseRetrievalPipeline from "./BaseRetrievalPipeline"; + +export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { + async run(): Promise { + const { input } = this.options; + + // Get all retrieval results + const retrievalResults: Chunk[] = []; + + // Full-text search + const ftsResults = await this.retrieveFts(input, this.options.nFinal / 2); + retrievalResults.push(...ftsResults); + + // Embeddings + const embeddingResults = await this.retrieveEmbeddings( + input, + this.options.nFinal / 2, + ); + retrievalResults.push(...embeddingResults); + + const finalResults: Chunk[] = deduplicateChunks(retrievalResults); + return finalResults; + } +} diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts new file mode 100644 index 000000000..47b0f1f9d --- /dev/null +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -0,0 +1,125 @@ +import { Chunk } from "../../.."; +import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { deduplicateChunks } from "../util"; +import BaseRetrievalPipeline from "./BaseRetrievalPipeline"; + +export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { + private async _retrieveInitial(): Promise { + const { input, nRetrieve } = this.options; + + // Get all retrieval results + const retrievalResults: Chunk[] = []; + + // Full-text search + const ftsResults = await this.retrieveFts(input, nRetrieve / 2); + retrievalResults.push(...ftsResults); + + // Embeddings + const embeddingResults = await this.retrieveEmbeddings(input, nRetrieve); + retrievalResults.push( + ...embeddingResults.slice(0, nRetrieve - ftsResults.length), + ); + + const results: Chunk[] = deduplicateChunks(retrievalResults); + return results; + } + + private async _rerank(input: string, chunks: Chunk[]): Promise { + if (!this.options.reranker) { + throw new Error("No reranker provided"); + } + + let scores: number[] = await this.options.reranker.rerank(input, chunks); + + // Filter out low-scoring results + let results = chunks; + // let results = chunks.filter( + // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + // scores = scores.filter( + // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + + results.sort( + (a, b) => scores[results.indexOf(a)] - scores[results.indexOf(b)], + ); + results = results.slice(-this.options.nFinal); + return results; + } + + private async _expandWithEmbeddings(chunks: Chunk[]): Promise { + const topResults = chunks.slice( + -RETRIEVAL_PARAMS.nResultsToExpandWithEmbeddings, + ); + + const expanded = await Promise.all( + topResults.map(async (chunk, i) => { + const results = await this.retrieveEmbeddings( + chunk.content, + RETRIEVAL_PARAMS.nEmbeddingsExpandTo, + ); + return results; + }), + ); + return expanded.flat(); + } + + private async _expandRankedResults(chunks: Chunk[]): Promise { + let results: Chunk[] = []; + + const embeddingsResults = await this._expandWithEmbeddings(chunks); + results.push(...embeddingsResults); + + return results; + } + + async run(): Promise { + // Retrieve initial results + let results = await this._retrieveInitial(); + + // Rerank + const { input } = this.options; + results = await this._rerank(input, results); + + // // // Expand top reranked results + // const expanded = await this._expandRankedResults(results); + // results.push(...expanded); + + // // De-duplicate + // results = deduplicateChunks(results); + + // // Rerank again + // results = await this._rerank(input, results); + + // TODO: stitch together results + + return results; + } +} + +// Source: expansion with code graph +// consider doing this after reranking? Or just having a lower reranking threshold +// This is VS Code only until we use PSI for JetBrains or build our own general solution +// TODO: Need to pass in the expandSnippet function as a function argument +// because this import causes `tsc` to fail +// if ((await extras.ide.getIdeInfo()).ideType === "vscode") { +// const { expandSnippet } = await import( +// "../../../extensions/vscode/src/util/expandSnippet" +// ); +// let expansionResults = ( +// await Promise.all( +// extras.selectedCode.map(async (rif) => { +// return expandSnippet( +// rif.filepath, +// rif.range.start.line, +// rif.range.end.line, +// extras.ide, +// ); +// }), +// ) +// ).flat() as Chunk[]; +// retrievalResults.push(...expansionResults); +// } + +// Source: Open file exact match +// Source: Class/function name exact match diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index f3218685b..1138078d2 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,24 +1,14 @@ import { BranchAndDir, - Chunk, ContextItem, ContextProviderExtras, } from "../../index.js"; -import { LanceDbIndex } from "../../indexing/LanceDbIndex.js"; -import { deduplicateArray, getRelativePath } from "../../util/index.js"; +import { getRelativePath } from "../../util/index.js"; import { RETRIEVAL_PARAMS } from "../../util/parameters.js"; -import { retrieveFts } from "./fullTextSearch.js"; - -function deduplicateChunks(chunks: Chunk[]): Chunk[] { - return deduplicateArray(chunks, (a, b) => { - return ( - a.filepath === b.filepath && - a.startLine === b.startLine && - a.endLine === b.endLine - ); - }); -} +import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js"; +import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js"; +import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline.js"; export async function retrieveContextItemsFromEmbeddings( extras: ContextProviderExtras, @@ -66,80 +56,21 @@ export async function retrieveContextItemsFromEmbeddings( branch: branches[i], })); - // Get all retrieval results - const retrievalResults: Chunk[] = []; - - // Source: Full-text search - const ftsResults = await retrieveFts( - extras.fullInput, - nRetrieve / 2, - tags, - filterDirectory, - ); - retrievalResults.push(...ftsResults); - - // Source: expansion with code graph - // consider doing this after reranking? Or just having a lower reranking threshold - // This is VS Code only until we use PSI for JetBrains or build our own general solution - // TODO: Need to pass in the expandSnippet function as a function argument - // because this import causes `tsc` to fail - // if ((await extras.ide.getIdeInfo()).ideType === "vscode") { - // const { expandSnippet } = await import( - // "../../../extensions/vscode/src/util/expandSnippet" - // ); - // let expansionResults = ( - // await Promise.all( - // extras.selectedCode.map(async (rif) => { - // return expandSnippet( - // rif.filepath, - // rif.range.start.line, - // rif.range.end.line, - // extras.ide, - // ); - // }), - // ) - // ).flat() as Chunk[]; - // retrievalResults.push(...expansionResults); - // } - - // Source: Open file exact match - // Source: Class/function name exact match - - // Source: Embeddings - const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) => - extras.ide.readFile(path), - ); - const vecResults = await lanceDbIndex.retrieve( - extras.fullInput, + const pipelineType = useReranking + ? RerankerRetrievalPipeline + : NoRerankerRetrievalPipeline; + const pipelineOptions: RetrievalPipelineOptions = { + nFinal, nRetrieve, tags, + embeddingsProvider: extras.embeddingsProvider, + reranker: extras.reranker, filterDirectory, - ); - retrievalResults.push(...vecResults); - - // De-duplicate - let results: Chunk[] = deduplicateChunks(retrievalResults); - - // Re-rank - if (useReranking && extras.reranker) { - let scores: number[] = await extras.reranker.rerank( - extras.fullInput, - results, - ); - - // Filter out low-scoring results - results = results.filter( - (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, - ); - scores = scores.filter( - (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, - ); - - results.sort( - (a, b) => scores[results.indexOf(a)] - scores[results.indexOf(b)], - ); - results = results.slice(-nFinal); - } + ide: extras.ide, + input: extras.fullInput, + }; + const pipeline = new pipelineType(pipelineOptions); + const results = await pipeline.run(); if (results.length === 0) { throw new Error( diff --git a/core/context/retrieval/util.ts b/core/context/retrieval/util.ts new file mode 100644 index 000000000..e783a2ca0 --- /dev/null +++ b/core/context/retrieval/util.ts @@ -0,0 +1,12 @@ +import { Chunk } from "../.."; +import { deduplicateArray } from "../../util"; + +export function deduplicateChunks(chunks: Chunk[]): Chunk[] { + return deduplicateArray(chunks, (a, b) => { + return ( + a.filepath === b.filepath && + a.startLine === b.startLine && + a.endLine === b.endLine + ); + }); +} diff --git a/core/core.ts b/core/core.ts index 9dcfc13ea..6e6b8b997 100644 --- a/core/core.ts +++ b/core/core.ts @@ -6,7 +6,8 @@ import type { SiteIndexingConfig, } from "."; import { CompletionProvider } from "./autocomplete/completionProvider.js"; -import { ConfigHandler } from "./config/handler.js"; +import { ConfigHandler } from "./config/ConfigHandler.js"; +import { IConfigHandler } from "./config/IConfigHandler"; import { setupApiKeysMode, setupFreeTrialMode, @@ -16,9 +17,9 @@ import { import { createNewPromptFile } from "./config/promptFile.js"; import { addModel, addOpenAIKey, deleteModel } from "./config/util.js"; import { ContinueServerClient } from "./continueServer/stubs/client.js"; +import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js"; import { DocsService } from "./indexing/docs/DocsService"; import TransformersJsEmbeddingsProvider from "./indexing/embeddings/TransformersJsEmbeddingsProvider.js"; -import { CodebaseIndexer, PauseToken } from "./indexing/indexCodebase.js"; import Ollama from "./llm/llms/Ollama.js"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext.js"; @@ -33,7 +34,7 @@ import { streamDiffLines } from "./util/verticalEdit.js"; export class Core { // implements IMessenger - configHandler: ConfigHandler; + configHandler: IConfigHandler; codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; continueServerClientPromise: Promise; @@ -286,7 +287,7 @@ export class Core { }); async function* llmStreamChat( - configHandler: ConfigHandler, + configHandler: IConfigHandler, abortedMessageIds: Set, msg: Message, ) { @@ -321,7 +322,7 @@ export class Core { ); async function* llmStreamComplete( - configHandler: ConfigHandler, + configHandler: IConfigHandler, abortedMessageIds: Set, msg: Message, @@ -387,7 +388,7 @@ export class Core { }); async function* runNodeJsSlashCommand( - configHandler: ConfigHandler, + configHandler: IConfigHandler, abortedMessageIds: Set, msg: Message, messenger: IMessenger, @@ -476,7 +477,7 @@ export class Core { }); async function* streamDiffLinesGenerator( - configHandler: ConfigHandler, + configHandler: IConfigHandler, abortedMessageIds: Set, msg: Message, ) { diff --git a/core/index.d.ts b/core/index.d.ts index 9c12c07b4..99c6ad755 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -807,11 +807,42 @@ interface ModelRoles { applyCodeBlock?: string; } +/** + * Represents the configuration for a quick action in the Code Lens. + * Quick actions are custom commands that can be added to function and class declarations. + */ +interface QuickActionConfig { + /** + * The title of the quick action that will display in the Code Lens. + */ + title: string; + + /** + * The prompt that will be sent to the model when the quick action is invoked, + * with the function or class body concatenated. + */ + prompt: string; + + /** + * If `true`, the result of the quick action will be sent to the chat panel. + * If `false`, the streamed result will be inserted into the document. + * + * Defaults to `false`. + */ + sendToChat: boolean; +} + interface ExperimentalConfig { contextMenuPrompts?: ContextMenuConfig; modelRoles?: ModelRoles; defaultContext?: "activeFile"[]; promptPath?: string; + + /** + * Quick actions are a way to add custom commands to the Code Lens of + * function and class declarations. + */ + quickActions?: QuickActionConfig[]; } // config.json diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index d773b1dd3..a5ec68f8b 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -116,7 +116,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } yield { - desc: `Indexing ${compute.path}`, + desc: `Indexing ${getBasename(compute.path)}`, progress: i / results.compute.length, status: "indexing", }; diff --git a/core/indexing/indexCodebase.ts b/core/indexing/CodebaseIndexer.ts similarity index 98% rename from core/indexing/indexCodebase.ts rename to core/indexing/CodebaseIndexer.ts index a0ceeb3cb..5b90e0775 100644 --- a/core/indexing/indexCodebase.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,4 +1,4 @@ -import { ConfigHandler } from "../config/handler.js"; +import { IConfigHandler } from "../config/IConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; @@ -23,7 +23,7 @@ export class PauseToken { export class CodebaseIndexer { constructor( - private readonly configHandler: ConfigHandler, + private readonly configHandler: IConfigHandler, private readonly ide: IDE, private readonly pauseToken: PauseToken, private readonly continueServerClient: IContinueServerClient, diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearch.ts index 1e60d2c6c..c640eae20 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearch.ts @@ -4,6 +4,7 @@ import { IndexTag, IndexingProgressUpdate, } from "../index.js"; +import { getBasename } from "../util/index.js"; import { RETRIEVAL_PARAMS } from "../util/parameters.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; @@ -71,7 +72,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { yield { progress: i / results.compute.length, - desc: `Indexing ${item.path}`, + desc: `Indexing ${getBasename(item.path)}`, status: "indexing", }; markComplete([item], IndexResultType.Compute); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index d7e9899ef..1f6ea709e 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -11,7 +11,7 @@ import { } from "../index.js"; import { MAX_CHUNK_SIZE } from "../llm/constants.js"; import { getBasename } from "../util/index.js"; -import { getLanceDbPath } from "../util/paths.js"; +import { getLanceDbPath, migrate } from "../util/paths.js"; import { chunkDocument } from "./chunk/chunk.js"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { @@ -53,11 +53,25 @@ export class LanceDbIndex implements CodebaseIndex { uuid TEXT PRIMARY KEY, cacheKey TEXT NOT NULL, path TEXT NOT NULL, + artifact_id TEXT NOT NULL, vector TEXT NOT NULL, startLine INTEGER NOT NULL, endLine INTEGER NOT NULL, contents TEXT NOT NULL )`); + + await new Promise((resolve) => + migrate( + "lancedb_sqlite_artifact_id_column", + async () => { + await db.exec( + `ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'`, + ); + resolve(undefined); + }, + () => resolve(undefined), + ), + ); } private async *computeChunks( @@ -231,10 +245,11 @@ export class LanceDbIndex implements CodebaseIndex { rows.push(row); await sqlite.run( - "INSERT INTO lance_db_cache (uuid, cacheKey, path, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?)", + "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", row.uuid, row.cachekey, row.path, + this.artifactId, JSON.stringify(row.vector), chunk.startLine, chunk.endLine, @@ -265,10 +280,11 @@ export class LanceDbIndex implements CodebaseIndex { // Add the computed row to the cache await sqlite.run( - "INSERT INTO lance_db_cache (uuid, cacheKey, path, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?)", + "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", row.uuid, row.cachekey, row.path, + this.artifactId, JSON.stringify(row.vector), data.startLine, data.endLine, @@ -290,9 +306,10 @@ export class LanceDbIndex implements CodebaseIndex { // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { const stmt = await sqlite.prepare( - "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ?", + "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, + this.artifactId, ); const cachedItems = await stmt.all(); @@ -347,9 +364,10 @@ export class LanceDbIndex implements CodebaseIndex { // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { await sqlite.run( - "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ?", + "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, + this.artifactId, ); accumulatedProgress += 1 / results.del.length / 3; yield { diff --git a/core/indexing/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts index 22de70fb8..cd67a001a 100644 --- a/core/indexing/embeddings/BaseEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BaseEmbeddingsProvider.ts @@ -29,7 +29,7 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider { ...options, }; this.fetch = fetch; - this.id = this.options.model || this.constructor.name; + this.id = `${this.constructor.name}::${this.options.model}`; } abstract embed(chunks: string[]): Promise; diff --git a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts index 8ba07a728..6d356cef9 100644 --- a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts +++ b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts @@ -15,7 +15,7 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider { constructor(options: EmbedOptions, fetch: FetchFunction) { super(options, fetch); this.options.model = FreeTrialEmbeddingsProvider.defaultOptions?.model; - this.id = this.options.model || this.constructor.name; + this.id = `${this.constructor.name}::${this.options.model}`; } async embed(chunks: string[]) { diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 1277ba1cf..8881f6b5e 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -60,6 +60,11 @@ export const DEFAULT_IGNORE_FILETYPES = [ "*.gcno", "go.sum", ".env", + ".gitignore", + ".gitkeep", + ".continueignore", + "config.json", + "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt ]; export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); export const DEFAULT_IGNORE_DIRS = [ @@ -85,6 +90,7 @@ export const DEFAULT_IGNORE_DIRS = [ ".gradle", ".cache", "gems", + "vendor", ]; export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); diff --git a/core/jest.config.js b/core/jest.config.js index 035fe2139..1ec7c44f8 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -19,4 +19,5 @@ export default { __dirname: path.dirname(fileURLToPath(import.meta.url)), __filename: path.resolve(fileURLToPath(import.meta.url)), }, + globalSetup: "/jest.global-setup.ts", }; diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts new file mode 100644 index 000000000..1c4fe12e8 --- /dev/null +++ b/core/jest.global-setup.ts @@ -0,0 +1,6 @@ +// jest.global-setup.js +import path from "path"; + +export default async function () { + process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); +} diff --git a/core/test/.gitignore b/core/test/.gitignore new file mode 100644 index 000000000..227f3fc4f --- /dev/null +++ b/core/test/.gitignore @@ -0,0 +1 @@ +scratch.test.ts \ No newline at end of file diff --git a/core/test/_testEnv.test.ts b/core/test/_testEnv.test.ts new file mode 100644 index 000000000..3ebddd64b --- /dev/null +++ b/core/test/_testEnv.test.ts @@ -0,0 +1,6 @@ +describe("Test environment", () => { + test("should have CONTINUE_GLOBAL_DIR env var set to .continue-test", () => { + expect(process.env.CONTINUE_GLOBAL_DIR).toBeDefined(); + expect(process.env.CONTINUE_GLOBAL_DIR)?.toMatch(/\.continue-test$/); + }); +}); diff --git a/core/test/baseLLM.test.ts b/core/test/baseLLM.test.ts new file mode 100644 index 000000000..9a6f4fc3d --- /dev/null +++ b/core/test/baseLLM.test.ts @@ -0,0 +1,140 @@ +import { ChatMessage, LLMOptions, ModelProvider } from "../index"; +import { BaseLLM } from "../llm/index.js"; + +class DummyLLM extends BaseLLM { + static providerName: ModelProvider = "openai"; + static defaultOptions: Partial = { + model: "dummy-model", + contextLength: 200_000, + completionOptions: { + model: "some-model", + maxTokens: 4096, + }, + apiBase: "https://api.test-api-dummy.com/v1/", + }; +} +describe("BaseLLM", () => { + let baseLLM: BaseLLM; + + beforeEach(() => { + const options: LLMOptions = { + model: "dummy-model", + }; + // Instantiate a DummyLLM instance + baseLLM = new DummyLLM(options); + }); + + describe("BaseLLM constructor", () => { + it("should correctly initialize with given options", () => { + const templatMessagesFunction = (messages: ChatMessage[]) => { + return messages[0]?.content.toString() ?? ""; + }; + const writeLogFunction = async () => {}; + const options: LLMOptions = { + model: "gpt-3.5-turbo", + uniqueId: "testId", + systemMessage: "Test System Message", + contextLength: 1024, + completionOptions: { + model: "some-model", + maxTokens: 150, + }, + requestOptions: {}, + promptTemplates: {}, + templateMessages: templatMessagesFunction, + writeLog: writeLogFunction, + llmRequestHook: () => {}, + apiKey: "testApiKey", + aiGatewaySlug: "testSlug", + apiBase: "https://api.example.com", + accountId: "testAccountId", + engine: "davinci", + apiVersion: "v1", + apiType: "public", + region: "us", + projectId: "testProjectId", + }; + + const instance = new DummyLLM(options); + + expect(instance.title).toBeDefined(); + expect(instance.uniqueId).toBe("testId"); + expect(instance.model).toBe("gpt-3.5-turbo"); + expect(instance.systemMessage).toBe("Test System Message"); + expect(instance.contextLength).toBe(1024); + expect(instance.completionOptions.maxTokens).toBe(150); + expect(instance.requestOptions).toEqual({}); + expect(instance.promptTemplates).toEqual({}); + expect(instance.templateMessages).toEqual(templatMessagesFunction); + expect(instance.writeLog).toBe(writeLogFunction); + expect(instance.apiKey).toBe("testApiKey"); + expect(instance.aiGatewaySlug).toBe("testSlug"); + expect(instance.apiBase).toBe("https://api.example.com/"); + expect(instance.accountId).toBe("testAccountId"); + expect(instance.engine).toBe("davinci"); + expect(instance.apiVersion).toBe("v1"); + expect(instance.apiType).toBe("public"); + expect(instance.region).toBe("us"); + expect(instance.projectId).toBe("testProjectId"); + }); + }); + + test("model should return correct provider model", () => { + expect(baseLLM.model).toBe("dummy-model"); + }); + + test("supportsFim should always return false", () => { + expect(baseLLM.supportsFim()).toBe(false); + }); + + describe("supportsImages", () => { + test("should return true when modelSupportsImages returns true", () => { + baseLLM.model = "gpt-4-vision"; + expect(baseLLM.supportsImages()).toBe(true); + }); + + test("should return false when modelSupportsImages returns false", () => { + expect(baseLLM.supportsImages()).toBe(false); + }); + }); + + describe("supportsCompletions", () => { + test("should return correctly under specific conditions", () => { + // Mocking properties and scenarios to match the conditions in supportsCompletions + baseLLM.apiBase = "api.groq.com"; + expect(baseLLM.supportsCompletions()).toBe(false); + + baseLLM.apiBase = "api.mistral.ai"; + expect(baseLLM.supportsCompletions()).toBe(false); + + baseLLM.apiBase = ":1337"; + expect(baseLLM.supportsCompletions()).toBe(false); + + baseLLM.apiBase = "something:3000"; + expect(baseLLM.supportsCompletions()).toBe(true); + }); + }); + describe("supportsPrefill", () => { + test("should return correctly under specific conditions", () => { + expect(baseLLM.supportsPrefill()).toBe(false); + + class PrefillLLM extends BaseLLM { + static providerName: ModelProvider = "ollama"; + } + const prefillLLM = new PrefillLLM({ model: "some-model" }); + expect(prefillLLM.supportsPrefill()).toBe(true); + }); + }); + describe("fetch", () => { + // TODO: Implement tests for fetch method + }); + describe("*_streamFim", () => { + // TODO: Implement tests for *_streamFim method + }); + describe("complete", () => { + // TODO: Implement tests for complete method + }); + describe("*streamChat", () => { + // TODO: Implement tests for *streamChat method + }); +}); diff --git a/core/test/context/retrieval/RetrievalPipeline.test.ts b/core/test/context/retrieval/RetrievalPipeline.test.ts new file mode 100644 index 000000000..cb707d39a --- /dev/null +++ b/core/test/context/retrieval/RetrievalPipeline.test.ts @@ -0,0 +1,20 @@ +import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline"; + +function testRetrievalPipeline(pipeline: IRetrievalPipeline) { + test("should successfully run"); +} + +// describe("Retrieval Pipelines", () => { +// const ide = new FileSystemIde(); +// const options: RetrievalPipelineOptions; + +// test("NoRerankerRetrievalPipeline", () => { +// const pipeline = new NoRerankerRetrievalPipeline(options); +// testRetrievalPipeline(pipeline); +// }); + +// test("NoRerankerRetrievalPipeline", () => { +// const pipeline = new NoRerankerRetrievalPipeline(options); +// testRetrievalPipeline(pipeline); +// }); +// }); diff --git a/core/test/indexing/CodebaseIndexer.test.ts b/core/test/indexing/CodebaseIndexer.test.ts new file mode 100644 index 000000000..db4c5107e --- /dev/null +++ b/core/test/indexing/CodebaseIndexer.test.ts @@ -0,0 +1,174 @@ +import fs from "node:fs"; +import path from "node:path"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { ContinueServerClient } from "../../continueServer/stubs/client"; +import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer"; +import { LanceDbIndex } from "../../indexing/LanceDbIndex"; +import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import FileSystemIde from "../../util/filesystem"; +import { + getIndexFolderPath, + getIndexSqlitePath, + getLanceDbPath, +} from "../../util/paths"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR, +} from "../testUtils/testDir"; + +const TEST_TS = `\ +function main() { + console.log("Hello, world!"); +} + +class Foo { + constructor(public bar: string) {} +} +`; + +const TEST_PY = `\ +def main(): + print("Hello, world!") + +class Foo: + def __init__(self, bar: str): + self.bar = bar +`; + +const TEST_RS = `\ +fn main() { + println!("Hello, world!"); +} + +struct Foo { + bar: String, +} +`; + +// These are more like integration tests, whereas we should separately test +// the individual CodebaseIndex classes +describe.skip("CodebaseIndexer", () => { + const ide = new FileSystemIde(TEST_DIR); + const ideSettingsPromise = ide.getIdeSettings(); + const configHandler = new ConfigHandler( + ide, + ideSettingsPromise, + async (text) => {}, + ); + const pauseToken = new PauseToken(false); + const continueServerClient = new ContinueServerClient(undefined, undefined); + const codebaseIndexer = new CodebaseIndexer( + configHandler, + ide, + pauseToken, + continueServerClient, + ); + const lancedbIndex = new LanceDbIndex( + new TransformersJsEmbeddingsProvider(), + ide.readFile.bind(ide), + continueServerClient, + ); + + beforeAll(async () => { + setUpTestDir(); + }); + + afterAll(async () => { + tearDownTestDir(); + }); + + test("should index test folder without problem", async () => { + addToTestDir([ + ["test.ts", TEST_TS], + ["py/main.py", TEST_PY], + ]); + const abortController = new AbortController(); + const abortSignal = abortController.signal; + + const updates = []; + for await (const update of codebaseIndexer.refresh( + [TEST_DIR], + abortSignal, + )) { + updates.push(update); + } + + expect(updates.length).toBeGreaterThan(0); + }); + + test("should have created index folder with all necessary files", async () => { + expect(fs.existsSync(getIndexFolderPath())).toBe(true); + expect(fs.existsSync(getIndexSqlitePath())).toBe(true); + expect(fs.existsSync(getLanceDbPath())).toBe(true); + }); + + test("should be able to query lancedb index", async () => { + const chunks = await lancedbIndex.retrieve( + "What is the main function doing?", + 10, + await ide.getTags(lancedbIndex.artifactId), + undefined, + ); + + expect(chunks.length).toBe(2); + // Check that the main function from both files is returned + expect(chunks.some((chunk) => chunk.filepath.endsWith("test.ts"))).toBe( + true, + ); + expect(chunks.some((chunk) => chunk.filepath.endsWith("main.py"))).toBe( + true, + ); + }); + + test("should successfully re-index after adding a file", async () => { + addToTestDir([["main.rs", TEST_RS]]); + const abortController = new AbortController(); + const abortSignal = abortController.signal; + const updates = []; + for await (const update of codebaseIndexer.refresh( + [TEST_DIR], + abortSignal, + )) { + updates.push(update); + } + expect(updates.length).toBeGreaterThan(0); + // Check that the new file was indexed + const chunks = await lancedbIndex.retrieve( + "What is the main function doing?", + 3, + await ide.getTags(lancedbIndex.artifactId), + undefined, + ); + expect(chunks.length).toBe(3); + expect(chunks.some((chunk) => chunk.filepath.endsWith("main.rs"))).toBe( + true, + ); + }); + + test("should successfully re-index after deleting a file", async () => { + fs.rmSync(path.join(TEST_DIR, "main.rs")); + const abortController = new AbortController(); + const abortSignal = abortController.signal; + const updates = []; + for await (const update of codebaseIndexer.refresh( + [TEST_DIR], + abortSignal, + )) { + updates.push(update); + } + expect(updates.length).toBeGreaterThan(0); + // Check that the deleted file was removed from the index + const chunks = await lancedbIndex.retrieve( + "What is the main function doing?", + 10, + await ide.getTags(lancedbIndex.artifactId), + undefined, + ); + expect(chunks.length).toBe(2); + expect(chunks.every((chunk) => !chunk.filepath.endsWith("main.rs"))).toBe( + true, + ); + }); +}); diff --git a/core/test/testUtils/testDir.ts b/core/test/testUtils/testDir.ts new file mode 100644 index 000000000..33a636d08 --- /dev/null +++ b/core/test/testUtils/testDir.ts @@ -0,0 +1,27 @@ +import fs from "fs"; +import path from "path"; + +export const TEST_DIR = path.join(__dirname, "testDir"); + +export function setUpTestDir() { + if (fs.existsSync(TEST_DIR)) { + fs.rmSync(TEST_DIR, { recursive: true }); + } + fs.mkdirSync(TEST_DIR); +} + +export function tearDownTestDir() { + fs.rmSync(TEST_DIR, { recursive: true }); +} + +export function addToTestDir(paths: (string | string[])[]) { + for (const p of paths) { + if (Array.isArray(p)) { + fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]); + } else if (p.endsWith("/")) { + fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true }); + } else { + fs.writeFileSync(path.join(TEST_DIR, p), ""); + } + } +} diff --git a/core/test/util/deduplicateArray.test.ts b/core/test/util/deduplicateArray.test.ts new file mode 100644 index 000000000..f26b2c782 --- /dev/null +++ b/core/test/util/deduplicateArray.test.ts @@ -0,0 +1,82 @@ +import { deduplicateArray } from "../../util"; + +describe("deduplicateArray", () => { + it("should return an empty array when given an empty array", () => { + const result = deduplicateArray([], (a, b) => a === b); + expect(result).toEqual([]); + }); + + it("should return the same array when there are no duplicates", () => { + const input = [1, 2, 3, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(input); + }); + + it("should remove duplicates based on the equality function", () => { + const input = [1, 2, 2, 3, 4, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1, 2, 3, 4, 5]); + }); + + it("should work with objects using custom equality function", () => { + const input = [ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 1, name: "Alice" }, + { id: 3, name: "Charlie" }, + ]; + const result = deduplicateArray(input, (a, b) => a.id === b.id); + expect(result).toEqual([ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 3, name: "Charlie" }, + ]); + }); + + it("should preserve the order of items", () => { + const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); + }); + + it("should work with strings", () => { + const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(["apple", "banana", "cherry", "date"]); + }); + + it("should handle arrays with all duplicate elements", () => { + const input = [1, 1, 1, 1, 1]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1]); + }); + + it("should work with custom equality function for complex objects", () => { + const input = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, + { x: 3, y: 4 }, + ]; + const result = deduplicateArray( + input, + (a, b) => a.x === b.x && a.y === b.y, + ); + expect(result).toEqual([ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 3, y: 4 }, + ]); + }); + + it("should handle large arrays efficiently", () => { + const input = Array(10000) + .fill(0) + .map((_, i) => i % 100); + const start = performance.now(); + const result = deduplicateArray(input, (a, b) => a === b); + const end = performance.now(); + expect(result).toHaveLength(100); + expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second + }); +}); diff --git a/core/test/walkDir.test.ts b/core/test/walkDir.test.ts index e3f4b9e0b..93abbe911 100644 --- a/core/test/walkDir.test.ts +++ b/core/test/walkDir.test.ts @@ -1,22 +1,13 @@ -import fs from "fs"; import path from "path"; import { walkDir, WalkerOptions } from "../indexing/walkDir"; import FileSystemIde from "../util/filesystem"; -const ide = new FileSystemIde(); - -const TEST_DIR = path.join(__dirname, "testDir"); - -function buildTestDir(paths: (string | string[])[]) { - for (const p of paths) { - if (Array.isArray(p)) { - fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]); - } else if (p.endsWith("/")) { - fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true }); - } else { - fs.writeFileSync(path.join(TEST_DIR, p), ""); - } - } -} +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR, +} from "./testUtils/testDir"; +const ide = new FileSystemIde(TEST_DIR); async function walkTestDir( options?: WalkerOptions, @@ -44,14 +35,11 @@ async function expectPaths( describe("walkDir", () => { beforeEach(() => { - if (fs.existsSync(TEST_DIR)) { - fs.rmSync(TEST_DIR, { recursive: true }); - } - fs.mkdirSync(TEST_DIR); + setUpTestDir(); }); afterEach(() => { - fs.rmSync(TEST_DIR, { recursive: true }); + tearDownTestDir(); }); test("should return nothing for empty dir", async () => { @@ -61,20 +49,20 @@ describe("walkDir", () => { test("should return all files in flat dir", async () => { const files = ["a.txt", "b.py", "c.ts"]; - buildTestDir(files); + addToTestDir(files); const result = await walkTestDir(); expect(result).toEqual(files); }); test("should ignore ignored files in flat dir", async () => { const files = [[".gitignore", "*.py"], "a.txt", "c.ts", "b.py"]; - buildTestDir(files); - await expectPaths(["a.txt", "c.ts", ".gitignore"], ["b.py"]); + addToTestDir(files); + await expectPaths(["a.txt", "c.ts"], ["b.py"]); }); test("should handle negation in flat folder", async () => { const files = [[".gitignore", "**/*\n!*.py"], "a.txt", "c.ts", "b.py"]; - buildTestDir(files); + addToTestDir(files); await expectPaths(["b.py"], [".gitignore", "a.txt", "c.ts"]); }); @@ -89,7 +77,7 @@ describe("walkDir", () => { "d/g/", "d/g/h.ts", ]; - buildTestDir(files); + addToTestDir(files); await expectPaths( files.filter((files) => !files.endsWith("/")), [], @@ -108,16 +96,16 @@ describe("walkDir", () => { "d/g/h.ts", ["d/.gitignore", "*.py"], ]; - buildTestDir(files); + addToTestDir(files); await expectPaths( - ["a.txt", "b.py", "c.ts", "d/e.txt", "d/g/h.ts", "d/.gitignore"], + ["a.txt", "b.py", "c.ts", "d/e.txt", "d/g/h.ts"], ["d/f.py"], ); }); test("should handle leading slash in gitignore", async () => { const files = [[".gitignore", "/no.txt"], "a.txt", "b.py", "no.txt"]; - buildTestDir(files); + addToTestDir(files); await expectPaths(["a.txt", "b.py"], ["no.txt"]); }); @@ -131,7 +119,7 @@ describe("walkDir", () => { "c/e.py", ["c/.gitignore", "*.py"], ]; - buildTestDir(files); + addToTestDir(files); await expectPaths(["a.py"], ["b.txt", "c/e.py", "c/d.txt"]); }); @@ -146,7 +134,7 @@ describe("walkDir", () => { "d/f.py", "d/g.ts", ]; - buildTestDir(files); + addToTestDir(files); await expectPaths( ["c.ts", "d/g.ts"], ["a.txt", "b.py", "d/e.txt", "d/f.py"], @@ -162,7 +150,7 @@ describe("walkDir", () => { "ignored_dir/c/", "ignored_dir/c/d.py", ]; - buildTestDir(files); + addToTestDir(files); await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]); }); @@ -178,7 +166,7 @@ describe("walkDir", () => { "temp/", "temp/c.txt", ]; - buildTestDir(files); + addToTestDir(files); await expectPaths( ["important.what", "subdir/root_only.txt"], ["a.what", "root_only.txt", "subdir/b.what", "temp/c.txt"], @@ -194,11 +182,8 @@ describe("walkDir", () => { "c.ts", "d.js", ]; - buildTestDir(files); - await expectPaths( - ["a.txt", "d.js", ".gitignore", ".continueignore"], - ["b.py", "c.ts"], - ); + addToTestDir(files); + await expectPaths(["a.txt", "d.js"], ["b.py", "c.ts"]); }); test("should return dirs and only dirs in onlyDirs mode", async () => { @@ -212,7 +197,7 @@ describe("walkDir", () => { "d/g/", "d/g/h.ts", ]; - buildTestDir(files); + addToTestDir(files); await expectPaths( ["d", "d/g"], ["a.txt", "b.py", "c.ts", "d/e.txt", "d/f.py", "d/g/h.ts"], @@ -222,7 +207,7 @@ describe("walkDir", () => { test("should return valid paths in absolute path mode", async () => { const files = ["a.txt", "b/", "b/c.txt"]; - buildTestDir(files); + addToTestDir(files); await expectPaths( [path.join(TEST_DIR, "a.txt"), path.join(TEST_DIR, "b", "c.txt")], [], @@ -232,28 +217,60 @@ describe("walkDir", () => { ); }); - test.skip("should walk continue repo", async () => { - const results = await walkDir(path.join(__dirname, "..", ".."), ide, { - ignoreFiles: [".gitignore", ".continueignore"], - }); - console.log(results); - }); - - test.skip("should skip .git and node_modules folders", async () => { + test("should skip .git and node_modules folders", async () => { const files = [ "a.txt", ".git/", ".git/config", ".git/HEAD", + ".git/objects/", + ".git/objects/1234567890abcdef", "node_modules/", + "node_modules/package/", "node_modules/package/index.js", "src/", "src/index.ts", ]; - buildTestDir(files); + addToTestDir(files); await expectPaths( ["a.txt", "src/index.ts"], - [".git/config", ".git/HEAD", "node_modules/package/index.js"], + [ + ".git/config", + ".git/HEAD", + "node_modules/package/index.js", + ".git/objects/1234567890abcdef", + ], ); }); + + test("should walk continue repo without getting any files of the default ignore types", async () => { + const results = await walkDir(path.join(__dirname, "..", ".."), ide, { + ignoreFiles: [".gitignore", ".continueignore"], + }); + expect(results.length).toBeGreaterThan(0); + expect(results.some((file) => file.includes("/node_modules/"))).toBe(false); + expect(results.some((file) => file.includes("/.git/"))).toBe(false); + expect( + results.some( + (file) => + file.endsWith(".gitignore") || + file.endsWith(".continueignore") || + file.endsWith("package-lock.json"), + ), + ).toBe(false); + // At some point we will cross this number, but in case we leap past it suddenly I think we'd want to investigate why + expect(results.length).toBeLessThan(1500); + }); + + test("should walk continue/extensions/vscode without getting any files in the .continueignore", async () => { + const vscodePath = path.join(__dirname, "..", "..", "extensions", "vscode"); + const results = await walkDir(vscodePath, ide, { + ignoreFiles: [".gitignore", ".continueignore"], + }); + expect(results.length).toBeGreaterThan(0); + expect(results.some((file) => file.includes("/textmate-syntaxes/"))).toBe( + false, + ); + expect(results.some((file) => file.includes(".tmLanguage"))).toBe(false); + }); }); diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index cde6332b6..b9d35cdb9 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -17,11 +17,7 @@ import { import { getContinueGlobalPath } from "./paths.js"; class FileSystemIde implements IDE { - static workspaceDir = "/tmp/continue"; - - constructor() { - fs.mkdirSync(FileSystemIde.workspaceDir, { recursive: true }); - } + constructor(private readonly workspaceDir: string) {} pathSep(): Promise { return Promise.resolve(path.sep); } @@ -141,14 +137,7 @@ class FileSystemIde implements IDE { } getWorkspaceDirs(): Promise { - return new Promise((resolve, reject) => { - fs.mkdtemp(FileSystemIde.workspaceDir, (err, folder) => { - if (err) { - reject(err); - } - resolve([folder]); - }); - }); + return Promise.resolve([this.workspaceDir]); } listFolders(): Promise { diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 8909af6f4..13b38626d 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -27,7 +27,9 @@ export const DO_NOT_COUNT_REJECTED_BEFORE = 250; export const RETRIEVAL_PARAMS = { rerankThreshold: 0.3, - nFinal: 10, - nRetrieve: 20, + nFinal: 20, + nRetrieve: 50, bm25Threshold: -2.5, + nResultsToExpandWithEmbeddings: 5, + nEmbeddingsExpandTo: 5, }; diff --git a/core/util/paths.ts b/core/util/paths.ts index 1cb76c47a..f7c7fc1d3 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -177,12 +177,22 @@ function getMigrationsFolderPath(): string { return migrationsPath; } -export function migrate(id: string, callback: () => void) { +export function migrate( + id: string, + callback: () => void, + onAlreadyComplete?: () => void, +) { const migrationsPath = getMigrationsFolderPath(); const migrationPath = path.join(migrationsPath, id); if (!fs.existsSync(migrationPath)) { - fs.writeFileSync(migrationPath, ""); - callback(); + try { + callback(); + fs.writeFileSync(migrationPath, ""); + } catch (e) { + console.error(`Migration ${id} failed`, e); + } + } else if (onAlreadyComplete) { + onAlreadyComplete(); } } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 1978a88a7..cff56a21c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -93,6 +93,11 @@ export async function getParserForFile(filepath: string) { } } +// Loading the wasm files to create a Language object is an expensive operation and with +// sufficient number of files can result in errors, instead keep a map of language name +// to Language object +const nameToLanguage = new Map(); + export async function getLanguageForFile( filepath: string, ): Promise { @@ -100,18 +105,15 @@ export async function getLanguageForFile( await Parser.init(); const extension = path.extname(filepath).slice(1); - if (!supportedLanguages[extension]) { + const languageName = supportedLanguages[extension]; + if (!languageName) { return undefined; } - - const wasmPath = path.join( - __dirname, - ...(process.env.NODE_ENV === "test" - ? ["node_modules", "tree-sitter-wasms", "out"] - : ["tree-sitter-wasms"]), - `tree-sitter-${supportedLanguages[extension]}.wasm`, - ); - const language = await Parser.Language.load(wasmPath); + let language = nameToLanguage.get(languageName); + if (!language) { + language = await loadLanguageForFileExt(extension); + nameToLanguage.set(languageName, language); + } return language; } catch (e) { console.error("Unable to load language for file", filepath, e); @@ -149,3 +151,14 @@ export async function getQueryForFile( const query = language.query(querySource); return query; } + +async function loadLanguageForFileExt(fileExtension: string): Promise { + const wasmPath = path.join( + __dirname, + ...(process.env.NODE_ENV === "test" + ? ["node_modules", "tree-sitter-wasms", "out"] + : ["tree-sitter-wasms"]), + `tree-sitter-${supportedLanguages[fileExtension]}.wasm`, + ); + return await Parser.Language.load(wasmPath); +} diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index dfce3a6da..886f129c8 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -21,7 +21,7 @@ All data is anonymous and cleaned of PII before being sent to PostHog. ## What we track - Whether you accept or reject suggestions (never including the code or the prompt) -- The name of the model and slash command used +- The name of the model and command used - The number of tokens generated - The name of your OS and IDE - Pageviews diff --git a/docs/docs/walkthroughs/quick-actions.md b/docs/docs/walkthroughs/quick-actions.md new file mode 100644 index 000000000..c08cfc746 --- /dev/null +++ b/docs/docs/walkthroughs/quick-actions.md @@ -0,0 +1,95 @@ +--- +title: Quick Actions (experimental, VS Code only) +description: Quick Actions automate repetitive tasks and streamline your development workflow +keywords: [experimental, automate, configuration] +toc_max_heading_level: 5 +--- + +# Quick Actions (experimental, VS Code only) + +Quick Actions automate repetitive tasks and streamline your development workflow. Configure custom actions to execute complex operations with a single click. + +![Quick actions example](/img/quick-actions-demo.gif) + +## How It Works + +:::info[Note] +For the language of the file you have open, you must have the Language Server Protocol extension installed. +::: + +Quick Actions use a CodeLens provider to add interactive elements above functions and classes in your code. + +By default, Quick Actions include two predefined actions: + +1. `Explain`: This action provides a short explanation of the selected code. +2. `Docstring`: This action generates a docstring comment and inserts it above the code. + +## How to disable Quick Actions + +Quick Actions are enabled by default _for pre-release versions of Contine_. + +To disable Quick Actions, open the settings menu (`⌘ + ,`), search for `"continue.enableQuickActions"`, and toggle the checkbox to disable. + +## Custom Quick Actions + +Custom Quick Actions allow you to tailor functionality to your specific needs, extending beyond the default actions. You can easily configure these custom actions in your `~/.continue/config.json` file. + +:::info +[View the Configuration Options reference](../reference/config) for specific schema details. +::: + +### Example Use Cases + +#### 1. Write an inline unit test + +A quick action that generates and inserts a unit test above the selected code. + +```json title=~/.continue/config.json +"experimental": { + "quickActions": [ + { + "title": "Unit test", + "prompt": "Write a unit test for this code. Do not change anything about the code itself.", + } + ] + } +``` + +#### 2. Send code to chat panel to learn more about it + +The default "Explain" aims to provide a brief overview of the code. This quick action sends the prompt and the code to the chat to provides a more detailed explanation. + +```json title=~/.continue/config.json +"experimental": { + "quickActions": [ + { + "title": "Detailed explanation", + "prompt": "Explain the following code in detail, including all methods and properties.", + "sendToChat": true + } + ] + } +``` + +#### 3. Create a Typescript interface + +A quick action that generates and inserts a Typescript interface above the selected code. + +```json title=~/.continue/config.json +"experimental": { + "quickActions": [ + { + "title": "Create Interface", + "prompt": "Create a new Typescript interface for the following code.", + } + ] + } +``` + +## Share your feedback + +We'd love to hear your thoughts on Quick Actions! Share your feedback and help us improve. + + + +Give Feedback on Discord diff --git a/docs/sidebars.js b/docs/sidebars.js index ab007865d..08ebe4d20 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -50,6 +50,7 @@ const sidebars = { "walkthroughs/codebase-embeddings", "walkthroughs/tab-autocomplete", "walkthroughs/prompt-files", + "walkthroughs/quick-actions", ], }, "development-data", diff --git a/docs/static/img/quick-actions-demo.gif b/docs/static/img/quick-actions-demo.gif new file mode 100644 index 000000000..8487ac022 Binary files /dev/null and b/docs/static/img/quick-actions-demo.gif differ diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index b236a4909..657d48c16 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -2161,6 +2161,29 @@ "promptPath": { "type": "string" }, + "quickActions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The title of the quick action that will display in the Code Lens." + }, + "prompt": { + "type": "string", + "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." + }, + "sendToChat": { + "type": "boolean", + "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", + "default": false + } + }, + "required": ["prompt", "title"] + }, + "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." + }, "contextMenuPrompts": { "type": "object", "properties": { diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index b236a4909..657d48c16 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -2161,6 +2161,29 @@ "promptPath": { "type": "string" }, + "quickActions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The title of the quick action that will display in the Code Lens." + }, + "prompt": { + "type": "string", + "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." + }, + "sendToChat": { + "type": "boolean", + "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", + "default": false + } + }, + "required": ["prompt", "title"] + }, + "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." + }, "contextMenuPrompts": { "type": "object", "properties": { diff --git a/extensions/vscode/.continueignore b/extensions/vscode/.continueignore index 7fd2a214a..2a5d96ea4 100644 --- a/extensions/vscode/.continueignore +++ b/extensions/vscode/.continueignore @@ -1,3 +1,6 @@ media **/*.tmLanguage -textmate-syntaxes \ No newline at end of file +models/**/* +builtin-themes/ +**/textmate-syntaxes/ +**/*.scm \ No newline at end of file diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index b236a4909..657d48c16 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2161,6 +2161,29 @@ "promptPath": { "type": "string" }, + "quickActions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The title of the quick action that will display in the Code Lens." + }, + "prompt": { + "type": "string", + "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." + }, + "sendToChat": { + "type": "boolean", + "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", + "default": false + } + }, + "required": ["prompt", "title"] + }, + "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." + }, "contextMenuPrompts": { "type": "object", "properties": { diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 67eba418e..37d8bfe1b 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -2425,6 +2425,32 @@ "promptPath": { "type": "string" }, + "quickActions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The title of the quick action that will display in the Code Lens." + }, + "prompt": { + "type": "string", + "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." + }, + "sendToChat": { + "type": "boolean", + "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", + "default": false + } + }, + "required": [ + "prompt", + "title" + ] + }, + "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." + }, "contextMenuPrompts": { "type": "object", "properties": { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 6873f1d75..92cd86f32 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.172", + "version": "0.9.174", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.172", + "version": "0.9.174", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index c5381e16a..4f1a3a103 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -1,7 +1,7 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.9.174", + "version": "0.9.175", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -79,10 +79,15 @@ "default": true, "description": "Show inline suggestion to use the Continue keyboard shortcuts (e.g. \"Cmd/Ctrl L to select code, Cmd/Ctrl I to edit\")." }, + "continue.enableQuickActions": { + "type": "boolean", + "default": true, + "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/walkthroughs/quick-actions)" + }, "continue.enableTabAutocomplete": { "type": "boolean", "default": true, - "markdownDescription": "Enable Continue's tab autocomplete feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete](https://docs.continue.dev/walkthroughs/tab-autocomplete)" + "markdownDescription": "Enable Continue's tab autocomplete feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete (beta)](https://docs.continue.dev/walkthroughs/tab-autocomplete)" }, "continue.pauseTabAutocompleteOnBattery": { "type": "boolean", @@ -317,7 +322,8 @@ { "command": "continue.toggleTabAutocompleteEnabled", "mac": "cmd+k cmd+a", - "key": "ctrl+k ctrl+a" + "key": "ctrl+k ctrl+a", + "when": "!terminalFocus" } ], "submenus": [ diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index 47882d669..9aa62fa7a 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -9,7 +9,7 @@ const esbuildConfig = { external: ["vscode", "esbuild", "./xhr-sync-worker.js"], format: "cjs", platform: "node", - sourcemap: false, + sourcemap: flags.includes("--sourcemap"), loader: { // eslint-disable-next-line @typescript-eslint/naming-convention ".node": "file", diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index e76effba8..3befe838e 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -4,13 +4,18 @@ import { CompletionProvider, type AutocompleteInput, } from "core/autocomplete/completionProvider"; -import type { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; -import { StatusBarStatus, setupStatusBar, stopStatusBarLoading, getStatusBarStatus } from "./statusBar"; +import { + StatusBarStatus, + getStatusBarStatus, + setupStatusBar, + stopStatusBarLoading, +} from "./statusBar"; interface VsCodeCompletionInput { document: vscode.TextDocument; @@ -43,7 +48,7 @@ export class ContinueCompletionProvider private recentlyEditedTracker = new RecentlyEditedTracker(); constructor( - private readonly configHandler: ConfigHandler, + private readonly configHandler: IConfigHandler, private readonly ide: IDE, private readonly tabAutocompleteModel: TabAutocompleteModel, ) { @@ -73,7 +78,8 @@ export class ContinueCompletionProvider token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { - const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled; + const enableTabAutocomplete = + getStatusBarStatus() === StatusBarStatus.Enabled; if (token.isCancellationRequested || !enableTabAutocomplete) { return null; } diff --git a/extensions/vscode/src/autocomplete/statusBar.ts b/extensions/vscode/src/autocomplete/statusBar.ts index 48b2788f3..db707c754 100644 --- a/extensions/vscode/src/autocomplete/statusBar.ts +++ b/extensions/vscode/src/autocomplete/statusBar.ts @@ -1,5 +1,9 @@ import * as vscode from "vscode"; import { Battery } from "../util/battery"; +import { + CONTINUE_WORKSPACE_KEY, + getContinueWorkspaceConfig, +} from "../util/workspaceConfig"; export enum StatusBarStatus { Disabled, @@ -91,13 +95,18 @@ export function setupStatusBar( statusBarItem.command = "continue.openTabAutocompleteConfigMenu"; statusBarItem.show(); - if (status !== undefined) statusBarStatus = status; + if (status !== undefined) { + statusBarStatus = status; + } vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("continue")) { - const config = vscode.workspace.getConfiguration("continue"); - const enabled = config.get("enableTabAutocomplete"); - if (enabled && statusBarStatus === StatusBarStatus.Paused) return; + if (event.affectsConfiguration(CONTINUE_WORKSPACE_KEY)) { + const enabled = getContinueWorkspaceConfig().get( + "enableTabAutocomplete", + ); + if (enabled && statusBarStatus === StatusBarStatus.Paused) { + return; + } setupStatusBar( enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled, ); diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 411bde18a..06f3b2f58 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/naming-convention */ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; @@ -5,7 +6,7 @@ import * as vscode from "vscode"; import { ContextMenuConfig, IDE } from "core"; import { CompletionProvider } from "core/autocomplete/completionProvider"; -import { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; import { GlobalContext } from "core/util/GlobalContext"; import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths"; @@ -34,6 +35,18 @@ function getFullScreenTab() { ); } +type TelemetryCaptureParams = Parameters; + +/** + * Helper method to add the `isCommandEvent` to all telemetry captures + */ +function captureCommandTelemetry( + commandName: TelemetryCaptureParams[0], + properties: TelemetryCaptureParams[1] = {}, +) { + Telemetry.capture(commandName, { isCommandEvent: true, ...properties }); +} + async function addHighlightedCodeToContext( edit: boolean, webviewProtocol: VsCodeWebviewProtocol | undefined, @@ -153,7 +166,7 @@ const commandsMap: ( ide: IDE, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, - configHandler: ConfigHandler, + configHandler: IConfigHandler, diffManager: DiffManager, verticalDiffManager: VerticalPerLineDiffManager, continueServerClientPromise: Promise, @@ -168,23 +181,42 @@ const commandsMap: ( continueServerClientPromise, battery, ) => { + /** + * 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 modelTitle = config.experimental?.modelRoles?.inlineEdit ?? (await sidebar.webviewProtocol.request( "getDefaultModelTitle", undefined, )); + sidebar.webviewProtocol.request("incrementFtc", undefined); + await verticalDiffManager.streamEdit( config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, modelTitle, onlyOneInsertion, + undefined, + range, ); } @@ -202,6 +234,8 @@ const commandsMap: ( return { "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + if (newFilepath instanceof vscode.Uri) { newFilepath = newFilepath.fsPath; } @@ -209,6 +243,8 @@ const commandsMap: ( await diffManager.acceptDiff(newFilepath); }, "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); + if (newFilepath instanceof vscode.Uri) { newFilepath = newFilepath.fsPath; } @@ -216,9 +252,11 @@ const commandsMap: ( await diffManager.rejectDiff(newFilepath); }, "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 ( @@ -226,6 +264,10 @@ const commandsMap: ( code: string, edit: boolean, ) => { + captureCommandTelemetry("rejectVerticalDiffBlock", { + edit, + }); + sidebar.webviewProtocol?.request("newSessionWithPrompt", { prompt: `${ edit ? "/edit " : "" @@ -236,6 +278,47 @@ const commandsMap: ( vscode.commands.executeCommand("continue.continueGUIView.focus"); } }, + "continue.defaultQuickActionDocstring": async (range: vscode.Range) => { + captureCommandTelemetry("defaultQuickActionDocstring"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + range, + ); + }, + "continue.defaultQuickActionExplain": async (code: string) => { + captureCommandTelemetry("defaultQuickActionExplain"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: + `Explain the following code in a few sentences without ` + + `going into detail on specific methods:\n\n ${code}`, + }); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + code: string, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `${prompt}:\n\n ${code}`, + }); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); + + streamInlineEdit("docstring", prompt, false, range); + }, "continue.focusContinueInput": async () => { const fullScreenTab = getFullScreenTab(); if (!fullScreenTab) { @@ -262,15 +345,20 @@ const commandsMap: ( vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); }, "continue.quickEdit": (injectedPrompt?: string) => { + captureCommandTelemetry("quickEdit"); quickEdit.run(injectedPrompt); }, "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.", @@ -278,21 +366,27 @@ const commandsMap: ( ); }, "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 @@ -305,8 +399,12 @@ const commandsMap: ( 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()}`, }); @@ -319,6 +417,8 @@ const commandsMap: ( // Commands without keyboard shortcuts "continue.addModel": () => { + captureCommandTelemetry("addModel"); + vscode.commands.executeCommand("continue.continueGUIView.focus"); sidebar.webviewProtocol?.request("addModel", undefined); }, @@ -354,6 +454,7 @@ const commandsMap: ( }); }, "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); ide.runCommand(text); }, "continue.newSession": () => { @@ -380,7 +481,7 @@ const commandsMap: ( } //Full screen not open - open it - Telemetry.capture("openFullScreen", {}); + captureCommandTelemetry("openFullScreen"); // Close the sidebar.webviews // vscode.commands.executeCommand("workbench.action.closeSidebar"); @@ -437,6 +538,8 @@ const commandsMap: ( completionProvider.accept(completionId); }, "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); + const config = vscode.workspace.getConfiguration("continue"); const enabled = config.get("enableTabAutocomplete"); const pauseOnBattery = config.get( @@ -471,6 +574,8 @@ const commandsMap: ( } }, "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); + const config = vscode.workspace.getConfiguration("continue"); const quickPick = vscode.window.createQuickPick(); const selected = new GlobalContext().get("selectedTabAutocompleteModel"); @@ -565,9 +670,11 @@ const commandsMap: ( } }, "continue.quickEditHistoryUp": async () => { + captureCommandTelemetry("quickEditHistoryUp"); historyUpEventEmitter.fire(); }, "continue.quickEditHistoryDown": async () => { + captureCommandTelemetry("quickEditHistoryDown"); historyDownEventEmitter.fire(); }, }; @@ -578,7 +685,7 @@ export function registerAllCommands( ide: IDE, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, - configHandler: ConfigHandler, + configHandler: IConfigHandler, diffManager: DiffManager, verticalDiffManager: VerticalPerLineDiffManager, continueServerClientPromise: Promise, diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 41d2f26ea..2c22158c6 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -1,5 +1,5 @@ import type { FileEdit } from "core"; -import type { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import * as vscode from "vscode"; import { getTheme } from "./util/getTheme"; import { getExtensionVersion } from "./util/util"; @@ -46,7 +46,7 @@ export class ContinueGUIWebviewViewProvider } constructor( - private readonly configHandlerPromise: Promise, + private readonly configHandlerPromise: Promise, private readonly windowId: string, private readonly extensionContext: vscode.ExtensionContext, ) { diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index 5259b4665..f6c4eafb4 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -1,4 +1,4 @@ -import type { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; import { streamDiffLines } from "core/util/verticalEdit"; @@ -21,7 +21,7 @@ export class VerticalPerLineDiffManager { private userChangeListener: vscode.Disposable | undefined; - constructor(private readonly configHandler: ConfigHandler) { + constructor(private readonly configHandler: IConfigHandler) { this.userChangeListener = undefined; } @@ -172,11 +172,36 @@ export class VerticalPerLineDiffManager { } } + /** + * 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, onlyOneInsertion?: boolean, quickEdit?: string, + range?: vscode.Range, ) { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -188,9 +213,15 @@ export class VerticalPerLineDiffManager { const filepath = editor.document.uri.fsPath; - // Initialize start/end at editor selection - let startLine = editor.selection.start.line; - let endLine = editor.selection.end.line; + let startLine, endLine: number; + + if (range) { + startLine = range.start.line; + endLine = range.end.line; + } else { + startLine = editor.selection.start.line; + endLine = editor.selection.end.line; + } // Check for existing handlers in the same file the new one will be created in const existingHandler = this.getHandlerForFile(filepath); @@ -274,11 +305,13 @@ export class VerticalPerLineDiffManager { llm.model, ); - // Unselect the range - editor.selection = new vscode.Selection( - editor.selection.active, - editor.selection.active, - ); + if (editor.selection) { + // Unselect the range + editor.selection = new vscode.Selection( + editor.selection.active, + editor.selection.active, + ); + } vscode.commands.executeCommand( "setContext", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 002b6a2d9..557f6b17d 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -1,5 +1,5 @@ import { IContextProvider } from "core"; -import { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import { Core } from "core/core"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; import { InProcessMessenger } from "core/util/messenger"; @@ -25,11 +25,12 @@ import { Battery } from "../util/battery"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; import { VsCodeMessenger } from "./VsCodeMessenger"; +import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig"; export class VsCodeExtension { // Currently some of these are public so they can be used in testing (test/test-suites) - private configHandler: ConfigHandler; + private configHandler: IConfigHandler; private extensionContext: vscode.ExtensionContext; private ide: VsCodeIde; private tabAutocompleteModel: TabAutocompleteModel; @@ -40,6 +41,7 @@ export class VsCodeExtension { webviewProtocolPromise: Promise; private core: Core; private battery: Battery; + private quickActionsCodeLensDisposable?: vscode.Disposable; constructor(context: vscode.ExtensionContext) { let resolveWebviewProtocol: any = undefined; @@ -64,7 +66,7 @@ export class VsCodeExtension { }, ); let resolveConfigHandler: any = undefined; - const configHandlerPromise = new Promise((resolve) => { + const configHandlerPromise = new Promise((resolve) => { resolveConfigHandler = resolve; }); this.sidebar = new ContinueGUIWebviewViewProvider( @@ -113,9 +115,6 @@ export class VsCodeExtension { }); this.configHandler = this.core.configHandler; resolveConfigHandler?.(this.configHandler); - this.configHandler.onConfigUpdate(() => { - this.sidebar.webviewProtocol?.request("configUpdate", undefined); - }); this.configHandler.reloadConfig(); this.verticalDiffManager = new VerticalPerLineDiffManager( @@ -131,14 +130,30 @@ export class VsCodeExtension { // Indexing + pause token this.diffManager.webviewProtocol = this.sidebar.webviewProtocol; - // CodeLens - const verticalDiffCodeLens = registerAllCodeLensProviders( - context, - this.diffManager, - this.verticalDiffManager.filepathToCodeLens, - ); - this.verticalDiffManager.refreshCodeLens = - verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens); + this.configHandler.loadConfig().then((config) => { + const { verticalDiffCodeLens } = registerAllCodeLensProviders( + context, + this.diffManager, + this.verticalDiffManager.filepathToCodeLens, + config, + ); + + this.verticalDiffManager.refreshCodeLens = + verticalDiffCodeLens.refresh.bind(verticalDiffCodeLens); + }); + + this.configHandler.onConfigUpdate((newConfig) => { + this.sidebar.webviewProtocol?.request("configUpdate", undefined); + + this.tabAutocompleteModel.clearLlm.bind(this.tabAutocompleteModel); + + registerAllCodeLensProviders( + context, + this.diffManager, + this.verticalDiffManager.filepathToCodeLens, + newConfig, + ); + }); // Tab autocomplete const config = vscode.workspace.getConfiguration("continue"); @@ -189,10 +204,6 @@ export class VsCodeExtension { this.configHandler.reloadConfig(); }); - this.configHandler.onConfigUpdate( - this.tabAutocompleteModel.clearLlm.bind(this.tabAutocompleteModel), - ); - vscode.workspace.onDidSaveTextDocument((event) => { // Listen for file changes in the workspace const filepath = event.uri.fsPath; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23873a923..8cd14dfae 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,4 +1,4 @@ -import { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; import { ToWebviewFromCoreProtocol } from "core/protocol/coreWebview"; import { ToIdeFromWebviewOrCoreProtocol } from "core/protocol/ide"; @@ -70,7 +70,7 @@ export class VsCodeMessenger { private readonly webviewProtocol: VsCodeWebviewProtocol, private readonly ide: VsCodeIde, private readonly verticalDiffManagerPromise: Promise, - private readonly configHandlerPromise: Promise, + private readonly configHandlerPromise: Promise, ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index ebb210cf8..c284a3356 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -15,7 +15,6 @@ import type { Thread, } from "core"; import { Range } from "core"; -import { defaultIgnoreDir, defaultIgnoreFile } from "core/indexing/ignore"; import { walkDir } from "core/indexing/walkDir"; import { editConfigJson, @@ -505,15 +504,7 @@ class VsCodeIde implements IDE { } async listDir(dir: string): Promise<[string, FileType][]> { - const files = await vscode.workspace.fs.readDirectory(uriFromFilePath(dir)); - const results = files.filter( - ([name, type]) => - !( - (type === vscode.FileType.File && defaultIgnoreFile.ignores(name)) || - (type === vscode.FileType.Directory && defaultIgnoreDir.ignores(name)) - ), - ) as any; - return results; + return vscode.workspace.fs.readDirectory(uriFromFilePath(dir)) as any; } getIdeSettingsSync(): IdeSettings { diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts deleted file mode 100644 index 7c1b12ec8..000000000 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ /dev/null @@ -1,442 +0,0 @@ -import * as os from "node:os"; -import * as path from "node:path"; -import * as vscode from "vscode"; -import { DIFF_DIRECTORY, type DiffManager } from "../diff/horizontal"; -import type { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; -import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions"; -import { getAltOrOption, getMetaKeyLabel, getPlatform } from "../util/util"; -import { getExtensionUri } from "../util/vscode"; - -class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { - private _eventEmitter: vscode.EventEmitter = - new vscode.EventEmitter(); - onDidChangeCodeLenses: vscode.Event = this._eventEmitter.event; - - public refresh(): void { - this._eventEmitter.fire(); - } - - constructor( - private readonly editorToVerticalDiffCodeLens: Map< - string, - VerticalDiffCodeLens[] - >, - ) {} - - public provideCodeLenses( - document: vscode.TextDocument, - _: vscode.CancellationToken, - ): vscode.CodeLens[] | Thenable { - const filepath = document.uri.fsPath; - const blocks = this.editorToVerticalDiffCodeLens.get(filepath); - if (!blocks) { - return []; - } - - const codeLenses: vscode.CodeLens[] = []; - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; - const start = new vscode.Position(block.start, 0); - const range = new vscode.Range( - start, - start.translate(block.numGreen + block.numRed), - ); - if (codeLenses.length === 0) { - codeLenses.push( - new vscode.CodeLens(range, { - title: `Accept All (${getMetaKeyLabel()}⇧↩)`, - command: "continue.acceptDiff", - arguments: [filepath, i], - }), - new vscode.CodeLens(range, { - title: `Reject All (${getMetaKeyLabel()}⇧⌫)`, - command: "continue.rejectDiff", - arguments: [filepath, i], - }), - ); - } - codeLenses.push( - new vscode.CodeLens(range, { - title: `Accept${ - codeLenses.length === 2 - ? ` (${getAltOrOption()}${getMetaKeyLabel()}Y)` - : "" - }`, - command: "continue.acceptVerticalDiffBlock", - arguments: [filepath, i], - }), - new vscode.CodeLens(range, { - title: `Reject${ - codeLenses.length === 2 - ? ` (${getAltOrOption()}${getMetaKeyLabel()}N)` - : "" - }`, - command: "continue.rejectVerticalDiffBlock", - arguments: [filepath, i], - }), - ); - if (codeLenses.length === 4) { - codeLenses.push( - new vscode.CodeLens(range, { - title: `${getMetaKeyLabel()}I to add instructions`, - command: "", - }), - ); - } - } - - return codeLenses; - } -} - -class SuggestionsCodeLensProvider implements vscode.CodeLensProvider { - public provideCodeLenses( - document: vscode.TextDocument, - _: vscode.CancellationToken, - ): vscode.CodeLens[] | Thenable { - const suggestions = editorToSuggestions.get(document.uri.toString()); - if (!suggestions) { - return []; - } - const locked = editorSuggestionsLocked.get(document.uri.fsPath.toString()); - - const codeLenses: vscode.CodeLens[] = []; - for (const suggestion of suggestions) { - const range = new vscode.Range( - suggestion.oldRange.start, - suggestion.newRange.end, - ); - codeLenses.push( - new vscode.CodeLens(range, { - title: "Accept", - command: "continue.acceptSuggestion", - arguments: [suggestion], - }), - new vscode.CodeLens(range, { - title: "Reject", - command: "continue.rejectSuggestion", - arguments: [suggestion], - }), - ); - if (codeLenses.length === 2) { - codeLenses.push( - new vscode.CodeLens(range, { - title: `(${getMetaKeyLabel()}⇧⏎/${getMetaKeyLabel()}⇧⌫ to accept/reject all)`, - command: "", - }), - ); - } - } - - return codeLenses; - } -} - -class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { - diffManager: DiffManager; - - constructor(diffManager: DiffManager) { - this.diffManager = diffManager; - } - - public provideCodeLenses( - document: vscode.TextDocument, - _: vscode.CancellationToken, - ): vscode.CodeLens[] | Thenable { - if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) { - const codeLenses: vscode.CodeLens[] = []; - let range = new vscode.Range(0, 0, 1, 0); - const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath); - if (diffInfo) { - range = diffInfo.range; - } - codeLenses.push( - new vscode.CodeLens(range, { - title: `Accept All ✅ (${getMetaKeyLabel()}⇧⏎)`, - command: "continue.acceptDiff", - arguments: [document.uri.fsPath], - }), - new vscode.CodeLens(range, { - title: `Reject All ❌ (${getMetaKeyLabel()}⇧⌫)`, - command: "continue.rejectDiff", - arguments: [document.uri.fsPath], - }), - // new vscode.CodeLens(range, { - // title: `Further Edit ✏️ (${getMetaKeyLabel()}⇧M)`, - // command: "continue.focusContinueInputWithEdit", - // }) - ); - return codeLenses; - } else { - return []; - } - } -} - -class ConfigPyCodeLensProvider implements vscode.CodeLensProvider { - public provideCodeLenses( - document: vscode.TextDocument, - _: vscode.CancellationToken, - ): vscode.CodeLens[] | Thenable { - const codeLenses: vscode.CodeLens[] = []; - - if ( - !document.uri.fsPath.endsWith(".continue/config.json") && - !document.uri.fsPath.endsWith(".continue\\config.json") - ) { - return codeLenses; - } - - const lines = document.getText().split(os.EOL); - const lineOfModels = lines.findIndex((line) => - line.includes('"models": ['), - ); - - if (lineOfModels >= 0) { - const range = new vscode.Range(lineOfModels, 0, lineOfModels + 1, 0); - // codeLenses.push( - // new vscode.CodeLens(range, { - // title: `+ Add a Model`, - // command: "continue.addModel", - // }) - // ); - } - - const lineOfSystemMessage = lines.findIndex((line) => - line.includes("ContinueConfig("), - ); - - if (lineOfSystemMessage >= 0) { - const range = new vscode.Range( - lineOfSystemMessage, - 0, - lineOfSystemMessage + 1, - 0, - ); - codeLenses.push( - new vscode.CodeLens(range, { - title: "✏️ Edit in UI", - command: "continue.openSettingsUI", - }), - ); - } - - return codeLenses; - } -} - -interface TutorialCodeLensItems { - lineIncludes: string; - commands: vscode.Command[]; -} - -const cmdCtrl = getPlatform() === "mac" ? "Cmd" : "Ctrl"; - -const actions: TutorialCodeLensItems[] = [ - { - lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+L]`, - commands: [ - { - title: `${cmdCtrl}+L`, - command: "continue.focusContinueInput", - }, - ], - }, - { - lineIncludes: "Step 3: Ask a question", - commands: [ - { - title: `"what does this code do?"`, - command: "continue.sendMainUserInput", - arguments: ["what does this code do?"], - }, - { - title: `"what is an alternative to this?"`, - command: "continue.sendMainUserInput", - arguments: ["what is an alternative to this?"], - }, - ], - }, - { - lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+I] to edit`, - commands: [ - { - title: `${cmdCtrl}+I`, - command: "continue.quickEdit", - arguments: ["Add comments"], - }, - ], - }, - { - lineIncludes: "Step 1: Run this Python file", - commands: [ - { - title: "Run the file", - command: "continue.sendToTerminal", - arguments: [ - `python ${path.join( - getExtensionUri().fsPath, - "continue_tutorial.py", - )}\n`, - ], - }, - ], - }, - { - lineIncludes: "Step 2: Use the keyboard shortcut cmd/ctrl + shift + R", - commands: [ - { - title: "Debug the error", - command: "continue.debugTerminal", - }, - ], - }, - { - lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+Shift+R]`, - commands: [ - { - title: `${cmdCtrl}+Shift+R`, - command: "continue.debugTerminal", - }, - ], - }, -]; - -class TutorialCodeLensProvider implements vscode.CodeLensProvider { - public provideCodeLenses( - document: vscode.TextDocument, - _: vscode.CancellationToken, - ): vscode.CodeLens[] | Thenable { - const codeLenses: vscode.CodeLens[] = []; - - if (!document.uri.fsPath.endsWith("continue_tutorial.py")) { - return codeLenses; - } - - const lines = document.getText().split(os.EOL); - - for (const action of actions) { - const lineOfAction = lines.findIndex((line) => - line.includes(action.lineIncludes), - ); - - if (lineOfAction >= 0) { - const range = new vscode.Range(lineOfAction, 0, lineOfAction + 1, 0); - for (const command of action.commands) { - codeLenses.push(new vscode.CodeLens(range, command)); - } - } - } - - const lineOf11 = lines.findIndex((line) => - line.includes("Step 1: Highlight the function below"), - ); - if (lineOf11 >= 0) { - const range = new vscode.Range(lineOf11, 0, lineOf11 + 1, 0); - codeLenses.push( - new vscode.CodeLens(range, { - title: "Highlight the function", - command: "continue.selectRange", - arguments: [lineOf11 + 3, lineOf11 + 11], - }), - ); - } - const lineOf21 = lines.findIndex((line) => - line.includes("Step 1: Highlight this code"), - ); - if (lineOf21 >= 0) { - const range = new vscode.Range(lineOf21, 0, lineOf21 + 1, 0); - codeLenses.push( - new vscode.CodeLens(range, { - title: "Highlight the function", - command: "continue.selectRange", - arguments: [lineOf21 + 3, lineOf21 + 14], - }), - ); - } - - // Folding of the tutorial - // const regionLines = lines - // .map((line, i) => [line, i]) - // .filter(([line, i]) => (line as string).startsWith("# region ")) - // .map(([line, i]) => i); - // for (const lineOfRegion of regionLines as number[]) { - // const range = new vscode.Range(lineOfRegion, 0, lineOfRegion + 1, 0); - - // const linesToFold = regionLines - // .filter((i) => lineOfRegion !== i) - // .flatMap((i) => { - // return [i, (i as number) + 1]; - // }); - // codeLenses.push( - // new vscode.CodeLens(range, { - // title: `Begin Section`, - // command: "continue.foldAndUnfold", - // arguments: [linesToFold, [lineOfRegion, lineOfRegion + 1]], - // }), - // ); - // } - - return codeLenses; - } -} - -export let verticalPerLineCodeLensProvider: vscode.Disposable | undefined = - undefined; -let diffsCodeLensDisposable: vscode.Disposable | undefined = undefined; -let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; -let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; -let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; - -export function registerAllCodeLensProviders( - context: vscode.ExtensionContext, - diffManager: DiffManager, - editorToVerticalDiffCodeLens: Map, -) { - if (verticalPerLineCodeLensProvider) { - verticalPerLineCodeLensProvider.dispose(); - } - if (suggestionsCodeLensDisposable) { - suggestionsCodeLensDisposable.dispose(); - } - if (diffsCodeLensDisposable) { - diffsCodeLensDisposable.dispose(); - } - if (configPyCodeLensDisposable) { - configPyCodeLensDisposable.dispose(); - } - if (tutorialCodeLensDisposable) { - tutorialCodeLensDisposable.dispose(); - } - - const verticalDiffCodeLens = new VerticalPerLineCodeLensProvider( - editorToVerticalDiffCodeLens, - ); - verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider( - "*", - verticalDiffCodeLens, - ); - suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider( - "*", - new SuggestionsCodeLensProvider(), - ); - diffsCodeLensDisposable = vscode.languages.registerCodeLensProvider( - "*", - new DiffViewerCodeLensProvider(diffManager), - ); - configPyCodeLensDisposable = vscode.languages.registerCodeLensProvider( - "*", - new ConfigPyCodeLensProvider(), - ); - tutorialCodeLensDisposable = vscode.languages.registerCodeLensProvider( - "*", - new TutorialCodeLensProvider(), - ); - context.subscriptions.push(verticalPerLineCodeLensProvider); - context.subscriptions.push(suggestionsCodeLensDisposable); - context.subscriptions.push(diffsCodeLensDisposable); - context.subscriptions.push(configPyCodeLensDisposable); - context.subscriptions.push(tutorialCodeLensDisposable); - - return verticalDiffCodeLens; -} diff --git a/extensions/vscode/src/lang-server/codeLens/index.ts b/extensions/vscode/src/lang-server/codeLens/index.ts new file mode 100644 index 000000000..8e4337016 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/index.ts @@ -0,0 +1 @@ +export { registerAllCodeLensProviders } from "./registerAllCodeLensProviders"; diff --git a/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts new file mode 100644 index 000000000..c3f374c48 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts @@ -0,0 +1,44 @@ +import * as vscode from "vscode"; +import * as os from "os"; + +export class ConfigPyCodeLensProvider implements vscode.CodeLensProvider { + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + const codeLenses: vscode.CodeLens[] = []; + + if ( + !document.uri.fsPath.endsWith(".continue/config.json") && + !document.uri.fsPath.endsWith(".continue\\config.json") + ) { + return codeLenses; + } + + const lines = document.getText().split(os.EOL); + const lineOfModels = lines.findIndex((line) => + line.includes('"models": ['), + ); + + const lineOfSystemMessage = lines.findIndex((line) => + line.includes("ContinueConfig("), + ); + + if (lineOfSystemMessage >= 0) { + const range = new vscode.Range( + lineOfSystemMessage, + 0, + lineOfSystemMessage + 1, + 0, + ); + codeLenses.push( + new vscode.CodeLens(range, { + title: "✏️ Edit in UI", + command: "continue.openSettingsUI", + }), + ); + } + + return codeLenses; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts new file mode 100644 index 000000000..405df9a24 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts @@ -0,0 +1,41 @@ +import path from "path"; +import * as vscode from "vscode"; +import { DiffManager, DIFF_DIRECTORY } from "../../../diff/horizontal"; +import { getMetaKeyLabel } from "../../../util/util"; + +export class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { + diffManager: DiffManager; + + constructor(diffManager: DiffManager) { + this.diffManager = diffManager; + } + + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) { + const codeLenses: vscode.CodeLens[] = []; + let range = new vscode.Range(0, 0, 1, 0); + const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath); + if (diffInfo) { + range = diffInfo.range; + } + codeLenses.push( + new vscode.CodeLens(range, { + title: `Accept All ✅ (${getMetaKeyLabel()}⇧⏎)`, + command: "continue.acceptDiff", + arguments: [document.uri.fsPath], + }), + new vscode.CodeLens(range, { + title: `Reject All ❌ (${getMetaKeyLabel()}⇧⌫)`, + command: "continue.rejectDiff", + arguments: [document.uri.fsPath], + }), + ); + return codeLenses; + } else { + return []; + } + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts new file mode 100644 index 000000000..c2ba05d04 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -0,0 +1,136 @@ +import { ContinueConfig, QuickActionConfig } from "core"; +import * as vscode from "vscode"; +import { + CONTINUE_WORKSPACE_KEY, + getContinueWorkspaceConfig, +} from "../../../util/workspaceConfig"; +import { isTutorialFile } from "./TutorialCodeLensProvider"; +import { Telemetry } from "core/util/posthog"; + +export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions"; + +export function getQuickActionsConfig(config: ContinueConfig) { + return config.experimental?.quickActions; +} + +export function subscribeToVSCodeQuickActionsSettings(listener: Function) { + vscode.workspace.onDidChangeConfiguration((e) => { + const configKey = `${CONTINUE_WORKSPACE_KEY}.${ENABLE_QUICK_ACTIONS_KEY}`; + + if (e.affectsConfiguration(configKey)) { + Telemetry.capture("VSCode Quick Actions Settings Changed", { + enabled: quickActionsEnabledStatus(), + }); + + listener(); + } + }); +} + +export function toggleQuickActions() { + const curStatus = quickActionsEnabledStatus(); + + getContinueWorkspaceConfig().update(ENABLE_QUICK_ACTIONS_KEY, curStatus); +} + +export function quickActionsEnabledStatus() { + return getContinueWorkspaceConfig().get(ENABLE_QUICK_ACTIONS_KEY); +} + +/** + * A CodeLensProvider for Quick Actions. + * + * This class provides code lenses for Quick Actions, which can be either custom or default actions. + * It supports actions for functions and classes, and can be configured with custom quick action settings. + */ +export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { + /** + * Defines which code elements are eligible for Quick Actions. + * + * Right now, we only allow functions, methods and classes + * to keep things simple. + */ + static quickActionSymbolKinds = [ + vscode.SymbolKind.Function, + vscode.SymbolKind.Method, + vscode.SymbolKind.Class, + ]; + + customQuickActionsConfig?: QuickActionConfig[]; + + constructor(customQuickActionsConfigs?: QuickActionConfig[]) { + if (customQuickActionsConfigs) { + this.customQuickActionsConfig = customQuickActionsConfigs; + } + } + + getCustomCommands( + code: string, + range: vscode.Range, + quickActionConfigs: QuickActionConfig[], + ): vscode.Command[] { + return quickActionConfigs.map(({ title, prompt, sendToChat }) => { + return sendToChat + ? { + title, + command: "continue.customQuickActionSendToChat", + arguments: [prompt, code], + } + : { + title, + command: "continue.customQuickActionStreamInlineEdit", + arguments: [prompt, range], + }; + }); + } + + getDefaultCommands(code: string, range: vscode.Range): vscode.Command[] { + const explain: vscode.Command = { + command: "continue.defaultQuickActionExplain", + title: "Explain", + arguments: [code], + }; + + const comment: vscode.Command = { + command: "continue.defaultQuickActionDocstring", + title: "Docstring", + arguments: [range], + }; + + return [explain, comment]; + } + + async provideCodeLenses( + document: vscode.TextDocument, + ): Promise { + // The tutorial file already has a lot of Code Lenses + // so we don't want to add more to it. + if (isTutorialFile(document.uri)) { + return []; + } + + const editor = vscode.window.activeTextEditor; + + if (!editor) { + return []; + } + + const symbols = await vscode.commands.executeCommand< + Array + >("vscode.executeDocumentSymbolProvider", document.uri); + + const filteredSmybols = symbols?.filter((def) => + QuickActionsCodeLensProvider.quickActionSymbolKinds.includes(def.kind), + ); + + return filteredSmybols.flatMap(({ range }) => { + const code = editor.document.getText(range); + + const commands: vscode.Command[] = !!this.customQuickActionsConfig + ? this.getCustomCommands(code, range, this.customQuickActionsConfig) + : this.getDefaultCommands(code, range); + + return commands.map((command) => new vscode.CodeLens(range, command)); + }); + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts new file mode 100644 index 000000000..d0541d228 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts @@ -0,0 +1,45 @@ +import * as vscode from "vscode"; +import { editorToSuggestions } from "../../../suggestions"; +import { getMetaKeyLabel } from "../../../util/util"; + +export class SuggestionsCodeLensProvider implements vscode.CodeLensProvider { + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + const suggestions = editorToSuggestions.get(document.uri.toString()); + if (!suggestions) { + return []; + } + + const codeLenses: vscode.CodeLens[] = []; + for (const suggestion of suggestions) { + const range = new vscode.Range( + suggestion.oldRange.start, + suggestion.newRange.end, + ); + codeLenses.push( + new vscode.CodeLens(range, { + title: "Accept", + command: "continue.acceptSuggestion", + arguments: [suggestion], + }), + new vscode.CodeLens(range, { + title: "Reject", + command: "continue.rejectSuggestion", + arguments: [suggestion], + }), + ); + if (codeLenses.length === 2) { + codeLenses.push( + new vscode.CodeLens(range, { + title: `(${getMetaKeyLabel()}⇧⏎/${getMetaKeyLabel()}⇧⌫ to accept/reject all)`, + command: "", + }), + ); + } + } + + return codeLenses; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts new file mode 100644 index 000000000..0c3105b72 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts @@ -0,0 +1,145 @@ +import * as os from "node:os"; +import path from "path"; +import * as vscode from "vscode"; +import { getPlatform } from "../../../util/util"; +import { getExtensionUri } from "../../../util/vscode"; + +interface TutorialCodeLensItems { + lineIncludes: string; + commands: vscode.Command[]; +} + +const TUTORIAL_FILE_NAME = "continue_tutorial.py"; + +const cmdCtrl = getPlatform() === "mac" ? "Cmd" : "Ctrl"; + +const actions: TutorialCodeLensItems[] = [ + { + lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+L]`, + commands: [ + { + title: `${cmdCtrl}+L`, + command: "continue.focusContinueInput", + }, + ], + }, + { + lineIncludes: "Step 3: Ask a question", + commands: [ + { + title: `"what does this code do?"`, + command: "continue.sendMainUserInput", + arguments: ["what does this code do?"], + }, + { + title: `"what is an alternative to this?"`, + command: "continue.sendMainUserInput", + arguments: ["what is an alternative to this?"], + }, + ], + }, + { + lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+I] to edit`, + commands: [ + { + title: `${cmdCtrl}+I`, + command: "continue.quickEdit", + arguments: ["Add comments"], + }, + ], + }, + { + lineIncludes: "Step 1: Run this Python file", + commands: [ + { + title: "Run the file", + command: "continue.sendToTerminal", + arguments: [ + `python ${path.join( + getExtensionUri().fsPath, + "continue_tutorial.py", + )}\n`, + ], + }, + ], + }, + { + lineIncludes: "Step 2: Use the keyboard shortcut cmd/ctrl + shift + R", + commands: [ + { + title: "Debug the error", + command: "continue.debugTerminal", + }, + ], + }, + { + lineIncludes: `Step 2: Use the keyboard shortcut [${cmdCtrl}+Shift+R]`, + commands: [ + { + title: `${cmdCtrl}+Shift+R`, + command: "continue.debugTerminal", + }, + ], + }, +]; + +export function isTutorialFile(uri: vscode.Uri) { + return uri.fsPath.endsWith(TUTORIAL_FILE_NAME); +} + +export class TutorialCodeLensProvider implements vscode.CodeLensProvider { + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + const codeLenses: vscode.CodeLens[] = []; + + if (!isTutorialFile(document.uri)) { + return codeLenses; + } + + const lines = document.getText().split(os.EOL); + + for (const action of actions) { + const lineOfAction = lines.findIndex((line) => + line.includes(action.lineIncludes), + ); + + if (lineOfAction >= 0) { + const range = new vscode.Range(lineOfAction, 0, lineOfAction + 1, 0); + for (const command of action.commands) { + codeLenses.push(new vscode.CodeLens(range, command)); + } + } + } + + const lineOf11 = lines.findIndex((line) => + line.includes("Step 1: Highlight the function below"), + ); + if (lineOf11 >= 0) { + const range = new vscode.Range(lineOf11, 0, lineOf11 + 1, 0); + codeLenses.push( + new vscode.CodeLens(range, { + title: "Highlight the function", + command: "continue.selectRange", + arguments: [lineOf11 + 3, lineOf11 + 11], + }), + ); + } + const lineOf21 = lines.findIndex((line) => + line.includes("Step 1: Highlight this code"), + ); + if (lineOf21 >= 0) { + const range = new vscode.Range(lineOf21, 0, lineOf21 + 1, 0); + codeLenses.push( + new vscode.CodeLens(range, { + title: "Highlight the function", + command: "continue.selectRange", + arguments: [lineOf21 + 3, lineOf21 + 14], + }), + ); + } + + return codeLenses; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts new file mode 100644 index 000000000..b0effc563 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts @@ -0,0 +1,96 @@ +import * as vscode from "vscode"; +import { VerticalDiffCodeLens } from "../../../diff/verticalPerLine/manager"; +import { getAltOrOption, getMetaKeyLabel } from "../../../util/util"; + +export class VerticalPerLineCodeLensProvider + implements vscode.CodeLensProvider +{ + private _eventEmitter: vscode.EventEmitter = + new vscode.EventEmitter(); + + onDidChangeCodeLenses: vscode.Event = this._eventEmitter.event; + + public refresh(): void { + this._eventEmitter.fire(); + } + + constructor( + private readonly editorToVerticalDiffCodeLens: Map< + string, + VerticalDiffCodeLens[] + >, + ) {} + + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + const filepath = document.uri.fsPath; + const blocks = this.editorToVerticalDiffCodeLens.get(filepath); + + if (!blocks) { + return []; + } + + const codeLenses: vscode.CodeLens[] = []; + + for (let i = 0; i < blocks.length; i++) { + const isFirstBlockInMultiBlockDocument = + codeLenses.length === 0 && blocks.length > 1; + + const block = blocks[i]; + const start = new vscode.Position(block.start, 0); + const range = new vscode.Range( + start, + start.translate(block.numGreen + block.numRed), + ); + + if (isFirstBlockInMultiBlockDocument) { + codeLenses.push( + new vscode.CodeLens(range, { + title: `Accept All (${getMetaKeyLabel()}⇧↩)`, + command: "continue.acceptDiff", + arguments: [filepath, i], + }), + new vscode.CodeLens(range, { + title: `Reject All (${getMetaKeyLabel()}⇧⌫)`, + command: "continue.rejectDiff", + arguments: [filepath, i], + }), + ); + } + + codeLenses.push( + new vscode.CodeLens(range, { + title: `Accept${ + codeLenses.length === 2 + ? ` (${getAltOrOption()}${getMetaKeyLabel()}Y)` + : "" + }`, + command: "continue.acceptVerticalDiffBlock", + arguments: [filepath, i], + }), + new vscode.CodeLens(range, { + title: `Reject${ + codeLenses.length === 2 + ? ` (${getAltOrOption()}${getMetaKeyLabel()}N)` + : "" + }`, + command: "continue.rejectVerticalDiffBlock", + arguments: [filepath, i], + }), + ); + + if (codeLenses.length === 4) { + codeLenses.push( + new vscode.CodeLens(range, { + title: `${getMetaKeyLabel()}I to add instructions`, + command: "", + }), + ); + } + } + + return codeLenses; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/index.ts b/extensions/vscode/src/lang-server/codeLens/providers/index.ts new file mode 100644 index 000000000..f5bdfc4d7 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/index.ts @@ -0,0 +1,6 @@ +export { ConfigPyCodeLensProvider } from "./ConfigPyCodeLensProvider"; +export { DiffViewerCodeLensProvider } from "./DiffViewerCodeLensProvider"; +export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider"; +export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider"; +export { TutorialCodeLensProvider } from "./TutorialCodeLensProvider"; +export { VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider"; diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts new file mode 100644 index 000000000..89066fbc8 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts @@ -0,0 +1,142 @@ +import { ContinueConfig } from "core"; +import * as vscode from "vscode"; +import { VerticalDiffCodeLens } from "../../diff/verticalPerLine/manager"; +import { DiffManager } from "../../diff/horizontal"; +import * as providers from "./providers"; +import { + getQuickActionsConfig, + quickActionsEnabledStatus, + subscribeToVSCodeQuickActionsSettings, +} from "./providers/QuickActionsCodeLensProvider"; + +const { registerCodeLensProvider } = vscode.languages; + +export let verticalPerLineCodeLensProvider: vscode.Disposable | undefined = + undefined; +let diffsCodeLensDisposable: vscode.Disposable | undefined = undefined; +let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; +let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; +let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; +let quickActionsCodeLensDisposable: vscode.Disposable | undefined = undefined; + +/** + * Registers the Quick Actions CodeLens provider if Quick Actions are enabled. + * + * This function checks if Quick Actions are enabled in the VSCode workspace settings, + * and if so, it registers a new QuickActionsCodeLensProvider. If the user has custom + * actions defined in their config, it initiaizes the provider with these actions. + * + * If a previous provider was registered, it is disposed of before the new one is created. + * + * @param config - The Continue configuration object + * @param context - The VS Code extension context + */ +function registerQuickActionsProvider( + config: ContinueConfig, + context: vscode.ExtensionContext, +) { + if (quickActionsCodeLensDisposable) { + quickActionsCodeLensDisposable.dispose(); + } + + if (quickActionsEnabledStatus()) { + const quickActionsConfig = getQuickActionsConfig(config); + + quickActionsCodeLensDisposable = registerCodeLensProvider( + "*", + new providers.QuickActionsCodeLensProvider(quickActionsConfig), + ); + + context.subscriptions.push(quickActionsCodeLensDisposable); + } +} + +/** + * Registers all CodeLens providers for the Continue extension. + * + * This function disposes of any existing CodeLens providers and registers new ones for: + * - Vertical per-line diffs + * - Suggestions + * - Diff viewer + * - Config.py + * - Tutorial + * - Quick Actions + * + * It also sets up a subscription to VS Code Quick Actions settings changes. + * + * @param context - The VS Code extension context + * @param diffManager - The DiffManager instance for managing diffs + * @param editorToVerticalDiffCodeLens - A Map of editor IDs to VerticalDiffCodeLens arrays + * @param config - The Continue configuration object + * + * @returns An object containing the verticalDiffCodeLens provider + */ +export function registerAllCodeLensProviders( + context: vscode.ExtensionContext, + diffManager: DiffManager, + editorToVerticalDiffCodeLens: Map, + config: ContinueConfig, +) { + if (verticalPerLineCodeLensProvider) { + verticalPerLineCodeLensProvider.dispose(); + } + + if (suggestionsCodeLensDisposable) { + suggestionsCodeLensDisposable.dispose(); + } + + if (diffsCodeLensDisposable) { + diffsCodeLensDisposable.dispose(); + } + + if (configPyCodeLensDisposable) { + configPyCodeLensDisposable.dispose(); + } + + if (tutorialCodeLensDisposable) { + tutorialCodeLensDisposable.dispose(); + } + + const verticalDiffCodeLens = new providers.VerticalPerLineCodeLensProvider( + editorToVerticalDiffCodeLens, + ); + + verticalPerLineCodeLensProvider = registerCodeLensProvider( + "*", + verticalDiffCodeLens, + ); + + suggestionsCodeLensDisposable = registerCodeLensProvider( + "*", + new providers.SuggestionsCodeLensProvider(), + ); + + diffsCodeLensDisposable = registerCodeLensProvider( + "*", + new providers.DiffViewerCodeLensProvider(diffManager), + ); + + configPyCodeLensDisposable = registerCodeLensProvider( + "*", + new providers.ConfigPyCodeLensProvider(), + ); + + tutorialCodeLensDisposable = registerCodeLensProvider( + "*", + new providers.TutorialCodeLensProvider(), + ); + + registerQuickActionsProvider(config, context); + + subscribeToVSCodeQuickActionsSettings(() => + registerQuickActionsProvider(config, context), + ); + + context.subscriptions.push(verticalPerLineCodeLensProvider); + context.subscriptions.push(suggestionsCodeLensDisposable); + context.subscriptions.push(diffsCodeLensDisposable); + context.subscriptions.push(configPyCodeLensDisposable); + context.subscriptions.push(tutorialCodeLensDisposable); + + return { verticalDiffCodeLens }; +} diff --git a/extensions/vscode/src/quickEdit/QuickEdit.ts b/extensions/vscode/src/quickEdit/QuickEdit.ts index 5e598f51f..e5c4e6933 100644 --- a/extensions/vscode/src/quickEdit/QuickEdit.ts +++ b/extensions/vscode/src/quickEdit/QuickEdit.ts @@ -1,5 +1,5 @@ import { IDE } from "core"; -import { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import { fetchwithRequestOptions } from "core/util/fetchWithOptions"; import * as vscode from "vscode"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; @@ -17,7 +17,7 @@ interface QuickEditFlowStuff { export class QuickEdit { constructor( private readonly verticalDiffManager: VerticalPerLineDiffManager, - private readonly configHandler: ConfigHandler, + private readonly configHandler: IConfigHandler, private readonly webviewProtocol: VsCodeWebviewProtocol, private readonly ide: IDE, private readonly context: vscode.ExtensionContext, diff --git a/extensions/vscode/src/stubs/remoteConfig.ts b/extensions/vscode/src/stubs/remoteConfig.ts index 2e70e4ace..fa5293a39 100644 --- a/extensions/vscode/src/stubs/remoteConfig.ts +++ b/extensions/vscode/src/stubs/remoteConfig.ts @@ -5,6 +5,7 @@ import { } from "core/util/paths"; import * as fs from "fs"; import * as vscode from "vscode"; +import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig"; export class RemoteConfigSync { private userToken: string | null; @@ -28,7 +29,7 @@ export class RemoteConfigSync { // Listen for changes to VS Code settings, then trigger a refresh vscode.workspace.onDidChangeConfiguration(async (event) => { - if (event.affectsConfiguration("continue")) { + if (event.affectsConfiguration(CONTINUE_WORKSPACE_KEY)) { const { userToken, remoteConfigServerUrl, remoteConfigSyncPeriod } = await this.loadVsCodeSettings(); if ( @@ -92,13 +93,12 @@ export class RemoteConfigSync { if (this.syncInterval !== undefined) { clearInterval(this.syncInterval); } - this.syncInterval = setInterval( - () => { - if (!this.userToken || !this.remoteConfigServerUrl) return; - this.sync(this.userToken, this.remoteConfigServerUrl); - }, - this.remoteConfigSyncPeriod * 1000 * 60, - ); + this.syncInterval = setInterval(() => { + if (!this.userToken || !this.remoteConfigServerUrl) { + return; + } + this.sync(this.userToken, this.remoteConfigServerUrl); + }, this.remoteConfigSyncPeriod * 1000 * 60); } async sync(userToken: string, remoteConfigServerUrl: string) { diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index c4498c74a..db56c7e31 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -1,5 +1,5 @@ import type { ILLM } from "core"; -import type { ConfigHandler } from "core/config/handler"; +import { IConfigHandler } from "core/config/IConfigHandler"; import Ollama from "core/llm/llms/Ollama"; import { GlobalContext } from "core/util/GlobalContext"; import * as vscode from "vscode"; @@ -13,9 +13,9 @@ export class TabAutocompleteModel { private shownOllamaWarning = false; private shownDeepseekWarning = false; - private configHandler: ConfigHandler; + private configHandler: IConfigHandler; - constructor(configHandler: ConfigHandler) { + constructor(configHandler: IConfigHandler) { this.configHandler = configHandler; } diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index bc3f85fa9..fb0d88c14 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -2,8 +2,12 @@ const os = require("node:os"); import * as vscode from "vscode"; function charIsEscapedAtIndex(index: number, str: string): boolean { - if (index === 0) return false; - if (str[index - 1] !== "\\") return false; + if (index === 0) { + return false; + } + if (str[index - 1] !== "\\") { + return false; + } return !charIsEscapedAtIndex(index - 1, str); } diff --git a/extensions/vscode/src/util/workspaceConfig.ts b/extensions/vscode/src/util/workspaceConfig.ts new file mode 100644 index 000000000..3adc6d252 --- /dev/null +++ b/extensions/vscode/src/util/workspaceConfig.ts @@ -0,0 +1,7 @@ +import { workspace } from "vscode"; + +export const CONTINUE_WORKSPACE_KEY = "continue"; + +export function getContinueWorkspaceConfig() { + return workspace.getConfiguration(CONTINUE_WORKSPACE_KEY); +}