diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index bd8504986..fb1be39bb 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -234,15 +234,17 @@ describe("Test Suite", () => { result: { config }, } = await messenger.request("config/getSerializedProfileInfo", undefined); - expect(config!.models.some((m) => m.title === model.title)).toBe(true); + expect(config!.modelsByRole.chat.some((m) => m.title === model.title)).toBe( + true, + ); await messenger.request("config/deleteModel", { title: model.title }); const { result: { config: configAfterDelete }, } = await messenger.request("config/getSerializedProfileInfo", undefined); - expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe( - false, - ); + expect( + configAfterDelete!.modelsByRole.chat.some((m) => m.title === model.title), + ).toBe(false); }); it("should make an LLM completion", async () => { diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index bf71952e9..4b4be0762 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -19,7 +19,9 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should load the default config successfully", async () => { const result = await testConfigHandler.loadConfig(); - expect(result.config!.models.length).toBe(defaultConfig.models?.length); + expect(result.config!.modelsByRole.chat.length).toBe( + defaultConfig.models?.length, + ); }); test.skip("should add a system message from config.ts", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 2d4a471d5..6fa6e4204 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -11,17 +11,11 @@ import { IContextProvider, IDE, IdeSettings, - ILLM, ILLMLogger, } from "../index.js"; -import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; import { getAllAssistantFiles } from "./loadLocalAssistants.js"; -import { - LOCAL_ONBOARDING_CHAT_MODEL, - LOCAL_ONBOARDING_PROVIDER_TITLE, -} from "./onboarding.js"; import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; @@ -473,27 +467,6 @@ export class ConfigHandler { } } - // Only used till we move to using selectedModelByRole.chat - async llmFromTitle(title?: string): Promise { - const { config } = await this.loadConfig(); - const model = config?.models.find((m) => m.title === title); - if (!model) { - if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) { - // Special case, make calls to Ollama before we have it in the config - const ollama = new Ollama({ - model: LOCAL_ONBOARDING_CHAT_MODEL, - }); - return ollama; - } else if (config?.models?.length) { - return config?.models[0]; - } - - throw new Error("No model found"); - } - - return model; - } - // Ancient method of adding custom providers through vs code private additionalContextProviders: IContextProvider[] = []; registerCustomContextProvider(contextProvider: IContextProvider) { diff --git a/core/config/load.ts b/core/config/load.ts index b85359641..8575206ad 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -504,7 +504,6 @@ async function intermediateToFinalConfig( const continueConfig: ContinueConfig = { ...config, contextProviders, - models, tools: [...allTools], mcpServerStatuses: [], slashCommands: config.slashCommands ?? [], @@ -544,7 +543,7 @@ async function intermediateToFinalConfig( // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; if (inlineEditModel) { - const match = continueConfig.models.find( + const match = continueConfig.modelsByRole.chat.find( (m) => m.title === inlineEditModel, ); if (match) { @@ -563,7 +562,7 @@ async function intermediateToFinalConfig( "applyCodeBlock", )?.title; if (applyBlockModel) { - const match = continueConfig.models.find( + const match = continueConfig.modelsByRole.chat.find( (m) => m.title === applyBlockModel, ); if (match) { @@ -607,6 +606,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { promptTemplates: llm.promptTemplates as any, capabilities: llm.capabilities, roles: llm.roles, + configurationStatus: llm.getConfigurationStatus(), }; } @@ -616,7 +616,6 @@ async function finalToBrowserConfig( ): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, - models: final.models.map(llmToSerializedModelDescription), systemMessage: final.systemMessage, completionOptions: final.completionOptions, slashCommands: final.slashCommands?.map( diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 626546b74..2957ca9d6 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -258,7 +258,7 @@ async function injectControlPlaneProxyInfo( } }); - config.models.forEach((model) => { + config.modelsByRole.chat.forEach((model) => { if (model.providerName === "continue-proxy") { (model as ContinueProxy).controlPlaneProxyInfo = info; } diff --git a/core/config/selectedModels.ts b/core/config/selectedModels.ts index dd537665d..42b966cf7 100644 --- a/core/config/selectedModels.ts +++ b/core/config/selectedModels.ts @@ -1,6 +1,7 @@ import { ModelRole } from "@continuedev/config-yaml"; import { ContinueConfig, ILLM } from ".."; +import { LLMConfigurationStatuses } from "../llm/constants"; import { GlobalContext, GlobalContextModelSelections, @@ -19,19 +20,20 @@ export function rectifySelectedModelsFromGlobalContext( let fellBack = false; - // chat and summarize not implemented yet - // default chat model is stored in GUI still - + // summarize not implemented yet const roles: ModelRole[] = [ "autocomplete", "apply", "edit", "embed", "rerank", + "chat", ]; + for (const role of roles) { let newModel: ILLM | null = null; const currentSelection = currentForProfile[role] ?? null; + if (currentSelection) { const match = continueConfig.modelsByRole[role].find( (m) => m.title === currentSelection, @@ -40,12 +42,23 @@ export function rectifySelectedModelsFromGlobalContext( newModel = match; } } + if (!newModel && continueConfig.modelsByRole[role].length > 0) { newModel = continueConfig.modelsByRole[role][0]; } + if (!(currentSelection === (newModel?.title ?? null))) { fellBack = true; } + + // Currently only check for configuration status for apply + if ( + role === "apply" && + newModel?.getConfigurationStatus() !== LLMConfigurationStatuses.VALID + ) { + continue; + } + configCopy.selectedModelByRole[role] = newModel; } diff --git a/core/config/util.ts b/core/config/util.ts index ee827c2f9..957e6c6ff 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -94,7 +94,7 @@ export function getModelByRole( return undefined; } - const matchingModel = config.models.find( + const matchingModel = config.modelsByRole.chat.find( (model) => model.title === roleTitle, ); diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index ffdae1f3f..8ecd35e10 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -135,7 +135,6 @@ async function configYamlToContinueConfig( const continueConfig: ContinueConfig = { slashCommands: [], - models: [], tools: [...allTools], mcpServerStatuses: [], systemMessage: config.rules?.join("\n"), @@ -150,7 +149,7 @@ async function configYamlToContinueConfig( summarize: [], }, selectedModelByRole: { - chat: null, // not currently used - defaultModel on GUI is used + chat: null, edit: null, // not currently used apply: null, embed: null, @@ -246,10 +245,6 @@ async function configYamlToContinueConfig( config: continueConfig, }); - if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { - continueConfig.models.push(...llms); - } - if (model.roles?.includes("chat")) { continueConfig.modelsByRole.chat.push(...llms); } @@ -347,7 +342,7 @@ async function configYamlToContinueConfig( if (allowFreeTrial) { // Obtain auth token (iff free trial being used) - const freeTrialModels = continueConfig.models.filter( + const freeTrialModels = continueConfig.modelsByRole.chat.filter( (model) => model.providerName === "free-trial", ); if (freeTrialModels.length > 0) { @@ -362,14 +357,15 @@ async function configYamlToContinueConfig( message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`, }); // Remove free trial models - continueConfig.models = continueConfig.models.filter( - (model) => model.providerName !== "free-trial", - ); + continueConfig.modelsByRole.chat = + continueConfig.modelsByRole.chat.filter( + (model) => model.providerName !== "free-trial", + ); } } } else { // Remove free trial models - continueConfig.models = continueConfig.models.filter( + continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter( (model) => model.providerName !== "free-trial", ); } diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index d8eb90ef9..468aac6ec 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -45,7 +45,7 @@ async function getContextProviderExtras( config, embeddingsProvider: config.selectedModelByRole.embed, fetch: fetch, - llm: config.models[0], + llm: config.modelsByRole.chat[0], reranker: config.selectedModelByRole.rerank, selectedCode: [], }; diff --git a/core/core.ts b/core/core.ts index e929a863b..68aa605ac 100644 --- a/core/core.ts +++ b/core/core.ts @@ -32,6 +32,7 @@ import { TTS } from "./util/tts"; import { DiffLine, IdeSettings, + ModelDescription, RangeInFile, type ContextItemId, type IDE, @@ -60,7 +61,13 @@ async function* streamDiffLinesGenerator( msg: Message, ): AsyncGenerator { const data = msg.data; - const llm = await configHandler.llmFromTitle(msg.data.modelTitle); + const llm = (await configHandler.loadConfig()).config?.selectedModelByRole + .chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + for await (const diffLine of streamDiffLines( data.prefix, data.highlighted, @@ -430,7 +437,13 @@ export class Core { ); on("llm/complete", async (msg) => { - const model = await this.configHandler.llmFromTitle(msg.data.title); + const model = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } + const completion = await model.complete( msg.data.prompt, new AbortController().signal, @@ -449,9 +462,13 @@ export class Core { }); on("chatDescriber/describe", async (msg) => { - const currentModel = await this.configHandler.llmFromTitle( - msg.data.selectedModelTitle, - ); + const currentModel = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!currentModel) { + throw new Error("No chat model selected"); + } + return await ChatDescriber.describe(currentModel, {}, msg.data.text); }); @@ -477,32 +494,7 @@ export class Core { on("completeOnboarding", this.handleCompleteOnboarding); - on("addAutocompleteModel", (msg) => { - const model = msg.data.model; - editConfigFile( - (config) => { - return { - ...config, - tabAutocompleteModel: model, - }; - }, - (config) => ({ - ...config, - models: [ - ...(config.models ?? []), - { - name: model.title, - provider: model.provider, - model: model.model, - apiKey: model.apiKey, - roles: ["autocomplete"], - apiBase: model.apiBase, - }, - ], - }), - ); - void this.configHandler.reloadConfig(); - }); + on("addAutocompleteModel", this.handleAddAutocompleteModel); on("stats/getTokensPerDay", async (msg) => { const rows = await DevDataSqliteDb.getTokensPerDay(); @@ -513,7 +505,6 @@ export class Core { return rows; }); - // Codebase indexing on("index/forceReIndex", async ({ data }) => { const { config } = await this.configHandler.loadConfig(); if (!config || config.disableIndexing) { @@ -599,11 +590,7 @@ export class Core { } }); - on("files/opened", async ({ data }) => { - if (data?.uris?.length) { - // Do something on files opened - } - }); + on("files/opened", async () => {}); // Docs, etc. indexing on("indexing/reindex", async (msg) => { @@ -618,7 +605,6 @@ export class Core { }); on("indexing/setPaused", async (msg) => { if (msg.data.type === "docs") { - // this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet } }); on("docs/initStatuses", async (msg) => { @@ -681,7 +667,12 @@ export class Core { throw new Error(`Tool ${toolCall.function.name} not found`); } - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } const contextItems = await callTool( tool, @@ -711,12 +702,15 @@ export class Core { return false; } - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } - // Count the size of the file tokenwise const tokens = countTokens(item.content); - // File exceeds context length of the model if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { return true; } @@ -725,6 +719,37 @@ export class Core { }); } + private handleAddAutocompleteModel( + msg: Message<{ + model: ModelDescription; + }>, + ) { + const model = msg.data.model; + editConfigFile( + (config) => { + return { + ...config, + tabAutocompleteModel: model, + }; + }, + (config) => ({ + ...config, + models: [ + ...(config.models ?? []), + { + name: model.title, + provider: model.provider, + model: model.model, + apiKey: model.apiKey, + roles: ["autocomplete"], + apiBase: model.apiBase, + }, + ], + }), + ); + void this.configHandler.reloadConfig(); + } + private async handleFilesChanged({ data, }: Message<{ @@ -789,8 +814,13 @@ export class Core { } const model = - config.models.find((model) => model.title === msg.data.title) ?? - config.models.find((model) => model.title?.startsWith(msg.data.title)); + config.modelsByRole.chat.find( + (model) => model.title === msg.data.title, + ) ?? + config.modelsByRole.chat.find((model) => + model.title?.startsWith(msg.data.title), + ); + try { if (model) { return await model.listModels(); @@ -854,10 +884,15 @@ export class Core { return []; } - const { name, query, fullInput, selectedCode, selectedModelTitle } = - msg.data; + const { name, query, fullInput, selectedCode } = msg.data; + + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); const provider = config.contextProviders?.find( (provider) => provider.description.title === name, diff --git a/core/index.d.ts b/core/index.d.ts index e7fb25ef9..f81f14262 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,5 +1,6 @@ import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; +import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -162,6 +163,8 @@ export interface ILLM extends LLMOptions { otherData: Record, canPutWordsInModelsMouth?: boolean, ): string | ChatMessage[]; + + getConfigurationStatus(): LLMConfigurationStatuses; } export interface ModelInstaller { @@ -1061,6 +1064,7 @@ export interface ModelDescription { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; + configurationStatus?: LLMConfigurationStatuses; } export interface EmbedOptions { @@ -1389,7 +1393,6 @@ export interface Config { // in the actual Continue source code export interface ContinueConfig { allowAnonymousTelemetry?: boolean; - models: ILLM[]; systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; @@ -1413,7 +1416,6 @@ export interface ContinueConfig { export interface BrowserSerializedContinueConfig { allowAnonymousTelemetry?: boolean; - models: ModelDescription[]; systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 333c79e70..8532aa33b 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -32,6 +32,11 @@ const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) const DEFAULT_MAX_BATCH_SIZE = 64; +export enum LLMConfigurationStatuses { + VALID = "valid", + MISSING_API_KEY = "missing-api-key", +} + export { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, diff --git a/core/llm/index.ts b/core/llm/index.ts index 7544b5292..723ab2f45 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -46,6 +46,7 @@ import { DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, + LLMConfigurationStatuses, } from "./constants.js"; import { compileChatMessages, @@ -265,6 +266,10 @@ export abstract class BaseLLM implements ILLM { this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; } + getConfigurationStatus() { + return LLMConfigurationStatuses.VALID; + } + protected createOpenAiAdapter() { return constructLlmApi({ provider: this.providerName as any, diff --git a/core/llm/llms/Relace.ts b/core/llm/llms/Relace.ts index f7a27c9e3..d65a94dc1 100644 --- a/core/llm/llms/Relace.ts +++ b/core/llm/llms/Relace.ts @@ -1,4 +1,5 @@ import { LLMOptions } from "../.."; +import { LLMConfigurationStatuses } from "../constants"; import { LlmApiRequestType } from "../openaiTypeConverters"; import OpenAI from "./OpenAI"; @@ -9,4 +10,12 @@ export class Relace extends OpenAI { apiBase: "https://instantapply.endpoint.relace.run/v1/", }; protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"]; + + getConfigurationStatus() { + if (!this.apiKey) { + return LLMConfigurationStatuses.MISSING_API_KEY; + } + + return LLMConfigurationStatuses.VALID; + } } diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 181db2abd..e43e2bfe2 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,10 +1,15 @@ -import { ContinueProperties } from "@continuedev/config-yaml"; +import { + ContinueProperties, + decodeSecretLocation, + SecretType, +} from "@continuedev/config-yaml"; import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js"; import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; import type { Chunk, LLMOptions } from "../../../index.js"; +import { LLMConfigurationStatuses } from "../../constants.js"; class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { @@ -49,6 +54,19 @@ class ContinueProxy extends OpenAI { }; } + getConfigurationStatus() { + if (!this.apiKeyLocation) { + return LLMConfigurationStatuses.VALID; + } + + const secretLocation = decodeSecretLocation(this.apiKeyLocation); + if (secretLocation.secretType === SecretType.NotFound) { + return LLMConfigurationStatuses.MISSING_API_KEY; + } + + return LLMConfigurationStatuses.VALID; + } + protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 9b1ea87b3..223b5b20e 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -23,19 +23,22 @@ export async function* llmStreamChat( void TTS.kill(); } - const { title, legacySlashCommandData, completionOptions, messages } = - msg.data; + const { legacySlashCommandData, completionOptions, messages } = msg.data; - const model = await configHandler.llmFromTitle(title); + const model = config.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } // Log to return in case of error const errorPromptLog = { - modelTitle: model.title ?? model.model, + modelTitle: model?.title ?? model?.model, completion: "", prompt: "", completionOptions: { ...msg.data.completionOptions, - model: model.model, + model: model?.model, }, }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 6aae337f0..b477fcce9 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -17,7 +17,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { { text: string; streamId: string; - curSelectedModelTitle: string; filepath?: string; toolCallId?: string; }, @@ -52,7 +51,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { { prompt: MessageContent; range: RangeInFileWithContents; - selectedModelTitle: string; }, void, ]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 9564f557d..1d854f948 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -68,7 +68,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", - "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. "addContextItem", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 5d17fbe6c..100ee2aad 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -60,7 +60,6 @@ class MessageTypes { // core/protocol/passThrough.ts val PASS_THROUGH_TO_WEBVIEW = listOf( "configUpdate", - "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. "addContextItem", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 4378d273d..cbcee8e98 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -65,21 +65,6 @@ class CoreMessenger( // Forward to webview if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { - // TODO: Currently we aren't set up to receive a response back from the webview - // Can circumvent for getDefaultsModelTitle here for now - if (messageType == "getDefaultModelTitle") { - val continueSettingsService = service() - val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel - val message = - gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to defaultModelTitle - ) - ) - write(message) - } val continuePluginService = project.service() continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 41c2c4892..5bdb31cd4 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -497,21 +497,18 @@ class IdeProtocolClient( val config = result["config"] as Map<*, *> val selectedModels = config["selectedModelByRole"] as? Map<*, *> - val applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *> + var applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *> + + // If "apply" role model is not found, try "chat" role + if (applyCodeBlockModel == null) { + applyCodeBlockModel = selectedModels?.get("chat") as? Map<*, *> + } if (applyCodeBlockModel != null) { continuation.resume(applyCodeBlockModel) } else { - val models = - config["models"] as List> - val curSelectedModel = - models.find { it["title"] == params.curSelectedModelTitle } - - if (curSelectedModel == null) { - continuation.resumeWithException(IllegalStateException("Model '${params.curSelectedModelTitle}' not found in config.")) - } else { - continuation.resume(curSelectedModel) - } + // If neither "apply" nor "chat" models are available, return with exception + continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration.")) } } catch (e: Exception) { continuation.resumeWithException(e) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 5c587c54d..718755a99 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -11,7 +11,6 @@ data class SetGitHubAuthTokenParams( data class ApplyToFileParams( val text: String, val streamId: String, - val curSelectedModelTitle: String, val filepath: String?, val toolCallId: String? ) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 5d8335220..d0d44655c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -11,7 +11,7 @@ import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory import javax.swing.* -const val JS_QUERY_POOL_SIZE = 200 +const val JS_QUERY_POOL_SIZE = "200" class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { @@ -43,6 +43,11 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { class ContinuePluginWindow(project: Project) { private val defaultGUIUrl = "http://continue/index.html" + init { + System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) + System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true") + } + val browser: ContinueBrowser by lazy { val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 108520e49..efc342f19 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 9009d2b58..719c1a5d1 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -12,7 +12,10 @@ 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 { startLocalOllama } from "core/util/ollamaHelper"; import { getDevDataFilePath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import readLastLines from "read-last-lines"; @@ -29,7 +32,6 @@ import { } from "./autocomplete/statusBar"; import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; - import { VerticalDiffManager } from "./diff/vertical/manager"; import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; @@ -37,9 +39,6 @@ import { Battery } from "./util/battery"; import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; -import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; -import { isModelInstaller } from "core/llm"; -import { startLocalOllama } from "core/util/ollamaHelper"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -364,18 +363,18 @@ const getCommandsMap: ( throw new Error("Config not loaded"); } - const modelTitle = - config.selectedModelByRole.edit?.title ?? - (await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - )); + const llm = + config.selectedModelByRole.edit ?? config.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No edit or chat model selected"); + } void sidebar.webviewProtocol.request("incrementFtc", undefined); await verticalDiffManager.streamEdit( config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, + llm, undefined, onlyOneInsertion, undefined, diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 4d4256a1f..48741a142 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,4 +1,4 @@ -import { ChatMessage, DiffLine } from "core"; +import { ChatMessage, DiffLine, ILLM } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; @@ -7,9 +7,9 @@ import * as URI from "uri-js"; import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; +import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; -import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -272,7 +272,7 @@ export class VerticalDiffManager { async streamEdit( input: string, - modelTitle: string | undefined, + llm: ILLM, streamId?: string, onlyOneInsertion?: boolean, quickEdit?: string, @@ -308,13 +308,13 @@ export class VerticalDiffManager { // Previous diff was a quickEdit // Check if user has highlighted a range let rangeBool = - startLine != endLine || - editor.selection.start.character != editor.selection.end.character; + startLine !== endLine || + editor.selection.start.character !== editor.selection.end.character; // Check if the range is different from the previous range let newRangeBool = - startLine != existingHandler.range.start.line || - endLine != existingHandler.range.end.line; + startLine !== existingHandler.range.start.line || + endLine !== existingHandler.range.end.line; if (!rangeBool || !newRangeBool) { // User did not highlight a new range -> use start/end from the previous quickEdit @@ -374,7 +374,6 @@ export class VerticalDiffManager { ); } - const llm = await this.configHandler.llmFromTitle(modelTitle); const rangeContent = editor.document.getText(selectedRange); const prefix = pruneLinesFromTop( editor.document.getText( diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 9563eb8a9..591c82454 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,7 +18,6 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; -import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -180,19 +179,14 @@ export class VsCodeMessenger { return; } - let llm: ILLM | null | undefined = config.selectedModelByRole.apply; + let llm = + config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; if (!llm) { - llm = config.models.find( - (model) => model.title === data.curSelectedModelTitle, + vscode.window.showErrorMessage( + `No model with roles "apply" or "chat" found in config.`, ); - - if (!llm) { - vscode.window.showErrorMessage( - `Model ${data.curSelectedModelTitle} not found in config.`, - ); - return; - } + return; } const fastLlm = getModelByRole(config, "repoMapFileSelection") ?? llm; @@ -229,7 +223,7 @@ export class VsCodeMessenger { await verticalDiffManager.streamEdit( prompt, - llm.title, + llm, data.streamId, undefined, undefined, @@ -292,9 +286,19 @@ export class VsCodeMessenger { const { start, end } = msg.data.range.range; const verticalDiffManager = await verticalDiffManagerPromise; + const configHandler = await configHandlerPromise; + const { config } = await configHandler.loadConfig(); + + const model = + config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No Edit or Chat model selected"); + } + const fileAfterEdit = await verticalDiffManager.streamEdit( stripImages(prompt), - msg.data.selectedModelTitle, + model, "edit", undefined, undefined, diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index 074ec4d86..f982c5c55 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -34,7 +34,7 @@ export async function getContextProvidersString( provider.description.displayTitle === selectedProvider.label, ); - if (!provider) { + if (!provider || !config.selectedModelByRole.chat) { return []; } @@ -43,7 +43,7 @@ export async function getContextProvidersString( ide, embeddingsProvider: config.selectedModelByRole.embed, reranker: config.selectedModelByRole.rerank, - llm: config.models[0], + llm: config.selectedModelByRole.chat, fullInput: "", selectedCode: [], fetch: (url, init) => diff --git a/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts b/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts deleted file mode 100644 index d46ed6d43..000000000 --- a/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ContinueConfig } from "core"; -import { QuickPickItem, window } from "vscode"; - -export async function getModelQuickPickVal( - curModelTitle: string, - config: ContinueConfig, -) { - const modelItems: QuickPickItem[] = config.models.map((model) => { - const isCurModel = curModelTitle === model.title; - - return { - label: model.title - ? `${isCurModel ? "$(check)" : " "} ${model.title}` - : "Model title not set", - }; - }); - - const selectedItem = await window.showQuickPick(modelItems, { - title: "Models", - placeHolder: "Select a model", - }); - - if (!selectedItem) { - return undefined; - } - - const selectedModelTitle = config.models.find( - (model) => model.title && selectedItem.label.includes(model.title), - )?.title; - - return selectedModelTitle; -} diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index ec84eb81b..e0c826fb1 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { IDE } from "core"; +import { IDE, ILLM } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; +import { DataLogger } from "core/data/log"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -8,10 +9,8 @@ import { VerticalDiffManager } from "../diff/vertical/manager"; import { FileSearch } from "../util/FileSearch"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { DataLogger } from "core/data/log"; import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick"; import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick"; -import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; // @ts-ignore - error finding typings // @ts-ignore @@ -23,7 +22,6 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; enum QuickEditInitialItemLabels { History = "History", ContextProviders = "Context providers", - Model = "Model", Submit = "Submit", } @@ -100,11 +98,6 @@ export class QuickEdit { */ private contextProviderStr?: string; - /** - * Stores the current model title for potential changes - */ - private _curModelTitle?: string; - constructor( private readonly verticalDiffManager: VerticalDiffManager, private readonly configHandler: ConfigHandler, @@ -224,7 +217,7 @@ export class QuickEdit { default: break; } - let model = await this.getCurModelTitle(); + let model = await this.getCurModel(); void DataLogger.getInstance().logDevData({ name: "quickEdit", @@ -233,7 +226,7 @@ export class QuickEdit { path, label, diffs: this.verticalDiffManager.logDiffs, - model, + model: model?.title, }, }); @@ -245,12 +238,12 @@ export class QuickEdit { prompt: string, path: string | undefined, ) => { - const modelTitle = await this.getCurModelTitle(); - if (!modelTitle) { + const model = await this.getCurModel(); + if (!model) { throw new Error("No model selected"); } - await this._streamEditWithInputAndContext(prompt, modelTitle); + await this._streamEditWithInputAndContext(prompt, model); this.openAcceptRejectMenu(prompt, path); }; @@ -266,25 +259,13 @@ export class QuickEdit { /** * Gets the model title the user has chosen, or their default model */ - private async getCurModelTitle(): Promise { - if (this._curModelTitle) { - return this._curModelTitle; - } - + private async getCurModel(): Promise { const { config } = await this.configHandler.loadConfig(); if (!config) { - return undefined; + return null; } - return ( - config.selectedModelByRole.edit?.title ?? - (await this.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - false, - )) ?? - config.models[0]?.title - ); + return config.selectedModelByRole.edit ?? config.selectedModelByRole.chat; } /** @@ -314,10 +295,7 @@ export class QuickEdit { }`; }; - private async _streamEditWithInputAndContext( - prompt: string, - modelTitle: string, - ) { + private async _streamEditWithInputAndContext(prompt: string, model: ILLM) { // Extracts all file references from the prompt string, // which are denoted by an '@' symbol followed by // one or more non-whitespace characters. @@ -343,7 +321,7 @@ export class QuickEdit { await this.verticalDiffManager.streamEdit( prompt, - modelTitle, + model, undefined, undefined, this.previousInput, @@ -351,7 +329,7 @@ export class QuickEdit { ); } - private getInitialItems(modelTitle: string): vscode.QuickPickItem[] { + private getInitialItems(): vscode.QuickPickItem[] { return [ { label: QuickEditInitialItemLabels.History, @@ -361,10 +339,6 @@ export class QuickEdit { label: QuickEditInitialItemLabels.ContextProviders, detail: "$(add) Add context to your prompt", }, - { - label: QuickEditInitialItemLabels.Model, - detail: `$(chevron-down) ${modelTitle}`, - }, ]; } @@ -372,7 +346,7 @@ export class QuickEdit { label: QuickEditInitialItemLabels | undefined; value: string | undefined; }> { - const modelTitle = await this.getCurModelTitle(); + const modelTitle = await this.getCurModel(); if (!modelTitle) { this.ide.showToast("error", "Please configure a model to use Quick Edit"); @@ -381,7 +355,7 @@ export class QuickEdit { const quickPick = vscode.window.createQuickPick(); - const initialItems = this.getInitialItems(modelTitle); + const initialItems = this.getInitialItems(); quickPick.items = initialItems; quickPick.placeholder = "Enter a prompt to edit your code (@ to search files, ⏎ to submit)"; @@ -552,27 +526,6 @@ export class QuickEdit { break; - case QuickEditInitialItemLabels.Model: - const curModelTitle = await this.getCurModelTitle(); - - if (!curModelTitle) { - break; - } - - const selectedModelTitle = await getModelQuickPickVal( - curModelTitle, - config, - ); - - if (selectedModelTitle) { - this._curModelTitle = selectedModelTitle; - } - - // Recurse back to let the user write their prompt - this.initiateNewQuickPick(editor, params); - - break; - case QuickEditInitialItemLabels.Submit: if (selectedValue) { prompt = selectedValue; diff --git a/extensions/vscode/src/test/test-suites/main.test.ts b/extensions/vscode/src/test/test-suites/main.test.ts deleted file mode 100644 index 2cd1945fa..000000000 --- a/extensions/vscode/src/test/test-suites/main.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from "node:assert"; - -import { describe, test } from "mocha"; -import * as vscode from "vscode"; - -import { VsCodeExtension } from "../../extension/VsCodeExtension"; - -describe("Extension Test Suite", () => { - vscode.window.showInformationMessage("Start all tests."); - - // test("Make sure that nothing breaks after 10 seconds", async () => { - // await new Promise((resolve) => setTimeout(resolve, 10_000)); - // }); - - test("Get the default model from webview", async () => { - const continueExtensionApi = - vscode.extensions.getExtension("continue.continue"); - const extension: VsCodeExtension = continueExtensionApi?.exports.extension; - await new Promise((resolve) => setTimeout(resolve, 400)); - await vscode.commands.executeCommand("continue.focusContinueInput"); - await new Promise((resolve) => setTimeout(resolve, 400)); - const title = await ( - await extension.webviewProtocolPromise - ).request("getDefaultModelTitle", undefined); - assert.strictEqual(typeof title, "string"); - assert.strictEqual(title, "Test Model"); - }); -}); diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index b2efd221c..d6e79651c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -1,11 +1,11 @@ import { useAppSelector } from "../redux/hooks"; -import { selectDefaultModel } from "../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../redux/slices/configSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; import { getLocalStorage } from "../util/localStorage"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; function Footer() { - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); if (defaultModel?.provider === "free-trial") { return ( diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index a4baa9a1e..aa8be2a29 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -37,7 +37,7 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { return ( onboardingCard.close()} testId="onboarding-card" > diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index 389ed72dd..d739a8434 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -1,11 +1,12 @@ import { CubeIcon } from "@heroicons/react/24/outline"; import { FormEventHandler, useContext, useState } from "react"; -import { useDispatch } from "react-redux"; import { Button, Input, InputSubtext, lightGray } from "../.."; +import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { models } from "../../../pages/AddNewModel/configs/models"; import { providers } from "../../../pages/AddNewModel/configs/providers"; -import { setDefaultModel } from "../../../redux/slices/configSlice"; +import { useAppDispatch } from "../../../redux/hooks"; +import { updateSelectedModelByRole } from "../../../redux/thunks"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; const { anthropic, mistral } = providers; @@ -25,7 +26,8 @@ interface BestExperienceConfigFormProps { function BestExperienceConfigForm({ onComplete, }: BestExperienceConfigFormProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); + const { selectedProfile } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); @@ -61,7 +63,14 @@ function BestExperienceConfigForm({ model: repoMapConfig, role: "repoMapFileSelection", }); - dispatch(setDefaultModel({ title: chatModelConfig.title, force: true })); + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: chatModelConfig.title, + }), + ); if (!!autocompleteApiKey) { await ideMessenger.request("addAutocompleteModel", { diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index 4c0deda74..daa064ea2 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -28,7 +28,7 @@ export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { return ( onboardingCard.close()} >
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 81b0a7a6b..0f1e05da0 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -6,15 +6,16 @@ import { LOCAL_ONBOARDING_PROVIDER_TITLE, } from "core/config/onboarding"; import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; import { Button } from "../.."; +import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { updateSelectedModelByRole } from "../../../redux/thunks"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; -import { setDefaultModel } from "../../../redux/slices/configSlice"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; const OLLAMA_CHECK_INTERVAL_MS = 3000; @@ -23,13 +24,14 @@ interface OnboardingLocalTabProps { } function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const { submitOnboarding } = useSubmitOnboarding("Local", isDialog); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< string[] >([]); + const { selectedProfile } = useAuth(); const [isOllamaConnected, setIsOllamaConnected] = useState(false); @@ -135,11 +137,11 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { dispatch(setShowDialog(false)); } - // Set the selected model to the local chat model dispatch( - setDefaultModel({ - title: LOCAL_ONBOARDING_CHAT_TITLE, - force: true, // Because it doesn't exist in the webview's config object yet + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: LOCAL_ONBOARDING_CHAT_TITLE, }), ); }} diff --git a/gui/src/components/StepContainer/ThinkingIndicator.tsx b/gui/src/components/StepContainer/ThinkingIndicator.tsx index 862351872..3dcbf9491 100644 --- a/gui/src/components/StepContainer/ThinkingIndicator.tsx +++ b/gui/src/components/StepContainer/ThinkingIndicator.tsx @@ -1,7 +1,7 @@ import { ChatHistoryItem } from "core"; import { useEffect, useState } from "react"; import { useAppSelector } from "../../redux/hooks"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; interface ThinkingIndicatorProps { historyItem: ChatHistoryItem; @@ -22,7 +22,7 @@ const ThinkingIndicator = ({ historyItem }: ThinkingIndicatorProps) => { }; }, []); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const hasContent = Array.isArray(historyItem.message.content) diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index c028b7a87..9d5a10bec 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -26,6 +26,7 @@ import { } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppSelector } from "../../../redux/hooks"; +import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import FileIcon from "../../FileIcon"; @@ -161,9 +162,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const ideMessenger = useContext(IdeMessengerContext); - const selectedModelTitle = useAppSelector( - (store) => store.config.defaultModelTitle, - ); + const selectedModelTitle = useAppSelector(selectSelectedChatModel); const [selectedIndex, setSelectedIndex] = useState(0); @@ -192,7 +191,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { query, fullInput: "", selectedCode, - selectedModelTitle: selectedModelTitle ?? "", + selectedModelTitle: selectedModelTitle?.title ?? "", }, ); @@ -205,7 +204,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { // Check if the context item exceeds the context length of the selected model const result = await ideMessenger.request("isItemTooBig", { item, - selectedModelTitle: selectedModelTitle, + selectedModelTitle: selectedModelTitle?.title, }); if (result.status === "error") { diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 20e40d9a9..252126425 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -14,7 +14,7 @@ import { import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { selectHasCodeToEdit, selectIsInEditMode, @@ -92,7 +92,7 @@ interface InputToolbarProps { function InputToolbar(props: InputToolbarProps) { const dispatch = useAppDispatch(); const fileInputRef = useRef(null); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx index 05e9352f0..b128db0a2 100644 --- a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -1,54 +1,31 @@ import { ModelRole } from "@continuedev/config-yaml"; import { ModelDescription } from "core"; -import { useContext } from "react"; import { useAuth } from "../../../../context/Auth"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, - updateConfig, -} from "../../../../redux/slices/configSlice"; +import { updateSelectedModelByRole } from "../../../../redux/thunks"; import { isJetBrains } from "../../../../util"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; export function ModelsSection() { const { selectedProfile } = useAuth(); const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); const jetbrains = isJetBrains(); - const selectedChatModel = useAppSelector(selectDefaultModel); function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) { - if (!selectedProfile) { - return; - } - // Optimistic update - dispatch( - updateConfig({ - ...config, - selectedModelByRole: { - ...config.selectedModelByRole, - [role]: model, - }, - }), - ); - ideMessenger.post("config/updateSelectedModel", { - profileId: selectedProfile.id, - role, - title: model?.title ?? null, - }); - } - - // TODO use handleRoleUpdate for chat - function handleChatModelSelection(model: ModelDescription | null) { if (!model) { return; } - dispatch(setDefaultModel({ title: model.title })); + + dispatch( + updateSelectedModelByRole({ + role, + selectedProfile, + modelTitle: model.title, + }), + ); } return ( @@ -58,16 +35,8 @@ export function ModelsSection() { displayName="Chat" description="Used in the chat interface" models={config.modelsByRole.chat} - selectedModel={ - selectedChatModel - ? { - title: selectedChatModel.title, - provider: selectedChatModel.provider, - model: selectedChatModel.model, - } - : null - } - onSelect={(model) => handleChatModelSelection(model)} + selectedModel={config.selectedModelByRole.chat} + onSelect={(model) => handleRoleUpdate("chat", model)} /> state.session.isStreaming); const isInEditMode = useAppSelector(selectIsInEditMode); const historyLength = useAppSelector((store) => store.session.history.length); diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 6e7808ba7..400f08019 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -123,8 +123,6 @@ export function useMainEditorWebviewListeners({ } } - debugger; - editor .chain() .insertContentAt(index, { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index e50769ac8..9c56819e3 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -21,7 +21,7 @@ import { useInputHistory } from "../../../../hooks/useInputHistory"; import useUpdatingRef from "../../../../hooks/useUpdatingRef"; import { useAppSelector } from "../../../../redux/hooks"; import { selectUseActiveFile } from "../../../../redux/selectors"; -import { selectDefaultModel } from "../../../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; import { addCodeToEdit, selectHasCodeToEdit, @@ -83,7 +83,7 @@ export function createEditorConfig(options: { const posthog = usePostHog(); const { getSubmenuContextItems } = useSubmenuContextProviders(); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const useActiveFile = useAppSelector(selectUseActiveFile); const historyLength = useAppSelector((store) => store.session.history.length); diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 85ece0990..7e42dfb1c 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -13,10 +13,7 @@ import { import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - selectUIConfig, -} from "../../redux/slices/configSlice"; +import { selectUIConfig } from "../../redux/slices/configSlice"; import { isJetBrains } from "../../util"; import { CopyIconButton } from "../gui/CopyIconButton"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; @@ -56,16 +53,14 @@ export default function StepContainerPreActionButtons({ streamIdRef.current = uuidv4(); } - const defaultModel = useAppSelector(selectDefaultModel); - function onClickApply() { - if (!defaultModel || !streamIdRef.current) { + if (!streamIdRef.current) { return; } + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, }); } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index f09ed1a9f..c00290e4c 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -11,7 +11,7 @@ import { import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { selectApplyStateByStreamId, selectIsInEditMode, @@ -31,6 +31,7 @@ const TopDiv = styled.div` outline-offset: -0.5px; border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; + margin-top: 8px !important; background-color: ${vscEditorBackground}; min-width: 0; `; @@ -81,10 +82,10 @@ export default function StepContainerPreToolbar( const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath); - const defaultModel = useAppSelector(selectDefaultModel); + const selectedChatModel = useAppSelector(selectSelectedChatModel); async function onClickApply() { - if (!defaultModel) { + if (!selectedChatModel) { return; } @@ -97,7 +98,6 @@ export default function StepContainerPreToolbar( streamId: props.codeBlockStreamId, filepath: fileUri, text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, }); } diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/modelSelection/ModeSelect.tsx index 0e14adfad..92395f545 100644 --- a/gui/src/components/modelSelection/ModeSelect.tsx +++ b/gui/src/components/modelSelection/ModeSelect.tsx @@ -12,7 +12,7 @@ import { useEffect, useMemo } from "react"; import styled from "styled-components"; import { lightGray } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { cycleMode, selectCurrentMode, @@ -40,7 +40,7 @@ const ShortcutText = styled.span` function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector(selectCurrentMode); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const agentModeSupported = selectedModel && modelSupportsTools(selectedModel); const jetbrains = useMemo(() => { diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 4c2e31387..aa84f9f33 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -6,18 +6,15 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray } from ".."; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; -import { useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, -} from "../../redux/slices/configSlice"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { updateSelectedModelByRole } from "../../redux/thunks"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; @@ -122,9 +119,11 @@ function ModelOption({ } function ModelSelect() { - const dispatch = useDispatch(); - const defaultModel = useAppSelector(selectDefaultModel); - const allModels = useAppSelector((state) => state.config.config.models); + const dispatch = useAppDispatch(); + const selectedChatModel = useAppSelector(selectSelectedChatModel); + const allChatModels = useAppSelector( + (state) => state.config.config.modelsByRole.chat, + ); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -142,7 +141,7 @@ function ModelSelect() { useEffect(() => { setOptions( - allModels + allChatModels .filter((m) => !m.roles || m.roles.includes("chat")) .map((model) => { return { @@ -152,19 +151,30 @@ function ModelSelect() { }; }), ); - }, [allModels]); + }, [allChatModels]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { + if (!selectedProfile) { + return; + } + const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( - (option) => option.value === defaultModel?.title, + (option) => option.value === selectedChatModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; const newModelTitle = options[nextIndex].value; - dispatch(setDefaultModel({ title: newModelTitle })); + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: newModelTitle, + }), + ); } }; @@ -172,7 +182,7 @@ function ModelSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [options, defaultModel]); + }, [options, selectedChatModel]); function onClickAddModel(e: MouseEvent) { e.stopPropagation(); @@ -195,11 +205,16 @@ function ModelSelect() { } return ( - // Hiad sfasdfasdf asdfasdf { - if (val === defaultModel?.title) return; - dispatch(setDefaultModel({ title: val })); + if (val === selectedChatModel?.title) return; + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: val, + }), + ); }} >
@@ -209,7 +224,7 @@ function ModelSelect() { className="h-[18px] gap-1 border-none text-gray-400" > - {modelSelectTitle(defaultModel) || "Select model"} + {modelSelectTitle(selectedChatModel) || "Select model"} ))}
diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index e0d88dc12..71a10547e 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -1,5 +1,5 @@ import { - ArrowPathRoundedSquareIcon, + ArrowPathIcon, ArrowTopRightOnSquareIcon, BuildingOfficeIcon, ChevronDownIcon, @@ -99,7 +99,7 @@ const AssistantSelectOption = ({ fontSize: tinyFont, }} > -
+
@@ -291,6 +291,20 @@ export default function AssistantSelect() { +
+ Assistants +
{ + e.stopPropagation(); + refreshProfiles(); + buttonRef.current?.click(); + }} + > + +
+
+
@@ -314,8 +328,9 @@ export default function AssistantSelect() { }} /> -
+
login(false)} @@ -330,24 +345,6 @@ export default function AssistantSelect() { New Assistant
-
{ - e.stopPropagation(); - refreshProfiles(); - buttonRef.current?.click(); - }} - > - - - Refresh - -
void; @@ -33,13 +34,14 @@ function AddModelForm({ const [selectedProvider, setSelectedProvider] = useState( providers["openai"]!, ); + const dispatch = useAppDispatch(); + const { selectedProfile } = useAuth(); const [selectedModel, setSelectedModel] = useState( selectedProvider.packages[0], ); const formMethods = useForm(); - const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); const popularProviderTitles = [ @@ -115,7 +117,13 @@ function AddModelForm({ profileId: "local", }); - dispatch(setDefaultModel({ title: model.title, force: true })); + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: model.title, + }), + ); onDone(); } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 5b3e665ad..3f65ecfa3 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -11,7 +11,7 @@ import { } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { - selectDefaultModel, + selectSelectedChatModel, setConfigResult, } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; @@ -35,7 +35,7 @@ function useSetup() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => store.session.history); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const selectedProfileId = useAppSelector( (store) => store.profiles.selectedProfileId, ); @@ -50,6 +50,7 @@ function useSetup() { organizations, selectedOrgId, } = result; + debugger; if (isInitial && hasDoneInitialConfigLoad.current) { return; } @@ -253,26 +254,12 @@ function useSetup() { dispatch(updateIndexingStatus(data)); }); - useWebviewListener( - "getDefaultModelTitle", - async () => { - return defaultModel?.title; - }, - [defaultModel], - ); - const activeToolStreamId = useAppSelector( (store) => store.session.activeToolStreamId, ); useWebviewListener( "updateApplyState", async (state) => { - // dispatch( - // updateCurCheckpoint({ - // filepath: state.filepath, - // content: state.fileContent, - // }), - // ); dispatch(updateApplyState(state)); if ( activeToolStreamId && diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index cdc0d16d1..e3464a6f2 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -1,5 +1,12 @@ -import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/24/outline"; -import { type ModelDescription } from "core"; +import { + CheckIcon, + ChevronUpDownIcon, + Cog6ToothIcon, + CubeIcon, +} from "@heroicons/react/24/outline"; +import { ModelDescription } from "core"; +import { LLMConfigurationStatuses } from "core/llm/constants"; +import { MouseEvent, useContext, useState } from "react"; import { defaultBorderRadius } from "../../components"; import { ToolTip } from "../../components/gui/Tooltip"; import InfoHover from "../../components/InfoHover"; @@ -10,6 +17,7 @@ import { ListboxOptions, Transition, } from "../../components/ui"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { fontSize } from "../../util"; interface ModelRoleSelectorProps { @@ -27,10 +35,33 @@ const ModelRoleSelector = ({ displayName, description, }: ModelRoleSelectorProps) => { + const ideMessenger = useContext(IdeMessengerContext); + const [hoveredIdx, setHoveredIdx] = useState(null); + + const noConfiguredModels = models.every( + (model) => model.configurationStatus !== LLMConfigurationStatuses.VALID, + ); + function handleSelect(title: string | null) { onSelect(models.find((m) => m.title === title) ?? null); } + function onClickGear(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + ideMessenger.post("config/openProfile", { profileId: undefined }); + } + + function handleOptionClick( + showMissingApiKeyMsg: boolean, + e: MouseEvent, + ) { + if (showMissingApiKeyMsg) { + e.preventDefault(); + e.stopPropagation(); + } + } + return ( <>
@@ -52,8 +83,14 @@ const ModelRoleSelector = ({ disabled={models.length === 0} className={`bg-vsc-editor-background hover:bg-list-active hover:text-list-active-foreground w-full justify-between`} > - {models.length === 0 ? ( - {`No ${displayName} models${["Chat", "Apply", "Edit"].includes(displayName) ? ". Using chat model" : ""}`} + {models.length === 0 || noConfiguredModels ? ( + + {`No ${models.length === 0 ? "" : "valid "}${displayName} models${ + ["Chat", "Apply", "Edit"].includes(displayName) + ? ". Using Chat model" + : "" + }`} + ) : ( {selectedModel?.title ?? `Select ${displayName} model`} @@ -71,19 +108,55 @@ const ModelRoleSelector = ({ style={{ borderRadius: defaultBorderRadius }} className="min-w-40" > - {models.map((option, idx) => ( - - { + const showMissingApiKeyMsg = + option.configurationStatus === + LLMConfigurationStatuses.MISSING_API_KEY; + + return ( + setHoveredIdx(idx)} + onMouseLeave={() => setHoveredIdx(null)} + onClick={(e: any) => + handleOptionClick(showMissingApiKeyMsg, e) + } + className={""} > - {option.title} - - {option.title === selectedModel?.title && ( - - ))} +
+
+
+ + + {option.title} + {showMissingApiKeyMsg && ( + + (Missing API key) + + )} + +
+
+ {hoveredIdx === idx && ( + + )} + {option.title === selectedModel?.title && ( + + )} +
+
+
+ + ); + })}
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 682671cbb..0ffd577c1 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -31,7 +31,7 @@ import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { submitEdit } from "../../redux/slices/editModeState"; import { newSession, @@ -105,7 +105,7 @@ export function Chat() { const showSessionTabs = useAppSelector( (store) => store.config.config.ui?.showSessionTabs, ); - const defaultModel = useAppSelector(selectDefaultModel); + const selectedChatModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); @@ -165,7 +165,7 @@ export function Chat() { "Cannot submit message while awaiting tool confirmation", ); } - if (defaultModel?.provider === "free-trial") { + if (selectedChatModel?.provider === "free-trial") { const newCount = incrementFreeTrialCount(); if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { @@ -224,7 +224,7 @@ export function Chat() { }, [ history, - defaultModel, + selectedChatModel, streamResponse, isSingleRangeEditOrInsertion, codeToEdit, @@ -233,7 +233,7 @@ export function Chat() { ); async function handleSingleRangeEditOrInsertion(editorState: JSONContent) { - if (!defaultModel) { + if (!selectedChatModel) { console.error("No selected chat model"); return; } @@ -248,7 +248,7 @@ export function Chat() { defaultContextProviders: [], availableSlashCommands: [], dispatch, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); const prompt = [ @@ -259,7 +259,6 @@ export function Chat() { ideMessenger.post("edit/sendPrompt", { prompt, range: codeToEdit[0] as RangeInFileWithContents, - selectedModelTitle: defaultModel.title, }); dispatch(submitEdit(prompt)); diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 389528cd0..35fe3dc91 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -9,7 +9,7 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { selectSelectedProfile } from "../../redux/"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { isLocalProfile } from "../../util"; import { providers } from "../AddNewModel/configs/providers"; @@ -20,7 +20,7 @@ interface StreamErrorProps { const StreamErrorDialog = ({ error }: StreamErrorProps) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const hubEnabled = useAppSelector(selectUseHub); const selectedProfile = useAppSelector(selectSelectedProfile); const { session, refreshProfiles } = useAuth(); diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 3092f01c5..9c33ec3ff 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -6,7 +6,6 @@ import { DEFAULT_MAX_TOKENS } from "core/llm/constants"; export type ConfigState = { configError: ConfigValidationError[] | undefined; config: BrowserSerializedContinueConfig; - defaultModelTitle?: string; }; const EMPTY_CONFIG: BrowserSerializedContinueConfig = { @@ -21,7 +20,6 @@ const EMPTY_CONFIG: BrowserSerializedContinueConfig = { }, ], contextProviders: [], - models: [], tools: [], mcpServerStatuses: [], usePlatform: true, @@ -47,7 +45,6 @@ const EMPTY_CONFIG: BrowserSerializedContinueConfig = { const initialState: ConfigState = { configError: undefined, - defaultModelTitle: undefined, config: EMPTY_CONFIG, }; @@ -70,12 +67,8 @@ export const configSlice = createSlice({ // Don't invalidate the loaded config if (!config) { state.config = EMPTY_CONFIG; - state.defaultModelTitle = undefined; } else { state.config = config; - state.defaultModelTitle = - config.models.find((model) => model.title === state.defaultModelTitle) - ?.title || config.models[0]?.title; } }, updateConfig: ( @@ -84,63 +77,29 @@ export const configSlice = createSlice({ ) => { state.config = config; }, - setDefaultModel: ( - state, - { payload }: PayloadAction<{ title: string; force?: boolean }>, - ) => { - const model = state.config.models.find( - (model) => model.title === payload.title, - ); - if (!model && !payload.force) return; - return { - ...state, - defaultModelTitle: payload.title, - }; - }, - cycleDefaultModel: (state, { payload }: PayloadAction<"next" | "prev">) => { - const currentIndex = state.config.models.findIndex( - (model) => model.title === state.defaultModelTitle, - ); - const nextIndex = - (currentIndex + - (payload === "next" ? 1 : -1) + - state.config.models.length) % - state.config.models.length; - return { - ...state, - defaultModelTitle: state.config.models[nextIndex].title, - }; - }, }, selectors: { - selectDefaultModel: (state) => { - return state.config.models.find( - (model) => model.title === state.defaultModelTitle, - ); - }, - selectDefaultModelContextLength: (state): number => { + selectSelectedChatModelContextLength: (state): number => { return ( - configSlice.getSelectors().selectDefaultModel(state)?.contextLength || + state.config.selectedModelByRole.chat?.contextLength || DEFAULT_MAX_TOKENS ); }, + selectSelectedChatModel: (state) => { + return state.config.selectedModelByRole.chat; + }, selectUIConfig: (state) => { return state.config?.ui ?? null; }, }, }); -export const { - setDefaultModel, - cycleDefaultModel, - updateConfig, - setConfigResult, -} = configSlice.actions; +export const { updateConfig, setConfigResult } = configSlice.actions; export const { - selectDefaultModel, - selectDefaultModelContextLength, + selectSelectedChatModelContextLength, selectUIConfig, + selectSelectedChatModel, } = configSlice.selectors; export default configSlice.reducer; diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index bf15e7ae8..cb875f805 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -5,7 +5,7 @@ import { EditToolArgs } from "core/tools/definitions/editFile"; import { resolveRelativePathInDir } from "core/util/ideUtils"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { acceptToolCall, cancelToolCall, @@ -30,8 +30,9 @@ export const callTool = createAsyncThunk( return; } - const defaultModel = selectDefaultModel(state); - if (!defaultModel) { + const selectedChatModel = selectSelectedChatModel(state); + + if (!selectedChatModel) { throw new Error("No model selected"); } @@ -54,7 +55,6 @@ export const callTool = createAsyncThunk( args, extra.ideMessenger, state.session.activeToolStreamId[0], - defaultModel.title, toolCallState.toolCallId, ); } catch (e) { @@ -77,7 +77,7 @@ export const callTool = createAsyncThunk( } else { const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); if (result.status === "error") { errorMessage = result.error; @@ -125,7 +125,6 @@ async function customGuiEditImpl( args: EditToolArgs, ideMessenger: IIdeMessenger, streamId: string, - modelTitle: string, toolCallId: string, ) { const firstUriMatch = await resolveRelativePathInDir( @@ -138,7 +137,6 @@ async function customGuiEditImpl( const apply = await ideMessenger.request("applyToFile", { streamId, text: args.new_contents, - curSelectedModelTitle: modelTitle, toolCallId, filepath: firstUriMatch, }); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 450471164..2ba244d3f 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -9,7 +9,7 @@ import { } from "core"; import * as URI from "uri-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; export const gatherContext = createAsyncThunk< @@ -37,11 +37,12 @@ export const gatherContext = createAsyncThunk< { dispatch, extra, getState }, ) => { const state = getState(); - const defaultModel = selectDefaultModel(state); + const selectedChatModel = selectSelectedChatModel(state); + const defaultContextProviders = state.config.config.experimental?.defaultContext ?? []; - if (!defaultModel) { + if (!selectedChatModel) { console.error( "gatherContext thunk: Cannot gather context, no model selected", ); @@ -57,12 +58,12 @@ export const gatherContext = createAsyncThunk< defaultContextProviders, availableSlashCommands: state.config.config.slashCommands, dispatch, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); // Automatically use currently open file if (!modifiers.noContext) { - const usingFreeTrial = defaultModel.provider === "free-trial"; + const usingFreeTrial = selectedChatModel.provider === "free-trial"; const currentFileResponse = await extra.ideMessenger.request( "context/getContextItems", @@ -71,7 +72,7 @@ export const gatherContext = createAsyncThunk< query: "non-mention-usage", fullInput: "", selectedCode: [], - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }, ); if (currentFileResponse.status === "success") { diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index 59b556f8d..ad987fafa 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -5,3 +5,4 @@ export { streamNormalInput } from "./streamNormalInput"; export { streamResponseThunk } from "./streamResponse"; export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; export { streamThunkWrapper } from "./streamThunkWrapper"; +export { updateSelectedModelByRole } from "./updateSelectedModelByRole"; diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index b5ef0ac9a..7572b1fe4 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -3,7 +3,7 @@ import { ChatMessage, Session, SessionMetadata } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage } from "core/util/messageContent"; import { IIdeMessenger } from "../../context/IdeMessenger"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { deleteSessionMetadata, newSession, @@ -167,8 +167,9 @@ export const saveCurrentSession = createAsyncThunk< // Now save previous session and update chat title if relevant let title = state.session.title; if (title === NEW_SESSION_TITLE) { - const defaultModel = selectDefaultModel(state); - if (!state.config.config?.disableSessionTitles && defaultModel) { + const selectedChatModel = selectSelectedChatModel(state); + + if (!state.config.config?.disableSessionTitles && selectedChatModel) { let assistantResponse = state.session.history ?.filter((h) => h.message.role === "assistant")[0] ?.message?.content?.toString(); @@ -179,7 +180,7 @@ export const saveCurrentSession = createAsyncThunk< "chatDescriber/describe", { text: assistantResponse, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }, ); if (result.status === "success" && result.content) { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index afc80fbe4..c8b10dc37 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -3,13 +3,13 @@ import { ChatMessage } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { ToCoreProtocol } from "core/protocol"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { abortStream, addPromptCompletionPair, selectUseTools, setToolGenerated, - streamUpdate + streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { callTool } from "./callTool"; @@ -29,15 +29,16 @@ export const streamNormalInput = createAsyncThunk< ) => { // Gather state const state = getState(); - const defaultModel = selectDefaultModel(state); + const selectedChatModel = selectSelectedChatModel(state); + const toolSettings = state.ui.toolSettings; const toolGroupSettings = state.ui.toolGroupSettings; const streamAborter = state.session.streamAborter; const useTools = selectUseTools(state); - if (!defaultModel) { + if (!selectedChatModel) { throw new Error("Default model not defined"); } - const includeTools = useTools && modelSupportsTools(defaultModel); + const includeTools = useTools && modelSupportsTools(selectedChatModel); // Send request const gen = extra.ideMessenger.llmStreamChat( @@ -51,7 +52,7 @@ export const streamNormalInput = createAsyncThunk< ), } : {}, - title: defaultModel.title, + title: selectedChatModel.title, messages, legacySlashCommandData, }, @@ -81,8 +82,8 @@ export const streamNormalInput = createAsyncThunk< data: { prompt: next.value.prompt, completion: next.value.completion, - modelProvider: defaultModel.provider, - modelTitle: defaultModel.title, + modelProvider: selectedChatModel.provider, + modelTitle: selectedChatModel.title, sessionId: state.session.id, }, }); @@ -93,8 +94,8 @@ export const streamNormalInput = createAsyncThunk< // data: { // prompt: next.value.prompt, // completion: next.value.completion, - // modelProvider: defaultModel.provider, - // modelTitle: defaultModel.title, + // modelProvider: selectedChatModel.provider, + // modelTitle: selectedChatModel.title, // }, // }); // } diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 9b802ffbb..e79bcdf85 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -4,7 +4,7 @@ import { InputModifiers } from "core"; import { constructMessages } from "core/llm/constructMessages"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { submitEditorAndInitAtIndex, updateHistoryItemAtIndex, @@ -34,11 +34,10 @@ export const streamResponseThunk = createAsyncThunk< await dispatch( streamThunkWrapper(async () => { const state = getState(); - const defaultModel = selectDefaultModel(state); - const slashCommands = state.config.config.slashCommands || []; + const selectedChatModel = selectSelectedChatModel(state); const inputIndex = index ?? state.session.history.length; // Either given index or concat to end - if (!defaultModel) { + if (!selectedChatModel) { throw new Error("No chat model selected"); } diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 99554a628..3fa335d8b 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -2,7 +2,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage, ContextItem } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; -import { selectDefaultModel } from "../slices/configSlice"; +import { selectSelectedChatModel } from "../slices/configSlice"; import { addContextItemsAtIndex, setActive, @@ -27,9 +27,9 @@ export const streamResponseAfterToolCall = createAsyncThunk< streamThunkWrapper(async () => { const state = getState(); const initialHistory = state.session.history; - const defaultModel = selectDefaultModel(state); + const selectedChatModel = selectSelectedChatModel(state); - if (!defaultModel) { + if (!selectedChatModel) { throw new Error("No model selected"); } diff --git a/gui/src/redux/thunks/updateSelectedModelByRole.ts b/gui/src/redux/thunks/updateSelectedModelByRole.ts new file mode 100644 index 000000000..8ad4f3df5 --- /dev/null +++ b/gui/src/redux/thunks/updateSelectedModelByRole.ts @@ -0,0 +1,58 @@ +import { ModelRole } from "@continuedev/config-yaml"; +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ProfileDescription } from "core/config/ProfileLifecycleManager"; +import { updateConfig } from "../slices/configSlice"; +import { ThunkApiType } from "../store"; + +export const updateSelectedModelByRole = createAsyncThunk< + void, + { + role: ModelRole; + modelTitle: string; + selectedProfile: ProfileDescription | null; + }, + ThunkApiType +>( + "config/updateSelectedModel", + async ( + { role, modelTitle, selectedProfile }, + { dispatch, extra, getState }, + ) => { + if (!selectedProfile) { + return; + } + + const state = getState(); + + const { + config: { config }, + } = state; + + const model = state.config.config.modelsByRole[role]?.find( + (m) => m.title === modelTitle, + ); + + if (!model) { + console.error( + `Model with title "${modelTitle}" not found for role "${role}"`, + ); + return; + } + + dispatch( + updateConfig({ + ...config, + selectedModelByRole: { + ...config.selectedModelByRole, + [role]: model, + }, + }), + ); + + extra.ideMessenger.post("config/updateSelectedModel", { + role, + profileId: selectedProfile.id, + title: modelTitle, + }); + }, +); diff --git a/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js index 44c55402e..eee0aa7c5 100644 --- a/manual-testing-sandbox/test.js +++ b/manual-testing-sandbox/test.js @@ -9,7 +9,6 @@ class Calculator { } subtract(number) { - this.result -= number; return this; } diff --git a/manual-testing-sandbox/test.kt b/manual-testing-sandbox/test.kt index 683993e81..bb13ae9ee 100644 --- a/manual-testing-sandbox/test.kt +++ b/manual-testing-sandbox/test.kt @@ -30,3 +30,4 @@ class Test { return this } } +