Elffuss BraidHub

kikocis/continue public

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