| 1 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 2 | import { open, type Database } from "sqlite"; |
| 3 | import sqlite3 from "sqlite3"; |
| 4 | |
| 5 | import { |
| 6 | Chunk, |
| 7 | ContinueConfig, |
| 8 | DocsIndexingDetails, |
| 9 | IDE, |
| 10 | IdeInfo, |
| 11 | ILLM, |
| 12 | IndexingStatus, |
| 13 | SiteIndexingConfig, |
| 14 | } from "../.."; |
| 15 | import { ConfigHandler } from "../../config/ConfigHandler"; |
| 16 | import { isSupportedLanceDbCpuTargetForLinux } from "../../config/util"; |
| 17 | import DocsContextProvider from "../../context/providers/DocsContextProvider"; |
| 18 | import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; |
| 19 | import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; |
| 20 | import { IMessenger } from "../../protocol/messenger"; |
| 21 | import { fetchFavicon } from "../../util/fetchFavicon"; |
| 22 | import { GlobalContext } from "../../util/GlobalContext"; |
| 23 | import { |
| 24 | editConfigFile, |
| 25 | getDocsSqlitePath, |
| 26 | getLanceDbPath, |
| 27 | } from "../../util/paths"; |
| 28 | import { Telemetry } from "../../util/posthog"; |
| 29 | |
| 30 | import { |
| 31 | ArticleWithChunks, |
| 32 | htmlPageToArticleWithChunks, |
| 33 | markdownPageToArticleWithChunks, |
| 34 | } from "./article"; |
| 35 | import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; |
| 36 | import { runLanceMigrations, runSqliteMigrations } from "./migrations"; |
| 37 | |
| 38 | import type * as LanceType from "vectordb"; |
| 39 | import { LLMError } from "../../llm"; |
| 40 | |
| 41 | // Purposefully lowercase because lancedb converts |
| 42 | export interface LanceDbDocsRow { |
| 43 | title: string; |
| 44 | starturl: string; |
| 45 | // Chunk |
| 46 | content: string; |
| 47 | path: string; |
| 48 | startline: number; |
| 49 | endline: number; |
| 50 | vector: number[]; |
| 51 | [key: string]: any; |
| 52 | } |
| 53 | |
| 54 | export interface SqliteDocsRow { |
| 55 | title: string; |
| 56 | startUrl: string; |
| 57 | favicon: string; |
| 58 | } |
| 59 | |
| 60 | export type AddParams = { |
| 61 | siteIndexingConfig: SiteIndexingConfig; |
| 62 | chunks: Chunk[]; |
| 63 | embeddings: number[][]; |
| 64 | favicon?: string; |
| 65 | }; |
| 66 | |
| 67 | const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => { |
| 68 | const globalContext = new GlobalContext(); |
| 69 | const failedDocs = globalContext.get("failedDocs") ?? []; |
| 70 | const newFailedDocs = failedDocs.filter( |
| 71 | (d) => !docConfigsAreEqual(siteIndexingConfig, d), |
| 72 | ); |
| 73 | newFailedDocs.push(siteIndexingConfig); |
| 74 | globalContext.update("failedDocs", newFailedDocs); |
| 75 | }; |
| 76 | |
| 77 | const removeFromFailedGlobalContext = ( |
| 78 | siteIndexingConfig: SiteIndexingConfig, |
| 79 | ) => { |
| 80 | const globalContext = new GlobalContext(); |
| 81 | const failedDocs = globalContext.get("failedDocs") ?? []; |
| 82 | const newFailedDocs = failedDocs.filter( |
| 83 | (d) => !docConfigsAreEqual(siteIndexingConfig, d), |
| 84 | ); |
| 85 | globalContext.update("failedDocs", newFailedDocs); |
| 86 | }; |
| 87 | |
| 88 | const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => { |
| 89 | const globalContext = new GlobalContext(); |
| 90 | const failedDocs = globalContext.get("failedDocs") ?? []; |
| 91 | return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d)); |
| 92 | }; |
| 93 | |
| 94 | export function embedModelsAreEqual( |
| 95 | llm1: ILLM | null | undefined, |
| 96 | llm2: ILLM | null | undefined, |
| 97 | ): boolean { |
| 98 | return ( |
| 99 | llm1?.underlyingProviderName === llm2?.underlyingProviderName && |
| 100 | llm1?.title === llm2?.title && |
| 101 | llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize |
| 102 | ); |
| 103 | } |
| 104 | |
| 105 | const docConfigsAreEqual = ( |
| 106 | siteConfig1: SiteIndexingConfig, |
| 107 | siteConfig2: SiteIndexingConfig, |
| 108 | ) => { |
| 109 | return ( |
| 110 | siteConfig1.faviconUrl === siteConfig2.faviconUrl && |
| 111 | siteConfig1.title === siteConfig2.title && |
| 112 | docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) |
| 113 | ); |
| 114 | }; |
| 115 | |
| 116 | const docConfigsAreEqualExceptTitleAndFavicon = ( |
| 117 | siteConfig1: SiteIndexingConfig, |
| 118 | siteConfig2: SiteIndexingConfig, |
| 119 | ) => { |
| 120 | return ( |
| 121 | siteConfig1.startUrl === siteConfig2.startUrl && |
| 122 | siteConfig1.maxDepth === siteConfig2.maxDepth && |
| 123 | siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling |
| 124 | ); |
| 125 | }; |
| 126 | |
| 127 | const siteIndexingConfigsAreEqual = ( |
| 128 | siteConfig1: SiteIndexingConfig, |
| 129 | siteConfig2: SiteIndexingConfig, |
| 130 | contConfig1: ContinueConfig | undefined, |
| 131 | contConfig2: ContinueConfig, |
| 132 | ) => { |
| 133 | return ( |
| 134 | docConfigsAreEqual(siteConfig1, siteConfig2) && |
| 135 | embedModelsAreEqual( |
| 136 | contConfig1?.selectedModelByRole.embed, |
| 137 | contConfig2.selectedModelByRole.embed, |
| 138 | ) |
| 139 | ); |
| 140 | }; |
| 141 | |
| 142 | const siteIndexingConfigsAreEqualExceptTitleAndFavicon = ( |
| 143 | siteConfig1: SiteIndexingConfig, |
| 144 | siteConfig2: SiteIndexingConfig, |
| 145 | contConfig1: ContinueConfig | undefined, |
| 146 | contConfig2: ContinueConfig, |
| 147 | ) => { |
| 148 | return ( |
| 149 | docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) && |
| 150 | embedModelsAreEqual( |
| 151 | contConfig1?.selectedModelByRole.embed, |
| 152 | contConfig2.selectedModelByRole.embed, |
| 153 | ) |
| 154 | ); |
| 155 | }; |
| 156 | |
| 157 | /* |
| 158 | General process: |
| 159 | - On config update: |
| 160 | - Reindex ALL docs if embeddings provider has changed |
| 161 | - Otherwise, reindex docs with CHANGED URL/DEPTH |
| 162 | - And update docs with CHANGED TITLE/FAVICON |
| 163 | - Also, messages to core can trigger: |
| 164 | - delete |
| 165 | - reindex all |
| 166 | - add/index one |
| 167 | */ |
| 168 | export default class DocsService { |
| 169 | private static lance: typeof LanceType | null = null; |
| 170 | static lanceTableName = "docs"; |
| 171 | static sqlitebTableName = "docs"; |
| 172 | |
| 173 | static defaultEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); |
| 174 | |
| 175 | public isInitialized: Promise<void>; |
| 176 | public isSyncing: boolean = false; |
| 177 | |
| 178 | private docsIndexingQueue = new Set<string>(); |
| 179 | private lanceTableNamesSet = new Set<string>(); |
| 180 | |
| 181 | private config!: ContinueConfig; |
| 182 | private sqliteDb?: Database; |
| 183 | |
| 184 | private ideInfoPromise: Promise<IdeInfo>; |
| 185 | private githubToken?: string; |
| 186 | |
| 187 | constructor( |
| 188 | configHandler: ConfigHandler, |
| 189 | private readonly ide: IDE, |
| 190 | private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>, |
| 191 | ) { |
| 192 | this.ideInfoPromise = this.ide.getIdeInfo(); |
| 193 | this.isInitialized = this.init(configHandler); |
| 194 | } |
| 195 | |
| 196 | setGithubToken(token: string) { |
| 197 | this.githubToken = token; |
| 198 | } |
| 199 | |
| 200 | private async initLanceDb() { |
| 201 | if (!isSupportedLanceDbCpuTargetForLinux()) { |
| 202 | return null; |
| 203 | } |
| 204 | |
| 205 | try { |
| 206 | if (!DocsService.lance) { |
| 207 | DocsService.lance = await import("vectordb"); |
| 208 | } |
| 209 | return DocsService.lance; |
| 210 | } catch (err) { |
| 211 | console.error("Failed to load LanceDB:", err); |
| 212 | return null; |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // Singleton pattern: only one service globally |
| 217 | private static instance?: DocsService; |
| 218 | static createSingleton( |
| 219 | configHandler: ConfigHandler, |
| 220 | ide: IDE, |
| 221 | messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>, |
| 222 | ) { |
| 223 | const docsService = new DocsService(configHandler, ide, messenger); |
| 224 | DocsService.instance = docsService; |
| 225 | return docsService; |
| 226 | } |
| 227 | |
| 228 | static getSingleton() { |
| 229 | return DocsService.instance; |
| 230 | } |
| 231 | |
| 232 | // Initialization - load config and attach config listener |
| 233 | private async init(configHandler: ConfigHandler) { |
| 234 | const result = await configHandler.loadConfig(); |
| 235 | await this.handleConfigUpdate(result); |
| 236 | configHandler.onConfigUpdate( |
| 237 | this.handleConfigUpdate.bind(this) as (arg: any) => void, |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | readonly statuses: Map<string, IndexingStatus> = new Map(); |
| 242 | |
| 243 | handleStatusUpdate(update: IndexingStatus) { |
| 244 | this.statuses.set(update.id, update); |
| 245 | this.messenger?.send("indexing/statusUpdate", update); |
| 246 | } |
| 247 | |
| 248 | // A way for gui to retrieve initial statuses |
| 249 | async initStatuses(): Promise<void> { |
| 250 | if (!this.config?.docs) { |
| 251 | return; |
| 252 | } |
| 253 | const metadata = await this.listMetadata(); |
| 254 | |
| 255 | this.config.docs?.forEach((doc) => { |
| 256 | if (!doc.startUrl) { |
| 257 | console.error("Invalid config docs entry, no start url", doc.title); |
| 258 | return; |
| 259 | } |
| 260 | |
| 261 | const currentStatus = this.statuses.get(doc.startUrl); |
| 262 | if (currentStatus) { |
| 263 | this.handleStatusUpdate(currentStatus); |
| 264 | return; |
| 265 | } |
| 266 | |
| 267 | const sharedStatus: Omit< |
| 268 | IndexingStatus, |
| 269 | "progress" | "description" | "status" |
| 270 | > = { |
| 271 | type: "docs", |
| 272 | id: doc.startUrl, |
| 273 | isReindexing: false, |
| 274 | title: doc.title, |
| 275 | debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`, |
| 276 | icon: doc.faviconUrl, |
| 277 | url: doc.startUrl, |
| 278 | }; |
| 279 | if (this.config.selectedModelByRole.embed) { |
| 280 | sharedStatus.embeddingsProviderId = |
| 281 | this.config.selectedModelByRole.embed.embeddingId; |
| 282 | } |
| 283 | const indexedStatus: IndexingStatus = metadata.find( |
| 284 | (meta) => meta.startUrl === doc.startUrl, |
| 285 | ) |
| 286 | ? { |
| 287 | ...sharedStatus, |
| 288 | progress: 0, |
| 289 | description: "Pending", |
| 290 | status: "pending", |
| 291 | } |
| 292 | : { |
| 293 | ...sharedStatus, |
| 294 | progress: 1, |
| 295 | description: "Complete", |
| 296 | status: "complete", |
| 297 | }; |
| 298 | this.handleStatusUpdate(indexedStatus); |
| 299 | }); |
| 300 | } |
| 301 | |
| 302 | abort(startUrl: string) { |
| 303 | if (this.docsIndexingQueue.has(startUrl)) { |
| 304 | const status = this.statuses.get(startUrl); |
| 305 | if (status) { |
| 306 | this.handleStatusUpdate({ |
| 307 | ...status, |
| 308 | status: "aborted", |
| 309 | progress: 0, |
| 310 | description: "Canceled", |
| 311 | }); |
| 312 | } |
| 313 | this.docsIndexingQueue.delete(startUrl); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | // Used to check periodically during indexing if should cancel indexing |
| 318 | shouldCancel(startUrl: string, startedWithEmbedder: string) { |
| 319 | // Check if aborted |
| 320 | const isAborted = this.statuses.get(startUrl)?.status === "aborted"; |
| 321 | if (isAborted) { |
| 322 | return true; |
| 323 | } |
| 324 | |
| 325 | // Handle embeddings provider change mid-indexing |
| 326 | if ( |
| 327 | this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder |
| 328 | ) { |
| 329 | this.abort(startUrl); |
| 330 | return true; |
| 331 | } |
| 332 | return false; |
| 333 | } |
| 334 | |
| 335 | // Determine if transformers.js embeddings are supported in this environment |
| 336 | async canUseTransformersEmbeddings() { |
| 337 | const ideInfo = await this.ideInfoPromise; |
| 338 | if (ideInfo.ideType === "jetbrains") { |
| 339 | return false; |
| 340 | } |
| 341 | return true; |
| 342 | } |
| 343 | |
| 344 | // Get the appropriate embeddings provider |
| 345 | async getEmbeddingsProvider() { |
| 346 | // First check if there's a config selected embeddings provider |
| 347 | if (this.config.selectedModelByRole.embed) { |
| 348 | return { |
| 349 | provider: this.config.selectedModelByRole.embed, |
| 350 | }; |
| 351 | } |
| 352 | |
| 353 | // Fall back to transformers if supported |
| 354 | const canUseTransformers = await this.canUseTransformersEmbeddings(); |
| 355 | if (canUseTransformers) { |
| 356 | return { |
| 357 | provider: DocsService.defaultEmbeddingsProvider, |
| 358 | }; |
| 359 | } |
| 360 | |
| 361 | // No provider available |
| 362 | return { |
| 363 | provider: undefined, |
| 364 | }; |
| 365 | } |
| 366 | |
| 367 | private async handleConfigUpdate({ |
| 368 | config: newConfig, |
| 369 | }: ConfigResult<ContinueConfig>) { |
| 370 | if (newConfig) { |
| 371 | const oldConfig = this.config; |
| 372 | this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in |
| 373 | |
| 374 | // No point in indexing if no docs context provider |
| 375 | const hasDocsContextProvider = this.hasDocsContextProvider(); |
| 376 | if (!hasDocsContextProvider) { |
| 377 | return; |
| 378 | } |
| 379 | |
| 380 | // Skip docs indexing if not supported |
| 381 | // No warning message here because would show on ANY config update |
| 382 | if (!this.config.selectedModelByRole.embed) { |
| 383 | return; |
| 384 | } |
| 385 | |
| 386 | await this.syncDocs(oldConfig, newConfig, false); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | async syncDocsWithPrompt(reIndex: boolean = false) { |
| 391 | await this.syncDocs(undefined, this.config, reIndex); |
| 392 | |
| 393 | void this.ide.showToast("info", "Docs indexing completed"); |
| 394 | } |
| 395 | |
| 396 | // Returns true if startUrl has been indexed with current embeddingsProvider |
| 397 | async hasMetadata(startUrl: string): Promise<boolean> { |
| 398 | if (!this.config.selectedModelByRole.embed) { |
| 399 | return false; |
| 400 | } |
| 401 | const db = await this.getOrCreateSqliteDb(); |
| 402 | const title = await db.get( |
| 403 | `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, |
| 404 | startUrl, |
| 405 | this.config.selectedModelByRole.embed.embeddingId, |
| 406 | ); |
| 407 | |
| 408 | return !!title; |
| 409 | } |
| 410 | |
| 411 | async listMetadata() { |
| 412 | const embeddingsProvider = this.config.selectedModelByRole.embed; |
| 413 | if (!embeddingsProvider) { |
| 414 | return []; |
| 415 | } |
| 416 | const db = await this.getOrCreateSqliteDb(); |
| 417 | const docs = await db.all<SqliteDocsRow[]>( |
| 418 | `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName} |
| 419 | WHERE embeddingsProviderId = ?`, |
| 420 | embeddingsProvider.embeddingId, |
| 421 | ); |
| 422 | |
| 423 | return docs; |
| 424 | } |
| 425 | |
| 426 | async reindexDoc(startUrl: string) { |
| 427 | const docConfig = this.config.docs?.find( |
| 428 | (doc) => doc.startUrl === startUrl, |
| 429 | ); |
| 430 | if (docConfig) { |
| 431 | await this.indexAndAdd(docConfig, true); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | // eslint-disable-next-line max-statements |
| 436 | async indexAndAdd( |
| 437 | siteIndexingConfig: SiteIndexingConfig, |
| 438 | forceReindex: boolean = false, |
| 439 | ): Promise<void> { |
| 440 | const { startUrl, useLocalCrawling, maxDepth, faviconUrl } = |
| 441 | siteIndexingConfig; |
| 442 | |
| 443 | // First, if indexing is already in process, don't attempt |
| 444 | // This queue is necessary because indexAndAdd is invoked circularly by config edits |
| 445 | // TODO shouldn't really be a gap between adding and checking in queue but probably fine |
| 446 | if (this.docsIndexingQueue.has(startUrl)) { |
| 447 | return; |
| 448 | } |
| 449 | |
| 450 | const { provider } = await this.getEmbeddingsProvider(); |
| 451 | if (!provider) { |
| 452 | console.warn("@docs indexAndAdd: no embeddings provider found"); |
| 453 | return; |
| 454 | } |
| 455 | |
| 456 | const startedWithEmbedder = provider.embeddingId; |
| 457 | |
| 458 | // Check if doc has been successfully indexed with the given embedder |
| 459 | const indexExists = await this.hasMetadata(startUrl); |
| 460 | |
| 461 | // Build status update - most of it is fixed values |
| 462 | const fixedStatus: Omit< |
| 463 | IndexingStatus, |
| 464 | "progress" | "description" | "status" |
| 465 | > = { |
| 466 | type: "docs", |
| 467 | id: siteIndexingConfig.startUrl, |
| 468 | embeddingsProviderId: provider.embeddingId, |
| 469 | isReindexing: forceReindex && indexExists, |
| 470 | title: siteIndexingConfig.title, |
| 471 | debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`, |
| 472 | icon: siteIndexingConfig.faviconUrl, |
| 473 | url: siteIndexingConfig.startUrl, |
| 474 | }; |
| 475 | |
| 476 | // If not force-reindexing and has failed with same config, don't reattempt |
| 477 | if (!forceReindex) { |
| 478 | if (hasIndexingFailed(siteIndexingConfig)) { |
| 479 | console.log( |
| 480 | `Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`, |
| 481 | ); |
| 482 | this.handleStatusUpdate({ |
| 483 | ...fixedStatus, |
| 484 | description: "Failed", |
| 485 | status: "failed", |
| 486 | progress: 1, |
| 487 | }); |
| 488 | return; |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | if (indexExists && !forceReindex) { |
| 493 | this.handleStatusUpdate({ |
| 494 | ...fixedStatus, |
| 495 | progress: 1, |
| 496 | description: "Complete", |
| 497 | status: "complete", |
| 498 | debugInfo: "Already indexed", |
| 499 | }); |
| 500 | return; |
| 501 | } |
| 502 | |
| 503 | // Do a test run on the embedder |
| 504 | // This particular failure will not mark as a failed config in global context |
| 505 | // Since SiteIndexingConfig is likely to be valid |
| 506 | try { |
| 507 | await provider.embed(["continue-test-run"]); |
| 508 | } catch (e) { |
| 509 | if (e instanceof LLMError) { |
| 510 | // Report the error to the IDE |
| 511 | await this.messenger?.request("reportError", e); |
| 512 | } |
| 513 | this.handleStatusUpdate({ |
| 514 | ...fixedStatus, |
| 515 | description: `Failed to test embeddings connection. ${e}`, |
| 516 | status: "failed", |
| 517 | progress: 1, |
| 518 | }); |
| 519 | console.error("Failed to test embeddings connection", e); |
| 520 | return; |
| 521 | } |
| 522 | |
| 523 | try { |
| 524 | this.docsIndexingQueue.add(startUrl); |
| 525 | |
| 526 | // Clear current indexes if reIndexing |
| 527 | if (indexExists && forceReindex) { |
| 528 | await this.deleteIndexes(startUrl); |
| 529 | } |
| 530 | |
| 531 | this.addToConfig(siteIndexingConfig); |
| 532 | |
| 533 | this.handleStatusUpdate({ |
| 534 | ...fixedStatus, |
| 535 | status: "indexing", |
| 536 | description: "Finding subpages", |
| 537 | progress: 0, |
| 538 | }); |
| 539 | |
| 540 | // Crawl pages to get page data |
| 541 | const pages: PageData[] = []; |
| 542 | let processedPages = 0; |
| 543 | let estimatedProgress = 0; |
| 544 | let done = false; |
| 545 | let usedCrawler: DocsCrawlerType | undefined = undefined; |
| 546 | |
| 547 | const docsCrawler = new DocsCrawler( |
| 548 | this.ide, |
| 549 | this.config, |
| 550 | maxDepth, |
| 551 | undefined, |
| 552 | useLocalCrawling, |
| 553 | this.githubToken, |
| 554 | ); |
| 555 | const crawlerGen = docsCrawler.crawl(new URL(startUrl)); |
| 556 | |
| 557 | while (!done) { |
| 558 | const result = await crawlerGen.next(); |
| 559 | if (result.done) { |
| 560 | done = true; |
| 561 | usedCrawler = result.value; |
| 562 | } else { |
| 563 | const page = result.value; |
| 564 | estimatedProgress += 1 / 2 ** (processedPages + 1); |
| 565 | |
| 566 | // NOTE - during "indexing" phase, check if aborted before each status update |
| 567 | if (this.shouldCancel(startUrl, startedWithEmbedder)) { |
| 568 | return; |
| 569 | } |
| 570 | this.handleStatusUpdate({ |
| 571 | ...fixedStatus, |
| 572 | description: `Finding subpages (${page.path})`, |
| 573 | status: "indexing", |
| 574 | progress: |
| 575 | 0.15 * estimatedProgress + |
| 576 | Math.min(0.35, (0.35 * processedPages) / 500), |
| 577 | // For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max |
| 578 | }); |
| 579 | |
| 580 | pages.push(page); |
| 581 | |
| 582 | processedPages++; |
| 583 | |
| 584 | // Locks down GUI if no sleeping |
| 585 | // Wait proportional to how many docs are indexing |
| 586 | const toWait = 100 * this.docsIndexingQueue.size + 50; |
| 587 | await new Promise((resolve) => setTimeout(resolve, toWait)); |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | void Telemetry.capture("docs_pages_crawled", { |
| 592 | count: processedPages, |
| 593 | }); |
| 594 | |
| 595 | // Chunk pages based on which crawler was used |
| 596 | const articles: ArticleWithChunks[] = []; |
| 597 | const chunks: Chunk[] = []; |
| 598 | const articleChunker = |
| 599 | usedCrawler === "github" |
| 600 | ? markdownPageToArticleWithChunks |
| 601 | : htmlPageToArticleWithChunks; |
| 602 | for (const page of pages) { |
| 603 | const articleWithChunks = await articleChunker( |
| 604 | page, |
| 605 | provider.maxEmbeddingChunkSize, |
| 606 | ); |
| 607 | if (articleWithChunks) { |
| 608 | articles.push(articleWithChunks); |
| 609 | } |
| 610 | const toWait = 20 * this.docsIndexingQueue.size + 10; |
| 611 | await new Promise((resolve) => setTimeout(resolve, toWait)); |
| 612 | } |
| 613 | |
| 614 | // const chunks: Chunk[] = []; |
| 615 | const embeddings: number[][] = []; |
| 616 | |
| 617 | // Create embeddings of retrieved articles |
| 618 | for (let i = 0; i < articles.length; i++) { |
| 619 | const article = articles[i]; |
| 620 | |
| 621 | if (this.shouldCancel(startUrl, startedWithEmbedder)) { |
| 622 | return; |
| 623 | } |
| 624 | this.handleStatusUpdate({ |
| 625 | ...fixedStatus, |
| 626 | status: "indexing", |
| 627 | description: `Creating Embeddings: ${article.article.subpath}`, |
| 628 | progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80% |
| 629 | }); |
| 630 | |
| 631 | try { |
| 632 | const subpathEmbeddings = |
| 633 | article.chunks.length > 0 |
| 634 | ? await provider.embed(article.chunks.map((c) => c.content)) |
| 635 | : []; |
| 636 | chunks.push(...article.chunks); |
| 637 | embeddings.push(...subpathEmbeddings); |
| 638 | const toWait = 100 * this.docsIndexingQueue.size + 50; |
| 639 | await new Promise((resolve) => setTimeout(resolve, toWait)); |
| 640 | } catch (e) { |
| 641 | console.warn("Error embedding article chunks: ", e); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | if (embeddings.length === 0) { |
| 646 | console.error( |
| 647 | `No embeddings were created for site: ${startUrl}\n Num chunks: ${chunks.length}`, |
| 648 | ); |
| 649 | |
| 650 | if (this.shouldCancel(startUrl, startedWithEmbedder)) { |
| 651 | return; |
| 652 | } |
| 653 | this.handleStatusUpdate({ |
| 654 | ...fixedStatus, |
| 655 | description: `No embeddings were created for site: ${startUrl}`, |
| 656 | status: "failed", |
| 657 | progress: 1, |
| 658 | }); |
| 659 | |
| 660 | // void this.ide.showToast("info", `Failed to index ${startUrl}`); |
| 661 | markFailedInGlobalContext(siteIndexingConfig); |
| 662 | return; |
| 663 | } |
| 664 | |
| 665 | // Add docs to databases |
| 666 | console.log(`Adding ${embeddings.length} embeddings to db`); |
| 667 | |
| 668 | if (this.shouldCancel(startUrl, startedWithEmbedder)) { |
| 669 | return; |
| 670 | } |
| 671 | this.handleStatusUpdate({ |
| 672 | ...fixedStatus, |
| 673 | description: "Deleting old embeddings from the db", |
| 674 | status: "indexing", |
| 675 | progress: 0.8, |
| 676 | }); |
| 677 | |
| 678 | // Delete indexed docs if re-indexing |
| 679 | if (forceReindex && indexExists) { |
| 680 | console.log("Deleting old embeddings"); |
| 681 | await this.deleteIndexes(startUrl); |
| 682 | } |
| 683 | |
| 684 | const favicon = |
| 685 | faviconUrl || |
| 686 | (await fetchFavicon(new URL(siteIndexingConfig.startUrl))); |
| 687 | |
| 688 | if (this.shouldCancel(startUrl, startedWithEmbedder)) { |
| 689 | return; |
| 690 | } |
| 691 | this.handleStatusUpdate({ |
| 692 | ...fixedStatus, |
| 693 | description: `Adding ${embeddings.length} embeddings to db`, |
| 694 | status: "indexing", |
| 695 | progress: 0.85, |
| 696 | }); |
| 697 | |
| 698 | await this.add({ |
| 699 | siteIndexingConfig, |
| 700 | chunks, |
| 701 | embeddings, |
| 702 | favicon, |
| 703 | }); |
| 704 | |
| 705 | this.handleStatusUpdate({ |
| 706 | ...fixedStatus, |
| 707 | description: "Complete", |
| 708 | status: "complete", |
| 709 | progress: 1, |
| 710 | }); |
| 711 | |
| 712 | // Only show notificaitons if the user manually re-indexed, otherwise |
| 713 | // they are too noisy, especially when switching embeddings providers |
| 714 | // and we automatically re-index all docs |
| 715 | if (forceReindex) { |
| 716 | void this.ide.showToast("info", `Successfully indexed ${startUrl}`); |
| 717 | } |
| 718 | |
| 719 | removeFromFailedGlobalContext(siteIndexingConfig); |
| 720 | } catch (e) { |
| 721 | console.error( |
| 722 | `Error indexing docs at: ${siteIndexingConfig.startUrl}`, |
| 723 | e, |
| 724 | ); |
| 725 | let description = `Error indexing docs at: ${siteIndexingConfig.startUrl}`; |
| 726 | if (e instanceof Error) { |
| 727 | if ( |
| 728 | e.message.includes("github.com") && |
| 729 | e.message.includes("rate limit") |
| 730 | ) { |
| 731 | description = "Github rate limit exceeded"; // This text is used verbatim elsewhere |
| 732 | } |
| 733 | } |
| 734 | this.handleStatusUpdate({ |
| 735 | ...fixedStatus, |
| 736 | description, |
| 737 | status: "failed", |
| 738 | progress: 1, |
| 739 | }); |
| 740 | markFailedInGlobalContext(siteIndexingConfig); |
| 741 | } finally { |
| 742 | this.docsIndexingQueue.delete(startUrl); |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | // Retrieve docs embeds based on user input |
| 747 | async retrieveChunksFromQuery( |
| 748 | query: string, |
| 749 | startUrl: string, |
| 750 | nRetrieve: number, |
| 751 | ) { |
| 752 | const { provider } = await this.getEmbeddingsProvider(); |
| 753 | |
| 754 | if (!provider) { |
| 755 | void this.ide.showToast( |
| 756 | "error", |
| 757 | "Set up an embeddings model to use the @docs context provider. See: " + |
| 758 | "https://docs.continue.dev/customize/model-roles/embeddings", |
| 759 | ); |
| 760 | return []; |
| 761 | } |
| 762 | |
| 763 | // Try to get embeddings for the query |
| 764 | const [vector] = await provider.embed([query]); |
| 765 | |
| 766 | // Retrieve chunks using the query vector |
| 767 | return await this.retrieveChunks(startUrl, vector, nRetrieve); |
| 768 | } |
| 769 | |
| 770 | private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk { |
| 771 | return { |
| 772 | digest: row.path, |
| 773 | filepath: row.path, |
| 774 | startLine: row.startline, |
| 775 | endLine: row.endline, |
| 776 | index: 0, |
| 777 | content: row.content, |
| 778 | otherMetadata: { |
| 779 | title: row.title, |
| 780 | }, |
| 781 | }; |
| 782 | } |
| 783 | async getDetails(startUrl: string): Promise<DocsIndexingDetails> { |
| 784 | const db = await this.getOrCreateSqliteDb(); |
| 785 | |
| 786 | try { |
| 787 | const { provider } = await this.getEmbeddingsProvider(); |
| 788 | |
| 789 | if (!provider) { |
| 790 | throw new Error("No embeddings model set"); |
| 791 | } |
| 792 | |
| 793 | const result = await db.get( |
| 794 | `SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, |
| 795 | startUrl, |
| 796 | provider.embeddingId, |
| 797 | ); |
| 798 | |
| 799 | if (!result) { |
| 800 | throw new Error(`${startUrl} not found in sqlite`); |
| 801 | } |
| 802 | const siteIndexingConfig: SiteIndexingConfig = { |
| 803 | startUrl, |
| 804 | faviconUrl: result.favicon, |
| 805 | title: result.title, |
| 806 | }; |
| 807 | |
| 808 | const table = await this.getOrCreateLanceTable({ |
| 809 | initializationVector: [], |
| 810 | startUrl, |
| 811 | }); |
| 812 | const rows = (await table |
| 813 | .filter(`starturl = '${startUrl}'`) |
| 814 | .limit(1000) |
| 815 | .execute()) as LanceDbDocsRow[]; |
| 816 | |
| 817 | return { |
| 818 | startUrl, |
| 819 | config: siteIndexingConfig, |
| 820 | indexingStatus: this.statuses.get(startUrl), |
| 821 | chunks: rows.map(this.lanceDBRowToChunk), |
| 822 | }; |
| 823 | } catch (e) { |
| 824 | console.warn("Error getting details", e); |
| 825 | throw e; |
| 826 | } |
| 827 | } |
| 828 | // This function attempts to retrieve chunks by vector similarity |
| 829 | async retrieveChunks( |
| 830 | startUrl: string, |
| 831 | vector: number[], |
| 832 | nRetrieve: number, |
| 833 | isRetry: boolean = false, |
| 834 | ): Promise<Chunk[]> { |
| 835 | // Get the appropriate embeddings provider |
| 836 | const { provider } = await this.getEmbeddingsProvider(); |
| 837 | if (!provider) { |
| 838 | return []; |
| 839 | } |
| 840 | |
| 841 | // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name |
| 842 | const table = await this.getOrCreateLanceTable({ |
| 843 | initializationVector: vector, |
| 844 | startUrl, |
| 845 | }); |
| 846 | |
| 847 | let docs: LanceDbDocsRow[] = []; |
| 848 | try { |
| 849 | docs = await table |
| 850 | .search(vector) |
| 851 | .limit(nRetrieve) |
| 852 | .where(`starturl = '${startUrl}'`) |
| 853 | .execute(); |
| 854 | } catch (e: any) { |
| 855 | console.warn("Error retrieving chunks from LanceDB", e); |
| 856 | } |
| 857 | |
| 858 | return docs.map(this.lanceDBRowToChunk); |
| 859 | } |
| 860 | |
| 861 | async getIndexedPages(startUrl: string): Promise<Set<string>> { |
| 862 | try { |
| 863 | const table = await this.getOrCreateLanceTable({ |
| 864 | initializationVector: [], |
| 865 | startUrl, |
| 866 | }); |
| 867 | |
| 868 | const rows = (await table |
| 869 | .filter(`starturl = '${startUrl}'`) |
| 870 | .select(["path"]) // Only select path to minimize data transfer |
| 871 | .limit(99999999) // Default is 10, we want to show all |
| 872 | .execute()) as { path: string }[]; |
| 873 | |
| 874 | // Get unique paths (pages) |
| 875 | return new Set(rows.map((row) => row.path)); |
| 876 | } catch (e) { |
| 877 | console.warn(`Error getting page list for ${startUrl}:`, e); |
| 878 | return new Set(); |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | // SQLITE DB |
| 883 | private async getOrCreateSqliteDb() { |
| 884 | if (!this.sqliteDb) { |
| 885 | const db = await open({ |
| 886 | filename: getDocsSqlitePath(), |
| 887 | driver: sqlite3.Database, |
| 888 | }); |
| 889 | |
| 890 | await db.exec("PRAGMA busy_timeout = 3000;"); |
| 891 | |
| 892 | // First create the table if it doesn't exist |
| 893 | await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} ( |
| 894 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 895 | title STRING NOT NULL, |
| 896 | startUrl STRING NOT NULL, |
| 897 | favicon STRING, |
| 898 | embeddingsProviderId STRING |
| 899 | )`); |
| 900 | |
| 901 | await runSqliteMigrations(db); |
| 902 | |
| 903 | this.sqliteDb = db; |
| 904 | } |
| 905 | |
| 906 | return this.sqliteDb; |
| 907 | } |
| 908 | |
| 909 | async getFavicon(startUrl: string) { |
| 910 | if (!this.config.selectedModelByRole.embed) { |
| 911 | console.warn( |
| 912 | "Attempting to get favicon without embeddings provider specified", |
| 913 | ); |
| 914 | return; |
| 915 | } |
| 916 | const db = await this.getOrCreateSqliteDb(); |
| 917 | const result = await db.get( |
| 918 | `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, |
| 919 | startUrl, |
| 920 | this.config.selectedModelByRole.embed.embeddingId, |
| 921 | ); |
| 922 | |
| 923 | if (!result) { |
| 924 | return; |
| 925 | } |
| 926 | return result.favicon; |
| 927 | } |
| 928 | |
| 929 | /** |
| 930 | * Sync with no embeddings provider change |
| 931 | */ |
| 932 | private async syncDocs( |
| 933 | oldConfig: ContinueConfig | undefined, |
| 934 | newConfig: ContinueConfig, |
| 935 | forceReindex: boolean, |
| 936 | ) { |
| 937 | try { |
| 938 | this.isSyncing = true; |
| 939 | |
| 940 | // Otherwise sync the index based on config changes |
| 941 | const oldConfigDocs = oldConfig?.docs || []; |
| 942 | const newConfigDocs = newConfig.docs || []; |
| 943 | |
| 944 | // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here |
| 945 | const currentlyIndexedDocs = await this.listMetadata(); |
| 946 | const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); |
| 947 | |
| 948 | // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed |
| 949 | // Anything found in new config that isn't in sqlite should be added/indexed |
| 950 | const addedDocs: SiteIndexingConfig[] = []; |
| 951 | const changedDocs: SiteIndexingConfig[] = []; |
| 952 | for (const doc of newConfigDocs) { |
| 953 | const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); |
| 954 | |
| 955 | if (currentIndexedDoc) { |
| 956 | const oldConfigDoc = oldConfigDocs.find( |
| 957 | (d) => d.startUrl === doc.startUrl, |
| 958 | ); |
| 959 | |
| 960 | // TODO: Changes to the docs config made while Continue isn't running won't be caught |
| 961 | if ( |
| 962 | oldConfigDoc && |
| 963 | !siteIndexingConfigsAreEqual( |
| 964 | oldConfigDoc, |
| 965 | doc, |
| 966 | oldConfig, |
| 967 | newConfig, |
| 968 | ) |
| 969 | ) { |
| 970 | // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing |
| 971 | if ( |
| 972 | siteIndexingConfigsAreEqualExceptTitleAndFavicon( |
| 973 | oldConfigDoc, |
| 974 | doc, |
| 975 | oldConfig, |
| 976 | newConfig, |
| 977 | ) |
| 978 | ) { |
| 979 | await this.updateMetadataInSqlite(doc); |
| 980 | } else { |
| 981 | changedDocs.push(doc); |
| 982 | } |
| 983 | } else { |
| 984 | if (forceReindex) { |
| 985 | changedDocs.push(doc); |
| 986 | } else { |
| 987 | // This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running |
| 988 | // We only update title and faviconUrl here |
| 989 | await this.updateMetadataInSqlite(doc); |
| 990 | // if get's here, not changed, no update needed, mark as complete |
| 991 | this.handleStatusUpdate({ |
| 992 | type: "docs", |
| 993 | id: doc.startUrl, |
| 994 | embeddingsProviderId: |
| 995 | this.config.selectedModelByRole.embed?.embeddingId, |
| 996 | isReindexing: false, |
| 997 | title: doc.title, |
| 998 | debugInfo: "Config sync: not changed", |
| 999 | icon: doc.faviconUrl, |
| 1000 | url: doc.startUrl, |
| 1001 | progress: 1, |
| 1002 | description: "Complete", |
| 1003 | status: "complete", |
| 1004 | }); |
| 1005 | } |
| 1006 | } |
| 1007 | } else { |
| 1008 | addedDocs.push(doc); |
| 1009 | void Telemetry.capture("add_docs_config", { url: doc.startUrl }); |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | await Promise.allSettled([ |
| 1014 | ...changedDocs.map((doc) => this.indexAndAdd(doc, true)), |
| 1015 | ...addedDocs.map((doc) => this.indexAndAdd(doc)), |
| 1016 | ]); |
| 1017 | } catch (e) { |
| 1018 | console.error("Error syncing docs index on config update", e); |
| 1019 | } finally { |
| 1020 | this.isSyncing = false; |
| 1021 | // Refresh the submenu items for docs |
| 1022 | this.messenger?.send("refreshSubmenuItems", { |
| 1023 | providers: ["docs"], |
| 1024 | }); |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | private hasDocsContextProvider() { |
| 1029 | return !!this.config.contextProviders?.some( |
| 1030 | (provider) => |
| 1031 | provider.description.title === DocsContextProvider.description.title, |
| 1032 | ); |
| 1033 | } |
| 1034 | |
| 1035 | // Lance DB Initialization |
| 1036 | private async createLanceDocsTable( |
| 1037 | connection: LanceType.Connection, |
| 1038 | initializationVector: number[], |
| 1039 | tableName: string, |
| 1040 | ) { |
| 1041 | const mockRowTitle = "mockRowTitle"; |
| 1042 | const mockRow: LanceDbDocsRow[] = [ |
| 1043 | { |
| 1044 | title: mockRowTitle, |
| 1045 | vector: initializationVector, |
| 1046 | starturl: "", |
| 1047 | content: "", |
| 1048 | path: "", |
| 1049 | startline: 0, |
| 1050 | endline: 0, |
| 1051 | }, |
| 1052 | ]; |
| 1053 | |
| 1054 | const table = await connection.createTable(tableName, mockRow); |
| 1055 | |
| 1056 | await runLanceMigrations(table); |
| 1057 | |
| 1058 | await table.delete(`title = '${mockRowTitle}'`); |
| 1059 | } |
| 1060 | |
| 1061 | /** |
| 1062 | * From Lance: Table names can only contain alphanumeric characters, |
| 1063 | * underscores, hyphens, and periods |
| 1064 | */ |
| 1065 | private sanitizeLanceTableName(name: string) { |
| 1066 | return name.replace(/[^a-zA-Z0-9_.-]/g, "_"); |
| 1067 | } |
| 1068 | |
| 1069 | private async getLanceTableName(embeddingsProvider: ILLM) { |
| 1070 | const tableName = this.sanitizeLanceTableName( |
| 1071 | `${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`, |
| 1072 | ); |
| 1073 | |
| 1074 | return tableName; |
| 1075 | } |
| 1076 | |
| 1077 | private async getOrCreateLanceTable({ |
| 1078 | initializationVector, |
| 1079 | startUrl, |
| 1080 | }: { |
| 1081 | initializationVector: number[]; |
| 1082 | startUrl: string; |
| 1083 | }) { |
| 1084 | const lance = await this.initLanceDb(); |
| 1085 | if (!lance) { |
| 1086 | throw new Error("LanceDB not available on this platform"); |
| 1087 | } |
| 1088 | |
| 1089 | const conn = await lance.connect(getLanceDbPath()); |
| 1090 | const tableNames = await conn.tableNames(); |
| 1091 | const { provider } = await this.getEmbeddingsProvider(); |
| 1092 | |
| 1093 | if (!provider) { |
| 1094 | throw new Error( |
| 1095 | "Could not retrieve @docs Lance Table: no embeddings provider specified", |
| 1096 | ); |
| 1097 | } |
| 1098 | |
| 1099 | const tableNameFromEmbeddingsProvider = |
| 1100 | await this.getLanceTableName(provider); |
| 1101 | |
| 1102 | if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { |
| 1103 | if (initializationVector) { |
| 1104 | await this.createLanceDocsTable( |
| 1105 | conn, |
| 1106 | initializationVector, |
| 1107 | tableNameFromEmbeddingsProvider, |
| 1108 | ); |
| 1109 | } else { |
| 1110 | console.trace( |
| 1111 | "No existing Lance DB docs table was found and no initialization " + |
| 1112 | "vector was passed to create one", |
| 1113 | ); |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | const table = await conn.openTable(tableNameFromEmbeddingsProvider); |
| 1118 | |
| 1119 | this.lanceTableNamesSet.add(tableNameFromEmbeddingsProvider); |
| 1120 | |
| 1121 | return table; |
| 1122 | } |
| 1123 | |
| 1124 | // Methods for adding individual docs |
| 1125 | private async addToLance({ |
| 1126 | chunks, |
| 1127 | siteIndexingConfig, |
| 1128 | embeddings, |
| 1129 | }: AddParams) { |
| 1130 | const sampleVector = embeddings[0]; |
| 1131 | const { startUrl } = siteIndexingConfig; |
| 1132 | |
| 1133 | const table = await this.getOrCreateLanceTable({ |
| 1134 | startUrl, |
| 1135 | initializationVector: sampleVector, |
| 1136 | }); |
| 1137 | |
| 1138 | const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({ |
| 1139 | vector: embeddings[i], |
| 1140 | starturl: startUrl, |
| 1141 | title: chunk.otherMetadata?.title || siteIndexingConfig.title, |
| 1142 | content: chunk.content, |
| 1143 | path: chunk.filepath, |
| 1144 | startline: chunk.startLine, |
| 1145 | endline: chunk.endLine, |
| 1146 | })); |
| 1147 | |
| 1148 | await table.add(rows); |
| 1149 | } |
| 1150 | |
| 1151 | private async addMetadataToSqlite({ |
| 1152 | siteIndexingConfig: { title, startUrl }, |
| 1153 | favicon, |
| 1154 | }: AddParams) { |
| 1155 | if (!this.config.selectedModelByRole.embed) { |
| 1156 | console.warn( |
| 1157 | `Attempting to add metadata for ${startUrl} without embeddings provider specified`, |
| 1158 | ); |
| 1159 | return; |
| 1160 | } |
| 1161 | const db = await this.getOrCreateSqliteDb(); |
| 1162 | await db.run( |
| 1163 | `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`, |
| 1164 | title, |
| 1165 | startUrl, |
| 1166 | favicon, |
| 1167 | this.config.selectedModelByRole.embed.embeddingId, |
| 1168 | ); |
| 1169 | } |
| 1170 | |
| 1171 | private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) { |
| 1172 | const { startUrl, title, faviconUrl } = siteIndexingConfig; |
| 1173 | const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl))); |
| 1174 | if (!this.config.selectedModelByRole.embed) { |
| 1175 | console.warn( |
| 1176 | `Attempting to add metadata for ${startUrl} without embeddings provider specified`, |
| 1177 | ); |
| 1178 | return; |
| 1179 | } |
| 1180 | |
| 1181 | const db = await this.getOrCreateSqliteDb(); |
| 1182 | |
| 1183 | await db.run( |
| 1184 | `UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`, |
| 1185 | title, |
| 1186 | favicon, |
| 1187 | startUrl, |
| 1188 | this.config.selectedModelByRole.embed.embeddingId, |
| 1189 | ); |
| 1190 | } |
| 1191 | |
| 1192 | private addToConfig(siteIndexingConfig: SiteIndexingConfig) { |
| 1193 | // Handles the case where a user has manually added the doc to config.json |
| 1194 | // so it already exists in the file |
| 1195 | const doesEquivalentDocExist = this.config.docs?.some((doc) => |
| 1196 | docConfigsAreEqual(doc, siteIndexingConfig), |
| 1197 | ); |
| 1198 | |
| 1199 | if (!doesEquivalentDocExist) { |
| 1200 | editConfigFile( |
| 1201 | (config) => ({ |
| 1202 | ...config, |
| 1203 | docs: [ |
| 1204 | ...(config.docs?.filter( |
| 1205 | (doc) => doc.startUrl !== siteIndexingConfig.startUrl, |
| 1206 | ) ?? []), |
| 1207 | siteIndexingConfig, |
| 1208 | ], |
| 1209 | }), |
| 1210 | (config) => ({ |
| 1211 | ...config, |
| 1212 | docs: [ |
| 1213 | ...(config.docs?.filter( |
| 1214 | (doc) => (doc as any).startUrl !== siteIndexingConfig.startUrl, |
| 1215 | ) ?? []), |
| 1216 | { |
| 1217 | name: siteIndexingConfig.title, |
| 1218 | faviconUrl: siteIndexingConfig.faviconUrl, |
| 1219 | startUrl: siteIndexingConfig.startUrl, |
| 1220 | }, |
| 1221 | ], |
| 1222 | }), |
| 1223 | ); |
| 1224 | } |
| 1225 | } |
| 1226 | |
| 1227 | private async add(params: AddParams) { |
| 1228 | await this.addToLance(params); |
| 1229 | await this.addMetadataToSqlite(params); |
| 1230 | } |
| 1231 | |
| 1232 | // Delete methods |
| 1233 | private async deleteEmbeddingsFromLance(startUrl: string) { |
| 1234 | const lance = await this.initLanceDb(); |
| 1235 | if (!lance) { |
| 1236 | return; |
| 1237 | } |
| 1238 | |
| 1239 | for (const tableName of this.lanceTableNamesSet) { |
| 1240 | const conn = await lance.connect(getLanceDbPath()); |
| 1241 | const table = await conn.openTable(tableName); |
| 1242 | await table.delete(`starturl = '${startUrl}'`); |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | private async deleteMetadataFromSqlite(startUrl: string) { |
| 1247 | if (!this.config.selectedModelByRole.embed) { |
| 1248 | console.warn( |
| 1249 | `Attempting to delete metadata for ${startUrl} without embeddings provider specified`, |
| 1250 | ); |
| 1251 | return; |
| 1252 | } |
| 1253 | const db = await this.getOrCreateSqliteDb(); |
| 1254 | |
| 1255 | await db.run( |
| 1256 | `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, |
| 1257 | startUrl, |
| 1258 | this.config.selectedModelByRole.embed.embeddingId, |
| 1259 | ); |
| 1260 | } |
| 1261 | |
| 1262 | private deleteFromConfig(startUrl: string) { |
| 1263 | const doesDocExist = this.config.docs?.some( |
| 1264 | (doc) => doc.startUrl === startUrl, |
| 1265 | ); |
| 1266 | if (doesDocExist) { |
| 1267 | editConfigFile( |
| 1268 | (config) => ({ |
| 1269 | ...config, |
| 1270 | docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], |
| 1271 | }), |
| 1272 | (config) => ({ |
| 1273 | ...config, |
| 1274 | docs: |
| 1275 | config.docs?.filter( |
| 1276 | (doc) => "startUrl" in doc && doc.startUrl !== startUrl, |
| 1277 | ) || [], |
| 1278 | }), |
| 1279 | ); |
| 1280 | } |
| 1281 | } |
| 1282 | |
| 1283 | private async deleteIndexes(startUrl: string) { |
| 1284 | await this.deleteEmbeddingsFromLance(startUrl); |
| 1285 | await this.deleteMetadataFromSqlite(startUrl); |
| 1286 | } |
| 1287 | |
| 1288 | async delete(startUrl: string) { |
| 1289 | this.docsIndexingQueue.delete(startUrl); |
| 1290 | this.abort(startUrl); |
| 1291 | await this.deleteIndexes(startUrl); |
| 1292 | this.deleteFromConfig(startUrl); |
| 1293 | this.messenger?.send("refreshSubmenuItems", { |
| 1294 | providers: ["docs"], |
| 1295 | }); |
| 1296 | this.statuses.delete(startUrl); |
| 1297 | } |
| 1298 | } |