From af4e5ee4400f65843319ce4f50e487e80344605d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 17 Nov 2024 01:22:57 -0800 Subject: [PATCH] indexing manager --- core/context/providers/DocsContextProvider.ts | 1 - core/core.ts | 41 +++-- core/index.d.ts | 19 +- core/indexing/IndexingStatusManager.ts | 104 +++++++++++ core/indexing/docs/DocsService.test.ts | 9 +- core/indexing/docs/DocsService.ts | 171 +++++++++++------- core/protocol/core.ts | 12 ++ core/protocol/passThrough.ts | 15 +- core/protocol/webview.ts | 7 +- gui/src/hooks/useSetup.ts | 8 - 10 files changed, 274 insertions(+), 113 deletions(-) create mode 100644 core/indexing/IndexingStatusManager.ts diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f3a1e5d77..2f2ca9002 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -9,7 +9,6 @@ import { } from "../.."; import DocsService from "../../indexing/docs/DocsService"; import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; -import { Telemetry } from "../../util/posthog"; import { INSTRUCTIONS_BASE_ITEM } from "./utils"; diff --git a/core/core.ts b/core/core.ts index c1075dfd6..fe07ecbce 100644 --- a/core/core.ts +++ b/core/core.ts @@ -35,6 +35,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./util/messenger"; +import { IndexingStatusManager } from "./indexing/IndexingStatusManager"; export class Core { // implements IMessenger @@ -43,8 +44,8 @@ export class Core { completionProvider: CompletionProvider; continueServerClientPromise: Promise; codebaseIndexingState: IndexingProgressUpdate; - docsIndexingStates: Map = new Map(); controlPlaneClient: ControlPlaneClient; + private indexingManager: IndexingStatusManager; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -109,6 +110,8 @@ export class Core { this.controlPlaneClient, ); + this.indexingManager = new IndexingStatusManager(this.messenger); + this.docsService = DocsService.createSingleton( this.configHandler, this.ide, @@ -278,32 +281,15 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - // let hasFailed = false; - // for await (const result of this.docsService.indexAndAdd(msg.data)) { - // if (result.status === "failed") { - // hasFailed = true; - // break; - // } - // } - // if (hasFailed) { - // void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); - // } else { - // void this.ide.showToast( - // "info", - // `Successfully indexed ${msg.data.startUrl}`, - // ); - // this.messenger.send("refreshSubmenuItems", undefined); - // } + void this.docsService.indexAndAdd(msg.data); }); on("context/removeDocs", async (msg) => { await this.docsService.delete(msg.data.startUrl); - this.messenger.send("refreshSubmenuItems", undefined); }); on("context/indexDocs", async (msg) => { - await this.docsService.indexAllDocs(msg.data.reIndex); - this.messenger.send("refreshSubmenuItems", undefined); + await this.docsService.indexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -726,6 +712,19 @@ export class Core { recentlyEditedFilesCache.set(filepath, filepath); } }); + + on("indexing/reindex", async (msg) => { + this.indexingManager.reindex(msg.data.id); + }); + on("indexing/abort", async (msg) => { + this.indexingManager.abort(msg.data.id); + }); + on("indexing/setPaused", async (msg) => { + this.indexingManager.setPaused(msg.data.id, msg.data.pause); + }); + on("indexing/getStatuses", async (msg) => { + return this.indexingManager.statuses; + }); } private indexingCancellationController: AbortController | undefined; @@ -768,4 +767,6 @@ export class Core { this.messenger.send("refreshSubmenuItems", undefined); } + + // private } diff --git a/core/index.d.ts b/core/index.d.ts index b6b4c7f0c..f1c7263eb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -47,22 +47,21 @@ export interface IndexingProgressUpdate { // This is more or less a V2 of IndexingProgressUpdate export interface IndexingStatusUpdate { + id: string; type: "docs"; - id: string; // Unique identifier, e.g. docs start url progress: number; description: string; - status: - | "initializing" - | "indexing" - | "complete" - | "paused" - | "failed" - | "disabled"; - embeddingsModel: string; - isReindexing: boolean; + status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "deleted"; + embeddingsProviderId: string; + isReindexing?: boolean; debugInfo?: string; } +export type IndexingStatusMap = Map< + string, + Map +>; + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, diff --git a/core/indexing/IndexingStatusManager.ts b/core/indexing/IndexingStatusManager.ts new file mode 100644 index 000000000..1ba177493 --- /dev/null +++ b/core/indexing/IndexingStatusManager.ts @@ -0,0 +1,104 @@ +import { IndexingStatusMap, IndexingStatusUpdate } from ".."; +import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; +import { IMessenger } from "../util/messenger"; + +/* + Any service that sends indexing updates can use an instance of this class + 1. Pass indexingManager to the service + 2. Register the service with the manager using `registerService` + E.g. docs uses startUrl as id + 3. +*/ +export class IndexingStatusManager { + private readonly messenger: IMessenger; + readonly statuses: IndexingStatusMap = new Map(); + private readonly reindexTypeFunctions: Map< + string, + (id: string) => Promise + > = new Map(); + + constructor(messenger: IMessenger) { + this.messenger = messenger; + } + + // Services that use an instance of this class should add their reindex functions here + registerService(type: string, fn: (id: string) => Promise) { + this.reindexTypeFunctions.set(type, fn); + this.statuses.set(type, new Map()); + } + + reindex(type: string, id: string) { + const byType = this.statuses.get(type); + const reindexFn = this.reindexTypeFunctions.get(type); + + if (byType && reindexFn) { + const status = byType.get(id); + if (status) { + if (status.status === "deleted") { + throw new Error( + "Cannot reindex a deleted item, shouldn't ever happen", + ); + } + void reindexFn(id); + } + } + } + + handleUpdate(status: IndexingStatusUpdate) { + const byType = this.statuses.get(status.type); + if (byType) { + byType.set(status.id, status); + this.messenger.send("indexing/statusUpdate", status); + } + } + + delete(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: "deleted" }); + } + } + } + + abort(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: "aborted" }); + } + } + } + + isAborted(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + return status.status === "aborted"; + } + } + } + + setPaused(type: string, id: string, pause: boolean) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + this.handleUpdate({ ...status, status: pause ? "paused" : "indexing" }); + } + } + } + + isPaused(type: string, id: string) { + const byType = this.statuses.get(type); + if (byType) { + const status = byType.get(id); + if (status) { + return status.status === "paused"; + } + } + } +} diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 11fed29e5..4a911b38a 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -66,8 +66,7 @@ describe.skip("DocsService Integration Tests", () => { }); test("Indexing, retrieval, and deletion of a new documentation site", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); let latestConfig = await getReloadedConfig(); @@ -133,13 +132,11 @@ describe.skip("DocsService Integration Tests", () => { test("Handles pulling down and adding pre-indexed docs", async () => { const preIndexedDoc = Object.values(preIndexedDocs)[0]; - const generator = docsService.indexAndAdd(preIndexedDoc); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(preIndexedDoc); }); test("Config synchronization with SQLite", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); await getReloadedConfig(); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 79dea28e6..9450cca6b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -24,6 +24,7 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; +import { IndexingStatusManager } from "../IndexingStatusManager"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; @@ -78,6 +79,8 @@ export type AddParams = { export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; + static indexingType = "docs"; + static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); @@ -97,6 +100,7 @@ export default class DocsService { configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, + private readonly indexingManager?: IndexingStatusManager, ) { this.isInitialized = this.init(configHandler); } @@ -119,9 +123,12 @@ export default class DocsService { // Initialization - load config and attach config listener private async init(configHandler: ConfigHandler) { + this.indexingManager?.registerService( + DocsService.indexingType, + this.reindexDoc, + ); this.config = await configHandler.loadConfig(); await this.handleConfigUpdate({ config: this.config }); - configHandler.onConfigUpdate(this.handleConfigUpdate); } @@ -180,14 +187,7 @@ export default class DocsService { return; } - const newConfigDocs = newConfig.docs || []; - const oldConfigDocs = oldConfig.docs || []; - - const newPreindexed = newConfigDocs.filter( - (doc) => !!preIndexedDocs[doc.startUrl], - ); - - // On embeddings provider change, reindex all docs + // On embeddings provider change, reindex all non-preindexed docs // change = doesn't match last successful embeddings provider const curEmbeddingsProviderId = this.globalContext.get( "curEmbeddingsProviderId", @@ -204,7 +204,7 @@ export default class DocsService { } } - await this.syncConfigAndSqlite(); + await this.syncDocsOnConfigUpdate(oldConfig, newConfig); } } @@ -251,7 +251,7 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocs(reIndex: boolean = false) { + async indexAllDocsWithPrompt(reIndex: boolean = false) { if (!this.hasDocsContextProvider()) { const didAddDocsContextProvider = await this.showAddDocsContextProviderToast(); @@ -264,8 +264,7 @@ export default class DocsService { const docs = await this.listMetadata(); for (const doc of docs) { - const generator = this.indexAndAdd(doc, reIndex); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc, reIndex); } void this.ide.showToast("info", "Docs indexing completed"); @@ -280,10 +279,23 @@ export default class DocsService { return docs; } - async *indexAndAdd( + updateIndexingStatus(update: IndexingStatusUpdate) { + this.indexingManager?.handleUpdate(update); + } + + async reindexDoc(startUrl: string) { + const docConfig = this.config.docs?.find( + (doc) => doc.startUrl === startUrl, + ); + if (docConfig) { + await this.indexAndAdd(docConfig, true); + } + } + + async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, - ): AsyncGenerator { + ): Promise { const { startUrl } = siteIndexingConfig; if (this.docsIndexingQueue.has(startUrl)) { @@ -296,38 +308,34 @@ export default class DocsService { const fixedStatus: Pick< IndexingStatusUpdate, - "type" | "id" | "embeddingsModel" | "isReindexing" + "type" | "id" | "embeddingsProviderId" | "isReindexing" > = { type: "docs", id: siteIndexingConfig.startUrl, - embeddingsModel: embeddingsProvider.id, + embeddingsProviderId: embeddingsProvider.id, isReindexing: reIndex && indexExists, }; - const completeStatus: IndexingStatusUpdate = { - ...fixedStatus, - progress: 1, - description: "Complete", - status: "complete", - }; - if (indexExists && !reIndex) { - yield { - ...completeStatus, + this.updateIndexingStatus({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", debugInfo: "Already indexed", - }; + }); return; } // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - yield { + this.updateIndexingStatus({ ...fixedStatus, status: "indexing", description: "Finding subpages", progress: 0, - }; + }); const articles: Article[] = []; let processedPages = 0; @@ -348,12 +356,12 @@ export default class DocsService { // Use a heuristic approach for progress calculation const progress = Math.min(processedPages / maxKnownPages, 1); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `Finding subpages (${page.path})`, status: "indexing", progress, // Yield the heuristic progress - }; + }); // Increase maxKnownPages to delay progress reaching 100% too soon if (processedPages === maxKnownPages) { @@ -375,12 +383,12 @@ export default class DocsService { for (let i = 0; i < articles.length; i++) { const article = articles[i]; - yield { + this.updateIndexingStatus({ ...fixedStatus, status: "indexing", description: `Creating Embeddings: ${article.subpath}`, progress: i / articles.length, - }; + }); try { const chunkedArticle = chunkArticle( @@ -409,12 +417,14 @@ export default class DocsService { `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, ); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, status: "failed", progress: 1, - }; + }); + + void this.ide.showToast("info", `Failed to index ${startUrl}`); this.docsIndexingQueue.delete(startUrl); @@ -424,12 +434,12 @@ export default class DocsService { // Add docs to databases console.log(`Adding ${embeddings.length} embeddings to db`); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: `Adding ${embeddings.length} embeddings to db`, status: "indexing", progress: 0.5, - }; + }); // Delete indexed docs if re-indexing if (reIndex && (await this.hasMetadata(startUrl.toString()))) { @@ -448,14 +458,14 @@ export default class DocsService { this.docsIndexingQueue.delete(startUrl); - yield { + this.updateIndexingStatus({ ...fixedStatus, description: "Complete", status: "complete", progress: 1, - }; + }); - console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); if (this.messenger) { this.messenger.send("refreshSubmenuItems", undefined); @@ -480,8 +490,7 @@ export default class DocsService { return []; } - const preIndexedDoc = preIndexedDocs[query]; - + const preIndexedDoc = preIndexedDocs[startUrl]; if (!!preIndexedDoc) { void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDoc["title"], @@ -583,32 +592,72 @@ export default class DocsService { return result.favicon; } - private async syncConfigAndSqlite() { + /* + Sync with no embeddings provider change + Ignores pre-indexed docs + */ + private async syncDocsOnConfigUpdate( + oldConfig: ContinueConfig, + newConfig: ContinueConfig, + ) { try { this.isSyncing = true; - const sqliteDocs = await this.listMetadata(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; + // Otherwise sync the index based on config changes + const oldConfigDocs = oldConfig.docs || []; + const newConfigDocs = newConfig.docs || []; + const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; + const currentlyIndexedDocs = await this.listMetadata(); + const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( + // const newDocs = newConfigDocs.filter( + // (doc) => !currentStartUrls.includes(doc.startUrl), + // ); + + // Anything found in sqlite but not in new config should be deleted + const deletedDocs = currentlyIndexedDocs.filter( (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], + !preIndexedDocs[doc.startUrl] && + !newConfigStartUrls.includes(doc.startUrl), ); + // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed + // TODO if only favicon and title change, only update, don't embed + // Otherwise anything found in new config that isn't in sqlite should be added/indexed + const newDocs: SiteIndexingConfig[] = []; + const changedDocs: SiteIndexingConfig[] = []; + for (const doc of newConfigDocs) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); + const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); + + if (currentIndexedDoc) { + if ( + oldConfigDoc && + (oldConfigDoc.maxDepth !== doc.maxDepth || + oldConfigDoc.title !== doc.title || + oldConfigDoc.faviconUrl !== doc.faviconUrl) + ) { + changedDocs.push(doc); + } + // if get's here, not changed, no update needed + } else { + newDocs.push(doc); + } + } + + for (const doc of changedDocs) { + console.log(`Updating indexed doc: ${doc.startUrl}`); + await this.indexAndAdd(doc, true); + } + for (const doc of newDocs) { console.log(`Indexing new doc: ${doc.startUrl}`); void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc); } for (const doc of deletedDocs) { @@ -706,8 +755,7 @@ export default class DocsService { return table; } - // Add methods for Individual docs - + // Methods for adding individual docs private async addToLance({ chunks, siteIndexingConfig, @@ -858,7 +906,7 @@ export default class DocsService { } console.log( - `Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`, + `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); for (const doc of docs) { @@ -866,8 +914,7 @@ export default class DocsService { } for (const doc of docs) { - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc); } // Important that this only is invoked after we have successfully @@ -875,6 +922,6 @@ export default class DocsService { // invalid state. this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - console.log("Completed reindexing of all docs"); + console.log("Completed reindexing of all non-preindexed docs"); } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2c9af1433..fec158eac 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -8,6 +8,7 @@ import type { ContextSubmenuItem, DiffLine, IdeSettings, + IndexingStatusMap, LLMFullCompletionOptions, MessageContent, ModelDescription, @@ -142,6 +143,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { { model: string; promptTokens: number; generatedTokens: number }[], ]; "tts/kill": [undefined, void]; + + // Codebase indexing "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, @@ -154,6 +157,15 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + + // Docs Indexing. TODO move codebase to this + "indexing/reindex": [ + { id: string; shouldClearAllOfIndexType?: boolean }, + void, + ]; + "indexing/abort": [{ id: string }, void]; + "indexing/setPaused": [{ id: string; pause: boolean }, void]; + "indexing/getStatuses": [undefined, IndexingStatusMap]; addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 077fa4315..b2d18c533 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -39,11 +39,16 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "chatDescriber/describe", "stats/getTokensPerDay", "stats/getTokensPerModel", + // Codebase "index/setPaused", "index/forceReIndex", - "index/indexingProgressBarInitialized", // Deprecated - "index/getStatuses", - + "index/indexingProgressBarInitialized", + // Docs, etc. + "indexing/getStatuses", + "indexing/reindex", + "indexing/abort", + "indexing/setPaused", + // "completeOnboarding", "addAutocompleteModel", "config/listProfiles", @@ -56,8 +61,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", "getDefaultModelTitle", - "indexProgress", - "index/statusUpdate", // + "indexProgress", // Codebase + "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index d974c1516..4fd2f7094 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,12 +1,17 @@ import { ConfigValidationError } from "../config/validation.js"; -import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js"; +import type { + ContextItemWithId, + IndexingProgressUpdate, + IndexingStatusUpdate, +} from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; + "indexing/statusUpdate": [IndexingStatusUpdate, void]; refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 58feba2a5..5329abdda 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -110,16 +110,8 @@ function useSetup(dispatch: Dispatch) { }); }); - const debouncedIndexDocs = debounce(() => { - ideMessenger.request("context/indexDocs", { reIndex: false }); - }, 1000); - useWebviewListener("configUpdate", async () => { await loadConfig(); - - if (!isJetBrains) { - debouncedIndexDocs(); - } }); useWebviewListener("configError", async (error) => {