diff --git a/.continue/prompts/core-unit-test.prompt b/.continue/prompts/core-unit-test.prompt index 42ecef7bb..1a08945b4 100644 --- a/.continue/prompts/core-unit-test.prompt +++ b/.continue/prompts/core-unit-test.prompt @@ -4,7 +4,7 @@ description: Generate unit tests for core utilities Write jest tests for the provided code. Use jest version ^29 (e.g. jest 29.7.0) -Use best practices. Be clear and consise. +Use best practices. Be clear and concise. Aim for 100% code coverage where reasonable. Multiple tests can be written, split up tests for best clarity and readability. Only use typescript, and if the file/code is not typescript, warn the user. @@ -15,7 +15,7 @@ Use double quotes (or backticks if needed) for strings The code being tested is used in IDE extensions, and it: - accesses code workspaces through the IDE ("workspace directories") - persists extension-related data to the the local machine of the user ("global directory"), and -- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient` +- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient` Jest testing setup includes - @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live. @@ -31,7 +31,7 @@ Jest testing setup includes Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests. -IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible. +IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible. Instead, generate actual mock files and data for operations Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 84ee4e60f..e40d9d054 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -71,7 +71,27 @@ } ] }, - // Build the React app. It gets bundled into the extension as a file resource and has a seprate build step + { + "label": "vscode-extension:package", + "dependsOn": ["vscode-extension:esbuild"], + "type": "npm", + "script": "package", + "path": "extensions/vscode", + "problemMatcher": [ + { + "pattern": [ + { + "regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + ] + } + ] + }, { "label": "vscode-extension:continue-ui:build", "type": "shell", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b69b1fd44..4f7e1634f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -128,7 +128,7 @@ nvm use 1. The new VS Code window with the extension is referred to as the _Host VS Code_ 2. The window you started debugging from is referred to as the _Main VS Code_ -3. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX". +3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX". ##### Debugging diff --git a/binary/build.js b/binary/build.js index 609a4b68c..adc461396 100644 --- a/binary/build.js +++ b/binary/build.js @@ -285,7 +285,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { // Informs the `continue-binary` of where to look for node_sqlite3.node // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found - // fs.writeFileSync(`${targetDir}/package.json`, ""); + fs.writeFileSync(`${targetDir}/package.json`, ""); } // Cleanup - this is needed when running locally diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index d51fe1f1f..82b169677 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -240,6 +240,14 @@ export const Solidity = { endOfLine: [";"], }; +// Lua +export const Lua = { + name: "Lua", + topLevelKeywords: ["function"], + singleLineComment: "--", + endOfLine: [], +}; + // YAML export const YAML: AutocompleteLanguageInfo = { name: "YAML", @@ -367,6 +375,8 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { yaml: YAML, yml: YAML, md: Markdown, + lua: Lua, + luau: Lua, }; export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo { diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 7f5366df0..2c8b12a31 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -399,7 +399,8 @@ export function getTemplateForModel(model: string): AutocompleteTemplate { lowerCaseModel.includes("gpt") || lowerCaseModel.includes("davinci-002") || lowerCaseModel.includes("claude") || - lowerCaseModel.includes("granite3") + lowerCaseModel.includes("granite3") || + lowerCaseModel.includes("granite-3") ) { return holeFillerTemplate; } diff --git a/core/config/load.ts b/core/config/load.ts index 78efccd79..1d29124d6 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -18,6 +18,7 @@ import { EmbeddingsProviderDescription, IContextProvider, IDE, + IdeInfo, IdeSettings, IdeType, ILLM, @@ -62,7 +63,11 @@ import { getEsbuildBinaryPath, } from "../util/paths"; -import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; +import { + ConfigResult, + ConfigValidationError, + ModelRole, +} from "@continuedev/config-yaml"; import { useHub } from "../control-plane/env"; import { localPathToUri } from "../util/pathToUri"; import { @@ -72,7 +77,8 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -import { modifyContinueConfigWithSharedConfig } from "./sharedConfig"; +import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; +import { getModelByRole } from "./util"; import { validateConfig } from "./validation.js"; export function resolveSerializedConfig( @@ -238,6 +244,7 @@ async function intermediateToFinalConfig( config: Config, ide: IDE, ideSettings: IdeSettings, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -326,7 +333,7 @@ async function intermediateToFinalConfig( ...model.requestOptions, ...config.requestOptions, }; - model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified + model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified } if (allowFreeTrial) { @@ -436,23 +443,28 @@ async function intermediateToFinalConfig( } // Embeddings Provider - const embeddingsProviderDescription = config.embeddingsProvider as - | EmbeddingsProviderDescription - | undefined; - if (embeddingsProviderDescription?.provider) { - const { provider, ...options } = embeddingsProviderDescription; + function getEmbeddingsILLM( + embedConfig: EmbeddingsProviderDescription | ILLM | undefined, + ): ILLM | null { + if (!embedConfig) { + return null; + } + if ("providerName" in embedConfig) { + return embedConfig; + } + const { provider, ...options } = embedConfig; const embeddingsProviderClass = allEmbeddingsProviders[provider]; if (embeddingsProviderClass) { if ( embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" ) { - config.embeddingsProvider = new embeddingsProviderClass(); + return new embeddingsProviderClass(); } else { const llmOptions: LLMOptions = { model: options.model ?? "UNSPECIFIED", ...options, }; - config.embeddingsProvider = new embeddingsProviderClass( + return new embeddingsProviderClass( llmOptions, (url: string | URL, init: any) => fetchwithRequestOptions(url, init, { @@ -461,42 +473,74 @@ async function intermediateToFinalConfig( }), ); } + } else { + errors.push({ + fatal: false, + message: `Embeddings provider ${provider} not found. Using default`, + }); } + return null; } - - if (!config.embeddingsProvider) { - config.embeddingsProvider = new TransformersJsEmbeddingsProvider(); - } + const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider); // Reranker - if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) { + function getRerankingILLM( + rerankingConfig: ILLM | RerankerDescription | undefined, + ): ILLM | null { + if (!rerankingConfig) { + return null; + } + if ("providerName" in rerankingConfig) { + return rerankingConfig; + } const { name, params } = config.reranker as RerankerDescription; const rerankerClass = AllRerankers[name]; if (name === "llm") { const llm = models.find((model) => model.title === params?.modelTitle); if (!llm) { - console.warn(`Unknown model ${params?.modelTitle}`); + errors.push({ + fatal: false, + message: `Unknown reranking model ${params?.modelTitle}`, + }); + return null; } else { - config.reranker = new LLMReranker(llm); + return new LLMReranker(llm); } } else if (rerankerClass) { const llmOptions: LLMOptions = { model: "rerank-2", ...params, }; - config.reranker = new rerankerClass(llmOptions); + return new rerankerClass(llmOptions); } + return null; } + const newReranker = getRerankingILLM(config.reranker); - let continueConfig: ContinueConfig = { + const continueConfig: ContinueConfig = { ...config, contextProviders, models, - embeddingsProvider: config.embeddingsProvider as any, - tabAutocompleteModels, - reranker: config.reranker as any, tools: allTools, + modelsByRole: { + chat: models, + edit: models, + apply: models, + summarize: models, + autocomplete: [...tabAutocompleteModels], + embed: newEmbedder ? [newEmbedder] : [], + rerank: newReranker ? [newReranker] : [], + }, + selectedModelByRole: { + chat: null, // Not implemented (uses GUI defaultModel) + edit: null, + apply: null, + embed: newEmbedder ?? null, + autocomplete: null, + rerank: newReranker ?? null, + summarize: null, // Not implemented + }, }; // Apply MCP if specified @@ -538,49 +582,112 @@ 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( + (m) => m.title === inlineEditModel, + ); + if (match) { + continueConfig.selectedModelByRole.edit = match; + continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set + } else { + errors.push({ + fatal: false, + message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`, + }); + } + } + + const applyBlockModel = getModelByRole( + continueConfig, + "applyCodeBlock", + )?.title; + if (applyBlockModel) { + const match = continueConfig.models.find( + (m) => m.title === applyBlockModel, + ); + if (match) { + continueConfig.selectedModelByRole.apply = match; + continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set + } else { + errors.push({ + fatal: false, + message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`, + }); + } + } + + // Add transformers JS to the embed models list if not already added + if ( + ideInfo.ideType === "vscode" && + !continueConfig.modelsByRole.embed.find( + (m) => m.providerName === "transformers.js", + ) + ) { + continueConfig.modelsByRole.embed.push( + new TransformersJsEmbeddingsProvider(), + ); + } + return { config: continueConfig, errors }; } +function llmToSerializedModelDescription(llm: ILLM): ModelDescription { + return { + provider: llm.providerName, + model: llm.model, + title: llm.title ?? llm.model, + apiKey: llm.apiKey, + apiBase: llm.apiBase, + contextLength: llm.contextLength, + template: llm.template, + completionOptions: llm.completionOptions, + systemMessage: llm.systemMessage, + requestOptions: llm.requestOptions, + promptTemplates: llm.promptTemplates as any, + capabilities: llm.capabilities, + roles: llm.roles, + }; +} + async function finalToBrowserConfig( final: ContinueConfig, ide: IDE, ): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, - models: final.models.map((m) => ({ - provider: m.providerName, - model: m.model, - title: m.title ?? m.model, - apiKey: m.apiKey, - apiBase: m.apiBase, - contextLength: m.contextLength, - template: m.template, - completionOptions: m.completionOptions, - systemMessage: m.systemMessage, - requestOptions: m.requestOptions, - promptTemplates: m.promptTemplates as any, - capabilities: m.capabilities, - roles: m.roles, - })), + models: final.models.map(llmToSerializedModelDescription), systemMessage: final.systemMessage, completionOptions: final.completionOptions, slashCommands: final.slashCommands?.map((s) => ({ name: s.name, description: s.description, - params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands? + params: s.params, // TODO: is this why params aren't referenced properly by slash commands? })), contextProviders: final.contextProviders?.map((c) => c.description), disableIndexing: final.disableIndexing, disableSessionTitles: final.disableSessionTitles, userToken: final.userToken, - embeddingsProvider: final.embeddingsProvider?.embeddingId, ui: final.ui, experimental: final.experimental, docs: final.docs, tools: final.tools, tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), - // data not included here + modelsByRole: Object.fromEntries( + Object.entries(final.modelsByRole).map(([k, v]) => [ + k, + v.map(llmToSerializedModelDescription), + ]), + ) as Record, // TODO better types here + selectedModelByRole: Object.fromEntries( + Object.entries(final.selectedModelByRole).map(([k, v]) => [ + k, + v ? llmToSerializedModelDescription(v) : null, + ]), + ) as Record, // TODO better types here + // data not included here because client doesn't need }; } @@ -768,7 +875,7 @@ async function loadContinueConfigFromJson( ide: IDE, workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, - ideType: IdeType, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -782,7 +889,7 @@ async function loadContinueConfigFromJson( } = loadSerializedConfig( workspaceConfigs, ideSettings, - ideType, + ideInfo.ideType, overrideConfigJson, ide, ); @@ -799,16 +906,16 @@ async function loadContinueConfigFromJson( // Apply shared config // TODO: override several of these values with user/org shared config const sharedConfig = new GlobalContext().getSharedConfig(); - const withShared = modifyContinueConfigWithSharedConfig( - serialized, - sharedConfig, - ); + const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig); // Convert serialized to intermediate config let intermediate = await serializedToIntermediateConfig(withShared, ide); // Apply config.ts to modify intermediate config - const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType); + const configJsContents = await buildConfigTsandReadConfigJs( + ide, + ideInfo.ideType, + ); if (configJsContents) { try { // Try config.ts first @@ -868,6 +975,7 @@ async function loadContinueConfigFromJson( intermediate, ide, ideSettings, + ideInfo, uniqueId, writeLog, workOsAccessToken, diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 3196faff4..9ccf5c812 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -38,6 +38,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, undefined, + this.description.id, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index a23432af2..5ef71a246 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -69,6 +69,7 @@ export default class PlatformProfileLoader implements IProfileLoader { ownerSlug: this.ownerSlug, packageSlug: this.packageSlug, }, + this.description.id, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index af8c59c97..0ec9b4137 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -4,6 +4,7 @@ import { AssistantUnrolled, ConfigResult, ConfigValidationError, + ModelRole, } from "@continuedev/config-yaml"; import { ContinueConfig, @@ -24,6 +25,7 @@ import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -33,7 +35,7 @@ export default async function doLoadConfig( overrideConfigJson: SerializedContinueConfig | undefined, overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, - workspaceId?: string, + profileId: string, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -59,7 +61,7 @@ export default async function doLoadConfig( ide, workspaceConfigs.map((c) => JSON.stringify(c)), ideSettings, - ideInfo.ideType, + ideInfo, uniqueId, writeLog, workOsAccessToken, @@ -75,7 +77,7 @@ export default async function doLoadConfig( ide, workspaceConfigs, ideSettings, - ideInfo.ideType, + ideInfo, uniqueId, writeLog, workOsAccessToken, @@ -86,6 +88,11 @@ export default async function doLoadConfig( configLoadInterrupted = result.configLoadInterrupted; } + // Rectify model selections for each role + if (newConfig) { + newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); + } + if (configLoadInterrupted || !newConfig) { return { errors, config: newConfig, configLoadInterrupted: true }; } @@ -117,7 +124,7 @@ export default async function doLoadConfig( controlPlaneProxyUrl += "/"; } const controlPlaneProxyInfo = { - workspaceId, + profileId, controlPlaneProxyUrl, workOsAccessToken, }; @@ -147,21 +154,26 @@ async function injectControlPlaneProxyInfo( config: ContinueConfig, info: ControlPlaneProxyInfo, ): Promise { - [...config.models, ...(config.tabAutocompleteModels ?? [])].forEach( - async (model) => { + Object.keys(config.modelsByRole).forEach((key) => { + config.modelsByRole[key as ModelRole].forEach((model) => { if (model.providerName === "continue-proxy") { (model as ContinueProxy).controlPlaneProxyInfo = info; } - }, - ); + }); + }); - if (config.embeddingsProvider?.providerName === "continue-proxy") { - (config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info; - } + Object.keys(config.selectedModelByRole).forEach((key) => { + const model = config.selectedModelByRole[key as ModelRole]; + if (model?.providerName === "continue-proxy") { + (model as ContinueProxy).controlPlaneProxyInfo = info; + } + }); - if (config.reranker?.providerName === "continue-proxy") { - (config.reranker as ContinueProxy).controlPlaneProxyInfo = info; - } + config.models.forEach((model) => { + if (model.providerName === "continue-proxy") { + (model as ContinueProxy).controlPlaneProxyInfo = info; + } + }); return config; } diff --git a/core/config/selectedModels.ts b/core/config/selectedModels.ts new file mode 100644 index 000000000..dd537665d --- /dev/null +++ b/core/config/selectedModels.ts @@ -0,0 +1,67 @@ +import { ModelRole } from "@continuedev/config-yaml"; + +import { ContinueConfig, ILLM } from ".."; +import { + GlobalContext, + GlobalContextModelSelections, +} from "../util/GlobalContext"; + +export function rectifySelectedModelsFromGlobalContext( + continueConfig: ContinueConfig, + profileId: string, +): ContinueConfig { + const configCopy = { ...continueConfig }; + + const globalContext = new GlobalContext(); + const currentSelectedModels = globalContext.get("selectedModelsByProfileId"); + const currentForProfile: GlobalContextModelSelections = + currentSelectedModels?.[profileId] ?? {}; + + let fellBack = false; + + // chat and summarize not implemented yet + // default chat model is stored in GUI still + + const roles: ModelRole[] = [ + "autocomplete", + "apply", + "edit", + "embed", + "rerank", + ]; + 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, + ); + if (match) { + newModel = match; + } + } + if (!newModel && continueConfig.modelsByRole[role].length > 0) { + newModel = continueConfig.modelsByRole[role][0]; + } + if (!(currentSelection === (newModel?.title ?? null))) { + fellBack = true; + } + configCopy.selectedModelByRole[role] = newModel; + } + + // In the case shared config wasn't respected, + // Rewrite the shared config + if (fellBack) { + globalContext.update("selectedModelsByProfileId", { + ...currentSelectedModels, + [profileId]: Object.fromEntries( + Object.entries(configCopy.selectedModelByRole).map(([key, value]) => [ + key, + value?.title ?? null, + ]), + ), + }); + } + + return configCopy; +} diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 9f2335243..6bec99452 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -1,13 +1,22 @@ +import { + ModelRole, + modelRolesSchema, +} from "@continuedev/config-yaml/dist/schemas/models"; import z from "zod"; + import { BrowserSerializedContinueConfig, ContinueConfig, Config, SerializedContinueConfig, } from ".."; +import { GlobalContext } from "../util/GlobalContext"; + +const selectedModelsSchema = z.record(modelRolesSchema, z.string().nullable()); export const sharedConfigSchema = z .object({ + // boolean fields in config.json allowAnonymousTelemetry: z.boolean(), disableIndexing: z.boolean(), disableSessionTitles: z.boolean(), @@ -65,7 +74,19 @@ export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema { return salvagedConfig; } -export function modifyContinueConfigWithSharedConfig< +// Apply shared config to all forms of config +// - SerializedContinueConfig (config.json) +// - Config ("intermediate") - passed to config.ts +// - ContinueConfig +// - BrowserSerializedContinueConfig (final converted to be passed to GUI) + +// This modify function is split into two steps +// - rectifySharedModelsFromSharedConfig - includes boolean flags like allowAnonymousTelemetry which +// must be added BEFORE config.ts and remote server config apply for JSON +// for security reasons +// - setSharedModelsFromSharedConfig - exists because of selectedModelsByRole +// Which don't exist on SerializedContinueConfig/Config types, so must be added after the fact +export function modifyAnyConfigWithSharedConfig< T extends | ContinueConfig | BrowserSerializedContinueConfig @@ -92,6 +113,7 @@ export function modifyContinueConfigWithSharedConfig< configCopy.ui = { ...configCopy.ui, }; + if (sharedConfig.codeBlockToolbarPosition !== undefined) { configCopy.ui.codeBlockToolbarPosition = sharedConfig.codeBlockToolbarPosition; @@ -135,28 +157,3 @@ export function modifyContinueConfigWithSharedConfig< return configCopy; } - -// continueConfig.tabAutocompleteOptions = { -// ...continueConfig.tabAutocompleteOptions, -// useCache: sharedConfig.useAutocompleteCache, -// disableInFiles: sharedConfig.disableAutocompleteInFiles, -// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions, -// }; -// continueConfig.ui = { -// ...continueConfig.ui, -// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition, -// fontSize: sharedConfig.fontSize, -// codeWrap: sharedConfig.codeWrap, -// displayRawMarkdown: sharedConfig.displayRawMarkdown, -// showChatScrollbar: sharedConfig.showChatScrollbar, -// }; -// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; -// continueConfig.disableIndexing = sharedConfig.disableIndexing; -// continueConfig.disableIndexing = sharedConfig.disableIndexing; -// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles; -// continueConfig.experimental = { -// ...continueConfig.experimental, -// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling, -// readResponseTTS: sharedConfig.readResponseTTS, -// promptPath: sharedConfig.promptPath, -// }; diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index a989d2631..fdf73606f 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -15,10 +15,11 @@ export function convertConfigJsonToConfigYaml( name: model.title, // defaultCompletionOptions: model.completionOptions, provider: model.provider, - roles: ["chat"], + roles: ["chat", "edit", "apply", "summarize"], }), ), - // ... tabAutocompleteModels + // TODO + // tabAutocompleteModels // embeddingsModels // rerankModels ], diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 4c94802cd..25790f393 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -14,8 +14,8 @@ import { ContinueConfig, IContextProvider, IDE, + IdeInfo, IdeSettings, - IdeType, SlashCommand, } from "../.."; import { slashFromCustomCommand } from "../../commands"; @@ -37,7 +37,7 @@ import { GlobalContext } from "../../util/GlobalContext"; import { getConfigYamlPath } from "../../util/paths"; import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; -import { modifyContinueConfigWithSharedConfig } from "../sharedConfig"; +import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { llmsFromModelConfig } from "./models"; @@ -98,6 +98,7 @@ async function configYamlToContinueConfig( config: AssistantUnrolled, ide: IDE, ideSettings: IdeSettings, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -111,10 +112,8 @@ async function configYamlToContinueConfig( ...(config.prompts?.map(slashFromCustomCommand) ?? []), ], models: [], - tabAutocompleteModels: [], tools: allTools, systemMessage: config.rules?.join("\n"), - embeddingsProvider: new TransformersJsEmbeddingsProvider(), experimental: { modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ transport: { @@ -132,60 +131,125 @@ async function configYamlToContinueConfig( faviconUrl: doc.faviconUrl, })), contextProviders: [], + modelsByRole: { + chat: [], + edit: [], + apply: [], + embed: [], + autocomplete: [], + rerank: [], + summarize: [], + }, + selectedModelByRole: { + chat: null, // not currently used - defaultModel on GUI is used + edit: null, // not currently used + apply: null, + embed: null, + autocomplete: null, + rerank: null, + summarize: null, + }, data: config.data, }; // Models const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { - model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified + model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified + const llms = await llmsFromModelConfig( + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + continueConfig.systemMessage, + ); + + // if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { - // Main model array - const llms = await llmsFromModelConfig( - model, - ide, - uniqueId, - ideSettings, - writeLog, - platformConfigMetadata, - continueConfig.systemMessage, - ); continueConfig.models.push(...llms); } + if (model.roles?.includes("chat")) { + continueConfig.modelsByRole.chat.push(...llms); + } + + if (model.roles?.includes("summarize")) { + continueConfig.modelsByRole.summarize.push(...llms); + } + + if (model.roles?.includes("apply")) { + continueConfig.modelsByRole.apply.push(...llms); + } + + if (model.roles?.includes("edit")) { + continueConfig.modelsByRole.edit.push(...llms); + } + if (model.roles?.includes("autocomplete")) { - // Autocomplete models array - const llms = await llmsFromModelConfig( - model, - ide, - uniqueId, - ideSettings, - writeLog, - platformConfigMetadata, - continueConfig.systemMessage, - ); - continueConfig.tabAutocompleteModels?.push(...llms); + continueConfig.modelsByRole.autocomplete.push(...llms); } - if ( - model.roles?.includes("apply") && - !continueConfig.experimental?.modelRoles?.applyCodeBlock - ) { - continueConfig.experimental ??= {}; - continueConfig.experimental!.modelRoles ??= {}; - continueConfig.experimental!.modelRoles!.applyCodeBlock = model.name; + if (model.roles?.includes("embed")) { + const { provider, ...options } = model; + const embeddingsProviderClass = allEmbeddingsProviders[provider]; + if (embeddingsProviderClass) { + if ( + embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" + ) { + continueConfig.modelsByRole.embed.push(new embeddingsProviderClass()); + } else { + continueConfig.modelsByRole.embed.push( + new embeddingsProviderClass( + options, + (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), + ), + ); + } + } else { + errors.push({ + fatal: false, + message: `Unsupported embeddings model provider found: ${provider}`, + }); + } } - if ( - model.roles?.includes("edit") && - !continueConfig.experimental?.modelRoles?.inlineEdit - ) { - continueConfig.experimental ??= {}; - continueConfig.experimental!.modelRoles ??= {}; - continueConfig.experimental!.modelRoles!.inlineEdit = model.name; + if (model.roles?.includes("rerank")) { + const { provider, ...options } = model; + const rerankerClass = AllRerankers[provider]; + if (rerankerClass) { + continueConfig.modelsByRole.rerank.push( + new rerankerClass(options, (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), + ), + ); + } else { + errors.push({ + fatal: false, + message: `Unsupported reranking model provider found: ${provider}`, + }); + } } } + // Add transformers js to the embed models in vs code if not already added + if ( + ideInfo.ideType === "vscode" && + !continueConfig.modelsByRole.embed.find( + (m) => m.providerName === "transformers.js", + ) + ) { + continueConfig.modelsByRole.embed.push( + new TransformersJsEmbeddingsProvider(), + ); + } + if (allowFreeTrial) { // Obtain auth token (iff free trial being used) const freeTrialModels = continueConfig.models.filter( @@ -204,8 +268,6 @@ async function configYamlToContinueConfig( ); } - // TODO: Split into model roles. - // Context providers const codebaseContextParams: IContextProvider[] = (config.context || []).find((cp) => cp.provider === "codebase")?.params || @@ -244,51 +306,6 @@ async function configYamlToContinueConfig( continueConfig.contextProviders.push(new DocsContextProvider({})); } - // Embeddings Provider - // IMPORTANT this currently will grab the first model found with an embed role - const embedConfig = config.models?.find((model) => - model.roles?.includes("embed"), - ); - if (embedConfig) { - const { provider, ...options } = embedConfig; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { - continueConfig.embeddingsProvider = new embeddingsProviderClass(); - } else { - continueConfig.embeddingsProvider = new embeddingsProviderClass( - options, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ); - } - } - } - - // Reranker - // IMPORTANT this currently will grab the first model found with a rerank role - const rerankConfig = config.models?.find((model) => - model.roles?.includes("rerank"), - ); - if (rerankConfig) { - const { provider, ...options } = rerankConfig; - const rerankerClass = AllRerankers[provider]; - - if (rerankerClass) { - continueConfig.reranker = new rerankerClass( - options, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ); - } - } - // Apply MCP if specified const mcpManager = MCPManagerSingleton.getInstance(); await Promise.all( @@ -342,7 +359,7 @@ export async function loadContinueConfigFromYaml( ide: IDE, workspaceConfigs: string[], ideSettings: IdeSettings, - ideType: IdeType, + ideInfo: IdeInfo, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, @@ -352,7 +369,7 @@ export async function loadContinueConfigFromYaml( ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideType), "utf-8") + ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") : ""; const configYamlResult = await loadConfigYaml( @@ -375,6 +392,7 @@ export async function loadContinueConfigFromYaml( configYamlResult.config, ide, ideSettings, + ideInfo, uniqueId, writeLog, workOsAccessToken, @@ -393,7 +411,7 @@ export async function loadContinueConfigFromYaml( // Apply shared config // TODO: override several of these values with user/org shared config const sharedConfig = new GlobalContext().getSharedConfig(); - const withShared = modifyContinueConfigWithSharedConfig( + const withShared = modifyAnyConfigWithSharedConfig( continueConfig, sharedConfig, ); diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index e877c10e7..345d21e37 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -42,10 +42,10 @@ async function getContextProviderExtras( fullInput, ide, config, - embeddingsProvider: config.embeddingsProvider, + embeddingsProvider: config.selectedModelByRole.embed, fetch: fetch, llm: config.models[0], - reranker: config.reranker, + reranker: config.selectedModelByRole.rerank, selectedCode: [], }; } diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 0ba94964c..e341c681c 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -7,6 +7,8 @@ import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCod import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; +const DEFAULT_CHUNK_SIZE = 384; + export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; @@ -16,13 +18,13 @@ export interface RetrievalPipelineOptions { nFinal: number; tags: BranchAndDir[]; filterDirectory?: string; - includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model } export interface RetrievalPipelineRunArguments { query: string; tags: BranchAndDir[]; filterDirectory?: string; + includeEmbeddings: boolean; } export interface IRetrievalPipeline { @@ -35,7 +37,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { constructor(protected readonly options: RetrievalPipelineOptions) { this.lanceDbIndex = new LanceDbIndex( - options.config.embeddingsProvider, + options.config.selectedModelByRole.embed, (uri) => options.ide.readFile(uri), ); } @@ -109,7 +111,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { filepath, contents, maxChunkSize: - this.options.config.embeddingsProvider.maxEmbeddingChunkSize, + this.options.config.selectedModelByRole.embed?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE, digest: filepath, }); diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index af72c0639..889005414 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -9,7 +9,7 @@ import BaseRetrievalPipeline, { export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { async run(args: RetrievalPipelineRunArguments): Promise { - const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; + const { input, nFinal, filterDirectory, config } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, // and the remaining 1/2 to embeddings @@ -21,7 +21,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { const ftsChunks = await this.retrieveFts(args, ftsNFinal); - const embeddingsChunks = includeEmbeddings + const embeddingsChunks = !!config.selectedModelByRole.embed ? await this.retrieveEmbeddings(input, embeddingsNFinal) : []; diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 7c7e69860..67f4bcd45 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -12,13 +12,12 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { private async _retrieveInitial( args: RetrievalPipelineRunArguments, ): Promise { - const { input, nRetrieve, filterDirectory, includeEmbeddings } = - this.options; + const { input, nRetrieve, filterDirectory, config } = this.options; let retrievalResults: Chunk[] = []; const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = includeEmbeddings + const embeddingsChunks = !!config.selectedModelByRole.embed ? await this.retrieveEmbeddings(input, nRetrieve) : []; const recentlyEditedFilesChunks = @@ -53,17 +52,18 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { } private async _rerank(input: string, chunks: Chunk[]): Promise { - if (!this.options.config.reranker) { - throw new Error("No reranker provided"); + if (!this.options.config.selectedModelByRole.rerank) { + throw new Error("No reranker set up"); } // remove empty chunks -- some APIs fail on that chunks = chunks.filter((chunk) => chunk.content); - let scores: number[] = await this.options.config.reranker.rerank( - input, - chunks, - ); + let scores: number[] = + await this.options.config.selectedModelByRole.rerank.rerank( + input, + chunks, + ); // Filter out low-scoring results let results = chunks; diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 39223321b..5637019ad 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -2,7 +2,6 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; import generateRepoMap from "../../util/generateRepoMap"; import { renderChatMessage } from "../../util/messageContent"; -import { getUriPathBasename } from "../../util/uri"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -16,7 +15,7 @@ function isSupportedModel( config: ContinueConfig, modelTitle?: string, ): boolean { - if (config.experimental?.modelRoles?.applyCodeBlock) { + if (config.experimental?.modelRoles?.repoMapFileSelection) { return true; } diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 0f0a238eb..f3d57f053 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,5 +1,4 @@ import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; -import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { getUriDescription } from "../../util/uri"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; @@ -14,26 +13,16 @@ export async function retrieveContextItemsFromEmbeddings( options: any | undefined, filterDirectory: string | undefined, ): Promise { - if (!extras.embeddingsProvider) { - return []; - } - - // transformers.js not supported in JetBrains IDEs right now - - const isJetBrainsAndTransformersJs = - extras.embeddingsProvider.providerName === - TransformersJsEmbeddingsProvider.providerName && - (await extras.ide.getIdeInfo()).ideType === "jetbrains"; - - if (isJetBrainsAndTransformersJs) { - void extras.ide.showToast( - "warning", - "Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " + - "You can use Ollama to set up local embeddings, use our 'free-trial', " + - "or configure your own. See here to learn more: " + - "https://docs.continue.dev/customize/model-types/embeddings", - ); - } + // Currently you can use codebase without an embeddings provider and it will just skip the embeddings inputs + // if (!extras.embeddingsProvider) { + // void extras.ide.showToast( + // "warning", + // "Set up an embeddings model to use this feature. Visit the docs to learn more: " + + // "https://docs.continue.dev/customize/model-types/embeddings", + // ); + // return []; + // } + const includeEmbeddings = !!extras.config.selectedModelByRole.embed; // Get tags to retrieve for const workspaceDirs = await extras.ide.getWorkspaceDirs(); @@ -78,7 +67,6 @@ export async function retrieveContextItemsFromEmbeddings( input: extras.fullInput, llm: extras.llm, config: extras.config, - includeEmbeddings: !isJetBrainsAndTransformersJs, }; const pipeline = new pipelineType(pipelineOptions); @@ -86,16 +74,17 @@ export async function retrieveContextItemsFromEmbeddings( tags, filterDirectory, query: extras.fullInput, + includeEmbeddings, }); if (results.length === 0) { if (extras.config.disableIndexing) { - void extras.ide.showToast("warning", "No embeddings results found."); + void extras.ide.showToast("warning", "No results found."); return []; } else { void extras.ide.showToast( "warning", - "No embeddings results found. If you think this is an error, re-index your codebase.", + "No results found. If you think this is an error, re-index your codebase.", ); // TODO - add "re-index" option to warning message which clears and reindexes codebase } diff --git a/core/core.ts b/core/core.ts index 426d5bf9c..dbadb82c0 100644 --- a/core/core.ts +++ b/core/core.ts @@ -14,6 +14,8 @@ import { setupQuickstartConfig, } from "./config/onboarding"; import { addContextProvider, addModel, deleteModel } from "./config/util"; +import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; +import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; @@ -51,8 +53,6 @@ import { type IndexingProgressUpdate, } from "."; -import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; -import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -199,12 +199,10 @@ export class Core { const getLlm = async () => { const { config } = await this.configHandler.loadConfig(); - const selected = this.globalContext.get("selectedTabAutocompleteModel"); - return ( - config?.tabAutocompleteModels?.find( - (model) => model.title === selected, - ) ?? config?.tabAutocompleteModels?.[0] - ); + if (!config) { + return undefined; + } + return config.selectedModelByRole.autocomplete ?? undefined; }; this.completionProvider = new CompletionProvider( this.configHandler, @@ -238,11 +236,6 @@ export class Core { } }); - on("update/selectTabAutocompleteModel", async (msg) => { - this.globalContext.update("selectedTabAutocompleteModel", msg.data); - void this.configHandler.reloadConfig(); - }); - // Special on("abort", (msg) => { this.abortedMessageIds.add(msg.messageId); @@ -317,8 +310,19 @@ export class Core { }); on("config/updateSharedConfig", async (msg) => { - this.globalContext.updateSharedConfig(msg.data); + const newSharedConfig = this.globalContext.updateSharedConfig(msg.data); await this.configHandler.reloadConfig(); + return newSharedConfig; + }); + + on("config/updateSelectedModel", async (msg) => { + const newSelectedModels = this.globalContext.updateSelectedModel( + msg.data.profileId, + msg.data.role, + msg.data.title, + ); + await this.configHandler.reloadConfig(); + return newSelectedModels; }); on("controlPlane/openUrl", async (msg) => { @@ -398,11 +402,11 @@ export class Core { const items = await provider.getContextItems(query, { config, llm, - embeddingsProvider: config.embeddingsProvider, + embeddingsProvider: config.selectedModelByRole.embed, fullInput, ide, selectedCode, - reranker: config.reranker, + reranker: config.selectedModelByRole.rerank, fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), }); @@ -423,26 +427,25 @@ export class Core { let knownError = false; if (e instanceof Error) { - // A specific error where we're forcing the presence of embeddings provider on the config - // But Jetbrains doesn't support transformers JS - // So if a context provider needs it it will throw this error when the file isn't found - if (e.message.includes("all-MiniLM-L6-v2")) { - knownError = true; - const toastOption = "See Docs"; - void this.ide - .showToast( - "error", - `Set up an embeddings model to use @${name}`, - toastOption, - ) - .then((userSelection) => { - if (userSelection === toastOption) { - void this.ide.openUrl( - "https://docs.continue.dev/customize/model-types/embeddings", - ); - } - }); - } + // After removing transformers JS embeddings provider from jetbrains + // Should no longer see this error + // if (e.message.toLowerCase().includes("embeddings provider")) { + // knownError = true; + // const toastOption = "See Docs"; + // void this.ide + // .showToast( + // "error", + // `Set up an embeddings model to use @${name}`, + // toastOption, + // ) + // .then((userSelection) => { + // if (userSelection === toastOption) { + // void this.ide.openUrl( + // "https://docs.continue.dev/customize/model-types/embeddings", + // ); + // } + // }); + // } } if (!knownError) { void this.ide.showToast( diff --git a/core/index.d.ts b/core/index.d.ts index 15482d95c..d2fa5562b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -60,7 +60,7 @@ export interface IndexingStatus { progress: number; description: string; status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending"; - embeddingsProviderId: string; + embeddingsProviderId?: string; isReindexing?: boolean; debugInfo?: string; title: string; @@ -179,8 +179,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise; export interface ContextProviderExtras { config: ContinueConfig; fullInput: string; - embeddingsProvider: ILLM; - reranker: ILLM | undefined; + embeddingsProvider: ILLM | null; + reranker: ILLM | null; llm: ILLM; ide: IDE; selectedCode: RangeInFile[]; @@ -1028,9 +1028,9 @@ export interface ContextMenuConfig { } export interface ExperimentalModelRoles { + repoMapFileSelection?: string; inlineEdit?: string; applyCodeBlock?: string; - repoMapFileSelection?: string; } export type EditStatus = @@ -1215,15 +1215,14 @@ export interface ContinueConfig { disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; - embeddingsProvider: ILLM; - tabAutocompleteModels?: ILLM[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; - reranker?: ILLM; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + modelsByRole: Record; + selectedModelByRole: Record; data?: DataDestination[]; } @@ -1238,15 +1237,15 @@ export interface BrowserSerializedContinueConfig { disableIndexing?: boolean; disableSessionTitles?: boolean; userToken?: string; - embeddingsProvider?: string; ui?: ContinueUIConfig; - reranker?: RerankerDescription; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; + modelsByRole: Record; + selectedModelByRole: Record; } // DOCS SUGGESTIONS AND PACKAGE INFO diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 677cc4305..6f5a5e946 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -5,8 +5,8 @@ import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; - import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; @@ -80,14 +80,19 @@ export class CodebaseIndexer { return []; } + const embeddingsModel = config.selectedModelByRole.embed; + if (!embeddingsModel) { + return []; + } + const indexes = [ new ChunkCodebaseIndex( this.ide.readFile.bind(this.ide), this.continueServerClient, - config.embeddingsProvider.maxEmbeddingChunkSize, + embeddingsModel.maxEmbeddingChunkSize, ), // Chunking must come first new LanceDbIndex( - config.embeddingsProvider, + embeddingsModel, this.ide.readFile.bind(this.ide), this.continueServerClient, ), diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index 08c8f9982..d8a7c9852 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -3,15 +3,15 @@ import lance from "vectordb"; import { testConfigHandler, testIde } from "../test/fixtures"; import { getLanceDbPath } from "../util/paths"; + +import { LanceDbIndex } from "./LanceDbIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { mockPathAndCacheKey, mockTag, testContinueServerClient, updateIndexAndAwaitGenerator, } from "./test/indexing"; - -import { LanceDbIndex } from "./LanceDbIndex"; -import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { IndexResultType } from "./types"; jest.useFakeTimers(); @@ -30,9 +30,12 @@ describe.skip("ChunkCodebaseIndex", () => { if (!mockConfig) { throw new Error("Failed to load config"); } + if (!mockConfig.selectedModelByRole.embed) { + throw new Error("No embeddings model selected"); + } index = new LanceDbIndex( - mockConfig.embeddingsProvider, + mockConfig.selectedModelByRole.embed, testIde.readFile.bind(testIde), testContinueServerClient, ); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index d11feb1d1..077b2ace0 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -40,11 +40,11 @@ type ChunkMap = Map; export class LanceDbIndex implements CodebaseIndex { relativeExpectedTime: number = 13; get artifactId(): string { - return `vectordb::${this.embeddingsProvider.embeddingId}`; + return `vectordb::${this.embeddingsProvider?.embeddingId}`; } constructor( - private readonly embeddingsProvider: ILLM, + private readonly embeddingsProvider: ILLM | null, private readonly readFile: (filepath: string) => Promise, private readonly continueServerClient?: IContinueServerClient, ) {} @@ -142,6 +142,9 @@ export class LanceDbIndex implements CodebaseIndex { item: PathAndCacheKey, content: string, ): Promise { + if (!this.embeddingsProvider) { + return []; + } const chunks: Chunk[] = []; const chunkParams = { @@ -163,6 +166,9 @@ export class LanceDbIndex implements CodebaseIndex { } private async getEmbeddings(chunks: Chunk[]): Promise { + if (!this.embeddingsProvider) { + return []; + } try { return await this.embeddingsProvider.embed(chunks.map((c) => c.content)); } catch (err) { @@ -436,6 +442,9 @@ export class LanceDbIndex implements CodebaseIndex { tags: BranchAndDir[], filterDirectory: string | undefined, ): Promise { + if (!this.embeddingsProvider) { + return []; + } const [vector] = await this.embeddingsProvider.embed([query]); const db = await lance.connect(getLanceDbPath()); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 4d555f557..93ae4a906 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,3 +1,4 @@ +import { ConfigResult } from "@continuedev/config-yaml"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; import lancedb, { Connection } from "vectordb"; @@ -19,6 +20,7 @@ import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbed import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { IMessenger } from "../../protocol/messenger"; import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; +import { GlobalContext } from "../../util/GlobalContext"; import { editConfigJson, getDocsSqlitePath, @@ -26,8 +28,6 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; -import { ConfigResult } from "@continuedev/config-yaml"; -import { GlobalContext } from "../../util/GlobalContext"; import { ArticleWithChunks, htmlPageToArticleWithChunks, @@ -161,16 +161,22 @@ export default class DocsService { return; } - const sharedStatus = { - type: "docs" as IndexingStatus["type"], + const sharedStatus: Omit< + IndexingStatus, + "progress" | "description" | "status" + > = { + type: "docs", id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.embeddingId, isReindexing: false, title: doc.title, debugInfo: `max depth: ${doc.maxDepth}`, icon: doc.faviconUrl, url: doc.startUrl, }; + if (this.config.selectedModelByRole.embed) { + sharedStatus.embeddingsProviderId = + this.config.selectedModelByRole.embed.embeddingId; + } const indexedStatus: IndexingStatus = metadata.find( (meta) => meta.startUrl === doc.startUrl, ) @@ -214,7 +220,9 @@ export default class DocsService { } // Handle embeddings provider change mid-indexing - if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) { + if ( + this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder + ) { this.abort(startUrl); return true; } @@ -234,14 +242,6 @@ export default class DocsService { return true; } - async isUsingUnsupportedPreIndexedEmbeddingsProvider() { - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.embeddingId === - DocsService.preIndexedDocsEmbeddingsProvider.embeddingId; - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - return isPreIndexedDocsProvider && !canUsePreindexedDocs; - } - // Determines if using preIndexed and returns proper embeddings provider async getEmbeddingsProvider(startUrl: string) { // Conditions for using a pre-indexed doc @@ -262,7 +262,7 @@ export default class DocsService { } } return { - provider: this.config.embeddingsProvider, + provider: this.config.selectedModelByRole.embed, isPreindexed: false, }; } @@ -282,9 +282,7 @@ export default class DocsService { // Skip docs indexing if not supported // No warning message here because would show on ANY config update - const unsupported = - await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); - if (unsupported) { + if (!this.config.selectedModelByRole.embed) { return; } @@ -323,18 +321,21 @@ export default class DocsService { // Returns true if startUrl has been indexed with current embeddingsProvider async hasMetadata(startUrl: string): Promise { + if (!this.config.selectedModelByRole.embed) { + return false; + } const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); return !!title; } async listMetadata() { - const embeddingsProvider = this.config.embeddingsProvider; + const embeddingsProvider = this.config.selectedModelByRole.embed; if (!embeddingsProvider) { return []; } @@ -376,6 +377,11 @@ export default class DocsService { console.warn("Attempted to indexAndAdd pre-indexed doc"); return; } + if (!provider) { + console.warn("@docs indexAndAdd: no embeddings provider found"); + return; + } + const startedWithEmbedder = provider.embeddingId; // Check if doc has been successfully indexed with the given embedder @@ -716,21 +722,18 @@ export default class DocsService { startUrl: string, nRetrieve: number, ) { - if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { - await this.ide.showToast( - "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.embeddingId} is configured as ` + - "the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE" - "Please select a different embeddings provider to use the '@docs' " + - "context provider.", - ); - - return []; - } - const { isPreindexed, provider } = await this.getEmbeddingsProvider(startUrl); + if (!provider) { + void this.ide.showToast( + "error", + "Set up an embeddings model to use the @docs context provider. See: " + + "https://docs.continue.dev/customize/model-types/embeddings", + ); + return []; + } + if (isPreindexed) { void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDocs[startUrl]!["title"], @@ -761,8 +764,10 @@ export default class DocsService { try { const { isPreindexed, provider } = await this.getEmbeddingsProvider(startUrl); - const preIndexedDoc = preIndexedDocs[startUrl]; - const isPreIndexedDoc = !!preIndexedDoc; + + if (!provider) { + throw new Error("No embeddings model set"); + } const result = await db.get( `SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, @@ -793,7 +798,7 @@ export default class DocsService { config: siteIndexingConfig, indexingStatus: this.statuses.get(startUrl), chunks: rows.map(this.lanceDBRowToChunk), - isPreIndexedDoc, + isPreIndexedDoc: isPreindexed, }; } catch (e) { console.warn("Error getting details", e); @@ -867,7 +872,7 @@ export default class DocsService { } async getFavicon(startUrl: string) { - if (!this.config.embeddingsProvider) { + if (!this.config.selectedModelByRole.embed) { console.warn( "Attempting to get favicon without embeddings provider specified", ); @@ -877,7 +882,7 @@ export default class DocsService { const result = await db.get( `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); if (!result) { @@ -941,7 +946,7 @@ export default class DocsService { type: "docs", id: doc.startUrl, embeddingsProviderId: - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed?.embeddingId, isReindexing: false, title: doc.title, debugInfo: "Config sync: not changed", @@ -1033,6 +1038,13 @@ export default class DocsService { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const { provider } = await this.getEmbeddingsProvider(startUrl); + + if (!provider) { + throw new Error( + "Could not retrieve @docs Lance Table: no embeddings provider specified", + ); + } + const tableNameFromEmbeddingsProvider = await this.getLanceTableName(provider); @@ -1089,13 +1101,19 @@ export default class DocsService { siteIndexingConfig: { title, startUrl }, favicon, }: AddParams) { + if (!this.config.selectedModelByRole.embed) { + console.warn( + `Attempting to add metadata for ${startUrl} without embeddings provider specified`, + ); + return; + } const db = await this.getOrCreateSqliteDb(); await db.run( `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`, title, startUrl, favicon, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); } @@ -1147,7 +1165,7 @@ export default class DocsService { } private async deleteMetadataFromSqlite(startUrl: string) { - if (!this.config.embeddingsProvider) { + if (!this.config.selectedModelByRole.embed) { console.warn( `Attempting to delete metadata for ${startUrl} without embeddings provider specified`, ); @@ -1158,7 +1176,7 @@ export default class DocsService { await db.run( `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, startUrl, - this.config.embeddingsProvider.embeddingId, + this.config.selectedModelByRole.embed.embeddingId, ); } diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 428bae967..aba1da6b0 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -139,24 +139,35 @@ export async function htmlPageToArticleWithChunks( return undefined; } + const title = readability.title || subpath; + const titles = Array.from(dom.window.document.querySelectorAll("h2")); - const article_components = titles.map((titleElement) => { - const title = titleElement.textContent || ""; - let body = ""; - let nextSibling = titleElement.nextElementSibling; - while (nextSibling && nextSibling.tagName !== "H2") { - body += nextSibling.textContent || ""; - nextSibling = nextSibling.nextElementSibling; - } + const article_components = + titles.length > 0 + ? titles.map((titleElement) => { + const title = titleElement.textContent || ""; + let body = ""; + let nextSibling = titleElement.nextElementSibling; - return { title, body }; - }); + while (nextSibling && nextSibling.tagName !== "H2") { + body += nextSibling.textContent || ""; + nextSibling = nextSibling.nextElementSibling; + } + + return { title, body }; + }) + : [ + { + title: title, + body: readability.textContent, + }, + ]; const article = { url, subpath, - title: readability.title, + title: title, article_components, }; return { diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 4b0c12fee..5342396fd 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -358,6 +358,11 @@ const preIndexedDocs: Record< startUrl: "https://angular.dev/", rootUrl: "https://angular.dev/", }, + "https://docs.djangoproject.com/": { + title: "Django", + startUrl: "https://docs.djangoproject.com/", + rootUrl: "https://docs.djangoproject.com/", + } }; export default preIndexedDocs; diff --git a/core/llm/llms/TransformersJsEmbeddingsProvider.ts b/core/llm/llms/TransformersJsEmbeddingsProvider.ts index 206d534d3..d17c9e0f1 100644 --- a/core/llm/llms/TransformersJsEmbeddingsProvider.ts +++ b/core/llm/llms/TransformersJsEmbeddingsProvider.ts @@ -43,6 +43,7 @@ export class TransformersJsEmbeddingsProvider extends BaseLLM { static maxGroupSize: number = 1; static model: string = "all-MiniLM-L6-v2"; static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[]; + static title: string = "Transformers.js (Built-In)"; static defaultOptions: Partial | undefined = { model: TransformersJsEmbeddingsProvider.model, diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 8d20c3212..4d52e5c43 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -445,7 +445,7 @@ class VertexAI extends BaseLLM { } const resp = await this.fetch( - new URL(this.apiBase + `/publishers/google/models/${this.model}:predict`), + new URL(`publishers/google/models/${this.model}:predict`, this.apiBase), { method: "POST", body: JSON.stringify({ diff --git a/core/promptFiles/v1/getContextProviderHelpers.ts b/core/promptFiles/v1/getContextProviderHelpers.ts index e027ffbc5..30b51bf8b 100644 --- a/core/promptFiles/v1/getContextProviderHelpers.ts +++ b/core/promptFiles/v1/getContextProviderHelpers.ts @@ -19,12 +19,12 @@ export function getContextProviderHelpers( async (helperContext: any) => { const items = await provider.getContextItems(helperContext, { config: context.config, - embeddingsProvider: context.config.embeddingsProvider, + embeddingsProvider: context.config.selectedModelByRole.embed, fetch: context.fetch, fullInput: context.input, ide: context.ide, llm: context.llm, - reranker: context.config.reranker, + reranker: context.config.selectedModelByRole.rerank, selectedCode: context.selectedCode, }); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 79bb07661..dcf25b413 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,4 +1,4 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, ModelRole } from "@continuedev/config-yaml"; import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; @@ -28,6 +28,7 @@ import type { ToolCall, } from "../"; import { DevDataLogEvent } from "../../packages/config-yaml/src/schemas/data"; +import { GlobalContextModelSelections } from "../util/GlobalContext"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -37,8 +38,6 @@ export interface ListHistoryOptions { } export type ToCoreFromIdeOrWebviewProtocol = { - "update/selectTabAutocompleteModel": [string, void]; - // Special ping: [string, string]; abort: [undefined, void]; @@ -71,7 +70,15 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/reload": [undefined, ConfigResult]; "config/listProfiles": [undefined, ProfileDescription[] | null]; "config/openProfile": [{ profileId: string | undefined }, void]; - "config/updateSharedConfig": [SharedConfigSchema, void]; + "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; + "config/updateSelectedModel": [ + { + profileId: string; + role: ModelRole; + title: string | null; + }, + GlobalContextModelSelections, + ]; "context/getContextItems": [ { name: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f0c66f465..d3a7259f2 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -24,6 +24,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/listProfiles", "config/openProfile", "config/updateSharedConfig", + "config/updateSelectedModel", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/core/util/GlobalContext.test.ts b/core/util/GlobalContext.test.ts index 0d6b9d799..b13f3b87b 100644 --- a/core/util/GlobalContext.test.ts +++ b/core/util/GlobalContext.test.ts @@ -29,12 +29,6 @@ describe("GlobalContext", () => { expect(value).toBe(true); }); - it("should update and get a string value correctly", () => { - globalContext.update("selectedTabAutocompleteModel", "test-model"); - const value = globalContext.get("selectedTabAutocompleteModel"); - expect(value).toBe("test-model"); - }); - it("should update and get an object value correctly", () => { const workspaceIdentifier = "workspace-1"; globalContext.update("lastSelectedProfileForWorkspace", { @@ -108,13 +102,9 @@ describe("GlobalContext", () => { it("should update and retrieve multiple values correctly", () => { globalContext.update("indexingPaused", true); - globalContext.update("selectedTabAutocompleteModel", "test-model"); globalContext.update("hasDismissedConfigTsNoticeJetBrains", false); expect(globalContext.get("indexingPaused")).toBe(true); - expect(globalContext.get("selectedTabAutocompleteModel")).toBe( - "test-model", - ); expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe( false, ); diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 34c3d8ddf..06cede64c 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,5 +1,8 @@ import fs from "node:fs"; +import { ModelRole } from "@continuedev/config-yaml"; + +import { SiteIndexingConfig } from ".."; import { salvageSharedConfig, sharedConfigSchema, @@ -7,17 +10,22 @@ import { } from "../config/sharedConfig"; import { getGlobalContextFilePath } from "./paths"; -import { SiteIndexingConfig } from ".."; + +export type GlobalContextModelSelections = Partial< + Record +>; export type GlobalContextType = { indexingPaused: boolean; - selectedTabAutocompleteModel: string; lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string | null; }; lastSelectedOrgIdForWorkspace: { [workspaceIdentifier: string]: string | null; }; + selectedModelsByProfileId: { + [profileId: string]: GlobalContextModelSelections; + }; /** * This is needed to handle the case where a JetBrains user has created @@ -113,4 +121,23 @@ export class GlobalContext { this.update("sharedConfig", updatedSharedConfig); return updatedSharedConfig; } + + updateSelectedModel( + profileId: string, + role: ModelRole, + title: string | null, + ): GlobalContextModelSelections { + const currentSelections = this.get("selectedModelsByProfileId") ?? {}; + const forProfile = currentSelections[profileId] ?? {}; + const newSelections = { + ...forProfile, + [role]: title, + }; + + this.update("selectedModelsByProfileId", { + ...currentSelections, + [profileId]: newSelections, + }); + return newSelections; + } } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 067445994..df1296e0c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -93,6 +93,7 @@ export const supportedLanguages: { [key: string]: LanguageName } = { htm: LanguageName.HTML, java: LanguageName.JAVA, lua: LanguageName.LUA, + luau: LanguageName.LUA, ocaml: LanguageName.OCAML, ml: LanguageName.OCAML, mli: LanguageName.OCAML, diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index cc603ce1c..22f8655a0 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -143,7 +143,7 @@ models: - apply ``` -Note that the `repoMapFileSelection` experimental model role has been deprecated. +Note that the `repoMapFileSelection` experimental model role has been deprecated and is only available in `config.json`. ### Context Providers 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 c6e5684e3..bfbe614cc 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 @@ -91,6 +91,7 @@ class MessageTypes { "config/listProfiles", "config/openProfile", "config/updateSharedConfig", + "config/updateSelectedModel", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", 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 9b8f558c2..735b23cff 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 @@ -447,7 +447,8 @@ class IdeProtocolClient( val result = responseContent["result"] as Map<*, *> val config = result["config"] as Map - val applyCodeBlockModel = getModelByRole(config, "applyCodeBlock") + val selectedModels = config["selectedModelByRole"] as Map + val applyCodeBlockModel = selectedModels["apply"] as Map if (applyCodeBlockModel != null) { continuation.resume(applyCodeBlockModel) @@ -588,19 +589,4 @@ class IdeProtocolClient( fun deleteAtIndex(index: Int) { continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid()) } - - private fun getModelByRole( - config: Any, - role: Any - ): Any? { - val experimental = (config as? Map<*, *>)?.get("experimental") as? Map<*, *> - val roleTitle = (experimental?.get("modelRoles") as? Map<*, *>)?.get(role) as? String ?: return null - - val models = (config as? Map<*, *>)?.get("models") as? List<*> - val matchingModel = models?.find { model -> - (model as? Map<*, *>)?.get("title") == roleTitle - } - - return matchingModel - } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index e121e5687..035c52db8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -192,10 +192,12 @@ class VerticalDiffBlock( private fun revertDiff() { WriteCommandAction.runWriteCommandAction(project) { - // Delete the added lines val startOffset = editor.document.getLineStartOffset(startLine) - val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1 - editor.document.deleteString(startOffset, endOffset) + // Delete the added lines + if (addedLines.isNotEmpty()) { + val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1 + editor.document.deleteString(startOffset, endOffset) + } // Add the deleted lines back if (deletedLines.isNotEmpty()) { diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 2254bb1f3..c4d392cfa 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -504,21 +504,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { async function copyScripts() { process.chdir(path.join(continueDir, "extensions", "vscode")); console.log("[info] Copying scripts from core"); - await new Promise((resolve, reject) => { - ncp( - path.join(__dirname, "../../../core/scripts"), - path.join(__dirname, "../out"), - { dereference: true }, - (error) => { - if (error) { - console.warn("[error] Error copying script files", error); - reject(error); - } else { - resolve(); - } - }, - ); - }); + fs.copyFileSync( + path.join(__dirname, "../../../core/util/start_ollama.sh"), + path.join(__dirname, "../out/start_ollama.sh"), + ); + console.log("[info] Copied script files"); } module.exports = { diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index fb174b53c..497de3875 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -21,7 +21,6 @@ import { stopStatusBarLoading, } from "./statusBar"; -import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { startLocalOllama } from "core/util/ollamaHelper"; import type { IDE } from "core"; @@ -41,7 +40,8 @@ interface VsCodeCompletionInput { } export class ContinueCompletionProvider - implements vscode.InlineCompletionItemProvider { + implements vscode.InlineCompletionItemProvider +{ private onError(e: any) { let options = ["Documentation"]; if (e.message.includes("Ollama may not be installed")) { @@ -82,13 +82,19 @@ export class ContinueCompletionProvider constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, - private readonly tabAutocompleteModel: TabAutocompleteModel, private readonly webviewProtocol: VsCodeWebviewProtocol, ) { + async function getAutocompleteModel() { + const { config } = await configHandler.loadConfig(); + if (!config) { + return; + } + return config.selectedModelByRole.autocomplete ?? undefined; + } this.completionProvider = new CompletionProvider( this.configHandler, this.ide, - this.tabAutocompleteModel.get.bind(this.tabAutocompleteModel), + getAutocompleteModel, this.onError.bind(this), getDefinitionsFromLsp, ); diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 78d202b7f..1ef13d5f7 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -4,7 +4,6 @@ import * as os from "node:os"; import { ContextMenuConfig, RangeInFileWithContents } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; -import { getModelByRole } from "core/config/util"; import { ContinueServerClient } from "core/continueServer/stubs/client"; import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; @@ -349,7 +348,7 @@ const getCommandsMap: ( ); const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + config.selectedModelByRole.edit?.title ?? defaultModelTitle; void sidebar.webviewProtocol.request("incrementFtc", undefined); @@ -873,16 +872,12 @@ const getCommandsMap: ( const config = vscode.workspace.getConfiguration(EXTENSION_NAME); const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig()).config?.tabAutocompleteModels ?? []; - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0]?.title; - } + const { config: continueConfig } = await configHandler.loadConfig(); + const autocompleteModels = + continueConfig?.modelsByRole.autocomplete ?? []; + const selected = + continueConfig?.selectedModelByRole?.autocomplete?.title ?? undefined; // Toggle between Disabled, Paused, and Enabled const pauseOnBattery = @@ -957,11 +952,14 @@ const getCommandsMap: ( } else if ( autocompleteModels.some((model) => model.title === selectedOption) ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); + if (core.configHandler.currentProfile?.profileDescription.id) { + core.invoke("config/updateSelectedModel", { + profileId: + core.configHandler.currentProfile?.profileDescription.id, + role: "autocomplete", + title: selectedOption, + }); + } } else if (selectedOption === "$(feedback) Give feedback") { vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index f8b8ca130..33deb7324 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -34,7 +34,6 @@ import { } from "../stubs/WorkOsAuthProvider"; import { Battery } from "../util/battery"; import { FileSearch } from "../util/FileSearch"; -import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeMessenger } from "./VsCodeMessenger"; @@ -47,7 +46,6 @@ export class VsCodeExtension { private configHandler: ConfigHandler; private extensionContext: vscode.ExtensionContext; private ide: VsCodeIde; - private tabAutocompleteModel: TabAutocompleteModel; private sidebar: ContinueGUIWebviewViewProvider; private windowId: string; private editDecorationManager: EditDecorationManager; @@ -143,7 +141,6 @@ export class VsCodeExtension { this.editDecorationManager, ); resolveVerticalDiffManager?.(this.verticalDiffManager); - this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); setupRemoteConfigSync( this.configHandler.reloadConfig.bind(this.configHandler), @@ -168,8 +165,6 @@ export class VsCodeExtension { } else if (newConfig) { setupStatusBar(undefined, undefined, false); - this.tabAutocompleteModel.clearLlm(); - registerAllCodeLensProviders( context, this.verticalDiffManager.fileUriToCodeLens, @@ -193,7 +188,6 @@ export class VsCodeExtension { new ContinueCompletionProvider( this.configHandler, this.ide, - this.tabAutocompleteModel, this.sidebar.webviewProtocol, ), ), @@ -347,7 +341,8 @@ export class VsCodeExtension { // Register a content provider for the readonly virtual documents const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider { + implements vscode.TextDocumentContentProvider + { // emitter and its event onDidChangeEmitter = new vscode.EventEmitter(); onDidChange = this.onDidChangeEmitter.event; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 6a6da6de0..23669305a 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -28,6 +28,7 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -177,7 +178,7 @@ export class VsCodeMessenger { return; } - let llm = getModelByRole(config, "applyCodeBlock"); + let llm: ILLM | null | undefined = config.selectedModelByRole.apply; if (!llm) { llm = config.models.find( diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index 1296a3466..074ec4d86 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -41,8 +41,8 @@ export async function getContextProvidersString( return provider.getContextItems("", { config, ide, - embeddingsProvider: config.embeddingsProvider, - reranker: config.reranker, + embeddingsProvider: config.selectedModelByRole.embed, + reranker: config.selectedModelByRole.rerank, llm: config.models[0], fullInput: "", selectedCode: [], diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index fdfaf0271..ec84eb81b 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { IDE } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; -import { getModelByRole } from "core/config/util"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -9,10 +8,10 @@ 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"; -import { DataLogger } from "core/data/log"; // @ts-ignore - error finding typings // @ts-ignore @@ -278,7 +277,7 @@ export class QuickEdit { } return ( - getModelByRole(config, "inlineEdit")?.title ?? + config.selectedModelByRole.edit?.title ?? (await this.webviewProtocol.request( "getDefaultModelTitle", undefined, diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts deleted file mode 100644 index fda69f023..000000000 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { ConfigHandler } from "core/config/ConfigHandler"; -import Ollama from "core/llm/llms/Ollama"; -import { GlobalContext } from "core/util/GlobalContext"; - -import type { ILLM } from "core"; - -export class TabAutocompleteModel { - private _llm: ILLM | undefined; - private defaultTag = "qwen2.5-coder:1.5b"; - private globalContext: GlobalContext = new GlobalContext(); - - constructor(private configHandler: ConfigHandler) {} - - clearLlm() { - this._llm = undefined; - } - - async getDefaultTabAutocompleteModel() { - const llm = new Ollama({ - model: this.defaultTag, - }); - - try { - const models = await llm.listModels(); - if (!models.includes(this.defaultTag)) { - return undefined; - } - } catch (e) { - return undefined; - } - - return llm; - } - - async get() { - if (!this._llm) { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - return undefined; - } - - if (config.tabAutocompleteModels?.length) { - const selected = this.globalContext.get("selectedTabAutocompleteModel"); - if (selected) { - this._llm = - config.tabAutocompleteModels?.find( - (model) => model.title === selected, - ) ?? config.tabAutocompleteModels?.[0]; - } else { - if (config.tabAutocompleteModels[0].title) { - this.globalContext.update( - "selectedTabAutocompleteModel", - config.tabAutocompleteModels[0].title, - ); - } - this._llm = config.tabAutocompleteModels[0]; - } - } else { - this._llm = await this.getDefaultTabAutocompleteModel(); - } - } - - return this._llm; - } -} diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index b54db7549..f5d8cf178 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -278,9 +278,7 @@ const Layout = () => { onClick={() => navigate(ROUTES.CONFIG_ERROR)} > Error!{" "} - - Could not load config.json - + Could not load config
Learn More
)} diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index df75e6203..eb3d3bcbb 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -110,7 +110,6 @@ function AddDocsDialog() { type: "docs", description: "Initializing", id: startUrl, - embeddingsProviderId: "mock-embeddings-provider-id", progress: 0, status: "indexing", title, @@ -164,7 +163,6 @@ function AddDocsDialog() { type: "docs", description: "Initializing", id: docsResult.details.docsLink, - embeddingsProviderId: "mock-embeddings-provider-id", progress: 0, status: "indexing", title: docsResult.details.title ?? docsResult.packageInfo.name, diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index 7d6105e6d..8957038ac 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -13,10 +13,10 @@ const ToggleSwitch: React.FC = ({ }) => { return (
- {text} + {text}
diff --git a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx index aef66670a..b98cf364b 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx @@ -21,7 +21,8 @@ export function AssistantSelectOptions({ onClose, }: AssistantSelectOptionsProps) { const ideMessenger = useContext(IdeMessengerContext); - const { profiles, selectedProfile, selectedOrganization } = useAuth(); + const { profiles, selectedProfile, selectedOrganization, session, login } = + useAuth(); const dispatch = useAppDispatch(); const navigate = useNavigate(); @@ -85,7 +86,10 @@ export function AssistantSelectOptions({
- + login(true)} + >
state.config.config.embeddingsProvider, + (state) => state.config.config.selectedModelByRole.embed, ); - const showJbError = - (isJetBrains() && embeddingsProvider === "all-MiniLM-L6-v2") || true; - - if (showJbError) { + if (!embeddingsProvider) { return (
- The transformers.js embeddingsProvider is currently - unsupported in JetBrains. To enable codebase indexing, you can use any - of the other providers described in the docs:{" "} + Add an Embeddings model to enable codebase indexing. See the docs for + examples: void; + displayName: string; + description: string; +} + +const ModelRoleSelector = ({ + models, + selectedModel, + onSelect, + displayName, + description, +}: ModelRoleSelectorProps) => { + function handleSelect(title: string | null) { + onSelect(models.find((m) => m.title === title) ?? null); + } + + return ( + <> +
+ {displayName} + + + {description} + +
+ + {({ open }) => ( +
+ + {models.length === 0 ? ( + {`No ${displayName} models${["Chat", "Apply", "Edit"].includes(displayName) ? ". Using chat model" : ""}`} + ) : ( + + {selectedModel?.title ?? `Select ${displayName} model`} + + )} + {models.length ? ( +
+
+ ) : null} +
+ + + + {models.map((option, idx) => ( + + + {option.title} + + + ))} + + +
+ )} +
+ + ); +}; + +export default ModelRoleSelector; diff --git a/gui/src/pages/config/UserSettings.tsx b/gui/src/pages/config/UserSettings.tsx deleted file mode 100644 index 6912cd031..000000000 --- a/gui/src/pages/config/UserSettings.tsx +++ /dev/null @@ -1,322 +0,0 @@ -import { useContext, useEffect, useState } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; - -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { - SharedConfigSchema, - modifyContinueConfigWithSharedConfig, -} from "core/config/sharedConfig"; -import { Input } from "../../components"; -import NumberInput from "../../components/gui/NumberInput"; -import { Select } from "../../components/gui/Select"; -import ToggleSwitch from "../../components/gui/Switch"; -import { updateConfig } from "../../redux/slices/configSlice"; -import { getFontSize } from "../../util"; - -function UserSettingsUI() { - const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - - const config = useAppSelector((state) => state.config.config); - - function handleUpdate(sharedConfig: Partial) { - dispatch( - updateConfig(modifyContinueConfigWithSharedConfig(config, sharedConfig)), - ); - ideMessenger.post("config/updateSharedConfig", sharedConfig); - } - - // TODO defaults are in multiple places, should be consolidated and probably not explicit here - const codeWrap = config.ui?.codeWrap ?? false; - const showChatScrollbar = config.ui?.showChatScrollbar ?? false; - const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; - const disableSessionTitles = config.disableSessionTitles ?? false; - const readResponseTTS = config.experimental?.readResponseTTS ?? false; - - const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; - const disableIndexing = config.disableIndexing ?? false; - - const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false; - const useChromiumForDocsCrawling = - config.experimental?.useChromiumForDocsCrawling ?? false; - const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top"; - const useAutocompleteMultilineCompletions = - config.tabAutocompleteOptions?.multilineCompletions ?? "auto"; - const fontSize = getFontSize(); - - // Disable autocomplete - const disableAutocompleteInFiles = ( - config.tabAutocompleteOptions?.disableInFiles ?? [] - ).join(", "); - const [formDisableAutocomplete, setFormDisableAutocomplete] = useState( - disableAutocompleteInFiles, - ); - const cancelChangeDisableAutocomplete = () => { - setFormDisableAutocomplete(disableAutocompleteInFiles); - }; - const handleDisableAutocompleteSubmit = () => { - handleUpdate({ - disableAutocompleteInFiles: formDisableAutocomplete - .split(",") - .map((val) => val.trim()) - .filter((val) => !!val), - }); - }; - - useEffect(() => { - // Necessary so that reformatted/trimmed values don't cause dirty state - setFormDisableAutocomplete(disableAutocompleteInFiles); - }, [disableAutocompleteInFiles]); - - // Workspace prompts - const promptPath = config.experimental?.promptPath || ""; - const [formPromptPath, setFormPromptPath] = useState(promptPath); - const cancelChangePromptPath = () => { - setFormPromptPath(promptPath); - }; - const handleSubmitPromptPath = () => { - handleUpdate({ - promptPath: formPromptPath || "", - }); - }; - - useEffect(() => { - // Necessary so that reformatted/trimmed values don't cause dirty state - setFormPromptPath(promptPath); - }, [promptPath]); - - return ( -
-
-

User settings

-
- -
- - handleUpdate({ - codeWrap: !codeWrap, - }) - } - text="Wrap Codeblocks" - /> - - handleUpdate({ - displayRawMarkdown: !displayRawMarkdown, - }) - } - text="Display Raw Markdown" - /> - - handleUpdate({ - allowAnonymousTelemetry: !allowAnonymousTelemetry, - }) - } - text="Allow Anonymous Telemetry" - /> - - handleUpdate({ - disableIndexing: !disableIndexing, - }) - } - text="Disable Indexing" - /> - - - handleUpdate({ - disableSessionTitles: !disableSessionTitles, - }) - } - text="Disable Session Titles" - /> - - handleUpdate({ - readResponseTTS: !readResponseTTS, - }) - } - text="Response Text to Speech" - /> - - - handleUpdate({ - showChatScrollbar: !showChatScrollbar, - }) - } - text="Show Chat Scrollbar" - /> - - - handleUpdate({ - useAutocompleteCache: !useAutocompleteCache, - }) - } - text="Use Autocomplete Cache" - /> - - - handleUpdate({ - useChromiumForDocsCrawling: !useChromiumForDocsCrawling, - }) - } - text="Use Chromium for Docs Crawling" - /> - - - - - - - -
{ - e.preventDefault(); - handleSubmitPromptPath(); - }} - > -
- Workspace prompts path -
- { - setFormPromptPath(e.target.value); - }} - /> -
- {formPromptPath !== promptPath ? ( - <> -
- -
-
- -
- - ) : ( -
- -
- )} -
-
-
-
-
{ - e.preventDefault(); - handleDisableAutocompleteSubmit(); - }} - > -
- Disable autocomplete in files -
- { - setFormDisableAutocomplete(e.target.value); - }} - /> -
- {formDisableAutocomplete !== disableAutocompleteInFiles ? ( - <> -
- -
-
- -
- - ) : ( -
- -
- )} -
-
-
- - Comma-separated list of path matchers - -
-
-
- ); -} - -export default UserSettingsUI; diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 56fe464f7..f187c1067 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -1,16 +1,32 @@ +import { ModelRole } from "@continuedev/config-yaml"; import { Listbox, Transition } from "@headlessui/react"; -import { ChevronUpDownIcon, PlusCircleIcon } from "@heroicons/react/24/outline"; +import { + CheckIcon, + ChevronUpDownIcon, + PlusCircleIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { ModelDescription } from "core"; +import { + SharedConfigSchema, + modifyAnyConfigWithSharedConfig, +} from "core/config/sharedConfig"; import { Fragment, useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; -import { SecondaryButton } from "../../components"; +import { Input, SecondaryButton } from "../../components"; +import NumberInput from "../../components/gui/NumberInput"; +import { Select } from "../../components/gui/Select"; +import ToggleSwitch from "../../components/gui/Switch"; import PageHeader from "../../components/PageHeader"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { useAppDispatch } from "../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setDefaultModel, updateConfig } from "../../redux/slices/configSlice"; import { selectProfileThunk } from "../../redux/thunks/profileAndOrg"; +import { getFontSize, isJetBrains } from "../../util"; +import ModelRoleSelector from "./ModelRoleSelector"; import { ScopeSelect } from "./ScopeSelect"; -import UserSettingsUI from "./UserSettings"; function ConfigPage() { useNavigationListener(); @@ -52,6 +68,113 @@ function ConfigPage() { // NOTE Hub takes priority over Continue for Teams // Since teams will be moving to hub, not vice versa + /////// User settings section ////// + const config = useAppSelector((state) => state.config.config); + const selectedChatModel = useAppSelector( + (store) => store.config.defaultModelTitle, + ); + + function handleUpdate(sharedConfig: SharedConfigSchema) { + // Optimistic update + const updatedConfig = modifyAnyConfigWithSharedConfig(config, sharedConfig); + dispatch(updateConfig(updatedConfig)); + // IMPORTANT no need for model role updates (separate logic for selected model roles) + // simply because this function won't be used to update model roles + + // Actual update to core which propagates back with config update event + ideMessenger.post("config/updateSharedConfig", sharedConfig); + } + + 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 })); + } + + // TODO defaults are in multiple places, should be consolidated and probably not explicit here + const codeWrap = config.ui?.codeWrap ?? false; + const showChatScrollbar = config.ui?.showChatScrollbar ?? false; + const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; + const disableSessionTitles = config.disableSessionTitles ?? false; + const readResponseTTS = config.experimental?.readResponseTTS ?? false; + + const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; + const disableIndexing = config.disableIndexing ?? false; + + const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false; + const useChromiumForDocsCrawling = + config.experimental?.useChromiumForDocsCrawling ?? false; + const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top"; + const useAutocompleteMultilineCompletions = + config.tabAutocompleteOptions?.multilineCompletions ?? "auto"; + const fontSize = getFontSize(); + + // Disable autocomplete + const disableAutocompleteInFiles = ( + config.tabAutocompleteOptions?.disableInFiles ?? [] + ).join(", "); + const [formDisableAutocomplete, setFormDisableAutocomplete] = useState( + disableAutocompleteInFiles, + ); + const cancelChangeDisableAutocomplete = () => { + setFormDisableAutocomplete(disableAutocompleteInFiles); + }; + const handleDisableAutocompleteSubmit = () => { + handleUpdate({ + disableAutocompleteInFiles: formDisableAutocomplete + .split(",") + .map((val) => val.trim()) + .filter((val) => !!val), + }); + }; + + useEffect(() => { + // Necessary so that reformatted/trimmed values don't cause dirty state + setFormDisableAutocomplete(disableAutocompleteInFiles); + }, [disableAutocompleteInFiles]); + + // Workspace prompts + const promptPath = config.experimental?.promptPath || ""; + const [formPromptPath, setFormPromptPath] = useState(promptPath); + const cancelChangePromptPath = () => { + setFormPromptPath(promptPath); + }; + const handleSubmitPromptPath = () => { + handleUpdate({ + promptPath: formPromptPath || "", + }); + }; + + useEffect(() => { + // Necessary so that reformatted/trimmed values don't cause dirty state + setFormPromptPath(promptPath); + }, [promptPath]); + + const jetbrains = isJetBrains(); + return (
navigate("/")} title="Chat" /> @@ -143,10 +266,14 @@ function ConfigPage() { value={null} className={`text-vsc-foreground hover:bg-list-active bg-vsc-input-background flex cursor-pointer flex-row items-center gap-2 px-3 py-2`} onClick={() => { - ideMessenger.post("controlPlane/openUrl", { - path: "new", - orgSlug: selectedOrganization?.slug, - }); + if (session) { + ideMessenger.post("controlPlane/openUrl", { + path: "new", + orgSlug: selectedOrganization?.slug, + }); + } else { + login(true); + } }} > @@ -173,12 +300,301 @@ function ConfigPage() { ) : (
Loading...
)} +
+

+ Active Models +

+
+ handleChatModelSelection(model)} + /> + handleRoleUpdate("autocomplete", model)} + /> + {/* Jetbrains has a model selector inline */} + {!jetbrains && ( + handleRoleUpdate("edit", model)} + /> + )} + handleRoleUpdate("apply", model)} + /> + handleRoleUpdate("embed", model)} + /> + handleRoleUpdate("rerank", model)} + /> +
+
{!controlServerBetaEnabled || hubEnabled ? (
- +
+
+

User settings

+
+ +
+ + handleUpdate({ + codeWrap: !codeWrap, + }) + } + text="Wrap Codeblocks" + /> + + handleUpdate({ + displayRawMarkdown: !displayRawMarkdown, + }) + } + text="Display Raw Markdown" + /> + + handleUpdate({ + allowAnonymousTelemetry: !allowAnonymousTelemetry, + }) + } + text="Allow Anonymous Telemetry" + /> + + handleUpdate({ + disableIndexing: !disableIndexing, + }) + } + text="Disable Indexing" + /> + + + handleUpdate({ + disableSessionTitles: !disableSessionTitles, + }) + } + text="Disable Session Titles" + /> + + handleUpdate({ + readResponseTTS: !readResponseTTS, + }) + } + text="Response Text to Speech" + /> + + + handleUpdate({ + showChatScrollbar: !showChatScrollbar, + }) + } + text="Show Chat Scrollbar" + /> + + + handleUpdate({ + useAutocompleteCache: !useAutocompleteCache, + }) + } + text="Use Autocomplete Cache" + /> + + + handleUpdate({ + useChromiumForDocsCrawling: !useChromiumForDocsCrawling, + }) + } + text="Use Chromium for Docs Crawling" + /> + + + + + + + +
{ + e.preventDefault(); + handleSubmitPromptPath(); + }} + > +
+ Workspace prompts path +
+ { + setFormPromptPath(e.target.value); + }} + /> +
+ {formPromptPath !== promptPath ? ( + <> +
+ +
+
+ +
+ + ) : ( +
+ +
+ )} +
+
+
+
+
{ + e.preventDefault(); + handleDisableAutocompleteSubmit(); + }} + > +
+ Disable autocomplete in files +
+ { + setFormDisableAutocomplete(e.target.value); + }} + /> +
+ {formDisableAutocomplete !== + disableAutocompleteInFiles ? ( + <> +
+ +
+
+ +
+ + ) : ( +
+ +
+ )} +
+
+
+ + Comma-separated list of path matchers + +
+
+
) : null} diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 604f583e4..3b5c55137 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -27,6 +27,24 @@ const initialState: ConfigState = { models: [], tools: [], usePlatform: true, + modelsByRole: { + chat: [], + apply: [], + edit: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + apply: null, + edit: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, }, };