| 1 | import * as fs from "fs/promises"; |
| 2 | |
| 3 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 4 | import { |
| 5 | ContinueConfig, |
| 6 | IDE, |
| 7 | IndexingProgressUpdate, |
| 8 | IndexTag, |
| 9 | } from "../index.js"; |
| 10 | import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; |
| 11 | import type { IMessenger } from "../protocol/messenger"; |
| 12 | import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; |
| 13 | import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; |
| 14 | import { Telemetry } from "../util/posthog.js"; |
| 15 | import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; |
| 16 | |
| 17 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 18 | import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js"; |
| 19 | import { ContinueServerClient } from "../continueServer/stubs/client"; |
| 20 | import { LLMError } from "../llm/index.js"; |
| 21 | import { getRootCause } from "../util/errors.js"; |
| 22 | import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; |
| 23 | import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; |
| 24 | import { embedModelsAreEqual } from "./docs/DocsService.js"; |
| 25 | import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; |
| 26 | import { LanceDbIndex } from "./LanceDbIndex.js"; |
| 27 | import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js"; |
| 28 | import { |
| 29 | CodebaseIndex, |
| 30 | IndexResultType, |
| 31 | PathAndCacheKey, |
| 32 | RefreshIndexResults, |
| 33 | } from "./types.js"; |
| 34 | import { walkDirAsync } from "./walkDir.js"; |
| 35 | |
| 36 | export class PauseToken { |
| 37 | constructor(private _paused: boolean) {} |
| 38 | |
| 39 | set paused(value: boolean) { |
| 40 | this._paused = value; |
| 41 | } |
| 42 | |
| 43 | get paused(): boolean { |
| 44 | return this._paused; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | export class CodebaseIndexer { |
| 49 | /** |
| 50 | * We batch for two reasons: |
| 51 | * - To limit memory usage for indexes that perform computations locally, e.g. FTS |
| 52 | * - To make as few requests as possible to the embeddings providers |
| 53 | */ |
| 54 | filesPerBatch = 200; |
| 55 | // We normally allow this to run in the background, |
| 56 | // and only need to `await` it for tests. |
| 57 | public initPromise: Promise<void>; |
| 58 | private config!: ContinueConfig; |
| 59 | private indexingCancellationController: AbortController | undefined; |
| 60 | private codebaseIndexingState: IndexingProgressUpdate; |
| 61 | private readonly pauseToken: PauseToken; |
| 62 | |
| 63 | private getUserFriendlyIndexName(artifactId: string): string { |
| 64 | if (artifactId === FullTextSearchCodebaseIndex.artifactId) |
| 65 | return "Full text search"; |
| 66 | if (artifactId === CodeSnippetsCodebaseIndex.artifactId) |
| 67 | return "Code snippets"; |
| 68 | if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking"; |
| 69 | if (artifactId.startsWith("vectordb")) return "Embedding"; |
| 70 | return artifactId; // fallback to original |
| 71 | } |
| 72 | |
| 73 | // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on, |
| 74 | // e.g. a `SQLITE_BUSY` error. |
| 75 | errorsRegexesToClearIndexesOn = [ |
| 76 | /Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/, |
| 77 | /SQLITE_CONSTRAINT/, |
| 78 | /SQLITE_ERROR/, |
| 79 | /SQLITE_CORRUPT/, |
| 80 | /SQLITE_IOERR/, |
| 81 | /SQLITE_FULL/, |
| 82 | ]; |
| 83 | |
| 84 | constructor( |
| 85 | private readonly configHandler: ConfigHandler, |
| 86 | protected readonly ide: IDE, |
| 87 | private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>, |
| 88 | initialPaused: boolean = false, |
| 89 | ) { |
| 90 | this.codebaseIndexingState = { |
| 91 | status: "loading", |
| 92 | desc: "loading", |
| 93 | progress: 0, |
| 94 | }; |
| 95 | |
| 96 | // Initialize pause token |
| 97 | this.pauseToken = new PauseToken(initialPaused); |
| 98 | |
| 99 | this.initPromise = this.init(configHandler); |
| 100 | } |
| 101 | |
| 102 | // Initialization - load config and attach config listener |
| 103 | private async init(configHandler: ConfigHandler) { |
| 104 | const result = await configHandler.loadConfig(); |
| 105 | await this.handleConfigUpdate(result); |
| 106 | configHandler.onConfigUpdate( |
| 107 | this.handleConfigUpdate.bind(this) as (arg: any) => void, |
| 108 | ); |
| 109 | } |
| 110 | |
| 111 | set paused(value: boolean) { |
| 112 | this.pauseToken.paused = value; |
| 113 | } |
| 114 | |
| 115 | get paused(): boolean { |
| 116 | return this.pauseToken.paused; |
| 117 | } |
| 118 | |
| 119 | async clearIndexes() { |
| 120 | const sqliteFilepath = getIndexSqlitePath(); |
| 121 | const lanceDbFolder = getLanceDbPath(); |
| 122 | |
| 123 | try { |
| 124 | await fs.unlink(sqliteFilepath); |
| 125 | } catch (error) { |
| 126 | console.error(`Error deleting ${sqliteFilepath} folder: ${error}`); |
| 127 | } |
| 128 | |
| 129 | try { |
| 130 | await fs.rm(lanceDbFolder, { recursive: true, force: true }); |
| 131 | } catch (error) { |
| 132 | console.error(`Error deleting ${lanceDbFolder}: ${error}`); |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | protected async getIndexesToBuild(): Promise<CodebaseIndex[]> { |
| 137 | const { config } = await this.configHandler.loadConfig(); |
| 138 | if (!config) { |
| 139 | return []; |
| 140 | } |
| 141 | |
| 142 | const embeddingsModel = config.selectedModelByRole.embed; |
| 143 | if (!embeddingsModel) { |
| 144 | return []; |
| 145 | } |
| 146 | |
| 147 | const ideSettings = await this.ide.getIdeSettings(); |
| 148 | if (!ideSettings) { |
| 149 | return []; |
| 150 | } |
| 151 | const continueServerClient = new ContinueServerClient( |
| 152 | ideSettings.remoteConfigServerUrl, |
| 153 | ideSettings.userToken, |
| 154 | ); |
| 155 | if (!continueServerClient) { |
| 156 | return []; |
| 157 | } |
| 158 | |
| 159 | const indexes: CodebaseIndex[] = [ |
| 160 | new ChunkCodebaseIndex( |
| 161 | this.ide.readFile.bind(this.ide), |
| 162 | continueServerClient, |
| 163 | embeddingsModel.maxEmbeddingChunkSize, |
| 164 | ), // Chunking must come first |
| 165 | ]; |
| 166 | |
| 167 | const lanceDbIndex = await LanceDbIndex.create( |
| 168 | embeddingsModel, |
| 169 | this.ide.readFile.bind(this.ide), |
| 170 | ); |
| 171 | |
| 172 | if (lanceDbIndex) { |
| 173 | indexes.push(lanceDbIndex); |
| 174 | } |
| 175 | |
| 176 | indexes.push( |
| 177 | new FullTextSearchCodebaseIndex(), |
| 178 | new CodeSnippetsCodebaseIndex(this.ide), |
| 179 | ); |
| 180 | |
| 181 | return indexes; |
| 182 | } |
| 183 | |
| 184 | private totalIndexOps(results: RefreshIndexResults): number { |
| 185 | return ( |
| 186 | results.compute.length + |
| 187 | results.del.length + |
| 188 | results.addTag.length + |
| 189 | results.removeTag.length |
| 190 | ); |
| 191 | } |
| 192 | |
| 193 | private singleFileIndexOps( |
| 194 | results: RefreshIndexResults, |
| 195 | lastUpdated: PathAndCacheKey[], |
| 196 | filePath: string, |
| 197 | ): [RefreshIndexResults, PathAndCacheKey[]] { |
| 198 | const filterFn = (item: PathAndCacheKey) => item.path === filePath; |
| 199 | const compute = results.compute.filter(filterFn); |
| 200 | const del = results.del.filter(filterFn); |
| 201 | const addTag = results.addTag.filter(filterFn); |
| 202 | const removeTag = results.removeTag.filter(filterFn); |
| 203 | const newResults = { |
| 204 | compute, |
| 205 | del, |
| 206 | addTag, |
| 207 | removeTag, |
| 208 | }; |
| 209 | const newLastUpdated = lastUpdated.filter(filterFn); |
| 210 | return [newResults, newLastUpdated]; |
| 211 | } |
| 212 | |
| 213 | public async refreshFile( |
| 214 | file: string, |
| 215 | workspaceDirs: string[], |
| 216 | ): Promise<void> { |
| 217 | if (this.pauseToken.paused) { |
| 218 | // FIXME: by returning here, there is a chance that while paused a file is modified and |
| 219 | // then after unpausing the file is not reindexed |
| 220 | return; |
| 221 | } |
| 222 | const { foundInDir } = findUriInDirs(file, workspaceDirs); |
| 223 | if (!foundInDir) { |
| 224 | return; |
| 225 | } |
| 226 | const branch = await this.ide.getBranch(foundInDir); |
| 227 | const repoName = await this.ide.getRepoName(foundInDir); |
| 228 | const indexesToBuild = await this.getIndexesToBuild(); |
| 229 | const stats = await this.ide.getFileStats([file]); |
| 230 | const filePath = Object.keys(stats)[0]; |
| 231 | for (const index of indexesToBuild) { |
| 232 | const tag = { |
| 233 | directory: foundInDir, |
| 234 | branch, |
| 235 | artifactId: index.artifactId, |
| 236 | }; |
| 237 | const [fullResults, fullLastUpdated, markComplete] = |
| 238 | await getComputeDeleteAddRemove( |
| 239 | tag, |
| 240 | { ...stats }, |
| 241 | (filepath) => this.ide.readFile(filepath), |
| 242 | repoName, |
| 243 | ); |
| 244 | |
| 245 | const [results, lastUpdated] = this.singleFileIndexOps( |
| 246 | fullResults, |
| 247 | fullLastUpdated, |
| 248 | filePath, |
| 249 | ); |
| 250 | // Don't update if nothing to update. Some of the indices might do unnecessary setup work |
| 251 | if (this.totalIndexOps(results) + lastUpdated.length === 0) { |
| 252 | continue; |
| 253 | } |
| 254 | |
| 255 | for await (const _ of index.update( |
| 256 | tag, |
| 257 | results, |
| 258 | markComplete, |
| 259 | repoName, |
| 260 | )) { |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | private async *refreshFiles( |
| 266 | files: string[], |
| 267 | ): AsyncGenerator<IndexingProgressUpdate> { |
| 268 | let progress = 0; |
| 269 | if (files.length === 0) { |
| 270 | yield { |
| 271 | progress: 1, |
| 272 | desc: "Indexing Complete", |
| 273 | status: "done", |
| 274 | }; |
| 275 | } |
| 276 | |
| 277 | const workspaceDirs = await this.ide.getWorkspaceDirs(); |
| 278 | |
| 279 | const progressPer = 1 / files.length; |
| 280 | try { |
| 281 | for (const file of files) { |
| 282 | yield { |
| 283 | progress, |
| 284 | desc: `Indexing file ${file}...`, |
| 285 | status: "indexing", |
| 286 | }; |
| 287 | await this.refreshFile(file, workspaceDirs); |
| 288 | |
| 289 | progress += progressPer; |
| 290 | |
| 291 | if (this.pauseToken.paused) { |
| 292 | yield* this.yieldUpdateAndPause(); |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | yield { |
| 297 | progress: 1, |
| 298 | desc: "Indexing Complete", |
| 299 | status: "done", |
| 300 | }; |
| 301 | } catch (err) { |
| 302 | yield this.handleErrorAndGetProgressUpdate(err); |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | async *refreshDirs( |
| 307 | dirs: string[], |
| 308 | abortSignal: AbortSignal, |
| 309 | ): AsyncGenerator<IndexingProgressUpdate> { |
| 310 | let progress = 0; |
| 311 | |
| 312 | if (dirs.length === 0) { |
| 313 | yield { |
| 314 | progress: 1, |
| 315 | desc: "Nothing to index", |
| 316 | status: "done", |
| 317 | }; |
| 318 | return; |
| 319 | } |
| 320 | |
| 321 | const { config } = await this.configHandler.loadConfig(); |
| 322 | if (!config) { |
| 323 | return; |
| 324 | } |
| 325 | if (config.disableIndexing) { |
| 326 | yield { |
| 327 | progress, |
| 328 | desc: "Indexing is disabled in config.json", |
| 329 | status: "disabled", |
| 330 | }; |
| 331 | return; |
| 332 | } else { |
| 333 | yield { |
| 334 | progress, |
| 335 | desc: "Starting indexing", |
| 336 | status: "loading", |
| 337 | }; |
| 338 | } |
| 339 | |
| 340 | // Wait until Git Extension has loaded to report progress |
| 341 | // so we don't appear stuck at 0% while waiting |
| 342 | await this.ide.getRepoName(dirs[0]); |
| 343 | |
| 344 | yield { |
| 345 | progress, |
| 346 | desc: "Starting indexing...", |
| 347 | status: "loading", |
| 348 | }; |
| 349 | const beginTime = Date.now(); |
| 350 | let collectedWarnings: string[] = []; |
| 351 | |
| 352 | for (const directory of dirs) { |
| 353 | const dirBasename = getUriPathBasename(directory); |
| 354 | yield { |
| 355 | progress, |
| 356 | desc: `Discovering files in ${dirBasename}...`, |
| 357 | status: "indexing", |
| 358 | }; |
| 359 | const directoryFiles = []; |
| 360 | for await (const p of walkDirAsync(directory, this.ide, { |
| 361 | source: "codebase indexing: refresh dirs", |
| 362 | })) { |
| 363 | directoryFiles.push(p); |
| 364 | if (abortSignal.aborted) { |
| 365 | yield { |
| 366 | progress: 0, |
| 367 | desc: "Indexing cancelled", |
| 368 | status: "cancelled", |
| 369 | }; |
| 370 | return; |
| 371 | } |
| 372 | if (this.pauseToken.paused) { |
| 373 | yield* this.yieldUpdateAndPause(); |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | const branch = await this.ide.getBranch(directory); |
| 378 | const repoName = await this.ide.getRepoName(directory); |
| 379 | let nextLogThreshold = 0; |
| 380 | |
| 381 | for await (const updateDesc of this.indexFiles( |
| 382 | directory, |
| 383 | directoryFiles, |
| 384 | branch, |
| 385 | repoName, |
| 386 | )) { |
| 387 | // Handle pausing in this loop because it's the only one really taking time |
| 388 | if (abortSignal.aborted) { |
| 389 | yield { |
| 390 | progress: 0, |
| 391 | desc: "Indexing cancelled", |
| 392 | status: "cancelled", |
| 393 | }; |
| 394 | return; |
| 395 | } |
| 396 | if (this.pauseToken.paused) { |
| 397 | yield* this.yieldUpdateAndPause(); |
| 398 | } |
| 399 | |
| 400 | // Collect warnings from indexFiles |
| 401 | if (updateDesc.warnings && updateDesc.warnings.length > 0) { |
| 402 | collectedWarnings = [...updateDesc.warnings]; |
| 403 | } |
| 404 | |
| 405 | yield updateDesc; |
| 406 | if (updateDesc.progress >= nextLogThreshold) { |
| 407 | // log progress every 2.5% |
| 408 | nextLogThreshold += 0.025; |
| 409 | this.logProgress( |
| 410 | beginTime, |
| 411 | Math.floor(directoryFiles.length * updateDesc.progress), |
| 412 | updateDesc.progress, |
| 413 | ); |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // Final completion message with preserved warnings |
| 419 | yield { |
| 420 | progress: 1, |
| 421 | desc: |
| 422 | collectedWarnings.length > 0 |
| 423 | ? `Indexing completed with ${collectedWarnings.length} warning(s)` |
| 424 | : "Indexing Complete", |
| 425 | status: "done", |
| 426 | warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined, |
| 427 | }; |
| 428 | this.logProgress(beginTime, 0, 1); |
| 429 | } |
| 430 | |
| 431 | private handleErrorAndGetProgressUpdate( |
| 432 | err: unknown, |
| 433 | ): IndexingProgressUpdate { |
| 434 | console.log("error when indexing: ", err); |
| 435 | if (err instanceof Error) { |
| 436 | const cause = getRootCause(err); |
| 437 | if (cause instanceof LLMError) { |
| 438 | throw cause; |
| 439 | } |
| 440 | return this.errorToProgressUpdate(err); |
| 441 | } |
| 442 | return { |
| 443 | progress: 0, |
| 444 | desc: `Indexing failed: ${err}`, |
| 445 | status: "failed", |
| 446 | debugInfo: extractMinimalStackTraceInfo((err as any)?.stack), |
| 447 | }; |
| 448 | } |
| 449 | |
| 450 | private errorToProgressUpdate(err: Error): IndexingProgressUpdate { |
| 451 | const cause = getRootCause(err); |
| 452 | let errMsg: string = `${cause}`; |
| 453 | let shouldClearIndexes = false; |
| 454 | |
| 455 | // Check if any of the error regexes match |
| 456 | for (const regexStr of this.errorsRegexesToClearIndexesOn) { |
| 457 | const regex = new RegExp(regexStr); |
| 458 | const match = err.message.match(regex); |
| 459 | |
| 460 | if (match !== null) { |
| 461 | shouldClearIndexes = true; |
| 462 | break; |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | return { |
| 467 | progress: 0, |
| 468 | desc: errMsg, |
| 469 | status: "failed", |
| 470 | shouldClearIndexes, |
| 471 | debugInfo: extractMinimalStackTraceInfo(err.stack), |
| 472 | }; |
| 473 | } |
| 474 | |
| 475 | private logProgress( |
| 476 | beginTime: number, |
| 477 | completedFileCount: number, |
| 478 | progress: number, |
| 479 | ) { |
| 480 | const timeTaken = Date.now() - beginTime; |
| 481 | const seconds = Math.round(timeTaken / 1000); |
| 482 | const progressPercentage = (progress * 100).toFixed(1); |
| 483 | const filesPerSec = (completedFileCount / seconds).toFixed(2); |
| 484 | // console.debug( |
| 485 | // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`, |
| 486 | // ); |
| 487 | } |
| 488 | |
| 489 | private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> { |
| 490 | yield { |
| 491 | progress: 0, |
| 492 | desc: "Indexing Paused", |
| 493 | status: "paused", |
| 494 | }; |
| 495 | while (this.pauseToken.paused) { |
| 496 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /* |
| 501 | * Enables the indexing operation to be completed in batches, this is important in large |
| 502 | * repositories where indexing can quickly use up all the memory available |
| 503 | */ |
| 504 | private *batchRefreshIndexResults( |
| 505 | results: RefreshIndexResults, |
| 506 | ): Generator<RefreshIndexResults> { |
| 507 | let curPos = 0; |
| 508 | while ( |
| 509 | curPos < results.compute.length || |
| 510 | curPos < results.del.length || |
| 511 | curPos < results.addTag.length || |
| 512 | curPos < results.removeTag.length |
| 513 | ) { |
| 514 | yield { |
| 515 | compute: results.compute.slice(curPos, curPos + this.filesPerBatch), |
| 516 | del: results.del.slice(curPos, curPos + this.filesPerBatch), |
| 517 | addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch), |
| 518 | removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch), |
| 519 | }; |
| 520 | curPos += this.filesPerBatch; |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | private async *indexFiles( |
| 525 | directory: string, |
| 526 | files: string[], |
| 527 | branch: string, |
| 528 | repoName: string | undefined, |
| 529 | ): AsyncGenerator<IndexingProgressUpdate> { |
| 530 | const stats = await this.ide.getFileStats(files); |
| 531 | const indexesToBuild = await this.getIndexesToBuild(); |
| 532 | let completedIndexCount = 0; |
| 533 | let progress = 0; |
| 534 | const warnings: string[] = []; |
| 535 | |
| 536 | for (const codebaseIndex of indexesToBuild) { |
| 537 | const tag: IndexTag = { |
| 538 | directory, |
| 539 | branch, |
| 540 | artifactId: codebaseIndex.artifactId, |
| 541 | }; |
| 542 | yield { |
| 543 | progress: progress, |
| 544 | desc: `Planning changes for ${codebaseIndex.artifactId} index...`, |
| 545 | status: "indexing", |
| 546 | warnings: warnings.length > 0 ? [...warnings] : undefined, |
| 547 | }; |
| 548 | |
| 549 | try { |
| 550 | const [results, lastUpdated, markComplete] = |
| 551 | await getComputeDeleteAddRemove( |
| 552 | tag, |
| 553 | { ...stats }, |
| 554 | (filepath) => this.ide.readFile(filepath), |
| 555 | repoName, |
| 556 | ); |
| 557 | const totalOps = this.totalIndexOps(results); |
| 558 | let completedOps = 0; |
| 559 | |
| 560 | // Don't update if nothing to update. Some of the indices might do unnecessary setup work |
| 561 | if (totalOps > 0) { |
| 562 | for (const subResult of this.batchRefreshIndexResults(results)) { |
| 563 | try { |
| 564 | for await (const { desc } of codebaseIndex.update( |
| 565 | tag, |
| 566 | subResult, |
| 567 | markComplete, |
| 568 | repoName, |
| 569 | )) { |
| 570 | yield { |
| 571 | progress, |
| 572 | desc, |
| 573 | status: "indexing", |
| 574 | warnings: warnings.length > 0 ? [...warnings] : undefined, |
| 575 | }; |
| 576 | } |
| 577 | completedOps += |
| 578 | subResult.compute.length + |
| 579 | subResult.del.length + |
| 580 | subResult.addTag.length + |
| 581 | subResult.removeTag.length; |
| 582 | progress = |
| 583 | (completedIndexCount + completedOps / totalOps) * |
| 584 | (1 / indexesToBuild.length); |
| 585 | } catch (err) { |
| 586 | // Collect non-fatal errors as warnings and continue |
| 587 | const warningMsg = |
| 588 | err instanceof Error ? err.message : String(err); |
| 589 | const friendlyName = this.getUserFriendlyIndexName( |
| 590 | codebaseIndex.artifactId, |
| 591 | ); |
| 592 | warnings.push(`${friendlyName}: ${warningMsg}`); |
| 593 | console.warn(`${friendlyName}: ${warningMsg}`, err); |
| 594 | |
| 595 | // Complete this batch and continue with next |
| 596 | completedOps += |
| 597 | subResult.compute.length + |
| 598 | subResult.del.length + |
| 599 | subResult.addTag.length + |
| 600 | subResult.removeTag.length; |
| 601 | progress = |
| 602 | (completedIndexCount + completedOps / totalOps) * |
| 603 | (1 / indexesToBuild.length); |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); |
| 609 | completedIndexCount += 1; |
| 610 | } catch (err) { |
| 611 | // Handle errors during planning phase |
| 612 | const cause = getRootCause(err as Error); |
| 613 | if (cause instanceof LLMError) { |
| 614 | // LLM errors are critical, re-throw them |
| 615 | throw cause; |
| 616 | } |
| 617 | |
| 618 | // Collect planning errors as warnings and continue to next index |
| 619 | const errorMsg = err instanceof Error ? err.message : String(err); |
| 620 | const friendlyName = this.getUserFriendlyIndexName( |
| 621 | codebaseIndex.artifactId, |
| 622 | ); |
| 623 | warnings.push(`${friendlyName}: ${errorMsg}`); |
| 624 | console.warn( |
| 625 | `Warning during ${codebaseIndex.artifactId} planning:`, |
| 626 | err, |
| 627 | ); |
| 628 | completedIndexCount += 1; |
| 629 | progress = completedIndexCount * (1 / indexesToBuild.length); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | // Final update with any collected warnings |
| 634 | if (warnings.length > 0) { |
| 635 | yield { |
| 636 | progress: 1, |
| 637 | desc: `Indexing completed with ${warnings.length} warning(s)`, |
| 638 | status: "done", |
| 639 | warnings: [...warnings], |
| 640 | }; |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | // New methods using messenger directly |
| 645 | |
| 646 | private updateProgress(update: IndexingProgressUpdate) { |
| 647 | this.codebaseIndexingState = update; |
| 648 | if (this.messenger) { |
| 649 | void this.messenger.request("indexProgress", update); |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) { |
| 654 | console.debug( |
| 655 | "Indexing failed with error: ", |
| 656 | update.desc, |
| 657 | update.debugInfo, |
| 658 | ); |
| 659 | void Telemetry.capture( |
| 660 | "indexing_error", |
| 661 | { |
| 662 | error: update.desc, |
| 663 | stack: update.debugInfo, |
| 664 | }, |
| 665 | false, |
| 666 | ); |
| 667 | } |
| 668 | |
| 669 | /** |
| 670 | * We want to prevent sqlite concurrent write errors |
| 671 | * when there are 2 indexing happening from different windows. |
| 672 | * We want the other window to wait until the first window's indexing finishes. |
| 673 | * Incase the first window closes before indexing is finished, |
| 674 | * we want to unlock the IndexLock by checking the last timestamp. |
| 675 | */ |
| 676 | private async *waitForDBIndex(): AsyncGenerator<IndexingProgressUpdate> { |
| 677 | let foundLock = await IndexLock.isLocked(); |
| 678 | while (foundLock?.locked) { |
| 679 | if ((Date.now() - foundLock.timestamp) / 1000 > 10) { |
| 680 | console.log(`${foundLock.dirs} is not being indexed... unlocking`); |
| 681 | await IndexLock.unlock(); |
| 682 | break; |
| 683 | } |
| 684 | console.log(`indexing ${foundLock.dirs}`); |
| 685 | yield { |
| 686 | progress: 0, |
| 687 | desc: "", |
| 688 | status: "waiting", |
| 689 | }; |
| 690 | await new Promise((resolve) => setTimeout(resolve, 1000)); |
| 691 | foundLock = await IndexLock.isLocked(); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | public async refreshCodebaseIndex(paths: string[]) { |
| 696 | if (this.indexingCancellationController) { |
| 697 | this.indexingCancellationController.abort(); |
| 698 | } |
| 699 | this.indexingCancellationController = new AbortController(); |
| 700 | for await (const update of this.waitForDBIndex()) { |
| 701 | this.updateProgress(update); |
| 702 | } |
| 703 | |
| 704 | await IndexLock.lock(paths.join(", ")); // acquire the index lock to prevent multiple windows to begin indexing |
| 705 | const indexLockTimestampUpdateInterval = setInterval( |
| 706 | () => void IndexLock.updateTimestamp(), |
| 707 | 5_000, |
| 708 | ); |
| 709 | |
| 710 | try { |
| 711 | for await (const update of this.refreshDirs( |
| 712 | paths, |
| 713 | this.indexingCancellationController.signal, |
| 714 | )) { |
| 715 | this.updateProgress(update); |
| 716 | |
| 717 | if (update.status === "failed") { |
| 718 | await this.sendIndexingErrorTelemetry(update); |
| 719 | } |
| 720 | } |
| 721 | } catch (e: any) { |
| 722 | console.log(`Failed refreshing codebase index directories: ${e}`); |
| 723 | await this.handleIndexingError(e); |
| 724 | } |
| 725 | |
| 726 | clearInterval(indexLockTimestampUpdateInterval); // interval will also be cleared when window closes before indexing is finished |
| 727 | await IndexLock.unlock(); |
| 728 | |
| 729 | // Directly refresh submenu items |
| 730 | if (this.messenger) { |
| 731 | this.messenger.send("refreshSubmenuItems", { |
| 732 | providers: "all", |
| 733 | }); |
| 734 | } |
| 735 | this.indexingCancellationController = undefined; |
| 736 | } |
| 737 | |
| 738 | public async refreshCodebaseIndexFiles(files: string[]) { |
| 739 | // Can be cancelled by codebase index but not vice versa |
| 740 | if ( |
| 741 | this.indexingCancellationController && |
| 742 | !this.indexingCancellationController.signal.aborted |
| 743 | ) { |
| 744 | return; |
| 745 | } |
| 746 | this.indexingCancellationController = new AbortController(); |
| 747 | try { |
| 748 | for await (const update of this.refreshFiles(files)) { |
| 749 | this.updateProgress(update); |
| 750 | |
| 751 | if (update.status === "failed") { |
| 752 | await this.sendIndexingErrorTelemetry(update); |
| 753 | } |
| 754 | } |
| 755 | } catch (e: any) { |
| 756 | console.log(`Failed refreshing codebase index files: ${e}`); |
| 757 | await this.handleIndexingError(e); |
| 758 | } |
| 759 | |
| 760 | // Directly refresh submenu items |
| 761 | if (this.messenger) { |
| 762 | this.messenger.send("refreshSubmenuItems", { |
| 763 | providers: "all", |
| 764 | }); |
| 765 | } |
| 766 | this.indexingCancellationController = undefined; |
| 767 | } |
| 768 | |
| 769 | public async handleIndexingError(e: any) { |
| 770 | if (e instanceof LLMError && this.messenger) { |
| 771 | // Need to report this specific error to the IDE for special handling |
| 772 | void this.messenger.request("reportError", e); |
| 773 | } |
| 774 | |
| 775 | // broadcast indexing error |
| 776 | const updateToSend: IndexingProgressUpdate = { |
| 777 | progress: 0, |
| 778 | status: "failed", |
| 779 | desc: e.message, |
| 780 | }; |
| 781 | |
| 782 | this.updateProgress(updateToSend); |
| 783 | void this.sendIndexingErrorTelemetry(updateToSend); |
| 784 | } |
| 785 | |
| 786 | public get currentIndexingState(): IndexingProgressUpdate { |
| 787 | return this.codebaseIndexingState; |
| 788 | } |
| 789 | |
| 790 | private hasCodebaseContextProvider() { |
| 791 | return !!this.config.contextProviders?.some( |
| 792 | (provider) => |
| 793 | provider.description.title === |
| 794 | CodebaseContextProvider.description.title, |
| 795 | ); |
| 796 | } |
| 797 | |
| 798 | private isIndexingConfigSame( |
| 799 | config1: ContinueConfig | undefined, |
| 800 | config2: ContinueConfig, |
| 801 | ) { |
| 802 | return embedModelsAreEqual( |
| 803 | config1?.selectedModelByRole.embed, |
| 804 | config2.selectedModelByRole.embed, |
| 805 | ); |
| 806 | } |
| 807 | |
| 808 | private async handleConfigUpdate({ |
| 809 | config: newConfig, |
| 810 | }: ConfigResult<ContinueConfig>) { |
| 811 | if (newConfig) { |
| 812 | const needsReindex = !this.isIndexingConfigSame(this.config, newConfig); |
| 813 | |
| 814 | this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in |
| 815 | |
| 816 | // No point in indexing if no codebase context provider |
| 817 | const hasCodebaseContextProvider = this.hasCodebaseContextProvider(); |
| 818 | if (!hasCodebaseContextProvider) { |
| 819 | return; |
| 820 | } |
| 821 | |
| 822 | // Skip codebase indexing if not supported |
| 823 | // No warning message here because would show on ANY config update |
| 824 | if (!this.config.selectedModelByRole.embed) { |
| 825 | return; |
| 826 | } |
| 827 | |
| 828 | if (needsReindex) { |
| 829 | const dirs = await this.ide.getWorkspaceDirs(); |
| 830 | await this.refreshCodebaseIndex(dirs); |
| 831 | } |
| 832 | } |
| 833 | } |
| 834 | } |