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