From a835ac1126eb5e9bff4dcb4a49536c69dc4b1dcb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 20 Dec 2024 10:10:03 -0800 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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 ||