From a5db30dab316581781f9b1c5d499ac6686797377 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 28 May 2025 22:02:00 -0700 Subject: [PATCH 1/4] refactor: :recycle: Refactor CodeBaseIndexer out of core --- core/config/yaml/loadYaml.ts | 38 ++-- core/core.ts | 167 +++--------------- core/indexing/CodebaseIndexer.test.ts | 141 ++++++++++++++- core/indexing/CodebaseIndexer.ts | 155 +++++++++++++++- .../vscode/src/extension/VsCodeExtension.ts | 1 + 5 files changed, 337 insertions(+), 165 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index aa4c3919a..4f5a9dac5 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -67,7 +67,7 @@ function convertYamlMcpToContinueMcp( return { transport: { type: "stdio", - command: server.command, + command: server.command || "", // Add default empty string to handle undefined args: server.args ?? [], env: server.env, } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) @@ -424,16 +424,28 @@ async function configYamlToContinueConfig(options: { // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.setConnections( - (config.mcpServers ?? []).map((server) => ({ - id: server.name, - name: server.name, - transport: { - type: "stdio", - args: [], - ...(server as any), // TODO: fix the types on mcpServers in config-yaml - }, - timeout: server.connectionTimeout, - })), + (config.mcpServers ?? []).map((server) => { + // Create proper transport object based on type + const transport = server.type === "sse" + ? { + type: "sse" as const, + url: server.url || "", + faviconUrl: server.faviconUrl + } + : { + type: "stdio" as const, + command: server.command || "", + args: server.args || [], + env: server.env, + faviconUrl: server.faviconUrl + }; + return { + id: server.name, + name: server.name, + transport, + timeout: server.connectionTimeout + }; + }), false, ); @@ -479,8 +491,8 @@ export async function loadContinueConfigFromYaml(options: { errors: configYamlResult.errors, config: undefined, configLoadInterrupted: true, - }; - } + }; +} const { config: continueConfig, errors: localErrors } = await configYamlToContinueConfig({ diff --git a/core/core.ts b/core/core.ts index 2c13fd6a7..9673c5515 100644 --- a/core/core.ts +++ b/core/core.ts @@ -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"; @@ -40,8 +40,7 @@ import { RangeInFile, type ContextItem, type ContextItemId, - type IDE, - type IndexingProgressUpdate, + type IDE } from "."; import { ConfigYaml } from "@continuedev/config-yaml"; @@ -57,7 +56,6 @@ import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; 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"; @@ -66,18 +64,13 @@ import { StreamAbortManager } from "./util/abortManager"; export class Core { configHandler: ConfigHandler; - codebaseIndexerPromise: Promise; + codeBaseIndexer: CodebaseIndexer; completionProvider: CompletionProvider; - continueServerClientPromise: Promise; - codebaseIndexingState: IndexingProgressUpdate; + continueServerClientPromise: Promise; private docsService: DocsService; private globalContext = new GlobalContext(); llmLogger = new LLMLogger(); - private readonly indexingPauseToken = new PauseToken( - this.globalContext.get("indexingPaused") === true, - ); - private messageAbortControllers = new Map(); private addMessageAbortController(id: string): AbortController { const controller = new AbortController(); @@ -115,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", { @@ -145,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", { @@ -171,38 +165,24 @@ 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( + 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", @@ -211,7 +191,7 @@ export class Core { return; } - void this.refreshCodebaseIndex(dirs); + await this.codeBaseIndexer.refreshCodebaseIndex(dirs); }); }); @@ -556,25 +536,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); } }); @@ -594,7 +573,7 @@ export class Core { }); const { config } = await this.configHandler.loadConfig(); if (config && !config.disableIndexing) { - await this.refreshCodebaseIndexFiles(toRefresh); + await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh); } } }; @@ -860,7 +839,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]); } } } @@ -1031,100 +1010,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); - } } diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index cdcd61006..a03f752c4 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -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,116 @@ 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); + }); + }); +}); \ No newline at end of file diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 1f9017e3d..b5b975406 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -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, + 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,107 @@ 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; + } +} \ No newline at end of file diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index b15d4420c..2dfb3166c 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -244,6 +244,7 @@ export class VsCodeExtension { this.consoleView, this.configHandler, this.verticalDiffManager, + // This is expected to exist, but it's no longer used? Can I remove it? this.core.continueServerClientPromise, this.battery, quickEdit, From cd944cb22075b811e04c73d45632250b09c8c20c Mon Sep 17 00:00:00 2001 From: Shawn Smith Date: Thu, 29 May 2025 17:24:59 -0700 Subject: [PATCH 2/4] roll back loadYaml.ts to main --- core/config/yaml/loadYaml.ts | 38 ++++++++++++------------------------ 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 4f5a9dac5..aa4c3919a 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -67,7 +67,7 @@ function convertYamlMcpToContinueMcp( return { transport: { type: "stdio", - command: server.command || "", // Add default empty string to handle undefined + command: server.command, args: server.args ?? [], env: server.env, } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) @@ -424,28 +424,16 @@ async function configYamlToContinueConfig(options: { // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.setConnections( - (config.mcpServers ?? []).map((server) => { - // Create proper transport object based on type - const transport = server.type === "sse" - ? { - type: "sse" as const, - url: server.url || "", - faviconUrl: server.faviconUrl - } - : { - type: "stdio" as const, - command: server.command || "", - args: server.args || [], - env: server.env, - faviconUrl: server.faviconUrl - }; - return { - id: server.name, - name: server.name, - transport, - timeout: server.connectionTimeout - }; - }), + (config.mcpServers ?? []).map((server) => ({ + id: server.name, + name: server.name, + transport: { + type: "stdio", + args: [], + ...(server as any), // TODO: fix the types on mcpServers in config-yaml + }, + timeout: server.connectionTimeout, + })), false, ); @@ -491,8 +479,8 @@ export async function loadContinueConfigFromYaml(options: { errors: configYamlResult.errors, config: undefined, configLoadInterrupted: true, - }; -} + }; + } const { config: continueConfig, errors: localErrors } = await configYamlToContinueConfig({ From 764d1366336fee0619f1f500418eb6f62ca2dd52 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 2 Jun 2025 13:02:48 -0700 Subject: [PATCH 3/4] Remove continueServerClientPromise --- core/core.ts | 12 ++----- extensions/vscode/src/commands.ts | 35 +------------------ .../vscode/src/extension/VsCodeExtension.ts | 2 -- 3 files changed, 3 insertions(+), 46 deletions(-) diff --git a/core/core.ts b/core/core.ts index 9673c5515..2a133a6e0 100644 --- a/core/core.ts +++ b/core/core.ts @@ -40,7 +40,7 @@ import { RangeInFile, type ContextItem, type ContextItemId, - type IDE + type IDE, } from "."; import { ConfigYaml } from "@continuedev/config-yaml"; @@ -66,7 +66,6 @@ export class Core { configHandler: ConfigHandler; codeBaseIndexer: CodebaseIndexer; completionProvider: CompletionProvider; - continueServerClientPromise: Promise; private docsService: DocsService; private globalContext = new GlobalContext(); llmLogger = new LLMLogger(); @@ -165,18 +164,11 @@ export class Core { dataLogger.ideInfoPromise = ideInfoPromise; dataLogger.ideSettingsPromise = ideSettingsPromise; - let continueServerClientResolve: (_: any) => void | undefined; - this.continueServerClientPromise = new Promise( - (resolve) => (continueServerClientResolve = resolve), - ); - - void ideSettingsPromise.then((ideSettings) => { - const continueServerClient = new ContinueServerClient( + const continueServerClient = new ContinueServerClient( ideSettings.remoteConfigServerUrl, ideSettings.userToken, ); - continueServerClientResolve(continueServerClient); // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 84885f757..1dbc69b60 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -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, 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(); @@ -895,7 +864,6 @@ export function registerAllCommands( consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, - continueServerClientPromise: Promise, battery: Battery, quickEdit: QuickEdit, core: Core, @@ -909,7 +877,6 @@ export function registerAllCommands( consoleView, configHandler, verticalDiffManager, - continueServerClientPromise, battery, quickEdit, core, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 2dfb3166c..914624895 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -244,8 +244,6 @@ export class VsCodeExtension { this.consoleView, this.configHandler, this.verticalDiffManager, - // This is expected to exist, but it's no longer used? Can I remove it? - this.core.continueServerClientPromise, this.battery, quickEdit, this.core, From 2a719dea8836e492c525c95be648412cf307a348 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 3 Jun 2025 12:56:54 -0700 Subject: [PATCH 4/4] mak'in it prettier --- core/indexing/CodebaseIndexer.test.ts | 163 ++++++++++++++++---------- core/indexing/CodebaseIndexer.ts | 22 ++-- 2 files changed, 113 insertions(+), 72 deletions(-) diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index a03f752c4..7ba08594d 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -72,21 +72,21 @@ type MockMessengerType = { // the individual CodebaseIndex classes describe("CodebaseIndexer", () => { const pauseToken = new PauseToken(false); - + // Replace mockProgressReporter with mockMessenger const mockMessenger: MockMessengerType = { send: jest.fn(), request: jest.fn(async () => {}), invoke: jest.fn(), on: jest.fn(), - onError: jest.fn() + onError: jest.fn(), }; - + const codebaseIndexer = new TestCodebaseIndexer( testConfigHandler, testIde, mockMessenger as any, - false + false, ); const testIndex = new TestCodebaseIndex(); @@ -265,111 +265,150 @@ describe("CodebaseIndexer", () => { 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" }; - }); - + 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" }); + + 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" }; - }); - + 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" }); + + 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" }; - }); - + 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(() => {}); - + const consoleLogSpy = jest + .spyOn(console, "log") + .mockImplementation(() => {}); + // Mock refreshDirs to throw an error - jest.spyOn(codebaseIndexer as any, 'refreshDirs').mockImplementation(() => { - throw testError; - }); - + 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" - })); - + 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 = { + const mockLlm: any = { providerName: "test-provider", - model: "test-model" + 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(() => {}); - + jest.spyOn(console, "log").mockImplementation(() => {}); + // Mock refreshDirs to throw an LLMError - jest.spyOn(codebaseIndexer as any, 'refreshDirs').mockImplementation(() => { - throw 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" - })); + + 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" }; - + 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; - }); - + 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); }); }); -}); \ No newline at end of file +}); diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b5b975406..719c95aec 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -64,7 +64,7 @@ export class CodebaseIndexer { private readonly configHandler: ConfigHandler, protected readonly ide: IDE, private readonly messenger?: IMessenger, - initialPaused: boolean = false + initialPaused: boolean = false, ) { this.codebaseIndexingState = { status: "loading", @@ -124,12 +124,12 @@ export class CodebaseIndexer { } const continueServerClient = new ContinueServerClient( ideSettings.remoteConfigServerUrl, - ideSettings.userToken + ideSettings.userToken, ); if (!continueServerClient) { return []; } - + const indexes: CodebaseIndex[] = [ new ChunkCodebaseIndex( this.ide.readFile.bind(this.ide), @@ -546,7 +546,7 @@ export class CodebaseIndexer { completedIndexCount += 1; } } - + // New methods using messenger directly private async updateProgress(update: IndexingProgressUpdate) { @@ -579,8 +579,8 @@ export class CodebaseIndexer { this.indexingCancellationController = new AbortController(); try { for await (const update of this.refreshDirs( - paths, - this.indexingCancellationController.signal + paths, + this.indexingCancellationController.signal, )) { await this.updateProgress(update); @@ -595,7 +595,9 @@ export class CodebaseIndexer { // Directly refresh submenu items if (this.messenger) { - this.messenger.send("refreshSubmenuItems", { providers: "dependsOnIndexing" }); + this.messenger.send("refreshSubmenuItems", { + providers: "dependsOnIndexing", + }); } this.indexingCancellationController = undefined; } @@ -634,14 +636,14 @@ export class CodebaseIndexer { // 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); } @@ -649,4 +651,4 @@ export class CodebaseIndexer { public get currentIndexingState(): IndexingProgressUpdate { return this.codebaseIndexingState; } -} \ No newline at end of file +}