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