diff --git a/.vscode/launch.json b/.vscode/launch.json index 896793040..f5c81180f 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -12,7 +12,7 @@ "cwd": "${workspaceFolder}/extensions/vscode", "args": [ // Pass a directory to manually test in - "${workspaceFolder}/manual-testing-sandbox", + "${workspaceFolder}/gui", "${workspaceFolder}/manual-testing-sandbox/test.js", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], diff --git a/core/config/util.ts b/core/config/util.ts index 5abf0b9b5..69e088a18 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,4 +1,10 @@ -import { ContextProviderWithParams, ModelDescription } from "../"; +import { + ContextProviderWithParams, + ContinueConfig, + ILLM, + ModelDescription, + ModelRoles, +} from "../"; import { editConfigJson } from "../util/paths"; function stringify(obj: any, indentation?: number): string { @@ -61,3 +67,20 @@ export function deleteModel(title: string) { return config; }); } + +export function getModelByRole( + config: ContinueConfig, + role: T, +): ILLM | undefined { + const roleTitle = config.experimental?.modelRoles?.[role]; + + if (!roleTitle) { + return undefined; + } + + const matchingModel = config.models.find( + (model) => model.title === roleTitle, + ); + + return matchingModel; +} diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index 2de4352d9..5e77c537b 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -2,9 +2,9 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, -} from "../../index.js"; -import { BaseContextProvider } from "../index.js"; -import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval.js"; +} from "../../"; +import { BaseContextProvider } from "../"; +import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval"; class CodebaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 88df47318..e9ae11bde 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -1,3 +1,4 @@ +import { INSTRUCTIONS_BASE_ITEM } from "./utils"; import { BaseContextProvider } from "../"; import { Chunk, @@ -149,8 +150,7 @@ class DocsContextProvider extends BaseContextProvider { })) .reverse(), { - name: "Instructions", - description: "Instructions", + ...INSTRUCTIONS_BASE_ITEM, content: "Use the above documentation to answer the following question. You should not reference " + "anything outside of what is shown, unless it is a commonly known concept. Reference URLs " + diff --git a/core/context/providers/OSContextProvider.ts b/core/context/providers/OSContextProvider.ts index e0894a1cd..45852c934 100644 --- a/core/context/providers/OSContextProvider.ts +++ b/core/context/providers/OSContextProvider.ts @@ -23,8 +23,10 @@ class OSContextProvider extends BaseContextProvider { return [ { description: "Your operating system and CPU", - content: `I am running ${platform === "win32" ? "Windows" : platform} on ${cpu}.`, - name: "os", + content: `I am running ${ + platform === "win32" ? "Windows" : platform + } on ${cpu}.`, + name: "Operating System", }, ]; } diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 3d6c1d63f..6aefe0301 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -3,15 +3,28 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, } from "../../"; -import generateRepoMap from "../../util/repoMap"; +import { + groupByLastNPathParts, + getBasename, + getUniqueFilePath, +} from "../../util"; +import generateRepoMap from "../../util/generateRepoMap"; + +const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = { + id: "entire-codebase", + title: "Entire codebase", + description: "Search the entire codebase", +}; class RepoMapContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { title: "repo-map", displayTitle: "Repository Map", - description: "List of files and signatures", - type: "normal", + description: "Select a folder", + type: "submenu", dependsOnIndexing: true, }; @@ -23,10 +36,28 @@ class RepoMapContextProvider extends BaseContextProvider { { name: "Repository Map", description: "Overview of the repository structure", - content: await generateRepoMap(extras.llm, extras.ide), + content: await generateRepoMap(extras.llm, extras.ide, { + dirs: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query], + }), }, ]; } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const folders = await args.ide.listFolders(); + const folderGroups = groupByLastNPathParts(folders, 2); + + return [ + ENTIRE_PROJECT_ITEM, + ...folders.map((folder) => ({ + id: folder, + title: getBasename(folder), + description: getUniqueFilePath(folder, folderGroups), + })), + ]; + } } export default RepoMapContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 92cabb222..9c2ab4303 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,4 +1,4 @@ -import { ContextProviderName } from "../../"; +import { ContextItem, ContextProviderName } from "../../"; import { BaseContextProvider } from "../"; import CodeContextProvider from "./CodeContextProvider"; import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; @@ -30,7 +30,7 @@ import RepoMapContextProvider from "./RepoMapContextProvider"; * * See this issue for details: https://github.com/continuedev/continue/issues/1365 */ -const Providers: (typeof BaseContextProvider)[] = [ +export const Providers: (typeof BaseContextProvider)[] = [ DiffContextProvider, FileTreeContextProvider, GitHubIssuesContextProvider, diff --git a/core/context/providers/utils.ts b/core/context/providers/utils.ts new file mode 100644 index 000000000..7bc20e491 --- /dev/null +++ b/core/context/providers/utils.ts @@ -0,0 +1,7 @@ +import { ContextItem } from "../.."; + +export const INSTRUCTIONS_BASE_ITEM: ContextItem = { + name: "Instructions", + description: "Instructions", + content: "", +}; diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 8d2eb9e4f..618be4808 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,6 +1,33 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; +import { getModelByRole } from "../../config/util"; import { stripImages } from "../../llm/images"; -import generateRepoMap from "../../util/repoMap"; +import generateRepoMap from "../../util/generateRepoMap"; + +const SUPPORTED_MODEL_TITLE_FAMILIES = [ + "claude-3", + "llama3.1", + "gemini-1.5", + "gpt-4", +]; + +function isSupportedModel( + config: ContinueConfig, + modelTitle?: string, +): boolean { + if (config.experimental?.modelRoles?.applyCodeBlock) { + return true; + } + + if (!modelTitle) { + return false; + } + + const lowercaseModelTitle = modelTitle.toLowerCase(); + + return SUPPORTED_MODEL_TITLE_FAMILIES.some((title) => + lowercaseModelTitle.includes(title), + ); +} export async function requestFilesFromRepoMap( defaultLlm: ILLM, @@ -9,20 +36,16 @@ export async function requestFilesFromRepoMap( input: string, filterDirectory?: string, ): Promise { - const llm = - config.models.find( - (model) => - model.title === config.experimental?.modelRoles?.repoMapFileSelection, - ) ?? defaultLlm; + const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm; // Only supported for Claude models right now - if (!llm.model.toLowerCase().includes("claude")) { + if (!isSupportedModel(config, llm.title)) { return []; } try { const repoMap = await generateRepoMap(llm, ide, { - signatures: false, + includeSignatures: false, dirs: filterDirectory ? [filterDirectory] : undefined, }); diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 34c6bd87c..1b250e548 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,14 +1,11 @@ -import { - BranchAndDir, - ContextItem, - ContextProviderExtras, -} from "../../index.js"; -import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js"; -import { resolveRelativePathInWorkspace } from "../../util/ideUtils.js"; -import { getRelativePath } from "../../util/index.js"; -import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js"; -import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js"; -import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline.js"; +import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; +import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; +import { getRelativePath } from "../../util/"; +import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; +import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; +import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; +import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; export async function retrieveContextItemsFromEmbeddings( extras: ContextProviderExtras, @@ -109,8 +106,7 @@ export async function retrieveContextItemsFromEmbeddings( }; }), { - name: "Instructions", - description: "Instructions", + ...INSTRUCTIONS_BASE_ITEM, content: "Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.", }, diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index f567a48d2..6a02babd4 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -383,20 +383,18 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); const query = ` - SELECT path, signature - FROM code_snippets - WHERE path LIKE ${placeholders} - ORDER BY path - LIMIT ? OFFSET ? -`; + SELECT DISTINCT path, signature + FROM code_snippets + WHERE path LIKE ${placeholders} + ORDER BY path, signature + LIMIT ? OFFSET ? + `; const rows = await db.all(query, [...likePatterns, batchSize, offset]); - const validRows = rows.filter((row) => row.path && row.signature !== null); - const groupedByPath: { [path: string]: string[] } = {}; - for (const { path, signature } of validRows) { + for (const { path, signature } of rows) { if (!groupedByPath[path]) { groupedByPath[path] = []; } diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index aea21e3cf..70d6ead29 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -411,7 +411,7 @@ class ChromiumCrawler { for (const link of linkGroup) { enqueuedLinkCount++; - console.log({ enqueuedLinkCount, url: this.startUrl }); + console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { yield* this.crawlSitePages(page, new URL(link), visitedLinks); } diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts new file mode 100644 index 000000000..785a62c41 --- /dev/null +++ b/core/util/generateRepoMap.ts @@ -0,0 +1,213 @@ +import fs from "node:fs"; +import path from "node:path"; +import { IDE, ILLM } from ".."; +import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; +import { walkDirAsync } from "../indexing/walkDir"; +import { pruneLinesFromTop } from "../llm/countTokens"; +import { getRepoMapFilePath } from "./paths"; + +export interface RepoMapOptions { + includeSignatures?: boolean; + dirs?: string[]; +} + +class RepoMapGenerator { + private llm: ILLM; + private ide: IDE; + private options: RepoMapOptions; + private maxRepoMapTokens: number; + + private repoMapPath: string = getRepoMapFilePath(); + private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath); + private contentTokens: number = 0; + private repoMapDirs: string[] = []; + private allPathsInDirs: Set = new Set(); + private pathsInDirsWithSnippets: Set = new Set(); + + private BATCH_SIZE = 100; + private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; + private PREAMBLE = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n"; + + constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) { + this.llm = llm; + this.ide = ide; + this.options = options; + this.maxRepoMapTokens = + llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; + } + + async generate(): Promise { + this.repoMapDirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs()); + this.allPathsInDirs = await this.getAllPathsInDirs(); + + await this.initializeWriteStream(); + await this.processPathsAndSignatures(); + + this.writeStream.end(); + this.logRepoMapGeneration(); + + return fs.readFileSync(this.repoMapPath, "utf8"); + } + + private async initializeWriteStream(): Promise { + await this.writeToStream(this.PREAMBLE); + this.contentTokens += this.llm.countTokens(this.PREAMBLE); + } + + private async getAllPathsInDirs(): Promise> { + const paths = new Set(); + + for (const dir of this.repoMapDirs) { + for await (const filepath of walkDirAsync(dir, this.ide)) { + paths.add(filepath.replace(dir, "").slice(1)); + } + } + + return paths; + } + + private async processPathsAndSignatures(): Promise { + let offset = 0; + while (true) { + const { groupedByPath, hasMore } = + await CodeSnippetsCodebaseIndex.getPathsAndSignatures( + this.repoMapDirs, + offset, + this.BATCH_SIZE, + ); + await this.processBatch(groupedByPath); + if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) { + break; + } + offset += this.BATCH_SIZE; + } + await this.writeRemainingPaths(); + } + + private async processBatch( + groupedByPath: Record, + ): Promise { + for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { + const content = await this.processFile(absolutePath, signatures); + + if (content) { + await this.writeToStream(content); + } + } + } + + private async processFile( + absolutePath: string, + signatures: string[], + ): Promise { + const workspaceDir = + this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || ""; + const relativePath = path.relative(workspaceDir, absolutePath); + + let fileContent: string; + + try { + fileContent = await fs.promises.readFile(absolutePath, "utf8"); + } catch (err) { + console.error( + "Failed to read file:\n" + + ` Path: ${absolutePath}\n` + + ` Error: ${err instanceof Error ? err.message : String(err)}`, + ); + + return; + } + + const filteredSignatures = signatures.filter( + (signature) => signature.trim() !== fileContent.trim(), + ); + + if (filteredSignatures.length > 0) { + this.pathsInDirsWithSnippets.add(relativePath); + } + + return this.generateContentForPath(relativePath, filteredSignatures); + } + + private generateContentForPath( + relativePath: string, + signatures: string[], + ): string { + if (this.options.includeSignatures === false) { + return `${relativePath}\n`; + } + + let content = `${relativePath}:\n`; + + for (const signature of signatures.slice(0, -1)) { + content += `${this.indentMultilineString(signature)}\n\t...\n`; + } + + content += `${this.indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; + + return content; + } + + private async writeToStream(content: string): Promise { + const tokens = this.llm.countTokens(content); + + if (this.contentTokens + tokens > this.maxRepoMapTokens) { + content = pruneLinesFromTop( + content, + this.maxRepoMapTokens - this.contentTokens, + this.llm.model, + ); + } + + this.contentTokens += this.llm.countTokens(content); + + await new Promise((resolve) => this.writeStream.write(content, resolve)); + } + + private async writeRemainingPaths(): Promise { + const pathsWithoutSnippets = new Set( + [...this.allPathsInDirs].filter( + (x) => !this.pathsInDirsWithSnippets.has(x), + ), + ); + + if (pathsWithoutSnippets.size > 0) { + await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n")); + } + } + + private logRepoMapGeneration(): void { + console.debug( + `Generated repo map for ${this.repoMapDirs.join(", ")} at ${ + this.repoMapPath + }`, + ); + if (this.contentTokens >= this.maxRepoMapTokens) { + console.debug( + "Full repo map was unable to be generated due to context window limitations", + ); + } + } + + private indentMultilineString(str: string) { + return str + .split("\n") + .map((line: any) => "\t" + line) + .join("\n"); + } +} + +export default async function generateRepoMap( + llm: ILLM, + ide: IDE, + options: RepoMapOptions, +): Promise { + const generator = new RepoMapGenerator(llm, ide, options); + return generator.generate(); +} diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts deleted file mode 100644 index 6c0a73e1f..000000000 --- a/core/util/repoMap.ts +++ /dev/null @@ -1,131 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { IDE, ILLM } from ".."; -import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; -import { walkDirAsync } from "../indexing/walkDir"; -import { pruneLinesFromTop } from "../llm/countTokens"; -import { getRepoMapFilePath } from "./paths"; - -const repoMapPreamble = - "Below is a repository map. \n" + - "For each file in the codebase, " + - "this map contains the name of the file, and the signature for any " + - "classes, methods, or functions in the file.\n\n"; - -// The max percent of the context window we will take -const REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; - -function indentMultilineString(str: string) { - return str - .split("\n") - .map((line: any) => "\t" + line) - .join("\n"); -} - -export interface RepoMapOptions { - signatures?: boolean; - dirs?: string[]; -} - -async function generateRepoMap(llm: ILLM, ide: IDE, options?: RepoMapOptions) { - const repoMapPath = getRepoMapFilePath(); - const dirs = options?.dirs ?? (await ide.getWorkspaceDirs()); - const maxRepoMapTokens = llm.contextLength * REPO_MAX_CONTEXT_LENGTH_RATIO; - - const pathsWithoutSnippets = new Set(); - for (const dir of dirs) { - for await (const filepath of walkDirAsync(dir, ide)) { - pathsWithoutSnippets.add(filepath.replace(dir, "").slice(1)); - } - } - - if (fs.existsSync(repoMapPath)) { - console.debug(`Overwriting existing repo map at ${repoMapPath}`); - } - - const writeStream = fs.createWriteStream(repoMapPath); - await new Promise((resolve) => writeStream.write(repoMapPreamble, resolve)); - - let curTokens = llm.countTokens(repoMapPreamble); - let offset = 0; - const batchSize = 100; - - while (true) { - const { groupedByPath, hasMore } = - await CodeSnippetsCodebaseIndex.getPathsAndSignatures( - dirs, - offset, - batchSize, - ); - - let content = ""; - - for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { - const workspaceDir = - dirs.find((dir) => absolutePath.startsWith(dir)) || ""; - - const relativePath = path.relative(workspaceDir, absolutePath); - - pathsWithoutSnippets.delete(relativePath); - - if (options?.signatures !== false) { - content += `${relativePath}:\n`; - for (const signature of signatures.slice(0, -1)) { - content += `${indentMultilineString(signature)}\n\t...\n`; - } - if (signatures.length > 0) { - // Don't add the trailing ellipsis for the last entry - content += `${indentMultilineString( - signatures[signatures.length - 1], - )}\n\n`; - } - } else { - // No signatures mode - content += `${relativePath}\n`; - } - } - - const contentTokens = llm.countTokens(content); - - if (curTokens + contentTokens >= maxRepoMapTokens) { - // Fit what we can, then stop - const prunedContent = pruneLinesFromTop( - content, - maxRepoMapTokens - curTokens, - llm.model, - ); - await new Promise((resolve) => writeStream.write(prunedContent, resolve)); - break; - } else { - await new Promise((resolve) => writeStream.write(content, resolve)); - } - - curTokens += contentTokens; - - if (!hasMore) { - break; - } - - offset += batchSize; - } - - const content = Array.from(pathsWithoutSnippets).join("\n"); - if (content.length > 0) { - await new Promise((resolve) => writeStream.write(content, resolve)); - } - - writeStream.end(); - console.debug(`Generated repo map at ${repoMapPath}`); - - if (curTokens >= maxRepoMapTokens) { - console.debug( - "Full repo map was unable to be genereated due to context window limitations", - ); - } - - const repoMap = fs.readFileSync(repoMapPath, "utf8"); - - return repoMap; -} - -export default generateRepoMap; diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index e2fb6c029..daed6d63b 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -415,7 +415,9 @@ Reference the outline of your codebase. } ``` -Provides an overview of all files and the call signatures of top-level classes, functions, and methods. This helps the model better understand how a particular piece of code relates to the rest of the codebase. +Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. + +In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index a74cd1a88..0d70f9b53 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -70,3 +70,7 @@ Continue respects `.gitignore` files in order to determine which files should no If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window". + +## Repository map + +Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebsae retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index cbf47d4b4..911278ebb 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -2476,13 +2476,16 @@ "type": "object", "properties": { "inlineEdit": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for inline edits", + "type": "string" }, "applyCodeBlock": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for applying code blocks", + "type": "string" }, "repoMapFileSelection": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for repo map file selections", + "type": "string" } } }, @@ -2545,12 +2548,6 @@ } } } - }, - "ModelTitle": { - "type": "string", - "enum": { - "$data": "/models/title" - } } } } diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index cbf47d4b4..911278ebb 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -2476,13 +2476,16 @@ "type": "object", "properties": { "inlineEdit": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for inline edits", + "type": "string" }, "applyCodeBlock": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for applying code blocks", + "type": "string" }, "repoMapFileSelection": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for repo map file selections", + "type": "string" } } }, @@ -2545,12 +2548,6 @@ } } } - }, - "ModelTitle": { - "type": "string", - "enum": { - "$data": "/models/title" - } } } } diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 58453fc5c..101296fe6 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -2782,13 +2782,16 @@ "type": "object", "properties": { "inlineEdit": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for inline edits", + "type": "string" }, "applyCodeBlock": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for applying code blocks", + "type": "string" }, "repoMapFileSelection": { - "$ref": "#/definitions/ModelTitle" + "description": "The 'title' property of the model you wish to use for repo map file selections", + "type": "string" } } }, @@ -2864,12 +2867,6 @@ "markdownDescription": "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json." } } - }, - "ModelTitle": { - "type": "string", - "enum": { - "$data": "/models/title" - } } } } \ No newline at end of file diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 238a2c841..1efe40dfa 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.213", + "version": "0.9.211", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.213", + "version": "0.9.211", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index abc33fe8b..7ac639326 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -30,6 +30,7 @@ import { Battery } from "./util/battery"; import { uriFromFilePath } from "./util/vscode"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; import { getFullyQualifiedPath } from "./util/util"; +import { getModelByRole } from "core/config/util"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -208,12 +209,13 @@ const commandsMap: ( ) { const config = await configHandler.loadConfig(); + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + ); + const modelTitle = - config.experimental?.modelRoles?.inlineEdit ?? - (await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - )); + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; sidebar.webviewProtocol.request("incrementFtc", undefined); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 792d504d3..786f5377a 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -27,6 +27,7 @@ import { import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { getModelByRole } from "core/config/util"; /** * A shared messenger class between Core and Webview @@ -145,26 +146,26 @@ export class VsCodeMessenger { // Get LLM from config const configHandler = await configHandlerPromise; const config = await configHandler.loadConfig(); - const modelTitle = - config.experimental?.modelRoles?.applyCodeBlock ?? - (await this.webviewProtocol.request("getDefaultModelTitle", undefined)); - const llm = config.models.find((model) => model.title === modelTitle); + + let llm = getModelByRole(config, "applyCodeBlock"); + if (!llm) { - vscode.window.showErrorMessage( - `Model ${modelTitle} not found in config.`, + const defaultModelTitle = await this.webviewProtocol.request( + "getDefaultModelTitle", + undefined, ); - return; + + llm = config.models.find((model) => model.title === defaultModelTitle); + + if (!llm) { + vscode.window.showErrorMessage( + `Model ${defaultModelTitle} not found in config.`, + ); + return; + } } - let fastLlm: ILLM | undefined; - if (config.experimental?.modelRoles?.repoMapFileSelection) { - fastLlm = config.models.find( - (model) => - model.title === - config.experimental?.modelRoles?.repoMapFileSelection, - ); - } - fastLlm ??= llm; + const fastLlm = getModelByRole(config, "repoMapFileSelection") ?? llm; // Generate the diff and pass through diff manager const [instant, diffLines] = await applyCodeBlock( @@ -179,7 +180,7 @@ export class VsCodeMessenger { verticalDiffManager.streamDiffLines(diffLines, instant); } else { const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`; - verticalDiffManager.streamEdit(prompt, modelTitle); + verticalDiffManager.streamEdit(prompt, llm.title); } }); diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 6fc3404c6..b501c0250 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -13,6 +13,7 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; import { ConfigHandler } from "core/config/ConfigHandler"; // @ts-ignore import MiniSearch from "minisearch"; +import { getModelByRole } from "core/config/util"; /** * Used to track what action to take after a user interacts @@ -222,30 +223,21 @@ export class QuickEdit { * Gets the model title the user has chosen, or their default model */ private async getCurModelTitle() { - const config = await this.configHandler.loadConfig(); - if (this._curModelTitle) { return this._curModelTitle; } - const inlineEditModel = config.experimental?.modelRoles?.inlineEdit; + const config = await this.configHandler.loadConfig(); - if (inlineEditModel) { - return inlineEditModel; - } - - let defaultModelTitle: string | undefined = - await this.webviewProtocol.request( + return ( + getModelByRole(config, "inlineEdit")?.title ?? + (await this.webviewProtocol.request( "getDefaultModelTitle", undefined, false, - ); - - if (!defaultModelTitle) { - defaultModelTitle = config.models[0].title; - } - - return defaultModelTitle || inlineEditModel; + )) ?? + config.models[0]?.title + ); } /** diff --git a/gui/package-lock.json b/gui/package-lock.json index 30f10d3fd..59c98a50f 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -4474,6 +4474,11 @@ "license": "MIT", "peer": true }, + "../core/node_modules/@types/diff": { + "version": "5.2.2", + "dev": true, + "license": "MIT" + }, "../core/node_modules/@types/follow-redirects": { "version": "1.14.4", "dev": true, @@ -6447,6 +6452,13 @@ "version": "0.0.1312386", "license": "BSD-3-Clause" }, + "../core/node_modules/diff": { + "version": "7.0.0", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, "../core/node_modules/diff-sequences": { "version": "29.6.3", "dev": true, @@ -13960,8 +13972,6 @@ }, "node_modules/@swc/core": { "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.7.26.tgz", - "integrity": "sha512-f5uYFf+TmMQyYIoxkn/evWhNGuUzC730dFwAKGwBVHHVoPyak1/GvJUm6i1SKl+2Hrj9oN0i3WSoWWZ4pgI8lw==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", @@ -13997,27 +14007,8 @@ } } }, - "node_modules/@swc/core-darwin-arm64": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.7.26.tgz", - "integrity": "sha512-FF3CRYTg6a7ZVW4yT9mesxoVVZTrcSWtmZhxKCYJX9brH4CS/7PRPjAKNk6kzWgWuRoglP7hkjQcd6EpMcZEAw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=10" - } - }, "node_modules/@swc/core-darwin-x64": { "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.7.26.tgz", - "integrity": "sha512-az3cibZdsay2HNKmc4bjf62QVukuiMRh5sfM5kHR/JMTrLyS6vSw7Ihs3UTkZjUxkLTT8ro54LI6sV6sUQUbLQ==", "cpu": [ "x64" ], @@ -14031,142 +14022,6 @@ "node": ">=10" } }, - "node_modules/@swc/core-linux-arm-gnueabihf": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.7.26.tgz", - "integrity": "sha512-VYPFVJDO5zT5U3RpCdHE5v1gz4mmR8BfHecUZTmD2v1JeFY6fv9KArJUpjrHEEsjK/ucXkQFmJ0jaiWXmpOV9Q==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-linux-arm64-gnu": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.7.26.tgz", - "integrity": "sha512-YKevOV7abpjcAzXrhsl+W48Z9mZvgoVs2eP5nY+uoMAdP2b3GxC0Df1Co0I90o2lkzO4jYBpTMcZlmUXLdXn+Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-linux-arm64-musl": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.7.26.tgz", - "integrity": "sha512-3w8iZICMkQQON0uIcvz7+Q1MPOW6hJ4O5ETjA0LSP/tuKqx30hIniCGOgPDnv3UTMruLUnQbtBwVCZTBKR3Rkg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-linux-x64-gnu": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.7.26.tgz", - "integrity": "sha512-c+pp9Zkk2lqb06bNGkR2Looxrs7FtGDMA4/aHjZcCqATgp348hOKH5WPvNLBl+yPrISuWjbKDVn3NgAvfvpH4w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-linux-x64-musl": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.7.26.tgz", - "integrity": "sha512-PgtyfHBF6xG87dUSSdTJHwZ3/8vWZfNIXQV2GlwEpslrOkGqy+WaiiyE7Of7z9AvDILfBBBcJvJ/r8u980wAfQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-win32-arm64-msvc": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.7.26.tgz", - "integrity": "sha512-9TNXPIJqFynlAOrRD6tUQjMq7KApSklK3R/tXgIxc7Qx+lWu8hlDQ/kVPLpU7PWvMMwC/3hKBW+p5f+Tms1hmA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-win32-ia32-msvc": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.7.26.tgz", - "integrity": "sha512-9YngxNcG3177GYdsTum4V98Re+TlCeJEP4kEwEg9EagT5s3YejYdKwVAkAsJszzkXuyRDdnHUpYbTrPG6FiXrQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=10" - } - }, - "node_modules/@swc/core-win32-x64-msvc": { - "version": "1.7.26", - "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.7.26.tgz", - "integrity": "sha512-VR+hzg9XqucgLjXxA13MtV5O3C0bK0ywtLIBw/+a+O+Oc6mxFWHtdUeXDbIi5AiPbn0fjgVJMqYnyjGyyX8u0w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 AND MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=10" - } - }, "node_modules/@swc/counter": { "version": "0.1.3", "dev": true, diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 83b9c4b02..3d3200433 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -13,6 +13,8 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { getFontSize } from "../../util"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; +import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; +import { getIconFromDropdownItem } from "./MentionList"; const ContextItemDiv = styled.div` cursor: pointer; @@ -47,12 +49,20 @@ interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; } +function filterInstructionContextItem( + contextItems: ContextItemsPeekProps["contextItems"], +) { + return contextItems?.filter( + (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), + ); +} + const ContextItemsPeek = (props: ContextItemsPeekProps) => { const ideMessenger = useContext(IdeMessengerContext); const [open, setOpen] = React.useState(false); - const ctxItems = props.contextItems; + const ctxItems = filterInstructionContextItem(props.contextItems); if (!ctxItems || ctxItems.length === 0) { return null; @@ -84,6 +94,50 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { } } + const getContextItemIcon = (contextItem: ContextItemWithId) => { + const dimmensions = "1.4em"; + + if (contextItem.icon) { + return ( + + ); + } + + // Heuristic to check if it's a file + const shouldShowFileIcon = contextItem.content.includes("```"); + + if (shouldShowFileIcon) { + return ( + + ); + } + + const ProviderIcon = getIconFromDropdownItem( + contextItem.id.providerTitle, + "contextProvider", + ); + + return ( + + ); + }; + return (
{ )} {contextItemsText}
+ {open && (
{ }} > {ctxItems?.map((contextItem, idx) => { - if (contextItem.description.startsWith("http")) { - return ( - - { - openContextItem(contextItem); - }} - > - {!!contextItem.icon ? ( - - ) : ( - - )} - {contextItem.name} - - - ); - } - - return ( - { - openContextItem(contextItem); - }} - > - {!!contextItem.icon ? ( - - ) : ( - - )} + const contextItemContent = ( + openContextItem(contextItem)}> + {getContextItemIcon(contextItem)} {contextItem.name} ); + + return contextItem.description.startsWith("http") ? ( + + {contextItemContent} + + ) : ( + {contextItemContent} + ); })}
)} diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index ebe6048d2..95ddc15ca 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -44,7 +44,7 @@ import ButtonWithTooltip from "../ButtonWithTooltip"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; import AddDocsDialog from "../dialogs/AddDocsDialog"; -import { ComboBoxItem } from "./types"; +import { ComboBoxItem, ComboBoxItemType } from "./types"; const ICONS_FOR_DROPDOWN: { [key: string]: any } = { file: FolderIcon, @@ -60,6 +60,7 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { docs: BookOpenIcon, issue: ExclamationCircleIcon, trash: TrashIcon, + "repo-map": FolderIcon, "/edit": PencilIcon, "/clear": TrashIcon, "/comment": HashtagIcon, @@ -67,6 +68,13 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { "/cmd": CommandLineIcon, }; +export function getIconFromDropdownItem(id: string, type: ComboBoxItemType) { + return ( + ICONS_FOR_DROPDOWN[id] ?? + (type === "contextProvider" ? AtSymbolIcon : BoltIcon) + ); +} + function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { if (props.item.type === "action") { return ( @@ -74,19 +82,12 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { ); } - const provider = (() => { - switch (props.item.type) { - case "contextProvider": - case "slashCommand": - return props.item.id; - default: - return props.item.type; - } - })(); + const provider = + props.item.type === "contextProvider" || props.item.type === "slashCommand" + ? props.item.id + : props.item.type; - const IconComponent = - ICONS_FOR_DROPDOWN[provider] ?? - (props.item.type === "contextProvider" ? AtSymbolIcon : BoltIcon); + const IconComponent = getIconFromDropdownItem(provider, props.item.type); const fallbackIcon = (