diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index f629f9331..ccc9e8a44 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -1,7 +1,7 @@ name: PR checks on: - pull_request: + pull_request_target: branches: - main paths: @@ -22,10 +22,22 @@ on: - ".github/workflows/**" jobs: + validate-pr: + runs-on: ubuntu-latest + environment: tests-requiring-secrets + steps: + - uses: actions/checkout@v4 + install-root: + needs: validate-pr runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + # This is important - it switches from the base repo to the fork + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -45,6 +57,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -70,8 +86,13 @@ jobs: core-checks: needs: install-core runs-on: ubuntu-latest + environment: tests-requiring-secrets steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -97,10 +118,14 @@ 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 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -132,6 +157,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -158,10 +187,14 @@ 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 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -194,10 +227,14 @@ 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 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -231,6 +268,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -262,6 +303,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -283,11 +328,14 @@ 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: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} - name: Cache node modules uses: actions/cache@v3 @@ -312,9 +360,13 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [ install-vscode, install-core ] + needs: [install-vscode, install-core] steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -344,9 +396,13 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [ install-vscode, install-core ] + needs: [install-vscode, install-core] steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -386,13 +442,19 @@ jobs: install-core, ] runs-on: ubuntu-latest + # Tests requiring secrets need approval from maintainers + environment: tests-requiring-secrets 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 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -451,10 +513,14 @@ 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 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -482,10 +548,13 @@ jobs: npm test jetbrains-tests: - needs: [ install-root, core-checks ] + needs: [install-root, core-checks] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} - uses: actions/cache@v4 with: @@ -578,4 +647,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/.vscode/launch.json b/.vscode/launch.json index cdb502c8c..7a5161729 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -38,6 +38,7 @@ "internalConsoleOptions": "openOnSessionStart", "cwd": "${workspaceFolder}/binary", "env": { + // "CONTROL_PLANE_ENV": "test", "CONTINUE_DEVELOPMENT": "true", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca26d38fe..b69b1fd44 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,7 +49,7 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti ## ✨ Suggest Enhancements -Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are +Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are: - Create an issue @@ -192,7 +192,7 @@ Continue has support for more than a dozen different LLM "providers", making it 1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example. -- `providerName` - the identifier for your provider +- `providerName` - the identifier for your provider. - At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion". 2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts). diff --git a/binary/package-lock.json b/binary/package-lock.json index 89ecc53cc..316fddcd2 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.10", + "@continuedev/config-yaml": "^1.0.16", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", 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/commands/index.ts b/core/commands/index.ts index 723a4d247..f4a0084da 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -9,7 +9,7 @@ export function slashFromCustomCommand( ): SlashCommand { return { name: customCommand.name, - description: customCommand.description, + description: customCommand.description ?? "", run: async function* ({ input, llm, history, ide }) { // Remove slash command prefix from input let userInput = input; diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 24987528a..edcf62071 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,3 +1,5 @@ +import * as fs from "node:fs"; + import { ControlPlaneClient, ControlPlaneSessionInfo, @@ -12,12 +14,15 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath } from "../util/paths.js"; +import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { ConfigResult, ConfigYaml } from "@continuedev/config-yaml"; +import { + AssistantUnrolled, + ConfigResult, + FullSlug, +} from "@continuedev/config-yaml"; import * as YAML from "yaml"; -import { controlPlaneEnv } from "../control-plane/env.js"; -import { usePlatform } from "../control-plane/flags.js"; +import { getControlPlaneEnv, useHub } from "../control-plane/env.js"; import { localPathToUri } from "../util/pathToUri.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, @@ -61,7 +66,7 @@ export class ConfigHandler { controlPlaneClient, writeLog, ); - this.profiles = [new ProfileLifecycleManager(localProfileLoader)]; + this.profiles = [new ProfileLifecycleManager(localProfileLoader, this.ide)]; this.selectedProfileId = localProfileLoader.description.id; // Always load local profile immediately in case control plane doesn't load @@ -97,9 +102,16 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; if (openProfileId === "local") { - await this.ide.openFile(localPathToUri(getConfigJsonPath())); + const ideInfo = await this.ide.getIdeInfo(); + const configYamlPath = getConfigYamlPath(ideInfo.ideType); + if (fs.existsSync(configYamlPath)) { + await this.ide.openFile(localPathToUri(configYamlPath)); + } else { + await this.ide.openFile(localPathToUri(getConfigJsonPath())); + } } else { - await this.ide.openUrl(`${controlPlaneEnv.APP_URL}${openProfileId}`); + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + await this.ide.openUrl(`${env.APP_URL}platform/${openProfileId}`); } } @@ -108,12 +120,9 @@ export class ConfigHandler { this.controlPlaneClient .listAssistants() .then(async (assistants) => { - this.profiles = this.profiles.filter( - (profile) => profile.profileDescription.id === "local", - ); - await Promise.all( + 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), @@ -126,21 +135,25 @@ export class ConfigHandler { { ...assistant.configResult, config: renderedConfig }, assistant.ownerSlug, assistant.packageSlug, + assistant.configResult.config?.version ?? "latest", this.controlPlaneClient, this.ide, this.ideSettingsPromise, this.writeLog, this.reloadConfig.bind(this), ); - this.profiles = [ - ...this.profiles.filter( - (profile) => profile.profileDescription.id === "local", - ), - new ProfileLifecycleManager(profileLoader), - ]; + + return new ProfileLifecycleManager(profileLoader, this.ide); }), ); + this.profiles = [ + ...this.profiles.filter( + (profile) => profile.profileDescription.id === "local", + ), + ...hubProfiles, + ]; + this.notifyProfileListeners( this.profiles.map((profile) => profile.profileDescription), ); @@ -168,15 +181,49 @@ export class ConfigHandler { } private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; + // We use this to keep track of whether we should reload the assistants + private lastFullSlugsList: FullSlug[] = []; + + private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean { + if (a.length !== b.length) { + return true; + } + for (let i = 0; i < a.length; i++) { + if (a[i].ownerSlug !== b[i].ownerSlug) { + return true; + } + if (a[i].packageSlug !== b[i].packageSlug) { + return true; + } + if (a[i].versionSlug !== b[i].versionSlug) { + return true; + } + } + return false; + } private async fetchControlPlaneProfiles() { - if (usePlatform()) { + if (await useHub(this.ideSettingsPromise)) { clearInterval(this.platformProfilesRefreshInterval); await this.loadPlatformProfiles(); - this.platformProfilesRefreshInterval = setInterval( - this.loadPlatformProfiles.bind(this), - PlatformProfileLoader.RELOAD_INTERVAL, - ); + + // Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds + // If so, we do the full (more expensive) reload + this.platformProfilesRefreshInterval = setInterval(async () => { + const newFullSlugsList = + await this.controlPlaneClient.listAssistantFullSlugs(); + + if (newFullSlugsList) { + const shouldReload = this.fullSlugsListsDiffer( + newFullSlugsList, + this.lastFullSlugsList, + ); + if (shouldReload) { + await this.loadPlatformProfiles(); + } + this.lastFullSlugsList = newFullSlugsList; + } + }, PlatformProfileLoader.RELOAD_INTERVAL); } else { this.controlPlaneClient .listWorkspaces() @@ -194,7 +241,9 @@ export class ConfigHandler { this.writeLog, this.reloadConfig.bind(this), ); - this.profiles.push(new ProfileLifecycleManager(profileLoader)); + this.profiles.push( + new ProfileLifecycleManager(profileLoader, this.ide), + ); }); this.notifyProfileListeners( @@ -249,11 +298,12 @@ export class ConfigHandler { void this.reloadConfig(); } - updateControlPlaneSessionInfo( + async updateControlPlaneSessionInfo( sessionInfo: ControlPlaneSessionInfo | undefined, ) { this.controlPlaneClient = new ControlPlaneClient( Promise.resolve(sessionInfo), + this.ideSettingsPromise, ); this.fetchControlPlaneProfiles().catch((e) => { console.error("Failed to fetch control plane profiles: ", e); diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 88fc387c5..fa76c6b55 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -1,14 +1,21 @@ -import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; +import { + ConfigResult, + ConfigValidationError, + FullSlug, +} from "@continuedev/config-yaml"; import { BrowserSerializedContinueConfig, ContinueConfig, IContextProvider, + IDE, } from "../index.js"; import { finalToBrowserConfig } from "./load.js"; import { IProfileLoader } from "./profile/IProfileLoader.js"; export interface ProfileDescription { + fullSlug: FullSlug; + profileType: "control-plane" | "local" | "platform"; title: string; id: string; errors: ConfigValidationError[] | undefined; @@ -19,7 +26,10 @@ export class ProfileLifecycleManager { private savedBrowserConfigResult?: ConfigResult; private pendingConfigPromise?: Promise>; - constructor(private readonly profileLoader: IProfileLoader) {} + constructor( + private readonly profileLoader: IProfileLoader, + private readonly ide: IDE, + ) {} get profileDescription(): ProfileDescription { return this.profileLoader.description; @@ -87,7 +97,10 @@ export class ProfileLifecycleManager { config: undefined, }; } - const serializedConfig = finalToBrowserConfig(result.config); + const serializedConfig = await finalToBrowserConfig( + result.config, + this.ide, + ); return { ...result, config: serializedConfig, diff --git a/core/config/load.ts b/core/config/load.ts index 689f53ca5..da95ec5a8 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -63,7 +63,6 @@ import { } from "../util/paths"; import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; -import { usePlatform } from "../control-plane/flags"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -71,11 +70,14 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -// import { isSupportedLanceDbCpuTarget } from "./util"; -import { validateConfig } from "./validation.js"; +import { useHub } from "../control-plane/env"; import { localPathToUri } from "../util/pathToUri"; +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)) { @@ -111,11 +113,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}`); } @@ -135,13 +136,6 @@ function loadSerializedConfig( config.allowAnonymousTelemetry = true; } - if (config.ui?.getChatTitles === undefined) { - config.ui = { - ...config.ui, - getChatTitles: true, - }; - } - if (ideSettings.remoteConfigServerUrl) { try { const remoteConfigJson = resolveSerializedConfig( @@ -544,9 +538,10 @@ async function intermediateToFinalConfig( return { config: continueConfig, errors }; } -function finalToBrowserConfig( +async function finalToBrowserConfig( final: ContinueConfig, -): BrowserSerializedContinueConfig { + ide: IDE, +): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, models: final.models.map((m) => ({ @@ -579,7 +574,8 @@ function finalToBrowserConfig( experimental: final.experimental, docs: final.docs, tools: final.tools, - usePlatform: usePlatform(), + tabAutocompleteOptions: final.tabAutocompleteOptions, + usePlatform: await useHub(ide.getIdeSettings()), }; } @@ -763,7 +759,7 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { return readConfigJs(); } -async function loadFullConfigNode( +async function loadContinueConfigFromJson( ide: IDE, workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, @@ -795,8 +791,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); @@ -873,6 +877,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 38c7fb389..dfb111e1f 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -31,6 +31,12 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { ) { this.description = { id: workspaceId, + profileType: "control-plane", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, title: workspaceTitle, errors: undefined, }; diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 644e97069..cb8694bbc 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -10,6 +10,12 @@ export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; description: ProfileDescription = { id: LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, title: "Local Config", errors: undefined, }; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 5319097b3..12e166c2d 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -1,12 +1,10 @@ -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js"; -import * as YAML from "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 { clientRenderHelper } from "../yaml/clientRender.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -21,14 +19,15 @@ export interface PlatformConfigMetadata { } export default class PlatformProfileLoader implements IProfileLoader { - static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes + static RELOAD_INTERVAL = 1000 * 5; // 5 seconds description: ProfileDescription; constructor( - private configResult: ConfigResult, + private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, + versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, @@ -37,37 +36,15 @@ export default class PlatformProfileLoader implements IProfileLoader { ) { this.description = { id: `${ownerSlug}/${packageSlug}`, - title: `${ownerSlug}/${packageSlug}`, + profileType: "platform", + fullSlug: { + ownerSlug, + packageSlug, + versionSlug, + }, + title: `${ownerSlug}/${packageSlug}@${versionSlug}`, errors: configResult.errors, }; - - setInterval(async () => { - const assistants = await this.controlPlaneClient.listAssistants(); - const newConfigResult = assistants.find( - (assistant) => - assistant.packageSlug === this.packageSlug && - assistant.ownerSlug === this.ownerSlug, - )?.configResult; - if (!newConfigResult) { - return; - } - - let renderedConfig: ConfigYaml | undefined = undefined; - if (newConfigResult.config) { - renderedConfig = await clientRenderHelper( - YAML.stringify(newConfigResult.config), - this.ide, - this.controlPlaneClient, - ); - } - - this.configResult = { - config: renderedConfig, - errors: newConfigResult.errors, - configLoadInterrupted: false, - }; - this.onReload(); - }, PlatformProfileLoader.RELOAD_INTERVAL); } async doLoadConfig(): Promise> { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 8e2326e3d..5ee0620a6 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, @@ -14,15 +14,16 @@ import { } from "../../"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; -import { controlPlaneEnv } from "../../control-plane/env.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 { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; +import { migrateJsonSharedConfig } from "../migrateSharedConfig"; export default async function doLoadConfig( ide: IDE, @@ -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, @@ -99,9 +107,11 @@ export default async function doLoadConfig( const controlPlane = (newConfig as any).controlPlane; const useOnPremProxy = controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; + + const env = await getControlPlaneEnv(ideSettingsPromise); let controlPlaneProxyUrl: string = useOnPremProxy ? controlPlane?.proxyUrl - : controlPlaneEnv.DEFAULT_CONTROL_PLANE_PROXY_URL; + : env.DEFAULT_CONTROL_PLANE_PROXY_URL; if (!controlPlaneProxyUrl.endsWith("/")) { controlPlaneProxyUrl += "/"; 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 e5797bdb7..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; @@ -947,7 +945,6 @@ declare global { fontSize?: number; displayRawMarkdown?: boolean; showChatScrollbar?: boolean; - getChatTitles?: boolean; codeWrap?: boolean; } 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 09003f6eb..9503c0865 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -1,8 +1,8 @@ import fs from "node:fs"; import { + AssistantUnrolled, ConfigResult, - ConfigYaml, validateConfigYaml, } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; @@ -32,17 +32,20 @@ import { getConfigYamlPath } from "../../util/paths"; import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; +import { slashFromCustomCommand } from "../../commands"; import { allTools } from "../../tools"; import { clientRenderHelper } from "./clientRender"; import { llmsFromModelConfig } from "./models"; +import { GlobalContext } from "../../util/GlobalContext"; +import { modifyContinueConfigWithSharedConfig } from "../sharedConfig"; async function loadConfigYaml( workspaceConfigs: string[], rawYaml: string, - overrideConfigYaml: ConfigYaml | undefined, + overrideConfigYaml: AssistantUnrolled | undefined, ide: IDE, controlPlaneClient: ControlPlaneClient, -): Promise> { +): Promise> { let config = overrideConfigYaml ?? (await clientRenderHelper(rawYaml, ide, controlPlaneClient)); @@ -85,7 +88,7 @@ async function slashCommandsFromV1PromptFiles( } async function configYamlToContinueConfig( - config: ConfigYaml, + config: AssistantUnrolled, ide: IDE, ideSettings: IdeSettings, uniqueId: string, @@ -95,7 +98,10 @@ async function configYamlToContinueConfig( allowFreeTrial: boolean = true, ): Promise { const continueConfig: ContinueConfig = { - slashCommands: await slashCommandsFromV1PromptFiles(ide), + slashCommands: [ + ...(await slashCommandsFromV1PromptFiles(ide)), + ...(config.prompts?.map(slashFromCustomCommand) ?? []), + ], models: [], tabAutocompleteModels: [], tools: allTools, @@ -117,6 +123,7 @@ async function configYamlToContinueConfig( rootUrl: doc.rootUrl, faviconUrl: doc.faviconUrl, })), + contextProviders: [], }; // Models @@ -176,7 +183,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), @@ -187,19 +195,19 @@ async function configYamlToContinueConfig( ({ description: { title } }) => title, ); - continueConfig.contextProviders = config.context + 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[]; + .filter((p) => !!p) ?? []) as IContextProvider[]; continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS); // Embeddings Provider @@ -291,14 +299,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( @@ -336,8 +343,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/providers/ContinueProxyContextProvider.ts b/core/context/providers/ContinueProxyContextProvider.ts index 2dcb91cc8..278a12678 100644 --- a/core/context/providers/ContinueProxyContextProvider.ts +++ b/core/context/providers/ContinueProxyContextProvider.ts @@ -1,4 +1,4 @@ -import { controlPlaneEnv } from "../../control-plane/env.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import { ContextItem, ContextProviderDescription, @@ -35,11 +35,9 @@ class ContinueProxyContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { + const env = await getControlPlaneEnv(args.ide.getIdeSettings()); const response = await args.fetch( - new URL( - `/proxy/context/${this.options.id}/list`, - controlPlaneEnv.CONTROL_PLANE_URL, - ), + new URL(`/proxy/context/${this.options.id}/list`, env.CONTROL_PLANE_URL), { method: "GET", headers: { @@ -56,10 +54,11 @@ class ContinueProxyContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + const env = await getControlPlaneEnv(extras.ide.getIdeSettings()); const response = await extras.fetch( new URL( `/proxy/context/${this.options.id}/retrieve`, - controlPlaneEnv.CONTROL_PLANE_URL, + env.CONTROL_PLANE_URL, ), { method: "POST", 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/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 24cac2c44..22f1dffbc 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -31,7 +31,7 @@ async function getContextProviderExtras( ide, ideSettingsPromise, async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined)), + new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise), ); const { config } = await configHandler.loadConfig(); if (!config) { 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/auth/index.ts b/core/control-plane/auth/index.ts index c1a6f881d..8965f4fdb 100644 --- a/core/control-plane/auth/index.ts +++ b/core/control-plane/auth/index.ts @@ -1,16 +1,16 @@ import { v4 as uuidv4 } from "uuid"; +import { IdeSettings } from "../.."; +import { getControlPlaneEnv } from "../env"; -import { controlPlaneEnv } from "../env"; - -const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; -// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging - -export async function getAuthUrlForTokenPage(): Promise { +export async function getAuthUrlForTokenPage( + ideSettingsPromise: Promise, +): Promise { + const env = await getControlPlaneEnv(ideSettingsPromise); const url = new URL("https://api.workos.com/user_management/authorize"); const params = { response_type: "code", - client_id: CLIENT_ID, - redirect_uri: `${controlPlaneEnv.APP_URL}tokens/callback`, + client_id: env.WORKOS_CLIENT_ID, + redirect_uri: `${env.APP_URL}tokens/callback`, // redirect_uri: "http://localhost:3000/tokens/callback", state: uuidv4(), provider: "authkit", diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index bb7661ee8..6200bc8de 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -1,11 +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 { ModelDescription } from "../index.js"; +import { IdeSettings, ModelDescription } from "../index.js"; -import { ConfigResult, FQSN, SecretResult } from "@continuedev/config-yaml"; -import { controlPlaneEnv } from "./env.js"; +import { + AssistantUnrolled, + ConfigResult, + FQSN, + FullSlug, + SecretResult, +} from "@continuedev/config-yaml"; +import { getControlPlaneEnv } from "./env.js"; export interface ControlPlaneSessionInfo { accessToken: string; @@ -27,7 +32,6 @@ export const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; export class ControlPlaneClient { - private static URL = controlPlaneEnv.CONTROL_PLANE_URL; private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes private lastAccessTokenRefresh = 0; @@ -36,6 +40,7 @@ export class ControlPlaneClient { private readonly sessionInfoPromise: Promise< ControlPlaneSessionInfo | undefined >, + private readonly ideSettingsPromise: Promise, ) {} async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { @@ -66,7 +71,9 @@ export class ControlPlaneClient { if (!accessToken) { throw new Error("No access token"); } - const url = new URL(path, ControlPlaneClient.URL).toString(); + + const env = await getControlPlaneEnv(this.ideSettingsPromise); + const url = new URL(path, env.CONTROL_PLANE_URL).toString(); const resp = await fetch(url, { ...init, headers: { @@ -102,7 +109,7 @@ export class ControlPlaneClient { public async listAssistants(): Promise< { - configResult: ConfigResult; + configResult: ConfigResult; ownerSlug: string; packageSlug: string; iconUrl: string; @@ -123,6 +130,23 @@ export class ControlPlaneClient { } } + public async listAssistantFullSlugs(): Promise { + const userId = await this.userId; + if (!userId) { + return null; + } + + try { + const resp = await this.request("ide/list-assistant-full-slugs", { + method: "GET", + }); + const { fullSlugs } = (await resp.json()) as any; + return fullSlugs; + } catch (e) { + return null; + } + } + async getSettingsForWorkspace(workspaceId: string): Promise { const userId = await this.userId; if (!userId) { diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 16adf0990..8f5bb40a4 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,7 +1,6 @@ -import { readUsePlatform } from "../util/paths"; -import { usePlatform } from "./flags"; +import { IdeSettings } from ".."; -interface ControlPlaneEnv { +export interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; CONTROL_PLANE_URL: string; AUTH_TYPE: string; @@ -27,6 +26,14 @@ const PRODUCTION_ENV: ControlPlaneEnv = { APP_URL: "https://app.continue.dev/", }; +const PRODUCTION_HUB_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", + CONTROL_PLANE_URL: "https://api.continue.dev/", + AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, + APP_URL: "https://hub.continue.dev/", +}; + const STAGING_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://control-plane-api-service-537175798139.us-central1.run.app/", @@ -53,17 +60,39 @@ const LOCAL_ENV: ControlPlaneEnv = { APP_URL: "http://localhost:3000/", }; -function getControlPlaneEnv(): ControlPlaneEnv { - const usePlatformFileEnv = readUsePlatform(); - const env = usePlatformFileEnv || process.env.CONTROL_PLANE_ENV; +export async function getControlPlaneEnv( + ideSettingsPromise: Promise, +): Promise { + const ideSettings = await ideSettingsPromise; + return getControlPlaneEnvSync(ideSettings.continueTestEnvironment); +} + +export function getControlPlaneEnvSync( + ideTestEnvironment: IdeSettings["continueTestEnvironment"], +): ControlPlaneEnv { + const env = + ideTestEnvironment === "production" + ? "hub" + : ideTestEnvironment === "test" + ? "test" + : ideTestEnvironment === "local" + ? "local" + : process.env.CONTROL_PLANE_ENV; return env === "local" ? LOCAL_ENV : env === "staging" ? STAGING_ENV - : env === "test" || usePlatform() + : env === "test" ? TEST_ENV - : PRODUCTION_ENV; + : env === "hub" + ? PRODUCTION_HUB_ENV + : PRODUCTION_ENV; } -export const controlPlaneEnv = getControlPlaneEnv(); +export async function useHub( + ideSettingsPromise: Promise, +): Promise { + const ideSettings = await ideSettingsPromise; + return ideSettings.continueTestEnvironment !== "none"; +} diff --git a/core/control-plane/flags.ts b/core/control-plane/flags.ts deleted file mode 100644 index 7b8ff6799..000000000 --- a/core/control-plane/flags.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { readUsePlatform, usePlatformPathExists } from "../util/paths"; - -export function usePlatform(): boolean { - return usePlatformPathExists(); -} - -export function getEnvFromUsePlatformFile(): string | undefined { - const contents = readUsePlatform(); - if (contents && contents.trim().length > 0) { - return contents.trim(); - } - return undefined; -} diff --git a/core/core.ts b/core/core.ts index c74f2e539..4db77443c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -52,7 +52,7 @@ import { type IndexingProgressUpdate, } from "."; -import { usePlatform } from "./control-plane/flags"; +import { getControlPlaneEnv } from "./control-plane/env"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -111,10 +111,13 @@ export class Core { const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { silent: true, - useOnboarding: usePlatform(), + useOnboarding: false, }); - this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise); + this.controlPlaneClient = new ControlPlaneClient( + sessionInfoPromise, + ideSettingsPromise, + ); this.configHandler = new ConfigHandler( this.ide, @@ -294,6 +297,16 @@ 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}`); + }); + // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); @@ -855,6 +868,9 @@ 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) => { @@ -865,7 +881,7 @@ export class Core { this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo); }); on("auth/getAuthUrl", async (msg) => { - const url = await getAuthUrlForTokenPage(); + const url = await getAuthUrlForTokenPage(ideSettingsPromise); return { url }; }); diff --git a/core/index.d.ts b/core/index.d.ts index 63847aa14..f65c10622 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 { @@ -583,8 +599,8 @@ export interface IdeSettings { remoteConfigSyncPeriod: number; userToken: string; enableControlServerBeta: boolean; + continueTestEnvironment: "none" | "production" | "test" | "local"; pauseCodebaseIndexOnStart: boolean; - enableDebugLogs: boolean; } export interface FileStats { @@ -826,7 +842,7 @@ export interface SlashCommandDescription { export interface CustomCommand { name: string; prompt: string; - description: string; + description?: string; } export interface Prediction { @@ -940,7 +956,6 @@ export interface RerankerDescription { export interface TabAutocompleteOptions { disable: boolean; - useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; maxSuffixPercentage: number; @@ -986,7 +1001,6 @@ export interface ContinueUIConfig { fontSize?: number; displayRawMarkdown?: boolean; showChatScrollbar?: boolean; - getChatTitles?: boolean; codeWrap?: boolean; } @@ -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/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 6f9853afe..0064f064c 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -4,7 +4,6 @@ import { ConfigHandler } from "../../config/ConfigHandler.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; -import FreeTrial from "../../llm/llms/FreeTrial.js"; import FileSystemIde from "../../util/filesystem.js"; import { editConfigJson } from "../../util/paths.js"; @@ -37,17 +36,19 @@ describe.skip("DocsService Integration Tests", () => { beforeEach(async () => { ide = new FileSystemIde(process.cwd()); + const ideSettingsPromise = Promise.resolve({ + remoteConfigSyncPeriod: 60, + userToken: "", + enableControlServerBeta: false, + continueTestEnvironment: "none" as const, + pauseCodebaseIndexOnStart: false, + ideSettings: {} as any, + enableDebugLogs: false, + remoteConfigServerUrl: "", + }); configHandler = new ConfigHandler( ide, - Promise.resolve({ - remoteConfigSyncPeriod: 60, - userToken: "", - enableControlServerBeta: false, - pauseCodebaseIndexOnStart: false, - ideSettings: {} as any, - enableDebugLogs: false, - remoteConfigServerUrl: "", - }), + ideSettingsPromise, async () => {}, new ControlPlaneClient( Promise.resolve({ @@ -57,6 +58,7 @@ describe.skip("DocsService Integration Tests", () => { label: "", }, }), + ideSettingsPromise, ), ); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index c8507f256..f0d1e2f3c 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -5,6 +5,7 @@ import lancedb, { Connection } from "vectordb"; import { Chunk, ContinueConfig, + DocsIndexingDetails, IDE, IdeInfo, ILLM, @@ -31,7 +32,6 @@ import { markdownPageToArticleWithChunks, } from "./article"; import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; -import { ConfigResult } from "@continuedev/config-yaml"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import { downloadFromS3, @@ -40,6 +40,7 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import { ConfigResult } from "@continuedev/config-yaml"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -327,7 +328,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 = ?`, @@ -695,6 +696,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( @@ -732,17 +791,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 @@ -798,7 +847,7 @@ export default class DocsService { private async syncDocs( oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, - reindex: boolean, + forceReindex: boolean, ) { try { this.isSyncing = true; @@ -838,20 +887,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/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..4831cf800 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,67 +73,106 @@ 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, + ); } }); } @@ -165,7 +194,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/Groq.ts b/core/llm/llms/Groq.ts index cf26f993c..3585e73d8 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -10,19 +10,16 @@ class Groq extends OpenAI { maxStopWords: number | undefined = 4; private static modelConversion: { [key: string]: string } = { - "llama2-70b": "llama2-70b-4096", "mistral-8x7b": "mixtral-8x7b-32768", - gemma: "gemma-7b-it", gemma2: "gemma2-9b-it", "llama3-8b": "llama3-8b-8192", "llama3-70b": "llama3-70b-8192", "llama3.1-8b": "llama-3.1-8b-instant", - "llama3.1-70b": "llama-3.1-70b-versatile", - "llama3.1-405b": "llama-3.1-405b-reasoning", "llama3.2-1b": "llama-3.2-1b-preview", "llama3.2-3b": "llama-3.2-3b-preview", "llama3.2-11b": "llama-3.2-11b-vision-preview", "llama3.2-90b": "llama-3.2-90b-vision-preview", + "llama3.3-70b": "llama-3.3-70b-versatile", }; protected _convertModelName(model: string): string { return Groq.modelConversion[model] ?? model; 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..7edab380e 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,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.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -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.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/core/package.json b/core/package.json index 477290c9b..111fbe902 100644 --- a/core/package.json +++ b/core/package.json @@ -46,7 +46,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.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index b48b11398..ce24dfcbb 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -7,6 +7,7 @@ import type { ContextProviderWithParams, ContextSubmenuItem, DiffLine, + DocsIndexingDetails, FileSymbolMap, IdeSettings, LLMFullCompletionOptions, @@ -22,6 +23,7 @@ import type { } from "../"; import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; +import { SharedConfigSchema } from "../config/sharedConfig"; export type OnboardingModes = | "Local" @@ -70,6 +72,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 +183,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]; @@ -191,4 +194,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; + "controlPlane/openUrl": [{ path: string }, void]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index a638eafb4..0ce81bfe8 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,12 +53,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "indexing/setPaused", "docs/getSuggestedDocs", "docs/initStatuses", + "docs/getDetails", // "completeOnboarding", "addAutocompleteModel", "profiles/switch", "didChangeSelectedProfile", "tools/call", + "controlPlane/openUrl", ]; // Message types to pass through from core to webview diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index 78ee60150..4f8601303 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -11,6 +11,7 @@ export const ideSettingsPromise = testIde.getIdeSettings(); export const testControlPlaneClient = new ControlPlaneClient( Promise.resolve(undefined), + ideSettingsPromise, ); export const testConfigHandler = new ConfigHandler( 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/util/GlobalContext.ts b/core/util/GlobalContext.ts index 336dc8293..90b403d41 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,5 +1,11 @@ import fs from "node:fs"; +import { + salvageSharedConfig, + sharedConfigSchema, + SharedConfigSchema, +} from "../config/sharedConfig"; + import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { @@ -16,6 +22,7 @@ export type GlobalContextType = { hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; isSupportedLanceDbCpuTarget: boolean; + sharedConfig: SharedConfigSchema; }; /** @@ -26,9 +33,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 +46,7 @@ export class GlobalContext { ), ); } else { - const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); + const data = fs.readFileSync(filepath, "utf-8"); let parsed; try { @@ -49,21 +57,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 +78,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 ccb550ec9..3c6963071 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -53,8 +53,8 @@ class FileSystemIde implements IDE { remoteConfigSyncPeriod: 60, userToken: "", enableControlServerBeta: false, + continueTestEnvironment: "none", pauseCodebaseIndexOnStart: false, - enableDebugLogs: false, }; } async getGitHubAuthToken(args: GetGhTokenArgs): Promise { 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 562d2e819..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`); } @@ -301,18 +305,6 @@ export function getPathToRemoteConfig(remoteConfigServerUrl: string): string { return dir; } -export function usePlatformPathExists(): boolean { - const sPath = path.join(getContinueGlobalPath(), ".use_platform"); - return fs.existsSync(sPath); -} - -export function readUsePlatform(): string | undefined { - const sPath = path.join(getContinueGlobalPath(), ".use_platform"); - if (fs.existsSync(sPath)) { - return fs.readFileSync(sPath, "utf8"); - } -} - export function getConfigJsonPathForRemote( remoteConfigServerUrl: string, ): string { 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 eb7dc5430..e7e6ca94a 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -129,7 +129,8 @@ If your local machine can run an 8B parameter model, then we recommend running L { "title": "Llama 3.1 8B", "provider": "ollama", - "model": "llama3.1:8b" + "model": "llama3.1:8b", + "apiBase": "http://localhost:11434" } ] ``` @@ -158,7 +159,8 @@ If your local machine can run a 16B parameter model, then we recommend running D { "title": "DeepSeek Coder 2 16B", "provider": "ollama", - "model": "deepseek-coder-v2:16b" + "model": "deepseek-coder-v2:16b", + "apiBase": "http://localhost:11434" } ] ``` diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 221a6d49f..8d90f2145 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -58,16 +58,15 @@ This is just another object like the ones in the `"models"` array of `config.jso This object allows you to customize the behavior of tab-autocomplete. The available options are shown below, and you can find their default values [here](https://github.com/continuedev/continue/blob/fbeb2e4fe15d4b434a30a136f74b672485c852d9/core/util/parameters.ts). -- `disable`: Disable autocomplete (can also be done from IDE settings) +- `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) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "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. -- `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. +- `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`) +- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) (default: `350`) +- `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: `[]`) ### 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/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index 67d919a2f..c2fab040a 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -41,9 +41,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. ## Autocomplete model -Bedrock currently does not offer any autocomplete models. +Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +In the meantime, you can view a list of autocomplete model providers [here](../../model-types/autocomplete.md). ## Embeddings model 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/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/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 d3c491f4c..b492f47e9 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -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. -- `maxPromptTokens`: Maximum number of tokens for the prompt. -- `debounceDelay`: Delay (in ms) before triggering autocomplete. -- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. -- `prefixPercentage`: Percentage of input for prefix. +- `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"`). -- `useCache`: If `true`, caches completions. -- `onlyMyCode`: If `true`, only includes code within the repository. -- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. +- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). Example @@ -341,40 +337,6 @@ Example } ``` -### `disableSessionTitles` - -Prevents generating summary titles for each chat session when set to `true`. - -### `ui` - -Customizable UI settings to control interface appearance and behavior. - -**Properties:** - -- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. -- `fontSize`: Specifies font size for UI elements. -- `displayRawMarkdown`: If `true`, shows raw markdown in responses. -- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. -- `codeWrap`: If `true`, enables text wrapping in code blocks. - -Example: - -```json title="config.json" -{ - "ui": { - "codeBlockToolbarPosition": "bottom", - "fontSize": 14, - "displayRawMarkdown": false, - "showChatScrollbar": false, - "codeWrap": false - } -} -``` - -### `allowAnonymousTelemetry` - -When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. - ### `userToken` An optional token that identifies the user, primarily for authenticated services. @@ -383,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: @@ -398,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. @@ -409,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 @@ -420,7 +375,6 @@ Example "modelRoles": { "inlineEdit": "Edit Model" }, - "promptPath": "custom/.prompts", "quickActions": [ { "title": "Tags", @@ -431,8 +385,6 @@ Example "contextMenuPrompts": { "fixGrammar": "Fix grammar in the above but allow for typos." }, - "readResponseTTS": false, - "useChromiumForDocsCrawling": true, "modelContextProtocolServers": [ { "transport": { @@ -445,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/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 0eeacafec..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,16 +83,15 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useFileSuffix`: If `true`, includes file suffix in the prompt. -- `maxPromptTokens`: Maximum number of tokens for the prompt. -- `debounceDelay`: Delay (in ms) before triggering autocomplete. -- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. -- `prefixPercentage`: Percentage of input for prefix. +- `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. -- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). -- `useCache`: If `true`, caches completions. -- `onlyMyCode`: If `true`, only includes code within the repository. -- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. +- `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 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/.run/IDE Logs.run.xml b/extensions/intellij/.run/IDE Logs.run.xml new file mode 100644 index 000000000..2743ca662 --- /dev/null +++ b/extensions/intellij/.run/IDE Logs.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue.run.xml b/extensions/intellij/.run/Run Continue.run.xml index 2cc85210f..1366cd39e 100644 --- a/extensions/intellij/.run/Run Continue.run.xml +++ b/extensions/intellij/.run/Run Continue.run.xml @@ -2,6 +2,7 @@ + diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index c62084620..26f80ee42 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -90,10 +90,7 @@ allow for changes to your `config.json` and other files during development, with ### Viewing logs -When using the `Run Continue` task, we automatically run a script that outputs logs into the "Prompt Logs" terminal tab. - -Alternatively, you can view logs for a particular IDE instance by selecting `Help` -> `Open Log in Editor` in the window -toolbar. +When using the `Run Continue` task, we automatically tail both prompt logs and IDE logs. ### Reloading changes @@ -109,7 +106,9 @@ toolbar. - `extensions/intellij`: Breakpoints can be set in Intellij - `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools -- `core`: Breakpoints can be set in Intellij (requires restarting the `Start Core Dev Server` task +- `core`: Breakpoints can be set in Intellij (requires restarting the `Start Core Dev Server` task) + - If you have Community Edition installed, you won't be able to use breakpoints in IntelliJ. Instead, you can start + the `Core Binary` task in VS Code and set breakpoints in that IDE. ### Available Gradle tasks 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/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index 22178004e..d23308cf1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -135,7 +135,7 @@ class ContinueAuthService { private fun openSignInPage(project: Project) { val coreMessenger = project.service().coreMessenger coreMessenger?.request("auth/getAuthUrl", null, null) { response -> - val authUrl = (response as? Map<*, *>)?.get("url") as? String + val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String if (authUrl != null) { // Open the auth URL in the browser Desktop.getDesktop().browse(java.net.URI(authUrl)) 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 9c2b8c2dc..2388ce8ab 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", @@ -116,6 +117,7 @@ class MessageTypes { "profiles/switch", "didChangeSelectedProfile", "tools/call", + "controlPlane/openUrl" ) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt index 73a707f80..0ce128e5b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt @@ -59,8 +59,11 @@ class CoreMessengerManager( coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope) coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val result = (response as Map)["result"] as Map + val responseObject = response as Map<*, *> + val responseContent = responseObject["content"] as Map<*, *> + val result = responseContent["result"] as Map<*, *> val config = result["config"] as Map + val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean val telemetryService = service() if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { 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 ad70dd147..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" -> { @@ -439,8 +453,11 @@ class IdeProtocolClient( null, null ) { response -> - val result = (response as Map)["result"] as Map + val responseObject = response as Map<*, *> + val responseContent = responseObject["content"] as Map<*, *> + val result = responseContent["result"] as Map<*, *> val config = result["config"] as Map + val applyCodeBlockModel = getModelByRole(config, "applyCodeBlock") if (applyCodeBlockModel != null) { @@ -451,7 +468,6 @@ class IdeProtocolClient( config["models"] as List> val curSelectedModel = models.find { it["title"] == params.curSelectedModelTitle } -// continuation.resume(curSelectedModel) if (curSelectedModel == null) { return@request } else { 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..f871fc69e 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,6 @@ class IntelliJIDE( userToken = settings.continueState.userToken ?: "", enableControlServerBeta = settings.continueState.enableContinueTeamsBeta, pauseCodebaseIndexOnStart = false, // TODO: Needs to be implemented - enableDebugLogs = false // TODO: Needs to be implemented ) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index ce2c260e1..9f314ede6 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.`continue`.GetTheme import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel +import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction @@ -130,7 +131,8 @@ fun openInlineEdit(project: Project?, editor: Editor) { val modelTitles = mutableListOf() continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val result = (response as Map)["result"] as Map + val content = (response as Map)["content"] as Map + val result = content["result"] as Map val config = result["config"] as Map val models = config["models"] as List> modelTitles.addAll(models.map { it["title"] as String }) @@ -166,13 +168,13 @@ fun openInlineEdit(project: Project?, editor: Editor) { val prefix = editor.document.getText(TextRange(0, startOffset)) val highlighted = editor.document.getText(TextRange(startOffset, endOffset)) val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) - val lineNumber = max(0, startLineNumber - 1) + val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1) // Un-highlight the selected text selectionModel.removeSelection() // Get indentation width in pixels - val indentationLineNum = lineNumber + 1 + val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1 val lineStart = editor.document.getLineStartOffset(indentationLineNum) val lineEnd = editor.document.getLineEndOffset(indentationLineNum) val text = editor.document.getText(TextRange(lineStart, lineEnd)) @@ -488,14 +490,14 @@ class CustomPanel( } val leftButton = - CustomButton("Reject All (${getMetaKeyLabel()}⇧⌫)") { onReject() } + CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() } .apply { background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) } val rightButton = - CustomButton("Accept All (${getMetaKeyLabel()}⇧⏎)") { onAccept() } + CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() } .apply { background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 1400e5c54..201b259de 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -88,7 +88,6 @@ data class IdeSettings( val userToken: String, val enableControlServerBeta: Boolean, val pauseCodebaseIndexOnStart: Boolean, - val enableDebugLogs: Boolean ) data class ContinueRcJson( diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index a5e16ecc5..5a43ff24f 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -132,12 +132,12 @@ - - + text="Continue Config" + description="Continue Config"> + - + diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt new file mode 100644 index 000000000..d153deda5 --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt @@ -0,0 +1,94 @@ +package com.github.continuedev.continueintellijextension.e2e + +import com.automation.remarks.junit5.Video +import com.github.continuedev.continueintellijextension.fixtures.dialog +import com.github.continuedev.continueintellijextension.fixtures.idea +import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame +import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension +import com.github.continuedev.continueintellijextension.utils.StepsLogger +import com.github.continuedev.continueintellijextension.utils.* +import com.intellij.remoterobot.RemoteRobot +import com.intellij.remoterobot.fixtures.ComponentFixture +import com.intellij.remoterobot.search.locators.byXpath +import com.intellij.remoterobot.steps.CommonSteps +import com.intellij.remoterobot.utils.keyboard +import com.intellij.remoterobot.utils.waitFor +import com.intellij.remoterobot.utils.waitForIgnoringError +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import java.awt.event.KeyEvent.VK_I +import java.time.Duration.ofMinutes +import java.time.Duration.ofSeconds + +@ExtendWith(RemoteRobotExtension::class) +class InlineEdit { + init { + StepsLogger.init() + } + + @BeforeEach + fun waitForIde(remoteRobot: RemoteRobot) { + waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } + } + + @AfterEach + fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject() + + @Test + @Video + fun submitInlineEdit(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { + welcomeFrame { + createNewProjectLink.click() + dialog("New Project") { + findText("Java").click() + checkBox("Add sample code").select() + button("Create").click() + } + } + + // Wait for the default "Main.java" tab to load + // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. + waitFor(ofSeconds(20)) { + findAll( + byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") + ).isNotEmpty() + } + + idea { + with(textEditor()) { + val userMsg = "TEST_USER_MESSAGE_0" + editor.insertTextAtLine(0, 0, userMsg) + editor.selectText(userMsg) + + keyboard { + hotKey(getMetaKey(), VK_I) + } + + val textArea = find(byXpath("//div[@class='CustomTextArea']")) + textArea.hasText("Enter instructions...") + + val modelSelect = find(byXpath("//div[@class='JComboBox']")) + modelSelect.hasText("TEST LLM") + + keyboard { + enterText("Hello world!") + } + + val enterBtn = find(byXpath("//div[@class='CustomButton']")) + enterBtn.click() + + val rejectText = "${getAltKeyLabel()}${getShiftKeyLabel()}N" + val acceptText = "${getAltKeyLabel()}${getShiftKeyLabel()}Y" + val acceptAllText = "Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)" + val rejectAllText = "Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)" + + find(byXpath("//div[@text='$rejectText']")).isShowing + find(byXpath("//div[@text='$acceptText']")).isShowing + find(byXpath("//div[@text='$acceptAllText']")).isShowing + find(byXpath("//div[@text='$rejectAllText']")).isShowing + } + } + } +} \ No newline at end of file diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 1273a7c40..2b12cf21e 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -3080,10 +3080,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/selectors/GUI.selectors.ts b/extensions/vscode/e2e/selectors/GUI.selectors.ts index 71a38c9f2..319157500 100644 --- a/extensions/vscode/e2e/selectors/GUI.selectors.ts +++ b/extensions/vscode/e2e/selectors/GUI.selectors.ts @@ -79,6 +79,31 @@ export class GUISelectors { ); } + public static getOnboardingTabButton(view: WebView, title: string) { + return SelectorUtils.getElementByDataTestId( + view, + `onboarding-tab-${title}`, + ); + } + + public static getBestChatApiKeyInput(view: WebView) { + return SelectorUtils.getElementByDataTestId( + view, + "best-chat-api-key-input", + ); + } + + public static getBestAutocompleteApiKeyInput(view: WebView) { + return SelectorUtils.getElementByDataTestId( + view, + "best-autocomplete-api-key-input", + ); + } + + public static getTutorialCard(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "tutorial-card"); + } + public static getThreadMessageByText(view: WebView, text: string) { return view.findWebElement( By.xpath(`//*[@class="thread-message"]//*[contains(text(), "${text}")]`), 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/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index 316db2d0e..4369a917f 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -1,5 +1,6 @@ import { expect } from "chai"; import { + By, EditorView, Key, VSBrowser, @@ -53,6 +54,45 @@ describe("GUI Test", () => { "Quickly get up and running using our API keys.", ); }).timeout(DEFAULT_TIMEOUT.XL); + + it("should display tutorial card after accepting onboarding quick start", async () => { + // Get paragraph with text Best + const bestTab = await GUISelectors.getOnboardingTabButton(view, "Best"); + await bestTab.click(); + + const anthropicInput = await TestUtils.waitForSuccess( + async () => await GUISelectors.getBestChatApiKeyInput(view), + ); + anthropicInput.sendKeys("invalid_api_key"); + + const mistralInput = + await GUISelectors.getBestAutocompleteApiKeyInput(view); + mistralInput.sendKeys("invalid_api_key"); + + // Get button with text "Connect" and click it + const connectButton = await view.findWebElement( + By.xpath("//button[text()='Connect']"), + ); + await connectButton.click(); + + await TestUtils.waitForSuccess( + async () => await GUISelectors.getTutorialCard(view), + ); + + // TODO validate that claude has been added to list + + // Skip testing Quick Start because github auth opens external app and breaks test + // const quickStartButton = await view.findWebElement( + // By.xpath("//*[contains(text(), 'Get started using our API keys')]") + // ); + // await quickStartButton.click(); + // await view.switchBack(); + // const allowButton = await TestUtils.waitForSuccess( + // async () => await driver.findElement(By.xpath(`//a[contains(text(), "Allow")]`)) + // ); + // await allowButton.click(); + // ({ view, driver } = await GUIActions.switchToReactIframe()); + }).timeout(DEFAULT_TIMEOUT.XL); }); describe("Chat", () => { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 38d0db7c8..3149ab142 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.255", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.254", + "version": "0.9.255", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,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.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 23c151699..257b6a4d4 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.254", + "version": "0.9.258", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -96,6 +96,11 @@ "default": false, "markdownDescription": "Enable Continue for teams beta features. To sign in, click the person icon in the bottom right of the sidebar." }, + "continue.enableContinueHub": { + "type": "boolean", + "default": false, + "description": "Enable Continue Hub (internal)" + }, "continue.showInlineTip": { "type": "boolean", "default": true, @@ -213,7 +218,7 @@ "group": "Continue" }, { - "command": "continue.openConfig", + "command": "continue.openConfigPage", "category": "Continue", "title": "Open Continue Config", "icon": "$(gear)", @@ -522,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 && !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 && 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 51008db8a..7f9f561f6 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -636,11 +636,13 @@ class VsCodeIde implements IDE { "enableContinueForTeams", false, ), + continueTestEnvironment: settings.get("enableContinueHub") + ? "production" + : "none", pauseCodebaseIndexOnStart: settings.get( "pauseCodebaseIndexOnStart", false, ), - enableDebugLogs: false, // settings.get( // "enableControlServerBeta", // false, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index d8019cfe1..da5e7db94 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -792,10 +792,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, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 9e6da728d..be58bb375 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -2,7 +2,7 @@ import fs from "fs"; import { IContextProvider } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; -import { controlPlaneEnv, EXTENSION_NAME } from "core/control-plane/env"; +import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env"; import { Core } from "core/core"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; import { InProcessMessenger } from "core/protocol/messenger"; @@ -294,7 +294,8 @@ export class VsCodeExtension { // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { - if (e.provider.id === controlPlaneEnv.AUTH_TYPE) { + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + if (e.provider.id === env.AUTH_TYPE) { vscode.commands.executeCommand( "setContext", "continue.isSignedInToControlPlane", @@ -374,6 +375,9 @@ export class VsCodeExtension { void this.core.invoke("didChangeActiveTextEditor", { filepath }); }); + const enableContinueHub = vscode.workspace + .getConfiguration(EXTENSION_NAME) + .get("enableContinueHub"); vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = this.ide.getIdeSettingsSync(); @@ -381,6 +385,14 @@ export class VsCodeExtension { void webviewProtocol.request("didChangeIdeSettings", { settings, }); + + 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 a22c4934a..de10f9c7d 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -1,7 +1,7 @@ import crypto from "crypto"; import { ControlPlaneSessionInfo } from "core/control-plane/client"; -import { controlPlaneEnv } from "core/control-plane/env"; +import { EXTENSION_NAME, getControlPlaneEnvSync } from "core/control-plane/env"; import fetch from "node-fetch"; import { v4 as uuidv4 } from "uuid"; import { @@ -17,6 +17,7 @@ import { Uri, UriHandler, window, + workspace, } from "vscode"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; @@ -24,6 +25,12 @@ import { SecretStorage } from "./SecretStorage"; const AUTH_NAME = "Continue"; +const controlPlaneEnv = getControlPlaneEnvSync( + workspace.getConfiguration(EXTENSION_NAME).get("enableContinueHub") + ? "production" + : "none", +); + const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; class UriEventHandler extends EventEmitter implements UriHandler { 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/gui/package-lock.json b/gui/package-lock.json index 922ac8e10..cca979250 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,7 +108,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.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -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/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/Footer.tsx b/gui/src/components/Footer.tsx index 9b5a6840c..b2efd221c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -1,6 +1,7 @@ import { useAppSelector } from "../redux/hooks"; import { selectDefaultModel } from "../redux/slices/configSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; +import { getLocalStorage } from "../util/localStorage"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; function Footer() { @@ -10,7 +11,7 @@ function Footer() { return (
diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index e8a0deb12..cadaa5830 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -13,7 +13,6 @@ import { newSession, } from "../redux/slices/sessionSlice"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { ROUTES } from "../util/navigation"; import TextDialog from "./dialogs"; import Footer from "./Footer"; @@ -23,6 +22,7 @@ import AccountDialog from "./AccountDialog"; import { AuthProvider } from "../context/Auth"; import { exitEditMode } from "../redux/thunks"; import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; +import { incrementFreeTrialCount } from "../util/freeTrial"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -150,12 +150,7 @@ const Layout = () => { useWebviewListener( "incrementFtc", async () => { - const u = getLocalStorage("ftc"); - if (u) { - setLocalStorage("ftc", u + 1); - } else { - setLocalStorage("ftc", 1); - } + incrementFreeTrialCount(); }, [], ); diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index 78caa4b5b..eebbfb2bc 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -20,7 +20,11 @@ export interface OnboardingCardState { activeTab?: TabTitle; } -export function OnboardingCard() { +interface OnboardingCardProps { + isDialog?: boolean; +} + +export function OnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); function renderTabContent() { @@ -49,9 +53,11 @@ export function OnboardingCard() { activeTab={onboardingCard.activeTab || "Best"} onTabClick={onboardingCard.setActiveTab} /> - - - + {!isDialog && ( + onboardingCard.close()}> + + + )}
{renderTabContent()}
); diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index 575e1e8a3..86e7cd693 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -99,6 +99,7 @@ function BestExperienceConfigForm({ placeholder="Enter your Anthropic API Key" value={chatApiKey} onChange={(e) => setChatApiKey(e.target.value)} + data-testid="best-chat-api-key-input" /> setAutocompleteApiKey(e.target.value)} + data-testid="best-autocomplete-api-key-input" /> onTabClick(tabType as TabTitle)} + data-testid={`onboarding-tab-${tabType}`} >

{titles.default} diff --git a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx index 04eabf345..00d0702c3 100644 --- a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx +++ b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx @@ -9,11 +9,15 @@ import { useSubmitOnboarding } from "../hooks"; import JetBrainsFetchGitHubTokenDialog from "./JetBrainsFetchGitHubTokenDialog"; import { setDefaultModel } from "../../../redux/slices/configSlice"; -function QuickstartSubmitButton() { +interface QuickstartSubmitButtonProps { + isDialog?: boolean; +} + +function QuickstartSubmitButton({ isDialog }: QuickstartSubmitButtonProps) { const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); - const { submitOnboarding } = useSubmitOnboarding("Quickstart"); + const { submitOnboarding } = useSubmitOnboarding("Quickstart", isDialog); function onComplete() { submitOnboarding(); diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index ac6078818..9622754c4 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,7 +1,11 @@ import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import { TabTitle } from "../components/OnboardingCardTabs"; -import { setOnboardingCard } from "../../../redux/slices/uiSlice"; +import { + setDialogMessage, + setOnboardingCard, + setShowDialog, +} from "../../../redux/slices/uiSlice"; import { OnboardingCardState } from ".."; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; @@ -12,7 +16,7 @@ export interface UseOnboardingCard { activeTab: OnboardingCardState["activeTab"]; setActiveTab: (tab: TabTitle) => void; open: (tab: TabTitle) => void; - close: () => void; + close: (isDialog?: boolean) => void; } export function useOnboardingCard(): UseOnboardingCard { @@ -38,20 +42,16 @@ export function useOnboardingCard(): UseOnboardingCard { async function open(tab: TabTitle) { navigate("/"); - - // Used to clear the chat panel before showing onboarding card - dispatch( - saveCurrentSession({ - openNewSession: true, - }), - ); - dispatch(setOnboardingCard({ show: true, activeTab: tab })); } - function close() { + function close(isDialog = false) { setLocalStorage("hasDismissedOnboardingCard", true); dispatch(setOnboardingCard({ show: false })); + if (isDialog) { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + } } function setActiveTab(tab: TabTitle) { diff --git a/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts b/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts index a0407c171..93b24ea91 100644 --- a/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts +++ b/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts @@ -6,7 +6,7 @@ import { OnboardingModes } from "core/protocol/core"; import { useTutorialCard } from "../../../hooks/useTutorialCard"; import { useOnboardingCard } from "./useOnboardingCard"; -export function useSubmitOnboarding(mode: OnboardingModes) { +export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) { const posthog = usePostHog(); const ideMessenger = useContext(IdeMessengerContext); const { openTutorialCard } = useTutorialCard(); @@ -16,7 +16,7 @@ export function useSubmitOnboarding(mode: OnboardingModes) { const onboardingStatus = getLocalStorage("onboardingStatus"); // Always close the onboarding card and update config.json - closeOnboardingCard(); + closeOnboardingCard(isDialog); ideMessenger.post("completeOnboarding", { mode, }); diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index 360282e4a..ede9295b3 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -23,7 +23,11 @@ export interface OnboardingCardState { activeTab?: TabTitle; } -export function PlatformOnboardingCard() { +interface OnboardingCardProps { + isDialog: boolean; +} + +export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); if (getLocalStorage("onboardingStatus") === undefined) { @@ -34,13 +38,18 @@ export function PlatformOnboardingCard() { return ( - - - + {!isDialog && ( + onboardingCard.close()}> + + + )}

diff --git a/gui/src/components/OnboardingCard/platform/tabs/local.tsx b/gui/src/components/OnboardingCard/platform/tabs/local.tsx deleted file mode 100644 index ae30085ec..000000000 --- a/gui/src/components/OnboardingCard/platform/tabs/local.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { useAuth } from "../../../../context/Auth"; -import ContinueLogo from "../../../gui/ContinueLogo"; -import { useOnboardingCard } from "../../hooks"; - -export default function LocalTab() { - const onboardingCard = useOnboardingCard(); - const auth = useAuth(); - - return ( -
-
- -
- -

- Log in to quickly build your first custom AI code assistant -

- - {/*

- To prevent abuse, we'll ask you to sign in to GitHub. -

*/} - -
-
- ); -} diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx index f6a14cb93..94e3c0de0 100644 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ b/gui/src/components/OnboardingCard/platform/tabs/main.tsx @@ -3,47 +3,78 @@ import { Button, ButtonSubtext } from "../../.."; import { useAuth } from "../../../../context/Auth"; import ContinueLogo from "../../../gui/ContinueLogo"; import { useOnboardingCard } from "../../hooks"; +import { hasPassedFTL } from "../../../../util/freeTrial"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; export default function MainTab({ onRemainLocal, + isDialog, }: { onRemainLocal: () => void; + isDialog: boolean; }) { + const ideMessenger = useContext(IdeMessengerContext); const onboardingCard = useOnboardingCard(); const auth = useAuth(); function onGetStarted() { auth.login(true).then((success) => { if (success) { - onboardingCard.close(); + onboardingCard.close(isDialog); } }); } + function openPastFreeTrialOnboarding() { + ideMessenger.post("controlPlane/openUrl", { + path: "setup-models", + }); + onboardingCard.close(isDialog); + } + + const pastFreeTrialLimit = hasPassedFTL(); + return (
-

- Log in to quickly build your first custom AI code assistant -

+ {pastFreeTrialLimit ? ( + <> +

+ You've reached the free trial limit. Visit the Continue Platform to + select a Coding Assistant. +

+ + + ) : ( + <> +

+ Log in to quickly build your first custom AI code assistant +

-
- - -
- Or, remain local - -
-
-
+ + + )} + + +
+ Or, remain local + +
+
); } diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx index f4c02cefd..17d2ead00 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx @@ -2,8 +2,12 @@ import BestExperienceConfigForm from "../components/BestExperienceConfigForm"; import ProviderAlert from "../components/ProviderAlert"; import { useSubmitOnboarding } from "../hooks"; -function OnboardingBestTab() { - const { submitOnboarding } = useSubmitOnboarding("Best"); +interface OnboardingBestTabProps { + isDialog?: boolean; +} + +function OnboardingBestTab({ isDialog }: OnboardingBestTabProps) { + const { submitOnboarding } = useSubmitOnboarding("Best", isDialog); return (
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 71b4a13ac..76ba5bf5c 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -14,14 +14,20 @@ import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; import { setDefaultModel } from "../../../redux/slices/configSlice"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; const OLLAMA_CHECK_INTERVAL_MS = 3000; -function OnboardingLocalTab() { +interface OnboardingLocalTabProps { + isDialog?: boolean; +} + +function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); const { submitOnboarding } = useSubmitOnboarding( hasPassedFTL() ? "LocalAfterFreeTrial" : "Local", + isDialog, ); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< @@ -117,6 +123,11 @@ function OnboardingLocalTab() { onClick={() => { submitOnboarding(); + if (isDialog) { + dispatch(setDialogMessage(undefined)); + dispatch(setShowDialog(false)); + } + // Set the selected model to the local chat model dispatch( setDefaultModel({ diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx index 326fd32e2..f291cf7c8 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx @@ -1,7 +1,11 @@ import ContinueLogo from "../../gui/ContinueLogo"; import QuickStartSubmitButton from "../components/QuickStartSubmitButton"; -function OnboardingQuickstartTab() { +interface OnboardingQuickstartTabProps { + isDialog?: boolean; +} + +function OnboardingQuickstartTab({ isDialog }: OnboardingQuickstartTabProps) { return (
@@ -18,7 +22,7 @@ function OnboardingQuickstartTab() { To prevent abuse, we'll ask you to sign in to GitHub.

- +
); 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/dialogs/FreeTrialOverDialog.tsx b/gui/src/components/dialogs/FreeTrialOverDialog.tsx new file mode 100644 index 000000000..d8666b1b2 --- /dev/null +++ b/gui/src/components/dialogs/FreeTrialOverDialog.tsx @@ -0,0 +1,32 @@ +import { useDispatch } from "react-redux"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { useAppSelector } from "../../redux/hooks"; +import { useEffect } from "react"; +import { selectUsePlatform } from "../../redux/selectors"; +import { PlatformOnboardingCard } from "../OnboardingCard/platform/PlatformOnboardingCard"; +import { OnboardingCard } from "../OnboardingCard"; + +function FreeTrialOverDialog() { + const dispatch = useDispatch(); + const history = useAppSelector((store) => store.session.history); + const usePlatform = useAppSelector(selectUsePlatform); + + useEffect(() => { + if (history.length === 0) { + dispatch(setShowDialog(false)); + dispatch(setDialogMessage(undefined)); + } + }, [history]); + + return ( +
+ {usePlatform ? ( + + ) : ( + + )} +
+ ); +} + +export default FreeTrialOverDialog; diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 9e515d6cb..1cf0567ee 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -78,7 +78,7 @@ const TextDialog = (props: TextDialogProps) => { > - + {typeof props.message === "string" ? ( diff --git a/gui/src/components/gui/CopyIconButton.tsx b/gui/src/components/gui/CopyIconButton.tsx index 560042026..c2fcfd322 100644 --- a/gui/src/components/gui/CopyIconButton.tsx +++ b/gui/src/components/gui/CopyIconButton.tsx @@ -1,7 +1,4 @@ import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline"; -import { useContext, useState } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { isJetBrains } from "../../util"; import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip"; import useCopy from "../../hooks/useCopy"; @@ -10,6 +7,7 @@ interface CopyIconButtonProps { tabIndex?: number; checkIconClassName?: string; clipboardIconClassName?: string; + tooltipPlacement?: "top" | "bottom"; } export function CopyIconButton({ @@ -17,13 +15,14 @@ export function CopyIconButton({ tabIndex, checkIconClassName = "h-4 w-4 text-green-400", clipboardIconClassName = "h-4 w-4 text-gray-400", + tooltipPlacement = "bottom", }: CopyIconButtonProps) { const { copyText, copied } = useCopy(text); return ( <> 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..9ca52e5d3 --- /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/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/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 530144e4a..323b586d0 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -155,7 +155,6 @@ const ItemDiv = styled.div` text-align: left; width: 100%; color: ${vscForeground}; - cursor: pointer; &.is-selected { background-color: ${vscListActiveBackground}; @@ -203,6 +202,9 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { const [querySubmenuItem, setQuerySubmenuItem] = useState< ComboBoxItem | undefined >(undefined); + const [loadingSubmenuItem, setLoadingSubmenuItem] = useState< + ComboBoxItem | undefined + >(undefined); const [allItems, setAllItems] = useState([]); @@ -245,8 +247,8 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { description: "Create a new .prompt file", }); } - - setAllItems(items); + setLoadingSubmenuItem(items.find((item) => item.id === "loading")); + setAllItems(items.filter((item) => item.id !== "loading")); }, [subMenuTitle, props.items, props.editor]); const queryInputRef = useRef(null); @@ -403,78 +405,98 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { ) : ( <> {subMenuTitle && {subMenuTitle}} - {allItems.length ? ( - allItems.map((item, index) => ( - (itemRefs.current[index] = el)} - className={`item ${ - index === selectedIndex ? "is-selected" : "" - }`} - key={index} - onClick={() => selectItem(index)} - onMouseEnter={() => setSelectedIndex(index)} - data-testid="context-provider-dropdown-item" - > - -
- {showFileIconForItem(item) && ( - - )} - {!showFileIconForItem(item) && ( - <> - - - )} - {item.title} - {" "} -
- - {item.description} - {item.type === "contextProvider" && - item.contextProvider?.type === "submenu" && ( - - )} - {item.subActions?.map((subAction) => { - const Icon = getIconFromDropdownItem( - subAction.icon, - "action", - ); - return ( - { - subAction.action(item); - e.stopPropagation(); - e.preventDefault(); - props.onClose(); - }} - text={undefined} - > - - - ); - })} - + {loadingSubmenuItem && ( + + +
+ + {loadingSubmenuItem.title} + {" "} +
+ + {loadingSubmenuItem.description} -
- )) +
+
+ )} + {allItems.length ? ( + allItems.map((item, index) => { + const isSelected = index === selectedIndex; + return ( + (itemRefs.current[index] = el)} + className={`item cursor-pointer ${isSelected ? "is-selected" : ""}`} + key={index} + onClick={() => selectItem(index)} + onMouseEnter={() => setSelectedIndex(index)} + data-testid="context-provider-dropdown-item" + > + +
+ {showFileIconForItem(item) ? ( + + ) : ( + + )} + {item.title} + {" "} +
+ + {item.description} + {item.type === "contextProvider" && + item.contextProvider?.type === "submenu" && ( + + )} + {item.subActions?.map((subAction) => { + const Icon = getIconFromDropdownItem( + subAction.icon, + "action", + ); + return ( + { + subAction.action(item); + e.stopPropagation(); + e.preventDefault(); + props.onClose(); + }} + text={undefined} + > + + + ); + })} + +
+
+ ); + }) ) : ( No results )} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 8b360457d..232dafae3 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -303,7 +303,6 @@ function TipTapEditor(props: TipTapEditorProps) { "Images need to be in jpg or png format and less than 10MB in size.", ]); } - return undefined; } const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); @@ -351,7 +350,7 @@ function TipTapEditor(props: TipTapEditorProps) { }, }).configure({ HTMLAttributes: { - class: "editor-image bg-black object-contain max-h-[250px] w-full", + class: "object-contain max-h-[210px] max-w-full mx-1", }, }), Placeholder.configure({ @@ -802,7 +801,7 @@ function TipTapEditor(props: TipTapEditorProps) { const contextItem = rifWithContentsToContextItem( data.rangeInFileWithContents, ); - console.log(contextItem); + let index = 0; for (const el of editor.getJSON()?.content ?? []) { if (el.attrs?.item?.name === contextItem.name) { diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx index 4e07ead6d..c94f63598 100644 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ b/gui/src/components/mainInput/TutorialCard.tsx @@ -44,7 +44,7 @@ export function TutorialCard({ onClose }: TutorialCardProps) { const ideMessenger = useContext(IdeMessengerContext); return ( - + @@ -57,10 +57,7 @@ export function TutorialCard({ onClose }: TutorialCardProps) { - ideMessenger.post( - "vscode/openMoveRightMarkdown", - undefined, - ) + ideMessenger.post("vscode/openMoveRightMarkdown", undefined) } > Move Chat panel to the right 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/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 4ecce8315..641e17c13 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -1,5 +1,4 @@ import { useContext, useRef, useState } from "react"; -import styled from "styled-components"; import { CommandLineIcon, PlayIcon, @@ -19,36 +18,6 @@ import { selectUIConfig, } from "../../redux/slices/configSlice"; -const TopDiv = styled.div` - outline: 0.5px solid rgba(153, 153, 152); - outline-offset: -0.5px; - border-radius: ${defaultBorderRadius}; - margin-bottom: 8px; - background-color: ${vscEditorBackground}; -`; - -const HoverDiv = styled.div` - position: sticky; - top: 0; - left: 100%; - height: 0; - width: 0; - overflow: visible; - z-index: 100; -`; - -const InnerHoverDiv = styled.div<{ isBottomToolbarPosition: boolean }>` - position: absolute; - ${(props) => (props.isBottomToolbarPosition ? "bottom: 3px;" : "top: -11px;")} - right: 10px; - display: flex; - padding: 1px 2px; - gap: 4px; - border: 0.5px solid #8888; - border-radius: ${defaultBorderRadius}; - background-color: ${vscEditorBackground}; -`; - interface StepContainerPreActionButtonsProps { language: string | null; codeBlockContent: string; @@ -69,9 +38,12 @@ export default function StepContainerPreActionButtons({ const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); - + const isStreaming = useAppSelector((state) => state.session.isStreaming); const isBottomToolbarPosition = uiConfig?.codeBlockToolbarPosition == "bottom"; + + const toolTipPlacement = isBottomToolbarPosition ? "top" : "bottom"; + const shouldRunTerminalCmd = !isJetBrains() && isTerminalCodeBlock(language, codeBlockContent); const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; @@ -107,31 +79,27 @@ export default function StepContainerPreActionButtons({ !isNextCodeBlock, ); - if (!hovering) { - return ( - setHovering(true)} - onMouseLeave={() => setHovering(false)} - > - {children} - - ); - } - return ( - setHovering(true)} onMouseLeave={() => setHovering(false)} + className="bg-vsc-editor-background border-vsc-input-border relative rounded-md border-[1px] border-solid" > - - +
{children}
+ {hovering && !isStreaming && ( +
{shouldRunTerminalCmd && ( @@ -140,6 +108,7 @@ export default function StepContainerPreActionButtons({ text="Apply" style={{ backgroundColor: vscEditorBackground }} onClick={onClickApply} + tooltipPlacement={toolTipPlacement} > @@ -149,13 +118,16 @@ export default function StepContainerPreActionButtons({ onClick={() => ideMessenger.post("insertAtCursor", { text: codeBlockContent }) } + tooltipPlacement={toolTipPlacement} > - - - - {children} - + +
+ )} +
); } 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 index 4d0df15e7..c33c3a586 100644 --- a/gui/src/components/modelSelection/platform/AssistantAndModelSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantAndModelSelect.tsx @@ -155,7 +155,7 @@ function AssistantAndModelSelect() { aria-hidden="true" /> - {selectedProfile?.title || "Select assistant"} + {selectedProfile?.fullSlug.packageSlug || "Select assistant"} {" / "} {modelSelectTitle(defaultModel) || "Select model"} diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 383c50f1e..972dd2782 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -25,7 +25,9 @@ export function AssistantSelect(props: AssistantSelectProps) { const dispatch = useAppDispatch(); function onNewAssistant() { - ideMessenger.post("openUrl", "https://app-test.continue.dev/new"); + ideMessenger.post("controlPlane/openUrl", { + path: "new", + }); } return ( diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 361ee8e0c..c81aa1bc1 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -135,13 +135,16 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ useState(false); useEffect(() => { - ideMessenger.ide.getIdeSettings().then(({ enableControlServerBeta }) => { - setControlServerBetaEnabled(enableControlServerBeta); - dispatch(setLastControlServerBetaEnabledStatus(enableControlServerBeta)); + ideMessenger.ide + .getIdeSettings() + .then(({ enableControlServerBeta, continueTestEnvironment }) => { + const enabled = + enableControlServerBeta || continueTestEnvironment !== "none"; + setControlServerBetaEnabled(enabled); + dispatch(setLastControlServerBetaEnabledStatus(enabled)); - const shouldShowPopup = - !lastControlServerBetaEnabledStatus && enableControlServerBeta; - }); + const shouldShowPopup = !lastControlServerBetaEnabledStatus && enabled; + }); }, []); useWebviewListener( diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index e5bb876a3..5b6e58fa4 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -116,7 +116,10 @@ export const SubmenuContextProvidersProvider = ({ }; }, [ideMessenger]); - const providersLoading = useRef(new Set()).current; + const providersLoading = useRef(new Set()).current; + const abortControllers = useRef( + new Map(), + ).current; const getSubmenuContextItems = useCallback( ( @@ -217,94 +220,116 @@ export const SubmenuContextProvidersProvider = ({ ); const loadSubmenuItems = useCallback( - (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => { - submenuContextProviders.forEach( - async (description: ContextProviderDescription) => { - try { - if (providersLoading.has(description.title)) { - return; - } - providersLoading.add(description.title); + async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => { + await Promise.allSettled( + submenuContextProviders.map( + async (description: ContextProviderDescription) => { + const controller = new AbortController(); + try { + const refreshProvider = + providers === "all" + ? true + : providers === "dependsOnIndexing" + ? description.dependsOnIndexing + : providers.includes(description.title); - const refreshProvider = - providers === "all" - ? true - : providers === "dependsOnIndexing" - ? description.dependsOnIndexing - : providers.includes(description.title); + if (!refreshProvider) { + if (providers === "dependsOnIndexing") { + console.debug( + `Skipping ${description.title} provider due to disabled indexing`, + ); + } + return; + } - if (!refreshProvider) { - return; - } - - if (description.dependsOnIndexing && disableIndexing) { - console.debug( - `Skipping ${description.title} provider due to disabled indexing`, + // Submenu loading requests cancel existing requests + abortControllers.get(description.title)?.abort(); + abortControllers.set(description.title, controller); + providersLoading.add(description.title); + console.log( + `Refreshing items for ${description.title} submenu provider`, + ); + const result = await ideMessenger.request( + "context/loadSubmenuItems", + { + title: description.title, + }, ); - return; - } - const result = await ideMessenger.request( - "context/loadSubmenuItems", - { - title: description.title, - }, - ); - if (result.status === "error") { - throw new Error(result.error); - } - const submenuItems = result.content; - const providerTitle = description.title; + // IMPORTANT - the controller only prevents invalid loading state + // But does not cancel using data from the request + // Could uncomment this to truly cancel the request + // if (controller.signal.aborted) { + // return console.debug( + // `${description.title} provider loading aborted`, + // ); + // } - const itemsWithProvider = submenuItems.map((item) => ({ - ...item, - providerTitle, - })); + if (result.status === "error") { + throw new Error(result.error); + } + const submenuItems = result.content; + const providerTitle = description.title; - const minisearch = new MiniSearch({ - fields: ["title", "description"], - storeFields: ["id", "title", "description", "providerTitle"], - }); - - minisearch.addAll( - submenuItems.map((item) => ({ ...item, providerTitle })), - ); - - setMinisearches((prev) => ({ - ...prev, - [providerTitle]: minisearch, - })); - - if (providerTitle === "file") { - setFallbackResults((prev) => ({ - ...prev, - file: deduplicateArray( - [...lastOpenFilesRef.current, ...(prev.file ?? [])], - (a, b) => a.id === b.id, - ), + const itemsWithProvider = submenuItems.map((item) => ({ + ...item, + providerTitle, })); - } else { - setFallbackResults((prev) => ({ + + const minisearch = new MiniSearch( + { + fields: ["title", "description"], + storeFields: ["id", "title", "description", "providerTitle"], + }, + ); + + minisearch.addAll( + submenuItems.map((item) => ({ ...item, providerTitle })), + ); + + setMinisearches((prev) => ({ ...prev, - [providerTitle]: itemsWithProvider, + [providerTitle]: minisearch, })); + + if (providerTitle === "file") { + setFallbackResults((prev) => ({ + ...prev, + file: deduplicateArray( + [...lastOpenFilesRef.current, ...(prev.file ?? [])], + (a, b) => a.id === b.id, + ), + })); + } else { + setFallbackResults((prev) => ({ + ...prev, + [providerTitle]: itemsWithProvider, + })); + } + } catch (error) { + console.error( + `Error loading items for ${description.title}:`, + error, + ); + console.error( + "Error details:", + JSON.stringify(error, Object.getOwnPropertyNames(error)), + ); + } finally { + if (!controller.signal.aborted) { + providersLoading.delete(description.title); + } } - } catch (error) { - console.error( - `Error loading items for ${description.title}:`, - error, - ); - console.error( - "Error details:", - JSON.stringify(error, Object.getOwnPropertyNames(error)), - ); - } finally { - providersLoading.delete(description.title); - } - }, + }, + ), ); }, - [submenuContextProviders, disableIndexing, providersLoading], + [ + submenuContextProviders, + disableIndexing, + providersLoading, + abortControllers, + ], ); useWebviewListener( @@ -318,14 +343,13 @@ export const SubmenuContextProvidersProvider = ({ // Reload all submenu items on the initial config load // TODO - could refresh on any change const initialLoad = useRef(false); - const config = useAppSelector((store) => store.config.config); useEffect(() => { - if (!config?.contextProviders?.length || initialLoad.current) { + if (!submenuContextProviders.length || initialLoad.current) { return; } void loadSubmenuItems("all"); initialLoad.current = true; - }, [loadSubmenuItems, config, initialLoad]); + }, [loadSubmenuItems, submenuContextProviders, initialLoad]); return ( 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(); + + // 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, + }); + } + + return ( +
+ navigate("/")} title="Chat" /> +

Continue Config

+ + {!selectedProfile ? ( +

No config profile selected

+ ) : ( +
+
+ +
+

Other 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(); + }} + > + +
+ +
{ + e.preventDefault(); + handleDisableAutocompleteSubmit(); + }} + > + + + 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 3f36adcef..1bb5f5714 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -66,13 +66,17 @@ import { getMetaKeyLabel, isMetaEquivalentKeyPressed, } from "../../util"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; +import { + FREE_TRIAL_LIMIT_REQUESTS, + incrementFreeTrialCount, +} from "../../util/freeTrial"; import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; +import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -247,21 +251,29 @@ export function Chat() { editorToClearOnSend?: Editor, ) => { if (defaultModel?.provider === "free-trial") { - const u = getLocalStorage("ftc"); - if (u) { - setLocalStorage("ftc", u + 1); + const newCount = incrementFreeTrialCount(); - if (u >= FREE_TRIAL_LIMIT_REQUESTS) { - onboardingCard.open("Best"); - posthog?.capture("ftc_reached"); - ideMessenger.ide.showToast( - "info", - "You've reached the free trial limit. Please configure a model to continue.", - ); - return; + if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { + posthog?.capture("ftc_reached"); + } + if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) { + // Show this message whether using platform or not + // So that something happens if in new chat + ideMessenger.ide.showToast( + "error", + "You've reached the free trial limit. Please configure a model to continue.", + ); + + // Card in chat will only show if no history + // Also, note that platform card ignore the "Best", always opens to main tab + onboardingCard.open("Best"); + + // If history, show the dialog, which will automatically close if there is not history + if (history.length) { + dispatch(setDialogMessage()); + dispatch(setShowDialog(true)); } - } else { - setLocalStorage("ftc", 1); + return; } } @@ -543,14 +555,14 @@ export function Chat() { {onboardingCard.show && (
{usePlatform ? ( - + ) : ( - + )}
)} - {showTutorialCard !== false && !onboardingCard.open && ( + {showTutorialCard !== false && !onboardingCard.show && (
diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 10414fbb7..2ece67b85 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -90,6 +90,12 @@ const initialState: SessionState = { id: "local", title: "Local", errors: undefined, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, }, ], curCheckpointIndex: 0, @@ -356,9 +362,26 @@ 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] && diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 4432b3be6..b1c74f34b 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -36,6 +36,7 @@ const saveSubsetFilters = [ createFilter("editModeState", []), createFilter("config", ["defaultModelTitle"]), createFilter("ui", ["toolSettings", "useTools"]), + createFilter("indexing", []), ]; const migrations: MigrationManifest = { diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index d9f35cfd6..c311df194 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -166,7 +166,7 @@ export const saveCurrentSession = createAsyncThunk< let title = state.session.title; if (title === NEW_SESSION_TITLE) { if ( - state.config.config?.ui?.getChatTitles && + !state.config.config?.disableSessionTitles && state.config.defaultModelTitle ) { let assistantResponse = state.session.history @@ -190,7 +190,7 @@ export const saveCurrentSession = createAsyncThunk< } } } - // Fallbacks if above doesn't work out or getChatTitles = false + // Fallbacks if above doesn't work out or session titles disabled if (title === NEW_SESSION_TITLE) { title = getChatTitleFromMessage(state.session.history[0].message); } diff --git a/gui/src/util/freeTrial.ts b/gui/src/util/freeTrial.ts index 83e9ea510..1961fb358 100644 --- a/gui/src/util/freeTrial.ts +++ b/gui/src/util/freeTrial.ts @@ -1,11 +1,13 @@ -import { getLocalStorage } from "./localStorage"; +import { getLocalStorage, setLocalStorage } from "./localStorage"; export const FREE_TRIAL_LIMIT_REQUESTS = 50; -/** - * - * @returns {boolean} true if the user has passed the free trial limit, false otherwise. - */ export function hasPassedFTL(): boolean { return (getLocalStorage("ftc") ?? 0) > FREE_TRIAL_LIMIT_REQUESTS; } + +export function incrementFreeTrialCount(): number { + const u = getLocalStorage("ftc") ?? 0; + setLocalStorage("ftc", u + 1); + return u + 1; +} 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/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",