diff --git a/.gitignore b/.gitignore index 763b96238..92cb4b852 100644 --- a/.gitignore +++ b/.gitignore @@ -157,11 +157,15 @@ Icon? notes.md manual-testing-sandbox/.idea/** +manual-testing-sandbox/.continue/** extensions/intellij/.idea/** **/.idea/workspace.xml **/.idea/usage.statistics.xml **/.idea/shelf/ +**/.idea/inspectionProfiles/Project_Default.xml +**/.idea/php.xml + extensions/intellij/bin extensions/.continue-debug/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4f7e1634f..73997880a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,6 @@ - [Writing Context Providers](#writing-context-providers) - [Adding an LLM Provider](#adding-an-llm-provider) - [Adding Models](#adding-models) - - [Adding Pre-indexed Documentation](#adding-pre-indexed-documentation) - [📐 Continue Architecture](#-continue-architecture) - [Continue VS Code Extension](#continue-vs-code-extension) - [Continue JetBrains Extension](#continue-jetbrains-extension) @@ -212,10 +211,6 @@ While any model that works with a supported provider can be used with Continue, - LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models). - [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates. -### Adding Pre-indexed Documentation - -Continue's @docs context provider lets you easily reference entire documentation sites and then uses embeddings to add the most relevant pages to context. To make the experience as smooth as possible, we pre-index many of the most popular documentation sites. If you'd like to add new documentation to this list, just add an object to the list in [preIndexedDocs.ts](./core/indexing/docs/preIndexedDocs.ts). `startUrl` is where the crawler will start and `rootUrl` will filter out any pages not on that site and under the path of `rootUrl`. - ## 📐 Continue Architecture Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible: diff --git a/binary/build.js b/binary/build.js index adc461396..99a5d0e12 100644 --- a/binary/build.js +++ b/binary/build.js @@ -243,7 +243,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { fs.mkdirSync(targetDir, { recursive: true }); console.log(`[info] Building ${target}...`); execCmdSync( - `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`, + `npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`, ); // Download and unzip prebuilt sqlite3 binary for the target diff --git a/binary/package-lock.json b/binary/package-lock.json index c823d785e..5ce095e37 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -51,7 +51,7 @@ "@continuedev/config-yaml": "^1.0.63", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", - "@continuedev/openai-adapters": "^1.0.10", + "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index e541d57c1..633895fb7 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -14,7 +14,7 @@ "eqeqeq": "error", "complexity": ["error", { "max": 38 }], "max-lines-per-function": ["error", { "max": 996 }], - "max-statements": ["error", { "max": 112 }], + "max-statements": ["error", { "max": 114 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], "max-params": ["error", { "max": 11 }] diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index 5528d223c..e2288138a 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -5,6 +5,7 @@ import { getParserForFile, getQueryForFile, } from "../../util/treeSitter"; +import { findUriInDirs } from "../../util/uri"; interface FileInfo { imports: { [key: string]: RangeInFileWithContents[] }; @@ -44,7 +45,15 @@ export class ImportDefinitionsService { let fileContents: string | undefined = undefined; try { - fileContents = await this.ide.readFile(filepath); + const { foundInDir } = findUriInDirs( + filepath, + await this.ide.getWorkspaceDirs(), + ); + if (!foundInDir) { + return null; + } else { + fileContents = await this.ide.readFile(filepath); + } } catch (err) { // File removed return null; diff --git a/core/commands/index.ts b/core/commands/index.ts index 72719d832..486eaccf2 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -10,6 +10,7 @@ export function slashFromCustomCommand( return { name: customCommand.name, description: customCommand.description ?? "", + prompt: customCommand.prompt, run: async function* ({ input, llm, history, ide, completionOptions }) { // Remove slash command prefix from input let userInput = input; diff --git a/core/commands/util.ts b/core/commands/util.ts index 1cd493fad..5a0ea32e4 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -1,6 +1,7 @@ +import { v4 as uuidv4 } from "uuid"; + import { ContextItemWithId, RangeInFileWithContents } from "../"; import { findUriInDirs, getUriPathBasename } from "../util/uri"; -import { v4 as uuidv4 } from "uuid"; export function rifWithContentsToContextItem( rif: RangeInFileWithContents, diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index eadaa137f..031075e90 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -19,7 +19,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should load the default config successfully", async () => { const result = await testConfigHandler.loadConfig(); - expect(result.config!.models.length).toBe(defaultConfig.models.length); + expect(result.config!.models.length).toBe(defaultConfig.models?.length); }); test.skip("should add a system message from config.ts", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 7db61161a..3a3c81fab 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -199,8 +199,8 @@ export class ConfigHandler { this.ide, this.ideSettingsPromise, this.writeLog, - this.reloadConfig.bind(this), assistant.rawYaml, + selectedOrgId, ); return new ProfileLifecycleManager(profileLoader, this.ide); diff --git a/core/config/default.ts b/core/config/default.ts index 8c349a13b..81c133455 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -1,93 +1,37 @@ -import { - ContextProviderWithParams, - ModelDescription, - SerializedContinueConfig, - SlashCommandDescription, -} from "../"; +import { ConfigYaml } from "@continuedev/config-yaml"; -export const FREE_TRIAL_MODELS: ModelDescription[] = [ - { - title: "Claude 3.5 Sonnet (Free Trial)", - provider: "free-trial", - model: "claude-3-5-sonnet-latest", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", - }, - { - title: "GPT-4o (Free Trial)", - provider: "free-trial", - model: "gpt-4o", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", - }, - { - title: "Llama3.1 70b (Free Trial)", - provider: "free-trial", - model: "llama3.1-70b", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", - }, - { - title: "Codestral (Free Trial)", - provider: "free-trial", - model: "codestral-latest", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", - }, +export const defaultContextProvidersVsCode: NonNullable< + ConfigYaml["context"] +>[number][] = [ + { provider: "code" }, + { provider: "docs" }, + { provider: "diff" }, + { provider: "terminal" }, + { provider: "problems" }, + { provider: "folder" }, + { provider: "codebase" }, ]; -export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [ - { name: "code", params: {} }, - { name: "docs", params: {} }, - { name: "diff", params: {} }, - { name: "terminal", params: {} }, - { name: "problems", params: {} }, - { name: "folder", params: {} }, - { name: "codebase", params: {} }, +export const defaultContextProvidersJetBrains: NonNullable< + ConfigYaml["context"] +>[number][] = [ + { provider: "diff" }, + { provider: "folder" }, + { provider: "codebase" }, ]; -export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [ - { name: "diff", params: {} }, - { name: "folder", params: {} }, - { name: "codebase", params: {} }, -]; - -export const defaultSlashCommandsVscode: SlashCommandDescription[] = [ - { - name: "share", - description: "Export the current chat session to markdown", - }, - { - name: "cmd", - description: "Generate a shell command", - }, - { - name: "commit", - description: "Generate a git commit message", - }, -]; - -export const defaultSlashCommandsJetBrains = [ - { - name: "share", - description: "Export the current chat session to markdown", - }, - { - name: "commit", - description: "Generate a git commit message", - }, -]; - -export const defaultConfig: SerializedContinueConfig = { +export const defaultConfig: ConfigYaml = { + name: "Local Assistant", + version: "1.0.0", + schema: "v1", models: [], - contextProviders: defaultContextProvidersVsCode, - slashCommands: defaultSlashCommandsVscode, - data: [], + context: defaultContextProvidersVsCode, }; -export const defaultConfigJetBrains: SerializedContinueConfig = { +export const defaultConfigJetBrains: ConfigYaml = { + name: "Local Assistant", + version: "1.0.0", + schema: "v1", models: [], - contextProviders: defaultContextProvidersJetBrains, - slashCommands: defaultSlashCommandsJetBrains, - data: [], + context: defaultContextProvidersJetBrains, }; diff --git a/core/config/load.ts b/core/config/load.ts index a198f37bf..1a3acd6c6 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -28,7 +28,6 @@ import { IdeType, ILLM, LLMOptions, - MCPOptions, ModelDescription, RerankerDescription, SerializedContinueConfig, @@ -45,7 +44,6 @@ import ContinueProxyContextProvider from "../context/providers/ContinueProxyCont import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; -import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; import { useHub } from "../control-plane/env"; import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; @@ -72,12 +70,6 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { - defaultContextProvidersJetBrains, - defaultContextProvidersVsCode, - defaultSlashCommandsJetBrains, - defaultSlashCommandsVscode, -} from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util"; @@ -124,7 +116,7 @@ function loadSerializedConfig( let config: SerializedContinueConfig = overrideConfigJson!; if (!config) { try { - config = resolveSerializedConfig(getConfigJsonPath(ideType)); + config = resolveSerializedConfig(getConfigJsonPath()); } catch (e) { throw new Error(`Failed to parse config.json: ${e}`); } @@ -164,16 +156,6 @@ function loadSerializedConfig( ); } - // Set defaults if undefined (this lets us keep config.json uncluttered for new users) - config.contextProviders ??= - ideType === "vscode" - ? [...defaultContextProvidersVsCode] - : [...defaultContextProvidersJetBrains]; - config.slashCommands ??= - ideType === "vscode" - ? [...defaultSlashCommandsVscode] - : [...defaultSlashCommandsJetBrains]; - if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) { config.disableIndexing = true; } @@ -401,8 +383,6 @@ async function intermediateToFinalConfig( ...(!config.disableIndexing ? [new CodebaseContextProvider(codebaseContextParams)] : []), - // Add prompt files provider if enabled - ...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []), ]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( @@ -520,7 +500,9 @@ async function intermediateToFinalConfig( ...config, contextProviders, models, - tools: allTools, + tools: [...allTools], + mcpServerStatuses: [], + slashCommands: config.slashCommands ?? [], modelsByRole: { chat: models, edit: models, @@ -541,53 +523,18 @@ async function intermediateToFinalConfig( }, }; - // Apply MCP if specified + // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - function getMcpId(options: MCPOptions) { - return JSON.stringify(options); - } - if (config.experimental?.modelContextProtocolServers) { - await mcpManager.removeUnusedConnections( - config.experimental.modelContextProtocolServers.map(getMcpId), - ); - } - - if (config.experimental?.modelContextProtocolServers) { - const abortController = new AbortController(); - const mcpConnectionTimeout = setTimeout( - () => abortController.abort(), - 5000, - ); - - await Promise.allSettled( - config.experimental.modelContextProtocolServers?.map( - async (server, index) => { - try { - const mcpId = getMcpId(server); - const mcpConnection = mcpManager.createConnection(mcpId, server); - await mcpConnection.modifyConfig( - continueConfig, - mcpId, - abortController.signal, - "MCP Server", - server.faviconUrl, - ); - } catch (e) { - let errorMessage = "Failed to load MCP server"; - if (e instanceof Error) { - errorMessage += ": " + e.message; - } - errors.push({ - fatal: false, - message: errorMessage, - }); - } finally { - clearTimeout(mcpConnectionTimeout); - } - }, - ) || [], - ); - } + mcpManager.setConnections( + (config.experimental?.modelContextProtocolServers ?? []).map( + (server, index) => ({ + id: `continue-mcp-server-${index + 1}`, + name: `MCP Server`, + ...server, + }), + ), + false, + ); // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; @@ -667,11 +614,9 @@ async function finalToBrowserConfig( 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, // TODO: is this why params aren't referenced properly by slash commands? - })), + slashCommands: final.slashCommands?.map( + ({ run, ...slashCommandDescription }) => slashCommandDescription, + ), contextProviders: final.contextProviders?.map((c) => c.description), disableIndexing: final.disableIndexing, disableSessionTitles: final.disableSessionTitles, @@ -681,6 +626,7 @@ async function finalToBrowserConfig( rules: final.rules, docs: final.docs, tools: final.tools, + mcpServerStatuses: final.mcpServerStatuses, tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), modelsByRole: Object.fromEntries( diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index 189bb21ed..cf689b45d 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -1,7 +1,6 @@ import { IDE } from ".."; import { deduplicateArray } from "../util"; import { GlobalContext } from "../util/GlobalContext"; -import { editConfigJson } from "../util/paths"; import { resolveSerializedConfig } from "./load"; import { SharedConfigSchema } from "./sharedConfig"; @@ -196,11 +195,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { if (effected) { new GlobalContext().updateSharedConfig(shareConfigUpdates); - editConfigJson(() => config); - // void ide.showToast( - // "warning", - // "Migrated deprecated Continue JSON settings. Edit in the Settings Page", - // ); } } catch (e) { throw new Error(`Migration: Failed to parse config.json: ${e}`); diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index 8babfffde..729653674 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -1,6 +1,4 @@ -import { SerializedContinueConfig } from "../"; - -import { FREE_TRIAL_MODELS } from "./default"; +import { ConfigYaml } from "@continuedev/config-yaml"; export const TRIAL_FIM_MODEL = "codestral-latest"; export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama"; @@ -9,64 +7,46 @@ export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B"; export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b"; export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B"; export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest"; +export const LOCAL_ONBOARDING_EMBEDDINGS_TITLE = "Nomic Embed"; /** * We set the "best" chat + autocopmlete models by default * whenever a user doesn't have a config.json */ -export function setupBestConfig( - config: SerializedContinueConfig, -): SerializedContinueConfig { +export function setupBestConfig(config: ConfigYaml): ConfigYaml { return { ...config, - models: config.models.filter((model) => model.provider !== "free-trial"), + models: config.models, }; } -export function setupLocalConfig( - config: SerializedContinueConfig, -): SerializedContinueConfig { +export function setupLocalConfig(config: ConfigYaml): ConfigYaml { return { ...config, models: [ { - title: LOCAL_ONBOARDING_CHAT_TITLE, + name: LOCAL_ONBOARDING_CHAT_TITLE, provider: "ollama", model: LOCAL_ONBOARDING_CHAT_MODEL, + roles: ["chat", "edit", "apply"], }, - ...config.models.filter((model) => model.provider !== "free-trial"), + { + name: LOCAL_ONBOARDING_FIM_TITLE, + provider: "ollama", + model: LOCAL_ONBOARDING_FIM_MODEL, + roles: ["autocomplete"], + }, + { + name: LOCAL_ONBOARDING_EMBEDDINGS_TITLE, + provider: "ollama", + model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL, + roles: ["embed"], + }, + ...(config.models ?? []), ], - tabAutocompleteModel: { - title: LOCAL_ONBOARDING_FIM_TITLE, - provider: "ollama", - model: LOCAL_ONBOARDING_FIM_MODEL, - }, - embeddingsProvider: { - provider: "ollama", - model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL, - }, }; } -export function setupQuickstartConfig( - config: SerializedContinueConfig, -): SerializedContinueConfig { - return { - ...config, - models: [ - ...FREE_TRIAL_MODELS, - ...config.models.filter((model) => model.provider !== "free-trial"), - ], - tabAutocompleteModel: { - title: "Tab Autocomplete", - provider: "free-trial", - model: TRIAL_FIM_MODEL, - }, - embeddingsProvider: { - provider: "free-trial", - }, - reranker: { - name: "free-trial", - }, - }; +export function setupQuickstartConfig(config: ConfigYaml): ConfigYaml { + return config; } diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 8d12e771f..85130676b 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -2,6 +2,7 @@ import { ConfigJson } from "@continuedev/config-types"; import { ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; +import { PRODUCTION_ENV } from "../../control-plane/env.js"; import { ContinueConfig, IDE, @@ -10,7 +11,6 @@ import { } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; -import { PRODUCTION_ENV } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -71,6 +71,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { undefined, this.workspaceId, undefined, + null, ); } diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 46245a7f0..464d16804 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -65,6 +65,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, this.description.id, this.overrideAssistantFile?.path, + null, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 49fd2d0c1..468d3511a 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -1,11 +1,10 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; - import { ProfileDescription } from "../ProfileLifecycleManager.js"; -import { getControlPlaneEnv } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -32,8 +31,8 @@ export default class PlatformProfileLoader implements IProfileLoader { private readonly ide: IDE, private ideSettingsPromise: Promise, private writeLog: (message: string) => Promise, - private readonly onReload: () => void, readonly description: ProfileDescription, + private readonly orgScopeId: string | null, ) {} static async create( @@ -46,8 +45,8 @@ export default class PlatformProfileLoader implements IProfileLoader { ide: IDE, ideSettingsPromise: Promise, writeLog: (message: string) => Promise, - onReload: () => void, rawYaml: string, + orgScopeId: string | null, ): Promise { const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); @@ -76,8 +75,8 @@ export default class PlatformProfileLoader implements IProfileLoader { ide, ideSettingsPromise, writeLog, - onReload, description, + orgScopeId, ); } @@ -103,6 +102,7 @@ export default class PlatformProfileLoader implements IProfileLoader { }, this.description.id, undefined, + this.orgScopeId, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 224b7b64e..6351c4474 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -6,18 +6,24 @@ import { ConfigValidationError, ModelRole, } from "@continuedev/config-yaml"; + import { ContinueConfig, ContinueRcJson, IDE, IdeSettings, SerializedContinueConfig, + Tool, } from "../../"; +import { constructMcpSlashCommand } from "../../commands/slash/mcp"; +import { MCPManagerSingleton } from "../../context/mcp"; +import MCPContextProvider from "../../context/providers/MCPContextProvider"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; +import { encodeMCPToolUri } from "../../tools/callTool"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; @@ -26,6 +32,7 @@ import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; + import { PlatformConfigMetadata } from "./PlatformProfileLoader"; export default async function doLoadConfig( @@ -38,6 +45,7 @@ export default async function doLoadConfig( platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, overrideConfigYamlByPath: string | undefined, + orgScopeId: string | null, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -47,7 +55,7 @@ export default async function doLoadConfig( // Migrations for old config files // Removes - const configJsonPath = getConfigJsonPath(ideInfo.ideType); + const configJsonPath = getConfigJsonPath(); if (fs.existsSync(configJsonPath)) { migrateJsonSharedConfig(configJsonPath, ide); } @@ -63,7 +71,6 @@ export default async function doLoadConfig( if (overrideConfigYaml || fs.existsSync(configYamlPath)) { const result = await loadContinueConfigFromYaml( ide, - workspaceConfigs.map((c) => JSON.stringify(c)), ideSettings, ideInfo, uniqueId, @@ -73,6 +80,7 @@ export default async function doLoadConfig( platformConfigMetadata, controlPlaneClient, configYamlPath, + orgScopeId, ); newConfig = result.config; errors = result.errors; @@ -93,15 +101,89 @@ 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 }; } + // TODO using config result but result with non-fatal errors is an antipattern? + // Remove ability have undefined errors, just have an array + errors = [...(errors ?? [])]; + + // Rectify model selections for each role + newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); + + // Add things from MCP servers + const mcpManager = MCPManagerSingleton.getInstance(); + const mcpServerStatuses = mcpManager.getStatuses(); + + // Slightly hacky just need connection's client to make slash command for now + const serializableStatuses = mcpServerStatuses.map((server) => { + const { client, ...rest } = server; + return rest; + }); + newConfig.mcpServerStatuses = serializableStatuses; + + for (const server of mcpServerStatuses) { + if (server.status === "connected") { + const serverTools: Tool[] = server.tools.map((tool) => ({ + displayTitle: server.name + " " + tool.name, + function: { + description: tool.description, + name: tool.name, + parameters: tool.inputSchema, + }, + faviconUrl: server.faviconUrl, + readonly: false, + type: "function" as const, + uri: encodeMCPToolUri(server.id, tool.name), + group: server.name, + })); + newConfig.tools.push(...serverTools); + + const serverSlashCommands = server.prompts.map((prompt) => + constructMcpSlashCommand( + server.client, + prompt.name, + prompt.description, + prompt.arguments?.map((a: any) => a.name), + ), + ); + newConfig.slashCommands.push(...serverSlashCommands); + + const submenuItems = server.resources.map((resource) => ({ + title: resource.name, + description: resource.description ?? resource.name, + id: resource.uri, + icon: server.faviconUrl, + })); + if (submenuItems.length > 0) { + const serverContextProvider = new MCPContextProvider({ + submenuItems, + mcpId: server.id, + }); + newConfig.contextProviders.push(serverContextProvider); + } + } + } + + // Detect duplicate tool names + const counts: Record = {}; + newConfig.tools.forEach((tool) => { + if (counts[tool.function.name]) { + counts[tool.function.name] = counts[tool.function.name] + 1; + } else { + counts[tool.function.name] = 1; + } + }); + Object.entries(counts).forEach(([toolName, count]) => { + if (count > 1) { + errors!.push({ + fatal: false, + message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`, + }); + } + }); + newConfig.allowAnonymousTelemetry = newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled()); diff --git a/core/config/util.ts b/core/config/util.ts index 8bfe6a84f..ee827c2f9 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -2,17 +2,14 @@ import fs from "fs"; import os from "os"; import { - ContextProviderWithParams, ContinueConfig, + ExperimentalModelRoles, IDE, ILLM, ModelDescription, - ExperimentalModelRoles, } from "../"; import { GlobalContext } from "../util/GlobalContext"; -import { editConfigJson } from "../util/paths"; - -import { ConfigHandler } from "./ConfigHandler"; +import { editConfigFile } from "../util/paths"; function stringify(obj: any, indentation?: number): string { return JSON.stringify( @@ -24,78 +21,67 @@ function stringify(obj: any, indentation?: number): string { ); } -export function addContextProvider(provider: ContextProviderWithParams, configHandler?: ConfigHandler) { - let isAdded = false; - editConfigJson((config) => { - - if (!config.contextProviders) { - config.contextProviders = []; - } - if (!config.contextProviders.some((p) => p.name === provider.name)) { - config.contextProviders.push(provider); - isAdded = true; - } - - return config; - }); - - if (isAdded && configHandler) { - void configHandler.reloadConfig(); - } -} - export function addModel( model: ModelDescription, role?: keyof ExperimentalModelRoles, ) { - editConfigJson((config) => { - if (config.models?.some((m: any) => stringify(m) === stringify(model))) { - return config; - } - if (config.models?.some((m: any) => m?.title === model.title)) { - model.title = `${model.title} (1)`; - } - - config.models.push(model); - - // Set the role for the model - if (role) { - if (!config.experimental) { - config.experimental = {}; + editConfigFile( + (config) => { + if (config.models?.some((m: any) => stringify(m) === stringify(model))) { + return config; } - if (!config.experimental.modelRoles) { - config.experimental.modelRoles = {}; + if (config.models?.some((m: any) => m?.title === model.title)) { + model.title = `${model.title} (1)`; } - config.experimental.modelRoles[role] = model.title; - } - return config; - }); -} + config.models.push(model); -export function addOpenAIKey(key: string) { - editConfigJson((config) => { - config.models = config.models - .filter( - (model) => - model.provider !== "free-trial" || model.model.startsWith("gpt"), - ) - .map((m: ModelDescription) => { - if (m.provider === "free-trial") { - m.apiKey = key; - m.provider = "openai"; + // Set the role for the model + if (role) { + if (!config.experimental) { + config.experimental = {}; } - return m; + if (!config.experimental.modelRoles) { + config.experimental.modelRoles = {}; + } + config.experimental.modelRoles[role] = model.title; + } + + return config; + }, + (config) => { + if (config.models?.some((m: any) => m?.title === model.title)) { + model.title = `${model.title} (1)`; + } + + if (!config.models) { + config.models = []; + } + + config.models.push({ + name: model.title, + provider: model.provider, + model: model.model, + apiKey: model.apiKey, + apiBase: model.apiBase, + defaultCompletionOptions: model.completionOptions, }); - return config; - }); + return config; + }, + ); } export function deleteModel(title: string) { - editConfigJson((config) => { - config.models = config.models.filter((m: any) => m.title !== title); - return config; - }); + editConfigFile( + (config) => { + config.models = config.models.filter((m: any) => m.title !== title); + return config; + }, + (config) => { + config.models = config.models?.filter((m: any) => m.name !== title); + return config; + }, + ); } export function getModelByRole( diff --git a/core/config/validation.ts b/core/config/validation.ts index d28bb7809..a3bc40099 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -1,4 +1,5 @@ import { ConfigValidationError } from "@continuedev/config-yaml"; + import { ModelDescription, SerializedContinueConfig } from "../"; import { Telemetry } from "../util/posthog"; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index d946b4754..f2fefbb39 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -28,7 +28,6 @@ import CodebaseContextProvider from "../../context/providers/CodebaseContextProv import DocsContextProvider from "../../context/providers/DocsContextProvider"; import FileContextProvider from "../../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../../context/providers/index"; -import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider"; import { ControlPlaneClient } from "../../control-plane/client"; import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders"; import FreeTrial from "../../llm/llms/FreeTrial"; @@ -42,22 +41,31 @@ import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; +import { getControlPlaneEnvSync } from "../../control-plane/env"; import { llmsFromModelConfig } from "./models"; export class LocalPlatformClient implements PlatformClient { + constructor( + private orgScopeId: string | null, + private readonly client: ControlPlaneClient, + ) {} + async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { - return fqsns.map((fqsn) => { - return undefined; - }); + if (fqsns.length === 0) { + return []; + } + + const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId); + return response; } } async function loadConfigYaml( - workspaceConfigs: string[], rawYaml: string, overrideConfigYaml: AssistantUnrolled | undefined, - ide: IDE, controlPlaneClient: ControlPlaneClient, + orgScopeId: string | null, + ideSettings: IdeSettings, ): Promise> { let config = overrideConfigYaml ?? @@ -69,12 +77,18 @@ async function loadConfigYaml( versionSlug: "", }, rawYaml, - new RegistryClient(), + new RegistryClient( + await controlPlaneClient.getAccessToken(), + getControlPlaneEnvSync( + ideSettings.continueTestEnvironment, + ideSettings.enableControlServerBeta, + ).CONTROL_PLANE_URL, + ), { currentUserSlug: "", onPremProxyUrl: null, - orgScopeId: null, - platformClient: new LocalPlatformClient(), + orgScopeId, + platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient), renderSecrets: true, }, )); @@ -111,7 +125,8 @@ async function configYamlToContinueConfig( const continueConfig: ContinueConfig = { slashCommands: [], models: [], - tools: allTools, + tools: [...allTools], + mcpServerStatuses: [], systemMessage: config.rules?.join("\n"), experimental: { modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ @@ -206,7 +221,6 @@ async function configYamlToContinueConfig( continueConfig.systemMessage, ); - // if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { continueConfig.models.push(...llms); } @@ -244,7 +258,10 @@ async function configYamlToContinueConfig( } else { continueConfig.modelsByRole.embed.push( new embeddingsProviderClass( - options, + { + ...options, + title: options.name, + }, (url: string | URL, init: any) => fetchwithRequestOptions(url, init, { ...options.requestOptions, @@ -265,10 +282,15 @@ async function configYamlToContinueConfig( const rerankerClass = AllRerankers[provider]; if (rerankerClass) { continueConfig.modelsByRole.rerank.push( - new rerankerClass(options, (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), + new rerankerClass( + { + ...options, + title: options.name, + }, + (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), ), ); } else { @@ -334,7 +356,6 @@ async function configYamlToContinueConfig( const DEFAULT_CONTEXT_PROVIDERS = [ new FileContextProvider({}), new CodebaseContextProvider(codebaseContextParams), - new PromptFilesContextProvider({}), ]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( @@ -368,52 +389,19 @@ async function configYamlToContinueConfig( continueConfig.contextProviders.push(new DocsContextProvider({})); } - // Apply MCP if specified + // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - if (config.mcpServers) { - await mcpManager.removeUnusedConnections( - config.mcpServers.map((s) => s.name), - ); - } - - await Promise.allSettled( - config.mcpServers?.map(async (server) => { - const abortController = new AbortController(); - const mcpConnectionTimeout = setTimeout( - () => abortController.abort(), - 5000, - ); - - try { - const mcpId = server.name; - const mcpConnection = mcpManager.createConnection(mcpId, { - transport: { - type: "stdio", - args: [], - ...server, - }, - }); - - await mcpConnection.modifyConfig( - continueConfig, - mcpId, - abortController.signal, - server.name, - server.faviconUrl, - ); - } catch (e) { - let errorMessage = `Failed to load MCP server ${server.name}`; - if (e instanceof Error) { - errorMessage += ": " + e.message; - } - localErrors.push({ - fatal: false, - message: errorMessage, - }); - } finally { - clearTimeout(mcpConnectionTimeout); - } - }) ?? [], + mcpManager.setConnections( + (config.mcpServers ?? []).map((server) => ({ + id: server.name, + name: server.name, + transport: { + type: "stdio", + args: [], + ...server, + }, + })), + false, ); return { config: continueConfig, errors: localErrors }; @@ -421,7 +409,6 @@ async function configYamlToContinueConfig( export async function loadContinueConfigFromYaml( ide: IDE, - workspaceConfigs: string[], ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, @@ -431,6 +418,7 @@ export async function loadContinueConfigFromYaml( platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, configYamlPath: string | undefined, + orgScopeId: string | null, ): Promise> { const rawYaml = overrideConfigYaml === undefined @@ -441,11 +429,11 @@ export async function loadContinueConfigFromYaml( : ""; const configYamlResult = await loadConfigYaml( - workspaceConfigs, rawYaml, overrideConfigYaml, - ide, controlPlaneClient, + orgScopeId, + ideSettings, ); if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index ec6d3903a..7e77561bf 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -4,16 +4,23 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; -import { constructMcpSlashCommand } from "../../commands/slash/mcp"; -import { encodeMCPToolUri } from "../../tools/callTool"; -import MCPContextProvider from "../providers/MCPContextProvider"; +import { + MCPConnectionStatus, + MCPOptions, + MCPPrompt, + MCPResource, + MCPServerStatus, + MCPTool, +} from "../.."; export class MCPManagerSingleton { private static instance: MCPManagerSingleton; + public onConnectionsRefreshed?: () => void; private connections: Map = new Map(); + private abortController: AbortController = new AbortController(); + private constructor() {} public static getInstance(): MCPManagerSingleton { @@ -46,18 +53,90 @@ export class MCPManagerSingleton { this.connections.delete(id); } - async removeUnusedConnections(keepIds: string[]) { - const toRemove = Array.from(this.connections.keys()).filter( - (k) => !keepIds.includes(k), - ); - await Promise.all(toRemove.map((id) => this.removeConnection(id))); + setConnections(servers: MCPOptions[], forceRefresh: boolean) { + let refresh = false; + + // Remove any connections that are no longer in config + Array.from(this.connections.entries()).forEach(([id, connection]) => { + if (!servers.find((s) => s.id === id)) { + refresh = true; + connection.abortController.abort(); + void connection.client.close(); + this.connections.delete(id); + } + }); + + // Add any connections that are not yet in manager + servers.forEach((server) => { + if (!this.connections.has(server.id)) { + refresh = true; + this.connections.set(server.id, new MCPConnection(server)); + } + }); + + // NOTE the id is made by stringifying the options + if (refresh) { + void this.refreshConnections(forceRefresh); + } + } + + async refreshConnection(serverId: string) { + const connection = this.connections.get(serverId); + if (!connection) { + throw new Error(`MCP Connection ${serverId} not found`); + } + await connection.connectClient(true, this.abortController.signal); + if (this.onConnectionsRefreshed) { + this.onConnectionsRefreshed(); + } + } + + async refreshConnections(force: boolean) { + this.abortController.abort(); + this.abortController = new AbortController(); + await Promise.race([ + new Promise((resolve) => { + this.abortController.signal.addEventListener("abort", () => { + resolve(undefined); + }); + }), + (async () => { + await Promise.all( + Array.from(this.connections.values()).map(async (connection) => { + await connection.connectClient(force, this.abortController.signal); + }), + ); + if (this.onConnectionsRefreshed) { + this.onConnectionsRefreshed(); + } + })(), + ]); + } + + getStatuses(): (MCPServerStatus & { client: Client })[] { + return Array.from(this.connections.values()).map((connection) => ({ + ...connection.getStatus(), + client: connection.client, + })); } } +const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds + class MCPConnection { public client: Client; private transport: Transport; + private connectionPromise: Promise | null = null; + public abortController: AbortController; + + public status: MCPConnectionStatus = "not-connected"; + public errors: string[] = []; + + public prompts: MCPPrompt[] = []; + public tools: MCPTool[] = []; + public resources: MCPResource[] = []; + constructor(private readonly options: MCPOptions) { this.transport = this.constructTransport(options); @@ -70,6 +149,8 @@ class MCPConnection { capabilities: {}, }, ); + + this.abortController = new AbortController(); } private constructTransport(options: MCPOptions): Transport { @@ -95,131 +176,170 @@ class MCPConnection { } } - private isConnected: boolean = false; - private connectPromise: Promise | null = null; - - private async connectClient() { - if (this.isConnected) { - // Already connected - return; - } - - if (this.connectPromise) { - // Connection is already in progress; wait for it to complete - await this.connectPromise; - return; - } - - this.connectPromise = (async () => { - await this.client.connect(this.transport); - this.isConnected = true; - })(); - - try { - await this.connectPromise; - } finally { - // Reset the promise so future attempts can try again if necessary - this.connectPromise = null; - } + getStatus(): MCPServerStatus { + return { + ...this.options, + errors: this.errors, + prompts: this.prompts, + resources: this.resources, + tools: this.tools, + status: this.status, + }; } - async modifyConfig( - config: ContinueConfig, - mcpId: string, - signal: AbortSignal, - name: string, - faviconUrl: string | undefined, - ) { - try { - await Promise.race([ - this.connectClient(), - new Promise((_, reject) => { - signal.addEventListener("abort", () => - reject(new Error("Connection timed out")), - ); - }), - ]); - } catch (error) { - if (error instanceof Error) { - const msg = error.message.toLowerCase(); - if (msg.includes("spawn") && msg.includes("enoent")) { - const command = msg.split(" ")[1]; - throw new Error( - `command "${command}" not found. To use this MCP server, install the ${command} CLI.`, - ); - } else if ( - !error.message.startsWith("StdioClientTransport already started") - ) { - // don't throw error if it's just a "server already running" case - throw error; + async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) { + if (!forceRefresh) { + // Already connected + if (this.status === "connected") { + return; + } + + // Connection is already in progress; wait for it to complete + if (this.connectionPromise) { + await this.connectionPromise; + return; + } + } + + this.status = "connecting"; + this.tools = []; + this.prompts = []; + this.resources = []; + this.errors = []; + + this.abortController.abort(); + this.abortController = new AbortController(); + + this.connectionPromise = Promise.race([ + // If aborted by a refresh or other, cancel and don't do anything + new Promise((resolve) => { + externalSignal.addEventListener("abort", () => { + resolve(undefined); + }); + }), + new Promise((resolve) => { + this.abortController.signal.addEventListener("abort", () => { + resolve(undefined); + }); + }), + (async () => { + const timeoutController = new AbortController(); + const connectionTimeout = setTimeout( + () => timeoutController.abort(), + this.options.timeout ?? DEFAULT_MCP_TIMEOUT, + ); + + try { + await Promise.race([ + new Promise((_, reject) => { + timeoutController.signal.addEventListener("abort", () => { + reject(new Error("Connection timed out")); + }); + }), + (async () => { + this.transport = this.constructTransport(this.options); + try { + await this.client.connect(this.transport); + } catch (error) { + // Allow the case where for whatever reason is already connected + if ( + error instanceof Error && + error.message.startsWith( + "StdioClientTransport already started", + ) + ) { + await this.client.close(); + await this.client.connect(this.transport); + } else { + throw error; + } + } + + // TODO register server notification handlers + // this.client.transport?.onmessage(msg => console.log()) + // this.client.setNotificationHandler(, notification => { + // console.log(notification) + // }) + + const capabilities = this.client.getServerCapabilities(); + + // Resources <—> Context Provider + if (capabilities?.resources) { + try { + const { resources } = await this.client.listResources( + {}, + { signal: timeoutController.signal }, + ); + this.resources = resources; + } catch (e) { + let errorMessage = `Error loading resources for MCP Server ${this.options.name}`; + if (e instanceof Error) { + errorMessage += `: ${e.message}`; + } + this.errors.push(errorMessage); + } + } + + // Tools <—> Tools + if (capabilities?.tools) { + try { + const { tools } = await this.client.listTools( + {}, + { signal: timeoutController.signal }, + ); + this.tools = tools; + } catch (e) { + let errorMessage = `Error loading tools for MCP Server ${this.options.name}`; + if (e instanceof Error) { + errorMessage += `: ${e.message}`; + } + this.errors.push(errorMessage); + } + } + + // Prompts <—> Slash commands + if (capabilities?.prompts) { + try { + const { prompts } = await this.client.listPrompts( + {}, + { signal: timeoutController.signal }, + ); + this.prompts = prompts; + } catch (e) { + let errorMessage = `Error loading prompts for MCP Server ${this.options.name}`; + if (e instanceof Error) { + errorMessage += `: ${e.message}`; + } + this.errors.push(errorMessage); + } + } + + this.status = "connected"; + })(), + ]); + } catch (error) { + // Otherwise it's a connection error + let errorMessage = `Failed to connect to MCP server ${this.options.name}`; + if (error instanceof Error) { + const msg = error.message.toLowerCase(); + if (msg.includes("spawn") && msg.includes("enoent")) { + const command = msg.split(" ")[1]; + errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`; + } else { + errorMessage += ": " + error.message; + } + } + + this.status = "error"; + this.errors.push(errorMessage); + } finally { + this.connectionPromise = null; + clearTimeout(connectionTimeout); } - } else { - throw error; - } - } + })(), + ]); - const capabilities = this.client.getServerCapabilities(); - - // Resources <—> Context Provider - if (capabilities?.resources) { - const { resources } = await this.client.listResources({}, { signal }); - const submenuItems = resources.map((resource: any) => ({ - title: resource.name, - description: resource.description, - id: resource.uri, - icon: faviconUrl, - })); - - if (!config.contextProviders) { - config.contextProviders = []; - } - - config.contextProviders.push( - new MCPContextProvider({ - submenuItems, - mcpId, - }), - ); - } - - // Tools <—> Tools - if (capabilities?.tools) { - const { tools } = await this.client.listTools({}, { signal }); - const continueTools: Tool[] = tools.map((tool: any) => ({ - displayTitle: name + " " + tool.name, - function: { - description: tool.description, - name: tool.name, - parameters: tool.inputSchema, - }, - faviconUrl, - readonly: false, - type: "function", - wouldLikeTo: `use the ${name} ${tool.name} tool`, - uri: encodeMCPToolUri(mcpId, tool.name), - })); - - config.tools = [...continueTools, ...config.tools]; - } - - // Prompts <—> Slash commands - if (capabilities?.prompts) { - const { prompts } = await this.client.listPrompts({}, { signal }); - if (!config.slashCommands) { - config.slashCommands = []; - } - - const slashCommands: SlashCommand[] = prompts.map((prompt: any) => - constructMcpSlashCommand( - this.client, - prompt.name, - prompt.description, - prompt.arguments?.map((a: any) => a.name), - ), - ); - - config.slashCommands.push(...slashCommands); - } + await this.connectionPromise; } } diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 3b9fa0cf4..360e68670 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -9,7 +9,6 @@ import { LoadSubmenuItemsArgs, } from "../.."; import DocsService from "../../indexing/docs/DocsService"; -import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; import { INSTRUCTIONS_BASE_ITEM } from "./utils"; @@ -64,23 +63,12 @@ class DocsContextProvider extends BaseContextProvider { return chunksCopy; } - private _sortByPreIndexedDocs( + private _sortAlphabetically( submenuItems: ContextSubmenuItem[], ): ContextSubmenuItem[] { - // Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized + // Sort submenu items alphabetically by title return submenuItems.sort((a, b) => { - const aTitleInConfigs = a.metadata?.preIndexed ?? false; - const bTitleInConfigs = b.metadata?.preIndexed ?? false; - - // Primary criterion: Items not in configs come first - if (!aTitleInConfigs && bTitleInConfigs) { - return -1; - } else if (aTitleInConfigs && !bTitleInConfigs) { - return 1; - } else { - // Secondary criterion: Alphabetical order when both items are in the same category - return a.title.toString().localeCompare(b.title.toString()); - } + return a.title.toString().localeCompare(b.title.toString()); }); } @@ -165,13 +153,13 @@ class DocsContextProvider extends BaseContextProvider { } await docsService.isInitialized; - // Create map of docs url -> submenu item - const submenuItemsMap = new Map(); + // Create an array to hold submenu items + const submenuItems: ContextSubmenuItem[] = []; - // Add custom docs from config + // Get all indexed docs from the database const docs = (await docsService.listMetadata()) ?? []; for (const { startUrl, title, favicon } of docs) { - submenuItemsMap.set(startUrl, { + submenuItems.push({ title, id: startUrl, description: new URL(startUrl).hostname, @@ -179,32 +167,8 @@ class DocsContextProvider extends BaseContextProvider { }); } - // Add pre-indexed docs if supported - const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); - if (canUsePreindexedDocs) { - for (const { startUrl, title } of Object.values(preIndexedDocs)) { - // Skip if overridden in config - if (docs.find((d) => d.startUrl === startUrl)) { - continue; - } - submenuItemsMap.set(startUrl, { - title, - id: startUrl, - description: new URL(startUrl).hostname, - metadata: { - preIndexed: true, - }, - }); - } - } - - // Create array and sort if pre-indexed is supported - const submenuItems = Array.from(submenuItemsMap.values()); - if (canUsePreindexedDocs) { - return this._sortByPreIndexedDocs(submenuItems); - } - - return submenuItems; + // Sort alphabetically + return this._sortAlphabetically(submenuItems); } } diff --git a/core/context/providers/PromptFilesContextProvider.ts b/core/context/providers/PromptFilesContextProvider.ts deleted file mode 100644 index c3b4381f4..000000000 --- a/core/context/providers/PromptFilesContextProvider.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { BaseContextProvider } from ".."; -import { - ContextItem, - ContextProviderDescription, - ContextProviderExtras, - ContextSubmenuItem, - LoadSubmenuItemsArgs, -} from "../../"; -import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; -import { parsePreamble } from "../../promptFiles/v2/parse"; -import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile"; - -class PromptFilesContextProvider extends BaseContextProvider { - static description: ContextProviderDescription = { - title: "prompt-files", - displayTitle: "Prompt Files", - description: ".prompt files", - type: "submenu", - }; - - async getContextItems( - query: string, - extras: ContextProviderExtras, - ): Promise { - const rawContent = await extras.ide.readFile(query); - const preamble = parsePreamble(query, rawContent); - const [contextItems, body] = await renderPromptFileV2(rawContent, extras); - return [ - ...contextItems, - { - content: body, - name: preamble.name, - description: preamble.description, - }, - ]; - } - - async loadSubmenuItems( - args: LoadSubmenuItemsArgs, - ): Promise { - const promptFiles = await getAllPromptFiles( - args.ide, - args.config.experimental?.promptPath, - // Note, NOT checking v1 default folder here, deprecated for context provider - ); - return promptFiles.map((file) => { - const preamble = parsePreamble(file.path, file.content); - return { - id: file.path, - title: preamble.name, - description: preamble.description, - }; - }); - } -} - -export default PromptFilesContextProvider; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index dee4d7ef4..77a3dc108 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -5,6 +5,7 @@ import { FQSN, FullSlug, SecretResult, + SecretType, } from "@continuedev/config-yaml"; import fetch, { RequestInit, Response } from "node-fetch"; @@ -46,7 +47,14 @@ export class ControlPlaneClient { ): Promise<(SecretResult | undefined)[]> { const userId = await this.userId; if (!userId) { - throw new Error("No user id"); + return fqsns.map((fqsn) => ({ + found: false, + fqsn, + secretLocation: { + secretName: fqsn.secretName, + secretType: SecretType.NotFound, + }, + })); } const resp = await this.request("ide/sync-secrets", { diff --git a/core/core.ts b/core/core.ts index 629aa84ca..11fecffb2 100644 --- a/core/core.ts +++ b/core/core.ts @@ -10,7 +10,7 @@ import { setupLocalConfig, setupQuickstartConfig, } from "./config/onboarding"; -import { addContextProvider, addModel, deleteModel } from "./config/util"; +import { addModel, deleteModel } from "./config/util"; import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; @@ -22,7 +22,6 @@ import { DataLogger } from "./data/log"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; -import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -30,7 +29,7 @@ import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { editConfigJson, migrateV1DevDataFiles } from "./util/paths"; +import { editConfigFile, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -42,7 +41,9 @@ import { type IndexingProgressUpdate, } from "."; +import { ConfigYaml } from "@continuedev/config-yaml"; import { isLocalAssistantFile } from "./config/loadLocalAssistants"; +import { MCPManagerSingleton } from "./context/mcp"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; import { llmStreamChat } from "./llm/streamChat"; @@ -120,6 +121,13 @@ export class Core { this.messenger, ); + const mcpManager = MCPManagerSingleton.getInstance(); + mcpManager.onConnectionsRefreshed = async () => { + // This ensures that it triggers a NEW load after waiting for config promise to finish + await this.configHandler.loadConfig(); + await this.configHandler.reloadConfig(); + }; + this.configHandler.onConfigUpdate(async (result) => { const serializedResult = await this.configHandler.getSerializedConfig(); this.messenger.send("configUpdate", { @@ -311,10 +319,6 @@ export class Core { await this.configHandler.loadAssistantsForSelectedOrg(); }); - on("config/addContextProvider", async (msg) => { - addContextProvider(msg.data, this.configHandler); - }); - on("config/updateSharedConfig", async (msg) => { const newSharedConfig = this.globalContext.updateSharedConfig(msg.data); await this.configHandler.reloadConfig(); @@ -344,6 +348,9 @@ export class Core { return await this.configHandler.listOrganizations(); }); + on("mcp/reloadServer", async (msg) => { + mcpManager.refreshConnection(msg.data.id); + }); // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); @@ -597,38 +604,55 @@ export class Core { return; } - let editConfigJsonCallback: Parameters[0]; + let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; switch (mode) { case "Local": - editConfigJsonCallback = setupLocalConfig; + editConfigYamlCallback = setupLocalConfig; break; case "Quickstart": - editConfigJsonCallback = setupQuickstartConfig; + editConfigYamlCallback = setupQuickstartConfig; break; case "Best": - editConfigJsonCallback = setupBestConfig; + editConfigYamlCallback = setupBestConfig; break; default: console.error(`Invalid mode: ${mode}`); - editConfigJsonCallback = (config) => config; + editConfigYamlCallback = (config) => config; } - editConfigJson(editConfigJsonCallback); + editConfigFile((c) => c, editConfigYamlCallback); void this.configHandler.reloadConfig(); }); on("addAutocompleteModel", (msg) => { - editConfigJson((config) => { - return { + const model = msg.data.model; + editConfigFile( + (config) => { + return { + ...config, + tabAutocompleteModel: model, + }; + }, + (config) => ({ ...config, - tabAutocompleteModel: msg.data.model, - }; - }); + models: [ + ...(config.models ?? []), + { + name: model.title, + provider: model.provider, + model: model.model, + apiKey: model.apiKey, + roles: ["autocomplete"], + apiBase: model.apiBase, + }, + ], + }), + ); void this.configHandler.reloadConfig(); }); @@ -796,14 +820,6 @@ export class Core { // this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet } }); - on("docs/getSuggestedDocs", async (msg) => { - if (hasRequestedDocs) { - return; - } // TODO, remove, hack because of rerendering - hasRequestedDocs = true; - const suggestedDocs = await getAllSuggestedDocs(this.ide); - this.messenger.send("docs/suggestions", suggestedDocs); - }); on("docs/initStatuses", async (msg) => { void this.docsService.initStatuses(); }); @@ -977,5 +993,3 @@ export class Core { // private } - -let hasRequestedDocs = false; diff --git a/core/index.d.ts b/core/index.d.ts index 6926179bf..ba97377d3 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -43,13 +43,13 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: - | "loading" - | "indexing" - | "done" - | "failed" - | "paused" - | "disabled" - | "cancelled"; + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } @@ -236,7 +236,6 @@ export interface SiteIndexingConfig { maxDepth?: number; faviconUrl?: string; useLocalCrawling?: boolean; - rootUrl?: string; // Currently only used by preindexed docs } export interface DocsIndexingDetails { @@ -244,7 +243,6 @@ export interface DocsIndexingDetails { config: SiteIndexingConfig; indexingStatus: IndexingStatus | undefined; chunks: Chunk[]; - isPreIndexedDoc: boolean; } export interface IContextProvider { @@ -316,7 +314,12 @@ export interface CompletionOptions extends BaseCompletionOptions { model: string; } -export type ChatMessageRole = "user" | "assistant" | "thinking" | "system" | "tool"; +export type ChatMessageRole = + | "user" + | "assistant" + | "thinking" + | "system" + | "tool"; export type TextMessagePart = { type: "text"; @@ -434,7 +437,7 @@ export interface PromptLog { completion: string; } -export type MessageModes = "chat" | "edit"; +export type MessageModes = "chat" | "edit" | "agent"; export type ToolStatus = | "generating" @@ -692,10 +695,10 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; getLastFileSaveTimestamp?(): number; @@ -761,6 +764,7 @@ export interface ContinueSDK { export interface SlashCommand { name: string; description: string; + prompt?: string; params?: { [key: string]: any }; run: (sdk: ContinueSDK) => AsyncGenerator; } @@ -864,11 +868,7 @@ export interface ContextProviderWithParams { params: { [key: string]: any }; } -export interface SlashCommandDescription { - name: string; - description: string; - params?: { [key: string]: any }; -} +export type SlashCommandDescription = Omit; export interface CustomCommand { name: string; @@ -879,11 +879,11 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { @@ -903,10 +903,13 @@ export interface Tool { }; displayTitle: string; - wouldLikeTo: string; + wouldLikeTo?: string; + isCurrently?: string; + hasAlready?: string; readonly: boolean; uri?: string; faviconUrl?: string; + group: string; } interface ToolChoice { @@ -1042,8 +1045,54 @@ export interface SSEOptions { export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; export interface MCPOptions { + name: string; + id: string; transport: TransportOptions; faviconUrl?: string; + timeout?: number; +} + +export type MCPConnectionStatus = + | "connecting" + | "connected" + | "error" + | "not-connected"; + +export interface MCPPrompt { + name: string; + description?: string; + arguments?: { + name: string; + description?: string; + required?: boolean; + }[]; +} + +// Leaving here to ideate on +// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub" + +export interface MCPResource { + name: string; + uri: string; + description?: string; + mimeType?: string; +} +export interface MCPTool { + name: string; + description?: string; + inputSchema: { + type: "object"; + properties?: Record; + }; +} + +export interface MCPServerStatus extends MCPOptions { + status: MCPConnectionStatus; + errors: string[]; + + prompts: MCPPrompt[]; + tools: MCPTool[]; + resources: MCPResource[]; } export interface ContinueUIConfig { @@ -1069,6 +1118,11 @@ export interface ExperimentalModelRoles { applyCodeBlock?: string; } +export interface ExperimentalMCPOptions { + transport: TransportOptions; + faviconUrl?: string; +} + export type EditStatus = | "not-started" | "streaming" @@ -1152,7 +1206,7 @@ export interface ExperimentalConfig { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - modelContextProtocolServers?: MCPOptions[]; + modelContextProtocolServers?: ExperimentalMCPOptions[]; } export interface AnalyticsConfig { @@ -1223,9 +1277,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1246,8 +1300,8 @@ export interface ContinueConfig { systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; - slashCommands?: SlashCommand[]; - contextProviders?: IContextProvider[]; + slashCommands: SlashCommand[]; + contextProviders: IContextProvider[]; disableSessionTitles?: boolean; disableIndexing?: boolean; userToken?: string; @@ -1257,6 +1311,7 @@ export interface ContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + mcpServerStatuses: MCPServerStatus[]; rules?: string[]; modelsByRole: Record; selectedModelByRole: Record; @@ -1269,8 +1324,8 @@ export interface BrowserSerializedContinueConfig { systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; - slashCommands?: SlashCommandDescription[]; - contextProviders?: ContextProviderDescription[]; + slashCommands: SlashCommandDescription[]; + contextProviders: ContextProviderDescription[]; disableIndexing?: boolean; disableSessionTitles?: boolean; userToken?: string; @@ -1279,6 +1334,7 @@ export interface BrowserSerializedContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + mcpServerStatuses: MCPServerStatus[]; rules?: string[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; @@ -1319,9 +1375,9 @@ export type PackageDetailsSuccess = PackageDetails & { export type PackageDocsResult = { packageInfo: ParsedPackageInfo; } & ( - | { error: string; details?: never } - | { details: PackageDetailsSuccess; error?: never } - ); + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } +); export interface TerminalOptions { reuseTerminal?: boolean; diff --git a/core/indexing/docs/DocsCache.test.ts b/core/indexing/docs/DocsCache.test.ts new file mode 100644 index 000000000..341cd0229 --- /dev/null +++ b/core/indexing/docs/DocsCache.test.ts @@ -0,0 +1,25 @@ +import OpenAI from "../../llm/llms/OpenAI"; +import { DocsCache } from "./DocsCache"; // adjust import path as needed + +describe("DocsCache", () => { + let openAIEmbeddings: OpenAI; + + beforeAll(() => { + openAIEmbeddings = new OpenAI({ + apiKey: "", + model: "text-embedding-ada-002", + }); + }); + + test("normalizeEmbeddingId() produces a valid ID without constructor name", async () => { + // Get the embedding ID from OpenAI embeddings provider + const embeddingId = DocsCache.normalizeEmbeddingId( + openAIEmbeddings.embeddingId, + ); + + // The ID should not contain the constructor name (OpenAI) + expect(embeddingId).toEqual( + `${openAIEmbeddings.model}::${openAIEmbeddings.maxEmbeddingChunkSize}`, + ); + }); +}); diff --git a/core/indexing/docs/DocsCache.ts b/core/indexing/docs/DocsCache.ts new file mode 100644 index 000000000..f250b797c --- /dev/null +++ b/core/indexing/docs/DocsCache.ts @@ -0,0 +1,83 @@ +import request from "request"; +import { Chunk } from "../.."; + +export interface SiteIndexingResults { + chunks: (Chunk & { embedding: number[] })[]; + url: string; + title: string; +} + +export class DocsCache { + static readonly AWS_REGION: string = "us-west-1"; + static readonly BUCKET_NAME: string = "continue-preindexed-docs"; + + /** + * Normalizes an embedding ID by stripping the constructor name part. + * This is done because we don't care about the provider, just the + * model and the max embedding chunk size. + */ + static normalizeEmbeddingId(embeddingId: string): string { + // Split by "::" and remove the first part (constructor name) + const parts = embeddingId.split("::"); + if (parts.length <= 1) return embeddingId; // Return original if no "::" found + + // Return everything except the first part, joining with "::" + return parts.slice(1).join("::"); + } + + /** + * Gets the filepath for a given embedding ID and URL + */ + static getFilepathForEmbeddingIdAndUrl( + embeddingId: string, + url: string, + ): string { + const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId); + const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_")); + return normalizedEmbeddingId + "/" + normalizedUrl; + } + + /** + * Gets the fully qualified S3 URL for a given filepath + */ + private static getS3Url(filepath: string): string { + const pathname = filepath.split("/").map(encodeURIComponent).join("/"); + return `https://${this.BUCKET_NAME}.s3.${this.AWS_REGION}.amazonaws.com/${pathname}`; + } + + /** + * Downloads cached site indexing results from S3 for a given embedding ID and URL + * @param embeddingId The embedding ID + * @param url The URL of the document + * @returns The downloaded data as a string + */ + static async getDocsCacheForUrl( + embeddingId: string, + url: string, + ): Promise { + const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl( + embeddingId, + url, + ); + + return new Promise((resolve, reject) => { + let data = ""; + const url = this.getS3Url(filepath); + const download = request({ + url, + }); + + download.on("response", (response: any) => { + if (response.statusCode !== 200) { + reject( + new Error("There was an error retrieving the pre-indexed doc"), + ); + } + }); + + download.on("error", (err: any) => reject(err)); + download.on("data", (chunk: any) => (data += chunk)); + download.on("end", () => resolve(data)); + }); + } +} diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 682b76a23..6021fc260 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -1,156 +1,156 @@ -/** - * @jest-environment jsdom - */ -import { ConfigHandler } from "../../config/ConfigHandler.js"; -import { SiteIndexingConfig } from "../../index.js"; -import FileSystemIde from "../../util/filesystem.js"; -import { editConfigJson } from "../../util/paths.js"; +// /** +// * @jest-environment jsdom +// */ +// import { ConfigHandler } from "../../config/ConfigHandler.js"; +// import { SiteIndexingConfig } from "../../index.js"; +// import FileSystemIde from "../../util/filesystem.js"; +// import { editConfigJson } from "../../util/paths.js"; -import DocsService from "./DocsService.js"; -import preIndexedDocs from "./preIndexedDocs.js"; +// import DocsService from "./DocsService.js"; +// import preIndexedDocs from "./preIndexedDocs.js"; -describe.skip("DocsService Integration Tests", () => { - let ide: FileSystemIde; - let configHandler: ConfigHandler; - let docsService: DocsService; +// describe.skip("DocsService Integration Tests", () => { +// let ide: FileSystemIde; +// let configHandler: ConfigHandler; +// let docsService: DocsService; - const mockSiteConfig: SiteIndexingConfig = { - startUrl: "https://amplified.dev/", - title: "Test repo", - faviconUrl: "https://github.com/favicon.ico", - }; +// const mockSiteConfig: SiteIndexingConfig = { +// startUrl: "https://amplified.dev/", +// title: "Test repo", +// faviconUrl: "https://github.com/favicon.ico", +// }; - /** - * We need to reload config explicitly to handle the scenario where the - * config file update listeners are not called before we attempt to - * use the new config - */ - async function getReloadedConfig() { - await configHandler.reloadConfig(); - const latestConfig = await configHandler.loadConfig(); +// /** +// * We need to reload config explicitly to handle the scenario where the +// * config file update listeners are not called before we attempt to +// * use the new config +// */ +// async function getReloadedConfig() { +// await configHandler.reloadConfig(); +// const latestConfig = await configHandler.loadConfig(); - return latestConfig; - } +// return latestConfig; +// } - beforeEach(async () => { - ide = new FileSystemIde(process.cwd()); +// beforeEach(async () => { +// ide = new FileSystemIde(process.cwd()); - const ideSettingsPromise = Promise.resolve({ - remoteConfigSyncPeriod: 60, - userToken: "", - enableControlServerBeta: false, - continueTestEnvironment: "none" as const, - pauseCodebaseIndexOnStart: false, - ideSettings: {} as any, - enableDebugLogs: false, - remoteConfigServerUrl: "", - }); - configHandler = new ConfigHandler( - ide, - ideSettingsPromise, - async () => {}, - Promise.resolve(undefined), - ); +// const ideSettingsPromise = Promise.resolve({ +// remoteConfigSyncPeriod: 60, +// userToken: "", +// enableControlServerBeta: false, +// continueTestEnvironment: "none" as const, +// pauseCodebaseIndexOnStart: false, +// ideSettings: {} as any, +// enableDebugLogs: false, +// remoteConfigServerUrl: "", +// }); +// configHandler = new ConfigHandler( +// ide, +// ideSettingsPromise, +// async () => {}, +// Promise.resolve(undefined), +// ); - docsService = DocsService.createSingleton(configHandler, ide); +// docsService = DocsService.createSingleton(configHandler, ide); - await docsService.isInitialized; - }); +// await docsService.isInitialized; +// }); - test("Indexing, retrieval, and deletion of a new documentation site", async () => { - await docsService.indexAndAdd(mockSiteConfig); +// test("Indexing, retrieval, and deletion of a new documentation site", async () => { +// await docsService.indexAndAdd(mockSiteConfig); - let latestConfig = await getReloadedConfig(); +// let latestConfig = await getReloadedConfig(); - // Sqlite check - expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); +// // Sqlite check +// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); - // config.json check - expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig); +// // config.json check +// expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig); - // Lance DB check - let retrievedChunks = await docsService.retrieveChunksFromQuery( - "test", - mockSiteConfig.startUrl, - 5, - ); +// // Lance DB check +// let retrievedChunks = await docsService.retrieveChunksFromQuery( +// "test", +// mockSiteConfig.startUrl, +// 5, +// ); - expect(retrievedChunks.length).toBeGreaterThan(0); +// expect(retrievedChunks.length).toBeGreaterThan(0); - await docsService.delete(mockSiteConfig.startUrl); +// await docsService.delete(mockSiteConfig.startUrl); - // Sqlite check - expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); +// // Sqlite check +// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); - // config.json check - latestConfig = await getReloadedConfig(); - expect(latestConfig.config!.docs).not.toContainEqual( - expect.objectContaining(mockSiteConfig), - ); +// // config.json check +// latestConfig = await getReloadedConfig(); +// expect(latestConfig.config!.docs).not.toContainEqual( +// expect.objectContaining(mockSiteConfig), +// ); - // LanceDB check - retrievedChunks = await docsService.retrieveChunksFromQuery( - "test", - mockSiteConfig.startUrl, - 5, - ); - expect(retrievedChunks.length).toBe(0); - }); +// // LanceDB check +// retrievedChunks = await docsService.retrieveChunksFromQuery( +// "test", +// mockSiteConfig.startUrl, +// 5, +// ); +// expect(retrievedChunks.length).toBe(0); +// }); - // test("Reindexes when changing embeddings provider", async () => { - // const originalEmbeddingsProvider = - // await docsService.getEmbeddingsProvider(); +// // test("Reindexes when changing embeddings provider", async () => { +// // const originalEmbeddingsProvider = +// // await docsService.getEmbeddingsProvider(); - // // Change embeddings provider - // editConfigJson((config) => ({ - // ...config, - // embeddingsProvider: { - // provider: FreeTrial.providerName, - // }, - // })); +// // // Change embeddings provider +// // editConfigJson((config) => ({ +// // ...config, +// // embeddingsProvider: { +// // provider: FreeTrial.providerName, +// // }, +// // })); - // await getReloadedConfig(); +// // await getReloadedConfig(); - // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider(); +// // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider(); - // // Verify reindexing - // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]); - // const [newMockVector] = await provider.embed(["test"]); +// // // Verify reindexing +// // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]); +// // const [newMockVector] = await provider.embed(["test"]); - // expect(originalVector).not.toEqual(newMockVector); - // }); +// // expect(originalVector).not.toEqual(newMockVector); +// // }); - test("Handles pulling down and adding pre-indexed docs", async () => { - const preIndexedDoc = Object.values(preIndexedDocs)[0]; - await docsService.indexAndAdd(preIndexedDoc); - }); +// test("Handles pulling down and adding pre-indexed docs", async () => { +// const preIndexedDoc = Object.values(preIndexedDocs)[0]; +// await docsService.indexAndAdd(preIndexedDoc); +// }); - test("Config synchronization with SQLite", async () => { - await docsService.indexAndAdd(mockSiteConfig); +// test("Config synchronization with SQLite", async () => { +// await docsService.indexAndAdd(mockSiteConfig); - await getReloadedConfig(); +// await getReloadedConfig(); - expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); +// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); - editConfigJson((config) => { - const { docs, ...restConfig } = config; - return restConfig; - }); +// editConfigJson((config) => { +// const { docs, ...restConfig } = config; +// return restConfig; +// }); - await getReloadedConfig(); +// await getReloadedConfig(); - const startTime = Date.now(); - const maxWaitTimeMs = 10_000; +// const startTime = Date.now(); +// const maxWaitTimeMs = 10_000; - while (docsService.isSyncing) { - if (Date.now() - startTime > maxWaitTimeMs) { - throw new Error( - `Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`, - ); - } - await new Promise((resolve) => setTimeout(resolve, 100)); - } +// while (docsService.isSyncing) { +// if (Date.now() - startTime > maxWaitTimeMs) { +// throw new Error( +// `Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`, +// ); +// } +// await new Promise((resolve) => setTimeout(resolve, 100)); +// } - expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); - }); -}); +// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); +// }); +// }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 75f92b145..99dc1d539 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -13,18 +13,15 @@ import { SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; -import { - addContextProvider, - isSupportedLanceDbCpuTargetForLinux, -} from "../../config/util"; +import { isSupportedLanceDbCpuTargetForLinux } from "../../config/util"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { IMessenger } from "../../protocol/messenger"; -import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; +import { fetchFavicon } from "../../util/fetchFavicon"; import { GlobalContext } from "../../util/GlobalContext"; import { - editConfigJson, + editConfigFile, getDocsSqlitePath, getLanceDbPath, } from "../../util/paths"; @@ -37,15 +34,9 @@ import { } from "./article"; import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; -import { - downloadFromS3, - getS3Filename, - S3Buckets, - SiteIndexingResults, -} from "./preIndexed"; -import preIndexedDocs from "./preIndexedDocs"; import type * as LanceType from "vectordb"; +import { DocsCache, SiteIndexingResults } from "./DocsCache"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -89,8 +80,7 @@ export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; - static preIndexedDocsEmbeddingsProvider = - new TransformersJsEmbeddingsProvider(); + static defaultEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); public isInitialized: Promise; public isSyncing: boolean = false; @@ -250,12 +240,8 @@ export default class DocsService { return false; } - /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers. - * However, we don't ship transformers with the JetBrains extension. - * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. - */ - async canUsePreindexedDocs() { + // Determine if transformers.js embeddings are supported in this environment + async canUseTransformersEmbeddings() { const ideInfo = await this.ideInfoPromise; if (ideInfo.ideType === "jetbrains") { return false; @@ -263,28 +249,26 @@ export default class DocsService { return true; } - // Determines if using preIndexed and returns proper embeddings provider - async getEmbeddingsProvider(startUrl: string) { - // Conditions for using a pre-indexed doc - - // Must be in pre indexed docs file - const preIndexedDoc = preIndexedDocs[startUrl]; - if (preIndexedDoc) { - // Most not be overriden by config - if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) { - // Must be supported - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - if (canUsePreindexedDocs) { - return { - provider: DocsService.preIndexedDocsEmbeddingsProvider, - isPreindexed: true, - }; - } - } + // Get the appropriate embeddings provider + async getEmbeddingsProvider() { + // First check if there's a config selected embeddings provider + if (this.config.selectedModelByRole.embed) { + return { + provider: this.config.selectedModelByRole.embed, + }; } + + // Fall back to transformers if supported + const canUseTransformers = await this.canUseTransformersEmbeddings(); + if (canUseTransformers) { + return { + provider: DocsService.defaultEmbeddingsProvider, + }; + } + + // No provider available return { - provider: this.config.selectedModelByRole.embed, - isPreindexed: false, + provider: undefined, }; } @@ -312,29 +296,6 @@ export default class DocsService { } async syncDocsWithPrompt(reIndex: boolean = false) { - if (!this.hasDocsContextProvider()) { - const actionMsg = "Add 'docs' context provider"; - const res = await this.ide.showToast( - "info", - "Starting docs indexing", - actionMsg, - ); - - if (res === actionMsg) { - addContextProvider({ - name: DocsContextProvider.description.title, - params: {}, - }); - - void this.ide.showToast( - "info", - "Successfuly added docs context provider", - ); - } else { - return; - } - } - await this.syncDocs(undefined, this.config, reIndex); void this.ide.showToast("info", "Docs indexing completed"); @@ -379,6 +340,45 @@ export default class DocsService { } } + /** + * Attempt to load document embeddings from cache + * @returns true if cache was successfully loaded, false otherwise + */ + private async tryLoadFromCache( + startUrl: string, + embeddingId: string, + siteIndexingConfig: SiteIndexingConfig, + ): Promise { + try { + const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId); + + if (cacheHit) { + console.log(`Successfully loaded cached embeddings for ${startUrl}`); + // Update status to complete + this.handleStatusUpdate({ + type: "docs", + id: startUrl, + embeddingsProviderId: embeddingId, + isReindexing: false, + title: siteIndexingConfig.title, + debugInfo: "Loaded from cache", + icon: siteIndexingConfig.faviconUrl, + url: startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); + + return true; + } + } catch (e) { + console.log(`Error trying to fetch from cache: ${e}`); + // Continue with regular indexing + } + + return false; + } + async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, forceReindex: boolean = false, @@ -392,21 +392,28 @@ export default class DocsService { return; } - const { isPreindexed, provider } = - await this.getEmbeddingsProvider(startUrl); - if (isPreindexed) { - console.warn("Attempted to indexAndAdd pre-indexed doc"); - return; - } + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { console.warn("@docs indexAndAdd: no embeddings provider found"); return; } + // Try to fetch from cache first before crawling + if (!forceReindex) { + const cacheLoaded = await this.tryLoadFromCache( + startUrl, + provider.embeddingId, + siteIndexingConfig, + ); + + if (cacheLoaded) { + return; + } + } + const startedWithEmbedder = provider.embeddingId; // Check if doc has been successfully indexed with the given embedder - // Note at this point we know it's not a pre-indexed doc const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values @@ -622,7 +629,7 @@ export default class DocsService { progress: 1, }); - void this.ide.showToast("info", `Failed to index ${startUrl}`); + // void this.ide.showToast("info", `Failed to index ${startUrl}`); markFailedInGlobalContext(); return; } @@ -672,7 +679,12 @@ export default class DocsService { progress: 1, }); - void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + // Only show notificaitons if the user manually re-indexed, otherwise + // they are too noisy, especially when switching embeddings providers + // and we automatically re-index all docs + if (forceReindex) { + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + } this.messenger?.send("refreshSubmenuItems", { providers: ["docs"], @@ -705,36 +717,42 @@ export default class DocsService { } } - // When user requests a pre-indexed doc for the first time - // And pre-indexed embeddings are supported - // Fetch pre-indexed embeddings from S3, add to Lance, and then search those - private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const data = await downloadFromS3( - S3Buckets.continueIndexedDocs, - getS3Filename( - DocsService.preIndexedDocsEmbeddingsProvider.embeddingId, - title, - ), - ); + /** + * Try to fetch embeddings from the S3 cache for any document URL + * @param startUrl The URL of the documentation site + * @param embeddingsProviderId The ID of the embeddings provider + * @returns True if cache hit and successfully loaded, false otherwise + */ + private async tryFetchFromCache( + startUrl: string, + embeddingId: string, + ): Promise { + try { + const data = await DocsCache.getDocsCacheForUrl(embeddingId, startUrl); - const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const startUrl = new URL(siteEmbeddings.url).toString(); + // Parse the cached data + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const faviconUrl = preIndexedDocs[startUrl].faviconUrl; - const favicon = - typeof faviconUrl === "string" - ? await getFaviconBase64(faviconUrl) - : undefined; + // Try to get a favicon for the site + const favicon = await fetchFavicon(new URL(startUrl)); - await this.add({ - favicon, - siteIndexingConfig: { - startUrl, - title: siteEmbeddings.title, - }, - chunks: siteEmbeddings.chunks, - embeddings: siteEmbeddings.chunks.map((c) => c.embedding), - }); + // Add the cached embeddings to our database + await this.add({ + favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title || new URL(startUrl).hostname, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), + }); + + return true; + } catch (e) { + // Cache miss or error - silently fail + console.log(`Cache miss for ${startUrl} with provider ${embeddingId}`); + return false; + } } // Retrieve docs embeds based on user input @@ -743,8 +761,7 @@ export default class DocsService { startUrl: string, nRetrieve: number, ) { - const { isPreindexed, provider } = - await this.getEmbeddingsProvider(startUrl); + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { void this.ide.showToast( @@ -755,15 +772,11 @@ export default class DocsService { return []; } - if (isPreindexed) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDocs[startUrl]!["title"], - }); - } - + // Try to get embeddings for the query const [vector] = await provider.embed([query]); - return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed); + // Retrieve chunks using the query vector + return await this.retrieveChunks(startUrl, vector, nRetrieve); } private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk { @@ -783,8 +796,7 @@ export default class DocsService { const db = await this.getOrCreateSqliteDb(); try { - const { isPreindexed, provider } = - await this.getEmbeddingsProvider(startUrl); + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { throw new Error("No embeddings model set"); @@ -819,22 +831,26 @@ export default class DocsService { config: siteIndexingConfig, indexingStatus: this.statuses.get(startUrl), chunks: rows.map(this.lanceDBRowToChunk), - isPreIndexedDoc: isPreindexed, }; } catch (e) { console.warn("Error getting details", e); throw e; } } - // This is split into its own function so that it can be recursive - // in the case of fetching preindexed docs from s3 + // This function attempts to retrieve chunks by vector similarity + // It will also attempt to fetch from cache if no results are found async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, - isPreindexed: boolean, isRetry: boolean = false, ): Promise { + // Get the appropriate embeddings provider + const { provider } = await this.getEmbeddingsProvider(); + if (!provider) { + return []; + } + // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name const table = await this.getOrCreateLanceTable({ initializationVector: vector, @@ -852,15 +868,22 @@ export default class DocsService { console.warn("Error retrieving chunks from LanceDB", e); } - // No docs are found for preindexed? try fetching once - if (docs.length === 0 && isPreindexed) { - if (isRetry) { - return []; + // If no docs are found and this isn't a retry, try fetching from cache + if (docs.length === 0 && !isRetry) { + try { + // Try to fetch the document from the S3 cache + const cacheHit = await this.tryFetchFromCache( + startUrl, + provider.embeddingId, + ); + + if (cacheHit) { + // If cache hit, retry the search once + return await this.retrieveChunks(startUrl, vector, nRetrieve, true); + } + } catch (e) { + console.warn("Error trying to fetch from cache:", e); } - await this.fetchAndAddPreIndexedDocEmbeddings( - preIndexedDocs[startUrl]!["title"], - ); - return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true); } return docs.map(this.lanceDBRowToChunk); @@ -912,10 +935,9 @@ export default class DocsService { return result.favicon; } - /* - Sync with no embeddings provider change - Ignores pre-indexed docs - */ + /** + * Sync with no embeddings provider change + */ private async syncDocs( oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, @@ -933,11 +955,9 @@ export default class DocsService { const currentlyIndexedDocs = await this.listMetadata(); const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); - // Anything found in sqlite but not in new config should be deleted if not preindexed + // Anything found in sqlite but not in new config should be deleted const deletedDocs = currentlyIndexedDocs.filter( - (doc) => - !preIndexedDocs[doc.startUrl] && - !newConfigStartUrls.includes(doc.startUrl), + (doc) => !newConfigStartUrls.includes(doc.startUrl), ); // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed @@ -1063,7 +1083,7 @@ export default class DocsService { const conn = await lance.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); - const { provider } = await this.getEmbeddingsProvider(startUrl); + const { provider } = await this.getEmbeddingsProvider(); if (!provider) { throw new Error( @@ -1164,15 +1184,30 @@ export default class DocsService { ); if (!doesEquivalentDocExist) { - editConfigJson((config) => ({ - ...config, - docs: [ - ...(config.docs?.filter( - (doc) => doc.startUrl !== siteIndexingConfig.startUrl, - ) ?? []), - siteIndexingConfig, - ], - })); + editConfigFile( + (config) => ({ + ...config, + docs: [ + ...(config.docs?.filter( + (doc) => doc.startUrl !== siteIndexingConfig.startUrl, + ) ?? []), + siteIndexingConfig, + ], + }), + (config) => ({ + ...config, + docs: [ + ...(config.docs?.filter( + (doc) => (doc as any).startUrl !== siteIndexingConfig.startUrl, + ) ?? []), + { + name: siteIndexingConfig.title, + faviconUrl: siteIndexingConfig.faviconUrl, + startUrl: siteIndexingConfig.startUrl, + }, + ], + }), + ); } } @@ -1216,10 +1251,19 @@ export default class DocsService { (doc) => doc.startUrl === startUrl, ); if (doesDocExist) { - editConfigJson((config) => ({ - ...config, - docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], - })); + editConfigFile( + (config) => ({ + ...config, + docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], + }), + (config) => ({ + ...config, + docs: + config.docs?.filter( + (doc) => "startUrl" in doc && doc.startUrl !== startUrl, + ) || [], + }), + ); } } diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts index ef9b528ce..03fc44212 100644 --- a/core/indexing/docs/crawlers/ChromiumCrawler.ts +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -9,7 +9,7 @@ import PCR from "puppeteer-chromium-resolver"; import { ContinueConfig, IDE } from "../../.."; import { - editConfigJson, + editConfigFile, getChromiumPath, getContinueUtilsPath, } from "../../../util/paths"; @@ -26,13 +26,16 @@ export class ChromiumCrawler { ) {} static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { - editConfigJson((config) => ({ - ...config, - experimental: { - ...config.experimental, - useChromiumForDocsCrawling, - }, - })); + editConfigFile( + (config) => ({ + ...config, + experimental: { + ...config.experimental, + useChromiumForDocsCrawling, + }, + }), + (config) => config, // Not used in config.yaml + ); } async *crawl(): AsyncGenerator { diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index 64e313175..b9d5fbcf8 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -1,7 +1,7 @@ import { type Database } from "sqlite"; import { type Table } from "vectordb"; -import { editConfigJson, migrate } from "../../util/paths.js"; +import { editConfigFile, migrate } from "../../util/paths.js"; import DocsService, { SqliteDocsRow } from "./DocsService.js"; @@ -58,10 +58,22 @@ export async function runSqliteMigrations(db: Database) { const sqliteDocs = await db.all< Array> >(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`); - editConfigJson((config) => ({ - ...config, - docs: [...(config.docs || []), ...sqliteDocs], - })); + editConfigFile( + (config) => ({ + ...config, + docs: [...(config.docs || []), ...sqliteDocs], + }), + (config) => ({ + ...config, + docs: [ + ...(config.docs || []), + ...sqliteDocs.map((doc) => ({ + name: doc.title, + startUrl: doc.startUrl, + })), + ], + }), + ); } } finally { resolve(undefined); diff --git a/core/indexing/docs/preIndexed.ts b/core/indexing/docs/preIndexed.ts deleted file mode 100644 index b66d21e70..000000000 --- a/core/indexing/docs/preIndexed.ts +++ /dev/null @@ -1,52 +0,0 @@ -import request from "request"; - -import { Chunk } from "../../"; - -export function getS3Filename( - embeddingsProviderId: string, - title: string, -): string { - return `_TransformersJsEmbeddingsProvider::all-MiniLM-L6-v2/${title}`; -} - -export enum S3Buckets { - continueIndexedDocs = "continue-indexed-docs", -} - -const AWS_REGION = "us-west-1"; - -export async function downloadFromS3( - bucket: string, - fileName: string, -): Promise { - return new Promise((resolve, reject) => { - let data = ""; - - const download = request({ - url: `https://${bucket}.s3.${AWS_REGION}.amazonaws.com/${fileName}`, - }); - download.on("response", (response: any) => { - if (response.statusCode !== 200) { - reject(new Error("There was an error retreiving the pre-indexed doc")); - } - }); - - download.on("error", (err: any) => { - reject(err); - }); - - download.on("data", (chunk: any) => { - data += chunk; - }); - - download.on("end", () => { - resolve(data); - }); - }); -} - -export interface SiteIndexingResults { - chunks: (Chunk & { embedding: number[] })[]; - url: string; - title: string; -} diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts deleted file mode 100644 index 5342396fd..000000000 --- a/core/indexing/docs/preIndexedDocs.ts +++ /dev/null @@ -1,368 +0,0 @@ -import { SiteIndexingConfig } from "../../"; - -const preIndexedDocs: Record< - SiteIndexingConfig["startUrl"], - SiteIndexingConfig -> = { - "https://jinja.palletsprojects.com/en/3.1.x/": { - title: "Jinja", - startUrl: "https://jinja.palletsprojects.com/en/3.1.x/", - rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/", - faviconUrl: "https://jinja.palletsprojects.com/favicon.ico", - }, - "https://react.dev/reference/": { - title: "React", - startUrl: "https://react.dev/reference/", - rootUrl: "https://react.dev/reference/", - faviconUrl: "https://react.dev/favicon.ico", - }, - "https://posthog.com/docs": { - title: "PostHog", - startUrl: "https://posthog.com/docs", - rootUrl: "https://posthog.com/docs", - faviconUrl: "https://posthog.com/favicon.ico", - }, - "https://expressjs.com/en/5x/api.html": { - title: "Express", - startUrl: "https://expressjs.com/en/5x/api.html", - rootUrl: "https://expressjs.com/en/5x/", - faviconUrl: "https://expressjs.com/favicon.ico", - }, - "https://platform.openai.com/docs/": { - title: "OpenAI", - startUrl: "https://platform.openai.com/docs/", - rootUrl: "https://platform.openai.com/docs/", - faviconUrl: "https://platform.openai.com/favicon.ico", - }, - "https://www.prisma.io/docs": { - title: "Prisma", - startUrl: "https://www.prisma.io/docs", - rootUrl: "https://www.prisma.io/docs", - faviconUrl: "https://www.prisma.io/favicon.ico", - }, - "https://boto3.amazonaws.com/v1/documentation/api/latest/index.html": { - title: "Boto3", - startUrl: - "https://boto3.amazonaws.com/v1/documentation/api/latest/index.html", - rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/", - faviconUrl: "https://boto3.amazonaws.com/favicon.ico", - }, - "https://pytorch.org/docs/stable/": { - title: "Pytorch", - startUrl: "https://pytorch.org/docs/stable/", - rootUrl: "https://pytorch.org/docs/stable/", - faviconUrl: "https://pytorch.org/favicon.ico", - }, - "https://redis.io/docs/": { - title: "Redis", - startUrl: "https://redis.io/docs/", - rootUrl: "https://redis.io/docs/", - faviconUrl: "https://redis.io/favicon.ico", - }, - "https://axios-http.com/docs/intro": { - title: "Axios", - startUrl: "https://axios-http.com/docs/intro", - rootUrl: "https://axios-http.com/docs", - faviconUrl: "https://axios-http.com/favicon.ico", - }, - "https://redwoodjs.com/docs/introduction": { - title: "Redwood JS", - startUrl: "https://redwoodjs.com/docs/introduction", - rootUrl: "https://redwoodjs.com/docs", - faviconUrl: "https://redwoodjs.com/favicon.ico", - }, - "https://graphql.org/learn/": { - title: "GraphQL", - startUrl: "https://graphql.org/learn/", - rootUrl: "https://graphql.org/learn/", - faviconUrl: "https://graphql.org/favicon.ico", - }, - "https://www.typescriptlang.org/docs/": { - title: "Typescript", - startUrl: "https://www.typescriptlang.org/docs/", - rootUrl: "https://www.typescriptlang.org/docs/", - faviconUrl: "https://www.typescriptlang.org/favicon.ico", - }, - "https://jestjs.io/docs/getting-started": { - title: "Jest", - startUrl: "https://jestjs.io/docs/getting-started", - rootUrl: "https://jestjs.io/docs", - faviconUrl: "https://jestjs.io/favicon.ico", - }, - "https://tailwindcss.com/docs/installation": { - title: "Tailwind CSS", - startUrl: "https://tailwindcss.com/docs/installation", - rootUrl: "https://tailwindcss.com/docs", - faviconUrl: "https://tailwindcss.com/favicon.ico", - }, - "https://vuejs.org/guide/introduction.html": { - title: "Vue.js", - startUrl: "https://vuejs.org/guide/introduction.html", - rootUrl: "https://vuejs.org", - faviconUrl: "https://vuejs.org/favicon.ico", - }, - "https://svelte.dev/docs/introduction": { - title: "Svelte", - startUrl: "https://svelte.dev/docs/introduction", - rootUrl: "https://svelte.dev/docs", - faviconUrl: "https://svelte.dev/favicon.ico", - }, - "https://docs.github.com/en/actions": { - title: "GitHub Actions", - startUrl: "https://docs.github.com/en/actions", - rootUrl: "https://docs.github.com/en/actions", - faviconUrl: "https://docs.github.com/favicon.ico", - }, - "https://nodejs.org/docs/latest/api/": { - title: "NodeJS", - startUrl: "https://nodejs.org/docs/latest/api/", - rootUrl: "https://nodejs.org/docs/latest/api/", - faviconUrl: "https://nodejs.org/favicon.ico", - }, - "https://socket.io/docs/v4/": { - title: "Socket.io", - startUrl: "https://socket.io/docs/v4/", - rootUrl: "https://socket.io/docs/v4/", - faviconUrl: "https://socket.io/favicon.ico", - }, - "https://docs.gradle.org/current/userguide/userguide.html": { - title: "Gradle", - startUrl: "https://docs.gradle.org/current/userguide/userguide.html", - rootUrl: "https://docs.gradle.org/current", - faviconUrl: "https://docs.gradle.org/favicon.ico", - }, - "https://redux-toolkit.js.org/introduction/getting-started": { - title: "Redux Toolkit", - startUrl: "https://redux-toolkit.js.org/introduction/getting-started", - rootUrl: "https://redux-toolkit.js.org", - faviconUrl: "https://redux-toolkit.js.org/favicon.ico", - }, - "https://docs.trychroma.com/": { - title: "Chroma", - startUrl: "https://docs.trychroma.com/", - rootUrl: "https://docs.trychroma.com/", - faviconUrl: "https://docs.trychroma.com/favicon.ico", - }, - "https://www.sqlite.org/docs.html": { - title: "SQLite", - startUrl: "https://www.sqlite.org/docs.html", - rootUrl: "https://www.sqlite.org", - faviconUrl: "https://www.sqlite.org/favicon.ico", - }, - "https://redux.js.org/introduction/getting-started": { - title: "Redux", - startUrl: "https://redux.js.org/introduction/getting-started", - rootUrl: "https://redux.js.org", - faviconUrl: "https://redux.js.org/favicon.ico", - }, - "https://prettier.io/docs/en/": { - title: "Prettier", - startUrl: "https://prettier.io/docs/en/", - rootUrl: "https://prettier.io/docs/en/", - faviconUrl: "https://prettier.io/favicon.ico", - }, - "https://code.visualstudio.com/api": { - title: "VS Code Extension API", - startUrl: "https://code.visualstudio.com/api", - rootUrl: "https://code.visualstudio.com/api", - faviconUrl: "https://code.visualstudio.com/favicon.ico", - }, - "https://docs.continue.dev/intro": { - title: "Continue", - startUrl: "https://docs.continue.dev/intro", - rootUrl: "https://docs.continue.dev", - faviconUrl: "https://docs.continue.dev/favicon.ico", - }, - "https://api.jquery.com/": { - title: "jQuery", - startUrl: "https://api.jquery.com/", - rootUrl: "https://api.jquery.com/", - faviconUrl: "https://api.jquery.com/favicon.ico", - }, - "https://docs.python.org/3/": { - title: "Python", - startUrl: "https://docs.python.org/3/", - rootUrl: "https://docs.python.org/3/", - faviconUrl: "https://docs.python.org/favicon.ico", - }, - "https://doc.rust-lang.org/book/": { - title: "Rust", - startUrl: "https://doc.rust-lang.org/book/", - rootUrl: "https://doc.rust-lang.org/book/", - faviconUrl: "https://doc.rust-lang.org/favicon.ico", - }, - "https://plugins.jetbrains.com/docs/intellij/welcome.html": { - title: "IntelliJ Platform SDK", - startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html", - rootUrl: "https://plugins.jetbrains.com/docs/intellij", - faviconUrl: "https://plugins.jetbrains.com/favicon.ico", - }, - "https://docs.docker.com/": { - title: "Docker", - startUrl: "https://docs.docker.com/", - rootUrl: "https://docs.docker.com/", - faviconUrl: "https://docs.docker.com/favicon.ico", - }, - "https://docs.npmjs.com/": { - title: "NPM", - startUrl: "https://docs.npmjs.com/", - rootUrl: "https://docs.npmjs.com/", - faviconUrl: "https://docs.npmjs.com/favicon.ico", - }, - "https://tiptap.dev/docs/editor/introduction": { - title: "TipTap", - startUrl: "https://tiptap.dev/docs/editor/introduction", - rootUrl: "https://tiptap.dev/docs", - faviconUrl: "https://tiptap.dev/favicon.ico", - }, - "https://esbuild.github.io/": { - title: "esbuild", - startUrl: "https://esbuild.github.io/", - rootUrl: "https://esbuild.github.io/", - faviconUrl: "https://esbuild.github.io/favicon.ico", - }, - "https://tree-sitter.github.io/tree-sitter/": { - title: "Tree Sitter", - startUrl: "https://tree-sitter.github.io/tree-sitter/", - rootUrl: "https://tree-sitter.github.io/tree-sitter/", - faviconUrl: "https://tree-sitter.github.io/favicon.ico", - }, - "https://docs.netlify.com/": { - title: "Netlify", - startUrl: "https://docs.netlify.com/", - rootUrl: "https://docs.netlify.com/", - faviconUrl: "https://docs.netlify.com/favicon.ico", - }, - "https://replicate.com/docs": { - title: "Replicate", - startUrl: "https://replicate.com/docs", - rootUrl: "https://replicate.com/docs", - faviconUrl: "https://replicate.com/favicon.ico", - }, - "https://www.w3schools.com/html/default.asp": { - title: "HTML", - startUrl: "https://www.w3schools.com/html/default.asp", - rootUrl: "https://www.w3schools.com/html", - faviconUrl: "https://www.w3schools.com/favicon.ico", - }, - "https://www.w3schools.com/css/default.asp": { - title: "CSS", - startUrl: "https://www.w3schools.com/css/default.asp", - rootUrl: "https://www.w3schools.com/css", - faviconUrl: "https://www.w3schools.com/favicon.ico", - }, - "https://python.langchain.com/docs/get_started/introduction": { - title: "Langchain", - startUrl: "https://python.langchain.com/docs/get_started/introduction", - rootUrl: "https://python.langchain.com/docs", - faviconUrl: "https://python.langchain.com/favicon.ico", - }, - "https://developer.woocommerce.com/docs/": { - title: "WooCommerce", - startUrl: "https://developer.woocommerce.com/docs/", - rootUrl: "https://developer.woocommerce.com/docs/", - faviconUrl: "https://developer.woocommerce.com/favicon.ico", - }, - "https://developer.wordpress.org/reference/": { - title: "WordPress", - startUrl: "https://developer.wordpress.org/reference/", - rootUrl: "https://developer.wordpress.org/reference/", - faviconUrl: "https://developer.wordpress.org/favicon.ico", - }, - "https://doc.qt.io/qtforpython-6/quickstart.html": { - title: "PySide6", - startUrl: "https://doc.qt.io/qtforpython-6/quickstart.html", - rootUrl: "https://doc.qt.io/qtforpython-6/api.html", - faviconUrl: "https://doc.qt.io/favicon.ico", - }, - "https://getbootstrap.com/docs/5.3/getting-started/introduction/": { - title: "Bootstrap", - startUrl: "https://getbootstrap.com/docs/5.3/getting-started/introduction/", - rootUrl: "https://getbootstrap.com/docs/5.3/", - faviconUrl: "https://getbootstrap.com/favicon.ico", - }, - "https://alpinejs.dev/start-here": { - title: "Alpine.js", - startUrl: "https://alpinejs.dev/start-here", - rootUrl: "https://alpinejs.dev/", - faviconUrl: "https://alpinejs.dev/favicon.ico", - }, - "https://learn.microsoft.com/en-us/dotnet/csharp/": { - title: "C# Language Reference", - startUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/", - rootUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/", - faviconUrl: "https://learn.microsoft.com/favicon.ico", - }, - "https://docs.godotengine.org/en/latest/": { - title: "Godot", - startUrl: "https://docs.godotengine.org/en/latest/", - rootUrl: "https://docs.godotengine.org/en/latest/", - faviconUrl: "https://godotengine.org/favicon.ico", - }, - "https://docs.amplify.aws/react/start/": { - title: "AWS Amplify (Gen 2)", - startUrl: "https://docs.amplify.aws/react/start/", - rootUrl: "https://docs.amplify.aws/react/", - faviconUrl: "https://docs.amplify.aws/favicon.ico", - }, - "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": { - title: "AWS SDK for JavaScript v3", - startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", - rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", - faviconUrl: "https://docs.aws.amazon.com/favicon.ico", - }, - "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": { - title: "AWS CDK v2", - startUrl: - "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html", - rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/", - faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png", - }, - "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": { - title: "AWS CLI commands", - startUrl: - "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html", - rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/", - faviconUrl: "https://docs.aws.amazon.com/favicon.ico", - }, - "https://llama-stack.readthedocs.io/": { - title: "Llama Stack", - startUrl: "https://llama-stack.readthedocs.io/", - rootUrl: "https://llama-stack.readthedocs.io/", - }, - "https://go.dev/doc": { - title: "Go", - startUrl: "https://go.dev/doc", - rootUrl: "https://go.dev", - faviconUrl: "https://go.dev/favicon.ico", - }, - "https://api.flutter.dev": { - title: "Flutter", - startUrl: "https://api.flutter.dev", - rootUrl: "https://api.flutter.dev", - faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png", - }, - "https://api.dart.dev": { - title: "Dart", - startUrl: "https://api.dart.dev", - rootUrl: "https://api.dart.dev", - faviconUrl: "https://api.dart.dev/static-assets/favicon.png", - }, - "https://docs.asksage.ai/": { - title: "Ask Sage", - startUrl: "https://docs.asksage.ai/", - rootUrl: "https://docs.asksage.ai/", - }, - "https://angular.dev/": { - title: "Angular", - 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/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts deleted file mode 100644 index fac5091fd..000000000 --- a/core/indexing/docs/suggestions/index.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { - PackageDocsResult, - FilePathAndName, - PackageFilePathAndName, - IDE, - PackageDetails, - ParsedPackageInfo, -} from "../../.."; -import { getUriPathBasename } from "../../../util/uri"; -import { walkDir, walkDirs } from "../../walkDir"; - -import { PythonPackageCrawler } from "./packageCrawlers/Python"; -import { NodePackageCrawler } from "./packageCrawlers/TsJs"; - -const PACKAGE_CRAWLERS = [NodePackageCrawler, PythonPackageCrawler]; - -export interface PackageCrawler { - packageRegistry: string; - getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[]; - parsePackageFile( - file: PackageFilePathAndName, - contents: string, - ): ParsedPackageInfo[]; - getPackageDetails(packageInfo: ParsedPackageInfo): Promise; -} - -export async function getAllSuggestedDocs(ide: IDE) { - const allFileUris = await walkDirs(ide); - const allFiles = allFileUris.map((uri) => ({ - path: uri, - name: getUriPathBasename(uri), - })); - - // Build map of language -> package files - const packageFilesByRegistry: Record = {}; - for (const Crawler of PACKAGE_CRAWLERS) { - const crawler = new Crawler(); - const packageFilePaths = crawler.getPackageFiles(allFiles); - packageFilesByRegistry[crawler.packageRegistry] = packageFilePaths; - } - - // Get file contents for all unique package files - const uniqueFilePaths = Array.from( - new Set( - Object.values(packageFilesByRegistry).flatMap((files) => - files.map((file) => file.path), - ), - ), - ); - const fileContentsArray = await Promise.all( - uniqueFilePaths.map(async (path) => { - const contents = await ide.readFile(path); - return { path, contents }; - }), - ); - const fileContents = new Map( - fileContentsArray.map(({ path, contents }) => [path, contents]), - ); - - // Parse package files and build map of language -> packages - const packagesByCrawler: Record = {}; - PACKAGE_CRAWLERS.forEach((Crawler) => { - const crawler = new Crawler(); - packagesByCrawler[crawler.packageRegistry] = []; - const packageFiles = packageFilesByRegistry[crawler.packageRegistry]; - packageFiles.forEach((file) => { - const contents = fileContents.get(file.path); - if (!contents) { - return; - } - const packages = crawler.parsePackageFile(file, contents); - packagesByCrawler[crawler.packageRegistry].push(...packages); - }); - }); - - // Deduplicate packages per language - // TODO - this is where you would allow docs for different versions - // by e.g. using "name-version" as the map key instead of just name - // For now have not allowed - const registries = Object.keys(packagesByCrawler); - registries.forEach((registry) => { - const packages = packagesByCrawler[registry]; - const uniquePackages = Array.from( - new Map(packages.map((pkg) => [pkg.name, pkg])).values(), - ); - packagesByCrawler[registry] = uniquePackages; - }); - - // Get documentation links for all packages - const allDocsResults: PackageDocsResult[] = []; - await Promise.all( - PACKAGE_CRAWLERS.map(async (Crawler) => { - const crawler = new Crawler(); - const packages = packagesByCrawler[crawler.packageRegistry]; - const docsByRegistry = await Promise.all( - packages.map(async (packageInfo) => { - try { - const details = await crawler.getPackageDetails(packageInfo); - if (!details.docsLink) { - return { - packageInfo, - error: `No documentation link found for ${packageInfo.name}`, - }; - } - return { - packageInfo, - details: { - ...details, - docsLink: details.docsLink, - docsLinkWarning: details.docsLink.includes("github.com") - ? "Github docs not supported, find the docs site" - : details.docsLink.includes("docs") - ? undefined - : "May not be a docs site, check the URL", - }, - }; - } catch (error) { - return { - packageInfo, - error: `Error getting package details for ${packageInfo.name}`, - }; - } - }), - ); - allDocsResults.push(...docsByRegistry); - }), - ); - return allDocsResults; -} diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts deleted file mode 100644 index 3a617568f..000000000 --- a/core/indexing/docs/suggestions/packageCrawlers/Python.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { PackageCrawler } from ".."; -import { - FilePathAndName, - PackageDetails, - PackageFilePathAndName, - ParsedPackageInfo, -} from "../../../.."; - -export class PythonPackageCrawler implements PackageCrawler { - packageRegistry = "pypi"; - - getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { - // For Python, we typically look for files like requirements.txt or Pipfile - return files - .filter( - (file) => file.name === "requirements.txt" || file.name === "Pipfile", - ) - .map((file) => ({ - ...file, - packageRegistry: "pypi", - })); - } - - parsePackageFile( - file: PackageFilePathAndName, - contents: string, - ): ParsedPackageInfo[] { - // Assume the fileContent is a string from a requirements.txt formatted file - return contents - .split("\n") - .map((line) => { - const [name, version] = line.split("=="); - return { name, version, packageFile: file, language: "py" }; - }) - .filter((pkg) => pkg.name && pkg.version); - } - - async getPackageDetails( - packageInfo: ParsedPackageInfo, - ): Promise { - // Fetch metadata from PyPI to find the documentation link - const response = await fetch( - `https://pypi.org/pypi/${packageInfo.name}/json`, - ); - if (!response.ok) { - throw new Error(`Could not fetch data for package ${packageInfo.name}`); - } - const data = await response.json(); - const homePage = data?.info?.home_page as string | undefined; - - return { - docsLink: - (data?.info?.project_urls?.Documentation as string | undefined) ?? - homePage, - title: data?.info?.name as string | undefined, - description: data?.info?.summary as string | undefined, - repo: - (data?.info?.project_urls?.Repository as string | undefined) ?? - homePage, - license: data?.info?.license as string | undefined, - }; - } -} diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts deleted file mode 100644 index 3a9ef96c2..000000000 --- a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { PackageCrawler } from ".."; -import { - FilePathAndName, - PackageDetails, - PackageFilePathAndName, - ParsedPackageInfo, -} from "../../../.."; - -export class NodePackageCrawler implements PackageCrawler { - packageRegistry = "npm"; - - getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { - // For Javascript/TypeScript, we look for package.json file - return files - .filter((file) => file.name === "package.json") - .map((file) => ({ - ...file, - packageRegistry: this.packageRegistry, - })); - } - - parsePackageFile( - file: PackageFilePathAndName, - contents: string, - ): ParsedPackageInfo[] { - // Parse the package.json content - const jsonData = JSON.parse(contents) as Record; - const dependencies = Object.entries(jsonData.dependencies || {}).concat( - Object.entries(jsonData.devDependencies || {}), - ); - - // Filter out types packages and check if typescript is present - let foundTypes = false; - const filtered = dependencies.filter(([name, _]) => { - if (name.startsWith("@types/")) { - foundTypes = true; - return false; - } - if (name.includes("typescript")) { - foundTypes = true; - } - return true; - }); - return filtered.map(([name, version]) => ({ - name, - version, - packageFile: file, - language: foundTypes ? "ts" : "js", - })); - } - - async getPackageDetails( - packageInfo: ParsedPackageInfo, - ): Promise { - const { name } = packageInfo; - // Fetch metadata from the NPM registry to find the documentation link - const response = await fetch(`https://registry.npmjs.org/${name}`); - if (!response.ok) { - throw new Error(`Could not fetch data for package ${name}`); - } - const data = await response.json(); - - // const dependencies = Object.keys(packageContentData.dependencies || {}) - // .concat(Object.keys(packageContentData.devDependencies || {})); - // const usesTypescript = dependencies.includes("typescript"); - - return { - docsLink: data.homepage as string | undefined, - title: name, // package.json doesn't have specific title field - description: data.description as string | undefined, - repo: Array.isArray(data.repository) - ? (data.respository[0]?.url as string | undefined) - : undefined, - license: data.license as string | undefined, - }; - } -} diff --git a/core/indexing/docs/suggestions/suggestions.test.ts b/core/indexing/docs/suggestions/suggestions.test.ts deleted file mode 100644 index 60b58caa6..000000000 --- a/core/indexing/docs/suggestions/suggestions.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -// Generated by continue - -import { getAllSuggestedDocs } from "./index"; -import { testIde } from "../../../test/fixtures"; -import { - setUpTestDir, - tearDownTestDir, - addToTestDir, -} from "../../../test/testDir"; -import fetch, { RequestInfo } from "node-fetch"; - -jest.mock("node-fetch", undefined, { - virtual: false, -}); - -describe.skip("getAllSuggestedDocs", () => { - beforeEach(() => { - setUpTestDir(); - jest.clearAllMocks(); - }); - - afterEach(() => { - tearDownTestDir(); - jest.restoreAllMocks(); - }); - - it("should return package docs for JavaScript and Python projects", async () => { - // Set up test files - addToTestDir([ - [ - "package.json", - JSON.stringify({ - dependencies: { - express: "^4.17.1", - lodash: "^4.17.21", - }, - devDependencies: { - typescript: "^4.0.0", - }, - }), - ], - ["requirements.txt", "requests==2.25.1\nflask==1.1.2"], - ]); - - const mockedFetch = fetch as jest.MockedFunction; - mockedFetch.mockImplementation((url: URL | RequestInfo) => { - if (url.toString().includes("registry.npmjs.org/express")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - homepage: "https://expressjs.com/", - name: "express", - description: "Fast, unopinionated, minimalist web framework", - license: "MIT", - }), - }) as any; - } else if (url.toString().includes("registry.npmjs.org/lodash")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - homepage: "https://lodash.com/", - name: "lodash", - description: "Lodash modular utilities.", - license: "MIT", - }), - }) as any; - } else if (url.toString().includes("pypi.org/pypi/requests/json")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - info: { - home_page: "https://docs.python-requests.org/", - name: "requests", - summary: "Python HTTP for Humans.", - license: "Apache 2.0", - }, - }), - }) as any; - } else if (url.toString().includes("pypi.org/pypi/flask/json")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - info: { - home_page: "https://palletsprojects.com/p/flask/", - name: "flask", - summary: - "A simple framework for building complex web applications.", - license: "BSD-3-Clause", - }, - }), - }) as any; - } else { - return Promise.reject(new Error(`Unhandled URL: ${url}`)); - } - }); - - const results = await getAllSuggestedDocs(testIde); - - expect(results).toHaveLength(4); - expect(results).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - packageInfo: expect.objectContaining({ name: "express" }), - details: expect.objectContaining({ - docsLink: "https://expressjs.com/", - }), - }), - expect.objectContaining({ - packageInfo: expect.objectContaining({ name: "lodash" }), - details: expect.objectContaining({ - docsLink: "https://lodash.com/", - }), - }), - expect.objectContaining({ - packageInfo: expect.objectContaining({ name: "requests" }), - details: expect.objectContaining({ - docsLink: "https://docs.python-requests.org/", - }), - }), - expect.objectContaining({ - packageInfo: expect.objectContaining({ name: "flask" }), - details: expect.objectContaining({ - docsLink: "https://palletsprojects.com/p/flask/", - }), - }), - ]), - ); - - // Verify no errors are present - results.forEach((result) => { - expect(result.error).toBeUndefined(); - }); - }); - - it("should handle packages without documentation links", async () => { - addToTestDir([ - [ - "package.json", - JSON.stringify({ - dependencies: { - "no-docs-package": "^1.0.0", - }, - }), - ], - ]); - - // Mock fetch - const mockedFetch = fetch as jest.MockedFunction; - mockedFetch.mockImplementation((url: RequestInfo | URL) => { - if (url.toString().includes("registry.npmjs.org/no-docs-package")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - name: "no-docs-package", - description: "A package without docs", - license: "MIT", - // No homepage provided - }), - }) as any; - } else { - return Promise.reject(new Error(`Unhandled URL: ${url}`)); - } - }); - - const results = await getAllSuggestedDocs(testIde); - - expect(results).toHaveLength(1); - expect(results[0].error).toContain( - "No documentation link found for no-docs-package", - ); - expect(results[0].details).toBeUndefined(); - }); - - it("should handle errors when fetching package details", async () => { - addToTestDir([ - [ - "package.json", - JSON.stringify({ - dependencies: { - "error-package": "^1.0.0", - }, - }), - ], - ]); - - // Mock fetch - const mockedFetch = fetch as jest.MockedFunction; - mockedFetch.mockImplementation((url: URL | RequestInfo) => { - if (url.toString().includes("registry.npmjs.org/error-package")) { - return Promise.resolve({ - ok: false, - }) as any; - } else { - return Promise.reject(new Error(`Unhandled URL: ${url}`)); - } - }); - - const results = await getAllSuggestedDocs(testIde); - - expect(results).toHaveLength(1); - expect(results[0].error).toContain( - "Error getting package details for error-package", - ); - expect(results[0].details).toBeUndefined(); - }); - - it("should handle workspaces with no package files", async () => { - const results = await getAllSuggestedDocs(testIde); - - expect(results).toEqual([]); - }); - - it("should handle packages with GitHub documentation links", async () => { - addToTestDir([ - [ - "package.json", - JSON.stringify({ - dependencies: { - "github-docs-package": "^1.0.0", - }, - }), - ], - ]); - - // Mock fetch - const mockedFetch = fetch as jest.MockedFunction; - mockedFetch.mockImplementation((url: URL | RequestInfo) => { - if (url.toString().includes("registry.npmjs.org/github-docs-package")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - homepage: "https://github.com/user/repo", - name: "github-docs-package", - description: "A package with GitHub docs", - license: "MIT", - }), - }) as any; - } else { - return Promise.reject(new Error(`Unhandled URL: ${url}`)); - } - }); - - const results = await getAllSuggestedDocs(testIde); - - expect(results).toHaveLength(1); - expect(results[0].details?.docsLink).toBe("https://github.com/user/repo"); - expect(results[0].details?.docsLinkWarning).toBe( - "Github docs not supported, find the docs site", - ); - }); - - it("should handle packages with non-docs links", async () => { - addToTestDir([["requirements.txt", "non-docs-package==1.0.0"]]); - - // Mock fetch - const mockedFetch = fetch as jest.MockedFunction; - mockedFetch.mockImplementation((url: URL | RequestInfo) => { - if (url.toString().includes("pypi.org/pypi/non-docs-package/json")) { - return Promise.resolve({ - ok: true, - json: jest.fn().mockResolvedValue({ - info: { - home_page: "https://somewebsite.com", - name: "non-docs-package", - summary: "A package with non-docs homepage", - license: "MIT", - }, - }), - }) as any; - } else { - return Promise.reject(new Error(`Unhandled URL: ${url}`)); - } - }); - - const results = await getAllSuggestedDocs(testIde); - - expect(results).toHaveLength(1); - expect(results[0].details?.docsLink).toBe("https://somewebsite.com"); - expect(results[0].details?.docsLinkWarning).toBe( - "May not be a docs site, check the URL", - ); - }); -}); diff --git a/core/llm/index.ts b/core/llm/index.ts index dda2e7a87..028bc42c3 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -177,7 +177,11 @@ export abstract class BaseLLM implements ILLM { this.model = options.model; // Use @continuedev/llm-info package to autodetect certain parameters - const llmInfo = findLlmInfo(this.model); + const modelSearchString = + this.providerName === "continue-proxy" + ? this.model?.split("/").pop() || this.model + : this.model; + const llmInfo = findLlmInfo(modelSearchString); const templateType = options.template ?? autodetectTemplateType(options.model); @@ -195,11 +199,11 @@ export abstract class BaseLLM implements ILLM { options.completionOptions?.maxTokens ?? (llmInfo?.maxCompletionTokens ? Math.min( - llmInfo.maxCompletionTokens, - // Even if the model has a large maxTokens, we don't want to use that every time, - // because it takes away from the context length - this.contextLength / 4, - ) + llmInfo.maxCompletionTokens, + // Even if the model has a large maxTokens, we don't want to use that every time, + // because it takes away from the context length + this.contextLength / 4, + ) : DEFAULT_MAX_TOKENS), }; this.requestOptions = options.requestOptions; @@ -840,7 +844,6 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { - if (chunk.role === "assistant") { completion += chunk.content; yield chunk; @@ -948,7 +951,7 @@ export abstract class BaseLLM implements ILLM { ); } - protected async * _streamComplete( + protected async *_streamComplete( prompt: string, signal: AbortSignal, options: CompletionOptions, @@ -956,7 +959,7 @@ export abstract class BaseLLM implements ILLM { throw new Error("Not implemented"); } - protected async * _streamChat( + protected async *_streamChat( messages: ChatMessage[], signal: AbortSignal, options: CompletionOptions, diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index ff897d5a3..2ce2d93b2 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -140,8 +140,11 @@ function testLLM( }, }, type: "function", - wouldLikeTo: "Say hello", + wouldLikeTo: "say hello", + isCurrently: "saying hello", + hasAlready: "said hello", readonly: true, + group: "Hello", }, ], toolChoice: { diff --git a/core/llm/llms/TransformersJsEmbeddingsProvider.ts b/core/llm/llms/TransformersJsEmbeddingsProvider.ts index d17c9e0f1..7bd7b78ec 100644 --- a/core/llm/llms/TransformersJsEmbeddingsProvider.ts +++ b/core/llm/llms/TransformersJsEmbeddingsProvider.ts @@ -43,14 +43,16 @@ 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, }; constructor() { - super({ model: TransformersJsEmbeddingsProvider.model }); + super({ + model: TransformersJsEmbeddingsProvider.model, + title: "Transformers.js (Built-In)", + }); } async embed(chunks: string[]) { diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 01f62cd00..181db2abd 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -11,7 +11,7 @@ class ContinueProxy extends OpenAI { this.apiKey = value.workOsAccessToken; if (!this.onPremProxyUrl) { this.apiBase = new URL( - "openai/v1/", + "model-proxy/v1/", value.controlPlaneProxyUrl, ).toString(); } @@ -29,7 +29,7 @@ class ContinueProxy extends OpenAI { this.orgScopeId = options.orgScopeId; this.onPremProxyUrl = options.onPremProxyUrl; if (this.onPremProxyUrl) { - this.apiBase = new URL("openai/v1/", this.onPremProxyUrl).toString(); + this.apiBase = new URL("model-proxy/v1/", this.onPremProxyUrl).toString(); } } diff --git a/core/package-lock.json b/core/package-lock.json index 765c3541e..50df2a6f3 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,9 +13,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.63", + "@continuedev/config-yaml": "^1.0.67", "@continuedev/fetch": "^1.0.4", - "@continuedev/llm-info": "^1.0.2", + "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", @@ -100,7 +100,8 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", - "ts-jest": "^29.1.1" + "ts-jest": "^29.1.1", + "typescript": "^5.6.3" }, "engines": { "node": ">=20.11.0" @@ -2973,9 +2974,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.63", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.63.tgz", - "integrity": "sha512-KBfyOUU/mWOXeNf6v+4IfMkbvfEEe/YP6n/g/reJBhrpApchG2A/P11JviH87N2To1SrhZxnW//0g5FIGupDFw==", + "version": "1.0.67", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", + "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -2995,9 +2996,9 @@ } }, "node_modules/@continuedev/llm-info": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.7.tgz", - "integrity": "sha512-MyYmP4tbTzOnlT6hItC9tFkVZpYkaAg45AUXqdXzEfZhz8ZWpaiN8jZ789KLVmq+NKqhMUbKAHIZUUY1d39eRw==" + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.8.tgz", + "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" }, "node_modules/@continuedev/openai-adapters": { "version": "1.0.18", @@ -15449,7 +15450,6 @@ "version": "5.7.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz", "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/core/package.json b/core/package.json index a60eda4ad..205e3b778 100644 --- a/core/package.json +++ b/core/package.json @@ -39,16 +39,17 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", - "ts-jest": "^29.1.1" + "ts-jest": "^29.1.1", + "typescript": "^5.6.3" }, "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.758.0", "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.63", + "@continuedev/config-yaml": "^1.0.67", "@continuedev/fetch": "^1.0.4", - "@continuedev/llm-info": "^1.0.2", + "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index b6cbd05fb..b9d4e88c8 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -53,16 +53,15 @@ export function slashCommandFromPromptFileV1( path: string, content: string, ): SlashCommand | null { - const { name, description, systemMessage, prompt, version } = - parsePromptFileV1V2(path, content); - - if (version !== 1) { - return null; - } + const { name, description, systemMessage, prompt } = parsePromptFileV1V2( + path, + content, + ); return { name, description, + prompt, run: async function* (context) { const originalSystemMessage = context.llm.systemMessage; context.llm.systemMessage = systemMessage; diff --git a/core/promptFiles/v2/parse.ts b/core/promptFiles/v2/parse.ts index 95e60230e..ec543cbdc 100644 --- a/core/promptFiles/v2/parse.ts +++ b/core/promptFiles/v2/parse.ts @@ -1,4 +1,5 @@ import * as YAML from "yaml"; + import { getLastNPathParts } from "../../util/uri"; export function extractName(preamble: { name?: string }, path: string): string { diff --git a/core/promptFiles/v2/parsePromptFileV1V2.ts b/core/promptFiles/v2/parsePromptFileV1V2.ts index 11e2b10be..a883c5e7b 100644 --- a/core/promptFiles/v2/parsePromptFileV1V2.ts +++ b/core/promptFiles/v2/parsePromptFileV1V2.ts @@ -1,4 +1,5 @@ import * as YAML from "yaml"; + import { getLastNPathParts } from "../../util/uri"; export function parsePromptFileV1V2(path: string, content: string) { diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 4f6bb1534..1f08011a8 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -3,6 +3,7 @@ import { contextProviderClassFromName } from "../../context/providers"; import URLContextProvider from "../../context/providers/URLContextProvider"; import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getUriPathBasename } from "../../util/uri"; + import { getPreambleAndBody } from "./parse"; async function resolveAttachment( diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 3ab9f1448..03940c283 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,17 +1,20 @@ -import { ConfigResult, ModelRole } from "@continuedev/config-yaml"; +import { + ConfigResult, + DevDataLogEvent, + ModelRole, +} from "@continuedev/config-yaml"; import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; import { OrganizationDescription } from "../config/ProfileLifecycleManager"; import { SharedConfigSchema } from "../config/sharedConfig"; +import { GlobalContextModelSelections } from "../util/GlobalContext"; -import { DevDataLogEvent } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ChatMessage, ContextItem, ContextItemWithId, - ContextProviderWithParams, ContextSubmenuItem, DiffLine, DocsIndexingDetails, @@ -29,7 +32,6 @@ import type { SlashCommandDescription, ToolCall, } from "../"; -import { GlobalContextModelSelections } from "../util/GlobalContext"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -67,7 +69,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ]; "config/deleteModel": [{ title: string }, void]; - "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; "config/listProfiles": [ undefined, @@ -94,6 +95,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "mcp/reloadServer": [ + { + id: string; + }, + void, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 30cf5417c..c6ae172f4 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -16,7 +16,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "history/save", "devdata/log", "config/addModel", - "config/addContextProvider", "config/newPromptFile", "config/ideSettingsUpdate", "config/getSerializedProfileInfo", @@ -26,6 +25,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/openProfile", "config/updateSharedConfig", "config/updateSelectedModel", + "mcp/reloadServer", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -51,7 +51,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "indexing/reindex", "indexing/abort", "indexing/setPaused", - "docs/getSuggestedDocs", "docs/initStatuses", "docs/getDetails", // @@ -80,7 +79,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", - "docs/suggestions", "didCloseFiles", "didSelectOrganization", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 45c3fb424..329f71bdc 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -37,6 +37,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { setTTSActive: [boolean, void]; getWebviewHistoryLength: [undefined, number]; getCurrentSessionId: [undefined, string]; - "docs/suggestions": [PackageDocsResult[], void]; "jetbrains/setColors": [Record, void]; }; diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index d15db456c..268cbb9a8 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -8,4 +8,5 @@ export enum BuiltInToolNames { ExactSearch = "builtin_exact_search", SearchWeb = "builtin_search_web", ViewDiff = "builtin_view_diff", -} \ No newline at end of file +} +export const BUILT_IN_GROUP_NAME = "Built-In"; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 7af42d6a8..46db25cb9 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,10 +1,13 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const createNewFileTool: Tool = { type: "function", displayTitle: "Create New File", - wouldLikeTo: "create a new file", + wouldLikeTo: "create a new file at {{{ filepath }}}", + isCurrently: "creating a new file at {{{ filepath }}}", + hasAlready: "created a new file at {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, readonly: false, function: { name: BuiltInToolNames.CreateNewFile, diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index 8358b55da..d20db3cec 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -1,11 +1,14 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const exactSearchTool: Tool = { type: "function", displayTitle: "Exact Search", wouldLikeTo: 'search for "{{{ query }}}" in the repository', + isCurrently: 'getting search results for "{{{ query }}}"', + hasAlready: 'retreived search results for "{{{ query }}}"', readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ExactSearch, description: "Perform an exact search over the repository using ripgrep.", diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 5abc2edb1..f4df8e1e5 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -1,11 +1,14 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const readCurrentlyOpenFileTool: Tool = { type: "function", displayTitle: "Read Currently Open File", wouldLikeTo: "read the current file", + isCurrently: "reading the current file", + hasAlready: "read the current file", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ReadCurrentlyOpenFile, description: diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 4f5366e23..0133b54b0 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,11 +1,14 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const readFileTool: Tool = { type: "function", displayTitle: "Read File", wouldLikeTo: "read {{{ filepath }}}", + isCurrently: "reading {{{ filepath }}}", + hasAlready: "read {{{ filepath }}}", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ReadFile, description: diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 1b526009a..e7f48ea32 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,11 +1,14 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const runTerminalCommandTool: Tool = { type: "function", displayTitle: "Run Terminal Command", - wouldLikeTo: "run a terminal command", + wouldLikeTo: "run the following terminal command:", + isCurrently: "running the following terminal command:", + hasAlready: "ran the following terminal command:", readonly: false, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.RunTerminalCommand, description: diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index dfbcb04f7..0f98f382c 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,12 +1,15 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const searchWebTool: Tool = { type: "function", displayTitle: "Search Web", wouldLikeTo: 'search the web for "{{{ query }}}"', + isCurrently: 'searching the web for "{{{ query }}}"', + hasAlready: 'searched the web fore "{{{ query }}}"', readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.SearchWeb, description: diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index e54086d05..e7ce716a8 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -1,12 +1,15 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewDiffTool: Tool = { type: "function", displayTitle: "View Diff", - wouldLikeTo: "view a diff", + wouldLikeTo: "view the git diff", + isCurrently: "getting the git diff", + hasAlready: "viewed the git diff", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ViewDiff, description: "View the current diff of working changes", diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index 9cf3d319d..21c8050a6 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -1,12 +1,15 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewRepoMapTool: Tool = { type: "function", displayTitle: "View Repo Map", wouldLikeTo: "view the repository map", + isCurrently: "getting the repository map", + hasAlready: "viewed the repository map", readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ViewRepoMap, description: "View the repository map", diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 70b7524bd..2f9093c54 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,11 +1,14 @@ import { Tool } from "../.."; -import { BuiltInToolNames } from "../builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewSubdirectoryTool: Tool = { type: "function", displayTitle: "View Subdirectory", - wouldLikeTo: 'view the contents of "{{{ directory_path }}}"', + wouldLikeTo: 'view a map of "{{{ directory_path }}}"', + isCurrently: 'getting a map of "{{{ directory_path }}}"', + hasAlready: 'viewed a map of "{{{ directory_path }}}"', readonly: true, + group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.ViewSubdirectory, description: "View the contents of a subdirectory", diff --git a/core/util/paths.ts b/core/util/paths.ts index 3bc2ee3cf..a277d4977 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -1,11 +1,12 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import * as YAML from "yaml"; +import { ConfigYaml, DevEventName } from "@continuedev/config-yaml"; import * as JSONC from "comment-json"; import dotenv from "dotenv"; -import { DevEventName } from "@continuedev/config-yaml"; import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; @@ -91,27 +92,20 @@ export function getSessionsListPath(): string { return filepath; } -export function getConfigJsonPath(ideType: IdeType = "vscode"): string { +export function getConfigJsonPath(): string { const p = path.join(getContinueGlobalPath(), "config.json"); - if (!fs.existsSync(p)) { - if (ideType === "jetbrains") { - fs.writeFileSync(p, JSON.stringify(defaultConfigJetBrains, null, 2)); - } else { - fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2)); - } - } return p; } export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); - // if (!fs.existsSync(p)) { - // if (ideType === "jetbrains") { - // fs.writeFileSync(p, YAML.stringify(defaultConfigYamlJetBrains)); - // } else { - // fs.writeFileSync(p, YAML.stringify(defaultConfigYaml)); - // } - // } + if (!fs.existsSync(p) && !fs.existsSync(getConfigJsonPath())) { + if (ideType === "jetbrains") { + fs.writeFileSync(p, YAML.stringify(defaultConfigJetBrains)); + } else { + fs.writeFileSync(p, YAML.stringify(defaultConfig)); + } + } return p; } @@ -234,7 +228,7 @@ export function getDevDataFilePath( return path.join(versionPath, `${String(eventName)}.jsonl`); } -export function editConfigJson( +function editConfigJson( callback: (config: SerializedContinueConfig) => SerializedContinueConfig, ): void { const config = fs.readFileSync(getConfigJsonPath(), "utf8"); @@ -248,6 +242,31 @@ export function editConfigJson( } } +function editConfigYaml(callback: (config: ConfigYaml) => ConfigYaml): void { + const config = fs.readFileSync(getConfigYamlPath(), "utf8"); + let configYaml = YAML.parse(config); + // Check if it's an object + if (typeof configYaml === "object" && configYaml !== null) { + configYaml = callback(configYaml as any) as any; + fs.writeFileSync(getConfigYamlPath(), YAML.stringify(configYaml)); + } else { + console.warn("config.yaml is not a valid object"); + } +} + +export function editConfigFile( + configJsonCallback: ( + config: SerializedContinueConfig, + ) => SerializedContinueConfig, + configYamlCallback: (config: ConfigYaml) => ConfigYaml, +): void { + if (fs.existsSync(getConfigYamlPath())) { + editConfigYaml(configYamlCallback); + } else if (fs.existsSync(getConfigJsonPath())) { + editConfigJson(configJsonCallback); + } +} + function getMigrationsFolderPath(): string { const migrationsPath = path.join(getContinueGlobalPath(), ".migrations"); if (!fs.existsSync(migrationsPath)) { diff --git a/docs/docs/actions/context-selection.md b/docs/docs/actions/context-selection.md deleted file mode 100644 index 90bc7c0d2..000000000 --- a/docs/docs/actions/context-selection.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Context selection -description: Actions \-context selection -keywords: [context, slash, debug, quick fix, right click] -sidebar_position: 3 ---- - -## Slash commands - -Slash commands can be combined with additional instructions, including [context providers](../customize/context-providers.mdx) or [highlighted code](../edit/context-selection#highlighted-code). - -## Quick actions - -Quick actions are always displayed above a class or function and will edit that class or function, but nothing outside of it. - -## Right click actions - -The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit. - -## Debug action - -The debug action selects the most recently run terminal command and its output and then injects the following prompt into the chat window. There is no additional, non-visible information sent to the language model. - -``` -I got the following error, can you please help explain how to fix it? - -[ERROR_MESSAGE] -``` - -## Quick fixes - -Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”. diff --git a/docs/docs/actions/how-it-works.mdx b/docs/docs/actions/how-it-works.mdx deleted file mode 100644 index afacc3dbe..000000000 --- a/docs/docs/actions/how-it-works.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: How it works -description: How Actions work -keywords: [how, slash, commands, prompt, right click, quick fix, debug, action] -sidebar_position: 4 ---- - -While many Actions are based on templated prompts and can be customized with .prompt files, there are a number that execute more complex code under the hood. - -Right click actions that generate inline diffs, use the same prompt and response processing logic as [Edit](../edit/how-it-works.md). - -To learn how other slash commands work, see the full reference [here](../customize/slash-commands.mdx). diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md deleted file mode 100644 index 2f13e4f1a..000000000 --- a/docs/docs/actions/how-to-customize.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: How to customize -description: How to customize Actions -keywords: [customize, actions] -sidebar_position: 5 ---- - -The easiest way to add actions is by adding [`prompt` blocks](../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../chat/how-it-works.md). - -Check out the [slash commands deep dive](../customize/slash-commands.mdx) for more information on extending actions. diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md deleted file mode 100644 index d69ec3851..000000000 --- a/docs/docs/actions/how-to-use-it.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Actions -description: How to use Actions -sidebar_label: How to use it -keywords: [how, slash, commands, prompt, right click, quick fix, debug, action] -sidebar_position: 1 ---- - -![actions](/img/actions.gif) - -## How to use it - -Actions are shortcuts for common use cases. For example, you might want to review code, write tests, or add a docstring. - -### Slash commands - -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. - -![slash-commands](/img/slash-commands.png) - -In YAML assistants, slash commands are generated from [`prompts` blocks](../hub/blocks/block-types.md#prompts). - -Learn more about slash commands [here](../customize/slash-commands.mdx). - -:::info -Important: For assistants, slash commands only come from `prompts` blocks. When using older `config.json` configuration, other slash commands like `/share` and `/cmd` are included by default. -::: - -### Prompt files - -It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. - -Learn more about prompt files [here](../customize/deep-dives/prompt-files.md) - -### Other triggers for Actions (VS Code) - -:::info -Currently all of these are only available in VS Code -::: - -To make common use cases even more accessible, we provide a handful of other ways to invoke actions. - -#### Quick actions - -Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They can also be customized with .prompt files to perform custom actions. - -![quick-actions](/img/quick-actions.png) - -By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings. - -#### Right click actions - -Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu. - -![context-menu](/img/context-menu.png) - -#### Debug action - -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. - -#### Quick fixes - -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. - -![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/actions/model-setup.md b/docs/docs/actions/model-setup.md deleted file mode 100644 index 91912dcbf..000000000 --- a/docs/docs/actions/model-setup.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Model setup -description: Actions model setup -keywords: [model] -sidebar_position: 2 ---- - -By default, Actions uses the same model as [Chat](chat/model-setup.mdx), since we recommend a similar, 400B+ parameter model or one of the frontier models for the complex instructions that will be carried out. - -You can also set specific models to be used for Edit and Apply actions. See the [Model roles](../customize/model-roles/intro.mdx) page for more details. diff --git a/docs/docs/agent/context-selection.md b/docs/docs/agent/context-selection.md new file mode 100644 index 000000000..e341707d7 --- /dev/null +++ b/docs/docs/agent/context-selection.md @@ -0,0 +1,12 @@ +--- +title: Context selection +description: How context can be selected for Chat +keywords: [context] +sidebar_position: 3 +--- + +You can use the same [methods to manually add context as Chat](../chat/context-selection.md). + +In addition, tool call responses are automatically included as context items. + +This enables Agent mode to see the result of the previous action and decide what to do next. \ No newline at end of file diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md new file mode 100644 index 000000000..b89c7ac85 --- /dev/null +++ b/docs/docs/agent/how-it-works.md @@ -0,0 +1,38 @@ +--- +title: How it works +description: How Agent works +keywords: [how, agent, works] +sidebar_position: 4 +--- + +Agent offers the same functionality as Chat, while also including tools in the request to the model and an interface for handling tool calls and responses. + +## The tool handshake + +Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file. + +The following handshake describes how Agent uses tools: +1. In Agent mode, available tools are sent along with `user` chat requests +2. The model can choose to include a tool call in its response +3. The user gives permission. This step is skipped if the policy for that tool is set to `Automatic` +4. Continue calls the tool using built-in functionality or the MCP server that offers that particular tool +5. Continue sends the result back to the model +6. The model responds, potentially with another tool call and step 2 begins again + +:::info +In [Chat mode](../chat/how-to-use-it.md), tools are **not** included in the request to the model. +::: + +## Built-in tools + +Continue includes several built-in tools which provide the model access to IDE functionality: + +- **Read file** (`builtin_read_file`): read the contents of a file within the project +- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file +- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model +- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project +- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root +- **Search web** (`builtin_search_web`): Perform a web search to get top results +- **View diff** (`builtin_view_diff`): View the current working git diff +- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map) +- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project \ No newline at end of file diff --git a/docs/docs/agent/how-to-customize.md b/docs/docs/agent/how-to-customize.md new file mode 100644 index 000000000..9159ea871 --- /dev/null +++ b/docs/docs/agent/how-to-customize.md @@ -0,0 +1,32 @@ +--- +title: How to customize +description: How to customize Chat +keywords: [customize, chat] +sidebar_position: 5 +--- + +## Add MCP tools + +You can add MCP servers to your assistant to give Agent access to more tools. [Explore MCP Servers on the Hub](https://hub.continue.dev/explore/mcp) and see the [MCP guide](../customize/deep-dives/mcp.mdx) for more details. + +## Tool policies + +You can adjust Agent's usage behavior for each tool in your assistant to one of these options: + +- **Ask First (default)** - request permission from the user; show the `Cancel` and `Continue` buttons +- **Automatic** - do not request permission, automatically call the tool and feed the response back to the model +- **Excluded** - do not send this tool to the model + +:::warning +Be careful setting any tools to `automatic` if their behavior is not read-only. +::: + +First, open `Tool Policies` by clicking the tools icon in the input toolbar + +![Input Toolbar](/img/lump-toolbar.png) + +Then, you can view and change tool policies. To change a policy, click on the policy text ("Excluded", etc.) to toggle it. You can also turn groups of tools (e.g. all Built-in tools or all tools from a specific MCP server) off using the section toggles. + +![Tool Policies](/img/tool-policies.png) + +Tool policies are stored locally per user. \ No newline at end of file diff --git a/docs/docs/agent/how-to-use-it.md b/docs/docs/agent/how-to-use-it.md new file mode 100644 index 000000000..780163faf --- /dev/null +++ b/docs/docs/agent/how-to-use-it.md @@ -0,0 +1,49 @@ +--- +title: Agent +description: How to use Agent +sidebar_label: How to use it +keywords: [how, use, agent] +sidebar_position: 1 +--- + +![agent mode](/img/agent.gif) + +## How to use it + +Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. + +### Use Agent + +You can switch to `Agent` in the mode selector below the chat input box. + +![How to select agent mode](/img/mode-select-agent.png) + +:::info +If Agent is disabled with a `Not Supported` message, the selected model or provider doesn't support tools, or Continue doesn't yet support tools with it. See [Model Setup](./model-setup.mdx) for more information. +::: + +### Chat with Agent + +Agent lives within the same interface as [Chat](../chat/how-it-works.md), so the same [input](../chat/how-to-use-it.md#type-a-request-and-press-enter) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](../chat/how-to-use-it.md#reference-context-with-the--symbol) or adding [highlighted code from the editor](../chat/how-to-use-it.md#highlight-a-code-section-to-include-as-context). + +#### Use natural language + +With Agent, you can provide natural language instruction and let the model do the work. As an example, you might say + +> Set the @typescript-eslint/naming-convention rule to "off" for all eslint configurations in this project + +Agent will then decide which tools to use to get the job done. + +## Give Agent permission + +By default, Agent will ask permission when it wants to use a tool. Click `Continue` to allow Agent mode to proceed with the tool call or `Cancel` to reject it. + +![agent requesting permission](/img/agent-permission.png) + +You can use tool policies to exclude or make usage automatic for specific tools. See [How to Customize](./how-to-customize.md) for more background. + +## View Tool Responses + +Any data returned from a tool call is automatically fed back into the model as a context item. Most errors are also caught and returned, so that Agent mode can decide how to proceed. + +![agent response](/img/agent-response.png) \ No newline at end of file diff --git a/docs/docs/agent/model-setup.mdx b/docs/docs/agent/model-setup.mdx new file mode 100644 index 000000000..89e1cdf7e --- /dev/null +++ b/docs/docs/agent/model-setup.mdx @@ -0,0 +1,19 @@ +--- +title: Model setup +description: Models for Continue Agent +keywords: [model, agent] +sidebar_position: 2 +--- + +Agent can be used with models that support tool use through Continue. + +For the best Agent experience we recommend Claude 3.7 Sonnet from Anthropic. Add Claude 3.7 Sonnet to your assistant from the hub [here](https://hub.continue.dev/anthropic/claude-3-7-sonnet). You can get an API key from the [Anthropic console](https://console.anthropic.com/settings/keys). + +Currently the following providers are supported: + +- [Anthropic](../customize/model-providers/top-level/anthropic.mdx) - we recommend [Claude Sonnet 3.7](https://hub.continue.dev/anthropic/claude-3-7-sonnet) +- [Ollama](../customize/model-providers/top-level/ollama.mdx) - we recommend [Qwen 2.5 Coder 7b](https://hub.continue.dev/ollama/qwen2.5-coder-7b). Also see all Ollama models that support tools [here](https://ollama.com/search?c=tools). +- [OpenAI](../customize/model-providers/top-level/openai.mdx) - we recommend [GPT-4o](https://hub.continue.dev/openai/gpt-4o) +- [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.0 Flash](https://hub.continue.dev/google/gemini-2.0-flash) + +The best chat models generally support tool usage. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more. diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index db77a43f0..5f7327a0d 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -5,6 +5,6 @@ keywords: [customize] sidebar_position: 5 --- -Continue offers a handful of settings to customize autocomplete behavior. For the most part, these options can be found in the [User Settings Page](../customize/settings.md). +Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](../customize/deep-dives/settings.md) to manage these settings. For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](../customize/deep-dives/autocomplete.mdx). diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index acb357983..ce8c9ff1b 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -10,6 +10,5 @@ There are a number of different ways to customize Chat: - You can add a [`rules` block](../hub/blocks/block-types.md#rules) to your assistant to give the model persistent instructions through the system prompt. See the [rules deep dive](../customize/deep-dives/rules.md) for more information. - You can configure [`@Codebase`](../customize/deep-dives/codebase.mdx) - You can configure [`@Docs`](../customize/deep-dives/docs.mdx) -- You can configure and create custom [tools](../customize/tools.mdx) - You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.mdx) - You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.mdx) diff --git a/docs/docs/customize/deep-dives/autocomplete.mdx b/docs/docs/customize/deep-dives/autocomplete.mdx index c350b4d2c..6fd498e8d 100644 --- a/docs/docs/customize/deep-dives/autocomplete.mdx +++ b/docs/docs/customize/deep-dives/autocomplete.mdx @@ -90,15 +90,15 @@ Explore autocomplete model configurations on [the hub](https://hub.continue.dev/ ### Autocomplete User Settings -The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md): +{/* - `Use autocomplete cache`: If on, caches completions */} +The following settings can be configured for autocompletion in the IDE extension [User Settings Page](./settings.md): -- `Use autocomplete cache`: If on, caches completions - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" ### `config.json` Configuration -The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](../../reference.md#tabautocompleteoptions) for more details. +The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](../../json-reference.md#tabautocompleteoptions) for more details. ## FAQs diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index dd48ddbe7..c6c87ae7a 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -5,20 +5,26 @@ keywords: [config, settings, customize] # Configuration +You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. + +![configure an assistant](/img/configure-continue.png) + +## Hub Assistants + +Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md) + ## YAML Config -Continue can be deeply customized. Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: +Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: To open `config.yaml`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open Assistant configuration` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. - `~/.continue/config.yaml` (MacOS / Linux) - `%USERPROFILE%\.continue\config.yaml` (Windows) -To open your configuration file, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below. - When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. -See the full reference for `config.yaml` [here](../../yaml-reference.md). +See the full reference for `config.yaml` [here](../../reference.md). ## Deprecated configuration methods @@ -26,7 +32,7 @@ See the full reference for `config.yaml` [here](../../yaml-reference.md). View the `config.json` migration guide [here](../../yaml-migration.md) ::: -- [`config.json`](../../reference.md) - The original configuration format which is stored in a file at the same location as `config.yaml` +- [`config.json`](../../json-reference.md) - The original configuration format which is stored in a file at the same location as `config.yaml` - [`.continuerc.json`](#continuercjson) - Workspace-level configuration - [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema: - `~/.continue/config.ts` (MacOS / Linux) @@ -49,7 +55,9 @@ Example ### `config.ts` -To programatically extend `config.json`, you can place a `config.ts` script in same directory as `config.json` and export a `modifyConfig` function, like: +`config.yaml` or `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically extend Continue configuration, you can use a `config.ts` file, placed at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows). + +`config.ts` must export a `modifyConfig` function, like: ```ts title="config.ts" export function modifyConfig(config: Config): Config { @@ -75,4 +83,4 @@ export function modifyConfig(config: Config): Config { } ``` -This can be used for slash commands and custom context providers. +For examples of how to use `config.ts`, see [writing custom slash commands](../tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](../tutorials/build-your-own-context-provider.mdx). diff --git a/docs/docs/customize/deep-dives/development-data.md b/docs/docs/customize/deep-dives/development-data.md index da9f5136c..dd1e0c546 100644 --- a/docs/docs/customize/deep-dives/development-data.md +++ b/docs/docs/customize/deep-dives/development-data.md @@ -16,6 +16,6 @@ You can also configure custom destinations for your data, including remote HTTP For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data). -See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data) +See more details about adding `data` blocks to your configuration files in the [YAML specification](../../reference.md#data) When sending development data to your own HTTP endpoint, it will receive an event JSON blob at the given `schema` version. You can view event names, schema versions, and fields [here in the source code](https://github.com/continuedev/continue/tree/main/packages/config-yaml/src/schemas/data). diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index ee806263e..b21f78092 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -54,12 +54,6 @@ The `@Docs` context provider works by 3. Storing the embeddings locally on your machine 4. Embedding chat input to include similar documentation chunks as context -## Pre-indexed Documentation Sites - -In VS Code, Continue offers a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). - -Pre-indexed docs are only available in VS Code because the VS Code extension ships with the Transformers.js embedder built in, while Jetbrains currently does not. You can override a pre-indexed doc to index it with your own embeddings provider by adding it to your config (unique by `startUrl`). Otherwise, it will always use Transformers.js for queries. - ## Indexing Your Own Documentation ### Hub `docs` Blocks @@ -221,7 +215,10 @@ If your documentation is private, you can skip the default crawler and use a loc -The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. +:::info +Chromium crawling has been deprecated +{/* The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../deep-dives/settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. */} +::: Further notes: @@ -248,7 +245,7 @@ You can also use the following IDE command to force a re-index of all docs: `Con ### VS Code minimal setup -The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. Pre-indexed docs will be accessible. +The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. @@ -282,7 +279,7 @@ The following configuration example works out of the box for VS Code. This uses ### Jetbrains minimal setup -Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx). Pre-indexed docs will _not_ be accessible. +Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx). @@ -407,4 +404,4 @@ The following configuration example includes: -This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../settings.md). +{/* This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../deep-dives/settings.md). */} diff --git a/docs/docs/customize/tools.mdx b/docs/docs/customize/deep-dives/mcp.mdx similarity index 52% rename from docs/docs/customize/tools.mdx rename to docs/docs/customize/deep-dives/mcp.mdx index 1aad549f1..e4e828520 100644 --- a/docs/docs/customize/tools.mdx +++ b/docs/docs/customize/deep-dives/mcp.mdx @@ -1,36 +1,19 @@ --- -title: Tools -description: Tool use and customization +title: MCP +description: MCP use and customization keywords: [tool, use, function calling, claude, automatic] --- import TabItem from "@theme/TabItem"; import Tabs from "@theme/Tabs"; -Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported for the following providers: - -- [Anthropic](./model-providers/top-level/anthropic.mdx) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model). -- [Ollama](./model-providers/top-level/ollama.mdx) - see recommended models [here](https://ollama.com/search?c=tools). -- [OpenAI](./model-providers/top-level/openai.mdx) -- [Gemini](./model-providers/top-level/gemini.mdx) - -To use tools, click on the icon in the input toolbar like below. - -![tools](/img/tool-use-example.png) - -To let you balance speed and safety, each tool can be set to 1 of 3 modes: - -- `Automatic`: When the LLM requests to use the tool, Continue will automatically call it and send the response to the LLM. -- `Allowed`: When the LLM requests to use the tool, Continue will first give you the opportunity to "Cancel" or "Continue" with the tool. -- `Disabled`: The LLM will not know about or be able to use the tool. - -### Custom tools +## MCP Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). -To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): +To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](./configuration.md): diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index f5c834c17..68995746f 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -2,11 +2,11 @@ title: Prompt files --- -Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts. +Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub. -On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules). - -Prompt files can also be stored within your project's root directory as `.prompt` files. See below. +:::info +Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) +::: ## Quick start @@ -25,7 +25,7 @@ Attached is a summary of the current Ruby on Rails application, including the @G Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. -Then, type "@", select "Prompt files", and choose the one called "Rails Project". You can now ask any question as usual and the LLM will have the information from your .prompt file. +Then, type / and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file. ## Format diff --git a/docs/docs/customize/settings.md b/docs/docs/customize/deep-dives/settings.md similarity index 50% rename from docs/docs/customize/settings.md rename to docs/docs/customize/deep-dives/settings.md index f76494032..0d3b57127 100644 --- a/docs/docs/customize/settings.md +++ b/docs/docs/customize/deep-dives/settings.md @@ -14,21 +14,21 @@ Which takes you to this page: ![User Settings Page](/img/settings-page.png) -Click the `Open Assistant configuration` button to open your configuration file. See the [Configuration Reference](../reference.md) for more information. - Below that, the following settings which are not part of a configuration file are available: +- `Show Session Tabs`: If on, displays tabs above the chat as an alternative way to organize and access your sessions. Off by default - `Wrap Codeblocks`: If on, enables text wrapping in code blocks. Off by default. -- `Display Raw Markdown`: If on, shows raw markdown in responses. Off by default. -- `Allow Anonymous Telemetry`: If on, allows Continue to send anonymous telemetry. **On** by default. -- `Disable Indexing`: Prevents indexing of the codebase, useful primarily for debugging purposes. Off by default. -- `Disable Session Titles`: Prevents generating summary titles for each chat session when turned on. Off by default -- `Response Text to Speech`: If on, reads LLM responses aloud with TTS. Off by default. - `Show Chat Scrollbar`: If on, enables a scrollbar in the chat window. Off by default. -- `Use autocomplete cache`: If on, caches completions. -- `Use Chromium for Docs Crawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to ~/.continue/.utils. Off by default -- `Codeblock Actions Position`: Sets the position for the actions that show when hovering over codeblocks. Defaults to `top` -- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` +- `Text-to-Speech Output`: If on, reads LLM responses aloud with TTS. Off by default. +- `Enable Session Titles`: If on, generates summary titles for each chat session after the first message, using the current Chat model. On by default. +- `Format Markdown`: If off, shows responses as raw text. On by default. +- `Allow Anonymous Telemetry`: If on, allows Continue to send anonymous telemetry. **On** by default. +- `Enable Indexing`: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default. - `Font Size`: Specifies base font size for UI elements -- `Workspace prompts path`: Where to find Prompt Files in a workspace - replaces the default .continue/prompts +- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" + + + + + diff --git a/docs/docs/customize/deep-dives/slash-commands.mdx b/docs/docs/customize/deep-dives/slash-commands.mdx new file mode 100644 index 000000000..0c9796768 --- /dev/null +++ b/docs/docs/customize/deep-dives/slash-commands.mdx @@ -0,0 +1,33 @@ +--- +title: Slash commands +description: Shortcuts that can be activated by prefacing your input with '/' +keywords: [slash command, custom commands, step] +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +![actions](/img/actions.gif) + +## Slash commands + +Slash commands are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. +{/* ![slash-commands](/img/slash-commands.png) */} + +Slash commands can be combined with additional instructions, including [context providers](../context-providers.mdx) or [highlighted code](../../edit/context-selection#highlighted-code). + +## Prompts + +### Assistant prompt blocks + +The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../chat/how-it-works.md). + +### Prompt files + +It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. + +Learn more about prompt files [here](./prompt-files.md) + +### MCP Server prompts + +Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp.mdx) for more details. diff --git a/docs/docs/customize/deep-dives/vscode-actions.md b/docs/docs/customize/deep-dives/vscode-actions.md new file mode 100644 index 000000000..0c0cdd1f1 --- /dev/null +++ b/docs/docs/customize/deep-dives/vscode-actions.md @@ -0,0 +1,49 @@ +--- +title: VS Code Actions +description: VS Code Actions +keywords: [vscode, quick actions, quick, actions] +--- + +### Other triggers for Actions (VS Code) + +:::info +Currently all of these are only available in VS Code +::: + +To make common use cases even more accessible, we provide a handful of other ways to invoke actions in VS Code. + +## Quick actions + +Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompt-files.md) to perform custom actions. + +![quick-actions](/img/quick-actions.png) + +By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings. + +## Right click actions + +Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu. + +The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit. + +Right click actions that generate inline diffs use the same prompt and response processing logic as [Edit](../../edit/how-it-works.md). + +![context-menu](/img/context-menu.png) + +## Debug action + +The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the most recent terminal output into the chat sidebar and get debugging advice. There is no additional, non-visible information sent to the language model. + +``` +I got the following error, can you please help explain how to fix it? + +[ERROR_MESSAGE] +``` + +## Quick fixes + +Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. + +Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”. + +![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/customize/model-providers/more/nebius.mdx b/docs/docs/customize/model-providers/more/nebius.mdx index 12a660ead..35c654bbb 100644 --- a/docs/docs/customize/model-providers/more/nebius.mdx +++ b/docs/docs/customize/model-providers/more/nebius.mdx @@ -15,9 +15,9 @@ Available models can be found on the [Nebius AI Studio models page](https://stud ```yaml title="config.yaml" models: - - name: Llama 3.1 405b + - name: DeepSeek R1 provider: nebius - model: llama3.1-405b + model: deepseek-ai/DeepSeek-R1 apiKey: ``` @@ -26,9 +26,9 @@ Available models can be found on the [Nebius AI Studio models page](https://stud { "models": [ { - "title": "Llama 3.1 405b", + "title": "DeepSeek R1", "provider": "nebius", - "model": "llama3.1-405b", + "model": "deepseek-ai/DeepSeek-R1", "apiKey": "" } ] diff --git a/docs/docs/customize/model-roles/chat.mdx b/docs/docs/customize/model-roles/chat.mdx index 90b97e17c..aca683782 100644 --- a/docs/docs/customize/model-roles/chat.mdx +++ b/docs/docs/customize/model-roles/chat.mdx @@ -10,7 +10,7 @@ import Tabs from "@theme/Tabs"; A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters. -In Continue, these models are used for [Chat](../../chat/how-to-use-it.md) and [Actions](../../actions/how-to-use-it.md). The selected chat model will also be used for [Edit](../../edit/how-to-use-it.md) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. +In Continue, these models are used for normal [Chat](../../chat/how-to-use-it.md) and [VS Code actions](../deep-dives/vscode-actions.md). The selected chat model will also be used for [Edit](../../edit/how-to-use-it.md) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. ## Recommended Chat models @@ -51,117 +51,66 @@ Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-pr -### Llama 3.1 405B from Meta +### Gemma from Google DeepMind -If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../model-providers/more/together.mdx) or [Groq](../model-providers/more/groq.mdx)) or self-host it (e.g. using [vLLM](../model-providers//more/vllm.mdx) or [Ollama](../model-providers/top-level/ollama.mdx)). +If you prefer to use an open-weight model, then the Gemma family of Models from Google DeepMind is a good choice. You will need to decide if you use it through a SaaS model provider, e.g. [Together](../model-providers/more/together.mdx), or self-host it, e.g. [Ollama](../model-providers/top-level/ollama.mdx). - {/* HUB_TODO nonexistent blocks */} - {/* + - - Add the [Together Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub - - - Add the [Groq Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub - - - Add the [vLLM Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub - - Add the [Ollama Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub + Add the [Ollama Gemma 3 27B block](https://hub.continue.dev/ollama/gemma3-27b) from the hub + + + Add the [Together Gemma 2 27B Instruct block](https://hub.continue.dev/togetherai/gemma-2-instruct-27b) from the hub - */} + - - ```yaml title="config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "together" - model: "llama3.1-405b" - apiKey: - ``` - - - ```yaml title="config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "groq" - model: "llama3.1-405b" - apiKey: - ``` - - - ```yaml title="config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "vllm" - model: "llama3.1-405b" - ``` - ```yaml title="config.yaml" models: - - name: "Llama 3.1 405B" + - name: "Gemma 3 27B" provider: "ollama" - model: "llama3.1:405b" + model: "gemma3:27b" + ``` + + + ```yaml title="config.yaml" + models: + - name: "Gemma 3 27B" + provider: "together" + model: "google/gemma-2-27b-it" + apiKey: ``` - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "together", - "model": "llama3.1-405b", - "apiKey": "" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "groq", - "model": "llama3.1-405b", - "apiKey": "" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "vllm", - "model": "llama3.1-405b" - } - ] - } - ``` - ```json title="config.json" { "models": [ { - "title": "Llama 3.1 405B", + "title": "Gemma 3 27B", "provider": "ollama", - "model": "llama3.1:405b" + "model": "gemma3:27b" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemma 3 27B", + "provider": "together", + "model": "google/gemma-2-27b-it", + "apiKey": "" } ] } diff --git a/docs/docs/customize/model-roles/intro.mdx b/docs/docs/customize/model-roles/intro.mdx index 3c3a6476e..5a2cb4b05 100644 --- a/docs/docs/customize/model-roles/intro.mdx +++ b/docs/docs/customize/model-roles/intro.mdx @@ -18,14 +18,14 @@ Models in Continue can be configured to be used for various roles in the extensi - [`embed`](./embeddings.mdx): Used to generate embeddings used for vector search (@Codebase and @Docs context providers) - [`rerank`](./reranking.mdx): Used to rerank results from vector search -These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](../../yaml-reference.md#models) for more details. +These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](../../reference.md#models) for more details. ## Selecting model roles -You can control which of the models in your assistant for a given role will be currently used for that role. Visit the [Settings page](../settings.md) and go to the **Active Models** section. +You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. ![Settings Active Models Section](/img/settings-model-roles.png) :::info -Note that `roles` do not exist within `config.json` - they are infered by the top level keys like `embeddingsProvider` +`roles` are not explicitly defined within `config.json` (deprecated) - they are infered by the top level keys like `embeddingsProvider` ::: diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index ae2baf79a..15ed68ec9 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -7,44 +7,18 @@ keywords: [customize, configure, config] Continue can be deeply customized. For example you might: - **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](../customize/model-providers/). -- **Select different model providers for each Compose feature**. Different Continue features can use different model providers. We call these _model types_. For example, you can use a different model provider for chat than you do for autocomplete. Learn more about [model types](../customize/model-roles/) . -- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/context-providers). -- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/slash-commands). -- **Call external tools and functions**. Unchain your LLM with the power of _Tools_. You can call any external tool or function from your prompts. Currently only available with Anthropic. Learn more about [Tools](/customize/tools). +- **Select different models for specific tasks**. Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](./model-roles/) . +- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](./context-providers.mdx). +- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](./deep-dives/slash-commands.mdx). +- **Call external tools and functions**. Unchain your LLM with the power of tools using [Agent](../agent/how-to-use-it.md). Add custom tools using [MCP Servers](./deep-dives/mcp.mdx) -Whatever you choose, you'll probably start by editing `config.yaml`. +Whatever you choose, you'll probably start by editing your Assistant. -## Editing config.json +## Editing your assistant -Most custom configuration is done by editing `config.yaml` (or the older `config.json`). This is a YAML file that allows you to customize Continue to your liking. It is found at: +You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. -- MacOS and Linux: `~/.continue/config.yaml` -- Windows: `%USERPROFILE%\.continue\config.yaml` +![configure an assistant](/img/configure-continue.png) -You can easily access config file from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open Assistant configuration`. - -![configure-continue](/img/configure-continue.png) - -When editing this file, you can see the available options suggested as you type, or you can check the [full reference](./deep-dives/configuration.md). - -:::info - -A configuration file is created the first time you use Continue. If you'd like to reset your configuration to the default, you can delete this file and Continue will automatically recreate it with the default settings. - -::: - -:::info - -When you save a configuration file from the IDE, Continue will automatically refresh to take into account your changes. - -::: - -## Per-workspace configuration - -If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. It has the same [definition](./deep-dives/configuration.md) as `config.json`, and will automatically be applied on top of the local config.json. - -## Programmatic configuration - -`config.yaml` or `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically configure Continue, you can use `config.ts`, which is located at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows). - -For examples of how to use `config.ts`, see [writing custom slash commands](./tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](./tutorials/build-your-own-context-provider.mdx). +- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hug assistant +- See the [Config Deep Dive](./deep-dives/configuration.md) for more details on configuring local assistants. diff --git a/docs/docs/customize/slash-commands.mdx b/docs/docs/customize/slash-commands.mdx deleted file mode 100644 index e1890ba81..000000000 --- a/docs/docs/customize/slash-commands.mdx +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Slash commands -description: Shortcuts that can be activated by prefacing your input with '/' -keywords: [slash command, custom commands, step] ---- - -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; - -:::info -Slash commands can currently only be added using [`config.json`](../reference.md). The [`YAML Config Format`](../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../customize/deep-dives/prompt-files.md) to achieve similar functionality. -::: - -Slash commands are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. - -![slash-commands](/img/slash-commands.png) - -## Built-in Slash Commands - -To use any of the built-in slash commands, open `config.json` and add it to the `slashCommands` list. - -### `/share` - -Generate a shareable markdown transcript of your current chat history. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "share", - "description": "Export the current chat session to markdown", - "params": { "outputDir": "~/.continue/session-transcripts" } - } - ] -} -``` - -Use the `outputDir` parameter to specify where you want to the markdown file to be saved. - -### `/cmd` - -Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "cmd", - "description": "Generate a shell command" - } - ] -} -``` - -### `/commit` - -Shows the LLM your current git diff and asks it to generate a commit message. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "commit", - "description": "Generate a commit message for the current changes" - } - ] -} -``` - -### `/http` - -Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "http", - "description": "Does something custom", - "params": { "url": "" } - } - ] -} -``` - -### `/issue` - -Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "issue", - "description": "Generate a link to a drafted GitHub issue", - "params": { "repositoryUrl": "https://github.com/continuedev/continue" } - } - ] -} -``` - -### `/onboard` - -The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "onboard", - "description": "Familiarize yourself with the codebase" - } - ] -} -``` - -### Model Context Protocol - -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this: - - - - ```yaml title="config.yaml" - mcpServers: - - name: My MCP Server - command: uvx - args: - - mcp-server-sqlite - - --db-path - - /Users/NAME/test.db - ``` - - - ```json title="config.json" - { - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } - } - ``` - - - -### Build your own Slash Command - -You can build your own slash command by following [this tutorial](/customize/tutorials/build-your-own-slash-command). diff --git a/docs/docs/customize/tutorials/build-your-own-slash-command.md b/docs/docs/customize/tutorials/build-your-own-slash-command.md index f0cc1147f..27b0517b3 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -3,7 +3,7 @@ title: Build your own slash command --- :::info -Slash commands can currently only be added using [`config.json`](../../reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality. +Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality. ::: There are two ways to add custom slash commands: diff --git a/docs/docs/customize/tutorials/running-continue-without-internet.md b/docs/docs/customize/tutorials/running-continue-without-internet.md index e3de1e79e..2ba683909 100644 --- a/docs/docs/customize/tutorials/running-continue-without-internet.md +++ b/docs/docs/customize/tutorials/running-continue-without-internet.md @@ -7,6 +7,6 @@ keywords: [no internet, air-gapped, local model] Continue can be run even on an air-gapped computer if you use a local model. Only a few adjustments are required for this to work. 1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix). -2. Open the [User Settings Page](../settings.md) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). +2. Open the [User Settings Page](../deep-dives/settings.md) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). 3. Also in `config.json`, set the default model to a local model. You can available options [here](../model-providers/). 4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect. diff --git a/docs/docs/edit/context-selection.md b/docs/docs/edit/context-selection.md index 0a4fbe3f8..ebe12d8da 100644 --- a/docs/docs/edit/context-selection.md +++ b/docs/docs/edit/context-selection.md @@ -9,10 +9,10 @@ keywords: [edit, cmd i, works] The input you provide is included in the prompt. -## Highlighted code +## Code to Edit -The highlighted code you’ve selected is included in the prompt. This is the only section of code that the model will attempt to edit. +The **entire contents** of each file (the current file for Jetbrains inline Edit, each `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. -## Current file +## Context Providers -The entire contents of the file containing your highlighted code selection are included as additional context. This gives the model a broader understanding of the code's environment. If the file is too large to fit within the context window, we will trim the file's contents to fit. \ No newline at end of file +In VS Code Edit mode, you can use `@` to add context using [Context Providers](../customize/context-providers.mdx), similar to [Chat](../chat/context-selection.md). Some context providers may be disabled in Edit mode. diff --git a/docs/docs/edit/how-it-works.md b/docs/docs/edit/how-it-works.md index 453d1e98f..e9ff3bbb1 100644 --- a/docs/docs/edit/how-it-works.md +++ b/docs/docs/edit/how-it-works.md @@ -1,14 +1,14 @@ --- title: How Edit works sidebar_position: 4 -description: How Edit works +description: How it works keywords: [edit, cmd l, works] --- -Using the highlighted code, the contents of the file containing your highlight, and your input instructions, we prompt the model to edit the code according to your instructions. No other additional context is provided to the model. +Using the highlighted code, the contents of the current file containing your highlight, and your input instructions, we prompt the model to edit the code according to your instructions. No other additional context is provided to the model. The model response is then streamed directly back to the highlighted range in your code, where we apply a diff formatting to show the proposed changes. If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes. -If you would like to view the exact prompt that is sent to the model during an edit, you can [view this in the prompt logs](../troubleshooting.mdx#check-the-logs). +If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](../troubleshooting.mdx#check-the-logs). diff --git a/docs/docs/edit/how-to-customize.mdx b/docs/docs/edit/how-to-customize.mdx index 35b918393..46dd5e3da 100644 --- a/docs/docs/edit/how-to-customize.mdx +++ b/docs/docs/edit/how-to-customize.mdx @@ -5,7 +5,10 @@ description: How to customize Edit keywords: [edit, cmd i, works] --- -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; +## Setting active Edit/Apply model -You can configure a particular model to be used for Edit by setting/overriding `roles` in the model's YAML config. See [Edit role](../customize/model-roles/edit.mdx) for more details. +You can configure particular models from your Assistant to be used for Edit and Apply requests (see [How it Works](./how-it-works.md)). Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then, you can use the dropdowns to select models to use for Edit and Apply. + +![Settings Active Models Section](/img/model-roles-edit.png) + +See [Edit role](../customize/model-roles/edit.mdx) and [Apply role](../customize/model-roles/apply.mdx) for more details. diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 850c34b60..620a18eda 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -10,9 +10,9 @@ keywords: [edit, cmd l, use] ## How to use it -Edit is a convenient way to modify code without leaving your current file. Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. +Edit is a convenient way to make quick changes to specific code and files. Select code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. -Edit is best used for small, quick changes such as: +Edit is recommended for small, targeted changes, such as - Writing comments - Generating unit tests @@ -20,7 +20,7 @@ Edit is best used for small, quick changes such as: ## Highlight code and activate -Highlight the block of code you would like to modify, and press cmd/ctrl + i to activate the edit input. +Highlight the block of code you would like to modify and press cmd/ctrl + i to active Edit mode. You can also enter Edit mode by pressing cmd/ctrl + i with no code highlighted. ## Describe code changes @@ -35,3 +35,45 @@ You can navigate through each proposed change, accepting or rejecting them using You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. + +## VS Code + +In VS Code, Edit is implemented in the extension sidebar with a similar interface to [Chat](../chat/how-it-works.md), and you can also enter Edit mode by using the Mode Selector below the main Chat input to select `Edit`. + +![edit mode selected](/img/select-edit-mode.png) + +You can also reject and accept diffs using the `Reject All` and `Accept All` buttons that show up in the Chat when diffs are present (see examples below). + +### Adding Code to Edit + +Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor. + +**_Add file combobox_** + +![edit mode add file combobox](/img/edit-mode-add-files.png) + +**_Add all open files dropdown_** + +![edit mode add file combobox](/img/edit-mode-add-all-open-files.png) + +### Single File Edit + +If one file/range is present in `Code to Edit` on submission, Continue will prompt the Edit model and then automatically stream the diff into the editor. + +![Edit mode single file diffs](/img/edit-mode-single-file-diff.png) + +### Multi-File Edit + +If multiple files/ranges are present in `Code to Edit` on submission, Continue will prompt the Edit model to output codeblocks per-file, which the user can then choose to apply and accept/reject independently. + +**_Generated Content_** + +![Edit mode multi file generated content](/img/edit-mode-multi-file-generation.png) + +**_Diffs_** + +![Edit mode multi file diffs](/img/edit-mode-multi-file-diffs.png) + +## Jetbrains + +In Jetbrains, Edit is implemented as an inline popup (see the header GIF example) for single-file edit. Multi-file edit mode is not currently implemented. diff --git a/docs/docs/edit/model-setup.md b/docs/docs/edit/model-setup.md index 606bd0654..a76865dcd 100644 --- a/docs/docs/edit/model-setup.md +++ b/docs/docs/edit/model-setup.md @@ -5,8 +5,6 @@ description: How to set up an Edit model keywords: [edit, cmd l, model] --- -By default, Edit uses the [same model as Chat](../chat/model-setup.mdx) since we recommend a similar, 400B+ parameter model or one of the frontier model for code edits. +By default, Edit uses the [same model as Chat](../chat/model-setup.mdx), and we recommend [Claude 3.7 Sonnet](https://hub.continue.dev/anthropic/claude-3-7-sonnet) from Anthropic. Visit [the Hub](https://hub.continue.dev/explore/models?roles=edit) to explore other Edit models. -Visit [the hub](https://hub.continue.dev/explore/models?roles=edit) to explore Edit models. - -You can configure a different model to be used for edits by updating your [configuration](../customize/model-roles/edit.mdx). +For the best Edit experience, we also recommend setting up an Apply model, specially trained to apply diffs to files. We recommend [Morph v0 Fast Apply](https://hub.continue.dev/morphllm/morph-v0) or [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply). Explore other apply models on the [the Hub](https://hub.continue.dev/explore/models?roles=apply). diff --git a/docs/docs/getting-started/overview.mdx b/docs/docs/getting-started/overview.mdx index 446031fa7..fdd6a46d7 100644 --- a/docs/docs/getting-started/overview.mdx +++ b/docs/docs/getting-started/overview.mdx @@ -4,9 +4,9 @@ description: Getting started with Continue keywords: [quickstart, start, overview, chat, autocomplete, edit, actions] --- -import Tabs from "@theme/Tabs"; -import TabItem from "@theme/TabItem"; import Admonition from "@theme/Admonition"; +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; To quickly understand what you can do with Continue, check out each tab below. @@ -33,26 +33,29 @@ To quickly understand what you can do with Continue, check out each tab below. + - [Edit](../edit/how-to-use-it.md#how-to-use-it) is a convenient way to modify code without leaving your current file + [Edit](../edit/how-to-use-it.md#how-to-use-it) is a convenient way to modify code without leaving your current file - ![edit](/img/edit.gif) + ![edit](/img/edit.gif) + + + Learn more about [Edit](../edit/how-to-use-it.md#how-to-use-it) + + + + + + + [Agent](../agent/how-to-use-it.md#how-to-use-it) equips the Chat model with the tools needed to handle a wide range of coding tasks + + ![agent](/img/agent.gif) - Learn more about [Edit](../edit/how-to-use-it.md#how-to-use-it) + Learn more about [Agent](../agent/how-to-use-it.md#how-to-use-it) - - [Actions](../actions/how-to-use-it.md#how-to-use-it) are shortcuts for common use cases - - ![actions](/img/actions.gif) - - - Learn more about how to use [Actions](../actions/how-to-use-it.md#how-to-use-it) - - - diff --git a/docs/docs/hub/assistants/create-an-assistant.md b/docs/docs/hub/assistants/create-an-assistant.md index 207f1c955..62fdf666c 100644 --- a/docs/docs/hub/assistants/create-an-assistant.md +++ b/docs/docs/hub/assistants/create-an-assistant.md @@ -32,7 +32,6 @@ Choose a name, slug, description, and icon for your assistant. The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar. -Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](../../yaml-reference.md#complete-yaml-config-example) docs for more details. +Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](../../reference.md#complete-yaml-config-example) docs for more details. ![New assistant YAML](/img/hub/assistant-create-yaml.png) - diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index 51ec97b10..0c2698542 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -11,31 +11,31 @@ sidebar_label: Types Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models). -Continue supports [many model providers](../../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](../../customize/model-roles). View [`models`](../../yaml-reference.md#models) in the YAML Reference for more details. +Continue supports [many model providers](../../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](../../customize/model-roles). View [`models`](../../reference.md#models) in the YAML Reference for more details. ## Context Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and Github issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. -Learn more about context providers [here](../../yaml-reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../yaml-reference.md#context). +Learn more about context providers [here](../../reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../reference.md#context). ## Docs Docs are blocks that point to documentation sites, which will be indexed locally and then can be referenced as context using @Docs in Chat. [Explore docs](https://hub.continue.dev/explore/docs) on the hub. -Learn more in the [@Docs deep dive](../../customize/deep-dives/docs.mdx), and view [`docs`](../../yaml-reference.md#docs) in the YAML Reference for more details. +Learn more in the [@Docs deep dive](../../customize/deep-dives/docs.mdx), and view [`docs`](../../reference.md#docs) in the YAML Reference for more details. ## MCP Servers Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub. -Learn more in the [Tools deep dive](../../customize/tools.mdx), and view [`mcpServers`](../../yaml-reference.md#mcpservers) in the YAML Reference for more details. +Learn more in the [MCP deep dive](../../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../../reference.md#mcpservers) in the YAML Reference for more details. ## Rules Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub. -Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and view [`rules`](../../yaml-reference.md#rules) in the YAML Reference for more details. +Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and view [`rules`](../../reference.md#rules) in the YAML Reference for more details. ## Prompts @@ -43,13 +43,13 @@ Prompts blocks are pre-written, reusable prompts that can be referenced at any t Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files: -1. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and -2. Prompt blocks only show up as slash commands in Chat, not under the `@Prompt Files` context provider +1. Currently, prompt blocks cannot use context providers +2. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and -The `config.yaml` spec for `prompts` can be found [here](../../yaml-reference.md#prompts). +The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). ## Data Data blocks allow you send your development data to custom destinations of your choice. Development data can be used for a variety of purposes, including analyzing usage, gathering insights, or fine-tuning models. You can read more about development data [here](../../customize/deep-dives/development-data.md). Explore data block examples [here](https://hub.continue.dev/explore/data). -Data destinations are configured in the[`data`](../../yaml-reference.md#data) section of `config.yaml`. \ No newline at end of file +Data destinations are configured in the [`data`](../../reference.md#data) section of `config.yaml`. diff --git a/docs/docs/hub/blocks/create-a-block.md b/docs/docs/hub/blocks/create-a-block.md index 870295c99..fcf12acfd 100644 --- a/docs/docs/hub/blocks/create-a-block.md +++ b/docs/docs/hub/blocks/create-a-block.md @@ -23,10 +23,10 @@ To create a block from scratch, you will need to click “New block” in the to ![New block button](/img/hub/block-new-button.png) -After filling out information on the block, you will want to create a block following the `config.yaml` [reference documentation](../../yaml-reference.md). Refer to examples of blocks on [hub.continue.dev](https://hub.continue.dev/explore/models) and visit the [YAML Reference](../../yaml-reference.md#complete-yaml-config-example) docs for more details. +After filling out information on the block, you will want to create a block following the `config.yaml` [reference documentation](../../reference.md). Refer to examples of blocks on [hub.continue.dev](https://hub.continue.dev/explore/models) and visit the [YAML Reference](../../reference.md#complete-yaml-config-example) docs for more details. ![New block page](/img/hub/block-new-page.png) ### Block inputs -Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant. \ No newline at end of file +Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant. diff --git a/docs/docs/hub/blocks/intro.md b/docs/docs/hub/blocks/intro.md index 919aa9f7d..69d0f9224 100644 --- a/docs/docs/hub/blocks/intro.md +++ b/docs/docs/hub/blocks/intro.md @@ -9,4 +9,4 @@ keywords: [blocks, introduction, basics] Blocks are the components you use to build a custom AI code assistant. These include [models](./block-types.md#models), [rules](./block-types.md#rules), [context providers](./block-types.md#context), [prompts](./block-types.md#prompts), [docs](./block-types.md#docs), [data destinations](./block-types.md#data), and [MCP servers](./block-types.md#mcp-servers). -Blocks follow the [`config.yaml`](../../yaml-reference.md) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant. +Blocks follow the [`config.yaml`](../../reference.md) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant. diff --git a/docs/docs/hub/governance/creating-an-org.md b/docs/docs/hub/governance/creating-an-org.md new file mode 100644 index 000000000..aa91d8f5e --- /dev/null +++ b/docs/docs/hub/governance/creating-an-org.md @@ -0,0 +1,20 @@ +--- +title: Creating an Organization +description: Creating an Organization +keywords: [governance, organization, org, create] +--- + +To Create an Organization, click the organization selector in the top right and select `Create Organization` + +![create an org selector](/img/hub/org-selector.png) + +1. Choose a name, which will be used as the display name for your organization throughout the hub +2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and assistant slugs +3. Select an icon for your organization using the image uploader +4. Finally, add a Biography, which will be displayed on your org Home Page + +![Creating an org](/img/hub/create-org-form.png) + +You will then be signed in to your org and taken to the org home page + +![Org home page](/img/hub/org-home-page.png) diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md index 9628dd4cb..e8bd4269e 100644 --- a/docs/docs/introduction.md +++ b/docs/docs/introduction.md @@ -22,4 +22,4 @@ keywords: - [Chat](chat/how-to-use-it) to understand and iterate on code in the sidebar - [Autocomplete](autocomplete/how-to-use-it) to receive inline code suggestions as you type - [Edit](edit/how-to-use-it) to modify code without leaving your current file -- [Actions](actions/how-to-use-it) to establish shortcuts for common use cases +- [Agent](agent/how-to-use-it) to make more substantial changes to your codebase diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md index 11e92a183..0fa8e2d25 100644 --- a/docs/docs/json-reference.md +++ b/docs/docs/json-reference.md @@ -5,7 +5,7 @@ keywords: [config, config_schema.json, json] --- :::info -`config.json` is the original Continue configuration format. The newer and preferred format is [`YAML Config`](./reference). See the [migration guide](./yaml-migration). +We recently introduced a new configuration format, `config.yaml`, to replace `config.json`. See the `config.yaml` reference and migration guide [here](./reference.md). ::: Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). @@ -14,7 +14,8 @@ Below are details for each property that can be set in `config.json`. The config ### `models` -Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it), [Edit](./edit/how-to-use-it), and [Actions](./actions/how-to-use-it). +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md) and [VS Code actions](./customize/deep-dives/vscode-actions.md). + Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. **Properties:** @@ -36,7 +37,7 @@ Each model has specific configuration options tailored to its provider and funct - `engine`: Engine for Azure OpenAI requests. - `capabilities`: Override auto-detected capabilities: - `uploadImage`: Boolean indicating if the model supports image uploads. - - `tools`: Boolean indicating if the model supports tool calls. + - `tools`: Boolean indicating if the model supports tool use. _(AWS Only)_ @@ -59,7 +60,7 @@ Example: "contextLength": 128000, "title": "GPT-4o", "provider": "openai", - "apiKey": "" + "apiKey": "YOUR_API_KEY" } ] } @@ -97,7 +98,7 @@ Specifies options for tab autocompletion behavior. Example -````json title="config.json" +```json title="config.json" { "tabAutocompleteOptions": { "debounceDelay": 500, @@ -105,6 +106,7 @@ Example "disableInFiles": ["*.md"] } } +``` ### `embeddingsProvider` @@ -117,8 +119,8 @@ Embeddings model settings - the model used for @Codebase and @docs. - `apiKey`: API key for the provider. - `apiBase`: Base URL for API requests. - `requestOptions`: Additional HTTP request settings specific to the embeddings provider. -- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. -- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. +- `maxEmbeddingChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxEmbeddingBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. (AWS ONLY) @@ -132,12 +134,12 @@ Example: "embeddingsProvider": { "provider": "openai", "model": "text-embedding-ada-002", - "apiKey": "", - "maxChunkSize": 256, - "maxBatchSize": 5 + "apiKey": "", + "maxEmbeddingChunkSize": 256, + "maxEmbeddingBatchSize": 5 } } -```` +``` ### `completionOptions` @@ -150,7 +152,7 @@ Parameters that control the behavior of text generation and completion settings. - `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. - `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. - `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. -- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `frequencyPenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. - `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). - `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. - `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). @@ -220,7 +222,7 @@ Example "name": "voyage", "params": { "model": "rerank-2", - "apiKey": "" + "apiKey": "" } } } @@ -234,23 +236,21 @@ List of documentation sites to index. - `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs -- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -- `maxDepth`: Maximum depth for crawling. Default `3` + +- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). +- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. Example ```json title="config.json" -{ - "docs": [ +"docs": [ { - "title": "Continue", - "startUrl": "https://docs.continue.dev/intro", - "rootUrl": "https://docs.continue.dev", - "faviconUrl": "https://docs.continue.dev/favicon.ico" - } - ] -} + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] ``` ### `slashCommands` @@ -261,9 +261,106 @@ Custom commands initiated by typing "/" in the sidebar. Commands include predefi - `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". - `description`: Brief description of the command. -- `step`: Used for built-in commands; set the name for pre-configured options. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. - `params`: Additional parameters to configure command behavior (command-specific - see code for command) +The following commands are built-in and can be added to `config.json` to make them visible: + +#### `/share` + +Generate a shareable markdown transcript of your current chat history. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "share", + "description": "Export the current chat session to markdown", + "params": { "outputDir": "~/.continue/session-transcripts" } + } + ] +} +``` + +Use the `outputDir` parameter to specify where you want to the markdown file to be saved. + +#### `/cmd` + +Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +#### `/commit` + +Shows the LLM your current git diff and asks it to generate a commit message. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message for the current changes" + } + ] +} +``` + +#### `/http` + +Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "http", + "description": "Does something custom", + "params": { "url": "" } + } + ] +} +``` + +#### `/issue` + +Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "issue", + "description": "Generate a link to a drafted GitHub issue", + "params": { "repositoryUrl": "https://github.com/continuedev/continue" } + } + ] +} +``` + +#### `/onboard` + +The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "onboard", + "description": "Familiarize yourself with the codebase" + } + ] +} +``` + Example: ```json title="config.json" @@ -285,6 +382,8 @@ Example: } ``` +You can also add your own slash command by following [this tutorial](./customize/tutorials/build-your-own-slash-command.md). + ### `customCommands` User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. @@ -343,40 +442,6 @@ Example } ``` -### `disableSessionTitles` - -Prevents generating summary titles for each chat session when set to `true`. - -### `ui` - -Customizable UI settings to control interface appearance and behavior. - -**Properties:** - -- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. -- `fontSize`: Specifies font size for UI elements. -- `displayRawMarkdown`: If `true`, shows raw markdown in responses. -- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. -- `codeWrap`: If `true`, enables text wrapping in code blocks. - -Example: - -```json title="config.json" -{ - "ui": { - "codeBlockToolbarPosition": "bottom", - "fontSize": 14, - "displayRawMarkdown": false, - "showChatScrollbar": false, - "codeWrap": false - } -} -``` - -### `allowAnonymousTelemetry` - -When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. - ### `userToken` An optional token that identifies the user, primarily for authenticated services. @@ -437,3 +502,28 @@ Example } } ``` + +### Fully deprecated settings + +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/deep-dives/settings.md). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`. + +- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). +- `promptPath`: This value will override during migration. +- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). +- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false +- `tabAutocompleteOptions` + - `useCache`: This value will override during migration. + - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) + - `multilineCompletions`: This value will override during migration. +- `experimental` + - `useChromiumForDocsCrawling`: This value will override during migration. + - `readResponseTTS`: This value will override during migration. +- `ui` - all will override during migration + + - `codeBlockToolbarPosition` + - `fontSize` + - `codeWrap` + - `displayRawMarkdown` + - `showChatScrollbar` + + See [User Settings Page](./customize/deep-dives/settings.md) for more information about each option. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 143fec98b..69f301366 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,231 +1,278 @@ --- -title: config.json Reference -description: Reference for the Continue _config.json_ configuration file -keywords: [config, config_schema.json, json] +title: Config YAML Reference +description: Reference for the Continue configuration YAML file +keywords: [config, yaml, configuration, customize, customization] --- +# config.yaml Reference + +## Introduction + +Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally + +- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension +- Locally + - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml` + - in your workspace in a `/.continue/assistants` folder, with the same naming convention + :::info -We recently introduced a new configuration format, `config.yaml`, to replace `config.json`. See the `config.yaml` reference and migration guide [here](./yaml-reference.md). +Config YAML replaces [`config.json`](./json-reference.md), which is deprecated. View the **[Migration Guide](./yaml-migration.md)**. ::: -Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). +An assistant is made up of: -**All properties at all levels are optional unless explicitly marked required** +1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant +2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. + +A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. + +Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). + +Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. + +### Using Blocks + +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. + +Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. + +:::info +Note that local assistants cannot use blocks that require organization-level secrets. +::: + +For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. + +```yaml title="Assistant models section" +models: + - uses: anthropic/claude-3.5-sonnet # an imported model block + - model: deepseek-reasoner # an explicit model block + provider: ollama +``` + +### Inputs + +Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: + +```yaml title="Block config.yaml" +name: myprofile/custom-model +models: + - name: My Favorite Model + provider: anthropic + apiKey: ${{ inputs.ANTHROPIC_API_KEY }} + defaultCompletionOptions: + temperature: ${{ inputs.TEMP }} +``` + +Which can then be imported like + +```yaml title="Assistant config.yaml" +name: myprofile/custom-assistant +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 +``` + +Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`. + +### Overrides + +Block properties can be also be directly overriden using `override`. For example: + +```yaml title="Assistant config.yaml" +name: myprofile/custom-assistant +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 + override: + roles: + - chat +``` + +## Properties + +Below are details for each property that can be set in `config.yaml`. + +**All properties at all levels are optional unless explicitly marked as required.** + +The top-level properties in the `config.yaml` configuration file are: + +- [`name`](#name) (**required**) +- [`version`](#version) (**required**) +- [`schema`](#schema) (**required**) +- [`models`](#models) +- [`context`](#context) +- [`rules`](#rules) +- [`prompts`](#prompts) +- [`docs`](#docs) +- [`mcpServers`](#mcpservers) +- [`data`](#data) + +--- + +### `name` + +The `name` property specifies the name of your project or configuration. + +```yaml title="config.yaml" +name: MyProject +``` + +--- + +### `version` + +The `version` property specifies the version of your project or configuration. + +### `schema` + +The `schema` property specifies the schema version used for the `config.yaml`, e.g. `v1` + +--- ### `models` -Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). -Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. +The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing. **Properties:** -- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. -- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, `xAI`, etc., see IntelliJ suggestions. -- `model` (**required**): The name of the model, used for prompt template auto-detection. Use `AUTODETECT` special name to get all available models. -- `apiKey`: API key required by providers like OpenAI, Anthropic, Cohere, and xAI. -- `apiBase`: The base URL of the LLM API. -- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). -- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. -- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. -- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). -- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. -- `systemMessage`: A system message that will precede responses from the LLM. -- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. -- `apiType`: Specifies the type of API (`openai` or `azure`). -- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). -- `engine`: Engine for Azure OpenAI requests. -- `capabilities`: Override auto-detected capabilities: - - `uploadImage`: Boolean indicating if the model supports image uploads. - - `tools`: Boolean indicating if the model supports tool use. +- `name` (**required**): A unique name to identify the model within your configuration. +- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). +- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). +- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. +- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. +- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: -_(AWS Only)_ + - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. + - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. -- `profile`: AWS security profile for authorization. -- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). -- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). +- `defaultCompletionOptions`: Default completion options for model settings. -Example: + **Properties:** -```json title="config.json" -{ - "models": [ - { - "title": "Ollama", - "provider": "ollama", - "model": "AUTODETECT" - }, - { - "model": "gpt-4o", - "contextLength": 128000, - "title": "GPT-4o", - "provider": "openai", - "apiKey": "YOUR_API_KEY" - } - ] -} + - `contextLength`: Maximum context length of the model, typically in tokens. + - `maxTokens`: Maximum number of tokens to generate in a completion. + - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). + - `topP`: The cumulative probability for nucleus sampling. + - `topK`: Maximum number of tokens considered at each step. + - `stop`: An array of stop tokens that will terminate the completion. + - `n`: Number of completions to generate. + +- `requestOptions`: HTTP request options specific to the model. + + **Properties:** + + - `timeout`: Timeout for each request to the language model. + - `verifySsl`: Whether to verify SSL certificates for requests. + - `caBundlePath`: Path to a custom CA bundle for HTTP requests. + - `proxy`: Proxy URL for HTTP requests. + - `headers`: Custom headers for HTTP requests. + - `extraBodyProperties`: Additional properties to merge with the HTTP request body. + - `noProxy`: List of hostnames that should bypass the specified proxy. + - `clientCertificate`: Client certificate for HTTP requests. + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +#### Example: + +```yaml title="config.yaml" +models: + - name: GPT-4o + provider: openai + model: gpt-4o + roles: + - chat + - edit + - apply + defaultCompletionOptions: + temperature: 0.7 + maxTokens: 1500 + + - name: Codestral + provider: mistral + model: codestral-latest + roles: + - autocomplete + + - name: My Model - OpenAI-Compatible + provider: openai + apiBase: http://my-endpoint/v1 + model: my-custom-model + capabilities: + - tool_use + - image_input + roles: + - chat + - edit ``` -### `tabAutocompleteModel` +--- -Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. +### `context` + +The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters. + +More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx) + +**Properties:** + +- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). +- `params`: Optional parameters to configure the context provider's behavior. + +**Example:** + +```yaml title="config.yaml" +context: + - provider: files + - provider: code + - provider: codebase + params: + nFinal: 10 + - provider: docs + - provider: diff + - provider: folder + - provider: terminal +``` + +--- + +### `rules` + +List of rules that the LLM should follow. These are inserted into the system message for all chat requests. Example -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "My Starcoder", - "provider": "ollama", - "model": "starcoder2:3b" - } -} +```yaml title="config.yaml" +rules: + - uses: myprofile/my-mood-setter + with: + MOOD: happy + - Always annotate Python functions with their parameter and return types + - Always write Google style docstrings for functions and classes ``` -### `tabAutocompleteOptions` +--- -Specifies options for tab autocompletion behavior. +### `prompts` -**Properties:** +A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. -- `disable`: If `true`, disables tab autocomplete (default: `false`). -- `maxPromptTokens`: Maximum number of tokens for the prompt (default: `1024`). -- `debounceDelay`: Delay (in ms) before triggering autocomplete (default: `350`). -- `maxSuffixPercentage`: Maximum percentage of prompt for suffix (default: `0.2`). -- `prefixPercentage`: Percentage of input for prefix (default: `0.3`). -- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. -- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). - -Example - -```json title="config.json" -{ - "tabAutocompleteOptions": { - "debounceDelay": 500, - "maxPromptTokens": 1500, - "disableInFiles": ["*.md"] - } -} +```yaml title="config.yaml" +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities ``` -### `embeddingsProvider` - -Embeddings model settings - the model used for @Codebase and @docs. - -**Properties:** - -- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `gemini`, etc -- `model`: Model name for embeddings. -- `apiKey`: API key for the provider. -- `apiBase`: Base URL for API requests. -- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. -- `maxEmbeddingChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. -- `maxEmbeddingBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - -(AWS ONLY) - -- `region`: Specifies the region hosting the model. -- `profile`: AWS security profile. - -Example: - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "openai", - "model": "text-embedding-ada-002", - "apiKey": "", - "maxEmbeddingChunkSize": 256, - "maxEmbeddingBatchSize": 5 - } -} -``` - -### `completionOptions` - -Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. - -**Properties:** - -- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). -- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. -- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. -- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. -- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. -- `frequencyPenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. -- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). -- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. -- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). -- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. -- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). -- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. - -Example - -```json title="config.json" -{ - "completionOptions": { - "stream": false, - "temperature": 0.5 - } -} -``` - -### `requestOptions` - -Default HTTP request options that apply to all models and context providers, unless overridden at the model level. - -**Properties:** - -- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). -- `verifySsl`: Whether to verify SSL certificates for requests. -- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) -- `proxy`: Proxy URL to use for HTTP requests. -- `headers`: Custom headers for HTTP requests. -- `extraBodyProperties`: Additional properties to merge with the HTTP request body. -- `noProxy`: List of hostnames that should bypass the specified proxy. -- `clientCertificate`: Client certificate for HTTP requests. - - - `cert`: Path to the client certificate file. - - `key`: Path to the client certificate key file. - - `passphrase`: Optional passphrase for the client certificate key file. - -Example - -```json title="config.json" -{ - "requestOptions": { - "headers": { - "X-Auth-Token": "xxx" - } - } -} -``` - -### `reranker` - -Configuration for the reranker model used in response ranking. - -**Properties:** - -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `huggingface-tei`, `bedrock` -- `params`: - - `model`: Model name - - `apiKey`: Api key - - `region`: Region (for Bedrock only) - -Example - -```json title="config.json" -{ - "reranker": { - "name": "voyage", - "params": { - "model": "rerank-2", - "apiKey": "" - } - } -} -``` +--- ### `docs` @@ -233,7 +280,7 @@ List of documentation sites to index. **Properties:** -- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs - `maxDepth`: Maximum link depth for crawling. Default `4` @@ -242,188 +289,192 @@ List of documentation sites to index. Example -```json title="config.json" -"docs": [ - { - "title": "Continue", - "startUrl": "https://docs.continue.dev/intro", - "faviconUrl": "https://docs.continue.dev/favicon.ico", - } -] +```yaml title="config.yaml" +docs: + - name: Continue + startUrl: https://docs.continue.dev/intro + favicon: https://docs.continue.dev/favicon.ico ``` -### `slashCommands` +--- -Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. +### `mcpServers` + + + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. **Properties:** -- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". -- `description`: Brief description of the command. -- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. -- `params`: Additional parameters to configure command behavior (command-specific - see code for command) +- `name` (**required**): The name of the MCP server. +- `command` (**required**): The command used to start the server. +- `args`: An optional array of arguments for the command. +- `env`: An optional map of environment variables for the server process. -Example: +**Example:** -```json title="config.json" -{ - "slashCommands": [ - { - "name": "commit", - "description": "Generate a commit message" - }, - { - "name": "share", - "description": "Export this session as markdown" - }, - { - "name": "cmd", - "description": "Generate a shell command" - } - ] -} +```yaml title="config.yaml" +mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db ``` -### `customCommands` +### `data` -User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. +Destinations to which [development data](./customize/deep-dives/development-data.md) will be sent. **Properties:** -- `name`: The name of the custom command. -- `prompt`: Text prompt for the command. -- `description`: Brief description explaining the command's function. +- `name` (**required**): The display name of the data destination +- `destination` (**required**): The destination/endpoint that will receive the data. Can be: + - an HTTP endpoint that will receive a POST request with a JSON blob + - a file URL to a directory in which events will be dumpted to `.jsonl` files +- `schema` (**required**): the schema version of the JSON blobs to be sent +- `events`: an array of event names to include. Defaults to all events if not specified. +- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` +- `apiKey`: api key to be sent with request (Bearer header) +- `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models). -Example: + **Example:** -```json title="config.json" -{ - "customCommands": [ - { - "name": "test", - "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "Write unit tests for highlighted code" - } - ] -} +```yaml title="config.yaml" +data: + - name: Local Data Bank + destination: file:///Users/dallin/Documents/code/continuedev/continue-extras/external-data + schema: 0.2.0 + level: all + - name: My Private Company + destination: https://mycompany.com/ingest + schema: 0.2.0 + level: noCode + events: + - autocomplete + - chatInteraction ``` -### `contextProviders` +--- -List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. +## Complete YAML Config Example -**Properties:** +Putting it all together, here's a complete example of a `config.yaml` configuration file: -- `name`: Name of the context provider, e.g. `docs` or `web` -- `params`: A context-provider-specific record of params to configure the context behavior +```yaml title="config.yaml" +name: MyProject +version: 0.0.1 +schema: v1 -Example +models: + - uses: anthropic/claude-3.5-sonnet + with: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + override: + defaultCompletionOptions: + temperature: 0.8 + - name: GPT-4 + provider: openai + model: gpt-4 + roles: + - chat + - edit + defaultCompletionOptions: + temperature: 0.5 + maxTokens: 2000 + requestOptions: + headers: + Authorization: Bearer YOUR_OPENAI_API_KEY -```json title="config.json" -{ - "contextProviders": [ - { - "name": "code", - "params": {} - }, - { - "name": "docs", - "params": {} - }, - { - "name": "diff", - "params": {} - }, - { - "name": "open", - "params": {} - } - ] -} + - name: Ollama Starcoder + provider: ollama + model: starcoder + roles: + - autocomplete + defaultCompletionOptions: + temperature: 0.3 + stop: + - "\n" + +rules: + - Give concise responses + - Always assume TypeScript rather than JavaScript + +prompts: + - name: test + description: Unit test a function + prompt: | + Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. + - uses: myprofile/my-favorite-prompt + +context: + - provider: diff + - provider: file + - provider: codebase + - provider: code + - provider: docs + params: + startUrl: https://docs.example.com/introduction + rootUrl: https://docs.example.com + maxDepth: 3 + +mcpServers: + - name: DevServer + command: npm + args: + - run + - dev + env: + PORT: "3000" + +data: + - name: My Private Company + destination: https://mycompany.com/ingest + schema: 0.2.0 + level: noCode + events: + - autocomplete + - chatInteraction ``` -### `userToken` +## Using YAML anchors to avoid config duplication -An optional token that identifies the user, primarily for authenticated services. +You can also use node anchors to avoid duplication of properties. To do so, +adding the YAML version header `%YAML 1.1` is needed, here's an example of +a `config.yaml` configuration file using anchors: -### `systemMessage` +```yaml title="config.yaml" +%YAML 1.1 +--- +name: MyProject +version: 0.0.1 +schema: v1 -Defines a system message that appears before every response from the language model, providing guidance or context. +model_defaults: &model_defaults + provider: openai + apiKey: my-api-key + apiBase: https://api.example.com/llm -### `experimental` +models: + - name: mistral + <<: *model_defaults + model: mistral-7b-instruct + roles: + - chat + - edit -Several experimental config parameters are available, as described below: + - name: qwen2.5-coder-7b-instruct + <<: *model_defaults + model: qwen2.5-coder-7b-instruct + roles: + - chat + - edit -`experimental`: - -- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= -- `modelRoles`: - - `inlineEdit`: Model title for inline edits. - - `applyCodeBlock`: Model title for applying code blocks. - - `repoMapFileSelection`: Model title for repo map selections. -- `quickActions`: Array of custom quick actions - - `title` (**required**): Display title for the quick action. - - `prompt` (**required**): Prompt for quick action. - - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. -- `contextMenuPrompts`: - - `comment`: Prompt for commenting code. - - `docstring`: Prompt for adding docstrings. - - `fix`: Prompt for fixing code. - - `optimize`: Prompt for optimizing code. -- `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol) - -Example - -```json title="config.json" -{ - "experimental": { - "modelRoles": { - "inlineEdit": "Edit Model" - }, - "quickActions": [ - { - "title": "Tags", - "prompt": "Return a list of any function and class names from the included code block", - "sendToChat": true - } - ], - "contextMenuPrompts": { - "fixGrammar": "Fix grammar in the above but allow for typos." - }, - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } -} + - name: qwen2.5-coder-7b + <<: *model_defaults + model: qwen2.5-coder-7b + useLegacyCompletionsEndpoint: false + roles: + - autocomplete ``` - -### Fully deprecated settings - -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. - -- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). -- `promptPath`: This value will override during migration. -- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). -- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false -- `tabAutocompleteOptions` - - `useCache`: This value will override during migration. - - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) - - `multilineCompletions`: This value will override during migration. -- `experimental` - - `useChromiumForDocsCrawling`: This value will override during migration. - - `readResponseTTS`: This value will override during migration. -- `ui` - all will override during migration - - - `codeBlockToolbarPosition` - - `fontSize` - - `codeWrap` - - `displayRawMarkdown` - - `showChatScrollbar` - - See [User Settings Page](./customize/settings.md) for more information about each option. diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index e21a93164..2383b6242 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -26,6 +26,6 @@ The following usage information is collected and reported: ## How to Opt Out -You can disable anonymous telemetry by visiting the [User Settings Page](./customize/settings.md) and toggling "Allow Anonymous Telemetry" off. +You can disable anonymous telemetry by visiting the [User Settings Page](./customize/deep-dives/settings.md) and toggling "Allow Anonymous Telemetry" off. Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index ec189e429..82df8edd2 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -12,7 +12,7 @@ See also - [Intro to YAML](https://yaml.org/) - [JSON Continue Config Reference](/json-reference) -- [YAML Continue Config Reference](/yaml-reference) +- [YAML Continue Config Reference](/reference) ## Create YAML file @@ -38,9 +38,9 @@ Add all model configurations in `config.json`, including models in `models`, `ta - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` -Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](./reference.md#models) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](./reference.md#models) @@ -327,9 +327,9 @@ mcpServers: ## Deprecated configuration options -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md) (Gear Icon). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/deep-dives/settings.md) (Gear Icon). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`. -See the [JSON Config Reference](./reference#fully-deprecated-settings) for more information on fully deprecated options. +See the [JSON Config Reference](./json-reference#fully-deprecated-settings) for more information on fully deprecated options. The following top-level fields from `config.json` still work when using `config.json` but have been deprecated and don't have a YAML equivalent: diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md deleted file mode 100644 index 2039c3887..000000000 --- a/docs/docs/yaml-reference.md +++ /dev/null @@ -1,500 +0,0 @@ ---- -title: Config YAML Reference -description: Reference for the Continue configuration YAML file -keywords: [config, yaml, configuration, customize, customization] ---- - -# config.yaml Reference - -## Introduction - -Continue hub assistants are defined using the `config.yaml` specification. Local assistants can also be configured using a YAML file `config.yaml` placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) - -:::info -Config YAML replaces `config.json`. View the **[Migration Guide](/yaml-migration)**. -::: - -An assistant is made up of: - -1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant -2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. - -A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. - -Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). - -Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. - -### Using Blocks - -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. - -Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. - -:::info -Note that `uses` blocks cannot be used with a local `config.yaml` -::: - -For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. - -```yaml title="Assistant models section" -models: - - uses: anthropic/claude-3.5-sonnet # an imported model block - - model: deepseek-reasoner # an explicit model block - provider: ollama -``` - -### Inputs - -Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: - -```yaml title="Block config.yaml" -name: myprofile/custom-model -models: - - name: My Favorite Model - provider: anthropic - apiKey: ${{ inputs.ANTHROPIC_API_KEY }} - defaultCompletionOptions: - temperature: ${{ inputs.TEMP }} -``` - -Which can then be imported like - -```yaml title="Assistant config.yaml" -name: myprofile/custom-assistant -models: - - uses: myprofile/custom-model - with: - ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} - TEMP: 0.9 -``` - -Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`. - -### Overrides - -Block properties can be also be directly overriden using `override`. For example: - -```yaml title="Assistant config.yaml" -name: myprofile/custom-assistant -models: - - uses: myprofile/custom-model - with: - ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} - TEMP: 0.9 - override: - roles: - - chat -``` - -## Properties - -Below are details for each property that can be set in `config.yaml`. - -**All properties at all levels are optional unless explicitly marked as required.** - -The top-level properties in the `config.yaml` configuration file are: - -- [`name`](#name) (**required**) -- [`version`](#version) (**required**) -- [`schema`](#schema) (**required**) -- [`models`](#models) -- [`context`](#context) -- [`rules`](#rules) -- [`prompts`](#prompts) -- [`docs`](#docs) -- [`mcpServers`](#mcpservers) -- [`data`](#data) - ---- - -### `name` - -The `name` property specifies the name of your project or configuration. - -```yaml title="config.yaml" -name: MyProject -``` - ---- - -### `version` - -The `version` property specifies the version of your project or configuration. - -### `schema` - -The `schema` property specifies the schema version used for the `config.yaml`, e.g. `v1` - ---- - -### `models` - -The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing. - -**Properties:** - -- `name` (**required**): A unique name to identify the model within your configuration. -- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). -- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). -- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. -- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. -- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: - - - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. - - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - -- `defaultCompletionOptions`: Default completion options for model settings. - - **Properties:** - - - `contextLength`: Maximum context length of the model, typically in tokens. - - `maxTokens`: Maximum number of tokens to generate in a completion. - - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). - - `topP`: The cumulative probability for nucleus sampling. - - `topK`: Maximum number of tokens considered at each step. - - `stop`: An array of stop tokens that will terminate the completion. - - `n`: Number of completions to generate. - -- `requestOptions`: HTTP request options specific to the model. - - **Properties:** - - - `timeout`: Timeout for each request to the language model. - - `verifySsl`: Whether to verify SSL certificates for requests. - - `caBundlePath`: Path to a custom CA bundle for HTTP requests. - - `proxy`: Proxy URL for HTTP requests. - - `headers`: Custom headers for HTTP requests. - - `extraBodyProperties`: Additional properties to merge with the HTTP request body. - - `noProxy`: List of hostnames that should bypass the specified proxy. - - `clientCertificate`: Client certificate for HTTP requests. - - `cert`: Path to the client certificate file. - - `key`: Path to the client certificate key file. - - `passphrase`: Optional passphrase for the client certificate key file. - -#### Example: - -```yaml title="config.yaml" -models: - - name: GPT-4o - provider: openai - model: gpt-4o - roles: - - chat - - edit - - apply - defaultCompletionOptions: - temperature: 0.7 - maxTokens: 1500 - - - name: Codestral - provider: mistral - model: codestral-latest - roles: - - autocomplete - - - name: My Model - OpenAI-Compatible - provider: openai - apiBase: http://my-endpoint/v1 - model: my-custom-model - capabilities: - - tool_use - - image_input - roles: - - chat - - edit -``` - ---- - -### `context` - -The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters. - -More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx) - -**Properties:** - -- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). -- `params`: Optional parameters to configure the context provider's behavior. - -**Example:** - -```yaml title="config.yaml" -context: - - provider: files - - provider: code - - provider: codebase - params: - nFinal: 10 - - provider: docs - - provider: diff - - provider: folder - - provider: terminal -``` - ---- - -### `rules` - -List of rules that the LLM should follow. These are inserted into the system message for all chat requests. - -Example - -```yaml title="config.yaml" -rules: - - uses: myprofile/my-mood-setter - with: - MOOD: happy - - Always annotate Python functions with their parameter and return types - - Always write Google style docstrings for functions and classes -``` - ---- - -### `prompts` - -A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. - -```yaml title="config.yaml" -prompts: - - name: check - description: Check for mistakes in my code - prompt: | - Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: - - Syntax errors - - Logic errors - - Security vulnerabilities -``` - ---- - -### `docs` - -List of documentation sites to index. - -**Properties:** - -- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. -- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs - -- `maxDepth`: Maximum link depth for crawling. Default `4` -- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). -- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. - -Example - -```yaml title="config.yaml" -docs: - - name: Continue - startUrl: https://docs.continue.dev/intro - favicon: https://docs.continue.dev/favicon.ico -``` - ---- - -### `mcpServers` - - - -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. - -**Properties:** - -- `name` (**required**): The name of the MCP server. -- `command` (**required**): The command used to start the server. -- `args`: An optional array of arguments for the command. -- `env`: An optional map of environment variables for the server process. - -**Example:** - -```yaml title="config.yaml" -mcpServers: - - name: My MCP Server - command: uvx - args: - - mcp-server-sqlite - - --db-path - - /Users/NAME/test.db -``` - -### `data` - -Destinations to which [development data](./customize/deep-dives/development-data.md) will be sent. - -**Properties:** - -- `name` (**required**): The display name of the data destination -- `destination` (**required**): The destination/endpoint that will receive the data. Can be: - - an HTTP endpoint that will receive a POST request with a JSON blob - - a file URL to a directory in which events will be dumpted to `.jsonl` files -- `schema` (**required**): the schema version of the JSON blobs to be sent -- `events`: an array of event names to include. Defaults to all events if not specified. -- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` -- `apiKey`: api key to be sent with request (Bearer header) -- `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models). - - **Example:** - -```yaml title="config.yaml" -data: - - name: Local Data Bank - destination: file:///Users/dallin/Documents/code/continuedev/continue-extras/external-data - schema: 0.2.0 - level: all - - name: My Private Company - destination: https://mycompany.com/ingest - schema: 0.2.0 - level: noCode - events: - - autocomplete - - chatInteraction -``` - ---- - -## Complete YAML Config Example - -Putting it all together, here's a complete example of a `config.yaml` configuration file: - -```yaml title="config.yaml" -name: MyProject -version: 0.0.1 -schema: v1 - -models: - - uses: anthropic/claude-3.5-sonnet - with: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - override: - defaultCompletionOptions: - temperature: 0.8 - - name: GPT-4 - provider: openai - model: gpt-4 - roles: - - chat - - edit - defaultCompletionOptions: - temperature: 0.5 - maxTokens: 2000 - requestOptions: - headers: - Authorization: Bearer YOUR_OPENAI_API_KEY - - - name: Ollama Starcoder - provider: ollama - model: starcoder - roles: - - autocomplete - defaultCompletionOptions: - temperature: 0.3 - stop: - - "\n" - -rules: - - Give concise responses - - Always assume TypeScript rather than JavaScript - -prompts: - - name: test - description: Unit test a function - prompt: | - Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. - - uses: myprofile/my-favorite-prompt - -context: - - provider: diff - - provider: file - - provider: codebase - - provider: code - - provider: docs - params: - startUrl: https://docs.example.com/introduction - rootUrl: https://docs.example.com - maxDepth: 3 - -mcpServers: - - name: DevServer - command: npm - args: - - run - - dev - env: - PORT: "3000" - -data: - - name: My Private Company - destination: https://mycompany.com/ingest - schema: 0.2.0 - level: noCode - events: - - autocomplete - - chatInteraction -``` - -## Using YAML anchors to avoid config duplication - -You can also use node anchors to avoid duplication of properties. To do so, -adding the YAML version header `%YAML 1.1` is needed, here's an example of -a `config.yaml` configuration file using anchors: - -```yaml title="config.yaml" -%YAML 1.1 ---- -name: MyProject -version: 0.0.1 -schema: v1 - -model_defaults: &model_defaults - provider: openai - apiKey: my-api-key - apiBase: https://api.example.com/llm - -models: - - name: mistral - <<: *model_defaults - model: mistral-7b-instruct - roles: - - chat - - edit - - - name: qwen2.5-coder-7b-instruct - <<: *model_defaults - model: qwen2.5-coder-7b-instruct - roles: - - chat - - edit - - - name: qwen2.5-coder-7b - <<: *model_defaults - model: qwen2.5-coder-7b - useLegacyCompletionsEndpoint: false - roles: - - autocomplete -``` - -### Fully deprecated settings - -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. - -- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). -- `promptPath`: This value will override during migration. -- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). -- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false -- `tabAutocompleteOptions` - - `useCache`: This value will override during migration. - - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) - - `multilineCompletions`: This value will override during migration. -- `experimental` - - `useChromiumForDocsCrawling`: This value will override during migration. - - `readResponseTTS`: This value will override during migration. -- `ui` - all will override during migration - - - `codeBlockToolbarPosition` - - `fontSize` - - `codeWrap` - - `displayRawMarkdown` - - `showChatScrollbar` - - See [User Settings Page](./customize/settings.md) for more information about each option. diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c8d987266..c74e6a71b 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -93,6 +93,13 @@ const config = { label: "User Guide", href: "/", }, + { + type: "docSidebar", + sidebarId: "hubSidebar", + position: "left", + label: "Hub", + href: "/hub/introduction", + }, { type: "docSidebar", sidebarId: "customizingSidebar", @@ -107,13 +114,7 @@ const config = { label: "Reference", href: "/reference", }, - { - type: "docSidebar", - sidebarId: "hubSidebar", - position: "left", - label: "Hub", - href: "/hub/introduction", - }, + { to: "https://github.com/continuedev/continue", label: "GitHub", @@ -222,20 +223,20 @@ const config = { }, { to: "/customize/overview", - from: "/customize", + from: ["/customize", "/customization"], }, { - to: "/customize/overview", - from: "/customization", + to: "/customize/deep-dives/mcp", + from: "/customize/tools", }, { to: "/getting-started/install", from: ["/install/vscode", "/install/jetbrains"], }, - // { - // to: "/getting-started/install", - // from: "/getting-started", - // }, + { + to: "/customize/deep-dives/settings", + from: "/customize/settings", + }, { to: "/customize/model-roles", from: ["/customize/model-types", "/setup/overview"], @@ -288,9 +289,24 @@ const config = { to: "/customize/deep-dives/prompt-files", from: ["/walkthroughs/prompt-files", "/features/prompt-files"], }, + // TODO - actions redirects { - to: "/actions/how-to-use-it#quick-actions", - from: "/walkthroughs/quick-actions", + to: "/customize/deep-dives/slash-commands", + from: [ + "/actions/how-to-use-it", + "/actions/how-to-customize", + "/actions", + "/actions/model-setup", + "/actions/context-selection", + "/actions/how-it-works", + "/customize/slash-commands", + "/customization/slash-commands", + ], + }, + + { + to: "/customize/deep-dives/vscode-actions", + from: ["/walkthroughs/quick-actions"], }, { to: "/customize/changelog", @@ -298,7 +314,11 @@ const config = { }, { to: "/reference", - from: ["/customization/code-config", "/reference/config"], + from: [ + "/customization/code-config", + "/reference/config", + "/yaml-reference", + ], }, { to: "/customize/context-providers", @@ -348,10 +368,6 @@ const config = { to: "/customize/model-providers/openai", from: "/reference/Model Providers/openai", }, - { - to: "/customize/slash-commands", - from: "/customization/slash-commands", - }, { to: "/customize/tutorials/custom-code-rag", from: "/walkthroughs/custom-code-rag", @@ -458,12 +474,12 @@ const config = { from: "/chat", }, { - to: "/edit/how-to-use-it", - from: "/edit", + to: "/agent/how-to-use-it", + from: "/agent", }, { - to: "/actions/how-to-use-it", - from: "/actions", + to: "/edit/how-to-use-it", + from: "/edit", }, { to: "/autocomplete/how-to-use-it", diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md index e14ac4afc..151eb87e8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md @@ -31,12 +31,6 @@ toc_max_heading_level: 5 3. 本地保存嵌入在你的机器上 4. 通过 `@Docs` 上下文提供者提供访问索引内容 -## 预先索引文档网站 - -我们提供一个流行的框架和库的预先索引文档网站的选择。你可以 [在这里查看可用的预先索引网站和请求附加内容](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts) 列表。 - -## 索引你自己的文档 - ### 通过 `@Docs` 上下文提供者 为了添加一个单独的文档网站,我们推荐使用 `@Docs` 上下文提供者。 diff --git a/docs/sidebars.js b/docs/sidebars.js index 0e83628a4..20a47be93 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -47,11 +47,11 @@ const sidebars = { }, { type: "category", - label: "Actions", + label: "Agent", items: [ { type: "autogenerated", - dirName: "actions", + dirName: "agent", }, ], }, @@ -59,8 +59,8 @@ const sidebars = { "troubleshooting", { type: "link", - label: "Customize", - href: "/customize/overview", + label: "Hub", + href: "/hub/introduction", }, ], customizingSidebar: [ @@ -128,18 +128,11 @@ const sidebars = { }, ], }, - "customize/settings", { type: "link", label: "Reference", href: "/reference", }, - { - type: "link", - label: "YAML Reference", - href: "/yaml-reference", - }, - "customize/changelog", ], hubSidebar: [ "hub/introduction", @@ -172,7 +165,16 @@ const sidebars = { { type: "category", label: "Governance", - items: ["hub/governance/org-permissions", "hub/governance/pricing"], + items: [ + "hub/governance/org-permissions", + "hub/governance/creating-an-org", + "hub/governance/pricing", + ], + }, + { + type: "link", + label: "Customize", + href: "/customize/overview", }, ], }; diff --git a/docs/static/img/agent-permission.png b/docs/static/img/agent-permission.png new file mode 100644 index 000000000..ca7cfaf4f Binary files /dev/null and b/docs/static/img/agent-permission.png differ diff --git a/docs/static/img/agent-response.png b/docs/static/img/agent-response.png new file mode 100644 index 000000000..472360df1 Binary files /dev/null and b/docs/static/img/agent-response.png differ diff --git a/docs/static/img/agent.gif b/docs/static/img/agent.gif new file mode 100644 index 000000000..7edf735a6 Binary files /dev/null and b/docs/static/img/agent.gif differ diff --git a/docs/static/img/configure-continue.png b/docs/static/img/configure-continue.png index 57355638f..bb1d5ed30 100644 Binary files a/docs/static/img/configure-continue.png and b/docs/static/img/configure-continue.png differ diff --git a/docs/static/img/edit-mode-add-all-open-files.png b/docs/static/img/edit-mode-add-all-open-files.png new file mode 100644 index 000000000..9aa981347 Binary files /dev/null and b/docs/static/img/edit-mode-add-all-open-files.png differ diff --git a/docs/static/img/edit-mode-add-files.png b/docs/static/img/edit-mode-add-files.png new file mode 100644 index 000000000..b2f97f314 Binary files /dev/null and b/docs/static/img/edit-mode-add-files.png differ diff --git a/docs/static/img/edit-mode-multi-file-diffs.png b/docs/static/img/edit-mode-multi-file-diffs.png new file mode 100644 index 000000000..caa9f2d25 Binary files /dev/null and b/docs/static/img/edit-mode-multi-file-diffs.png differ diff --git a/docs/static/img/edit-mode-multi-file-generation.png b/docs/static/img/edit-mode-multi-file-generation.png new file mode 100644 index 000000000..20f3fe98e Binary files /dev/null and b/docs/static/img/edit-mode-multi-file-generation.png differ diff --git a/docs/static/img/edit-mode-multi-file-output.png b/docs/static/img/edit-mode-multi-file-output.png new file mode 100644 index 000000000..1ceb00714 Binary files /dev/null and b/docs/static/img/edit-mode-multi-file-output.png differ diff --git a/docs/static/img/edit-mode-single-file-diff.png b/docs/static/img/edit-mode-single-file-diff.png new file mode 100644 index 000000000..90e33cfc7 Binary files /dev/null and b/docs/static/img/edit-mode-single-file-diff.png differ diff --git a/docs/static/img/header-buttons.png b/docs/static/img/header-buttons.png index f6a644d03..6824043cf 100644 Binary files a/docs/static/img/header-buttons.png and b/docs/static/img/header-buttons.png differ diff --git a/docs/static/img/hub/assistant-create-sidebar.png b/docs/static/img/hub/assistant-create-sidebar.png index 159806d31..45a1e22ee 100644 Binary files a/docs/static/img/hub/assistant-create-sidebar.png and b/docs/static/img/hub/assistant-create-sidebar.png differ diff --git a/docs/static/img/hub/create-org-form.png b/docs/static/img/hub/create-org-form.png new file mode 100644 index 000000000..db4497ec2 Binary files /dev/null and b/docs/static/img/hub/create-org-form.png differ diff --git a/docs/static/img/hub/org-home-page.png b/docs/static/img/hub/org-home-page.png new file mode 100644 index 000000000..a85e283c4 Binary files /dev/null and b/docs/static/img/hub/org-home-page.png differ diff --git a/docs/static/img/hub/org-selector.png b/docs/static/img/hub/org-selector.png new file mode 100644 index 000000000..a154659be Binary files /dev/null and b/docs/static/img/hub/org-selector.png differ diff --git a/docs/static/img/lump-toolbar.png b/docs/static/img/lump-toolbar.png new file mode 100644 index 000000000..b3dcf88c2 Binary files /dev/null and b/docs/static/img/lump-toolbar.png differ diff --git a/docs/static/img/mode-select-agent.png b/docs/static/img/mode-select-agent.png new file mode 100644 index 000000000..2940a94fb Binary files /dev/null and b/docs/static/img/mode-select-agent.png differ diff --git a/docs/static/img/model-roles-edit.png b/docs/static/img/model-roles-edit.png new file mode 100644 index 000000000..2d033a5d1 Binary files /dev/null and b/docs/static/img/model-roles-edit.png differ diff --git a/docs/static/img/select-edit-mode.png b/docs/static/img/select-edit-mode.png new file mode 100644 index 000000000..e68d6dc25 Binary files /dev/null and b/docs/static/img/select-edit-mode.png differ diff --git a/docs/static/img/settings-model-roles.png b/docs/static/img/settings-model-roles.png index 7a2d24407..347140c7e 100644 Binary files a/docs/static/img/settings-model-roles.png and b/docs/static/img/settings-model-roles.png differ diff --git a/docs/static/img/settings-page.png b/docs/static/img/settings-page.png index f4b58cfd5..53bd1296f 100644 Binary files a/docs/static/img/settings-page.png and b/docs/static/img/settings-page.png differ diff --git a/docs/static/img/tool-policies.png b/docs/static/img/tool-policies.png new file mode 100644 index 000000000..d5e52a607 Binary files /dev/null and b/docs/static/img/tool-policies.png differ diff --git a/docs/static/img/tool-use-example.png b/docs/static/img/tool-use-example.png deleted file mode 100644 index 63f1c456a..000000000 Binary files a/docs/static/img/tool-use-example.png and /dev/null differ diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 0d846c3d2..cf4a7e0f1 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.5 +pluginVersion=1.0.8 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index 3c6b27f05..a4e060265 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -126,12 +126,3 @@ class OpenConfigAction : AnAction() { continuePluginService.sendToWebview("navigateTo", params) } } - -class OpenMorePageAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val continuePluginService = getContinuePluginService(e.project) ?: return - continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - val params = mapOf("path" to "/more", "toggle" to true) - continuePluginService.sendToWebview("navigateTo", params) - } -} \ No newline at end of file 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 fcf9a468b..b9546aa63 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 @@ -69,7 +69,6 @@ class MessageTypes { "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", - "docs/suggestions", "didCloseFiles", "didSelectOrganization" ) @@ -84,7 +83,6 @@ class MessageTypes { "history/save", "devdata/log", "config/addModel", - "config/addContextProvider", "config/newPromptFile", "config/ideSettingsUpdate", "config/getSerializedProfileInfo", @@ -94,6 +92,7 @@ class MessageTypes { "config/openProfile", "config/updateSharedConfig", "config/updateSelectedModel", + "mcp/reloadServer", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -120,7 +119,6 @@ class MessageTypes { "indexing/reindex", "indexing/abort", "indexing/setPaused", - "docs/getSuggestedDocs", "docs/initStatuses", "docs/getDetails", // diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index abc50a092..591136551 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -140,19 +140,10 @@ - - - - - =20.11.0" diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index b6d94af28..142f9f95d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.13", + "version": "1.1.17", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -258,13 +258,6 @@ "title": "Navigate to a path", "group": "Continue" }, - { - "command": "continue.openMorePage", - "category": "Continue", - "title": "More", - "icon": "$(ellipsis)", - "group": "Continue" - }, { "command": "continue.writeCommentsForCode", "category": "Continue", @@ -512,11 +505,6 @@ "command": "continue.openConfigPage", "group": "navigation@4", "when": "view == continue.continueGUIView" - }, - { - "command": "continue.openMorePage", - "group": "navigation@6", - "when": "view == continue.continueGUIView" } ], "editor/title": [ @@ -636,7 +624,7 @@ "mocha": "^10.4.0", "ovsx": "^0.8.3", "rimraf": "^5.0.5", - "typescript": "^5.3.3", + "typescript": "^5.6.3", "vite": "^4.3.9", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index e44fc60af..d8a9d4e68 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -1,6 +1,7 @@ -const esbuild = require("esbuild"); const fs = require("fs"); +const esbuild = require("esbuild"); + const flags = process.argv.slice(2); const esbuildConfig = { @@ -59,9 +60,9 @@ const esbuildConfig = { // The watcher automatically notices changes to source files // so the only thing it needs to be notified about is if the // output file gets removed. - if (fs.existsSync (outFile)) { - console.log("VS Code Extension esbuild up to date"); - return; + if (fs.existsSync(outFile)) { + console.log("VS Code Extension esbuild up to date"); + return; } fs.watchFile(outFile, (current, previous) => { diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 6972ad9ff..883039263 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -4,7 +4,7 @@ import { exec } from "node:child_process"; import { Range } from "core"; import { EXTENSION_NAME } from "core/control-plane/env"; import { GetGhTokenArgs } from "core/protocol/ide"; -import { editConfigJson, getConfigJsonPath } from "core/util/paths"; +import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; @@ -155,26 +155,39 @@ class VsCodeIde implements IDE { ); // Remove free trial models - editConfigJson((config) => { - let tabAutocompleteModel = undefined; - if (Array.isArray(config.tabAutocompleteModel)) { - tabAutocompleteModel = config.tabAutocompleteModel.filter( - (model) => model.provider !== "free-trial", - ); - } else if ( - config.tabAutocompleteModel?.provider === "free-trial" - ) { - tabAutocompleteModel = undefined; - } + editConfigFile( + (config) => { + let tabAutocompleteModel = undefined; + if (Array.isArray(config.tabAutocompleteModel)) { + tabAutocompleteModel = config.tabAutocompleteModel.filter( + (model) => model.provider !== "free-trial", + ); + } else if ( + config.tabAutocompleteModel?.provider === "free-trial" + ) { + tabAutocompleteModel = undefined; + } - return { - ...config, - models: config.models.filter( - (model) => model.provider !== "free-trial", - ), - tabAutocompleteModel, - }; - }); + return { + ...config, + models: config.models.filter( + (model) => model.provider !== "free-trial", + ), + tabAutocompleteModel, + }; + }, + (config) => { + return { + ...config, + models: config.models?.filter( + (model) => + !( + "provider" in model && model.provider === "free-trial" + ), + ), + }; + }, + ); } else if (selection === "Learn more") { vscode.env.openExternal( vscode.Uri.parse( @@ -216,13 +229,22 @@ class VsCodeIde implements IDE { ) .then((selection) => { if (selection === "Remove for me") { - editConfigJson((configJson) => { - configJson.models = configJson.models.filter( - (model) => model.provider !== "free-trial", - ); - configJson.tabAutocompleteModel = undefined; - return configJson; - }); + editConfigFile( + (configJson) => { + configJson.models = configJson.models.filter( + (model) => model.provider !== "free-trial", + ); + configJson.tabAutocompleteModel = undefined; + return configJson; + }, + (config) => { + config.models = config.models?.filter( + (model) => + !("provider" in model && model.provider === "free-trial"), + ); + return config; + }, + ); } else if (selection === "Open Assistant configuration") { this.openFile(getConfigJsonPath()); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index de8f5cd1e..6a1e35424 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -284,6 +284,9 @@ async function processDiff( } await sidebar.webviewProtocol.request("exitEditMode", undefined); + + // Save the file + await ide.saveFile(newOrCurrentUri); } function waitForSidebarReady( @@ -991,9 +994,6 @@ const getCommandsMap: ( vscode.commands.executeCommand("continue.focusContinueInput"); } else if (selectedOption === "$(screen-full) Open full screen chat") { vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more", true); } quickPick.dispose(); }); @@ -1016,9 +1016,6 @@ const getCommandsMap: ( client.sendFeedback(feedback, lastLines); } }, - "continue.openMorePage": () => { - vscode.commands.executeCommand("continue.navigateTo", "/more", true); - }, "continue.navigateTo": (path: string, toggle: boolean) => { sidebar.webviewProtocol?.request("navigateTo", { path, toggle }); focusGUI(); diff --git a/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts b/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts new file mode 100644 index 000000000..1c0a76251 --- /dev/null +++ b/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts @@ -0,0 +1,43 @@ +import * as vscode from "vscode"; + +export class ConfigYamlDocumentLinkProvider + implements vscode.DocumentLinkProvider +{ + private usesPattern = /^\s*#?\s*-\s*uses:\s*(.+)$/; + provideDocumentLinks( + document: vscode.TextDocument, + token: vscode.CancellationToken, + ): vscode.ProviderResult { + const links: vscode.DocumentLink[] = []; + + for (let lineIndex = 0; lineIndex < document.lineCount; lineIndex++) { + const line = document.lineAt(lineIndex); + const match = this.usesPattern.exec(line.text); + + if (match) { + const slug = match[1].trim(); + const startPos = line.text.indexOf(slug); + const range = new vscode.Range( + lineIndex, + startPos, + lineIndex, + startPos + slug.length, + ); + + const link = new vscode.DocumentLink( + range, + vscode.Uri.parse(`https://hub.continue.dev/${slug}`), + ); + links.push(link); + } + } + + return links; + } + resolveDocumentLink( + link: vscode.DocumentLink, + token: vscode.CancellationToken, + ): vscode.ProviderResult { + return link; + } +} diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index a4a90afd3..9441d70cd 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -37,6 +37,7 @@ import { Battery } from "../util/battery"; import { FileSearch } from "../util/FileSearch"; import { VsCodeIde } from "../VsCodeIde"; +import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -401,6 +402,12 @@ export class VsCodeExtension { ), ); + const linkProvider = vscode.languages.registerDocumentLinkProvider( + { language: "yaml" }, + new ConfigYamlDocumentLinkProvider(), + ); + context.subscriptions.push(linkProvider); + this.ide.onDidChangeActiveTextEditor((filepath) => { void this.core.invoke("didChangeActiveTextEditor", { filepath }); }); diff --git a/gui/editorInset/index.html b/gui/editorInset/index.html deleted file mode 100644 index 1e6607ff2..000000000 --- a/gui/editorInset/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Continue - - -
- - - diff --git a/gui/editorInset/vite.config.ts b/gui/editorInset/vite.config.ts deleted file mode 100644 index fdc63bbdb..000000000 --- a/gui/editorInset/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import react from "@vitejs/plugin-react-swc"; -import tailwindcss from "tailwindcss"; -import { defineConfig } from "vite"; - -// https://vitejs.dev/config/ -export default defineConfig({ - plugins: [react(), tailwindcss()], - build: { - // Change the output .js filename to not include a hash - rollupOptions: { - // external: ["vscode-webview"], - output: { - entryFileNames: `assets/[name].js`, - chunkFileNames: `assets/[name].js`, - assetFileNames: `assets/[name].[ext]`, - }, - }, - }, -}); diff --git a/gui/package-lock.json b/gui/package-lock.json index b0918360d..389343794 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,8 +7,8 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.63", - "@headlessui/react": "^1.7.17", + "@continuedev/config-yaml": "^1.0.67", + "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", @@ -26,6 +26,7 @@ "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", "@types/vscode-webview": "^1.57.1", + "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", @@ -59,6 +60,7 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", + "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", @@ -91,7 +93,7 @@ "jsdom": "^25.0.1", "postcss": "^8.4.21", "tailwindcss": "^3.2.7", - "typescript": "^4.9.3", + "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", "vite": "^4.1.0", "vitest": "^2.1.3" @@ -109,9 +111,9 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.63", + "@continuedev/config-yaml": "^1.0.67", "@continuedev/fetch": "^1.0.4", - "@continuedev/llm-info": "^1.0.2", + "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", @@ -196,7 +198,8 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", - "ts-jest": "^29.1.1" + "ts-jest": "^29.1.1", + "typescript": "^5.6.3" }, "engines": { "node": ">=20.11.0" @@ -551,9 +554,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.63", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.63.tgz", - "integrity": "sha512-KBfyOUU/mWOXeNf6v+4IfMkbvfEEe/YP6n/g/reJBhrpApchG2A/P11JviH87N2To1SrhZxnW//0g5FIGupDFw==", + "version": "1.0.67", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", + "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -1098,25 +1101,53 @@ "@floating-ui/utils": "^0.2.8" } }, + "node_modules/@floating-ui/react": { + "version": "0.26.28", + "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.26.28.tgz", + "integrity": "sha512-yORQuuAtVpiRjpMhdc0wJj06b9JFjrYF4qp96j++v2NBpbi6SEGF7donUJ3TMieerQ6qVkAv1tgr7L4r5roTqw==", + "dependencies": { + "@floating-ui/react-dom": "^2.1.2", + "@floating-ui/utils": "^0.2.8", + "tabbable": "^6.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.2.tgz", + "integrity": "sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==", + "dependencies": { + "@floating-ui/dom": "^1.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, "node_modules/@floating-ui/utils": { "version": "0.2.8", "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.8.tgz", "integrity": "sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig==" }, "node_modules/@headlessui/react": { - "version": "1.7.19", - "resolved": "https://registry.npmjs.org/@headlessui/react/-/react-1.7.19.tgz", - "integrity": "sha512-Ll+8q3OlMJfJbAKM/+/Y2q6PPYbryqNTXDbryx7SXLIDamkF6iQFbriYHga0dY44PvDhvvBWCx1Xj4U5+G4hOw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@headlessui/react/-/react-2.2.0.tgz", + "integrity": "sha512-RzCEg+LXsuI7mHiSomsu/gBJSjpupm6A1qIZ5sWjd7JhARNlMiSA4kKfJpCKwU9tE+zMRterhhrP74PvfJrpXQ==", "dependencies": { - "@tanstack/react-virtual": "^3.0.0-beta.60", - "client-only": "^0.0.1" + "@floating-ui/react": "^0.26.16", + "@react-aria/focus": "^3.17.1", + "@react-aria/interactions": "^3.21.3", + "@tanstack/react-virtual": "^3.8.1" }, "engines": { "node": ">=10" }, "peerDependencies": { - "react": "^16 || ^17 || ^18", - "react-dom": "^16 || ^17 || ^18" + "react": "^18 || ^19 || ^19.0.0-rc", + "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "node_modules/@heroicons/react": { @@ -1702,6 +1733,96 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@react-aria/focus": { + "version": "3.20.1", + "resolved": "https://registry.npmjs.org/@react-aria/focus/-/focus-3.20.1.tgz", + "integrity": "sha512-lgYs+sQ1TtBrAXnAdRBQrBo0/7o5H6IrfDxec1j+VRpcXL0xyk0xPq+m3lZp8typzIghqDgpnKkJ5Jf4OrzPIw==", + "dependencies": { + "@react-aria/interactions": "^3.24.1", + "@react-aria/utils": "^3.28.1", + "@react-types/shared": "^3.28.0", + "@swc/helpers": "^0.5.0", + "clsx": "^2.0.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", + "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-aria/interactions": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/@react-aria/interactions/-/interactions-3.24.1.tgz", + "integrity": "sha512-OWEcIC6UQfWq4Td5Ptuh4PZQ4LHLJr/JL2jGYvuNL6EgL3bWvzPrRYIF/R64YbfVxIC7FeZpPSkS07sZ93/NoA==", + "dependencies": { + "@react-aria/ssr": "^3.9.7", + "@react-aria/utils": "^3.28.1", + "@react-stately/flags": "^3.1.0", + "@react-types/shared": "^3.28.0", + "@swc/helpers": "^0.5.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", + "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-aria/ssr": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/@react-aria/ssr/-/ssr-3.9.7.tgz", + "integrity": "sha512-GQygZaGlmYjmYM+tiNBA5C6acmiDWF52Nqd40bBp0Znk4M4hP+LTmI0lpI1BuKMw45T8RIhrAsICIfKwZvi2Gg==", + "dependencies": { + "@swc/helpers": "^0.5.0" + }, + "engines": { + "node": ">= 12" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-aria/utils": { + "version": "3.28.1", + "resolved": "https://registry.npmjs.org/@react-aria/utils/-/utils-3.28.1.tgz", + "integrity": "sha512-mnHFF4YOVu9BRFQ1SZSKfPhg3z+lBRYoW5mLcYTQihbKhz48+I1sqRkP7ahMITr8ANH3nb34YaMME4XWmK2Mgg==", + "dependencies": { + "@react-aria/ssr": "^3.9.7", + "@react-stately/flags": "^3.1.0", + "@react-stately/utils": "^3.10.5", + "@react-types/shared": "^3.28.0", + "@swc/helpers": "^0.5.0", + "clsx": "^2.0.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", + "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-stately/flags": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@react-stately/flags/-/flags-3.1.0.tgz", + "integrity": "sha512-KSHOCxTFpBtxhIRcKwsD1YDTaNxFtCYuAUb0KEihc16QwqZViq4hasgPBs2gYm7fHRbw7WYzWKf6ZSo/+YsFlg==", + "dependencies": { + "@swc/helpers": "^0.5.0" + } + }, + "node_modules/@react-stately/utils": { + "version": "3.10.5", + "resolved": "https://registry.npmjs.org/@react-stately/utils/-/utils-3.10.5.tgz", + "integrity": "sha512-iMQSGcpaecghDIh3mZEpZfoFH3ExBwTtuBEcvZ2XnGzCgQjeYXcMdIUwAfVQLXFTdHUHGF6Gu6/dFrYsCzySBQ==", + "dependencies": { + "@swc/helpers": "^0.5.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-types/shared": { + "version": "3.28.0", + "resolved": "https://registry.npmjs.org/@react-types/shared/-/shared-3.28.0.tgz", + "integrity": "sha512-9oMEYIDc3sk0G5rysnYvdNrkSg7B04yTKl50HHSZVbokeHpnU0yRmsDaWb9B/5RprcKj8XszEk5guBO8Sa/Q+Q==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, "node_modules/@reduxjs/toolkit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.3.0.tgz", @@ -2201,6 +2322,14 @@ "integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==", "dev": true }, + "node_modules/@swc/helpers": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz", + "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==", + "dependencies": { + "tslib": "^2.8.0" + } + }, "node_modules/@swc/types": { "version": "0.1.12", "resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.12.tgz", @@ -4265,11 +4394,6 @@ "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==" }, - "node_modules/client-only": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", - "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==" - }, "node_modules/clone-response": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz", @@ -4282,6 +4406,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "engines": { + "node": ">=6" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -11398,6 +11530,11 @@ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, + "node_modules/tabbable": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.2.0.tgz", + "integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==" + }, "node_modules/table": { "version": "6.8.2", "resolved": "https://registry.npmjs.org/table/-/table-6.8.2.tgz", @@ -11413,6 +11550,15 @@ "node": ">=10.0.0" } }, + "node_modules/tailwind-merge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.0.2.tgz", + "integrity": "sha512-l7z+OYZ7mu3DTqrL88RiKrKIqO3NcpEO8V/Od04bNpvk0kiIFndGEoqfuzvj4yuhRkHKjRkII2z+KS2HfPcSxw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, "node_modules/tailwindcss": { "version": "3.4.12", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz", @@ -11730,9 +11876,9 @@ "dev": true }, "node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==" + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" }, "node_modules/type-check": { "version": "0.4.0", @@ -11833,16 +11979,16 @@ } }, "node_modules/typescript": { - "version": "4.9.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", - "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "version": "5.8.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz", + "integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==", "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=14.17" } }, "node_modules/typescript-eslint": { diff --git a/gui/package.json b/gui/package.json index 6724bd757..33f326de3 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,8 +15,8 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.63", - "@headlessui/react": "^1.7.17", + "@continuedev/config-yaml": "^1.0.67", + "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", @@ -34,6 +34,7 @@ "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", "@types/vscode-webview": "^1.57.1", + "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", @@ -67,6 +68,7 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", + "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", @@ -99,7 +101,7 @@ "jsdom": "^25.0.1", "postcss": "^8.4.21", "tailwindcss": "^3.2.7", - "typescript": "^4.9.3", + "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", "vite": "^4.1.0", "vitest": "^2.1.3" diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 73d667292..deb1e376f 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,19 +1,16 @@ -import { useDispatch } from "react-redux"; import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; +import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; +import ConfigPage from "./pages/config"; import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; -import MigrationPage from "./pages/migration"; -import MorePage from "./pages/More"; import Stats from "./pages/stats"; import { ROUTES } from "./util/navigation"; -import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; -import ConfigPage from "./pages/config"; const router = createMemoryRouter([ { @@ -45,10 +42,6 @@ const router = createMemoryRouter([ path: "/addModel/provider/:providerName", element: , }, - { - path: "/more", - element: , - }, { path: ROUTES.CONFIG_ERROR, element: , @@ -57,10 +50,6 @@ const router = createMemoryRouter([ path: ROUTES.CONFIG, element: , }, - { - path: "/migration", - element: , - }, ], }, ]); diff --git a/gui/src/components/CodeToEditCard/AddFileButton.tsx b/gui/src/components/CodeToEditCard/AddFileButton.tsx index b1e1966fe..d051f847f 100644 --- a/gui/src/components/CodeToEditCard/AddFileButton.tsx +++ b/gui/src/components/CodeToEditCard/AddFileButton.tsx @@ -1,9 +1,14 @@ +import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; -import { Listbox } from "@headlessui/react"; -import { addCodeToEdit } from "../../redux/slices/sessionSlice"; import { useAppDispatch } from "../../redux/hooks"; +import { addCodeToEdit } from "../../redux/slices/sessionSlice"; +import { + Listbox, + ListboxButton, + ListboxOption, + ListboxOptions, +} from "../ui/Listbox"; export interface AddFileButtonProps { onClick: () => void; @@ -29,20 +34,20 @@ export default function AddFileButton({ onClick }: AddFileButtonProps) { return (
-
{ e.preventDefault(); e.stopPropagation(); onClick(); }} > - - + + Add file
@@ -50,16 +55,11 @@ export default function AddFileButton({ onClick }: AddFileButtonProps) {
- + - - - Add all open files - - + + Add all open files +
); diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index 07ab68a2c..d096f90a2 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -1,10 +1,15 @@ -import { useState, useEffect, useRef } from "react"; -import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; -import { Combobox } from "@headlessui/react"; -import FileIcon from "../FileIcon"; -import { useAppSelector } from "../../redux/hooks"; import { ContextSubmenuItemWithProvider } from "core"; - +import { useEffect, useRef, useState } from "react"; +import { + Combobox, + ComboboxButton, + ComboboxInput, + ComboboxOption, + ComboboxOptions, +} from "../../components/ui/Combobox"; +import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; +import { useAppSelector } from "../../redux/hooks"; +import FileIcon from "../FileIcon"; export interface AddFileComboboxProps { onSelect: (filepaths: string[]) => void | Promise; onEscape: () => void | Promise; @@ -54,8 +59,8 @@ export default function AddFileCombobox({ > {({ open }) => (
- - + { if (!open) { @@ -65,7 +70,7 @@ export default function AddFileCombobox({ onFocus={() => { buttonRef.current?.click(); }} - className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 focus:outline-none" + className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 text-xs focus:outline-none" onChange={(event) => setQuery(event.target.value)} placeholder="Type to search files..." onKeyDown={(e) => { @@ -75,10 +80,10 @@ export default function AddFileCombobox({ }} /> - + {filteredFiles.length > 0 ? ( filteredFiles.map((file) => ( - @@ -109,14 +114,14 @@ export default function AddFileCombobox({
)} - + )) ) : (
No results
)} - +
)} diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 99149ba5f..6e16d4d4f 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -1,16 +1,16 @@ +import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import type { CodeToEdit } from "core"; import { useContext, useState } from "react"; import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import CodeToEditListItem from "./CodeToEditListItem"; -import type { CodeToEdit } from "core"; -import AddFileButton from "./AddFileButton"; -import AddFileCombobox from "./AddFileCombobox"; -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { addCodeToEdit, removeCodeToEdit, } from "../../redux/slices/sessionSlice"; +import AddFileButton from "./AddFileButton"; +import AddFileCombobox from "./AddFileCombobox"; +import CodeToEditListItem from "./CodeToEditListItem"; export default function CodeToEditCard() { const dispatch = useDispatch(); @@ -18,12 +18,12 @@ export default function CodeToEditCard() { const [showAddFileCombobox, setShowAddFileCombobox] = useState(false); const codeToEdit = useAppSelector((state) => state.session.codeToEdit); - const title = + const itemCount = codeToEdit.length === 0 - ? "Code to edit" + ? "" : codeToEdit.length === 1 - ? "Code to edit (1 item)" - : `Code to edit (${codeToEdit.length} items)`; + ? "(1 item)" + : `(${codeToEdit.length} items)`; function onDelete(rif: CodeToEdit) { dispatch(removeCodeToEdit(rif)); @@ -57,7 +57,11 @@ export default function CodeToEditCard() { return (
- {title} +
+ Code to edit + {itemCount} +
+ setShowAddFileCombobox(true)} />
diff --git a/gui/src/components/ConversationStarters/ConversationStarterCard.tsx b/gui/src/components/ConversationStarters/ConversationStarterCard.tsx new file mode 100644 index 000000000..29ff81833 --- /dev/null +++ b/gui/src/components/ConversationStarters/ConversationStarterCard.tsx @@ -0,0 +1,31 @@ +import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; +import { SlashCommandDescription } from "core"; + +interface ConversationStarterCardProps { + command: SlashCommandDescription; + onClick: (command: SlashCommandDescription) => void; +} + +export function ConversationStarterCard({ + command, + onClick, +}: ConversationStarterCardProps) { + return ( +
onClick(command)} + > +
+
+ +
+
+
{command.name}
+ {command.description && ( +
{command.description}
+ )} +
+
+
+ ); +} diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx new file mode 100644 index 000000000..7e0e2e183 --- /dev/null +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -0,0 +1,62 @@ +import { SlashCommandDescription } from "core"; +import { useState } from "react"; +import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice"; +import { getParagraphNodeFromString } from "../mainInput/utils"; +import { ConversationStarterCard } from "./ConversationStarterCard"; + +const NUM_CARDS_TO_RENDER = 5; + +export function ConversationStarterCards() { + const dispatch = useAppDispatch(); + const [showAll, setShowAll] = useState(false); + const { isCommandBookmarked } = useBookmarkedSlashCommands(); + const slashCommands = useAppSelector( + (state) => state.config.config.slashCommands ?? [], + ); + + const bookmarkedSlashCommands = slashCommands.filter((command) => + isCommandBookmarked(command.name), + ); + + function onClick(command: SlashCommandDescription) { + if (command.prompt) { + dispatch( + setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)), + ); + } + } + + if (bookmarkedSlashCommands.length === 0) { + return null; + } + + const visibleCommands = showAll + ? bookmarkedSlashCommands + : bookmarkedSlashCommands.slice(0, NUM_CARDS_TO_RENDER); + + const remainingCount = bookmarkedSlashCommands.length - NUM_CARDS_TO_RENDER; + + return ( +
+
+ {visibleCommands.map((command, i) => ( + + ))} +
+ {bookmarkedSlashCommands.length > NUM_CARDS_TO_RENDER && ( + setShowAll(!showAll)} + > + {showAll ? "Show less" : `Show ${remainingCount} more...`} + + )} +
+ ); +} diff --git a/gui/src/components/ConversationStarters/__tests__/utils.test.ts b/gui/src/components/ConversationStarters/__tests__/utils.test.ts new file mode 100644 index 000000000..3e7050985 --- /dev/null +++ b/gui/src/components/ConversationStarters/__tests__/utils.test.ts @@ -0,0 +1,45 @@ +import { SlashCommandDescription } from "core"; +import { sortCommandsByBookmarkStatus } from "../utils"; + +describe("sortCommandsByBookmarkStatus", () => { + const mockCommands: SlashCommandDescription[] = [ + { + name: "command1", + description: "First command", + prompt: "This is command 1", + }, + { + name: "command2", + description: "Second command", + prompt: "This is command 2", + }, + { + name: "command3", + description: "Third command", + prompt: "This is command 3", + }, + { + name: "command4", + description: "Fourth command", + prompt: "This is command 4", + }, + ]; + + it("should return commands in the same order when no bookmarks exist", () => { + const result = sortCommandsByBookmarkStatus(mockCommands, []); + expect(result).toEqual(mockCommands); + // Ensure it's a new array, not the original + expect(result).not.toBe(mockCommands); + }); + + it("should put bookmarked commands first", () => { + const bookmarkedCommands = ["command3", "command1"]; + const result = sortCommandsByBookmarkStatus( + mockCommands, + bookmarkedCommands, + ); + + expect(result[0].name).toBe("command1"); + expect(result[1].name).toBe("command3"); + }); +}); diff --git a/gui/src/components/ConversationStarters/index.ts b/gui/src/components/ConversationStarters/index.ts new file mode 100644 index 000000000..72b23e0b7 --- /dev/null +++ b/gui/src/components/ConversationStarters/index.ts @@ -0,0 +1 @@ +export * from "./ConversationStarterCards"; diff --git a/gui/src/components/ConversationStarters/utils.ts b/gui/src/components/ConversationStarters/utils.ts new file mode 100644 index 000000000..1f9ef09ae --- /dev/null +++ b/gui/src/components/ConversationStarters/utils.ts @@ -0,0 +1,22 @@ +import { SlashCommandDescription } from "core"; +import {} from "core/config/default"; + +/** + * Sorts commands with bookmarked ones first + * @param commands The list of commands to sort + * @param bookmarkedCommands An array of bookmarked command names + * @returns A new sorted array with bookmarked commands first + */ +export function sortCommandsByBookmarkStatus( + commands: SlashCommandDescription[], + bookmarkedCommands: string[], +): SlashCommandDescription[] { + return [...commands].sort((a, b) => { + const aIsBookmarked = bookmarkedCommands.includes(a.name); + const bIsBookmarked = bookmarkedCommands.includes(b.name); + + if (aIsBookmarked && !bIsBookmarked) return -1; + if (!aIsBookmarked && bIsBookmarked) return 1; + return 0; + }); +} diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index c546becd4..bf6327c35 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -23,12 +23,17 @@ export function ExploreHubCard() { return dispatch(setIsExploreDialogOpen(false)); }} > -
-

Create Your Own Assistant

+
+
+

+ Create Your Own Assistant +

-

- Discover and remix popular assistants, or create your own from scratch -

+

+ Discover and remix popular assistants, or create your own from + scratch +

+
*/} -
+ {docsIndexingStatuses.length > 0 && ( + <> + +

+ Closing this dialog will not affect indexing progress +

+ + )}
); } diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index 8957038ac..3b98338d3 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -1,27 +1,38 @@ import React from "react"; +import { vscButtonBackground } from ".."; type ToggleSwitchProps = { isToggled: boolean; onToggle: () => void; text: string; + size?: number; }; const ToggleSwitch: React.FC = ({ isToggled, onToggle, text, + size = 16, }) => { return (
{text}
diff --git a/gui/src/components/gui/Tooltip.tsx b/gui/src/components/gui/Tooltip.tsx index b1477ba73..cf934f750 100644 --- a/gui/src/components/gui/Tooltip.tsx +++ b/gui/src/components/gui/Tooltip.tsx @@ -1,10 +1,10 @@ import ReactDOM from "react-dom"; import { Tooltip } from "react-tooltip"; import { vscBackground, vscForeground, vscInputBorder } from ".."; -import { getFontSize } from "../../util"; +import { fontSize } from "../../util"; const TooltipStyles = { - fontSize: `${getFontSize() - 2}px`, + fontSize: fontSize(-2), backgroundColor: vscBackground, outline: `0.5px solid ${vscInputBorder}`, color: vscForeground, @@ -25,7 +25,7 @@ export function ToolTip(props: any) { return ( tooltipPortalDiv && ReactDOM.createPortal( - , + , tooltipPortalDiv, ) ); diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 04460f3b1..036f912c8 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -1,5 +1,5 @@ import styled from "styled-components"; -import { getFontSize, isJetBrains } from "../util"; +import { getFontSize } from "../util"; export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background"; export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background"; @@ -59,6 +59,7 @@ export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, $ export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`; export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`; export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`; +export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`; export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`; export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`; export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`; @@ -132,7 +133,7 @@ export const Button = styled.button` export const SecondaryButton = styled.button` padding: 6px 12px; - margin: 8px 0; + margin: 8px; border-radius: ${defaultBorderRadius}; border: 1px solid ${vscInputBorder}; @@ -151,14 +152,13 @@ export const SecondaryButton = styled.button` `; export const GhostButton = styled.button` - padding: 10px 12px; - margin: 8px 0; + padding: 6px 8px; + margin: 6px 0; border-radius: ${defaultBorderRadius}; border: none; color: ${vscForeground}; - background-color: transparent; - + background-color: rgba(255, 255, 255, 0.08); &:disabled { color: gray; pointer-events: none; @@ -166,7 +166,7 @@ export const GhostButton = styled.button` &:hover:enabled { cursor: pointer; - background-color: rgba(255, 255, 255, 0.08); /* Subtle hover effect */ + filter: brightness(125%); } `; diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index aa5edfe32..3c0856f45 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -1,8 +1,8 @@ -import { useDispatch } from "react-redux"; +import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline"; import { IndexingStatus } from "core"; import { useMemo } from "react"; +import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; -import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { setIndexingChatPeekHidden } from "../../redux/slices/indexingSlice"; @@ -32,15 +32,10 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { if (hiddenPeeks[state.type]) return null; return ( -
{ - navigate("/more"); - }} - > +
-

+

{state.displayName}

@@ -52,17 +47,17 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { }} />
-
+
{state.progressPercentage.toFixed(0)}%
{ dispatch( setIndexingChatPeekHidden({ type: state.type, hidden: true }), diff --git a/gui/src/components/indexing/DocsIndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx deleted file mode 100644 index 224d96265..000000000 --- a/gui/src/components/indexing/DocsIndexingStatus.tsx +++ /dev/null @@ -1,218 +0,0 @@ -import { IndexingStatus, SiteIndexingConfig } from "core"; -import { useContext, useMemo, useState } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { - ArrowPathIcon, - ArrowTopRightOnSquareIcon, - CheckCircleIcon, - ExclamationTriangleIcon, - EyeIcon, - PauseCircleIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import ConfirmationDialog from "../dialogs/ConfirmationDialog"; -import DocsDetailsDialog from "./DocsDetailsDialog"; - -interface IndexingStatusViewerProps { - docConfig: SiteIndexingConfig; -} - -const STATUS_TO_ICON: Record = { - indexing: ArrowPathIcon, - paused: PauseCircleIcon, - complete: CheckCircleIcon, - aborted: null, - pending: null, - failed: ExclamationTriangleIcon, // Since we show an error message below -}; - -function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { - const config = useAppSelector((store) => store.config.config); - const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useAppDispatch(); - - const status = useAppSelector( - (store) => store.indexing.indexing.statuses[docConfig.startUrl], - ); - - const reIndex = () => - ideMessenger.post("indexing/reindex", { - type: "docs", - id: docConfig.startUrl, - }); - - const abort = () => { - ideMessenger.post("indexing/abort", { - type: "docs", - id: docConfig.startUrl, - }); - // Optimistic abort status - if (status) { - dispatch( - updateIndexingStatus({ ...status, status: "aborted", progress: 0 }), - ); - } - }; - - const [hasDeleted, setHasDeleted] = useState(false); // simple alternative to optimistic redux update - const onDelete = () => { - // optimistic update - dispatch( - setDialogMessage( - { - ideMessenger.post("context/removeDocs", { - startUrl: docConfig.startUrl, - }); - setHasDeleted(true); - }} - />, - ), - ); - dispatch(setShowDialog(true)); - }; - - const progressPercentage = useMemo(() => { - if (!status) { - return 0; - } - return Math.min(100, Math.max(0, status.progress * 100)).toFixed(0); - }, [status?.progress]); - - const Icon = STATUS_TO_ICON[status?.status]; - const showProgressPercentage = progressPercentage !== "100"; - - if (hasDeleted) return null; - - return ( -
-
-
{ - if (status?.url) { - ideMessenger.post("openUrl", status.url); - } - }} - > - {docConfig.faviconUrl ? ( - doc icon - ) : null} -

- {docConfig.title ?? docConfig.startUrl} -

- -
- {status?.status === "pending" ? ( -
Pending...
- ) : ( -
- {showProgressPercentage && ( - {progressPercentage}% - )} - {status?.status !== "indexing" ? ( - - ) : null} - {Icon ? ( - - ) : null} -
- )} -
- -
-
-
- -
- {}, - pending: () => {}, - }[status?.status] - } - > - {config.disableIndexing - ? "Indexing disabled" - : { - complete: "Click to re-index", - indexing: "Cancel indexing", - failed: "Click to retry", - aborted: "Click to index", - paused: "", - pending: "", - }[status?.status]} - -
- {status?.description === "Github rate limit exceeded" ? ( - - ideMessenger.post( - "openUrl", - "https://docs.continue.dev/customize/deep-dives/docs#github", - ) - } - > - {status.description} - - ) : ( - - {status?.description} - - )} - {status?.status === "complete" ? ( - { - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - , - ), - ); - }} - > - Add Docs - - ) : null} -
-
-
- ); -} - -export default DocsIndexingStatus; diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx deleted file mode 100644 index f1e261dfb..000000000 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import { useDispatch } from "react-redux"; -import { SecondaryButton } from ".."; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import AddDocsDialog from "../dialogs/AddDocsDialog"; -import DocsIndexingStatus from "./DocsIndexingStatus"; -import { useAppSelector } from "../../redux/hooks"; -import { useContext, useMemo } from "react"; -import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { IndexingStatus } from "core"; - -function DocsIndexingStatuses() { - const dispatch = useDispatch(); - const config = useAppSelector((store) => store.config.config); - const ideMessenger = useContext(IdeMessengerContext); - const indexingStatuses = useAppSelector( - (store) => store.indexing.indexing.statuses, - ); - - const hasDocsProvider = useMemo(() => { - return !!config.contextProviders?.some( - (provider) => provider.title === "docs", - ); - }, [config]); - - // TODO - this might significantly impact performance during indexing - const sortedConfigDocs = useMemo(() => { - const sorter = (status: IndexingStatus["status"]) => { - // TODO - further sorting? - if (status === "indexing" || status === "paused") return 0; - if (status === "failed") return 1; - if (status === "aborted" || status === "pending") return 2; - return 3; - }; - - const docs = [...(config.docs ?? [])]; - docs.sort((a, b) => - sorter(indexingStatuses[b.startUrl]?.status ?? "pending") > - sorter(indexingStatuses[a.startUrl]?.status ?? "pending") - ? -1 - : 1, - ); - return docs; - }, [config, indexingStatuses]); - - return ( -
-
-

@docs indexes

- {sortedConfigDocs.length ? ( - { - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - }} - > - Add - - ) : null} -
- - {hasDocsProvider ? ( - sortedConfigDocs.length ? ( - "Manage your documentation sources" - ) : ( - "No docs yet" - ) - ) : ( -
-
-
- -
- - @docs is not in your config - -
- { - ideMessenger.post("config/addContextProvider", { - name: "docs", - params: {}, - }); - }} - > - Add @docs to my config - -
- )} -
-
-
- {sortedConfigDocs.length === 0 && ( - { - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - }} - > - Add Docs - - )} -
- {sortedConfigDocs.map((doc) => { - return ; - })} -
-
- ); -} - -export default DocsIndexingStatuses; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx similarity index 84% rename from gui/src/components/mainInput/MentionList.tsx rename to gui/src/components/mainInput/AtMentionDropdown/index.tsx index 94324b75e..beeb37070 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -1,25 +1,8 @@ import { ArrowRightIcon, - ArrowUpOnSquareIcon, AtSymbolIcon, - Bars3BottomLeftIcon, - BoltIcon, - BookOpenIcon, - BugAntIcon, - CircleStackIcon, - CodeBracketIcon, - CommandLineIcon, - CpuChipIcon, - DocumentTextIcon, - ExclamationTriangleIcon, - FolderIcon, - FolderOpenIcon, - GlobeAltIcon, - MagnifyingGlassIcon, - PaperClipIcon, + ChatBubbleLeftIcon, PlusIcon, - SparklesIcon, - TrashIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; import { @@ -39,64 +22,29 @@ import { vscListActiveBackground, vscListActiveForeground, vscQuickInputBackground, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import FileIcon from "../FileIcon"; -import SafeImg from "../SafeImg"; -import AddDocsDialog from "../dialogs/AddDocsDialog"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { DiscordIcon } from "../svg/DiscordIcon"; -import { GithubIcon } from "../svg/GithubIcon"; -import { GitlabIcon } from "../svg/GitlabIcon"; -import { GoogleIcon } from "../svg/GoogleIcon"; -import { ComboBoxItem, ComboBoxItemType } from "./types"; - -const ICONS_FOR_DROPDOWN: { [key: string]: any } = { - file: FolderIcon, - code: CodeBracketIcon, - terminal: CommandLineIcon, - diff: PlusIcon, - search: MagnifyingGlassIcon, - url: GlobeAltIcon, - open: FolderOpenIcon, - codebase: SparklesIcon, - problems: ExclamationTriangleIcon, - folder: FolderIcon, - docs: BookOpenIcon, - web: GlobeAltIcon, - clipboard: PaperClipIcon, - database: CircleStackIcon, - postgres: CircleStackIcon, - debugger: BugAntIcon, - os: CpuChipIcon, - tree: Bars3BottomLeftIcon, - "prompt-files": DocumentTextIcon, - "repo-map": FolderIcon, - "/clear": TrashIcon, - "/share": ArrowUpOnSquareIcon, - "/cmd": CommandLineIcon, - issue: GithubIcon, - discord: DiscordIcon, - google: GoogleIcon, - "gitlab-mr": GitlabIcon, - http: GlobeAltIcon, - trash: TrashIcon, -}; +} from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { fontSize } from "../../../util"; +import FileIcon from "../../FileIcon"; +import SafeImg from "../../SafeImg"; +import AddDocsDialog from "../../dialogs/AddDocsDialog"; +import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip"; +import { NAMED_ICONS } from "../icons"; +import { ComboBoxItem, ComboBoxItemType } from "../types"; export function getIconFromDropdownItem( id: string | undefined, type: ComboBoxItemType, ) { - const typeIcon = type === "contextProvider" ? AtSymbolIcon : BoltIcon; - return id ? (ICONS_FOR_DROPDOWN[id] ?? typeIcon) : typeIcon; + const typeIcon = + type === "contextProvider" ? AtSymbolIcon : ChatBubbleLeftIcon; + return id ? (NAMED_ICONS[id] ?? typeIcon) : typeIcon; } function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { if (props.item.type === "action") { - return ( - - ); + return ; } const provider = @@ -134,7 +82,7 @@ const ItemsDiv = styled.div` box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0px 10px 20px rgba(0, 0, 0, 0.1); - font-size: 0.9rem; + font-size: ${fontSize(-2)}; overflow-x: hidden; overflow-y: auto; max-height: 330px; @@ -151,10 +99,11 @@ const ItemDiv = styled.div` border-radius: 0.4rem; display: block; margin: 0; - padding: 0.2rem 0.4rem; + padding: 2px 4px; text-align: left; width: 100%; color: ${vscForeground}; + font-size: ${fontSize(-2)}; &.is-selected { background-color: ${vscListActiveBackground}; @@ -180,7 +129,7 @@ const QueryInput = styled.textarea` resize: none; `; -interface MentionListProps { +interface AtMentionDropdownProps { items: ComboBoxItem[]; command: (item: any) => void; @@ -189,7 +138,7 @@ interface MentionListProps { onClose: () => void; } -const MentionList = forwardRef((props: MentionListProps, ref) => { +const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); @@ -226,7 +175,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { tr.delete(start, tr.selection.from).scrollIntoView(), ); }, - description: "Add a new documentation source", + description: "", }); } else if (subMenuTitle === ".prompt files") { items.push({ @@ -423,7 +372,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { textAlign: "right", minWidth: "30px", }} - className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap text-xs" + className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap" > {loadingSubmenuItem.description} @@ -468,7 +417,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { opacity: isSelected ? 1 : 0, minWidth: "30px", }} - className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap text-xs" + className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap" > {item.description} {item.type === "contextProvider" && @@ -506,10 +455,9 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { ) : ( No results )} - {/* */} )} ); }); -export default MentionList; +export default AtMentionDropdown; diff --git a/gui/src/components/mainInput/ContinueButton.tsx b/gui/src/components/mainInput/ContinueButton.tsx deleted file mode 100644 index 23776bbcf..000000000 --- a/gui/src/components/mainInput/ContinueButton.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { PlayIcon, StopIcon } from "@heroicons/react/24/outline"; -import styled from "styled-components"; -import { Button } from ".."; -import { getFontSize } from "../../util"; - -const StyledButton = styled(Button)<{ - color?: string | null; - isDisabled: boolean; - showStop: boolean; -}>` - margin: auto; - margin-top: 8px; - margin-bottom: 16px; - display: grid; - width: 130px; - grid-template-columns: 22px 1fr; - align-items: center; - background-color: ${(props) => - `${props.color || "#be1b55"}${props.showStop ? "33" : ""}`}; - - opacity: ${(props) => (props.isDisabled ? 0.5 : 1.0)}; - - border: 1px solid - ${(props) => (props.showStop ? props.color || "#be1b55" : "transparent")}; - - cursor: ${(props) => (props.isDisabled ? "default" : "pointer")}; - - &:hover:enabled { - background-color: ${(props) => - `${props.color || "#be1b55"}${props.showStop ? "33" : ""}`}; - ${(props) => - props.isDisabled - ? "cursor: default;" - : ` - opacity: 0.7; - `} - } -`; - -function ContinueButton(props: { - onClick?: () => void; - hidden?: boolean; - disabled: boolean; - showStop: boolean; -}) { - return ( - - ); -} - -export default ContinueButton; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 69264eb35..2b91b707b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,14 +1,14 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useDispatch } from "react-redux"; +import { useMemo, useState } from "react"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; -import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; -import ContextItemsPeek from "./ContextItemsPeek"; -import TipTapEditor from "./TipTapEditor"; import { useAppSelector } from "../../redux/hooks"; +import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; +import ContextItemsPeek from "./belowMainInput/ContextItemsPeek"; import { ToolbarOptions } from "./InputToolbar"; -import { useMemo } from "react"; +import { Lump } from "./Lump"; +import TipTapEditor from "./tiptap/TipTapEditor"; interface ContinueInputBoxProps { isEditMode?: boolean; @@ -113,9 +113,12 @@ function ContinueInputBox(props: ContinueInputBoxProps) { } : {}; + const [lumpOpen, setLumpOpen] = useState(true); + return (
+ {props.isMainInput && } diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index d948dc288..de2c410f7 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -13,6 +13,7 @@ import { } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; +import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../../redux/slices/configSlice"; import { selectHasCodeToEdit, @@ -28,8 +29,9 @@ import { } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; -import HoverItem from "./InputToolbar/HoverItem"; -import ToggleToolsButton from "./InputToolbar/ToggleToolsButton"; +import ModeSelect from "../modelSelection/ModeSelect"; +import { useFontSize } from "../ui/font"; +import HoverItem from "./InputToolbar/bottom/HoverItem"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -54,9 +56,12 @@ const EnterButton = styled.button<{ isPrimary?: boolean }>` display: flex; align-items: center; background-color: ${(props) => - props.isPrimary ? vscButtonBackground : lightGray + "33"}; + !props.disabled && props.isPrimary + ? vscButtonBackground + : lightGray + "33"}; border-radius: ${defaultBorderRadius}; - color: ${(props) => (props.isPrimary ? vscButtonForeground : vscForeground)}; + color: ${(props) => + !props.disabled && props.isPrimary ? vscButtonForeground : vscForeground}; cursor: pointer; :disabled { @@ -75,7 +80,6 @@ export interface ToolbarOptions { interface InputToolbarProps { onEnter?: (modifiers: InputModifiers) => void; onAddContextItem?: () => void; - onAddSlashCommand?: () => void; onClick?: () => void; onImageFileSelected?: (file: File) => void; hidden?: boolean; @@ -83,6 +87,8 @@ interface InputToolbarProps { toolbarOptions?: ToolbarOptions; disabled?: boolean; isMainInput?: boolean; + lumpOpen: boolean; + setLumpOpen: (open: boolean) => void; } function InputToolbar(props: InputToolbarProps) { @@ -92,8 +98,13 @@ function InputToolbar(props: InputToolbarProps) { const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); + const toolCallState = useAppSelector(selectCurrentToolCall); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; + + const isEnterDisabled = + props.disabled || + isEditModeAndNoCodeToEdit || + toolCallState?.status === "generated"; const toolsSupported = defaultModel && modelSupportsTools(defaultModel); const supportsImages = @@ -105,14 +116,20 @@ function InputToolbar(props: InputToolbarProps) { defaultModel.capabilities, ); + const smallFont = useFontSize(-2); + const tinyFont = useFontSize(-3); + return ( <> - -
+
+
{props.toolbarOptions?.hideImageUpload || @@ -132,7 +149,7 @@ function InputToolbar(props: InputToolbarProps) { /> { fileInputRef.current?.click(); @@ -148,7 +165,7 @@ function InputToolbar(props: InputToolbarProps) { @@ -156,12 +173,15 @@ function InputToolbar(props: InputToolbarProps) { )} - -
-
+
{!props.toolbarOptions?.hideUseCodebase && !isInEditMode && ( - +
); } diff --git a/gui/src/components/mainInput/InputToolbar/PopoverTransition.tsx b/gui/src/components/mainInput/InputToolbar/PopoverTransition.tsx deleted file mode 100644 index 24b64c27b..000000000 --- a/gui/src/components/mainInput/InputToolbar/PopoverTransition.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Transition } from "@headlessui/react"; - -export default function PopoverTransition({ - children, - show, - afterLeave, -}: { - children: React.ReactNode; - show?: boolean; - afterLeave?: () => void; -}) { - return ( - - {children} - - ); -} diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx deleted file mode 100644 index 20dae9160..000000000 --- a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx +++ /dev/null @@ -1,178 +0,0 @@ -import { Listbox } from "@headlessui/react"; -import { - EllipsisHorizontalCircleIcon as EllipsisHorizontalIcon, - WrenchScrewdriverIcon as WrenchScrewdriverIconOutline, -} from "@heroicons/react/24/outline"; -import { WrenchScrewdriverIcon as WrenchScrewdriverIconSolid } from "@heroicons/react/24/solid"; -import { useEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import { lightGray, vscForeground } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; -import { toggleUseTools } from "../../../redux/slices/uiSlice"; -import { ToolTip } from "../../gui/Tooltip"; -import InfoHover from "../../InfoHover"; -import HoverItem from "./HoverItem"; -import PopoverTransition from "./PopoverTransition"; -import ToolDropdownItem from "./ToolDropdownItem"; -import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; - -interface ToolDropdownProps { - disabled: boolean; -} - -export default function ToolDropdown(props: ToolDropdownProps) { - const buttonRef = useRef(null); - const dispatch = useDispatch(); - const [isDropdownOpen, setDropdownOpen] = useState(false); - const [isHovered, setIsHovered] = useState(false); - - const useTools = useAppSelector((state) => state.ui.useTools); - const availableTools = useAppSelector((state) => state.config.config.tools); - const [showAbove, setShowAbove] = useState(false); - const isInEditMode = useAppSelector(selectIsInEditMode); - - const ToolsIcon = useTools - ? WrenchScrewdriverIconSolid - : WrenchScrewdriverIconOutline; - - useEffect(() => { - const checkPosition = () => { - if (buttonRef.current) { - const rect = buttonRef.current.getBoundingClientRect(); - const windowHeight = window.innerHeight; - const spaceBelow = windowHeight - rect.bottom; - setShowAbove(spaceBelow < 250); - } - }; - - if (isDropdownOpen) { - checkPosition(); - } - }, [isDropdownOpen]); - - const isDisabled = props.disabled || isInEditMode; - - return ( - !isDisabled && dispatch(toggleUseTools())}> -
- !isDisabled && setIsHovered(true)} - onMouseLeave={() => !isDisabled && setIsHovered(false)} - /> - {isDisabled && ( - - {isInEditMode - ? "Tool use not supported in edit mode" - : "This model does not support tool use"} - - )} - {!useTools && !isDisabled && ( - - Enable tool usage - - )} - - {useTools && !isDisabled && ( - <> - Tools - -
- {}} - as="div" - onClick={(e) => e.stopPropagation()} - disabled={isDisabled} - > - {({ open }) => ( - <> - { - e.stopPropagation(); - setDropdownOpen(!isDropdownOpen); - }} - className="text-lightgray flex cursor-pointer items-center border-none bg-transparent px-0 outline-none" - aria-disabled={isDisabled} - > - - - setDropdownOpen(false)} - > - -
-
- Tool policies{" "} - -

- - Automatic: - {" "} - Can be used without asking -

-

- - Allowed: - {" "} - Will ask before using -

-

- - Disabled: - {" "} - Cannot be used -

-
- } - /> -
-
-
- {availableTools.map((tool: any) => ( - - - - ))} -
- - - - )} - -
- - )} -
- - ); -} diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx deleted file mode 100644 index 5df66f147..000000000 --- a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { Tool } from "core"; -import { useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { addTool, toggleToolSetting } from "../../../redux/slices/uiSlice"; -import { RootState } from "../../../redux/store"; - -interface ToolDropdownItemProps { - tool: Tool; -} - -function ToolDropdownItem(props: ToolDropdownItemProps) { - const dispatch = useDispatch(); - const settings = useSelector( - (state: RootState) => state.ui.toolSettings[props.tool.function.name], - ); - - useEffect(() => { - if (!settings) { - dispatch(addTool(props.tool)); - } - }, [props.tool.function.name, settings]); - - if (!settings) { - return null; - } - - return ( -
{ - dispatch(toggleToolSetting(props.tool.function.name)); - e.stopPropagation(); - e.preventDefault(); - }} - > - - {props.tool.faviconUrl && ( - {props.tool.displayTitle} - )} - {props.tool.displayTitle}{" "} - {/* */} - -
- {(settings === "allowedWithPermission" || settings === undefined) && ( - Allowed - )} - {settings === "allowedWithoutPermission" && ( - Automatic - )} - {settings === "disabled" && ( - Disabled - )} -
-
- ); -} - -export default ToolDropdownItem; diff --git a/gui/src/components/mainInput/InputToolbar/HoverItem.tsx b/gui/src/components/mainInput/InputToolbar/bottom/HoverItem.tsx similarity index 65% rename from gui/src/components/mainInput/InputToolbar/HoverItem.tsx rename to gui/src/components/mainInput/InputToolbar/bottom/HoverItem.tsx index e668a69f2..4a8aefcdc 100644 --- a/gui/src/components/mainInput/InputToolbar/HoverItem.tsx +++ b/gui/src/components/mainInput/InputToolbar/bottom/HoverItem.tsx @@ -1,7 +1,7 @@ import styled from "styled-components"; -const HoverItem = styled.span<{ isActive?: boolean }>` - padding: 0 4px; +const HoverItem = styled.span<{ isActive?: boolean; px?: number }>` + padding: 0 ${(props) => props.px ?? 4}px; padding-top: 2px; padding-bottom: 2px; cursor: pointer; diff --git a/gui/src/components/mainInput/InputToolbar/bottom/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/bottom/ToolDropdownItem.tsx new file mode 100644 index 000000000..d607c3f2e --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/bottom/ToolDropdownItem.tsx @@ -0,0 +1,99 @@ +import { InformationCircleIcon } from "@heroicons/react/24/outline"; +import { Tool } from "core"; +import { useEffect } from "react"; +import { useDispatch } from "react-redux"; +import { useAppSelector } from "../../../../redux/hooks"; +import { addTool, toggleToolSetting } from "../../../../redux/slices/uiSlice"; +import { fontSize } from "../../../../util"; +import { ToolTip } from "../../../gui/Tooltip"; + +interface ToolDropdownItemProps { + tool: Tool; + duplicatesDetected: boolean; + excluded: boolean; +} + +function ToolDropdownItem(props: ToolDropdownItemProps) { + const dispatch = useDispatch(); + const settings = useAppSelector( + (state) => state.ui.toolSettings[props.tool.function.name], + ); + + useEffect(() => { + if (!settings) { + dispatch(addTool(props.tool)); + } + }, [props.tool.function.name, settings]); + + if (!settings) { + return null; + } + + return ( +
{ + dispatch(toggleToolSetting(props.tool.function.name)); + e.stopPropagation(); + e.preventDefault(); + }} + > +
+ {props.duplicatesDetected ? ( + <> +
+ +
+ +

+ Duplicate tool name{" "} + {props.tool.function.name}{" "} + + detected. Permissions will conflict and usage may be + unpredictable + +

+
+ + ) : null} + + {props.tool.faviconUrl && ( + {props.tool.displayTitle} + )} +
{props.tool.function.name}
+
+
+ {props.excluded ? ( + Excluded + ) : ( +
+ {(settings === "allowedWithPermission" || settings === undefined) && ( + Ask First + )} + {settings === "allowedWithoutPermission" && ( + Automatic + )} + {settings === "disabled" && ( + Excluded + )} +
+ )} +
+ ); +} + +export default ToolDropdownItem; diff --git a/gui/src/components/mainInput/InputToolbar/bottom/ToolPermissionsDialog.tsx b/gui/src/components/mainInput/InputToolbar/bottom/ToolPermissionsDialog.tsx new file mode 100644 index 000000000..5ab7bfa45 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/bottom/ToolPermissionsDialog.tsx @@ -0,0 +1,79 @@ +import { Tool } from "core"; +import { useMemo } from "react"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { toggleToolGroupSetting } from "../../../../redux/slices/uiSlice"; +import { fontSize } from "../../../../util"; +import ToggleSwitch from "../../../gui/Switch"; +import ToolDropdownItem from "./ToolDropdownItem"; + +export const ToolPermissionsDialog = () => { + const availableTools = useAppSelector((state) => state.config.config.tools); + const toolGroupSettings = useAppSelector( + (store) => store.ui.toolGroupSettings, + ); + const dispatch = useAppDispatch(); + + const toolsByGroup = useMemo(() => { + const byGroup: Record = {}; + for (const tool of availableTools) { + if (!byGroup[tool.group]) { + byGroup[tool.group] = []; + } + byGroup[tool.group].push(tool); + } + return Object.entries(byGroup); + }, [availableTools]); + + // Detect duplicate tool names + const duplicateDetection = useMemo(() => { + const counts: Record = {}; + availableTools.forEach((tool) => { + if (counts[tool.function.name]) { + counts[tool.function.name] = counts[tool.function.name] + 1; + } else { + counts[tool.function.name] = 1; + } + }); + return Object.fromEntries( + Object.entries(counts).map(([k, v]) => [k, v > 1]), + ); + }, [availableTools]); + + return ( + <> + {toolsByGroup.map(([groupName, tools]) => ( +
+
+

+ {groupName} +

+ dispatch(toggleToolGroupSetting(groupName))} + text="" + size={10} + /> +
+
+ {tools.map((tool) => ( + + ))} + {toolGroupSettings[groupName] === "exclude" && ( +
+ )} +
+
+ ))} + + ); +}; diff --git a/gui/src/components/mainInput/InputToolbar/top/TopInputToolbar.tsx b/gui/src/components/mainInput/InputToolbar/top/TopInputToolbar.tsx new file mode 100644 index 000000000..f82ea9860 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/top/TopInputToolbar.tsx @@ -0,0 +1,22 @@ +import { EllipsisHorizontalIcon } from "@heroicons/react/24/outline"; +import { ToolbarOptions } from "../../InputToolbar"; +import HoverItem from "../bottom/HoverItem"; + +interface TopInputToolbarProps { + toolbarOptions?: ToolbarOptions; + onAddContextItem?: () => void; + lumpOpen: boolean; + setLumpOpen: (open: boolean) => void; +} +export function TopInputToolbar(props: TopInputToolbarProps) { + return ( +
+ props.setLumpOpen(!props.lumpOpen)} + className="ml-auto" + > + + +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx new file mode 100644 index 000000000..5a6a27ae2 --- /dev/null +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -0,0 +1,137 @@ +import { + BookOpenIcon, + ChatBubbleLeftIcon, + ChevronLeftIcon, + CubeIcon, + EllipsisHorizontalIcon, + PencilIcon, + Squares2X2Icon, + WrenchScrewdriverIcon, +} from "@heroicons/react/24/outline"; +import { vscBadgeBackground, vscBadgeForeground } from "../.."; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice"; +import { fontSize } from "../../../util"; +import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; +import HoverItem from "../InputToolbar/bottom/HoverItem"; + +interface BlockSettingsToolbarIcon { + tooltip: string; + icon: React.ComponentType; + itemCount?: number; + onClick: () => void; + isSelected?: boolean; + className?: string; +} + +interface Section { + id: string; + tooltip: string; + icon: React.ComponentType; +} + +const sections: Section[] = [ + { id: "models", tooltip: "Models", icon: CubeIcon }, + { id: "rules", tooltip: "Rules", icon: PencilIcon }, + { id: "docs", tooltip: "Docs", icon: BookOpenIcon }, + { id: "prompts", tooltip: "Prompts", icon: ChatBubbleLeftIcon }, + { id: "tools", tooltip: "Tools", icon: WrenchScrewdriverIcon }, + { id: "mcp", tooltip: "MCP", icon: Squares2X2Icon }, +]; + +function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) { + return ( + +
{ + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + props.onClick(); + } + }} + style={{ + backgroundColor: props.isSelected ? vscBadgeBackground : undefined, + }} + className={`relative flex select-none items-center rounded-full px-1 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 ${props.className || ""}`} + > +
+
+ ); +} + +interface BlockSettingsTopToolbarProps { + selectedSection: string | null; + setSelectedSection: (value: string | null) => void; +} + +export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) { + const isExpanded = useAppSelector( + (state) => state.ui.isBlockSettingsToolbarExpanded, + ); + const dispatch = useAppDispatch(); + const handleEllipsisClick = () => { + if (isExpanded) { + props.setSelectedSection(null); + } + dispatch(toggleBlockSettingsToolbar()); + }; + + return ( +
+
+ +
+
+ {sections.map((section) => ( + + props.setSelectedSection( + props.selectedSection === section.id ? null : section.id, + ) + } + /> + ))} +
+
+
+
+ +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx new file mode 100644 index 000000000..53cd82cfb --- /dev/null +++ b/gui/src/components/mainInput/Lump/EditBlockButton.tsx @@ -0,0 +1,52 @@ +import { ConfigYaml } from "@continuedev/config-yaml"; +import { PencilIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { useAuth } from "../../../context/Auth"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; + +type SectionKey = Exclude; + +interface EditBlockButtonProps { + blockType: T; + block?: NonNullable[number]; + className?: string; +} + +function isUsesBlock(block: any): block is { uses: string } { + return typeof block !== "string" && "uses" in block; +} + +export default function EditBlockButton({ + block, + blockType, + className = "", +}: EditBlockButtonProps) { + const ideMessenger = useContext(IdeMessengerContext); + const { selectedProfile } = useAuth(); + + const openUrl = (path: string) => + ideMessenger.request("controlPlane/openUrl", { + path, + orgSlug: undefined, + }); + + const handleEdit = () => { + if (selectedProfile?.profileType === "local") { + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + } else if (block && isUsesBlock(block)) { + openUrl(`${block.uses}/new-version`); + } else if (selectedProfile?.fullSlug) { + const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`; + openUrl(`${slug}/new-version`); + } + }; + + return ( + + ); +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx new file mode 100644 index 000000000..cca7885d3 --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -0,0 +1,73 @@ +import { useContext } from "react"; +import styled from "styled-components"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { + clearLastEmptyResponse, + setInactive, +} from "../../../redux/slices/sessionSlice"; +import { getFontSize, getMetaKeyLabel } from "../../../util"; +import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; + +const Container = styled.div` + display: flex; + justify-content: flex-end; + width: 100%; +`; + +const StopButton = styled.div` + font-size: ${getFontSize() - 3}px; + padding: 2px; + padding-right: 4px; + cursor: pointer; +`; + +interface TopToolbarProps { + selectedSection: string | null; + setSelectedSection: (value: string | null) => void; +} + +export function LumpToolbar(props: TopToolbarProps) { + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const ttsActive = useAppSelector((state) => state.ui.ttsActive); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + + if (ttsActive) { + return ( + + { + ideMessenger.post("tts/kill", undefined); + }} + > + ■ Stop TTS + + + ); + } + + if (isStreaming) { + return ( + + { + dispatch(setInactive()); + dispatch(clearLastEmptyResponse()); + }} + > + {getMetaKeyLabel()} ⌫ Cancel + + + ); + } + + return ( + + ); +} diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx new file mode 100644 index 000000000..a642136b4 --- /dev/null +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -0,0 +1,83 @@ +import { useEffect, useState } from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + vscCommandCenterInactiveBorder, + vscInputBackground, +} from "../.."; +import { useAppSelector } from "../../../redux/hooks"; +import { LumpToolbar } from "./LumpToolbar"; +import { SelectedSection } from "./sections/SelectedSection"; + +interface LumpProps { + open: boolean; + setOpen: (open: boolean) => void; +} + +const LumpDiv = styled.div<{ open: boolean }>` + background-color: ${vscInputBackground}; + margin-left: 4px; + margin-right: 4px; + border-radius: ${defaultBorderRadius} ${defaultBorderRadius} 0 0; + border-top: 1px solid ${vscCommandCenterInactiveBorder}; + border-left: 1px solid ${vscCommandCenterInactiveBorder}; + border-right: 1px solid ${vscCommandCenterInactiveBorder}; +`; + +const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>` + transition: + max-height 0.3s ease-in-out, + margin 0.3s ease-in-out, + opacity 0.2s ease-in-out; + max-height: ${(props) => (props.hasSection ? "200px" : "0px")}; + margin: ${(props) => (props.hasSection ? "4px 0" : "0")}; + opacity: ${(props) => (props.isVisible ? "1" : "0")}; + overflow-y: auto; +`; + +export function Lump(props: LumpProps) { + const { open, setOpen } = props; + const [selectedSection, setSelectedSection] = useState(null); + const [displayedSection, setDisplayedSection] = useState(null); + const [isVisible, setIsVisible] = useState(false); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + + useEffect(() => { + if (selectedSection) { + setDisplayedSection(selectedSection); + setIsVisible(true); + } else { + setIsVisible(false); + // Delay clearing the displayed section until after the fade-out + const timeout = setTimeout(() => { + setDisplayedSection(null); + }, 300); // Match the transition duration + return () => clearTimeout(timeout); + } + }, [selectedSection]); + + if (!open) { + return null; + } + + return ( + +
+ + + + {!isStreaming && ( + + )} + +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/ContextSection.tsx b/gui/src/components/mainInput/Lump/sections/ContextSection.tsx new file mode 100644 index 000000000..7524fd08d --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ContextSection.tsx @@ -0,0 +1,3 @@ +export function ContextSection() { + return
Context content
; +} diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx new file mode 100644 index 000000000..ad2212ac7 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -0,0 +1,67 @@ +import { + ArrowTopRightOnSquareIcon, + PlusIcon, +} from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { GhostButton } from "../../.."; +import { useAuth } from "../../../../context/Auth"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../../redux/hooks"; +import { + setDialogMessage, + setShowDialog, +} from "../../../../redux/slices/uiSlice"; +import { fontSize } from "../../../../util"; +import AddDocsDialog from "../../../dialogs/AddDocsDialog"; + +export function ExploreBlocksButton(props: { blockType: string }) { + const { selectedProfile } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); + const dispatch = useAppDispatch(); + + const isLocal = selectedProfile?.profileType === "local"; + + const Icon = isLocal ? PlusIcon : ArrowTopRightOnSquareIcon; + const text = `${isLocal ? "Add" : "Explore"} ${ + props.blockType === "mcpServers" + ? "MCP Servers" + : props.blockType.charAt(0).toUpperCase() + props.blockType.slice(1) + }`; + + const handleClick = () => { + if (isLocal) { + switch (props.blockType) { + case "docs": + dispatch(setShowDialog(true)); + dispatch(setDialogMessage()); + break; + default: + ideMessenger.request("config/openProfile", { + profileId: selectedProfile.id, + }); + } + } else { + ideMessenger.request("controlPlane/openUrl", { + path: `new?type=block&blockType=${props.blockType}`, + orgSlug: undefined, + }); + } + }; + + return ( + { + e.preventDefault(); + handleClick(); + }} + > +
+ {text} +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/MCPSection.tsx new file mode 100644 index 000000000..b365dca34 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/MCPSection.tsx @@ -0,0 +1,5 @@ +import MCPServersPreview from "../../../../pages/config/MCPServersPreview"; + +export function MCPSection() { + return ; +} diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx new file mode 100644 index 000000000..05e9352f0 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -0,0 +1,114 @@ +import { ModelRole } from "@continuedev/config-yaml"; +import { ModelDescription } from "core"; +import { useContext } from "react"; +import { useAuth } from "../../../../context/Auth"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { + selectDefaultModel, + setDefaultModel, + updateConfig, +} from "../../../../redux/slices/configSlice"; +import { isJetBrains } from "../../../../util"; +import { ExploreBlocksButton } from "./ExploreBlocksButton"; + +export function ModelsSection() { + const { selectedProfile } = useAuth(); + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const config = useAppSelector((state) => state.config.config); + const jetbrains = isJetBrains(); + const selectedChatModel = useAppSelector(selectDefaultModel); + + function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) { + if (!selectedProfile) { + return; + } + // Optimistic update + dispatch( + updateConfig({ + ...config, + selectedModelByRole: { + ...config.selectedModelByRole, + [role]: model, + }, + }), + ); + ideMessenger.post("config/updateSelectedModel", { + profileId: selectedProfile.id, + role, + title: model?.title ?? null, + }); + } + + // TODO use handleRoleUpdate for chat + function handleChatModelSelection(model: ModelDescription | null) { + if (!model) { + return; + } + dispatch(setDefaultModel({ title: model.title })); + } + + return ( +
+
+ handleChatModelSelection(model)} + /> + handleRoleUpdate("autocomplete", model)} + /> + {/* Jetbrains has a model selector inline */} + {!jetbrains && ( + handleRoleUpdate("edit", model)} + /> + )} + handleRoleUpdate("apply", model)} + /> + handleRoleUpdate("embed", model)} + /> + handleRoleUpdate("rerank", model)} + /> +
+ +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx new file mode 100644 index 000000000..6ad536809 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -0,0 +1,91 @@ +import { + BookmarkIcon as BookmarkOutline, + PencilIcon, +} from "@heroicons/react/24/outline"; +import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid"; +import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands"; +import { useAppSelector } from "../../../../redux/hooks"; +import { fontSize } from "../../../../util"; +import { ExploreBlocksButton } from "./ExploreBlocksButton"; + +interface PromptRowProps { + command: string; + description: string; + isBookmarked: boolean; + setIsBookmarked: (isBookmarked: boolean) => void; + onEdit?: () => void; +} + +function PromptRow({ + command, + description, + isBookmarked, + setIsBookmarked, + onEdit, +}: PromptRowProps) { + return ( +
+
+ {command} + {description} +
+
+ +
setIsBookmarked(!isBookmarked)} + className="cursor-pointer pt-0.5 text-gray-400 hover:brightness-125" + > + {isBookmarked ? ( + + ) : ( + + )} +
+
+
+ ); +} + +export function PromptsSection() { + const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands(); + const slashCommands = useAppSelector( + (state) => state.config.config.slashCommands ?? [], + ); + + const handleEdit = (prompt: any) => { + // Handle edit action here + console.log("Editing prompt:", prompt); + }; + + const sortedCommands = [...slashCommands].sort((a, b) => { + const aBookmarked = isCommandBookmarked(a.name); + const bBookmarked = isCommandBookmarked(b.name); + if (aBookmarked && !bBookmarked) return -1; + if (!aBookmarked && bBookmarked) return 1; + return 0; + }); + + return ( +
+ {sortedCommands.map((prompt) => ( + toggleBookmark(prompt)} + onEdit={() => handleEdit(prompt)} + /> + ))} + +
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx new file mode 100644 index 000000000..4cb7b0051 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -0,0 +1,163 @@ +import { parseConfigYaml } from "@continuedev/config-yaml"; +import { ArrowsPointingOutIcon, PencilIcon } from "@heroicons/react/24/outline"; +import { useContext, useMemo } from "react"; +import { useSelector } from "react-redux"; +import { defaultBorderRadius, vscCommandCenterActiveBorder } from "../../.."; +import { useAuth } from "../../../../context/Auth"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../../redux/hooks"; +import { + setDialogMessage, + setShowDialog, +} from "../../../../redux/slices/uiSlice"; +import { RootState } from "../../../../redux/store"; +import { fontSize } from "../../../../util"; +import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; +import { ExploreBlocksButton } from "./ExploreBlocksButton"; + +interface RuleCardProps { + index: number; + rule: string; + onClick: () => void; + title: string; +} + +const RuleCard: React.FC = ({ index, rule, onClick, title }) => { + const dispatch = useAppDispatch(); + + function onClickExpand() { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( +
+

{title}

+
{rule}
+
, + ), + ); + } + + return ( +
+
+
+
+
+ {title} +
+
+ {rule} +
+
+
+ + + {" "} + + + +
+
+
+
+ ); +}; + +export function RulesSection() { + const ideMessenger = useContext(IdeMessengerContext); + const { selectedProfile } = useAuth(); + + const rules = useSelector( + (state: RootState) => state.config.config.rules ?? [], + ); + + const mergedRules = useMemo(() => { + const parsed = selectedProfile?.rawYaml + ? parseConfigYaml(selectedProfile?.rawYaml ?? "") + : undefined; + return rules.map((rule, index) => ({ + unrolledRule: rule, + ruleFromYaml: parsed?.rules?.[index], + })); + }, [rules]); + + const openUrl = (path: string) => + ideMessenger.request("controlPlane/openUrl", { + path, + orgSlug: undefined, + }); + + return ( +
+
+ {mergedRules.map((rule, index) => { + if (!rule.ruleFromYaml) { + return ( + + ideMessenger.post("config/openProfile", { + profileId: undefined, + }) + } + title="Locally Defined Rule" + /> + ); + } + + if (typeof rule.ruleFromYaml === "string") { + const slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; + + return ( + openUrl(`${slug}/new-version`)} + title="Inline Rule" + /> + ); + } + + if (!rule.ruleFromYaml?.uses) { + return null; + } + + const ruleSlug = rule.ruleFromYaml?.uses; + + return ( + openUrl(`${ruleSlug}/new-version`)} + title={ruleSlug} + /> + ); + })} +
+ +
+ ); +} +function useTypedDispatch() { + throw new Error("Function not implemented."); +} diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx new file mode 100644 index 000000000..28dc37c28 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -0,0 +1,32 @@ +import { ContextSection } from "./ContextSection"; +import DocsSection from "./docs/DocsSection"; +import { MCPSection } from "./MCPSection"; +import { ModelsSection } from "./ModelsSection"; +import { PromptsSection } from "./PromptsSection"; +import { RulesSection } from "./RulesSection"; +import { ToolsSection } from "./ToolsSection"; + +interface SelectedSectionProps { + selectedSection: string | null; +} + +export function SelectedSection(props: SelectedSectionProps) { + switch (props.selectedSection) { + case "models": + return ; + case "rules": + return ; + case "docs": + return ; + case "prompts": + return ; + case "context": + return ; + case "tools": + return ; + case "mcp": + return ; + default: + return null; + } +} diff --git a/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx b/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx new file mode 100644 index 000000000..af03f7220 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx @@ -0,0 +1,7 @@ +import { ToolPermissionsDialog } from "../../InputToolbar/bottom/ToolPermissionsDialog"; + +interface ToolsSectionProps {} + +export function ToolsSection({}: ToolsSectionProps) { + return ; +} diff --git a/gui/src/components/indexing/DocsDetailsDialog.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsDetailsDialog.tsx similarity index 81% rename from gui/src/components/indexing/DocsDetailsDialog.tsx rename to gui/src/components/mainInput/Lump/sections/docs/DocsDetailsDialog.tsx index f8d0a54e9..d9faee814 100644 --- a/gui/src/components/indexing/DocsDetailsDialog.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsDetailsDialog.tsx @@ -1,38 +1,15 @@ -import { - CheckIcon, - InformationCircleIcon, - PencilIcon, - PlusIcon, -} from "@heroicons/react/24/outline"; -import { - DocsIndexingDetails, - IndexingStatus, - PackageDocsResult, - SiteIndexingConfig, -} from "core"; -import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; +import { DocsIndexingDetails } from "core"; import { usePostHog } from "posthog-js/react"; -import { - useCallback, - useContext, - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, -} from "react"; +import { useCallback, useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { Input, SecondaryButton } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; -import { updateConfig } from "../../redux/slices/configSlice"; -import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import FileIcon from "../FileIcon"; -import { ToolTip } from "../gui/Tooltip"; -import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; import { Tooltip } from "react-tooltip"; - +import { SecondaryButton } from "../../../.."; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { useAppSelector } from "../../../../../redux/hooks"; +import { + setDialogMessage, + setShowDialog, +} from "../../../../../redux/slices/uiSlice"; interface DocsDetailsDialogProps { startUrl: string; } @@ -89,7 +66,6 @@ function DocsDetailsDialog({ startUrl }: DocsDetailsDialogProps) { comp = (

{`Title: ${data.config.title}`}

-

{`Pre-indexed doc: ${data.isPreIndexedDoc}`}

{!data.chunks?.length ? (
No article chunks
) : ( @@ -122,7 +98,7 @@ function DocsDetailsDialog({ startUrl }: DocsDetailsDialogProps) { data-tooltip-id={contentToolTipId} data-tooltip-delay-show={500} > - + {chunk.content} @@ -168,7 +144,7 @@ function DocsDetailsDialog({ startUrl }: DocsDetailsDialogProps) {

Docs index

{ e.stopPropagation(); ideMessenger.post("openUrl", startUrl); diff --git a/gui/src/components/indexing/DocsIndexingPeeks.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingPeeks.tsx similarity index 67% rename from gui/src/components/indexing/DocsIndexingPeeks.tsx rename to gui/src/components/mainInput/Lump/sections/docs/DocsIndexingPeeks.tsx index 833c71430..548cde046 100644 --- a/gui/src/components/indexing/DocsIndexingPeeks.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingPeeks.tsx @@ -1,9 +1,11 @@ -import { useDispatch } from "react-redux"; import { IndexingStatus } from "core"; import { useMemo } from "react"; +import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; -import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { useAppSelector } from "../../redux/hooks"; +import { + setDialogMessage, + setShowDialog, +} from "../../../../../redux/slices/uiSlice"; export interface DocsIndexingPeekProps { status: IndexingStatus; @@ -19,14 +21,14 @@ function DocsIndexingPeek({ status }: DocsIndexingPeekProps) { return (

{ - navigate("/more"); + // navigate("/more"); TODO dispatch(setShowDialog(false)); dispatch(setDialogMessage(undefined)); }} > -

+

{status.title}

@@ -37,12 +39,12 @@ function DocsIndexingPeek({ status }: DocsIndexingPeekProps) { }} />
-
+
{progressPercentage.toFixed(0)}% {/* */}
@@ -56,17 +58,10 @@ interface DocsIndexingPeeksProps { function DocsIndexingPeekList({ statuses }: DocsIndexingPeeksProps) { return (
-

- Currently Indexing: -

- {statuses.length ? ( - statuses.map((status) => { - return ; - }) - ) : ( -

None

- )} + {statuses.map((status) => { + return ; + })}
); diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx new file mode 100644 index 000000000..51b9d35c3 --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx @@ -0,0 +1,154 @@ +import { ConfigYaml } from "@continuedev/config-yaml"; +import { ArrowPathIcon, StopIcon } from "@heroicons/react/24/outline"; +import { SiteIndexingConfig } from "core"; +import { useContext, useMemo, useState } from "react"; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; +import { updateIndexingStatus } from "../../../../../redux/slices/indexingSlice"; +import { + setDialogMessage, + setShowDialog, +} from "../../../../../redux/slices/uiSlice"; +import { fontSize } from "../../../../../util"; +import ConfirmationDialog from "../../../../dialogs/ConfirmationDialog"; +import EditBlockButton from "../../EditBlockButton"; +import { StatusIndicator } from "./StatusIndicator"; +interface IndexingStatusViewerProps { + docConfig: SiteIndexingConfig; + docFromYaml?: NonNullable[number]; +} + +function DocsIndexingStatus({ + docConfig, + docFromYaml, +}: IndexingStatusViewerProps) { + const ideMessenger = useContext(IdeMessengerContext); + const dispatch = useAppDispatch(); + + const status = useAppSelector( + (store) => store.indexing.indexing.statuses[docConfig.startUrl], + ); + + const reIndex = () => + ideMessenger.post("indexing/reindex", { + type: "docs", + id: docConfig.startUrl, + }); + + const abort = () => { + ideMessenger.post("indexing/abort", { + type: "docs", + id: docConfig.startUrl, + }); + // Optimistic abort status + if (status) { + dispatch( + updateIndexingStatus({ ...status, status: "aborted", progress: 0 }), + ); + } + }; + + const [hasDeleted, setHasDeleted] = useState(false); // simple alternative to optimistic redux update + const onDelete = () => { + // optimistic update + dispatch( + setDialogMessage( + { + ideMessenger.post("context/removeDocs", { + startUrl: docConfig.startUrl, + }); + setHasDeleted(true); + }} + />, + ), + ); + dispatch(setShowDialog(true)); + }; + + const progressPercentage = useMemo(() => { + if (!status) { + return 0; + } + return Math.min(100, Math.max(0, status.progress * 100)).toFixed(0); + }, [status?.progress]); + + if (hasDeleted) return null; + + return ( +
+
+
{ + if (status?.url) { + ideMessenger.post("openUrl", status.url); + } + }} + > + {docConfig.faviconUrl ? ( + doc icon + ) : null} +

+ {docConfig.title ?? docConfig.startUrl} +

+
+ +
+
+ {status?.status === "indexing" && ( + + {progressPercentage}% + + )} + + {status?.status === "indexing" && ( + + )} + + + + {["aborted", "complete", "failed"].includes( + status?.status ?? "", + ) && ( + + )} + + +
+
+
+
+ ); +} + +export default DocsIndexingStatus; diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx new file mode 100644 index 000000000..27796aecb --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx @@ -0,0 +1,78 @@ +import { parseConfigYaml } from "@continuedev/config-yaml"; +import { IndexingStatus } from "core"; +import { useMemo } from "react"; +import { useDispatch } from "react-redux"; +import { useAuth } from "../../../../../context/Auth"; +import { useAppSelector } from "../../../../../redux/hooks"; +import { ExploreBlocksButton } from "../ExploreBlocksButton"; +import DocsIndexingStatus from "./DocsIndexingStatus"; + +function DocsIndexingStatuses() { + const dispatch = useDispatch(); + const config = useAppSelector((store) => store.config.config); + const indexingStatuses = useAppSelector( + (store) => store.indexing.indexing.statuses, + ); + const { selectedProfile } = useAuth(); + + const mergedDocs = useMemo(() => { + const parsed = selectedProfile?.rawYaml + ? parseConfigYaml(selectedProfile?.rawYaml ?? "") + : undefined; + return (config.docs ?? []).map((doc, index) => ({ + doc, + docFromYaml: parsed?.docs?.[index], + })); + }, [config.docs, selectedProfile?.rawYaml]); + + const sortedConfigDocs = useMemo(() => { + const sorter = (status: IndexingStatus["status"]) => { + if (status === "complete") return 0; + if (status === "indexing" || status === "paused") return 1; + if (status === "failed") return 2; + if (status === "aborted" || status === "pending") return 3; + return 4; + }; + + const docs = [...mergedDocs]; + docs.sort((a, b) => { + const statusA = indexingStatuses[a.doc.startUrl]?.status ?? "pending"; + const statusB = indexingStatuses[b.doc.startUrl]?.status ?? "pending"; + + // First, compare by status + const statusCompare = sorter(statusA) - sorter(statusB); + if (statusCompare !== 0) return statusCompare; + + // If status is the same, sort by presence of icon + const hasIconA = !!a.doc.faviconUrl; + const hasIconB = !!b.doc.faviconUrl; + return hasIconB === hasIconA ? 0 : hasIconB ? 1 : -1; + }); + return docs; + }, [mergedDocs, indexingStatuses]); + + return ( +
+
+ {sortedConfigDocs.map((docConfig) => { + return ( +
+
+ +
+
+ ); + })} +
+ +
+ ); +} + +export default DocsIndexingStatuses; diff --git a/gui/src/components/mainInput/Lump/sections/docs/StatusIndicator.tsx b/gui/src/components/mainInput/Lump/sections/docs/StatusIndicator.tsx new file mode 100644 index 000000000..d6dd2d55a --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/docs/StatusIndicator.tsx @@ -0,0 +1,44 @@ +import { IndexingStatus } from "core"; +import { ToolTip } from "../../../../gui/Tooltip"; + +interface StatusIndicatorProps { + status?: IndexingStatus["status"]; + className?: string; + size?: number; + hoverMessage?: string; +} + +const STATUS_TO_COLOR: Record = { + indexing: "bg-yellow-500", + paused: "bg-blue-500", + complete: "bg-green-500", + aborted: "bg-gray-500", + pending: "bg-gray-300", + failed: "bg-red-500", +}; + +export function StatusIndicator({ + status, + className = "", + size = 2, + hoverMessage, +}: StatusIndicatorProps) { + if (!status) return null; + + const indicator = ( +
+ ); + + return ( + <> + {indicator} + {hoverMessage && } + + ); +} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx deleted file mode 100644 index 046da1021..000000000 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ /dev/null @@ -1,1036 +0,0 @@ -import Document from "@tiptap/extension-document"; -import History from "@tiptap/extension-history"; -import Image from "@tiptap/extension-image"; -import Paragraph from "@tiptap/extension-paragraph"; -import Placeholder from "@tiptap/extension-placeholder"; -import Text from "@tiptap/extension-text"; -import { Plugin } from "@tiptap/pm/state"; -import { Editor, EditorContent, JSONContent, useEditor } from "@tiptap/react"; -import { ContextProviderDescription, InputModifiers } from "core"; -import { rifWithContentsToContextItem } from "core/commands/util"; -import { modelSupportsImages } from "core/llm/autodetect"; -import { debounce } from "lodash"; -import { usePostHog } from "posthog-js/react"; -import { - KeyboardEvent, - useCallback, - useContext, - useEffect, - useRef, - useState, -} from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscBadgeBackground, - vscCommandCenterActiveBorder, - vscCommandCenterInactiveBorder, - vscForeground, - vscInputBackground, - vscInputBorderFocus, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; -import { useInputHistory } from "../../hooks/useInputHistory"; -import useIsOSREnabled from "../../hooks/useIsOSREnabled"; -import useUpdatingRef from "../../hooks/useUpdatingRef"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectUseActiveFile } from "../../redux/selectors"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; -import { - addCodeToEdit, - clearCodeToEdit, - selectHasCodeToEdit, - selectIsInEditMode, - setMainEditorContentTrigger, - setNewestCodeblocksForInput, -} from "../../redux/slices/sessionSlice"; -import { exitEditMode } from "../../redux/thunks"; -import { - loadLastSession, - loadSession, - saveCurrentSession, -} from "../../redux/thunks/session"; -import { - getFontSize, - isJetBrains, - isMetaEquivalentKeyPressed, -} from "../../util"; -import { AddCodeToEdit } from "./AddCodeToEditExtension"; -import { CodeBlockExtension } from "./CodeBlockExtension"; -import { SlashCommand } from "./CommandsExtension"; -import { MockExtension } from "./FillerExtension"; -import InputToolbar, { ToolbarOptions } from "./InputToolbar"; -import { Mention } from "./MentionExtension"; -import "./TipTapEditor.css"; -import { - getContextProviderDropdownOptions, - getSlashCommandDropdownOptions, -} from "./getSuggestion"; -import { - handleJetBrainsOSRMetaKeyIssues, - handleVSCMetaKeyIssues, -} from "./handleMetaKeyIssues"; -import { ComboBoxItem } from "./types"; - -const InputBoxDiv = styled.div<{}>` - resize: none; - padding-bottom: 4px; - font-family: inherit; - border-radius: ${defaultBorderRadius}; - margin: 0; - height: auto; - width: 100%; - background-color: ${vscInputBackground}; - color: ${vscForeground}; - - border: 1px solid ${vscCommandCenterInactiveBorder}; - transition: border-color 0.15s ease-in-out; - &:focus-within { - border: 1px solid ${vscCommandCenterActiveBorder}; - } - - outline: none; - font-size: ${getFontSize()}px; - - &:focus { - outline: none; - - border: 0.5px solid ${vscInputBorderFocus}; - } - - &::placeholder { - color: ${lightGray}cc; - } - - display: flex; - flex-direction: column; -`; - -const HoverDiv = styled.div` - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; - opacity: 0.5; - background-color: ${vscBadgeBackground}; - color: ${vscForeground}; - display: flex; - align-items: center; - justify-content: center; -`; - -const HoverTextDiv = styled.div` - position: absolute; - width: 100%; - height: 100%; - top: 0; - left: 0; - color: ${vscForeground}; - display: flex; - align-items: center; - justify-content: center; -`; - -const IMAGE_RESOLUTION = 1024; -function getDataUrlForFile( - file: File, - img: HTMLImageElement, -): string | undefined { - const targetWidth = IMAGE_RESOLUTION; - const targetHeight = IMAGE_RESOLUTION; - const scaleFactor = Math.min( - targetWidth / img.width, - targetHeight / img.height, - ); - - const canvas = document.createElement("canvas"); - canvas.width = img.width * scaleFactor; - canvas.height = img.height * scaleFactor; - - const ctx = canvas.getContext("2d"); - if (!ctx) { - console.error("Error getting image data url: 2d context not found"); - return; - } - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); - - const downsizedDataUrl = canvas.toDataURL("image/jpeg", 0.7); - return downsizedDataUrl; -} - -interface TipTapEditorProps { - availableContextProviders: ContextProviderDescription[]; - availableSlashCommands: ComboBoxItem[]; - isMainInput: boolean; - onEnter: ( - editorState: JSONContent, - modifiers: InputModifiers, - editor: Editor, - ) => void; - editorState?: JSONContent; - toolbarOptions?: ToolbarOptions; - placeholder?: string; - historyKey: string; - inputId: string; -} - -export const TIPPY_DIV_ID = "tippy-js-div"; - -function TipTapEditor(props: TipTapEditorProps) { - const dispatch = useAppDispatch(); - - const ideMessenger = useContext(IdeMessengerContext); - const { getSubmenuContextItems } = useSubmenuContextProviders(); - - const historyLength = useAppSelector((store) => store.session.history.length); - - const useActiveFile = useAppSelector(selectUseActiveFile); - - const posthog = usePostHog(); - - const inSubmenuRef = useRef(undefined); - const inDropdownRef = useRef(false); - - const isOSREnabled = useIsOSREnabled(); - - const enterSubmenu = async (editor: Editor, providerId: string) => { - const contents = editor.getText(); - const indexOfAt = contents.lastIndexOf("@"); - if (indexOfAt === -1) { - return; - } - - // Find the position of the last @ character - // We do this because editor.getText() isn't a correct representation including node views - let startPos = editor.state.selection.anchor; - while ( - startPos > 0 && - editor.state.doc.textBetween(startPos, startPos + 1) !== "@" - ) { - startPos--; - } - startPos++; - - editor.commands.deleteRange({ - from: startPos, - to: editor.state.selection.anchor, - }); - inSubmenuRef.current = providerId; - - // to trigger refresh of suggestions - editor.commands.insertContent(":"); - editor.commands.deleteRange({ - from: editor.state.selection.anchor - 1, - to: editor.state.selection.anchor, - }); - }; - - const onClose = () => { - inSubmenuRef.current = undefined; - inDropdownRef.current = false; - }; - - const onOpen = () => { - inDropdownRef.current = true; - }; - - const defaultModel = useAppSelector(selectDefaultModel); - const defaultModelRef = useUpdatingRef(defaultModel); - - const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); - const availableContextProvidersRef = useUpdatingRef( - props.availableContextProviders, - ); - - const historyLengthRef = useUpdatingRef(historyLength); - const availableSlashCommandsRef = useUpdatingRef( - props.availableSlashCommands, - ); - - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const isStreamingRef = useUpdatingRef(isStreaming); - - const isInEditMode = useAppSelector(selectIsInEditMode); - const isInEditModeRef = useUpdatingRef(isInEditMode); - const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); - const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - async function handleImageFile( - file: File, - ): Promise<[HTMLImageElement, string] | undefined> { - let filesize = file.size / 1024 / 1024; // filesize in MB - // check image type and size - if ( - [ - "image/jpeg", - "image/jpg", - "image/png", - "image/gif", - "image/svg", - "image/webp", - ].includes(file.type) && - filesize < 10 - ) { - // check dimensions - let _URL = window.URL || window.webkitURL; - let img = new window.Image(); - img.src = _URL.createObjectURL(file); - - return await new Promise((resolve) => { - img.onload = function () { - const dataUrl = getDataUrlForFile(file, img); - if (!dataUrl) { - return; - } - - let image = new window.Image(); - image.src = dataUrl; - image.onload = function () { - resolve([image, dataUrl]); - }; - }; - }); - } else { - ideMessenger.post("showToast", [ - "error", - "Images need to be in jpg or png format and less than 10MB in size.", - ]); - } - } - - const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); - - const editor: Editor | null = useEditor({ - extensions: [ - Document, - History, - Image.extend({ - addProseMirrorPlugins() { - const plugin = new Plugin({ - props: { - handleDOMEvents: { - paste(view, event) { - const model = defaultModelRef.current; - if (!model) return; - const items = event.clipboardData?.items; - if (items) { - for (const item of items) { - const file = item.getAsFile(); - file && - modelSupportsImages( - model.provider, - model.model, - model.title, - model.capabilities, - ) && - handleImageFile(file).then((resp) => { - if (!resp) return; - const [img, dataUrl] = resp; - const { schema } = view.state; - const node = schema.nodes.image.create({ - src: dataUrl, - }); - const tr = view.state.tr.insert(0, node); - view.dispatch(tr); - }); - } - } - }, - }, - }, - }); - return [plugin]; - }, - }).configure({ - HTMLAttributes: { - class: "object-contain max-h-[210px] max-w-full mx-1", - }, - }), - Placeholder.configure({ - placeholder: getPlaceholderText( - props.placeholder, - historyLengthRef.current, - ), - }), - Paragraph.extend({ - addKeyboardShortcuts() { - return { - Enter: () => { - if (inDropdownRef.current) { - return false; - } - - onEnterRef.current({ - useCodebase: false, - noContext: !useActiveFile, - }); - return true; - }, - - "Mod-Enter": () => { - onEnterRef.current({ - useCodebase: true, - noContext: !useActiveFile, - }); - return true; - }, - "Alt-Enter": () => { - posthog.capture("gui_use_active_file_enter"); - - onEnterRef.current({ - useCodebase: false, - noContext: !!useActiveFile, - }); - - return true; - }, - "Mod-Backspace": () => { - // If you press cmd+backspace wanting to cancel, - // but are inside of a text box, it shouldn't - // delete the text - if (isStreamingRef.current) { - return true; - } - return false; - }, - "Shift-Enter": () => - this.editor.commands.first(({ commands }) => [ - () => commands.newlineInCode(), - () => commands.createParagraphNear(), - () => commands.liftEmptyBlock(), - () => commands.splitBlock(), - ]), - - ArrowUp: () => { - if (this.editor.state.selection.anchor > 1) { - return false; - } - - const previousInput = prevRef.current( - this.editor.state.toJSON().doc, - ); - if (previousInput) { - this.editor.commands.setContent(previousInput); - setTimeout(() => { - this.editor.commands.blur(); - this.editor.commands.focus("start"); - }, 0); - return true; - } - return false; - }, - Escape: () => { - if (inDropdownRef.current || !isInEditModeRef.current) { - ideMessenger.post("focusEditor", undefined); - return true; - } - (async () => { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); - })(); - - return true; - }, - ArrowDown: () => { - if ( - this.editor.state.selection.anchor < - this.editor.state.doc.content.size - 1 - ) { - return false; - } - const nextInput = nextRef.current(); - if (nextInput) { - this.editor.commands.setContent(nextInput); - setTimeout(() => { - this.editor.commands.blur(); - this.editor.commands.focus("end"); - }, 0); - return true; - } - return false; - }, - }; - }, - }).configure({ - HTMLAttributes: { - class: "my-1", - }, - }), - Text, - Mention.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }), - - AddCodeToEdit.configure({ - HTMLAttributes: { - class: "add-code-to-edit", - }, - suggestion: { - ...getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - allow: () => isInEditModeRef.current, - command: async ({ editor, range, props }) => { - editor.chain().focus().insertContentAt(range, "").run(); - const filepath = props.id; - const contents = await ideMessenger.ide.readFile(filepath); - dispatch( - addCodeToEdit({ - filepath, - contents, - }), - ); - }, - items: async ({ query }) => { - // Only display files in the dropdown - const results = getSubmenuContextItemsRef.current("file", query); - return results.map((result) => ({ - ...result, - label: result.title, - type: "file", - query: result.id, - icon: result.icon, - })); - }, - }, - }), - props.availableSlashCommands.length - ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) - : MockExtension, - CodeBlockExtension, - ], - editorProps: { - attributes: { - class: "outline-none -mt-1 overflow-hidden", - style: `font-size: ${getFontSize()}px;`, - }, - }, - content: props.editorState, - editable: !isStreaming || props.isMainInput, - }); - - const [shouldHideToolbar, setShouldHideToolbar] = useState(false); - const debouncedShouldHideToolbar = debounce((value) => { - setShouldHideToolbar(value); - }, 200); - - function getPlaceholderText( - placeholder: TipTapEditorProps["placeholder"], - historyLength: number, - ) { - if (placeholder) { - return placeholder; - } - - return historyLength === 0 - ? "Ask anything, '@' to add context" - : "Ask a follow-up"; - } - - useEffect(() => { - if (!editor) { - return; - } - const placeholder = getPlaceholderText( - props.placeholder, - historyLengthRef.current, - ); - - editor.extensionManager.extensions.filter( - (extension) => extension.name === "placeholder", - )[0].options["placeholder"] = placeholder; - - editor.view.dispatch(editor.state.tr); - }, [editor, props.placeholder, historyLengthRef.current]); - - useEffect(() => { - if (props.isMainInput) { - editor?.commands.clearContent(true); - } - }, [editor, isInEditMode, props.isMainInput]); - - useEffect(() => { - if (editor) { - const handleFocus = () => { - setShouldHideToolbar(false); - }; - - const handleBlur = () => { - // TODO - make toolbar auto-hiding work without breaking tool dropdown focus - // debouncedShouldHideToolbar(true); - }; - - editor.on("focus", handleFocus); - editor.on("blur", handleBlur); - - return () => { - editor.off("focus", handleFocus); - editor.off("blur", handleBlur); - }; - } - }, [editor]); - - const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); - - /** - * This handles various issues with meta key actions - * - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to - * highlight code using arrow keys is not working - * - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect - * the actual notebook cells, even when performing them in our GUI - * - * Currently keydown events for a number of keys are not registering if the - * meta/shift key is pressed, for example "x", "c", "v", "z", etc. - * Until this is resolved we can't turn on OSR for non-Mac users due to issues - * with those key actions. - */ - const handleKeyDown = async (e: KeyboardEvent) => { - if (!editor) { - return; - } - - setActiveKey(e.key); - - if (!editorFocusedRef?.current || !isMetaEquivalentKeyPressed(e)) return; - - if (isOSREnabled) { - handleJetBrainsOSRMetaKeyIssues(e, editor); - } else if (!isJetBrains()) { - await handleVSCMetaKeyIssues(e, editor); - } - }; - - const handleKeyUp = () => { - setActiveKey(null); - }; - - const onEnterRef = useUpdatingRef( - (modifiers: InputModifiers) => { - if (!editor) { - return; - } - if (isStreaming || isEditModeAndNoCodeToEdit) { - return; - } - - const json = editor.getJSON(); - - // Don't do anything if input box is empty - if (!json.content?.some((c) => c.content)) { - return; - } - - if (props.isMainInput) { - addRef.current(json); - } - - props.onEnter(json, modifiers, editor); - }, - [props.onEnter, editor, props.isMainInput], - ); - - useEffect(() => { - if (props.isMainInput) { - /** - * I have a strong suspicion that many of the other focus - * commands are redundant, especially the ones inside - * useTimeout. - */ - editor?.commands.focus(); - } - }, [props.isMainInput, editor]); - - // Re-focus main input after done generating - useEffect(() => { - if (editor && !isStreaming && props.isMainInput && document.hasFocus()) { - editor.commands.focus(undefined, { scrollIntoView: false }); - } - }, [props.isMainInput, isStreaming, editor]); - - // This allows anywhere in the app to set the content of the main input - const mainInputContentTrigger = useAppSelector( - (store) => store.session.mainEditorContentTrigger, - ); - useEffect(() => { - if (!props.isMainInput || !mainInputContentTrigger) { - return; - } - queueMicrotask(() => { - editor?.commands.setContent(mainInputContentTrigger); - }); - dispatch(setMainEditorContentTrigger(undefined)); - }, [editor, props.isMainInput, mainInputContentTrigger]); - - // IDE event listeners - useWebviewListener( - "userInput", - async (data) => { - if (!props.isMainInput) { - return; - } - editor?.commands.insertContent(data.input); - onEnterRef.current({ useCodebase: false, noContext: true }); - }, - [editor, onEnterRef.current, props.isMainInput], - ); - - useWebviewListener("jetbrains/editorInsetRefresh", async () => { - editor?.chain().clearContent().focus().run(); - }); - - useWebviewListener( - "focusContinueInput", - async (data) => { - if (!props.isMainInput) { - return; - } - - dispatch(clearCodeToEdit()); - - if (historyLength > 0) { - await dispatch( - saveCurrentSession({ - openNewSession: false, - generateTitle: true, - }), - ); - } - setTimeout(() => { - editor?.commands.blur(); - editor?.commands.focus("end"); - }, 20); - }, - [historyLength, editor, props.isMainInput], - ); - - useWebviewListener( - "focusContinueInputWithoutClear", - async () => { - if (!props.isMainInput) { - return; - } - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "focusContinueInputWithNewSession", - async () => { - if (!props.isMainInput) { - return; - } - await dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: true, - }), - ); - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "highlightedCode", - async (data) => { - if (!props.isMainInput || !editor) { - return; - } - - const contextItem = rifWithContentsToContextItem( - data.rangeInFileWithContents, - ); - - let index = 0; - for (const el of editor.getJSON()?.content ?? []) { - if (el.attrs?.item?.name === contextItem.name) { - return; // Prevent exact duplicate code blocks - } - if (el.type === "codeBlock") { - index += 2; - } else { - break; - } - } - editor - .chain() - .insertContentAt(index, { - type: "codeBlock", - attrs: { - item: contextItem, - inputId: props.inputId, - }, - }) - .run(); - dispatch( - setNewestCodeblocksForInput({ - inputId: props.inputId, - contextItemId: contextItem.id.itemId, - }), - ); - if (data.prompt) { - editor.commands.focus("end"); - editor.commands.insertContent(data.prompt); - } - - if (data.shouldRun) { - onEnterRef.current({ useCodebase: false, noContext: true }); - } - - setTimeout(() => { - editor.commands.blur(); - editor.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput, historyLength, onEnterRef.current], - ); - - useWebviewListener( - "focusEdit", - async () => { - if (!props.isMainInput) { - return; - } - - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "focusEditWithoutClear", - async () => { - if (!props.isMainInput) { - return; - } - - setTimeout(() => { - editor?.commands.focus("end"); - }, 2000); - }, - [editor, props.isMainInput], - ); - - useWebviewListener( - "isContinueInputFocused", - async () => { - return props.isMainInput && !!editorFocusedRef.current; - }, - [editorFocusedRef, props.isMainInput], - !props.isMainInput, - ); - - useWebviewListener( - "focusContinueSessionId", - async (data) => { - if (!props.isMainInput || !data.sessionId) { - return; - } - await dispatch( - loadSession({ - sessionId: data.sessionId, - saveCurrentSession: true, - }), - ); - }, - [props.isMainInput], - ); - - const [showDragOverMsg, setShowDragOverMsg] = useState(false); - - useEffect(() => { - const overListener = (event: DragEvent) => { - if (event.shiftKey) return; - setShowDragOverMsg(true); - }; - window.addEventListener("dragover", overListener); - - const leaveListener = (event: DragEvent) => { - if (event.shiftKey) { - setShowDragOverMsg(false); - } else { - setTimeout(() => setShowDragOverMsg(false), 2000); - } - }; - window.addEventListener("dragleave", leaveListener); - - return () => { - window.removeEventListener("dragover", overListener); - window.removeEventListener("dragleave", leaveListener); - }; - }, []); - - const [activeKey, setActiveKey] = useState(null); - - const insertCharacterWithWhitespace = useCallback( - (char: string) => { - if (!editor) { - return; - } - const text = editor.getText(); - if (!text.endsWith(char)) { - if (text.length > 0 && !text.endsWith(" ")) { - editor.commands.insertContent(` ${char}`); - } else { - editor.commands.insertContent(char); - } - } - }, - [editor], - ); - - return ( - { - editor?.commands.focus(); - }} - onDragOver={(event) => { - event.preventDefault(); - setShowDragOverMsg(true); - }} - onDragLeave={(e) => { - if (e.relatedTarget === null) { - if (e.shiftKey) { - setShowDragOverMsg(false); - } else { - setTimeout(() => setShowDragOverMsg(false), 2000); - } - } - }} - onDragEnter={() => { - setShowDragOverMsg(true); - }} - onDrop={(event) => { - if ( - !defaultModel || - !modelSupportsImages( - defaultModel.provider, - defaultModel.model, - defaultModel.title, - defaultModel.capabilities, - ) - ) { - return; - } - setShowDragOverMsg(false); - let file = event.dataTransfer.files[0]; - handleImageFile(file).then((result) => { - if (!editor) { - return; - } - if (result) { - const [_, dataUrl] = result; - const { schema } = editor.state; - const node = schema.nodes.image.create({ src: dataUrl }); - const tr = editor.state.tr.insert(0, node); - editor.view.dispatch(tr); - } - }); - event.preventDefault(); - }} - > -
- { - event.stopPropagation(); - }} - /> -
- - {showDragOverMsg && - modelSupportsImages( - defaultModel?.provider || "", - defaultModel?.model || "", - defaultModel?.title, - defaultModel?.capabilities, - ) && ( - <> - - Hold ⇧ to drop image - - )} -
- - ); -} - -export default TipTapEditor; diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx deleted file mode 100644 index c31c8f4a3..000000000 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { - ArrowRightStartOnRectangleIcon, - BookOpenIcon, - ClipboardDocumentIcon, - Cog6ToothIcon, - PencilSquareIcon, - XMarkIcon, -} from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { lightGray } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { isJetBrains } from "../../util"; -import Shortcut from "../gui/Shortcut"; - -interface TutorialCardProps { - onClose: () => void; -} - -export function TutorialCard({ onClose }: TutorialCardProps) { - const ideMessenger = useContext(IdeMessengerContext); - const jetbrains = isJetBrains(); - - return ( -
-
-

-
- -
-
- -
    - {!jetbrains && ( -
  • - - - - ideMessenger.post("vscode/openMoveRightMarkdown", undefined) - } - > - Move Chat panel to the right - {" "} - for the cleanest experience - -
  • - )} -
  • -
    - -
    - - Highlight code and press meta I to quickly make - natural language edits - -
  • -
  • -
    - -
    - - Highlight code and press meta L to add it to - the chat window - -
  • -
  • -
    - -
    - - Click the gear icon in the upper right to configure Continue - -
  • -
  • -
    - -
    - - - ideMessenger.post("openUrl", "https://docs.continue.dev") - } - > - Read our documentation - {" "} - to learn more - -
  • -
-
- ); -} diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx similarity index 86% rename from gui/src/components/mainInput/ContextItemsPeek.tsx rename to gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 9e7d34070..eb63e0ee9 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -7,13 +7,14 @@ import { ContextItemWithId } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; import { getUriPathBasename } from "core/util/uri"; import { useContext, useMemo, useState } from "react"; -import { AnimatedEllipsis, lightGray, vscBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsGatheringContext } from "../../redux/slices/sessionSlice"; -import FileIcon from "../FileIcon"; -import SafeImg from "../SafeImg"; -import { getIconFromDropdownItem } from "./MentionList"; +import { AnimatedEllipsis, lightGray, vscBackground } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectIsGatheringContext } from "../../../redux/slices/sessionSlice"; +import FileIcon from "../../FileIcon"; +import SafeImg from "../../SafeImg"; +import { getIconFromDropdownItem } from "../AtMentionDropdown"; +import { NAMED_ICONS } from "../icons"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; @@ -59,13 +60,28 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const dimensions = "18px"; if (contextItem.icon) { + const NamedIcon = contextItem.icon + ? NAMED_ICONS[contextItem.icon] + : undefined; return ( + +
+ ) : null + } /> ); } diff --git a/gui/src/components/mainInput/NewSessionButton.tsx b/gui/src/components/mainInput/belowMainInput/NewSessionButton.tsx similarity index 90% rename from gui/src/components/mainInput/NewSessionButton.tsx rename to gui/src/components/mainInput/belowMainInput/NewSessionButton.tsx index 04193450c..d8623af96 100644 --- a/gui/src/components/mainInput/NewSessionButton.tsx +++ b/gui/src/components/mainInput/belowMainInput/NewSessionButton.tsx @@ -1,6 +1,6 @@ import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscForeground } from ".."; -import { getFontSize } from "../../util"; +import { defaultBorderRadius, lightGray, vscForeground } from "../.."; +import { getFontSize } from "../../../util"; export const NewSessionButton = styled.div` width: fit-content; diff --git a/gui/src/components/mainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx similarity index 97% rename from gui/src/components/mainInput/ThinkingBlockPeek.tsx rename to gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx index 851635230..a89ba2e6a 100644 --- a/gui/src/components/mainInput/ThinkingBlockPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx @@ -4,9 +4,9 @@ import { ChevronUpIcon } from "@heroicons/react/24/solid"; import { ChatHistoryItem } from "core"; import { useEffect, useState } from "react"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscBackground } from ".."; -import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import { defaultBorderRadius, lightGray, vscBackground } from "../.."; +import { getFontSize } from "../../../util"; +import StyledMarkdownPreview from "../../markdown/StyledMarkdownPreview"; const SpoilerButton = styled.div` background-color: ${vscBackground}; diff --git a/gui/src/components/mainInput/icons.ts b/gui/src/components/mainInput/icons.ts new file mode 100644 index 000000000..42b80da66 --- /dev/null +++ b/gui/src/components/mainInput/icons.ts @@ -0,0 +1,56 @@ +import { + ArrowUpOnSquareIcon, + Bars3BottomLeftIcon, + BookOpenIcon, + BugAntIcon, + CircleStackIcon, + CodeBracketIcon, + CommandLineIcon, + CpuChipIcon, + DocumentTextIcon, + ExclamationTriangleIcon, + FolderIcon, + FolderOpenIcon, + GlobeAltIcon, + MagnifyingGlassIcon, + PaperClipIcon, + PlusIcon, + SparklesIcon, + TrashIcon, +} from "@heroicons/react/24/outline"; +import { DiscordIcon } from "../svg/DiscordIcon"; +import { GithubIcon } from "../svg/GithubIcon"; +import { GitlabIcon } from "../svg/GitlabIcon"; +import { GoogleIcon } from "../svg/GoogleIcon"; + +export const NAMED_ICONS: { [key: string]: any } = { + file: FolderIcon, + code: CodeBracketIcon, + terminal: CommandLineIcon, + diff: PlusIcon, + search: MagnifyingGlassIcon, + url: GlobeAltIcon, + open: FolderOpenIcon, + codebase: SparklesIcon, + problems: ExclamationTriangleIcon, + folder: FolderIcon, + docs: BookOpenIcon, + web: GlobeAltIcon, + clipboard: PaperClipIcon, + database: CircleStackIcon, + postgres: CircleStackIcon, + debugger: BugAntIcon, + os: CpuChipIcon, + tree: Bars3BottomLeftIcon, + "prompt-files": DocumentTextIcon, + "repo-map": FolderIcon, + "/clear": TrashIcon, + "/share": ArrowUpOnSquareIcon, + "/cmd": CommandLineIcon, + issue: GithubIcon, + discord: DiscordIcon, + google: GoogleIcon, + "gitlab-mr": GitlabIcon, + http: GlobeAltIcon, + trash: TrashIcon, +}; diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx similarity index 92% rename from gui/src/components/mainInput/CodeBlockComponent.tsx rename to gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx index 61403a261..e63e273ad 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx @@ -1,7 +1,7 @@ import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; import { ContextItemWithId } from "core"; -import { vscBadgeBackground } from ".."; -import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; +import { vscBadgeBackground } from "../.."; +import CodeSnippetPreview from "../../markdown/CodeSnippetPreview"; export const CodeBlockComponent = (props: any) => { const { node, deleteNode, selected, editor, updateAttributes } = props; diff --git a/gui/src/components/mainInput/tiptap/DragOverlay.tsx b/gui/src/components/mainInput/tiptap/DragOverlay.tsx new file mode 100644 index 000000000..1417a8228 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/DragOverlay.tsx @@ -0,0 +1,40 @@ +import React, { useEffect } from "react"; +import { HoverDiv, HoverTextDiv } from "./StyledComponents"; + +interface DragOverlayProps { + show: boolean; + setShow: (show: boolean) => void; +} + +export const DragOverlay: React.FC = ({ show, setShow }) => { + useEffect(() => { + const overListener = (event: DragEvent) => { + if (event.shiftKey) return; + setShow(true); + }; + window.addEventListener("dragover", overListener); + + const leaveListener = (event: DragEvent) => { + if (event.shiftKey) { + setShow(false); + } else { + setTimeout(() => setShow(false), 2000); + } + }; + window.addEventListener("dragleave", leaveListener); + + return () => { + window.removeEventListener("dragover", overListener); + window.removeEventListener("dragleave", leaveListener); + }; + }, []); + + if (!show) return null; + + return ( + <> + + Hold ⇧ to drop image + + ); +}; diff --git a/gui/src/components/mainInput/tiptap/StyledComponents.ts b/gui/src/components/mainInput/tiptap/StyledComponents.ts new file mode 100644 index 000000000..2aca4f1be --- /dev/null +++ b/gui/src/components/mainInput/tiptap/StyledComponents.ts @@ -0,0 +1,72 @@ +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscBadgeBackground, + vscCommandCenterActiveBorder, + vscCommandCenterInactiveBorder, + vscForeground, + vscInputBackground, + vscInputBorderFocus, +} from "../.."; +import { getFontSize } from "../../../util"; + +export const InputBoxDiv = styled.div<{}>` + resize: none; + font-family: inherit; + border-radius: ${defaultBorderRadius}; + padding-bottom: 1px; + margin: 0; + height: auto; + width: 100%; + background-color: ${vscInputBackground}; + color: ${vscForeground}; + + border: 1px solid ${vscCommandCenterInactiveBorder}; + transition: border-color 0.15s ease-in-out; + &:focus-within { + border: 1px solid ${vscCommandCenterActiveBorder}; + } + + outline: none; + font-size: ${getFontSize()}px; + + &:focus { + outline: none; + + border: 0.5px solid ${vscInputBorderFocus}; + } + + &::placeholder { + color: ${lightGray}cc; + } + + display: flex; + flex-direction: column; +`; + +export const HoverDiv = styled.div` + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + opacity: 0.5; + background-color: ${vscBadgeBackground}; + color: ${vscForeground}; + display: flex; + align-items: center; + justify-content: center; +`; + +export const HoverTextDiv = styled.div` + position: absolute; + width: 100%; + height: 100%; + top: 0; + left: 0; + color: ${vscForeground}; + display: flex; + align-items: center; + justify-content: center; +`; diff --git a/gui/src/components/mainInput/TipTapEditor.css b/gui/src/components/mainInput/tiptap/TipTapEditor.css similarity index 100% rename from gui/src/components/mainInput/TipTapEditor.css rename to gui/src/components/mainInput/tiptap/TipTapEditor.css diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx new file mode 100644 index 000000000..47323e4ee --- /dev/null +++ b/gui/src/components/mainInput/tiptap/TipTapEditor.tsx @@ -0,0 +1,302 @@ +import { Editor, EditorContent, JSONContent } from "@tiptap/react"; +import { ContextProviderDescription, InputModifiers } from "core"; +import { modelSupportsImages } from "core/llm/autodetect"; +import { useCallback, useContext, useEffect, useRef, useState } from "react"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; +import useUpdatingRef from "../../../hooks/useUpdatingRef"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { + selectIsInEditMode, + setMainEditorContentTrigger, +} from "../../../redux/slices/sessionSlice"; +import InputToolbar, { ToolbarOptions } from "../InputToolbar"; +import { ComboBoxItem } from "../types"; +import { DragOverlay } from "./DragOverlay"; +import { createEditorConfig, getPlaceholderText } from "./editorConfig"; +import { handleImageFile } from "./imageUtils"; +import { useEditorEventHandlers } from "./keyHandlers"; +import { InputBoxDiv } from "./StyledComponents"; +import "./TipTapEditor.css"; +import { useWebviewListeners } from "./useWebviewListeners"; + +export interface TipTapEditorProps { + availableContextProviders: ContextProviderDescription[]; + availableSlashCommands: ComboBoxItem[]; + isMainInput: boolean; + onEnter: ( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) => void; + editorState?: JSONContent; + toolbarOptions?: ToolbarOptions; + lumpOpen: boolean; + setLumpOpen: (open: boolean) => void; + placeholder?: string; + historyKey: string; + inputId: string; +} + +export const TIPPY_DIV_ID = "tippy-js-div"; + +function TipTapEditor(props: TipTapEditorProps) { + const dispatch = useAppDispatch(); + + const ideMessenger = useContext(IdeMessengerContext); + + const isOSREnabled = useIsOSREnabled(); + + const defaultModel = useAppSelector(selectDefaultModel); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const isInEditMode = useAppSelector(selectIsInEditMode); + const historyLength = useAppSelector((store) => store.session.history.length); + + const { editor, onEnterRef } = createEditorConfig({ + props, + ideMessenger, + dispatch, + }); + + const [shouldHideToolbar, setShouldHideToolbar] = useState(true); + + useEffect(() => { + if (!editor) { + return; + } + const placeholder = getPlaceholderText(props.placeholder, historyLength); + + editor.extensionManager.extensions.filter( + (extension) => extension.name === "placeholder", + )[0].options["placeholder"] = placeholder; + + editor.view.dispatch(editor.state.tr); + }, [editor, props.placeholder, historyLength]); + + useEffect(() => { + if (isInEditMode) { + setShouldHideToolbar(false); + } + if (props.isMainInput) { + editor?.commands.clearContent(true); + } + }, [editor, isInEditMode, props.isMainInput]); + + const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); + + useEffect(() => { + if (props.isMainInput) { + /** + * I have a strong suspicion that many of the other focus + * commands are redundant, especially the ones inside + * useTimeout. + */ + editor?.commands.focus(); + } + }, [props.isMainInput, editor]); + + // Re-focus main input after done generating + useEffect(() => { + if (editor && !isStreaming && props.isMainInput && document.hasFocus()) { + editor.commands.focus(undefined, { scrollIntoView: false }); + } + }, [props.isMainInput, isStreaming, editor]); + + // This allows anywhere in the app to set the content of the main input + const mainInputContentTrigger = useAppSelector( + (store) => store.session.mainEditorContentTrigger, + ); + useEffect(() => { + if (!props.isMainInput || !mainInputContentTrigger) { + return; + } + queueMicrotask(() => { + editor?.commands.setContent(mainInputContentTrigger); + }); + dispatch(setMainEditorContentTrigger(undefined)); + }, [editor, props.isMainInput, mainInputContentTrigger]); + + // IDE event listeners + useWebviewListeners({ + editor, + onEnterRef, + dispatch, + historyLength, + props, + editorFocusedRef, + }); + + const [showDragOverMsg, setShowDragOverMsg] = useState(false); + + const [activeKey, setActiveKey] = useState(null); + + const insertCharacterWithWhitespace = useCallback( + (char: string) => { + if (!editor) { + return; + } + const text = editor.getText(); + if (!text.endsWith(char)) { + if (text.length > 0 && !text.endsWith(" ")) { + editor.commands.insertContent(` ${char}`); + } else { + editor.commands.insertContent(char); + } + } + }, + [editor], + ); + + const { handleKeyUp, handleKeyDown } = useEditorEventHandlers({ + editor, + isOSREnabled: isOSREnabled, + editorFocusedRef, + isInEditMode, + setActiveKey, + }); + + const blurTimeout = useRef(null); + const cancelBlurTimeout = useCallback(() => { + if (blurTimeout.current) { + clearTimeout(blurTimeout.current); + blurTimeout.current = null; + } + }, [blurTimeout]); + + const handleBlur = useCallback( + (e: React.FocusEvent) => { + if (isInEditMode) { + return; + } + // Check if the new focus target is within our InputBoxDiv + const currentTarget = e.currentTarget; + const relatedTarget = e.relatedTarget as Node | null; + + if (relatedTarget && currentTarget?.contains(relatedTarget)) { + return; + } + // Otherwise give e.g. listboxes a chance to cancel the hiding + blurTimeout.current = setTimeout(() => { + setShouldHideToolbar(true); + }, 100); + }, + [isInEditMode, blurTimeout], + ); + + const handleFocus = useCallback(() => { + cancelBlurTimeout(); + setShouldHideToolbar(false); + }, [cancelBlurTimeout]); + + // TODO pass clear blur timeout to model and mode selectors + // Seems like unnecessary for now? + + return ( + { + editor?.commands.focus(); + }} + onDragOver={(event) => { + event.preventDefault(); + setShowDragOverMsg(true); + }} + onDragLeave={(e) => { + if (e.relatedTarget === null) { + if (e.shiftKey) { + setShowDragOverMsg(false); + } else { + setTimeout(() => setShowDragOverMsg(false), 2000); + } + } + }} + onDragEnter={() => { + setShowDragOverMsg(true); + }} + onDrop={(event) => { + if ( + !defaultModel || + !modelSupportsImages( + defaultModel.provider, + defaultModel.model, + defaultModel.title, + defaultModel.capabilities, + ) + ) { + return; + } + setShowDragOverMsg(false); + let file = event.dataTransfer.files[0]; + handleImageFile(ideMessenger, file).then((result) => { + if (!editor) { + return; + } + if (result) { + const [_, dataUrl] = result; + const { schema } = editor.state; + const node = schema.nodes.image.create({ src: dataUrl }); + const tr = editor.state.tr.insert(0, node); + editor.view.dispatch(tr); + } + }); + event.preventDefault(); + }} + > +
+ { + event.stopPropagation(); + }} + /> +
+ + {showDragOverMsg && + modelSupportsImages( + defaultModel?.provider || "", + defaultModel?.model || "", + defaultModel?.title, + defaultModel?.capabilities, + ) && ( + + )} +
+ + ); +} + +export default TipTapEditor; diff --git a/gui/src/components/mainInput/tiptap/editorConfig.ts b/gui/src/components/mainInput/tiptap/editorConfig.ts new file mode 100644 index 000000000..d79981d39 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/editorConfig.ts @@ -0,0 +1,409 @@ +import { Editor } from "@tiptap/core"; +import Document from "@tiptap/extension-document"; +import History from "@tiptap/extension-history"; +import Image from "@tiptap/extension-image"; +import Paragraph from "@tiptap/extension-paragraph"; +import Placeholder from "@tiptap/extension-placeholder"; +import Text from "@tiptap/extension-text"; +import { Plugin } from "@tiptap/pm/state"; +import { useEditor } from "@tiptap/react"; +import { InputModifiers } from "core"; +import { modelSupportsImages } from "core/llm/autodetect"; +import { usePostHog } from "posthog-js/react"; +import { useRef } from "react"; +import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders"; +import { useInputHistory } from "../../../hooks/useInputHistory"; +import useUpdatingRef from "../../../hooks/useUpdatingRef"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectUseActiveFile } from "../../../redux/selectors"; +import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { + addCodeToEdit, + selectHasCodeToEdit, + selectIsInEditMode, +} from "../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../redux/store"; +import { exitEditMode } from "../../../redux/thunks"; +import { loadLastSession } from "../../../redux/thunks/session"; +import { getFontSize } from "../../../util"; +import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; +import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; +import { SlashCommand } from "./extensions/CommandsExtension"; +import { MockExtension } from "./extensions/FillerExtension"; +import { Mention } from "./extensions/MentionExtension"; +import { + getContextProviderDropdownOptions, + getSlashCommandDropdownOptions, +} from "./getSuggestion"; +import { handleImageFile } from "./imageUtils"; +import { TipTapEditorProps } from "./TipTapEditor"; + +export function getPlaceholderText( + placeholder: TipTapEditorProps["placeholder"], + historyLength: number, +) { + if (placeholder) { + return placeholder; + } + + return historyLength === 0 + ? "Ask anything, '/' for prompts, '@' to add context" + : "Ask a follow-up"; +} + +/** + * This function is called only once, so we need to use refs to pass in the latest values + */ +export function createEditorConfig(options: { + props: TipTapEditorProps; + ideMessenger: IIdeMessenger; + dispatch: AppDispatch; +}) { + const { props, ideMessenger, dispatch } = options; + + const posthog = usePostHog(); + + // #region Selectors + const { getSubmenuContextItems } = useSubmenuContextProviders(); + const defaultModel = useAppSelector(selectDefaultModel); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const useActiveFile = useAppSelector(selectUseActiveFile); + const historyLength = useAppSelector((store) => store.session.history.length); + const isInEditMode = useAppSelector(selectIsInEditMode); + const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); + const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + // #endregion + + // #region Refs + const inSubmenuRef = useRef(undefined); + const inDropdownRef = useRef(false); + const defaultModelRef = useUpdatingRef(defaultModel); + const isStreamingRef = useUpdatingRef(isStreaming); + const isInEditModeRef = useUpdatingRef(isInEditMode); + const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); + const availableContextProvidersRef = useUpdatingRef( + props.availableContextProviders, + ); + const historyLengthRef = useUpdatingRef(historyLength); + const availableSlashCommandsRef = useUpdatingRef( + props.availableSlashCommands, + ); + const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); + + // #endregion + + const enterSubmenu = async (editor: Editor, providerId: string) => { + const contents = editor.getText(); + const indexOfAt = contents.lastIndexOf("@"); + if (indexOfAt === -1) { + return; + } + + // Find the position of the last @ character + // We do this because editor.getText() isn't a correct representation including node views + let startPos = editor.state.selection.anchor; + while ( + startPos > 0 && + editor.state.doc.textBetween(startPos, startPos + 1) !== "@" + ) { + startPos--; + } + startPos++; + + editor.commands.deleteRange({ + from: startPos, + to: editor.state.selection.anchor, + }); + inSubmenuRef.current = providerId; + + // to trigger refresh of suggestions + editor.commands.insertContent(":"); + editor.commands.deleteRange({ + from: editor.state.selection.anchor - 1, + to: editor.state.selection.anchor, + }); + }; + + const onClose = () => { + inSubmenuRef.current = undefined; + inDropdownRef.current = false; + }; + + const onOpen = () => { + inDropdownRef.current = true; + }; + + const editor: Editor | null = useEditor({ + extensions: [ + Document, + History, + Image.extend({ + addProseMirrorPlugins() { + const plugin = new Plugin({ + props: { + handleDOMEvents: { + paste(view, event) { + const model = defaultModelRef.current; + if (!model) return; + const items = event.clipboardData?.items; + if (items) { + for (const item of items) { + const file = item.getAsFile(); + file && + modelSupportsImages( + model.provider, + model.model, + model.title, + model.capabilities, + ) && + handleImageFile(ideMessenger, file).then((resp) => { + if (!resp) return; + const [img, dataUrl] = resp; + const { schema } = view.state; + const node = schema.nodes.image.create({ + src: dataUrl, + }); + const tr = view.state.tr.insert(0, node); + view.dispatch(tr); + }); + } + } + }, + }, + }, + }); + return [plugin]; + }, + }).configure({ + HTMLAttributes: { + class: "object-contain max-h-[210px] max-w-full mx-1", + }, + }), + Placeholder.configure({ + placeholder: getPlaceholderText( + props.placeholder, + historyLengthRef.current, + ), + }), + Paragraph.extend({ + addKeyboardShortcuts() { + return { + Enter: () => { + if (inDropdownRef.current) { + return false; + } + + onEnterRef.current({ + useCodebase: false, + noContext: !useActiveFile, + }); + return true; + }, + + "Mod-Enter": () => { + onEnterRef.current({ + useCodebase: true, + noContext: !useActiveFile, + }); + return true; + }, + "Alt-Enter": () => { + posthog.capture("gui_use_active_file_enter"); + + onEnterRef.current({ + useCodebase: false, + noContext: !!useActiveFile, + }); + + return true; + }, + "Mod-Backspace": () => { + // If you press cmd+backspace wanting to cancel, + // but are inside of a text box, it shouldn't + // delete the text + if (isStreamingRef.current) { + return true; + } + return false; + }, + "Shift-Enter": () => + this.editor.commands.first(({ commands }) => [ + () => commands.newlineInCode(), + () => commands.createParagraphNear(), + () => commands.liftEmptyBlock(), + () => commands.splitBlock(), + ]), + + ArrowUp: () => { + if (this.editor.state.selection.anchor > 1) { + return false; + } + + const previousInput = prevRef.current( + this.editor.state.toJSON().doc, + ); + if (previousInput) { + this.editor.commands.setContent(previousInput); + setTimeout(() => { + this.editor.commands.blur(); + this.editor.commands.focus("start"); + }, 0); + return true; + } + return false; + }, + Escape: () => { + if (inDropdownRef.current || !isInEditModeRef.current) { + ideMessenger.post("focusEditor", undefined); + return true; + } + (async () => { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + dispatch(exitEditMode()); + })(); + + return true; + }, + ArrowDown: () => { + if ( + this.editor.state.selection.anchor < + this.editor.state.doc.content.size - 1 + ) { + return false; + } + const nextInput = nextRef.current(); + if (nextInput) { + this.editor.commands.setContent(nextInput); + setTimeout(() => { + this.editor.commands.blur(); + this.editor.commands.focus("end"); + }, 0); + return true; + } + return false; + }, + }; + }, + }).configure({ + HTMLAttributes: { + class: "my-1", + }, + }), + Text, + Mention.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }), + + AddCodeToEdit.configure({ + HTMLAttributes: { + class: "add-code-to-edit", + }, + suggestion: { + ...getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + allow: () => isInEditModeRef.current, + command: async ({ editor, range, props }) => { + editor.chain().focus().insertContentAt(range, "").run(); + const filepath = props.id; + const contents = await ideMessenger.ide.readFile(filepath); + dispatch( + addCodeToEdit({ + filepath, + contents, + }), + ); + }, + items: async ({ query }) => { + // Only display files in the dropdown + const results = getSubmenuContextItemsRef.current("file", query); + return results.map((result) => ({ + ...result, + label: result.title, + type: "file", + query: result.id, + icon: result.icon, + })); + }, + }, + }), + props.availableSlashCommands.length + ? SlashCommand.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) + : MockExtension, + CodeBlockExtension, + ], + editorProps: { + attributes: { + class: "outline-none -mt-1 overflow-hidden", + style: `font-size: ${getFontSize()}px;`, + }, + }, + content: props.editorState, + editable: !isStreaming || props.isMainInput, + }); + + const onEnterRef = useUpdatingRef( + (modifiers: InputModifiers) => { + if (!editor) { + return; + } + if (isStreaming || isEditModeAndNoCodeToEdit) { + return; + } + + const json = editor.getJSON(); + + // Don't do anything if input box is empty + if (!json.content?.some((c) => c.content)) { + return; + } + + if (props.isMainInput) { + addRef.current(json); + } + + props.onEnter(json, modifiers, editor); + }, + [props.onEnter, editor, props.isMainInput], + ); + + return { editor, onEnterRef }; +} diff --git a/gui/src/components/mainInput/AddCodeToEditExtension.ts b/gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts similarity index 100% rename from gui/src/components/mainInput/AddCodeToEditExtension.ts rename to gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts diff --git a/gui/src/components/mainInput/CodeBlockExtension.tsx b/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx similarity index 91% rename from gui/src/components/mainInput/CodeBlockExtension.tsx rename to gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx index 091694db9..aea6e18af 100644 --- a/gui/src/components/mainInput/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx @@ -1,6 +1,6 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeBlockComponent } from "./CodeBlockComponent"; +import { CodeBlockComponent } from "../CodeBlockComponent"; export const CodeBlockExtension = Node.create({ name: "codeBlock", diff --git a/gui/src/components/mainInput/CommandsExtension.ts b/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts similarity index 100% rename from gui/src/components/mainInput/CommandsExtension.ts rename to gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts diff --git a/gui/src/components/mainInput/FillerExtension.tsx b/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx similarity index 100% rename from gui/src/components/mainInput/FillerExtension.tsx rename to gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx diff --git a/gui/src/components/mainInput/MentionExtension.ts b/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts similarity index 100% rename from gui/src/components/mainInput/MentionExtension.ts rename to gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/tiptap/getSuggestion.ts similarity index 84% rename from gui/src/components/mainInput/getSuggestion.ts rename to gui/src/components/mainInput/tiptap/getSuggestion.ts index ecc7b835e..264258dd5 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/tiptap/getSuggestion.ts @@ -6,9 +6,9 @@ import { } from "core"; import { MutableRefObject } from "react"; import tippy from "tippy.js"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import MentionList from "./MentionList"; -import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "./types"; +import { IIdeMessenger } from "../../../context/IdeMessenger"; +import AtMentionDropdown from "../AtMentionDropdown"; +import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../types"; import { TIPPY_DIV_ID } from "./TipTapEditor"; function getSuggestion( @@ -32,7 +32,7 @@ function getSuggestion( return { onStart: (props: any) => { - component = new ReactRenderer(MentionList, { + component = new ReactRenderer(AtMentionDropdown, { props: { ...props, enterSubmenu, onClose: onExit }, editor: props.editor, }); @@ -95,7 +95,7 @@ function getSubActionsForSubmenuItem( item: ContextSubmenuItem & { providerTitle: string }, ideMessenger: IIdeMessenger, ): ComboBoxSubAction[] | undefined { - if (item.providerTitle === "docs" && !item.metadata?.preIndexed) { + if (item.providerTitle === "docs") { return [ { label: "Open in new tab", @@ -198,27 +198,18 @@ export function getSlashCommandDropdownOptions( ideMessenger: IIdeMessenger, ) { const items = async ({ query }: { query: string }) => { - const options = [ - ...availableSlashCommandsRef.current, - // { - // title: "Build a custom prompt", - // description: "Build a custom prompt", - // type: "action", - // id: "createPromptFile", - // label: "Create Prompt File", - // action: () => { - // ideMessenger.post("config/newPromptFile", undefined); - // }, - // name: "Create Prompt File", - // }, - ]; - return ( - options.filter((slashCommand) => { - const sc = slashCommand.title.substring(1).toLowerCase(); - const iv = query.toLowerCase(); - return sc.startsWith(iv); - }) || [] - ).map((provider) => ({ + const options = [...availableSlashCommandsRef.current]; + + const filteredCommands = + query.length > 0 + ? options.filter((slashCommand) => { + const sc = slashCommand.title.substring(1).toLowerCase(); + const iv = query.toLowerCase(); + return sc.startsWith(iv); + }) + : options; + + const commandItems = (filteredCommands || []).map((provider) => ({ name: provider.title, description: provider.description, id: provider.title, @@ -227,6 +218,24 @@ export function getSlashCommandDropdownOptions( type: (provider.type ?? "slashCommand") as ComboBoxItemType, action: provider.action, })); + + if (query.length === 0 && commandItems.length > 0) { + commandItems.push({ + title: "Explore prompts", + type: "action", + action: () => + ideMessenger.post( + "openUrl", + "https://hub.continue.dev/explore/prompts", + ), + description: "", + name: "", + id: "", + label: "", + }); + } + + return commandItems; }; return getSuggestion(items, undefined, onClose, onOpen); } diff --git a/gui/src/components/mainInput/tiptap/imageUtils.ts b/gui/src/components/mainInput/tiptap/imageUtils.ts new file mode 100644 index 000000000..0803e5ab8 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/imageUtils.ts @@ -0,0 +1,73 @@ +import { IIdeMessenger } from "../../../context/IdeMessenger"; + +const IMAGE_RESOLUTION = 1024; + +export function getDataUrlForFile( + file: File, + img: HTMLImageElement, +): string | undefined { + const targetWidth = IMAGE_RESOLUTION; + const targetHeight = IMAGE_RESOLUTION; + const scaleFactor = Math.min( + targetWidth / img.width, + targetHeight / img.height, + ); + + const canvas = document.createElement("canvas"); + canvas.width = img.width * scaleFactor; + canvas.height = img.height * scaleFactor; + + const ctx = canvas.getContext("2d"); + if (!ctx) { + console.error("Error getting image data url: 2d context not found"); + return; + } + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + + const downsizedDataUrl = canvas.toDataURL("image/jpeg", 0.7); + return downsizedDataUrl; +} + +export async function handleImageFile( + ideMessenger: IIdeMessenger, + file: File, +): Promise<[HTMLImageElement, string] | undefined> { + let filesize = file.size / 1024 / 1024; // filesize in MB + // check image type and size + if ( + [ + "image/jpeg", + "image/jpg", + "image/png", + "image/gif", + "image/svg", + "image/webp", + ].includes(file.type) && + filesize < 10 + ) { + // check dimensions + let _URL = window.URL || window.webkitURL; + let img = new window.Image(); + img.src = _URL.createObjectURL(file); + + return await new Promise((resolve) => { + img.onload = function () { + const dataUrl = getDataUrlForFile(file, img); + if (!dataUrl) { + return; + } + + let image = new window.Image(); + image.src = dataUrl; + image.onload = function () { + resolve([image, dataUrl]); + }; + }; + }); + } else { + ideMessenger.post("showToast", [ + "error", + "Images need to be in jpg or png format and less than 10MB in size.", + ]); + } +} diff --git a/gui/src/components/mainInput/tiptap/keyHandlers.ts b/gui/src/components/mainInput/tiptap/keyHandlers.ts new file mode 100644 index 000000000..c25a53271 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/keyHandlers.ts @@ -0,0 +1,50 @@ +import { Editor } from "@tiptap/react"; +import { KeyboardEvent } from "react"; +import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util"; +import { + handleJetBrainsOSRMetaKeyIssues, + handleVSCMetaKeyIssues, +} from "../util/handleMetaKeyIssues"; + +export function useEditorEventHandlers(options: { + editor: Editor | null; + isOSREnabled: boolean; + editorFocusedRef: React.MutableRefObject; + isInEditMode: boolean; + setActiveKey: (key: string | null) => void; +}) { + const { editor, isOSREnabled, editorFocusedRef, isInEditMode, setActiveKey } = + options; + + /** + * This handles various issues with meta key actions + * - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to + * highlight code using arrow keys is not working + * - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect + * the actual notebook cells, even when performing them in our GUI + * + * Currently keydown events for a number of keys are not registering if the + * meta/shift key is pressed, for example "x", "c", "v", "z", etc. + * Until this is resolved we can't turn on OSR for non-Mac users due to issues + * with those key actions. + */ + const handleKeyDown = async (e: KeyboardEvent) => { + if (!editor) { + return; + } + + setActiveKey(e.key); + + if (!editorFocusedRef?.current || !isMetaEquivalentKeyPressed(e)) return; + + if (isOSREnabled) { + handleJetBrainsOSRMetaKeyIssues(e, editor); + } else if (!isJetBrains()) { + await handleVSCMetaKeyIssues(e, editor); + } + }; + + const handleKeyUp = () => setActiveKey(null); + + return { handleKeyDown, handleKeyUp }; +} diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts similarity index 98% rename from gui/src/components/mainInput/resolveInput.ts rename to gui/src/components/mainInput/tiptap/resolveInput.ts index 1113d2fc3..d9eb47b6c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/tiptap/resolveInput.ts @@ -1,3 +1,4 @@ +import { Dispatch } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/react"; import { ContextItemWithId, @@ -8,12 +9,11 @@ import { RangeInFile, TextMessagePart, } from "core"; -import { stripImages } from "core/util/messageContent"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import { Dispatch } from "@reduxjs/toolkit"; -import { setIsGatheringContext } from "../../redux/slices/sessionSlice"; import { ctxItemToRifWithContents } from "core/commands/util"; +import { stripImages } from "core/util/messageContent"; import { getUriFileExtension } from "core/util/uri"; +import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { setIsGatheringContext } from "../../../redux/slices/sessionSlice"; interface MentionAttrs { label: string; diff --git a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts b/gui/src/components/mainInput/tiptap/useWebviewListeners.ts new file mode 100644 index 000000000..3a4694939 --- /dev/null +++ b/gui/src/components/mainInput/tiptap/useWebviewListeners.ts @@ -0,0 +1,211 @@ +import { Editor } from "@tiptap/core"; +import { InputModifiers } from "core"; +import { rifWithContentsToContextItem } from "core/commands/util"; +import { MutableRefObject } from "react"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { + clearCodeToEdit, + setNewestCodeblocksForInput, +} from "../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../redux/store"; +import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; +import { TipTapEditorProps } from "./TipTapEditor"; + +export function useWebviewListeners(options: { + editor: Editor | null; + onEnterRef: MutableRefObject<(modifiers: InputModifiers) => void>; + dispatch: AppDispatch; + historyLength: number; + props: TipTapEditorProps; + editorFocusedRef: MutableRefObject; +}) { + const { + editor, + onEnterRef, + dispatch, + historyLength, + props, + editorFocusedRef, + } = options; + + useWebviewListener( + "userInput", + async (data) => { + if (!props.isMainInput) { + return; + } + editor?.commands.insertContent(data.input); + onEnterRef.current({ useCodebase: false, noContext: true }); + }, + [editor, onEnterRef.current, props.isMainInput], + ); + + useWebviewListener("jetbrains/editorInsetRefresh", async () => { + editor?.chain().clearContent().focus().run(); + }); + + useWebviewListener( + "focusContinueInput", + async (data) => { + if (!props.isMainInput) { + return; + } + + dispatch(clearCodeToEdit()); + + if (historyLength > 0) { + await dispatch( + saveCurrentSession({ + openNewSession: false, + generateTitle: true, + }), + ); + } + setTimeout(() => { + editor?.commands.blur(); + editor?.commands.focus("end"); + }, 20); + }, + [historyLength, editor, props.isMainInput], + ); + + useWebviewListener( + "focusContinueInputWithoutClear", + async () => { + if (!props.isMainInput) { + return; + } + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "focusContinueInputWithNewSession", + async () => { + if (!props.isMainInput) { + return; + } + await dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: true, + }), + ); + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "highlightedCode", + async (data) => { + if (!props.isMainInput || !editor) { + return; + } + + const contextItem = rifWithContentsToContextItem( + data.rangeInFileWithContents, + ); + + let index = 0; + for (const el of editor.getJSON()?.content ?? []) { + if (el.attrs?.item?.name === contextItem.name) { + return; // Prevent exact duplicate code blocks + } + if (el.type === "codeBlock") { + index += 2; + } else { + break; + } + } + editor + .chain() + .insertContentAt(index, { + type: "codeBlock", + attrs: { + item: contextItem, + inputId: props.inputId, + }, + }) + .run(); + dispatch( + setNewestCodeblocksForInput({ + inputId: props.inputId, + contextItemId: contextItem.id.itemId, + }), + ); + if (data.prompt) { + editor.commands.focus("end"); + editor.commands.insertContent(data.prompt); + } + + if (data.shouldRun) { + onEnterRef.current({ useCodebase: false, noContext: true }); + } + + setTimeout(() => { + editor.commands.blur(); + editor.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput, historyLength, onEnterRef.current], + ); + + useWebviewListener( + "focusEdit", + async () => { + if (!props.isMainInput) { + return; + } + + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "focusEditWithoutClear", + async () => { + if (!props.isMainInput) { + return; + } + + setTimeout(() => { + editor?.commands.focus("end"); + }, 2000); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "isContinueInputFocused", + async () => { + return props.isMainInput && !!editorFocusedRef.current; + }, + [editorFocusedRef, props.isMainInput], + !props.isMainInput, + ); + + useWebviewListener( + "focusContinueSessionId", + async (data) => { + if (!props.isMainInput || !data.sessionId) { + return; + } + await dispatch( + loadSession({ + sessionId: data.sessionId, + saveCurrentSession: true, + }), + ); + }, + [props.isMainInput], + ); +} diff --git a/gui/src/components/mainInput/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts similarity index 98% rename from gui/src/components/mainInput/handleMetaKeyIssues.ts rename to gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 1adf5593a..9f9078303 100644 --- a/gui/src/components/mainInput/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,6 +1,6 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; -import { getPlatform, isWebEnvironment } from "../../util"; +import { getPlatform, isWebEnvironment } from "../../../util"; const isWebEnv = isWebEnvironment(); diff --git a/gui/src/components/mainInput/inputModifiers.ts b/gui/src/components/mainInput/util/inputModifiers.ts similarity index 100% rename from gui/src/components/mainInput/inputModifiers.ts rename to gui/src/components/mainInput/util/inputModifiers.ts diff --git a/gui/src/components/mainInput/utils.ts b/gui/src/components/mainInput/utils.ts new file mode 100644 index 000000000..71565a429 --- /dev/null +++ b/gui/src/components/mainInput/utils.ts @@ -0,0 +1,18 @@ +import { JSONContent } from "@tiptap/core"; + +export function getParagraphNodeFromString(str: string): JSONContent { + return { + type: "doc", + content: [ + { + type: "paragraph", + content: [ + { + type: "text", + text: str, + }, + ], + }, + ], + }; +} diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 5cb33d939..85ece0990 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -1,22 +1,26 @@ -import { useContext, useRef, useState } from "react"; import { + ArrowLeftEndOnRectangleIcon, CommandLineIcon, PlayIcon, - ArrowLeftEndOnRectangleIcon, } from "@heroicons/react/24/outline"; -import { defaultBorderRadius, vscEditorBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { isJetBrains } from "../../util"; -import { isTerminalCodeBlock, getTerminalCommand } from "./utils"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { CopyIconButton } from "../gui/CopyIconButton"; +import { useContext, useRef, useState } from "react"; import { v4 as uuidv4 } from "uuid"; +import { + defaultBorderRadius, + vscCommandCenterInactiveBorder, + vscEditorBackground, +} from ".."; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppSelector } from "../../redux/hooks"; import { selectDefaultModel, selectUIConfig, } from "../../redux/slices/configSlice"; +import { isJetBrains } from "../../util"; +import { CopyIconButton } from "../gui/CopyIconButton"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { getTerminalCommand, isTerminalCodeBlock } from "./utils"; interface StepContainerPreActionButtonsProps { language: string | null; @@ -84,14 +88,20 @@ export default function StepContainerPreActionButtons({ tabIndex={-1} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)} - className="bg-vsc-editor-background border-vsc-input-border relative my-2.5 rounded-md border-[1px] border-solid" + className="bg-vsc-editor-background relative my-2.5" + style={{ + border: `1px solid ${vscCommandCenterInactiveBorder}`, + borderRadius: defaultBorderRadius, + }} >
{children}
{hovering && !isStreaming && (
{shouldRunTerminalCmd && ( diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 99e449cc7..46fa90d68 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -4,7 +4,11 @@ import { debounce } from "lodash"; import { useContext, useEffect, useRef, useState } from "react"; import styled from "styled-components"; import { v4 as uuidv4 } from "uuid"; -import { lightGray, vscEditorBackground } from "../.."; +import { + defaultBorderRadius, + vscCommandCenterInactiveBorder, + vscEditorBackground, +} from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; @@ -22,9 +26,9 @@ import GeneratingCodeLoader from "./GeneratingCodeLoader"; import RunInTerminalButton from "./RunInTerminalButton"; const TopDiv = styled.div` - outline: 0.5px solid rgba(153, 153, 152); + outline: 1px solid ${vscCommandCenterInactiveBorder}; outline-offset: -0.5px; - border-radius: 2.5px; + border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; background-color: ${vscEditorBackground}; min-width: 0; @@ -39,7 +43,7 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>` padding: 4px 6px; margin: 0; border-bottom: ${({ isExpanded }) => - isExpanded ? `0.5px solid ${lightGray}80` : "inherit"}; + isExpanded ? `1px solid ${vscCommandCenterInactiveBorder}` : "inherit"}; `; export interface StepContainerPreToolbarProps { @@ -225,7 +229,7 @@ export default function StepContainerPreToolbar( {isExpanded && (
{props.children} diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/modelSelection/ModeSelect.tsx new file mode 100644 index 000000000..0e14adfad --- /dev/null +++ b/gui/src/components/modelSelection/ModeSelect.tsx @@ -0,0 +1,168 @@ +// A dropdown menu for selecting between Chat, Edit, and Agent modes with keyboard shortcuts +import { + ChatBubbleLeftIcon, + CheckIcon, + ChevronDownIcon, + PencilIcon, + SparklesIcon, +} from "@heroicons/react/24/outline"; +import { MessageModes } from "core"; +import { modelSupportsTools } from "core/llm/autodetect"; +import { useEffect, useMemo } from "react"; +import styled from "styled-components"; +import { lightGray } from ".."; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { + cycleMode, + selectCurrentMode, + setMode, +} from "../../redux/slices/sessionSlice"; +import { exitEditMode } from "../../redux/thunks"; +import { + loadLastSession, + saveCurrentSession, +} from "../../redux/thunks/session"; +import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util"; +import { + Listbox, + ListboxButton, + ListboxOption, + ListboxOptions, +} from "../ui/Listbox"; + +const ShortcutText = styled.span` + color: ${lightGray}; + font-size: ${getFontSize() - 3}px; + margin-right: auto; +`; + +function ModeSelect() { + const dispatch = useAppDispatch(); + const mode = useAppSelector(selectCurrentMode); + const selectedModel = useAppSelector(selectDefaultModel); + const agentModeSupported = selectedModel && modelSupportsTools(selectedModel); + + const jetbrains = useMemo(() => { + return isJetBrains(); + }, []); + const metaKeyLabel = useMemo(() => { + return getMetaKeyLabel(); + }, []); + + const getModeIcon = (mode: MessageModes) => { + switch (mode) { + case "agent": + return ; + case "chat": + return ; + case "edit": + return ; + } + }; + + // Switch to chat mode if agent mode is selected but not supported + useEffect(() => { + if (!selectedModel) { + return; + } + if (mode === "agent" && !agentModeSupported) { + dispatch(setMode("chat")); + } + }, [mode, agentModeSupported, dispatch, selectedModel]); + + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === "." && (e.metaKey || e.ctrlKey)) { + e.preventDefault(); + dispatch(cycleMode({ isJetBrains: jetbrains })); + } + }; + + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); + }, [dispatch, mode, jetbrains]); + + return ( + { + if (newMode === mode) { + return; + } + dispatch(setMode(newMode)); + if (newMode === "edit") { + await dispatch( + saveCurrentSession({ + generateTitle: false, + openNewSession: true, + }), + ); + } else if (mode === "edit") { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + dispatch(exitEditMode()); + } + }} + > +
+ + {getModeIcon(mode)} + + {mode.charAt(0).toUpperCase() + mode.slice(1)} + + + + +
+ + Agent +
+ {mode === "agent" && } + {!agentModeSupported && (Not supported)} +
+ + +
+ + Chat + {getMetaKeyLabel()}L +
+ {mode === "chat" && } +
+ + {!jetbrains && ( + +
+ + Edit + {getMetaKeyLabel()}I +
+ {mode === "edit" && } +
+ )} + +
+ {metaKeyLabel}. for next mode +
+
+
+
+ ); +} + +export default ModeSelect; diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 3bda3b95e..4c2e31387 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -1,16 +1,14 @@ -import { Listbox } from "@headlessui/react"; import { + CheckIcon, ChevronDownIcon, Cog6ToothIcon, CubeIcon, PlusIcon, - TrashIcon, - CheckIcon, } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscInputBackground } from ".."; +import { defaultBorderRadius, lightGray } from ".."; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; @@ -20,16 +18,13 @@ import { setDefaultModel, } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { getFontSize, isMetaEquivalentKeyPressed } from "../../util"; -import ConfirmationDialog from "../dialogs/ConfirmationDialog"; -import Shortcut from "../gui/Shortcut"; -import { Divider } from "./platform/shared"; +import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; +import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; interface ModelOptionProps { option: Option; idx: number; showMissingApiKeyMsg: boolean; - showDelete?: boolean; isSelected?: boolean; } @@ -39,67 +34,6 @@ interface Option { apiKey?: string; } -const MAX_HEIGHT_PX = 300; - -const StyledListboxButton = styled(Listbox.Button)` - font-family: inherit; - display: flex; - align-items: center; - gap: 2px; - border: none; - cursor: pointer; - font-size: ${getFontSize() - 2}px; - background: transparent; - color: ${lightGray}; - &:focus { - outline: none; - } -`; - -const StyledListboxOptions = styled(Listbox.Options)<{ $showabove: boolean }>` - margin-top: 4px; - position: absolute; - list-style: none; - padding: 0px; - white-space: nowrap; - cursor: default; - - display: flex; - flex-direction: column; - - border-radius: ${defaultBorderRadius}; - border: 0.5px solid ${lightGray}; - background-color: ${vscInputBackground}; - - max-height: ${MAX_HEIGHT_PX}px; - overflow-y: scroll; - - scrollbar-width: none; - - ${(props) => (props.$showabove ? "bottom: 100%;" : "top: 100%;")} -`; - -const StyledListboxOption = styled(Listbox.Option)<{ isDisabled?: boolean }>` - border-radius: ${defaultBorderRadius}; - padding: 6px 12px; - - ${({ isDisabled }) => - !isDisabled && - ` - cursor: pointer; - - &:hover { - background: ${lightGray}33; - } - `} - - ${({ isDisabled }) => - isDisabled && - ` - opacity: 0.5; - `} -`; - const IconBase = styled.div<{ $hovered: boolean }>` width: 1.2em; height: 1.2em; @@ -115,9 +49,6 @@ const IconBase = styled.div<{ $hovered: boolean }>` } `; -const StyledTrashIcon = styled(IconBase).attrs({ as: TrashIcon })``; -const StyledCog6ToothIcon = styled(IconBase).attrs({ as: Cog6ToothIcon })``; - function modelSelectTitle(model: any): string { if (model?.title) return model?.title; if (model?.model !== undefined && model?.model.trim() !== "") { @@ -132,35 +63,13 @@ function modelSelectTitle(model: any): string { function ModelOption({ option, idx, - showDelete, showMissingApiKeyMsg, isSelected, }: ModelOptionProps) { const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useDispatch(); const [hovered, setHovered] = useState(false); - function onClickDelete(e: any) { - e.stopPropagation(); - e.preventDefault(); - - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - { - ideMessenger.post("config/deleteModel", { - title: option.title, - }); - }} - />, - ), - ); - } - function onClickGear(e: any) { e.stopPropagation(); e.preventDefault(); @@ -176,19 +85,19 @@ function ModelOption({ } return ( - setHovered(true)} onMouseLeave={() => setHovered(false)} onClick={handleOptionClick} > -
-
-
- - +
+
+
+ + {option.title} {showMissingApiKeyMsg && ( @@ -197,18 +106,18 @@ function ModelOption({ )}
-
- - {showDelete && ( - - )} - {isSelected && ( - +
+ {isSelected && } + {hovered && ( + )}
- + ); } @@ -216,8 +125,6 @@ function ModelSelect() { const dispatch = useDispatch(); const defaultModel = useAppSelector(selectDefaultModel); const allModels = useAppSelector((state) => state.config.config.models); - const ideMessenger = useContext(IdeMessengerContext); - const [showAbove, setShowAbove] = useState(false); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -247,12 +154,6 @@ function ModelSelect() { ); }, [allModels]); - useEffect(() => { - const handleResize = () => calculatePosition(); - window.addEventListener("resize", handleResize); - return () => window.removeEventListener("resize", handleResize); - }, []); - useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { @@ -273,18 +174,6 @@ function ModelSelect() { }; }, [options, defaultModel]); - function calculatePosition() { - if (!buttonRef.current) { - return; - } - const rect = buttonRef.current.getBoundingClientRect(); - const spaceBelow = window.innerHeight - rect.bottom; - const spaceAbove = rect.top; - const dropdownHeight = MAX_HEIGHT_PX; - - setShowAbove(spaceBelow < dropdownHeight && spaceAbove > spaceBelow); - } - function onClickAddModel(e: MouseEvent) { e.stopPropagation(); e.preventDefault(); @@ -306,74 +195,61 @@ function ModelSelect() { } return ( + // Hiad sfasdfasdf asdfasdf { if (val === defaultModel?.title) return; dispatch(setDefaultModel({ title: val })); }} > -
- + -
- - {modelSelectTitle(defaultModel) || "Select model"}{" "} - -
-
- -
+ + {modelSelectTitle(defaultModel) || "Select model"} + +