diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index ba2bf29b6..6eab55fa4 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"; @@ -88,38 +87,10 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const isJetBrainsAndPreIndexedDocsProvider = - await docsService.isJetBrainsAndPreIndexedDocsProvider(); - - if (isJetBrainsAndPreIndexedDocsProvider) { - void extras.ide.showToast( - "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + - "the embeddings provider, but it cannot be used with JetBrains. " + - "Please select a different embeddings provider to use the '@docs' " + - "context provider.", - ); - - return []; - } - - const preIndexedDoc = preIndexedDocs[query]; - - if (!!preIndexedDoc) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDoc["title"], - }); - } - - const embeddingsProvider = await docsService.getEmbeddingsProvider( - !!preIndexedDoc, - ); - - const [vector] = await embeddingsProvider.embed([extras.fullInput]); - - let chunks = await docsService.retrieveChunks( + await docsService.isInitialized; + let chunks = await docsService.retrieveChunksFromQuery( + extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, - vector, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); @@ -175,7 +146,7 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const docs = (await docsService.list()) ?? []; + const docs = (await docsService.listMetadata()) ?? []; const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); const submenuItemsMap = new Map(); diff --git a/core/core.ts b/core/core.ts index 18ae323c6..6510add64 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,6 +30,7 @@ import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; @@ -42,7 +43,7 @@ export class Core { codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; continueServerClientPromise: Promise; - indexingState: IndexingProgressUpdate; + codebaseIndexingState: IndexingProgressUpdate; controlPlaneClient: ControlPlaneClient; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -88,7 +89,11 @@ export class Core { // Ensure .continue directory is created setupInitialDotContinueDirectory(); - this.indexingState = { status: "loading", desc: "loading", progress: 0 }; + this.codebaseIndexingState = { + status: "loading", + desc: "loading", + progress: 0, + }; const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { @@ -148,6 +153,7 @@ export class Core { // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings + this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { void this.messenger.request("indexProgress", { progress: 1, @@ -272,34 +278,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.syncOrReindexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -365,6 +352,11 @@ export class Core { } }); + on("context/getSymbolsForFiles", async (msg) => { + const { uris } = msg.data; + return await getSymbolsForManyFiles(uris, this.ide); + }); + on("config/getSerializedProfileInfo", async (msg) => { return { config: await this.configHandler.getSerializedConfig(), @@ -687,6 +679,8 @@ export class Core { const rows = await DevDataSqliteDb.getTokensPerModel(); return rows; }); + + // Codebase indexing on("index/forceReIndex", async ({ data }) => { if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; @@ -702,17 +696,41 @@ export class Core { } }); on("index/setPaused", (msg) => { - new GlobalContext().update("indexingPaused", msg.data); + this.globalContext.update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; }); on("index/indexingProgressBarInitialized", async (msg) => { // Triggered when progress bar is initialized. // If a non-default state has been stored, update the indexing display to that state - if (this.indexingState.status !== "loading") { - void this.messenger.request("indexProgress", this.indexingState); + if (this.codebaseIndexingState.status !== "loading") { + void this.messenger.request( + "indexProgress", + this.codebaseIndexingState, + ); } }); + // Docs, etc. indexing + on("indexing/reindex", async (msg) => { + if (msg.data.type === "docs") { + void this.docsService.reindexDoc(msg.data.id); + } + }); + on("indexing/abort", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.abort(msg.data.id); + } + }); + on("indexing/setPaused", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.setPaused(msg.data.id, msg.data.paused); + } + }); + on("indexing/initStatuses", async (msg) => { + return this.docsService.initStatuses(); + }); + // + on("didChangeSelectedProfile", (msg) => { void this.configHandler.setSelectedProfile(msg.data.id); void this.configHandler.reloadConfig(); @@ -769,7 +787,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { void this.sendIndexingErrorTelemetry(update); @@ -803,7 +821,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { void this.sendIndexingErrorTelemetry(update); @@ -812,4 +830,6 @@ export class Core { this.messenger.send("refreshSubmenuItems", undefined); } + + // private } diff --git a/core/index.d.ts b/core/index.d.ts index 392a9e11c..ce2e59449 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,3 +1,4 @@ +import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -45,6 +46,30 @@ export interface IndexingProgressUpdate { debugInfo?: string; } +// This is more or less a V2 of IndexingProgressUpdate +export interface IndexingStatus { + id: string; + type: "docs"; + progress: number; + description: string; + status: + | "indexing" + | "complete" + | "paused" + | "failed" + | "aborted" + | "deleted" + | "pending"; + embeddingsProviderId: string; + isReindexing?: boolean; + debugInfo?: string; + title: string; + icon?: string; + url?: string; +} + +export type IndexingStatusMap = Map; + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, @@ -311,13 +336,19 @@ export interface InputModifiers { noContext: boolean; } +export interface SymbolWithRange extends RangeInFile { + name: string; + type: Parser.SyntaxNode["type"]; +} + +export type FileSymbolMap = Record; + export interface PromptLog { modelTitle: string; completionOptions: CompletionOptions; prompt: string; completion: string; } - export interface ChatHistoryItem { message: ChatMessage; editorState?: any; diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 599c4202a..8854d8e87 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -95,6 +95,6 @@ export default DocsCrawler; export { CheerioCrawler, ChromiumCrawler, - ChromiumInstaller as ChromiumInstaller, + ChromiumInstaller, GitHubCrawler, }; diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 9bac503c9..67d33020d 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -66,23 +66,20 @@ 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(); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); // config.json check expect(latestConfig.docs).toContainEqual(mockSiteConfig); // Lance DB check - const embeddingsProvider = await docsService.getEmbeddingsProvider(); - const [mockVector] = await embeddingsProvider.embed(["test"]); - let retrievedChunks = await docsService.retrieveChunks( + let retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); @@ -91,7 +88,7 @@ describe.skip("DocsService Integration Tests", () => { await docsService.delete(mockSiteConfig.startUrl); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); // config.json check latestConfig = await getReloadedConfig(); @@ -100,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => { ); // LanceDB check - retrievedChunks = await docsService.retrieveChunks( + retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); expect(retrievedChunks.length).toBe(0); @@ -133,17 +130,15 @@ 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(); - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); editConfigJson((config) => { const { docs, ...restConfig } = config; @@ -164,6 +159,6 @@ describe.skip("DocsService Integration Tests", () => { await new Promise((resolve) => setTimeout(resolve, 100)); } - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); }); }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index dde15f502..838e8fb54 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,8 +7,10 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingProgressUpdate, + IndexingStatusMap, + IndexingStatus, SiteIndexingConfig, + IdeInfo, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; @@ -36,6 +38,12 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +// Progress heuristic values +// subpages -> embeddings -> delete from db -> add to db +const PROGRESS_AT_EMBEDDING = 0.5; +const PROGRESS_AT_DELETE_OPERATIONS = 0.7; +const PROGRESS_AT_ADD_OPERATIONS = 0.8; + // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -62,13 +70,27 @@ export type AddParams = { favicon?: string; }; +/* + General process: + - On config update: + - Reindex ALL docs if embeddings provider has changed + - Otherwise, reindex docs with CHANGED URL/DEPTH + - And update docs with CHANGED TITLE/FAVICON + - Also, messages to core can trigger: + - delete + - reindex all + - add/index one + - Currently a full reindex deletes all docs rather than storing PER embeddings provider + - The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful +*/ export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; + static indexingType = "docs"; + static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); - private static instance?: DocsService; public isInitialized: Promise; public isSyncing: boolean = false; @@ -80,19 +102,19 @@ export default class DocsService { private sqliteDb?: Database; private docsCrawler!: DocsCrawler; + private ideInfoPromise: Promise; constructor( configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, ) { + this.ideInfoPromise = this.ide.getIdeInfo(); this.isInitialized = this.init(configHandler); } - static getSingleton() { - return DocsService.instance; - } - + // Singleton pattern: only one service globally + private static instance?: DocsService; static createSingleton( configHandler: ConfigHandler, ide: IDE, @@ -103,14 +125,79 @@ export default class DocsService { return docsService; } - async isJetBrainsAndPreIndexedDocsProvider(): Promise { - const isJetBrains = await this.isJetBrains(); + static getSingleton() { + return DocsService.instance; + } - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; + // Initialization - load config and attach config listener + private async init(configHandler: ConfigHandler) { + const config = await configHandler.loadConfig(); + await this.handleConfigUpdate({ config }); + configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); + } - return isJetBrains && isPreIndexedDocsProvider; + readonly statuses: IndexingStatusMap = new Map(); + + // Function for GUI to retrieve initial pending statuses + // And kickoff indexing where needed + async initStatuses() { + this.config?.docs?.forEach(async (doc) => { + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + this.handleStatusUpdate(currentStatus); + } else { + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + progress: 0, + description: "Pending", + status: "pending", + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }); + } + }); + } + + handleStatusUpdate(update: IndexingStatus) { + this.statuses.set(update.id, update); + this.messenger?.send("indexing/statusUpdate", update); + } + + abort(startUrl: string) { + const status = this.statuses.get(startUrl); + if (status) { + this.docsIndexingQueue.delete(startUrl); + this.handleStatusUpdate({ + ...status, + status: "aborted", + progress: 0, + description: "Canceled", + }); + } + } + + isAborted(startUrl: string) { + return this.statuses.get(startUrl)?.status === "aborted"; + } + + // NOTE Pausing not supported for docs yet + setPaused(startUrl: string, pause: boolean) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: pause ? "paused" : "indexing", + }); + } + } + + isPaused(startUrl: string) { + return this.statuses.get(startUrl)?.status === "paused"; } /* @@ -119,21 +206,95 @@ export default class DocsService { * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. */ async canUsePreindexedDocs() { - const isJetBrains = await this.isJetBrains(); - return !isJetBrains; + const ideInfo = await this.ideInfoPromise; + if (ideInfo.ideType === "jetbrains") { + return false; + } + return true; } - async delete(startUrl: string) { - await this.deleteFromLance(startUrl); - await this.deleteFromSqlite(startUrl); - this.deleteFromConfig(startUrl); + async isUsingUnsupportedPreIndexedEmbeddingsProvider() { + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + return isPreIndexedDocsProvider && !canUsePreindexedDocs; + } - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + async getEmbeddingsProvider( + isPreIndexedDoc: boolean = false, + ): Promise { + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + + if (canUsePreindexedDocs && isPreIndexedDoc) { + return DocsService.preIndexedDocsEmbeddingsProvider; + } + + return this.config.embeddingsProvider; + } + + private async handleConfigUpdate({ + config: newConfig, + }: { + config: ContinueConfig | undefined; + }) { + if (newConfig) { + const oldConfig = this.config; + this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in + + this.docsCrawler = new DocsCrawler(this.ide, newConfig); + + // Skip docs indexing if not supported + const unsupported = + await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); + if (unsupported) { + return; + } + + await this.syncOrReindexAllDocs(newConfig, oldConfig); } } - async has(startUrl: string): Promise> { + 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.id + ) { + // 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) { + if (!this.hasDocsContextProvider()) { + const didAddDocsContextProvider = + await this.showAddDocsContextProviderToast(); + + if (!didAddDocsContextProvider) { + return; + } + } + + await this.syncOrReindexAllDocs(this.config); + + void this.ide.showToast("info", "Docs indexing completed"); + } + + async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -166,27 +327,7 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocs(reIndex: boolean = false) { - if (!this.hasDocsContextProvider()) { - const didAddDocsContextProvider = - await this.showAddDocsContextProviderToast(); - - if (!didAddDocsContextProvider) { - return; - } - } - - const docs = await this.list(); - - for (const doc of docs) { - const generator = this.indexAndAdd(doc, reIndex); - while (!(await generator.next()).done) {} - } - - void this.ide.showToast("info", "Docs indexing completed"); - } - - async list() { + async listMetadata() { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, @@ -195,162 +336,303 @@ export default class DocsService { return docs; } - async *indexAndAdd( + 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; + + // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs + if (this.docsIndexingQueue.has(startUrl)) { + return; + } + const embeddingsProvider = await this.getEmbeddingsProvider(); - if (this.docsIndexingQueue.has(startUrl)) { - console.log("Already in queue"); - return; - } - - if (!reIndex && (await this.has(startUrl))) { - yield { - progress: 1, - desc: "Already indexed", - status: "done", - }; - return; - } - - // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - yield { - progress: 0, - desc: "Finding subpages", - status: "indexing", + const indexExists = await this.hasMetadata(startUrl); + + const fixedStatus: Pick< + IndexingStatus, + | "type" + | "id" + | "embeddingsProviderId" + | "isReindexing" + | "debugInfo" + | "icon" + | "url" + | "title" + > = { + type: "docs", + id: siteIndexingConfig.startUrl, + embeddingsProviderId: embeddingsProvider.id, + isReindexing: reIndex && indexExists, + title: siteIndexingConfig.title, + debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, + icon: siteIndexingConfig.faviconUrl, + url: siteIndexingConfig.startUrl, }; - const articles: Article[] = []; - let processedPages = 0; - let maxKnownPages = 1; - - // Crawl pages and retrieve info as articles - for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - processedPages++; - - const article = pageToArticle(page); - - if (!article) { - continue; - } - - articles.push(article); - - // Use a heuristic approach for progress calculation - const progress = Math.min(processedPages / maxKnownPages, 1); - - yield { - progress, // Yield the heuristic progress - desc: `Finding subpages (${page.path})`, - status: "indexing", - }; - - // Increase maxKnownPages to delay progress reaching 100% too soon - if (processedPages === maxKnownPages) { - maxKnownPages *= 2; - } - - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - void Telemetry.capture("docs_pages_crawled", { - count: processedPages, - }); - - const chunks: Chunk[] = []; - const embeddings: number[][] = []; - - // Create embeddings of retrieved articles - console.log(`Creating embeddings for ${articles.length} articles`); - - for (let i = 0; i < articles.length; i++) { - const article = articles[i]; - yield { - progress: i / articles.length, - desc: `Creating Embeddings: ${article.subpath}`, - status: "indexing", - }; - - try { - const chunkedArticle = chunkArticle( - article, - embeddingsProvider.maxChunkSize, - ); - - const chunkedArticleContents = chunkedArticle.map( - (chunk) => chunk.content, - ); - - chunks.push(...chunkedArticle); - - const subpathEmbeddings = await embeddingsProvider.embed( - chunkedArticleContents, - ); - - embeddings.push(...subpathEmbeddings); - } catch (e) { - console.warn("Error chunking article: ", e); + if (indexExists) { + if (reIndex) { + await this.deleteIndexes(startUrl); + } else { + this.handleStatusUpdate({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + debugInfo: "Already indexed", + }); + return; } } - if (embeddings.length === 0) { - console.error( - `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, - ); + try { + this.handleStatusUpdate({ + ...fixedStatus, + status: "indexing", + description: "Finding subpages", + progress: 0, + }); - yield { - progress: 1, - desc: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, - status: "failed", - }; + const articles: Article[] = []; + let processedPages = 0; + let estimatedProgress = 0; + + // Crawl pages and retrieve info as articles + for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { + estimatedProgress += 1 / 2 ** (processedPages + 1); + + // NOTE - during "indexing" phase, check if aborted before each status update + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Finding subpages (${page.path})`, + status: "indexing", + progress: + 0.3 * estimatedProgress + + Math.min(0.2, (0.2 * processedPages) / 500), + // For the first 50%, 30% is sum of series 1/(2^n) and the other 20% is based on number of files/ 500 max + }); + + const article = pageToArticle(page); + if (!article) { + continue; + } + articles.push(article); + + processedPages++; + await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping + } + + void Telemetry.capture("docs_pages_crawled", { + count: processedPages, + }); + + const chunks: Chunk[] = []; + const embeddings: number[][] = []; + + // Create embeddings of retrieved articles + console.debug(`Creating embeddings for ${articles.length} articles`); + + for (let i = 0; i < articles.length; i++) { + const article = articles[i]; + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + status: "indexing", + description: `Creating Embeddings: ${article.subpath}`, + progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80% + }); + + try { + const chunkedArticle = chunkArticle( + article, + embeddingsProvider.maxChunkSize, + ); + + const chunkedArticleContents = chunkedArticle.map( + (chunk) => chunk.content, + ); + + chunks.push(...chunkedArticle); + + const subpathEmbeddings = await embeddingsProvider.embed( + chunkedArticleContents, + ); + + embeddings.push(...subpathEmbeddings); + } catch (e) { + console.warn("Error chunking article: ", e); + } + } + + if (embeddings.length === 0) { + console.error( + `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, + ); + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...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); + return; + } + + // Add docs to databases + console.log(`Adding ${embeddings.length} embeddings to db`); + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: "Deleting old embeddings from the db", + status: "indexing", + progress: 0.8, + }); + + // Delete indexed docs if re-indexing + if (reIndex && indexExists) { + console.log("Deleting old embeddings"); + await this.deleteIndexes(startUrl); + } + + const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + progress: 0.85, + }); + + await this.add({ + siteIndexingConfig, + chunks, + embeddings, + favicon, + }); this.docsIndexingQueue.delete(startUrl); - return; + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: "Complete", + status: "complete", + progress: 1, + }); + + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } catch (e) { + console.error("Error indexing docs", e); + this.handleStatusUpdate({ + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + status: "failed", + progress: 1, + }); + } finally { + this.docsIndexingQueue.delete(startUrl); } + } - // Add docs to databases - console.log(`Adding ${embeddings.length} embeddings to db`); + // When user requests a pre-indexed doc for the first time + // And pre-indexed embeddings are supported + // Fetch pre-indexed embeddings from S3, add to Lance, and then search those + private async fetchAndAddPreIndexedDocEmbeddings(title: string) { + const embeddingsProvider = await this.getEmbeddingsProvider(true); - yield { - progress: 0.5, - desc: `Adding ${embeddings.length} embeddings to db`, - status: "indexing", - }; + const data = await downloadFromS3( + S3Buckets.continueIndexedDocs, + getS3Filename(embeddingsProvider.id, title), + ); - // Delete indexed docs if re-indexing - if (reIndex && (await this.has(startUrl.toString()))) { - console.log("Deleting old embeddings"); - await this.delete(startUrl); - } + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; + const startUrl = new URL(siteEmbeddings.url).toString(); - const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + const faviconUrl = preIndexedDocs[startUrl].faviconUrl; + const favicon = + typeof faviconUrl === "string" + ? await getFaviconBase64(faviconUrl) + : undefined; await this.add({ - siteIndexingConfig, - chunks, - embeddings, favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), }); + } - this.docsIndexingQueue.delete(startUrl); + // Retrieve docs embeds based on user input + async retrieveChunksFromQuery( + query: string, + startUrl: string, + nRetrieve: number, + ) { + if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { + await this.ide.showToast( + "error", + `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + + "the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE" + "Please select a different embeddings provider to use the '@docs' " + + "context provider.", + ); - yield { - progress: 1, - desc: "Done", - status: "done", - }; - - console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); - - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + return []; } + + const preIndexedDoc = preIndexedDocs[startUrl]; + if (!!preIndexedDoc) { + void Telemetry.capture("docs_pre_indexed_doc_used", { + doc: preIndexedDoc["title"], + }); + } + + const embeddingsProvider = + await this.getEmbeddingsProvider(!!preIndexedDoc); + + const [vector] = await embeddingsProvider.embed([query]); + + return await this.retrieveChunks(startUrl, vector, nRetrieve); } async retrieveChunks( @@ -359,9 +641,10 @@ export default class DocsService { nRetrieve: number, isRetry: boolean = false, ): Promise { + const isPreIndexedDoc = !!preIndexedDocs[startUrl]; const table = await this.getOrCreateLanceTable({ initializationVector: vector, - isPreIndexedDoc: !!preIndexedDocs[startUrl], + isPreIndexedDoc, }); let docs: LanceDbDocsRow[] = []; @@ -372,10 +655,10 @@ export default class DocsService { .where(`starturl = '${startUrl}'`) .execute(); } catch (e: any) { - console.error("Error retrieving chunks from LanceDB", e); + console.warn("Error retrieving chunks from LanceDB", e); } - const hasIndexedDoc = await this.hasIndexedDoc(startUrl); + const hasIndexedDoc = await this.hasMetadata(startUrl); if (!hasIndexedDoc && docs.length === 0) { const preIndexedDoc = preIndexedDocs[startUrl]; @@ -401,105 +684,7 @@ export default class DocsService { })); } - async getEmbeddingsProvider(isPreIndexedDoc: boolean = false) { - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - - if (isPreIndexedDoc && canUsePreindexedDocs) { - return DocsService.preIndexedDocsEmbeddingsProvider; - } - - return this.config.embeddingsProvider; - } - - async getFavicon(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const result = await db.get( - `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - if (!result) { - return; - } - return result.favicon; - } - - private async init(configHandler: ConfigHandler) { - this.config = await configHandler.loadConfig(); - this.docsCrawler = new DocsCrawler(this.ide, this.config); - - const embeddingsProvider = await this.getEmbeddingsProvider(); - - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - - configHandler.onConfigUpdate(async ({ config: newConfig }) => { - if (newConfig) { - const oldConfig = this.config; - - // Need to update class property for config at the beginning of this callback - // to ensure downstream methods have access to the latest config. - this.config = newConfig; - - if (oldConfig.docs !== newConfig.docs) { - await this.syncConfigAndSqlite(); - } - - const shouldReindex = - await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); - - if (shouldReindex) { - await this.reindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider, - ); - } - } - }); - } - - private async syncConfigAndSqlite() { - this.isSyncing = true; - - const sqliteDocs = await this.list(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; - - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; - - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( - (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], - ); - - 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) {} - } - - for (const doc of deletedDocs) { - // console.debug(`Deleting doc: ${doc.startUrl}`); - await this.delete(doc.startUrl); - } - - this.isSyncing = false; - } - - private hasDocsContextProvider() { - return !!this.config.contextProviders?.some( - (provider) => - provider.description.title === DocsContextProvider.description.title, - ); - } - + // SQLITE DB private async getOrCreateSqliteDb() { if (!this.sqliteDb) { const db = await open({ @@ -524,6 +709,118 @@ export default class DocsService { return this.sqliteDb; } + async getFavicon(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + const result = await db.get( + `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + if (!result) { + return; + } + return result.favicon; + } + + /* + Sync with no embeddings provider change + Ignores pre-indexed docs + */ + private async syncDocsOnConfigUpdate( + oldConfig: ContinueConfig | undefined, + newConfig: ContinueConfig, + ) { + try { + this.isSyncing = true; + + // Otherwise sync the index based on config changes + const oldConfigDocs = oldConfig?.docs || []; + const newConfigDocs = newConfig.docs || []; + const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); + + const currentlyIndexedDocs = await this.listMetadata(); + const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); + + // Anything found in sqlite but not in new config should be deleted if not preindexed + const deletedDocs = currentlyIndexedDocs.filter( + (doc) => + !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 currentIndexedDoc = currentStartUrls.includes(doc.startUrl); + + if (currentIndexedDoc) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); + if ( + oldConfigDoc && + (oldConfigDoc.maxDepth !== doc.maxDepth || + oldConfigDoc.title !== doc.title || + oldConfigDoc.faviconUrl !== doc.faviconUrl) + ) { + changedDocs.push(doc); + } else { + // if get's here, not changed, no update needed, mark as complete + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + title: doc.title, + debugInfo: "Config sync: not changed", + icon: doc.faviconUrl, + url: doc.startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); + } + } else { + newDocs.push(doc); + } + } + + // Sends "Pending" or current status for each + await this.initStatuses(); + + 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 }); + + await this.indexAndAdd(doc); + } + + for (const doc of deletedDocs) { + await this.deleteIndexes(doc.startUrl); + } + } catch (e) { + console.error("Error syncing docs index on config update", e); + } finally { + this.isSyncing = false; + } + } + + private hasDocsContextProvider() { + return !!this.config.contextProviders?.some( + (provider) => + provider.description.title === DocsContextProvider.description.title, + ); + } + + // Lance DB Initialization private async createLanceDocsTable( connection: Connection, initializationVector: number[], @@ -604,21 +901,7 @@ export default class DocsService { return table; } - private async isJetBrains() { - const ideInfo = await this.ide.getIdeInfo(); - return ideInfo.ideType === "jetbrains"; - } - - private async hasIndexedDoc(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const docs = await db.all( - `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - return docs.length > 0; - } - + // Methods for adding individual docs private async addToLance({ chunks, siteIndexingConfig, @@ -626,6 +909,7 @@ export default class DocsService { }: AddParams) { const sampleVector = embeddings[0]; const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + const table = await this.getOrCreateLanceTable({ isPreIndexedDoc, initializationVector: sampleVector, @@ -644,7 +928,7 @@ export default class DocsService { await table.add(rows); } - private async addToSqlite({ + private async addMetadataToSqlite({ siteIndexingConfig: { title, startUrl }, favicon, }: AddParams) { @@ -674,7 +958,7 @@ export default class DocsService { private async add(params: AddParams) { await this.addToLance(params); - await this.addToSqlite(params); + await this.addMetadataToSqlite(params); const isPreIndexedDoc = !!preIndexedDocs[params.siteIndexingConfig.startUrl]; @@ -684,7 +968,8 @@ export default class DocsService { } } - private async deleteFromLance(startUrl: string) { + // Delete methods + private async deleteEmbeddingsFromLance(startUrl: string) { for (const tableName of this.lanceTableNamesSet) { const conn = await lancedb.connect(getLanceDbPath()); const table = await conn.openTable(tableName); @@ -692,7 +977,7 @@ export default class DocsService { } } - private async deleteFromSqlite(startUrl: string) { + private async deleteMetadataFromSqlite(startUrl: string) { const db = await this.getOrCreateSqliteDb(); await db.run( `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -700,81 +985,32 @@ export default class DocsService { ); } - deleteFromConfig(startUrl: string) { - editConfigJson((config) => ({ - ...config, - docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], - })); + private deleteFromConfig(startUrl: string) { + const doesDocExist = this.config.docs?.some( + (doc) => doc.startUrl === startUrl, + ); + if (doesDocExist) { + editConfigJson((config) => ({ + ...config, + docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], + })); + } } - private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const embeddingsProvider = await this.getEmbeddingsProvider(true); - - const data = await downloadFromS3( - S3Buckets.continueIndexedDocs, - getS3Filename(embeddingsProvider.id, title), - ); - - const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const startUrl = new URL(siteEmbeddings.url).toString(); - - const faviconUrl = preIndexedDocs[startUrl].faviconUrl; - const favicon = - typeof faviconUrl === "string" - ? await getFaviconBase64(faviconUrl) - : undefined; - - await this.add({ - favicon, - siteIndexingConfig: { - startUrl, - title: siteEmbeddings.title, - }, - chunks: siteEmbeddings.chunks, - embeddings: siteEmbeddings.chunks.map((c) => c.embedding), - }); + async deleteIndexes(startUrl: string) { + await this.deleteEmbeddingsFromLance(startUrl); + await this.deleteMetadataFromSqlite(startUrl); } - private async shouldReindexDocsOnNewEmbeddingsProvider( - curEmbeddingsProviderId: EmbeddingsProvider["id"], - ): Promise { - const isJetBrainsAndPreIndexedDocsProvider = - await this.isJetBrainsAndPreIndexedDocsProvider(); + async delete(startUrl: string) { + await this.deleteIndexes(startUrl); + this.deleteFromConfig(startUrl); - if (isJetBrainsAndPreIndexedDocsProvider) { - // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider - // void this.ide.showToast( - // "error", - // "The 'transformers.js' embeddings provider currently cannot be used to index " + - // "documentation in JetBrains. To enable documentation indexing, you can use " + - // "any of the other providers described in the docs: " + - // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - // ); - - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ ...status, status: "deleted" }); } - - const lastEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - - if (!lastEmbeddingsProviderId) { - // If it's the first time we're setting the `curEmbeddingsProviderId` - // global state, we don't need to reindex docs - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - return lastEmbeddingsProviderId !== curEmbeddingsProviderId; + this.messenger?.send("refreshSubmenuItems", undefined); } /** @@ -782,27 +1018,21 @@ export default class DocsService { * A more optimal solution in the future will be to create * a per-embeddings-provider table for docs. */ - private async reindexDocsOnNewEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, - ) { + 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 } = this.config; + const { docs, embeddingsProvider } = this.config; if (!docs || docs.length === 0) { return; } console.log( - `Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`, + `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); - + await this.initStatuses(); for (const doc of docs) { - await this.delete(doc.startUrl); - - const generator = this.indexAndAdd(doc); - - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc, true); } // Important that this only is invoked after we have successfully @@ -810,8 +1040,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"); } } - -export const docsServiceSingleton = DocsService.getSingleton(); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 01a0201eb..c2f76d0a8 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,6 +14,11 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +/** + * Bedrock class implements AWS Bedrock LLM integration. + * It handles streaming completions and chat messages using AWS Bedrock runtime. + * Supports both text and image inputs through Claude 3 models. + */ class Bedrock extends BaseLLM { static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { @@ -122,7 +127,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -164,7 +171,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e30de4673..a53ef3f2b 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -7,7 +7,9 @@ import type { ContextItemWithId, ContextSubmenuItem, DiffLine, + FileSymbolMap, IdeSettings, + IndexingStatusMap, LLMFullCompletionOptions, MessageContent, ModelDescription, @@ -76,6 +78,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; @@ -142,6 +145,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 }, @@ -155,6 +160,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + + // Docs etc. Indexing. TODO move codebase to this + "indexing/reindex": [{ type: string; id: string }, void]; + "indexing/abort": [{ type: string; id: string }, void]; + "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; + "indexing/initStatuses": [undefined, void]; + addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 21ac52c8d..7a1392617 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/deleteModel", "config/reload", "context/getContextItems", + "context/getSymbolsForFiles", "context/loadSubmenuItems", "context/addDocs", "context/removeDocs", @@ -39,10 +40,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "chatDescriber/describe", "stats/getTokensPerDay", "stats/getTokensPerModel", + // Codebase "index/setPaused", "index/forceReIndex", "index/forceReIndexFiles", "index/indexingProgressBarInitialized", + // Docs, etc. + "indexing/initStatuses", + "indexing/reindex", + "indexing/abort", + "indexing/setPaused", + // "completeOnboarding", "addAutocompleteModel", "config/listProfiles", @@ -55,7 +63,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", "getDefaultModelTitle", - "indexProgress", + "indexProgress", // Codebase + "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index d974c1516..d259fde9e 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, + IndexingStatus, +} from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; - indexProgress: [IndexingProgressUpdate, void]; + indexProgress: [IndexingProgressUpdate, void]; // Codebase + "indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc. refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 9118b80ee..22a59e85c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; +import { FileSymbolMap, IDE, SymbolWithRange } from ".."; export enum LanguageName { CPP = "cpp", @@ -205,3 +206,93 @@ async function loadLanguageForFileExt( ); return await Parser.Language.load(wasmPath); } + +// See https://tree-sitter.github.io/tree-sitter/using-parsers +const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ + "class_declaration", + "class_definition", + "function_item", // function name = first "identifier" child + "function_definition", + "method_declaration", // method name = first "identifier" child + "method_definition", + "generator_function_declaration", + // property_identifier + // field_declaration + // "arrow_function", +]; + +export async function getSymbolsForFile( + filepath: string, + contents: string, +): Promise { + const parser = await getParserForFile(filepath); + + if (!parser) { + return; + } + + const tree = parser.parse(contents); + // console.log(`file: ${filepath}`); + + // Function to recursively find all named nodes (classes and functions) + const symbols: SymbolWithRange[] = []; + function findNamedNodesRecursive(node: Parser.SyntaxNode) { + // console.log(`node: ${node.type}, ${node.text}`); + if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { + // console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); + // node.children.forEach((child) => { + // console.log(`child: ${child.type}, ${child.text}`); + // }); + + // Empirically, the actual name is the last identifier in the node + // Especially with languages where return type is declared before the name + // TODO use findLast in newer version of node target + let identifier: Parser.SyntaxNode | undefined = undefined; + for (let i = node.children.length - 1; i >= 0; i--) { + if ( + node.children[i].type === "identifier" || + node.children[i].type === "property_identifier" + ) { + identifier = node.children[i]; + break; + } + } + + if (identifier?.text) { + symbols.push({ + filepath, + type: node.type, + name: identifier.text, + range: { + start: { + character: node.startPosition.column, + line: node.startPosition.row, + }, + end: { + character: node.endPosition.column + 1, + line: node.endPosition.row + 1, + }, + }, + }); + } + } + node.children.forEach(findNamedNodesRecursive); + } + findNamedNodesRecursive(tree.rootNode); + + return symbols; +} + +export async function getSymbolsForManyFiles( + uris: string[], + ide: IDE, +): Promise { + const filesAndSymbols = await Promise.all( + uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { + const contents = await ide.readFile(uri); + const symbols = await getSymbolsForFile(uri, contents); + return [uri, symbols ?? []]; + }), + ); + return Object.fromEntries(filesAndSymbols); +} diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 7761b605f..7edceced4 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2356,7 +2356,7 @@ "type": "integer", "description": "The maximum depth to crawl the documentation site" }, - "favicon": { + "faviconUrl": { "type": "string", "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 26107c199..695389c29 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,11 +1,12 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionInfo } from "core"; import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; import useHistory from "../../hooks/useHistory"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { RootState } from "../../redux/store"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -29,6 +30,9 @@ export function HistoryTableRow({ const [sessionTitleEditValue, setSessionTitleEditValue] = useState( session.title, ); + const currentSessionId = useSelector( + (state: RootState) => state.state.sessionId, + ); const { saveSession, deleteSession, loadSession, getSession, updateSession } = useHistory(dispatch); @@ -59,8 +63,11 @@ export function HistoryTableRow({ className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { // Save current session - await saveSession(); - await loadSession(session.sessionId); + if (session.sessionId !== currentSessionId) { + await saveSession(); + await loadSession(session.sessionId); + } + navigate("/"); }} > diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index f5673e4e8..4fdd6eda2 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -93,6 +93,7 @@ export default function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 3c97e09e6..098194886 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,11 +1,20 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; +import { + CheckCircleIcon, + ChevronDownIcon, + ChevronUpIcon, +} from "@heroicons/react/24/outline"; import { SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import { Button, HelperText, Input, lightGray } from ".."; +import { useDispatch, useSelector } from "react-redux"; +import { Button, HelperText, Input, lightGray, SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "../indexing/IndexingStatus"; function AddDocsDialog() { const posthog = usePostHog(); @@ -18,7 +27,12 @@ function AddDocsDialog() { const [faviconUrl, setFaviconUrl] = useState(""); const [isOpen, setIsOpen] = useState(false); + const [submittedConfig, setSubmittedConfig] = useState(); + const ideMessenger = useContext(IdeMessengerContext); + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexing.statuses, + ); const isFormValid = startUrl && title; @@ -41,15 +55,66 @@ function AddDocsDialog() { ideMessenger.post("context/addDocs", siteIndexingConfig); + setSubmittedConfig(siteIndexingConfig); setTitle(""); setStartUrl(""); setFaviconUrl(""); - dispatch(setShowDialog(false)); - posthog.capture("add_docs_gui", { url: startUrl }); } + if (submittedConfig) { + const status = indexingStatuses[submittedConfig.startUrl]; + return ( +
+
+ +

{`Docs added`}

+
+
+

Title: {submittedConfig.title}

+

Start URL: {submittedConfig.startUrl}

+ {submittedConfig.rootUrl && ( +

Root URL: {submittedConfig.rootUrl}

+ )} + {submittedConfig.maxDepth && ( +

Max depth: {submittedConfig.maxDepth}

+ )} + {submittedConfig.faviconUrl && ( +

Favicon URL: {submittedConfig.faviconUrl}

+ )} +
+ {!!status && ( +
+

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

+
+ +
+
+ )} +
+ { + setSubmittedConfig(undefined); + }} + > + Add another + + +
+
+ ); + } + return (
diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 33214fdfb..7685109ba 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -34,7 +34,6 @@ const DialogContainer = styled.div` top: 50%; left: 50%; transform: translate(-50%, -50%); - width: 75%; `; const Dialog = styled.div` @@ -72,6 +71,7 @@ const TextDialog = (props: TextDialogProps) => { return (
+
+ +

Help center

diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index c601c9650..26fbacbb1 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -174,8 +174,11 @@ function Edit() { }, ideMessenger, [], + dispatch, ); + // Note, not currently updating file symbols in edit mode + const prompt = [ ...contextItems.map((item) => item.content), stripImages(userInstructions), diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index aee6d9416..a48ac244b 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -59,6 +59,7 @@ import { } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; import { useFindWidget } from "../../components/find/FindWidget"; const StopButton = styled.div` @@ -317,7 +318,7 @@ export function Chat() { {widget} 0 ? "h-full" : ""}`} + className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${state.history.length > 0 ? "flex-1" : ""}`} onScroll={handleScroll} > {highlights} @@ -464,6 +465,11 @@ export function Chat() { )}
+
+ +
); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 5fba54889..770e9ce69 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -5,14 +5,16 @@ import { ChatMessage, Checkpoint, ContextItemWithId, + FileSymbolMap, + IndexingStatus, PersistedSessionInfo, PromptLog, } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { v4 as uuidv4, v4 } from "uuid"; import { ApplyState } from "core/protocol/ideWebview"; +import { v4 as uuidv4, v4 } from "uuid"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -21,9 +23,13 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { }; type State = { history: ChatHistoryItemWithMessageId[]; + symbols: FileSymbolMap; + context: { + isGathering: boolean; + gatheringMessage: string; + }; ttsActive: boolean; active: boolean; - isGatheringContext: boolean; config: BrowserSerializedContinueConfig; title: string; sessionId: string; @@ -35,15 +41,23 @@ type State = { curCheckpointIndex: number; applyStates: ApplyState[]; nextCodeBlockToApplyIndex: number; + indexing: { + hiddenChatPeekTypes: Record; + statuses: Record; + }; streamAborter: AbortController; isMultifileEdit: boolean; }; const initialState: State = { history: [], + symbols: {}, + context: { + isGathering: false, + gatheringMessage: "Gathering Context", + }, ttsActive: false, active: false, - isGatheringContext: false, configError: undefined, config: { slashCommands: [ @@ -68,6 +82,12 @@ const initialState: State = { curCheckpointIndex: 0, nextCodeBlockToApplyIndex: 0, applyStates: [], + indexing: { + statuses: {}, + hiddenChatPeekTypes: { + docs: false, + }, + }, streamAborter: new AbortController(), }; @@ -112,8 +132,17 @@ export const stateSlice = createSlice({ setActive: (state) => { state.active = true; }, - setIsGatheringContext: (state, { payload }: PayloadAction) => { - state.isGatheringContext = payload; + setIsGatheringContext: ( + state, + { + payload, + }: PayloadAction<{ + isGathering: boolean; + gatheringMessage: string; + }>, + ) => { + state.context.isGathering = payload.isGathering; + state.context.gatheringMessage = payload.gatheringMessage; }, clearLastEmptyResponse: (state) => { if (state.history.length < 2) { @@ -129,6 +158,12 @@ export const stateSlice = createSlice({ consumeMainEditorContent: (state) => { state.mainEditorContent = undefined; }, + updateFileSymbols: (state, action: PayloadAction) => { + state.symbols = { + ...state.symbols, + ...action.payload, + }; + }, setContextItemsAtIndex: ( state, { @@ -245,10 +280,13 @@ export const stateSlice = createSlice({ if (!historyItem) { return; } - historyItem.contextItems.push(...payload.contextItems); + historyItem.contextItems = [ + ...historyItem.contextItems, + ...payload.contextItems, + ]; }, setInactive: (state) => { - state.isGatheringContext = false; + state.context.isGathering = false; state.active = false; }, abortStream: (state) => { @@ -269,8 +307,9 @@ export const stateSlice = createSlice({ state.streamAborter = new AbortController(); state.active = false; - state.isGatheringContext = false; + state.context.isGathering = false; state.isMultifileEdit = false; + state.symbols = {}; if (payload) { state.history = payload.history as any; state.title = payload.title; @@ -372,10 +411,47 @@ export const stateSlice = createSlice({ resetNextCodeBlockToApplyIndex: (state) => { state.nextCodeBlockToApplyIndex = 0; }, + updateIndexingStatus: ( + state, + { payload }: PayloadAction, + ) => { + state.indexing.statuses = { + ...state.indexing.statuses, + [payload.id]: payload, + }; + + // This check is so that if all indexing is stopped for e.g. docs + // The next time docs indexing starts the peek will show again + const indexingThisType = Object.values(state.indexing.statuses).filter( + (status) => + status.type === payload.type && status.status === "indexing", + ); + if (indexingThisType.length === 0) { + state.indexing.hiddenChatPeekTypes = { + ...state.indexing.hiddenChatPeekTypes, + [payload.type]: false, + }; + } + }, + setIndexingChatPeekHidden: ( + state, + { + payload, + }: PayloadAction<{ + type: IndexingStatus["type"]; + hidden: boolean; + }>, + ) => { + state.indexing.hiddenChatPeekTypes = { + ...state.indexing.hiddenChatPeekTypes, + [payload.type]: payload.hidden, + }; + }, }, }); export const { + updateFileSymbols, setContextItemsAtIndex, addContextItemsAtIndex, setInactive, @@ -401,6 +477,8 @@ export const { setCurCheckpointIndex, resetNextCodeBlockToApplyIndex, updateApplyState, + updateIndexingStatus, + setIndexingChatPeekHidden, abortStream, } = stateSlice.actions; diff --git a/gui/src/util/symbols.ts b/gui/src/util/symbols.ts new file mode 100644 index 000000000..5c4e1be12 --- /dev/null +++ b/gui/src/util/symbols.ts @@ -0,0 +1,35 @@ +import { ContextItemWithId } from "core"; +import { IIdeMessenger } from "../context/IdeMessenger"; +import { updateFileSymbols } from "../redux/slices/stateSlice"; +import { Dispatch } from "@reduxjs/toolkit"; + +export async function updateFileSymbolsFromContextItems( + contextItems: ContextItemWithId[], + ideMessenger: IIdeMessenger, + dispatch: Dispatch, +) { + // Given a list of context items, + // Get unique file uris + try { + const contextUris = Array.from( + new Set( + contextItems + .filter((item) => item.uri?.type === "file" && item?.uri?.value) + .map((item) => item.uri.value), + ), + ); + // And then update symbols for those files + if (contextUris.length > 0) { + const symbolsResult = await ideMessenger.request( + "context/getSymbolsForFiles", + { uris: contextUris }, + ); + if (symbolsResult.status === "success") { + dispatch(updateFileSymbols(symbolsResult.content)); + } + } + } catch (e) { + // Catch all - don't want file symbols to break the chat experience for now + console.error("Error updating file symbols from context items", e); + } +}