From 0a3364df6b771842d8eca19376090ab4828d3edf Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Dec 2024 08:56:11 -0800 Subject: [PATCH] clean up config loading --- core/config/ConfigHandler.ts | 8 +- core/config/ProfileLifecycleManager.ts | 56 +++++++----- core/config/load.ts | 89 +++++++++++-------- core/context/mcp/index.ts | 7 +- core/core.ts | 22 +++-- core/protocol/webview.ts | 6 +- core/util/uri.ts | 2 +- .../vscode/src/extension/VsCodeExtension.ts | 19 +++- gui/src/hooks/useSetup.ts | 58 +++++++----- 9 files changed, 168 insertions(+), 99 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 3eb55643f..0106a96c5 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -224,7 +224,9 @@ export class ConfigHandler { return { config, errors }; } - getSerializedConfig(): Promise { + getSerializedConfig(): Promise< + ConfigResult + > { return this.currentProfile.getSerializedConfig( this.additionalContextProviders, ); @@ -235,7 +237,9 @@ export class ConfigHandler { } async loadConfig(): Promise { - return this.currentProfile.loadConfig(this.additionalContextProviders); + return ( + await this.currentProfile.loadConfig(this.additionalContextProviders) + ).config!; // <-- TODO } async llmFromTitle(title?: string): Promise { diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 8d44c8bac..7b595c0e6 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -13,9 +13,9 @@ export interface ProfileDescription { } export class ProfileLifecycleManager { - private savedConfig: ContinueConfig | undefined; + private savedConfig: ConfigResult | undefined; private savedBrowserConfig?: BrowserSerializedContinueConfig; - private pendingConfigPromise?: Promise; + private pendingConfigPromise?: Promise>; constructor(private readonly profileLoader: IProfileLoader) {} @@ -46,35 +46,37 @@ export class ProfileLifecycleManager { this.savedBrowserConfig = undefined; this.pendingConfigPromise = undefined; - return this.profileLoader.doLoadConfig(); + return this.loadConfig([], true); } async loadConfig( additionalContextProviders: IContextProvider[], - ): Promise { + forceReload: boolean = false, + ): Promise> { // If we already have a config, return it - if (this.savedConfig) { - return this.savedConfig; - } else if (this.pendingConfigPromise) { - return this.pendingConfigPromise; + if (!forceReload) { + if (this.savedConfig) { + return this.savedConfig; + } else if (this.pendingConfigPromise) { + return this.pendingConfigPromise; + } } // Set pending config promise this.pendingConfigPromise = new Promise(async (resolve, reject) => { - const { config: newConfig, errors } = - await this.profileLoader.doLoadConfig(); + const result = await this.profileLoader.doLoadConfig(); - if (newConfig) { + if (result.config) { // Add registered context providers - newConfig.contextProviders = (newConfig.contextProviders ?? []).concat( - additionalContextProviders, - ); + result.config.contextProviders = ( + result.config.contextProviders ?? [] + ).concat(additionalContextProviders); - this.savedConfig = newConfig; - resolve(newConfig); - } else if (errors) { + this.savedConfig = result; + resolve(result); + } else if (result.errors) { reject( - `Error in config.json: ${errors.map((item) => item.message).join(" | ")}`, + `Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`, ); } }); @@ -87,11 +89,21 @@ export class ProfileLifecycleManager { async getSerializedConfig( additionalContextProviders: IContextProvider[], - ): Promise { + ): Promise> { if (!this.savedBrowserConfig) { - const continueConfig = await this.loadConfig(additionalContextProviders); - this.savedBrowserConfig = finalToBrowserConfig(continueConfig); + const result = await this.loadConfig(additionalContextProviders); + if (!result.config) { + return { + ...result, + config: undefined, + }; + } + this.savedBrowserConfig = finalToBrowserConfig(result.config); } - return this.savedBrowserConfig; + return { + config: this.savedBrowserConfig, + errors: [], + configLoadInterrupted: false, + }; } } diff --git a/core/config/load.ts b/core/config/load.ts index 8463f3f83..99c701141 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -61,6 +61,8 @@ import { getEsbuildBinaryPath, } from "../util/paths"; +import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; +import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -69,8 +71,6 @@ import { } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { ConfigValidationError, validateConfig } from "./validation.js"; -import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; -import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; export interface ConfigResult { config: T | undefined; @@ -239,7 +239,9 @@ async function intermediateToFinalConfig( workOsAccessToken: string | undefined, loadPromptFiles: boolean = true, allowFreeTrial: boolean = true, -): Promise { +): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { + const errors: ConfigValidationError[] = []; + // Auto-detect models let models: BaseLLM[] = []; for (const desc of config.models) { @@ -490,37 +492,41 @@ async function intermediateToFinalConfig( // Apply MCP if specified const mcpManager = MCPManagerSingleton.getInstance(); if (config.experimental?.modelContextProtocolServers) { - config.experimental.modelContextProtocolServers?.forEach( - async (server, index) => { - const mcpId = index.toString(); - const mcpConnection = mcpManager.createConnection(mcpId, server); - if (!mcpConnection) { - return; - } - - const abortController = new AbortController(); - const mcpConnectionTimeout = setTimeout( - () => abortController.abort(), - 2000, - ); - - try { - await mcpConnection.modifyConfig( - continueConfig, - mcpId, - abortController.signal, - ); - } catch (e: any) { - if (e.name !== "AbortError") { - throw e; + await Promise.all( + config.experimental.modelContextProtocolServers?.map( + async (server, index) => { + const mcpId = index.toString(); + const mcpConnection = mcpManager.createConnection(mcpId, server); + if (!mcpConnection) { + return; } - } - clearTimeout(mcpConnectionTimeout); - }, + + const abortController = new AbortController(); + + try { + const mcpError = await mcpConnection.modifyConfig( + continueConfig, + mcpId, + abortController.signal, + ); + if (mcpError) { + errors.push(mcpError); + } + } catch (e: any) { + errors.push({ + fatal: false, + message: `Failed to load MCP server: ${e.message}`, + }); + if (e.name !== "AbortError") { + throw e; + } + } + }, + ) || [], ); } - return continueConfig; + return { config: continueConfig, errors }; } function finalToBrowserConfig( @@ -831,15 +837,20 @@ async function loadFullConfigNode( } // Convert to final config format - const finalConfig = await intermediateToFinalConfig( - intermediate, - ide, - ideSettings, - uniqueId, - writeLog, - workOsAccessToken, - ); - return { config: finalConfig, errors, configLoadInterrupted: false }; + const { config: finalConfig, errors: finalErrors } = + await intermediateToFinalConfig( + intermediate, + ide, + ideSettings, + uniqueId, + writeLog, + workOsAccessToken, + ); + return { + config: finalConfig, + errors: [...(errors ?? []), ...finalErrors], + configLoadInterrupted: false, + }; } export { diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 552153a80..0a2e63494 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -6,6 +6,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; import { constructMcpSlashCommand } from "../../commands/slash/mcp"; +import { ConfigValidationError } from "../../config/validation"; import MCPContextProvider from "../providers/MCPContextProvider"; export class MCPManagerSingleton { @@ -117,7 +118,7 @@ class MCPConnection { config: ContinueConfig, mcpId: string, signal: AbortSignal, - ): Promise { + ): Promise { try { await Promise.race([ this.connectClient(), @@ -133,6 +134,10 @@ class MCPConnection { } if (!error.message.startsWith("StdioClientTransport already started")) { console.error("Failed to connect client:", error); + return { + fatal: false, + message: `Failed to connect to MCP ${mcpId}: ${error.message}`, + }; } } diff --git a/core/core.ts b/core/core.ts index fb3840d05..aa9c1eb5b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -12,7 +12,7 @@ import { setupLocalConfigAfterFreeTrial, setupQuickstartConfig, } from "./config/onboarding"; -import { addModel, addOpenAIKey, deleteModel } from "./config/util"; +import { addModel, deleteModel } from "./config/util"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; @@ -42,9 +42,9 @@ import { TTS } from "./util/tts"; import { type ContextItemId, type IDE, type IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; +import * as URI from "uri-js"; import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; import type { IMessenger, Message } from "./protocol/messenger"; -import * as URI from "uri-js"; import { localPathToUri } from "./util/pathToUri"; export class Core { @@ -119,9 +119,15 @@ export class Core { this.messenger, ); - this.configHandler.onConfigUpdate( - (() => this.messenger.send("configUpdate", undefined)).bind(this), - ); + this.configHandler.onConfigUpdate(async (result) => { + const serialized = await ( + await this.configHandler.getSerializedConfig() + ).config!; + this.messenger.send("configUpdate", { + config: serialized, + profileId: this.configHandler.currentProfile.profileId, + }); + }); this.configHandler.onDidChangeAvailableProfiles((profiles) => this.messenger.send("didChangeAvailableProfiles", { profiles }), @@ -264,9 +270,9 @@ export class Core { await this.configHandler.openConfigProfile(msg.data.profileId); }); - on("config/reload", (msg) => { + on("config/reload", async (msg) => { void this.configHandler.reloadConfig(); - return this.configHandler.getSerializedConfig(); + return (await this.configHandler.getSerializedConfig()).config!; // <-- TODO }); on("config/ideSettingsUpdate", (msg) => { @@ -360,7 +366,7 @@ export class Core { on("config/getSerializedProfileInfo", async (msg) => { return { - config: await this.configHandler.getSerializedConfig(), + config: (await this.configHandler.getSerializedConfig()).config!, // <-- TODO profileId: this.configHandler.currentProfile.profileId, }; }); diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 27fd2fc38..65ecde912 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,6 +1,7 @@ import { ConfigValidationError } from "../config/validation.js"; import type { + BrowserSerializedContinueConfig, ContextItemWithId, IndexingProgressUpdate, IndexingStatus, @@ -8,7 +9,10 @@ import type { } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { - configUpdate: [undefined, void]; + configUpdate: [ + { config: BrowserSerializedContinueConfig; profileId: string }, + void, + ]; configError: [ConfigValidationError[] | undefined, void]; getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; // Codebase diff --git a/core/util/uri.ts b/core/util/uri.ts index 49a9e8389..708408ce0 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -36,6 +36,7 @@ export function findUriInDirs( if (!uriComps.scheme) { throw new Error(`Invalid uri: ${uri}`); } + for (const dir of dirUriCandidates) { const dirComps = URI.parse(dir); @@ -78,7 +79,6 @@ export function findUriInDirs( } } // Not found - console.trace("Directory not found for uri", uri, dirUriCandidates); return { uri, relativePathOrBasename: getUriPathBasename(uri), diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index ce506cfec..ac3f7fbf7 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -136,7 +136,7 @@ export class VsCodeExtension { this.configHandler = this.core.configHandler; resolveConfigHandler?.(this.configHandler); - this.configHandler.reloadConfig(); + this.configHandler.loadConfig(); this.verticalDiffManager = new VerticalDiffManager( this.configHandler, this.sidebar.webviewProtocol, @@ -161,14 +161,18 @@ export class VsCodeExtension { }); this.configHandler.onConfigUpdate( - ({ config: newConfig, errors, configLoadInterrupted }) => { + async ({ config: newConfig, errors, configLoadInterrupted }) => { if (configLoadInterrupted) { // Show error in status bar setupStatusBar(undefined, undefined, true); } else if (newConfig) { setupStatusBar(undefined, undefined, false); - this.sidebar.webviewProtocol?.request("configUpdate", undefined); + const serialized = await this.configHandler.getSerializedConfig(); + this.sidebar.webviewProtocol?.request("configUpdate", { + config: serialized.config!, // <-- TODO + profileId: this.configHandler.currentProfile.profileId, + }); this.tabAutocompleteModel.clearLlm(); @@ -246,6 +250,9 @@ export class VsCodeExtension { // Listen for file saving - use global file watcher so that changes // from outside the window are also caught fs.watchFile(getConfigJsonPath(), { interval: 1000 }, async (stats) => { + if (stats.size === 0) { + return; + } await this.configHandler.reloadConfig(); }); @@ -253,11 +260,17 @@ export class VsCodeExtension { getConfigYamlPath("vscode"), { interval: 1000 }, async (stats) => { + if (stats.size === 0) { + return; + } await this.configHandler.reloadConfig(); }, ); fs.watchFile(getConfigTsPath(), { interval: 1000 }, (stats) => { + if (stats.size === 0) { + return; + } this.configHandler.reloadConfig(); }); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 0381d3a6d..5534fbc3b 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,24 +1,24 @@ import { useCallback, useContext, useEffect, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { AppDispatch } from "../redux/store"; -import { streamResponseThunk } from "../redux/thunks/streamResponse"; -import { isJetBrains } from "../util"; -import { setLocalStorage } from "../util/localStorage"; -import { useWebviewListener } from "./useWebviewListener"; +import { BrowserSerializedContinueConfig } from "core"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setConfig, setConfigError } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { updateDocsSuggestions } from "../redux/slices/miscSlice"; import { - setSelectedProfileId, - setInactive, addContextItemsAtIndex, + setInactive, + setSelectedProfileId, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; -import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; import { refreshSessionMetadata } from "../redux/thunks/session"; +import { streamResponseThunk } from "../redux/thunks/streamResponse"; +import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; +import { isJetBrains } from "../util"; +import { setLocalStorage } from "../util/localStorage"; +import { useWebviewListener } from "./useWebviewListener"; function useSetup() { const dispatch = useAppDispatch(); @@ -29,16 +29,13 @@ function useSetup() { ); const hasLoadedConfig = useRef(false); - const loadConfig = useCallback( - async (initial: boolean) => { - const result = await ideMessenger.request( - "config/getSerializedProfileInfo", - undefined, - ); - if (result.status === "error") { - return; - } - const { config, profileId } = result.content; + + const handleConfigUpdate = useCallback( + async ( + initial: boolean, + result: { config: BrowserSerializedContinueConfig; profileId: string }, + ) => { + const { config, profileId } = result; if (initial && hasLoadedConfig.current) { return; } @@ -52,7 +49,21 @@ function useSetup() { document.body.style.fontSize = `${config.ui.fontSize}px`; } }, - [dispatch, ideMessenger, hasLoadedConfig], + [dispatch, hasLoadedConfig], + ); + + const loadConfig = useCallback( + async (initial: boolean) => { + const result = await ideMessenger.request( + "config/getSerializedProfileInfo", + undefined, + ); + if (result.status === "error") { + return; + } + await handleConfigUpdate(initial, result.content); + }, + [ideMessenger, handleConfigUpdate], ); // Load config from the IDE @@ -78,8 +89,11 @@ function useSetup() { useWebviewListener( "configUpdate", - async () => { - await loadConfig(false); + async (update) => { + if (!update) { + return; + } + await handleConfigUpdate(false, update); }, [loadConfig], ); @@ -147,7 +161,7 @@ function useSetup() { useWebviewListener( "getCurrentSessionId", async () => { - return sessionId + return sessionId; }, [sessionId], );