From a835ac1126eb5e9bff4dcb4a49536c69dc4b1dcb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Dec 2024 10:10:03 -0800 Subject: [PATCH 01/33] fix chat indexing peek --- core/indexing/docs/DocsService.ts | 8 +++++++- .../components/indexing/ChatIndexingPeeks.tsx | 20 ++++++++++++------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index f35f83466..5480dc161 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -710,14 +710,20 @@ export default class DocsService { await db.exec("PRAGMA busy_timeout = 3000;"); await runSqliteMigrations(db); - + // First create the table if it doesn't exist await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, startUrl STRING NOT NULL UNIQUE, favicon STRING + embeddingsProviderId STRING )`); + // embeddingsProviderId was added later + await db.exec(`ALTER TABLE ${DocsService.sqlitebTableName} + ADD COLUMN IF NOT EXISTS embeddingsProviderId STRING; + `); + this.sqliteDb = db; } diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index 1ec1076c0..dbca84b05 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -75,25 +75,31 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { } function ChatIndexingPeeks() { + const config = useAppSelector((store) => store.config.config); const indexingStatuses = useAppSelector( (store) => store.indexing.indexing.statuses, ); const mergedIndexingStates: MergedIndexingState[] = useMemo(() => { const mergedStates: MergedIndexingState[] = []; - const docsStates = Object.values(indexingStatuses).filter( - (status) => status.type === "docs" && status.status === "indexing", - ); - if (docsStates.length > 0) { + const configDocs = config?.docs ?? []; + const docsIndexing: IndexingStatus[] = []; + configDocs.forEach((doc) => { + const status = indexingStatuses[doc.startUrl]; + if (status && status.status === "indexing") { + docsIndexing.push(status); + } + }); + if (docsIndexing.length > 0) { mergedStates.push({ displayName: "Docs indexing", type: "docs", - titles: docsStates.map((state) => state.title), - progressPercentage: mergeProgress(docsStates), + titles: docsIndexing.map((doc) => doc.title), + progressPercentage: mergeProgress(docsIndexing), }); } return mergedStates; - }, [indexingStatuses]); + }, [config, indexingStatuses]); if (!mergedIndexingStates.length) return null; From baca0805bf9935f7322100ca42e29f0224c1afe5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Dec 2024 12:27:42 -0800 Subject: [PATCH 02/33] embeddings provider in docs --- core/context/providers/DocsContextProvider.ts | 41 ++-- core/core.ts | 2 +- core/indexing/docs/DocsService.ts | 196 ++++++++---------- core/util/GlobalContext.test.ts | 21 +- core/util/GlobalContext.ts | 1 - gui/src/components/dialogs/AddDocsDialog.tsx | 16 ++ .../components/indexing/DocsIndexingPeeks.tsx | 1 + 7 files changed, 135 insertions(+), 143 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 6eab55fa4..47542bc1c 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -80,22 +80,28 @@ class DocsContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + // Get docs service const docsService = DocsService.getSingleton(); - if (!docsService) { console.error(`${DocsService.name} has not been initialized`); return []; } - await docsService.isInitialized; + + // Get chunks let chunks = await docsService.retrieveChunksFromQuery( extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); + if(!chunks?.length) { + return []; + } + // We found chunks, so check if there's a favicon for the docs page const favicon = await docsService.getFavicon(query); + // Rerank if there's a rerankder if (extras.reranker) { chunks = await this._rerankChunks( chunks, @@ -139,18 +145,30 @@ class DocsContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { + // Get docs service const docsService = DocsService.getSingleton(); - if (!docsService) { console.error(`${DocsService.name} has not been initialized`); return []; } + await docsService.isInitialized; - const docs = (await docsService.listMetadata()) ?? []; - const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); - + // Create map of docs url -> submenu item const submenuItemsMap = new Map(); + // Add custom docs from config + const docs = (await docsService.listMetadata()) ?? []; + for (const { startUrl, title, favicon } of docs) { + submenuItemsMap.set(startUrl, { + title,\ + id: startUrl, + description: new URL(startUrl).hostname, + icon: favicon, + }); + } + + // Add pre-indexed docs if supported + const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); if (canUsePreindexedDocs) { for (const { startUrl, title } of Object.values(preIndexedDocs)) { submenuItemsMap.set(startUrl, { @@ -164,17 +182,8 @@ class DocsContextProvider extends BaseContextProvider { } } - for (const { startUrl, title, favicon } of docs) { - submenuItemsMap.set(startUrl, { - title, - id: startUrl, - description: new URL(startUrl).hostname, - icon: favicon, - }); - } - + // Create array and sort if pre-indexed is supported const submenuItems = Array.from(submenuItemsMap.values()); - if (canUsePreindexedDocs) { return this._sortByPreIndexedDocs(submenuItems); } diff --git a/core/core.ts b/core/core.ts index fb3840d05..bea254c81 100644 --- a/core/core.ts +++ b/core/core.ts @@ -286,7 +286,7 @@ export class Core { }); on("context/indexDocs", async (msg) => { - await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex); + await this.docsService.syncDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 5480dc161..0af6aa28f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -185,7 +185,6 @@ export default class DocsService { abort(startUrl: string) { const status = this.statuses.get(startUrl); if (status) { - this.docsIndexingQueue.delete(startUrl); this.handleStatusUpdate({ ...status, status: "aborted", @@ -193,6 +192,7 @@ export default class DocsService { description: "Canceled", }); } + this.docsIndexingQueue.delete(startUrl); } isAborted(startUrl: string) { @@ -256,93 +256,79 @@ export default class DocsService { this.docsCrawler = new DocsCrawler(this.ide, newConfig); + if (this.config.disableIndexing) { + return; + } + + // No point in indexing if no docs context provider + const hasDocsContextProvider = this.hasDocsContextProvider(); + if (!hasDocsContextProvider) { + return; + } + // Skip docs indexing if not supported + // No warning message here because would show on ANY config update const unsupported = await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); if (unsupported) { return; } - await this.syncOrReindexAllDocs(newConfig, oldConfig); + await this.syncDocs(oldConfig, newConfig, false); } } - private async syncOrReindexAllDocs( - newConfig: ContinueConfig, - oldConfig?: ContinueConfig, - ) { - // On embeddings provider change, reindex all non-preindexed docs - // change = doesn't match last successful embeddings provider - const curEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - if ( - !curEmbeddingsProviderId || - curEmbeddingsProviderId !== newConfig.embeddingsProvider.embeddingId - ) { - // If not set, we're initializing - const currentDocs = await this.listMetadata(); - if (currentDocs.length > 0) { - await this.reindexDocsOnNewEmbeddingsProvider(); - return; - } - } - - await this.syncDocsOnConfigUpdate(oldConfig, newConfig); - } - - async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) { + async syncDocsWithPrompt(reIndex: boolean = false) { if (!this.hasDocsContextProvider()) { - const didAddDocsContextProvider = - await this.showAddDocsContextProviderToast(); + const actionMsg = "Add 'docs' context provider"; + const res = await this.ide.showToast( + "info", + "Starting docs indexing", + actionMsg, + ); - if (!didAddDocsContextProvider) { + if (res === actionMsg) { + addContextProvider({ + name: DocsContextProvider.description.title, + params: {}, + }); + + void this.ide.showToast( + "info", + "Successfuly added docs context provider", + ); + } else { return; } } - await this.syncOrReindexAllDocs(this.config); + await this.syncDocs(undefined, this.config, reIndex); void this.ide.showToast("info", "Docs indexing completed"); } + // Returns true if startUrl has been indexed with current embeddingsProvider async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( - `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, + this.config.embeddingsProvider.embeddingId, ); return !!title; } - async showAddDocsContextProviderToast() { - const actionMsg = "Add 'docs' context provider"; - const res = await this.ide.showToast( - "info", - "Starting docs indexing", - actionMsg, - ); - - if (res === actionMsg) { - addContextProvider({ - name: DocsContextProvider.description.title, - params: {}, - }); - - void this.ide.showToast( - "info", - "Successfuly added docs context provider", - ); - } - - return res === actionMsg; - } - async listMetadata() { + const embeddingsProvider = this.config.embeddingsProvider; + if (!embeddingsProvider) { + return []; + } const db = await this.getOrCreateSqliteDb(); const docs = await db.all( - `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, + `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName} + WHERE embeddingsProviderId = ?`, + embeddingsProvider.embeddingId, ); return docs; @@ -363,15 +349,21 @@ export default class DocsService { ): Promise { const { startUrl } = siteIndexingConfig; + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + if (canUsePreindexedDocs) { + const preIndexedDoc = preIndexedDocs[startUrl]; + const isPreIndexedDoc = !!preIndexedDoc; + if (isPreIndexedDoc) { + console.warn("Can only use pre"); + } + } + // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs if (this.docsIndexingQueue.has(startUrl)) { return; } const embeddingsProvider = await this.getEmbeddingsProvider(); - - this.docsIndexingQueue.add(startUrl); - const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values @@ -404,12 +396,9 @@ export default class DocsService { return; } } + this.docsIndexingQueue.add(startUrl); - // If not preindexed - const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; - if (!isPreIndexedDoc) { - this.addToConfig(siteIndexingConfig); - } + this.addToConfig(siteIndexingConfig); try { this.handleStatusUpdate({ @@ -650,13 +639,18 @@ export default class DocsService { return await this.retrieveChunks(startUrl, vector, nRetrieve); } + // This is split into its own function so that it can be recursive + // in the case of fetching preindexed docs from s3 async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, isRetry: boolean = false, ): Promise { - const isPreIndexedDoc = !!preIndexedDocs[startUrl]; + const preIndexedDoc = preIndexedDocs[startUrl]; + const isPreIndexedDoc = !!preIndexedDoc; + + // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name const table = await this.getOrCreateLanceTable({ initializationVector: vector, isPreIndexedDoc, @@ -673,19 +667,21 @@ export default class DocsService { console.warn("Error retrieving chunks from LanceDB", e); } - const hasIndexedDoc = await this.hasMetadata(startUrl); - - if (!hasIndexedDoc && docs.length === 0) { - const preIndexedDoc = preIndexedDocs[startUrl]; - - if (isRetry || !preIndexedDoc) { + // No docs are found for preindexed? try fetching once + if (docs.length === 0 && isPreIndexedDoc) { + if (isRetry) { return []; } - await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title); return await this.retrieveChunks(startUrl, vector, nRetrieve, true); } + if (isPreIndexedDoc) { + void Telemetry.capture("docs_pre_indexed_doc_used", { + doc: preIndexedDoc["title"], + }); + } + return docs.map((doc) => ({ digest: doc.path, filepath: doc.path, @@ -747,9 +743,10 @@ export default class DocsService { Sync with no embeddings provider change Ignores pre-indexed docs */ - private async syncDocsOnConfigUpdate( + private async syncDocs( oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, + reindex: boolean, ) { try { this.isSyncing = true; @@ -869,9 +866,7 @@ export default class DocsService { return name.replace(/[^a-zA-Z0-9_.-]/g, "_"); } - private async getLanceTableNameFromEmbeddingsProvider( - isPreIndexedDoc: boolean, - ) { + private async getLanceTableName(isPreIndexedDoc: boolean) { const embeddingsProvider = await this.getEmbeddingsProvider(isPreIndexedDoc); @@ -892,7 +887,7 @@ export default class DocsService { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const tableNameFromEmbeddingsProvider = - await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); + await this.getLanceTableName(!!isPreIndexedDoc); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -949,10 +944,11 @@ export default class DocsService { }: AddParams) { const db = await this.getOrCreateSqliteDb(); await db.run( - `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon) VALUES (?, ?, ?)`, + `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`, title, startUrl, favicon, + this.config.embeddingsProvider.embeddingId, ); } @@ -960,13 +956,23 @@ export default class DocsService { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file const doesDocExist = this.config.docs?.some( - (doc) => doc.startUrl === siteIndexingConfig.startUrl, + (doc) => + doc.startUrl === siteIndexingConfig.startUrl && + doc.faviconUrl === siteIndexingConfig.faviconUrl && + siteIndexingConfig.title === doc.title, + // siteIndexingConfig.maxDepth === doc.maxDepth && + // doc.rootUrl === siteIndexingConfig.rootUrl, ); if (!doesDocExist) { editConfigJson((config) => ({ ...config, - docs: [...(config.docs ?? []), siteIndexingConfig], + docs: [ + ...(config.docs?.filter( + (doc) => doc.startUrl !== siteIndexingConfig.startUrl, + ) ?? []), + siteIndexingConfig, + ], })); } } @@ -1017,34 +1023,4 @@ export default class DocsService { this.deleteFromConfig(startUrl); this.messenger?.send("refreshSubmenuItems", undefined); } - - /** - * Currently this deletes re-crawls + re-indexes all docs. - * A more optimal solution in the future will be to create - * a per-embeddings-provider table for docs. - */ - private async reindexDocsOnNewEmbeddingsProvider() { - // We use config as our source of truth here since it contains additional information - // needed for re-crawling such as `faviconUrl` and `maxDepth`. - const { docs, embeddingsProvider } = this.config; - - if (!docs || docs.length === 0) { - return; - } - - console.log( - `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.embeddingId}`, - ); - await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc))); - - // Important that this only is invoked after we have successfully - // cleared and reindex the docs so that the table cannot end up in an - // invalid state. - this.globalContext.update( - "curEmbeddingsProviderId", - embeddingsProvider.embeddingId, - ); - - console.log("Completed reindexing of all non-preindexed docs"); - } } diff --git a/core/util/GlobalContext.test.ts b/core/util/GlobalContext.test.ts index 6014a1d1d..0d6b9d799 100644 --- a/core/util/GlobalContext.test.ts +++ b/core/util/GlobalContext.test.ts @@ -75,7 +75,7 @@ describe("GlobalContext", () => { const value = globalContext.get("indexingPaused"); expect(value).toBeUndefined(); expect(consoleWarnMock).toHaveBeenCalledWith( - expect.stringContaining("Error parsing global context") + expect.stringContaining("Error parsing global context"), ); // Clean up @@ -99,7 +99,7 @@ describe("GlobalContext", () => { expect(value).toBeUndefined(); expect(consoleWarnMock).toHaveBeenCalledWith( - expect.stringContaining("Error updating global context") + expect.stringContaining("Error updating global context"), ); // Clean up @@ -113,10 +113,10 @@ describe("GlobalContext", () => { expect(globalContext.get("indexingPaused")).toBe(true); expect(globalContext.get("selectedTabAutocompleteModel")).toBe( - "test-model" + "test-model", ); expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe( - false + false, ); }); @@ -125,16 +125,7 @@ describe("GlobalContext", () => { expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true); }); - it("should handle curEmbeddingsProviderId correctly", () => { - globalContext.update("curEmbeddingsProviderId", "test-provider-id"); - expect(globalContext.get("curEmbeddingsProviderId")).toBe( - "test-provider-id" - ); - }); - it("should not crash or throw when getting a key that hasn't been set", () => { - expect( - globalContext.get("hasAlreadyCreatedAPromptFile") - ).toBeUndefined(); + expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBeUndefined(); }); -}); \ No newline at end of file +}); diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 1095234d8..5e4f7c6d7 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -12,7 +12,6 @@ export type GlobalContextType = { * * For VS Code users, it is unnecessary since we use transformers.js by default. */ - curEmbeddingsProviderId: string; hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 0bcd40fd9..f816369c8 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -17,8 +17,10 @@ import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; import { useAppSelector } from "../../redux/hooks"; +import { setConfig } from "../../redux/slices/configSlice"; function AddDocsDialog() { + const config = useAppSelector((store) => store.config.config); const posthog = usePostHog(); const dispatch = useDispatch(); @@ -125,6 +127,7 @@ function AddDocsDialog() { } const suggestedTitle = docsResult.details.title ?? docsResult.packageInfo.name; + if (docsResult.details?.docsLinkWarning) { setTitle(suggestedTitle); setStartUrl(docsResult.details.docsLink); @@ -143,6 +146,19 @@ function AddDocsDialog() { // Optimistic status update dispatch( + setConfig({ + ...config, + docs: [ + ...(config.docs?.filter( + (doc) => doc.startUrl !== docsResult.details.docsLink, + ) ?? []), + { + startUrl: docsResult.details.docsLink, + title: suggestedTitle, + faviconUrl: undefined, + }, + ], + }), updateIndexingStatus({ type: "docs", description: "Initializing", diff --git a/gui/src/components/indexing/DocsIndexingPeeks.tsx b/gui/src/components/indexing/DocsIndexingPeeks.tsx index f659b48f9..833c71430 100644 --- a/gui/src/components/indexing/DocsIndexingPeeks.tsx +++ b/gui/src/components/indexing/DocsIndexingPeeks.tsx @@ -3,6 +3,7 @@ import { IndexingStatus } from "core"; import { useMemo } from "react"; import { useNavigate } from "react-router-dom"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { useAppSelector } from "../../redux/hooks"; export interface DocsIndexingPeekProps { status: IndexingStatus; From ada10398f748aa1cd94d44ba42aeee741b3b7d31 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Dec 2024 15:26:19 -0800 Subject: [PATCH 03/33] embeddingsprovider docs column --- core/context/providers/DocsContextProvider.ts | 4 +- core/indexing/docs/DocsService.ts | 25 +++++------ core/indexing/docs/migrations.ts | 43 +++++++++++-------- 3 files changed, 38 insertions(+), 34 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 47542bc1c..9ee50c256 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -94,7 +94,7 @@ class DocsContextProvider extends BaseContextProvider { query, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); - if(!chunks?.length) { + if (!chunks?.length) { return []; } @@ -160,7 +160,7 @@ class DocsContextProvider extends BaseContextProvider { const docs = (await docsService.listMetadata()) ?? []; for (const { startUrl, title, favicon } of docs) { submenuItemsMap.set(startUrl, { - title,\ + title, id: startUrl, description: new URL(startUrl).hostname, icon: favicon, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 0af6aa28f..a65c65879 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -17,7 +17,6 @@ import DocsContextProvider from "../../context/providers/DocsContextProvider"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; -import { GlobalContext } from "../../util/GlobalContext"; import { IMessenger } from "../../protocol/messenger"; import { editConfigJson, @@ -87,7 +86,6 @@ export default class DocsService { public isSyncing: boolean = false; private docsIndexingQueue = new Set(); - private globalContext = new GlobalContext(); private lanceTableNamesSet = new Set(); private config!: ContinueConfig; @@ -144,7 +142,7 @@ export default class DocsService { this.config.docs?.forEach((doc) => { if (!doc.startUrl) { - console.error("Invalid config docs entry, no start"); + console.error("Invalid config docs entry, no start url", doc.title); return; } @@ -396,11 +394,12 @@ export default class DocsService { return; } } - this.docsIndexingQueue.add(startUrl); - - this.addToConfig(siteIndexingConfig); try { + this.docsIndexingQueue.add(startUrl); + + this.addToConfig(siteIndexingConfig); + this.handleStatusUpdate({ ...fixedStatus, status: "indexing", @@ -710,16 +709,11 @@ export default class DocsService { await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, - startUrl STRING NOT NULL UNIQUE, - favicon STRING + startUrl STRING NOT NULL, + favicon STRING, embeddingsProviderId STRING )`); - // embeddingsProviderId was added later - await db.exec(`ALTER TABLE ${DocsService.sqlitebTableName} - ADD COLUMN IF NOT EXISTS embeddingsProviderId STRING; - `); - this.sqliteDb = db; } @@ -756,6 +750,7 @@ export default class DocsService { const newConfigDocs = newConfig.docs || []; const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); + // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); @@ -955,7 +950,7 @@ export default class DocsService { private addToConfig(siteIndexingConfig: SiteIndexingConfig) { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file - const doesDocExist = this.config.docs?.some( + const doesEquivalentDocExist = this.config.docs?.some( (doc) => doc.startUrl === siteIndexingConfig.startUrl && doc.faviconUrl === siteIndexingConfig.faviconUrl && @@ -964,7 +959,7 @@ export default class DocsService { // doc.rootUrl === siteIndexingConfig.rootUrl, ); - if (!doesDocExist) { + if (!doesEquivalentDocExist) { editConfigJson((config) => ({ ...config, docs: [ diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index e3483d507..b84b0b842 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -27,41 +27,50 @@ export async function runLanceMigrations(table: Table) { export async function runSqliteMigrations(db: Database) { await new Promise((resolve) => { - migrate( + void migrate( "sqlite_modify_docs_columns_and_copy_to_config", async () => { try { const pragma = await db.all( - `PRAGMA table_info(${DocsService.sqlitebTableName})`, + `PRAGMA table_info(${DocsService.sqlitebTableName});`, ); const hasFaviconCol = pragma.some( (pragma) => pragma.name === "favicon", ); + if (!hasFaviconCol) { + await db.exec( + `ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB;`, + ); + } + const hasBaseUrlCol = pragma.some( (pragma) => pragma.name === "baseUrl", ); - - if (!hasFaviconCol) { - await db.exec( - `ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB`, - ); - } - if (hasBaseUrlCol) { await db.exec( - `ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl`, + `ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl;`, ); } - const sqliteDocs = await db.all< - Array> - >(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`); + const hasEmbeddingsProviderColumn = pragma.some( + (pragma) => pragma.name === "embeddingsProviderId", + ); + if (!hasEmbeddingsProviderColumn) { + // gotta just delete in this case since old docs will be unusable anyway + await db.exec(`DROP TABLE ${DocsService.sqlitebTableName};`); + } - editConfigJson((config) => ({ - ...config, - docs: [...(config.docs || []), ...sqliteDocs], - })); + const needsToUpdateConfig = !hasFaviconCol || hasBaseUrlCol; + if (needsToUpdateConfig) { + const sqliteDocs = await db.all< + Array> + >(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`); + editConfigJson((config) => ({ + ...config, + docs: [...(config.docs || []), ...sqliteDocs], + })); + } } finally { resolve(undefined); } From 82fd94d6b1ab64473707f32a63ef3c46ac9cd5fb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Dec 2024 15:51:25 -0800 Subject: [PATCH 04/33] config/addContextProvider message --- core/core.ts | 13 ++++++- core/indexing/docs/DocsService.ts | 7 +++- core/protocol/core.ts | 2 + core/protocol/passThrough.ts | 1 + .../toolWindow/ContinueBrowser.kt | 1 + .../indexing/DocsIndexingStatuses.tsx | 38 ++++++++++++++++++- 6 files changed, 58 insertions(+), 4 deletions(-) diff --git a/core/core.ts b/core/core.ts index bea254c81..3d00db55e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -12,7 +12,12 @@ import { setupLocalConfigAfterFreeTrial, setupQuickstartConfig, } from "./config/onboarding"; -import { addModel, addOpenAIKey, deleteModel } from "./config/util"; +import { + addContextProvider, + addModel, + addOpenAIKey, + deleteModel, +} from "./config/util"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; @@ -276,6 +281,10 @@ export class Core { return this.configHandler.listProfiles(); }); + on("config/addContextProvider", async (msg) => { + addContextProvider(msg.data); + }); + // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); @@ -794,7 +803,7 @@ export class Core { }); on("indexing/setPaused", async (msg) => { if (msg.data.type === "docs") { - // this.docsService.setPaused(msg.data.id, msg.data.paused); + // this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet } }); on("docs/getSuggestedDocs", async (msg) => { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index a65c65879..d81a4ec19 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -345,6 +345,10 @@ export default class DocsService { siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, ): Promise { + if (this.config.disableIndexing) { + console.warn("Attempting to add/index docs when indexing is disabled"); + return; + } const { startUrl } = siteIndexingConfig; const canUsePreindexedDocs = await this.canUsePreindexedDocs(); @@ -352,7 +356,8 @@ export default class DocsService { const preIndexedDoc = preIndexedDocs[startUrl]; const isPreIndexedDoc = !!preIndexedDoc; if (isPreIndexedDoc) { - console.warn("Can only use pre"); + console.warn("Can not override pre-indexed start urls"); + return; } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 9a7d85510..520f2dc41 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -6,6 +6,7 @@ import type { ChatMessage, ContextItem, ContextItemWithId, + ContextProviderWithParams, ContextSubmenuItem, DiffLine, FileSymbolMap, @@ -66,6 +67,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { { config: BrowserSerializedContinueConfig; profileId: string }, ]; "config/deleteModel": [{ title: string }, void]; + "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, BrowserSerializedContinueConfig]; "config/listProfiles": [undefined, ProfileDescription[]]; "config/openProfile": [{ profileId: string | undefined }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 0bbb5699a..756b3db54 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -16,6 +16,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "history/save", "devdata/log", "config/addModel", + "config/addContextProvider", "config/newPromptFile", "config/ideSettingsUpdate", "config/getSerializedProfileInfo", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index d682b8a3a..5523bdeff 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -26,6 +26,7 @@ class ContinueBrowser(val project: Project, url: String) { "history/save", "devdata/log", "config/addModel", + "config/addContextProvider", "config/newPromptFile", "config/ideSettingsUpdate", "config/getSerializedProfileInfo", diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx index 76feb21e0..9a9ffb4df 100644 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -4,11 +4,24 @@ import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import AddDocsDialog from "../dialogs/AddDocsDialog"; import DocsIndexingStatus from "./DocsIndexingStatus"; import { useAppSelector } from "../../redux/hooks"; +import { useContext, useMemo } from "react"; +import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; function DocsIndexingStatuses() { const dispatch = useDispatch(); const config = useAppSelector((store) => store.config.config); - const configDocs = config.docs ?? []; + const ideMessenger = useContext(IdeMessengerContext); + + const hasDocsProvider = useMemo(() => { + return !!config.contextProviders?.some( + (provider) => provider.title === "docs", + ); + }, [config]); + + const configDocs = useMemo(() => { + return config.docs ?? []; + }, [config]); return (
@@ -33,6 +46,29 @@ function DocsIndexingStatuses() { : "No docs yet"}
+ {!hasDocsProvider && ( +
+
+
+ +
+ + @docs is not in your config + +
+ { + ideMessenger.post("config/addContextProvider", { + name: "docs", + params: {}, + }); + }} + > + Add @docs to my config + +
+ )}
{configDocs.length === 0 && ( Date: Fri, 20 Dec 2024 16:46:19 -0800 Subject: [PATCH 05/33] messaging --- core/indexing/docs/DocsService.ts | 23 +++++++---- .../indexing/DocsIndexingStatus.tsx | 41 ++++++++++--------- .../indexing/DocsIndexingStatuses.tsx | 15 ++++--- .../IndexingProgressSubtext.tsx | 2 +- 4 files changed, 47 insertions(+), 34 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index d81a4ec19..7a35e8f24 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -193,8 +193,15 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); } - isAborted(startUrl: string) { - return this.statuses.get(startUrl)?.status === "aborted"; + shouldCancel(startUrl: string) { + const isAborted = this.statuses.get(startUrl)?.status === "aborted"; + if (isAborted) { + return true; + } + if (this.config.disableIndexing) { + this.abort(startUrl); + return true; + } } // NOTE Pausing not supported for docs yet @@ -421,7 +428,7 @@ export default class DocsService { estimatedProgress += 1 / 2 ** (processedPages + 1); // NOTE - during "indexing" phase, check if aborted before each status update - if (this.isAborted(startUrl)) { + if (this.shouldCancel(startUrl)) { return; } this.handleStatusUpdate({ @@ -459,7 +466,7 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - if (this.isAborted(startUrl)) { + if (this.shouldCancel(startUrl)) { return; } this.handleStatusUpdate({ @@ -496,7 +503,7 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - if (this.isAborted(startUrl)) { + if (this.shouldCancel(startUrl)) { return; } this.handleStatusUpdate({ @@ -514,7 +521,7 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - if (this.isAborted(startUrl)) { + if (this.shouldCancel(startUrl)) { return; } this.handleStatusUpdate({ @@ -532,7 +539,7 @@ export default class DocsService { const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); - if (this.isAborted(startUrl)) { + if (this.shouldCancel(startUrl)) { return; } this.handleStatusUpdate({ @@ -551,7 +558,7 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - if (this.isAborted(startUrl)) { + if (this.shouldCancel(startUrl)) { return; } this.handleStatusUpdate({ diff --git a/gui/src/components/indexing/DocsIndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx index 31604874f..7f11d9dfa 100644 --- a/gui/src/components/indexing/DocsIndexingStatus.tsx +++ b/gui/src/components/indexing/DocsIndexingStatus.tsx @@ -28,6 +28,7 @@ const STATUS_TO_ICON: Record = { }; function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { + const config = useAppSelector((store) => store.config.config); const ideMessenger = useContext(IdeMessengerContext); const dispatch = useAppDispatch(); @@ -146,28 +147,30 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {
{}, - pending: () => {}, - }[status?.status] + config.disableIndexing + ? undefined + : { + complete: reIndex, + indexing: abort, + failed: reIndex, + aborted: reIndex, + paused: () => {}, + pending: () => {}, + }[status?.status] } > - { - { - complete: "Click to re-index", - indexing: "Cancel indexing", - failed: "Click to retry", - aborted: "Click to index", - paused: "", - pending: "", - }[status?.status] - } + {config.disableIndexing + ? "Indexing disabled" + : { + complete: "Click to re-index", + indexing: "Cancel indexing", + failed: "Click to retry", + aborted: "Click to index", + paused: "", + pending: "", + }[status?.status]} diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx index 9a9ffb4df..9c52ab0af 100644 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -41,12 +41,13 @@ function DocsIndexingStatuses() { ) : null}
- {configDocs.length - ? "Manage your documentation sources" - : "No docs yet"} - -
- {!hasDocsProvider && ( + {hasDocsProvider ? ( + configDocs.length ? ( + "Manage your documentation sources" + ) : ( + "No docs yet" + ) + ) : (
@@ -69,6 +70,8 @@ function DocsIndexingStatuses() {
)} + +
{configDocs.length === 0 && ( Date: Fri, 20 Dec 2024 18:30:52 -0800 Subject: [PATCH 06/33] handle config changes mid-index --- core/indexing/docs/DocsService.ts | 47 ++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 7a35e8f24..ab2fb52ab 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -181,27 +181,37 @@ export default class DocsService { } abort(startUrl: string) { - const status = this.statuses.get(startUrl); - if (status) { - this.handleStatusUpdate({ - ...status, - status: "aborted", - progress: 0, - description: "Canceled", - }); + if (this.docsIndexingQueue.has(startUrl)) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: "aborted", + progress: 0, + description: "Canceled", + }); + } + this.docsIndexingQueue.delete(startUrl); } - this.docsIndexingQueue.delete(startUrl); } - shouldCancel(startUrl: string) { + shouldCancel(startUrl: string, startedWithEmbedder: string) { + // Check if aborted const isAborted = this.statuses.get(startUrl)?.status === "aborted"; if (isAborted) { return true; } + // Handle indexing disabled change mid-indexing if (this.config.disableIndexing) { this.abort(startUrl); return true; } + // Handle embeddings provider change mid-indexing + if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) { + this.abort(startUrl); + return true; + } + return false; } // NOTE Pausing not supported for docs yet @@ -374,6 +384,7 @@ export default class DocsService { } const embeddingsProvider = await this.getEmbeddingsProvider(); + const startedWithEmbedder = this.config.embeddingsProvider.embeddingId; const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values @@ -428,7 +439,7 @@ export default class DocsService { estimatedProgress += 1 / 2 ** (processedPages + 1); // NOTE - during "indexing" phase, check if aborted before each status update - if (this.shouldCancel(startUrl)) { + if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; } this.handleStatusUpdate({ @@ -466,7 +477,7 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - if (this.shouldCancel(startUrl)) { + if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; } this.handleStatusUpdate({ @@ -503,7 +514,7 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - if (this.shouldCancel(startUrl)) { + if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; } this.handleStatusUpdate({ @@ -521,7 +532,7 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - if (this.shouldCancel(startUrl)) { + if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; } this.handleStatusUpdate({ @@ -539,7 +550,7 @@ export default class DocsService { const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); - if (this.shouldCancel(startUrl)) { + if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; } this.handleStatusUpdate({ @@ -558,7 +569,7 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - if (this.shouldCancel(startUrl)) { + if (this.shouldCancel(startUrl, startedWithEmbedder)) { return; } this.handleStatusUpdate({ @@ -577,7 +588,7 @@ export default class DocsService { console.error("Error indexing docs", e); this.handleStatusUpdate({ ...fixedStatus, - description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + description: `Error getting docs from: ${siteIndexingConfig.startUrl}`, status: "failed", progress: 1, }); @@ -785,7 +796,9 @@ export default class DocsService { const oldConfigDoc = oldConfigDocs.find( (d) => d.startUrl === doc.startUrl, ); + // const currentStatus = this.statuses.get(doc.startUrl); if ( + // currentStatus?.status === "complete" && oldConfigDoc && (oldConfigDoc.maxDepth !== doc.maxDepth || oldConfigDoc.title !== doc.title || From e270b206808a35d5156f851fe66c1e1d13752812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E4=BF=8A=E6=9D=B0?= Date: Wed, 25 Dec 2024 17:37:49 +0800 Subject: [PATCH 07/33] Remove the extra "+" sign from the IDEA shortcut --- docs/docs/getting-started/install.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/getting-started/install.md b/docs/docs/getting-started/install.md index 20aa52baa..3729edbfd 100644 --- a/docs/docs/getting-started/install.md +++ b/docs/docs/getting-started/install.md @@ -18,7 +18,7 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ## JetBrains -1. Open your JetBrains IDE and open **Settings** using Ctrl + +Alt + S +1. Open your JetBrains IDE and open **Settings** using Ctrl + Alt + S 2. Select **Plugins** on the sidebar and search for "Continue" in the marketplace 3. Click `Install`, which will cause the Continue logo to show up on the right toolbar From decd04eddd4965b9f76c7a9a3abd276d8d2e1692 Mon Sep 17 00:00:00 2001 From: liuk Date: Wed, 25 Dec 2024 23:03:53 +0800 Subject: [PATCH 08/33] fix: Skip duplicate checks at document end or blank text Prevent autocomplete from truncating when the cursor is at the end of the document or when the text after the cursor is blank. --- .../autocomplete/AutocompleteService.kt | 7 +++++++ 1 file changed, 7 insertions(+) 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 6279e03f7..2dc6ba021 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 @@ -120,6 +120,10 @@ class AutocompleteService(private val project: Project) { return ApplicationManager.getApplication().runReadAction { val document = editor.document val caretOffset = editor.caretModel.offset + + // Don't care about it if it's at the end of the document + if (caretOffset == document.textLength) return@runReadAction completion + val N = 10 var textAfterCursor = if (caretOffset + N <= document.textLength) { document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N)) @@ -127,6 +131,9 @@ class AutocompleteService(private val project: Project) { document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength)) } + // Avoid truncating the completion text when the text after the cursor is blank + if (textAfterCursor.isBlank()) return@runReadAction completion + // Determine the index of a newline character within the text following the cursor. val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') // If a newline character is found and the current line is not empty, truncate the text at that point. From 1a1585e8800cb8f33425b6ddb4d83d107da0c7b9 Mon Sep 17 00:00:00 2001 From: Prajna Kandarpa Date: Fri, 27 Dec 2024 13:25:21 +0530 Subject: [PATCH 09/33] minor documentationtip for aws bedrock --- .../model-providers/top-level/bedrock.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index fb88d5ae0..67d919a2f 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -22,6 +22,22 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. ] } ``` +> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.` + +> You can fix this using the following config.json +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "bedrock", + "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0", + "region": "us-east-1", + "profile": "bedrock" + } + ] +} +``` ## Autocomplete model From 54e41d6de6eb7685425ec79241894a787a4260b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:25:22 +0100 Subject: [PATCH 10/33] Update model-setup.md --- docs/docs/autocomplete/model-setup.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index 8aae88c75..221c17ddd 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -31,14 +31,14 @@ For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers ```json title="config.json"" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", - "model": "qwen2.5-coder:1.5b", + "title": "Qwen2.5-Coder 1.5B Base", + "model": "qwen2.5-coder:1.5b-base", "provider": "ollama" } } ``` -Have more compute? Use `qwen2.5-coder:7b` for potentially higher-quality suggestions. +Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions. :::note From 11b657a1546d2e03814205a4de0158ccdf65bf15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:30:37 +0100 Subject: [PATCH 11/33] Update model-setup.md Fixed typo for LM studio --- docs/docs/autocomplete/model-setup.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index 221c17ddd..fc5233baa 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -42,7 +42,7 @@ Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality su :::note -For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/wen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. +For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. ::: From 8c6e33ad803ac5009b0ce7d6280ad05ac6dace03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:31:32 +0100 Subject: [PATCH 12/33] Update autocomplete.md --- docs/docs/customize/model-types/autocomplete.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index d85920605..7f5abc8e2 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -13,4 +13,4 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). -If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). +If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B-base` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). From fb9db1e12883435fad5cc6610312ff3240ef6803 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:32:25 +0100 Subject: [PATCH 13/33] Update ollama.md --- docs/docs/customize/model-providers/top-level/ollama.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index ed96ac385..c307a9344 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -23,14 +23,14 @@ We recommend configuring **Llama3.1 8B** as your chat model. ## Autocomplete model -We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. +We recommend configuring **Qwen2.5-Coder 1.5B-base** as your autocomplete model. ```json title="config.json" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", + "title": "Qwen2.5-Coder 1.5B-base", "provider": "ollama", - "model": "qwen2.5-coder:1.5b" + "model": "qwen2.5-coder:1.5b-base" } } ``` From fa18259a34a3b3940fbbe1a019136b94aa8c260f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:08:48 +0100 Subject: [PATCH 14/33] Update README.md --- core/autocomplete/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 1136b54ab..ab6e9adfb 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -7,7 +7,7 @@ Continue now provides support for tab autocomplete in [VS Code](https://marketpl We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: ```bash -ollama run qwen2.5-coder:1.5b +ollama run qwen2.5-coder:1.5b-base ``` Once it has been downloaded, you should begin to see completions in VS Code. @@ -101,7 +101,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b", + "model": "qwen2.5-coder:1.5b-base", "apiBase": "https://" }, "tabAutocompleteOptions": { @@ -123,9 +123,9 @@ Follow these steps to ensure that everything is set up correctly: 1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar). 2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded. +3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. +5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete. 6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. From 96200c094f89141ac33e10e9daa0a78ff2ef30e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:22:10 +0100 Subject: [PATCH 15/33] removed base from title --- docs/docs/autocomplete/model-setup.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index fc5233baa..2312123a0 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -31,7 +31,7 @@ For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers ```json title="config.json"" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B Base", + "title": "Qwen2.5-Coder 1.5B", "model": "qwen2.5-coder:1.5b-base", "provider": "ollama" } From 2966c9c57d7b4317504f1e8952d2367fc3d221a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:24:21 +0100 Subject: [PATCH 16/33] removed base since its a name and not specific model --- docs/docs/customize/model-types/autocomplete.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index 7f5abc8e2..d85920605 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -13,4 +13,4 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). -If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B-base` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). +If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). From 5516ba86ff0cbed6b0777380c273805094c9ac20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:25:26 +0100 Subject: [PATCH 17/33] removed base from title --- docs/docs/customize/model-providers/top-level/ollama.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index c307a9344..e1f3e53e8 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -23,12 +23,12 @@ We recommend configuring **Llama3.1 8B** as your chat model. ## Autocomplete model -We recommend configuring **Qwen2.5-Coder 1.5B-base** as your autocomplete model. +We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. ```json title="config.json" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B-base", + "title": "Qwen2.5-Coder 1.5B", "provider": "ollama", "model": "qwen2.5-coder:1.5b-base" } From abf1d89a3966498d7529ae2ca1747ac6bb1f9b2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 22:24:09 +0100 Subject: [PATCH 18/33] added -base to the qwen-modelse --- docs/docs/customize/deep-dives/autocomplete.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 4aa5f768d..221a6d49f 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -23,7 +23,7 @@ If you want to have the best autocomplete experience, we recommend using Codestr If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: ```bash -ollama run qwen2.5-coder:1.5b +ollama run qwen2.5-coder:1.5b-base ``` Once it has been downloaded, you should begin to see completions in VS Code. @@ -37,7 +37,7 @@ All of the configuration options available for chat models are available to use "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b", + "model": "qwen2.5-coder:1.5b-base", "apiBase": "https://" }, ... @@ -76,7 +76,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b", + "model": "qwen2.5-coder:1.5b-base", "apiBase": "https://" }, "tabAutocompleteOptions": { @@ -99,7 +99,7 @@ Follow these steps to ensure that everything is set up correctly: 1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar, and in JetBrains by going to Settings -> Tools -> Continue). 2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded. +3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. 5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. 6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) From abfffd831abe960b4881472b2c7c3ca94f187a81 Mon Sep 17 00:00:00 2001 From: "Johnny.H" Date: Thu, 2 Jan 2025 15:53:12 +0800 Subject: [PATCH 19/33] fix `renderInlineAs` not working in `HttpContextProvider` --- core/context/providers/HttpContextProvider.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 05a50e15d..7b7228eee 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -22,6 +22,9 @@ class HttpContextProvider extends BaseContextProvider { this.options.description || "Retrieve a context item from a custom server", type: "normal", + renderInlineAs: + this.options.renderInlineAs || + HttpContextProvider.description.renderInlineAs, }; } From 0001e275e14b26aaabadbeb30ac4fdeb843d6122 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 2 Jan 2025 15:29:12 -0500 Subject: [PATCH 20/33] update reference --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 527820556..b61357649 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -88,7 +88,7 @@ Specifies options for tab autocompletion behavior. - `debounceDelay`: Delay (in ms) before triggering autocomplete. - `maxSuffixPercentage`: Maximum percentage of prompt for suffix. - `prefixPercentage`: Percentage of input for prefix. -- `template`: Template string for autocomplete, using Mustache templating. +- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. - `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). - `useCache`: If `true`, caches completions. - `onlyMyCode`: If `true`, only includes code within the repository. From 9cc844fb178a77667a4cd49b0d671f9631af67af Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 2 Jan 2025 15:33:08 -0500 Subject: [PATCH 21/33] update config_schema.json --- extensions/vscode/config_schema.json | 108 +++++++++++++-------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f2c98642f..c9df4e976 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2805,10 +2805,7 @@ "type": "object", "properties": { "model": { - "enum": [ - "cohere.rerank-v3-5:0", - "amazon.rerank-v1:0" - ] + "enum": ["cohere.rerank-v3-5:0", "amazon.rerank-v1:0"] } }, "required": ["model"] @@ -3132,62 +3129,65 @@ "description": "Allow tool use. Currently only supported with Claude 3.5 Sonnet", "default": true }, - "modelContextProtocolServer": { - "type": "object", - "properties": { - "transport": { - "oneOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["stdio"] - }, - "command": { - "type": "string" - }, - "args": { - "type": "array", - "items": { + "modelContextProtocolServers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "transport": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["stdio"] + }, + "command": { "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } } - } - }, - "required": ["type", "command", "args"] - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["websocket"] }, - "url": { - "type": "string", - "format": "uri" - } + "required": ["type", "command", "args"] }, - "required": ["type", "url"] - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["sse"] + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["websocket"] + }, + "url": { + "type": "string", + "format": "uri" + } }, - "url": { - "type": "string", - "format": "uri" - } + "required": ["type", "url"] }, - "required": ["type", "url"] - } - ] - } - }, - "required": ["transport"] + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["sse"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] + } + ] + } + }, + "required": ["transport"] + } } } } From 0cf152ede652d975fd774faa40494020c7514196 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 17:41:28 -0600 Subject: [PATCH 22/33] feat: create SVG tooltip --- .../vscode/src/activation/InlineTipManager.ts | 427 ++++++++++++++++++ extensions/vscode/src/activation/activate.ts | 3 +- .../vscode/src/activation/inlineTips.ts | 122 ----- .../components/indexing/ChatIndexingPeeks.tsx | 2 +- package-lock.json | 8 + package.json | 3 + 6 files changed, 441 insertions(+), 124 deletions(-) create mode 100644 extensions/vscode/src/activation/InlineTipManager.ts delete mode 100644 extensions/vscode/src/activation/inlineTips.ts diff --git a/extensions/vscode/src/activation/InlineTipManager.ts b/extensions/vscode/src/activation/InlineTipManager.ts new file mode 100644 index 000000000..b335cc9dd --- /dev/null +++ b/extensions/vscode/src/activation/InlineTipManager.ts @@ -0,0 +1,427 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { EXTENSION_NAME } from "core/control-plane/env"; +// @ts-ignore +import svgBuilder from "svg-builder"; +import * as vscode from "vscode"; + +import { getTheme } from "../util/getTheme"; +import { getMetaKeyLabel, getMetaKeyName } from "../util/util"; + +const SVG_CONFIG = { + stroke: "#999998", + strokeWidth: 1, + shortcutColor: "#999998", + filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))", + radius: 4, + leftMargin: 40, + debounceDelay: 500, + chatLabel: "Add to Chat", + chatShortcut: `${getMetaKeyLabel()}L`, + editLabel: "Edit", + editShortcut: `${getMetaKeyLabel()}I`, + + get fontSize() { + return Math.ceil( + (vscode.workspace.getConfiguration("editor").get("fontSize") ?? + 14) * 0.7, + ); + }, + get fontFamily() { + return ( + vscode.workspace.getConfiguration("editor").get("fontFamily") || + "helvetica" + ); + }, + get paddingY() { + return Math.ceil(this.fontSize * 0.4); + }, + get paddingX() { + return Math.ceil(this.fontSize * 0.8); + }, + get gap() { + return this.fontSize * 2.5; + }, + get tipWidth() { + return ( + this.editShortcutX + + this.getEstimatedTextWidth(this.editShortcut) + + this.paddingX + ); + }, + get tipHeight() { + return this.fontSize + this.paddingY * 2; + }, + get textY() { + return this.tipHeight / 2 + this.fontSize * 0.35; + }, + get chatLabelX() { + return this.paddingX; + }, + get chatShortcutX() { + return this.chatLabelX + this.getEstimatedTextWidth(this.chatLabel) + 4; + }, + get editLabelX() { + return this.chatShortcutX + this.gap; + }, + get editShortcutX() { + return this.editLabelX + this.getEstimatedTextWidth(this.editLabel) + 4; + }, + getEstimatedTextWidth(text: string): number { + return text.length * this.fontSize * 0.6; + }, +} as const; + +export class InlineTipManager { + private static instance: InlineTipManager; + + private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"]; + private readonly hideCommand = "continue.hideInlineTip"; + private svgTooltip: vscode.Uri | undefined = undefined; + + private debounceTimer: NodeJS.Timeout | undefined; + private lastActiveEditor?: vscode.TextEditor; + private theme = getTheme(); + private svgTooltipDecoration = this.createSvgTooltipDecoration(); + private emptyFileTooltipDecoration = this.createEmptyFileTooltipDecoration(); + + public static getInstance(): InlineTipManager { + if (!InlineTipManager.instance) { + InlineTipManager.instance = new InlineTipManager(); + } + return InlineTipManager.instance; + } + + private constructor() { + this.createSvgTooltip(); + this.setupSvgTipListeners(); + } + + public setupInlineTips(context: vscode.ExtensionContext) { + context.subscriptions.push( + vscode.window.onDidChangeTextEditorSelection((e) => { + this.handleSelectionChange(e); + }), + ); + + this.setupEmptyFileTips(context); + + context.subscriptions.push(this); + } + + public handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { + const selection = e.selections[0]; + const editor = e.textEditor; + + if (selection.isEmpty || !this.shouldRenderTip(editor.document.uri)) { + editor.setDecorations(this.svgTooltipDecoration, []); + return; + } + + this.debouncedSelectionChange(editor, selection); + } + + public dispose() { + this.svgTooltipDecoration.dispose(); + this.emptyFileTooltipDecoration.dispose(); + + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + } + } + + private debouncedSelectionChange( + editor: vscode.TextEditor, + selection: vscode.Selection, + ) { + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + } + + this.debounceTimer = setTimeout(() => { + // Clear decoration from previous editor + if (this.lastActiveEditor && this.lastActiveEditor !== editor) { + this.lastActiveEditor.setDecorations(this.svgTooltipDecoration, []); + } + + this.lastActiveEditor = editor; + + this.updateTooltipPosition(editor, selection); + }, SVG_CONFIG.debounceDelay); + } + + private setupSvgTipListeners() { + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("workbench.colorTheme")) { + this.theme = getTheme(); + this.createSvgTooltip(); + } + }); + + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("editor.fontSize")) { + this.createSvgTooltip(); + } + }); + } + + private shouldRenderTip(uri: vscode.Uri): boolean { + const isAllowedUri = + !this.excludedURIPrefixes.some((prefix) => + uri.toString().startsWith(prefix), + ) && uri.scheme !== "comment"; + + const isEnabled = + !!vscode.workspace + .getConfiguration(EXTENSION_NAME) + .get("showInlineTip") === true; + + return isAllowedUri && isEnabled; + } + + private setupEmptyFileTips(context: vscode.ExtensionContext) { + context.subscriptions.push( + vscode.window.onDidChangeActiveTextEditor((editor) => { + if ( + editor?.document.getText() === "" && + this.shouldRenderTip(editor.document.uri) + ) { + editor.setDecorations(this.emptyFileTooltipDecoration, [ + { + range: new vscode.Range( + new vscode.Position(0, Number.MAX_VALUE), + new vscode.Position(0, Number.MAX_VALUE), + ), + }, + ]); + } + }), + ); + + context.subscriptions.push( + vscode.workspace.onDidChangeTextDocument((e) => { + if ( + e.document.getText() === "" && + this.shouldRenderTip(e.document.uri) + ) { + vscode.window.visibleTextEditors.forEach((editor) => { + editor.setDecorations(this.emptyFileTooltipDecoration, [ + { + range: new vscode.Range( + new vscode.Position(0, Number.MAX_VALUE), + new vscode.Position(0, Number.MAX_VALUE), + ), + }, + ]); + }); + } else { + vscode.window.visibleTextEditors.forEach((editor) => { + editor.setDecorations(this.emptyFileTooltipDecoration, []); + }); + } + }), + ); + } + + private createEmptyFileTooltipDecoration() { + return vscode.window.createTextEditorDecorationType({ + after: { + contentText: `Use ${getMetaKeyName()} + I to generate code`, + color: "#888", + margin: "2em 0 0 0", + fontStyle: "italic", + }, + }); + } + + private createSvgTooltipDecoration() { + return vscode.window.createTextEditorDecorationType({ + after: { + contentIconPath: this.svgTooltip, + margin: `-2.5px 0 0 ${SVG_CONFIG.leftMargin}px`, + width: `${SVG_CONFIG.tipWidth}px`, + }, + }); + } + + private createSvgTooltip() { + const baseTextConfig = { + y: SVG_CONFIG.textY, + "font-family": SVG_CONFIG.fontFamily, + "font-size": SVG_CONFIG.fontSize, + }; + + if (!this.theme) { + return; + } + + try { + const svgContent = svgBuilder + .width(SVG_CONFIG.tipWidth) + .height(SVG_CONFIG.tipHeight) + // Main rectangle + .rect({ + x: 0, + y: 0, + width: SVG_CONFIG.tipWidth, + height: SVG_CONFIG.tipHeight, + rx: SVG_CONFIG.radius, + ry: SVG_CONFIG.radius, + fill: this.theme.colors["editor.background"], + stroke: SVG_CONFIG.stroke, + "stroke-width": SVG_CONFIG.strokeWidth, + filter: SVG_CONFIG.filter, + }) + // Chat + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.chatLabelX, + fill: this.theme.colors["editor.foreground"], + }, + SVG_CONFIG.chatLabel, + ) + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.chatShortcutX, + fill: SVG_CONFIG.shortcutColor, + }, + SVG_CONFIG.chatShortcut, + ) + // Edit + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.editLabelX, + fill: this.theme.colors["editor.foreground"], + }, + SVG_CONFIG.editLabel, + ) + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.editShortcutX, + fill: SVG_CONFIG.shortcutColor, + }, + SVG_CONFIG.editShortcut, + ) + .render(); + + const dataUri = `data:image/svg+xml;base64,${Buffer.from(svgContent).toString("base64")}`; + + this.svgTooltip = vscode.Uri.parse(dataUri); + this.svgTooltipDecoration.dispose(); + this.svgTooltipDecoration = this.createSvgTooltipDecoration(); + } catch (error) { + console.error("Error creating SVG for inline tip:", error); + } + } + + private buildHideTooltipHoverMsg() { + const hoverMarkdown = new vscode.MarkdownString( + `[Disable](command:${this.hideCommand})`, + ); + + hoverMarkdown.isTrusted = true; + hoverMarkdown.supportHtml = true; + return hoverMarkdown; + } + + /** + * Calculates tooltip position using these rules: + * 1. For single-line selection: Place after the line's content + * 2. For multi-line selection: Place after the longer line between: + * - The first non-empty selected line + * - The line above the selection + * Returns null if selection is empty or contains only empty lines + */ + private calculateTooltipPosition( + editor: vscode.TextEditor, + selection: vscode.Selection, + ): vscode.Position | null { + const document = editor.document; + + // Get selection info + const startLine = selection.start.line; + const endLine = selection.end.line; + const isFullLineSelection = + selection.start.character === 0 && + (selection.end.line > selection.start.line + ? selection.end.character === 0 + : selection.end.character === + document.lineAt(selection.end.line).text.length); + + // Helper functions + const isLineEmpty = (lineNumber: number): boolean => { + return document.lineAt(lineNumber).text.trim().length === 0; + }; + + const getLineEndChar = (lineNumber: number): number => { + return document.lineAt(lineNumber).text.trimEnd().length; + }; + + // If single empty line selected and not full line selection, return null + if ( + startLine === endLine && + isLineEmpty(startLine) && + !isFullLineSelection + ) { + return null; + } + + // Find topmost non-empty line + let topNonEmptyLine = startLine; + while (topNonEmptyLine <= endLine && isLineEmpty(topNonEmptyLine)) { + topNonEmptyLine++; + } + + // If all lines empty, return null + if (topNonEmptyLine > endLine) { + return null; + } + + const OFFSET = 4; // Characters to offset from end of line + + // Single line or full line selection + if (isFullLineSelection || startLine === endLine) { + return new vscode.Position( + topNonEmptyLine, + getLineEndChar(topNonEmptyLine) + OFFSET, + ); + } + + // Check line above selection + const lineAboveSelection = Math.max(0, startLine - 1); + + // Get end positions + const topNonEmptyEndChar = getLineEndChar(topNonEmptyLine); + const lineAboveEndChar = getLineEndChar(lineAboveSelection); + + const baseEndChar = Math.max(topNonEmptyEndChar, lineAboveEndChar); + + return new vscode.Position(topNonEmptyLine, baseEndChar + OFFSET); + } + + private updateTooltipPosition( + editor: vscode.TextEditor, + selection: vscode.Selection, + ) { + const position = this.calculateTooltipPosition(editor, selection); + + if (!position) { + editor.setDecorations(this.svgTooltipDecoration, []); + return; + } + + editor.setDecorations(this.svgTooltipDecoration, [ + { + range: new vscode.Range(position, position), + hoverMessage: [this.buildHideTooltipHoverMsg()], + }, + ]); + } +} + +export default function setupInlineTips(context: vscode.ExtensionContext) { + InlineTipManager.getInstance().setupInlineTips(context); +} diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 7aa0ae4a9..d40aee740 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -7,7 +7,8 @@ import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; -import { setupInlineTips } from "./inlineTips"; +import setupInlineTips from "./InlineTipManager"; +// import { setupInlineTips } from "./inlineTips"; export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts deleted file mode 100644 index 49a8adf29..000000000 --- a/extensions/vscode/src/activation/inlineTips.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { EXTENSION_NAME } from "core/control-plane/env"; -import * as vscode from "vscode"; - -import { getMetaKeyName } from "../util/util"; - -const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ - after: { - contentText: `Add to chat (${getMetaKeyName()}+L) | Edit highlighted code (${getMetaKeyName()}+I).`, - color: "#888", - margin: "0 0 0 6em", - fontWeight: "bold", - }, -}); - -function showInlineTip() { - return vscode.workspace - .getConfiguration(EXTENSION_NAME) - .get("showInlineTip"); -} - -function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { - const selection = e.selections[0]; - const editor = e.textEditor; - - if (editor.document.uri.toString().startsWith("output:")) { - return; - } - - if (selection.isEmpty || showInlineTip() === false) { - editor.setDecorations(inlineTipDecoration, []); - return; - } - - const line = Math.max(0, selection.start.line - 1); - - const hoverMarkdown = new vscode.MarkdownString( - `Click [here](command:continue.hideInlineTip) to hide these suggestions`, - ); - hoverMarkdown.isTrusted = true; - hoverMarkdown.supportHtml = true; - editor.setDecorations(inlineTipDecoration, [ - { - range: new vscode.Range( - new vscode.Position(line, Number.MAX_VALUE), - new vscode.Position(line, Number.MAX_VALUE), - ), - hoverMessage: [hoverMarkdown], - }, - ]); -} - -const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType( - { - after: { - contentText: `Use ${getMetaKeyName()}+I to generate code`, - color: "#888", - margin: "2em 0 0 0", - fontStyle: "italic", - }, - }, -); - -let selectionChangeDebounceTimer: NodeJS.Timeout | undefined; - -export function setupInlineTips(context: vscode.ExtensionContext) { - context.subscriptions.push( - vscode.window.onDidChangeTextEditorSelection((e) => { - if (selectionChangeDebounceTimer) { - clearTimeout(selectionChangeDebounceTimer); - } - selectionChangeDebounceTimer = setTimeout(() => { - handleSelectionChange(e); - }, 200); - }), - ); - - context.subscriptions.push( - vscode.window.onDidChangeActiveTextEditor((editor) => { - if (editor?.document.getText() === "" && showInlineTip() === true) { - if ( - editor.document.uri.toString().startsWith("output:") || - editor.document.uri.scheme === "comment" - ) { - return; - } - - editor.setDecorations(emptyFileTooltipDecoration, [ - { - range: new vscode.Range( - new vscode.Position(0, Number.MAX_VALUE), - new vscode.Position(0, Number.MAX_VALUE), - ), - }, - ]); - } - }), - ); - - context.subscriptions.push( - vscode.workspace.onDidChangeTextDocument((e) => { - if (e.document.uri.toString().startsWith("vscode://inline-chat")) { - return; - } - if (e.document.getText() === "" && showInlineTip() === true) { - vscode.window.visibleTextEditors.forEach((editor) => { - editor.setDecorations(emptyFileTooltipDecoration, [ - { - range: new vscode.Range( - new vscode.Position(0, Number.MAX_VALUE), - new vscode.Position(0, Number.MAX_VALUE), - ), - }, - ]); - }); - } else { - vscode.window.visibleTextEditors.forEach((editor) => { - editor.setDecorations(emptyFileTooltipDecoration, []); - }); - } - }), - ); -} diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index 1ec1076c0..66936597d 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -62,7 +62,7 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) {
{ dispatch( setIndexingChatPeekHidden({ type: state.type, hidden: true }), diff --git a/package-lock.json b/package-lock.json index c147efa72..da3272555 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,9 @@ "requires": true, "packages": { "": { + "dependencies": { + "svg-builder": "^2.0.0" + }, "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", @@ -2828,6 +2831,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/svg-builder": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz", + "integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw==" + }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", diff --git a/package.json b/package.json index c093fccd9..e3091f198 100644 --- a/package.json +++ b/package.json @@ -11,5 +11,8 @@ "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" + }, + "dependencies": { + "svg-builder": "^2.0.0" } } From 5a13272d375c2630be03dc97e6234389fff2d02a Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 17:56:20 -0600 Subject: [PATCH 23/33] Update InlineTipManager.ts --- extensions/vscode/src/activation/InlineTipManager.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/activation/InlineTipManager.ts b/extensions/vscode/src/activation/InlineTipManager.ts index b335cc9dd..954dba19d 100644 --- a/extensions/vscode/src/activation/InlineTipManager.ts +++ b/extensions/vscode/src/activation/InlineTipManager.ts @@ -15,7 +15,7 @@ const SVG_CONFIG = { radius: 4, leftMargin: 40, debounceDelay: 500, - chatLabel: "Add to Chat", + chatLabel: "Chat", chatShortcut: `${getMetaKeyLabel()}L`, editLabel: "Edit", editShortcut: `${getMetaKeyLabel()}I`, From 02968fb1551c0a26af75340641312e1f9f5a1102 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 20:33:23 -0600 Subject: [PATCH 24/33] fix: correct package.json update --- extensions/vscode/package-lock.json | 10 ++++++++-- extensions/vscode/package.json | 1 + extensions/vscode/src/activation/InlineTipManager.ts | 4 ++-- extensions/vscode/src/activation/activate.ts | 1 - package-lock.json | 8 -------- package.json | 3 --- 6 files changed, 11 insertions(+), 16 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8f5cad8a0..c6db7f103 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -48,6 +48,7 @@ "request": "^2.88.2", "socket.io-client": "^4.7.2", "strip-ansi": "^7.1.0", + "svg-builder": "^2.0.0", "systeminformation": "^5.22.10", "tailwindcss": "^3.3.2", "undici": "^6.2.0", @@ -12122,6 +12123,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/svg-builder": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz", + "integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw==" + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 6a416096c..550ed3538 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -703,6 +703,7 @@ "request": "^2.88.2", "socket.io-client": "^4.7.2", "strip-ansi": "^7.1.0", + "svg-builder": "^2.0.0", "systeminformation": "^5.22.10", "tailwindcss": "^3.3.2", "undici": "^6.2.0", diff --git a/extensions/vscode/src/activation/InlineTipManager.ts b/extensions/vscode/src/activation/InlineTipManager.ts index 954dba19d..0ea078c21 100644 --- a/extensions/vscode/src/activation/InlineTipManager.ts +++ b/extensions/vscode/src/activation/InlineTipManager.ts @@ -23,7 +23,7 @@ const SVG_CONFIG = { get fontSize() { return Math.ceil( (vscode.workspace.getConfiguration("editor").get("fontSize") ?? - 14) * 0.7, + 14) * 0.8, ); }, get fontFamily() { @@ -237,7 +237,7 @@ export class InlineTipManager { return vscode.window.createTextEditorDecorationType({ after: { contentIconPath: this.svgTooltip, - margin: `-2.5px 0 0 ${SVG_CONFIG.leftMargin}px`, + margin: `-5px 0 0 ${SVG_CONFIG.leftMargin}px`, width: `${SVG_CONFIG.tipWidth}px`, }, }); diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index d40aee740..1bd22c7f4 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -8,7 +8,6 @@ import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; import setupInlineTips from "./InlineTipManager"; -// import { setupInlineTips } from "./inlineTips"; export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files diff --git a/package-lock.json b/package-lock.json index da3272555..c147efa72 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,9 +4,6 @@ "requires": true, "packages": { "": { - "dependencies": { - "svg-builder": "^2.0.0" - }, "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", @@ -2831,11 +2828,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/svg-builder": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz", - "integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw==" - }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", diff --git a/package.json b/package.json index e3091f198..c093fccd9 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,5 @@ "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" - }, - "dependencies": { - "svg-builder": "^2.0.0" } } From 92a38ccf5f0639d815684bd786f75ebede9e950c Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 23:24:32 -0600 Subject: [PATCH 25/33] bugfix: handle inline edit w/ myers diff --- .../vscode/src/diff/vertical/handler.ts | 75 ++++++++++--------- .../vscode/src/diff/vertical/manager.ts | 2 +- .../VerticalPerLineCodeLensProvider.ts | 9 --- 3 files changed, 40 insertions(+), 46 deletions(-) diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index a99c9c1c3..80331f805 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -343,6 +343,7 @@ export class VerticalDiffHandler implements vscode.Disposable { async run(diffLineGenerator: AsyncGenerator) { let diffLines = []; + try { // As an indicator of loading this.updateIndexLineDecorations(); @@ -481,9 +482,17 @@ export class VerticalDiffHandler implements vscode.Disposable { * we have received all of the diff lines. */ async reapplyWithMeyersDiff(diffLines: DiffLine[]) { + // First, we reset the original diff by deleting any new lines and clearing decorations + for (const range of this.greenDecorationManager.getRanges()) { + await this.deleteLinesAt( + range.start.line, + range.end.line - range.start.line + 1, + ); + } + this.clearDecorations(); - // First, get our old/new file content based on the diff lines + // Then, get our old/new file content based on the original lines const oldFileContent = diffLines .filter((line) => line.type === "same" || line.type === "old") .map((line) => line.line) @@ -497,55 +506,49 @@ export class VerticalDiffHandler implements vscode.Disposable { const diffs = myersDiff(oldFileContent, newFileContent); const meyersDiffLines = diffs.map((diff) => diff.line).join("\n"); - console.log({ newFileContent }); - - // Then, we overwrite the potentially miscalcualted diff blocks with our Meyers Diff - const fullRange = new vscode.Range( - this.editor.document.positionAt(0), - this.editor.document.positionAt(this.editor.document.getText().length), - ); + // Then, we insert our diff lines await this.editor.edit((editBuilder) => { - editBuilder.replace(fullRange, meyersDiffLines); + editBuilder.replace(this.range, meyersDiffLines), + { + undoStopAfter: false, + undoStopBefore: false, + }; }); - let currentBlock = { - start: 0, - numRed: 0, - numGreen: 0, - }; - - const blocks: VerticalDiffCodeLens[] = []; - // Lastly, we apply decorations + let numRed = 0; + let numGreen = 0; + + const codeLensBlocks: VerticalDiffCodeLens[] = []; + diffs.forEach((diff, index) => { if (diff.type === "old") { - this.redDecorationManager.addLine(index); - currentBlock.numRed++; + this.redDecorationManager.addLine(this.startLine + index); + numRed++; } else if (diff.type === "new") { - this.greenDecorationManager.addLine(index); - currentBlock.numGreen++; - } else if ( - diff.type === "same" && - (currentBlock.numRed > 0 || currentBlock.numGreen > 0) - ) { - blocks.push({ - ...currentBlock, - start: index - currentBlock.numRed - currentBlock.numGreen, + this.greenDecorationManager.addLine(this.startLine + index); + numGreen++; + } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) { + codeLensBlocks.push({ + numRed, + numGreen, + start: this.startLine + index - numRed - numGreen, }); - currentBlock = { - start: index + 1, - numRed: 0, - numGreen: 0, - }; + numRed = 0; + numGreen = 0; } }); - if (currentBlock.numRed > 0 || currentBlock.numGreen > 0) { - blocks.push(currentBlock); + if (numRed > 0 || numGreen > 0) { + codeLensBlocks.push({ + numGreen, + numRed, + start: this.startLine + diffs.length - 1 - numRed - numGreen, + }); } - this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks); + this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks); this.refreshCodeLens(); } } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index ee47fd173..1e1b41a17 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -3,13 +3,13 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; +import * as URI from "uri-js"; import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; -import * as URI from "uri-js"; export interface VerticalDiffCodeLens { start: number; diff --git a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts index 52fd07f79..43c9015f1 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts @@ -53,15 +53,6 @@ export class VerticalDiffCodeLensProvider implements vscode.CodeLensProvider { arguments: [uri, i], }), ); - - if (codeLenses.length === 2) { - codeLenses.push( - new vscode.CodeLens(range, { - title: `${getMetaKeyLabel()}I to add instructions`, - command: "", - }), - ); - } } return codeLenses; From cb77d90a896918f64a62a8e5ad7d95ad7ff56b78 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 23:26:33 -0600 Subject: [PATCH 26/33] Update handler.ts --- extensions/vscode/src/diff/vertical/handler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 80331f805..a3a7f651f 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -544,7 +544,7 @@ export class VerticalDiffHandler implements vscode.Disposable { codeLensBlocks.push({ numGreen, numRed, - start: this.startLine + diffs.length - 1 - numRed - numGreen, + start: this.startLine + diffs.length - numRed - numGreen, }); } From 2200b6eafd2773afbd7172e5fbd601464a5be906 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Jan 2025 10:10:25 +0100 Subject: [PATCH 27/33] uri util fixes --- core/util/ideUtils.ts | 18 ++--- core/util/uri.test.ts | 22 ------ core/util/uri.ts | 71 ++++++++----------- .../StepContainerPreToolbar.tsx | 4 +- 4 files changed, 42 insertions(+), 73 deletions(-) diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index 93cb5008d..b969b2286 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -1,6 +1,10 @@ import { IDE } from ".."; -import { joinPathsToUri, pathToUriPathSegment } from "./uri"; +import { + joinEncodedUriPathSegmentToUri, + joinPathsToUri, + pathToUriPathSegment, +} from "./uri"; /* This function takes a relative (to workspace) filepath @@ -51,7 +55,7 @@ export async function inferResolvedUriFromRelativePath( for (const suffix of suffixes) { const uris = dirs.map((dir) => ({ dir, - partialUri: joinPathsToUri(dir, suffix), + partialUri: joinEncodedUriPathSegmentToUri(dir, suffix), })); const promises = uris.map(async ({ partialUri, dir }) => { const exists = await ide.fileExists(partialUri); @@ -67,15 +71,13 @@ export async function inferResolvedUriFromRelativePath( // If exactly one directory matches, use it if (existingUris.length === 1) { - return joinPathsToUri(existingUris[0].dir, segments.join("/")); + return joinEncodedUriPathSegmentToUri( + existingUris[0].dir, + segments.join("/"), + ); } } // If no unique match found, use the first directory return joinPathsToUri(dirs[0], path); } - -interface ResolveResult { - resolvedUri: string; - matchedDir: string; -} diff --git a/core/util/uri.test.ts b/core/util/uri.test.ts index 9e2471054..8a915d73f 100644 --- a/core/util/uri.test.ts +++ b/core/util/uri.test.ts @@ -1,9 +1,7 @@ // Generated by continue -import * as URI from "uri-js"; import { pathToUriPathSegment, findUriInDirs, - relativePathOrUriToUri, getUriPathBasename, getUriFileExtension, getFileExtensionFromBasename, @@ -141,26 +139,6 @@ describe("uri utils", () => { }); }); - describe("relativePathOrUriToUri", () => { - const consoleSpy = jest.spyOn(console, "trace").mockImplementation(); - - afterEach(() => { - consoleSpy.mockClear(); - }); - - it("should return original URI if scheme exists", () => { - const uri = "file:///path/to/file.txt"; - expect(relativePathOrUriToUri(uri, "file:///base")).toBe(uri); - }); - - it("should convert relative path to URI", () => { - expect(relativePathOrUriToUri("path/to/file.txt", "file:///base")).toBe( - "file:///base/path/to/file.txt", - ); - expect(consoleSpy).toHaveBeenCalledWith("Received path with no scheme"); - }); - }); - describe("getLastNUriRelativePathParts", () => { it("should get last N parts of URI relative path", () => { const dirUris = ["file:///workspace/project1"]; diff --git a/core/util/uri.ts b/core/util/uri.ts index 708408ce0..a1bcd7745 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -5,23 +5,21 @@ import * as URI from "uri-js"; \this\is\afile.ts -> this/is/afile.ts is/already/clean -> is/already/clean **/ - export function pathToUriPathSegment(path: string) { let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes clean = clean.replace(/^\//, ""); // remove start slash clean = clean.replace(/\/$/, ""); // remove end slash return clean .split("/") - .map((segment) => encodeURIComponent(segment)) + .map((part) => encodeURIComponent(part)) .join("/"); } export function getCleanUriPath(uri: string) { - const path = URI.parse(uri).path; - if (!path) { - return ""; - } - return pathToUriPathSegment(path); + const path = URI.parse(uri).path ?? ""; + let clean = path.replace(/^\//, ""); // remove start slash + clean = clean.replace(/\/$/, ""); // remove end slash + return clean; } export function findUriInDirs( @@ -36,6 +34,7 @@ export function findUriInDirs( if (!uriComps.scheme) { throw new Error(`Invalid uri: ${uri}`); } + const uriPathParts = getCleanUriPath(uri).split("/"); for (const dir of dirUriCandidates) { const dirComps = URI.parse(dir); @@ -51,14 +50,7 @@ export function findUriInDirs( // file:///folder/file is not within file:///fold // At this point we break the path up and check if each dir path part matches - const dirPathParts = (dirComps.path ?? "") - .replace(/^\//, "") - .split("/") - .map((part) => encodeURIComponent(part)); - const uriPathParts = (uriComps.path ?? "") - .replace(/^\//, "") - .split("/") - .map((part) => encodeURIComponent(part)); + const dirPathParts = getCleanUriPath(dir).split("/"); if (uriPathParts.length < dirPathParts.length) { continue; @@ -70,7 +62,10 @@ export function findUriInDirs( } } if (allDirPartsMatch) { - const relativePath = uriPathParts.slice(dirPathParts.length).join("/"); + const relativePath = uriPathParts + .slice(dirPathParts.length) + .map(decodeURIComponent) + .join("/"); return { uri, relativePathOrBasename: relativePath, @@ -86,28 +81,13 @@ export function findUriInDirs( }; } -/* - To smooth out the transition from path to URI will use this function to warn when path is used - This will NOT work consistently with full OS paths like c:\blah\blah or ~/Users/etc -*/ -export function relativePathOrUriToUri( - relativePathOrUri: string, - defaultDirUri: string, -): string { - const out = URI.parse(relativePathOrUri); - if (out.scheme) { - return relativePathOrUri; - } - console.trace("Received path with no scheme"); - return joinPathsToUri(defaultDirUri, out.path ?? ""); -} - /* Returns just the file or folder name of a URI */ export function getUriPathBasename(uri: string): string { - const cleanPath = getCleanUriPath(uri); - return cleanPath.split("/")?.pop() || ""; + const path = getCleanUriPath(uri); + const basename = path.split("/").pop() || ""; + return decodeURIComponent(basename); } export function getFileExtensionFromBasename(basename: string) { @@ -142,6 +122,15 @@ export function joinPathsToUri(uri: string, ...pathSegments: string[]) { return URI.serialize(components); } +export function joinEncodedUriPathSegmentToUri( + uri: string, + pathSegment: string, +) { + const components = URI.parse(uri); + components.path = `${components.path}/${pathSegment}`; + return URI.serialize(components); +} + export function getShortestUniqueRelativeUriPaths( uris: string[], dirUriCandidates: string[], @@ -153,8 +142,7 @@ export function getShortestUniqueRelativeUriPaths( const segmentCombinationsMap = new Map(); const segmentsInfo = uris.map((uri) => { const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates); - const cleanPath = pathToUriPathSegment(relativePathOrBasename); - const segments = cleanPath.split("/"); + const segments = relativePathOrBasename.split("/"); const suffixes: string[] = []; // Generate all possible suffix combinations, starting from the shortest (basename) @@ -168,18 +156,19 @@ export function getShortestUniqueRelativeUriPaths( ); } - return { uri, segments, suffixes, cleanPath }; + return { uri, segments, suffixes, relativePathOrBasename }; }); // Find shortest unique path for each URI - return segmentsInfo.map(({ uri, suffixes, cleanPath }) => { + return segmentsInfo.map(({ uri, suffixes, relativePathOrBasename }) => { // Since suffixes are now ordered from shortest to longest, // the first unique one we find will be the shortest - const uniqueCleanPath = + const uniquePath = suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ?? - cleanPath; // fallback to full path if no unique suffix found - return { uri, uniquePath: decodeURIComponent(uniqueCleanPath) }; + relativePathOrBasename; // fallback to full path if no unique suffix found + return { uri, uniquePath }; }); } + // Only used when working with system paths and relative paths // Since doesn't account for URI segements before workspace export function getLastNPathParts(filepath: string, n: number): string { diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index c6a0d58f0..398ce5747 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -93,12 +93,12 @@ export default function StepContainerPreToolbar( if (!defaultModel) { return; } - + const fileUri = await inferResolvedUriFromRelativePath( props.relativeFilepath, ideMessenger.ide, ); - + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, filepath: fileUri, From 821c841b43e7b054a207d645df61e93cbc15baa4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Jan 2025 10:47:33 +0100 Subject: [PATCH 28/33] fix multifile edit --- core/util/ideUtils.ts | 6 +++--- extensions/vscode/package-lock.json | 4 ++-- .../StepContainerPreToolbar.tsx | 1 + gui/src/util/getMultifileEditPrompt.ts | 18 ++++++++++++------ 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index b969b2286..9ed4a47fc 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -34,7 +34,7 @@ export async function resolveRelativePathInDir( If no meaninful path match just concatenates to first dir's uri */ export async function inferResolvedUriFromRelativePath( - path: string, + relativePath: string, ide: IDE, dirCandidates?: string[], ): Promise { @@ -44,7 +44,7 @@ export async function inferResolvedUriFromRelativePath( throw new Error("inferResolvedUriFromRelativePath: no dirs provided"); } - const segments = pathToUriPathSegment(path).split("/"); + const segments = pathToUriPathSegment(relativePath).split("/"); // Generate all possible suffixes from shortest to longest const suffixes: string[] = []; for (let i = segments.length - 1; i >= 0; i--) { @@ -79,5 +79,5 @@ export async function inferResolvedUriFromRelativePath( } // If no unique match found, use the first directory - return joinPathsToUri(dirs[0], path); + return joinPathsToUri(dirs[0], relativePath); } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8f5cad8a0..0a2dd8330 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 398ce5747..1ee03d2f5 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -98,6 +98,7 @@ export default function StepContainerPreToolbar( props.relativeFilepath, ideMessenger.ide, ); + console.log("HERE", props.relativeFilepath, fileUri); ideMessenger.post("applyToFile", { streamId: streamIdRef.current, diff --git a/gui/src/util/getMultifileEditPrompt.ts b/gui/src/util/getMultifileEditPrompt.ts index 8f526f1e2..13ee8ac78 100644 --- a/gui/src/util/getMultifileEditPrompt.ts +++ b/gui/src/util/getMultifileEditPrompt.ts @@ -1,16 +1,22 @@ -import { CodeToEdit } from "core"; +import { CodeToEdit, IDE } from "core"; +import { findUriInDirs } from "core/util/uri"; export default function getMultifileEditPrompt( codeToEdit: CodeToEdit[], + dirs?: string[], ): string { const codeToEditStr = codeToEdit - .map( - (code) => ` -\`\`\` ${code.filepath} + .map((code) => { + const { relativePathOrBasename } = findUriInDirs( + code.filepath, + dirs ?? window.workspacePaths ?? [], + ); + return ` +\`\`\` ${relativePathOrBasename} ${code.contents} \`\`\` - `, - ) + `; + }) .join("\n"); return ` From f2820feca92490a4eff42aa6773dec2f6de471bd Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 3 Jan 2025 13:45:24 -0500 Subject: [PATCH 29/33] add env option to MCP --- core/context/mcp/index.ts | 1 + core/index.d.ts | 1 + extensions/vscode/config_schema.json | 7 +++++++ 3 files changed, 9 insertions(+) diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index e214b1e02..26be2f471 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -72,6 +72,7 @@ class MCPConnection { return new StdioClientTransport({ command: options.transport.command, args: options.transport.args, + env: options.transport.env, }); case "websocket": return new WebSocketClientTransport(new URL(options.transport.url)); diff --git a/core/index.d.ts b/core/index.d.ts index d916a19f1..2d7622895 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -940,6 +940,7 @@ export interface StdioOptions { type: "stdio"; command: string; args: string[]; + env?: Record; } export interface WebSocketOptions { diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index c9df4e976..c0ffddd3a 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -3151,6 +3151,13 @@ "items": { "type": "string" } + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables to pass to the command" } }, "required": ["type", "command", "args"] From efd3b7bf715f16cd29f2825e0e3d84f871829e63 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 3 Jan 2025 13:55:06 -0500 Subject: [PATCH 30/33] fix merge conflicts --- core/indexing/docs/DocsService.ts | 2 -- gui/src/components/dialogs/AddDocsDialog.tsx | 16 ++++++++-------- gui/src/redux/slices/configSlice.ts | 14 ++++++++++++-- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 3d9cb0fd7..1696466dc 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -18,8 +18,6 @@ import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbed import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { IMessenger } from "../../protocol/messenger"; import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; -import { IMessenger } from "../../protocol/messenger"; -import { GlobalContext } from "../../util/GlobalContext"; import { editConfigJson, getDocsSqlitePath, diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index f816369c8..01f924425 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -5,19 +5,19 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { IndexingStatus, PackageDocsResult, SiteIndexingConfig } from "core"; +import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import { Input, SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { ToolTip } from "../gui/Tooltip"; -import FileIcon from "../FileIcon"; -import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; -import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; -import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; import { useAppSelector } from "../../redux/hooks"; -import { setConfig } from "../../redux/slices/configSlice"; +import { updateConfig } from "../../redux/slices/configSlice"; +import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import FileIcon from "../FileIcon"; +import { ToolTip } from "../gui/Tooltip"; +import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; function AddDocsDialog() { const config = useAppSelector((store) => store.config.config); @@ -146,7 +146,7 @@ function AddDocsDialog() { // Optimistic status update dispatch( - setConfig({ + updateConfig({ ...config, docs: [ ...(config.docs?.filter( diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 35e530e47..99401fe05 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -55,6 +55,12 @@ export const configSlice = createSlice({ state.config = config; state.defaultModelTitle = defaultModelTitle; }, + updateConfig: ( + state, + { payload: config }: PayloadAction, + ) => { + state.config = config; + }, setConfigError: ( state, { payload: error }: PayloadAction, @@ -93,8 +99,12 @@ export const configSlice = createSlice({ }, }); -export const { setDefaultModel, setConfigResult, setConfigError } = - configSlice.actions; +export const { + setDefaultModel, + updateConfig, + setConfigResult, + setConfigError, +} = configSlice.actions; export const { selectDefaultModel, From 9fdd9a53484e73b6cf72da98b39365c348f51800 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 3 Jan 2025 14:28:29 -0500 Subject: [PATCH 31/33] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 550ed3538..08cb25e3a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.248", + "version": "0.9.249", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 064749116463f63bac47223e18eda0a13b750775 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 3 Jan 2025 22:54:03 -0500 Subject: [PATCH 32/33] don't show all webview message errors --- extensions/vscode/src/webviewProtocol.ts | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 0632d44b9..fea6a3e8e 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,7 +1,7 @@ import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; +import { Message } from "core/protocol/messenger"; import { WebviewMessengerResult } from "core/protocol/util"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; -import { Message } from "core/protocol/messenger"; import { Telemetry } from "core/util/posthog"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -140,25 +140,6 @@ export class VsCodeWebviewProtocol }, false, ); - vscode.window - .showErrorMessage( - message.split("\n\n")[0], - "Show Logs", - "Troubleshooting", - ) - .then((selection) => { - if (selection === "Show Logs") { - vscode.commands.executeCommand( - "workbench.action.toggleDevTools", - ); - } else if (selection === "Troubleshooting") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://docs.continue.dev/troubleshooting", - ), - ); - } - }); } } } From 723a75ca00e641a9ed6758f55ec6d0ef9ea6fe34 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 3 Jan 2025 22:55:16 -0500 Subject: [PATCH 33/33] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 08cb25e3a..4d4b2b8c7 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.249", + "version": "0.9.250", "repository": { "type": "git", "url": "https://github.com/continuedev/continue"