Merge pull request #5894 from chezsmithy/feat-refactor-codebaseIndexer-from-core

refactor: ♻️ Refactor CodeBaseIndexer out of core
This commit is contained in:
Nate Sesti 2025-06-03 14:20:16 -07:00 • committed by GitHub
commit bfa08bc938
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 347 additions and 189 deletions

View file

@ -14,7 +14,7 @@ import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { DataLogger } from "./data/log";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
@ -41,7 +41,6 @@ import {
type ContextItem,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
} from ".";
import { ConfigYaml } from "@continuedev/config-yaml";
@ -58,7 +57,6 @@ import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMError } from "./llm";
import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -67,18 +65,12 @@ import { StreamAbortManager } from "./util/abortManager";
export class Core {
configHandler: ConfigHandler;
codebaseIndexerPromise: Promise<CodebaseIndexer>;
codeBaseIndexer: CodebaseIndexer;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
codebaseIndexingState: IndexingProgressUpdate;
private docsService: DocsService;
private globalContext = new GlobalContext();
llmLogger = new LLMLogger();
private readonly indexingPauseToken = new PauseToken(
this.globalContext.get("indexingPaused") === true,
);
private messageAbortControllers = new Map<string, AbortController>();
private addMessageAbortController(id: string): AbortController {
const controller = new AbortController();
@ -116,12 +108,6 @@ export class Core {
// Ensure .continue directory is created
migrateV1DevDataFiles();
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
@ -146,6 +132,13 @@ export class Core {
await this.configHandler.reloadConfig();
};
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
this.configHandler.onConfigUpdate(async (result) => {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
@ -172,38 +165,17 @@ export class Core {
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
// Codebase Indexer and ContinueServerClient depend on IdeSettings
let codebaseIndexerResolve: (_: any) => void | undefined;
this.codebaseIndexerPromise = new Promise(
async (resolve) => (codebaseIndexerResolve = resolve),
);
let continueServerClientResolve: (_: any) => void | undefined;
this.continueServerClientPromise = new Promise(
(resolve) => (continueServerClientResolve = resolve),
);
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
continueServerClientResolve(continueServerClient);
codebaseIndexerResolve(
new CodebaseIndexer(
this.configHandler,
this.ide,
this.indexingPauseToken,
continueServerClient,
),
);
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
this.indexingPauseToken.paused = true;
this.codeBaseIndexer.paused = true;
void this.messenger.request("indexProgress", {
progress: 0,
desc: "Initial Indexing Skipped",
@ -212,7 +184,7 @@ export class Core {
return;
}
void this.refreshCodebaseIndex(dirs);
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
@ -557,25 +529,24 @@ export class Core {
}
walkDirCache.invalidate();
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
await this.codeBaseIndexer.clearIndexes();
}
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
await this.refreshCodebaseIndex(dirs);
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
on("index/setPaused", (msg) => {
this.globalContext.update("indexingPaused", msg.data);
this.indexingPauseToken.paused = msg.data;
// Update using the new setter instead of token
this.codeBaseIndexer.paused = msg.data;
});
on("index/indexingProgressBarInitialized", async (msg) => {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.codebaseIndexingState.status !== "loading") {
void this.messenger.request(
"indexProgress",
this.codebaseIndexingState,
);
const currentState = this.codeBaseIndexer.currentIndexingState;
if (currentState.status !== "loading") {
void this.messenger.request("indexProgress", currentState);
}
});
@ -595,7 +566,7 @@ export class Core {
});
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
await this.refreshCodebaseIndexFiles(toRefresh);
await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh);
}
}
};
@ -866,7 +837,7 @@ export class Core {
// Reindex the file
const ignore = await shouldIgnore(uri, this.ide);
if (!ignore) {
await this.refreshCodebaseIndexFiles([uri]);
await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
}
}
}
@ -1037,100 +1008,4 @@ export class Core {
return [];
}
};
private indexingCancellationController: AbortController | undefined;
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
console.debug(
"Indexing failed with error: ",
update.desc,
update.debugInfo,
);
void Telemetry.capture(
"indexing_error",
{
error: update.desc,
stack: update.debugInfo,
},
false,
);
}
private async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of (
await this.codebaseIndexerPromise
).refreshDirs(paths, this.indexingCancellationController.signal)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
private async refreshCodebaseIndexFiles(files: string[]) {
// Can be cancelled by codebase index but not vice versa
if (
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
return;
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of (
await this.codebaseIndexerPromise
).refreshFiles(files)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
// private
handleIndexingError(e: any) {
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
void this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
}
}

View file

@ -3,7 +3,7 @@ import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "path";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { LLMError } from "../llm/index.js";
import { testConfigHandler, testIde } from "../test/fixtures.js";
import {
addToTestDir,
@ -59,16 +59,34 @@ class TestCodebaseIndexer extends CodebaseIndexer {
}
}
// Create a mock messenger type that doesn't require actual protocol imports
type MockMessengerType = {
send: jest.Mock;
request: jest.Mock;
invoke: jest.Mock;
on: jest.Mock;
onError: jest.Mock;
};
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
// Replace mockProgressReporter with mockMessenger
const mockMessenger: MockMessengerType = {
send: jest.fn(),
request: jest.fn(async () => {}),
invoke: jest.fn(),
on: jest.fn(),
onError: jest.fn(),
};
const codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
pauseToken,
continueServerClient,
mockMessenger as any,
false,
);
const testIndex = new TestCodebaseIndex();
@ -89,6 +107,7 @@ describe("CodebaseIndexer", () => {
afterEach(() => {
walkDirCache.invalidate();
jest.clearAllMocks();
});
async function refreshIndex() {
@ -241,4 +260,155 @@ describe("CodebaseIndexer", () => {
execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
await expectPlan(0, 0, 0, 0);
});
// New tests for the methods added from Core.ts
describe("New methods from Core.ts", () => {
// Simplified tests to focus on behavior, not implementation details
test("should call messenger with progress updates when refreshing codebase index", async () => {
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(async function* () {
yield { status: "done", progress: 1, desc: "Completed" };
});
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.anything(),
);
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
});
test("should call messenger with progress updates when refreshing specific files", async () => {
jest
.spyOn(codebaseIndexer as any, "refreshFiles")
.mockImplementation(async function* () {
yield { status: "done", progress: 1, desc: "Completed" };
});
await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.anything(),
);
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
providers: "all",
});
});
test("should abort previous indexing when starting a new one", async () => {
// Set up a situation where indexingCancellationController exists
const mockAbort = jest.fn();
const controller = { abort: mockAbort, signal: { aborted: false } };
// Access the private property in a type-safe way for testing
(codebaseIndexer as any).indexingCancellationController = controller;
// Mock refreshDirs to return immediately
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(async function* () {
yield { status: "done", progress: 1, desc: "Completed" };
});
// Start indexing - this should call abort on the existing controller
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
// Verify abort was called
expect(mockAbort).toHaveBeenCalled();
});
test("should handle errors properly during indexing", async () => {
const testError = new Error("Test indexing error");
// Mock console.log to avoid printing errors
const consoleLogSpy = jest
.spyOn(console, "log")
.mockImplementation(() => {});
// Mock refreshDirs to throw an error
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(() => {
throw testError;
});
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
// Use the first argument only for the assertion since the second argument doesn't match exactly
expect(consoleLogSpy).toHaveBeenCalledWith(
`Failed refreshing codebase index directories: Error: ${testError.message}`,
);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.objectContaining({
status: "failed",
}),
);
consoleLogSpy.mockRestore();
});
test("should handle LLMError specially during indexing", async () => {
// Create a mock LLM
const mockLlm: any = {
providerName: "test-provider",
model: "test-model",
};
// Create a real LLMError
const llmError = new LLMError("Test LLM error", mockLlm);
// Mock console.log to avoid printing errors
jest.spyOn(console, "log").mockImplementation(() => {});
// Mock refreshDirs to throw an LLMError
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(() => {
throw llmError;
});
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
expect(mockMessenger.request).toHaveBeenCalledWith(
"reportError",
llmError,
);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.objectContaining({
status: "failed",
desc: "Test LLM error",
}),
);
});
test("should provide access to current indexing state", async () => {
const testState = {
progress: 0.5,
status: "indexing" as const,
desc: "Test state",
};
// Mock refreshDirs to set a specific state
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(async function* () {
yield testState;
});
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
// Check that the state was updated
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
});
});
});

View file

@ -3,10 +3,14 @@ import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { Telemetry } from "../util/posthog.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ContinueServerClient } from "../continueServer/stubs/client";
import { LLMError } from "../llm/index.js";
import { getRootCause } from "../util/errors.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
@ -41,6 +45,9 @@ export class CodebaseIndexer {
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 500;
private indexingCancellationController: AbortController | undefined;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
// e.g. a `SQLITE_BUSY` error.
@ -56,9 +63,32 @@ export class CodebaseIndexer {
constructor(
private readonly configHandler: ConfigHandler,
protected readonly ide: IDE,
private readonly pauseToken: PauseToken,
private readonly continueServerClient: IContinueServerClient,
) {}
private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
initialPaused: boolean = false,
) {
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
// Initialize pause token
this.pauseToken = new PauseToken(initialPaused);
}
/**
* Set the paused state of the indexer
*/
set paused(value: boolean) {
this.pauseToken.paused = value;
}
/**
* Get the current paused state of the indexer
*/
get paused(): boolean {
return this.pauseToken.paused;
}
async clearIndexes() {
const sqliteFilepath = getIndexSqlitePath();
@ -88,10 +118,22 @@ export class CodebaseIndexer {
return [];
}
const ideSettings = await this.ide.getIdeSettings();
if (!ideSettings) {
return [];
}
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
if (!continueServerClient) {
return [];
}
const indexes: CodebaseIndex[] = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
continueServerClient,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
];
@ -504,4 +546,109 @@ export class CodebaseIndexer {
completedIndexCount += 1;
}
}
// New methods using messenger directly
private async updateProgress(update: IndexingProgressUpdate) {
this.codebaseIndexingState = update;
if (this.messenger) {
await this.messenger.request("indexProgress", update);
}
}
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
console.debug(
"Indexing failed with error: ",
update.desc,
update.debugInfo,
);
void Telemetry.capture(
"indexing_error",
{
error: update.desc,
stack: update.debugInfo,
},
false,
);
}
public async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of this.refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
await this.updateProgress(update);
if (update.status === "failed") {
await this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories: ${e}`);
await this.handleIndexingError(e);
}
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
}
this.indexingCancellationController = undefined;
}
public async refreshCodebaseIndexFiles(files: string[]) {
// Can be cancelled by codebase index but not vice versa
if (
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
return;
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of this.refreshFiles(files)) {
await this.updateProgress(update);
if (update.status === "failed") {
await this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files: ${e}`);
await this.handleIndexingError(e);
}
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", { providers: "all" });
}
this.indexingCancellationController = undefined;
}
public async handleIndexingError(e: any) {
if (e instanceof LLMError && this.messenger) {
// Need to report this specific error to the IDE for special handling
await this.messenger.request("reportError", e);
}
// broadcast indexing error
const updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
await this.updateProgress(updateToSend);
void this.sendIndexingErrorTelemetry(updateToSend);
}
public get currentIndexingState(): IndexingProgressUpdate {
return this.codebaseIndexingState;
}
}

View file

@ -4,21 +4,14 @@ import * as fs from "node:fs";
import { ContextMenuConfig, ILLM, ModelInstaller } from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
import { ContinueServerClient } from "core/continueServer/stubs/client";
import { EXTENSION_NAME } from "core/control-plane/env";
import { Core } from "core/core";
import { LOCAL_DEV_DATA_VERSION } from "core/data/log";
import { walkDirAsync } from "core/indexing/walkDir";
import { isModelInstaller } from "core/llm";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { startLocalOllama } from "core/util/ollamaHelper";
import {
getConfigJsonPath,
getConfigYamlPath,
getDevDataFilePath,
} from "core/util/paths";
import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import readLastLines from "read-last-lines";
import * as vscode from "vscode";
import * as YAML from "yaml";
@ -173,7 +166,6 @@ const getCommandsMap: (
consoleView: ContinueConsoleWebviewViewProvider,
configHandler: ConfigHandler,
verticalDiffManager: VerticalDiffManager,
continueServerClientPromise: Promise<ContinueServerClient>,
battery: Battery,
quickEdit: QuickEdit,
core: Core,
@ -185,7 +177,6 @@ const getCommandsMap: (
consoleView,
configHandler,
verticalDiffManager,
continueServerClientPromise,
battery,
quickEdit,
core,
@ -686,9 +677,6 @@ const getCommandsMap: (
description:
getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + A",
},
{
label: "$(feedback) Give feedback",
},
{
kind: vscode.QuickPickItemKind.Separator,
label: "Switch model",
@ -721,8 +709,6 @@ const getCommandsMap: (
title: selectedOption,
});
}
} else if (selectedOption === "$(feedback) Give feedback") {
vscode.commands.executeCommand("continue.giveAutocompleteFeedback");
} else if (selectedOption === "$(comment) Open chat") {
vscode.commands.executeCommand("continue.focusContinueInput");
} else if (selectedOption === "$(screen-full) Open full screen chat") {
@ -735,23 +721,6 @@ const getCommandsMap: (
});
quickPick.show();
},
"continue.giveAutocompleteFeedback": async () => {
const feedback = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt:
"Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.",
});
if (feedback) {
const client = await continueServerClientPromise;
const completionsPath = getDevDataFilePath(
"autocomplete",
LOCAL_DEV_DATA_VERSION,
);
const lastLines = await readLastLines.read(completionsPath, 2);
client.sendFeedback(feedback, lastLines);
}
},
"continue.navigateTo": (path: string, toggle: boolean) => {
sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
focusGUI();
@ -931,7 +900,6 @@ export function registerAllCommands(
consoleView: ContinueConsoleWebviewViewProvider,
configHandler: ConfigHandler,
verticalDiffManager: VerticalDiffManager,
continueServerClientPromise: Promise<ContinueServerClient>,
battery: Battery,
quickEdit: QuickEdit,
core: Core,
@ -945,7 +913,6 @@ export function registerAllCommands(
consoleView,
configHandler,
verticalDiffManager,
continueServerClientPromise,
battery,
quickEdit,
core,

View file

@ -244,7 +244,6 @@ export class VsCodeExtension {
this.consoleView,
this.configHandler,
this.verticalDiffManager,
this.core.continueServerClientPromise,
this.battery,
quickEdit,
this.core,