Elffuss BraidHub

kikocis/continue public

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