diff --git a/.github/workflows/jetbrains-build.yaml b/.github/workflows/jetbrains-build.yaml index 871571043..ec71c7d4e 100644 --- a/.github/workflows/jetbrains-build.yaml +++ b/.github/workflows/jetbrains-build.yaml @@ -16,7 +16,7 @@ name: Build on: # Trigger the workflow on pushes to only the 'main' branch (this avoids duplicate checks being run e.g., for dependabot pull requests) push: - branches: [main] + branches: [main, preview] # Trigger the workflow on any pull request # pull_request: @@ -97,6 +97,12 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + - name: Cache gui node_modules + uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + # npm install core - name: Install core node_modules run: | @@ -109,6 +115,18 @@ jobs: cd ../../binary npm ci + # npm install gui + - name: Install gui node_modules + run: | + cd ../../gui + npm ci + + # build gui + - name: Build gui + run: | + cd ../../gui + npm run build + # Run prepackage.js script - name: Run prepackage script run: | diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 6c9e23ef9..291d9ebef 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -87,6 +87,12 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + - name: Cache gui node_modules + uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + # npm install core - name: Install core node_modules run: | @@ -99,6 +105,18 @@ jobs: cd ../../binary npm ci + # npm install gui + - name: Install gui node_modules + run: | + cd ../../gui + npm ci + + # build gui + - name: Build gui + run: | + cd ../../gui + npm run build + # Run prepackage.js script - name: Run prepackage script run: | @@ -120,6 +138,12 @@ jobs: run: | ./gradlew patchChangelog --release-note="$CHANGELOG" + # Upload artifact as a release asset + - name: Upload Release Asset + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* + # Publish the plugin to JetBrains Marketplace - name: Publish Plugin env: @@ -129,12 +153,6 @@ jobs: PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} run: ./gradlew publishPlugin - # Upload artifact as a release asset - - name: Upload Release Asset - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* - # Create a pull request - name: Create Pull Request if: ${{ steps.properties.outputs.changelog != '' }} diff --git a/.vscode/launch.json b/.vscode/launch.json index 8e79d0a32..692e94734 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -95,6 +95,22 @@ // Avoid timing out when stopping on breakpoints during debugging in VSCode "MOCHA_TIMEOUT": "0" } + }, + { + "name": "[Core] Jest Test Debugger, Current Open File", + "type": "node", + "request": "launch", + "runtimeArgs": [ + "--inspect-brk", + "${workspaceRoot}/core/node_modules/jest/bin/jest.js", + "--runInBand", + "--config", + "${workspaceRoot}/core/jest.config.js", + "${relativeFile}" + ], + "cwd": "${workspaceRoot}/core", + "console": "integratedTerminal", + "internalConsoleOptions": "neverOpen" } ] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 3850dd66b..49dbba82e 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -12,9 +12,7 @@ // To bundle the code the same way we do for publishing "vscode-extension:esbuild", // Start the React app that is used in the extension - "gui:dev", - // Start the docs site, without opening the browser - "docs:start" + "gui:dev" ], "group": { "kind": "build", diff --git a/binary/package-lock.json b/binary/package-lock.json index 4ed57c259..41875c6b2 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -46,6 +46,8 @@ "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.574.0", "@aws-sdk/credential-providers": "^3.596.0", + "@continuedev/config-types": "^1.0.6", + "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@types/jsdom": "^21.1.6", @@ -61,7 +63,7 @@ "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", - "dotenv": "^16.3.1", + "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", @@ -91,7 +93,8 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", - "yaml": "^2.4.2" + "yaml": "^2.4.2", + "zod": "^3.23.8" }, "devDependencies": { "@babel/preset-env": "^7.24.7", diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 6b37539e4..e01b41e0e 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -188,6 +188,13 @@ export class ConfigHandler { this.selectedProfileId = profileId; const newConfig = await this.loadConfig(); this.notifyConfigListerners(newConfig); + const selectedProfiles = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + selectedProfiles[await this.getWorkspaceId()] = profileId; + this.globalContext.update( + "lastSelectedProfileForWorkspace", + selectedProfiles, + ); } // A unique ID for the current workspace, built from folder names diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index c1062e421..5b727c34f 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -10,11 +10,6 @@ export function setupApiKeysMode( return { ...config, models: config.models.filter((model) => model.provider !== "free-trial"), - tabAutocompleteModel: { - title: "Tab Autocomplete", - provider: "free-trial", - model: TRIAL_FIM_MODEL, - }, embeddingsProvider: { provider: "free-trial", }, diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 822ea826c..ec6fba189 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -6,7 +6,7 @@ import { IProfileLoader } from "./IProfileLoader"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; profileId = LocalProfileLoader.ID; - profileTitle = "config.json"; + profileTitle = "Local Config"; constructor( private ide: IDE, diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index b9e98c171..83329a930 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -5,6 +5,7 @@ import { ContextProviderExtras, ContextSubmenuItem, LoadSubmenuItemsArgs, + SiteIndexingConfig, } from "../../index.js"; import { DocsService } from "../../indexing/docs/DocsService.js"; import configs from "../../indexing/docs/preIndexedDocs.js"; @@ -108,40 +109,44 @@ class DocsContextProvider extends BaseContextProvider { ]; } - async loadSubmenuItems( - args: LoadSubmenuItemsArgs, - ): Promise { - const docs = await this.docsService.list(); - const submenuItems: ContextSubmenuItem[] = docs.map((doc) => ({ + // Get combined site configs from preIndexedDocs and options.sites. + private _getDocsSitesConfig(): SiteIndexingConfig[] { + return [...configs, ...(this.options?.sites || [])]; + } + + // Get indexed docs as ContextSubmenuItems from database. + private async _getIndexedDocsContextSubmenuItems(): Promise { + return (await this.docsService.list()).map((doc) => ({ title: doc.title, description: new URL(doc.baseUrl).hostname, id: doc.baseUrl, - metadata: { - preIndexed: !!configs.find((config) => config.title === doc.title), - }, })); + } - submenuItems.push( - ...configs - // After it's actually downloaded, we don't want to show twice - .filter( - (config) => !submenuItems.some((item) => item.id === config.startUrl), - ) - .map((config) => ({ - title: config.title, - description: new URL(config.startUrl).hostname, - id: config.startUrl, - metadata: { - preIndexed: true, - }, - // iconUrl: config.faviconUrl, - })), - ); + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const submenuItemsMap = new Map(); + + for (const item of await this._getIndexedDocsContextSubmenuItems()) { + submenuItemsMap.set(item.id, item); + } + + for (const config of this._getDocsSitesConfig()) { + submenuItemsMap.set(config.startUrl, { + id: config.startUrl, + title: config.title, + description: new URL(config.startUrl).hostname, + metadata: { preIndexed: !!configs.find((cnf) => cnf.title === config.title), }, + }); + } + + const submenuItems = Array.from(submenuItemsMap.values()); // Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized submenuItems.sort((a, b) => { - const aTitleInConfigs = a.metadata?.preIndexed; - const bTitleInConfigs = b.metadata?.preIndexed; + const aTitleInConfigs = a.metadata?.preIndexed ?? false; + const bTitleInConfigs = b.metadata?.preIndexed ?? false; // Primary criterion: Items not in configs come first if (!aTitleInConfigs && bTitleInConfigs) { diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 1138078d2..3d7f08383 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -5,7 +5,6 @@ import { } from "../../index.js"; import { getRelativePath } from "../../util/index.js"; -import { RETRIEVAL_PARAMS } from "../../util/parameters.js"; import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js"; import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js"; import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline.js"; @@ -29,12 +28,14 @@ export async function retrieveContextItemsFromEmbeddings( ); } - const nFinal = options?.nFinal || RETRIEVAL_PARAMS.nFinal; + // Fill half of the context length, up to a max of 100 snippets + const contextLength = extras.llm.contextLength; + const tokensPerSnippet = 512; + const nFinal = + options?.nFinal ?? Math.min(50, contextLength / tokensPerSnippet / 2); const useReranking = extras.reranker !== undefined; const nRetrieve = - useReranking === false - ? nFinal - : options?.nRetrieve || RETRIEVAL_PARAMS.nRetrieve; + useReranking === false ? nFinal : options?.nRetrieve || 2 * nFinal; // Get tags to retrieve for const workspaceDirs = await extras.ide.getWorkspaceDirs(); diff --git a/core/core.ts b/core/core.ts index abb47f3e5..25e44a849 100644 --- a/core/core.ts +++ b/core/core.ts @@ -242,6 +242,19 @@ export class Core { await this.docsService.delete(baseUrl); this.messenger.send("refreshSubmenuItems", undefined); }); + on("context/indexDocs", async (msg) => { + const config = await this.config(); + const provider: any = config.contextProviders?.find( + (provider) => provider.description.title === "docs", + ); + + const siteIndexingOptions: SiteIndexingConfig[] = provider ? + (mProvider => mProvider?.options?.sites || [])({ ...provider }) : + []; + + await this.indexDocs(siteIndexingOptions, msg.data.reIndex); + this.ide.infoPopup("Docs indexing completed"); + }); on("context/loadSubmenuItems", async (msg) => { const config = await this.config(); const items = config.contextProviders @@ -623,4 +636,16 @@ export class Core { this.indexingState = update; } } + + private async indexDocs(sites: SiteIndexingConfig[], reIndex: boolean): Promise { + for (const site of sites) { + for await (const update of this.docsService.indexAndAdd(site, new TransformersJsEmbeddingsProvider(), reIndex)) { + // Temporary disabled posting progress updates to the UI due to + // possible collision with code indexing progress updates. + + // this.messenger.request("indexProgress", update); + // this.indexingState = update; + } + } + } } diff --git a/core/diff/streamDiff.ts b/core/diff/streamDiff.ts index 3bac09aec..62173eb93 100644 --- a/core/diff/streamDiff.ts +++ b/core/diff/streamDiff.ts @@ -13,46 +13,69 @@ export async function* streamDiff( oldLines: string[], newLines: LineStream, ): AsyncGenerator { - const mutatedOldLines = [...oldLines]; // be careful - // If one indentation mistake is made, others are likely. So we are more permissive about matching let seenIndentationMistake = false; let newLineResult = await newLines.next(); + while (oldLines.length > 0 && !newLineResult.done) { - const [matchIndex, isPerfectMatch, newLine] = matchLine( + const { matchIndex, isPerfectMatch, newLine } = matchLine( newLineResult.value, oldLines, seenIndentationMistake, ); + if (!seenIndentationMistake && newLineResult.value !== newLine) { seenIndentationMistake = true; } - if (matchIndex < 0) { - // Insert new line - yield { type: "new", line: newLine }; + let type: DiffLine["type"]; + + let isLineRemoval = false; + const isNewLine = matchIndex === -1; + + if (isNewLine) { + type = "new"; } else { // Insert all deleted lines before match for (let i = 0; i < matchIndex; i++) { yield { type: "old", line: oldLines.shift()! }; } - if (isPerfectMatch) { - // Same - yield { type: "same", line: oldLines.shift()! }; - } else { - // Delete old line and insert the new - yield { type: "old", line: oldLines.shift()! }; - yield { type: "new", line: newLine }; - } + type = isPerfectMatch ? "same" : "old"; } - newLineResult = await newLines.next(); + switch (type) { + case "new": + yield { type, line: newLine }; + break; + + case "same": + yield { type, line: oldLines.shift()! }; + break; + + case "old": + yield { type, line: oldLines.shift()! }; + + if (oldLines[0] !== newLine) { + yield { type: "new", line: newLine }; + } else { + isLineRemoval = true; + } + + break; + + default: + console.error(`Error streaming diff, unrecognized diff type: ${type}`); + } + + if (!isLineRemoval) { + newLineResult = await newLines.next(); + } } // Once at the edge, only one choice - if (newLineResult.done === true && oldLines.length > 0) { + if (newLineResult.done && oldLines.length > 0) { for (const oldLine of oldLines) { yield { type: "old", line: oldLine }; } diff --git a/core/diff/util.ts b/core/diff/util.ts index aff11a3c5..8583838d4 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -4,6 +4,16 @@ import { stripImages } from "../llm/countTokens.js"; export type LineStream = AsyncGenerator; +export type MatchLineResult = { + /** + * -1 if it's a new line, otherwise the index of the first match + * in the old lines. + */ + matchIndex: number; + isPerfectMatch: boolean; + newLine: string; +}; + function linesMatchPerfectly(lineA: string, lineB: string): boolean { return lineA === lineB && lineA !== ""; } @@ -18,6 +28,7 @@ function linesMatch(lineA: string, lineB: string, linesBetween = 0): boolean { } const d = distance(lineA, lineB); + return ( // Should be more unlikely for lines to fuzzy match if they are further away (d / Math.max(lineA.length, lineB.length) < 0.5 - linesBetween * 0.05 || @@ -34,21 +45,26 @@ export function matchLine( newLine: string, oldLines: string[], permissiveAboutIndentation = false, -): [number, boolean, string] { +): MatchLineResult { // Only match empty lines if it's the next one: if (newLine.trim() === "" && oldLines[0]?.trim() === "") { - return [0, true, newLine.trim()]; + return { + matchIndex: 0, + isPerfectMatch: true, + newLine: newLine.trim(), + }; } const isEndBracket = END_BRACKETS.includes(newLine.trim()); + for (let i = 0; i < oldLines.length; i++) { // Don't match end bracket lines if too far away if (i > 4 && isEndBracket) { - return [-1, false, newLine]; + return { matchIndex: -1, isPerfectMatch: false, newLine }; } if (linesMatchPerfectly(newLine, oldLines[i])) { - return [i, true, newLine]; + return { matchIndex: i, isPerfectMatch: true, newLine }; } if (linesMatch(newLine, oldLines[i], i)) { // This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines @@ -56,13 +72,17 @@ export function matchLine( newLine.trimStart() === oldLines[i].trimStart() && (permissiveAboutIndentation || newLine.trim().length > 8) ) { - return [i, true, oldLines[i]]; + return { + matchIndex: i, + isPerfectMatch: true, + newLine: oldLines[i], + }; } - return [i, false, newLine]; + return { matchIndex: i, isPerfectMatch: false, newLine }; } } - return [-1, false, newLine]; + return { matchIndex: -1, isPerfectMatch: false, newLine }; } /** diff --git a/core/index.d.ts b/core/index.d.ts index 816453c45..f56ba46ac 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -743,6 +743,7 @@ export interface EmbedOptions { apiType?: string; apiVersion?: string; requestOptions?: RequestOptions; + maxChunkSize?: number; } export interface EmbeddingsProviderDescription extends EmbedOptions { @@ -751,6 +752,7 @@ export interface EmbeddingsProviderDescription extends EmbedOptions { export interface EmbeddingsProvider { id: string; + maxChunkSize: number; embed(chunks: string[]): Promise; } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index a9145aa5b..5a5b73bd5 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -36,6 +36,7 @@ export class CodebaseIndexer { new ChunkCodebaseIndex( this.ide.readFile.bind(this.ide), this.continueServerClient, + config.embeddingsProvider.maxChunkSize, ), // Chunking must come first new LanceDbIndex( config.embeddingsProvider, diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index aa91f9fe5..db1af2780 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -9,7 +9,6 @@ import { IndexTag, IndexingProgressUpdate, } from "../index.js"; -import { MAX_CHUNK_SIZE } from "../llm/constants.js"; import { getBasename } from "../util/index.js"; import { getLanceDbPath, migrate } from "../util/paths.js"; import { chunkDocument } from "./chunk/chunk.js"; @@ -36,8 +35,6 @@ export class LanceDbIndex implements CodebaseIndex { return `vectordb::${this.embeddingsProvider.id}`; } - static MAX_CHUNK_SIZE = MAX_CHUNK_SIZE; - constructor( private readonly embeddingsProvider: EmbeddingsProvider, private readonly readFile: (filepath: string) => Promise, @@ -64,10 +61,13 @@ export class LanceDbIndex implements CodebaseIndex { migrate( "lancedb_sqlite_artifact_id_column", async () => { - await db.exec( - "ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'", - ); - resolve(undefined); + try { + await db.exec( + "ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'", + ); + } finally { + resolve(undefined); + } }, () => resolve(undefined), ), @@ -99,7 +99,7 @@ export class LanceDbIndex implements CodebaseIndex { for await (const chunk of chunkDocument( items[i].path, content, - LanceDbIndex.MAX_CHUNK_SIZE, + this.embeddingsProvider.maxChunkSize, items[i].cacheKey, )) { if (chunk.content.length == 0) { diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index d1eb2a20c..5dd08c895 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -1,6 +1,5 @@ import { IContinueServerClient } from "../../continueServer/interface.js"; import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; -import { MAX_CHUNK_SIZE } from "../../llm/constants.js"; import { getBasename } from "../../util/index.js"; import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js"; import { @@ -19,6 +18,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { constructor( private readonly readFile: (filepath: string) => Promise, private readonly continueServerClient: IContinueServerClient, + private readonly maxChunkSize: number ) { this.readFile = readFile; } @@ -108,7 +108,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { for await (const chunk of chunkDocument( item.path, contents[i], - MAX_CHUNK_SIZE, + this.maxChunkSize, item.cacheKey, )) { handleChunk(chunk); diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 04e4f7048..6ecacf5ce 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -1,5 +1,4 @@ import { Chunk, ChunkWithoutID } from "../../index.js"; -import { MAX_CHUNK_SIZE } from "../../llm/constants.js"; import { countTokens } from "../../llm/countTokens.js"; import { supportedLanguages } from "../../util/treeSitter.js"; import { basicChunker } from "./basic.js"; @@ -43,7 +42,7 @@ export async function* chunkDocument( contents, maxChunkSize, )) { - if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) { + if (countTokens(chunkWithoutId.content) > maxChunkSize) { console.warn( `Chunk with more than ${maxChunkSize} tokens constructed: `, filepath, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index a76de2cf1..9cd8feb5f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -30,6 +30,7 @@ export class DocsService { private static instance: DocsService; private static DOCS_TABLE_NAME = "docs"; private _sqliteTable: Database | undefined; + private docsIndexingQueue: Set = new Set(); public static getInstance(): DocsService { if (!DocsService.instance) { @@ -204,10 +205,16 @@ export class DocsService { async *indexAndAdd( siteIndexingConfig: SiteIndexingConfig, embeddingsProvider: EmbeddingsProvider, + reIndex: boolean = false, ): AsyncGenerator { - const startUrl = new URL(siteIndexingConfig.startUrl); + const startUrl = new URL(siteIndexingConfig.startUrl.toString()); - if (await this.has(siteIndexingConfig.startUrl.toString())) { + if (this.docsIndexingQueue.has(startUrl.toString())) { + console.log("Already in queue"); + return; + } + + if (!reIndex && await this.has(startUrl.toString())) { yield { progress: 1, desc: "Already indexed", @@ -216,6 +223,9 @@ export class DocsService { return; } + // Mark the site as currently being indexed + this.docsIndexingQueue.add(startUrl.toString()); + yield { progress: 0, desc: "Finding subpages", @@ -223,20 +233,31 @@ export class DocsService { }; const articles: Article[] = []; + let processedPages = 0; + let maxKnownPages = 1; // Crawl pages and retrieve info as articles for await (const page of crawlPage(startUrl, siteIndexingConfig.maxDepth)) { + processedPages++; const article = pageToArticle(page); if (!article) { continue; } articles.push(article); + // Use a heuristic approach for progress calculation + const progress = Math.min(processedPages / maxKnownPages, 1); + yield { - progress: 0, + progress, // Yield the heuristic progress desc: `Finding subpages (${page.path})`, status: "indexing", }; + + // Increase maxKnownPages to delay progress reaching 100% too soon + if (processedPages === maxKnownPages) { + maxKnownPages *= 2; + } } const chunks: Chunk[] = []; @@ -244,16 +265,17 @@ export class DocsService { // Create embeddings of retrieved articles console.log("Creating Embeddings for ", articles.length, " articles"); - for (const article of articles) { + for (let i = 0; i < articles.length; i++) { + const article = articles[i]; yield { - progress: Math.max(1, Math.floor(100 / (articles.length + 1))), - desc: `${article.subpath}`, + progress: i / articles.length, + desc: `Creating Embeddings: ${article.subpath}`, status: "indexing", }; try { const subpathEmbeddings = await embeddingsProvider.embed( - chunkArticle(article).map((chunk) => { + chunkArticle(article, embeddingsProvider.maxChunkSize).map((chunk) => { chunks.push(chunk); return chunk.content; @@ -268,7 +290,14 @@ export class DocsService { // Add docs to databases console.log("Adding ", embeddings.length, " embeddings to db"); + yield { + progress: 0.5, + desc: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + }; + await this.add(siteIndexingConfig.title, startUrl, chunks, embeddings); + this.docsIndexingQueue.delete(startUrl.toString()); yield { progress: 1, diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 4bf903142..d1f6a94a7 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -1,7 +1,6 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; import { Chunk } from "../../index.js"; -import { MAX_CHUNK_SIZE } from "../../llm/constants.js"; import { cleanFragment, cleanHeader } from "../chunk/markdown.js"; import { PageData } from "./crawl.js"; @@ -21,6 +20,7 @@ function breakdownArticleComponent( url: string, article: ArticleComponent, subpath: string, + max_chunk_size: number, ): Chunk[] { const chunks: Chunk[] = []; @@ -32,7 +32,7 @@ function breakdownArticleComponent( for (let i = 0; i < lines.length; i++) { const line = lines[i]; - if (content.length + line.length <= MAX_CHUNK_SIZE) { + if (content.length + line.length <= max_chunk_size) { content += `${line}\n`; endLine = i; } else { @@ -79,7 +79,10 @@ function breakdownArticleComponent( return chunks.filter((c) => c.content.trim().length > 20); } -export function chunkArticle(articleResult: Article): Chunk[] { +export function chunkArticle( + articleResult: Article, + maxChunkSize: number, +): Chunk[] { let chunks: Chunk[] = []; for (const article of articleResult.article_components) { @@ -87,6 +90,7 @@ export function chunkArticle(articleResult: Article): Chunk[] { articleResult.url, article, articleResult.subpath, + maxChunkSize, ); chunks = [...chunks, ...articleChunks]; } diff --git a/core/indexing/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts index cd67a001a..3a26f311d 100644 --- a/core/indexing/embeddings/BaseEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BaseEmbeddingsProvider.ts @@ -4,6 +4,8 @@ import { FetchFunction, } from "../../index.js"; +import { MAX_CHUNK_SIZE } from "../../llm/constants.js"; + export interface IBaseEmbeddingsProvider extends EmbeddingsProvider { options: EmbedOptions; fetch: FetchFunction; @@ -29,11 +31,20 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider { ...options, }; this.fetch = fetch; - this.id = `${this.constructor.name}::${this.options.model}`; + // Include the `max_chunk_size` if it is not the default, since we need to create other indices for different chunk_sizes + if (this.maxChunkSize !== MAX_CHUNK_SIZE) { + this.id = `${this.constructor.name}::${this.options.model}::${this.maxChunkSize}`; + } else { + this.id = `${this.constructor.name}::${this.options.model}`; + } } abstract embed(chunks: string[]): Promise; + get maxChunkSize(): number { + return this.options.maxChunkSize ?? MAX_CHUNK_SIZE; + } + static getBatchedChunks(chunks: string[]): string[][] { if (!this.maxBatchSize) { console.warn( diff --git a/core/llm/index.ts b/core/llm/index.ts index cddf6c7f6..4da78f690 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,3 +1,4 @@ +import { findLlmInfo } from "@continuedev/llm-info"; import Handlebars from "handlebars"; import { ChatMessage, @@ -114,14 +115,17 @@ export abstract class BaseLLM implements ILLM { ..._options, }; + this.model = options.model; + const llmInfo = findLlmInfo(this.model); + const templateType = options.template ?? autodetectTemplateType(options.model); this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; - this.model = options.model; this.systemMessage = options.systemMessage; - this.contextLength = options.contextLength ?? DEFAULT_CONTEXT_LENGTH; + this.contextLength = + options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; this.completionOptions = { ...options.completionOptions, model: options.model || "gpt-4", diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index fee8fadac..95208bb8c 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -14,8 +14,11 @@ class Mistral extends OpenAI { constructor(options: LLMOptions) { super(options); - if (options.model.includes("codestral")) { - this.apiBase = "https://codestral.mistral.ai/v1/"; + if ( + options.model.includes("codestral") && + !options.model.includes("mamba") + ) { + this.apiBase = options.apiBase ?? "https://codestral.mistral.ai/v1/"; } } @@ -31,7 +34,7 @@ class Mistral extends OpenAI { const finalOptions = super._convertArgs(options, messages); const lastMessage = finalOptions.messages[finalOptions.messages.length - 1]; - if (lastMessage.role === "assistant") { + if (lastMessage?.role === "assistant") { (lastMessage as any).prefix = true; } diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index f6bf1e848..fd288a48e 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -95,7 +95,7 @@ ${otherData.codeToEdit} ${suffixTag} \`\`\` -Please rewrite the entire code block above in order to satisfy the following request: "${otherData.userInput}".${suffixExplanation}`, +Please rewrite the entire code block above in order to satisfy the following request: "${otherData.userInput}". You should rewrite the entire code block without leaving placeholders, even if the code is the same as before.${suffixExplanation}`, }, { role: "assistant", @@ -115,7 +115,7 @@ ${otherData.codeToEdit} ${suffixTag} \`\`\` -Please rewrite the entire code block above, editing the portion below "${START_TAG}" in order to satisfy the following request: "${otherData.userInput}".${suffixExplanation} +Please rewrite the entire code block above, editing the portion below "${START_TAG}" in order to satisfy the following request: "${otherData.userInput}". You should rewrite the entire code block without leaving placeholders, even if the code is the same as before.${suffixExplanation} `, }, { diff --git a/core/package-lock.json b/core/package-lock.json index 9be2bdb6d..cc2167bf1 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -12,6 +12,7 @@ "@aws-sdk/client-bedrock-runtime": "^3.574.0", "@aws-sdk/credential-providers": "^3.596.0", "@continuedev/config-types": "^1.0.6", + "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@types/jsdom": "^21.1.6", @@ -3937,6 +3938,11 @@ "zod": "^3.23.8" } }, + "node_modules/@continuedev/llm-info": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.1.tgz", + "integrity": "sha512-fmRXuOSwJ9ogBPSDduoedHF3WVg1rge3o8SRRg1hkUagRnxwZqtQj1sS5SjQyAqjQv6VPMGPDEtD77Za/hc4Jg==" + }, "node_modules/@esbuild/android-arm": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", diff --git a/core/package.json b/core/package.json index e057ba169..cfd12929f 100644 --- a/core/package.json +++ b/core/package.json @@ -32,6 +32,7 @@ "@aws-sdk/client-bedrock-runtime": "^3.574.0", "@aws-sdk/credential-providers": "^3.596.0", "@continuedev/config-types": "^1.0.6", + "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@types/jsdom": "^21.1.6", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index ab15fa6c3..3ccc7ed16 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -69,6 +69,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; "context/removeDocs": [{ baseUrl: string }, void]; + "context/indexDocs": [{ reIndex: boolean }, void]; "autocomplete/cancel": [undefined, void]; "autocomplete/accept": [{ completionId: string }, void]; "command/run": [ diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index a228194e3..5fe14573a 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -25,6 +25,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "context/loadSubmenuItems", "context/addDocs", "context/removeDocs", + "context/indexDocs", "autocomplete/complete", "autocomplete/cancel", "autocomplete/accept", diff --git a/core/test/diff.test.ts b/core/test/diff.test.ts deleted file mode 100644 index 8bbd2cd25..000000000 --- a/core/test/diff.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { streamDiff } from "../diff/streamDiff.js"; - -const oldCode = [ - `A -B`, - `A -B -C`, - `A -B -C -A -B -B -A`, - `function mergeSortAlgorithm() { - // TODO: implement -}`, - `function mergeSortAlgorithm() { - // TODO: implement -}`, -]; - -const newCode = [ - `C -D`, - `D -E -C -F -C`, - `C -B -A -B -A -C`, - `function mergeSortAlgorithm(arr: number[]): number[] { - if (arr.length <= 1) { - return arr; - } - - const middle = Math.floor(arr.length / 2); - const left = arr.slice(0, middle); - const right = arr.slice(middle); - - return merge(mergeSortAlgorithm(left), mergeSortAlgorithm(right)); -} - -function merge(left: number[], right: number[]): number[] { - let resultArray = [], leftIndex = 0, rightIndex = 0; - - while (leftIndex < left.length && rightIndex < right.length) { - if (left[leftIndex] < right[rightIndex]) { - resultArray.push(left[leftIndex]); - leftIndex++; - } else { - resultArray.push(right[rightIndex]); - rightIndex++; - } - } - - return resultArray - .concat(left.slice(leftIndex)) - .concat(right.slice(rightIndex)); -}`, - `function mergeSortAlgorithm(array) { - if (array.length <= 1) { - return array; - } - - const mid = Math.floor(array.length / 2); - const left = array.slice(0, mid); - const right = array.slice(mid); - - return merge(mergeSortAlgorithm(left), mergeSortAlgorithm(right)); -} - -function merge(left, right) { - let resultArray = [], leftIndex = 0, rightIndex = 0; - - while (leftIndex < left.length && rightIndex < right.length) { - if (left[leftIndex] < right[rightIndex]) { - resultArray.push(left[leftIndex]); - leftIndex++; - } else { - resultArray.push(right[rightIndex]); - rightIndex++; - } - } - - return resultArray - .concat(left.slice(leftIndex)) - .concat(right.slice(rightIndex)); -} -`, -]; - -async function* generateLines(lines: string[]): AsyncGenerator { - for (const line of lines) { - yield line; - } -} - -describe.skip("streamDiff", () => { - for (let i = 0; i < oldCode.length; i++) { - test(`outputs valid diff #${i}`, async () => { - const oldLines = oldCode[i].split("\n"); - const newLines = newCode[i].split("\n"); - - const diff = []; - for await (const diffLine of streamDiff( - oldLines, - generateLines(newLines), - )) { - diff.push(diffLine); - } - - console.log( - diff - .map((dl) => { - return ( - (dl.type === "old" ? "- " : dl.type === "new" ? "+ " : " ") + - dl.line - ); - }) - .join("\n"), - ); - - const numSame = diff.filter((dl) => dl.type === "same").length; - const numOld = diff.filter((dl) => dl.type === "old").length; - const numNew = diff.filter((dl) => dl.type === "new").length; - - // Check that every line is represented - expect(oldLines.length).toEqual(numOld + numSame); - expect(newLines.length).toEqual(numNew + numSame); - - // Check that there are no red lines immediately following green (they should always be above) - for (let i = 1; i < diff.length; i++) { - if (diff[i].type === "old" && diff[i - 1].type === "new") { - throw new Error( - `Found red '${diff[i].line}' immediately after green line '${ - diff[i - 1].line - }`, - ); - } - } - }); - } -}); diff --git a/core/test/streamDiff.test.ts b/core/test/streamDiff.test.ts new file mode 100644 index 000000000..b539ec5ee --- /dev/null +++ b/core/test/streamDiff.test.ts @@ -0,0 +1,164 @@ +import { streamDiff } from "../diff/streamDiff.js"; +import { DiffLine } from "../index.js"; + +async function* generateLines(lines: string[]): AsyncGenerator { + for (const line of lines) { + yield line; + } +} + +const collectDiff = async ( + oldLines: string[], + newLines: string[], +): Promise => { + const result: DiffLine[] = []; + + for await (const diffLine of streamDiff(oldLines, generateLines(newLines))) { + result.push(diffLine); + } + + return result; +}; + +// We use a longer `console.log()` string here to not get +// caught by the fuzzy matcher +describe("streamDiff()", () => { + test("no changes", async () => { + const oldLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + ]; + const newLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + ]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "same", line: "console.log(first)" }, + { type: "same", line: "console.log(second)" }, + { type: "same", line: "console.log(third)" }, + ]); + }); + + test("add new line", async () => { + const oldLines = ["console.log(first)", "console.log(second)"]; + const newLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + ]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "same", line: "console.log(first)" }, + { type: "same", line: "console.log(second)" }, + { type: "new", line: "console.log(third)" }, + ]); + }); + + test("remove line", async () => { + const oldLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + ]; + const newLines = ["console.log(first)", "console.log(third)"]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "same", line: "console.log(first)" }, + { type: "old", line: "console.log(second)" }, + { type: "same", line: "console.log(third)" }, + ]); + }); + + test("modify line", async () => { + const oldLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + ]; + const newLines = [ + "console.log(first)", + "console.log(modified second)", + "console.log(third)", + ]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "same", line: "console.log(first)" }, + { type: "old", line: "console.log(second)" }, + { type: "new", line: "console.log(modified second)" }, + { type: "same", line: "console.log(third)" }, + ]); + }); + + test("add multiple lines", async () => { + const oldLines = ["console.log(first)", "fourth"]; + const newLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + "fourth", + ]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "same", line: "console.log(first)" }, + { type: "new", line: "console.log(second)" }, + { type: "new", line: "console.log(third)" }, + { type: "same", line: "fourth" }, + ]); + }); + + test("remove multiple lines", async () => { + const oldLines = [ + "console.log(first)", + "console.log(second)", + "console.log(third)", + "fourth", + ]; + const newLines = ["console.log(first)", "fourth"]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "same", line: "console.log(first)" }, + { type: "old", line: "console.log(second)" }, + { type: "old", line: "console.log(third)" }, + { type: "same", line: "fourth" }, + ]); + }); + + test("empty old lines", async () => { + const oldLines: string[] = []; + const newLines = ["console.log(first)", "console.log(second)"]; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "new", line: "console.log(first)" }, + { type: "new", line: "console.log(second)" }, + ]); + }); + + test("empty new lines", async () => { + const oldLines = ["console.log(first)", "console.log(second)"]; + const newLines: string[] = []; + + const diff = await collectDiff(oldLines, newLines); + + expect(diff).toEqual([ + { type: "old", line: "console.log(first)" }, + { type: "old", line: "console.log(second)" }, + ]); + }); +}); diff --git a/core/util/paths.ts b/core/util/paths.ts index 2764fa8be..1e8a5d772 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -139,6 +139,24 @@ export function getTsConfigPath(): string { return tsConfigPath; } +export function getContinueRcPath(): string { + // Disable indexing of the config folder to prevent infinite loops + const continuercPath = path.join(getContinueGlobalPath(), ".continuerc.json"); + if (!fs.existsSync(continuercPath)) { + fs.writeFileSync( + continuercPath, + JSON.stringify( + { + disableIndexing: true, + }, + null, + 2, + ), + ); + } + return continuercPath; +} + export function devDataPath(): string { const sPath = path.join(getContinueGlobalPath(), "dev_data"); if (!fs.existsSync(sPath)) { @@ -177,19 +195,20 @@ function getMigrationsFolderPath(): string { return migrationsPath; } -export function migrate( +export async function migrate( id: string, - callback: () => void, + callback: () => void | Promise, onAlreadyComplete?: () => void, ) { const migrationsPath = getMigrationsFolderPath(); const migrationPath = path.join(migrationsPath, id); + if (!fs.existsSync(migrationPath)) { try { - callback(); + await callback(); fs.writeFileSync(migrationPath, ""); } catch (e) { - console.error(`Migration ${id} failed`, e); + console.warn(`Migration ${id} failed`, e); } } else if (onAlreadyComplete) { onAlreadyComplete(); diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index c9f3f144e..82d6aa133 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -16,6 +16,14 @@ As an example, say you are working on solving a new GitHub Issue. You type '@iss To use any of the built-in context providers, open `~/.continue/config.json` and add it to the `contextProviders` list. +### Files + +Type '@file' to reference any file in your current workspace. + +```json +{ "name": "file" } +``` + ### Code Type '@code' to reference specific functions or classes from throughout your project. @@ -50,6 +58,28 @@ Type `@docs` to index and retrieve snippets from any documentation site. You can Continue also pre-indexes a number of common sites, listed [here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). The embeddings for these sites are hosted by us, but downloaded for local use after the first time. All other indexing occurs entirely locally. +#### Adding a Documentation Site via Configuration + +To add a documentation site via configuration, update the `config.json` file as follows: + +```json +{ + "name": "docs", + "params": { + "sites": [ + { + "title": "ExampleDocs", + "startUrl": "https://exampledocs.com/docs", + "rootUrl": "https://exampledocs.com", + "maxDepth": 3 // Default + } + ] + } +} +``` + +The docs are indexed when you modify the configuration file, unless indexing is disabled. If you want to manually trigger the indexing, you can use the command `Continue: Docs Index`. For force indexing, you can use the command `Continue: Docs Force Re-Index`. Note that these commands will work even if automatic indexing is disabled. + ### Open Files Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. @@ -498,9 +528,7 @@ Continue exposes an API for registering context providers from a 3rd party VSCod ```json { - "extensionDependencies": [ - "continue.continue" - ], + "extensionDependencies": ["continue.continue"] } ``` @@ -513,7 +541,6 @@ Here is an example: import * as vscode from "vscode"; class MyCustomProvider implements IContextProvider { - get description(): ContextProviderDescription { return { title: "custom", @@ -525,7 +552,7 @@ class MyCustomProvider implements IContextProvider { async getContextItems( query: string, - extras: ContextProviderExtras + extras: ContextProviderExtras, ): Promise { return [ { @@ -537,7 +564,7 @@ class MyCustomProvider implements IContextProvider { } async loadSubmenuItems( - args: LoadSubmenuItemsArgs + args: LoadSubmenuItemsArgs, ): Promise { return []; } @@ -554,5 +581,4 @@ const continueApi = continueExt?.exports; // register your custom provider continueApi?.registerCustomContextProvider(customProvider); - -``` \ No newline at end of file +``` diff --git a/docs/docs/reference/Model Providers/mistral.md b/docs/docs/reference/Model Providers/mistral.md index 3c3633438..448b8292a 100644 --- a/docs/docs/reference/Model Providers/mistral.md +++ b/docs/docs/reference/Model Providers/mistral.md @@ -7,8 +7,8 @@ The [Mistral](https://mistral.ai) API provides hosted access to their models, in "models": [ { "provider": "mistral", - "title": "Mistral Small", - "model": "mistral-small", + "title": "Codestral", + "model": "codestral-latest", "apiKey": "" } ] diff --git a/docs/docs/setup/configuration.md b/docs/docs/setup/configuration.md index 11cb29318..29c1110fd 100644 --- a/docs/docs/setup/configuration.md +++ b/docs/docs/setup/configuration.md @@ -267,7 +267,7 @@ function modifyConfig(config: Config): Config { } ``` -This exact function and a few other default implementations are available in [`continuedev.libs.llm.prompts.chat`](https://github.com/continuedev/continue/blob/main/server/continuedev/libs/llm/prompts/chat.py). +This exact function and a few other default implementations are available in [`core/llm/templates/chat.ts`](https://github.com/continuedev/continue/blob/main/core/llm/templates/chat.ts). ## Customizing the /edit Prompt diff --git a/docs/docs/walkthroughs/quick-actions.md b/docs/docs/walkthroughs/quick-actions.md index c08cfc746..7c6ce8887 100644 --- a/docs/docs/walkthroughs/quick-actions.md +++ b/docs/docs/walkthroughs/quick-actions.md @@ -1,13 +1,13 @@ --- title: Quick Actions (experimental, VS Code only) -description: Quick Actions automate repetitive tasks and streamline your development workflow +description: Quick Actions streamline your development workflow by allowing quick edits on selected classes or functions keywords: [experimental, automate, configuration] toc_max_heading_level: 5 --- -# Quick Actions (experimental, VS Code only) +## Quick Actions (experimental, VS Code only) -Quick Actions automate repetitive tasks and streamline your development workflow. Configure custom actions to execute complex operations with a single click. +Quick Actions streamline your development workflow by providing a tool to quickly select an entire class or function to perform a quick edit on. Configure custom actions to execute complex operations with a single click. ![Quick actions example](/img/quick-actions-demo.gif) @@ -19,10 +19,9 @@ For the language of the file you have open, you must have the Language Server Pr Quick Actions use a CodeLens provider to add interactive elements above functions and classes in your code. -By default, Quick Actions include two predefined actions: +By default, Quick Actions include a single predefined action: -1. `Explain`: This action provides a short explanation of the selected code. -2. `Docstring`: This action generates a docstring comment and inserts it above the code. +- `Continue`: This action allows you to perform a quick edit on the selected class or function. ## How to disable Quick Actions diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 6d16f6b91..a93e891ae 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -899,6 +899,7 @@ "model": { "enum": [ "codestral-latest", + "codestral-mamba-latest", "open-mistral-7b", "open-mixtral-8x7b", "open-mixtral-8x22b", @@ -1906,6 +1907,13 @@ "title": "Request Options", "description": "Request options to be used in any fetch requests made by the embeddings provider", "$ref": "#/definitions/RequestOptions" + }, + "maxChunkSize": { + "title": "Maximum Chunk Size", + "description": "The maximum number of tokens that each chunk of a document is allowed to have", + "type": "integer", + "minimum": 128, + "exclusiveMaximum": 2147483647 } }, "required": ["provider"], diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index f9e9a3446..755cf55ff 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.53 +pluginVersion = 0.0.54 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt new file mode 100644 index 000000000..bae9a8fe0 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt @@ -0,0 +1,29 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.DefaultActionGroup +import com.intellij.openapi.components.service + +class AutocompleteActionGroup : DefaultActionGroup() { + override fun getActionUpdateThread(): ActionUpdateThread { + return ActionUpdateThread.EDT + } + + override fun update(e: AnActionEvent) { + super.update(e) + removeAll() + + val continueSettingsService = service() + if (continueSettingsService.continueState.enableTabAutocomplete) { + addAll( + DisableTabAutocompleteAction(), + ) + } else { + addAll( + EnableTabAutocompleteAction(), + ) + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt index 9320705f8..a2ef465a3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt @@ -12,10 +12,15 @@ import com.intellij.openapi.util.TextRange class AutocompleteCaretListener: CaretListener { override fun caretPositionChanged(event: CaretEvent) { val caret = event.caret ?: return - val oldPosition = event.oldPosition val offset = caret.offset val editor = caret.editor val autocompleteService = editor.project?.service() ?: return + + if (autocompleteService.lastChangeWasPartialAccept) { + autocompleteService.lastChangeWasPartialAccept = false + return + } + val pending = autocompleteService.pendingCompletion; if (pending != null && pending.editor == editor && pending.offset == offset) { return @@ -29,10 +34,16 @@ class AutocompleteDocumentListener(private val editorManager: FileEditorManager, if (editor != editorManager.selectedTextEditor) { return } + + val service = editor.project?.service() ?: return + if (service.lastChangeWasPartialAccept) { + return + } + // Invoke later is important, otherwise the completion will be triggered before the document is updated // causing the old caret offset to be used invokeLater { - editor.project?.service()?.triggerCompletion(editor) + service.triggerCompletion(editor) } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 6d3691ad6..8731f7cac 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -14,18 +14,29 @@ import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.InlayProperties import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project +import com.intellij.openapi.wm.WindowManager data class PendingCompletion ( - val editor: Editor, - val offset: Int, - val completionId: String, - val text: String? + val editor: Editor, + var offset: Int, + val completionId: String, + var text: String? ) @Service(Service.Level.PROJECT) class AutocompleteService(private val project: Project) { var pendingCompletion: PendingCompletion? = null; private val autocompleteLookupListener = project.service() + private var widget: AutocompleteSpinnerWidget? = null + + // To avoid triggering another completion on partial acceptance, + // we need to keep track of whether the last change was a partial accept + var lastChangeWasPartialAccept = false + + init { + val statusBar = WindowManager.getInstance().getStatusBar(project) + widget = statusBar.getWidget("AutocompleteSpinnerWidget") as? AutocompleteSpinnerWidget + } fun triggerCompletion(editor: Editor) { val settings = @@ -42,6 +53,7 @@ class AutocompleteService(private val project: Project) { val completionId = uuid() val offset = editor.caretModel.primaryCaret.offset pendingCompletion = PendingCompletion(editor, offset, completionId, null) + widget?.setLoading(true) // Request a completion from the core val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) @@ -63,11 +75,13 @@ class AutocompleteService(private val project: Project) { val lineLength = lineEnd - lineStart project.service().coreMessenger?.request("autocomplete/complete", input, null, ({ response -> + widget?.setLoading(false) + val completions = response as List<*> if (completions.isNotEmpty()) { val completion = completions[0].toString() - if (completion.lines().size === 1 || column >= lineLength) { + if (completion.isNotEmpty() && (completion.lines().size === 1 || column >= lineLength)) { // Do not render if completion is multi-line and caret is in middle of line renderCompletion(editor, offset, completion) pendingCompletion = pendingCompletion?.copy(text = completion) @@ -80,12 +94,18 @@ class AutocompleteService(private val project: Project) { } private fun renderCompletion(editor: Editor, offset: Int, text: String) { + if (text.isEmpty()) { + return + } // Don't render completions when code completion dropdown is visible if (!autocompleteLookupListener.isLookupEmpty()) { return } ApplicationManager.getApplication().invokeLater { WriteAction.run { + // Clear existing completions + hideCompletions(editor) + val properties = InlayProperties() properties.relatesToPrecedingText(true) properties.disableSoftWrapping(true) @@ -120,8 +140,57 @@ class AutocompleteService(private val project: Project) { } } + private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { + val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) + .filter { it.isNotEmpty() } + + val result = mutableListOf() + var currentDelimiter = "" + + for (part in initialSplit) { + if (part.matches(delimiterPattern.toRegex())) { + currentDelimiter += part + } else { + if (currentDelimiter.isNotEmpty()) { + result.add(currentDelimiter) + currentDelimiter = "" + } + result.add(part) + } + } + + if (currentDelimiter.isNotEmpty()) { + result.add(currentDelimiter) + } + + return result +} + + fun partialAccept() { + val completion = pendingCompletion ?: return + val text = completion.text ?: return + val editor = completion.editor + val offset = completion.offset + + lastChangeWasPartialAccept = true + + // Split the text into words, keeping delimiters + val words = splitKeepingDelimiters(text) + println(words) + val word = words[0] + editor.document.insertString(offset, word) + editor.caretModel.moveToOffset(offset + word.length) + + // Remove the completion and re-display it + hideCompletions(editor) + completion.text = text.substring(word.length) + completion.offset += word.length + renderCompletion(editor, completion.offset, completion.text!!) + } + private fun cancelCompletion(completion: PendingCompletion) { // Send cancellation message to core + widget?.setLoading(false) project.service().coreMessenger?.request("autocomplete/cancel", null,null, ({})) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt new file mode 100644 index 000000000..8408a4964 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt @@ -0,0 +1,111 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.openapi.Disposable +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Disposer +import com.intellij.openapi.wm.StatusBar +import com.intellij.openapi.wm.StatusBarWidget +import com.intellij.openapi.util.IconLoader +import com.intellij.openapi.wm.StatusBarWidgetFactory +import com.intellij.openapi.wm.WindowManager +import com.intellij.openapi.wm.impl.status.EditorBasedWidget +import com.intellij.ui.AnimatedIcon +import com.intellij.util.Consumer +import java.awt.event.MouseEvent +import javax.swing.Icon +import javax.swing.JLabel + +class AutocompleteSpinnerWidget(project: Project): EditorBasedWidget(project), StatusBarWidget.IconPresentation, Disposable { + private val iconLabel = JLabel() + private var isLoading = false + + private val animatedIcon = AnimatedIcon( + 100, + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading1(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading2(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading3(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading4(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading5(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading6(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading7(RiderLight).svg", javaClass), + IconLoader.getIcon("/icons/AnimationLoadingIcon/AnimationLoading8(RiderLight).svg", javaClass), + ) + + init { + updateIcon() + } + + fun show() { + println("Showing autocomplete spinner widget") + } + + override fun dispose() {} + + override fun ID(): String { + return "AutocompleteSpinnerWidget" + } + + override fun getTooltipText(): String? { + val enabled = service().state.enableTabAutocomplete + return if (enabled) "Continue Autocomplete Enabled" else "Continue Autocomplete Disabled" + } + + override fun getClickConsumer(): Consumer? { + return null + } + + override fun getIcon(): Icon = if (isLoading) animatedIcon else + IconLoader.getIcon("/icons/continue.svg", javaClass) + + fun setLoading(loading: Boolean) { + isLoading = loading + updateIcon() + } + + private fun updateIcon() { + iconLabel.icon = getIcon() + + + // Update the widget + val statusBar = WindowManager.getInstance().getStatusBar(project) + statusBar.updateWidget(ID()) + } + + override fun install(statusBar: StatusBar) { + updateIcon() + } + + override fun getPresentation(): StatusBarWidget.WidgetPresentation? { + return this + } +} + +class AutocompleteSpinnerWidgetFactory: StatusBarWidgetFactory { + fun create(project: Project): AutocompleteSpinnerWidget { + return AutocompleteSpinnerWidget(project) + } + + override fun getId(): String { + return "AutocompleteSpinnerWidget" + } + + override fun getDisplayName(): String { + return "Continue Autocomplete" + } + + override fun isAvailable(p0: Project): Boolean { + return true + } + + override fun createWidget(project: Project): StatusBarWidget { + return AutocompleteSpinnerWidget(project) + } + + override fun disposeWidget(p0: StatusBarWidget) { + Disposer.dispose(p0) + } + + override fun canBeEnabledOn(p0: StatusBar): Boolean = true +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt index 3b8c8fe76..b151238c3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCustomElementRenderer.kt @@ -19,7 +19,8 @@ class ContinueCustomElementRenderer ( val text: String, ) : EditorCustomElementRenderer { override fun calcWidthInPixels(inlay: Inlay<*>): Int { - return (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(this.text) + val width = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(this.text) + return width } private fun font(editor: Editor): Font { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt index 989519cd6..38ecb5766 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueMultilineCustomElementRenderer.kt @@ -7,9 +7,8 @@ import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.FontInfo import com.intellij.openapi.editor.markup.TextAttributes -import com.intellij.ui.Gray import com.intellij.ui.JBColor -import java.awt.Color +import com.intellij.util.ui.UIUtil import java.awt.Font import java.awt.Graphics import java.awt.Rectangle @@ -39,7 +38,7 @@ class ContinueMultilineCustomElementRenderer ( protected val font: Font get() { val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN) - return editorFont.deriveFont(Font.PLAIN) ?: editorFont + return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize) } private fun offsetY(): Int { @@ -58,7 +57,9 @@ class ContinueMultilineCustomElementRenderer ( FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent)) val fontWidth = font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.width - val widthBeforeCaret = (editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(text.substring(0, currentColumn)) + val widthBeforeCaret = (editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth( + text.substring(0, minOf(currentColumn, text.length)) + ) return max(0, widthBeforeCaret - (editor as EditorImpl).scrollingModel.horizontalScrollOffset) } @@ -68,7 +69,7 @@ class ContinueMultilineCustomElementRenderer ( var additionalYOffset = -editor.lineHeight; var isFirstLine = true for (line in text.lines()) { - g.drawString(line, if (isFirstLine) targetRegion.x + offsetX() else targetRegion.x, targetRegion.y + offsetY() + additionalYOffset) + g.drawString(line, if (isFirstLine) targetRegion.x + offsetX() else targetRegion.x, targetRegion.y + inlay.editor.ascent + additionalYOffset) additionalYOffset += editor.lineHeight isFirstLine = false } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt new file mode 100644 index 000000000..d7e1f3b13 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt @@ -0,0 +1,12 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.components.service +class DisableTabAutocompleteAction : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val continueSettingsService = service() + continueSettingsService.continueState.enableTabAutocomplete = true + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt new file mode 100644 index 000000000..b14aa2190 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt @@ -0,0 +1,12 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.components.service +class EnableTabAutocompleteAction : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val continueSettingsService = service() + continueSettingsService.continueState.enableTabAutocomplete = true + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt index 1cd223df9..93c94ee0a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt @@ -11,8 +11,7 @@ import com.intellij.openapi.editor.actionSystem.EditorActionHandler class PartialAcceptAutocompleteAction: EditorAction(object : EditorActionHandler() { override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { ApplicationManager.getApplication().runWriteAction { - // TODO -// editor.project?.service()?.accept() + editor.project?.service()?.partialAccept() } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index 73a48e7ba..e974cf8fd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -66,7 +66,7 @@ class InlineEditAction : AnAction(), DumbAware { val modelTitles = mutableListOf() continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> val config = response as Map - val models = config["models"] as List> + val models = (config["config"] as Map)["models"] as List> modelTitles.addAll(models.map { it["title"] as String }) } val maxWaitTime = 200 diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 2ff6bbd89..50cab8fdf 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -22,6 +22,8 @@ + messages.MyBundle @@ -108,10 +110,6 @@ text="Start New Continue Session" icon="AllIcons.General.Add" description="Start New Continue Session"> - - + + + + diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 6d16f6b91..a93e891ae 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -899,6 +899,7 @@ "model": { "enum": [ "codestral-latest", + "codestral-mamba-latest", "open-mistral-7b", "open-mixtral-8x7b", "open-mixtral-8x22b", @@ -1906,6 +1907,13 @@ "title": "Request Options", "description": "Request options to be used in any fetch requests made by the embeddings provider", "$ref": "#/definitions/RequestOptions" + }, + "maxChunkSize": { + "title": "Maximum Chunk Size", + "description": "The maximum number of tokens that each chunk of a document is allowed to have", + "type": "integer", + "minimum": 128, + "exclusiveMaximum": 2147483647 } }, "required": ["provider"], diff --git a/extensions/intellij/src/main/resources/webview/continue-dev-square.png b/extensions/intellij/src/main/resources/webview/continue-dev-square.png deleted file mode 100644 index e4b625568..000000000 Binary files a/extensions/intellij/src/main/resources/webview/continue-dev-square.png and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/continue.gif b/extensions/intellij/src/main/resources/webview/continue.gif deleted file mode 100644 index daed66637..000000000 Binary files a/extensions/intellij/src/main/resources/webview/continue.gif and /dev/null differ diff --git a/extensions/intellij/src/main/resources/webview/play_button.png b/extensions/intellij/src/main/resources/webview/play_button.png deleted file mode 100644 index af3793758..000000000 Binary files a/extensions/intellij/src/main/resources/webview/play_button.png and /dev/null differ diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 6d16f6b91..a93e891ae 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -899,6 +899,7 @@ "model": { "enum": [ "codestral-latest", + "codestral-mamba-latest", "open-mistral-7b", "open-mixtral-8x7b", "open-mixtral-8x22b", @@ -1906,6 +1907,13 @@ "title": "Request Options", "description": "Request options to be used in any fetch requests made by the embeddings provider", "$ref": "#/definitions/RequestOptions" + }, + "maxChunkSize": { + "title": "Maximum Chunk Size", + "description": "The maximum number of tokens that each chunk of a document is allowed to have", + "type": "integer", + "minimum": 128, + "exclusiveMaximum": 2147483647 } }, "required": ["provider"], diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 2ce8beeaa..1b5e677c2 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -983,6 +983,7 @@ "model": { "enum": [ "codestral-latest", + "codestral-mamba-latest", "open-mistral-7b", "open-mixtral-8x7b", "open-mixtral-8x22b", @@ -2119,6 +2120,13 @@ "title": "Request Options", "description": "Request options to be used in any fetch requests made by the embeddings provider", "$ref": "#/definitions/RequestOptions" + }, + "maxChunkSize": { + "title": "Maximum Chunk Size", + "description": "The maximum number of tokens that each chunk of a document is allowed to have", + "type": "integer", + "minimum": 128, + "exclusiveMaximum": 2147483647 } }, "required": [ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 658636fe7..8cc798c0b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.181", + "version": "0.9.184", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.181", + "version": "0.9.184", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -98,6 +98,7 @@ "@aws-sdk/client-bedrock-runtime": "^3.574.0", "@aws-sdk/credential-providers": "^3.596.0", "@continuedev/config-types": "^1.0.6", + "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@types/jsdom": "^21.1.6", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 08faab27c..0152eb02a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -1,7 +1,7 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.9.182", + "version": "0.9.184", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -229,6 +229,18 @@ "category": "Continue", "title": "Fix Grammar / Spelling", "group": "Continue" + }, + { + "command": "continue.docsIndex", + "category": "Continue", + "title": "Docs Index", + "group": "Continue" + }, + { + "command": "continue.docsReIndex", + "category": "Continue", + "title": "Docs Force Re-Index", + "group": "Continue" } ], "keybindings": [ diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index f4ba3e34b..529372814 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -1,4 +1,4 @@ -import { getTsConfigPath, migrate } from "core/util/paths"; +import { getTsConfigPath, getContinueRcPath, migrate } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import path from "node:path"; import * as vscode from "vscode"; @@ -13,6 +13,7 @@ import { setupInlineTips } from "./inlineTips"; export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files getTsConfigPath(); + getContinueRcPath(); // Register commands and providers registerQuickFixProvider(); @@ -61,4 +62,4 @@ export async function activateExtension(context: vscode.ExtensionContext) { extension: vscodeExtension, } : continuePublicApi; -} +} \ No newline at end of file diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 1a897c9e2..7b1c9e623 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -22,9 +22,10 @@ import { import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; import { DiffManager } from "./diff/horizontal"; import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; -import { QuickEdit } from "./quickEdit/QuickEditQuickPick"; +import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { Core } from "core/core"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -170,6 +171,7 @@ const commandsMap: ( continueServerClientPromise: Promise, battery: Battery, quickEdit: QuickEdit, + core: Core, ) => { [command: string]: (...args: any) => any } = ( ide, extensionContext, @@ -180,6 +182,7 @@ const commandsMap: ( continueServerClientPromise, battery, quickEdit, + core ) => { /** * Streams an inline edit to the vertical diff manager. @@ -259,26 +262,10 @@ const commandsMap: ( vscode.commands.executeCommand("continue.continueGUIView.focus"); }, - "continue.defaultQuickActionDocstring": async (range: vscode.Range) => { - captureCommandTelemetry("defaultQuickActionDocstring"); - - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - range, - ); - }, - "continue.defaultQuickActionExplain": async (range: vscode.Range) => { - captureCommandTelemetry("defaultQuickActionExplain"); - - const prompt = - `Explain the above code in a few sentences without ` + - `going into detail on specific methods.`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); }, "continue.customQuickActionSendToChat": async ( prompt: string, @@ -301,6 +288,12 @@ const commandsMap: ( "continue.toggleAuxiliaryBar": () => { vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", {reIndex: false}); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", {reIndex: true}); + }, "continue.focusContinueInput": async () => { const fullScreenTab = getFullScreenTab(); if (!fullScreenTab) { @@ -346,9 +339,9 @@ const commandsMap: ( await addHighlightedCodeToContext(sidebar.webviewProtocol); } }, - "continue.quickEdit": async (initialPrompt?: string) => { + "continue.quickEdit": async (args: QuickEditShowParams) => { captureCommandTelemetry("quickEdit"); - quickEdit.show(initialPrompt); + quickEdit.show(args); }, "continue.writeCommentsForCode": async () => { captureCommandTelemetry("writeCommentsForCode"); @@ -685,6 +678,7 @@ export function registerAllCommands( continueServerClientPromise: Promise, battery: Battery, quickEdit: QuickEdit, + core: Core, ) { for (const [command, callback] of Object.entries( commandsMap( @@ -697,6 +691,7 @@ export function registerAllCommands( continueServerClientPromise, battery, quickEdit, + core ), )) { context.subscriptions.push( diff --git a/extensions/vscode/src/diff/oldVerticalPerLine.ts b/extensions/vscode/src/diff/oldVerticalPerLine.ts deleted file mode 100644 index 7a43fc088..000000000 --- a/extensions/vscode/src/diff/oldVerticalPerLine.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { matchLine } from "core/diff/util"; - -interface NextLineEvent { - type: "nextLine"; -} - -interface InsertDeletionEvent { - type: "insertDeletion"; - lines: string[]; - aboveLineAtIndex: number; -} - -interface ReplaceLineEvent { - type: "replaceLine"; - index: number; - newLine: string; -} - -interface InsertLineEvent { - type: "insertLine"; - aboveLineAtIndex: number; - line: string; -} - -type VerticalPerLineDiffEvent = - | NextLineEvent - | InsertDeletionEvent - | ReplaceLineEvent - | InsertLineEvent; - -async function* streamVerticalPerLineDiff( - lineGenerator: AsyncGenerator, - oldCode: string, -): AsyncGenerator { - const remainingLines = oldCode.split("\n"); - let index = 0; // Index in terms of oldCode - - let accumulatedDeletedLines: string[] = []; - - for await (const line of lineGenerator) { - const [matchIndex, isPerfectMatch] = matchLine(line, remainingLines); - - if (matchIndex < 0) { - // No match, so insert above remainingLines[0] - yield { - type: "insertLine", - aboveLineAtIndex: index, - line, - }; - } else if (matchIndex === 0) { - if (isPerfectMatch) { - // Perfect match of the next line, so insert and clear existing block - yield { - type: "insertDeletion", - lines: accumulatedDeletedLines, - aboveLineAtIndex: index, - }; - remainingLines.shift(); - accumulatedDeletedLines = []; - } else { - // Replace next line, so part of same block if one exists - yield { - type: "replaceLine", - index, - newLine: line, - }; - - const nextLine = remainingLines.shift(); - nextLine && accumulatedDeletedLines.push(); - } - } else { - // Already in a block, which is disconnected from this one, so insert and clear it - accumulatedDeletedLines.push(...remainingLines.splice(0, matchIndex)); - if (isPerfectMatch) { - yield { - type: "insertDeletion", - lines: accumulatedDeletedLines, - aboveLineAtIndex: index - accumulatedDeletedLines.length, - }; - accumulatedDeletedLines = []; - } else { - // Add to the current block all of the lines in between, then replace with the new line - yield { - type: "insertLine", - aboveLineAtIndex: index - accumulatedDeletedLines.length, - line, - }; - } - } - - index += Math.max(0, matchIndex); - remainingLines.splice(0, matchIndex); - } -} diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 251ba02fd..b0f5950fe 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -196,6 +196,7 @@ export class VsCodeExtension { this.core.continueServerClientPromise, this.battery, quickEdit, + this.core ); registerDebugTracker(this.sidebar.webviewProtocol, this.ide); diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts index 41ba94242..56ce22d4e 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -6,6 +6,7 @@ import { } from "../../../util/workspaceConfig"; import { isTutorialFile } from "./TutorialCodeLensProvider"; import { Telemetry } from "core/util/posthog"; +import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick"; export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions"; @@ -83,20 +84,14 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { }); } - getDefaultCommands(range: vscode.Range): vscode.Command[] { - const explain: vscode.Command = { - command: "continue.defaultQuickActionExplain", - title: "Explain", - arguments: [range], + getDefaultCommand(range: vscode.Range): vscode.Command[] { + const quickEdit: vscode.Command = { + command: "continue.defaultQuickAction", + title: "Continue", + arguments: [{ range } as QuickEditShowParams], }; - const comment: vscode.Command = { - command: "continue.defaultQuickActionDocstring", - title: "Docstring", - arguments: [range], - }; - - return [explain, comment]; + return [quickEdit]; } async provideCodeLenses( @@ -129,7 +124,7 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { return filteredSmybols.flatMap(({ range }) => { const commands: vscode.Command[] = !!this.customQuickActionsConfig ? this.getCustomCommands(range, this.customQuickActionsConfig) - : this.getDefaultCommands(range); + : this.getDefaultCommand(range); return commands.map((command) => new vscode.CodeLens(range, command)); }); diff --git a/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts index 0c3105b72..a70c62c7b 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/TutorialCodeLensProvider.ts @@ -3,6 +3,7 @@ import path from "path"; import * as vscode from "vscode"; import { getPlatform } from "../../../util/util"; import { getExtensionUri } from "../../../util/vscode"; +import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick"; interface TutorialCodeLensItems { lineIncludes: string; @@ -44,7 +45,7 @@ const actions: TutorialCodeLensItems[] = [ { title: `${cmdCtrl}+I`, command: "continue.quickEdit", - arguments: ["Add comments"], + arguments: [{ initialPrompt: "Add comments" } as QuickEditShowParams], }, ], }, diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index c95259dc5..5c6e87221 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,17 +1,18 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { IDE } from "core"; +import { walkDir } from "core/indexing/walkDir"; +import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { Telemetry } from "core/util/posthog"; -import { walkDir } from "core/indexing/walkDir"; -import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick"; import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick"; +import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick"; import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; // @ts-ignore - error finding typings -import MiniSearch from "minisearch"; import { ConfigHandler } from "core/config/ConfigHandler"; +// @ts-ignore +import MiniSearch from "minisearch"; /** * Used to track what action to take after a user interacts @@ -24,6 +25,15 @@ enum QuickEditInitialItemLabels { Submit = "Submit", } +export type QuickEditShowParams = { + initialPrompt?: string; + /** + * Used for Quick Actions where the user has not highlighted code. + * Instead the range comes from the document symbol. + */ + range?: vscode.Range; +}; + type FileMiniSearchResult = { filename: string }; /** @@ -42,6 +52,10 @@ export class QuickEdit { ); private static maxFileSearchResults = 20; + + private range?: vscode.Range; + private initialPrompt?: string; + private miniSearch = new MiniSearch({ fields: ["filename"], storeFields: ["filename"], @@ -77,11 +91,15 @@ export class QuickEdit { private readonly ide: IDE, private readonly context: vscode.ExtensionContext, ) { - this.intializeQuickEditState(); + this.initializeQuickEditState(); } - private async intializeQuickEditState() { - const editor = vscode.window.activeTextEditor!; + private async initializeQuickEditState() { + const editor = vscode.window.activeTextEditor; + + if (!editor) { + return; + } const existingHandler = this.verticalDiffManager.getHandlerForFile( editor.document.uri.fsPath ?? "", @@ -141,10 +159,14 @@ export class QuickEdit { } const fileName = vscode.workspace.asRelativePath(uri, true); - const { start, end } = this.editorWhenOpened.selection; - const selectionEmpty = this.editorWhenOpened.selection.isEmpty; - return selectionEmpty + const { start, end } = !!this.range + ? this.range + : this.editorWhenOpened.selection; + + const isSelectionEmpty = start.isEqual(end); + + return isSelectionEmpty ? `Edit ${fileName}` : `Edit ${fileName}:${start.line}${ end.line > start.line ? `-${end.line}` : "" @@ -182,12 +204,11 @@ export class QuickEdit { modelTitle, undefined, this.previousInput, + this.range, ); } - async _getInitialQuickPickVal( - injectedPrompt?: string, - ): Promise { + async _getInitialQuickPickVal(): Promise { const modelTitle = await this._getCurModelTitle(); const initialItems: vscode.QuickPickItem[] = [ @@ -236,7 +257,7 @@ export class QuickEdit { "Enter a prompt to edit your code (@ to search files, ⏎ to submit)"; quickPick.title = this._getQuickPickTitle(); quickPick.ignoreFocusOut = true; - quickPick.value = injectedPrompt ?? ""; + quickPick.value = this.initialPrompt ?? ""; quickPick.show(); @@ -341,18 +362,35 @@ export class QuickEdit { return selectedItemLabel; } + /** + * Reset the state of the quick pick + */ + private clear() { + this.initialPrompt = undefined; + this.range = undefined; + } + /** * Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt. * Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string. * Displays a quick pick for "Model" to set the current model title. * Appends the entered prompt to the history and streams the edit with input and context. */ - async show(initialPrompt?: string) { + async show(args?: QuickEditShowParams) { + // Clean up state from previous quick picks, e.g. if a user pressed `esc` + this.clear(); + const config = await this.configHandler.loadConfig(); - const selectedLabelOrInputVal = await this._getInitialQuickPickVal( - initialPrompt, - ); + if (!!args?.initialPrompt) { + this.initialPrompt = args.initialPrompt; + } + + if (!!args?.range) { + this.range = args.range; + } + + const selectedLabelOrInputVal = await this._getInitialQuickPickVal(); Telemetry.capture("quickEditSelection", { selection: selectedLabelOrInputVal, @@ -374,7 +412,7 @@ export class QuickEdit { this.contextProviderStr = contextProviderVal ?? ""; // Recurse back to let the user write their prompt - this.show(initialPrompt); + this.show(args); break; @@ -391,7 +429,7 @@ export class QuickEdit { } // Recurse back to let the user write their prompt - this.show(initialPrompt); + this.show(args); break; diff --git a/gui/package-lock.json b/gui/package-lock.json index 7de482640..92f1a4d1f 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -64,6 +64,7 @@ "devDependencies": { "@swc/cli": "^0.3.12", "@swc/core": "^1.5.25", + "@types/lodash": "^4.17.6", "@types/node": "^20.5.6", "@types/node-fetch": "^2.6.4", "@types/react": "^18.0.27", @@ -90,6 +91,7 @@ "@aws-sdk/client-bedrock-runtime": "^3.574.0", "@aws-sdk/credential-providers": "^3.596.0", "@continuedev/config-types": "^1.0.6", + "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@types/jsdom": "^21.1.6", @@ -1998,6 +2000,12 @@ "@types/node": "*" } }, + "node_modules/@types/lodash": { + "version": "4.17.6", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.6.tgz", + "integrity": "sha512-OpXEVoCKSS3lQqjx9GGGOapBeuW5eUboYHRlHP9urXPX25IKZ6AnP5ZRxtVf63iieUbsHxLn8NQ5Nlftc6yzAA==", + "dev": true + }, "node_modules/@types/mdast": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", diff --git a/gui/package.json b/gui/package.json index b2a4426e8..f0e4611e6 100644 --- a/gui/package.json +++ b/gui/package.json @@ -66,6 +66,7 @@ "devDependencies": { "@swc/cli": "^0.3.12", "@swc/core": "^1.5.25", + "@types/lodash": "^4.17.6", "@types/node": "^20.5.6", "@types/node-fetch": "^2.6.4", "@types/react": "^18.0.27", diff --git a/gui/public/continue-dev-square.png b/gui/public/continue-dev-square.png deleted file mode 100644 index e4b625568..000000000 Binary files a/gui/public/continue-dev-square.png and /dev/null differ diff --git a/gui/public/continue.gif b/gui/public/continue.gif deleted file mode 100644 index daed66637..000000000 Binary files a/gui/public/continue.gif and /dev/null differ diff --git a/gui/public/play_button.png b/gui/public/play_button.png deleted file mode 100644 index af3793758..000000000 Binary files a/gui/public/play_button.png and /dev/null differ diff --git a/gui/src/components/dialogs/ConfirmationDialog.tsx b/gui/src/components/dialogs/ConfirmationDialog.tsx index 6033e9b3d..6cb4dd18f 100644 --- a/gui/src/components/dialogs/ConfirmationDialog.tsx +++ b/gui/src/components/dialogs/ConfirmationDialog.tsx @@ -11,6 +11,14 @@ const GridDiv = styled.div` grid-template-columns: 1fr 1fr; grid-gap: 8px; align-items: center; + + > * { + grid-column: 2; + } + + > :nth-last-child(2):first-child { + grid-column: 1; + } `; interface ConfirmationDialogProps { @@ -18,6 +26,8 @@ interface ConfirmationDialogProps { onCancel?: () => void; text: string; title?: string; + hideCancelButton?: boolean; + confirmText?: string; } function ConfirmationDialog(props: ConfirmationDialogProps) { @@ -29,15 +39,17 @@ function ConfirmationDialog(props: ConfirmationDialogProps) {

{props.text}

- { - props.onCancel?.(); - dispatch(setShowDialog(false)); - dispatch(setDialogMessage(undefined)); - }} - > - Cancel - + {!!props.hideCancelButton || ( + { + props.onCancel?.(); + dispatch(setShowDialog(false)); + dispatch(setDialogMessage(undefined)); + }} + > + Cancel + + )} diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 50fc3ca07..6f5b450d5 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -4,9 +4,9 @@ import styled from "styled-components"; import { VSC_BACKGROUND_VAR, defaultBorderRadius, + lightGray, parseColorForHex, vscBackground, - vscFocusBorder, vscForeground, } from ".."; @@ -32,7 +32,7 @@ const Dialog = styled.div` border-radius: ${defaultBorderRadius}; display: flex; flex-direction: column; - border: 1px solid ${vscFocusBorder}; + border: 1px solid ${lightGray}; margin: auto; word-wrap: break-word; // overflow: hidden; diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 48a3422e1..47e45b69c 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -15,15 +15,16 @@ import FileIcon from "../FileIcon"; const ContextItemDiv = styled.div` cursor: pointer; - padding-left: 6px; - padding-right: 10px; - padding-top: 6px; - padding-bottom: 6px; + padding: 6px 10px 6px 6px; margin-left: 4px; display: flex; align-items: center; border-radius: ${defaultBorderRadius}; - width: fit-content; + font-size: ${getFontSize()}; + max-width: 100%; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; &:hover { background-color: #fff1; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 1b2dde188..f78afb71d 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -23,14 +23,19 @@ import { } from "../../util"; import ModelSelect from "../modelSelection/ModelSelect"; +const paddingTop = 4; +const height = 20; + const StyledDiv = styled.div<{ hidden?: boolean }>` - position: absolute; display: flex; - gap: 4px; - right: 4px; - bottom: 4px; - width: calc(100% - 10px); + justify-content: space-between; + flex-wrap: wrap-reverse; + flex-direction: row-reverse; + gap: 1px; background-color: ${vscInputBackground}; + padding-top: ${paddingTop}px; + + height: ${height}px; ${(props) => (props.hidden ? "display: none;" : "")} @@ -84,112 +89,127 @@ function InputToolbar(props: InputToolbarProps) { const useActiveFile = useSelector(selectUseActiveFile); return ( - + ); } diff --git a/gui/src/components/mainInput/TipTapEditor.css b/gui/src/components/mainInput/TipTapEditor.css index 746f639dd..ea5cd30bc 100644 --- a/gui/src/components/mainInput/TipTapEditor.css +++ b/gui/src/components/mainInput/TipTapEditor.css @@ -22,6 +22,7 @@ float: left; height: 0; pointer-events: none; + white-space: nowrap; } .gap-cursor { diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index c0e941e45..258c1780d 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -58,7 +58,7 @@ const InputBoxDiv = styled.div` resize: none; padding: 8px; - padding-bottom: 24px; + padding-bottom: 4px; font-family: inherit; border-radius: ${defaultBorderRadius}; margin: 0; @@ -70,7 +70,6 @@ const InputBoxDiv = styled.div` border: 0.5px solid ${vscInputBorder}; outline: none; font-size: ${getFontSize()}px; - &:focus { outline: none; diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx index d26c2502b..1abb5f059 100644 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ b/gui/src/components/mainInput/TutorialCard.tsx @@ -16,8 +16,8 @@ interface TutorialCardProps { const TutorialCardDiv = styled.div` border: 1px solid ${lightGray}; border-radius: 0.125rem; - padding: 0.5rem; - margin: 1.5rem; + padding: 1rem 2.5rem 1rem 2rem; + margin: 1rem; max-width: 28rem; position: relative; `; @@ -31,10 +31,10 @@ export function TutorialCard({ onClose }: TutorialCardProps) { role="button" aria-label="Close" > - + -
    +
    • ([]); + const selectedProfileId = useSelector( + (store: RootState) => store.state.selectedProfileId, + ); + useEffect(() => { setOptions( allModels.map((model) => { @@ -227,22 +231,26 @@ function ModelSelect() { /> ))} - + {selectedProfileId === "local" && ( + <> + {options.length > 0 && } - { - e.stopPropagation(); - e.preventDefault(); - navigate("/addModel"); - }} - value={"addModel" as any} - > -
      - - Add Model -
      -
      + { + e.stopPropagation(); + e.preventDefault(); + navigate("/addModel"); + }} + value={"addModel" as any} + > +
      + + Add Model +
      +
      + + )} diff --git a/gui/src/hooks/useAuth.tsx b/gui/src/hooks/useAuth.tsx index db69bf891..e8100ca7d 100644 --- a/gui/src/hooks/useAuth.tsx +++ b/gui/src/hooks/useAuth.tsx @@ -4,6 +4,7 @@ import { useDispatch } from "react-redux"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; export function useAuth(): { @@ -31,7 +32,27 @@ export function useAuth(): { console.log("login"); ideMessenger .request("getControlPlaneSessionInfo", { silent: false }) - .then(setSession); + .then((session) => { + setSession(session); + + // If this is the first time the user has logged in, explain how profiles work + if (!getLocalStorage("shownProfilesIntroduction")) { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( + {}} + />, + ), + ); + setLocalStorage("shownProfilesIntroduction", true); + } + }); }; const logout = () => { @@ -39,6 +60,8 @@ export function useAuth(): { dispatch( setDialogMessage( {}} />, diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index f43fc7902..28cd4019b 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -13,9 +13,10 @@ import { import { RootState } from "../redux/store"; import { isJetBrains } from "../util"; -import { setLocalStorage } from "../util/localStorage"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; +import { debounce } from "lodash"; function useSetup(dispatch: Dispatch) { const [configLoaded, setConfigLoaded] = useState(false); @@ -30,6 +31,7 @@ function useSetup(dispatch: Dispatch) { dispatch(setConfig(config)); dispatch(setSelectedProfileId(profileId)); setConfigLoaded(true); + setLocalStorage("disableIndexing", config.disableIndexing || false); // Perform any actions needed with the config if (config.ui?.fontSize) { @@ -86,8 +88,16 @@ function useSetup(dispatch: Dispatch) { }); }); + const debouncedIndexDocs = debounce(() => { + ideMessenger.request("context/indexDocs", { reIndex: false }); + }, 1000); + useWebviewListener("configUpdate", async () => { - loadConfig(); + await loadConfig(); + + if (!isJetBrains && !getLocalStorage("disableIndexing")) { + debouncedIndexDocs(); + } }); useWebviewListener("submitMessage", async (data) => { diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 1486a2856..c0105f241 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -276,7 +276,19 @@ export const models: { [key: string]: ModelPackage } = { }, icon: "mistral.png", providerOptions: ["mistral"], - isOpenSource: false, + isOpenSource: true, + }, + codestralMamba: { + title: "Codestral Mamba", + description: "A Mamba 2 language model specialized in code generation.", + params: { + title: "Codestral Mamba", + model: "codestral-mamba-latest", + contextLength: 256_000, + }, + icon: "mistral.png", + providerOptions: ["mistral"], + isOpenSource: true, }, mistral7b: { title: "Mistral 7B", diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 58bb562be..5c81efdb2 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -1,10 +1,10 @@ import { ModelProvider } from "core"; import { HTMLInputTypeAttribute } from "react"; import { ModelProviderTags } from "../../../components/modelSelection/ModelProviderTag"; +import { FREE_TRIAL_LIMIT_REQUESTS } from "../../../util/freeTrial"; import { completionParamsInputs } from "./completionParamsInputs"; import type { ModelPackage } from "./models"; import { models } from "./models"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../../../util/freeTrial"; export interface InputDescriptor { inputType: HTMLInputTypeAttribute; @@ -186,6 +186,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n ], packages: [ models.codestral, + models.codestralMamba, models.mistralLarge, models.mistralSmall, models.mistral8x22b, diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 8837e001e..08ec5fc6e 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -26,10 +26,12 @@ import { vscBackground, vscForeground, } from "../components"; +import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; import StepContainer from "../components/gui/StepContainer"; import TimelineItem from "../components/gui/TimelineItem"; import ContinueInputBox from "../components/mainInput/ContinueInputBox"; import { defaultInputModifiers } from "../components/mainInput/inputModifiers"; +import { TutorialCard } from "../components/mainInput/TutorialCard"; import { IdeMessengerContext } from "../context/IdeMessenger"; import useChatHandler from "../hooks/useChatHandler"; import useHistory from "../hooks/useHistory"; @@ -52,10 +54,8 @@ import { isJetBrains, isMetaEquivalentKeyPressed, } from "../util"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; -import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; -import { TutorialCard } from "../components/mainInput/TutorialCard"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; const TopGuiDiv = styled.div` overflow-y: scroll; diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index ca26b6ce4..1eecda363 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -15,6 +15,8 @@ type LocalStorageTypes = { signedInToGh: boolean; isOnboardingInProgress: boolean; showTutorialCard: boolean; + shownProfilesIntroduction: boolean; + disableIndexing: boolean; }; export function getLocalStorage( diff --git a/packages/control-plane-types/package-lock.json b/packages/control-plane-types/package-lock.json deleted file mode 100644 index 0df9c60ee..000000000 --- a/packages/control-plane-types/package-lock.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "control-plane-types", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "control-plane-types", - "version": "1.0.0", - "license": "Apache-2.0", - "devDependencies": { - "typescript": "^5.5.2" - } - }, - "node_modules/typescript": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.2.tgz", - "integrity": "sha512-NcRtPEOsPFFWjobJEtfihkLCZCXZt/os3zf8nTxjVH3RvTSxjrCamJpbExGvYOF+tFHc3pA65qpdwPbzjohhew==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - } - } -} diff --git a/packages/control-plane-types/src/index.d.ts b/packages/control-plane-types/src/index.d.ts deleted file mode 100644 index d716289a4..000000000 --- a/packages/control-plane-types/src/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface Test { - a: string; - b: number; -} diff --git a/packages/control-plane-types/tsconfig.json b/packages/control-plane-types/tsconfig.json deleted file mode 100644 index 8bb6097f8..000000000 --- a/packages/control-plane-types/tsconfig.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } -} diff --git a/packages/llm-info/README.md b/packages/llm-info/README.md new file mode 100644 index 000000000..068a1d24a --- /dev/null +++ b/packages/llm-info/README.md @@ -0,0 +1,3 @@ +# @continuedev/llm-info + +A lightweight package providing information about various Large Language Models (LLMs). diff --git a/packages/control-plane-types/package.json b/packages/llm-info/package.json similarity index 54% rename from packages/control-plane-types/package.json rename to packages/llm-info/package.json index 0bc5b95d5..450614c85 100644 --- a/packages/control-plane-types/package.json +++ b/packages/llm-info/package.json @@ -1,15 +1,18 @@ { - "name": "control-plane-types", - "version": "1.0.0", + "name": "@continuedev/llm-info", + "version": "1.0.1", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", + "type": "module", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "echo \"Error: no test specified\" && exit 1", + "build": "tsc" }, "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "devDependencies": { "typescript": "^5.5.2" - } + }, + "dependencies": {} } diff --git a/packages/llm-info/src/index.ts b/packages/llm-info/src/index.ts new file mode 100644 index 000000000..2c1e14808 --- /dev/null +++ b/packages/llm-info/src/index.ts @@ -0,0 +1,18 @@ +import { AnthropicLlms } from "./models/anthropic.js"; +import { GoogleLlms } from "./models/google.js"; +import { MistralLlms } from "./models/mistral.js"; +import { OpenAiLlms } from "./models/openai.js"; +import { LlmInfo } from "./types.js"; + +export const allLlms: LlmInfo[] = [ + ...OpenAiLlms, + ...GoogleLlms, + ...AnthropicLlms, + ...MistralLlms, +]; + +export function findLlmInfo(model: string): LlmInfo | undefined { + return allLlms.find((llm) => + llm.regex ? llm.regex.test(model) : llm.model === model, + ); +} diff --git a/packages/llm-info/src/models/anthropic.ts b/packages/llm-info/src/models/anthropic.ts new file mode 100644 index 000000000..e3c85230c --- /dev/null +++ b/packages/llm-info/src/models/anthropic.ts @@ -0,0 +1,60 @@ +import { LlmInfo } from "../types.js"; + +export const AnthropicLlms: LlmInfo[] = [ + { + model: "claude-3-5-sonnet-20240620", + displayName: "Claude 3.5 Sonnet", + contextLength: 200_000, + description: + "Most intelligent model with the highest level of intelligence and capability.", + regex: /claude-3\.5-sonnet/i, + }, + { + model: "claude-3-opus-20240229", + displayName: "Claude 3 Opus", + contextLength: 200_000, + description: + "Powerful model for highly complex tasks with top-level performance, intelligence, fluency, and understanding.", + regex: /claude-3-opus/i, + }, + { + model: "claude-3-sonnet-20240229", + displayName: "Claude 3 Sonnet", + contextLength: 200_000, + description: + "Balance of intelligence and speed with strong utility, balanced for scaled deployments.", + regex: /claude-3-sonnet/i, + }, + { + model: "claude-3-haiku-20240307", + displayName: "Claude 3 Haiku", + contextLength: 200_000, + description: + "Fastest and most compact model for near-instant responsiveness with quick and accurate targeted performance.", + regex: /claude-3-haiku/i, + }, + { + model: "claude-2.1", + displayName: "Claude 2.1", + contextLength: 200_000, + description: + "Updated version of Claude 2 with improved accuracy and consistency.", + regex: /claude-2\.1/i, + }, + { + model: "claude-2.0", + displayName: "Claude 2", + contextLength: 100_000, + description: + "Predecessor to Claude 3, offering strong all-round performance.", + regex: /claude-2\.0/i, + }, + { + model: "claude-instant-1.2", + displayName: "Claude Instant 1.2", + contextLength: 100_000, + description: + "Our cheapest small and fast model, a predecessor of Claude Haiku.", + regex: /claude-instant-1\.2/i, + }, +]; diff --git a/packages/llm-info/src/models/google.ts b/packages/llm-info/src/models/google.ts new file mode 100644 index 000000000..65704cdba --- /dev/null +++ b/packages/llm-info/src/models/google.ts @@ -0,0 +1,22 @@ +import { AllMediaTypes, LlmInfo } from "../types.js"; + +export const GoogleLlms: LlmInfo[] = [ + { + model: "gemini-1.5-flash", + displayName: "Gemini 1.5 Flash", + contextLength: 1_048_576, + mediaTypes: AllMediaTypes, + regex: /gemini-1\.5-flash/i, + }, + { + model: "gemini-1.5-pro", + displayName: "Gemini 1.5 Pro", + contextLength: 2_097_152, + regex: /gemini-1\.5-pro/i, + }, + { + model: "gemini-1.0-pro", + displayName: "Gemini 1.0 Pro", + regex: /gemini-1\.0-pro/i, + }, +]; diff --git a/packages/llm-info/src/models/mistral.ts b/packages/llm-info/src/models/mistral.ts new file mode 100644 index 000000000..796fc9c86 --- /dev/null +++ b/packages/llm-info/src/models/mistral.ts @@ -0,0 +1,75 @@ +import { LlmInfo } from "../types.js"; + +export const MistralLlms: LlmInfo[] = [ + { + model: "mistral-large-latest", + displayName: "Mistral Large", + contextLength: 32768, + description: + "Flagship model ideal for complex tasks requiring large reasoning capabilities or highly specialized tasks like synthetic text generation, code generation, RAG, or agents.", + regex: /mistral-large/i, + }, + { + model: "mistral-medium-latest", + displayName: "Mistral Medium", + contextLength: 32768, + description: + "Ideal for intermediate tasks requiring moderate reasoning such as data extraction, document summarization, email writing, job descriptions, or product descriptions. (Note: Will be deprecated in the coming months)", + regex: /mistral-medium/i, + }, + { + model: "mistral-small-latest", + displayName: "Mistral Small", + contextLength: 32768, + description: + "Suitable for simple tasks that can be done in bulk like classification, customer support, or text generation.", + regex: /mistral-small/i, + }, + { + model: "open-mistral-7b", + displayName: "Mistral 7B", + contextLength: 32768, + description: + "First dense model released by Mistral AI, perfect for experimentation, customization, and quick iteration. Matches capabilities of models up to 30B parameters at release time.", + regex: /open-mistral-7b/i, + }, + { + model: "open-mixtral-8x7b", + displayName: "Mixtral 8x7B", + contextLength: 32768, + description: + "Sparse mixture of experts model leveraging up to 45B parameters but using about 12B during inference, offering better inference throughput at the cost of more vRAM.", + regex: /open-mixtral-8x7b/i, + }, + { + model: "open-mixtral-8x22b", + displayName: "Mixtral 8x22B", + contextLength: 65536, + description: + "Larger sparse mixture of experts model leveraging up to 141B parameters but using about 39B during inference, providing better inference throughput at the cost of more vRAM.", + regex: /open-mixtral-8x22b/i, + }, + { + model: "mistral-embed", + displayName: "Mistral Embeddings", + contextLength: 8192, + description: + "Model that converts text into numerical vectors of embeddings in 1024 dimensions. Enables retrieval and retrieval-augmented generation applications with a retrieval score of 55.26 on MTEB.", + regex: /mistral-embed/i, + }, + { + model: "codestral-mamba-latest", + displayName: "Codestral Mamba", + contextLength: 256_000, + description: "A Mamba 2 language model specialized in code generation.", + regex: /codestral-mamba/i, + }, + { + model: "codestral-latest", + displayName: "Codestral", + contextLength: 32768, + description: + "Cutting-edge generative model specifically designed and optimized for code generation tasks, including fill-in-the-middle and code completion.", + regex: /codestral/i, + }, +]; diff --git a/packages/llm-info/src/models/openai.ts b/packages/llm-info/src/models/openai.ts new file mode 100644 index 000000000..2c7b70e1e --- /dev/null +++ b/packages/llm-info/src/models/openai.ts @@ -0,0 +1,69 @@ +import { LlmInfo } from "../types.js"; + +export const OpenAiLlms: LlmInfo[] = [ + { + model: "gpt-3.5-turbo", + displayName: "GPT-3.5 Turbo", + contextLength: 4096, + }, + { + model: "gpt-3.5-turbo-0613", + displayName: "GPT-3.5 Turbo (0613)", + contextLength: 4096, + }, + { + model: "gpt-3.5-turbo-16k", + displayName: "GPT-3.5 Turbo 16K", + contextLength: 16384, + }, + { + model: "gpt-35-turbo-16k", + displayName: "GPT-3.5 Turbo 16K", + contextLength: 16384, + }, + { + model: "gpt-35-turbo-0613", + displayName: "GPT-3.5 Turbo (0613)", + contextLength: 4096, + }, + { + model: "gpt-35-turbo", + displayName: "GPT-3.5 Turbo", + contextLength: 4096, + }, + { + model: "gpt-4", + displayName: "GPT-4", + contextLength: 4096, + }, + { + model: "gpt-4-32k", + displayName: "GPT-4 32K", + contextLength: 4096, + }, + { + model: "gpt-4-turbo-preview", + displayName: "GPT-4 Turbo Preview", + contextLength: 4096, + }, + { + model: "gpt-4o", + displayName: "GPT-4o", + contextLength: 4096, + }, + { + model: "gpt-4-vision", + displayName: "GPT-4 Vision", + contextLength: 4096, + }, + { + model: "gpt-4-0125-preview", + displayName: "GPT-4 (0125 Preview)", + contextLength: 4096, + }, + { + model: "gpt-4-1106-preview", + displayName: "GPT-4 (1106 Preview)", + contextLength: 4096, + }, +]; diff --git a/packages/llm-info/src/types.ts b/packages/llm-info/src/types.ts new file mode 100644 index 000000000..176989d57 --- /dev/null +++ b/packages/llm-info/src/types.ts @@ -0,0 +1,30 @@ +export interface LlmInfo { + model: string; + displayName?: string; + description?: string; + contextLength?: number; + regex?: RegExp; + + /** If not set, assumes "text" only */ + mediaTypes?: MediaType[]; +} + +export enum MediaType { + Text = "text", + Image = "image", + Audio = "audio", + Video = "video", +} + +export const AllMediaTypes = [ + MediaType.Text, + MediaType.Image, + MediaType.Audio, + MediaType.Video, +]; + +export interface ApiProviderInfo { + displayName: string; + supportsStreaming: boolean; + handlesTemplating: boolean; +} diff --git a/packages/llm-info/tsconfig.json b/packages/llm-info/tsconfig.json new file mode 100644 index 000000000..f21949f4b --- /dev/null +++ b/packages/llm-info/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "NodeNext", + "useDefineForClassFields": true, + "lib": ["DOM", "ESNext"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "NodeNext", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmitOnError": false, + "types": ["node"], + "outDir": "dist", + "declaration": true + // "sourceMap": true + }, + "include": ["src/**/*"] +}