diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index f629f9331..455a58428 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -10,6 +10,7 @@ on: - "core/**" - "gui/**" - ".github/workflows/**" + - "docs/**" push: branches: @@ -26,6 +27,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -45,6 +47,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -72,6 +75,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -97,10 +101,11 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [ install-root, install-core ] + needs: [install-root, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -132,6 +137,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -158,10 +164,11 @@ jobs: npx tsc --noEmit binary-checks: - needs: [ install-root, install-core ] + needs: [install-root, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -194,10 +201,11 @@ jobs: npx tsc --noEmit install-vscode: - needs: [ install-root, install-core ] + needs: [install-root, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -231,6 +239,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -262,6 +271,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -276,6 +286,7 @@ jobs: cd core npm test env: + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} @@ -283,7 +294,7 @@ jobs: vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [ install-root, install-vscode ] + needs: [install-root, install-vscode] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: @@ -312,9 +323,10 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [ install-vscode, install-core ] + needs: [install-vscode, install-core] steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -344,9 +356,10 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [ install-vscode, install-core ] + needs: [install-vscode, install-core] steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -386,13 +399,15 @@ jobs: install-core, ] runs-on: ubuntu-latest + # Tests requiring secrets need approval from maintainers strategy: fail-fast: false matrix: test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} - command: [ "e2e:ci:run", "e2e:ci:run-yaml" ] + command: ["e2e:ci:run", "e2e:ci:run-yaml"] steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -430,6 +445,7 @@ jobs: chmod 600 ~/.ssh/id_rsa ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config + if: ${{ github.event.pull_request.head.repo.fork == false }} - name: Set up Xvfb run: | @@ -439,7 +455,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 @@ -451,10 +467,11 @@ jobs: path: extensions/vscode/e2e/storage/screenshots gui-tests: - needs: [ install-gui, install-core ] + needs: [install-gui, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -482,11 +499,10 @@ jobs: npm test jetbrains-tests: - needs: [ install-root, core-checks ] + needs: [install-root, core-checks] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/cache@v4 with: path: core/node_modules @@ -578,4 +594,35 @@ jobs: with: name: jb-failure-report path: | - ${{ github.workspace }}/extensions/intellij/build/reports \ No newline at end of file + ${{ github.workspace }}/extensions/intellij/build/reports + + # GitHub does not have a way of requiring that all checks pass (you must manually select each job) + # This action at least lets us manage the list of required tests via source control + # so that creators of new jobs can add them to this list + require-all-checks-to-pass: + if: always() + runs-on: ubuntu-latest + needs: + - install-root + - install-core + - core-checks + - install-gui + - gui-checks + - binary-checks + - install-vscode + - vscode-checks + - core-tests + - vscode-get-test-file-matrix + - vscode-package-extension + - vscode-download-e2e-dependencies + - vscode-e2e-tests + - gui-tests + - jetbrains-tests + + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + allowed-failures: + allowed-skips: + jobs: ${{ toJSON(needs) }} diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..81efb94b6 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,16 @@ +# Security Policy + +## Reporting a Vulnerability + +If you discover a security vulnerability, please do not open a public issue. Instead, please report it by emailing security@continue.dev. We will be highly responsive to all security concerns and ask that you give us sufficient time to investigate and address the vulnerability before disclosing it publicly. + +Please include the following details in your report: + +- A description of the vulnerability +- Steps to reproduce the issue +- Your assessment of the potential impact +- Any possible mitigations + +## Contact + +For any other questions or concerns related to security, please contact us at security@continue.dev. diff --git a/binary/package-lock.json b/binary/package-lock.json index 316fddcd2..72c044f14 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.16", + "@continuedev/config-yaml": "^1.0.24", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index e90fbeb84..b92a8e6a2 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -75,7 +75,7 @@ class IPCMessengerBase< console.warn(`Error running handler for "${msg.messageType}": `, e); this._onErrorHandlers.forEach((handler) => { - handler(e); + handler(msg, e); }); } }); @@ -112,9 +112,9 @@ class IPCMessengerBase< lines.forEach((line) => this._handleLine(line)); } - private _onErrorHandlers: ((error: Error) => void)[] = []; + private _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; - onError(handler: (error: Error) => void) { + onError(handler: (message: Message, error: Error) => void) { this._onErrorHandlers.push(handler); } @@ -217,7 +217,7 @@ export class CoreBinaryMessenger< extends IPCMessengerBase implements IMessenger { - private errorHandler: (error: Error) => void = () => {}; + private errorHandler: (message: Message, error: Error) => void = () => {}; private messageHandlers: Map< keyof ToProtocol, (message: Message) => Promise | any diff --git a/binary/src/TcpMessenger.ts b/binary/src/TcpMessenger.ts index ad4713473..907e32ed7 100644 --- a/binary/src/TcpMessenger.ts +++ b/binary/src/TcpMessenger.ts @@ -41,9 +41,9 @@ export class TcpMessenger< }); } - private _onErrorHandlers: ((error: Error) => void)[] = []; + private _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; - onError(handler: (error: Error) => void) { + onError(handler: (message: Message, error: Error) => void) { this._onErrorHandlers.push(handler); } @@ -111,7 +111,7 @@ export class TcpMessenger< console.warn(`Error running handler for "${msg.messageType}": `, e); this._onErrorHandlers.forEach((handler) => { - handler(e); + handler(msg, e); }); } }); diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 77aadbdf5..32e8a4127 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -246,6 +246,7 @@ export class CompletionProvider { completionOptions, cacheHit, filepath: helper.filepath, + numLines: completion.split("\n").length, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 6bfc6cfe1..1bd90c503 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -76,7 +76,6 @@ export class StreamTransformPipeline { const timeoutValue = await Telemetry.getValueForFeatureFlag( PosthogFeatureFlag.AutocompleteTimeout, ); - // helper.options.showWhateverWeHaveAtXMs ?? DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!); diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index b6379dd61..3959bff9c 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -1,10 +1,4 @@ -import { - Position, - Range, - RangeInFile, - RangeInFileWithContents, - TabAutocompleteOptions, -} from "../.."; +import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../.."; import { AutocompleteCodeSnippet } from "../snippets/types"; export type RecentlyEditedRange = RangeInFile & { @@ -42,6 +36,7 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { modelName: string; completionOptions: any; cacheHit: boolean; + numLines: number; filepath: string; gitRepo?: string; completionId: string; diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 343bb9cfc..4ad045d30 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,9 +1,17 @@ import * as fs from "node:fs"; +import { + AssistantUnrolled, + ConfigResult, + FullSlug, +} from "@continuedev/config-yaml"; +import * as YAML from "yaml"; + import { ControlPlaneClient, ControlPlaneSessionInfo, } from "../control-plane/client.js"; +import { getControlPlaneEnv, useHub } from "../control-plane/env.js"; import { BrowserSerializedContinueConfig, ContinueConfig, @@ -15,11 +23,8 @@ import { import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; - -import { ConfigResult, ConfigYaml, FullSlug } from "@continuedev/config-yaml"; -import * as YAML from "yaml"; -import { getControlPlaneEnv, useHub } from "../control-plane/env.js"; import { localPathToUri } from "../util/pathToUri.js"; + import { LOCAL_ONBOARDING_CHAT_MODEL, ONBOARDING_LOCAL_MODEL_TITLE, @@ -44,6 +49,7 @@ export class ConfigHandler { private additionalContextProviders: IContextProvider[] = []; private profiles: ProfileLifecycleManager[]; private selectedProfileId: string; + private selectedOrgId: string | null; constructor( private readonly ide: IDE, @@ -64,6 +70,7 @@ export class ConfigHandler { ); this.profiles = [new ProfileLifecycleManager(localProfileLoader, this.ide)]; this.selectedProfileId = localProfileLoader.description.id; + this.selectedOrgId = null; // Always load local profile immediately in case control plane doesn't load try { @@ -72,6 +79,20 @@ export class ConfigHandler { console.error("Failed to load config: ", e); } + void this.init(); + } + + private async init() { + const workspaceId = await this.getWorkspaceId(); + const lastSelectedOrgIds = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + const selectedOrgId = lastSelectedOrgIds[workspaceId]; + + // We want to set the org ID before fetching control plane profiles + if (selectedOrgId) { + this.selectedOrgId = selectedOrgId; + } + // Load control plane profiles void this.fetchControlPlaneProfiles(); } @@ -114,11 +135,11 @@ export class ConfigHandler { private async loadPlatformProfiles() { // Get the profiles and create their lifecycle managers this.controlPlaneClient - .listAssistants() + .listAssistants(this.selectedOrgId) .then(async (assistants) => { const hubProfiles = await Promise.all( assistants.map(async (assistant) => { - let renderedConfig: ConfigYaml | undefined = undefined; + let renderedConfig: AssistantUnrolled | undefined = undefined; if (assistant.configResult.config) { renderedConfig = await clientRenderHelper( YAML.stringify(assistant.configResult.config), @@ -131,6 +152,7 @@ export class ConfigHandler { { ...assistant.configResult, config: renderedConfig }, assistant.ownerSlug, assistant.packageSlug, + assistant.iconUrl, assistant.configResult.config?.version ?? "latest", this.controlPlaneClient, this.ide, @@ -158,6 +180,7 @@ export class ConfigHandler { const workspaceId = await this.getWorkspaceId(); const lastSelectedWorkspaceIds = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId]; if (selectedWorkspaceId) { this.selectedProfileId = selectedWorkspaceId; @@ -207,7 +230,9 @@ export class ConfigHandler { // If so, we do the full (more expensive) reload this.platformProfilesRefreshInterval = setInterval(async () => { const newFullSlugsList = - await this.controlPlaneClient.listAssistantFullSlugs(); + await this.controlPlaneClient.listAssistantFullSlugs( + this.selectedOrgId, + ); if (newFullSlugsList) { const shouldReload = this.fullSlugsListsDiffer( @@ -269,6 +294,14 @@ export class ConfigHandler { } } + async setSelectedOrgId(orgId: string | null) { + this.selectedOrgId = orgId; + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + selectedOrgs[await this.getWorkspaceId()] = orgId; + this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + } + async setSelectedProfile(profileId: string) { this.selectedProfileId = profileId; const result = await this.loadConfig(); @@ -332,11 +365,11 @@ export class ConfigHandler { this.updateListeners.push(listener); } - async reloadConfig() { + async reloadConfig(additionalContextProviders: IContextProvider[] = []) { // TODO: this isn't right, there are two different senses in which you want to "reload" const { config, errors, configLoadInterrupted } = - await this.currentProfile.reloadConfig(); + await this.currentProfile.reloadConfig(additionalContextProviders); if (config) { this.inactiveProfiles.forEach((profile) => profile.clearConfig()); @@ -386,6 +419,6 @@ export class ConfigHandler { registerCustomContextProvider(contextProvider: IContextProvider) { this.additionalContextProviders.push(contextProvider); - void this.reloadConfig(); + void this.reloadConfig(this.additionalContextProviders); } } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index fa76c6b55..9fc3dc960 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -3,6 +3,7 @@ import { ConfigValidationError, FullSlug, } from "@continuedev/config-yaml"; + import { BrowserSerializedContinueConfig, ContinueConfig, @@ -18,9 +19,16 @@ export interface ProfileDescription { profileType: "control-plane" | "local" | "platform"; title: string; id: string; + iconUrl: string; errors: ConfigValidationError[] | undefined; } +export interface OrganizationDescription { + id: string; + iconUrl: string; + name: string; +} + export class ProfileLifecycleManager { private savedConfigResult: ConfigResult | undefined; private savedBrowserConfigResult?: ConfigResult; @@ -42,12 +50,14 @@ export class ProfileLifecycleManager { } // Clear saved config and reload - async reloadConfig(): Promise> { + async reloadConfig( + additionalContextProviders: IContextProvider[] = [], + ): Promise> { this.savedConfigResult = undefined; this.savedBrowserConfigResult = undefined; this.pendingConfigPromise = undefined; - return this.loadConfig([], true); + return this.loadConfig(additionalContextProviders, true); } async loadConfig( @@ -65,7 +75,21 @@ export class ProfileLifecycleManager { // Set pending config promise this.pendingConfigPromise = new Promise(async (resolve, reject) => { - const result = await this.profileLoader.doLoadConfig(); + let result: ConfigResult; + try { + result = await this.profileLoader.doLoadConfig(); + } catch (e: any) { + result = { + errors: [ + { + fatal: true, + message: e.message, + }, + ], + config: undefined, + configLoadInterrupted: true, + }; + } if (result.config) { // Add registered context providers diff --git a/core/config/load.ts b/core/config/load.ts index f89997875..3f725cff1 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -41,6 +41,7 @@ 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 { useHub } from "../control-plane/env"; import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; @@ -65,6 +66,7 @@ import { getEsbuildBinaryPath, } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { localPathToUri } from "../util/pathToUri"; import { defaultContextProvidersJetBrains, @@ -73,10 +75,12 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -import { isSupportedLanceDbCpuTargetForLinux } from "./util"; -import { validateConfig } from "./validation"; +import { modifyContinueConfigWithSharedConfig } from "./sharedConfig"; +import { validateConfig } from "./validation.js"; -function resolveSerializedConfig(filepath: string): SerializedContinueConfig { +export function resolveSerializedConfig( + filepath: string, +): SerializedContinueConfig { let content = fs.readFileSync(filepath, "utf8"); const config = JSONC.parse(content) as unknown as SerializedContinueConfig; if (config.env && Array.isArray(config.env)) { @@ -112,11 +116,10 @@ function loadSerializedConfig( overrideConfigJson: SerializedContinueConfig | undefined, ide: IDE, ): ConfigResult { - const configPath = getConfigJsonPath(ideType); let config: SerializedContinueConfig = overrideConfigJson!; if (!config) { try { - config = resolveSerializedConfig(configPath); + config = resolveSerializedConfig(getConfigJsonPath(ideType)); } catch (e) { throw new Error(`Failed to parse config.json: ${e}`); } @@ -136,16 +139,6 @@ function loadSerializedConfig( config.allowAnonymousTelemetry = true; } - // Deprecated getChatTitles property should be accounted for - // This is noted in docs - if ( - config.ui && - "getChatTitles" in config.ui && - config.ui.getChatTitles === false - ) { - config.disableSessionTitles = true; - } - if (ideSettings.remoteConfigServerUrl) { try { const remoteConfigJson = resolveSerializedConfig( @@ -576,6 +569,7 @@ async function finalToBrowserConfig( experimental: final.experimental, docs: final.docs, tools: final.tools, + tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), }; } @@ -760,7 +754,7 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { return readConfigJs(); } -async function loadFullConfigNode( +async function loadContinueConfigFromJson( ide: IDE, workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, @@ -792,8 +786,16 @@ async function loadFullConfigNode( serialized.systemMessage = systemPromptDotFile; } + // Apply shared config + // TODO: override several of these values with user/org shared config + const sharedConfig = new GlobalContext().getSharedConfig(); + const withShared = modifyContinueConfigWithSharedConfig( + serialized, + sharedConfig, + ); + // Convert serialized to intermediate config - let intermediate = await serializedToIntermediateConfig(serialized, ide); + let intermediate = await serializedToIntermediateConfig(withShared, ide); // Apply config.ts to modify intermediate config const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType); @@ -870,6 +872,6 @@ async function loadFullConfigNode( export { finalToBrowserConfig, intermediateToFinalConfig, - loadFullConfigNode, + loadContinueConfigFromJson, type BrowserSerializedContinueConfig, }; diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts new file mode 100644 index 000000000..b68e3adec --- /dev/null +++ b/core/config/migrateSharedConfig.ts @@ -0,0 +1,212 @@ +import * as fs from "fs"; + +import * as JSONC from "comment-json"; + +import { IDE, SerializedContinueConfig } from ".."; +import { SharedConfigSchema } from "./sharedConfig"; +import { GlobalContext } from "../util/GlobalContext"; +import { editConfigJson } from "../util/paths"; +import { resolveSerializedConfig } from "./load"; +import { deduplicateArray } from "../util"; + +/* + This migration function eliminates deprecated values from the json file + And writes them to the shared config +*/ +export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { + const globalContext = new GlobalContext(); + const currentSharedConfig = globalContext.getSharedConfig(); // for merging security concerns + + try { + let config = resolveSerializedConfig(filepath); + const shareConfigUpdates: SharedConfigSchema = {}; + + let effected = false; + + const { allowAnonymousTelemetry, ...withoutAllowTelemetry } = config; + if (allowAnonymousTelemetry !== undefined) { + if (currentSharedConfig.allowAnonymousTelemetry !== false) { + // safe merge for security + shareConfigUpdates.allowAnonymousTelemetry = allowAnonymousTelemetry; + } + config = withoutAllowTelemetry; + effected = true; + } + + const { disableIndexing, ...withoutDisableIndexing } = config; + if (disableIndexing !== undefined) { + if (currentSharedConfig.disableIndexing !== true) { + // safe merge for security + shareConfigUpdates.disableIndexing = disableIndexing; + } + config = withoutDisableIndexing; + effected = true; + } + + const { disableSessionTitles, ...withoutDisableSessionTitles } = config; + if (config.disableSessionTitles !== undefined) { + if (currentSharedConfig.disableSessionTitles !== true) { + // safe merge for security + shareConfigUpdates.disableSessionTitles = config.disableSessionTitles; + } + config = withoutDisableSessionTitles; + effected = true; + } + + const { tabAutocompleteOptions, ...withoutAutocompleteOptions } = config; + if (tabAutocompleteOptions !== undefined) { + let migratedAutocomplete = { ...tabAutocompleteOptions }; + + const { useCache, ...withoutUseCache } = migratedAutocomplete; + if (useCache !== undefined) { + shareConfigUpdates.useAutocompleteCache = useCache; + migratedAutocomplete = withoutUseCache; + effected = true; + } + + const { multilineCompletions, ...withoutMultiline } = + migratedAutocomplete; + if (multilineCompletions !== undefined) { + shareConfigUpdates.useAutocompleteMultilineCompletions = + multilineCompletions; + migratedAutocomplete = withoutMultiline; + effected = true; + } + + const { disableInFiles, ...withoutDisableInFiles } = migratedAutocomplete; + if (disableInFiles !== undefined) { + if (currentSharedConfig.disableAutocompleteInFiles !== undefined) { + // safe merge for security + shareConfigUpdates.disableAutocompleteInFiles = deduplicateArray( + [ + ...currentSharedConfig.disableAutocompleteInFiles, + ...disableInFiles, + ], + (a, b) => a === b, + ); + } else { + shareConfigUpdates.disableAutocompleteInFiles = disableInFiles; + } + shareConfigUpdates.disableAutocompleteInFiles = disableInFiles; + migratedAutocomplete = withoutDisableInFiles; + effected = true; + } + + if (Object.keys(migratedAutocomplete).length > 0) { + config = { + ...withoutAutocompleteOptions, + tabAutocompleteOptions: migratedAutocomplete, + }; + } else { + config = withoutAutocompleteOptions; + } + } + + const { experimental, ...withoutExperimental } = config; + if (experimental !== undefined) { + let migratedExperimental = { ...experimental }; + + const { useChromiumForDocsCrawling, ...rest10 } = migratedExperimental; + if (useChromiumForDocsCrawling !== undefined) { + shareConfigUpdates.useChromiumForDocsCrawling = + useChromiumForDocsCrawling; + migratedExperimental = rest10; + effected = true; + } + + const { promptPath, ...withoutPromptPath } = migratedExperimental; + if (promptPath !== undefined) { + shareConfigUpdates.promptPath = promptPath; + migratedExperimental = withoutPromptPath; + effected = true; + } + + const { readResponseTTS, ...withoutReadTTS } = migratedExperimental; + if (readResponseTTS !== undefined) { + shareConfigUpdates.readResponseTTS = readResponseTTS; + migratedExperimental = withoutReadTTS; + effected = true; + } + + if (Object.keys(migratedExperimental).length > 0) { + config = { + ...withoutExperimental, + experimental: migratedExperimental, + }; + } else { + config = withoutExperimental; + } + } + + const { ui, ...withoutUI } = config; + if (ui !== undefined) { + let migratedUI = { ...ui }; + + const { codeBlockToolbarPosition, ...withoutToolbarPosition } = + migratedUI; + if (codeBlockToolbarPosition !== undefined) { + shareConfigUpdates.codeBlockToolbarPosition = codeBlockToolbarPosition; + migratedUI = withoutToolbarPosition; + effected = true; + } + + const { fontSize, ...withoutFontSize } = migratedUI; + if (fontSize !== undefined) { + shareConfigUpdates.fontSize = fontSize; + migratedUI = withoutFontSize; + effected = true; + } + + const { codeWrap, ...withoutCodeWrap } = migratedUI; + if (codeWrap !== undefined) { + shareConfigUpdates.codeWrap = codeWrap; + migratedUI = withoutCodeWrap; + effected = true; + } + + const { displayRawMarkdown, ...withoutMD } = migratedUI; + if (displayRawMarkdown !== undefined) { + shareConfigUpdates.displayRawMarkdown = displayRawMarkdown; + migratedUI = withoutMD; + effected = true; + } + + const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI; + if (showChatScrollbar !== undefined) { + shareConfigUpdates.showChatScrollbar = showChatScrollbar; + migratedUI = withoutShowChatScrollbar; + effected = true; + } + + // Ancient param to overwrite disableSessionTitles + if ("getChatTitles" in migratedUI) { + const { getChatTitles, ...withoutChatTitles } = migratedUI; + if (getChatTitles === false) { + shareConfigUpdates.disableSessionTitles = true; + migratedUI = withoutChatTitles; + effected = true; + } + } + + if (Object.keys(migratedUI).length > 0) { + config = { + ...withoutUI, + ui: migratedUI, + }; + } else { + config = withoutUI; + } + } + + 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/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index dfb111e1f..6df837cf4 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -1,4 +1,5 @@ import { ConfigJson } from "@continuedev/config-types"; +import { ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { @@ -7,9 +8,8 @@ import { IdeSettings, SerializedContinueConfig, } from "../../index.js"; - -import { ConfigResult } from "@continuedev/config-yaml"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; + import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -32,6 +32,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { this.description = { id: workspaceId, profileType: "control-plane", + iconUrl: "", fullSlug: { ownerSlug: "", packageSlug: "", diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index cb8694bbc..3196faff4 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,8 +1,9 @@ import { ConfigResult } from "@continuedev/config-yaml"; + import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; - import { ProfileDescription } from "../ProfileLifecycleManager.js"; + import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -16,6 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader { packageSlug: "", versionSlug: "", }, + iconUrl: "", title: "Local Config", errors: undefined, }; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index f703b2a2c..7650cb0e3 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -1,10 +1,10 @@ -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js"; +import { ConfigResult } from "@continuedev/config-yaml"; +import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas/index.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; - -import { ConfigResult } from "@continuedev/config-yaml"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; + import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -24,9 +24,10 @@ export default class PlatformProfileLoader implements IProfileLoader { description: ProfileDescription; constructor( - private configResult: ConfigResult, + private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, + private readonly iconUrl: string, versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, @@ -44,6 +45,7 @@ export default class PlatformProfileLoader implements IProfileLoader { }, title: `${ownerSlug}/${packageSlug}@${versionSlug}`, errors: configResult.errors, + iconUrl: this.iconUrl, }; } diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 3a64ef71c..af8c59c97 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -1,9 +1,9 @@ import fs from "fs"; import { + AssistantUnrolled, ConfigResult, ConfigValidationError, - ConfigYaml, } from "@continuedev/config-yaml"; import { ContinueConfig, @@ -17,10 +17,11 @@ 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 { getConfigYamlPath } from "../../util/paths"; +import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; -import { loadFullConfigNode } from "../load"; +import { loadContinueConfigFromJson } from "../load"; +import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; @@ -30,7 +31,7 @@ export default async function doLoadConfig( controlPlaneClient: ControlPlaneClient, writeLog: (message: string) => Promise, overrideConfigJson: SerializedContinueConfig | undefined, - overrideConfigYaml: ConfigYaml | undefined, + overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, workspaceId?: string, ): Promise> { @@ -40,13 +41,20 @@ export default async function doLoadConfig( const ideSettings = await ideSettingsPromise; const workOsAccessToken = await controlPlaneClient.getAccessToken(); + // Migrations for old config files + // Removes + const configJsonPath = getConfigJsonPath(ideInfo.ideType); + if (fs.existsSync(configJsonPath)) { + migrateJsonSharedConfig(configJsonPath, ide); + } + const configYamlPath = getConfigYamlPath(ideInfo.ideType); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; let configLoadInterrupted = false; - if (fs.existsSync(configYamlPath) || overrideConfigYaml) { + if (overrideConfigYaml || fs.existsSync(configYamlPath)) { const result = await loadContinueConfigFromYaml( ide, workspaceConfigs.map((c) => JSON.stringify(c)), @@ -63,7 +71,7 @@ export default async function doLoadConfig( errors = result.errors; configLoadInterrupted = result.configLoadInterrupted; } else { - const result = await loadFullConfigNode( + const result = await loadContinueConfigFromJson( ide, workspaceConfigs, ideSettings, @@ -116,12 +124,14 @@ export default async function doLoadConfig( if (newConfig.analytics) { await TeamAnalytics.setup( - newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all + newConfig.analytics, uniqueId, ideInfo.extensionVersion, controlPlaneClient, controlPlaneProxyInfo, ); + } else { + await TeamAnalytics.shutdown(); } newConfig = await injectControlPlaneProxyInfo( diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts new file mode 100644 index 000000000..9f2335243 --- /dev/null +++ b/core/config/sharedConfig.ts @@ -0,0 +1,162 @@ +import z from "zod"; +import { + BrowserSerializedContinueConfig, + ContinueConfig, + Config, + SerializedContinueConfig, +} from ".."; + +export const sharedConfigSchema = z + .object({ + allowAnonymousTelemetry: z.boolean(), + disableIndexing: z.boolean(), + disableSessionTitles: z.boolean(), + + // `experimental` in `ContinueConfig` + useChromiumForDocsCrawling: z.boolean(), + readResponseTTS: z.boolean(), + promptPath: z.string(), + + // `ui` in `ContinueConfig` + codeBlockToolbarPosition: z.enum(["top", "bottom"]), + fontSize: z.number(), + codeWrap: z.boolean(), + displayRawMarkdown: z.boolean(), + showChatScrollbar: z.boolean(), + + // `tabAutocompleteOptions` in `ContinueConfig` + useAutocompleteCache: z.boolean(), + useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]), + disableAutocompleteInFiles: z.array(z.string()), + }) + .partial(); + +export type SharedConfigSchema = z.infer; + +// For security in case of damaged config file, try to salvage any security-related values +export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema { + const salvagedConfig: SharedConfigSchema = {}; + if ("allowAnonymousTelemetry" in sharedConfig) { + const val = z.boolean().safeParse(sharedConfig.allowAnonymousTelemetry); + if (val.success) { + salvagedConfig.allowAnonymousTelemetry = val.data; + } + } + if ("disableIndexing" in sharedConfig) { + const val = z.boolean().safeParse(sharedConfig.disableIndexing); + if (val.success) { + salvagedConfig.disableIndexing = val.data; + } + } + if ("disableSessionTitles" in sharedConfig) { + const val = z.boolean().safeParse(sharedConfig.disableSessionTitles); + if (val.success) { + salvagedConfig.disableSessionTitles = val.data; + } + } + if ("disableAutocompleteInFiles" in sharedConfig) { + const val = sharedConfigSchema.shape.disableAutocompleteInFiles.safeParse( + sharedConfig.disableAutocompleteInFiles, + ); + if (val.success) { + salvagedConfig.disableAutocompleteInFiles = val.data; + } + } + return salvagedConfig; +} + +export function modifyContinueConfigWithSharedConfig< + T extends + | ContinueConfig + | BrowserSerializedContinueConfig + | Config + | SerializedContinueConfig, +>(continueConfig: T, sharedConfig: SharedConfigSchema): T { + const configCopy = { ...continueConfig }; + configCopy.tabAutocompleteOptions = { + ...configCopy.tabAutocompleteOptions, + }; + if (sharedConfig.useAutocompleteCache !== undefined) { + configCopy.tabAutocompleteOptions.useCache = + sharedConfig.useAutocompleteCache; + } + if (sharedConfig.useAutocompleteMultilineCompletions !== undefined) { + configCopy.tabAutocompleteOptions.multilineCompletions = + sharedConfig.useAutocompleteMultilineCompletions; + } + if (sharedConfig.disableAutocompleteInFiles !== undefined) { + configCopy.tabAutocompleteOptions.disableInFiles = + sharedConfig.disableAutocompleteInFiles; + } + + configCopy.ui = { + ...configCopy.ui, + }; + if (sharedConfig.codeBlockToolbarPosition !== undefined) { + configCopy.ui.codeBlockToolbarPosition = + sharedConfig.codeBlockToolbarPosition; + } + if (sharedConfig.fontSize !== undefined) { + configCopy.ui.fontSize = sharedConfig.fontSize; + } + if (sharedConfig.codeWrap !== undefined) { + configCopy.ui.codeWrap = sharedConfig.codeWrap; + } + if (sharedConfig.displayRawMarkdown !== undefined) { + configCopy.ui.displayRawMarkdown = sharedConfig.displayRawMarkdown; + } + if (sharedConfig.showChatScrollbar !== undefined) { + configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar; + } + + if (sharedConfig.allowAnonymousTelemetry !== undefined) { + configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; + } + if (sharedConfig.disableIndexing !== undefined) { + configCopy.disableIndexing = sharedConfig.disableIndexing; + } + if (sharedConfig.disableSessionTitles !== undefined) { + configCopy.disableSessionTitles = sharedConfig.disableSessionTitles; + } + + configCopy.experimental = { + ...configCopy.experimental, + }; + if (sharedConfig.promptPath !== undefined) { + configCopy.experimental.promptPath = sharedConfig.promptPath; + } + if (sharedConfig.useChromiumForDocsCrawling !== undefined) { + configCopy.experimental.useChromiumForDocsCrawling = + sharedConfig.useChromiumForDocsCrawling; + } + if (sharedConfig.readResponseTTS !== undefined) { + configCopy.experimental.readResponseTTS = sharedConfig.readResponseTTS; + } + + return configCopy; +} + +// continueConfig.tabAutocompleteOptions = { +// ...continueConfig.tabAutocompleteOptions, +// useCache: sharedConfig.useAutocompleteCache, +// disableInFiles: sharedConfig.disableAutocompleteInFiles, +// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions, +// }; +// continueConfig.ui = { +// ...continueConfig.ui, +// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition, +// fontSize: sharedConfig.fontSize, +// codeWrap: sharedConfig.codeWrap, +// displayRawMarkdown: sharedConfig.displayRawMarkdown, +// showChatScrollbar: sharedConfig.showChatScrollbar, +// }; +// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; +// continueConfig.disableIndexing = sharedConfig.disableIndexing; +// continueConfig.disableIndexing = sharedConfig.disableIndexing; +// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles; +// continueConfig.experimental = { +// ...continueConfig.experimental, +// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling, +// readResponseTTS: sharedConfig.readResponseTTS, +// promptPath: sharedConfig.promptPath, +// }; diff --git a/core/config/types.ts b/core/config/types.ts index 269ae0e12..384da0c8f 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -572,7 +572,6 @@ declare global { userToken: string; enableControlServerBeta: boolean; pauseCodebaseIndexOnStart: boolean; - enableDebugLogs: boolean; } export interface IDE { @@ -902,7 +901,6 @@ declare global { export interface TabAutocompleteOptions { disable: boolean; - useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; maxSuffixPercentage: number; diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index 4109d7d37..576e196c8 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -1,11 +1,11 @@ import { ModelConfig } from "@continuedev/config-yaml"; -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; +import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas"; import { SerializedContinueConfig } from "../.."; export function convertConfigJsonToConfigYaml( configJson: SerializedContinueConfig, -): ConfigYaml { +): AssistantUnrolled { return { name: "Local Config", version: "1.0.0", @@ -24,8 +24,8 @@ export function convertConfigJsonToConfigYaml( // rerankModels ], context: configJson.contextProviders?.map((provider) => ({ - uses: provider.name, - with: provider.params, + provider: provider.name, + params: provider.params, })), }; } diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index cfdffc12d..0bc872f88 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -1,14 +1,14 @@ -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; +import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas"; // TODO -export const defaultConfigYaml: ConfigYaml = { +export const defaultConfigYaml: AssistantUnrolled = { models: [], context: [], name: "Local Config", version: "1.0.0", }; -export const defaultConfigYamlJetBrains: ConfigYaml = { +export const defaultConfigYamlJetBrains: AssistantUnrolled = { models: [], context: [], name: "Local Config", diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index cb1c5ea18..666317447 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -1,8 +1,9 @@ import fs from "node:fs"; import { + AssistantUnrolled, ConfigResult, - ConfigYaml, + parseAssistantUnrolled, validateConfigYaml, } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; @@ -34,19 +35,24 @@ import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { slashFromCustomCommand } from "../../commands"; import { allTools } from "../../tools"; +import { GlobalContext } from "../../util/GlobalContext"; +import { modifyContinueConfigWithSharedConfig } from "../sharedConfig"; import { clientRenderHelper } from "./clientRender"; import { llmsFromModelConfig } from "./models"; async function loadConfigYaml( workspaceConfigs: string[], rawYaml: string, - overrideConfigYaml: ConfigYaml | undefined, + overrideConfigYaml: AssistantUnrolled | undefined, ide: IDE, controlPlaneClient: ControlPlaneClient, -): Promise> { +): Promise> { + const ideSettings = await ide.getIdeSettings(); let config = overrideConfigYaml ?? - (await clientRenderHelper(rawYaml, ide, controlPlaneClient)); + (ideSettings.continueTestEnvironment === "production" + ? await clientRenderHelper(rawYaml, ide, controlPlaneClient) + : parseAssistantUnrolled(rawYaml)); const errors = validateConfigYaml(config); if (errors?.some((error) => error.fatal)) { @@ -86,7 +92,7 @@ async function slashCommandsFromV1PromptFiles( } async function configYamlToContinueConfig( - config: ConfigYaml, + config: AssistantUnrolled, ide: IDE, ideSettings: IdeSettings, uniqueId: string, @@ -181,7 +187,8 @@ async function configYamlToContinueConfig( // Context providers const codebaseContextParams: IContextProvider[] = - (config.context || []).find((cp) => cp.uses === "codebase")?.with || {}; + (config.context || []).find((cp) => cp.provider === "codebase")?.params || + {}; const DEFAULT_CONTEXT_PROVIDERS = [ new FileContextProvider({}), new CodebaseContextProvider(codebaseContextParams), @@ -194,14 +201,14 @@ async function configYamlToContinueConfig( continueConfig.contextProviders = (config.context ?.map((context) => { - const cls = contextProviderClassFromName(context.uses) as any; + const cls = contextProviderClassFromName(context.provider) as any; if (!cls) { - if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.uses)) { - console.warn(`Unknown context provider ${context.uses}`); + if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) { + console.warn(`Unknown context provider ${context.provider}`); } return undefined; } - const instance: IContextProvider = new cls(context.with ?? {}); + const instance: IContextProvider = new cls(context.params ?? {}); return instance; }) .filter((p) => !!p) ?? []) as IContextProvider[]; @@ -296,14 +303,13 @@ export async function loadContinueConfigFromYaml( uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, - overrideConfigYaml: ConfigYaml | undefined, + overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, ): Promise> { - const configYamlPath = getConfigYamlPath(ideType); const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(configYamlPath, "utf-8") + ? fs.readFileSync(getConfigYamlPath(ideType), "utf-8") : ""; const configYamlResult = await loadConfigYaml( @@ -341,8 +347,16 @@ export async function loadContinueConfigFromYaml( } } + // Apply shared config + // TODO: override several of these values with user/org shared config + const sharedConfig = new GlobalContext().getSharedConfig(); + const withShared = modifyContinueConfigWithSharedConfig( + continueConfig, + sharedConfig, + ); + return { - config: continueConfig, + config: withShared, errors: configYamlResult.errors, configLoadInterrupted: false, }; diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 304c2a8c4..b1a960910 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -69,10 +69,14 @@ class MCPConnection { private constructTransport(options: MCPOptions): Transport { switch (options.transport.type) { case "stdio": + const env: Record = options.transport.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } return new StdioClientTransport({ command: options.transport.command, args: options.transport.args, - env: options.transport.env, + env, }); case "websocket": return new WebSocketClientTransport(new URL(options.transport.url)); diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts index 837e4d05d..b746199b0 100644 --- a/core/context/providers/CodeContextProvider.ts +++ b/core/context/providers/CodeContextProvider.ts @@ -24,8 +24,12 @@ class CodeContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { // Assume the query is the id as returned by loadSubmenuItems + const workspaceDirs = await extras.ide.getWorkspaceDirs(); return [ - await CodeSnippetsCodebaseIndex.getForId(Number.parseInt(query, 10)), + await CodeSnippetsCodebaseIndex.getForId( + Number.parseInt(query, 10), + workspaceDirs, + ), ]; } diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index d3cef2dc1..e624f539a 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -4,7 +4,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../"; -import { getUriPathBasename } from "../../util/uri"; +import { getUriDescription } from "../../util/uri"; class CurrentFileContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -23,12 +23,27 @@ class CurrentFileContextProvider extends BaseContextProvider { if (!currentFile) { return []; } - const baseName = getUriPathBasename(currentFile.path); + + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + currentFile.path, + await extras.ide.getWorkspaceDirs(), + ); + + let prefix = "This is the currently open file:"; + let name = baseName; + + // This allows frontend to retrieve when using alt + enter or default context with slightly different copy + if (query === "non-mention-usage") { + prefix = + "The following file is currently open. Don't reference it if it's not relevant to the user's message:"; + name = "Active file: " + baseName; + } + return [ { - description: currentFile.path, - content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``, - name: baseName, + description: last2Parts, + content: `${prefix}\n\n\`\`\`${relativePathOrBasename}\n${currentFile.contents}\n\`\`\``, + name, uri: { type: "file", value: currentFile.path, diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 1e12b51fd..cb8e926d5 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -20,6 +20,10 @@ class DocsContextProvider extends BaseContextProvider { displayTitle: "Docs", description: "Type to search docs", type: "submenu", + // Todo: consider a different renderInline so that when multiple docs are referenced in one message, + // Or the doc has an odd name unrelated to the content + // The name of the doc itself doesn't skew the embedding results + // renderInlineAs: "", }; constructor(options: any) { @@ -82,6 +86,7 @@ class DocsContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve; const useReranking = this.options?.useReranking ?? true; // Get docs service @@ -96,7 +101,7 @@ class DocsContextProvider extends BaseContextProvider { let chunks = await docsService.retrieveChunksFromQuery( extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, - this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, + nRetrieve, ); if (!chunks?.length) { return []; diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index 674cc1a00..4953f5bdc 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -10,6 +10,7 @@ import { walkDirs } from "../../indexing/walkDir"; import { getUriPathBasename, getShortestUniqueRelativeUriPaths, + getUriDescription, } from "../../util/uri"; const MAX_SUBMENU_ITEMS = 10_000; @@ -27,16 +28,22 @@ class FileContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { // Assume the query is a filepath - query = query.trim(); - const content = await extras.ide.readFile(query); + const fileUri = query.trim(); + const content = await extras.ide.readFile(fileUri); + + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + fileUri, + await extras.ide.getWorkspaceDirs(), + ); + return [ { - name: query.split(/[\\/]/).pop() ?? query, - description: query, - content: `\`\`\`${query}\n${content}\n\`\`\``, + name: baseName, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``, uri: { type: "file", - value: query, + value: fileUri, }, }, ]; diff --git a/core/context/providers/OpenFilesContextProvider.ts b/core/context/providers/OpenFilesContextProvider.ts index 318ebb648..8267bf1c9 100644 --- a/core/context/providers/OpenFilesContextProvider.ts +++ b/core/context/providers/OpenFilesContextProvider.ts @@ -3,7 +3,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; -import { findUriInDirs, getUriPathBasename } from "../../util/uri.js"; +import { getUriDescription } from "../../util/uri.js"; import { BaseContextProvider } from "../index.js"; class OpenFilesContextProvider extends BaseContextProvider { @@ -24,14 +24,17 @@ class OpenFilesContextProvider extends BaseContextProvider { ? await ide.getPinnedFiles() : await ide.getOpenFiles(); const workspaceDirs = await extras.ide.getWorkspaceDirs(); + return await Promise.all( openFiles.map(async (filepath: string) => { + const content = await ide.readFile(filepath); + const { relativePathOrBasename, last2Parts, baseName } = + getUriDescription(filepath, workspaceDirs); + return { - description: filepath, - content: `\`\`\`${ - findUriInDirs(filepath, workspaceDirs).relativePathOrBasename - }\n${await ide.readFile(filepath)}\n\`\`\``, - name: getUriPathBasename(filepath), + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``, + name: baseName, uri: { type: "file", value: filepath, diff --git a/core/context/providers/ProblemsContextProvider.ts b/core/context/providers/ProblemsContextProvider.ts index b1a0372a5..d8df5687f 100644 --- a/core/context/providers/ProblemsContextProvider.ts +++ b/core/context/providers/ProblemsContextProvider.ts @@ -3,7 +3,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; -import { getUriPathBasename } from "../../util/uri.js"; +import { getUriDescription } from "../../util/uri.js"; import { BaseContextProvider } from "../index.js"; class ProblemsContextProvider extends BaseContextProvider { @@ -20,10 +20,14 @@ class ProblemsContextProvider extends BaseContextProvider { ): Promise { const ide = extras.ide; const problems = await ide.getProblems(); + const workspaceDirs = await ide.getWorkspaceDirs(); const items = await Promise.all( problems.map(async (problem) => { - const fileName = getUriPathBasename(problem.filepath); + const { relativePathOrBasename, baseName } = getUriDescription( + problem.filepath, + workspaceDirs, + ); const content = await ide.readFile(problem.filepath); const lines = content.split("\n"); const rangeContent = lines @@ -35,8 +39,8 @@ class ProblemsContextProvider extends BaseContextProvider { return { description: "Problems in current file", - content: `\`\`\`${fileName}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`, - name: `Warning in ${fileName}`, + content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`, + name: `Warning in ${baseName}`, }; }), ); diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 14dba3341..d2e73e060 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,6 +1,6 @@ import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; -import { getUriPathBasename } from "../../util/uri"; +import { getUriDescription } from "../../util/uri"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; @@ -111,18 +111,17 @@ export async function retrieveContextItemsFromEmbeddings( ...results .sort((a, b) => a.filepath.localeCompare(b.filepath)) .map((r) => { - const basename = getUriPathBasename(r.filepath); - const name = `${basename} (${r.startLine}-${r.endLine})`; - const description = `${r.filepath}`; + const { relativePathOrBasename, last2Parts, baseName } = + getUriDescription(r.filepath, workspaceDirs); - if (basename === "package.json") { + if (baseName === "package.json") { console.warn("Retrieval pipeline: package.json detected"); } return { - name, - description, - content: `\`\`\`${name}\n${r.content}\n\`\`\``, + name: `${baseName} (${r.startLine}-${r.endLine})`, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``, uri: { type: "file" as const, value: r.filepath, diff --git a/core/continueServer/interface.ts b/core/continueServer/interface.ts index 3c67aa25e..c6e7ceda2 100644 --- a/core/continueServer/interface.ts +++ b/core/continueServer/interface.ts @@ -22,7 +22,7 @@ export interface IContinueServerClient { connected: boolean; url: URL | undefined; getUserToken(): string | undefined; - getConfig(): Promise<{ configJson: string; configJs: string }>; + getConfig(): Promise<{ configJson: string }>; getFromIndexCache( keys: string[], artifactId: T, diff --git a/core/continueServer/stubs/client.ts b/core/continueServer/stubs/client.ts index 49f02fb65..febed8bbd 100644 --- a/core/continueServer/stubs/client.ts +++ b/core/continueServer/stubs/client.ts @@ -30,7 +30,7 @@ export class ContinueServerClient implements IContinueServerClient { return this.url !== undefined && this.userToken !== undefined; } - public async getConfig(): Promise<{ configJson: string; configJs: string }> { + public async getConfig(): Promise<{ configJson: string }> { const userToken = await this.userToken; const response = await fetch(new URL("sync", this.url).href, { method: "GET", diff --git a/core/control-plane/TeamAnalytics.ts b/core/control-plane/TeamAnalytics.ts index c9f543bb4..732567206 100644 --- a/core/control-plane/TeamAnalytics.ts +++ b/core/control-plane/TeamAnalytics.ts @@ -1,7 +1,5 @@ import os from "node:os"; -import { Analytics } from "@continuedev/config-types"; - import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js"; import { ControlPlaneProxyInfo, @@ -10,9 +8,10 @@ import { import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js"; import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js"; import { ControlPlaneClient } from "./client.js"; +import { AnalyticsConfig } from "../index.js"; function createAnalyticsProvider( - config: Analytics, + config: AnalyticsConfig, ): IAnalyticsProvider | undefined { // @ts-ignore switch (config.provider) { @@ -42,7 +41,7 @@ export class TeamAnalytics { } static async setup( - config: Analytics, + config: AnalyticsConfig, uniqueId: string, extensionVersion: string, controlPlaneClient: ControlPlaneClient, @@ -52,22 +51,27 @@ export class TeamAnalytics { TeamAnalytics.os = os.platform(); TeamAnalytics.extensionVersion = extensionVersion; - if (!config) { - await TeamAnalytics.provider?.shutdown(); - TeamAnalytics.provider = undefined; - } else { - TeamAnalytics.provider = createAnalyticsProvider(config); - await TeamAnalytics.provider?.setup( - config, - uniqueId, - controlPlaneProxyInfo, - ); + TeamAnalytics.provider = createAnalyticsProvider(config); + await TeamAnalytics.provider?.setup( + config, + uniqueId, + controlPlaneProxyInfo, + ); - if (config.provider === "continue-proxy") { - ( - TeamAnalytics.provider as ContinueProxyAnalyticsProvider - ).controlPlaneClient = controlPlaneClient; - } + if (config.provider === "continue-proxy") { + ( + TeamAnalytics.provider as ContinueProxyAnalyticsProvider + ).controlPlaneClient = controlPlaneClient; + } + } + + static async shutdown() { + if (TeamAnalytics.provider) { + await TeamAnalytics.provider.shutdown(); + TeamAnalytics.provider = undefined; + TeamAnalytics.os = undefined; + TeamAnalytics.extensionVersion = undefined; + TeamAnalytics.uniqueId = "NOT_UNIQUE"; } } } diff --git a/core/control-plane/analytics/IAnalyticsProvider.ts b/core/control-plane/analytics/IAnalyticsProvider.ts index c069695d0..6631a7c50 100644 --- a/core/control-plane/analytics/IAnalyticsProvider.ts +++ b/core/control-plane/analytics/IAnalyticsProvider.ts @@ -1,4 +1,4 @@ -import { Analytics } from "@continuedev/config-types"; +import { AnalyticsConfig } from "../.."; export interface AnalyticsMetadata { extensionVersion: string; @@ -13,7 +13,7 @@ export interface ControlPlaneProxyInfo { export interface IAnalyticsProvider { capture(event: string, properties: { [key: string]: any }): Promise; setup( - config: Analytics, + config: AnalyticsConfig, uniqueId: string, controlPlaneProxyInfo?: ControlPlaneProxyInfo, ): Promise; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 044006882..7d0e03cc8 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -1,15 +1,16 @@ import { ConfigJson } from "@continuedev/config-types"; -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js"; -import fetch, { RequestInit, Response } from "node-fetch"; - -import { IdeSettings, ModelDescription } from "../index.js"; - import { + AssistantUnrolled, ConfigResult, FQSN, FullSlug, SecretResult, } from "@continuedev/config-yaml"; +import fetch, { RequestInit, Response } from "node-fetch"; + +import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; +import { IdeSettings, ModelDescription } from "../index.js"; + import { getControlPlaneEnv } from "./env.js"; export interface ControlPlaneSessionInfo { @@ -32,10 +33,6 @@ export const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; export class ControlPlaneClient { - private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes - - private lastAccessTokenRefresh = 0; - constructor( private readonly sessionInfoPromise: Promise< ControlPlaneSessionInfo | undefined @@ -107,9 +104,9 @@ export class ControlPlaneClient { } } - public async listAssistants(): Promise< + public async listAssistants(organizationId: string | null): Promise< { - configResult: ConfigResult; + configResult: ConfigResult; ownerSlug: string; packageSlug: string; iconUrl: string; @@ -121,7 +118,11 @@ export class ControlPlaneClient { } try { - const resp = await this.request("ide/list-assistants", { + const url = organizationId + ? `ide/list-assistants?organizationId=${organizationId}` + : "ide/list-assistants"; + + const resp = await this.request(url, { method: "GET", }); return (await resp.json()) as any; @@ -130,14 +131,38 @@ export class ControlPlaneClient { } } - public async listAssistantFullSlugs(): Promise { + public async listOrganizations(): Promise> { + const userId = await this.userId; + + if (!userId) { + return []; + } + + try { + const resp = await this.request("ide/list-organizations", { + method: "GET", + }); + const { organizations } = (await resp.json()) as any; + return organizations; + } catch (e) { + return []; + } + } + + public async listAssistantFullSlugs( + organizationId: string | null, + ): Promise { const userId = await this.userId; if (!userId) { return null; } + const url = organizationId + ? `ide/list-assistant-full-slugs?organizationId=${organizationId}` + : "ide/list-assistant-full-slugs"; + try { - const resp = await this.request("ide/list-assistant-full-slugs", { + const resp = await this.request(url, { method: "GET", }); const { fullSlugs } = (await resp.json()) as any; diff --git a/core/core.ts b/core/core.ts index cf24053b4..edfbc6c95 100644 --- a/core/core.ts +++ b/core/core.ts @@ -19,6 +19,7 @@ import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFile import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { ControlPlaneClient } from "./control-plane/client"; +import { getControlPlaneEnv } from "./control-plane/env"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; @@ -52,12 +53,10 @@ import { type IndexingProgressUpdate, } from "."; -import { getControlPlaneEnv } from "./control-plane/env"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; export class Core { - // implements IMessenger configHandler: ConfigHandler; codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; @@ -209,13 +208,24 @@ export class Core { // Note, VsCode's in-process messenger doesn't do anything with this // It will only show for jetbrains - this.messenger.onError((err) => { - console.error(err); + this.messenger.onError((message, err) => { void Telemetry.capture("core_messenger_error", { message: err.message, stack: err.stack, }); - void this.ide.showToast("error", err.message); + + // Again, specifically for jetbrains to prevent duplicate error messages + // The same logic can currently be found in the webview protocol + // bc streaming errors are handled in the GUI + if ( + ["llm/streamChat", "chatDescriber/describe"].includes( + message.messageType, + ) + ) { + return; + } else { + void this.ide.showToast("error", err.message); + } }); on("update/selectTabAutocompleteModel", async (msg) => { @@ -289,6 +299,7 @@ export class Core { on("config/ideSettingsUpdate", (msg) => { this.configHandler.updateIdeSettings(msg.data); }); + on("config/listProfiles", (msg) => { return this.configHandler.listProfiles(); }); @@ -297,11 +308,20 @@ export class Core { addContextProvider(msg.data); }); + on("config/updateSharedConfig", async (msg) => { + this.globalContext.updateSharedConfig(msg.data); + await this.configHandler.reloadConfig(); + }); + on("controlPlane/openUrl", async (msg) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.messenger.request("openUrl", `${env.APP_URL}${msg.data.path}`); }); + on("controlPlane/listOrganizations", async (msg) => { + return await this.controlPlaneClient.listOrganizations(); + }); + // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); @@ -863,12 +883,21 @@ export class Core { on("docs/initStatuses", async (msg) => { void this.docsService.initStatuses(); }); + on("docs/getDetails", async (msg) => { + return await this.docsService.getDetails(msg.data.startUrl); + }); // on("didChangeSelectedProfile", (msg) => { void this.configHandler.setSelectedProfile(msg.data.id); void this.configHandler.reloadConfig(); }); + + on("didChangeSelectedOrg", (msg) => { + void this.configHandler.setSelectedOrgId(msg.data.id); + void this.configHandler.reloadConfig(); + }); + on("didChangeControlPlaneSessionInfo", async (msg) => { this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo); }); diff --git a/core/index.d.ts b/core/index.d.ts index 03c32a8b5..1184b412b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -229,6 +229,14 @@ export interface SiteIndexingConfig { rootUrl?: string; // Currently only used by preindexed docs } +export interface DocsIndexingDetails { + startUrl: string; + config: SiteIndexingConfig; + indexingStatus: IndexingStatus | undefined; + chunks: Chunk[]; + isPreIndexedDoc: boolean; +} + export interface IContextProvider { get description(): ContextProviderDescription; @@ -425,6 +433,13 @@ interface ToolCallState { output?: ContextItem[]; } +interface Reasoning { + active: boolean; + text: string; + startAt: number; + endAt?: number; +} + export interface ChatHistoryItem { message: ChatMessage; contextItems: ContextItemWithId[]; @@ -435,6 +450,7 @@ export interface ChatHistoryItem { isGatheringContext?: boolean; checkpoint?: Checkpoint; isBeforeCheckpoint?: boolean; + reasoning?: Reasoning; } export interface LLMFullCompletionOptions extends BaseCompletionOptions { @@ -585,7 +601,6 @@ export interface IdeSettings { enableControlServerBeta: boolean; continueTestEnvironment: "none" | "production" | "test" | "local"; pauseCodebaseIndexOnStart: boolean; - enableDebugLogs: boolean; } export interface FileStats { @@ -941,7 +956,6 @@ export interface RerankerDescription { export interface TabAutocompleteOptions { disable: boolean; - useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; maxSuffixPercentage: number; @@ -1091,7 +1105,7 @@ export interface ExperimentalConfig { } export interface AnalyticsConfig { - type: string; + provider: string; url?: string; clientKey?: string; } @@ -1214,6 +1228,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; usePlatform: boolean; + tabAutocompleteOptions?: Partial; } // DOCS SUGGESTIONS AND PACKAGE INFO diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index f207f096b..c0d386d07 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -28,7 +28,12 @@ import type { IndexTag, IndexingProgressUpdate, } from "../"; -import { getLastNPathParts, getUriPathBasename } from "../util/uri"; +import { + findUriInDirs, + getLastNPathParts, + getLastNUriRelativePathParts, + getUriPathBasename, +} from "../util/uri"; type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; @@ -347,14 +352,19 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } } - static async getForId(id: number): Promise { + static async getForId( + id: number, + workspaceDirs: string[], + ): Promise { const db = await SqliteDb.get(); const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]); + const last2Parts = getLastNUriRelativePathParts(workspaceDirs, row.path, 2); + const { relativePathOrBasename } = findUriInDirs(row.path, workspaceDirs); return { name: row.title, - description: getLastNPathParts(row.path, 2), - content: `\`\`\`${getUriPathBasename(row.path)}\n${row.content}\n\`\`\``, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${row.content}\n\`\`\``, uri: { type: "file", value: row.path, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 861dacb52..6429cc400 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -5,6 +5,7 @@ import sqlite3 from "sqlite3"; import { Chunk, ContinueConfig, + DocsIndexingDetails, IDE, IdeInfo, ILLM, @@ -42,6 +43,7 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import { ConfigResult } from "@continuedev/config-yaml"; import type * as LanceType from "vectordb"; @@ -348,7 +350,7 @@ export default class DocsService { } // Returns true if startUrl has been indexed with current embeddingsProvider - async hasMetadata(startUrl: string): Promise> { + async hasMetadata(startUrl: string): Promise { const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, @@ -716,6 +718,64 @@ export default class DocsService { return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed); } + private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk { + return { + digest: row.path, + filepath: row.path, + startLine: row.startline, + endLine: row.endline, + index: 0, + content: row.content, + otherMetadata: { + title: row.title, + }, + }; + } + async getDetails(startUrl: string): Promise { + const db = await this.getOrCreateSqliteDb(); + + try { + const { isPreindexed, provider } = + await this.getEmbeddingsProvider(startUrl); + const preIndexedDoc = preIndexedDocs[startUrl]; + const isPreIndexedDoc = !!preIndexedDoc; + + const result = await db.get( + `SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, + startUrl, + provider.embeddingId, + ); + + if (!result) { + throw new Error(`${startUrl} not found in sqlite`); + } + const siteIndexingConfig: SiteIndexingConfig = { + startUrl, + faviconUrl: result.favicon, + title: result.title, + }; + + const table = await this.getOrCreateLanceTable({ + initializationVector: [], + startUrl, + }); + const rows = (await table + .filter(`starturl = '${startUrl}'`) + .limit(1000) + .execute()) as LanceDbDocsRow[]; + + return { + startUrl, + config: siteIndexingConfig, + indexingStatus: this.statuses.get(startUrl), + chunks: rows.map(this.lanceDBRowToChunk), + isPreIndexedDoc, + }; + } 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 async retrieveChunks( @@ -753,17 +813,7 @@ export default class DocsService { return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true); } - return docs.map((doc) => ({ - digest: doc.path, - filepath: doc.path, - startLine: doc.startline, - endLine: doc.endline, - index: 0, - content: doc.content, - otherMetadata: { - title: doc.title, - }, - })); + return docs.map(this.lanceDBRowToChunk); } // SQLITE DB @@ -819,7 +869,7 @@ export default class DocsService { private async syncDocs( oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, - reindex: boolean, + forceReindex: boolean, ) { try { this.isSyncing = true; @@ -859,20 +909,25 @@ export default class DocsService { ) { changedDocs.push(doc); } else { - // if get's here, not changed, no update needed, mark as complete - this.handleStatusUpdate({ - type: "docs", - id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.embeddingId, - isReindexing: false, - title: doc.title, - debugInfo: "Config sync: not changed", - icon: doc.faviconUrl, - url: doc.startUrl, - progress: 1, - description: "Complete", - status: "complete", - }); + if (forceReindex) { + changedDocs.push(doc); + } else { + // if get's here, not changed, no update needed, mark as complete + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: + this.config.embeddingsProvider.embeddingId, + isReindexing: false, + title: doc.title, + debugInfo: "Config sync: not changed", + icon: doc.faviconUrl, + url: doc.startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); + } } } else { const currentStatus = this.statuses.get(doc.startUrl); diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts index 0f0d9e593..d5e717fc0 100644 --- a/core/indexing/docs/crawlers/DefaultCrawler.ts +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -26,7 +26,7 @@ export class DefaultCrawler { }); if (!resp.ok) { const text = await resp.text(); - throw new Error(`Failed to crawl site: ${text}`); + throw new Error(`Failed to crawl site (${resp.status}): ${text}`); } const json = (await resp.json()) as PageData[]; return json; diff --git a/core/indexing/docs/crawlers/DocsCrawler.test.ts b/core/indexing/docs/crawlers/DocsCrawler.test.ts index d3a246cf9..96c6dc24d 100644 --- a/core/indexing/docs/crawlers/DocsCrawler.test.ts +++ b/core/indexing/docs/crawlers/DocsCrawler.test.ts @@ -152,11 +152,15 @@ describe("DocsCrawler", () => { ); commonDocsSites.forEach((url) => { - test(`Default crawler common site: ${url}`, async () => { - const { pages, crawler } = await runCrawl(url); - expect(pages.length).toBeGreaterThanOrEqual(1); - expect(crawler).toEqual("default"); - }); + test( + `Default crawler common site: ${url}`, + async () => { + const { pages, crawler } = await runCrawl(url); + expect(pages.length).toBeGreaterThanOrEqual(1); + expect(crawler).toEqual("default"); + }, + TIMEOUT_MS, + ); }); }); diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 5f88c13eb..dfbd2da5d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -399,10 +399,10 @@ function compileChatMessages( if ( (systemMessage && systemMessage.trim() !== "") || - msgs?.[0].role === "system" + msgs?.[0]?.role === "system" ) { let content = ""; - if (msgs?.[0].role === "system") { + if (msgs?.[0]?.role === "system") { content = renderChatMessage(msgs?.[0]); } if (systemMessage && systemMessage.trim() !== "") { diff --git a/core/llm/index.ts b/core/llm/index.ts index 70565b5ee..da1825407 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -460,9 +460,11 @@ export abstract class BaseLLM implements ILLM { `${toolCall.function?.name}(${toolCall.function?.arguments})`, ) .join("\n"); - } else if ("content" in msg && Array.isArray(msg.content)) { - const content = renderChatMessage(msg); - msg.content = content; + } else if ("content" in msg) { + if (Array.isArray(msg.content)) { + msg.content = renderChatMessage(msg); + } + contentToShow = msg.content; } formatted += `<${msg.role}>\n${contentToShow}\n\n`; diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index 09777dae0..53729022a 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -26,7 +26,13 @@ function testLLM( skip, testFim, testToolCall, - }: { skip?: boolean; testFim?: boolean; testToolCall?: boolean }, + timeout, + }: { + skip?: boolean; + testFim?: boolean; + testToolCall?: boolean; + timeout?: number; + }, ) { if (skip) { return; @@ -37,45 +43,29 @@ function testLLM( }); describe(llm.providerName + "/" + llm.model, () => { - test("Stream Chat works", async () => { - let total = ""; - for await (const chunk of llm.streamChat( - [{ role: "user", content: "Hi" }], - new AbortController().signal, - )) { - total += chunk.content; - } - - expect(total.length).toBeGreaterThan(0); - return; - }); - - test("Stream Complete works", async () => { - let total = ""; - for await (const chunk of llm.streamComplete( - "Hi", - new AbortController().signal, - )) { - total += chunk; - } - - expect(total.length).toBeGreaterThan(0); - return; - }); - - test("Complete works", async () => { - const completion = await llm.complete("Hi", new AbortController().signal); - - expect(completion.length).toBeGreaterThan(0); - return; - }); - - if (testFim) { - test("FIM works", async () => { + test( + "Stream Chat works", + async () => { let total = ""; - for await (const chunk of llm.streamFim( + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi" }], + new AbortController().signal, + )) { + total += chunk.content; + } + + expect(total.length).toBeGreaterThan(0); + return; + }, + timeout, + ); + + test( + "Stream Complete works", + async () => { + let total = ""; + for await (const chunk of llm.streamComplete( "Hi", - "name is ChatGPT.", new AbortController().signal, )) { total += chunk; @@ -83,72 +73,120 @@ function testLLM( expect(total.length).toBeGreaterThan(0); return; - }); + }, + timeout, + ); + + test( + "Complete works", + async () => { + const completion = await llm.complete( + "Hi", + new AbortController().signal, + ); + + expect(completion.length).toBeGreaterThan(0); + return; + }, + timeout, + ); + + if (testFim) { + test( + "FIM works", + async () => { + let total = ""; + for await (const chunk of llm.streamFim( + "Hi", + "name is ChatGPT.", + new AbortController().signal, + )) { + total += chunk; + } + + expect(total.length).toBeGreaterThan(0); + return; + }, + timeout, + ); } if (testToolCall) { - test("Tool Call works", async () => { - let args = ""; - let isFirstChunk = true; - for await (const chunk of llm.streamChat( - [{ role: "user", content: "Hi, my name is Nate." }], - new AbortController().signal, - { - tools: [ - { - displayTitle: "Say Hello", - function: { - name: "say_hello", - description: "Say Hello", - parameters: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the person to greet", + test( + "Tool Call works", + async () => { + let args = ""; + let isFirstChunk = true; + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi, my name is Nate." }], + new AbortController().signal, + { + tools: [ + { + displayTitle: "Say Hello", + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, }, }, }, + type: "function", + wouldLikeTo: "Say hello", + readonly: true, }, + ], + toolChoice: { type: "function", - wouldLikeTo: "Say hello", - readonly: true, - }, - ], - toolChoice: { - type: "function", - function: { - name: "say_hello", + function: { + name: "say_hello", + }, }, }, - }, - )) { - const typedChunk = chunk as AssistantChatMessage; - if (!typedChunk.toolCalls) { - continue; + )) { + const typedChunk = chunk as AssistantChatMessage; + if (!typedChunk.toolCalls) { + continue; + } + const toolCall = typedChunk.toolCalls[0]; + args += toolCall.function?.arguments ?? ""; + + expect(chunk.role).toBe("assistant"); + expect(chunk.content).toBe(""); + expect(typedChunk.toolCalls).toHaveLength(1); + + if (isFirstChunk) { + isFirstChunk = false; + expect(toolCall.id).toBeDefined(); + expect(toolCall.function!.name).toBe("say_hello"); + } } - const toolCall = typedChunk.toolCalls[0]; - args += toolCall.function?.arguments ?? ""; - expect(chunk.role).toBe("assistant"); - expect(chunk.content).toBe(""); - expect(typedChunk.toolCalls).toHaveLength(1); - - if (isFirstChunk) { - isFirstChunk = false; - expect(toolCall.id).toBeDefined(); - expect(toolCall.function!.name).toBe("say_hello"); - } - } - - const parsedArgs = JSON.parse(args); - expect(parsedArgs.name).toBe("Nate"); - }); + const parsedArgs = JSON.parse(args); + expect(parsedArgs.name).toBe("Nate"); + }, + timeout, + ); } }); } describe("LLM", () => { + if (process.env.IGNORE_API_KEY_TESTS === "true") { + test("Skipping API key tests", () => { + console.log( + "Skipping API key tests due to IGNORE_API_KEY_TESTS being set", + ); + }); + return; + } + testLLM( new Anthropic({ model: "claude-3-5-sonnet-latest", @@ -165,7 +203,7 @@ describe("LLM", () => { }); testLLM( new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), - { skip: false }, + { skip: false, timeout: 20000 }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { skip: false, diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index f3b445df4..59554efe5 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -24,6 +24,7 @@ class Asksage extends BaseLLM { "gpt4-32k": "gpt4-32k", "gpt-o1": "gpt-o1", // Works "gpt-o1-mini": "gpt-o1-mini", // Works + "gpt-o3-mini": "gpt-o3-mini", // Stub "gpt-3.5-turbo": "gpt35-16k", // Works "aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works "claude-3-5-sonnet-latest": "claude-35-sonnet", // Works diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index c0940dbfd..4c0fb189b 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -251,9 +251,45 @@ class Gemini extends BaseLLM { return; } } + // Helper function to recursively clean JSON Schema objects + const cleanJsonSchema = (schema: any): any => { + if (!schema || typeof schema !== 'object') return schema; + + if (Array.isArray(schema)) { + return schema.map(cleanJsonSchema); + } + + const { + $schema, + additionalProperties, + default: defaultValue, + ...rest + } = schema; + + // Recursively clean nested properties + if (rest.properties) { + rest.properties = Object.entries(rest.properties).reduce( + (acc, [key, value]) => ({ + ...acc, + [key]: cleanJsonSchema(value), + }), + {} + ); + } + + // Clean items in arrays + if (rest.items) { + rest.items = cleanJsonSchema(rest.items); + } + + return rest; + }; + + // Clean the parameters and convert type to uppercase + const cleanedParams = cleanJsonSchema(tool.function.parameters); fn.parameters = { + ...cleanedParams, type: tool.function.parameters.type.toUpperCase(), - ...tool.function.parameters, }; } functions.push(fn); @@ -311,11 +347,16 @@ class Gemini extends BaseLLM { const supportedParts: MessagePart[] = []; const toolCalls: ToolCallDelta[] = []; + // Process all parts first to maintain order + const processedParts: Array<{ + type: 'content' | 'tool' | 'toolCall', + data: any + }> = []; + for (const part of content.parts) { if ("text" in part) { supportedParts.push({ type: "text", text: part.text }); } else if ("inlineData" in part) { - // TODO does this image url conversion actually work? supportedParts.push({ type: "imageUrl", imageUrl: { @@ -323,38 +364,56 @@ class Gemini extends BaseLLM { }, }); } else if ("functionCall" in part) { - // Handle function call - toolCalls.push({ - type: "function", - id: "", // Not supported by gemini - function: { - name: part.functionCall.name, - arguments: - typeof part.functionCall.args === "string" - ? part.functionCall.args - : JSON.stringify(part.functionCall.args), - }, + // Queue function call + processedParts.push({ + type: 'toolCall', + data: { + type: "function", + id: "", // Not supported by gemini + function: { + name: part.functionCall.name, + arguments: + typeof part.functionCall.args === "string" + ? part.functionCall.args + : JSON.stringify(part.functionCall.args), + }, + } }); } else if ("functionResponse" in part) { - // TODO hypothetically order could be off here - // Where function response is in the middle of something - yield { - role: "tool", - content: part.functionResponse.response.output as string, - toolCallId: part.functionResponse.name, - }; + // Queue function response + processedParts.push({ + type: 'tool', + data: { + role: "tool", + content: part.functionResponse.response.output as string, + toolCallId: part.functionResponse.name, + } + }); } else { console.warn("Unsupported gemini part type received", part); } } - if (supportedParts.length || toolCalls.length) { - // Incrementally stream the content to make it smoother + + // If we have supported content parts, yield them first + if (supportedParts.length) { yield { role: "assistant", - content: supportedParts.length ? supportedParts : "", - ...(toolCalls.length ? { toolCalls } : {}), + content: supportedParts, }; } + + // Then process tool calls and responses in order + for (const part of processedParts) { + if (part.type === 'toolCall') { + yield { + role: "assistant", + content: "", + toolCalls: [part.data], + }; + } else if (part.type === 'tool') { + yield part.data; + } + } } else { // Handle the case where the expected data structure is not found console.warn("Unexpected response format:", data); diff --git a/core/llm/llms/Novita.ts b/core/llm/llms/Novita.ts index 2f5c61b55..55b944829 100644 --- a/core/llm/llms/Novita.ts +++ b/core/llm/llms/Novita.ts @@ -9,6 +9,8 @@ class Novita extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { + "deepseek-r1": "deepseek/deepseek-r1", + "deepseek_v3": "deepseek/deepseek_v3", "llama3-8b": "meta-llama/llama-3-8b-instruct", "llama3-70b": "meta-llama/llama-3-70b-instruct", "llama3.1-8b": "meta-llama/llama-3.1-8b-instruct", diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 41b3c755b..e0acc961e 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -49,6 +49,7 @@ const CHAT_ONLY_MODELS = [ "gpt-4o-mini", "o1-preview", "o1-mini", + "o3-mini" ]; const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => { @@ -92,8 +93,8 @@ class OpenAI extends BaseLLM { return model; } - private isO1Model(model?: string): boolean { - return !!model && model.startsWith("o1"); + private isO3orO1Model(model?: string): boolean { + return !!model && (model.startsWith("o1") || model.startsWith("o3")); } protected supportsPrediction(model: string): boolean { @@ -144,8 +145,8 @@ class OpenAI extends BaseLLM { finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); - // OpenAI o1-preview and o1-mini: - if (this.isO1Model(options.model)) { + // OpenAI o1-preview and o1-mini or o3-mini: + if (this.isO3orO1Model(options.model)) { // a) use max_completion_tokens instead of max_tokens finalOptions.max_completion_tokens = options.maxTokens; finalOptions.max_tokens = undefined; @@ -239,8 +240,8 @@ class OpenAI extends BaseLLM { ): ChatCompletionCreateParams { body.stop = body.stop?.slice(0, this.getMaxStopWords()); - // OpenAI o1-preview and o1-mini: - if (this.isO1Model(body.model)) { + // OpenAI o1-preview and o1-mini or o3-mini: + if (this.isO3orO1Model(body.model)) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; diff --git a/core/package-lock.json b/core/package-lock.json index ec82ab0cd..9c6ab8b38 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,11 +13,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.16", + "@continuedev/config-yaml": "^1.0.24", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.4.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -3038,9 +3038,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.16", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.16.tgz", - "integrity": "sha512-r3dzTvL8aQ5RrzM+FX6fF+U12/crU4wpPXgDcDloSsxiOQfu3k/shLCbNzFPW57XhLUQAmUJYSZsJbIvYrNPNA==", + "version": "1.0.24", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.24.tgz", + "integrity": "sha512-xA4tRUh9r9p3aHIXr9zl5GQd5VygEusIc7Zw7AAFCbbl6ahMB4CDcweT8+iz0UvxJ11PLYizFSygpvxu/Yl19Q==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -4218,13 +4218,34 @@ ] }, "node_modules/@modelcontextprotocol/sdk": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.0.3.tgz", - "integrity": "sha512-2as3cX/VJ0YBHGmdv3GFyTpoM8q2gqE98zh3Vf1NwnsSY0h3mvoO07MUzfygCKkWsFjcZm4otIiqD6Xh7kiSBQ==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.4.1.tgz", + "integrity": "sha512-wS6YC4lkUZ9QpP+/7NBTlVNiEvsnyl0xF7rRusLF+RsG0xDPc/zWR7fEEyhKnnNutGsDAZh59l/AeoWGwIb1+g==", "dependencies": { "content-type": "^1.0.5", + "eventsource": "^3.0.2", "raw-body": "^3.0.0", - "zod": "^3.23.8" + "zod": "^3.23.8", + "zod-to-json-schema": "^3.24.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/zod": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz", + "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.1.tgz", + "integrity": "sha512-3h08nf3Vw3Wl3PK+q3ow/lIil81IT2Oa7YpQyUUDsEWbXveMesdfK1xBd2RhCkynwZndAxixji/7SYJJowr62w==", + "peerDependencies": { + "zod": "^3.24.1" } }, "node_modules/@mozilla/readability": { @@ -8313,6 +8334,25 @@ "node": ">=0.8.x" } }, + "node_modules/eventsource": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.5.tgz", + "integrity": "sha512-LT/5J605bx5SNyE+ITBDiM3FxffBiq9un7Vx0EwMDM3vg8sWKx/tO2zC+LMqZ+smAM0F2hblaDZUVZF0te2pSw==", + "dependencies": { + "eventsource-parser": "^3.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.0.tgz", + "integrity": "sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", diff --git a/core/package.json b/core/package.json index 477290c9b..c0f7f736d 100644 --- a/core/package.json +++ b/core/package.json @@ -46,11 +46,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.16", + "@continuedev/config-yaml": "^1.0.24", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.4.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 52cffb027..64bc5f5d4 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,4 +1,10 @@ import { ConfigResult } 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 type { BrowserSerializedContinueConfig, ChatMessage, @@ -7,6 +13,7 @@ import type { ContextProviderWithParams, ContextSubmenuItem, DiffLine, + DocsIndexingDetails, FileSymbolMap, IdeSettings, LLMFullCompletionOptions, @@ -20,8 +27,6 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; -import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; export type OnboardingModes = | "Local" @@ -70,6 +75,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/reload": [undefined, ConfigResult]; "config/listProfiles": [undefined, ProfileDescription[]]; "config/openProfile": [{ profileId: string | undefined }, void]; + "config/updateSharedConfig": [SharedConfigSchema, void]; "context/getContextItems": [ { name: string; @@ -180,7 +186,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; "docs/getSuggestedDocs": [undefined, void]; "docs/initStatuses": [undefined, void]; - + "docs/getDetails": [{ startUrl: string }, DocsIndexingDetails]; addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; @@ -192,4 +198,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string }, void]; + "controlPlane/listOrganizations": [undefined, OrganizationDescription[]]; }; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 1622b4be5..e8ef70ab9 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -5,6 +5,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedProfile: [{ id: string }, void]; + didChangeSelectedOrg: [{ id: string | null }, void]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { didChangeAvailableProfiles: [{ profiles: ProfileDescription[] }, void]; diff --git a/core/protocol/messenger/index.ts b/core/protocol/messenger/index.ts index 8b7245224..fb2528ae2 100644 --- a/core/protocol/messenger/index.ts +++ b/core/protocol/messenger/index.ts @@ -21,7 +21,7 @@ export interface IMessenger< ToProtocol extends IProtocol, FromProtocol extends IProtocol, > { - onError(handler: (error: Error) => void): void; + onError(handler: (message: Message, error: Error) => void): void; send( messageType: T, data: FromProtocol[T][0], @@ -64,9 +64,9 @@ export class InProcessMessenger< (message: Message) => any >(); - protected _onErrorHandlers: ((error: Error) => void)[] = []; + protected _onErrorHandlers: ((message: Message, error: Error) => void)[] = []; - onError(handler: (error: Error) => void) { + onError(handler: (message: Message, error: Error) => void) { this._onErrorHandlers.push(handler); } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 3d871c42a..8ee0c5ae8 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -23,6 +23,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/deleteModel", "config/listProfiles", "config/openProfile", + "config/updateSharedConfig", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -52,13 +53,16 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "indexing/setPaused", "docs/getSuggestedDocs", "docs/initStatuses", + "docs/getDetails", // "completeOnboarding", "addAutocompleteModel", "profiles/switch", "didChangeSelectedProfile", + "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "controlPlane/listOrganizations", ]; // Message types to pass through from core to webview diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index e5f2844cd..c5868f3e0 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -13,9 +13,9 @@ export const searchWebTool: Tool = { "Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.", parameters: { type: "object", - required: ["repo_url"], + required: ["query"], properties: { - repo_url: { + query: { type: "string", description: "The natural language search query", }, diff --git a/core/tools/implementations/readCurrentlyOpenFile.ts b/core/tools/implementations/readCurrentlyOpenFile.ts index d0db3b60c..a55aee2bd 100644 --- a/core/tools/implementations/readCurrentlyOpenFile.ts +++ b/core/tools/implementations/readCurrentlyOpenFile.ts @@ -1,4 +1,4 @@ -import { getUriPathBasename } from "../../util/uri"; +import { getUriDescription } from "../../util/uri"; import { ToolImpl } from "."; @@ -9,13 +9,16 @@ export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { return []; } - const basename = getUriPathBasename(result.path); + const { relativePathOrBasename, last2Parts, baseName } = getUriDescription( + result.path, + await extras.ide.getWorkspaceDirs(), + ); return [ { - name: "Current file", - description: basename, - content: `\`\`\`${basename}\n${result.contents}\n\`\`\``, + name: `Current file: ${baseName}`, + description: last2Parts, + content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``, uri: { type: "file", value: result.path, diff --git a/core/tools/implementations/viewRepoMap.ts b/core/tools/implementations/viewRepoMap.ts index 69f624feb..9d7c44809 100644 --- a/core/tools/implementations/viewRepoMap.ts +++ b/core/tools/implementations/viewRepoMap.ts @@ -5,7 +5,7 @@ import { ToolImpl } from "."; export const viewRepoMapImpl: ToolImpl = async (args, extras) => { const repoMap = await generateRepoMap(extras.llm, extras.ide, { outputRelativeUriPaths: true, - includeSignatures: false, + includeSignatures: true, }); return [ { diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 9f452a90f..aa1b66fcf 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,11 +1,21 @@ import fs from "node:fs"; +import { + salvageSharedConfig, + sharedConfigSchema, + SharedConfigSchema, +} from "../config/sharedConfig"; + import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { indexingPaused: boolean; selectedTabAutocompleteModel: string; lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string }; + lastSelectedOrgIdForWorkspace: { + [workspaceIdentifier: string]: string | null; + }; + /** * This is needed to handle the case where a JetBrains user has created * docs embeddings using one provider, and then updates to a new provider. @@ -15,7 +25,8 @@ export type GlobalContextType = { hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; - isSupportedLanceDbCpuTargetForLinux: boolean; + isSupportedLanceDbCpuTarget: boolean; + sharedConfig: SharedConfigSchema; }; /** @@ -26,9 +37,10 @@ export class GlobalContext { key: T, value: GlobalContextType[T], ) { - if (!fs.existsSync(getGlobalContextFilePath())) { + const filepath = getGlobalContextFilePath(); + if (!fs.existsSync(filepath)) { fs.writeFileSync( - getGlobalContextFilePath(), + filepath, JSON.stringify( { [key]: value, @@ -38,7 +50,7 @@ export class GlobalContext { ), ); } else { - const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); + const data = fs.readFileSync(filepath, "utf-8"); let parsed; try { @@ -49,21 +61,19 @@ export class GlobalContext { } parsed[key] = value; - fs.writeFileSync( - getGlobalContextFilePath(), - JSON.stringify(parsed, null, 2), - ); + fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2)); } } get( key: T, ): GlobalContextType[T] | undefined { - if (!fs.existsSync(getGlobalContextFilePath())) { + const filepath = getGlobalContextFilePath(); + if (!fs.existsSync(filepath)) { return undefined; } - const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); + const data = fs.readFileSync(filepath, "utf-8"); try { const parsed = JSON.parse(data); return parsed[key]; @@ -72,4 +82,31 @@ export class GlobalContext { return undefined; } } + + getSharedConfig(): SharedConfigSchema { + const sharedConfig = this.get("sharedConfig") ?? {}; + const result = sharedConfigSchema.safeParse(sharedConfig); + if (result.success) { + return result.data; + } else { + // in case of damaged shared config, repair it + // Attempt to salvage any values that are security concerns + console.error("Failed to load shared config, salvaging...", result.error); + const salvagedConfig = salvageSharedConfig(sharedConfig); + this.update("sharedConfig", salvagedConfig); + return salvagedConfig; + } + } + + updateSharedConfig( + newValues: Partial, + ): SharedConfigSchema { + const currentSharedConfig = this.getSharedConfig(); + const updatedSharedConfig = { + ...currentSharedConfig, + ...newValues, + }; + this.update("sharedConfig", updatedSharedConfig); + return updatedSharedConfig; + } } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index be33346e7..3c6963071 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -55,7 +55,6 @@ class FileSystemIde implements IDE { enableControlServerBeta: false, continueTestEnvironment: "none", pauseCodebaseIndexOnStart: false, - enableDebugLogs: false, }; } async getGitHubAuthToken(args: GetGhTokenArgs): Promise { diff --git a/core/util/index.test.ts b/core/util/index.test.ts index 74ee3ccc8..fc48a49b2 100644 --- a/core/util/index.test.ts +++ b/core/util/index.test.ts @@ -207,7 +207,7 @@ World it("should handle strings with only whitespace", () => { const result = dedent` - + `; expect(result).toBe(""); }); @@ -249,9 +249,9 @@ World it("should handle a string with only one non-empty line", () => { const result = dedent` - + Hello World! - + `; expect(result).toBe("Hello World!"); }); @@ -373,11 +373,16 @@ describe("getMarkdownLanguageTagForFile", () => { expect(getMarkdownLanguageTagForFile("test.py")).toBe("python"); expect(getMarkdownLanguageTagForFile("test.tsx")).toBe("tsx"); expect(getMarkdownLanguageTagForFile("test.java")).toBe("java"); + expect(getMarkdownLanguageTagForFile("test.class")).toBe("java"); expect(getMarkdownLanguageTagForFile("test.md")).toBe("markdown"); expect(getMarkdownLanguageTagForFile("test.sh")).toBe("shell"); expect(getMarkdownLanguageTagForFile("test.sql")).toBe("sql"); }); + it("should sanitize ranges from the extension", () => { + expect(getMarkdownLanguageTagForFile("test.java (1-5)")).toBe("java"); + }); + it("should return the extension if not in the known list", () => { expect(getMarkdownLanguageTagForFile("file.unknownext")).toBe("unknownext"); }); diff --git a/core/util/index.ts b/core/util/index.ts index 04dc6d567..4cb0f4920 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -74,6 +74,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string { tsx: "tsx", ts: "typescript", java: "java", + class:"java", //.class files decompile to Java go: "go", rb: "ruby", rs: "rust", @@ -96,17 +97,28 @@ export function getMarkdownLanguageTagForFile(filepath: string): string { ps1: "powershell", }; - const ext = filepath.split(".").pop(); + const ext = sanitizeExtension(filepath.split(".").pop()); return ext ? (extToLangMap[ext] ?? ext) : ""; } + +function sanitizeExtension(ext?: string): string|undefined { + if (ext) { + //ignore ranges in extension eg. "java (11-23)" + const match = ext.match(/^(\S+)\s*(\(.*\))?$/); + if (match) { + ext = match[1]; + } + } + return ext; +} + export function copyOf(obj: any): any { if (obj === null || obj === undefined) { return obj; } return JSON.parse(JSON.stringify(obj)); } -``; export function deduplicateArray( array: T[], diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index 1e9c52490..a00e869dd 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -11,7 +11,7 @@ export async function isOllamaInstalled(): Promise { }); } -export async function startLocalOllama(ide: IDE): Promise { +export async function startLocalOllama(ide: IDE): Promise { let startCommand: string | undefined; switch (process.platform) { @@ -20,16 +20,16 @@ export async function startLocalOllama(ide: IDE): Promise { break; case "win32"://Windows - startCommand = `& "ollama app.exe"\n`; + startCommand = "& \"ollama app.exe\"\n"; break; default: //Linux... - const start_script_path = path.resolve(__dirname, './start_ollama.sh'); + const start_script_path = path.resolve(__dirname, "./start_ollama.sh"); if (await ide.fileExists(`file:/${start_script_path}`)) { startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`; console.log(`Ollama Linux startup script at : ${start_script_path}`); } else { - ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`) + return ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`) } } if (startCommand) { diff --git a/core/util/parameters.ts b/core/util/parameters.ts index a7a11b503..648253712 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -2,7 +2,6 @@ import { TabAutocompleteOptions } from "../index.js"; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, - useFileSuffix: true, maxPromptTokens: 1024, prefixPercentage: 0.3, maxSuffixPercentage: 0.2, diff --git a/core/util/paths.ts b/core/util/paths.ts index 836bc84b9..1198dec49 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -74,6 +74,10 @@ export function getGlobalContextFilePath(): string { return path.join(getIndexFolderPath(), "globalContext.json"); } +export function getSharedConfigFilePath(): string { + return path.join(getContinueGlobalPath(), "sharedConfig.json"); +} + export function getSessionFilePath(sessionId: string): string { return path.join(getSessionsFolderPath(), `${sessionId}.json`); } diff --git a/core/util/uri.ts b/core/util/uri.ts index a1bcd7745..13d7956ac 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -177,3 +177,19 @@ export function getLastNPathParts(filepath: string, n: number): string { } return filepath.split(/[\\/]/).slice(-n).join("/"); } + +export function getUriDescription(uri: string, dirUriCandidates: string[]) { + const { relativePathOrBasename, foundInDir } = findUriInDirs( + uri, + dirUriCandidates, + ); + const baseName = getUriPathBasename(uri); + const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2); + return { + uri, + relativePathOrBasename, + foundInDir, + last2Parts, + baseName, + }; +} diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 81d33967b..0541bf464 100644 --- a/docs/docs/actions/how-to-customize.md +++ b/docs/docs/actions/how-to-customize.md @@ -50,6 +50,7 @@ export function modifyConfig(config: Config): Config { return config; } ``` + @@ -57,4 +58,4 @@ export function modifyConfig(config: Config): Config { Currently the other action triggers are not open for configuration, but we plan to allow this via .prompt files in the future. - + diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index e7e6ca94a..327f780d0 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -99,6 +99,21 @@ If you prefer to use a model from [OpenAI](../customize/model-providers/top-leve ] ``` +### Grok-2 from xAI + +If you prefer to use a model from [xAI](../customize/model-providers/top-level/xAI.md), then we recommend Grok-2. + +```json title="config.json" + "models": [ + { + "title": "Grok-2", + "provider": "xAI", + "model": "grok-2-latest", + "apiKey": "[XAI_API_KEY]" + } + ] +``` + ### Gemini 1.5 Pro from Google If you prefer to use a model from [Google](../customize/model-providers/top-level/gemini.md), then we recommend Gemini 1.5 Pro. diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 13b86c51d..8d90f2145 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `disable`: Disable autocomplete (can also be done from IDE settings) (default: `false`) - `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) (default: `true`) - `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) (default: `1024`) - `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) (default: `0.3`) - `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) (default: `0.2`) @@ -68,7 +67,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". (default: `auto`) - `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. (default: `true`) - `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. (default: `[]`) -- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). ### Full example diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index e2e2b91d1..05fac6842 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -10,7 +10,7 @@ Continue can be deeply customized. User-level configuration is stored and can be - `~/.continue/config.json` (MacOS / Linux) - `%USERPROFILE%\.continue\config.json` (Windows) -To open `config.json`, 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. +To open `config.json`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open [your config location]` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. When you save `config.json`, Continue will automatically refresh to take into account your changes. `config.json` is automatically created the first time you use Continue. `config.json` is automatically generated if it doesn't exist. diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index 31cd8b4b8..f06de9fe4 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -153,13 +153,7 @@ 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 `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. - -```json title="config.json" -"experimental": { - "useChromiumForDocsCrawling": true -} -``` +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. Further notes: @@ -232,7 +226,6 @@ The following configuration example includes: - A custom embeddings provider - A reranker model available, with reranking parameters customized - A Github token to enable Github crawling -- Chromium enabled as a backup for private documentation ```json title="config.json" { @@ -270,9 +263,8 @@ The following configuration example includes: "embeddingsProvider": { "provider": "lmstudio", "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" - }, - "experimental": { - "useChromiumForDocsCrawling": true } } ``` + +This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../settings.md). diff --git a/docs/docs/customize/model-providers/more/asksage.md b/docs/docs/customize/model-providers/more/asksage.md index e21133cb8..204d29421 100644 --- a/docs/docs/customize/model-providers/more/asksage.md +++ b/docs/docs/customize/model-providers/more/asksage.md @@ -60,6 +60,7 @@ The current Models available provided by Ask Sage are: | 8 | GPT-4-32K | Yes | ✅ | | 9 | GPT-o1 | Yes | ✅ | | 10 | GPT-o1-mini | Yes | ✅ | +| 10 | GPT-o3-mini | Yes | ✅ | | 11 | GPT-3.5-turbo | Yes | ✅ | | 12 | Calude 3.5 Sonnet Gov | Yes | ✅ | | 13 | Calude 3 Opus | Yes | ✅ | diff --git a/docs/docs/customize/model-providers/more/groq.md b/docs/docs/customize/model-providers/more/groq.md index 54e678abc..fa5bac12f 100644 --- a/docs/docs/customize/model-providers/more/groq.md +++ b/docs/docs/customize/model-providers/more/groq.md @@ -1,5 +1,11 @@ # Groq +:::info + +Check if your chosen model is still supported by referring to the [model documentation](https://console.groq.com/docs/models). If a model has been deprecated, you may encounter a 404 error when attempting to use it. + +::: + Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. 1. Obtain an API key [here](https://console.groq.com/keys) @@ -9,9 +15,9 @@ Groq provides the fastest available inference for open-source language models, i { "models": [ { - "title": "Llama 3.1 405b", + "title": "Llama 3.3 70b Versatile", "provider": "groq", - "model": "llama3.1-405b", + "model": "llama-3.3-70b-versatile", "apiKey": "" } ] diff --git a/docs/docs/customize/model-providers/top-level/xAI.md b/docs/docs/customize/model-providers/top-level/xAI.md index fbdfa83ad..550cc0641 100644 --- a/docs/docs/customize/model-providers/top-level/xAI.md +++ b/docs/docs/customize/model-providers/top-level/xAI.md @@ -11,15 +11,15 @@ You can get an API key from the [xAI console](https://console.x.ai/) ## Chat model -We recommend configuring **grok-beta** as your chat model. +We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). ```json title="config.json" { "models": [ { - "title": "Grok Beta", + "title": "Grok 2", "provider": "xAI", - "model": "grok-beta", + "model": "grok-2-latest", "apiKey": "[API_KEY]" } ] diff --git a/docs/docs/customize/model-types/chat.md b/docs/docs/customize/model-types/chat.md index fb6a91f15..d94f2ce2d 100644 --- a/docs/docs/customize/model-types/chat.md +++ b/docs/docs/customize/model-types/chat.md @@ -14,5 +14,6 @@ If you have the ability to use any model, we recommend [Claude 3.5 Sonnet](../mo Otherwise, some of the next best options are: - [GPT-4o](../model-providers/top-level/openai.md) +- [Grok-2](../model-providers/top-level/xAI.md) - [Gemini 1.5 Pro](../model-providers/top-level/gemini.md) - [Llama3.1 405B](../tutorials/llama3.1.md) diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 83e479132..80c18846a 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -6,22 +6,22 @@ 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-types) . -- **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). +- **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-types) . +- **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). Whatever you choose, you'll probably start by editing `config.json`. ## Editing config.json -Most custom configuration is done by editing `config.json`. This file is a JSON file that allows you to customize Continue to your liking. It is found at: +Most custom configuration is done by editing `config.json`. This file is a JSON file that allows you to customize Continue to your liking. It is found at: - MacOS and Linux: `~/.continue/config.json` - Windows: `%USERPROFILE%\.continue\config.json` -You can easily access `config.json` 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 the bottom right corner. +You can easily access `config.json` 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 [your config profile]`. ![configure-continue](/img/configure-continue.png) @@ -29,7 +29,7 @@ When editing this file, you can see the available options suggested as you type, :::info -`config.json` 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. +`config.json` 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. ::: diff --git a/docs/docs/customize/settings.md b/docs/docs/customize/settings.md new file mode 100644 index 000000000..0d917df6e --- /dev/null +++ b/docs/docs/customize/settings.md @@ -0,0 +1,34 @@ +--- +title: User Settings Page +description: Reference for Adjusting User-Specific Settings +keywords: [config, settings, configuration, customize, customization, sidebar] +--- + +# The User Settings Page + +The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar. + +![slash-commands](/img/header-buttons.png) + +Which takes you to this page: + +![User Settings Page](/img/settings-page.png) + +Click the `Open Config File` 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: + +- `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` +- `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 +- `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/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md index e2ac72986..bd40ad585 100644 --- a/docs/docs/customize/tutorials/llama3.1.md +++ b/docs/docs/customize/tutorials/llama3.1.md @@ -32,6 +32,12 @@ Ollama is the fastest way to get up and running with local language models. We r ## Groq +:::info + +Check if your chosen model is still supported by referring to the [model documentation](https://console.groq.com/docs/models). If a model has been deprecated, you may encounter a 404 error when attempting to use it. + +::: + Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family. 1. Obtain an API key [here](https://console.groq.com/keys) @@ -41,9 +47,9 @@ Groq provides the fastest available inference for open-source language models, i { "models": [ { - "title": "Llama 3.1 405b", + "title": "Llama 3.3 70b Versatile", "provider": "groq", - "model": "llama3.1-405b", + "model": "llama-3.3-70b-versatile", "apiKey": "" } ] diff --git a/docs/docs/customize/tutorials/running-continue-without-internet.md b/docs/docs/customize/tutorials/running-continue-without-internet.md index c945f8c43..277272767 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 `~/.continue/config.json` and set `"allowAnonymousTelemetry": false`. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). +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). 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` take effect. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 809d4d1c4..a14da2944 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -16,9 +16,9 @@ Each model has specific configuration options tailored to its provider and funct **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`, etc., see intelliJ suggestions. +- `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, and Cohere. +- `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. @@ -83,16 +83,12 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useFileSuffix`: If `true`, includes file suffix in the prompt (default: `true`). - `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. -- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`) (default: `auto`). -- `useCache`: If `true`, caches completions (default: `true`). - `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). -- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled (default: `[]`). Example @@ -341,42 +337,6 @@ Example } ``` -### `disableSessionTitles` - -Prevents generating summary titles for each chat session when set to `true`. - -Note that if the deprecated setting `ui.getChatTitles` is set to `false`, it will override this. - -### `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. @@ -385,10 +345,6 @@ An optional token that identifies the user, primarily for authenticated services Defines a system message that appears before every response from the language model, providing guidance or context. -### `disableIndexing` - -Prevents indexing of the codebase, useful primarily for debugging purposes. - ### `experimental` Several experimental config parameters are available, as described below: @@ -400,8 +356,6 @@ Several experimental config parameters are available, as described below: - `inlineEdit`: Model title for inline edits. - `applyCodeBlock`: Model title for applying code blocks. - `repoMapFileSelection`: Model title for repo map selections. -- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. -- `promptPath`: Change the path to custom prompt files from the default ".prompts" - `quickActions`: Array of custom quick actions - `title` (**required**): Display title for the quick action. - `prompt` (**required**): Prompt for quick action. @@ -411,7 +365,6 @@ Several experimental config parameters are available, as described below: - `docstring`: Prompt for adding docstrings. - `fix`: Prompt for fixing code. - `optimize`: Prompt for optimizing code. -- `useChromiumForDocsCrawling`: 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`.. - `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol) Example @@ -422,7 +375,6 @@ Example "modelRoles": { "inlineEdit": "Edit Model" }, - "promptPath": "custom/.prompts", "quickActions": [ { "title": "Tags", @@ -433,8 +385,6 @@ Example "contextMenuPrompts": { "fixGrammar": "Fix grammar in the above but allow for typos." }, - "readResponseTTS": false, - "useChromiumForDocsCrawling": true, "modelContextProtocolServers": [ { "transport": { @@ -447,3 +397,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/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 8e7152d01..3d59ebf74 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -26,26 +26,6 @@ The following usage information is collected and reported: ## How to Opt Out -You can disable anonymous telemetry by modifying the `config.json` file located in the `~/.continue` directory. This file typically includes the following entry: +You can disable anonymous telemetry by visiting the [User Settings Page](./customize/settings.md) and toggling "Allow Anonymous Telemetry" off. -```json title="config.json" -{ - "allowAnonymousTelemetry": true -} -``` - -To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box. - -### Steps to Disable Telemetry via Configuration File - -1. Open the `~/.continue/config.json` file in your text editor. -2. Locate the `"allowAnonymousTelemetry"` setting. -3. Change the value from `true` to `false`. -4. Save the file. - -### Steps to Disable Telemetry via VS Code Settings - -1. Open VS Code. -2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). -3. In the search bar, type "Continue: Telemetry Enabled". -4. Uncheck the "Continue: Telemetry Enabled" checkbox. +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). diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index d4bbe69db..52dc785b2 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -118,6 +118,12 @@ By default the Continue window is on the left side of VS Code, but it can be dra If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists. +### I'm getting a 404 error from OpenRouter + +If you have entered a valid API key and model, but are still getting a 404 error from OpenRouter, this may be because models that do not support function calling will return an error to Continue when a request is sent. +Example error: +`HTTP 404 Not Found from https://openrouter.ai/api/v1/chat/completions` + ### Indexing issues If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time. diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index ad62efaa7..04f1b4e15 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -151,8 +151,8 @@ Note that the `repoMapFileSelection` experimental model role has been deprecated The JSON `contextProviders` field is replaced by the YAML `context` array. -- JSON `name` maps to `uses` -- JSON `params` map to `with` +- JSON `name` maps to `provider` +- JSON `params` map to `params` **Before** @@ -181,14 +181,14 @@ The JSON `contextProviders` field is replaced by the YAML `context` array. ```yaml title="config.yaml" context: - - uses: docs + - provider: docs - - uses: codebase - with: + - provider: codebase + params: nRetrieve: 30 nFinal: 3 - - uses: diff + - params: diff ``` ### System Message @@ -327,20 +327,27 @@ mcpServers: ## Deprecated configuration options -The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI +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`. + +See the [JSON Config Reference](./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: - Slash commands (JSON `slashCommands`) - top-level `requestOptions` - top-level `completionOptions` - `tabAutocompleteOptions` + - `disable` + - `maxPromptTokens` + - `debounceDelay` + - `maxSuffixPercentage` + - `prefixPercentage` + - `template` + - `onlyMyCode` - `analytics` - `customCommands` -- `disableSessionTitles` - `experimental` -- `allowAnonymousTelemetry` (moved to user/IDE level) -- `ui` (moved to user/IDE level) - `userToken` -- `disableIndexing` (moved to user/IDE level) ## New Configuration options diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index b273353a4..e504c95fd 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -6,7 +6,7 @@ keywords: [config, yaml, configuration, customize, customization] # Config YAML Reference - + Continue can be configured using a YAML file `config.yaml` which for local configuration can be placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) @@ -23,7 +23,6 @@ Config YAML does not work alongside `config.json` - it replaces it. View the **[ The top-level properties in the `config.yaml` configuration file are: - [`name`](#name) (**required**) - - [`version`](#version) (**required**) - [`models`](#models) - [`context`](#context) @@ -120,22 +119,22 @@ More information about usage/params for each context provider can be found [here **Properties:** -- `uses` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). -- `with`: Optional parameters to configure the context provider's behavior. +- `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: - - uses: files - - uses: code - - uses: codebase - with: + - provider: files + - provider: code + - provider: codebase + params: nFinal: 10 - - uses: docs - - uses: diff - - uses: folder - - uses: terminal + - provider: docs + - provider: diff + - provider: folder + - provider: terminal ``` --- @@ -301,12 +300,12 @@ prompts: 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. context: - - uses: diff - - uses: file - - uses: codebase - - uses: code - - uses: docs - with: + - provider: diff + - provider: file + - provider: codebase + - provider: code + - provider: docs + params: startUrl: https://docs.example.com/introduction maxDepth: 3 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index 15cb94c4d..985a66809 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ ollama run starcoder2:3b - `disable`: 禁用自动补全(也可以在 IDE 配置中完成) - `template`: 一个用来自动补全的可选的模板字符串。它使用 Mustache 模板语言渲染,并且传递 'prefix' 和 'suffix' 变量。(字符串) -- `useFileSuffix`: 决定是否使用文件后缀在提示词中。(布尔型) - `maxPromptTokens`: 提示词使用的 token 的最大数量。一个较小的数字生成较快的补全,但是较少的上下文。(数字) - `prefixPercentage`: 输入专注于前缀的百分比。(数字) - `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md index 86a998b5b..98addf212 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -83,7 +83,6 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useFileSuffix`: If `true`, includes file suffix in the prompt (default: `true`). - `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`). diff --git a/docs/sidebars.js b/docs/sidebars.js index c5026b1ef..380377f8a 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -132,12 +132,13 @@ const sidebars = { }, ], }, - "customize/changelog", + "customize/settings", { type: "link", label: "Reference", href: "/reference", }, + "customize/changelog", // { // type: "link", // label: "YAML Reference", diff --git a/docs/static/img/header-buttons.png b/docs/static/img/header-buttons.png new file mode 100644 index 000000000..f6a644d03 Binary files /dev/null and b/docs/static/img/header-buttons.png differ diff --git a/docs/static/img/settings-page.png b/docs/static/img/settings-page.png new file mode 100644 index 000000000..f4b58cfd5 Binary files /dev/null and b/docs/static/img/settings-page.png differ diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 1d62950bc..7028aa723 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=0.0.86 +pluginVersion=0.0.87 # 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 852fb4f02..b93d294e1 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 @@ -120,8 +120,9 @@ class ViewHistoryAction : AnAction() { class OpenConfigAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return - val params = mapOf("profileId" to null) - continuePluginService.coreMessenger?.request("config/openProfile", params, null) { _ -> } + continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() + val params = mapOf("path" to "/config", "toggle" to true) + continuePluginService.sendToWebview("navigateTo", params) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 72819421a..bae7857a4 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -47,7 +47,15 @@ fun showTutorial(project: Project) { throw IOException("Resource not found: $tutorialFileName") } var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8) + + // All jetbrains will use J instead of L + content = content.replace("[Cmd + L]", "[Cmd + J]") + content = content.replace("[Cmd + Shift + L]", "[Cmd + Shift + J]") + if (!System.getProperty("os.name").lowercase().contains("mac")) { + content = content.replace("[Cmd + J]", "[Ctrl + J]") + content = content.replace("[Cmd + Shift + J]", "[Ctrl + Shift + J]") + content = content.replace("[Cmd + I]", "[Ctrl + I]") content = content.replace("⌘", "⌃") } val filepath = Paths.get(getContinueGlobalPath(), tutorialFileName).toString() 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 66910bced..d3f69bc7a 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 @@ -80,6 +80,7 @@ class MessageTypes { "config/deleteModel", "config/listProfiles", "config/openProfile", + "config/updateSharedConfig", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -115,8 +116,11 @@ class MessageTypes { "addAutocompleteModel", "profiles/switch", "didChangeSelectedProfile", + "didChangeSelectedOrg", "tools/call", - "controlPlane/openUrl" + "controlPlane/openUrl", + "controlPlane/listOrganizations" + ) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 0a0b6b83a..efffc54ee 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -54,8 +54,22 @@ class IdeProtocolClient( val messageType = message.messageType val dataElement = message.data + // A couple oddball messages respond directly to GUI, expect a different message format + // e.g. jetbrains/isOSREnabled + fun respondToWebview(content: Any) { + respond(mutableMapOf( + "done" to true, + "status" to "success", + "content" to content + )) + } + try { when (messageType) { + "toggleDevTools" -> { + continuePluginService.continuePluginWindow?.browser?.browser?.openDevtools() + } + "showTutorial" -> { showTutorial(project) } @@ -63,12 +77,12 @@ class IdeProtocolClient( "jetbrains/isOSREnabled" -> { val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR - respond(isOSREnabled) + respondToWebview(isOSREnabled) } "jetbrains/getColors" -> { val colors = GetTheme().getTheme(); - respond(colors) + respondToWebview(colors) } "jetbrains/onLoad" -> { @@ -78,7 +92,7 @@ class IdeProtocolClient( "vscMachineId" to getMachineUniqueID(), "vscMediaUrl" to "http://continue", ) - respond(jsonData) + respondToWebview(jsonData) } "getIdeSettings" -> { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index d30a5d5fe..4482aa5fe 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -94,7 +94,7 @@ class IntelliJIDE( userToken = settings.continueState.userToken ?: "", enableControlServerBeta = settings.continueState.enableContinueTeamsBeta, pauseCodebaseIndexOnStart = false, // TODO: Needs to be implemented - enableDebugLogs = false // TODO: Needs to be implemented + continueTestEnvironment = "none" ) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index ce548e5f5..7430f2bcb 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -98,6 +98,7 @@ open class ContinueExtensionSettings : PersistentStateComponent - - + text="Continue Config" + description="Continue Config"> + - + diff --git a/extensions/intellij/src/main/resources/continue_tutorial.java b/extensions/intellij/src/main/resources/continue_tutorial.java index 41ac854c0..e566b14ce 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.java +++ b/extensions/intellij/src/main/resources/continue_tutorial.java @@ -1,17 +1,24 @@ -/* _________ _____ _____ - __ ____/______ _______ __ /____(_)_______ ____ _______ - _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ - / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ - \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// _________ _____ _____ +// __ ____/______ _______ __ /____(_)_______ ____ _______ +// _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ +// / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ +// \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// +// Chat, Edit, and Autocomplete tutorial +// - Chat, Edit, and Autocomplete tutorial -*/ +// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- +// First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon. -/* ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— */ +// See an example at https://docs.continue.dev/getting-started/install + +// Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. + +// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + J] to add to Chat +// Press [Cmd + L] to add to Chat // Try asking Continue "what sorting algorithm is this?" public static int[] sortingAlgorithm(int[] x) { for (int i = 0; i < x.length; i++) { @@ -26,10 +33,13 @@ public static int[] sortingAlgorithm(int[] x) { return x; } -/* ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— */ +// [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L]. +// This will add the code into the current chat + +// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + I] to Edit +// Press [Cmd + I] to Edit // Try asking Continue to "make this more readable" public static int[] sortingAlgorithm2(int[] x) { for (int i = 0; i < x.length; i++) { @@ -44,12 +54,15 @@ public static int[] sortingAlgorithm2(int[] x) { return x; } -/* ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— */ +// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— -// Place cursor after `sortingAlgorithm...` below and press [Enter] +// Place cursor after `sortingAlgorithm:` below and press [Enter] // Press [Tab] to accept the Autocomplete suggestion -// Basic assertion for sortingAlgorithm... +// Basic assertion for sortingAlgorithm: -/* —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— */ + +// —————————————————————————————————————————————- Learn More -—————————————————————————————————————————————— + +// Visit the Continue Docs at https://docs.continue.dev/getting-started/overview diff --git a/extensions/intellij/src/main/resources/continue_tutorial.py b/extensions/intellij/src/main/resources/continue_tutorial.py index 16a297c16..4670772df 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.py +++ b/extensions/intellij/src/main/resources/continue_tutorial.py @@ -7,11 +7,18 @@ Chat, Edit, and Autocomplete tutorial """ +# ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- -# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— # +# First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon. + +# See an example at https://docs.continue.dev/getting-started/install + +# Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. + +# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— ## Highlight the code below -## Press [Cmd/Ctrl + J] to add to Chat +## Press [Cmd + L] to add to Chat ## Try asking Continue "what sorting algorithm is this?" def sorting_algorithm(x): for i in range(len(x)): @@ -20,11 +27,13 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x +# [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L]. +# This will add the code into the current chat -# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— # +# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— ## Highlight the code below -## Press [Cmd/Ctrl + I] to Edit +## Press [Cmd + I] to Edit ## Try asking Continue to "make this more readable" def sorting_algorithm(x): for i in range(len(x)): @@ -33,12 +42,16 @@ def sorting_algorithm(x): x[j], x[j + 1] = x[j + 1], x[j] return x -# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— # +# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— -## Place cursor after `sorting_algorithm...` below and press [Enter] +## Place cursor after `sorting_algorithm:` below and press [Enter] ## Press [Tab] to accept the Autocomplete suggestion -# Basic assertion for sorting_algorithm... +# Basic assertion for sorting_algorithm: -# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— # + + +# —————————————————————————————————————————————- Learn More -—————————————————————————————————————————————— + +# Visit the Continue Docs at https://docs.continue.dev/getting-started/overview diff --git a/extensions/intellij/src/main/resources/continue_tutorial.ts b/extensions/intellij/src/main/resources/continue_tutorial.ts index 301fc248c..4cde323ca 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.ts +++ b/extensions/intellij/src/main/resources/continue_tutorial.ts @@ -1,17 +1,24 @@ -/* _________ _____ _____ - __ ____/______ _______ __ /____(_)_______ ____ _______ - _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ - / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ - \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// _________ _____ _____ +// __ ____/______ _______ __ /____(_)_______ ____ _______ +// _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ +// / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ +// \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ +// +// Chat, Edit, and Autocomplete tutorial +// - Chat, Edit, and Autocomplete tutorial -*/ +// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- +// First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon. -/* ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— */ +// See an example at https://docs.continue.dev/getting-started/install + +// Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. + +// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + J] to add to Chat +// Press [Cmd + L] to add to Chat // Try asking Continue "what sorting algorithm is this?" function sortingAlgorithm(x: number[]): number[] { for (let i = 0; i < x.length; i++) { @@ -26,10 +33,13 @@ function sortingAlgorithm(x: number[]): number[] { return x; } -/* ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— */ +// [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L]. +// This will add the code into the current chat + +// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— // Highlight the code below -// Press [Cmd/Ctrl + I] to Edit +// Press [Cmd + I] to Edit // Try asking Continue to "make this more readable" function sortingAlgorithm2(x: number[]): number[] { for (let i = 0; i < x.length; i++) { @@ -44,12 +54,13 @@ function sortingAlgorithm2(x: number[]): number[] { return x; } -/* ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— */ +// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— -// Place cursor after `sortingAlgorithm...` below and press [Enter] +// Place cursor after `sortingAlgorithm:` below and press [Enter] // Press [Tab] to accept the Autocomplete suggestion -// Basic assertion for sortingAlgorithm... +// Basic assertion for sortingAlgorithm: +// —————————————————————————————————————————————- Learn More -—————————————————————————————————————————————— -/* —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— */ +// Visit the Continue Docs at https://docs.continue.dev/getting-started/overview diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 1273a7c40..827662dd2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -998,6 +998,8 @@ "anyOf": [ { "enum": [ + "deepseek-r1", + "deepseek_v3", "llama3-8b", "llama3-70b", "llama3.1-8b", @@ -3080,10 +3082,6 @@ "description": "Disable tab autocomplete. This can also be done from the IDE settings.", "default": false }, - "useFileSuffix": { - "type": "boolean", - "description": "Determines whether to use the file suffix in the prompt." - }, "maxPromptTokens": { "type": "number", "description": "The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context." diff --git a/extensions/vscode/e2e/test-continue-yaml/config.yaml b/extensions/vscode/e2e/test-continue-yaml/config.yaml index 487cdc8dd..5de426a94 100644 --- a/extensions/vscode/e2e/test-continue-yaml/config.yaml +++ b/extensions/vscode/e2e/test-continue-yaml/config.yaml @@ -69,8 +69,8 @@ models: - apply context: - - uses: docs - - uses: diff - - uses: url - - uses: folder - - uses: terminal + - provider: docs + - provider: diff + - provider: url + - provider: folder + - provider: terminal diff --git a/extensions/vscode/e2e/tests/Edit.test.ts b/extensions/vscode/e2e/tests/Edit.test.ts index e79dd010c..66b82aaf3 100644 --- a/extensions/vscode/e2e/tests/Edit.test.ts +++ b/extensions/vscode/e2e/tests/Edit.test.ts @@ -1,19 +1,15 @@ +import { expect } from "chai"; import { - EditorView, WebView, - WebDriver, - Key, VSBrowser, - InputBox, TextEditor, - Workbench, + CodeLens, } from "vscode-extension-tester"; import { EditActions } from "../actions/Edit.actions"; import { GlobalActions } from "../actions/Global.actions"; import { GUIActions } from "../actions/GUI.actions"; import { DEFAULT_TIMEOUT } from "../constants"; -import { EditSelectors } from "../selectors/Edit.selectors"; import { GUISelectors } from "../selectors/GUI.selectors"; import { TestUtils } from "../TestUtils"; @@ -58,9 +54,27 @@ describe("Edit Test", () => { afterEach(async function () { this.timeout(DEFAULT_TIMEOUT.XL); + await editor.clearText(); + + ({ view } = await GUIActions.switchToReactIframe()); + + const tipTapEditor = await GUISelectors.getMessageInputFieldAtIndex( + view, + 0, + ); + await tipTapEditor.clear(); }); + async function getCodeLensWithRetry(editor: TextEditor, text: string) { + let codeLens: CodeLens | undefined; + await TestUtils.waitForSuccess(async () => { + codeLens = await editor.getCodeLens(text); + expect(codeLens).to.not.be.undefined; + }, DEFAULT_TIMEOUT.SM); + return codeLens; + } + it("Accepts an Edit in the GUI", async () => { ({ view } = await GUIActions.switchToReactIframe()); @@ -68,14 +82,14 @@ describe("Edit Test", () => { await view.switchBack(); - const editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => { + const editorText = await editor.getText(); - await TestUtils.waitForSuccess( - async () => + expect( !editorText.includes(originalEditorText) && - editorText.includes(llmResponse), - DEFAULT_TIMEOUT.SM, - ); + editorText.includes(llmResponse), + ).to.be.true; + }, DEFAULT_TIMEOUT.SM); }).timeout(DEFAULT_TIMEOUT.XL); it("Rejects an Edit in the GUI", async () => { @@ -85,41 +99,41 @@ describe("Edit Test", () => { await view.switchBack(); - const editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => { + const editorText = await editor.getText(); - await TestUtils.waitForSuccess( - async () => + expect( editorText.includes(originalEditorText) && - !editorText.includes(llmResponse), - DEFAULT_TIMEOUT.SM, - ); + !editorText.includes(llmResponse), + ).to.be.true; + }, DEFAULT_TIMEOUT.SM); }).timeout(DEFAULT_TIMEOUT.XL); it("Accepts an Edit using CodeLens buttons", async () => { const acceptCodeLens = await editor.getCodeLens("Accept"); await acceptCodeLens?.click(); - const editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => { + const editorText = await editor.getText(); - await TestUtils.waitForSuccess( - async () => + expect( !editorText.includes(originalEditorText) && - editorText.includes(llmResponse), - DEFAULT_TIMEOUT.SM, - ); + editorText.includes(llmResponse), + ).to.be.true; + }, DEFAULT_TIMEOUT.SM); }).timeout(DEFAULT_TIMEOUT.XL); - it("Rejects an Edit using CodeLens buttons", async () => { - const rejectCodeLens = await editor.getCodeLens("Reject"); + it.only("Rejects an Edit using CodeLens buttons", async () => { + const rejectCodeLens = await getCodeLensWithRetry(editor, "Reject"); await rejectCodeLens?.click(); - const editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => { + const editorText = await editor.getText(); - await TestUtils.waitForSuccess( - async () => - !editorText.includes(originalEditorText) && - editorText.includes(llmResponse), - DEFAULT_TIMEOUT.SM, - ); + expect( + editorText.includes(originalEditorText) && + !editorText.includes(llmResponse), + ).to.be.true; + }, DEFAULT_TIMEOUT.SM); }).timeout(DEFAULT_TIMEOUT.XL); }); diff --git a/extensions/vscode/e2e/tests/SSH.test.ts b/extensions/vscode/e2e/tests/SSH.test.ts index 8683a35d3..f6b924b8e 100644 --- a/extensions/vscode/e2e/tests/SSH.test.ts +++ b/extensions/vscode/e2e/tests/SSH.test.ts @@ -1,18 +1,24 @@ import { EditorView, - TextEditor, InputBox, - Workbench, Key, - VSBrowser, + TextEditor, + Workbench, } from "vscode-extension-tester"; -import { DEFAULT_TIMEOUT } from "../constants"; -import { TestUtils } from "../TestUtils"; -import { SSHSelectors } from "../selectors/SSH.selectors"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { SSHSelectors } from "../selectors/SSH.selectors"; +import { TestUtils } from "../TestUtils"; describe("SSH", function () { + if (process.env.IGNORE_SSH_TESTS === "true") { + it("Skipping SSH tests", () => { + console.log("Skipping SSH tests due to IGNORE_SSH_TESTS being set"); + }); + return; + } + it("Should display completions", async () => { await TestUtils.waitForSuccess(async () => { await new Workbench().executeCommand( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 38d0db7c8..78a61be2b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.254", + "version": "0.9.260", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.254", + "version": "0.9.260", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,11 +106,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.16", + "@continuedev/config-yaml": "^1.0.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.4.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index fd5f55a70..5ef76d3dc 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": "0.9.255", + "version": "0.9.261", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -96,16 +96,10 @@ "default": false, "markdownDescription": "Enable Continue for teams beta features. To sign in, click the person icon in the bottom right of the sidebar." }, - "continue.continueTestEnvironment": { - "type": "string", - "enum": [ - "none", - "production", - "test", - "local" - ], - "default": "none", - "description": "Continue test environment" + "continue.enableContinueHub": { + "type": "boolean", + "default": false, + "description": "Enable Continue Hub (internal)" }, "continue.showInlineTip": { "type": "boolean", @@ -220,13 +214,13 @@ "command": "continue.toggleFullScreen", "category": "Continue", "title": "Toggle Full Screen", - "icon": "$(fullscreen)", + "icon": "$(link-external)", "group": "Continue" }, { - "command": "continue.openConfig", + "command": "continue.openConfigPage", "category": "Continue", - "title": "Open Continue Config", + "title": "Open Settings", "icon": "$(gear)", "group": "Continue" }, @@ -533,19 +527,19 @@ "when": "view == continue.continueGUIView" }, { - "command": "continue.openConfig", + "command": "continue.openConfigPage", "group": "navigation@4", "when": "view == continue.continueGUIView" }, { "command": "continue.signInToControlPlane", "group": "navigation@5", - "when": "(view == continue.continueGUIView) && (config.continue.enableContinueForTeams || config.continue.continueTestEnvironment !== 'none') && !continue.isSignedInToControlPlane" + "when": "(view == continue.continueGUIView) && (config.continue.enableContinueForTeams || config.continue.enableContinueHub) && !continue.isSignedInToControlPlane" }, { "command": "continue.openAccountDialog", "group": "navigation@5", - "when": "(view == continue.continueGUIView) && (config.continue.enableContinueForTeams || config.continue.continueTestEnvironment !== 'none') && continue.isSignedInToControlPlane" + "when": "(view == continue.continueGUIView) && (config.continue.enableContinueForTeams || config.continue.enableContinueHub) && continue.isSignedInToControlPlane" }, { "command": "continue.openMorePage", diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index fbd2077a1..7f9f561f6 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -636,14 +636,13 @@ class VsCodeIde implements IDE { "enableContinueForTeams", false, ), - continueTestEnvironment: settings.get< - IdeSettings["continueTestEnvironment"] - >("continueTestEnvironment", "none"), + continueTestEnvironment: settings.get("enableContinueHub") + ? "production" + : "none", pauseCodebaseIndexOnStart: settings.get( "pauseCodebaseIndexOnStart", false, ), - enableDebugLogs: false, // settings.get( // "enableControlServerBeta", // false, diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index c10d4d5f1..b7680b686 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -44,11 +44,11 @@ export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { private onError(e: any) { - const options = ["Documentation"]; + let options = ["Documentation"]; if (e.message.includes("Ollama may not be installed")) { options.push("Download Ollama"); } else if (e.message.includes("Ollama may not be running")) { - options.unshift("Start Ollama"); // We want "Start" to be the default choice + options = ["Start Ollama"]; // We want "Start" to be the only choice } if (e.message.includes("Please sign in with GitHub")) { @@ -70,7 +70,7 @@ export class ContinueCompletionProvider ); } else if (val === "Download Ollama") { vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val == "Start Ollama") { + } else if (val === "Start Ollama") { startLocalOllama(this.ide); } }); diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 6ab614c90..69b9b4d0f 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -46,6 +46,11 @@ export class RecentlyEditedTracker { private async insertRange( editedRange: Omit, ): Promise { + + if (editedRange.uri.scheme === "output") { + return; + } + // Check for overlap with any existing ranges for (let i = 0; i < this.recentlyEditedRanges.length; i++) { let range = this.recentlyEditedRanges[i]; @@ -78,6 +83,7 @@ export class RecentlyEditedTracker { RecentlyEditedTracker.maxRecentlyEditedRanges, ); } + } private insertDocument(uri: vscode.Uri): void { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index d8019cfe1..76045f196 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -31,8 +31,10 @@ import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { VsCodeIde } from "./VsCodeIde"; +import { getMetaKeyLabel } from "./util/util"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { startLocalOllama } from "core/util/ollamaHelper"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -776,6 +778,7 @@ const getCommandsMap: ( sessionId, ); } + panel.reveal(); sessionLoader.dispose(); }); @@ -792,10 +795,8 @@ const getCommandsMap: ( vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); }, - "continue.openConfig": () => { - core.invoke("config/openProfile", { - profileId: undefined, - }); + "continue.openConfigPage": () => { + vscode.commands.executeCommand("continue.navigateTo", "/config", true); }, "continue.selectFilesAsContext": async ( firstUri: vscode.Uri, @@ -904,15 +905,18 @@ const getCommandsMap: ( ? StatusBarStatus.Enabled : StatusBarStatus.Disabled; } + quickPick.items = [ { label: "$(question) Open help center", }, { - label: "$(comment) Open chat (Cmd+L)", + label: "$(comment) Open chat", + description: getMetaKeyLabel() + " + L", }, { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + label: "$(screen-full) Open full screen chat", + description: getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M", }, { label: quickPickStatusText(targetStatus), @@ -1000,6 +1004,9 @@ const getCommandsMap: ( "continue.openAccountDialog": () => { sidebar.webviewProtocol?.request("openDialogMessage", "account"); }, + "continue.startLocalOllama": () => { + startLocalOllama(ide); + }, }; }; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index b49960919..be58bb375 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -1,6 +1,6 @@ import fs from "fs"; -import { IContextProvider, IdeSettings } from "core"; +import { IContextProvider } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env"; import { Core } from "core/core"; @@ -375,9 +375,9 @@ export class VsCodeExtension { void this.core.invoke("didChangeActiveTextEditor", { filepath }); }); - const originalValue = vscode.workspace + const enableContinueHub = vscode.workspace .getConfiguration(EXTENSION_NAME) - .get("continueTestEnvironment"); + .get("enableContinueHub"); vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = this.ide.getIdeSettingsSync(); @@ -386,7 +386,11 @@ export class VsCodeExtension { settings, }); - if (settings.continueTestEnvironment !== originalValue) { + if ( + enableContinueHub + ? settings.continueTestEnvironment !== "production" + : settings.continueTestEnvironment === "production" + ) { await vscode.commands.executeCommand("workbench.action.reloadWindow"); } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index a150d2cd8..de10f9c7d 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -20,17 +20,15 @@ import { workspace, } from "vscode"; -import { IdeSettings } from "core"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; import { SecretStorage } from "./SecretStorage"; const AUTH_NAME = "Continue"; const controlPlaneEnv = getControlPlaneEnvSync( - workspace - .getConfiguration(EXTENSION_NAME) - .get("continueTestEnvironment") ?? - "none", + workspace.getConfiguration(EXTENSION_NAME).get("enableContinueHub") + ? "production" + : "none", ); const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; diff --git a/extensions/vscode/src/stubs/remoteConfig.ts b/extensions/vscode/src/stubs/remoteConfig.ts index 719d52db4..ffe1fe89b 100644 --- a/extensions/vscode/src/stubs/remoteConfig.ts +++ b/extensions/vscode/src/stubs/remoteConfig.ts @@ -2,10 +2,7 @@ import * as fs from "fs"; import { ContinueServerClient } from "core/continueServer/stubs/client"; import { EXTENSION_NAME } from "core/control-plane/env"; -import { - getConfigJsPathForRemote, - getConfigJsonPathForRemote, -} from "core/util/paths"; +import { getConfigJsonPathForRemote } from "core/util/paths"; import * as vscode from "vscode"; import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig"; @@ -126,16 +123,12 @@ export class RemoteConfigSync { remoteConfigServerUrl.toString(), userToken, ); - const { configJson, configJs } = await client.getConfig(); + const { configJson } = await client.getConfig(); fs.writeFileSync( getConfigJsonPathForRemote(remoteConfigServerUrl), configJson, ); - fs.writeFileSync( - getConfigJsPathForRemote(remoteConfigServerUrl), - configJs, - ); this.triggerReloadConfig(); } catch (e) { vscode.window.showWarningMessage(`Failed to sync remote config: ${e}`); diff --git a/extensions/vscode/src/util/tutorial.ts b/extensions/vscode/src/util/tutorial.ts index 45a86a675..6557b5790 100644 --- a/extensions/vscode/src/util/tutorial.ts +++ b/extensions/vscode/src/util/tutorial.ts @@ -16,7 +16,12 @@ export async function showTutorial(ide: IDE) { // Ensure keyboard shortcuts match OS if (process.platform !== "darwin") { let tutorialContent = await ide.readFile(tutorialUri.toString()); - tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl"); + tutorialContent = tutorialContent + .replaceAll("[Cmd + L]", "[Ctrl + L]") + .replaceAll("[Cmd + Shift + L]", "[Ctrl + Shift + L]") + .replaceAll("[Cmd + I]", "[Ctrl + I]") + .replaceAll("⌘", "^"); + await ide.writeFile(tutorialUri.toString(), tutorialContent); } diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 6691a66d2..916d7b3bc 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -99,9 +99,9 @@ export function getMetaKeyLabel() { return "⌘"; case "linux": case "windows": - return "^"; + return "Ctrl"; default: - return "^"; + return "Ctrl"; } } diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 2129c0ce3..14854f1c3 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -10,7 +10,8 @@ import { IMessenger } from "../../../core/protocol/messenger"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol - implements IMessenger { + implements IMessenger +{ listeners = new Map< keyof FromWebviewProtocol, ((message: Message) => any)[] @@ -85,6 +86,30 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { + let message = e.message; + //Intercept Ollama errors for special handling + if (message.includes("Ollama may not")) { + const options = []; + if (message.includes("be installed")) { + options.push("Download Ollama"); + } else if (message.includes("be running")) { + options.push("Start Ollama"); + } + if (options.length > 0) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); + // Show native vscode error message instead, with options to download/start Ollama + vscode.window.showErrorMessage(e.message, ...options).then(async (val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } + }); + return; + } + } + respond({ done: true, error: e.message, status: "error" }); const stringified = JSON.stringify({ msg }, null, 2); @@ -99,7 +124,6 @@ export class VsCodeWebviewProtocol return; } - let message = e.message; if (e.cause) { if (e.cause.name === "ConnectTimeoutError") { message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://docs.continue.dev/reference/config`; @@ -114,8 +138,7 @@ export class VsCodeWebviewProtocol message = message.split("\n").filter((l: string) => l !== "")[1]; try { message = JSON.parse(message).message; - } catch { - } + } catch {} if (message.includes("exceeded")) { message += " To keep using Continue, you can set up a local model or use your own API key."; @@ -152,8 +175,7 @@ export class VsCodeWebviewProtocol this._webviewListener = this._webview.onDidReceiveMessage(handleMessage); } - constructor(private readonly reloadConfig: () => void) { - } + constructor(private readonly reloadConfig: () => void) {} invoke( messageType: T, @@ -163,7 +185,7 @@ export class VsCodeWebviewProtocol throw new Error("Method not implemented."); } - onError(handler: (error: Error) => void): void { + onError(handler: (message: Message, error: Error) => void): void { throw new Error("Method not implemented."); } diff --git a/gui/package-lock.json b/gui/package-lock.json index 922ac8e10..0984ae74d 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.15", + "@continuedev/config-yaml": "^1.0.23", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -108,11 +108,11 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.16", + "@continuedev/config-yaml": "^1.0.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", - "@modelcontextprotocol/sdk": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.4.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -556,9 +556,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.15.tgz", - "integrity": "sha512-00c1pz+FqAVEWLo8t71OJzm1KBAAJCXqIjd917Vy8lr7xO0Eoj42lo2GFlVRnqQ0hQvhFQ0s9onHhRag/phHZA==", + "version": "1.0.23", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.23.tgz", + "integrity": "sha512-F2Hwc85iCwAHJuwJALOsmZIBeHdF+87mS0YT7dlC6QiE+zAhZKUHcLQ/nTt9bJuhyVyufpb9LApkp40UdGsaWw==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/gui/package.json b/gui/package.json index 5bed963dd..4500287fa 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.15", + "@continuedev/config-yaml": "^1.0.23", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/gui/public/logos/novita.png b/gui/public/logos/novita.png index b744cd35c..30ccb507e 100644 Binary files a/gui/public/logos/novita.png and b/gui/public/logos/novita.png differ diff --git a/gui/public/logos/siliconflow.png b/gui/public/logos/siliconflow.png new file mode 100644 index 000000000..f32fc6ebf Binary files /dev/null and b/gui/public/logos/siliconflow.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 18df91b86..73d667292 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -13,6 +13,7 @@ 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([ { @@ -52,6 +53,10 @@ const router = createMemoryRouter([ path: ROUTES.CONFIG_ERROR, element: , }, + { + path: ROUTES.CONFIG, + element: , + }, { path: "/migration", element: , diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index cadaa5830..747c2ddab 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -29,16 +29,6 @@ const LayoutTopDiv = styled(CustomScrollbarDiv)` border-radius: ${defaultBorderRadius}; position: relative; overflow-x: hidden; - - &::after { - position: absolute; - content: ""; - width: 100%; - height: 1px; - background-color: rgba(136, 136, 136, 0.3); - top: 0; - left: 0; - } `; const GridDiv = styled.div` diff --git a/gui/src/components/PageHeader.tsx b/gui/src/components/PageHeader.tsx index 23e108c38..04317c947 100644 --- a/gui/src/components/PageHeader.tsx +++ b/gui/src/components/PageHeader.tsx @@ -1,20 +1,32 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; export interface PageHeaderProps { - onClick: () => void; - title: string; + onTitleClick?: () => void; + title?: string; + rightContent?: React.ReactNode; } -export default function PageHeader({ onClick, title }: PageHeaderProps) { +export default function PageHeader({ + onTitleClick, + title, + rightContent, +}: PageHeaderProps) { return ( -
-
- - {title} +
+
+ {title && ( +
+ + + {title} + +
+ )}
+
{rightContent}
); } diff --git a/gui/src/components/StepContainer/Reasoning.tsx b/gui/src/components/StepContainer/Reasoning.tsx new file mode 100644 index 000000000..d5537c82b --- /dev/null +++ b/gui/src/components/StepContainer/Reasoning.tsx @@ -0,0 +1,138 @@ +import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; +import { ChatHistoryItem } from "core"; +import { stripImages } from "core/util/messageContent"; +import { useEffect, useState } from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscBackground, + vscQuickInputBackground, +} from ".."; +import { getFontSize } from "../../util"; +import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; + +interface ReasoningProps { + item: ChatHistoryItem; + index: number; + isLast: boolean; +} + +const SpoilerButton = styled.div` + margin: 8px 6px 16px 6px; + background-color: ${vscBackground}; + width: fit-content; + font-size: ${getFontSize() - 2}px; + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + cursor: pointer; + box-shadow: + 0 4px 6px rgba(0, 0, 0, 0.1), + 0 1px 3px rgba(0, 0, 0, 0.08); + transition: box-shadow 0.3s ease; + + &:hover { + box-shadow: + 0 6px 8px rgba(0, 0, 0, 0.15), + 0 3px 6px rgba(0, 0, 0, 0.1); + } +`; + +const ButtonContent = styled.div` + display: flex; + align-items: center; + gap: 6px; +`; + +const ContentDiv = styled.div<{ fontSize?: number }>` + margin: 4px; + padding: 4px; + padding-bottom: 8px; + font-size: ${getFontSize()}px; + overflow: hidden; + border-left: 4px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + background-color: ${vscQuickInputBackground}; +`; + +const ThinkingText = styled.span` + position: relative; + padding-right: 12px; + + &:after { + content: "..."; + position: absolute; + animation: ellipsis 1s steps(4, end) infinite; + width: 0px; + display: inline-block; + overflow: hidden; + } + + @keyframes ellipsis { + 0%, + 100% { + width: 0px; + } + 33% { + width: 8px; + } + 66% { + width: 16px; + } + 90% { + width: 24px; + } + } +`; + +export default function Reasoning(props: ReasoningProps) { + const [open, setOpen] = useState(false); + const [reasoningTime, setReasoningTime] = useState(""); + const isThinking = !props.item.reasoning?.endAt; + + useEffect(() => { + if (!props.item.reasoning) return; + if (!props.item.reasoning?.endAt) return; + + const startAt = props.item.reasoning?.startAt || Date.now(); + const endAt = props.item.reasoning?.endAt || Date.now(); + const diff = endAt - startAt; + const diffString = `${(diff / 1000).toFixed(1)}s`; + setReasoningTime(diffString); + }, [props.item.reasoning?.startAt, props.item.reasoning?.endAt]); + + if (!props.item.reasoning?.text) { + return null; + } + + return ( + <> + setOpen(!open)}> + + {isThinking ? ( + Thinking + ) : ( + `Thought for ${reasoningTime}` + )} + {open ? ( + + ) : ( + + )} + + + {open && ( + + + + )} + + ); +} diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 5709f7f60..b395db076 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -11,6 +11,7 @@ import { getFontSize } from "../../util"; import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; import ResponseActions from "./ResponseActions"; import ThinkingIndicator from "./ThinkingIndicator"; +import Reasoning from "./Reasoning"; interface StepContainerProps { item: ChatHistoryItem; @@ -90,11 +91,15 @@ export default function StepContainer(props: StepContainerProps) { {renderChatMessage(props.item.message)} ) : ( - + <> + + + + )} {props.isLast && } diff --git a/gui/src/components/gui/NumberInput.tsx b/gui/src/components/gui/NumberInput.tsx new file mode 100644 index 000000000..5ea817b84 --- /dev/null +++ b/gui/src/components/gui/NumberInput.tsx @@ -0,0 +1,63 @@ +import React from "react"; + +interface NumberInputProps { + value: number; + onChange: (value: number) => void; + max: number; + min: number; +} + +const NumberInput: React.FC = ({ + value, + onChange, + max, + min, +}) => { + const handleIncrement = () => { + if (value < max) { + onChange(value + 1); + } + }; + + const handleDecrement = () => { + if (value > min) { + onChange(value - 1); + } + }; + + return ( +
+ +
+ + +
+
+ ); +}; + +export default NumberInput; diff --git a/gui/src/components/gui/Select.tsx b/gui/src/components/gui/Select.tsx new file mode 100644 index 000000000..01ec79242 --- /dev/null +++ b/gui/src/components/gui/Select.tsx @@ -0,0 +1,48 @@ +// export const Select = styled.select` +// padding: 8px 12px; +// border-radius: ${defaultBorderRadius}; +// border: 1px solid ${vscInputBorder}; +// background-color: ${vscBackground}; +// color: ${vscForeground}; + +import { vscBackground, vscForeground, vscInputBorder } from ".."; + +// appearance: none; +// -webkit-appearance: none; +// -moz-appearance: none; +// padding-right: 30px; +// background: url('data:image/svg+xml;utf8,') +// no-repeat right 10px center; +// background-size: 10px 10px; +// `; + +// // gui/src/components/gui/Select.tsx +// import React from 'react'; + +export const Select: React.FC> = ( + props, +) => ( +
+ +
+); diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx new file mode 100644 index 000000000..7d6105e6d --- /dev/null +++ b/gui/src/components/gui/Switch.tsx @@ -0,0 +1,33 @@ +import React from "react"; + +type ToggleSwitchProps = { + isToggled: boolean; + onToggle: () => void; + text: string; +}; + +const ToggleSwitch: React.FC = ({ + isToggled, + onToggle, + text, +}) => { + return ( +
+ {text} +
+
+
+
+
+
+
+
+ ); +}; + +export default ToggleSwitch; diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 071900b51..8f1455c67 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -154,6 +154,13 @@ export const Button = styled.button` } `; +type NumberInputProps = { + value: number; + onChange: (value: number) => void; + max?: number; + min?: number; +}; + export const SecondaryButton = styled.button` padding: 10px 12px; margin: 8px 0; @@ -250,17 +257,6 @@ export const Input = styled.input` } `; -export const Select = styled.select` - padding: 8px 12px; - margin: 8px 0; - box-sizing: border-box; - border-radius: ${defaultBorderRadius}; - outline: 1px solid ${lightGray}; - border: none; - background-color: ${vscBackground}; - color: ${vscForeground}; -`; - export const Label = styled.label<{ fontSize?: number }>` font-size: ${(props) => props.fontSize || getFontSize()}px; `; diff --git a/gui/src/components/indexing/DocsDetailsDialog.tsx b/gui/src/components/indexing/DocsDetailsDialog.tsx new file mode 100644 index 000000000..7b824291a --- /dev/null +++ b/gui/src/components/indexing/DocsDetailsDialog.tsx @@ -0,0 +1,176 @@ +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 { usePostHog } from "posthog-js/react"; +import { + useCallback, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useRef, + 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"; + +interface DocsDetailsDialogProps { + startUrl: string; +} +function DocsDetailsDialog({ startUrl }: DocsDetailsDialogProps) { + const config = useAppSelector((store) => store.config.config); + const posthog = usePostHog(); + const dispatch = useDispatch(); + + const ideMessenger = useContext(IdeMessengerContext); + + const closeDialog = () => { + dispatch(setShowDialog(false)); + dispatch(setDialogMessage(undefined)); + }; + + const [isLoading, setIsLoading] = useState(false); + const [isError, setIsError] = useState(false); + const [data, setData] = useState(undefined); + + const fetchData = useCallback(async () => { + setIsLoading(true); + setIsError(false); + + try { + const response = await ideMessenger.request("docs/getDetails", { + startUrl, + }); + if (response.status === "error") { + throw new Error(response.error); + } + setData(response.content); + } catch (error) { + setIsError(true); + } finally { + setIsLoading(false); + } + }, []); + + useEffect(() => { + fetchData(); + }, []); + + let comp =
Loading...
; + if (!isLoading) { + if (isError) { + comp = ( +
+
Error fetching docs details
+ Try again +
+ ); + } + if (data) { + comp = ( +
+

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

+

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

+ {!data.chunks?.length ? ( +
No article chunks
+ ) : ( +
+ + + + + + + + + {data.chunks.map((chunk, i) => { + const contentToolTipId = `docs-content-peek-${i}`; + const urlToolTipId = `docs-url-peek-${i}`; + return ( + <> + + + + + + {chunk.filepath} + + + {chunk.content} + + + ); + })} + +
FilepathContent
+ + {chunk.filepath} + + + + {chunk.content} + +
+
+ )} +
+ ); + } + } + + return ( +
+

Docs index

+

{ + e.stopPropagation(); + ideMessenger.post("openUrl", startUrl); + }} + > + {startUrl} +

+ {comp} +
+ Close +
+
+ ); +} + +export default DocsDetailsDialog; diff --git a/gui/src/components/indexing/DocsIndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx index df2bc11f2..fe64ae2dc 100644 --- a/gui/src/components/indexing/DocsIndexingStatus.tsx +++ b/gui/src/components/indexing/DocsIndexingStatus.tsx @@ -6,6 +6,7 @@ import { ArrowTopRightOnSquareIcon, CheckCircleIcon, ExclamationTriangleIcon, + EyeIcon, PauseCircleIcon, TrashIcon, } from "@heroicons/react/24/outline"; @@ -13,6 +14,7 @@ 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; @@ -175,24 +177,40 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { 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?.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} +
); diff --git a/gui/src/components/mainInput/AddCodeToEditExtension.ts b/gui/src/components/mainInput/AddCodeToEditExtension.ts index 795b7a2e4..f633c342b 100644 --- a/gui/src/components/mainInput/AddCodeToEditExtension.ts +++ b/gui/src/components/mainInput/AddCodeToEditExtension.ts @@ -89,7 +89,7 @@ export const AddCodeToEdit = Node.create({ default: null, parseHTML: (element) => element.getAttribute("data-renderInlineAs"), renderHTML: (attributes) => { - if (!attributes.renderInlineAs) { + if (typeof attributes.renderInlineAs !== "string") { return {}; } diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 0a0e7996b..61403a261 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -6,6 +6,7 @@ import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; export const CodeBlockComponent = (props: any) => { const { node, deleteNode, selected, editor, updateAttributes } = props; const item: ContextItemWithId = node.attrs.item; + const inputId = node.attrs.inputId; // const contextItems = useSelector( // (store: RootState) => // store.session.messages[store.session.messages.length - 1].contextItems, @@ -23,6 +24,7 @@ export const CodeBlockComponent = (props: any) => { as={nodeViewWrapperTag} >
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 7ce52bec4..93b437fdc 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -10,7 +10,7 @@ import { vscInputBackground, } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectUseActiveFile, selectUsePlatform } from "../../redux/selectors"; +import { selectUseActiveFile } from "../../redux/selectors"; import { selectDefaultModel } from "../../redux/slices/configSlice"; import { selectHasCodeToEdit, @@ -26,7 +26,6 @@ import { } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; -import AssistantAndModelSelect from "../modelSelection/platform/AssistantAndModelSelect"; import HoverItem from "./InputToolbar/HoverItem"; import ToggleToolsButton from "./InputToolbar/ToggleToolsButton"; @@ -97,8 +96,6 @@ function InputToolbar(props: InputToolbarProps) { modelSupportsTools(defaultModel.model, defaultModel.provider) && !props.toolbarOptions?.hideTools; - const usePlatform = useAppSelector(selectUsePlatform); - const supportsImages = defaultModel && modelSupportsImages( @@ -117,7 +114,7 @@ function InputToolbar(props: InputToolbarProps) { className="find-widget-skip flex" >
- {usePlatform ? : } +
{props.toolbarOptions?.hideImageUpload || (supportsImages && ( diff --git a/gui/src/components/mainInput/MentionExtension.ts b/gui/src/components/mainInput/MentionExtension.ts index 71d282d46..364b241ee 100644 --- a/gui/src/components/mainInput/MentionExtension.ts +++ b/gui/src/components/mainInput/MentionExtension.ts @@ -116,7 +116,7 @@ export const Mention = Node.create({ default: null, parseHTML: (element) => element.getAttribute("data-renderInlineAs"), renderHTML: (attributes) => { - if (!attributes.renderInlineAs) { + if (typeof attributes.renderInlineAs !== "string") { return {}; } diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 232dafae3..f78b58720 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -50,6 +50,7 @@ import { selectHasCodeToEdit, selectIsInEditMode, setMainEditorContentTrigger, + setNewestCodeblocksForInput, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; import { @@ -108,11 +109,6 @@ const InputBoxDiv = styled.div<{ border?: string }>` flex-direction: column; `; -const PaddingDiv = styled.div` - padding: 8px 12px; - padding-bottom: 4px; -`; - const HoverDiv = styled.div` position: absolute; width: 100%; @@ -180,6 +176,7 @@ interface TipTapEditorProps { border?: string; placeholder?: string; historyKey: string; + inputId: string; } export const TIPPY_DIV_ID = "tippy-js-div"; @@ -782,22 +779,6 @@ function TipTapEditor(props: TipTapEditorProps) { return; } - // const rif: RangeInFile & { contents: string } = - // data.rangeInFileWithContents; - // const basename = getBasename(rif.filepath); - // const relativePath = getRelativePath( - // rif.filepath, - // await ideMessenger.ide.getWorkspaceDirs(), - // const rangeStr = `(${rif.range.start.line + 1}-${ - // rif.range.end.line + 1 - // })`; - - // const itemName = `${basename} ${rangeStr}`; - // const item: ContextItemWithId = { - // content: rif.contents, - // name: itemName - // } - const contextItem = rifWithContentsToContextItem( data.rangeInFileWithContents, ); @@ -819,10 +800,16 @@ function TipTapEditor(props: TipTapEditorProps) { 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); @@ -990,8 +977,9 @@ function TipTapEditor(props: TipTapEditorProps) { event.preventDefault(); }} > - +
{ @@ -1023,7 +1011,7 @@ function TipTapEditor(props: TipTapEditorProps) { }} disabled={isStreaming} /> - +
{showDragOverMsg && modelSupportsImages( diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx index c94f63598..3eb0da2ef 100644 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ b/gui/src/components/mainInput/TutorialCard.tsx @@ -69,14 +69,14 @@ export function TutorialCard({ onClose }: TutorialCardProps) {
  • - Highlight code and press {getMetaKeyLabel() + "I"} to + Highlight code and press {getMetaKeyLabel()} + I to quickly make natural language edits
  • - Highlight code and press {getMetaKeyLabel() + "L"} to + Highlight code and press {getMetaKeyLabel()} + L to add it to the chat window
  • diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index c58628cf0..1113d2fc3 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -53,7 +53,6 @@ async function resolveEditorContent({ for (const p of editorState.content) { if (p.type === "paragraph") { const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - // Only take the first slash command\ if (foundSlashCommand && typeof slashCommand === "undefined") { slashCommand = foundSlashCommand; @@ -240,7 +239,7 @@ function resolveParagraph( export function hasSlashCommandOrContextProvider( editorState: JSONContent, ): boolean { - if (!editorState.content) { + if (!editorState?.content) { return false; } diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 62565e5ea..06717c5ee 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -1,11 +1,11 @@ import { ChevronDownIcon, - ChevronUpIcon, + EyeSlashIcon, XMarkIcon, } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { dedent, getMarkdownLanguageTagForFile } from "core/util"; -import React, { useContext, useMemo } from "react"; +import { useContext, useEffect, useMemo, useRef, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscEditorBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -14,6 +14,8 @@ import FileIcon from "../FileIcon"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import StyledMarkdownPreview from "./StyledMarkdownPreview"; import { ctxItemToRifWithContents } from "core/commands/util"; +import { EyeIcon } from "@heroicons/react/24/solid"; +import { useAppSelector } from "../../redux/hooks"; const PreviewMarkdownDiv = styled.div<{ borderColor?: string; @@ -31,32 +33,30 @@ const PreviewMarkdownDiv = styled.div<{ } `; -const PreviewMarkdownHeader = styled.div` - margin: 0; - padding: 2px 6px; - border-bottom: 0.5px solid ${lightGray}; - word-break: break-all; - font-size: ${getFontSize() - 3}px; - display: flex; - align-items: center; -`; - interface CodeSnippetPreviewProps { item: ContextItemWithId; onDelete?: () => void; borderColor?: string; - hideHeader?: boolean; + inputId: string; } -const MAX_PREVIEW_HEIGHT = 300; +const MAX_PREVIEW_HEIGHT = 100; const backticksRegex = /`{3,}/gm; function CodeSnippetPreview(props: CodeSnippetPreviewProps) { const ideMessenger = useContext(IdeMessengerContext); - const [collapsed, setCollapsed] = React.useState(true); - const [hovered, setHovered] = React.useState(false); + const [localHidden, setLocalHidden] = useState(); + const [isSizeLimited, setIsSizeLimited] = useState(true); + + const newestCodeblockForInputId = useAppSelector( + (store) => store.session.newestCodeblockForInput[props.inputId], + ); + + const hidden = useMemo(() => { + return localHidden ?? newestCodeblockForInputId !== props.item.id.itemId; + }, [localHidden, newestCodeblockForInputId, props.item]); const content = useMemo(() => { return dedent`${props.item.content}`; @@ -67,20 +67,45 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { return backticks ? backticks.sort().at(-1) + "`" : "```"; }, [content]); - const codeBlockRef = React.useRef(null); + const codeBlockRef = useRef(null); + + const [codeblockDims, setCodeblockDims] = useState({ width: 0, height: 0 }); + useEffect(() => { + const resizeObserver = new ResizeObserver(() => { + setCodeblockDims({ + width: codeBlockRef.current?.scrollWidth ?? 0, + height: codeBlockRef.current?.scrollHeight ?? 0, + }); + }); + + if (codeBlockRef.current) { + resizeObserver.observe(codeBlockRef.current); + } + + return () => { + resizeObserver.disconnect(); + }; + }, [codeBlockRef]); return ( setHovered(true)} - onMouseLeave={() => setHovered(false)} borderColor={props.borderColor} className="find-widget-skip" > - {!props.hideHeader && ( - { +
    { + setLocalHidden(!hidden); + }} + > +
    { + e.stopPropagation(); if ( props.item.id.providerTitle === "file" && props.item.uri?.value @@ -103,29 +128,34 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { } }} > -
    - - {props.item.name} -
    -
    - { - e.stopPropagation(); - props.onDelete?.(); - }} - > - - -
    - - )} + + {props.item.name} +
    +
    + + {hidden ? ( + + ) : ( + + )} + + { + e.stopPropagation(); + props.onDelete?.(); + }} + > + + +
    +
    - {(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && ( + {codeblockDims.height > MAX_PREVIEW_HEIGHT && ( - {collapsed ? ( - setCollapsed(false)} - /> - ) : ( - setCollapsed(true)} - /> - )} + setIsSizeLimited((v) => !v)} + /> )}
    diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 641e17c13..5cb33d939 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -84,7 +84,7 @@ export default function StepContainerPreActionButtons({ tabIndex={-1} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)} - className="bg-vsc-editor-background border-vsc-input-border relative rounded-md border-[1px] border-solid" + className="bg-vsc-editor-background border-vsc-input-border relative my-2.5 rounded-md border-[1px] border-solid" >
    {children}
    {hovering && !isStreaming && ( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 52d343fe4..931c8c045 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -34,6 +34,7 @@ import { remarkTables } from "./utils/remarkTables"; const StyledMarkdown = styled.div<{ fontSize?: number; whiteSpace: string; + bgColor: string; }>` pre { white-space: ${(props) => props.whiteSpace}; @@ -63,7 +64,7 @@ const StyledMarkdown = styled.div<{ color: #f78383; } - background-color: ${vscBackground}; + background-color: ${(props) => props.bgColor}; font-family: var(--vscode-font-family), system-ui, @@ -104,6 +105,7 @@ interface StyledMarkdownPreviewProps { isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks scrollLocked?: boolean; itemIndex?: number; + useParentBackgroundColor?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -332,7 +334,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const uiConfig = useAppSelector(selectUIConfig); const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre"; return ( - + {reactContent} ); diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 63d097370..68f5ea996 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -332,7 +332,9 @@ function ModelSelect() { $showabove={showAbove} className="z-50 max-w-[90vw]" > -
    +
    {sortedOptions.map((option, idx) => (
    + + {selectedProfileId === "local" && ( <> ` - border: 1px ${(props) => (props.dashed ? "dashed" : "solid")} ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 8px; - margin-bottom: 16px; -`; - -type ModelOption = "apiKey" | "model" | "contextLength"; - -const DefaultModelOptions: { - [key: string]: { [key in ModelOption]?: string }; -} = { - OpenAI: { - apiKey: "", - model: "gpt-4", - }, - OpenAIFreeTrial: { - apiKey: "", - model: "gpt-4", - }, - Anthropic: { - apiKey: "", - model: "claude-2", - }, - default: { - apiKey: "", - model: "gpt-4", - }, -}; - -function ModelSettings(props: { llm: any | undefined; role: string }) { - const [modelOptions, setModelOptions] = useState<{ - [key in ModelOption]?: string; - }>(DefaultModelOptions[props.llm?.class_name || "default"]); - - const { register, setValue, getValues } = useFormContext(); - - return ( -
    - {props.llm ? ( - <> - {props.role}: {props.llm?.class_name || "gpt-4"} -
    - {typeof modelOptions.apiKey !== undefined && ( - <> - - - - )} - {modelOptions.model && ( - <> - - - - )} -
    - - ) : ( -
    - Add Model -
    - -
    -
    - )} -
    - ); -} - -export default ModelSettings; diff --git a/gui/src/components/modelSelection/platform/AssistantAndModelSelect.tsx b/gui/src/components/modelSelection/platform/AssistantAndModelSelect.tsx deleted file mode 100644 index c33c3a586..000000000 --- a/gui/src/components/modelSelection/platform/AssistantAndModelSelect.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import { Popover } from "@headlessui/react"; -import { - ChevronDownIcon, - DocumentIcon, - SparklesIcon, -} from "@heroicons/react/24/outline"; -import { useEffect, useRef, useState } from "react"; -import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscInputBackground } from "../.."; -import { useAuth } from "../../../context/Auth"; -import AddModelForm from "../../../forms/AddModelForm"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { - cycleDefaultModel, - selectDefaultModel, -} from "../../../redux/slices/configSlice"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; -import { cycleProfile } from "../../../redux/thunks/cycleProfile"; -import { getFontSize, isMetaEquivalentKeyPressed } from "../../../util"; -import PopoverTransition from "../../mainInput/InputToolbar/PopoverTransition"; -import { AssistantSelect } from "./AssistantSelect"; -import { ModelSelect, modelSelectTitle } from "./ModelSelect"; -import { MAX_HEIGHT_PX } from "./shared"; - -const StyledPopoverButton = styled(Popover.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 StyledPopoverPanel = styled(Popover.Panel)<{ $showabove: boolean }>` - margin-top: 4px; - position: absolute; - padding: 0px; - cursor: default; - - display: flex; - flex-direction: row; - - border-radius: ${defaultBorderRadius}; - border: 0.5px solid ${lightGray}; - background-color: ${vscInputBackground}; - - ${(props) => (props.$showabove ? "bottom: 100%;" : "top: 100%;")} -`; - -function AssistantAndModelSelect() { - const dispatch = useAppDispatch(); - const defaultModel = useAppSelector(selectDefaultModel); - const [showAbove, setShowAbove] = useState(false); - const buttonRef = useRef(null); - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, - ); - - const { profiles, selectedProfile } = useAuth(); - - useEffect(() => { - const handleResize = () => calculatePosition(); - window.addEventListener("resize", handleResize); - return () => window.removeEventListener("resize", handleResize); - }, []); - - 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: any) { - e.stopPropagation(); - e.preventDefault(); - - // Close the dropdown - if (buttonRef.current) { - buttonRef.current.click(); - } - dispatch(setShowDialog(true)); - dispatch( - setDialogMessage( - { - dispatch(setShowDialog(false)); - }} - />, - ), - ); - } - - useEffect(() => { - let lastToggleTime = 0; - const DEBOUNCE_MS = 500; - - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { - const now = Date.now(); - - if (event.shiftKey) { - dispatch(cycleDefaultModel("next")); - } else { - if (now - lastToggleTime >= DEBOUNCE_MS) { - dispatch(cycleProfile()); - lastToggleTime = now; - } - } - } - }; - - window.addEventListener("keydown", handleKeyDown); - return () => { - window.removeEventListener("keydown", handleKeyDown); - }; - }, []); - - return ( - -
    - -
    - {selectedProfile?.id === "local" ? ( - <> -
    -
    - - - { - if (buttonRef.current) { - buttonRef.current.click(); - } - }} - /> - - - -
    -
    - ); -} - -export default AssistantAndModelSelect; diff --git a/gui/src/components/modelSelection/platform/AssistantIcon.tsx b/gui/src/components/modelSelection/platform/AssistantIcon.tsx new file mode 100644 index 000000000..8575f0277 --- /dev/null +++ b/gui/src/components/modelSelection/platform/AssistantIcon.tsx @@ -0,0 +1,17 @@ +import { ProfileDescription } from "core/config/ProfileLifecycleManager"; +import { isLocalProfile } from "../../../util"; +import { ComputerDesktopIcon, SparklesIcon } from "@heroicons/react/24/outline"; + +export interface AssistantIconProps { + assistant: ProfileDescription; +} + +export default function AssistantIcon({ assistant }: AssistantIconProps) { + if (isLocalProfile(assistant)) { + return ; + } else if (assistant.iconUrl) { + return ; + } else { + return ; + } +} diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 972dd2782..f1216ac3f 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -1,113 +1,91 @@ -import { - DocumentIcon, - PlusIcon, - SparklesIcon, -} from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { lightGray } from "../.."; +import { Popover } from "@headlessui/react"; +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import { useEffect, useRef } from "react"; import { useAuth } from "../../../context/Auth"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; -import { setProfileId } from "../../../redux/thunks/setProfileId"; -import { getFontSize, getMetaKeyLabel } from "../../../util"; -import AboutAssistantDialog from "../../dialogs/AboutAssistantDialog"; -import { Divider, Option, OptionDiv } from "./shared"; - -interface AssistantSelectProps { - onClose: () => void; -} - -export function AssistantSelect(props: AssistantSelectProps) { - const ideMessenger = useContext(IdeMessengerContext); - const { profiles, selectedProfile } = useAuth(); +import { cycleProfile } from "../../../redux/thunks/cycleProfile"; +import { + getFontSize, + isLocalProfile, + isMetaEquivalentKeyPressed, +} from "../../../util"; +import PopoverTransition from "../../mainInput/InputToolbar/PopoverTransition"; +import { AssistantSelectOptions } from "./AssistantSelectOptions"; +import AssistantIcon from "./AssistantIcon"; +import { getProfileDisplayText } from "./utils"; +export default function AssistantSelect() { const dispatch = useAppDispatch(); + const buttonRef = useRef(null); + const { selectedProfile } = useAuth(); - function onNewAssistant() { - ideMessenger.post("controlPlane/openUrl", { - path: "new", - }); + const isLocalProfileSelected = + selectedProfile && isLocalProfile(selectedProfile); + + useEffect(() => { + let lastToggleTime = 0; + const DEBOUNCE_MS = 500; + + const handleKeyDown = (event: KeyboardEvent) => { + if ( + event.key === "'" && + isMetaEquivalentKeyPressed(event as any) && + event.shiftKey + ) { + const now = Date.now(); + + if (now - lastToggleTime >= DEBOUNCE_MS) { + dispatch(cycleProfile()); + lastToggleTime = now; + } + } + }; + + window.addEventListener("keydown", handleKeyDown); + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, []); + + if (!selectedProfile) { + return null; } return ( -
    -
    - {profiles.map((option, idx) => ( - - ))} -
    - -
    - -
    - - New Assistant -
    -
    - - - - +
    + - {getMetaKeyLabel()}' toggle assistant - +
    +
    + +
    + + {getProfileDisplayText(selectedProfile)} + +
    +
    + + + + { + if (buttonRef.current) { + buttonRef.current.click(); + } + }} + /> + +
    -
    + ); } diff --git a/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx new file mode 100644 index 000000000..436005f23 --- /dev/null +++ b/gui/src/components/modelSelection/platform/AssistantSelectOptions.tsx @@ -0,0 +1,130 @@ +import { BuildingOfficeIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { useNavigate } from "react-router-dom"; +import { lightGray } from "../.."; +import { useAuth } from "../../../context/Auth"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { setProfileId } from "../../../redux/thunks/setProfileId"; +import { getFontSize, getMetaKeyLabel, isLocalProfile } from "../../../util"; +import { ROUTES } from "../../../util/navigation"; +import AboutAssistantDialog from "../../dialogs/AboutAssistantDialog"; +import AssistantIcon from "./AssistantIcon"; +import { Divider, Option, OptionDiv } from "./shared"; +import { getProfileDisplayText } from "./utils"; + +interface AssistantSelectOptionsProps { + onClose: () => void; +} + +export function AssistantSelectOptions(props: AssistantSelectOptionsProps) { + const ideMessenger = useContext(IdeMessengerContext); + const { profiles, selectedProfile, selectedOrganization } = useAuth(); + const dispatch = useAppDispatch(); + const navigate = useNavigate(); + + function onNewAssistant() { + ideMessenger.post("controlPlane/openUrl", { + path: "new", + }); + } + + function handleOptionLink(e: React.MouseEvent, profileId: string) { + e.stopPropagation(); + e.preventDefault(); + ideMessenger.post("config/openProfile", { profileId }); + } + + function handleConfigure(e: React.MouseEvent, option: any) { + e.stopPropagation(); + e.preventDefault(); + + if (option.id === "local") { + ideMessenger.post("config/openProfile", { profileId: option.id }); + } else { + props.onClose(); + dispatch(setDialogMessage()); + dispatch(setShowDialog(true)); + } + } + + function handleClickError(profileId: string) { + ideMessenger.post("config/openProfile", { profileId }); + } + + return ( +
    +
    + {profiles.map((profile, idx) => ( + + ))} +
    + +
    + +
    + + New Assistant +
    +
    + + + +
    + + {getMetaKeyLabel()} ⇧ ' to toggle + +
    navigate(ROUTES.CONFIG)} + > + {selectedOrganization?.iconUrl ? ( + + ) : ( + + )} + + {selectedOrganization?.name || "Personal"} + +
    +
    +
    +
    + ); +} diff --git a/gui/src/components/modelSelection/platform/ModelSelect.tsx b/gui/src/components/modelSelection/platform/ModelSelect.tsx deleted file mode 100644 index 80ad7179a..000000000 --- a/gui/src/components/modelSelection/platform/ModelSelect.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { CubeIcon, PlusIcon } from "@heroicons/react/24/outline"; -import { useContext, useEffect, useState } from "react"; -import { lightGray } from "../.."; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, -} from "../../../redux/slices/configSlice"; -import { getFontSize, getMetaKeyLabel } from "../../../util"; -import { Divider, Option, OptionDiv } from "./shared"; - -export interface ModelOption { - value: string; - title: string; - apiKey?: string; -} - -export function modelSelectTitle(model: any): string { - if (model?.title) return model?.title; - if (model?.model !== undefined && model?.model.trim() !== "") { - if (model?.class_name) { - return `${model?.class_name} - ${model?.model}`; - } - return model?.model; - } - return model?.class_name; -} - -interface ModelSelectProps { - selectedProfileId: string; - onClickAddModel: (e: any) => void; -} - -export function ModelSelect(props: ModelSelectProps) { - const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const defaultModel = useAppSelector(selectDefaultModel); - const allModels = useAppSelector((state) => state.config.config.models); - const [options, setOptions] = useState([]); - const [sortedOptions, setSortedOptions] = useState([]); - - // Sort so that options without an API key are at the end - useEffect(() => { - const enabledOptions = options.filter((option) => option.apiKey !== ""); - const disabledOptions = options.filter((option) => option.apiKey === ""); - - const sorted = [...enabledOptions, ...disabledOptions]; - - setSortedOptions(sorted); - }, [options]); - - useEffect(() => { - setOptions( - allModels.map((model) => { - return { - value: model.title, - title: modelSelectTitle(model), - apiKey: model.apiKey, - }; - }), - ); - }, [allModels]); - - function onModelChange(modelTitle: string) { - if (modelTitle === defaultModel?.title) return; - dispatch(setDefaultModel({ title: modelTitle })); - } - - return ( -
    -
    - {sortedOptions.map((option, idx) => ( - - ))} -
    - -
    - {props.selectedProfileId === "local" && ( - <> - -
    - - Add Chat model -
    -
    - - )} - - - - - {getMetaKeyLabel()}⇧' toggle model - -
    -
    - ); -} diff --git a/gui/src/components/modelSelection/platform/shared.tsx b/gui/src/components/modelSelection/platform/shared.tsx index d860cab49..bb94188a9 100644 --- a/gui/src/components/modelSelection/platform/shared.tsx +++ b/gui/src/components/modelSelection/platform/shared.tsx @@ -13,7 +13,6 @@ export const OptionDiv = styled.div<{ isDisabled?: boolean; isSelected?: boolean; }>` - border-radius: ${defaultBorderRadius}; padding: 6px 12px; min-width: 0px; diff --git a/gui/src/components/modelSelection/platform/utils.ts b/gui/src/components/modelSelection/platform/utils.ts new file mode 100644 index 000000000..4a8ac8bd0 --- /dev/null +++ b/gui/src/components/modelSelection/platform/utils.ts @@ -0,0 +1,6 @@ +import { ProfileDescription } from "core/config/ProfileLifecycleManager"; +import { isLocalProfile } from "../../../util"; + +export function getProfileDisplayText(profile: ProfileDescription): string { + return isLocalProfile(profile) ? profile.title : profile.fullSlug.packageSlug; +} diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index c81aa1bc1..5154c67ae 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -1,4 +1,7 @@ -import { ProfileDescription } from "core/config/ProfileLifecycleManager"; +import { + OrganizationDescription, + ProfileDescription, +} from "core/config/ProfileLifecycleManager"; import { ControlPlaneSessionInfo } from "core/control-plane/client"; import React, { createContext, @@ -28,6 +31,8 @@ interface AuthContextType { selectedProfile: ProfileDescription | undefined; profiles: ProfileDescription[]; controlServerBetaEnabled: boolean; + organizations: OrganizationDescription[]; + selectedOrganization: OrganizationDescription | undefined; } const AuthContext = createContext(undefined); @@ -39,6 +44,20 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ undefined, ); + const [organizations, setOrganizations] = useState( + [], + ); + + const ideMessenger = useContext(IdeMessengerContext); + + const selectedOrganizationId = useAppSelector( + (store) => store.session.selectedOrganizationId, + ); + + const selectedOrganization = useMemo(() => { + return organizations.find((p) => p.id === selectedOrganizationId); + }, [organizations, selectedOrganizationId]); + const profiles = useAppSelector(selectAvailableProfiles); const selectedProfileId = useAppSelector( @@ -48,13 +67,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ return profiles.find((p) => p.id === selectedProfileId); }, [profiles, selectedProfileId]); - const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); - const lastControlServerBetaEnabledStatus = useAppSelector( - (state) => state.misc.lastControlServerBetaEnabledStatus, - ); - const login: AuthContextType["login"] = (useOnboarding: boolean) => { return new Promise((resolve) => { ideMessenger @@ -142,11 +156,23 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ enableControlServerBeta || continueTestEnvironment !== "none"; setControlServerBetaEnabled(enabled); dispatch(setLastControlServerBetaEnabledStatus(enabled)); - - const shouldShowPopup = !lastControlServerBetaEnabledStatus && enabled; }); }, []); + useEffect(() => { + if (session) { + ideMessenger + .request("controlPlane/listOrganizations", undefined) + .then((result) => { + if (result.status === "success") { + setOrganizations(result.content); + } + }); + } else { + setOrganizations([]); + } + }, [session]); + useWebviewListener( "didChangeIdeSettings", async (msg) => { @@ -185,6 +211,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ login, selectedProfile, profiles, + selectedOrganization, + organizations, controlServerBetaEnabled, }} > diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx index 43942ea0c..3e90926b1 100644 --- a/gui/src/editorInset/EditorInset.tsx +++ b/gui/src/editorInset/EditorInset.tsx @@ -36,6 +36,7 @@ function EditorInset() { console.log("Enter: ", e, modifiers); }} historyKey="chat" + inputId="editor-inset" /> ); diff --git a/gui/src/index.css b/gui/src/index.css index ba8454b7b..d51fbf004 100644 --- a/gui/src/index.css +++ b/gui/src/index.css @@ -8,7 +8,6 @@ --button-color: rgb(113, 28, 59); --button-color-hover: rgba(113, 28, 59, 0.667); --def-border-radius: 5px; - --vscode-editor-background: rgb(30, 30, 30); --vscode-editor-foreground: rgb(197, 200, 198); --vscode-textBlockQuote-background: rgba(255, 255, 255, 1); @@ -79,6 +78,7 @@ body { word-break: break-word; overflow: hidden; line-height: 1.375; + text-overflow: ellipsis; } .lines-3 { @@ -92,3 +92,42 @@ body { -webkit-line-clamp: 1; -webkit-box-orient: vertical; } + +.truncate-start { + display: inline-block; + vertical-align: middle; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + direction: rtl; + width: 100%; +} + +.scroll-container { + overflow-y: auto; /* Enable vertical scrolling only if needed */ + scrollbar-width: thin; /* Firefox */ + padding-right: 4px; +} + +.scroll-container::-webkit-scrollbar { + width: 8px; +} + +.scroll-container::-webkit-scrollbar-track { + background: #f1f1f1; + border-radius: 4px; +} + +.scroll-container::-webkit-scrollbar-thumb { + background-color: #888; + border-radius: 4px; + transition: background-color 0.3s ease; +} + +.scroll-container::-webkit-scrollbar-thumb:hover { + background-color: #555; +} + +.scroll-container:is(:hover, :focus)::-webkit-scrollbar { + display: block; /* Show scrollbar only on hover or focus */ +} diff --git a/gui/src/pages/AddNewModel/AddNewModel.tsx b/gui/src/pages/AddNewModel/AddNewModel.tsx index 5b9687537..d74cbf25c 100644 --- a/gui/src/pages/AddNewModel/AddNewModel.tsx +++ b/gui/src/pages/AddNewModel/AddNewModel.tsx @@ -49,7 +49,7 @@ const modelsByProvider: Record = { models.mistralLarge, ], Cohere: [models.commandR, models.commandRPlus], - DeepSeek: [models.deepseekCoderApi, models.deepseekChatApi], + DeepSeek: [models.deepseekCoderApi, models.deepseekChatApi, models.deepseekReasonerApi], Gemini: [models.geminiPro, models.gemini15Pro, models.gemini15Flash], "Open Source": [models.llama3Chat, models.mistralOs, models.deepseek], }; diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 8116c86ba..607e466d9 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -37,6 +37,60 @@ export interface ModelPackage { } export const models: { [key: string]: ModelPackage } = { + deepseekV3Chat: { + title: "deepseek v3", + description: "A model from deekseek for chat", + refUrl: "", + params: { + title: "deepseek_v3", + model: "deepseek/deepseek_v3", + contextLength: 2048, + }, + icon: "deepseek.png", + dimensions: [ + { + name: "Parameter Count", + description: "The number of parameters in the model", + options: { + "r1": { + model: "deepseek/deepseek_v3", + title: "deepseek_v3", + } + }, + }, + ], + providerOptions: [ + "novita" + ], + isOpenSource: true, + }, + deepseekR1Chat: { + title: "deepseek r1", + description: "A model from deekseek for chat", + refUrl: "", + params: { + title: "deepseek-r1", + model: "deepseek/deepseek-r1", + contextLength: 2048, + }, + icon: "deepseek.png", + dimensions: [ + { + name: "Parameter Count", + description: "The number of parameters in the model", + options: { + "r1": { + model: "deepseek/deepseek-r1", + title: "deepseek-r1", + } + }, + }, + ], + providerOptions: [ + "novita" + ], + isOpenSource: true, + }, llama318BChat: { title: "Llama 3.1 8B", description: "A model from Meta, fine-tuned for chat", @@ -230,6 +284,19 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["deepseek"], isOpenSource: false, }, + deepseekReasonerApi: { + title: "DeepSeek Reasoner", + description: + "An open-source reasoning model which generates a chain of thought to enhance the accuracy of its responses.", + params: { + title: "DeepSeek Reasoner", + model: "deepseek-reasoner", + contextLength: 64_000, + }, + icon: "deepseek.png", + providerOptions: ["deepseek"], + isOpenSource: true, + }, deepseekCoder2Lite: { title: "DeepSeek Coder 2 Lite", description: @@ -1228,6 +1295,21 @@ export const models: { [key: string]: ModelPackage } = { icon: "openai.png", isOpenSource: false, }, + asksagegpto3mini: { + title: "GPT-o3-mini", + description: + "o3-mini can outperform o1 in coding and other reasoning tasks, and is 93% cheaper and has lower latency. It supports function calling, Structured Outputs, streaming, and developer messages. o3-mini comes with a larger context window of 200,000 tokens and a max output of 100,000 tokens", + params: { + model: "gpt-o3-mini", + contextLength: 200_000, + title: "GPT-o3-mini", + systemMessage: + "You are an expert software developer. You give helpful and concise responses.", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, asksageclaude35gov: { title: "Claude 3.5 Sonnet gov", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 4890d5c2b..7e0560942 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -370,7 +370,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n required: true, }, ], - packages: [models.deepseekCoderApi, models.deepseekChatApi], + packages: [models.deepseekCoderApi, models.deepseekChatApi, models.deepseekReasonerApi], apiKeyUrl: "https://platform.deepseek.com/api_keys", }, together: { @@ -427,7 +427,8 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n }, ...completionParamsInputsConfigs, ], - packages: [models.llama318BChat, models.mistralChat].map((p) => { + packages: [models.llama318BChat, models.mistralChat, + models.deepseekR1Chat, models.deepseekV3Chat].map((p) => { p.params.contextLength = 4096; return p; }), @@ -785,7 +786,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo askSage: { title: "Ask Sage", provider: "askSage", - icon: "ask-Sage.png", + icon: "ask-sage.png", description: "The Ask Sage API provides seamless access to LLMs including OpenAI, Anthropic, Meta, Mistral, and more.", longDescription: `To get access to the Ask Sage API, obtain your API key from the [Ask Sage platform](https://chat.asksage.ai/) for all other models.`, diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index d391f5ef2..f1617a1c8 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -26,7 +26,7 @@ function MorePage() { return (
    - navigate("/")} title="Chat" /> + navigate("/")} title="Chat" />
    diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx new file mode 100644 index 000000000..9ee287e8b --- /dev/null +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -0,0 +1,91 @@ +import { Listbox } from "@headlessui/react"; +import { + ChevronDownIcon, + UserCircleIcon, + BuildingOfficeIcon, +} from "@heroicons/react/24/outline"; +import { useState } from "react"; +import { useAuth } from "../../context/Auth"; +import { setOrgId } from "../../redux/thunks/setOrgId"; +import { useAppDispatch } from "../../redux/hooks"; + +const USER_PROFILE_VAL = "personal"; + +export function ScopeSelect() { + const { organizations, selectedOrganization } = useAuth(); + const [value, setValue] = useState( + selectedOrganization?.id || USER_PROFILE_VAL, + ); + const dispatch = useAppDispatch(); + + const handleChange = (newValue: string) => { + setValue(newValue); + + const orgId = newValue === USER_PROFILE_VAL ? null : newValue; + dispatch(setOrgId(orgId)); + }; + const selectedDisplay = + value === USER_PROFILE_VAL + ? { name: "Personal", iconUrl: null } + : organizations.find((org) => org.id === value); + + return ( + +
    + +
    +
    + {selectedDisplay?.iconUrl ? ( + + ) : ( + + )} + + {selectedDisplay?.name || "Select Organization"} + +
    +
    +
    + + + {organizations.length > 0 && ( + <> +
    + Organizations +
    + {organizations.map((org) => ( + +
    + {org.iconUrl ? ( + + ) : ( + + )} + {org.name} +
    +
    + ))} + +
    + + )} + + +
    + + Personal +
    +
    + +
    + + ); +} diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx new file mode 100644 index 000000000..3f9cc611b --- /dev/null +++ b/gui/src/pages/config/index.tsx @@ -0,0 +1,410 @@ +import { useContext, useEffect, useState } from "react"; +import { useNavigate } from "react-router-dom"; +import PageHeader from "../../components/PageHeader"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useNavigationListener } from "../../hooks/useNavigationListener"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; + +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { + SharedConfigSchema, + modifyContinueConfigWithSharedConfig, +} from "core/config/sharedConfig"; +import { Input, SecondaryButton } from "../../components"; +import NumberInput from "../../components/gui/NumberInput"; +import { Select } from "../../components/gui/Select"; +import ToggleSwitch from "../../components/gui/Switch"; +import { useAuth } from "../../context/Auth"; +import { updateConfig } from "../../redux/slices/configSlice"; +import { getFontSize } from "../../util"; +import { ScopeSelect } from "./ScopeSelect"; + +function ConfigPage() { + useNavigationListener(); + const dispatch = useAppDispatch(); + const navigate = useNavigate(); + const ideMessenger = useContext(IdeMessengerContext); + + const { selectedProfile, selectedOrganization, session } = useAuth(); + const config = useAppSelector((state) => state.config.config); + + function handleUpdate(sharedConfig: Partial) { + dispatch( + updateConfig(modifyContinueConfigWithSharedConfig(config, sharedConfig)), + ); + ideMessenger.post("config/updateSharedConfig", sharedConfig); + } + + const codeWrap = config.ui?.codeWrap ?? false; + const showChatScrollbar = config.ui?.showChatScrollbar ?? false; + const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; + const disableSessionTitles = config.disableSessionTitles ?? false; + const readResponseTTS = config.experimental?.readResponseTTS ?? false; + + const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; + const disableIndexing = config.disableIndexing ?? false; + + const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false; + const useChromiumForDocsCrawling = + config.experimental?.useChromiumForDocsCrawling ?? false; + const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top"; + const useAutocompleteMultilineCompletions = + config.tabAutocompleteOptions?.multilineCompletions ?? "auto"; + const fontSize = getFontSize(); + + const [hubEnabled, setHubEnabled] = useState(false); + + useEffect(() => { + ideMessenger.ide.getIdeSettings().then(({ continueTestEnvironment }) => { + setHubEnabled(continueTestEnvironment === "production"); + }); + }, [ideMessenger]); + + // Disable autocomplete + const disableAutocompleteInFiles = ( + config.tabAutocompleteOptions?.disableInFiles ?? [] + ).join(", "); + const [formDisableAutocomplete, setFormDisableAutocomplete] = useState( + disableAutocompleteInFiles, + ); + const cancelChangeDisableAutocomplete = () => { + setFormDisableAutocomplete(disableAutocompleteInFiles); + }; + const handleDisableAutocompleteSubmit = () => { + handleUpdate({ + disableAutocompleteInFiles: formDisableAutocomplete + .split(",") + .map((val) => val.trim()) + .filter((val) => !!val), + }); + }; + + useEffect(() => { + // Necessary so that reformatted/trimmed values don't cause dirty state + setFormDisableAutocomplete(disableAutocompleteInFiles); + }, [disableAutocompleteInFiles]); + + // Workspace prompts + const promptPath = config.experimental?.promptPath || ""; + const [formPromptPath, setFormPromptPath] = useState(promptPath); + const cancelChangePromptPath = () => { + setFormPromptPath(promptPath); + }; + const handleSubmitPromptPath = () => { + handleUpdate({ + promptPath: formPromptPath || "", + }); + }; + + useEffect(() => { + // Necessary so that reformatted/trimmed values don't cause dirty state + setFormPromptPath(promptPath); + }, [promptPath]); + + function handleOpenConfig() { + if (!selectedProfile) { + return; + } + ideMessenger.post("config/openProfile", { + profileId: selectedProfile.id, + }); + } + + if (!selectedProfile) { + return ( +
    + navigate("/")} title="Chat" /> +
    +
    +

    Continue Config

    +
    +

    No config profile selected

    +
    +
    + ); + } + + return ( +
    + navigate("/")} title="Chat" /> + +
    + {hubEnabled && !!session && ( +
    +
    +

    Account

    + {selectedOrganization?.name && ( + + You are currently signed in to{" "} + + {selectedOrganization?.name} + + + )} +
    + + +
    + )} + +
    +

    Configuration

    + + + Open configuration file + +
    + +
    +
    +

    User settings

    +
    + +
    + + handleUpdate({ + codeWrap: !codeWrap, + }) + } + text="Wrap Codeblocks" + /> + + handleUpdate({ + displayRawMarkdown: !displayRawMarkdown, + }) + } + text="Display Raw Markdown" + /> + + handleUpdate({ + allowAnonymousTelemetry: !allowAnonymousTelemetry, + }) + } + text="Allow Anonymous Telemetry" + /> + + handleUpdate({ + disableIndexing: !disableIndexing, + }) + } + text="Disable Indexing" + /> + + + handleUpdate({ + disableSessionTitles: !disableSessionTitles, + }) + } + text="Disable Session Titles" + /> + + handleUpdate({ + readResponseTTS: !readResponseTTS, + }) + } + text="Response Text to Speech" + /> + + + handleUpdate({ + showChatScrollbar: !showChatScrollbar, + }) + } + text="Show Chat Scrollbar" + /> + + + handleUpdate({ + useAutocompleteCache: !useAutocompleteCache, + }) + } + text="Use Autocomplete Cache" + /> + + + handleUpdate({ + useChromiumForDocsCrawling: !useChromiumForDocsCrawling, + }) + } + text="Use Chromium for Docs Crawling" + /> + + + + + + + + +
    { + e.preventDefault(); + handleSubmitPromptPath(); + }} + > +
    + Workspace prompts path +
    + { + setFormPromptPath(e.target.value); + }} + /> +
    + {formPromptPath !== promptPath ? ( + <> +
    + +
    +
    + +
    + + ) : ( +
    + +
    + )} +
    +
    +
    +
    +
    { + e.preventDefault(); + handleDisableAutocompleteSubmit(); + }} + > +
    + Disable autocomplete in files +
    + { + setFormDisableAutocomplete(e.target.value); + }} + /> +
    + {formDisableAutocomplete !== disableAutocompleteInFiles ? ( + <> +
    + +
    +
    + +
    + + ) : ( +
    + +
    + )} +
    +
    +
    + + Comma-separated list of path matchers + +
    +
    +
    +
    +
    + ); +} + +export default ConfigPage; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 1bb5f5714..c91781417 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -77,6 +77,7 @@ import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; +import AssistantSelect from "../../components/modelSelection/platform/AssistantSelect"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -366,17 +367,25 @@ export function Chat() { return ( <> - {isInEditMode && ( + {(isInEditMode || usePlatform) && ( { - await dispatch(loadLastSession({ saveCurrentSession: false })); - dispatch(exitEditMode()); - }} + title={isInEditMode ? "Edit Mode" : ""} + onTitleClick={ + isInEditMode + ? async () => { + await dispatch( + loadLastSession({ saveCurrentSession: false }), + ); + dispatch(exitEditMode()); + } + : undefined + } + rightContent={usePlatform && } /> )} {widget} + 0 ? "flex-1" : ""}`} @@ -407,6 +416,7 @@ export function Chat() { isMainInput={false} editorState={item.editorState} contextItems={item.contextItems} + inputId={item.message.id} /> ) : item.message.role === "tool" ? ( @@ -503,6 +513,7 @@ export function Chat() { onEnter={(editorState, modifiers, editor) => sendInput(editorState, modifiers, undefined, editor) } + inputId={"main-editor"} /> )} diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx index 54b6cea0a..0d3c3429e 100644 --- a/gui/src/pages/history/index.tsx +++ b/gui/src/pages/history/index.tsx @@ -8,7 +8,7 @@ export default function HistoryPage() { return (
    - navigate("/")} title="Chat" /> + navigate("/")} title="Chat" />
    ); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 33ba33f59..fa6cfb03c 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -30,6 +30,7 @@ import { v4 as uuidv4 } from "uuid"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; import { findCurrentToolCall } from "../util"; +import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -46,6 +47,8 @@ type SessionState = { id: string; selectedProfileId: string; availableProfiles: ProfileDescription[]; + selectedOrganizationId: string | null; + availableOrganizations: OrganizationDescription[]; streamAborter: AbortController; codeToEdit: CodeToEdit[]; curCheckpointIndex: number; @@ -57,6 +60,7 @@ type SessionState = { states: ApplyState[]; curIndex: number; }; + newestCodeblockForInput: Record; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -96,8 +100,11 @@ const initialState: SessionState = { packageSlug: "", versionSlug: "", }, + iconUrl: "", }, ], + selectedOrganizationId: "", + availableOrganizations: [], curCheckpointIndex: 0, streamAborter: new AbortController(), codeToEdit: [], @@ -108,6 +115,7 @@ const initialState: SessionState = { curIndex: 0, }, lastSessionId: undefined, + newestCodeblockForInput: {}, }; export const sessionSlice = createSlice({ @@ -362,9 +370,30 @@ export const sessionSlice = createSlice({ } else { // Add to the existing message if (message.content) { - // Note this only works because new message above - // was already rendered from parts to string - lastMessage.content += renderChatMessage(message); + const messageContent = renderChatMessage(message); + if (messageContent.includes("")) { + lastItem.reasoning = { + startAt: Date.now(), + active: true, + text: messageContent.replace("", "").trim(), + }; + } else if ( + lastItem.reasoning?.active && + messageContent.includes("") + ) { + const [reasoningEnd, answerStart] = + messageContent.split(""); + lastItem.reasoning.text += reasoningEnd.trimEnd(); + lastItem.reasoning.active = false; + lastItem.reasoning.endAt = Date.now(); + lastMessage.content += answerStart.trimStart(); + } else if (lastItem.reasoning?.active) { + lastItem.reasoning.text += messageContent; + } else { + // Note this only works because new message above + // was already rendered from parts to string + lastMessage.content += messageContent; + } } else if ( message.role === "assistant" && message.toolCalls?.[0] && @@ -535,6 +564,29 @@ export const sessionSlice = createSlice({ : payload[0]?.id, }; }, + setSelectedOrganizationId: ( + state, + { payload }: PayloadAction, + ) => { + return { + ...state, + selectedOrganizationId: payload, + }; + }, + setAvailableOrganizations: ( + state, + { payload }: PayloadAction, + ) => { + return { + ...state, + availableOrganizations: payload, + selectedOrganizationId: payload.find( + (org) => org.id === state.selectedOrganizationId, + ) + ? state.selectedOrganizationId + : payload[0]?.id, + }; + }, updateCurCheckpoint: ( state, { payload }: PayloadAction<{ filepath: string; content: string }>, @@ -626,6 +678,17 @@ export const sessionSlice = createSlice({ setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, + setNewestCodeblocksForInput: ( + state, + { + payload, + }: PayloadAction<{ + inputId: string; + contextItemId: string; + }>, + ) => { + state.newestCodeblockForInput[payload.inputId] = payload.contextItemId; + }, }, selectors: { selectIsGatheringContext: (state) => { @@ -652,6 +715,9 @@ export const sessionSlice = createSlice({ selectAvailableProfiles: (state) => { return state.availableProfiles; }, + selectAvailableOrganizations: (state) => { + return state.availableOrganizations; + }, }, extraReducers: (builder) => { addPassthroughCases(builder, [streamResponseThunk]); @@ -703,6 +769,7 @@ export const { clearLastEmptyResponse, setMainEditorContentTrigger, setSelectedProfileId, + setSelectedOrganizationId, deleteMessage, setIsGatheringContext, updateCurCheckpoint, @@ -716,6 +783,7 @@ export const { setCalling, cancelToolCall, setAvailableProfiles, + setAvailableOrganizations, acceptToolCall, setToolGenerated, setToolCallOutput, @@ -724,6 +792,7 @@ export const { addSessionMetadata, updateSessionMetadata, deleteSessionMetadata, + setNewestCodeblocksForInput, } = sessionSlice.actions; export const { @@ -732,6 +801,7 @@ export const { selectIsSingleRangeEditOrInsertion, selectHasCodeToEdit, selectAvailableProfiles, + selectAvailableOrganizations, } = sessionSlice.selectors; export default sessionSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 4432b3be6..d716a6446 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -31,11 +31,17 @@ const rootReducer = combineReducers({ }); const saveSubsetFilters = [ - createFilter("session", ["history", "sessionId"]), + createFilter("session", [ + "history", + "sessionId", + "selectedOrganizationId", + "selectedProfileId", + ]), // Don't persist any of the edit state for now createFilter("editModeState", []), createFilter("config", ["defaultModelTitle"]), createFilter("ui", ["toolSettings", "useTools"]), + createFilter("indexing", []), ]; const migrations: MigrationManifest = { diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 0883ec3eb..8bae5227e 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -10,6 +10,8 @@ import resolveEditorContent from "../../components/mainInput/resolveInput"; import { ThunkApiType } from "../store"; import { selectDefaultModel } from "../slices/configSlice"; import { findUriInDirs, getUriPathBasename } from "core/util/uri"; +import * as URI from "uri-js"; +import { v4 as uuidv4 } from "uuid"; export const gatherContext = createAsyncThunk< { @@ -34,7 +36,7 @@ export const gatherContext = createAsyncThunk< const defaultContextProviders = state.config.config.experimental?.defaultContext ?? []; - if (!state.config.defaultModelTitle) { + if (!defaultModel) { console.error( "gatherContext thunk: Cannot gather context, no model selected", ); @@ -49,46 +51,52 @@ export const gatherContext = createAsyncThunk< ideMessenger: extra.ideMessenger, defaultContextProviders, dispatch, - selectedModelTitle: state.config.defaultModelTitle, + selectedModelTitle: defaultModel.title, }); // Automatically use currently open file if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; - const currentFile = await extra.ideMessenger.ide.getCurrentFile(); - if (currentFile) { - let currentFileContents = currentFile.contents; - if (usingFreeTrial) { - currentFileContents = currentFile.contents - .split("\n") - .slice(0, 1000) - .join("\n"); - } - if ( - !selectedContextItems.find( - (item) => item.uri?.value === currentFile.path, - ) - ) { + const currentFileResponse = await extra.ideMessenger.request( + "context/getContextItems", + { + name: "currentFile", + query: "non-mention-usage", + fullInput: "", + selectedCode: [], + selectedModelTitle: defaultModel.title, + }, + ); + if (currentFileResponse.status === "success") { + const items = currentFileResponse.content; + if (items.length > 0) { + const currentFile = items[0]; + const uri = currentFile.uri?.value; + // don't add the file if it's already in the context items - selectedContextItems.unshift({ - content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${ - findUriInDirs( - currentFile.path, - await extra.ideMessenger.ide.getWorkspaceDirs(), - ).relativePathOrBasename - }\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getUriPathBasename(currentFile.path)}`, - description: currentFile.path, - id: { - itemId: currentFile.path, + if ( + uri && + !selectedContextItems.find( + (item) => item.uri?.value && URI.equal(item.uri.value, uri), + ) + ) { + // Limit to 1000 lines if using free trial + if (usingFreeTrial) { + currentFile.content = currentFile.content + .split("\n") + .slice(0, 1000) + .join("\n"); + if (!currentFile.content.endsWith("```")) { + currentFile.content += "\n```"; + } + } + currentFile.id = { providerTitle: "file", - }, - uri: { - type: "file", - value: currentFile.path, - }, - }); + itemId: uri, + }; + selectedContextItems.unshift(currentFile); + } } } } diff --git a/gui/src/redux/thunks/setOrgId.ts b/gui/src/redux/thunks/setOrgId.ts new file mode 100644 index 000000000..9db496365 --- /dev/null +++ b/gui/src/redux/thunks/setOrgId.ts @@ -0,0 +1,13 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { setSelectedOrganizationId } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; + +export const setOrgId = createAsyncThunk( + "profile/setOrgId", + async (id, { dispatch, extra }) => { + dispatch(setSelectedOrganizationId(id)); + extra.ideMessenger.post("didChangeSelectedOrg", { + id, + }); + }, +); diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index 233589f34..cb00d2680 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -1,6 +1,7 @@ import _ from "lodash"; import { getLocalStorage } from "./localStorage"; import { KeyboardEvent } from "react"; +import { ProfileDescription } from "core/config/ProfileLifecycleManager"; type Platform = "mac" | "linux" | "windows" | "unknown"; @@ -105,3 +106,7 @@ export function updatedObj(old: any, pathToValue: { [key: string]: any }) { return newObject; } + +export function isLocalProfile(profile: ProfileDescription): boolean { + return profile.id === "local"; +} diff --git a/gui/src/util/navigation.ts b/gui/src/util/navigation.ts index 2416226d8..eed39333d 100644 --- a/gui/src/util/navigation.ts +++ b/gui/src/util/navigation.ts @@ -2,6 +2,7 @@ export const ROUTES = { HOME: "/", CONFIG_ERROR: "/config-error", + CONFIG: "/config", MORE: "/more", // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`, }; diff --git a/keycaps-todo.md b/keycaps-todo.md new file mode 100644 index 000000000..0004cd0ad --- /dev/null +++ b/keycaps-todo.md @@ -0,0 +1,15 @@ +gui\src\components\mainInput\TutorialCard.tsx + +![image](https://github.com/user-attachments/assets/2e682fe1-b5b4-4d2d-a615-645b409fefb1) + +![image](https://github.com/user-attachments/assets/d4b5f474-c8b8-478e-867d-aa9f8a2f0fbb) + +gui\src\components\modelSelection\ModelSelect.tsx + +![image](https://github.com/user-attachments/assets/346b6774-fa3b-462c-af25-fe6264457387) + +![image](https://github.com/user-attachments/assets/2881c290-f5a6-4b3d-8f36-8fece492e346) + +gui\src\components\modelSelection\platform\AssistantSelect.tsx + +??? diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 5ba03b8cc..8a0806d7b 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -133,7 +133,6 @@ export type UiOptions = z.infer; export const tabAutocompleteOptionsSchema = z.object({ disable: z.boolean(), - useFileSuffix: z.boolean(), maxPromptTokens: z.number(), debounceDelay: z.number(), maxSuffixPercentage: z.number(), diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 85474ad17..c3c5419a9 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.16", + "version": "1.0.23", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/index.ts b/packages/config-yaml/src/index.ts index 9ebf6cb32..0fcd5ae10 100644 --- a/packages/config-yaml/src/index.ts +++ b/packages/config-yaml/src/index.ts @@ -3,6 +3,7 @@ export * from "./interfaces/index.js"; export * from "./interfaces/SecretResult.js"; export * from "./interfaces/slugs.js"; export * from "./load/clientRender.js"; +export * from "./load/getBlockType.js"; export * from "./load/merge.js"; export * from "./load/proxySecretResolution.js"; export * from "./load/unroll.js"; diff --git a/packages/config-yaml/src/interfaces/SecretResult.ts b/packages/config-yaml/src/interfaces/SecretResult.ts index 987b33676..b15940d6e 100644 --- a/packages/config-yaml/src/interfaces/SecretResult.ts +++ b/packages/config-yaml/src/interfaces/SecretResult.ts @@ -4,6 +4,7 @@ export enum SecretType { User = "user", Package = "package", Organization = "organization", + NotFound = "not_found", } export interface OrgSecretLocation { @@ -24,18 +25,34 @@ export interface UserSecretLocation { secretName: string; } +/** + * If not found in user/package/org secrets, then there's a chance it's in + * - the on-prem proxy + * - models add-on + * - free trial + */ +export interface NotFoundSecretLocation { + secretType: SecretType.NotFound; + secretName: string; +} + export type SecretLocation = | OrgSecretLocation | PackageSecretLocation - | UserSecretLocation; + | UserSecretLocation + | NotFoundSecretLocation; export function encodeSecretLocation(secretLocation: SecretLocation): string { if (secretLocation.secretType === SecretType.Organization) { return `${SecretType.Organization}:${secretLocation.orgSlug}/${secretLocation.secretName}`; } else if (secretLocation.secretType === SecretType.User) { return `${SecretType.User}:${secretLocation.userSlug}/${secretLocation.secretName}`; - } else { + } else if (secretLocation.secretType === SecretType.Package) { return `${SecretType.Package}:${encodePackageSlug(secretLocation.packageSlug)}/${secretLocation.secretName}`; + } else if (secretLocation.secretType === SecretType.NotFound) { + return `${SecretType.NotFound}:${secretLocation.secretName}`; + } else { + throw new Error(`Invalid secret type: ${secretLocation}`); } } @@ -63,6 +80,11 @@ export function decodeSecretLocation(secretLocation: string): SecretLocation { packageSlug: { ownerSlug: parts[0], packageSlug: parts[1] }, secretName, }; + case SecretType.NotFound: + return { + secretType: SecretType.NotFound, + secretName, + }; default: throw new Error(`Invalid secret type: ${secretType}`); } @@ -70,6 +92,7 @@ export function decodeSecretLocation(secretLocation: string): SecretLocation { export interface NotFoundSecretResult { found: false; + secretLocation: NotFoundSecretLocation; fqsn: FQSN; } diff --git a/packages/config-yaml/src/interfaces/index.ts b/packages/config-yaml/src/interfaces/index.ts index 8ad1d9c38..3bbd17d92 100644 --- a/packages/config-yaml/src/interfaces/index.ts +++ b/packages/config-yaml/src/interfaces/index.ts @@ -69,7 +69,7 @@ export async function resolveFQSN( secretLocation, value: secret, }; - } else { + } else if (secretLocation.secretType !== SecretType.NotFound) { return { found: true, fqsn, @@ -81,6 +81,10 @@ export async function resolveFQSN( return { found: false, + secretLocation: { + secretName: fqsn.secretName, + secretType: SecretType.NotFound, + }, fqsn, }; } diff --git a/packages/config-yaml/src/load/clientRender.ts b/packages/config-yaml/src/load/clientRender.ts index cf9b6ba91..63bca7e0e 100644 --- a/packages/config-yaml/src/load/clientRender.ts +++ b/packages/config-yaml/src/load/clientRender.ts @@ -5,18 +5,18 @@ import { SecretLocation, } from "../interfaces/SecretResult.js"; import { decodeFQSN, encodeFQSN, FQSN } from "../interfaces/slugs.js"; -import { ConfigYaml } from "../schemas/index.js"; +import { AssistantUnrolled } from "../schemas/index.js"; import { fillTemplateVariables, getTemplateVariables, - parseConfigYaml, + parseAssistantUnrolled, } from "./unroll.js"; export async function clientRender( unrolledConfigContent: string, secretStore: SecretStore, platformClient?: PlatformClient, -): Promise { +): Promise { // 1. First we need to get a list of all the FQSNs that are required to render the config const secrets = getTemplateVariables(unrolledConfigContent); @@ -45,14 +45,6 @@ export async function clientRender( continue; } - if (!secretResult.found) { - // When a secret isn't found anywhere, we keep it templated as just the secret name - // in case it can be found in the on-prem proxy's env - secretsTemplateData["secrets." + encodeFQSN(secretResult.fqsn)] = - `\${{ secrets.${secretResult.fqsn.secretName} }}`; - continue; - } - if ("value" in secretResult) { secretStore.set(secretResult.fqsn.secretName, secretResult.value); } @@ -71,7 +63,7 @@ export async function clientRender( ); // 6. The rendered YAML is parsed and validated again - const parsedYaml = parseConfigYaml(renderedYaml); + const parsedYaml = parseAssistantUnrolled(renderedYaml); // 7. We update any of the items with the proxy version if there are un-rendered secrets const finalConfig = useProxyForUnrenderedSecrets(parsedYaml); @@ -102,7 +94,9 @@ function getUnrenderedSecretLocation( return undefined; } -function useProxyForUnrenderedSecrets(config: ConfigYaml): ConfigYaml { +function useProxyForUnrenderedSecrets( + config: AssistantUnrolled, +): AssistantUnrolled { if (config.models) { for (let i = 0; i < config.models.length; i++) { const apiKeyLocation = getUnrenderedSecretLocation( diff --git a/packages/config-yaml/src/load/getBlockType.ts b/packages/config-yaml/src/load/getBlockType.ts new file mode 100644 index 000000000..680c3b644 --- /dev/null +++ b/packages/config-yaml/src/load/getBlockType.ts @@ -0,0 +1,32 @@ +import { ConfigYaml } from "../schemas/index.js"; + +export type BlockType = + | "models" + | "context" + | "docs" + | "tools" + | "mcpServers" + | "data" + | "rules" + | "prompts"; +export function getBlockType(block: ConfigYaml): BlockType { + if (block.context?.length) { + return "context"; + } else if (block.models?.length) { + return "models"; + } else if (block.docs?.length) { + return "docs"; + } else if (block.tools?.length) { + return "tools"; + } else if (block.mcpServers?.length) { + return "mcpServers"; + } else if (block.data?.length) { + return "data"; + } else if (block.rules?.length) { + return "rules"; + } else if (block.prompts?.length) { + return "prompts"; + } else { + throw new Error("Unknown block type"); + } +} diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 54774c5a3..12a808b8b 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -1,12 +1,19 @@ import * as YAML from "yaml"; import { Registry } from "../interfaces/index.js"; import { - PackageSlug, decodeFullSlug, encodePackageSlug, + FullSlug, + PackageSlug, } from "../interfaces/slugs.js"; -import { ConfigYaml, configYamlSchema } from "../schemas/index.js"; -import { mergePackages } from "./merge.js"; +import { + AssistantUnrolled, + assistantUnrolledSchema, + Block, + blockSchema, + ConfigYaml, + configYamlSchema, +} from "../schemas/index.js"; export function parseConfigYaml(configYaml: string): ConfigYaml { try { @@ -14,7 +21,28 @@ export function parseConfigYaml(configYaml: string): ConfigYaml { const result = configYamlSchema.parse(parsed); return result; } catch (e: any) { - throw new Error(`Failed to parse config yaml: ${e.message}`); + console.log(configYaml); + throw new Error(`Failed to parse rolled assistant: ${e.message}`); + } +} + +export function parseAssistantUnrolled(configYaml: string): AssistantUnrolled { + try { + const parsed = YAML.parse(configYaml); + const result = assistantUnrolledSchema.parse(parsed); + return result; + } catch (e: any) { + throw new Error(`Failed to parse unrolled assistant: ${e.message}`); + } +} + +export function parseBlock(configYaml: string): Block { + try { + const parsed = YAML.parse(configYaml); + const result = blockSchema.parse(parsed); + return result; + } catch (e: any) { + throw new Error(`Failed to parse block: ${e.message}`); } } @@ -43,29 +71,8 @@ export function fillTemplateVariables( }); } -export async function unrollImportedPackage( - pkgImport: NonNullable[number], - parentPackages: PackageSlug[], - registry: Registry, -): Promise { - const { uses, with: params } = pkgImport; - - const fullSlug = decodeFullSlug(uses); - - // Request the content from the registry - const rawContent = await registry.getContent(fullSlug); - - // Convert the raw YAML to unrolled config - return await unrollPackageFromContent( - rawContent, - params, - parentPackages, - registry, - ); -} - export interface TemplateData { - params: Record | undefined; + inputs: Record | undefined; secrets: Record | undefined; continue: {}; } @@ -75,9 +82,9 @@ function flattenTemplateData( ): Record { const flattened: Record = {}; - if (templateData.params) { - for (const [key, value] of Object.entries(templateData.params)) { - flattened[`params.${key}`] = value; + if (templateData.inputs) { + for (const [key, value] of Object.entries(templateData.inputs)) { + flattened[`inputs.${key}`] = value; } } if (templateData.secrets) { @@ -116,57 +123,159 @@ function extractFQSNMap( return secretToFQSNMap(secrets, parentPackages); } -export async function unrollPackageFromContent( - rawContent: string, - params: Record | undefined, - packagePath: PackageSlug[], +export async function unrollAssistant( + fullSlug: string, registry: Registry, -): Promise { - // Collect template data +): Promise { + const assistantSlug = decodeFullSlug(fullSlug); + + // Request the content from the registry + const rawContent = await registry.getContent(assistantSlug); + return unrollAssistantFromContent(assistantSlug, rawContent, registry); +} + +export async function unrollAssistantFromContent( + assistantSlug: FullSlug, + rawYaml: string, + registry: Registry, +): Promise { + // Convert the raw YAML to unrolled config const templateData: TemplateData = { - // params are passed from the parent package - params: params, + // no inputs to an assistant + inputs: {}, // at this stage, secrets are mapped to a (still templated) FQSN - secrets: extractFQSNMap(rawContent, packagePath), + secrets: extractFQSNMap(rawYaml, [assistantSlug]), // Built-in variables continue: {}, }; + // Render the template const templatedYaml = fillTemplateVariables( - rawContent, + rawYaml, flattenTemplateData(templateData), ); + // Parse string to Zod-validated YAML let parsedYaml = parseConfigYaml(templatedYaml); - const unrolledChildPackages = await Promise.all( - parsedYaml.packages?.map((pkg) => { - const pkgSlug = decodeFullSlug(pkg.uses); - return unrollImportedPackage(pkg, [...packagePath, pkgSlug], registry); - }) ?? [], + // Unroll blocks + const unrolledAssistant = await unrollBlocks( + parsedYaml, + assistantSlug, + registry, ); - delete parsedYaml.packages; - for (const childPkg of unrolledChildPackages) { - parsedYaml = mergePackages(parsedYaml, childPkg); + return unrolledAssistant; +} + +export async function unrollBlocks( + assistant: ConfigYaml, + assistantFullSlug: FullSlug, + registry: Registry, +): Promise { + const unrolledAssistant: AssistantUnrolled = { + name: assistant.name, + version: assistant.version, + }; + + const sections: (keyof Omit)[] = [ + "models", + "context", + "data", + "tools", + "mcpServers", + "prompts", + "docs", + ]; + + // For each section, replace "uses/with" blocks with the real thing + for (const section of sections) { + if (assistant[section]) { + const sectionBlocks: any[] = []; + + for (const unrolledBlock of assistant[section]) { + // "uses/with" block + if ("uses" in unrolledBlock) { + const blockConfigYaml = await resolveBlock( + decodeFullSlug(unrolledBlock.uses), + unrolledBlock.with, + assistantFullSlug, + registry, + ); + const block = blockConfigYaml[section]?.[0]; + if (block) { + sectionBlocks.push( + mergeOverrides(block, unrolledBlock.override ?? {}), + ); + } + } else { + // Normal block + sectionBlocks.push(unrolledBlock); + } + } + + unrolledAssistant[section] = sectionBlocks; + } } + // Rules are a bit different because they're just strings, so handle separately + if (assistant.rules) { + const rules: string[] = []; + for (const rule of assistant.rules) { + if (typeof rule === "string") { + rules.push(rule); + } else { + const blockConfigYaml = await resolveBlock( + decodeFullSlug(rule.uses), + rule.with, + assistantFullSlug, + registry, + ); + const block = blockConfigYaml.rules?.[0]; + if (block) { + rules.push(block); + } + } + } + + unrolledAssistant.rules = rules; + } + + return unrolledAssistant; +} + +export async function resolveBlock( + fullSlug: FullSlug, + inputs: Record | undefined, + parentFullSlug: FullSlug, + registry: Registry, +): Promise { + // Retrieve block raw yaml + const rawYaml = await registry.getContent(fullSlug); + + // Render template variables + const templateData: TemplateData = { + inputs, + secrets: extractFQSNMap(rawYaml, [parentFullSlug, fullSlug]), + continue: {}, + }; + const templatedYaml = fillTemplateVariables( + rawYaml, + flattenTemplateData(templateData), + ); + + const parsedYaml = parseBlock(templatedYaml); return parsedYaml; } -/** - * Loading an assistant is equivalent to loading a package without params - */ -export async function unrollAssistant( - fullSlug: string, - registry: Registry, -): Promise { - const packageSlug = decodeFullSlug(fullSlug); - return await unrollImportedPackage( - { - uses: fullSlug, - }, - [packageSlug], - registry, - ); +export function mergeOverrides>( + block: T, + overrides: Partial, +): T { + for (const key in overrides) { + if (overrides.hasOwnProperty(key)) { + block[key] = overrides[key]!; + } + } + return block; } diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 394c1dd41..557e40b28 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,25 +1,21 @@ import * as z from "zod"; -import { modelSchema } from "./models.js"; - -const packageSchema = z.object({ - uses: z.string(), - with: z.any().optional(), -}); +import { modelSchema, partialModelSchema } from "./models.js"; export const dataSchema = z.object({ - provider: z.string(), + destination: z.string(), + levels: z.string().optional(), }); export const contextSchema = z.object({ - uses: z.string(), - with: z.any().optional(), + provider: z.string(), + params: z.any().optional(), }); const toolSchema = z.object({ name: z.string(), description: z.string(), - url: z.string(), - apiKey: z.string().optional(), + run: z.string(), + params: z.any().optional(), }); const mcpServerSchema = z.object({ @@ -42,10 +38,55 @@ const docSchema = z.object({ faviconUrl: z.string().optional(), }); +export const blockItemWrapperSchema = (schema: T) => + z.object({ + uses: z.string(), + with: z.record(z.string()).optional(), + override: schema.partial().optional(), + }); + +export const blockOrSchema = (schema: T) => + z.union([schema, blockItemWrapperSchema(schema)]); + export const configYamlSchema = z.object({ name: z.string(), version: z.string(), - packages: z.array(packageSchema).optional(), + models: z + .array( + z.union([ + modelSchema, + z.object({ + uses: z.string(), + with: z.record(z.string()).optional(), + override: partialModelSchema.optional(), + }), + ]), + ) + .optional(), + context: z.array(blockOrSchema(contextSchema)).optional(), + data: z.array(blockOrSchema(dataSchema)).optional(), + tools: z.array(blockOrSchema(toolSchema)).optional(), + mcpServers: z.array(blockOrSchema(mcpServerSchema)).optional(), + rules: z + .array( + z.union([ + z.string(), + z.object({ + uses: z.string(), + with: z.record(z.string()).optional(), + }), + ]), + ) + .optional(), + prompts: z.array(blockOrSchema(promptSchema)).optional(), + docs: z.array(blockOrSchema(docSchema)).optional(), +}); + +export type ConfigYaml = z.infer; + +export const assistantUnrolledSchema = z.object({ + name: z.string(), + version: z.string(), models: z.array(modelSchema).optional(), context: z.array(contextSchema).optional(), data: z.array(dataSchema).optional(), @@ -56,10 +97,24 @@ export const configYamlSchema = z.object({ docs: z.array(docSchema).optional(), }); -export type ConfigYaml = z.infer; +export type AssistantUnrolled = z.infer; -export const unrolledConfigYamlSchema = configYamlSchema.omit({ - packages: true, -}); +export const blockSchema = z + .object({ + name: z.string(), + version: z.string(), + }) + .and( + z.union([ + z.object({ models: z.array(modelSchema).length(1) }), + z.object({ context: z.array(contextSchema).length(1) }), + z.object({ data: z.array(dataSchema).length(1) }), + z.object({ tools: z.array(toolSchema).length(1) }), + z.object({ mcpServers: z.array(mcpServerSchema).length(1) }), + z.object({ rules: z.array(z.string()).length(1) }), + z.object({ prompts: z.array(promptSchema).length(1) }), + z.object({ docs: z.array(docSchema).length(1) }), + ]), + ); -export type UnrolledConfigYaml = z.infer; +export type Block = z.infer; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 713d2cc2d..3037d750f 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -64,4 +64,20 @@ export const modelSchema = z.union([ }), ]); +export const partialModelSchema = z.union([ + z + .object({ + ...baseModelFields, + provider: z.literal("continue-proxy"), + apiKeyLocation: z.string(), + }) + .partial(), + z + .object({ + ...baseModelFields, + provider: z.string().refine((val) => val !== "continue-proxy"), + }) + .partial(), +]); + export type ModelConfig = z.infer; diff --git a/packages/config-yaml/src/validation.ts b/packages/config-yaml/src/validation.ts index 7af938d99..766f852bd 100644 --- a/packages/config-yaml/src/validation.ts +++ b/packages/config-yaml/src/validation.ts @@ -28,6 +28,9 @@ export function validateConfigYaml( } config.models?.forEach((model) => { + if ("uses" in model) { + return; + } // Max tokens not too close to context length if ( model.defaultCompletionOptions?.contextLength && diff --git a/packages/config-yaml/test/index.test.ts b/packages/config-yaml/test/index.test.ts index 3f75ff092..8bba163ce 100644 --- a/packages/config-yaml/test/index.test.ts +++ b/packages/config-yaml/test/index.test.ts @@ -29,7 +29,7 @@ describe("E2E Scenarios", () => { const packageSecrets: Record = { "test-org/assistant/ANTHROPIC_API_KEY": "sk-ant", - "test-org/models/GEMINI_API_KEY": "gemini-api-key", + "test-org/gemini/GEMINI_API_KEY": "gemini-api-key", }; const proxyEnvSecrets: Record = { @@ -100,22 +100,24 @@ describe("E2E Scenarios", () => { ); // Test that packages were correctly unrolled and params replaced - expect(unrolledConfig.models?.length).toBe(4); + expect(unrolledConfig.models?.length).toBe(3); expect(unrolledConfig.models?.[0].apiKey).toBe( "${{ secrets.test-org/assistant/OPENAI_API_KEY }}", ); - expect(unrolledConfig.models?.[1].apiKey).toBe("sk-456"); - expect(unrolledConfig.models?.[2].apiKey).toBe( - "${{ secrets.test-org/assistant/test-org/models/ANTHROPIC_API_KEY }}", + expect(unrolledConfig.models?.[1].apiKey).toBe( + "${{ secrets.test-org/assistant/test-org/gemini/GEMINI_API_KEY }}", ); - expect(unrolledConfig.models?.[3].apiKey).toBe( - "${{ secrets.test-org/assistant/test-org/models/GEMINI_API_KEY }}", + expect(unrolledConfig.models?.[2].apiKey).toBe( + "${{ secrets.test-org/assistant/ANTHROPIC_API_KEY }}", ); - expect(unrolledConfig.rules?.length).toBe(3); + expect(unrolledConfig.rules?.length).toBe(2); expect(unrolledConfig.docs?.[0].startUrl).toBe( "https://docs.python.org/release/3.13.1", ); + expect(unrolledConfig.docs?.[0].rootUrl).toBe( + "https://docs.python.org/release/3.13.1", + ); const clientRendered = await clientRender( YAML.stringify(unrolledConfig), @@ -126,19 +128,18 @@ describe("E2E Scenarios", () => { // Test that user secrets were injected and others were changed to use proxy const anthropicSecretLocation = "package:test-org/assistant/ANTHROPIC_API_KEY"; - const geminiSecretLocation = "package:test-org/models/GEMINI_API_KEY"; + const geminiSecretLocation = "package:test-org/gemini/GEMINI_API_KEY"; expect(clientRendered.models?.[0].apiKey).toBe("sk-123"); - expect(clientRendered.models?.[1].apiKey).toBe("sk-456"); + expect(clientRendered.models?.[1].provider).toBe("continue-proxy"); + expect((clientRendered.models?.[1] as any).apiKeyLocation).toBe( + geminiSecretLocation, + ); + expect(clientRendered.models?.[1].apiKey).toBeUndefined(); expect(clientRendered.models?.[2].provider).toBe("continue-proxy"); expect((clientRendered.models?.[2] as any).apiKeyLocation).toBe( anthropicSecretLocation, ); expect(clientRendered.models?.[2].apiKey).toBeUndefined(); - expect(clientRendered.models?.[3].provider).toBe("continue-proxy"); - expect((clientRendered.models?.[3] as any).apiKeyLocation).toBe( - geminiSecretLocation, - ); - expect(clientRendered.models?.[3].apiKey).toBeUndefined(); // Test that proxy can correctly resolve secrets const decodedAnthropicSecretLocation = decodeSecretLocation( diff --git a/packages/config-yaml/test/packages/test-org/assistant.yaml b/packages/config-yaml/test/packages/test-org/assistant.yaml index 74fefc581..9099af2de 100644 --- a/packages/config-yaml/test/packages/test-org/assistant.yaml +++ b/packages/config-yaml/test/packages/test-org/assistant.yaml @@ -1,12 +1,14 @@ name: Assistant version: 0.0.1 -packages: - - uses: test-org/models +docs: - uses: test-org/docs with: version: 3.13.1 + +rules: - uses: test-org/rules + - Use KaTeX for math models: - name: gpt-5 @@ -14,5 +16,13 @@ models: model: gpt-5 apiKey: ${{ secrets.OPENAI_API_KEY }} -rules: - - Use KaTeX for math + - uses: test-org/gemini + override: + contextLength: 500000 + defaultCompletionOptions: + topP: 1.0 + apiBase: https://example.com + + - uses: test-org/claude35sonnet + with: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} diff --git a/packages/config-yaml/test/packages/test-org/claude35sonnet.yaml b/packages/config-yaml/test/packages/test-org/claude35sonnet.yaml new file mode 100644 index 000000000..0eda292d4 --- /dev/null +++ b/packages/config-yaml/test/packages/test-org/claude35sonnet.yaml @@ -0,0 +1,8 @@ +name: Claude 3.5 sonnet latest +version: 0.0.1 + +models: + - name: claude-3-5-sonnet-latest + provider: anthropic + model: claude-3-5-sonnet-latest + apiKey: ${{ inputs.ANTHROPIC_API_KEY }} diff --git a/packages/config-yaml/test/packages/test-org/docs.yaml b/packages/config-yaml/test/packages/test-org/docs.yaml index 1b540d227..10fa5b631 100644 --- a/packages/config-yaml/test/packages/test-org/docs.yaml +++ b/packages/config-yaml/test/packages/test-org/docs.yaml @@ -3,5 +3,5 @@ version: 0.0.1 docs: - name: Python - startUrl: https://docs.python.org/release/${{ params.version }} - rootUrl: https://docs.python.org/release/${{ params.version }} + startUrl: https://docs.python.org/release/${{ inputs.version }} + rootUrl: https://docs.python.org/release/${{ inputs.version }} diff --git a/packages/config-yaml/test/packages/test-org/gemini.yaml b/packages/config-yaml/test/packages/test-org/gemini.yaml new file mode 100644 index 000000000..6e4ea01b0 --- /dev/null +++ b/packages/config-yaml/test/packages/test-org/gemini.yaml @@ -0,0 +1,11 @@ +name: Gemini +version: 0.0.1 + +models: + - name: gemini + provider: gemini + model: gemini + apiKey: ${{ secrets.GEMINI_API_KEY }} + defaultCompletionOptions: + temperature: 0.7 + contextLength: 1000000 diff --git a/packages/config-yaml/test/packages/test-org/models.yaml b/packages/config-yaml/test/packages/test-org/models.yaml deleted file mode 100644 index f47831662..000000000 --- a/packages/config-yaml/test/packages/test-org/models.yaml +++ /dev/null @@ -1,18 +0,0 @@ -name: Models -version: 0.0.1 - -models: - - name: gpt-4 - provider: openai - model: gpt-4 - apiKey: sk-456 - - - name: claude-3-5-sonnet-latest - provider: anthropic - model: claude-3-5-sonnet-latest - apiKey: ${{ secrets.ANTHROPIC_API_KEY }} - - - name: gemini - provider: gemini - model: gemini - apiKey: ${{ secrets.GEMINI_API_KEY }} diff --git a/packages/config-yaml/test/packages/test-org/rules.yaml b/packages/config-yaml/test/packages/test-org/rules.yaml index 2a4f36a9e..4099af2a3 100644 --- a/packages/config-yaml/test/packages/test-org/rules.yaml +++ b/packages/config-yaml/test/packages/test-org/rules.yaml @@ -3,4 +3,3 @@ version: 0.0.1 rules: - Be kind - - Be concise diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index 5fd100a8b..b96461e4b 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -97,6 +97,13 @@ export const OpenAi: ModelProvider = { maxCompletionTokens: 65536, recommendedFor: ["chat"], }, + { + model: "o3-mini", + displayName: "o3 Mini", + contextLength: 128000, + maxCompletionTokens: 65536, + recommendedFor: ["chat"], + }, // embed { model: "text-embedding-3-large",