From 158faa1e5e4765e9953d97729fd8efa93cdd7c32 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 15:49:25 -0700 Subject: [PATCH 01/17] create `getModelByRole()` util fn --- core/config/util.ts | 25 ++++++++++++- core/context/retrieval/repoMapRequest.ts | 7 ++-- docs/static/schemas/config.json | 15 ++++---- .../src/main/resources/config_schema.json | 15 ++++---- extensions/vscode/continue_rc_schema.json | 15 ++++---- extensions/vscode/src/commands.ts | 12 ++++--- .../vscode/src/extension/VsCodeMessenger.ts | 35 ++++++++++--------- .../src/quickEdit/QuickEditQuickPick.ts | 24 +++++-------- 8 files changed, 77 insertions(+), 71 deletions(-) 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/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 8d2eb9e4f..1f07d61d0 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,4 +1,5 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; +import { getModelByRole } from "../../config/util"; import { stripImages } from "../../llm/images"; import generateRepoMap from "../../util/repoMap"; @@ -9,11 +10,7 @@ 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")) { 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/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 + ); } /** From 1837de9d90be058ab8fcaa19ba41dadeebadb595 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 16:35:28 -0700 Subject: [PATCH 02/17] Filter "Instructions" item from `ContextPeek` --- .../providers/CodebaseContextProvider.ts | 6 +- core/context/providers/DocsContextProvider.ts | 4 +- core/context/providers/index.ts | 8 +- core/context/retrieval/retrieval.ts | 22 +-- gui/package-lock.json | 169 ++---------------- .../components/mainInput/ContextItemsPeek.tsx | 12 +- 6 files changed, 44 insertions(+), 177 deletions(-) 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..b56373742 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -1,3 +1,4 @@ +import { INSTRUCTIONS_BASE_ITEM } from "."; 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/index.ts b/core/context/providers/index.ts index 92cabb222..d2804a8b6 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"; @@ -60,3 +60,9 @@ export function contextProviderClassFromName( ): typeof BaseContextProvider | undefined { return Providers.find((cls) => cls.description.title === name); } + +export const INSTRUCTIONS_BASE_ITEM: ContextItem = { + name: "Instructions", + description: "Instructions", + content: "", +}; diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 34c6bd87c..897ec65a8 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/"; +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/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..fce70afa2 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -13,6 +13,7 @@ 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"; const ContextItemDiv = styled.div` cursor: pointer; @@ -47,12 +48,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; @@ -118,6 +127,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { )} {contextItemsText} + {open && (
Date: Thu, 19 Sep 2024 18:28:18 -0700 Subject: [PATCH 03/17] add submenu for repo map context provider --- core/context/providers/DocsContextProvider.ts | 2 +- .../providers/RepoMapContextProvider.ts | 37 +++++++++++++++++-- core/context/providers/index.ts | 8 +--- core/context/providers/utils.ts | 7 ++++ core/context/retrieval/retrieval.ts | 2 +- core/util/repoMap.ts | 2 +- extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 2 +- gui/src/components/mainInput/MentionList.tsx | 5 +-- 10 files changed, 51 insertions(+), 20 deletions(-) create mode 100644 core/context/providers/utils.ts diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index b56373742..e9ae11bde 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -1,4 +1,4 @@ -import { INSTRUCTIONS_BASE_ITEM } from "."; +import { INSTRUCTIONS_BASE_ITEM } from "./utils"; import { BaseContextProvider } from "../"; import { Chunk, diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 3d6c1d63f..900cd87dc 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 { + groupByLastNPathParts, + getBasename, + getUniqueFilePath, +} from "../../util"; import generateRepoMap from "../../util/repoMap"; +const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = { + id: "entire-workspace", + title: "Entire workspace", + description: "Search the entire workspace", +}; + 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 d2804a8b6..9c2ab4303 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -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, @@ -60,9 +60,3 @@ export function contextProviderClassFromName( ): typeof BaseContextProvider | undefined { return Providers.find((cls) => cls.description.title === name); } - -export const INSTRUCTIONS_BASE_ITEM: ContextItem = { - name: "Instructions", - description: "Instructions", - content: "", -}; 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/retrieval.ts b/core/context/retrieval/retrieval.ts index 897ec65a8..1b250e548 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -2,7 +2,7 @@ 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/"; +import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts index 6c0a73e1f..8fb5a329f 100644 --- a/core/util/repoMap.ts +++ b/core/util/repoMap.ts @@ -115,7 +115,7 @@ async function generateRepoMap(llm: ILLM, ide: IDE, options?: RepoMapOptions) { } writeStream.end(); - console.debug(`Generated repo map at ${repoMapPath}`); + console.debug(`Generated repo map for ${dirs.join(", ")} at ${repoMapPath}`); if (curTokens >= maxRepoMapTokens) { console.debug( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 238a2c841..746043d15 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.214", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.213", + "version": "0.9.214", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 5f3265799..2269b08dc 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.213", + "version": "0.9.214", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index fce70afa2..50d3f32ac 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -13,7 +13,7 @@ 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"; +import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; const ContextItemDiv = styled.div` cursor: pointer; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index ebe6048d2..cd6622416 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -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, @@ -113,9 +114,7 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { const ItemsDiv = styled.div` border-radius: ${defaultBorderRadius}; - box-shadow: - 0 0 0 1px rgba(0, 0, 0, 0.05), - 0px 10px 20px rgba(0, 0, 0, 0.1); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0px 10px 20px rgba(0, 0, 0, 0.1); font-size: 0.9rem; overflow-x: hidden; overflow-y: auto; From 128356c35a77bf514cf519a4a9cb5883c9d8fa20 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 18:38:18 -0700 Subject: [PATCH 04/17] Update repoMap.ts --- core/util/repoMap.ts | 125 ++++++++++++++++++++++++++++--------------- 1 file changed, 82 insertions(+), 43 deletions(-) diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts index 8fb5a329f..07f9e28a5 100644 --- a/core/util/repoMap.ts +++ b/core/util/repoMap.ts @@ -12,7 +12,6 @@ const repoMapPreamble = "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) { @@ -27,25 +26,63 @@ export interface RepoMapOptions { 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; +async function getPaths(dirs: string[], ide: IDE): Promise> { + const paths = new Set(); - const pathsWithoutSnippets = new Set(); for (const dir of dirs) { for await (const filepath of walkDirAsync(dir, ide)) { - pathsWithoutSnippets.add(filepath.replace(dir, "").slice(1)); + paths.add(filepath.replace(dir, "").slice(1)); } } + return paths; +} + +async function initializeWriteStream( + repoMapPath: string, +): Promise { 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)); + return writeStream; +} +function generateContentForPath( + absolutePath: string, + signatures: string[], + dirs: string[], + options: RepoMapOptions, +): string { + const workspaceDir = dirs.find((dir) => absolutePath.startsWith(dir)) || ""; + const relativePath = path.relative(workspaceDir, absolutePath); + let content = ""; + + 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) { + content += `${indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; + } + } else { + content += `${relativePath}\n`; + } + + return content; +} + +async function processPathsAndSignatures( + llm: ILLM, + dirs: string[], + options: RepoMapOptions, + writeStream: fs.WriteStream, + maxRepoMapTokens: number, +): Promise { let curTokens = llm.countTokens(repoMapPreamble); let offset = 0; const batchSize = 100; @@ -59,59 +96,63 @@ async function generateRepoMap(llm: ILLM, ide: IDE, options?: RepoMapOptions) { ); 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`; - } + content += generateContentForPath( + absolutePath, + signatures, + dirs, + options, + ); } 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; + return curTokens + llm.countTokens(prunedContent); } else { await new Promise((resolve) => writeStream.write(content, resolve)); + curTokens += contentTokens; } - 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)); + return curTokens; +} + +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 paths = await getPaths(dirs, ide); + const writeStream = await initializeWriteStream(repoMapPath); + + const curTokens = await processPathsAndSignatures( + llm, + dirs, + options, + writeStream, + maxRepoMapTokens, + ); + + const remainingPaths = Array.from(paths).join("\n"); + + if (remainingPaths.length > 0) { + await new Promise((resolve) => writeStream.write(remainingPaths, resolve)); } writeStream.end(); @@ -119,13 +160,11 @@ async function generateRepoMap(llm: ILLM, ide: IDE, options?: RepoMapOptions) { if (curTokens >= maxRepoMapTokens) { console.debug( - "Full repo map was unable to be genereated due to context window limitations", + "Full repo map was unable to be generated due to context window limitations", ); } - const repoMap = fs.readFileSync(repoMapPath, "utf8"); - - return repoMap; + return fs.readFileSync(repoMapPath, "utf8"); } export default generateRepoMap; From 86a568d3a0a3e31305f3b35074a5a1318248a765 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 18:48:07 -0700 Subject: [PATCH 05/17] remove signatures if they are same as file content --- core/context/retrieval/repoMapRequest.ts | 2 +- core/util/repoMap.ts | 31 +++++++++++++++--------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 1f07d61d0..9dea96de0 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -19,7 +19,7 @@ export async function requestFilesFromRepoMap( try { const repoMap = await generateRepoMap(llm, ide, { - signatures: false, + includeSignatures: false, dirs: filterDirectory ? [filterDirectory] : undefined, }); diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts index 07f9e28a5..dfb6a63ab 100644 --- a/core/util/repoMap.ts +++ b/core/util/repoMap.ts @@ -13,6 +13,10 @@ const repoMapPreamble = "classes, methods, or functions in the file.\n\n"; const REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; +export interface RepoMapOptions { + includeSignatures?: boolean; + dirs?: string[]; +} function indentMultilineString(str: string) { return str @@ -21,9 +25,8 @@ function indentMultilineString(str: string) { .join("\n"); } -export interface RepoMapOptions { - signatures?: boolean; - dirs?: string[]; +function isSnippetSameAsFile(snippet: string, fileContent: string): boolean { + return snippet.trim() === fileContent.trim(); } async function getPaths(dirs: string[], ide: IDE): Promise> { @@ -53,22 +56,23 @@ function generateContentForPath( absolutePath: string, signatures: string[], dirs: string[], - options: RepoMapOptions, + { includeSignatures }: RepoMapOptions, ): string { const workspaceDir = dirs.find((dir) => absolutePath.startsWith(dir)) || ""; const relativePath = path.relative(workspaceDir, absolutePath); + let content = ""; - if (options.signatures !== false) { + if (includeSignatures) { content += `${relativePath}:\n`; + for (const signature of signatures.slice(0, -1)) { content += `${indentMultilineString(signature)}\n\t...\n`; } - if (signatures.length > 0) { - content += `${indentMultilineString( - signatures[signatures.length - 1], - )}\n\n`; - } + + content += `${indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; } else { content += `${relativePath}\n`; } @@ -97,9 +101,14 @@ async function processPathsAndSignatures( let content = ""; for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { + const fileContent = await fs.promises.readFile(absolutePath, "utf8"); + const filteredSignatures = signatures.filter( + (signature) => !isSnippetSameAsFile(signature, fileContent), + ); + content += generateContentForPath( absolutePath, - signatures, + filteredSignatures, dirs, options, ); From 4bb1a23a92c5663385434a7125fbad4bba7ba7e6 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 19:50:19 -0700 Subject: [PATCH 06/17] remove duplicate entries in repo map --- core/indexing/CodeSnippetsIndex.ts | 16 ++- core/util/repoMap.ts | 184 ++++++++++++++++++++--------- 2 files changed, 134 insertions(+), 66 deletions(-) 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/util/repoMap.ts b/core/util/repoMap.ts index dfb6a63ab..6f2166884 100644 --- a/core/util/repoMap.ts +++ b/core/util/repoMap.ts @@ -13,6 +13,9 @@ const repoMapPreamble = "classes, methods, or functions in the file.\n\n"; const REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; + +const BATCH_SIZE = 100; + export interface RepoMapOptions { includeSignatures?: boolean; dirs?: string[]; @@ -53,17 +56,13 @@ async function initializeWriteStream( } function generateContentForPath( - absolutePath: string, + relativePath: string, signatures: string[], - dirs: string[], { includeSignatures }: RepoMapOptions, ): string { - const workspaceDir = dirs.find((dir) => absolutePath.startsWith(dir)) || ""; - const relativePath = path.relative(workspaceDir, absolutePath); - let content = ""; - if (includeSignatures) { + if (includeSignatures !== false) { content += `${relativePath}:\n`; for (const signature of signatures.slice(0, -1)) { @@ -84,94 +83,165 @@ async function processPathsAndSignatures( llm: ILLM, dirs: string[], options: RepoMapOptions, - writeStream: fs.WriteStream, maxRepoMapTokens: number, -): Promise { + ide: IDE, +): Promise<{ content: string; remainingPaths: Set }> { + const paths = await getPaths(dirs, ide); + let pathsWithoutSignatures = new Set(paths); + + let content = ""; let curTokens = llm.countTokens(repoMapPreamble); let offset = 0; - const batchSize = 100; while (true) { const { groupedByPath, hasMore } = await CodeSnippetsCodebaseIndex.getPathsAndSignatures( dirs, offset, - batchSize, + BATCH_SIZE, ); - let content = ""; - for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { - const fileContent = await fs.promises.readFile(absolutePath, "utf8"); - const filteredSignatures = signatures.filter( - (signature) => !isSnippetSameAsFile(signature, fileContent), - ); + const { batchContent, updatedPathsWithoutSignatures } = await processBatch( + groupedByPath, + dirs, + options, + pathsWithoutSignatures, + ); - content += generateContentForPath( - absolutePath, - filteredSignatures, - dirs, - options, - ); - } + pathsWithoutSignatures = updatedPathsWithoutSignatures; - const contentTokens = llm.countTokens(content); + const batchTokens = llm.countTokens(batchContent); - if (curTokens + contentTokens >= maxRepoMapTokens) { - const prunedContent = pruneLinesFromTop( - content, + if (curTokens + batchTokens >= maxRepoMapTokens) { + content += pruneLinesFromTop( + batchContent, maxRepoMapTokens - curTokens, llm.model, ); - await new Promise((resolve) => writeStream.write(prunedContent, resolve)); - return curTokens + llm.countTokens(prunedContent); - } else { - await new Promise((resolve) => writeStream.write(content, resolve)); - curTokens += contentTokens; + break; } + content += batchContent; + curTokens += batchTokens; + if (!hasMore) { break; } - offset += batchSize; + offset += BATCH_SIZE; } - return curTokens; + return { content, remainingPaths: pathsWithoutSignatures }; } -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; +async function processBatch( + groupedByPath: Record, + dirs: string[], + options: RepoMapOptions, + pathsWithoutSignatures: Set, +): Promise<{ + batchContent: string; + updatedPathsWithoutSignatures: Set; +}> { + let batchContent = ""; + const updatedPathsWithoutSignatures = new Set(pathsWithoutSignatures); - const paths = await getPaths(dirs, ide); - const writeStream = await initializeWriteStream(repoMapPath); + for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { + const { content } = await processFile( + absolutePath, + signatures, + dirs, + options, + updatedPathsWithoutSignatures, + ); + batchContent += content; + } + return { batchContent, updatedPathsWithoutSignatures }; +} - const curTokens = await processPathsAndSignatures( - llm, - dirs, - options, - writeStream, - maxRepoMapTokens, +async function processFile( + absolutePath: string, + signatures: string[], + dirs: string[], + options: RepoMapOptions, + pathsWithoutSignatures: Set, +): Promise<{ relativePath: string; content: string }> { + const workspaceDir = dirs.find((dir) => absolutePath.startsWith(dir)) || ""; + const relativePath = path.relative(workspaceDir, absolutePath); + + const fileContent = await fs.promises.readFile(absolutePath, "utf8"); + const filteredSignatures = signatures.filter( + (signature) => !isSnippetSameAsFile(signature, fileContent), ); - const remainingPaths = Array.from(paths).join("\n"); - - if (remainingPaths.length > 0) { - await new Promise((resolve) => writeStream.write(remainingPaths, resolve)); + if (filteredSignatures.length > 0) { + pathsWithoutSignatures.delete(relativePath); } - writeStream.end(); - console.debug(`Generated repo map for ${dirs.join(", ")} at ${repoMapPath}`); + const content = generateContentForPath( + relativePath, + filteredSignatures, + options, + ); + return { relativePath, content }; +} - if (curTokens >= maxRepoMapTokens) { +async function writeContentToStream( + writeStream: fs.WriteStream, + content: string, +): Promise { + await new Promise((resolve) => writeStream.write(content, resolve)); +} + +async function writeRemainingPaths( + writeStream: fs.WriteStream, + remainingPaths: Set, +): Promise { + if (remainingPaths.size > 0) { + await new Promise((resolve) => + writeStream.write(Array.from(remainingPaths).join("\n"), resolve), + ); + } +} + +function logRepoMapGeneration( + dirs: string[], + repoMapPath: string, + contentTokens: number, + maxRepoMapTokens: number, +): void { + console.debug(`Generated repo map for ${dirs.join(", ")} at ${repoMapPath}`); + if (contentTokens >= maxRepoMapTokens) { console.debug( "Full repo map was unable to be generated due to context window limitations", ); } +} + +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 writeStream = await initializeWriteStream(repoMapPath); + + const { content, remainingPaths } = await processPathsAndSignatures( + llm, + dirs, + options, + maxRepoMapTokens, + ide, + ); + + await writeContentToStream(writeStream, content); + await writeRemainingPaths(writeStream, remainingPaths); + + writeStream.end(); + + logRepoMapGeneration( + dirs, + repoMapPath, + llm.countTokens(content), + maxRepoMapTokens, + ); return fs.readFileSync(repoMapPath, "utf8"); } From 8d09840e3a13501066e7928e59c67c9aae9005d6 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 20:15:14 -0700 Subject: [PATCH 07/17] Update repoMap.ts --- core/util/repoMap.ts | 357 ++++++++++++++++++------------------------- 1 file changed, 150 insertions(+), 207 deletions(-) diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts index 6f2166884..2d7f2a17f 100644 --- a/core/util/repoMap.ts +++ b/core/util/repoMap.ts @@ -6,244 +6,187 @@ 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"; - -const REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; - -const BATCH_SIZE = 100; - export interface RepoMapOptions { includeSignatures?: boolean; dirs?: string[]; } -function indentMultilineString(str: string) { - return str - .split("\n") - .map((line: any) => "\t" + line) - .join("\n"); -} +class RepoMapGenerator { + private llm: ILLM; + private ide: IDE; + private options: RepoMapOptions; + private repoMapPath: string; + private maxRepoMapTokens: number; + private writeStream: fs.WriteStream; + private contentTokens: number = 0; + private dirs: string[] = []; + private allPathsInDirs: Set = new Set(); + private pathsInDirsWithSnippets: Set = new Set(); + private BATCH_SIZE = 100; + private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; + private 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"; -function isSnippetSameAsFile(snippet: string, fileContent: string): boolean { - return snippet.trim() === fileContent.trim(); -} + constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) { + this.llm = llm; + this.ide = ide; + this.options = options; + this.repoMapPath = getRepoMapFilePath(); + this.maxRepoMapTokens = + llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; + this.writeStream = fs.createWriteStream(this.repoMapPath); + } -async function getPaths(dirs: string[], ide: IDE): Promise> { - const paths = new Set(); + async generate(): Promise { + this.dirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs()); + this.allPathsInDirs = await this.getAllPathsInDirs(); - for (const dir of dirs) { - for await (const filepath of walkDirAsync(dir, ide)) { - paths.add(filepath.replace(dir, "").slice(1)); + 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.repoMapPreamble); + this.contentTokens += this.llm.countTokens(this.repoMapPreamble); + } + + private async getAllPathsInDirs(): Promise> { + const paths = new Set(); + + for (const dir of this.dirs) { + 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.dirs, + 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); + await this.writeToStream(content); } } - return paths; -} + private async processFile( + absolutePath: string, + signatures: string[], + ): Promise { + const workspaceDir = + this.dirs.find((dir) => absolutePath.startsWith(dir)) || ""; + const relativePath = path.relative(workspaceDir, absolutePath); + const fileContent = await fs.promises.readFile(absolutePath, "utf8"); + const filteredSignatures = signatures.filter( + (signature) => !this.isSnippetSameAsFile(signature, fileContent), + ); -async function initializeWriteStream( - repoMapPath: string, -): Promise { - if (fs.existsSync(repoMapPath)) { - console.debug(`Overwriting existing repo map at ${repoMapPath}`); + if (filteredSignatures.length > 0) { + this.pathsInDirsWithSnippets.add(relativePath); + } + + return this.generateContentForPath(relativePath, filteredSignatures); } - const writeStream = fs.createWriteStream(repoMapPath); - await new Promise((resolve) => writeStream.write(repoMapPreamble, resolve)); - return writeStream; -} -function generateContentForPath( - relativePath: string, - signatures: string[], - { includeSignatures }: RepoMapOptions, -): string { - let content = ""; - - if (includeSignatures !== false) { - content += `${relativePath}:\n`; + 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 += `${indentMultilineString(signature)}\n\t...\n`; + content += `${this.indentMultilineString(signature)}\n\t...\n`; } - - content += `${indentMultilineString( + content += `${this.indentMultilineString( signatures[signatures.length - 1], )}\n\n`; - } else { - content += `${relativePath}\n`; + return content; } - return content; -} - -async function processPathsAndSignatures( - llm: ILLM, - dirs: string[], - options: RepoMapOptions, - maxRepoMapTokens: number, - ide: IDE, -): Promise<{ content: string; remainingPaths: Set }> { - const paths = await getPaths(dirs, ide); - let pathsWithoutSignatures = new Set(paths); - - let content = ""; - let curTokens = llm.countTokens(repoMapPreamble); - let offset = 0; - - while (true) { - const { groupedByPath, hasMore } = - await CodeSnippetsCodebaseIndex.getPathsAndSignatures( - dirs, - offset, - BATCH_SIZE, + 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, ); - - const { batchContent, updatedPathsWithoutSignatures } = await processBatch( - groupedByPath, - dirs, - options, - pathsWithoutSignatures, - ); - - pathsWithoutSignatures = updatedPathsWithoutSignatures; - - const batchTokens = llm.countTokens(batchContent); - - if (curTokens + batchTokens >= maxRepoMapTokens) { - content += pruneLinesFromTop( - batchContent, - maxRepoMapTokens - curTokens, - llm.model, - ); - break; } + this.contentTokens += this.llm.countTokens(content); + await new Promise((resolve) => this.writeStream.write(content, resolve)); + } - content += batchContent; - curTokens += batchTokens; + private async writeRemainingPaths(): Promise { + const pathsWithoutSnippets = new Set( + [...this.allPathsInDirs].filter( + (x) => !this.pathsInDirsWithSnippets.has(x), + ), + ); - if (!hasMore) { - break; + if (pathsWithoutSnippets.size > 0) { + await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n")); } - offset += BATCH_SIZE; } - return { content, remainingPaths: pathsWithoutSignatures }; -} - -async function processBatch( - groupedByPath: Record, - dirs: string[], - options: RepoMapOptions, - pathsWithoutSignatures: Set, -): Promise<{ - batchContent: string; - updatedPathsWithoutSignatures: Set; -}> { - let batchContent = ""; - const updatedPathsWithoutSignatures = new Set(pathsWithoutSignatures); - - for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { - const { content } = await processFile( - absolutePath, - signatures, - dirs, - options, - updatedPathsWithoutSignatures, - ); - batchContent += content; - } - return { batchContent, updatedPathsWithoutSignatures }; -} - -async function processFile( - absolutePath: string, - signatures: string[], - dirs: string[], - options: RepoMapOptions, - pathsWithoutSignatures: Set, -): Promise<{ relativePath: string; content: string }> { - const workspaceDir = dirs.find((dir) => absolutePath.startsWith(dir)) || ""; - const relativePath = path.relative(workspaceDir, absolutePath); - - const fileContent = await fs.promises.readFile(absolutePath, "utf8"); - const filteredSignatures = signatures.filter( - (signature) => !isSnippetSameAsFile(signature, fileContent), - ); - - if (filteredSignatures.length > 0) { - pathsWithoutSignatures.delete(relativePath); - } - - const content = generateContentForPath( - relativePath, - filteredSignatures, - options, - ); - return { relativePath, content }; -} - -async function writeContentToStream( - writeStream: fs.WriteStream, - content: string, -): Promise { - await new Promise((resolve) => writeStream.write(content, resolve)); -} - -async function writeRemainingPaths( - writeStream: fs.WriteStream, - remainingPaths: Set, -): Promise { - if (remainingPaths.size > 0) { - await new Promise((resolve) => - writeStream.write(Array.from(remainingPaths).join("\n"), resolve), - ); - } -} - -function logRepoMapGeneration( - dirs: string[], - repoMapPath: string, - contentTokens: number, - maxRepoMapTokens: number, -): void { - console.debug(`Generated repo map for ${dirs.join(", ")} at ${repoMapPath}`); - if (contentTokens >= maxRepoMapTokens) { + private logRepoMapGeneration(): void { console.debug( - "Full repo map was unable to be generated due to context window limitations", + `Generated repo map for ${this.dirs.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 isSnippetSameAsFile(snippet: string, fileContent: string): boolean { + return snippet.trim() === fileContent.trim(); + } + + private indentMultilineString(str: string) { + return str + .split("\n") + .map((line: any) => "\t" + line) + .join("\n"); } } -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 writeStream = await initializeWriteStream(repoMapPath); - - const { content, remainingPaths } = await processPathsAndSignatures( - llm, - dirs, - options, - maxRepoMapTokens, - ide, - ); - - await writeContentToStream(writeStream, content); - await writeRemainingPaths(writeStream, remainingPaths); - - writeStream.end(); - - logRepoMapGeneration( - dirs, - repoMapPath, - llm.countTokens(content), - maxRepoMapTokens, - ); - - return fs.readFileSync(repoMapPath, "utf8"); +export default async function generateRepoMap( + llm: ILLM, + ide: IDE, + options: RepoMapOptions, +): Promise { + const generator = new RepoMapGenerator(llm, ide, options); + return generator.generate(); } - -export default generateRepoMap; From f223de175795c0a733b8129d9c49afb23f3539ce Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 19 Sep 2024 20:43:46 -0700 Subject: [PATCH 08/17] Update ContextItemsPeek.tsx --- .../components/mainInput/ContextItemsPeek.tsx | 129 +++++++++--------- 1 file changed, 66 insertions(+), 63 deletions(-) diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 50d3f32ac..7f9a97318 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -1,4 +1,8 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; +import { + ChevronDownIcon, + ChevronUpIcon, + CircleStackIcon, +} from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { contextItemToRangeInFileWithContents } from "core/commands/util"; import React, { useContext } from "react"; @@ -14,6 +18,7 @@ import { getFontSize } from "../../util"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; +import { MapIcon } from "@heroicons/react/24/outline"; const ContextItemDiv = styled.div` cursor: pointer; @@ -48,6 +53,11 @@ interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; } +const CONTEXT_PROVIDERS_TO_ICONS: Record = { + "repo-map": MapIcon, + database: CircleStackIcon, +}; + function filterInstructionContextItem( contextItems: ContextItemsPeekProps["contextItems"], ) { @@ -93,6 +103,45 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { } } + const getContextItemIcon = (contextItem: ContextItemWithId) => { + const dimmensions = "1.4em"; + + if (contextItem.icon) { + return ( + + ); + } + + const ProviderIcon = + CONTEXT_PROVIDERS_TO_ICONS[contextItem.id.providerTitle]; + + if (ProviderIcon) { + return ( + + ); + } + + return ( + + ); + }; + return (
{ }} > {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} + ); })}
)} From 5cfcf3d9f5ef3b6285b44ae861e9e81cfdb1b861 Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 20 Sep 2024 10:00:57 -0700 Subject: [PATCH 09/17] cleanup --- .vscode/launch.json | 2 +- .../providers/RepoMapContextProvider.ts | 2 +- core/context/retrieval/repoMapRequest.ts | 9 +- core/util/repoMap.ts | 192 ------------------ 4 files changed, 7 insertions(+), 198 deletions(-) delete mode 100644 core/util/repoMap.ts 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/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 900cd87dc..cb2771638 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -11,7 +11,7 @@ import { getBasename, getUniqueFilePath, } from "../../util"; -import generateRepoMap from "../../util/repoMap"; +import generateRepoMap from "../../util/generateRepoMap"; const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = { id: "entire-workspace", diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 9dea96de0..3786e57be 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,7 +1,7 @@ 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"; export async function requestFilesFromRepoMap( defaultLlm: ILLM, @@ -13,9 +13,10 @@ export async function requestFilesFromRepoMap( const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm; // Only supported for Claude models right now - if (!llm.model.toLowerCase().includes("claude")) { - return []; - } + // TODO: Uncomment + // if (!llm.model.toLowerCase().includes("claude")) { + // return []; + // } try { const repoMap = await generateRepoMap(llm, ide, { diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts deleted file mode 100644 index 2d7f2a17f..000000000 --- a/core/util/repoMap.ts +++ /dev/null @@ -1,192 +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"; - -export interface RepoMapOptions { - includeSignatures?: boolean; - dirs?: string[]; -} - -class RepoMapGenerator { - private llm: ILLM; - private ide: IDE; - private options: RepoMapOptions; - private repoMapPath: string; - private maxRepoMapTokens: number; - private writeStream: fs.WriteStream; - private contentTokens: number = 0; - private dirs: string[] = []; - private allPathsInDirs: Set = new Set(); - private pathsInDirsWithSnippets: Set = new Set(); - private BATCH_SIZE = 100; - private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; - private 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"; - - constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) { - this.llm = llm; - this.ide = ide; - this.options = options; - this.repoMapPath = getRepoMapFilePath(); - this.maxRepoMapTokens = - llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; - this.writeStream = fs.createWriteStream(this.repoMapPath); - } - - async generate(): Promise { - this.dirs = 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.repoMapPreamble); - this.contentTokens += this.llm.countTokens(this.repoMapPreamble); - } - - private async getAllPathsInDirs(): Promise> { - const paths = new Set(); - - for (const dir of this.dirs) { - 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.dirs, - 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); - await this.writeToStream(content); - } - } - - private async processFile( - absolutePath: string, - signatures: string[], - ): Promise { - const workspaceDir = - this.dirs.find((dir) => absolutePath.startsWith(dir)) || ""; - const relativePath = path.relative(workspaceDir, absolutePath); - const fileContent = await fs.promises.readFile(absolutePath, "utf8"); - const filteredSignatures = signatures.filter( - (signature) => !this.isSnippetSameAsFile(signature, fileContent), - ); - - 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.dirs.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 isSnippetSameAsFile(snippet: string, fileContent: string): boolean { - return snippet.trim() === fileContent.trim(); - } - - 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(); -} From a9a34dd75421d44a9d8a25e0d527818a1e8a4b8d Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 20 Sep 2024 10:01:06 -0700 Subject: [PATCH 10/17] Create generateRepoMap.ts --- core/util/generateRepoMap.ts | 196 +++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 core/util/generateRepoMap.ts diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts new file mode 100644 index 000000000..1d130b82e --- /dev/null +++ b/core/util/generateRepoMap.ts @@ -0,0 +1,196 @@ +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); + 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); + const fileContent = await fs.promises.readFile(absolutePath, "utf8"); + 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(); +} From 213583b2a108c5410e6991d3a4d79b68de817b36 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 19 Sep 2024 21:07:55 -0700 Subject: [PATCH 11/17] user-select: none --- gui/src/components/mainInput/InputToolbar.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 960baa999..a95a71502 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -38,6 +38,8 @@ const StyledDiv = styled.div<{ isHidden: boolean }>` opacity: ${(props) => (props.isHidden ? 0 : 1)}; pointer-events: ${(props) => (props.isHidden ? "none" : "auto")}; + user-select: none; + & > * { flex: 0 0 auto; } From 4cc3029d23542769a54af9ec022b18075fa9b839 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 19 Sep 2024 21:10:17 -0700 Subject: [PATCH 12/17] workos bug fix --- extensions/vscode/src/stubs/SecretStorage.ts | 6 ++++-- extensions/vscode/src/stubs/WorkOsAuthProvider.ts | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index a12f313ae..4c85dfb01 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -92,13 +92,15 @@ export class SecretStorage { } async store(key: string, value: string): Promise { - const encryptedValue = await this.encrypt(value, this.keyToFilepath(key)); + const filePath = this.keyToFilepath(key); + await this.encrypt(value, filePath); } async get(key: string): Promise { const filePath = this.keyToFilepath(key); if (fs.existsSync(filePath)) { - return await this.decrypt(filePath); + const value = await this.decrypt(filePath); + return value; } return undefined; } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index bf5472d3d..ce3af8ff7 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -137,19 +137,24 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { if (!this._sessions.length) { return; } + + const finalSessions = []; for (const session of this._sessions) { try { const newSession = await this._refreshSession(session.refreshToken); session.accessToken = newSession.accessToken; session.refreshToken = newSession.refreshToken; session.expiresIn = newSession.expiresIn; + finalSessions.push(session); } catch (e: any) { if (e.message === "Network failure") { setTimeout(() => this._refreshSessions(), 60 * 1000); return; } + console.debug(`Error refreshing session token: ${e.message}`); } } + this._sessions = finalSessions; await this.storeSessions(this._sessions); this._sessionChangeEmitter.fire({ added: [], @@ -157,7 +162,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { changed: this._sessions, }); - if (this._sessions[0].expiresIn) { + if (this._sessions[0]?.expiresIn) { setTimeout( () => this._refreshSessions(), (this._sessions[0].expiresIn * 2) / 3, From 63b8f1bea88fd7fb5634ca05da790679fde12b0d Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 19 Sep 2024 21:11:17 -0700 Subject: [PATCH 13/17] bump version --- .changes/unreleased/Fixed-20240919-211112.yaml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .changes/unreleased/Fixed-20240919-211112.yaml diff --git a/.changes/unreleased/Fixed-20240919-211112.yaml b/.changes/unreleased/Fixed-20240919-211112.yaml new file mode 100644 index 000000000..5109006f8 --- /dev/null +++ b/.changes/unreleased/Fixed-20240919-211112.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Continue for teams auth bug fix +time: 2024-09-19T21:11:12.997946-07:00 From cb11cfb57c70992be9ccb2b557a6a370d991f49a Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 19 Sep 2024 21:13:39 -0700 Subject: [PATCH 14/17] -3 bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 2269b08dc..1f206771a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.214", + "version": "0.9.211", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From d055e2bc92b512530e6e6c868f0ee695326deca8 Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 20 Sep 2024 10:35:20 -0700 Subject: [PATCH 15/17] file read error handling --- core/context/retrieval/repoMapRequest.ts | 7 +++---- core/indexing/docs/DocsCrawler.ts | 2 +- core/util/generateRepoMap.ts | 23 ++++++++++++++++++++--- extensions/vscode/package-lock.json | 4 ++-- 4 files changed, 26 insertions(+), 10 deletions(-) diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 3786e57be..9a62041f6 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -13,10 +13,9 @@ export async function requestFilesFromRepoMap( const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm; // Only supported for Claude models right now - // TODO: Uncomment - // if (!llm.model.toLowerCase().includes("claude")) { - // return []; - // } + if (!llm.model.toLowerCase().includes("claude")) { + return []; + } try { const repoMap = await generateRepoMap(llm, ide, { 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 index 1d130b82e..785a62c41 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -93,18 +93,35 @@ class RepoMapGenerator { ): Promise { for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { const content = await this.processFile(absolutePath, signatures); - await this.writeToStream(content); + + if (content) { + await this.writeToStream(content); + } } } private async processFile( absolutePath: string, signatures: string[], - ): Promise { + ): Promise { const workspaceDir = this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || ""; const relativePath = path.relative(workspaceDir, absolutePath); - const fileContent = await fs.promises.readFile(absolutePath, "utf8"); + + 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(), ); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 746043d15..1efe40dfa 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.214", + "version": "0.9.211", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.214", + "version": "0.9.211", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", From 127a490e284e66d3c8d3b400a64fe99344a200b8 Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 20 Sep 2024 10:59:06 -0700 Subject: [PATCH 16/17] update context peek --- core/context/providers/OSContextProvider.ts | 6 ++++-- .../components/mainInput/ContextItemsPeek.tsx | 19 ++++++------------- gui/src/components/mainInput/MentionList.tsx | 14 ++++++++++---- 3 files changed, 20 insertions(+), 19 deletions(-) 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/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 7f9a97318..a8fb6b9f0 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -1,8 +1,4 @@ -import { - ChevronDownIcon, - ChevronUpIcon, - CircleStackIcon, -} from "@heroicons/react/24/outline"; +import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { contextItemToRangeInFileWithContents } from "core/commands/util"; import React, { useContext } from "react"; @@ -18,7 +14,7 @@ import { getFontSize } from "../../util"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; -import { MapIcon } from "@heroicons/react/24/outline"; +import { getIconFromDropdownItem } from "./MentionList"; const ContextItemDiv = styled.div` cursor: pointer; @@ -53,11 +49,6 @@ interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; } -const CONTEXT_PROVIDERS_TO_ICONS: Record = { - "repo-map": MapIcon, - database: CircleStackIcon, -}; - function filterInstructionContextItem( contextItems: ContextItemsPeekProps["contextItems"], ) { @@ -118,8 +109,10 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { ); } - const ProviderIcon = - CONTEXT_PROVIDERS_TO_ICONS[contextItem.id.providerTitle]; + const ProviderIcon = getIconFromDropdownItem( + contextItem.id.providerTitle, + "contextProvider", + ); if (ProviderIcon) { return ( diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index cd6622416..6df843ed7 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, @@ -68,6 +68,14 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { "/cmd": CommandLineIcon, }; +export function getIconFromDropdownItem(id: string, type: ComboBoxItemType) { + debugger; + return ( + ICONS_FOR_DROPDOWN[id] ?? + (type === "contextProvider" ? AtSymbolIcon : BoltIcon) + ); +} + function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { if (props.item.type === "action") { return ( @@ -85,9 +93,7 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { } })(); - const IconComponent = - ICONS_FOR_DROPDOWN[provider] ?? - (props.item.type === "contextProvider" ? AtSymbolIcon : BoltIcon); + const IconComponent = getIconFromDropdownItem(provider, props.item.type); const fallbackIcon = ( Date: Fri, 20 Sep 2024 12:16:50 -0700 Subject: [PATCH 17/17] update context peek --- .../providers/RepoMapContextProvider.ts | 6 ++-- core/context/retrieval/repoMapRequest.ts | 28 ++++++++++++++++++- docs/docs/customize/context-providers.md | 4 ++- docs/docs/customize/deep-dives/codebase.md | 4 +++ .../components/mainInput/ContextItemsPeek.tsx | 25 +++++++++-------- gui/src/components/mainInput/MentionList.tsx | 14 +++------- 6 files changed, 55 insertions(+), 26 deletions(-) diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index cb2771638..6aefe0301 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -14,9 +14,9 @@ import { import generateRepoMap from "../../util/generateRepoMap"; const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = { - id: "entire-workspace", - title: "Entire workspace", - description: "Search the entire workspace", + id: "entire-codebase", + title: "Entire codebase", + description: "Search the entire codebase", }; class RepoMapContextProvider extends BaseContextProvider { diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 9a62041f6..618be4808 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -3,6 +3,32 @@ import { getModelByRole } from "../../config/util"; import { stripImages } from "../../llm/images"; 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, config: ContinueConfig, @@ -13,7 +39,7 @@ export async function requestFilesFromRepoMap( 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 []; } 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/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index a8fb6b9f0..3d3200433 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -109,26 +109,29 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { ); } - const ProviderIcon = getIconFromDropdownItem( - contextItem.id.providerTitle, - "contextProvider", - ); + // Heuristic to check if it's a file + const shouldShowFileIcon = contextItem.content.includes("```"); - if (ProviderIcon) { + if (shouldShowFileIcon) { return ( - ); } + const ProviderIcon = getIconFromDropdownItem( + contextItem.id.providerTitle, + "contextProvider", + ); + return ( - diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 6df843ed7..95ddc15ca 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -69,7 +69,6 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { }; export function getIconFromDropdownItem(id: string, type: ComboBoxItemType) { - debugger; return ( ICONS_FOR_DROPDOWN[id] ?? (type === "contextProvider" ? AtSymbolIcon : BoltIcon) @@ -83,15 +82,10 @@ 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 = getIconFromDropdownItem(provider, props.item.type);