Merge pull request #2336 from continuedev/pe/repo-map-enhancements

feat: enhance repo map logic
This commit is contained in:
Patrick Erichsen 2024-09-20 12:22:38 -07:00 • committed by GitHub
commit 9a550efd67
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 498 additions and 481 deletions

2
.vscode/launch.json vendored
View file

@ -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"
],

View file

@ -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<T extends keyof ModelRoles>(
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;
}

View file

@ -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 = {

View file

@ -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 " +

View file

@ -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",
},
];
}

View file

@ -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<ContextSubmenuItem[]> {
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;

View file

@ -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,

View file

@ -0,0 +1,7 @@
import { ContextItem } from "../..";
export const INSTRUCTIONS_BASE_ITEM: ContextItem = {
name: "Instructions",
description: "Instructions",
content: "",
};

View file

@ -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<Chunk[]> {
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,
});

View file

@ -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.",
},

View file

@ -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] = [];
}

View file

@ -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);
}

View file

@ -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<string> = new Set();
private pathsInDirsWithSnippets: Set<string> = 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<string> {
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<void> {
await this.writeToStream(this.PREAMBLE);
this.contentTokens += this.llm.countTokens(this.PREAMBLE);
}
private async getAllPathsInDirs(): Promise<Set<string>> {
const paths = new Set<string>();
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<void> {
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<string, string[]>,
): Promise<void> {
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<string | undefined> {
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<void> {
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<void> {
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<string> {
const generator = new RepoMapGenerator(llm, ide, options);
return generator.generate();
}

View file

@ -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<string>();
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;

View file

@ -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).

View file

@ -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.

View file

@ -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"
}
}
}
}

View file

@ -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"
}
}
}
}

View file

@ -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"
}
}
}
}

View file

@ -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",

View file

@ -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);

View file

@ -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);
}
});

View file

@ -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
);
}
/**

169
gui/package-lock.json generated
View file

@ -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,

View file

@ -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 (
<SafeImg
className="flex-shrink-0 pr-2"
src={contextItem.icon}
height={dimmensions}
width={dimmensions}
fallback={null}
/>
);
}
// Heuristic to check if it's a file
const shouldShowFileIcon = contextItem.content.includes("```");
if (shouldShowFileIcon) {
return (
<FileIcon
filename={
contextItem.description.split(" ").shift()?.split("#").shift() || ""
}
height={dimmensions}
width={dimmensions}
/>
);
}
const ProviderIcon = getIconFromDropdownItem(
contextItem.id.providerTitle,
"contextProvider",
);
return (
<ProviderIcon
className="flex-shrink-0 pr-2"
height={dimmensions}
width={dimmensions}
/>
);
};
return (
<div
style={{
@ -118,6 +172,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
)}
<ContextItems>{contextItemsText}</ContextItems>
</div>
{open && (
<div
style={{
@ -125,71 +180,25 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
}}
>
{ctxItems?.map((contextItem, idx) => {
if (contextItem.description.startsWith("http")) {
return (
<a
key={idx}
href={contextItem.description}
target="_blank"
style={{ color: vscForeground, textDecoration: "none" }}
>
<ContextItemDiv
onClick={() => {
openContextItem(contextItem);
}}
>
{!!contextItem.icon ? (
<SafeImg
className="flex-shrink-0 pr-2"
src={contextItem.icon}
height="18em"
width="18em"
fallback={null}
/>
) : (
<FileIcon
filename={
contextItem.description
.split(" ")
.shift()
?.split("#")
.shift() || ""
}
height="1.6em"
width="1.6em"
></FileIcon>
)}
{contextItem.name}
</ContextItemDiv>
</a>
);
}
return (
<ContextItemDiv
key={idx}
onClick={() => {
openContextItem(contextItem);
}}
>
{!!contextItem.icon ? (
<SafeImg
className="flex-shrink-0 pr-2"
src={contextItem.icon}
height="18em"
width="18em"
fallback={null}
/>
) : (
<FileIcon
filename={contextItem.description.split(" ").shift()!}
height="1.6em"
width="1.6em"
></FileIcon>
)}
const contextItemContent = (
<ContextItemDiv onClick={() => openContextItem(contextItem)}>
{getContextItemIcon(contextItem)}
{contextItem.name}
</ContextItemDiv>
);
return contextItem.description.startsWith("http") ? (
<a
key={idx}
href={contextItem.description}
target="_blank"
style={{ color: vscForeground, textDecoration: "none" }}
>
{contextItemContent}
</a>
) : (
<React.Fragment key={idx}>{contextItemContent}</React.Fragment>
);
})}
</div>
)}

View file

@ -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 = (
<IconComponent
@ -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;