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