diff --git a/.changes/unreleased/Changed-20240905-130813.yaml b/.changes/unreleased/Changed-20240905-130813.yaml
new file mode 100644
index 000000000..415831eb6
--- /dev/null
+++ b/.changes/unreleased/Changed-20240905-130813.yaml
@@ -0,0 +1,4 @@
+project: extensions/vscode
+kind: Changed
+body: Use Chromium only as a fallback after asking user
+time: 2024-09-05T13:08:13.018136-07:00
diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml
index 7ce7aeb71..459774b74 100644
--- a/.github/workflows/main.yaml
+++ b/.github/workflows/main.yaml
@@ -161,9 +161,9 @@ jobs:
run: cd extensions/vscode && npx vsce package --no-dependencies --target ${{ env.target }}
# 6. Upload the .vsix as an artifact
- - uses: actions/upload-artifact@v2
+ - uses: actions/upload-artifact@v4
with:
- name: ${{ env.target }}
+ name: ${{ env.target }}-vsix
path: "extensions/vscode/*.vsix"
release:
@@ -182,21 +182,18 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: "*-vsix"
+ path: vsix-artifacts
+ merge-multiple: true
- name: Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
files: |
- alpine-x64/*.vsix
- darwin-arm64/*.vsix
- darwin-x64/*.vsix
- linux-arm64/*.vsix
- linux-armhf/*.vsix
- linux-x64/*.vsix
- win32-x64/*.vsix
- win32-arm64/*.vsix
+ vsix-artifacts/*.vsix
token: ${{ secrets.CI_GITHUB_TOKEN }}
repository: continuedev/continue
@@ -220,13 +217,17 @@ jobs:
run: git pull origin main
# 1. Download the artifacts
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: "*-vsix"
+ path: vsix-artifacts
+ merge-multiple: true
# 2. Publish the extension to VS Code Marketplace
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
- npx vsce publish --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
+ npx vsce publish --packagePath ../../vsix-artifacts/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
@@ -235,7 +236,7 @@ jobs:
continue-on-error: true
run: |
cd extensions/vscode
- npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
+ npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
# 4. Update the package.json version and push changes
# - name: Update version in package.json
diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml
index 3958730ec..fbc69b64f 100644
--- a/.github/workflows/preview.yaml
+++ b/.github/workflows/preview.yaml
@@ -156,9 +156,9 @@ jobs:
run: cd extensions/vscode && npx vsce package --pre-release --no-dependencies --target ${{ env.target }}
# 6. Upload the .vsix as an artifact
- - uses: actions/upload-artifact@v2
+ - uses: actions/upload-artifact@v4
with:
- name: ${{ env.target }}
+ name: ${{ env.target }}-vsix
path: "extensions/vscode/*.vsix"
release:
@@ -177,21 +177,18 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: "*-vsix"
+ path: vsix-artifacts
+ merge-multiple: true
- name: Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
files: |
- alpine-x64/*.vsix
- darwin-arm64/*.vsix
- darwin-x64/*.vsix
- linux-arm64/*.vsix
- linux-armhf/*.vsix
- linux-x64/*.vsix
- win32-x64/*.vsix
- win32-arm64/*.vsix
+ vsix-artifacts/*.vsix
token: ${{ secrets.CI_GITHUB_TOKEN }}
repository: continuedev/continue
prerelease: true
@@ -216,13 +213,17 @@ jobs:
run: git pull origin dev
# 1. Download the artifacts
- - uses: actions/download-artifact@v3
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: "*-vsix"
+ path: vsix-artifacts
+ merge-multiple: true
# 2. Publish the extension to VS Code Marketplace
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
- npx vsce publish --pre-release --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
+ npx vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
@@ -231,7 +232,7 @@ jobs:
continue-on-error: true
run: |
cd extensions/vscode
- npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
+ npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
# 4. Update the package.json version and push changes
# - name: Update version in package.json
diff --git a/.vscode/settings.json b/.vscode/settings.json
index f56d10f61..41b357765 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -18,5 +18,8 @@
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true
- }
+ },
+ "eslint.workingDirectories": [
+ "./core"
+ ]
}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0a998802a..9fad5eb06 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -238,7 +238,7 @@ Continue consists of 2 parts that are split so that it can be extended to work i
1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
-2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/debugPanel.ts).
+2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
### Continue VS Code Extension
diff --git a/archive/python.yaml b/archive/python.yaml
deleted file mode 100644
index db4edf41f..000000000
--- a/archive/python.yaml
+++ /dev/null
@@ -1,44 +0,0 @@
-on:
-
-defaults:
- run:
- working-directory: ./server
-
-jobs:
- lint:
- runs-on: ubuntu-latest
- name: ${{ matrix.name }}
- strategy:
- fail-fast: false
- matrix:
- include:
- - name: ruff
- command: ruff check --output-format=github .
- deps: --only lint-ruff
- - name: mypy
- command: mypy
- deps: --with lint-typing
- steps:
- - uses: actions/checkout@v4
- - name: Install Python
- uses: actions/setup-python@v4
- with:
- python-version: "3.11"
- - uses: snok/install-poetry@v1
- - name: Install dependencies
- run: poetry install ${{ matrix.deps }}
- - run: poetry run ${{ matrix.command }}
-
- # test:
- # runs-on: ubuntu-latest
- # steps:
- # - uses: actions/checkout@v4
- # - name: Install Python
- # uses: actions/setup-python@v4
- # with:
- # python-version: "3.12"
- # - uses: snok/install-poetry@v1
- # - run: poetry run python -m pip install --upgrade pip setuptools
- # - name: Install dependencies
- # run: poetry install
- # - run: poetry run pytest
diff --git a/archive/rust.yaml b/archive/rust.yaml
deleted file mode 100644
index 6bbb23423..000000000
--- a/archive/rust.yaml
+++ /dev/null
@@ -1,65 +0,0 @@
-on:
-
-name: Rust Continuous integration
-
-defaults:
- run:
- working-directory: ./server
-
-jobs:
- # test:
- # name: test
- # runs-on: ${{ matrix.os }}
- # strategy:
- # matrix:
- # os: [ubuntu-latest, macos-latest, windows-latest]
- # toolchain: [stable]
- # include:
- # - os: ubuntu-latest
- # toolchain: nightly
- # steps:
- # - uses: actions/checkout@v4
- # - uses: dtolnay/rust-toolchain@master
- # with:
- # toolchain: ${{ matrix.toolchain }}
- # - run: cargo test --all-features
-
- fmt:
- name: format
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - uses: dtolnay/rust-toolchain@nightly
- with:
- components: rustfmt
- - run: cargo fmt --all --check
-
- clippy:
- name: lint
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - uses: dtolnay/rust-toolchain@master
- with:
- toolchain: nightly-2023-12-10
- components: clippy
- - uses: actions-rs-plus/clippy-check@v2
- with:
- working-directory: server/
- args: --all-features --all-targets
-
- docs:
- name: docs
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - uses: dtolnay/rust-toolchain@stable
- - run: cargo doc --no-deps
-
- cargo-deny:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - uses: EmbarkStudios/cargo-deny-action@v1
- with:
- arguments: --manifest-path server/Cargo.toml
diff --git a/binary/package-lock.json b/binary/package-lock.json
index d2fd02d2b..7ed2f9aea 100644
--- a/binary/package-lock.json
+++ b/binary/package-lock.json
@@ -57,6 +57,7 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
+ "cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
diff --git a/core/autocomplete/cache.ts b/core/autocomplete/cache.ts
index c3daefb1c..5005480bf 100644
--- a/core/autocomplete/cache.ts
+++ b/core/autocomplete/cache.ts
@@ -20,6 +20,8 @@ export class AutocompleteLruCache {
driver: sqlite3.Database,
});
+ await db.exec("PRAGMA busy_timeout = 3000;");
+
await db.run(`
CREATE TABLE IF NOT EXISTS cache (
key TEXT PRIMARY KEY,
diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts
index 39d2d1e73..bbc2d2577 100644
--- a/core/autocomplete/completionProvider.ts
+++ b/core/autocomplete/completionProvider.ts
@@ -311,10 +311,17 @@ export class CompletionProvider {
// Get completion
const llm = await this.getLlm();
+
if (!llm) {
return undefined;
}
+ // Ignore empty API keys for Mistral since we currently write
+ // a template provider without one during onboarding
+ if (llm.providerName === "mistral" && llm.apiKey === "") {
+ return undefined;
+ }
+
// Set temperature (but don't overrride)
if (llm.completionOptions.temperature === undefined) {
llm.completionOptions.temperature = 0.01;
diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts
index 57f728a05..99f77270f 100644
--- a/core/config/ConfigHandler.ts
+++ b/core/config/ConfigHandler.ts
@@ -10,8 +10,13 @@ import {
IdeSettings,
ILLM,
} from "../index.js";
+import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { finalToBrowserConfig } from "./load.js";
+import {
+ LOCAL_ONBOARDING_CHAT_MODEL,
+ ONBOARDING_LOCAL_MODEL_TITLE,
+} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@@ -279,9 +284,18 @@ export class ConfigHandler {
async llmFromTitle(title?: string): Promise {
const config = await this.loadConfig();
- const model =
- config.models.find((m) => m.title === title) || config.models[0];
+ const model = config.models.find((m) => m.title === title);
if (!model) {
+ if (title === ONBOARDING_LOCAL_MODEL_TITLE) {
+ // Special case, make calls to Ollama before we have it in the config
+ const ollama = new Ollama({
+ model: LOCAL_ONBOARDING_CHAT_MODEL,
+ });
+ return ollama;
+ } else if (config.models.length > 0) {
+ return config.models[0];
+ }
+
throw new Error("No model found");
}
diff --git a/core/config/default.ts b/core/config/default.ts
index b4a05f6f5..af5b19913 100644
--- a/core/config/default.ts
+++ b/core/config/default.ts
@@ -3,9 +3,28 @@ import {
ModelDescription,
SerializedContinueConfig,
SlashCommandDescription,
-} from "../index.js";
+} from "../";
+
+export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = {
+ model: "claude-3-5-sonnet-20240620",
+ provider: "anthropic",
+ apiKey: "",
+ title: "Claude 3.5 Sonnet",
+};
+
+export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = {
+ title: "Codestral",
+ provider: "mistral",
+ model: "codestral-latest",
+ apiKey: "",
+};
export const FREE_TRIAL_MODELS: ModelDescription[] = [
+ {
+ title: "Claude 3 Sonnet (Free Trial)",
+ provider: "free-trial",
+ model: "claude-3-sonnet-20240229",
+ },
{
title: "GPT-4o (Free Trial)",
provider: "free-trial",
@@ -25,11 +44,6 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [
provider: "free-trial",
model: "codestral",
},
- {
- title: "Claude 3 Sonnet (Free Trial)",
- provider: "free-trial",
- model: "claude-3-sonnet-20240229",
- },
];
export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [
@@ -91,7 +105,8 @@ export const defaultSlashCommandsJetBrains = [
];
export const defaultConfig: SerializedContinueConfig = {
- models: [],
+ models: [DEFAULT_CHAT_MODEL_CONFIG],
+ tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
@@ -100,17 +115,13 @@ export const defaultConfig: SerializedContinueConfig = {
description: "Write unit tests for highlighted code",
},
],
- tabAutocompleteModel: {
- title: "Starcoder2 3b",
- provider: "ollama",
- model: "starcoder2:3b",
- },
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
- models: FREE_TRIAL_MODELS,
+ models: [DEFAULT_CHAT_MODEL_CONFIG],
+ tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
@@ -119,11 +130,6 @@ export const defaultConfigJetBrains: SerializedContinueConfig = {
description: "Write unit tests for highlighted code",
},
],
- tabAutocompleteModel: {
- title: "Starcoder2 3b",
- provider: "ollama",
- model: "starcoder2:3b",
- },
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
};
diff --git a/core/config/load.ts b/core/config/load.ts
index 2bb836d73..95fc73053 100644
--- a/core/config/load.ts
+++ b/core/config/load.ts
@@ -306,7 +306,7 @@ async function intermediateToFinalConfig(
(model) => model.providerName === "free-trial",
);
if (freeTrialModels.length > 0) {
- const ghAuthToken = await ide.getGitHubAuthToken();
+ const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
}
@@ -341,7 +341,7 @@ async function intermediateToFinalConfig(
// This shouldn't happen
throw new Error("Free trial cannot be used with control plane");
}
- const ghAuthToken = await ide.getGitHubAuthToken();
+ const ghAuthToken = await ide.getGitHubAuthToken({});
(llm as FreeTrial).setupGhAuthToken(ghAuthToken);
}
return llm;
@@ -356,7 +356,14 @@ async function intermediateToFinalConfig(
// These context providers are always included, regardless of what, if anything,
// the user has configured in config.json
- const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {};
+ const codebaseContextParams =
+ (
+ (config.contextProviders || [])
+ .filter(isContextProviderWithParams)
+ .find((cp) => cp.name === "codebase") as
+ | ContextProviderWithParams
+ | undefined
+ )?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts
index 5b727c34f..c0c5d7e9d 100644
--- a/core/config/onboarding.ts
+++ b/core/config/onboarding.ts
@@ -1,56 +1,51 @@
-import { SerializedContinueConfig } from "../index.js";
-import { FREE_TRIAL_MODELS } from "./default.js";
+import { SerializedContinueConfig } from "../";
+import { FREE_TRIAL_MODELS } from "./default";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
+export const LOCAL_ONBOARDING_FIM_MODEL = "starcoder2:3b";
+export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
+export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
-export function setupApiKeysMode(
+/**
+ * We set the "best" chat + autocopmlete models by default
+ * whenever a user doesn't have a config.json
+ */
+export function setupBestConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: config.models.filter((model) => model.provider !== "free-trial"),
- embeddingsProvider: {
- provider: "free-trial",
- },
- reranker: {
- name: "free-trial",
- },
};
}
-export function setupLocalMode(
+export function setupLocalConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
- title: "Llama 3",
+ title: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
- model: "llama3",
- },
- {
- title: ONBOARDING_LOCAL_MODEL_TITLE,
- provider: "ollama",
- model: "AUTODETECT",
+ model: LOCAL_ONBOARDING_CHAT_MODEL,
},
...config.models.filter((model) => model.provider !== "free-trial"),
],
tabAutocompleteModel: {
title: "Starcoder 3b",
provider: "ollama",
- model: "starcoder2:3b",
+ model: LOCAL_ONBOARDING_FIM_MODEL,
},
embeddingsProvider: {
provider: "ollama",
model: "nomic-embed-text",
},
- reranker: undefined,
};
}
-export function setupFreeTrialMode(
+export function setupQuickstartConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
@@ -73,16 +68,16 @@ export function setupFreeTrialMode(
};
}
-export function setupLocalAfterFreeTrial(
+export function setupLocalConfigAfterFreeTrial(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
- title: "Llama 3",
+ title: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
- model: "llama3",
+ model: LOCAL_ONBOARDING_CHAT_MODEL,
},
{
title: ONBOARDING_LOCAL_MODEL_TITLE,
diff --git a/core/config/types.ts b/core/config/types.ts
index 84e888244..e69c312ab 100644
--- a/core/config/types.ts
+++ b/core/config/types.ts
@@ -600,6 +600,7 @@ declare global {
| "msty"
| "watsonx"
| "openrouter"
+ | "sambanova"
| "nvidia";
export type ModelName =
diff --git a/core/config/util.ts b/core/config/util.ts
index 1b2c397b7..5abf0b9b5 100644
--- a/core/config/util.ts
+++ b/core/config/util.ts
@@ -1,5 +1,5 @@
-import { ModelDescription } from "../index.js";
-import { editConfigJson } from "../util/paths.js";
+import { ContextProviderWithParams, ModelDescription } from "../";
+import { editConfigJson } from "../util/paths";
function stringify(obj: any, indentation?: number): string {
return JSON.stringify(
@@ -11,6 +11,18 @@ function stringify(obj: any, indentation?: number): string {
);
}
+export function addContextProvider(provider: ContextProviderWithParams) {
+ editConfigJson((config) => {
+ if (!config.contextProviders) {
+ config.contextProviders = [provider];
+ } else {
+ config.contextProviders.push(provider);
+ }
+
+ return config;
+ });
+}
+
export function addModel(model: ModelDescription) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts
index 3f84c6fed..837e4d05d 100644
--- a/core/context/providers/CodeContextProvider.ts
+++ b/core/context/providers/CodeContextProvider.ts
@@ -16,6 +16,7 @@ class CodeContextProvider extends BaseContextProvider {
displayTitle: "Code",
description: "Type to search",
type: "submenu",
+ dependsOnIndexing: true,
};
async getContextItems(
diff --git a/core/context/providers/CustomContextProvider.ts b/core/context/providers/CustomContextProvider.ts
index fd996f398..ac14dc9f4 100644
--- a/core/context/providers/CustomContextProvider.ts
+++ b/core/context/providers/CustomContextProvider.ts
@@ -5,7 +5,7 @@ import type {
CustomContextProvider,
IContextProvider,
LoadSubmenuItemsArgs,
-} from "../../index.js";
+} from "../../";
class CustomContextProviderClass implements IContextProvider {
custom: CustomContextProvider;
diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts
index 972c12190..88df47318 100644
--- a/core/context/providers/DocsContextProvider.ts
+++ b/core/context/providers/DocsContextProvider.ts
@@ -90,7 +90,8 @@ class DocsContextProvider extends BaseContextProvider {
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
- extras.ide.errorPopup(
+ extras.ide.showToast(
+ "error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
@@ -108,8 +109,9 @@ class DocsContextProvider extends BaseContextProvider {
});
}
- const embeddingsProvider =
- await docsService.getEmbeddingsProvider(!!preIndexedDoc);
+ const embeddingsProvider = await docsService.getEmbeddingsProvider(
+ !!preIndexedDoc,
+ );
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts
index 5e9cc3f77..ef0bfeb54 100644
--- a/core/context/providers/FileContextProvider.ts
+++ b/core/context/providers/FileContextProvider.ts
@@ -21,6 +21,7 @@ class FileContextProvider extends BaseContextProvider {
displayTitle: "Files",
description: "Type to search",
type: "submenu",
+ dependsOnIndexing: true,
};
async getContextItems(
diff --git a/core/context/providers/FileTreeContextProvider.ts b/core/context/providers/FileTreeContextProvider.ts
index 52af97823..5b5d99fed 100644
--- a/core/context/providers/FileTreeContextProvider.ts
+++ b/core/context/providers/FileTreeContextProvider.ts
@@ -34,6 +34,7 @@ class FileTreeContextProvider extends BaseContextProvider {
description: "Attach a representation of the file tree",
type: "normal",
renderInlineAs: "",
+ dependsOnIndexing: true,
};
async getContextItems(
diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts
index 4c2869a90..a4b1101fb 100644
--- a/core/context/providers/FolderContextProvider.ts
+++ b/core/context/providers/FolderContextProvider.ts
@@ -5,7 +5,11 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
-import { getBasename, groupByLastNPathParts, getUniqueFilePath } from "../../util/index.js";
+import {
+ getBasename,
+ groupByLastNPathParts,
+ getUniqueFilePath,
+} from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
class FolderContextProvider extends BaseContextProvider {
@@ -14,6 +18,7 @@ class FolderContextProvider extends BaseContextProvider {
displayTitle: "Folder",
description: "Type to search",
type: "submenu",
+ dependsOnIndexing: true,
};
async getContextItems(
@@ -35,7 +40,7 @@ class FolderContextProvider extends BaseContextProvider {
return {
id: folder,
title: getBasename(folder),
- description: getUniqueFilePath(folder, folderGroups)
+ description: getUniqueFilePath(folder, folderGroups),
};
});
}
diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts
index c0f25c12b..ef34ad621 100644
--- a/core/context/providers/GitHubIssuesContextProvider.ts
+++ b/core/context/providers/GitHubIssuesContextProvider.ts
@@ -21,9 +21,11 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
): Promise {
const issueId = query;
const { Octokit } = await import("@octokit/rest");
+ const domain = this.options?.domain ?? "github.com";
const octokit = new Octokit({
auth: this.options?.githubToken,
+ baseUrl: `https://${domain}/api/v3`,
request: {
fetch: extras.fetch,
},
diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts
index 27f6df803..6c9320f8f 100644
--- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts
+++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts
@@ -1,6 +1,7 @@
-import { RequestOptions } from "../../../index.js";
+import { RequestOptions } from "../../../";
// @ts-ignore
import adf2md from "adf-to-md";
+
interface JiraClientOptions {
domain: string;
username: string;
@@ -112,7 +113,7 @@ export class JiraClient {
if (typeof issue.fields.description === "string") {
result.description = issue.fields.description;
} else if (issue.fields.description) {
- result.description = adf2md(issue.fields.description).result;
+ result.description = adf2md.validate(issue.fields.description).result;
} else {
result.description = "";
}
@@ -122,7 +123,7 @@ export class JiraClient {
const body =
typeof comment.body === "string"
? comment.body
- : adf2md(comment.body).result;
+ : adf2md.validate(comment.body).result;
return {
body,
diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts
index bf0a1f604..3d6c1d63f 100644
--- a/core/context/providers/RepoMapContextProvider.ts
+++ b/core/context/providers/RepoMapContextProvider.ts
@@ -12,6 +12,7 @@ class RepoMapContextProvider extends BaseContextProvider {
displayTitle: "Repository Map",
description: "List of files and signatures",
type: "normal",
+ dependsOnIndexing: true,
};
async getContextItems(
diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts
index 80f4b3aea..34c6bd87c 100644
--- a/core/context/retrieval/retrieval.ts
+++ b/core/context/retrieval/retrieval.ts
@@ -4,6 +4,7 @@ import {
ContextProviderExtras,
} from "../../index.js";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
+import { resolveRelativePathInWorkspace } from "../../util/ideUtils.js";
import { getRelativePath } from "../../util/index.js";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js";
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js";
@@ -66,6 +67,14 @@ export async function retrieveContextItemsFromEmbeddings(
? RerankerRetrievalPipeline
: NoRerankerRetrievalPipeline;
+ if (filterDirectory) {
+ // Handle relative paths
+ filterDirectory = await resolveRelativePathInWorkspace(
+ filterDirectory,
+ extras.ide,
+ );
+ }
+
const pipelineOptions: RetrievalPipelineOptions = {
nFinal,
nRetrieve,
diff --git a/core/core.ts b/core/core.ts
index d813ee830..7148c8c15 100644
--- a/core/core.ts
+++ b/core/core.ts
@@ -3,10 +3,10 @@ import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
import { CompletionProvider } from "./autocomplete/completionProvider";
import { ConfigHandler } from "./config/ConfigHandler";
import {
- setupApiKeysMode,
- setupFreeTrialMode,
- setupLocalAfterFreeTrial,
- setupLocalMode,
+ setupBestConfig,
+ setupLocalConfig,
+ setupLocalConfigAfterFreeTrial,
+ setupQuickstartConfig,
} from "./config/onboarding";
import { createNewPromptFile } from "./config/promptFile";
import { addModel, addOpenAIKey, deleteModel } from "./config/util";
@@ -15,7 +15,6 @@ import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
-import DocsCrawler from "./indexing/docs/DocsCrawler";
import DocsService from "./indexing/docs/DocsService";
import Ollama from "./llm/llms/Ollama";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@@ -169,12 +168,6 @@ export class Core {
(..._) => Promise.resolve([]),
);
- try {
- DocsCrawler.verifyOrInstallChromium();
- } catch (err) {
- console.debug(`Failed to install Chromium: ${err}`);
- }
-
const on = this.messenger.on.bind(this.messenger);
this.messenger.onError((err) => {
@@ -183,7 +176,7 @@ export class Core {
message: err.message,
stack: err.stack,
});
- this.messenger.request("errorPopup", { message: err.message });
+ this.ide.showToast("error", err.message);
});
// New
@@ -279,9 +272,9 @@ export class Core {
}
if (hasFailed) {
- this.ide.infoPopup(`Failed to index ${msg.data.startUrl}`);
+ this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
- this.ide.infoPopup(`Successfully indexed ${msg.data.startUrl}`);
+ this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`);
this.messenger.send("refreshSubmenuItems", undefined);
}
});
@@ -351,7 +344,10 @@ export class Core {
id,
}));
} catch (e) {
- this.ide.errorPopup(`Error getting context items from ${name}: ${e}`);
+ this.ide.showToast(
+ "error",
+ `Error getting context items from ${name}: ${e}`,
+ );
return [];
}
});
@@ -472,7 +468,7 @@ export class Core {
}
}
} catch (e) {
- console.warn(`Error listing Ollama models: ${e}`);
+ console.debug(`Error listing Ollama models: ${e}`);
return undefined;
}
});
@@ -610,31 +606,27 @@ export class Core {
on("completeOnboarding", (msg) => {
const mode = msg.data.mode;
- Telemetry.capture("onboardingSelection", {
- mode,
- });
-
- if (mode === "custom") {
+ if (mode === "Custom") {
return;
}
let editConfigJsonCallback: Parameters[0];
switch (mode) {
- case "local":
- editConfigJsonCallback = setupLocalMode;
+ case "Local":
+ editConfigJsonCallback = setupLocalConfig;
break;
- case "freeTrial":
- editConfigJsonCallback = setupFreeTrialMode;
+ case "Quickstart":
+ editConfigJsonCallback = setupQuickstartConfig;
break;
- case "localAfterFreeTrial":
- editConfigJsonCallback = setupLocalAfterFreeTrial;
+ case "LocalAfterFreeTrial":
+ editConfigJsonCallback = setupLocalConfigAfterFreeTrial;
break;
- case "apiKeys":
- editConfigJsonCallback = setupApiKeysMode;
+ case "Best":
+ editConfigJsonCallback = setupBestConfig;
break;
default:
diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.test.ts
index 72be00746..0ad669280 100644
--- a/core/diff/streamDiff.test.ts
+++ b/core/diff/streamDiff.test.ts
@@ -1,11 +1,19 @@
+import fs from "node:fs";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
+import path from "node:path";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract | "modification";
+const UNIFIED_DIFF_SYMBOLS = {
+ same: "",
+ new: "+",
+ old: "-",
+};
+
async function* generateLines(lines: string[]): AsyncGenerator {
for (const line of lines) {
yield line;
@@ -43,6 +51,43 @@ function getMyersDiffType(diff: any): MyersDiffTypes | undefined {
return undefined;
}
+function displayDiff(diff: DiffLine[]) {
+ return diff
+ .map(({ type, line }) => `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`)
+ .join("\n");
+}
+
+async function expectDiff(file: string) {
+ const testFilePath = path.join(
+ __dirname,
+ "diff",
+ "test-examples",
+ file + ".diff",
+ );
+ const testFileContents = fs.readFileSync(testFilePath, "utf-8");
+ const [oldText, newText, expectedDiff] = testFileContents
+ .split("\n---\n")
+ .map((s) => s.replace(/^\n+/, "").trimEnd());
+ const oldLines = oldText.split("\n");
+ const newLines = newText.split("\n");
+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
+ const displayedDiff = displayDiff(streamDiffs);
+
+ if (!expectedDiff || expectedDiff.trim() === "") {
+ console.log(
+ "Expected diff was empty. Writing computed diff to the test file",
+ );
+ fs.writeFileSync(
+ testFilePath,
+ `${oldText}\n\n---\n\n${newText}\n\n---\n\n${displayedDiff}`,
+ );
+
+ throw new Error("Expected diff is empty");
+ }
+
+ expect(displayedDiff).toEqual(expectedDiff);
+}
+
// We use a longer `)` string here to not get
// caught by the fuzzy matcher
describe("streamDiff(", () => {
@@ -177,4 +222,20 @@ describe("streamDiff(", () => {
expect(myersDiffs[0].lhs.del).toEqual(2);
expect(getMyersDiffType(myersDiffs[0])).toBe("old");
});
+
+ test("tabs vs. spaces differences are ignored", async () => {
+ await expectDiff("fastapi-tabs-vs-spaces");
+ });
+
+ test("FastAPI example", async () => {
+ await expectDiff("fastapi");
+ });
+
+ test("FastAPI comments", async () => {
+ await expectDiff("add-comments");
+ });
+
+ test("Mock LLM example", async () => {
+ await expectDiff("mock-llm");
+ });
});
diff --git a/core/diff/test-examples/README.md b/core/diff/test-examples/README.md
new file mode 100644
index 000000000..b9b95421a
--- /dev/null
+++ b/core/diff/test-examples/README.md
@@ -0,0 +1,23 @@
+# Diff algorithm tests
+
+Tests are specified as
+
+```
+
+
+---
+
+
+
+---
+
+
+```
+
+`---` is the delimeter, and surrounding whitespace will be trimmed.
+
+The expected diff can be generated with the `displayDiff` function.
+
+We make this explicit instead of comparing to the output of `myersDiff` in case the output from that is either unattainable or not exactly what we want.
+
+In order to generate the expected diff, you can first leave it empty and then run the test. The test will catch this and write the _computed_ diff to the test file. It is up to you to correct this to the expected diff.
diff --git a/core/diff/test-examples/add-comments.diff b/core/diff/test-examples/add-comments.diff
new file mode 100644
index 000000000..8cc084dce
--- /dev/null
+++ b/core/diff/test-examples/add-comments.diff
@@ -0,0 +1,53 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+@app.get("/landing")
+def read_landing_page():
+ return {"message": "Welcome to the landing page"}
+
+---
+
+# Import the FastAPI class from the fastapi module
+from fastapi import FastAPI
+
+# Create an instance of the FastAPI application
+app = FastAPI()
+
+# Define a route for the root endpoint ("/")
+@app.get("/")
+def read_root():
+ # Return a simple JSON response
+ return {"Hello": "World"} // This is an example comment
+
+# Define a route for the landing page endpoint ("/landing")
+@app.get("/landing")
+def read_landing_page():
+ # Return a JSON response with a welcome message
+ return {"message": "Welcome to the landing page"}
+
+---
+
++ # Import the FastAPI class from the fastapi module
+ from fastapi import FastAPI
+
++ # Create an instance of the FastAPI application
+ app = FastAPI()
+
++ # Define a route for the root endpoint ("/")
+ @app.get("/")
+ def read_root():
++ # Return a simple JSON response
++ return {"Hello": "World"} // This is an example comment
++
++ # Define a route for the landing page endpoint ("/landing")
+- return {"Hello": "World"}
+-
+ @app.get("/landing")
+ def read_landing_page():
++ # Return a JSON response with a welcome message
+ return {"message": "Welcome to the landing page"}
\ No newline at end of file
diff --git a/core/diff/test-examples/fastapi-tabs-vs-spaces.diff b/core/diff/test-examples/fastapi-tabs-vs-spaces.diff
new file mode 100644
index 000000000..37df56673
--- /dev/null
+++ b/core/diff/test-examples/fastapi-tabs-vs-spaces.diff
@@ -0,0 +1,42 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+@app.get("/")
+def read_root():
+\treturn {"Hello": "World"}
+
+@app.get("/landing")
+def read_landing_page():
+\treturn {"message": "Welcome to the landing page"}
+
+---
+
+from fastapi import FastAPI, HTTPException
+
+app = FastAPI()
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+@app.get("/landing")
+def read_landing_page():
+ raise HTTPException(status_code=404, detail="Page not found")
+
+---
+
+- from fastapi import FastAPI
++ from fastapi import FastAPI, HTTPException
+
+ app = FastAPI()
+
+ @app.get("/")
+ def read_root():
+- \treturn {"Hello": "World"}
++ return {"Hello": "World"}
+
+ @app.get("/landing")
+ def read_landing_page():
++ raise HTTPException(status_code=404, detail="Page not found")
+- \treturn {"message": "Welcome to the landing page"}
\ No newline at end of file
diff --git a/core/diff/test-examples/fastapi.diff b/core/diff/test-examples/fastapi.diff
new file mode 100644
index 000000000..0c8a0ba76
--- /dev/null
+++ b/core/diff/test-examples/fastapi.diff
@@ -0,0 +1,41 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+@app.get("/landing")
+def read_landing_page():
+ return {"message": "Welcome to the landing page"}
+
+---
+
+from fastapi import FastAPI, HTTPException
+
+app = FastAPI()
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+@app.get("/landing")
+def read_landing_page():
+ raise HTTPException(status_code=404, detail="Page not found")
+
+---
+
+- from fastapi import FastAPI
++ from fastapi import FastAPI, HTTPException
+
+ app = FastAPI()
+
+ @app.get("/")
+ def read_root():
+ return {"Hello": "World"}
+
+ @app.get("/landing")
+ def read_landing_page():
++ raise HTTPException(status_code=404, detail="Page not found")
+- return {"message": "Welcome to the landing page"}
\ No newline at end of file
diff --git a/core/diff/test-examples/mock-llm.diff b/core/diff/test-examples/mock-llm.diff
new file mode 100644
index 000000000..42321da5c
--- /dev/null
+++ b/core/diff/test-examples/mock-llm.diff
@@ -0,0 +1,103 @@
+import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
+import { BaseLLM } from "../index.js";
+
+class Mock extends BaseLLM {
+ static Completion = "Test Completion";
+ static providerName: ModelProvider = "mock";
+
+ protected async *_streamComplete(
+ prompt: string,
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ yield Mock.Completion;
+ }
+
+ protected async *_streamChat(
+ messages: ChatMessage[],
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ yield {
+ role: "assistant",
+ content: Mock.Completion,
+ };
+ }
+}
+
+export default Mock;
+
+---
+
+import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
+import { BaseLLM } from "../index.js";
+
+class Mock extends BaseLLM {
+ private static _completion: string = "Test Completion";
+ static providerName: ModelProvider = "mock";
+
+ static get completion(): string {
+ return Mock._completion;
+ }
+
+ static set completion(value: string) {
+ Mock._completion = value;
+ }
+
+ protected async *_streamComplete(
+ prompt: string,
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ yield Mock.completion;
+ }
+
+ protected async *_streamChat(
+ messages: ChatMessage[],
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ yield {
+ role: "assistant",
+ content: Mock.completion,
+ };
+ }
+}
+
+export default Mock;
+
+---
+
+ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
+ import { BaseLLM } from "../index.js";
+
+ class Mock extends BaseLLM {
+- static Completion = "Test Completion";
++ private static _completion: string = "Test Completion";
+ static providerName: ModelProvider = "mock";
+
++ static get completion(): string {
++ return Mock._completion;
++ }
++
++ static set completion(value: string) {
++ Mock._completion = value;
++ }
++
+ protected async *_streamComplete(
+ prompt: string,
+ options: CompletionOptions,
+ ): AsyncGenerator {
+- yield Mock.Completion;
++ yield Mock.completion;
+ }
+
+ protected async *_streamChat(
+ messages: ChatMessage[],
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ yield {
+ role: "assistant",
+- content: Mock.Completion,
++ content: Mock.completion,
+ };
+ }
+ }
+
+ export default Mock;
\ No newline at end of file
diff --git a/core/diff/util.ts b/core/diff/util.ts
index b3a895da9..0e24ee373 100644
--- a/core/diff/util.ts
+++ b/core/diff/util.ts
@@ -31,7 +31,8 @@ function linesMatch(lineA: string, lineB: string, linesBetween = 0): boolean {
return (
// Should be more unlikely for lines to fuzzy match if they are further away
- (d / Math.max(lineA.length, lineB.length) < 0.5 - linesBetween * 0.05 ||
+ (d / Math.max(lineA.length, lineB.length) <=
+ Math.max(0, 0.48 - linesBetween * 0.06) ||
lineA.trim() === lineB.trim()) &&
lineA.trim() !== ""
);
diff --git a/core/index.d.ts b/core/index.d.ts
index 68c39b3c9..0c7c9b521 100644
--- a/core/index.d.ts
+++ b/core/index.d.ts
@@ -1,3 +1,5 @@
+import { GetGhTokenArgs } from "./protocol/ide";
+
declare global {
interface Window {
ide?: "vscode";
@@ -121,11 +123,12 @@ export interface ILLM extends LLMOptions {
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
- title: string;
+ title: ContextProviderName;
displayTitle: string;
description: string;
renderInlineAs?: string;
type: ContextProviderType;
+ dependsOnIndexing?: boolean;
}
export type FetchFunction = (url: string | URL, init?: any) => Promise;
@@ -316,6 +319,9 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions {
model?: string;
}
+
+export type ToastType = "info" | "error" | "warning";
+
export interface LLMOptions {
model: string;
@@ -362,6 +368,7 @@ export interface LLMOptions {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
+ watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
}
@@ -496,13 +503,15 @@ export interface IDE {
getBranch(dir: string): Promise;
getTags(artifactId: string): Promise;
getRepoName(dir: string): Promise;
- errorPopup(message: string): Promise;
- infoPopup(message: string): Promise;
-
+ showToast(
+ type: ToastType,
+ message: string,
+ ...otherParams: any[]
+ ): Promise;
getGitRootPath(dir: string): Promise;
listDir(dir: string): Promise<[string, FileType][]>;
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
- getGitHubAuthToken(): Promise;
+ getGitHubAuthToken(args: GetGhTokenArgs): Promise;
// LSP
gotoDefinition(location: Location): Promise;
@@ -568,7 +577,15 @@ type ContextProviderName =
| "docs"
| "gitlab-mr"
| "os"
- | "currentFile";
+ | "currentFile"
+ | "outline"
+ | "continue-proxy"
+ | "highlights"
+ | "file"
+ | "issue"
+ | "repo-map"
+ | "url"
+ | string;
type TemplateType =
| "llama2"
@@ -621,6 +638,7 @@ type ModelProvider =
| "msty"
| "watsonx"
| "openrouter"
+ | "sambanova"
| "nvidia"
| "vllm"
| "mock";
@@ -772,6 +790,7 @@ export interface ModelDescription {
}
export type EmbeddingsProviderName =
+ | "bedrock"
| "huggingface-tei"
| "transformers.js"
| "ollama"
@@ -781,6 +800,7 @@ export type EmbeddingsProviderName =
| "gemini"
| "continue-proxy"
| "deepinfra"
+ | "nvidia"
| "voyage"
| "mistral";
@@ -793,6 +813,12 @@ export interface EmbedOptions {
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
+ maxBatchSize?: number;
+ // AWS options
+ profile?: string;
+
+ // AWS and GCP Options
+ region?: string;
}
export interface EmbeddingsProviderDescription extends EmbedOptions {
@@ -913,6 +939,13 @@ interface ExperimentalConfig {
* Automatically read LLM chat responses aloud using system TTS models
*/
readResponseTTS?: boolean;
+
+ /**
+ * If set to true, we will attempt to pull down and install an instance of Chromium
+ * that is compatible with the current version of Puppeteer.
+ * This is needed to crawl a large number of documentation sites that are dynamically rendered.
+ */
+ useChromiumForDocsCrawling?: boolean;
}
interface AnalyticsConfig {
diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts
index b3c4b2593..4e9f00de8 100644
--- a/core/indexing/docs/DocsCrawler.skip.ts
+++ b/core/indexing/docs/DocsCrawler.skip.ts
@@ -1,28 +1,81 @@
-import DocsCrawler, { type PageData } from "./DocsCrawler";
+import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
+import { jest } from "@jest/globals";
+import FileSystemIde from "../../util/filesystem";
+import { testConfigHandler } from "../../test/util/fixtures";
+import os from "os";
+import { ContinueConfig } from "../..";
// Temporary workaround until we have better caching of Chromium
// download between test runs
-const TIMEOUT = 1_000_000;
+const TIMEOUT_MS = 1_000_000_000;
+
+// Overwrite the Chromium download path to `os.tmpdir()`
+// so that we don't delete the Chromium install between tests
+ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
// Skipped until we have a better way to cache Chromium installs
// between tests and in CI
-describe.skip("crawl", () => {
- describe("GitHub repositories", () => {
+describe.skip("DocsCrawler", () => {
+ const NUM_PAGES_TO_CRAWL = 5;
+
+ let config: ContinueConfig;
+ let mockIde: FileSystemIde;
+ let chromiumInstaller;
+ let docsCrawler: DocsCrawler;
+
+ beforeAll(async () => {
+ config = await testConfigHandler.loadConfig();
+ mockIde = new FileSystemIde(process.cwd());
+ chromiumInstaller = new ChromiumInstaller(mockIde, config);
+ docsCrawler = new DocsCrawler(mockIde, config);
+
+ // Make sure we have Chromium pulled down before beginning tests
+ await chromiumInstaller.install();
+ }, TIMEOUT_MS);
+
+ function crawlTest(
+ urls: string[],
+ numPagesToCrawl: number = NUM_PAGES_TO_CRAWL,
+ ) {
+ const numUrlsToTest = 5;
+ const randomUrls = urls
+ .sort(() => 0.5 - Math.random())
+ .slice(0, numUrlsToTest);
+
+ randomUrls.forEach((url) => {
+ it(
+ `Crawl test for ${url}`,
+ async () => {
+ const crawlResults: PageData[] = [];
+
+ for await (const page of docsCrawler.crawl(
+ new URL(url),
+ NUM_PAGES_TO_CRAWL,
+ )) {
+ crawlResults.push(page);
+ }
+
+ expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl);
+ },
+ TIMEOUT_MS,
+ );
+ });
+ }
+
+ describe("GitHub Crawler", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
let crawlResults: PageData[];
beforeAll(async () => {
- const docsCrawler = new DocsCrawler(new URL(repoUrl));
-
crawlResults = [];
- for await (const page of docsCrawler.crawl()) {
+ for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
crawlResults.push(page);
}
- }, TIMEOUT);
+ }, TIMEOUT_MS);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
@@ -50,81 +103,36 @@ describe.skip("crawl", () => {
});
});
- describe.only("Non-Github repository sites", () => {
- it(
- "succeeds in crawling a list of common sites",
- async () => {
- const TEST_SITES = [
- "https://docs.nestjs.com/",
- "https://docs.nestjs.com/",
- "https://go.dev/doc/",
- "https://clickhouse.com/docs",
- "https://www.tensorflow.org/api_docs",
- "https://www.rust-lang.org/learn",
- "https://docs.anthropic.com/en/docs",
- ];
+ describe("Chromium Crawler", () => {
+ let shouldUseChromiumSpy: any;
- const NUM_PAGES_TO_CRAWL = 10;
+ beforeAll(() => {
+ shouldUseChromiumSpy = jest
+ .spyOn(docsCrawler as any, "shouldUseChromium")
+ .mockReturnValue(true);
+ });
- for (const site of TEST_SITES) {
- const crawlResults: PageData[] = [];
- const docsCrawler = new DocsCrawler(
- new URL(site),
- NUM_PAGES_TO_CRAWL,
- );
+ afterAll(() => {
+ shouldUseChromiumSpy.mockRestore();
+ });
- for await (const page of docsCrawler.crawl()) {
- crawlResults.push(page);
- }
+ describe("Pre-indexed Docs", () => {
+ crawlTest(Object.keys(preIndexedDocs));
+ });
- // `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee
- // an exact number of pages to crawl since it runs in parallel
- expect(crawlResults.length).toBeGreaterThanOrEqual(
- NUM_PAGES_TO_CRAWL,
- );
- }
- },
- TIMEOUT,
- );
- });
-
- describe("Pre-indexed Docs", () => {
- const results: { [url: string]: boolean } = {};
- let totalTests = 0;
- let passedTests = 0;
-
- Object.keys(preIndexedDocs).forEach((url) => {
- test(
- `Crawl test for ${url}`,
- async () => {
- totalTests++;
- let pageFound = false;
-
- try {
- const docsCrawler = new DocsCrawler(new URL(url), 1);
-
- for await (const page of docsCrawler.crawl()) {
- if (page.url === url) {
- pageFound = true;
- break;
- }
- }
- } catch (error) {
- console.error(`Error crawling ${url}:`, error);
- }
-
- results[url] = pageFound;
- if (pageFound) {
- passedTests++;
- console.log(`✅ ${url}`);
- } else {
- console.log(`❌ ${url}`);
- }
-
- expect(pageFound).toBe(true);
- },
- TIMEOUT,
- );
+ describe("Running list of common sites", () => {
+ crawlTest([
+ "https://docs.nestjs.com/",
+ "https://go.dev/doc/",
+ "https://clickhouse.com/docs",
+ "https://www.tensorflow.org/api_docs",
+ // "https://www.rust-lang.org/learn", TODO: This is failing
+ "https://docs.anthropic.com/en/docs",
+ ]);
});
});
+
+ describe("Cheerio Crawler", () => {
+ crawlTest(["https://amplified.dev/"], 1);
+ });
});
diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts
index afd3ea440..aea21e3cf 100644
--- a/core/indexing/docs/DocsCrawler.ts
+++ b/core/indexing/docs/DocsCrawler.ts
@@ -1,11 +1,18 @@
import { Octokit } from "@octokit/rest";
+import * as cheerio from "cheerio";
import * as fs from "fs";
+import fetch from "node-fetch";
import { URL } from "node:url";
-import { Page } from "puppeteer";
-import { getChromiumPath, getContinueUtilsPath } from "../../util/paths";
+import { Handler, HTTPResponse, Page } from "puppeteer";
+import {
+ editConfigJson,
+ getChromiumPath,
+ getContinueUtilsPath,
+} from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
+import { ContinueConfig, IDE } from "../..";
export type PageData = {
url: string;
@@ -13,35 +20,89 @@ export type PageData = {
content: string;
};
-export default class DocsCrawler {
- LINK_GROUP_SIZE = 2; // Controls parallelization of crawler
- GITHUB_HOST = "github.com";
- static MAX_REQUESTS_PER_CRAWL = 1000;
- markdownRegex = new RegExp(/\.(md|mdx)$/);
- octokit = new Octokit({
- auth: undefined,
- });
-
- static PCR_CONFIG = {
- downloadPath: getContinueUtilsPath(),
- };
+class DocsCrawler {
+ private readonly MAX_REQUESTS_PER_CRAWL = 1000;
+ private readonly GITHUB_HOST = "github.com";
+ private readonly chromiumInstaller: ChromiumInstaller;
constructor(
- private readonly startUrl: URL,
- private readonly maxRequestsPerCrawl: number = DocsCrawler.MAX_REQUESTS_PER_CRAWL,
- ) {}
-
- static verifyOrInstallChromium() {
- if (!fs.existsSync(getChromiumPath())) {
- PCR(DocsCrawler.PCR_CONFIG);
- }
+ private readonly ide: IDE,
+ private readonly config: ContinueConfig,
+ ) {
+ this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
}
- async *crawl(): AsyncGenerator {
- if (this.startUrl.host === this.GITHUB_HOST) {
- yield* this.crawlGithubRepo();
+ private shouldUseChromium() {
+ return (
+ this.config.experimental?.useChromiumForDocsCrawling &&
+ this.chromiumInstaller.isInstalled()
+ );
+ }
+
+ async *crawl(
+ startUrl: URL,
+ maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
+ ): AsyncGenerator {
+ if (startUrl.host === this.GITHUB_HOST) {
+ yield* new GitHubCrawler(startUrl).crawl();
+ } else if (this.shouldUseChromium()) {
+ yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
- yield* this.crawlSite();
+ let didCrawlSinglePage = false;
+
+ for await (const pageData of new CheerioCrawler(
+ startUrl,
+ maxRequestsPerCrawl,
+ ).crawl()) {
+ yield pageData;
+ didCrawlSinglePage = true;
+ }
+
+ // We assume that if we failed to crawl a single page,
+ // it was due to an error that using Chromium can resolve
+ const shouldProposeUseChromium =
+ !didCrawlSinglePage &&
+ this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
+
+ if (shouldProposeUseChromium) {
+ const didInstall =
+ await this.chromiumInstaller.proposeAndAttemptInstall(
+ startUrl.toString(),
+ );
+
+ if (didInstall) {
+ await this.ide.showToast(
+ "info",
+ `Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
+ );
+
+ yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
+ }
+ }
+ }
+ }
+}
+
+class GitHubCrawler {
+ private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
+ private octokit = new Octokit({ auth: undefined });
+
+ constructor(private readonly startUrl: URL) {}
+
+ async *crawl(): AsyncGenerator {
+ console.debug(
+ `[${
+ (this.constructor as any).name
+ }] Crawling GitHub repo: ${this.startUrl.toString()}`,
+ );
+ const urlStr = this.startUrl.toString();
+ const [_, owner, repo] = this.startUrl.pathname.split("/");
+ const branch = await this.getGithubRepoDefaultBranch(owner, repo);
+ const paths = await this.getGitHubRepoPaths(owner, repo, branch);
+
+ for await (const path of paths) {
+ const content = await this.getGithubRepoFileContent(path, owner, repo);
+ yield { path, url: urlStr, content: content ?? "" };
}
}
@@ -49,11 +110,7 @@ export default class DocsCrawler {
owner: string,
repo: string,
): Promise {
- const repoInfo = await this.octokit.repos.get({
- owner,
- repo,
- });
-
+ const repoInfo = await this.octokit.repos.get({ owner, repo });
return repoInfo.data.default_branch;
}
@@ -68,21 +125,17 @@ export default class DocsCrawler {
owner,
repo,
tree_sha: branch,
- headers: {
- "X-GitHub-Api-Version": "2022-11-28",
- },
+ headers: { "X-GitHub-Api-Version": "2022-11-28" },
recursive: "true",
},
);
- const paths = tree.data.tree
+ return tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
-
- return paths;
}
private async getGithubRepoFileContent(
@@ -95,34 +148,274 @@ export default class DocsCrawler {
owner,
repo,
path,
- headers: {
- Accept: "application/vnd.github.raw+json",
- },
+ headers: { Accept: "application/vnd.github.raw+json" },
});
-
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
+}
- private async *crawlGithubRepo() {
- console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`);
+class CheerioCrawler {
+ private readonly IGNORE_PATHS_ENDING_IN = [
+ "favicon.ico",
+ "robots.txt",
+ ".rst.txt",
+ "genindex",
+ "py-modindex",
+ "search.html",
+ "search",
+ "genindex.html",
+ "changelog",
+ "changelog.html",
+ ];
- const urlStr = this.startUrl.toString();
- const [_, owner, repo] = this.startUrl.pathname.split("/");
- const branch = await this.getGithubRepoDefaultBranch(owner, repo);
- const paths = await this.getGitHubRepoPaths(owner, repo, branch);
+ constructor(
+ private readonly startUrl: URL,
+ private readonly maxRequestsPerCrawl: number,
+ ) {}
- for await (const path of paths) {
- const content = await this.getGithubRepoFileContent(path, owner, repo);
+ async *crawl(): AsyncGenerator {
+ yield* this.crawlPage(this.startUrl);
+ }
- yield {
- path,
- url: urlStr,
- content: content ?? "",
- };
+ private async *crawlPage(
+ url: URL,
+ maxDepth: number = 3,
+ ): AsyncGenerator {
+ console.log(
+ `[${
+ (this.constructor as any).name
+ }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
+ );
+
+ const { baseUrl, basePath } = this.splitUrl(url);
+
+ let paths: { path: string; depth: number }[] = [
+ { path: basePath, depth: 0 },
+ ];
+
+ let index = 0;
+
+ while (index < paths.length) {
+ const batch = paths.slice(index, index + 50);
+
+ try {
+ const promises = batch.map(({ path, depth }) =>
+ this.getLinksFromUrl(baseUrl, path).then((links) => ({
+ links,
+ path,
+ depth,
+ })),
+ );
+
+ const results = await Promise.all(promises);
+ for (const {
+ links: { html, links: linksArray },
+ path,
+ depth,
+ } of results) {
+ if (html !== "" && depth <= maxDepth) {
+ yield { url: url.toString(), path, content: html };
+ }
+
+ if (depth < maxDepth) {
+ for (let link of linksArray) {
+ if (!paths.some((p) => p.path === link)) {
+ paths.push({ path: link, depth: depth + 1 });
+ }
+ }
+ }
+ }
+ } catch (e) {
+ console.debug("Error while crawling page: ", e);
+ }
+
+ index += batch.length;
+ }
+
+ console.log("Crawl completed");
+ }
+
+ private async getLinksFromUrl(url: string, path: string) {
+ const baseUrl = new URL(url);
+ const location = new URL(path, url);
+ let response;
+
+ try {
+ response = await fetch(location.toString());
+ } catch (error: unknown) {
+ if (
+ error instanceof Error &&
+ error.message.includes("maximum redirect")
+ ) {
+ console.error(
+ `[${
+ (this.constructor as any).name
+ }] Maximum redirect reached for: ${location.toString()}`,
+ );
+ return { html: "", links: [] };
+ }
+ console.error(error);
+ return { html: "", links: [] };
+ }
+
+ const html = await response.text();
+ let links: string[] = [];
+
+ if (url.includes("github.com")) {
+ return { html, links };
+ }
+
+ const $ = cheerio.load(html);
+
+ $("a").each((_: any, element: any) => {
+ const href = $(element).attr("href");
+ if (!href) {
+ return;
+ }
+
+ const parsedUrl = new URL(href, url);
+ if (parsedUrl.hostname === baseUrl.hostname) {
+ links.push(parsedUrl.pathname);
+ }
+ });
+
+ links = [...new Set(links)].filter((link) => {
+ return (
+ !link.includes("#") &&
+ !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
+ );
+ });
+
+ return { html, links };
+ }
+
+ private splitUrl(url: URL) {
+ const baseUrl = `${url.protocol}//${url.hostname}${
+ url.port ? ":" + url.port : ""
+ }`;
+ const basePath = url.pathname;
+ return { baseUrl, basePath };
+ }
+}
+
+class ChromiumCrawler {
+ private readonly LINK_GROUP_SIZE = 2;
+ private curCrawlCount = 0;
+
+ constructor(
+ private readonly startUrl: URL,
+ private readonly maxRequestsPerCrawl: number,
+ ) {}
+
+ static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
+ editConfigJson((config) => ({
+ ...config,
+ experimental: {
+ ...config.experimental,
+ useChromiumForDocsCrawling,
+ },
+ }));
+ }
+
+ async *crawl(): AsyncGenerator {
+ console.debug(
+ `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
+ );
+
+ const stats = await PCR(ChromiumInstaller.PCR_CONFIG);
+ const browser = await stats.puppeteer.launch({
+ args: [
+ "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
+ ],
+ executablePath: stats.executablePath,
+ });
+ const page = await browser.newPage();
+
+ try {
+ yield* this.crawlSitePages(page, this.startUrl);
+ } catch (e) {
+ console.debug("Error getting links: ", e);
+ console.debug(
+ "Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
+ );
+
+ ChromiumCrawler.setUseChromiumForDocsCrawling(false);
+ } finally {
+ await browser.close();
+ }
+ }
+
+ /**
+ * We need to handle redirects manually, otherwise there are race conditions.
+ *
+ * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
+ */
+ private async gotoPageAndHandleRedirects(page: Page, url: string) {
+ const MAX_PAGE_WAIT_MS = 5000;
+
+ await page.goto(url, {
+ timeout: 0,
+ waitUntil: "networkidle2",
+ });
+
+ let responseEventOccurred = false;
+ const responseHandler: Handler = (event) =>
+ (responseEventOccurred = true);
+
+ const responseWatcher = new Promise(function (resolve, reject) {
+ setTimeout(() => {
+ if (!responseEventOccurred) {
+ resolve();
+ } else {
+ setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
+ }
+ }, 500);
+ });
+
+ page.on("response", responseHandler);
+
+ await Promise.race([responseWatcher, page.waitForNavigation()]);
+ }
+
+ private async *crawlSitePages(
+ page: Page,
+ curUrl: URL,
+ visitedLinks: Set = new Set(),
+ ): AsyncGenerator {
+ const urlStr = curUrl.toString();
+
+ if (visitedLinks.has(urlStr)) {
+ return;
+ }
+
+ await this.gotoPageAndHandleRedirects(page, urlStr);
+
+ const htmlContent = await page.content();
+ const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
+ this.curCrawlCount++;
+
+ visitedLinks.add(urlStr);
+
+ yield {
+ path: curUrl.pathname,
+ url: urlStr,
+ content: htmlContent,
+ };
+
+ for (const linkGroup of linkGroups) {
+ let enqueuedLinkCount = this.curCrawlCount;
+
+ for (const link of linkGroup) {
+ enqueuedLinkCount++;
+ console.log({ enqueuedLinkCount, url: this.startUrl });
+ if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
+ yield* this.crawlSitePages(page, new URL(link), visitedLinks);
+ }
+ }
}
}
@@ -145,8 +438,6 @@ export default class DocsCrawler {
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
- // This additional step is due to issues getting the URL module to work
- // in an $$eval command
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
@@ -179,70 +470,89 @@ export default class DocsCrawler {
return groups;
}
+}
- private async *crawlSitePages(
- page: Page,
- curUrl: URL,
- visitedLinks: Set = new Set(),
- curRequestCount: number = 0,
- ): AsyncGenerator {
- if (curRequestCount >= this.maxRequestsPerCrawl) {
- console.warn("Max requests per crawl reached. Stopping crawler.");
- return;
- }
+class ChromiumInstaller {
+ static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
- if (visitedLinks.has(curUrl.toString())) {
- return;
- }
-
- console.debug(`Crawling page: ${curUrl.toString()}`);
-
- await page.goto(curUrl.toString());
-
- const htmlContent = await page.content();
- const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
- const requestCount = curRequestCount + 1;
-
- visitedLinks.add(curUrl.toString());
-
- yield {
- path: curUrl.pathname,
- url: curUrl.toString(),
- content: htmlContent,
- };
-
- for (const linkGroup of linkGroups) {
- for (const link of linkGroup) {
- yield* this.crawlSitePages(
- page,
- new URL(link),
- visitedLinks,
- requestCount,
- );
- }
+ constructor(
+ private readonly ide: IDE,
+ private readonly config: ContinueConfig,
+ ) {
+ if (this.shouldInstallOnStartup()) {
+ console.log("Installing Chromium");
+ void this.install();
}
}
- private async *crawlSite(): AsyncGenerator {
- console.debug(`Crawling site repo: ${this.startUrl}`);
+ isInstalled() {
+ return fs.existsSync(getChromiumPath());
+ }
- const stats = await PCR(DocsCrawler.PCR_CONFIG);
+ shouldInstallOnStartup() {
+ return (
+ !this.isInstalled() &&
+ this.config.experimental?.useChromiumForDocsCrawling
+ );
+ }
- const browser = await stats.puppeteer.launch({
- args: [
- "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
- ],
- executablePath: stats.executablePath,
- });
+ shouldProposeUseChromiumOnCrawlFailure() {
+ const { experimental } = this.config;
- const page = await browser.newPage();
+ return (
+ experimental?.useChromiumForDocsCrawling === undefined ||
+ experimental.useChromiumForDocsCrawling
+ );
+ }
- try {
- yield* this.crawlSitePages(page, this.startUrl);
- } catch (e) {
- console.debug("Error getting links: ", e);
- } finally {
- await browser.close();
+ async proposeAndAttemptInstall(site: string) {
+ const userAcceptedInstall = await this.proposeInstall(site);
+
+ if (userAcceptedInstall) {
+ const didInstall = await this.install();
+ return didInstall;
}
}
+
+ async install() {
+ try {
+ await PCR(ChromiumInstaller.PCR_CONFIG);
+
+ ChromiumCrawler.setUseChromiumForDocsCrawling(true);
+
+ return true;
+ } catch (error) {
+ console.debug("Error installing Chromium : ", error);
+ console.debug(
+ "Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
+ );
+
+ ChromiumCrawler.setUseChromiumForDocsCrawling(false);
+
+ await this.ide.showToast("error", "Failed to install Chromium");
+
+ return false;
+ }
+ }
+
+ private async proposeInstall(site: string) {
+ const msg =
+ `Unable to crawl documentation site: ${site}\n` +
+ "We recommend installing Chromium. " +
+ "Download progress can be viewed in the developer console.";
+
+ const actionMsg = "Install Chromium";
+
+ const res = await this.ide.showToast("warning", msg, actionMsg);
+
+ return res === actionMsg;
+ }
}
+
+export default DocsCrawler;
+export {
+ CheerioCrawler,
+ ChromiumCrawler,
+ ChromiumInstaller as ChromiumInstaller,
+ GitHubCrawler,
+};
diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts
index 9b5c593e8..79e6dc86f 100644
--- a/core/indexing/docs/DocsService.ts
+++ b/core/indexing/docs/DocsService.ts
@@ -31,6 +31,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
+import { addContextProvider } from "../../config/util";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@@ -75,16 +76,14 @@ export default class DocsService {
private config!: ContinueConfig;
private sqliteDb?: Database;
- // If we are instantiating a new DocsService from `getContextItems()`,
- // we have access to the direct config object.
- // When instantiating the DocsService from core, we have access
- // to a ConfigHandler instance.
+ private docsCrawler!: DocsCrawler;
+
constructor(
- configOrHandler: ConfigHandler,
+ configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly messenger?: IMessenger,
) {
- this.isInitialized = this.init(configOrHandler);
+ this.isInitialized = this.init(configHandler);
}
static getSingleton() {
@@ -92,11 +91,11 @@ export default class DocsService {
}
static createSingleton(
- configOrHandler: ConfigHandler,
+ configHandler: ConfigHandler,
ide: IDE,
messenger?: IMessenger,
) {
- const docsService = new DocsService(configOrHandler, ide, messenger);
+ const docsService = new DocsService(configHandler, ide, messenger);
DocsService.instance = docsService;
return docsService;
}
@@ -141,12 +140,34 @@ export default class DocsService {
return !!title;
}
+ async showAddDocsContextProviderToast() {
+ const actionMsg = "Add 'docs' context provider";
+ const res = await this.ide.showToast(
+ "info",
+ "Starting docs indexing",
+ actionMsg,
+ );
+
+ if (res === actionMsg) {
+ addContextProvider({
+ name: DocsContextProvider.description.title,
+ params: {},
+ });
+
+ this.ide.showToast("info", "Successfuly added docs context provider");
+ }
+
+ return res === actionMsg;
+ }
+
async indexAllDocs(reIndex: boolean = false) {
if (!this.hasDocsContextProvider()) {
- this.ide.infoPopup(
- "No 'docs' provider configured under 'contextProviders' in config.json",
- );
- return;
+ const didAddDocsContextProvider =
+ await this.showAddDocsContextProviderToast();
+
+ if (!didAddDocsContextProvider) {
+ return;
+ }
}
const docs = await this.list();
@@ -156,7 +177,7 @@ export default class DocsService {
while (!(await generator.next()).done) {}
}
- this.ide.infoPopup("Docs indexing completed");
+ this.ide.showToast("info", "Docs indexing completed");
}
async list() {
@@ -202,10 +223,8 @@ export default class DocsService {
let processedPages = 0;
let maxKnownPages = 1;
- const docsCrawler = new DocsCrawler(new URL(startUrl));
-
// Crawl pages and retrieve info as articles
- for await (const page of docsCrawler.crawl()) {
+ for await (const page of this.docsCrawler.crawl(new URL(startUrl))) {
processedPages++;
const article = pageToArticle(page);
@@ -385,19 +404,9 @@ export default class DocsService {
return favicon;
}
- /**
- * A ConfigHandler is passed to the DocsService in `core` when
- * we don't yet have access to the config object. This handler
- * is used to set up a single instance of the DocsService that
- * subscribes to config updates, e.g. to trigger re-indexing
- * on a new embeddings provider.
- */
private async init(configHandler: ConfigHandler) {
- if (configHandler instanceof ConfigHandler) {
- this.config = await configHandler.loadConfig();
- } else {
- this.config = configHandler;
- }
+ this.config = await configHandler.loadConfig();
+ this.docsCrawler = new DocsCrawler(this.ide, this.config);
const embeddingsProvider = await this.getEmbeddingsProvider();
@@ -475,6 +484,8 @@ export default class DocsService {
driver: sqlite3.Database,
});
+ await db.exec("PRAGMA busy_timeout = 3000;");
+
await runSqliteMigrations(db);
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
@@ -725,7 +736,8 @@ export default class DocsService {
if (isJetBrainsAndPreIndexedDocsProvider) {
// A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider
- // this.ide.errorPopup(
+ // this.ide.showToast(
+ // "error",
// "The 'transformers.js' embeddings provider currently cannot be used to index " +
// "documentation in JetBrains. To enable documentation indexing, you can use " +
// "any of the other providers described in the docs: " +
diff --git a/core/indexing/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts
index d23d61af1..a3aec7cb1 100644
--- a/core/indexing/embeddings/BaseEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/BaseEmbeddingsProvider.ts
@@ -45,7 +45,9 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
}
}
defaultOptions?: EmbedOptions | undefined;
- maxBatchSize?: number | undefined;
+ get maxBatchSize(): number | undefined {
+ return this.options.maxBatchSize ?? (this.constructor as typeof BaseEmbeddingsProvider).maxBatchSize;
+ }
abstract embed(chunks: string[]): Promise;
@@ -53,7 +55,7 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
return this.options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE;
}
- static getBatchedChunks(chunks: string[]): string[][] {
+ getBatchedChunks(chunks: string[]): string[][] {
if (!this.maxBatchSize) {
console.warn(
`${this.getBatchedChunks.name} should only be called if 'maxBatchSize' is defined`,
@@ -62,15 +64,10 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
return [chunks];
}
- if (chunks.length > this.maxBatchSize) {
- return [chunks];
- }
-
const batchedChunks = [];
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
- const batchSizedChunk = chunks.slice(i, i + this.maxBatchSize);
- batchedChunks.push(batchSizedChunk);
+ batchedChunks.push(chunks.slice(i, i + this.maxBatchSize));
}
return batchedChunks;
diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts
new file mode 100644
index 000000000..aa9e8bd41
--- /dev/null
+++ b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts
@@ -0,0 +1,93 @@
+import {
+ BedrockRuntimeClient,
+ InvokeModelCommand,
+} from "@aws-sdk/client-bedrock-runtime";
+import { fromIni } from "@aws-sdk/credential-providers";
+import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js";
+import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
+
+class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
+
+ static providerName: EmbeddingsProviderName = "bedrock";
+
+ static defaultOptions: Partial | undefined = {
+ model: "amazon.titan-embed-text-v2:0",
+ region: "us-east-1"
+ };
+ profile?: string | undefined;
+
+ constructor(options: EmbedOptions, fetch: FetchFunction) {
+ super(options, fetch);
+ if (!options.apiBase) {
+ options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
+ }
+
+ if (options.profile) {
+ this.profile = options.profile;
+ } else {
+ this.profile = "bedrock";
+ }
+ }
+
+ async embed(chunks: string[]) {
+ const credentials = await this._getCredentials();
+ const client = new BedrockRuntimeClient({
+ region: this.options.region,
+ credentials: {
+ accessKeyId: credentials.accessKeyId,
+ secretAccessKey: credentials.secretAccessKey,
+ sessionToken: credentials.sessionToken || "",
+ },
+ });
+
+ return (
+ await Promise.all(
+ chunks.map(async (chunk) => {
+ const input = this._generateInvokeModelCommandInput(chunk, this.options);
+ const command = new InvokeModelCommand(input);
+ const response = await client.send(command);
+
+ if (response.body) {
+ const responseBody = JSON.parse(new TextDecoder().decode(response.body));
+ return [responseBody.embedding];
+ }
+ }),
+ )
+ ).flat();
+ }
+
+ private _generateInvokeModelCommandInput(
+ prompt: string,
+ options: EmbedOptions,
+ ): any {
+ const payload = {
+ "inputText": prompt,
+ "dimensions": 512,
+ "normalize": true
+ };
+
+ return {
+ body: JSON.stringify(payload),
+ modelId: this.options.model,
+ accept: "application/json",
+ contentType: "application/json"
+ };
+ }
+
+ private async _getCredentials() {
+ try {
+ return await
+ fromIni({
+ profile: this.profile
+ })();
+ } catch (e) {
+ console.warn(
+ `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
+ );
+ return await fromIni()();
+ }
+ }
+
+}
+
+export default BedrockEmbeddingsProvider;
diff --git a/core/indexing/embeddings/CohereEmbeddingsProvider.ts b/core/indexing/embeddings/CohereEmbeddingsProvider.ts
index f1e760bb3..1375073e4 100644
--- a/core/indexing/embeddings/CohereEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/CohereEmbeddingsProvider.ts
@@ -18,16 +18,7 @@ class CohereEmbeddingsProvider extends BaseEmbeddingsProvider {
this.options.apiBase += "/";
}
- const batchedChunks = [];
- for (
- let i = 0;
- i < chunks.length;
- i += CohereEmbeddingsProvider.maxBatchSize
- ) {
- batchedChunks.push(
- chunks.slice(i, i + CohereEmbeddingsProvider.maxBatchSize),
- );
- }
+ const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {
diff --git a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts
index 70cd3d8c7..a539a38cc 100644
--- a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts
@@ -24,16 +24,7 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
- const batchedChunks = [];
- for (
- let i = 0;
- i < chunks.length;
- i += FreeTrialEmbeddingsProvider.maxBatchSize
- ) {
- batchedChunks.push(
- chunks.slice(i, i + FreeTrialEmbeddingsProvider.maxBatchSize),
- );
- }
+ const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {
diff --git a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts
index d3c22f3f0..a0d657321 100644
--- a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts
@@ -8,7 +8,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
*/
class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "gemini";
- static maxBatchSize = 2048;
+ static maxBatchSize = 100;
static defaultOptions = {
apiBase: "https://generativelanguage.googleapis.com/v1/",
@@ -55,10 +55,10 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
- const batches = GeminiEmbeddingsProvider.getBatchedChunks(chunks);
+ const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
- batches.map((batch) => this.getSingleBatchEmbedding(batch)),
+ batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)),
);
return results.flat();
}
diff --git a/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts b/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts
index 9ee6a5054..adcf4b7ee 100644
--- a/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts
@@ -9,7 +9,10 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "huggingface-tei";
- maxBatchSize = 32;
+ private _maxBatchSize?: number;
+ get maxBatchSize(): number | undefined {
+ return this._maxBatchSize ?? super.maxBatchSize;
+ }
static defaultOptions: Partial | undefined = {
apiBase: "http://localhost:8080",
@@ -24,18 +27,16 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
}
this.doInfoRequest().then((response) => {
this.options.model = response.model_id;
- this.maxBatchSize = response.max_client_batch_size;
+ this._maxBatchSize = response.max_client_batch_size;
});
}
async embed(chunks: string[]) {
- const promises = [];
- for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
- promises.push(
- this.doEmbedRequest(chunks.slice(i, i + this.maxBatchSize)),
- );
- }
- const results = await Promise.all(promises);
+ const batchedChunks = this.getBatchedChunks(chunks);
+
+ const results = await Promise.all(
+ batchedChunks.map((batch) => this.doEmbedRequest(batch)),
+ );
return results.flat();
}
diff --git a/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts b/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts
new file mode 100644
index 000000000..8e47a6db8
--- /dev/null
+++ b/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts
@@ -0,0 +1,80 @@
+import { Response } from "node-fetch";
+import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
+import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
+import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
+
+class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider {
+ static maxBatchSize = 96;
+
+ static providerName: EmbeddingsProviderName = "nvidia";
+
+ static defaultOptions: Partial | undefined = {
+ apiBase: "https://integrate.api.nvidia.com/v1/",
+ model: "nvidia/nv-embedqa-mistral-7b-v2",
+ };
+
+ async embed(chunks: string[]) {
+
+ if (!this.options.apiBase?.endsWith("/")) {
+ this.options.apiBase += "/";
+ }
+
+ const batchedChunks = [];
+ for (
+ let i = 0;
+ i < chunks.length;
+ i += NvidiaEmbeddingsProvider.maxBatchSize
+ ) {
+ batchedChunks.push(
+ chunks.slice(i, i + NvidiaEmbeddingsProvider.maxBatchSize),
+ );
+ }
+ return (
+ await Promise.all(
+ batchedChunks.map(async (batch) => {
+ if (batch.length === 0) {
+ return [];
+ }
+
+ // Input list must be non empty and all elements must be non empty, therefore, for all empty elements replace it with a token
+ const emptyToken = '[EMPTY]';
+ for (let i = 0; i < batch.length; i++) {
+ if (batch[i].trim() === '') {
+ batch[i] = emptyToken;
+ }
+ }
+
+ const fetchWithBackoff = () =>
+ withExponentialBackoff(() =>
+ this.fetch(new URL("embeddings", this.options.apiBase), {
+ method: "POST",
+ body: JSON.stringify({
+ input: batch,
+ model: this.options.model,
+ input_type: 'passage',
+ truncate: "END",
+ }),
+ headers: {
+ Authorization: `Bearer ${this.options.apiKey}`,
+ "Content-Type": "application/json",
+ },
+ }),
+ );
+
+ const resp = await fetchWithBackoff();
+
+ if (!resp.ok) {
+ throw new Error(await resp.text());
+ }
+
+ const data = (await resp.json()) as any;
+ return data.data.map(
+ (result: { embedding: number[] }) => result.embedding,
+ );
+ }),
+ )
+ ).flat();
+ }
+}
+
+export default NvidiaEmbeddingsProvider;
diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts
index e007554e7..290dad1fe 100644
--- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts
@@ -28,6 +28,7 @@ async function embedOne(
}),
headers: {
"Content-Type": "application/json",
+ Authorization: `Bearer ${options.apiKey}`,
},
});
diff --git a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts
index fc6af4547..0f755ae3a 100644
--- a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts
@@ -35,16 +35,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
- const batchedChunks = [];
- for (
- let i = 0;
- i < chunks.length;
- i += OpenAIEmbeddingsProvider.maxBatchSize
- ) {
- batchedChunks.push(
- chunks.slice(i, i + OpenAIEmbeddingsProvider.maxBatchSize),
- );
- }
+ const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {
diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts
index ddf44fe22..f22c8af42 100644
--- a/core/indexing/embeddings/index.ts
+++ b/core/indexing/embeddings/index.ts
@@ -1,5 +1,6 @@
import { EmbeddingsProviderName } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
+import BedrockEmbeddingsProvider from "./BedrockEmbeddingsProvider.js";
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js";
@@ -10,6 +11,7 @@ import MistralEmbeddingsProvider from "./MistralEmbeddingsProvider.js";
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
+import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js";
import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js";
type EmbeddingsProviderConstructor = new (
@@ -20,6 +22,7 @@ export const allEmbeddingsProviders: Record<
EmbeddingsProviderName,
EmbeddingsProviderConstructor
> = {
+ bedrock: BedrockEmbeddingsProvider,
ollama: OllamaEmbeddingsProvider,
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAIEmbeddingsProvider,
@@ -29,6 +32,7 @@ export const allEmbeddingsProviders: Record<
gemini: GeminiEmbeddingsProvider,
"continue-proxy": ContinueProxyEmbeddingsProvider,
deepinfra: DeepInfraEmbeddingsProvider,
+ nvidia: NvidiaEmbeddingsProvider,
voyage: VoyageEmbeddingsProvider,
mistral: MistralEmbeddingsProvider,
};
diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts
index 16526e7fb..fd111e56b 100644
--- a/core/indexing/ignore.ts
+++ b/core/indexing/ignore.ts
@@ -67,6 +67,7 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.csv",
"*.uasset",
"*.pdb",
+ "*.bin",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];
@@ -84,6 +85,7 @@ export const DEFAULT_IGNORE_DIRS = [
"node_modules/",
"dist/",
"build/",
+ "Build/",
"target/",
"out/",
"bin/",
diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts
index 6800a9e8a..51cbdb646 100644
--- a/core/indexing/refreshIndex.ts
+++ b/core/indexing/refreshIndex.ts
@@ -92,6 +92,8 @@ export class SqliteDb {
driver: sqlite3.Database,
});
+ await SqliteDb.db.exec("PRAGMA busy_timeout = 3000;");
+
await SqliteDb.createTables(SqliteDb.db);
return SqliteDb.db;
diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts
index 1696bd674..523bcb028 100644
--- a/core/llm/autodetect.ts
+++ b/core/llm/autodetect.ts
@@ -45,6 +45,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"sagemaker",
"continue-proxy",
"mistral",
+ "sambanova",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@@ -108,6 +109,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
"free-trial",
"replicate",
"together",
+ "sambanova",
];
function llmCanGenerateInParallel(
diff --git a/core/llm/index.ts b/core/llm/index.ts
index b6cbb65b8..9a1ddaf46 100644
--- a/core/llm/index.ts
+++ b/core/llm/index.ts
@@ -63,7 +63,7 @@ export abstract class BaseLLM implements ILLM {
}
supportsCompletions(): boolean {
- if (this.providerName === "openai") {
+ if (["openai", "azure"].includes(this.providerName)) {
if (
this.apiBase?.includes("api.groq.com") ||
this.apiBase?.includes("api.mistral.ai") ||
@@ -76,7 +76,7 @@ export abstract class BaseLLM implements ILLM {
return false;
}
}
- if (["groq", "mistral"].includes(this.providerName)) {
+ if (["groq", "mistral", "deepseek"].includes(this.providerName)) {
return false;
}
return true;
@@ -118,6 +118,7 @@ export abstract class BaseLLM implements ILLM {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
+ watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
@@ -180,6 +181,7 @@ export abstract class BaseLLM implements ILLM {
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxStopToken = options.watsonxStopToken;
this.watsonxApiVersion = options.watsonxApiVersion;
+ this.watsonxFullUrl = options.watsonxFullUrl;
this.cacheSystemMessage = options.cacheSystemMessage;
@@ -323,6 +325,20 @@ ${prompt}`;
) {
text =
"You may need to add pre-paid credits before using the OpenAI API.";
+ } else if (
+ resp.status === 401 &&
+ (resp.url.includes("api.mistral.ai") ||
+ resp.url.includes("codestral.mistral.ai"))
+ ) {
+ if (resp.url.includes("codestral.mistral.ai")) {
+ throw new Error(
+ `You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting "apiBase" to "https://api.mistral.ai/v1" in config.json.`,
+ );
+ } else {
+ throw new Error(
+ `You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting "apiBase" to "https://codestral.mistral.ai/v1" in config.json.`,
+ );
+ }
}
throw new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
@@ -332,8 +348,14 @@ ${prompt}`;
return resp;
} catch (e: any) {
// Errors to ignore
- if (!e.message.includes("/api/show")) {
- console.warn(
+ if (e.message.includes("/api/tags")) {
+ throw new Error(`Error fetching tags: ${e.message}`);
+ } else if (e.message.includes("/api/show")) {
+ throw new Error(
+ `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
+ );
+ } else {
+ console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);
diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts
index 415ec0f10..db2603c03 100644
--- a/core/llm/llms/Bedrock.ts
+++ b/core/llm/llms/Bedrock.ts
@@ -18,7 +18,7 @@ class Bedrock extends BaseLLM {
static defaultOptions: Partial = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
- contextLength: 200_000
+ contextLength: 200_000,
};
profile?: string | undefined;
@@ -49,8 +49,10 @@ class Bedrock extends BaseLLM {
options: CompletionOptions,
): AsyncGenerator {
const credentials = await this._getCredentials();
+
const client = new BedrockRuntimeClient({
region: this.region,
+ endpoint: this.apiBase,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
@@ -58,6 +60,27 @@ class Bedrock extends BaseLLM {
},
});
+ let config_headers =
+ this.requestOptions && this.requestOptions.headers
+ ? this.requestOptions.headers
+ : {};
+ // AWS SigV4 requires strict canonicalization of headers.
+ // DO NOT USE "_" in your header name. It will return an error like below.
+ // "The request signature we calculated does not match the signature you provided."
+
+ client.middlewareStack.add(
+ (next) => async (args: any) => {
+ args.request.headers = {
+ ...args.request.headers,
+ ...config_headers,
+ };
+ return next(args);
+ },
+ {
+ step: "build",
+ },
+ );
+
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);
diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts
index 4a7477102..e37b43799 100644
--- a/core/llm/llms/OpenAI.ts
+++ b/core/llm/llms/OpenAI.ts
@@ -89,9 +89,15 @@ class OpenAI extends BaseLLM {
return model;
}
+ private isO1Model(model?: string): boolean {
+ return (
+ !!model && (model.startsWith("o1-preview") || model.startsWith("o1-mini"))
+ );
+ }
+
protected _convertArgs(options: any, messages: ChatMessage[]) {
const url = new URL(this.apiBase!);
- const finalOptions = {
+ const finalOptions: any = {
messages: messages.map(this._convertMessage),
model: this._convertModelName(options.model),
max_tokens: options.maxTokens,
@@ -99,6 +105,7 @@ class OpenAI extends BaseLLM {
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
+ stream: options.stream ?? true,
stop:
// Jan + Azure OpenAI don't truncate and will throw an error
this.maxStopWords !== undefined
@@ -113,6 +120,21 @@ class OpenAI extends BaseLLM {
: options.stop,
};
+ // OpenAI o1-preview and o1-mini:
+ if (this.isO1Model(options.model)) {
+ // a) use max_completion_tokens instead of max_tokens
+ finalOptions.max_completion_tokens = options.maxTokens;
+ finalOptions.max_tokens = undefined;
+
+ // b) don't support streaming currently
+ finalOptions.stream = false;
+
+ // c) don't support system message
+ finalOptions.messages = finalOptions.messages?.filter(
+ (message: any) => message?.role !== "system",
+ );
+ }
+
return finalOptions;
}
@@ -216,12 +238,9 @@ class OpenAI extends BaseLLM {
return;
}
- const body = {
- ...this._convertArgs(options, messages),
- stream: true,
- };
+ const body = this._convertArgs(options, messages);
// Empty messages cause an error in LM Studio
- body.messages = body.messages.map((m) => ({
+ body.messages = body.messages.map((m: any) => ({
...m,
content: m.content === "" ? " " : m.content,
})) as any;
@@ -231,6 +250,13 @@ class OpenAI extends BaseLLM {
body: JSON.stringify(body),
});
+ // Handle non-streaming response
+ if (body.stream === false) {
+ const data = await response.json();
+ yield data.choices[0].message;
+ return;
+ }
+
for await (const value of streamSse(response)) {
if (value.choices?.[0]?.delta?.content) {
yield value.choices[0].delta;
diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts
index a59de352c..03b9a5b22 100644
--- a/core/llm/llms/SageMaker.ts
+++ b/core/llm/llms/SageMaker.ts
@@ -55,12 +55,24 @@ class SageMaker extends BaseLLM {
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
- const data = JSON.parse(line.replace(/^data:/, ""));
- if ("choices" in data) {
- yield data.choices[0].delta.content;
- }
- else if ("token" in data) {
- yield data.token.text;
+ try {
+ const data = JSON.parse(line.replace(/^data:/, ''));
+ let text = undefined;
+ if ("choices" in data) {
+ if ("delta" in data.choices[0]){
+ text = data.choices[0].delta.content;
+ }
+ else{
+ text = data.choices[0].text;
+ }
+ }
+ else if ("token" in data) {
+ text = data.token.text;
+ }
+ if (text !== undefined) {
+ yield text;
+ }
+ } catch (e) {
}
buffer = buffer.slice(position + 1);
}
@@ -94,12 +106,24 @@ class SageMaker extends BaseLLM {
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
- const data = JSON.parse(line.replace(/^data:/, ""));
- if ("choices" in data) {
- yield { role: "assistant", content: data.choices[0].delta.content };
- }
- else if ("token" in data) {
- yield { role: "assistant", content: data.token.text };
+ try {
+ const data = JSON.parse(line.replace(/^data:/, ''));
+ let text = undefined;
+ if ("choices" in data) {
+ if ("delta" in data.choices[0]){
+ text = data.choices[0].delta.content;
+ }
+ else{
+ text = data.choices[0].text;
+ }
+ }
+ else if ("token" in data) {
+ text = data.token.text;
+ }
+ if (text !== undefined) {
+ yield { role: "assistant", content: text };
+ }
+ } catch (e) {
}
buffer = buffer.slice(position + 1);
}
@@ -189,6 +213,7 @@ class CompletionAPIToolkit implements SageMakerModelToolkit {
): InvokeEndpointWithResponseStreamCommand {
const payload = {
inputs: prompt,
+ prompt: prompt,
parameters: this.sagemaker.completionOptions,
stream: true,
};
diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts
new file mode 100644
index 000000000..2b409dcde
--- /dev/null
+++ b/core/llm/llms/SambaNova.ts
@@ -0,0 +1,22 @@
+import type { LLMOptions, ModelProvider } from "../../index.js";
+
+import OpenAI from "./OpenAI.js";
+
+class SambaNova extends OpenAI {
+ static providerName: ModelProvider = "sambanova";
+ static defaultOptions: Partial = {
+ apiBase: "https://api.sambanova.ai/v1/",
+ };
+
+ private static MODEL_IDS: { [name: string]: string } = {
+ "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct",
+ "llama3.1-70b": "Meta-Llama-3.1-70B-Instruct",
+ "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct",
+ };
+
+ protected _convertModelName(model: string) {
+ return SambaNova.MODEL_IDS[model] || this.model;
+ }
+}
+
+export default SambaNova;
diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts
index 68dfef47c..f7ea473e0 100644
--- a/core/llm/llms/WatsonX.ts
+++ b/core/llm/llms/WatsonX.ts
@@ -84,6 +84,10 @@ class WatsonX extends BaseLLM {
}
}
+ getWatsonxEndpoint(): string {
+ return this.watsonxFullUrl ?? `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`;
+ }
+
static providerName: ModelProvider = "watsonx";
protected _convertMessage(message: ChatMessage) {
@@ -186,8 +190,9 @@ class WatsonX extends BaseLLM {
const stopToken =
this.watsonxStopToken ??
(options.model?.includes("granite") ? "<|im_end|>" : undefined);
+ const url = this.getWatsonxEndpoint();
var response = await this.fetch(
- `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`,
+ url,
{
method: "POST",
headers: {
diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts
index 55b6e1f7e..2b894f418 100644
--- a/core/llm/llms/index.ts
+++ b/core/llm/llms/index.ts
@@ -36,6 +36,7 @@ import OpenAI from "./OpenAI";
import OpenRouter from "./OpenRouter";
import Replicate from "./Replicate";
import SageMaker from "./SageMaker";
+import SambaNova from "./SambaNova";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import Vllm from "./Vllm";
@@ -75,6 +76,7 @@ const LLMs = [
OpenRouter,
Nvidia,
Vllm,
+ SambaNova,
Mock,
];
diff --git a/core/package-lock.json b/core/package-lock.json
index 6c03c4862..a3332dc01 100644
--- a/core/package-lock.json
+++ b/core/package-lock.json
@@ -22,6 +22,7 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
+ "cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
@@ -6256,6 +6257,46 @@
"node": ">=10"
}
},
+ "node_modules/cheerio": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0.tgz",
+ "integrity": "sha512-quS9HgjQpdaXOvsZz82Oz7uxtXiy6UIsIQcpBj7HRw2M63Skasm9qlDocAM7jNuaxdhpPU7c4kJN+gA5MCu4ww==",
+ "dependencies": {
+ "cheerio-select": "^2.1.0",
+ "dom-serializer": "^2.0.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.1.0",
+ "encoding-sniffer": "^0.2.0",
+ "htmlparser2": "^9.1.0",
+ "parse5": "^7.1.2",
+ "parse5-htmlparser2-tree-adapter": "^7.0.0",
+ "parse5-parser-stream": "^7.1.2",
+ "undici": "^6.19.5",
+ "whatwg-mimetype": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=18.17"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/cheerio?sponsor=1"
+ }
+ },
+ "node_modules/cheerio-select": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz",
+ "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==",
+ "dependencies": {
+ "boolbase": "^1.0.0",
+ "css-select": "^5.1.0",
+ "css-what": "^6.1.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
"node_modules/chownr": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
@@ -7038,6 +7079,18 @@
"iconv-lite": "^0.6.2"
}
},
+ "node_modules/encoding-sniffer": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.0.tgz",
+ "integrity": "sha512-ju7Wq1kg04I3HtiYIOrUrdfdDvkyO9s5XM8QAj/bN61Yo/Vb4vgJxy5vi4Yxk01gWHbrofpPtpxM8bKger9jhg==",
+ "dependencies": {
+ "iconv-lite": "^0.6.3",
+ "whatwg-encoding": "^3.1.1"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/encoding-sniffer?sponsor=1"
+ }
+ },
"node_modules/end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
@@ -8612,6 +8665,24 @@
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true
},
+ "node_modules/htmlparser2": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
+ "integrity": "sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ==",
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.1.0",
+ "entities": "^4.5.0"
+ }
+ },
"node_modules/http-cache-semantics": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz",
@@ -11507,6 +11578,29 @@
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
+ "node_modules/parse5-htmlparser2-tree-adapter": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz",
+ "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==",
+ "dependencies": {
+ "domhandler": "^5.0.2",
+ "parse5": "^7.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5-parser-stream": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz",
+ "integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==",
+ "dependencies": {
+ "parse5": "^7.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -13749,9 +13843,9 @@
}
},
"node_modules/undici": {
- "version": "6.18.2",
- "resolved": "https://registry.npmjs.org/undici/-/undici-6.18.2.tgz",
- "integrity": "sha512-o/MQLTwRm9IVhOqhZ0NQ9oXax1ygPjw6Vs+Vq/4QRjbOAC3B1GCHy7TYxxbExKlb7bzDRzt9vBWU6BDz0RFfYg==",
+ "version": "6.19.8",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.19.8.tgz",
+ "integrity": "sha512-U8uCCl2x9TK3WANvmBavymRzxbfFYG+tAu+fgx3zxQy3qdagQqBLwJVrdyO1TBfUXvfKveMKJZhpvUYoOjM+4g==",
"engines": {
"node": ">=18.17"
}
diff --git a/core/package.json b/core/package.json
index 4b20b5b2c..f261f7078 100644
--- a/core/package.json
+++ b/core/package.json
@@ -51,6 +51,7 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
+ "cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
diff --git a/core/protocol/core.ts b/core/protocol/core.ts
index 9cd4d4ec8..73f55946c 100644
--- a/core/protocol/core.ts
+++ b/core/protocol/core.ts
@@ -22,6 +22,13 @@ export type ProtocolGeneratorType = AsyncGenerator<{
content: T;
}>;
+export type OnboardingModes =
+ | "Local"
+ | "Best"
+ | "Custom"
+ | "Quickstart"
+ | "LocalAfterFreeTrial";
+
export interface ListHistoryOptions {
offset?: number;
limit?: number;
@@ -137,13 +144,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"index/indexingProgressBarInitialized": [undefined, void];
completeOnboarding: [
{
- mode:
- | "local"
- | "apiKeys"
- | "custom"
- | "freeTrial"
- | "localAfterFreeTrial"
- | "bestExperience";
+ mode: OnboardingModes;
},
void,
];
diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts
index bb5f59810..393797f5d 100644
--- a/core/protocol/ide.ts
+++ b/core/protocol/ide.ts
@@ -1,8 +1,8 @@
-import { ControlPlaneSessionInfo } from "../control-plane/client.js";
import type {
ContinueRcJson,
DiffLine,
FileType,
+ IDE,
IdeInfo,
IdeSettings,
IndexTag,
@@ -11,7 +11,12 @@ import type {
Range,
RangeInFile,
Thread,
-} from "../index.js";
+} from "../";
+import { ControlPlaneSessionInfo } from "../control-plane/client";
+
+export interface GetGhTokenArgs {
+ force?: boolean;
+}
export type ToIdeFromWebviewOrCoreProtocol = {
// Methods from IDE type
@@ -67,15 +72,17 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getBranch: [{ dir: string }, string];
getRepoName: [{ dir: string }, string | undefined];
- errorPopup: [{ message: string }, void];
- infoPopup: [{ message: string }, void];
+ showToast: [
+ Parameters,
+ Awaited>,
+ ];
getGitRootPath: [{ dir: string }, string | undefined];
listDir: [{ dir: string }, [string, FileType][]];
getLastModified: [{ files: string[] }, { [path: string]: number }];
gotoDefinition: [{ location: Location }, RangeInFile[]];
- getGitHubAuthToken: [undefined, string | undefined];
+ getGitHubAuthToken: [GetGhTokenArgs, string | undefined];
getControlPlaneSessionInfo: [
{ silent: boolean },
ControlPlaneSessionInfo | undefined,
diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts
index 5e1e74589..33a1ae2a9 100644
--- a/core/protocol/ideWebview.ts
+++ b/core/protocol/ideWebview.ts
@@ -58,7 +58,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];
addApiKey: [undefined, void];
- setupLocalModel: [undefined, void];
+ setupLocalConfig: [undefined, void];
incrementFtc: [undefined, void];
- openOnboarding: [undefined, void];
+ openOnboardingCard: [undefined, void];
};
diff --git a/core/util/dedent.test.ts b/core/util/dedent.test.ts
new file mode 100644
index 000000000..3b0d526e1
--- /dev/null
+++ b/core/util/dedent.test.ts
@@ -0,0 +1,138 @@
+import { dedent } from "./index";
+
+describe("dedent function", () => {
+ it("should remove common leading whitespace from all lines", () => {
+ const result = dedent`
+ Hello
+ World
+ !
+ `;
+ expect(result).toBe("Hello\n World\n !");
+ });
+
+ it("should handle strings with no indentation", () => {
+ const result = dedent`Hello
+World
+!`;
+ expect(result).toBe("Hello\nWorld\n!");
+ });
+
+ it("should handle strings with mixed indentation", () => {
+ const result = dedent`
+ Hello
+ World
+ !
+ `;
+ expect(result).toBe(" Hello\nWorld\n !");
+ });
+
+ it("should remove leading and trailing empty lines", () => {
+ const result = dedent`
+
+ Hello
+ World
+
+ `;
+ expect(result).toBe("Hello\nWorld");
+ });
+
+ it("should handle empty strings", () => {
+ const result = dedent``;
+ expect(result).toBe("");
+ });
+
+ it("should handle strings with only whitespace", () => {
+ const result = dedent`
+
+ `;
+ expect(result).toBe("");
+ });
+
+ it.skip("should handle strings with tabs", () => {
+ const result = dedent`
+ \tHello
+ \t\tWorld
+ \t\t\t!
+`;
+ expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
+ });
+
+ it("should handle interpolated values", () => {
+ const world = "World";
+ const result = dedent`
+ Hello ${world}
+ How are you?
+ `;
+ expect(result).toBe("Hello World\n How are you?");
+ });
+
+ it("should handle multiple interpolated values", () => {
+ const greeting = "Hello";
+ const name = "Alice";
+ const question = "How are you?";
+ const result = dedent`
+ ${greeting} ${name}
+ ${question}
+ `;
+ expect(result).toBe("Hello Alice\n How are you?");
+ });
+
+ it("should handle interpolated values with different indentation", () => {
+ const value1 = "foo";
+ const value2 = "bar";
+ const result = dedent`
+ ${value1}
+ ${value2}
+ `;
+ expect(result).toBe("foo\n bar");
+ });
+
+ it("should handle a single line with indentation", () => {
+ const result = dedent` Hello World!`;
+ expect(result).toBe("Hello World!");
+ });
+
+ it("should handle a string with only one non-empty line", () => {
+ const result = dedent`
+
+ Hello World!
+
+ `;
+ expect(result).toBe("Hello World!");
+ });
+
+ it("should handle a string with Unicode characters", () => {
+ const result = dedent`
+ こんにちは
+ 世界
+ `;
+ expect(result).toBe("こんにちは\n 世界");
+ });
+
+ it("should handle a string with emoji", () => {
+ const result = dedent`
+ 🌍
+ 🌎
+ 🌏
+ `;
+ expect(result).toBe("🌍\n 🌎\n 🌏");
+ });
+
+ it.skip("should handle a string with CRLF line endings", () => {
+ const result = dedent`
+ Hello\r
+ World\r
+ `;
+ expect(result).toBe("Hello\r\n World");
+ });
+
+ it("should not count empty lines in the minimum indentation", () => {
+ const result = dedent`
+ Hello
+
+ World
+ `;
+
+ expect(result).toBe("Hello\n\nWorld");
+ });
+});
diff --git a/core/util/devdataSqlite.ts b/core/util/devdataSqlite.ts
index 4f86cb1a1..103140c0d 100644
--- a/core/util/devdataSqlite.ts
+++ b/core/util/devdataSqlite.ts
@@ -79,6 +79,8 @@ export class DevDataSqliteDb {
driver: sqlite3.Database,
});
+ await DevDataSqliteDb.db.exec("PRAGMA busy_timeout = 3000;");
+
await DevDataSqliteDb.createTables(DevDataSqliteDb.db!);
return DevDataSqliteDb.db;
diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts
index 06209a474..fe64a6fbc 100644
--- a/core/util/filesystem.ts
+++ b/core/util/filesystem.ts
@@ -12,12 +12,21 @@ import {
Range,
RangeInFile,
Thread,
+ ToastType,
} from "../index.d.js";
+import { GetGhTokenArgs } from "../protocol/ide.js";
import { getContinueGlobalPath } from "./paths.js";
class FileSystemIde implements IDE {
constructor(private readonly workspaceDir: string) {}
+ showToast(
+ type: ToastType,
+ message: string,
+ ...otherParams: any[]
+ ): Promise {
+ return Promise.resolve();
+ }
pathSep(): Promise {
return Promise.resolve(path.sep);
}
@@ -42,7 +51,7 @@ class FileSystemIde implements IDE {
enableDebugLogs: false,
};
}
- async getGitHubAuthToken(): Promise {
+ async getGitHubAuthToken(args: GetGhTokenArgs): Promise {
return undefined;
}
async getLastModified(files: string[]): Promise<{ [path: string]: number }> {
@@ -68,28 +77,25 @@ class FileSystemIde implements IDE {
dirent.isDirectory()
? (2 as FileType.Directory)
: dirent.isSymbolicLink()
- ? (64 as FileType.SymbolicLink)
- : (1 as FileType.File),
+ ? (64 as FileType.SymbolicLink)
+ : (1 as FileType.File),
]);
return Promise.resolve(all);
}
- infoPopup(message: string): Promise {
- return Promise.resolve();
- }
- errorPopup(message: string): Promise {
- return Promise.resolve();
- }
+
getRepoName(dir: string): Promise {
return Promise.resolve(undefined);
}
async getTags(artifactId: string): Promise {
- const directory =(await this.getWorkspaceDirs())[0];
- return [{
- artifactId,
- branch: await this.getBranch(directory),
- directory
- }];
+ const directory = (await this.getWorkspaceDirs())[0];
+ return [
+ {
+ artifactId,
+ branch: await this.getBranch(directory),
+ directory,
+ },
+ ];
}
getIdeInfo(): Promise {
diff --git a/core/util/history.ts b/core/util/history.ts
index ac1744ada..5f4a85e5d 100644
--- a/core/util/history.ts
+++ b/core/util/history.ts
@@ -48,7 +48,10 @@ class HistoryManager {
(session) => session.sessionId !== sessionId,
);
- fs.writeFileSync(sessionsListFile, JSON.stringify(sessionsList));
+ fs.writeFileSync(
+ sessionsListFile,
+ JSON.stringify(sessionsList, undefined, 2),
+ );
}
load(sessionId: string): PersistedSessionInfo {
@@ -77,7 +80,7 @@ class HistoryManager {
// Save the main session json file
fs.writeFileSync(
getSessionFilePath(session.sessionId),
- JSON.stringify(session),
+ JSON.stringify(session, undefined, 2),
);
// Read and update the sessions list
@@ -117,7 +120,10 @@ class HistoryManager {
sessionsList.push(sessionInfo);
}
- fs.writeFileSync(sessionsListFilePath, JSON.stringify(sessionsList));
+ fs.writeFileSync(
+ sessionsListFilePath,
+ JSON.stringify(sessionsList, undefined, 2),
+ );
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(
diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts
new file mode 100644
index 000000000..0b7de8b02
--- /dev/null
+++ b/core/util/ideUtils.ts
@@ -0,0 +1,21 @@
+import { IDE } from "..";
+
+export async function resolveRelativePathInWorkspace(
+ path: string,
+ ide: IDE,
+): Promise {
+ const pathSep = await ide.pathSep();
+ if (path.startsWith(pathSep)) {
+ return path;
+ }
+
+ const workspaces = await ide.getWorkspaceDirs();
+ for (const workspace of workspaces) {
+ const fullPath = `${workspace}${pathSep}${path}`;
+ if (await ide.fileExists(fullPath)) {
+ return fullPath;
+ }
+ }
+
+ return undefined;
+}
diff --git a/core/util/index.ts b/core/util/index.ts
index a628948c7..3de43957e 100644
--- a/core/util/index.ts
+++ b/core/util/index.ts
@@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string {
output = output.trim();
// Replace smart quotes
- output = output.replace("“", "\"");
- output = output.replace("”", "\"");
+ output = output.replace("“", '"');
+ output = output.replace("”", '"');
output = output.replace("‘", "'");
output = output.replace("’", "'");
// Remove escapes
- output = output.replace("\\\"", "\"");
+ output = output.replace('\\"', '"');
output = output.replace("\\'", "'");
output = output.replace("\\n", "\n");
output = output.replace("\\t", "\t");
output = output.replace("\\\\", "\\");
while (
- (output.startsWith("\"") && output.endsWith("\"")) ||
+ (output.startsWith('"') && output.endsWith('"')) ||
(output.startsWith("'") && output.endsWith("'"))
) {
output = output.slice(1, -1);
@@ -120,7 +120,9 @@ export function getUniqueFilePath(
}
export function shortestRelativePaths(paths: string[]): string[] {
- if (paths.length === 0) {return [];}
+ if (paths.length === 0) {
+ return [];
+ }
const partsLengths = paths.map((x) => x.split(SEP_REGEX).length);
const currentRelativePaths = paths.map(getBasename);
@@ -135,7 +137,9 @@ export function shortestRelativePaths(paths: string[]): string[] {
const firstDuplicatedPath = currentRelativePaths.find(
(x, i) => isDuplicated[i],
);
- if (!firstDuplicatedPath) {break;}
+ if (!firstDuplicatedPath) {
+ break;
+ }
currentRelativePaths.forEach((x, i) => {
if (x === firstDuplicatedPath) {
@@ -270,3 +274,33 @@ export function deduplicateArray(
}
export type TODO = any;
+
+export function dedent(strings: TemplateStringsArray, ...values: any[]) {
+ let result = strings.reduce(
+ (acc, str, i) => acc + str + (values[i] || ""),
+ "",
+ );
+ result = result.replace(/^\n/, "").replace(/\n\s*$/, "");
+ let lines = result.split("\n");
+
+ // Remove leading white-space-only lines
+ while (lines.length > 0 && lines[0].trim() === "") {
+ lines.shift();
+ }
+
+ // Remove trailing white-space-only lines
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
+ lines.pop();
+ }
+
+ const minIndent = lines.reduce((min, line) => {
+ if (line.trim() === "") {
+ // Don't consider empty lines when calculating indentation
+ return min;
+ }
+ const match = line.match(/^\s*/);
+ return Math.min(min, match ? match[0].length : Infinity);
+ }, Infinity);
+
+ return lines.map((line) => line.slice(minIndent)).join("\n");
+}
diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts
index 396df29c7..7f00a9cc1 100644
--- a/core/util/messageIde.ts
+++ b/core/util/messageIde.ts
@@ -11,7 +11,10 @@ import type {
RangeInFile,
Thread,
} from "../index.js";
-import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js";
+import {
+ GetGhTokenArgs,
+ ToIdeFromWebviewOrCoreProtocol,
+} from "../protocol/ide.js";
import { FromIdeProtocol } from "../protocol/index.js";
export class MessageIde implements IDE {
@@ -25,6 +28,7 @@ export class MessageIde implements IDE {
callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1],
) => void,
) {}
+
pathSep(): Promise {
return this.request("pathSep", undefined);
}
@@ -41,8 +45,8 @@ export class MessageIde implements IDE {
getIdeSettings(): Promise {
return this.request("getIdeSettings", undefined);
}
- getGitHubAuthToken(): Promise {
- return this.request("getGitHubAuthToken", undefined);
+ getGitHubAuthToken(args: GetGhTokenArgs): Promise {
+ return this.request("getGitHubAuthToken", args);
}
getLastModified(files: string[]): Promise<{ [path: string]: number }> {
return this.request("getLastModified", { files });
@@ -54,13 +58,9 @@ export class MessageIde implements IDE {
return this.request("listDir", { dir });
}
- infoPopup(message: string): Promise {
- return this.request("infoPopup", { message });
- }
-
- errorPopup(message: string): Promise {
- return this.request("errorPopup", { message });
- }
+ showToast: IDE["showToast"] = (...params) => {
+ return this.request("showToast", params);
+ };
getRepoName(dir: string): Promise {
return this.request("getRepoName", { dir });
diff --git a/core/util/reverseMessageIde.ts b/core/util/reverseMessageIde.ts
index a65f1f1f2..2a8a3e406 100644
--- a/core/util/reverseMessageIde.ts
+++ b/core/util/reverseMessageIde.ts
@@ -33,8 +33,8 @@ export class ReverseMessageIde {
}
private initializeListeners() {
- this.on("getGitHubAuthToken", () => {
- return this.ide.getGitHubAuthToken();
+ this.on("getGitHubAuthToken", (data) => {
+ return this.ide.getGitHubAuthToken(data);
});
this.on("getLastModified", (data) => {
@@ -49,12 +49,8 @@ export class ReverseMessageIde {
return this.ide.listDir(data.dir);
});
- this.on("infoPopup", (data) => {
- return this.ide.infoPopup(data.message);
- });
-
- this.on("errorPopup", (data) => {
- return this.ide.errorPopup(data.message);
+ this.on("showToast", (data) => {
+ return this.ide.showToast(...data);
});
this.on("getRepoName", (data) => {
diff --git a/core/util/verticalEdit.ts b/core/util/verticalEdit.ts
index 0a32a6a5b..34a17ebd4 100644
--- a/core/util/verticalEdit.ts
+++ b/core/util/verticalEdit.ts
@@ -81,6 +81,9 @@ export async function* streamDiffLines(
oldLines = [];
}
+ // Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files
+ oldLines = oldLines.map((line) => line.trimEnd());
+
const prompt = constructPrompt(
prefix,
highlighted,
diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md
index c7777816a..7ae6b329b 100644
--- a/docs/docs/customize/deep-dives/docs.md
+++ b/docs/docs/customize/deep-dives/docs.md
@@ -38,7 +38,7 @@ We offer a selection of pre-indexed documentation sites for popular frameworks a
### Through the `@docs` Context Provider
-To add a single documentation site, we recommend going through the `@docs` context provider.
+To add a single documentation site, we recommend using the `@docs` context provider.
1. Type `@docs` in the chat panel, hit enter
2. Type "add" and select the "Add Docs" option
@@ -59,7 +59,6 @@ The configuration schema is as follows:
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
- "maxDepth": 3
}
]
```
@@ -68,18 +67,21 @@ The configuration schema is as follows:
- `startUrl`: The URL where the indexing process should begin.
- `rootUrl`: The base URL of the documentation site, used to determine which pages to index.
- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI.
-- `maxDepth`: The maximum number of levels deep the indexer should crawl from the start URL.
+
+## Crawling dynamically generated sites with `useChromiumForDocsCrawling`
+
+By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript.
+
+If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`.
+
+```json title=config.json
+"experimental": {
+ "useChromiumForDocsCrawling": true
+}
+```
## FAQ
-### Why did my documentation site fail to index?
-
-Our current crawler is designed to work with static websites and may encounter issues with dynamic or JavaScript-heavy sites. If your documentation site failed to index, it's possible that it contains non-static elements that our crawler couldn't process.
-
-If you're experiencing issues with indexing a documentation site, please let us know. We're continuously improving our indexing capabilities and would appreciate your feedback to help us enhance the feature.
-
-Report Indexing Issues on Discord
-
### How often is the indexed content updated?
Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`.
diff --git a/docs/docs/customize/model-providers/assets/watsonx2.gif b/docs/docs/customize/model-providers/assets/watsonx2.gif
new file mode 100644
index 000000000..e37443ad6
Binary files /dev/null and b/docs/docs/customize/model-providers/assets/watsonx2.gif differ
diff --git a/docs/docs/customize/model-providers/more/SambaNova.md b/docs/docs/customize/model-providers/more/SambaNova.md
new file mode 100644
index 000000000..9c20ba4d7
--- /dev/null
+++ b/docs/docs/customize/model-providers/more/SambaNova.md
@@ -0,0 +1,18 @@
+# SambaNova Cloud
+
+The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can sign up [here](https://cloud.sambanova.ai/), copy your API key on the initial welcome screen, and then hit the play button on any model from the [model list](https://community.sambanova.ai/t/quick-start-guide/104).
+
+```json title="config.json"
+{
+ "models": [
+ {
+ "title": "SambaNova Llama 3.1 405B",
+ "provider": "sambanova",
+ "model": "llama3.1-405b",
+ "apiKey": "YOUR_API_KEY"
+ }
+ ]
+}
+```
+
+[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/SambaNova.ts)
diff --git a/docs/docs/customize/model-providers/more/watsonx.md b/docs/docs/customize/model-providers/more/watsonx.md
index 51fa76dbe..5cc6b33fa 100644
--- a/docs/docs/customize/model-providers/more/watsonx.md
+++ b/docs/docs/customize/model-providers/more/watsonx.md
@@ -36,6 +36,49 @@ To authenticate to your watsonx.ai Software instance with Continue, you can use
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format.
-
+Add the following configuration to your `config.json` file to use the watsonx provider. Fill in the `watsonxCreds` with the authentication details you obtained in the setup step.
+
+```json title="~/.continue/config.json"
+{
+ "models": [
+ {
+ "model": "model ID",
+ "title": "watsonx - Model Name",
+ "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
+ "watsonxProjectId": "PROJECT_ID",
+ "watsonxCreds": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
+ "watsonxApiVersion": "2023-05-29",
+ "provider": "watsonx"
+ }
+ ]
+}
+```
+
+`watsonxAPIVersion` is optional and defaults to the latest version.
+
+### Configuration Options
+
+Add the full watsonx URL to `watsonxFullUrl` if you are using a custom endpoint. When `watsonxFullUrl` is set, `watsonxUrl` and `watsonxApiVersion` are ignored.
+
+```json title="~/.continue/config.json"
+{
+ "models": [
+ {
+ "model": "model ID",
+ "title": "watsonx - Model Name",
+ "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
+ "watsonxProjectId": "PROJECT_ID",
+ "watsonxCreds": "API_KEY",
+ "watsonxApiVersion": "2023-05-29",
+ "provider": "watsonx",
+ "watsonxFullUrl": "https://us-south.ml.cloud.ibm.com/m1/v1/text/generation"
+ }
+ ]
+}
+```
+
+## Usage
+
+
diff --git a/docs/docs/customize/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md
index e326bc564..290a7abbc 100644
--- a/docs/docs/customize/tutorials/llama3.1.md
+++ b/docs/docs/customize/tutorials/llama3.1.md
@@ -90,3 +90,24 @@ Replicate makes it easy to host and run open-source AI with an API.
]
}
```
+
+## SambaNova
+
+SambaNova Cloud provides world record Llama3.1 70B/405B serving.
+
+1. Create an account [here](https://cloud.sambanova.ai/)
+2. Copy your API key
+3. Update your Continue config file like this:
+
+```json title="~/.continue/config.json"
+{
+ "models": [
+ {
+ "title": "SambaNova Llama 3.1 405B",
+ "provider": "sambanova",
+ "model": "llama3.1-405b",
+ "apiKey": "YOUR_API_KEY"
+ }
+ ]
+}
+```
\ No newline at end of file
diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json
index 26733028a..45faeb06f 100644
--- a/docs/static/schemas/config.json
+++ b/docs/static/schemas/config.json
@@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
+ "sambanova",
"nvidia",
"vllm"
],
@@ -200,8 +201,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
- "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
- "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
+ "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
+ "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@@ -242,6 +243,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
+ },
+ "modelArn": {
+ "title": "Profile",
+ "description": "The AWS arn for the imported model",
+ "type": "string"
+ },
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@@ -383,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
- "cloudflare"
+ "cloudflare",
+ "sambanova"
]
}
},
@@ -393,6 +410,21 @@
"required": ["apiKey"]
}
},
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": [
+ "bedrockimport"
+ ]
+ }
+ },
+ "required": ["provider"]
+ },
+ "then": {
+ "required": ["modelArn"]
+ }
+ },
{
"if": {
"properties": {
@@ -1254,6 +1286,9 @@
"watsonxStopToken": {
"type": "string"
},
+ "watsonxFullUrl": {
+ "type": "string"
+ },
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@@ -1266,6 +1301,35 @@
},
"required": ["watsonxUrl", "watsonxProjectId"]
}
+ },
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": ["sambanova"]
+ }
+ },
+ "required": ["provider"]
+ },
+ "then": {
+ "properties": {
+ "model": {
+ "anyOf": [
+ {
+ "enum": [
+ "llama3.1-8b",
+ "llama3.1-70b",
+ "llama3.1-405b"
+ ]
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "markdownDescription": "Select a pre-defined option."
+ }
+ }
+ }
}
]
},
@@ -2029,7 +2093,9 @@
"cohere",
"free-trial",
"gemini",
- "voyage"
+ "voyage",
+ "nvidia",
+ "bedrock"
]
},
"model": {
@@ -2052,6 +2118,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
+ },
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
}
},
"required": ["provider"],
@@ -2060,20 +2136,7 @@
"if": {
"properties": {
"provider": {
- "enum": ["cohere", "voyage"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "required": ["apiKey"]
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["gemini"]
+ "enum": ["cohere", "voyage", "nvidia", "gemini"]
}
},
"required": ["provider"]
diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts
index 37586546a..87dd1f953 100644
--- a/extensions/intellij/build.gradle.kts
+++ b/extensions/intellij/build.gradle.kts
@@ -11,6 +11,7 @@ plugins {
alias(libs.plugins.changelog) // Gradle Changelog Plugin
alias(libs.plugins.qodana) // Gradle Qodana Plugin
alias(libs.plugins.kover) // Gradle Kover Plugin
+ kotlin("plugin.serialization") version "1.8.0"
}
group = properties("pluginGroup").get()
@@ -38,6 +39,7 @@ dependencies {
exclude(group = "org.slf4j", module = "slf4j-api")
}
implementation("com.posthog.java:posthog:1.+")
+ implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
}
@@ -84,6 +86,9 @@ tasks {
from("../../binary/bin") {
into("${intellij.pluginName.get()}/core/")
}
+ from("../vscode/node_modules/@vscode/ripgrep") {
+ into("${intellij.pluginName.get()}/ripgrep/")
+ }
}
wrapper {
@@ -144,7 +149,7 @@ tasks {
// Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more:
// https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel
channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap")))
-
+
// We always hide the stable releases until a few days of EAP have proven them stable
// hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false)
}
diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties
index 528ad8217..a416d2887 100644
--- a/extensions/intellij/gradle.properties
+++ b/extensions/intellij/gradle.properties
@@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
# SemVer format -> https://semver.org
-pluginVersion = 0.0.66
+pluginVersion = 0.0.68
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt
index 5eb8d8715..b600a7777 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt
@@ -33,6 +33,8 @@ import javax.swing.*
import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.PluginId
+import com.intellij.openapi.module.ModuleManager
+import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import org.jetbrains.plugins.terminal.TerminalToolWindowFactory
@@ -68,20 +70,20 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
removeShortcutFromAction(getPlatformSpecificKeyStroke("J"))
removeShortcutFromAction(getPlatformSpecificKeyStroke("shift J"))
- project.messageBus.connect().subscribe(
- ToolWindowManagerListener.TOPIC,
- object : ToolWindowManagerListener {
- override fun stateChanged(toolWindowManager: ToolWindowManager) {
- if (toolWindowManager.activeToolWindowId == TerminalToolWindowFactory.TOOL_WINDOW_ID
- || TerminalView.getInstance(project).isNotAvailable()
- ) {
- project.service().update(
- TerminalView.getInstance(project).widgets
- )
- }
- }
- }
- )
+// project.messageBus.connect().subscribe(
+// ToolWindowManagerListener.TOPIC,
+// object : ToolWindowManagerListener {
+// override fun stateChanged(toolWindowManager: ToolWindowManager) {
+// if (toolWindowManager.activeToolWindowId == TerminalToolWindowFactory.TOOL_WINDOW_ID
+// || TerminalView.getInstance(project).isNotAvailable()
+// ) {
+// project.service().update(
+// TerminalView.getInstance(project).widgets
+// )
+// }
+// }
+// }
+// )
ApplicationManager.getApplication().executeOnPooledThread {
initializePlugin(project)
@@ -134,6 +136,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
showTutorial(project)
}
+ settings.addRemoteSyncJob()
+
val ideProtocolClient = IdeProtocolClient(
continuePluginService,
defaultStrategy,
@@ -186,11 +190,16 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
)
// Reload the WebView
- continuePluginService?.let {
- val workspacePaths =
- if (project.basePath != null) arrayOf(project.basePath) else emptyList()
+ continuePluginService?.let { pluginService ->
+ val allModulePaths = ModuleManager.getInstance(project).modules
+ .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.path } }
+ .map { Paths.get(it).normalize() }
- continuePluginService.workspacePaths = workspacePaths as Array
+ val topLevelModulePaths = allModulePaths
+ .filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }
+ .map { it.toString() }
+
+ pluginService.workspacePaths = topLevelModulePaths.toTypedArray()
}
EditorFactory.getInstance().eventMulticaster.addSelectionListener(
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt
index 0fb203b57..d4168b6ba 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/ServerConstants.kt
@@ -81,17 +81,32 @@ fun getContinueGlobalPath(): String {
return continuePath.toString()
}
-fun getConfigJsonPath(): String {
- val path = Paths.get(getContinueGlobalPath(), "config.json")
+fun getContinueRemoteConfigPath(remoteHostname: String): String {
+ val path = Paths.get(getContinueGlobalPath(), ".configs")
+ if (Files.notExists(path)) {
+ Files.createDirectories(path)
+ }
+ return Paths.get(path.toString(), remoteHostname).toString()
+}
+
+
+fun getConfigJsonPath(remoteHostname: String? = null): String {
+ val path = Paths.get(
+ if (remoteHostname != null) getContinueRemoteConfigPath(remoteHostname) else getContinueGlobalPath(),
+ "config.json"
+ )
if (Files.notExists(path)) {
Files.createFile(path)
- Files.writeString(path, DEFAULT_CONFIG);
+ Files.writeString(path, if (remoteHostname == null) DEFAULT_CONFIG else "{}")
}
return path.toString()
}
-fun getConfigJsPath(): String {
- val path = Paths.get(getContinueGlobalPath(), "config.js")
+fun getConfigJsPath(remoteHostname: String? = null): String {
+ val path = Paths.get(
+ if (remoteHostname != null) getContinueRemoteConfigPath(remoteHostname) else getContinueGlobalPath(),
+ "config.js"
+ )
if (Files.notExists(path)) {
Files.createFile(path)
Files.writeString(path, DEFAULT_CONFIG_JS);
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt
index 8f3f00e32..590d1780b 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt
@@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.TelemetryService
+import com.github.continuedev.continueintellijextension.toolWindow.MessageTypes
import com.google.gson.Gson
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
@@ -56,7 +57,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
val data = responseMap["data"]
// IDE listeners
- if (ideMessageTypes.contains(messageType)) {
+ if (MessageTypes.ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf(
"messageId" to messageId,
@@ -68,7 +69,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
}
// Forward to webview
- if (PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
+ if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
// TODO: Currently we aren't set up to receive a response back from the webview
// Can circumvent for getDefaultsModelTitle here for now
if (messageType == "getDefaultModelTitle") {
@@ -88,7 +89,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
// Responses for messageId
responseListeners[messageId]?.let { listener ->
listener(data)
- if (generatorTypes.contains(messageType)) {
+ if (MessageTypes.generatorTypes.contains(messageType)) {
val done = (data as Map)["done"]
if (done == true) {
responseListeners.remove(messageId)
@@ -100,64 +101,6 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
}
}
- private val generatorTypes = listOf(
- "llm/streamComplete",
- "llm/streamChat",
- "command/run",
- "streamDiffLines"
- )
-
- private val ideMessageTypes = listOf(
- "readRangeInFile",
- "isTelemetryEnabled",
- "getUniqueId",
- "getWorkspaceConfigs",
- "getDiff",
- "getTerminalContents",
- "getWorkspaceDirs",
- "showLines",
- "listFolders",
- "getContinueDir",
- "writeFile",
- "fileExists",
- "showVirtualFile",
- "openFile",
- "runCommand",
- "saveFile",
- "readFile",
- "showDiff",
- "getOpenFiles",
- "getCurrentFile",
- "getPinnedFiles",
- "getSearchResults",
- "getProblems",
- "subprocess",
- "getBranch",
- "getIdeInfo",
- "getIdeSettings",
- "errorPopup",
- "getRepoName",
- "listDir",
- "getGitRootPath",
- "getLastModified",
- "insertAtCursor",
- "applyToFile",
- "getGitHubAuthToken",
- "setGitHubAuthToken",
- "pathSep",
- "getControlPlaneSessionInfo",
- "logoutOfControlPlane",
- "getTerminalContents"
- )
-
- private val PASS_THROUGH_TO_WEBVIEW = listOf(
- "configUpdate",
- "getDefaultModelTitle",
- "indexProgress",
- "refreshSubmenuItems",
- "didChangeAvailableProfiles"
- )
-
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
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 cd1b50904..a308ff0fe 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
@@ -14,6 +14,9 @@ import com.google.gson.reflect.TypeToken
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl
import com.intellij.codeInsight.daemon.impl.HighlightInfo
+import com.intellij.execution.configurations.GeneralCommandLine
+import com.intellij.execution.util.ExecUtil
+import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.Disposable
@@ -52,6 +55,7 @@ import java.awt.datatransfer.StringSelection
import java.io.*
import java.net.NetworkInterface
import java.nio.charset.Charset
+import java.nio.file.Paths
import java.util.*
@@ -197,6 +201,7 @@ class IdeProtocolClient (
private val project: Project
): DumbAware {
val diffManager = DiffManager(project)
+ private val ripgrep: String
init {
initIdeProtocol()
@@ -205,6 +210,20 @@ class IdeProtocolClient (
VirtualFileManager.getInstance().addAsyncFileListener(AsyncFileSaveListener(this), object : Disposable {
override fun dispose() {}
})
+
+ val myPluginId = "com.github.continuedev.continueintellijextension"
+ val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
+
+ val pluginPath = pluginDescriptor.pluginPath
+ val osName = System.getProperty("os.name").toLowerCase()
+ val os = when {
+ osName.contains("mac") || osName.contains("darwin") -> "darwin"
+ osName.contains("win") -> "win32"
+ osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
+ else -> "linux"
+ }
+
+ ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString()
}
private fun send(messageType: String, data: Any?, messageId: String? = null) {
@@ -461,8 +480,9 @@ class IdeProtocolClient (
}
"getBranch" -> {
// Get the current branch name
+ val dir = (data as Map)["dir"] as String
val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
- builder.directory(File(workspacePath ?: "."))
+ builder.directory(File(dir))
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
@@ -473,15 +493,21 @@ class IdeProtocolClient (
}
"getRepoName" -> {
// Get the current repository name
+ val dir = (data as Map)["dir"] as String
val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url")
- builder.directory(File(workspacePath ?: "."))
- val process = builder.start()
+ builder.directory(File(dir))
+ var output = "NONE"
+ try {
+ val process = builder.start()
- val reader = BufferedReader(InputStreamReader(process.inputStream))
- val output = reader.readLine()
- process.waitFor()
+ val reader = BufferedReader(InputStreamReader(process.inputStream))
+ output = reader.readLine()
+ process.waitFor()
+ } catch (error: Exception) {
+ println("Git not found: " + error)
+ }
- respond(output ?: "NONE")
+ respond(output)
}
// NEW //
@@ -592,7 +618,8 @@ class IdeProtocolClient (
}
"getSearchResults" -> {
- respond("")
+ val query = (data as Map)["query"] as String
+ respond(search(query))
}
// Other
@@ -634,7 +661,7 @@ class IdeProtocolClient (
if (ghAuthToken == null) {
// Open a dialog so user can enter their GitHub token
- continuePluginService.sendToWebview("openOnboarding", null, uuid())
+ continuePluginService.sendToWebview("openOnboardingCard", null, uuid())
respond(null)
} else {
respond(ghAuthToken)
@@ -850,10 +877,15 @@ class IdeProtocolClient (
}
private fun workspaceDirectories(): Array {
+ val dirs = this.continuePluginService.workspacePaths
+ if (dirs?.isNotEmpty() == true) {
+ return dirs
+ }
+
if (this.workspacePath != null) {
return arrayOf(this.workspacePath)
}
- return arrayOf();
+ return arrayOf()
}
private fun listDirectoryContents(directory: String?): List {
@@ -1018,6 +1050,12 @@ class IdeProtocolClient (
return contents
}
+
+ private fun search(query: String): String {
+ val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--", query, ".")
+ command.setWorkDirectory(project.basePath)
+ return ExecUtil.execAndGetOutput(command).stdout ?: ""
+ }
}
interface TextSelectionStrategy {
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt
index 81bbbb6af..76439f260 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt
@@ -1,12 +1,24 @@
package com.github.continuedev.continueintellijextension.services
+import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
+import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.DumbAware
+import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.messages.Topic
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.decodeFromString
+import kotlinx.serialization.json.Json
+import okhttp3.OkHttpClient
+import okhttp3.Request
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
+import java.io.File
+import java.io.IOException
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
import javax.swing.*
class ContinueSettingsComponent: DumbAware {
@@ -53,6 +65,12 @@ class ContinueSettingsComponent: DumbAware {
}
}
+@Serializable
+class ContinueRemoteConfigSyncResponse {
+ var configJson: String? = null
+ var configJs: String? = null
+}
+
@State(
name = "com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings",
storages = [Storage("ContinueExtensionSettings.xml")]
@@ -73,6 +91,8 @@ open class ContinueExtensionSettings : PersistentStateComponent? = null
+
override fun getState(): ContinueState {
return continueState
}
@@ -85,6 +105,72 @@ open class ContinueExtensionSettings : PersistentStateComponent
+ if (!response.isSuccessful) throw IOException("Unexpected code $response")
+
+ response.body?.string()?.let { responseBody ->
+ try {
+ configResponse =
+ Json.decodeFromString(responseBody)
+ } catch (e: Exception) {
+ e.printStackTrace()
+ return
+ }
+ }
+ }
+ } catch (e: IOException) {
+ e.printStackTrace()
+ return
+ }
+
+ if (configResponse?.configJson?.isNotEmpty()!!) {
+ val file = File(getConfigJsonPath(request.url.host))
+ file.writeText(configResponse!!.configJson!!)
+ }
+
+ if (configResponse?.configJs?.isNotEmpty()!!) {
+ val file = File(getConfigJsPath(request.url.host))
+ file.writeText(configResponse!!.configJs!!)
+ }
+ }
+ }
+
+ // Create a scheduled task to sync remote config every `remoteConfigSyncPeriod` minutes
+ fun addRemoteSyncJob() {
+
+ if (remoteSyncFuture != null) {
+ remoteSyncFuture?.cancel(false)
+ }
+
+ instance.remoteSyncFuture = AppExecutorUtil.getAppScheduledExecutorService()
+ .scheduleWithFixedDelay(
+ { syncRemoteConfig() },
+ 0,
+ continueState.remoteConfigSyncPeriod.toLong(),
+ TimeUnit.MINUTES
+ )
+ }
}
interface SettingsListener {
@@ -124,6 +210,7 @@ class ContinueExtensionConfigurable : Configurable {
settings.continueState.displayEditorTooltip = mySettingsComponent?.displayEditorTooltip?.isSelected ?: true
ApplicationManager.getApplication().messageBus.syncPublisher(SettingsListener.TOPIC).settingsUpdated(settings.continueState)
+ ContinueExtensionSettings.instance.addRemoteSyncJob()
}
override fun reset() {
@@ -134,6 +221,8 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.enableTabAutocomplete?.isSelected = settings.continueState.enableTabAutocomplete
mySettingsComponent?.enableContinueTeamsBeta?.isSelected = settings.continueState.enableContinueTeamsBeta
mySettingsComponent?.displayEditorTooltip?.isSelected = settings.continueState.displayEditorTooltip
+
+ ContinueExtensionSettings.instance.addRemoteSyncJob()
}
override fun disposeUIResources() {
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt
index db385565f..5d6c1cd11 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt
@@ -1,32 +1,22 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.showTutorial
-import com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
-import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
-import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
-import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
-import com.intellij.openapi.util.io.StreamUtil
-import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.jcef.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
-import java.io.File
-import java.io.IOException
-import java.nio.charset.StandardCharsets
-import java.nio.file.Paths
class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false) {
private val heightChangeListeners = mutableListOf<(Int) -> Unit>()
@@ -118,13 +108,20 @@ class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false
val ide = continuePluginService.ideProtocolClient;
val respond = fun(data: Any?) {
- val jsonData = mutableMapOf(
- "messageId" to messageId,
- "data" to data,
- "messageType" to messageType
- )
- val jsonString = Gson().toJson(jsonData)
- sendToWebview(messageType, data, messageId ?: uuid())
+ // This matches the way that we expect receive messages in IdeMessenger.ts (gui)
+ // and the way they are sent in VS Code (webviewProtocol.ts)
+ var result: Map? = null
+ if (MessageTypes.generatorTypes.contains(messageType)) {
+ result = data as? Map
+ } else {
+ result = mutableMapOf(
+ "status" to "success",
+ "done" to false,
+ "content" to data
+ )
+ }
+
+ sendToWebview(messageType, result, messageId ?: uuid())
}
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/MessageTypes.kt
new file mode 100644
index 000000000..da623bda7
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/MessageTypes.kt
@@ -0,0 +1,64 @@
+package com.github.continuedev.continueintellijextension.toolWindow
+
+class MessageTypes {
+ companion object {
+ val generatorTypes = listOf(
+ "llm/streamComplete",
+ "llm/streamChat",
+ "command/run",
+ "streamDiffLines"
+ )
+
+ val ideMessageTypes = listOf(
+ "readRangeInFile",
+ "isTelemetryEnabled",
+ "getUniqueId",
+ "getWorkspaceConfigs",
+ "getDiff",
+ "getTerminalContents",
+ "getWorkspaceDirs",
+ "showLines",
+ "listFolders",
+ "getContinueDir",
+ "writeFile",
+ "fileExists",
+ "showVirtualFile",
+ "openFile",
+ "runCommand",
+ "saveFile",
+ "readFile",
+ "showDiff",
+ "getOpenFiles",
+ "getCurrentFile",
+ "getPinnedFiles",
+ "getSearchResults",
+ "getProblems",
+ "subprocess",
+ "getBranch",
+ "getIdeInfo",
+ "getIdeSettings",
+ "errorPopup",
+ "getRepoName",
+ "listDir",
+ "getGitRootPath",
+ "getLastModified",
+ "insertAtCursor",
+ "applyToFile",
+ "getGitHubAuthToken",
+ "setGitHubAuthToken",
+ "pathSep",
+ "getControlPlaneSessionInfo",
+ "logoutOfControlPlane",
+ "getTerminalContents"
+ )
+
+ val PASS_THROUGH_TO_WEBVIEW = listOf(
+ "configUpdate",
+ "getDefaultModelTitle",
+ "indexProgress",
+ "refreshSubmenuItems",
+ "didChangeAvailableProfiles",
+ "addContextItem"
+ )
+ }
+}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json
index 26733028a..45faeb06f 100644
--- a/extensions/intellij/src/main/resources/config_schema.json
+++ b/extensions/intellij/src/main/resources/config_schema.json
@@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
+ "sambanova",
"nvidia",
"vllm"
],
@@ -200,8 +201,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
- "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
- "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
+ "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
+ "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@@ -242,6 +243,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
+ },
+ "modelArn": {
+ "title": "Profile",
+ "description": "The AWS arn for the imported model",
+ "type": "string"
+ },
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@@ -383,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
- "cloudflare"
+ "cloudflare",
+ "sambanova"
]
}
},
@@ -393,6 +410,21 @@
"required": ["apiKey"]
}
},
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": [
+ "bedrockimport"
+ ]
+ }
+ },
+ "required": ["provider"]
+ },
+ "then": {
+ "required": ["modelArn"]
+ }
+ },
{
"if": {
"properties": {
@@ -1254,6 +1286,9 @@
"watsonxStopToken": {
"type": "string"
},
+ "watsonxFullUrl": {
+ "type": "string"
+ },
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@@ -1266,6 +1301,35 @@
},
"required": ["watsonxUrl", "watsonxProjectId"]
}
+ },
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": ["sambanova"]
+ }
+ },
+ "required": ["provider"]
+ },
+ "then": {
+ "properties": {
+ "model": {
+ "anyOf": [
+ {
+ "enum": [
+ "llama3.1-8b",
+ "llama3.1-70b",
+ "llama3.1-405b"
+ ]
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "markdownDescription": "Select a pre-defined option."
+ }
+ }
+ }
}
]
},
@@ -2029,7 +2093,9 @@
"cohere",
"free-trial",
"gemini",
- "voyage"
+ "voyage",
+ "nvidia",
+ "bedrock"
]
},
"model": {
@@ -2052,6 +2118,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
+ },
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
}
},
"required": ["provider"],
@@ -2060,20 +2136,7 @@
"if": {
"properties": {
"provider": {
- "enum": ["cohere", "voyage"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "required": ["apiKey"]
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["gemini"]
+ "enum": ["cohere", "voyage", "nvidia", "gemini"]
}
},
"required": ["provider"]
diff --git a/extensions/intellij/src/main/resources/icons/continue.svg b/extensions/intellij/src/main/resources/icons/continue.svg
new file mode 100644
index 000000000..ab3f4d8bb
--- /dev/null
+++ b/extensions/intellij/src/main/resources/icons/continue.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md
index 70a854996..378686daf 100644
--- a/extensions/vscode/CHANGELOG.md
+++ b/extensions/vscode/CHANGELOG.md
@@ -5,6 +5,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
+Pre-release Changes
+### Changed
+* Use Chromium only as a fallback after asking user
+
## 0.8.50 - 2024-09-02
### Fixed
* Hotfix for ability to use more than one inline context provider
diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json
index 9101d205a..cbf47d4b4 100644
--- a/extensions/vscode/config_schema.json
+++ b/extensions/vscode/config_schema.json
@@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
+ "sambanova",
"nvidia",
"vllm"
],
@@ -200,10 +201,10 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
- "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
- "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
+ "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
+ "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
- "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
+ "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)",
@@ -242,6 +243,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
+ },
+ "modelArn": {
+ "title": "Profile",
+ "description": "The AWS arn for the imported model",
+ "type": "string"
+ },
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@@ -383,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
- "cloudflare"
+ "cloudflare",
+ "sambanova"
]
}
},
@@ -393,6 +410,19 @@
"required": ["apiKey"]
}
},
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": ["bedrockimport"]
+ }
+ },
+ "required": ["provider"]
+ },
+ "then": {
+ "required": ["modelArn"]
+ }
+ },
{
"if": {
"properties": {
@@ -494,7 +524,7 @@
"if": {
"properties": {
"provider": {
- "enum": ["openai", "azure"]
+ "enum": ["openai"]
}
},
"required": ["provider"]
@@ -678,13 +708,13 @@
"anyOf": [
{
"enum": [
+ "claude-2",
+ "claude-instant-1",
"claude-3-5-sonnet-20240620",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
- "claude-2.1",
- "claude-2",
- "claude-instant-1"
+ "claude-2.1"
]
},
{
@@ -727,7 +757,6 @@
"anyOf": [
{
"enum": [
- "anthropic.claude-3-5-sonnet-20240620-v1:0",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2"
@@ -774,6 +803,7 @@
},
"model": {
"enum": [
+ "chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
@@ -914,33 +944,33 @@
"anyOf": [
{
"enum": [
- "mistral:7b",
- "llama2:7b",
- "llama2:13b",
- "codellama:7b",
- "codellama:13b",
- "codellama:34b",
- "codellama:70b",
- "llama3:8b",
- "llama3:70b",
- "llama3.1:8b",
- "llama3.1:70b",
- "llama3.1:405b",
- "phi:2",
- "phind:codellama:34b",
- "wizardcoder:7b",
- "wizardcoder:13b",
- "wizardcoder:34b",
- "zephyr:7b",
- "codeup:13b",
- "deepseek:7b",
- "deepseek:33b",
- "neural:chat:7b",
- "deepseek:1b",
- "stable:code:3b",
- "starcoder:1b",
- "starcoder:3b",
- "starcoder2:3b",
+ "mistral-7b",
+ "llama2-7b",
+ "llama2-13b",
+ "codellama-7b",
+ "codellama-13b",
+ "codellama-34b",
+ "codellama-70b",
+ "llama3-8b",
+ "llama3-70b",
+ "llama3.1-8b",
+ "llama3.1-70b",
+ "llama3.1-405b",
+ "phi-2",
+ "phind-codellama-34b",
+ "wizardcoder-7b",
+ "wizardcoder-13b",
+ "wizardcoder-34b",
+ "zephyr-7b",
+ "codeup-13b",
+ "deepseek-7b",
+ "deepseek-33b",
+ "neural-chat-7b",
+ "deepseek-1b",
+ "stable-code-3b",
+ "starcoder-1b",
+ "starcoder-3b",
+ "starcoder2-3b",
"AUTODETECT"
]
},
@@ -1205,6 +1235,7 @@
"claude-2.1",
"command-r",
"command-r-plus",
+ "chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
@@ -1254,6 +1285,9 @@
"watsonxStopToken": {
"type": "string"
},
+ "watsonxFullUrl": {
+ "type": "string"
+ },
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@@ -1266,6 +1300,31 @@
},
"required": ["watsonxUrl", "watsonxProjectId"]
}
+ },
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": ["sambanova"]
+ }
+ },
+ "required": ["provider"]
+ },
+ "then": {
+ "properties": {
+ "model": {
+ "anyOf": [
+ {
+ "enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"]
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "markdownDescription": "Select a pre-defined option."
+ }
+ }
+ }
}
]
},
@@ -2030,7 +2089,8 @@
"free-trial",
"gemini",
"voyage",
- "mistral"
+ "nvidia",
+ "bedrock"
]
},
"model": {
@@ -2053,6 +2113,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
+ },
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
}
},
"required": ["provider"],
@@ -2061,7 +2131,7 @@
"if": {
"properties": {
"provider": {
- "enum": ["cohere", "voyage"]
+ "enum": ["cohere", "voyage", "nvidia", "gemini"]
}
},
"required": ["provider"]
@@ -2069,109 +2139,6 @@
"then": {
"required": ["apiKey"]
}
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["gemini"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "required": ["apiKey"],
- "properties": {
- "model": {
- "enum": ["models/text-embedding-004"]
- }
- }
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["ollama"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "properties": {
- "model": {
- "enum": ["nomic-embed-text"]
- }
- }
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["openai", "azure"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "properties": {
- "model": {
- "enum": ["text-embedding-3-large", "text-embedding-3-small"]
- }
- }
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["mistral"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "properties": {
- "model": {
- "enum": ["mistral-embed"]
- }
- }
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["voyage"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "properties": {
- "model": {
- "enum": ["voyage-code-2"]
- }
- }
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": ["cohere"]
- }
- },
- "required": ["provider"]
- },
- "then": {
- "properties": {
- "model": {
- "enum": ["embed-english-v3.0", "embed-english-light-v3.0"]
- }
- }
- }
}
]
},
@@ -2509,16 +2476,13 @@
"type": "object",
"properties": {
"inlineEdit": {
- "description": "The 'title' property of the model you wish to use for inline edits",
- "type": "string"
+ "$ref": "#/definitions/ModelTitle"
},
"applyCodeBlock": {
- "description": "The 'title' property of the model you wish to use for applying code blocks",
- "type": "string"
+ "$ref": "#/definitions/ModelTitle"
},
"repoMapFileSelection": {
- "description": "The 'title' property of the model you wish to use for repo map file selections",
- "type": "string"
+ "$ref": "#/definitions/ModelTitle"
}
}
},
@@ -2581,6 +2545,12 @@
}
}
}
+ },
+ "ModelTitle": {
+ "type": "string",
+ "enum": {
+ "$data": "/models/title"
+ }
}
}
}
diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json
index 9d5414bc9..c33df73c2 100644
--- a/extensions/vscode/continue_rc_schema.json
+++ b/extensions/vscode/continue_rc_schema.json
@@ -195,6 +195,7 @@
"msty",
"watsonx",
"openrouter",
+ "sambanova",
"nvidia",
"vllm"
],
@@ -203,8 +204,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
- "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
- "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
+ "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
+ "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@@ -245,6 +246,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
+ },
+ "modelArn": {
+ "title": "Profile",
+ "description": "The AWS arn for the imported model",
+ "type": "string"
+ },
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@@ -395,7 +411,8 @@
"huggingface-inference-api",
"replicate",
"together",
- "cloudflare"
+ "cloudflare",
+ "sambanova"
]
}
},
@@ -409,6 +426,25 @@
]
}
},
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": [
+ "bedrockimport"
+ ]
+ }
+ },
+ "required": [
+ "provider"
+ ]
+ },
+ "then": {
+ "required": [
+ "modelArn"
+ ]
+ }
+ },
{
"if": {
"properties": {
@@ -1390,6 +1426,9 @@
"watsonxStopToken": {
"type": "string"
},
+ "watsonxFullUrl": {
+ "type": "string"
+ },
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@@ -1405,6 +1444,39 @@
"watsonxProjectId"
]
}
+ },
+ {
+ "if": {
+ "properties": {
+ "provider": {
+ "enum": [
+ "sambanova"
+ ]
+ }
+ },
+ "required": [
+ "provider"
+ ]
+ },
+ "then": {
+ "properties": {
+ "model": {
+ "anyOf": [
+ {
+ "enum": [
+ "llama3.1-8b",
+ "llama3.1-70b",
+ "llama3.1-405b"
+ ]
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "markdownDescription": "Select a pre-defined option."
+ }
+ }
+ }
}
]
},
@@ -2257,7 +2329,9 @@
"cohere",
"free-trial",
"gemini",
- "voyage"
+ "voyage",
+ "nvidia",
+ "bedrock"
]
},
"model": {
@@ -2280,6 +2354,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
+ },
+ "region": {
+ "title": "Region",
+ "description": "The region where the model is hosted",
+ "type": "string"
+ },
+ "profile": {
+ "title": "Profile",
+ "description": "The AWS security profile to use",
+ "type": "string"
}
},
"required": [
@@ -2292,25 +2376,8 @@
"provider": {
"enum": [
"cohere",
- "voyage"
- ]
- }
- },
- "required": [
- "provider"
- ]
- },
- "then": {
- "required": [
- "apiKey"
- ]
- }
- },
- {
- "if": {
- "properties": {
- "provider": {
- "enum": [
+ "voyage",
+ "nvidia",
"gemini"
]
}
diff --git a/extensions/vscode/media/move-to-right-sidebar.gif b/extensions/vscode/media/move-to-right-sidebar.gif
new file mode 100644
index 000000000..d21ea71a0
Binary files /dev/null and b/extensions/vscode/media/move-to-right-sidebar.gif differ
diff --git a/extensions/vscode/media/sidebar.gif b/extensions/vscode/media/sidebar.gif
deleted file mode 100644
index 6912578ca..000000000
Binary files a/extensions/vscode/media/sidebar.gif and /dev/null differ
diff --git a/extensions/vscode/media/welcome.md b/extensions/vscode/media/welcome.md
index 1887f4641..33cdee623 100644
--- a/extensions/vscode/media/welcome.md
+++ b/extensions/vscode/media/welcome.md
@@ -1,21 +1,8 @@
-# 👋 Welcome to Continue
+# Move Continue to the right sidebar
-## ❗️ Before you get started
+
-Continue is currently in the left sidebar, but we recommend moving it to the right. This way it won't cover your file explorer.
+Continue is currently in the left sidebar, but we recommend moving it to the right.
+This way it won't cover your file explorer.
You can move it back at any time. If you close the sidebar, it can be re-opened with Cmd/Ctrl + L .
-
-
-
-## 🔑 Most important shortcuts
-
-> If you'd prefer different keys, these shortcuts can be customized in VS Code settings.
-
-Cmd/Ctrl + L = Select code
-
-Cmd/Ctrl + Shift + L = Select code for follow-up
-
-Cmd/Ctrl + I = Quick edit
-
-Cmd/Ctrl + Shift + R = Automatically debug terminal
diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json
index 8e728ecb0..890c69954 100644
--- a/extensions/vscode/package-lock.json
+++ b/extensions/vscode/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "continue",
- "version": "0.8.48",
+ "version": "0.9.209",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
- "version": "0.8.48",
+ "version": "0.9.209",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@@ -108,6 +108,7 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
+ "cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json
index 5335c91b6..20582c70b 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.206",
+ "version": "0.9.209",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/VsCodeIde.ts
similarity index 93%
rename from extensions/vscode/src/ideProtocol.ts
rename to extensions/vscode/src/VsCodeIde.ts
index b89e24b43..0df445b01 100644
--- a/extensions/vscode/src/ideProtocol.ts
+++ b/extensions/vscode/src/VsCodeIde.ts
@@ -16,6 +16,7 @@ import type {
} from "core";
import { Range } from "core";
import { walkDir } from "core/indexing/walkDir";
+import { GetGhTokenArgs } from "core/protocol/ide";
import {
editConfigJson,
getConfigJsonPath,
@@ -42,6 +43,7 @@ class VsCodeIde implements IDE {
) {
this.ideUtils = new VsCodeIdeUtils();
}
+
pathSep(): Promise {
return Promise.resolve(this.ideUtils.path.sep);
}
@@ -74,7 +76,7 @@ class VsCodeIde implements IDE {
private authToken: string | undefined;
private askedForAuth = false;
- async getGitHubAuthToken(): Promise {
+ async getGitHubAuthToken(args: GetGhTokenArgs): Promise {
// Saved auth token
if (this.authToken) {
return this.authToken;
@@ -90,6 +92,14 @@ class VsCodeIde implements IDE {
}
try {
+ if (args.force) {
+ this.askedForAuth = true;
+ this.authToken = await vscode.authentication
+ .getSession("github", [], { createIfNone: true })
+ .then((session) => session.accessToken);
+ return this.authToken;
+ }
+
// If we haven't asked yet, give explanation of what is happening and why
// But don't wait to return this immediately
// We will use a callback to refresh the config
@@ -107,7 +117,7 @@ class VsCodeIde implements IDE {
"continue.continueGUIView.focus",
);
(await this.vscodeWebviewProtocolPromise).request(
- "openOnboarding",
+ "openOnboardingCard",
undefined,
);
@@ -191,13 +201,24 @@ class VsCodeIde implements IDE {
return undefined;
}
- async infoPopup(message: string): Promise {
- vscode.window.showInformationMessage(message);
- }
+ showToast: IDE["showToast"] = async (...params) => {
+ const [type, message, ...otherParams] = params;
+ const { showErrorMessage, showWarningMessage, showInformationMessage } =
+ vscode.window;
- async errorPopup(message: string): Promise {
- vscode.window.showErrorMessage(message);
- }
+ switch (type) {
+ case "error":
+ return showErrorMessage(message, "Show logs").then((selection) => {
+ if (selection === "Show logs") {
+ vscode.commands.executeCommand("workbench.action.toggleDevTools");
+ }
+ });
+ case "info":
+ return showInformationMessage(message, ...otherParams);
+ case "warning":
+ return showWarningMessage(message, ...otherParams);
+ }
+ };
async getRepoName(dir: string): Promise {
const repo = await this.getRepo(vscode.Uri.file(dir));
diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts
index 7608443ae..821f215f1 100644
--- a/extensions/vscode/src/autocomplete/completionProvider.ts
+++ b/extensions/vscode/src/autocomplete/completionProvider.ts
@@ -38,7 +38,7 @@ export class ContinueCompletionProvider
showFreeTrialLoginMessage(
e.message,
this.configHandler.reloadConfig.bind(this.configHandler),
- () => this.webviewProtocol.request("openOnboarding", undefined),
+ () => this.webviewProtocol.request("openOnboardingCard", undefined),
);
return;
}
@@ -50,7 +50,7 @@ export class ContinueCompletionProvider
),
);
} else if (val === "Download Ollama") {
- vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai"));
+ vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
}
});
}
diff --git a/extensions/vscode/src/autocomplete/statusBar.ts b/extensions/vscode/src/autocomplete/statusBar.ts
index db707c754..8a5a468e0 100644
--- a/extensions/vscode/src/autocomplete/statusBar.ts
+++ b/extensions/vscode/src/autocomplete/statusBar.ts
@@ -4,6 +4,7 @@ import {
CONTINUE_WORKSPACE_KEY,
getContinueWorkspaceConfig,
} from "../util/workspaceConfig";
+import { ILLM } from "core";
export enum StatusBarStatus {
Disabled,
@@ -134,3 +135,37 @@ export function monitorBatteryChanges(battery: Battery): vscode.Disposable {
}
});
}
+
+export function getAutocompleteStatusBarDescription(
+ selected: string | undefined,
+ { title, apiKey, providerName }: ILLM,
+): string | undefined {
+ if (title !== selected) {
+ return undefined;
+ }
+
+ let description = "Currently selected";
+
+ // Only set for Mistral since our default config includes Codestral without
+ // an API key
+ if ((apiKey === undefined || apiKey === "") && providerName === "mistral") {
+ description += " (Missing API key)";
+ }
+
+ return description;
+}
+
+export function getAutocompleteStatusBarTitle(
+ selected: string | undefined,
+ { title }: ILLM,
+): string {
+ if (!title) {
+ return "Unnamed Model";
+ }
+
+ if (title === selected) {
+ return `$(check) ${title}`;
+ }
+
+ return title;
+}
diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts
index 979c782b0..ca91b71b7 100644
--- a/extensions/vscode/src/commands.ts
+++ b/extensions/vscode/src/commands.ts
@@ -3,7 +3,6 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import * as vscode from "vscode";
-
import { ContextMenuConfig, IDE } from "core";
import { CompletionProvider } from "core/autocomplete/completionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
@@ -16,6 +15,8 @@ import { Telemetry } from "core/util/posthog";
import readLastLines from "read-last-lines";
import {
StatusBarStatus,
+ getAutocompleteStatusBarDescription,
+ getAutocompleteStatusBarTitle,
getStatusBarStatus,
getStatusBarStatusFromQuickPickItemLabel,
quickPickStatusText,
@@ -590,15 +591,13 @@ const commandsMap: (
const quickPick = vscode.window.createQuickPick();
const autocompleteModels =
(await configHandler.loadConfig())?.tabAutocompleteModels ?? [];
- const autocompleteModelTitles = autocompleteModels
- .map((model) => model.title)
- .filter((t) => t !== undefined) as string[];
+
let selected = new GlobalContext().get("selectedTabAutocompleteModel");
if (
!selected ||
- !autocompleteModelTitles.some((title) => title === selected)
+ !autocompleteModels.some((model) => model.title === selected)
) {
- selected = autocompleteModelTitles[0];
+ selected = autocompleteModels[0].title;
}
// Toggle between Disabled, Paused, and Enabled
@@ -614,8 +613,8 @@ const commandsMap: (
currentStatus === StatusBarStatus.Paused
? StatusBarStatus.Enabled
: currentStatus === StatusBarStatus.Disabled
- ? StatusBarStatus.Paused
- : StatusBarStatus.Disabled;
+ ? StatusBarStatus.Paused
+ : StatusBarStatus.Disabled;
} else {
// Toggle between Disabled and Enabled
targetStatus =
@@ -637,9 +636,9 @@ const commandsMap: (
kind: vscode.QuickPickItemKind.Separator,
label: "Switch model",
},
- ...autocompleteModelTitles.map((title) => ({
- label: title === selected ? `$(check) ${title}` : title,
- description: title === selected ? "Currently selected" : undefined,
+ ...autocompleteModels.map((model) => ({
+ label: getAutocompleteStatusBarTitle(selected, model),
+ description: getAutocompleteStatusBarDescription(selected, model),
})),
];
quickPick.onDidAccept(() => {
@@ -658,7 +657,9 @@ const commandsMap: (
selectedOption === "$(gear) Configure autocomplete options"
) {
ide.openFile(getConfigJsonPath());
- } else if (autocompleteModelTitles.includes(selectedOption)) {
+ } else if (
+ autocompleteModels.some((model) => model.title === selectedOption)
+ ) {
new GlobalContext().update(
"selectedTabAutocompleteModel",
selectedOption,
diff --git a/extensions/vscode/src/debug/debug.ts b/extensions/vscode/src/debug/debug.ts
index d4f12ea5a..0671df7d5 100644
--- a/extensions/vscode/src/debug/debug.ts
+++ b/extensions/vscode/src/debug/debug.ts
@@ -1,5 +1,5 @@
import * as vscode from "vscode";
-import type { VsCodeIde } from "../ideProtocol";
+import type { VsCodeIde } from "../VsCodeIde";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
export const threadStopped: Map = new Map();
diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts
index 8323a0d6f..4f49e3a2b 100644
--- a/extensions/vscode/src/extension/VsCodeExtension.ts
+++ b/extensions/vscode/src/extension/VsCodeExtension.ts
@@ -15,10 +15,8 @@ import {
} from "../autocomplete/statusBar";
import { registerAllCommands } from "../commands";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
-import { registerDebugTracker } from "../debug/debug";
import { DiffManager } from "../diff/horizontal";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
-import { VsCodeIde } from "../ideProtocol";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
@@ -28,6 +26,7 @@ import {
} from "../stubs/WorkOsAuthProvider";
import { Battery } from "../util/battery";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
+import { VsCodeIde } from "../VsCodeIde";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
import { VsCodeMessenger } from "./VsCodeMessenger";
@@ -210,7 +209,8 @@ export class VsCodeExtension {
this.core,
);
- registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
+ // Disabled due to performance issues
+ // registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
// Listen for file saving - use global file watcher so that changes
// from outside the window are also caught
@@ -233,6 +233,7 @@ export class VsCodeExtension {
"showConfigUpdateToast",
true,
);
+
if (showToast) {
vscode.window
.showInformationMessage("Config updated", "Don't show again")
diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts
index a51bd8233..ceebe1fd9 100644
--- a/extensions/vscode/src/extension/VsCodeMessenger.ts
+++ b/extensions/vscode/src/extension/VsCodeMessenger.ts
@@ -17,12 +17,12 @@ import * as fs from "node:fs";
import * as path from "node:path";
import * as vscode from "vscode";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
-import { VsCodeIde } from "../ideProtocol";
import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
} from "../stubs/WorkOsAuthProvider";
import { getExtensionUri } from "../util/vscode";
+import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
/**
@@ -172,7 +172,9 @@ export class VsCodeMessenger {
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath),
);
- await vscode.window.showTextDocument(doc);
+ await vscode.window.showTextDocument(doc, {
+ preview: false,
+ });
});
this.onWebview("openUrl", (msg) => {
@@ -282,21 +284,11 @@ export class VsCodeMessenger {
const { filepath, startLine, endLine } = msg.data;
return ide.showLines(filepath, startLine, endLine);
});
- // Other
- this.onWebviewOrCore("errorPopup", (msg) => {
- vscode.window
- .showErrorMessage(msg.data.message, "Show Logs")
- .then((selection) => {
- if (selection === "Show Logs") {
- vscode.commands.executeCommand("workbench.action.toggleDevTools");
- }
- });
- });
- this.onWebviewOrCore("infoPopup", (msg) => {
- vscode.window.showInformationMessage(msg.data.message);
+ this.onWebviewOrCore("showToast", (msg) => {
+ this.ide.showToast(...msg.data);
});
this.onWebviewOrCore("getGitHubAuthToken", (msg) =>
- ide.getGitHubAuthToken(),
+ ide.getGitHubAuthToken(msg.data),
);
this.onWebviewOrCore("getControlPlaneSessionInfo", async (msg) => {
return getControlPlaneSessionInfo(msg.data.silent);
diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts
index 58f6696c7..6b8c4d6db 100644
--- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts
+++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts
@@ -312,7 +312,7 @@ export class QuickEdit {
const modelTitle = await this.getCurModelTitle();
if (!modelTitle) {
- this.ide.infoPopup("Please configure a model to use Quick Edit");
+ this.ide.showToast("info", "Please configure a model to use Quick Edit");
return undefined;
}
diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts
index 15f79ddfd..33ab80632 100644
--- a/extensions/vscode/src/util/ideUtils.ts
+++ b/extensions/vscode/src/util/ideUtils.ts
@@ -137,7 +137,12 @@ export class VsCodeIdeUtils {
openFile(filepath: string, range?: vscode.Range) {
// vscode has a builtin open/get open files
- return openEditorAndRevealRange(filepath, range, vscode.ViewColumn.One);
+ return openEditorAndRevealRange(
+ filepath,
+ range,
+ vscode.ViewColumn.One,
+ false,
+ );
}
async fileExists(filepath: string): Promise {
diff --git a/extensions/vscode/src/util/messages.ts b/extensions/vscode/src/util/messages.ts
index 2cef9d4b1..c01ceaa2a 100644
--- a/extensions/vscode/src/util/messages.ts
+++ b/extensions/vscode/src/util/messages.ts
@@ -3,7 +3,7 @@ import * as vscode from "vscode";
export function showFreeTrialLoginMessage(
message: string,
reloadConfig: () => void,
- openOnboarding: () => void,
+ openOnboardingCard: () => void,
) {
vscode.window
.showInformationMessage(message, "Sign In", "Use API key / local model")
@@ -17,7 +17,7 @@ export function showFreeTrialLoginMessage(
reloadConfig();
});
} else if (selection === "Use API key / local model") {
- openOnboarding();
+ openOnboardingCard();
}
});
}
diff --git a/extensions/vscode/src/util/vscode.ts b/extensions/vscode/src/util/vscode.ts
index fb394833c..9f9dd2093 100644
--- a/extensions/vscode/src/util/vscode.ts
+++ b/extensions/vscode/src/util/vscode.ts
@@ -125,9 +125,13 @@ function windowsToPosix(windowsPath: string): string {
function isWindowsLocalButNotRemote(): boolean {
return (
vscode.env.remoteName !== undefined &&
- ["wsl", "ssh-remote", "dev-container", "attached-container", "tunnel"].includes(
- vscode.env.remoteName,
- ) &&
+ [
+ "wsl",
+ "ssh-remote",
+ "dev-container",
+ "attached-container",
+ "tunnel",
+ ].includes(vscode.env.remoteName) &&
process.platform === "win32"
);
}
diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts
index bfc9cb125..89524a371 100644
--- a/extensions/vscode/src/webviewProtocol.ts
+++ b/extensions/vscode/src/webviewProtocol.ts
@@ -137,12 +137,12 @@ export class VsCodeWebviewProtocol
if (selection === "Add API Key") {
this.request("addApiKey", undefined);
} else if (selection === "Use Local Model") {
- this.request("setupLocalModel", undefined);
+ this.request("setupLocalConfig", undefined);
}
});
} else if (message.includes("Please sign in with GitHub")) {
showFreeTrialLoginMessage(message, this.reloadConfig, () =>
- this.request("openOnboarding", undefined),
+ this.request("openOnboardingCard", undefined),
);
} else {
Telemetry.capture(
diff --git a/gui/package-lock.json b/gui/package-lock.json
index 774db75f8..589d7578f 100644
--- a/gui/package-lock.json
+++ b/gui/package-lock.json
@@ -101,6 +101,7 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
+ "cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
diff --git a/gui/public/logos/sambanova.png b/gui/public/logos/sambanova.png
new file mode 100644
index 000000000..6f95c6a58
Binary files /dev/null and b/gui/public/logos/sambanova.png differ
diff --git a/gui/src/App.tsx b/gui/src/App.tsx
index 2410ed1f1..9cf442727 100644
--- a/gui/src/App.tsx
+++ b/gui/src/App.tsx
@@ -13,10 +13,6 @@ import History from "./pages/history";
import MigrationPage from "./pages/migration";
import MonacoPage from "./pages/monaco";
import { default as More, default as MorePage } from "./pages/more";
-import ApiKeyAutocompleteOnboarding from "./pages/onboarding/apiKeyAutocompleteOnboarding";
-import ApiKeysOnboarding from "./pages/onboarding/ApiKeysOnboarding";
-import LocalOnboarding from "./pages/onboarding/LocalOnboarding";
-import Onboarding from "./pages/onboarding/Onboarding";
import SettingsPage from "./pages/settings";
import Stats from "./pages/stats";
@@ -66,26 +62,10 @@ const router = createMemoryRouter([
path: "/monaco",
element: ,
},
- {
- path: "/onboarding",
- element: ,
- },
- {
- path: "/localOnboarding",
- element: ,
- },
{
path: "/migration",
element: ,
},
- {
- path: "/apiKeysOnboarding",
- element: ,
- },
- {
- path: "/apiKeyAutocompleteOnboarding",
- element: ,
- },
],
},
]);
diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx
new file mode 100644
index 000000000..8ff095926
--- /dev/null
+++ b/gui/src/components/AddModelButtonSubtext.tsx
@@ -0,0 +1,21 @@
+import { useContext } from "react";
+import { ButtonSubtext } from ".";
+import { IdeMessengerContext } from "../context/IdeMessenger";
+
+function AddModelButtonSubtext() {
+ const ideMessenger = useContext(IdeMessengerContext);
+
+ return (
+
+ This will update your{" "}
+ ideMessenger.post("openConfigJson", undefined)}
+ >
+ config file
+
+
+ );
+}
+
+export default AddModelButtonSubtext;
diff --git a/gui/src/components/ContinueLogo.tsx b/gui/src/components/ContinueLogo.tsx
new file mode 100644
index 000000000..88aa18b68
--- /dev/null
+++ b/gui/src/components/ContinueLogo.tsx
@@ -0,0 +1,63 @@
+import { vscForeground } from ".";
+
+interface ContinueLogoProps {
+ height?: number;
+ width?: number;
+}
+
+export default function ContinueLogo({
+ height = 987,
+ width = 299,
+}: ContinueLogoProps) {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx
index 2ec23ea2f..a02a4347a 100644
--- a/gui/src/components/Layout.tsx
+++ b/gui/src/components/Layout.tsx
@@ -11,11 +11,11 @@ import {
} from ".";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useWebviewListener } from "../hooks/useWebviewListener";
-import { isNewUserOnboarding } from "../pages/onboarding/utils";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import {
setBottomMessage,
setBottomMessageCloseTimeout,
+ setOnboardingCard,
setShowDialog,
} from "../redux/slices/uiStateSlice";
import { RootState } from "../redux/store";
@@ -27,6 +27,8 @@ import HeaderButtonWithText from "./HeaderButtonWithText";
import ProgressBar from "./loaders/ProgressBar";
import PostHogPageView from "./PosthogPageView";
import ProfileSwitcher from "./ProfileSwitcher";
+import { isNewUserOnboarding } from "./OnboardingCard/utils";
+import { useOnboardingCard } from "./OnboardingCard";
const FOOTER_HEIGHT = "1.8em";
@@ -102,17 +104,12 @@ const ProfileDropdownPortalDiv = styled.div`
font-size: ${getFontSize() - 2};
`;
-const HIDE_FOOTER_ON_PAGES = [
- "/onboarding",
- "/localOnboarding",
- "/apiKeyOnboarding",
-];
-
const Layout = () => {
const navigate = useNavigate();
const location = useLocation();
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
+ const onboardingCard = useOnboardingCard();
const dialogMessage = useSelector(
(state: RootState) => state.uiState.dialogMessage,
@@ -177,22 +174,6 @@ const Layout = () => {
[location, navigate],
);
- useWebviewListener(
- "addApiKey",
- async () => {
- navigate("/apiKeyOnboarding");
- },
- [navigate],
- );
-
- useWebviewListener(
- "openOnboarding",
- async () => {
- navigate("/onboarding");
- },
- [navigate],
- );
-
useWebviewListener(
"incrementFtc",
async () => {
@@ -207,14 +188,19 @@ const Layout = () => {
);
useWebviewListener(
- "setupLocalModel",
+ "openOnboardingCard",
async () => {
- ideMessenger.post("completeOnboarding", {
- mode: "localAfterFreeTrial",
- });
- navigate("/localOnboarding");
+ onboardingCard.open("Best");
},
- [navigate],
+ [],
+ );
+
+ useWebviewListener(
+ "setupLocalConfig",
+ async () => {
+ onboardingCard.open("Local");
+ },
+ [],
);
useEffect(() => {
@@ -222,7 +208,7 @@ const Layout = () => {
isNewUserOnboarding() &&
(location.pathname === "/" || location.pathname === "/index.html")
) {
- navigate("/onboarding");
+ onboardingCard.open("Quickstart");
}
}, [location]);
@@ -252,33 +238,31 @@ const Layout = () => {
- {HIDE_FOOTER_ON_PAGES.includes(location.pathname) || (
-
-
-
- );
-}
diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx
new file mode 100644
index 000000000..0dc00ad9d
--- /dev/null
+++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx
@@ -0,0 +1,64 @@
+import * as Tabs from "./tabs";
+import OnboardingCardTabs, { TabTitle } from "./components/OnboardingCardTabs";
+import { XMarkIcon } from "@heroicons/react/24/outline";
+import styled from "styled-components";
+import { CloseButton, defaultBorderRadius, vscInputBackground } from "../";
+import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
+import { useOnboardingCard } from "./hooks/useOnboardingCard";
+
+const StyledCard = styled.div`
+ margin: auto;
+ border-radius: ${defaultBorderRadius};
+ padding: 1rem 1.5rem;
+ background-color: ${vscInputBackground};
+ box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1),
+ 0 8px 10px -6px rgb(0 0 0 / 0.1);
+`;
+
+export interface OnboardingCardState {
+ show?: boolean;
+ activeTab?: TabTitle;
+}
+
+export const defaultOnboardingCardState: OnboardingCardState = {
+ show: false,
+ activeTab: "Quickstart",
+};
+
+export type OnboardingCardProps = Pick;
+
+function OnboardingCard(props: OnboardingCardProps) {
+ const onboardingCard = useOnboardingCard();
+
+ function renderTabContent() {
+ switch (onboardingCard.activeTab) {
+ case "Quickstart":
+ return ;
+ case "Best":
+ return ;
+ case "Local":
+ return ;
+ default:
+ return null;
+ }
+ }
+
+ if (getLocalStorage("onboardingStatus") === undefined) {
+ setLocalStorage("onboardingStatus", "Started");
+ }
+
+ return (
+
+
+
+
+
+ {renderTabContent()}
+
+ );
+}
+
+export default OnboardingCard;
diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx
new file mode 100644
index 000000000..ee061e1f9
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx
@@ -0,0 +1,142 @@
+import { CubeIcon } from "@heroicons/react/24/outline";
+import { DEFAULT_CHAT_MODEL_CONFIG } from "core/config/default";
+import { useContext, useState } from "react";
+import { useDispatch } from "react-redux";
+import { Button, Input, InputSubtext, lightGray } from "../..";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { models } from "../../../pages/AddNewModel/configs/models";
+import { providers } from "../../../pages/AddNewModel/configs/providers";
+import { setDefaultModel } from "../../../redux/slices/stateSlice";
+import AddModelButtonSubtext from "../../AddModelButtonSubtext";
+
+const { anthropic: chatProvider, mistral: autocompleteProvider } = providers;
+const { claude35Sonnet: chatModel, codestral: autocompleteModel } = models;
+
+interface BestExperienceConfigFormProps {
+ onComplete: () => void;
+}
+
+function BestExperienceConfigForm({
+ onComplete,
+}: BestExperienceConfigFormProps) {
+ const dispatch = useDispatch();
+
+ const ideMessenger = useContext(IdeMessengerContext);
+
+ const [autocompleteApiKey, setAutocompleteApiKey] = useState("");
+ const [chatApiKey, setChatApiKey] = useState("");
+
+ async function handleSubmit(e) {
+ e.preventDefault();
+
+ const chatModelConfig = {
+ model: chatModel.params.model,
+ provider: chatProvider.provider,
+ apiKey: chatApiKey,
+ title: chatModel.params.title,
+ };
+
+ const autocompleteModelConfig = {
+ title: autocompleteModel.params.title,
+ provider: autocompleteProvider.provider,
+ model: autocompleteModel.params.model,
+ apiKey: autocompleteApiKey,
+ };
+
+ ideMessenger.post("config/deleteModel", {
+ title: DEFAULT_CHAT_MODEL_CONFIG.title,
+ });
+ ideMessenger.post("config/addModel", { model: chatModelConfig });
+ dispatch(setDefaultModel({ title: chatModelConfig.title, force: true }));
+
+ if (!!autocompleteApiKey) {
+ await ideMessenger.request("addAutocompleteModel", {
+ model: autocompleteModelConfig,
+ });
+ }
+
+ onComplete();
+ }
+
+ return (
+
+ );
+}
+export default BestExperienceConfigForm;
diff --git a/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx b/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx
new file mode 100644
index 000000000..1c3ef9399
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx
@@ -0,0 +1,82 @@
+import { ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline";
+import { useContext, useState } from "react";
+import { StyledActionButton, Input, Button, ButtonSubtext } from "../..";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { setShowDialog } from "../../../redux/slices/uiStateSlice";
+import { useDispatch } from "react-redux";
+
+interface JetBrainsFetchGitHubTokenDialogProps {
+ onComplete: () => void;
+}
+
+const GITHUB_AUTH_URL =
+ "https://github.com/settings/tokens/new?scopes=user:email&description=Continue%20Free%20Trial%20Token%20";
+
+function JetBrainsFetchGitHubTokenDialog({
+ onComplete,
+}: JetBrainsFetchGitHubTokenDialogProps) {
+ const dispatch = useDispatch();
+ const ideMessenger = useContext(IdeMessengerContext);
+ const [jbGhAuthToken, setJbGhAuthToken] = useState("");
+ const [hasClickedGitHubButton, setHasClickedGitHubButton] = useState(false);
+
+ async function submitJetBrainsToken() {
+ await ideMessenger.request("setGitHubAuthToken", {
+ token: jbGhAuthToken,
+ });
+ dispatch(setShowDialog(false));
+ onComplete();
+ }
+
+ function openGitHubTokenPage() {
+ ideMessenger.post("openUrl", GITHUB_AUTH_URL);
+ setHasClickedGitHubButton(true);
+ }
+
+ return (
+
+
+
Sign in with GitHub
+
+ Continue will request read access to your GitHub email so that we can
+ prevent abuse of the free trial. If you prefer not to sign in, you can
+ use Continue with your own API keys or local model.
+
+
+
+
+ {hasClickedGitHubButton ? (
+
+ Token
+ setJbGhAuthToken(e.target.value)}
+ />
+
+ ) : (
+
+ Get GitHub token
+
+
+ )}
+
+
+
+ Get started using our API keys
+
+
+ Try 50 chat and 2k autocomplete requests
+
+
+
+
+ );
+}
+
+export default JetBrainsFetchGitHubTokenDialog;
diff --git a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx
new file mode 100644
index 000000000..ee3eb942c
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx
@@ -0,0 +1,16 @@
+import { CheckCircleIcon } from "@heroicons/react/24/solid";
+
+interface OllamaCompletedStepProps {
+ text: string;
+}
+
+function OllamaCompletedStep({ text }: OllamaCompletedStepProps) {
+ return (
+
+ );
+}
+
+export default OllamaCompletedStep;
diff --git a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx
new file mode 100644
index 000000000..e9683a431
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx
@@ -0,0 +1,53 @@
+import { CommandLineIcon } from "@heroicons/react/24/outline";
+import { useContext } from "react";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import ReactDOM from "react-dom";
+import { StyledActionButton, StyledTooltip } from "../..";
+import OllamaCompletedStep from "./OllamaCompletedStep";
+
+interface OllamaModelDownloadProps {
+ title: string;
+ modelName: string;
+ hasDownloaded: boolean;
+}
+
+function OllamaModelDownload({
+ title,
+ modelName,
+ hasDownloaded,
+}: OllamaModelDownloadProps) {
+ const ideMessenger = useContext(IdeMessengerContext);
+ const command = `ollama pull ${modelName}`;
+ const id = `info-hover-${encodeURIComponent(command)}`;
+ const tooltipPortalDiv = document.getElementById("tooltip-portal-div");
+
+ function onClick() {
+ ideMessenger.ide.runCommand(command);
+ ideMessenger.post("copyText", { text: command });
+ }
+
+ return (
+
+
{title}
+ {hasDownloaded ? (
+
+ ) : (
+ <>
+
+ {command}
+
+
+ {tooltipPortalDiv &&
+ ReactDOM.createPortal(
+
+ Copy into terminal
+ ,
+ tooltipPortalDiv,
+ )}
+ >
+ )}
+
+ );
+}
+
+export default OllamaModelDownload;
diff --git a/gui/src/components/OnboardingCard/components/OllamaStatus.tsx b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx
new file mode 100644
index 000000000..a6dcd89ad
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/OllamaStatus.tsx
@@ -0,0 +1,67 @@
+import {
+ ArrowPathIcon,
+ ArrowTopRightOnSquareIcon,
+} from "@heroicons/react/24/outline";
+import { useState, useContext } from "react";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { providers } from "../../../pages/AddNewModel/configs/providers";
+import { useCheckOllamaModels } from "../hooks/useCheckOllamaModels";
+import { StyledActionButton } from "../..";
+import OllamaCompletedStep from "./OllamaCompletedStep";
+
+export enum OllamaConnectionStatuses {
+ WaitingToDownload = "WaitingToDownload",
+ Downloading = "Downloading",
+ Verified = "Verified",
+}
+
+interface OllamaStatusProps {
+ onConnectionVerified: () => void;
+}
+
+const {
+ ollama: { downloadUrl },
+} = providers;
+
+function OllamaStatus({ onConnectionVerified }: OllamaStatusProps) {
+ const ideMessenger = useContext(IdeMessengerContext);
+
+ const [status, setStatus] = useState(
+ OllamaConnectionStatuses.WaitingToDownload,
+ );
+
+ useCheckOllamaModels((models) => {
+ setStatus(OllamaConnectionStatuses.Verified);
+ onConnectionVerified();
+ });
+
+ function onClickDownload() {
+ ideMessenger.post("openUrl", downloadUrl);
+ setStatus(OllamaConnectionStatuses.Downloading);
+ }
+
+ switch (status) {
+ case OllamaConnectionStatuses.WaitingToDownload:
+ return (
+
+ {downloadUrl}
+
+
+ );
+ case OllamaConnectionStatuses.Downloading:
+ return (
+
+
+ Checking for connection to Ollama at http://localhost:11434
+
+
+
+ );
+ case OllamaConnectionStatuses.Verified:
+ return (
+
+ );
+ }
+}
+
+export default OllamaStatus;
diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx
new file mode 100644
index 000000000..c35f2aa52
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx
@@ -0,0 +1,78 @@
+import styled from "styled-components";
+import { vscButtonBackground, vscForeground } from "../..";
+import { hasPassedFTL } from "../../../util/freeTrial";
+
+interface OnboardingCardTabsProps {
+ activeTab: TabTitle;
+ onTabClick: (tabName: TabTitle) => void;
+}
+
+export type TabTitle = "Quickstart" | "Best" | "Local";
+
+export const TabTitles: { [k in TabTitle]: { xs: string; default: string } } = {
+ Quickstart: {
+ xs: "Quickstart",
+ default: "Quickstart",
+ },
+ Best: {
+ xs: "Best",
+ default: "Best experience",
+ },
+ Local: {
+ xs: "Local",
+ default: "Local with Ollama",
+ },
+};
+
+const TabButton = styled.button<{ isActive: boolean }>`
+ padding: 1rem 1rem 0.5rem 1rem;
+ margin-bottom: -1px;
+ focus: outline-none;
+ background: transparent;
+ cursor: pointer;
+ color: ${vscForeground};
+ border: none;
+
+ ${({ isActive }) =>
+ isActive &&
+ `
+ border-style: solid;
+ border-width: 0 0 2.5px 0;
+ border-color: ${vscForeground};
+ font-weight: bold;
+ `}
+`;
+
+const TabList = styled.div`
+ border-style: solid;
+ border-width: 0 0 0.5px 0;
+ border-color: ${vscForeground};
+`;
+
+function OnboardingCardTabs({
+ activeTab,
+ onTabClick,
+}: OnboardingCardTabsProps) {
+ return (
+
+ {Object.entries(TabTitles).map(([tabType, titles]) => {
+ if (hasPassedFTL() && tabType === "Quickstart") {
+ return undefined;
+ }
+
+ return (
+ onTabClick(tabType as TabTitle)}
+ >
+ {titles.default}
+ {titles.xs}
+
+ );
+ })}
+
+ );
+}
+
+export default OnboardingCardTabs;
diff --git a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx
new file mode 100644
index 000000000..dd1e9f339
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx
@@ -0,0 +1,39 @@
+import { useDispatch } from "react-redux";
+import AddModelForm from "../../../forms/AddModelForm";
+import {
+ setDialogMessage,
+ setShowDialog,
+} from "../../../redux/slices/uiStateSlice";
+import Alert from "../../gui/Alert";
+import { useSubmitOnboarding } from "../hooks";
+
+function ProviderAlert() {
+ const dispatch = useDispatch();
+ const { submitOnboarding } = useSubmitOnboarding("Custom");
+
+ function onClick() {
+ dispatch(setShowDialog(true));
+ dispatch(setDialogMessage( ));
+ }
+
+ return (
+
+
+
+ Prefer to use an different provider like OpenAI?
+
+
+
+ Click here
+ {" "}
+ to add a Chat model from OpenAI, Gemini, and more
+
+
+
+ );
+}
+
+export default ProviderAlert;
diff --git a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx
new file mode 100644
index 000000000..fb8b21c0a
--- /dev/null
+++ b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx
@@ -0,0 +1,69 @@
+import { FREE_TRIAL_MODELS } from "core/config/default";
+import { useContext } from "react";
+import { useDispatch } from "react-redux";
+import { Button, ButtonSubtext } from "../..";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { setDefaultModel } from "../../../redux/slices/stateSlice";
+import {
+ setDialogMessage,
+ setShowDialog,
+} from "../../../redux/slices/uiStateSlice";
+import { isJetBrains } from "../../../util";
+import { useSubmitOnboarding } from "../hooks";
+import JetBrainsFetchGitHubTokenDialog from "./JetBrainsFetchGitHubTokenDialog";
+
+function QuickstartSubmitButton() {
+ const ideMessenger = useContext(IdeMessengerContext);
+ const dispatch = useDispatch();
+
+ const { submitOnboarding } = useSubmitOnboarding("Quickstart");
+
+ function onComplete() {
+ submitOnboarding();
+
+ // Set Sonnet as the default model
+ dispatch(
+ setDefaultModel({ title: FREE_TRIAL_MODELS[0].title, force: true }),
+ );
+ }
+
+ function openJetBrainsDialog() {
+ dispatch(setShowDialog(true));
+ dispatch(
+ setDialogMessage(
+ ,
+ ),
+ );
+ }
+
+ async function fetchGitHubAuthToken() {
+ const result = await ideMessenger.request("getGitHubAuthToken", {
+ force: true,
+ });
+ if (result.status === "success") {
+ onComplete();
+ }
+ }
+
+ async function onClick() {
+ if (isJetBrains()) {
+ openJetBrainsDialog();
+ } else {
+ await fetchGitHubAuthToken();
+ }
+ }
+
+ return (
+
+
+ Get started using our API keys
+
+ Try 50 chat and 2k autocomplete requests
+
+ );
+}
+
+export default QuickstartSubmitButton;
diff --git a/gui/src/components/OnboardingCard/hooks/index.ts b/gui/src/components/OnboardingCard/hooks/index.ts
new file mode 100644
index 000000000..88f66d231
--- /dev/null
+++ b/gui/src/components/OnboardingCard/hooks/index.ts
@@ -0,0 +1,2 @@
+export * from "./useCheckOllamaModels";
+export * from "./useSubmitOnboarding";
diff --git a/gui/src/components/OnboardingCard/hooks/useCheckOllamaModels.ts b/gui/src/components/OnboardingCard/hooks/useCheckOllamaModels.ts
new file mode 100644
index 000000000..e763c0d9a
--- /dev/null
+++ b/gui/src/components/OnboardingCard/hooks/useCheckOllamaModels.ts
@@ -0,0 +1,41 @@
+import { useContext, useEffect } from "react";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { ONBOARDING_LOCAL_MODEL_TITLE } from "core/config/onboarding";
+
+const CHECK_OLLAMA_CONNECTION_INTERVAL = 1000;
+
+export const useCheckOllamaModels = (
+ onDownloadedModels: (models: string[]) => void,
+) => {
+ const ideMessenger = useContext(IdeMessengerContext);
+
+ useEffect(() => {
+ const fetchDownloadedModels = async () => {
+ const result = (await ideMessenger.request("llm/listModels", {
+ title: ONBOARDING_LOCAL_MODEL_TITLE,
+ })) as any;
+
+ if (result.status === "success") {
+ const models = result.content;
+
+ if (Array.isArray(models)) {
+ onDownloadedModels(models);
+ clearInterval(interval);
+ }
+ }
+ };
+
+ fetchDownloadedModels();
+
+ const interval = setInterval(
+ fetchDownloadedModels,
+ CHECK_OLLAMA_CONNECTION_INTERVAL,
+ );
+
+ return () => {
+ if (interval) {
+ clearInterval(interval);
+ }
+ };
+ }, [ideMessenger, onDownloadedModels]);
+};
diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts
new file mode 100644
index 000000000..f6a29a472
--- /dev/null
+++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts
@@ -0,0 +1,67 @@
+import { useDispatch, useSelector } from "react-redux";
+import { useNavigate } from "react-router-dom";
+import { TabTitle } from "../components/OnboardingCardTabs";
+import useHistory from "../../../hooks/useHistory";
+import { setOnboardingCard } from "../../../redux/slices/uiStateSlice";
+import { OnboardingCardState } from "..";
+import { RootState } from "../../../redux/store";
+import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
+
+export interface UseOnboardingCard {
+ show: OnboardingCardState["show"];
+ activeTab: OnboardingCardState["activeTab"];
+ setActiveTab: (tab: TabTitle) => void;
+ open: (tab: TabTitle) => void;
+ close: () => void;
+}
+
+export function useOnboardingCard(): UseOnboardingCard {
+ const navigate = useNavigate();
+ const dispatch = useDispatch();
+ const { saveSession } = useHistory(dispatch);
+
+ const onboardingCard = useSelector(
+ (state: RootState) => state.uiState.onboardingCard,
+ );
+
+ const onboardingStatus = getLocalStorage("onboardingStatus");
+ const hasDismissedOnboardingCard = getLocalStorage(
+ "hasDismissedOnboardingCard",
+ );
+
+ let show: boolean;
+
+ // Always show if we explicitly want to, e.g. passing free trial
+ // and setting up keys
+ if (onboardingCard.show) {
+ show = true;
+ } else {
+ show = onboardingStatus !== "Completed" && !hasDismissedOnboardingCard;
+ }
+
+ function open(tab: TabTitle) {
+ navigate("/");
+
+ // Used to clear the chat panel before showing onboarding card
+ saveSession();
+
+ dispatch(setOnboardingCard({ show: true, activeTab: tab }));
+ }
+
+ function close() {
+ setLocalStorage("hasDismissedOnboardingCard", true);
+ dispatch(setOnboardingCard({ show: false }));
+ }
+
+ function setActiveTab(tab: TabTitle) {
+ dispatch(setOnboardingCard({ show: true, activeTab: tab }));
+ }
+
+ return {
+ show,
+ setActiveTab,
+ open,
+ close,
+ activeTab: onboardingCard.activeTab,
+ };
+}
diff --git a/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts b/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts
new file mode 100644
index 000000000..a0407c171
--- /dev/null
+++ b/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts
@@ -0,0 +1,45 @@
+import { usePostHog } from "posthog-js/react";
+import { useContext } from "react";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
+import { OnboardingModes } from "core/protocol/core";
+import { useTutorialCard } from "../../../hooks/useTutorialCard";
+import { useOnboardingCard } from "./useOnboardingCard";
+
+export function useSubmitOnboarding(mode: OnboardingModes) {
+ const posthog = usePostHog();
+ const ideMessenger = useContext(IdeMessengerContext);
+ const { openTutorialCard } = useTutorialCard();
+ const { close: closeOnboardingCard } = useOnboardingCard();
+
+ function submitOnboarding() {
+ const onboardingStatus = getLocalStorage("onboardingStatus");
+
+ // Always close the onboarding card and update config.json
+ closeOnboardingCard();
+ ideMessenger.post("completeOnboarding", {
+ mode,
+ });
+
+ if (onboardingStatus === "Started") {
+ // Telemetry
+ posthog.capture("Onboarding Step", { status: "Completed" });
+ posthog.capture("onboardingSelection", {
+ mode,
+ });
+
+ // Local state
+ setLocalStorage("onboardingStatus", "Completed");
+
+ // Show tutorial card
+ openTutorialCard();
+
+ // Move to next step in onboarding
+ ideMessenger.post("showTutorial", undefined);
+ }
+ }
+
+ return {
+ submitOnboarding,
+ };
+}
diff --git a/gui/src/components/OnboardingCard/index.ts b/gui/src/components/OnboardingCard/index.ts
new file mode 100644
index 000000000..ff4448f45
--- /dev/null
+++ b/gui/src/components/OnboardingCard/index.ts
@@ -0,0 +1,4 @@
+export * from "./OnboardingCard";
+export { default } from "./OnboardingCard";
+export * from "./utils";
+export * from "./hooks/useOnboardingCard";
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx
new file mode 100644
index 000000000..0f5e5f441
--- /dev/null
+++ b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx
@@ -0,0 +1,16 @@
+import BestExperienceConfigForm from "../components/BestExperienceConfigForm";
+import ProviderAlert from "../components/ProviderAlert";
+import { useSubmitOnboarding } from "../hooks";
+
+function OnboardingBestTab() {
+ const { submitOnboarding } = useSubmitOnboarding("Best");
+
+ return (
+
+ );
+}
+
+export default OnboardingBestTab;
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx
new file mode 100644
index 000000000..653950a27
--- /dev/null
+++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx
@@ -0,0 +1,106 @@
+import {
+ LOCAL_ONBOARDING_CHAT_MODEL,
+ LOCAL_ONBOARDING_CHAT_TITLE,
+ LOCAL_ONBOARDING_FIM_MODEL,
+ ONBOARDING_LOCAL_MODEL_TITLE,
+} from "core/config/onboarding";
+import { useContext, useEffect, useState } from "react";
+import { useDispatch } from "react-redux";
+import { Button } from "../..";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+import { setDefaultModel } from "../../../redux/slices/stateSlice";
+import { hasPassedFTL } from "../../../util/freeTrial";
+import AddModelButtonSubtext from "../../AddModelButtonSubtext";
+import OllamaModelDownload from "../components/OllamaModelDownload";
+import OllamaStatus from "../components/OllamaStatus";
+import { useCheckOllamaModels, useSubmitOnboarding } from "../hooks";
+
+function OnboardingLocalTab() {
+ const dispatch = useDispatch();
+ const ideMessenger = useContext(IdeMessengerContext);
+ const { submitOnboarding } = useSubmitOnboarding(
+ hasPassedFTL() ? "LocalAfterFreeTrial" : "Local",
+ );
+ const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false);
+ const [downloadedOllamaModels, setDownloadedOllamaModels] = useState<
+ string[]
+ >([]);
+
+ const [isOllamaConnected, setIsOllamaConnected] = useState(false);
+
+ const hasDownloadedChatModel = downloadedOllamaModels.some((ollamaModel) =>
+ ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL),
+ );
+
+ const hasDownloadedAutocompleteModel = downloadedOllamaModels.some(
+ (ollamaModel) => ollamaModel.startsWith(LOCAL_ONBOARDING_CHAT_MODEL),
+ );
+
+ /**
+ * The first time we detect that a chat model has been loaded,
+ * we send an empty request to load it
+ */
+ useEffect(() => {
+ if (!hasLoadedChatModel && hasDownloadedChatModel) {
+ ideMessenger.post("llm/complete", {
+ completionOptions: {},
+ prompt: "",
+ title: ONBOARDING_LOCAL_MODEL_TITLE,
+ });
+
+ setHasLoadedChatModel(true);
+ }
+ }, [downloadedOllamaModels, isOllamaConnected]);
+
+ useCheckOllamaModels((models) => {
+ setDownloadedOllamaModels(models);
+ });
+
+ function onConnectionVerified() {
+ setIsOllamaConnected(true);
+ }
+
+ return (
+
+
+
+
+
+
+
+
+
{
+ submitOnboarding();
+
+ // Set the selected model to the local chat model
+ dispatch(
+ setDefaultModel({
+ title: LOCAL_ONBOARDING_CHAT_TITLE,
+ force: true, // Because it doesn't exist in the webview's config object yet
+ }),
+ );
+ }}
+ className="w-full"
+ disabled={!hasDownloadedChatModel}
+ >
+ Connect
+
+
+
+
+ );
+}
+
+export default OnboardingLocalTab;
diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx
new file mode 100644
index 000000000..f0eadf43b
--- /dev/null
+++ b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx
@@ -0,0 +1,27 @@
+import ContinueLogo from "../../ContinueLogo";
+import QuickStartSubmitButton from "../components/QuickStartSubmitButton";
+
+function OnboardingQuickstartTab() {
+ return (
+
+
+
+
+
+
+
+ Quickly get up and running using our API keys. After this trial, we'll
+ help you set up your own models.
+
+
+
+ To prevent abuse, we'll ask you to sign in to GitHub.
+
+
+
+
+
+ );
+}
+
+export default OnboardingQuickstartTab;
diff --git a/gui/src/components/OnboardingCard/tabs/index.ts b/gui/src/components/OnboardingCard/tabs/index.ts
new file mode 100644
index 000000000..7e975a8ec
--- /dev/null
+++ b/gui/src/components/OnboardingCard/tabs/index.ts
@@ -0,0 +1,3 @@
+export { default as Best } from "./OnboardingBestTab";
+export { default as Local } from "./OnboardingLocalTab";
+export { default as Quickstart } from "./OnboardingQuickstartTab";
diff --git a/gui/src/pages/onboarding/utils.ts b/gui/src/components/OnboardingCard/utils.ts
similarity index 55%
rename from gui/src/pages/onboarding/utils.ts
rename to gui/src/components/OnboardingCard/utils.ts
index 48c15a28b..61e71626e 100644
--- a/gui/src/pages/onboarding/utils.ts
+++ b/gui/src/components/OnboardingCard/utils.ts
@@ -1,5 +1,3 @@
-import { usePostHog } from "posthog-js/react";
-import { useNavigate } from "react-router-dom";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
// Note that there is no "NotStarted" status since the
@@ -22,27 +20,3 @@ export function isNewUserOnboarding() {
return onboardingStatus === undefined;
}
-
-/**
- * Telemetry, status tracking, and routing logic for new user onboarding.
- */
-export function useCompleteOnboarding() {
- const posthog = usePostHog();
- const navigate = useNavigate();
-
- function completeOnboarding() {
- const onboardingStatus = getLocalStorage("onboardingStatus");
-
- if (onboardingStatus === "Started") {
- setLocalStorage("onboardingStatus", "Completed");
- setLocalStorage("showTutorialCard", true);
- posthog.capture("Onboarding Step", { status: "Completed" });
- }
-
- navigate("/");
- }
-
- return {
- completeOnboarding,
- };
-}
diff --git a/gui/src/components/ProfileSwitcher.tsx b/gui/src/components/ProfileSwitcher.tsx
index 4ffa1f085..44ba57b42 100644
--- a/gui/src/components/ProfileSwitcher.tsx
+++ b/gui/src/components/ProfileSwitcher.tsx
@@ -146,7 +146,7 @@ function ProfileSwitcher(props: {}) {
!lastControlServerBetaEnabledStatus && enableControlServerBeta;
if (shouldShowPopup) {
- ideMessenger.ide.infoPopup("Continue for Teams enabled");
+ ideMessenger.ide.showToast("info", "Continue for Teams enabled");
}
setControlServerBetaEnabled(enableControlServerBeta);
diff --git a/gui/src/components/dialogs/ConfirmationDialog.tsx b/gui/src/components/dialogs/ConfirmationDialog.tsx
index cf32d52c2..6064559e0 100644
--- a/gui/src/components/dialogs/ConfirmationDialog.tsx
+++ b/gui/src/components/dialogs/ConfirmationDialog.tsx
@@ -1,6 +1,6 @@
import { useDispatch } from "react-redux";
import styled from "styled-components";
-import { Button, SecondaryButton } from "..";
+import { Button, lightGray, SecondaryButton } from "..";
import {
setDialogMessage,
setShowDialog,
@@ -41,6 +41,7 @@ function ConfirmationDialog(props: ConfirmationDialogProps) {
{!!props.hideCancelButton || (
{
props.onCancel?.();
dispatch(setShowDialog(false));
diff --git a/gui/src/components/dialogs/FTCDialog.tsx b/gui/src/components/dialogs/FTCDialog.tsx
deleted file mode 100644
index 951ea47ef..000000000
--- a/gui/src/components/dialogs/FTCDialog.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import React, { useContext } from "react";
-import { useDispatch } from "react-redux";
-import { useNavigate } from "react-router-dom";
-import styled from "styled-components";
-import { Button, Input } from "..";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-import { setDefaultModel } from "../../redux/slices/stateSlice";
-import { setShowDialog } from "../../redux/slices/uiStateSlice";
-import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial";
-
-const GridDiv = styled.div`
- display: grid;
- grid-template-columns: 1fr 1fr;
- grid-gap: 8px;
- align-items: center;
-`;
-
-export const ftl = () => {
- // const ftc = parseInt(localStorage.getItem("ftc"));
- return 50;
-};
-
-function FTCDialog() {
- const navigate = useNavigate();
- const [apiKey, setApiKey] = React.useState("");
- const dispatch = useDispatch();
- const ideMessenger = useContext(IdeMessengerContext);
-
- return (
-
-
Free Trial Limit Reached
-
- You've reached the free trial limit of {FREE_TRIAL_LIMIT_REQUESTS} free
- inputs. To keep using Continue, you can either use your own API key, or
- use a local LLM. To read more about the options, see our{" "}
-
- documentation
-
- .
-
-
-
setApiKey(e.target.value)}
- />
-
- {
- dispatch(setShowDialog(false));
- navigate("/models");
- }}
- >
- Select model
-
- {
- ideMessenger.post("config/addOpenAiKey", apiKey);
- dispatch(setShowDialog(false));
- dispatch(setDefaultModel({ title: "GPT-4" }));
- }}
- >
- Use my API key
-
-
-
- );
-}
-
-export default FTCDialog;
diff --git a/gui/src/components/dialogs/SetupLocalOrKey.tsx b/gui/src/components/dialogs/SetupLocalOrKey.tsx
deleted file mode 100644
index a0164f74b..000000000
--- a/gui/src/components/dialogs/SetupLocalOrKey.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import React, { useContext } from "react";
-import { useDispatch } from "react-redux";
-import { useNavigate } from "react-router-dom";
-import styled from "styled-components";
-import { Button, Input } from "..";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-import { setDefaultModel } from "../../redux/slices/stateSlice";
-import { setShowDialog } from "../../redux/slices/uiStateSlice";
-
-const GridDiv = styled.div`
- display: grid;
- grid-template-columns: 1fr 1fr;
- grid-gap: 8px;
- align-items: center;
-`;
-
-function SetupLocalOrKeyDialog() {
- const navigate = useNavigate();
- const [apiKey, setApiKey] = React.useState("");
- const dispatch = useDispatch();
-
- const ideMessenger = useContext(IdeMessengerContext);
-
- return (
-
-
Set up your own model
-
- To keep using Continue after your free inputs, you can either use your
- own API key, or use a local LLM. To read more about the options, see our{" "}
-
- ideMessenger.request(
- "openUrl",
- "https://docs.continue.dev/reference/Model%20Providers/freetrial",
- )
- }
- >
- documentation
-
- .
-
-
-
setApiKey(e.target.value)}
- />
-
{
- ideMessenger.post("config/addOpenAiKey", apiKey);
- dispatch(setShowDialog(false));
- dispatch(setDefaultModel({ title: "GPT-4" }));
- }}
- >
- Use my OpenAI API key
-
-
— OR —
-
- {
- dispatch(setShowDialog(false));
- ideMessenger.request("completeOnboarding", {
- mode: "localAfterFreeTrial",
- });
- navigate("/localOnboarding");
- }}
- >
- Use local model
-
- {
- dispatch(setShowDialog(false));
- navigate("/models");
- }}
- >
- View all options
-
-
-
- );
-}
-
-export default SetupLocalOrKeyDialog;
diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx
index 6f5b450d5..33214fdfb 100644
--- a/gui/src/components/dialogs/index.tsx
+++ b/gui/src/components/dialogs/index.tsx
@@ -2,6 +2,7 @@ import React, { isValidElement, useEffect } from "react";
import ReactMarkdown from "react-markdown";
import styled from "styled-components";
import {
+ CloseButton,
VSC_BACKGROUND_VAR,
defaultBorderRadius,
lightGray,
@@ -9,6 +10,16 @@ import {
vscBackground,
vscForeground,
} from "..";
+import { useDispatch } from "react-redux";
+import { setShowDialog } from "../../redux/slices/uiStateSlice";
+import { XMarkIcon } from "@heroicons/react/24/outline";
+
+interface TextDialogProps {
+ showDialog: boolean;
+ onEnter: () => void;
+ onClose: () => void;
+ message?: string | JSX.Element;
+}
const ScreenCover = styled.div`
position: fixed;
@@ -38,12 +49,9 @@ const Dialog = styled.div`
// overflow: hidden;
`;
-const TextDialog = (props: {
- showDialog: boolean;
- onEnter: () => void;
- onClose: () => void;
- message?: string | JSX.Element;
-}) => {
+const TextDialog = (props: TextDialogProps) => {
+ const dispatch = useDispatch();
+
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
@@ -62,18 +70,16 @@ const TextDialog = (props: {
}
return (
- {
- props.onClose();
- }}
- hidden={!props.showDialog}
- >
+
{
e.stopPropagation();
}}
>
+
+
+
{typeof props.message === "string" ? (
{props.message || ""}
) : !React.isValidElement(props.message) ? null : (
diff --git a/gui/src/components/gui/Alert.tsx b/gui/src/components/gui/Alert.tsx
new file mode 100644
index 000000000..1e72e6386
--- /dev/null
+++ b/gui/src/components/gui/Alert.tsx
@@ -0,0 +1,57 @@
+import {
+ InformationCircleIcon,
+ ExclamationTriangleIcon,
+ CheckCircleIcon,
+ ExclamationCircleIcon,
+} from "@heroicons/react/24/solid";
+import { ReactNode } from "react";
+import { vscBackground } from "..";
+
+type AlertTypes = "info" | "success" | "warning" | "error";
+
+export interface AlertProps {
+ children?: ReactNode;
+ type?: AlertTypes;
+}
+
+type AlertConfig = {
+ [key in AlertTypes]: {
+ Icon: any;
+ };
+};
+
+const ALERT_CONFIGS: AlertConfig = {
+ info: {
+ Icon: InformationCircleIcon,
+ },
+ success: {
+ Icon: CheckCircleIcon,
+ },
+ warning: {
+ Icon: ExclamationTriangleIcon,
+ },
+ error: {
+ Icon: ExclamationCircleIcon,
+ },
+};
+
+function Alert({ children, type = "info" }: AlertProps) {
+ const { Icon } = ALERT_CONFIGS[type];
+
+ return (
+
+ );
+}
+
+export default Alert;
diff --git a/gui/src/components/index.tsx b/gui/src/components/index.tsx
index 86f771a61..d376f3dd5 100644
--- a/gui/src/components/index.tsx
+++ b/gui/src/components/index.tsx
@@ -127,11 +127,13 @@ export const Button = styled.button`
border-radius: ${defaultBorderRadius};
border: none;
- color: ${vscForeground};
- background-color: ${vscButtonBackground};
+ color: ${vscBackground};
+ background-color: ${vscForeground};
&:disabled {
- color: gray;
+ color: ${vscBackground};
+ opacity: 0.5;
+ pointer-events: none;
}
&:hover:enabled {
@@ -143,11 +145,12 @@ export const Button = styled.button`
export const SecondaryButton = styled.button`
padding: 10px 12px;
margin: 8px 0;
+ height: 2.5rem;
border-radius: ${defaultBorderRadius};
- border: 1px solid ${vscInputBorder};
+ border: 1px solid ${vscForeground};
color: ${vscForeground};
- background-color: ${vscBackground};
+ background-color: inherit;
&:disabled {
color: gray;
@@ -155,10 +158,25 @@ export const SecondaryButton = styled.button`
&:hover:enabled {
cursor: pointer;
- background-color: ${vscInputBackground};
+ background-color: ${vscBackground};
+ opacity: 0.9;
}
`;
+export const InputSubtext = styled.span`
+ font-size: 0.75rem;
+ line-height: 1rem;
+ color: ${lightGray};
+ margin-top: 0.25rem;
+`;
+
+export const ButtonSubtext = styled.span`
+ display: block;
+ margin-top: 0;
+ text-align: center;
+ color: ${lightGray};
+`;
+
export const CustomScrollbarDiv = styled.div`
scrollbar-base-color: transparent;
scrollbar-width: thin;
@@ -261,8 +279,8 @@ export const HelperText = styled.p`
export const Input = styled.input`
width: 100%;
padding: 8px 12px;
- margin: 8px 0;
box-sizing: border-box;
+ margin: 4px 0px;
border-radius: ${defaultBorderRadius};
outline: 1px solid ${lightGray};
border: none;
@@ -271,7 +289,7 @@ export const Input = styled.input`
&:focus {
background: ${vscInputBackground};
- outline: 1px solid ${vscFocusBorder};
+ outline: 1px solid ${lightGray};
}
&:invalid {
@@ -368,7 +386,7 @@ export const HeaderButton = styled.button<{
&:hover {
background-color: ${({ inverted, hoverBackgroundColor }) =>
typeof inverted === "undefined" || inverted
- ? (hoverBackgroundColor ?? vscInputBackground)
+ ? hoverBackgroundColor ?? vscInputBackground
: "transparent"};
}
display: flex;
@@ -377,3 +395,34 @@ export const HeaderButton = styled.button<{
gap: 4px;
padding: 2px;
`;
+
+export const Divider = styled.div`
+ height: 1px;
+ background-color: ${lightGray};
+`;
+
+export const StyledActionButton = styled.div`
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ cursor: pointer;
+ transition: background-color 200ms;
+ border-radius: ${defaultBorderRadius};
+ padding: 2px 12px;
+ background-color: ${lightGray}33;
+ background-opacity: 0.1;
+`;
+
+export const CloseButton = styled.button`
+ border: none;
+ background-color: inherit;
+ color: ${lightGray};
+ position: absolute;
+ top: 0.6rem;
+ right: 1rem;
+ padding: 0.25rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+`;
diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx
index 1aa3f2ee1..9677853da 100644
--- a/gui/src/components/loaders/IndexingProgressBar.tsx
+++ b/gui/src/components/loaders/IndexingProgressBar.tsx
@@ -212,7 +212,7 @@ const IndexingProgressBar = ({
margin: 0,
}}
>
- {Math.trunc(indexingState.progress)}%
+ {Math.trunc(Math.min(100, 100 * indexingState.progress))}%
@@ -259,20 +259,22 @@ const IndexingProgressBar = ({
>
Retry
- ) : indexingState.status === "indexing" ? (
- {
- if (indexingState.progress < 1 && indexingState.progress >= 0) {
- setPaused((prev) => !prev);
- } else {
- ideMessenger.post("index/forceReIndex", undefined);
- }
- }}
- >
- Pause
-
- ) : indexingState.status === "loading" ? null : indexingState.status ===
- "paused" ? (
+ ) : indexingState.status === "indexing" ||
+ indexingState.status === "loading" ? (
+
+ {
+ if (indexingState.progress < 1 && indexingState.progress >= 0) {
+ setPaused((prev) => !prev);
+ } else {
+ ideMessenger.post("index/forceReIndex", undefined);
+ }
+ }}
+ >
+ Pause
+
+
+ ) : indexingState.status === "paused" ? (
{
if (indexingState.progress < 1 && indexingState.progress >= 0) {
@@ -286,11 +288,16 @@ const IndexingProgressBar = ({
) : null}
- {indexingState.status === "failed" && (
-
- {getIndexingErrMsg(indexingState.desc)}
-
- )}
+
+ {indexingState.status === "failed" && (
+
+ {getIndexingErrMsg(indexingState.desc)}
+
+ )}
+ {indexingState.status === "indexing" && (
+
{indexingState.desc}
+ )}
+
);
};
diff --git a/gui/src/components/loaders/ProgressBar.tsx b/gui/src/components/loaders/ProgressBar.tsx
index 5844539f6..d347999b7 100644
--- a/gui/src/components/loaders/ProgressBar.tsx
+++ b/gui/src/components/loaders/ProgressBar.tsx
@@ -1,14 +1,15 @@
+import { ExclamationCircleIcon } from "@heroicons/react/24/outline";
import ReactDOM from "react-dom";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { StyledTooltip, lightGray, vscForeground } from "..";
+import AddModelForm from "../../forms/AddModelForm";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { getFontSize } from "../../util";
-import QuickModelSetup from "../modelSelection/quickSetup/QuickModelSetup";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial";
const ProgressBarWrapper = styled.div`
@@ -58,6 +59,27 @@ const ProgressBar = ({ completed, total }: ProgressBarProps) => {
const tooltipPortalDiv = document.getElementById("tooltip-portal-div");
+ if (completed > total) {
+ return (
+ <>
+
+
+ Trial limit reached
+
+ {tooltipPortalDiv &&
+ ReactDOM.createPortal(
+
+ Configure a model above in order to continue
+ ,
+ tooltipPortalDiv,
+ )}
+ >
+ );
+ }
+
return (
<>
{
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
- {
dispatch(setShowDialog(false));
navigate("/");
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx
index c718f5ed9..7462c69cd 100644
--- a/gui/src/components/mainInput/InputToolbar.tsx
+++ b/gui/src/components/mainInput/InputToolbar.tsx
@@ -33,7 +33,6 @@ const StyledDiv = styled.div<{ isHidden: boolean }>`
gap: 1px;
background-color: ${vscInputBackground};
align-items: center;
- z-index: 50;
font-size: ${getFontSize() - 2}px;
cursor: ${(props) => (props.isHidden ? "default" : "text")};
opacity: ${(props) => (props.isHidden ? 0 : 1)};
diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx
index 4cb6fb1fa..775efce97 100644
--- a/gui/src/components/mainInput/TipTapEditor.tsx
+++ b/gui/src/components/mainInput/TipTapEditor.tsx
@@ -60,7 +60,6 @@ import { ComboBoxItem } from "./types";
const InputBoxDiv = styled.div`
resize: none;
-
padding: 8px 12px;
padding-bottom: 4px;
font-family: inherit;
@@ -70,7 +69,6 @@ const InputBoxDiv = styled.div`
width: calc(100% - 24px);
background-color: ${vscInputBackground};
color: ${vscForeground};
- z-index: 1;
border: 0.5px solid ${vscInputBorder};
outline: none;
font-size: ${getFontSize()}px;
@@ -97,7 +95,6 @@ const HoverDiv = styled.div`
opacity: 0.5;
background-color: ${vscBadgeBackground};
color: ${vscForeground};
- z-index: 100;
display: flex;
align-items: center;
justify-content: center;
@@ -110,7 +107,6 @@ const HoverTextDiv = styled.div`
top: 0;
left: 0;
color: ${vscForeground};
- z-index: 100;
display: flex;
align-items: center;
justify-content: center;
@@ -158,6 +154,7 @@ function TipTapEditor(props: TipTapEditorProps) {
const posthog = usePostHog();
const [isEditorFocused, setIsEditorFocused] = useState(false);
+ const [hasDefaultModel, setHasDefaultModel] = useState(true);
const inSubmenuRef = useRef(undefined);
const inDropdownRef = useRef(false);
@@ -212,6 +209,20 @@ function TipTapEditor(props: TipTapEditorProps) {
const active = useSelector((state: RootState) => state.state.active);
const activeRef = useUpdatingRef(active);
+ // Only set `hasDefaultModel` after a timeout to prevent jank
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setHasDefaultModel(
+ !!defaultModel &&
+ defaultModel.apiKey !== undefined &&
+ defaultModel.apiKey !== "",
+ );
+ }, 3500);
+
+ // Cleanup function to clear the timeout if the component unmounts
+ return () => clearTimeout(timer);
+ }, [defaultModel]);
+
async function handleImageFile(
file: File,
): Promise<[HTMLImageElement, string] | undefined> {
@@ -245,10 +256,10 @@ function TipTapEditor(props: TipTapEditorProps) {
};
});
} else {
- ideMessenger.post("errorPopup", {
- message:
- "Images need to be in jpg or png format and less than 10MB in size.",
- });
+ ideMessenger.post("showToast", [
+ "error",
+ "Images need to be in jpg or png format and less than 10MB in size.",
+ ]);
}
return undefined;
}
@@ -259,6 +270,16 @@ function TipTapEditor(props: TipTapEditorProps) {
const { prevRef, nextRef, addRef } = useInputHistory();
+ function getPlaceholder() {
+ if (!hasDefaultModel) {
+ return "Configure a Chat model to get started";
+ }
+
+ return historyLengthRef.current === 0
+ ? "Ask anything, '/' for slash commands, '@' to add context"
+ : "Ask a follow-up";
+ }
+
const editor: Editor = useEditor({
extensions: [
Document,
@@ -299,10 +320,7 @@ function TipTapEditor(props: TipTapEditorProps) {
},
}),
Placeholder.configure({
- placeholder: () =>
- historyLengthRef.current === 0
- ? "Ask anything, '/' for slash commands, '@' to add context"
- : "Ask a follow-up",
+ placeholder: getPlaceholder,
}),
Paragraph.extend({
addKeyboardShortcuts() {
diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx
index ed59371b1..525a69887 100644
--- a/gui/src/components/mainInput/TutorialCard.tsx
+++ b/gui/src/components/mainInput/TutorialCard.tsx
@@ -6,7 +6,7 @@ import {
XMarkIcon,
} from "@heroicons/react/24/outline";
import styled from "styled-components";
-import { defaultBorderRadius, lightGray } from "..";
+import { defaultBorderRadius, lightGray, vscBackground } from "..";
import { getMetaKeyLabel } from "../../util";
interface TutorialCardProps {
@@ -16,25 +16,35 @@ interface TutorialCardProps {
const TutorialCardDiv = styled.div`
border: 1px solid ${lightGray};
border-radius: ${defaultBorderRadius};
+ background-color: ${vscBackground};
padding: 1rem 2.5rem 1rem 2rem;
margin: 1rem;
max-width: 28rem;
position: relative;
`;
+const CloseButton = styled.button`
+ border: none;
+ background-color: ${vscBackground};
+ color: ${lightGray};
+ position: absolute;
+ top: 0.4rem;
+ right: 0.5rem;
+ padding: 0.25rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+`;
+
export function TutorialCard({ onClose }: TutorialCardProps) {
return (
-
-
-
+
+
+
-
+
`
- background-color: ${({ selected }) =>
- selected ? vscListActiveBackground : vscInputBackground};
- cursor: pointer;
- padding: 6px 8px;
-
- &:hover {
- background-color: ${vscListActiveBackground};
- color: ${vscListActiveForeground};
- }
-`;
-
-function ListBoxOption({
- option,
- idx,
- showDelete,
-}: {
- option: Option;
- idx: number;
- showDelete?: boolean;
-}) {
- const ideMessenger = useContext(IdeMessengerContext);
-
- const dispatch = useDispatch();
- const [hovered, setHovered] = useState(false);
-
- return (
- {
- setHovered(true);
- }}
- onMouseLeave={() => {
- setHovered(false);
- }}
- >
-
- {option.title}
- {hovered && showDelete && (
- {
- dispatch(setShowDialog(true));
- dispatch(
- setDialogMessage(
- {
- ideMessenger.post("config/deleteModel", {
- title: option.title,
- });
- }}
- />,
- ),
- );
- e.stopPropagation();
- e.preventDefault();
- }}
- backgroundColor={vscInputBackground}
- hoverBackgroundColor={vscBackground}
- className="absolute right-0 p-1"
- >
-
-
- )}
-
-
- );
-}
-
-function modelSelectTitle(model: any): string {
- if (model?.title) return model?.title;
- if (model?.model !== undefined && model?.model.trim() !== "") {
- if (model?.class_name) {
- return `${model?.class_name} - ${model?.model}`;
- }
- return model?.model;
- }
- return model?.class_name;
-}
-
-interface Option {
- value: string;
- title: string;
-}
-
-function ModelSelect(props: {}) {
- const dispatch = useDispatch();
- const defaultModel = useSelector(defaultModelSelector);
- const allModels = useSelector(
- (state: RootState) => state.state.config.models,
- );
-
- const navigate = useNavigate();
-
- const [options, setOptions] = useState([]);
-
- useEffect(() => {
- setOptions(
- allModels.map((model) => {
- return {
- value: model.title,
- title: modelSelectTitle(model),
- };
- }),
- );
- }, [allModels]);
-
- const topDiv = document.getElementById("model-select-top-div");
-
- useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === "'" && isMetaEquivalentKeyPressed(event)) {
- const direction = event.shiftKey ? -1 : 1;
- const currentIndex = options.findIndex(
- (option) => option.value === defaultModel?.title,
- );
- let nextIndex = (currentIndex + 1 * direction) % options.length;
- if (nextIndex < 0) nextIndex = options.length - 1;
- dispatch(setDefaultModel({ title: options[nextIndex].value }));
- }
- };
-
- window.addEventListener("keydown", handleKeyDown);
- return () => {
- window.removeEventListener("keydown", handleKeyDown);
- };
- }, [options, defaultModel]);
-
- return (
- <>
-
- {
- if (val === defaultModel?.title) return;
- dispatch(setDefaultModel({ title: val }));
- // TODO
- // client?.setModelForRoleFromTitle("default", val);
- }}
- defaultValue={"GPT-4"}
- >
-
-
- {modelSelectTitle(defaultModel)}
-
-
-
-
- {topDiv &&
- ReactDOM.createPortal(
-
-
- {options.map((option, idx) => (
- 1}
- />
- ))}
- {options.length === 0 && No models found }
-
- {getMetaKeyLabel()}' to toggle
-
-
- ,
- topDiv,
- )}
-
-
-
- {
- navigate("/addModel");
- }}
- />
-
- >
- );
-}
-
-export default ModelSelect;
diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx
index 026b68215..71cdc1e5d 100644
--- a/gui/src/components/modelSelection/ModelSelect.tsx
+++ b/gui/src/components/modelSelection/ModelSelect.tsx
@@ -1,15 +1,20 @@
import { Listbox } from "@headlessui/react";
import {
ChevronDownIcon,
+ Cog6ToothIcon,
CubeIcon,
PlusIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { useContext, useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
-import { useNavigate } from "react-router-dom";
import styled from "styled-components";
-import { defaultBorderRadius, lightGray, vscInputBackground } from "..";
+import {
+ defaultBorderRadius,
+ Divider,
+ lightGray,
+ vscInputBackground,
+} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
import { setDefaultModel } from "../../redux/slices/stateSlice";
@@ -24,8 +29,23 @@ import {
isMetaEquivalentKeyPressed,
} from "../../util";
import ConfirmationDialog from "../dialogs/ConfirmationDialog";
+import AddModelForm from "../../forms/AddModelForm";
+
+interface ModelOptionProps {
+ option: Option;
+ idx: number;
+ showMissingApiKeyMsg: boolean;
+ showDelete?: boolean;
+}
+
+interface Option {
+ value: string;
+ title: string;
+ apiKey: string;
+}
const MAX_HEIGHT_PX = 300;
+
const StyledListboxButton = styled(Listbox.Button)`
font-family: inherit;
display: flex;
@@ -45,7 +65,7 @@ const StyledListboxOptions = styled(Listbox.Options)<{ showAbove: boolean }>`
margin-top: 4px;
position: absolute;
list-style: none;
- padding: 4px;
+ padding: 0px;
white-space: nowrap;
cursor: default;
@@ -57,45 +77,69 @@ const StyledListboxOptions = styled(Listbox.Options)<{ showAbove: boolean }>`
background-color: ${vscInputBackground};
max-height: ${MAX_HEIGHT_PX}px;
- overflow-y: auto;
+ overflow-y: scroll;
+
+ scrollbar-width: none;
${(props) => (props.showAbove ? "bottom: 100%;" : "top: 100%;")}
`;
-const StyledListboxOption = styled(Listbox.Option)`
- cursor: pointer;
+const StyledListboxOption = styled(Listbox.Option)<{ isDisabled?: boolean }>`
border-radius: ${defaultBorderRadius};
- padding: 6px;
+ padding: 8px 12px;
- &:hover {
- background: ${(props) => `${lightGray}33`};
- }
+ ${({ isDisabled }) =>
+ !isDisabled &&
+ `
+ cursor: pointer;
+
+ &:hover {
+ background: ${lightGray}33;
+ }
+ `}
+
+ ${({ isDisabled }) =>
+ isDisabled &&
+ `
+ opacity: 0.5;
+ `}
`;
-const StyledTrashIcon = styled(TrashIcon)`
+const IconBase = styled.div<{ hovered: boolean }>`
+ width: 1.2em;
+ height: 1.2em;
cursor: pointer;
- flex-shrink: 0;
- margin-left: 8px;
+ padding: 4px;
+ border-radius: ${defaultBorderRadius};
+ opacity: ${(props) => (props.hovered ? 0.75 : 0)};
+ visibility: ${(props) => (props.hovered ? "visible" : "hidden")};
+
&:hover {
- color: red;
+ opacity: 1;
+ background-color: ${lightGray}33;
}
`;
-const Divider = styled.div`
- height: 1px;
- background-color: ${lightGray};
- margin: 4px;
-`;
+const StyledTrashIcon = styled(IconBase).attrs({ as: TrashIcon })``;
+const StyledCog6ToothIcon = styled(IconBase).attrs({ as: Cog6ToothIcon })``;
+
+function modelSelectTitle(model: any): string {
+ if (model?.title) return model?.title;
+ if (model?.model !== undefined && model?.model.trim() !== "") {
+ if (model?.class_name) {
+ return `${model?.class_name} - ${model?.model}`;
+ }
+ return model?.model;
+ }
+ return model?.class_name;
+}
function ModelOption({
option,
idx,
showDelete,
-}: {
- option: Option;
- idx: number;
- showDelete?: boolean;
-}) {
+ showMissingApiKeyMsg,
+}: ModelOptionProps) {
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useDispatch();
@@ -121,77 +165,96 @@ function ModelOption({
);
}
+ function onClickGear(e) {
+ e.stopPropagation();
+ e.preventDefault();
+
+ ideMessenger.post("openConfigJson", undefined);
+ }
+
+ function handleOptionClick(e) {
+ if (showMissingApiKeyMsg) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }
+
return (
{
- setHovered(true);
- }}
- onMouseLeave={() => {
- setHovered(false);
- }}
+ isDisabled={showMissingApiKeyMsg}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ onClick={handleOptionClick}
>
-
-
-
-
{option.title}
+
+
+
+
+ {option.title}
+
+
+
+ {showDelete && (
+
+ )}
+
-
+ {showMissingApiKeyMsg && (
+
+ Missing API key
+
+ )}
);
}
-function modelSelectTitle(model: any): string {
- if (model?.title) return model?.title;
- if (model?.model !== undefined && model?.model.trim() !== "") {
- if (model?.class_name) {
- return `${model?.class_name} - ${model?.model}`;
- }
- return model?.model;
- }
- return model?.class_name;
-}
-
-interface Option {
- value: string;
- title: string;
-}
-
function ModelSelect() {
const dispatch = useDispatch();
const defaultModel = useSelector(defaultModelSelector);
const allModels = useSelector(
(state: RootState) => state.state.config.models,
);
-
- const navigate = useNavigate();
-
+ const ideMessenger = useContext(IdeMessengerContext);
+ const [showAbove, setShowAbove] = useState(false);
+ const buttonRef = useRef
(null);
const [options, setOptions] = useState([]);
-
+ const [sortedOptions, setSortedOptions] = useState ([]);
const selectedProfileId = useSelector(
(store: RootState) => store.state.selectedProfileId,
);
+ // Sort so that options without an API key are at the end
+ useEffect(() => {
+ const enabledOptions = options.filter((option) => option.apiKey !== "");
+ const disabledOptions = options.filter((option) => option.apiKey === "");
+
+ const sorted = [...enabledOptions, ...disabledOptions];
+
+ setSortedOptions(sorted);
+ }, [options]);
+
useEffect(() => {
setOptions(
allModels.map((model) => {
return {
value: model.title,
title: modelSelectTitle(model),
+ apiKey: model.apiKey,
};
}),
);
}, [allModels]);
+ useEffect(() => {
+ const handleResize = () => calculatePosition();
+ window.addEventListener("resize", handleResize);
+ return () => window.removeEventListener("resize", handleResize);
+ }, []);
+
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "'" && isMetaEquivalentKeyPressed(event)) {
@@ -211,27 +274,34 @@ function ModelSelect() {
};
}, [options, defaultModel]);
- const ideMessenger = useContext(IdeMessengerContext);
+ function calculatePosition() {
+ const rect = buttonRef.current.getBoundingClientRect();
+ const spaceBelow = window.innerHeight - rect.bottom;
+ const spaceAbove = rect.top;
+ const dropdownHeight = MAX_HEIGHT_PX;
- const [showAbove, setShowAbove] = useState(false);
- const buttonRef = useRef(null);
+ setShowAbove(spaceBelow < dropdownHeight && spaceAbove > spaceBelow);
+ }
- const calculatePosition = () => {
+ function onClickAddModel(e) {
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Close the dropdown
if (buttonRef.current) {
- const rect = buttonRef.current.getBoundingClientRect();
- const spaceBelow = window.innerHeight - rect.bottom;
- const spaceAbove = rect.top;
- const dropdownHeight = MAX_HEIGHT_PX;
-
- setShowAbove(spaceBelow < dropdownHeight && spaceAbove > spaceBelow);
+ buttonRef.current.click();
}
- };
-
- useEffect(() => {
- const handleResize = () => calculatePosition();
- window.addEventListener("resize", handleResize);
- return () => window.removeEventListener("resize", handleResize);
- }, []);
+ dispatch(setShowDialog(true));
+ dispatch(
+ setDialogMessage(
+ {
+ dispatch(setShowDialog(false));
+ }}
+ />,
+ ),
+ );
+ }
return (
-
-
- {options.map((option, idx) => (
+
+
+ {sortedOptions.map((option, idx) => (
1}
+ showMissingApiKeyMsg={option.apiKey === ""}
/>
))}
@@ -268,37 +339,26 @@ function ModelSelect() {
{selectedProfileId === "local" && (
<>
- {options.length > 0 &&
}
+ {options.length > 0 &&
}
{
- e.stopPropagation();
- e.preventDefault();
- navigate("/addModel");
- }}
+ onClick={onClickAddModel}
value={"addModel" as any}
>
-
+
- Add Model
+ Add Chat model
>
)}
-
+
-
- {getMetaKeyLabel()}' to toggle
-
+
+ {getMetaKeyLabel()} + ' to toggle
+
diff --git a/gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx
similarity index 60%
rename from gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx
rename to gui/src/components/modelSelection/ModelSelectionListbox.tsx
index 9a187fd2a..fd732d163 100644
--- a/gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx
+++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx
@@ -1,30 +1,114 @@
import { Transition } from "@headlessui/react";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/24/outline";
import { Dispatch, Fragment, SetStateAction } from "react";
-
+import { Listbox } from "@headlessui/react";
+import styled from "styled-components";
import {
- StyledListbox,
- StyledListboxButton,
- StyledListboxOption,
- StyledListboxOptions,
-} from "./StyledListbox";
+ defaultBorderRadius,
+ lightGray,
+ vscBackground,
+ vscButtonBackground,
+ vscForeground,
+ vscInputBackground,
+ vscListActiveBackground,
+ vscListActiveForeground,
+} from "..";
+
+export const StyledListbox = styled(Listbox)`
+ background-color: ${vscBackground};
+`;
+
+export const StyledListboxButton = styled(Listbox.Button)`
+ cursor: pointer;
+ background-color: ${vscBackground};
+ text-align: left;
+
+ padding-left: 0.75rem;
+ padding-right: 2.5rem;
+ padding-top: 0.5rem;
+ padding-bottom: 0.5rem;
+
+ border-radius: 0.5em;
+ border: 1px solid ${lightGray};
+
+ margin: 0;
+ height: 100%;
+ width: 100%;
+
+ position: relative;
+
+ display: grid;
+ grid-template-columns: 1fr auto;
+ align-items: center;
+
+ color: ${vscForeground};
+
+ &:focus {
+ outline: none;
+ }
+
+ &:hover {
+ background-color: ${vscInputBackground};
+ }
+`;
+
+export const StyledListboxOptions = styled(Listbox.Options)`
+ background-color: ${vscInputBackground};
+ padding: 0;
+
+ position: absolute;
+ top: 100%;
+ left: 0;
+ right: 0;
+
+ margin-top: 0.25rem;
+
+ max-height: 15rem;
+ overflow: auto;
+
+ border-radius: ${defaultBorderRadius};
+ overflow-y: scroll;
+ z-index: 10;
+
+ &:focus {
+ outline: none;
+ }
+`;
+
+export const StyledListboxOption = styled(Listbox.Option)<{
+ selected: boolean;
+}>`
+ background-color: ${({ selected }) =>
+ selected ? vscListActiveBackground : vscInputBackground};
+ cursor: pointer;
+ padding: 6px 8px;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ &:hover {
+ background-color: ${vscListActiveBackground};
+ color: ${vscListActiveForeground};
+ }
+`;
interface DisplayInfo {
title: string;
icon?: string;
}
-interface QuickSetupListBoxProps {
+interface ModelSelectionListboxProps {
selectedProvider: DisplayInfo;
setSelectedProvider: Dispatch>;
options: DisplayInfo[];
}
-function QuickSetupListBox({
+function ModelSelectionListbox({
selectedProvider,
setSelectedProvider,
options,
-}: QuickSetupListBoxProps) {
+}: ModelSelectionListboxProps) {
return (
@@ -91,4 +175,4 @@ function QuickSetupListBox({
);
}
-export default QuickSetupListBox;
+export default ModelSelectionListbox;
diff --git a/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx b/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx
deleted file mode 100644
index db79a7a9b..000000000
--- a/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { useContext, useState } from "react";
-import { Button, Input, SecondaryButton, vscForeground } from "../..";
-import { IdeMessengerContext } from "../../../context/IdeMessenger";
-import { isJetBrains } from "../../../util";
-import { setLocalStorage } from "../../../util/localStorage";
-
-interface GitHubSignInButtonProps {
- onComplete: (token: string) => void;
-}
-
-function GitHubSignInButton(props: GitHubSignInButtonProps) {
- const ideMessenger = useContext(IdeMessengerContext);
-
- const [jbGhAuthToken, setJbGhAuthToken] = useState("");
-
- return isJetBrains() ? (
-
-
-
{
- ideMessenger.post(
- "openUrl",
- "https://github.com/settings/tokens/new?scopes=user:email&description=Continue%20Free%20Trial%20Token%20",
- );
- }}
- className="grid grid-flow-col items-center gap-2"
- >
-
-
-
- Generate Token
-
-
-
setJbGhAuthToken(e.target.value)}
- />
-
{
- await ideMessenger.request("setGitHubAuthToken", {
- token: jbGhAuthToken,
- });
- setLocalStorage("signedInToGh", true);
- props.onComplete(jbGhAuthToken);
- }}
- >
- Continue
-
-
- ) : (
-
-
{
- const result = await ideMessenger.request(
- "getGitHubAuthToken",
- undefined,
- );
- if (result.status === "success") {
- setLocalStorage("signedInToGh", true);
- props.onComplete(result.content);
- }
- }}
- className="grid grid-flow-col items-center gap-2"
- >
-
-
-
- Sign in with GitHub
-
-
- );
-}
-
-export default GitHubSignInButton;
diff --git a/gui/src/components/modelSelection/quickSetup/QuickModelSetup.tsx b/gui/src/components/modelSelection/quickSetup/QuickModelSetup.tsx
deleted file mode 100644
index 4c12f0a8f..000000000
--- a/gui/src/components/modelSelection/quickSetup/QuickModelSetup.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import { useContext, useEffect, useState } from "react";
-import { FormProvider, useForm } from "react-hook-form";
-import { useDispatch } from "react-redux";
-import { Button, Input, SecondaryButton } from "../..";
-import { IdeMessengerContext } from "../../../context/IdeMessenger";
-import {
- ProviderInfo,
- providers,
-} from "../../../pages/AddNewModel/configs/providers";
-import { setDefaultModel } from "../../../redux/slices/stateSlice";
-import {
- FREE_TRIAL_LIMIT_REQUESTS,
- hasPassedFTL,
-} from "../../../util/freeTrial";
-import QuickSetupListBox from "./QuickSetupListBox";
-
-interface QuickModelSetupProps {
- onDone: () => void;
- hideFreeTrialLimitMessage?: boolean;
-}
-
-function QuickModelSetup(props: QuickModelSetupProps) {
- const [selectedProvider, setSelectedProvider] = useState
(
- providers["openai"]!,
- );
- const [selectedModel, setSelectedModel] = useState(
- selectedProvider.packages[0],
- );
- const formMethods = useForm();
- const dispatch = useDispatch();
- const ideMessenger = useContext(IdeMessengerContext);
-
- useEffect(() => {
- setSelectedModel(selectedProvider.packages[0]);
- }, [selectedProvider]);
-
- const [hasAddedModel, setHasAddedModel] = useState(false);
-
- return (
-
-
- {!props.hideFreeTrialLimitMessage && hasPassedFTL() && (
-
- You've reached the free trial limit of {FREE_TRIAL_LIMIT_REQUESTS}{" "}
- free inputs. To keep using Continue, you can either use your own API
- key, or use a local LLM. To read more about the options, see our{" "}
-
- ideMessenger.post(
- "openUrl",
- "https://docs.continue.dev/setup/overview",
- )
- }
- >
- documentation
-
- .
-
- )}
-
-
1. Select a provider
-
!["freetrial", "openai-aiohttp"].includes(key))
- .map(([, provider]) => provider)}
- >
-
-
2. Select a model
-
provider.title === selectedProvider.title,
- )?.[1].packages
- }
- >
-
- {selectedProvider.apiKeyUrl && (
- <>
-
3. Paste your API key
- {selectedModel.params.model.startsWith("codestral") && (
-
- Note: Codestral requires a different API key from other Mistral
- models
-
- )}
-
{
- let apiKeyUrl = selectedProvider.apiKeyUrl;
- if (selectedModel.params.model.startsWith("codestral")) {
- apiKeyUrl = "https://console.mistral.ai/codestral";
- }
- if (apiKeyUrl) {
- ideMessenger.post("openUrl", apiKeyUrl);
- }
- }}
- >
- Get API Key
-
-
- >
- )}
- {selectedProvider.downloadUrl && (
- <>
-
3. Download {selectedProvider.title}
-
{
- selectedProvider.downloadUrl &&
- ideMessenger.post("openUrl", selectedProvider.downloadUrl);
- }}
- >
- Download {selectedProvider.title}
-
- >
- )}
-
-
- {
- const model = {
- ...selectedProvider.params,
- ...selectedModel.params,
- provider: selectedProvider.provider,
- apiKey: formMethods.watch("apiKey"),
- title: selectedModel.title,
- };
- ideMessenger.post("config/addModel", { model });
- dispatch(setDefaultModel({ title: model.title, force: true }));
- setHasAddedModel(true);
- }}
- className="w-full"
- >
- Add Model
-
-
- Done
-
-
-
-
- );
-}
-
-export default QuickModelSetup;
diff --git a/gui/src/components/modelSelection/quickSetup/StyledListbox.tsx b/gui/src/components/modelSelection/quickSetup/StyledListbox.tsx
deleted file mode 100644
index ee40afa31..000000000
--- a/gui/src/components/modelSelection/quickSetup/StyledListbox.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { Listbox } from "@headlessui/react";
-import styled from "styled-components";
-import {
- defaultBorderRadius,
- vscBackground,
- vscButtonBackground,
- vscForeground,
- vscInputBackground,
- vscListActiveBackground,
- vscListActiveForeground,
-} from "../..";
-
-export const StyledListbox = styled(Listbox)`
- background-color: ${vscBackground};
-`;
-
-export const StyledListboxButton = styled(Listbox.Button)`
- cursor: pointer;
- background-color: ${vscBackground};
- text-align: left;
-
- padding-left: 0.75rem;
- padding-right: 2.5rem;
- padding-top: 0.5rem;
- padding-bottom: 0.5rem;
-
- border-radius: 0.5em;
- border: 1px solid ${vscButtonBackground};
-
- margin: 0;
- height: 100%;
- width: 100%;
-
- position: relative;
-
- display: grid;
- grid-template-columns: 1fr auto;
- align-items: center;
-
- color: ${vscForeground};
-
- &:focus {
- outline: none;
- }
-
- &:hover {
- background-color: ${vscInputBackground};
- }
-`;
-
-export const StyledListboxOptions = styled(Listbox.Options)`
- background-color: ${vscInputBackground};
- padding: 0;
-
- position: absolute;
- top: 100%;
- left: 0;
- right: 0;
-
- margin-top: 0.25rem;
-
- max-height: 15rem;
- overflow: auto;
-
- border-radius: ${defaultBorderRadius};
- overflow-y: scroll;
- z-index: 10;
-
- &:focus {
- outline: none;
- }
-`;
-
-export const StyledListboxOption = styled(Listbox.Option)<{
- selected: boolean;
-}>`
- background-color: ${({ selected }) =>
- selected ? vscListActiveBackground : vscInputBackground};
- cursor: pointer;
- padding: 6px 8px;
-
- display: flex;
- gap: 8px;
- align-items: center;
-
- &:hover {
- background-color: ${vscListActiveBackground};
- color: ${vscListActiveForeground};
- }
-`;
diff --git a/gui/src/continue_arrow.png b/gui/src/continue_arrow.png
deleted file mode 100644
index 3b16ddf9b..000000000
Binary files a/gui/src/continue_arrow.png and /dev/null differ
diff --git a/gui/src/forms/AddModelForm.tsx b/gui/src/forms/AddModelForm.tsx
new file mode 100644
index 000000000..ddb29799d
--- /dev/null
+++ b/gui/src/forms/AddModelForm.tsx
@@ -0,0 +1,214 @@
+import { ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline";
+import { useContext, useEffect, useState } from "react";
+import { FormProvider, useForm } from "react-hook-form";
+import { useDispatch } from "react-redux";
+import { Button, Input, InputSubtext, StyledActionButton } from "../components";
+import AddModelButtonSubtext from "../components/AddModelButtonSubtext";
+import Alert from "../components/gui/Alert";
+import ModelSelectionListbox from "../components/modelSelection/ModelSelectionListbox";
+import { IdeMessengerContext } from "../context/IdeMessenger";
+import {
+ ProviderInfo,
+ providers,
+} from "../pages/AddNewModel/configs/providers";
+import { setDefaultModel } from "../redux/slices/stateSlice";
+import { FREE_TRIAL_LIMIT_REQUESTS, hasPassedFTL } from "../util/freeTrial";
+
+interface QuickModelSetupProps {
+ onDone: () => void;
+ hideFreeTrialLimitMessage?: boolean;
+}
+
+function AddModelForm({
+ onDone,
+ hideFreeTrialLimitMessage,
+}: QuickModelSetupProps) {
+ const [selectedProvider, setSelectedProvider] = useState(
+ providers["openai"]!,
+ );
+
+ const [selectedModel, setSelectedModel] = useState(
+ selectedProvider.packages[0],
+ );
+
+ const formMethods = useForm();
+ const dispatch = useDispatch();
+ const ideMessenger = useContext(IdeMessengerContext);
+
+ const selectedProviderApiKeyUrl = selectedModel.params.model.startsWith(
+ "codestral",
+ )
+ ? "https://console.mistral.ai/codestral"
+ : selectedProvider.apiKeyUrl;
+
+ function isDisabled() {
+ if (
+ selectedProvider.downloadUrl ||
+ selectedProvider.provider === "free-trial"
+ ) {
+ return false;
+ }
+
+ const apiKey = formMethods.watch("apiKey");
+ return typeof apiKey === "undefined" || apiKey.length === 0;
+ }
+
+ useEffect(() => {
+ setSelectedModel(selectedProvider.packages[0]);
+ }, [selectedProvider]);
+
+ function onSubmit() {
+ const apiKey = formMethods.watch("apiKey");
+ const hasValidApiKey = apiKey !== undefined && apiKey !== "";
+
+ const model = {
+ ...selectedProvider.params,
+ ...selectedModel.params,
+ provider: selectedProvider.provider,
+ title: selectedModel.title,
+ ...(hasValidApiKey ? { apiKey } : {}),
+ };
+
+ ideMessenger.post("config/addModel", { model });
+ ideMessenger.post("openConfigJson", undefined);
+
+ dispatch(setDefaultModel({ title: model.title, force: true }));
+
+ onDone();
+ }
+
+ function onClickDownloadProvider() {
+ selectedProvider.downloadUrl &&
+ ideMessenger.post("openUrl", selectedProvider.downloadUrl);
+ }
+
+ return (
+
+
+
+ );
+}
+
+export default AddModelForm;
diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts
index fa7e01945..34bcdafa5 100644
--- a/gui/src/hooks/useChatHandler.ts
+++ b/gui/src/hooks/useChatHandler.ts
@@ -282,10 +282,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
);
}
} catch (e: any) {
- console.log("Continue: error streaming response: ", e);
- ideMessenger.post("errorPopup", {
- message: `Error streaming response: ${e.message}`,
- });
+ console.debug("Error streaming response: ", e);
+ ideMessenger.post("showToast", [
+ "error",
+ `Error streaming response: ${e.message}`,
+ ]);
} finally {
dispatch(setInactive());
}
diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx
index 1c79fe0c6..d33abc660 100644
--- a/gui/src/hooks/useSubmenuContextProviders.tsx
+++ b/gui/src/hooks/useSubmenuContextProviders.tsx
@@ -6,11 +6,13 @@ import {
groupByLastNPathParts,
} from "core/util";
import MiniSearch, { SearchResult } from "minisearch";
-import { useContext, useEffect, useMemo, useState } from "react";
+import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { selectContextProviderDescriptions } from "../redux/selectors";
import { useWebviewListener } from "./useWebviewListener";
+import { WebviewMessengerResult } from "core/protocol/util";
+import { getLocalStorage } from "../util/localStorage";
const MINISEARCH_OPTIONS = {
prefix: true,
@@ -32,28 +34,37 @@ function useSubmenuContextProviders() {
);
const [loaded, setLoaded] = useState(false);
+ const [initialLoadComplete, setInitialLoadComplete] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+ const [autoLoadTriggered, setAutoLoadTriggered] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
- async function getOpenFileItems() {
- const openFiles = await ideMessenger.ide.getOpenFiles();
- const openFileGroups = groupByLastNPathParts(openFiles, 2);
+ const memoizedGetOpenFileItems = useMemo(() => {
+ return async () => {
+ const openFiles = await ideMessenger.ide.getOpenFiles();
+ const openFileGroups = groupByLastNPathParts(openFiles, 2);
- return openFiles.map((file) => {
- return {
+ return openFiles.map((file) => ({
id: file,
title: getBasename(file),
description: getUniqueFilePath(file, openFileGroups),
providerTitle: "file",
- };
- });
- }
+ }));
+ };
+ }, [ideMessenger]);
useWebviewListener("refreshSubmenuItems", async (data) => {
- setLoaded(false);
+ console.debug("refreshSubmenuItems called with data:", data);
+ if (!isLoading) {
+ setLoaded(false);
+ setInitialLoadComplete(false);
+ setAutoLoadTriggered((prev) => !prev); // Toggle to trigger effect
+ }
});
useWebviewListener("updateSubmenuItems", async (data) => {
+ console.debug("updateSubmenuItems called with data:", data);
const minisearch = new MiniSearch({
fields: ["title", "description"],
storeFields: ["id", "title", "description"],
@@ -64,7 +75,7 @@ function useSubmenuContextProviders() {
setMinisearches((prev) => ({ ...prev, [data.provider]: minisearch }));
if (data.provider === "file") {
- const openFiles = await getOpenFileItems();
+ const openFiles = await memoizedGetOpenFileItems();
setFallbackResults((prev) => ({
...prev,
file: [
@@ -80,17 +91,21 @@ function useSubmenuContextProviders() {
}
});
- function addItem(providerTitle: string, item: ContextSubmenuItem) {
- if (!minisearches[providerTitle]) {
- return;
- }
- minisearches[providerTitle].add(item);
- }
+ const addItem = useCallback(
+ (providerTitle: string, item: ContextSubmenuItem) => {
+ if (!minisearches[providerTitle]) {
+ return;
+ }
+ minisearches[providerTitle].add(item);
+ },
+ [minisearches],
+ );
useEffect(() => {
- // Refresh open files periodically
- const interval = setInterval(async () => {
- const openFiles = await getOpenFileItems();
+ let isMounted = true;
+ const refreshOpenFiles = async () => {
+ if (!isMounted) return;
+ const openFiles = await memoizedGetOpenFileItems();
setFallbackResults((prev) => ({
...prev,
file: deduplicateArray(
@@ -98,12 +113,17 @@ function useSubmenuContextProviders() {
(a, b) => a.id === b.id,
),
}));
- }, 2_000);
+ };
+
+ const interval = setInterval(refreshOpenFiles, 2000);
+
+ refreshOpenFiles(); // Initial call
return () => {
+ isMounted = false;
clearInterval(interval);
};
- }, []);
+ }, [memoizedGetOpenFileItems]);
const getSubmenuSearchResults = useMemo(
() =>
@@ -165,89 +185,172 @@ function useSubmenuContextProviders() {
"Limit:",
limit,
);
+ console.debug("Current fallbackResults:", fallbackResults);
+ console.debug("Current minisearches:", Object.keys(minisearches));
- const results = getSubmenuSearchResults(providerTitle, query);
- if (results.length === 0) {
- const fallbackItems = (fallbackResults[providerTitle] ?? [])
- .slice(0, limit)
- .map((result) => {
- return {
- ...result,
- providerTitle,
- };
- });
- console.debug("Using fallback results:", fallbackItems.length);
- return fallbackItems;
+ if (!initialLoadComplete) {
+ console.debug("Initial load not complete, returning loading state");
+ return [
+ {
+ id: "loading",
+ title: "Loading...",
+ description: "Please wait while items are being loaded",
+ providerTitle: providerTitle || "unknown",
+ },
+ ];
+ }
+
+ try {
+ const results = getSubmenuSearchResults(providerTitle, query);
+ if (results.length === 0) {
+ const fallbackItems = (fallbackResults[providerTitle] ?? [])
+ .slice(0, limit)
+ .map((result) => {
+ return {
+ ...result,
+ providerTitle,
+ };
+ });
+ console.debug("Using fallback results:", fallbackItems.length);
+ console.debug("Fallback items:", fallbackItems);
+ return fallbackItems;
+ }
+ const limitedResults = results.slice(0, limit).map((result) => {
+ return {
+ id: result.id,
+ title: result.title,
+ description: result.description,
+ providerTitle: result.providerTitle,
+ };
+ });
+ return limitedResults;
+ } catch (error) {
+ console.error("Error in getSubmenuContextItems:", error);
+ return [];
}
- const limitedResults = results.slice(0, limit).map((result) => {
- return {
- id: result.id,
- title: result.title,
- description: result.description,
- providerTitle: result.providerTitle,
- };
- });
- return limitedResults;
},
- [fallbackResults, getSubmenuSearchResults],
+ [fallbackResults, getSubmenuSearchResults, initialLoadComplete],
);
useEffect(() => {
- if (contextProviderDescriptions.length === 0 || loaded) {
+ if (contextProviderDescriptions.length === 0 || loaded || isLoading) {
return;
}
setLoaded(true);
+ setIsLoading(true);
const loadSubmenuItems = async () => {
- for (const description of contextProviderDescriptions) {
- const minisearch = new MiniSearch({
- fields: ["title", "description"],
- storeFields: ["id", "title", "description"],
- });
- const result = await ideMessenger.request("context/loadSubmenuItems", {
- title: description.title,
- });
+ console.debug("Starting loadSubmenuItems");
+ console.debug(
+ "contextProviderDescriptions:",
+ contextProviderDescriptions,
+ );
- if (result.status === "error") {
- continue;
- }
- const items = result.content;
+ try {
+ const disableIndexing = getLocalStorage("disableIndexing") ?? false;
- try {
- minisearch.addAll(items);
- } catch (itemError) {
- console.error(
- "Error adding item to minisearch:",
- itemError.message,
- itemError.stack,
- );
- }
+ await Promise.all(
+ contextProviderDescriptions.map(async (description) => {
+ const shouldSkipProvider =
+ description.dependsOnIndexing && disableIndexing;
- setMinisearches((prev) => ({
- ...prev,
- [description.title]: minisearch,
- }));
+ if (shouldSkipProvider) {
+ console.debug(
+ `Skipping ${description.title} provider due to disabled indexing`,
+ );
+ return;
+ }
- if (description.title === "file") {
- const openFiles = await getOpenFileItems();
- setFallbackResults((prev) => ({
- ...prev,
- file: [
- ...openFiles,
- ...items.slice(0, MAX_LENGTH - openFiles.length),
- ],
- }));
- } else {
- setFallbackResults((prev) => ({
- ...prev,
- [description.title]: items.slice(0, MAX_LENGTH),
- }));
- }
+ console.debug(`Processing provider: ${description.title}`);
+
+ try {
+ const minisearch = new MiniSearch({
+ fields: ["title", "description"],
+ storeFields: ["id", "title", "description"],
+ });
+ console.debug(`Requesting items for ${description.title}`);
+ const result = (await ideMessenger.request(
+ "context/loadSubmenuItems",
+ {
+ title: description.title,
+ },
+ )) as WebviewMessengerResult<"context/loadSubmenuItems">;
+
+ console.debug(
+ `Received result for ${description.title}:`,
+ result,
+ );
+
+ if (result.status === "error") {
+ console.error(
+ `Error loading items for ${description.title}:`,
+ result.error,
+ );
+ return;
+ }
+ const items = result.content;
+
+ console.debug(
+ `Adding ${items.length} items to minisearch for ${description.title}`,
+ );
+ minisearch.addAll(items);
+
+ console.debug(`Updating minisearches for ${description.title}`);
+ setMinisearches((prev) => ({
+ ...prev,
+ [description.title]: minisearch,
+ }));
+
+ if (description.title === "file") {
+ console.debug("Processing file provider");
+ const openFiles = await memoizedGetOpenFileItems();
+ console.debug(`Got ${openFiles.length} open files`);
+ setFallbackResults((prev) => ({
+ ...prev,
+ file: [
+ ...openFiles,
+ ...items.slice(0, MAX_LENGTH - openFiles.length),
+ ],
+ }));
+ } else {
+ console.debug(
+ `Updating fallbackResults for ${description.title}`,
+ );
+ setFallbackResults((prev) => ({
+ ...prev,
+ [description.title]: items.slice(0, MAX_LENGTH),
+ }));
+ }
+ } catch (error) {
+ console.error(`Error processing ${description.title}:`, error);
+ console.error(
+ "Error details:",
+ JSON.stringify(error, Object.getOwnPropertyNames(error)),
+ );
+ }
+ }),
+ );
+ } catch (error) {
+ console.error("Error in loadSubmenuItems:", error);
+ } finally {
+ console.debug("Finished loadSubmenuItems");
+ console.debug("Final minisearches:", Object.keys(minisearches));
+ console.debug("Final fallbackResults:", Object.keys(fallbackResults));
+ setInitialLoadComplete(true);
+ setIsLoading(false);
}
};
- loadSubmenuItems();
- }, [contextProviderDescriptions, loaded]);
+ loadSubmenuItems()
+ .then(() => {
+ console.debug("loadSubmenuItems completed successfully");
+ })
+ .catch((error) => {
+ console.error("Error in loadSubmenuItems:", error);
+ setInitialLoadComplete(true);
+ setIsLoading(false);
+ });
+ }, [contextProviderDescriptions, loaded, autoLoadTriggered]);
useWebviewListener("configUpdate", async () => {
// When config is updated (for example switching to a different workspace)
diff --git a/gui/src/hooks/useTutorialCard.ts b/gui/src/hooks/useTutorialCard.ts
new file mode 100644
index 000000000..2fcbca038
--- /dev/null
+++ b/gui/src/hooks/useTutorialCard.ts
@@ -0,0 +1,32 @@
+import { useState } from "react";
+import { getLocalStorage, setLocalStorage } from "../util/localStorage";
+import { usePostHog } from "posthog-js/react";
+
+export type UseTutorialCard = {
+ showTutorialCard: boolean;
+ closeTutorialCard: () => void;
+ openTutorialCard: () => void;
+};
+
+export function useTutorialCard(): UseTutorialCard {
+ const posthog = usePostHog();
+
+ const [showTutorialCard, setShowTutorialCard] = useState(
+ getLocalStorage("showTutorialCard"),
+ );
+
+ function closeTutorialCard() {
+ posthog.capture("closedTutorialCard");
+ setLocalStorage("showTutorialCard", false);
+ setShowTutorialCard(false);
+ }
+
+ function openTutorialCard() {
+ setLocalStorage("showTutorialCard", true);
+ setShowTutorialCard(true);
+ }
+
+ return { showTutorialCard, closeTutorialCard, openTutorialCard };
+}
+
+export default UseTutorialCard;
diff --git a/gui/src/hooks/useVscTheme.ts b/gui/src/hooks/useVscTheme.ts
index 4a28f945c..959142ba6 100644
--- a/gui/src/hooks/useVscTheme.ts
+++ b/gui/src/hooks/useVscTheme.ts
@@ -54,7 +54,7 @@ const hljsToTextMate: Record = {
};
function constructTheme(
- tmTheme: typeof window.fullColorTheme
+ tmTheme: typeof window.fullColorTheme,
): Record {
const rules = tmTheme["rules"] || [];
@@ -151,7 +151,7 @@ function fallbackTheme() {
export function useVscTheme() {
const [theme, setTheme] = useState(
- constructTheme(window.fullColorTheme || {})
+ constructTheme(window.fullColorTheme || {}),
);
useWebviewListener("setTheme", async (data) => {
diff --git a/gui/src/index.css b/gui/src/index.css
index 8511531f3..090ee88fc 100644
--- a/gui/src/index.css
+++ b/gui/src/index.css
@@ -19,18 +19,8 @@ body,
#root {
height: 100%;
background-color: var(--vscode-editor-background);
- font-family:
- system-ui,
- -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- Roboto,
- Oxygen,
- Ubuntu,
- Cantarell,
- "Open Sans",
- "Helvetica Neue",
- sans-serif;
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
+ Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body {
diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts
index 4763f77ff..c261568eb 100644
--- a/gui/src/pages/AddNewModel/configs/models.ts
+++ b/gui/src/pages/AddNewModel/configs/models.ts
@@ -67,6 +67,7 @@ export const models: { [key: string]: ModelPackage } = {
"together",
"llama.cpp",
"replicate",
+ "sambanova",
],
isOpenSource: true,
},
@@ -454,7 +455,7 @@ export const models: { [key: string]: ModelPackage } = {
codestral: {
title: "Codestral",
description:
- "Codestral is an advanced generative model created by Mistral AI, tailored for coding tasks like fill-in-the-middle and code completion. Trained on more than 80 programming languages, Codestral demonstrates proficiency in both widely-used and less-common languages.",
+ "Codestral is an advanced generative model created by Mistral AI, tailored for coding tasks like fill-in-the-middle and code completion.",
params: {
title: "Codestral",
model: "codestral-latest",
@@ -741,7 +742,7 @@ export const models: { [key: string]: ModelPackage } = {
params: {
model: "ibm/granite-20b-code-instruct",
contextLength: 20_000,
- title: "watsonx - Granite Code 20b"
+ title: "watsonx - Granite Code 20b",
},
providerOptions: ["watsonx"],
icon: "watsonx.png",
diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts
index e82a81753..4ba859a47 100644
--- a/gui/src/pages/AddNewModel/configs/providers.ts
+++ b/gui/src/pages/AddNewModel/configs/providers.ts
@@ -165,7 +165,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
],
},
mistral: {
- title: "Mistral API",
+ title: "Mistral",
provider: "mistral",
description:
"The Mistral API provides seamless access to their models, including Codestral, Mistral 8x22B, Mistral Large, and more.",
@@ -202,7 +202,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
description:
"One of the fastest ways to get started with local models on Mac, Linux, or Windows",
longDescription:
- 'To get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model="codellama:7b-instruct"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.',
+ 'To get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/download) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model="codellama:7b-instruct"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.',
icon: "ollama.png",
tags: [ModelProviderTags.Local, ModelProviderTags.OpenSource],
packages: [
@@ -219,7 +219,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
...completionParamsInputsConfigs,
{ ...apiBaseInput, defaultValue: "http://localhost:11434" },
],
- downloadUrl: "https://ollama.ai/",
+ downloadUrl: "https://ollama.ai/download",
},
cohere: {
title: "Cohere",
@@ -490,28 +490,35 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
key: "watsonxUrl",
label: "watsonx URL",
placeholder: "e.g. http://us-south.dataplatform.cloud.ibm.com",
- required: true
+ required: true,
},
{
inputType: "text",
key: "watsonxProjectId",
label: "watsonx Project ID",
placeholder: "Enter your project ID",
- required: true
+ required: true,
},
{
inputType: "text",
key: "watsonxCreds",
label: "watsonx API key",
placeholder: "Enter your API key (SaaS) or ZenApiKey (Software)",
- required: true
+ required: true,
},
{
inputType: "text",
key: "watsonxApiVersion",
label: "watsonx API version",
placeholder: "Enter the API Version",
- defaultValue: "2023-05-29"
+ defaultValue: "2023-05-29",
+ },
+ {
+ inputType: "text",
+ key: "watsonxFullUrl",
+ label: "Full watsonx URL",
+ placeholder: "http://us-south.dataplatform.cloud.ibm.com/m1/v1/text/generation_stream?version=2023-05-29",
+ required: false
},
// {
// inputType: "text",
@@ -573,4 +580,34 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
],
collectInputFor: [...completionParamsInputsConfigs],
},
+ sambanova: {
+ title: "SambaNova Cloud",
+ provider: "sambanova",
+ refPage: "sambanova",
+ description:
+ "Use SambaNova Cloud for Llama3.1 fast inference performance",
+ icon: "sambanova.png",
+ longDescription: `The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can sign up [here](https://cloud.sambanova.ai/)`,
+ tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
+ params: {
+ apiKey: "",
+ },
+ collectInputFor: [
+ {
+ inputType: "text",
+ key: "apiKey",
+ label: "API Key",
+ placeholder: "Enter your SambaNova Cloud API key",
+ required: true,
+ },
+ ...completionParamsInputsConfigs,
+ ],
+ packages: [
+ models.llama31Chat,
+ ].map((p) => {
+ p.params.contextLength = 4096;
+ return p;
+ }),
+ apiKeyUrl: "https://cloud.sambanova.ai/apis",
+ },
};
diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx
index 6460b6a59..5f00d93e6 100644
--- a/gui/src/pages/gui.tsx
+++ b/gui/src/pages/gui.tsx
@@ -17,7 +17,6 @@ import {
} from "react";
import { ErrorBoundary } from "react-error-boundary";
import { useDispatch, useSelector } from "react-redux";
-import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import {
Button,
@@ -32,9 +31,13 @@ import TimelineItem from "../components/gui/TimelineItem";
import ContinueInputBox from "../components/mainInput/ContinueInputBox";
import { defaultInputModifiers } from "../components/mainInput/inputModifiers";
import { TutorialCard } from "../components/mainInput/TutorialCard";
+import OnboardingCard, {
+ useOnboardingCard,
+} from "../components/OnboardingCard";
import { IdeMessengerContext } from "../context/IdeMessenger";
import useChatHandler from "../hooks/useChatHandler";
import useHistory from "../hooks/useHistory";
+import { useTutorialCard } from "../hooks/useTutorialCard";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import {
@@ -93,24 +96,10 @@ const StepsDiv = styled.div`
position: relative;
}
- // Gray, vertical line on the left ("thread")
- // &::before {
- // content: "";
- // position: absolute;
- // height: calc(100% - 12px);
- // border-left: 2px solid ${lightGray};
- // left: 28px;
- // z-index: 0;
- // bottom: 12px;
- // }
-
.thread-message {
margin: 8px 4px 0 4px;
padding-bottom: 8px;
}
- // .thread-message:not(:first-child) {
- // border-top: 1px solid ${lightGray}22;
- // }
`;
const NewSessionButton = styled.div`
@@ -155,9 +144,11 @@ function fallbackRender({ error, resetErrorBoundary }: any) {
function GUI() {
const posthog = usePostHog();
const dispatch = useDispatch();
- const navigate = useNavigate();
const ideMessenger = useContext(IdeMessengerContext);
+ const onboardingCard = useOnboardingCard();
+ const { showTutorialCard, closeTutorialCard } = useTutorialCard();
+
const sessionState = useSelector((state: RootState) => state.state);
const defaultModel = useSelector(defaultModelSelector);
@@ -174,16 +165,6 @@ function GUI() {
const state = useSelector((state: RootState) => state.state);
- const [showTutorialCard, setShowTutorialCard] = useState(
- getLocalStorage("showTutorialCard") ?? true,
- );
-
- const onCloseTutorialCard = () => {
- posthog.capture("closedTutorialCard");
- setLocalStorage("showTutorialCard", false);
- setShowTutorialCard(false);
- };
-
const handleScroll = () => {
// Temporary fix to account for additional height when code blocks are added
const OFFSET_HERUISTIC = 300;
@@ -237,8 +218,12 @@ function GUI() {
setLocalStorage("ftc", u + 1);
if (u >= FREE_TRIAL_LIMIT_REQUESTS) {
- navigate("/onboarding");
+ 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;
}
} else {
@@ -508,9 +493,15 @@ function GUI() {
) : null}
- {!!showTutorialCard && (
+ {onboardingCard.show && (
+
+
+
+ )}
+
+ {showTutorialCard !== false && !onboardingCard.open && (
-
+
)}
>
diff --git a/gui/src/pages/history.tsx b/gui/src/pages/history.tsx
index 47744fd7f..f81dd1769 100644
--- a/gui/src/pages/history.tsx
+++ b/gui/src/pages/history.tsx
@@ -404,6 +404,11 @@ function History() {
This Month
)}
+ {date < lastMonth && prevDate > lastMonth && (
+
+ Older
+
+ )}
void;
+ href?: string;
+}
+
+function MoreActionRow({
+ title,
+ description,
+ buttonText,
+ onClick,
+ href,
+}: MoreActionRowProps) {
+ const ButtonOrLink = href ? "a" : "div";
+ const buttonProps = href
+ ? { href, target: "_blank", className: "no-underline w-1/2" }
+ : { className: "w-1/2" };
+
+ return (
+
+
+
{title}
+
{description}
+
+
+
+ {buttonText}
+
+
+
+ );
+}
function MorePage() {
useNavigationListener();
+
+ const dispatch = useDispatch();
const navigate = useNavigate();
const ideMessenger = useContext(IdeMessengerContext);
+ const { saveSession } = useHistory(dispatch);
const [indexingState, setIndexingState] = useState({
desc: "Loading indexing config",
@@ -44,7 +88,7 @@ function MorePage() {
Codebase Indexing
-
-
-
Documentation
-
- Visit the documentation site to learn how to configure and use
- Continue.
-
-
-
- View docs
-
-
+
-
-
-
Tutorial
-
- Open the tutorial to get a quick walkthrough of the most commonly
- used features in Continue.
-
-
-
{
- ideMessenger.post("showTutorial", undefined);
- }}
- >
- Open tutorial
-
-
+
{
+ navigate("/");
+ // Used to clear the chat panel before showing onboarding card
+ saveSession();
+ dispatch(setOnboardingCard({ show: true, activeTab: "Best" }));
+ ideMessenger.post("showTutorial", undefined);
+ }}
+ />
-
-
-
Token usage stats
-
- See how many tokens you're using each day and how they're
- distributed across your models.
-
-
-
{
- navigate("/stats");
- }}
- >
- View token usage
-
-
+ navigate("/stats")}
+ />
-
+
-
-
-
Join the community!
-
- Join us on Discord to stay up-to-date on the latest developments
-
-
-
-
- Continue Discord
-
-
-
+
-
-
navigate(-1)}
- className="inline-block cursor-pointer"
- />
-
-
-
-
Model setup
-
- Choose between our default configuration that includes the best models
- available, or configure your own setup.
-
-
-
- {
- setIsBestToggle((prev) => !prev);
- }}
- />
-
- {isBestToggle && }
-
- {!isBestToggle && (
- {
- ideMessenger.post("showTutorial", undefined);
-
- if (getLocalStorage("signedInToGh")) {
- completeOnboarding();
- } else {
- navigate("/apiKeyAutocompleteOnboarding");
- }
- }}
- >
- )}
-
- );
-}
-
-export default ApiKeysOnboarding;
diff --git a/gui/src/pages/onboarding/CheckMarkHeader.tsx b/gui/src/pages/onboarding/CheckMarkHeader.tsx
deleted file mode 100644
index 6e3b27c57..000000000
--- a/gui/src/pages/onboarding/CheckMarkHeader.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { CheckCircleIcon as CheckCircleIconSolid } from "@heroicons/react/24/solid";
-import { lightGray } from "../../components";
-
-export function CheckMarkHeader(props: {
- children: string;
- isComplete: boolean;
-}) {
- return (
-
- {props.isComplete ? (
-
- ) : (
-
- )}
-
{props.children}
-
- );
-}
diff --git a/gui/src/pages/onboarding/CopyToTerminalButton.tsx b/gui/src/pages/onboarding/CopyToTerminalButton.tsx
deleted file mode 100644
index d2c371169..000000000
--- a/gui/src/pages/onboarding/CopyToTerminalButton.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-import ReactDOM from "react-dom";
-import { useState, useContext } from "react";
-import { CheckIcon, CommandLineIcon } from "@heroicons/react/24/outline";
-import styled from "styled-components";
-import {
- StyledTooltip,
- defaultBorderRadius,
- lightGray,
- vscForeground,
-} from "../../components";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-
-export type CopyToTerminalButtonProps = {
- children: string;
-};
-
-const StyledDiv = styled.div<{ clicked: boolean }>`
- padding-left: 8px;
- padding-right: 8px;
- display: flex;
- border-radius: ${defaultBorderRadius};
- width: fit-content;
- gap: 8px;
-
- ${({ clicked }) => clicked && "background-color: #0f02;"}
-
- align-items: center;
-
- border: 1px solid ${lightGray};
-
- cursor: pointer;
- &:hover {
- background-color: ${({ clicked }) => (clicked ? "#0f02" : "#fff1")};
- }
-`;
-
-export function CopyToTerminalButton(props: CopyToTerminalButtonProps) {
- const [clicked, setClicked] = useState(false);
-
- const id = `info-hover-${encodeURIComponent(props.children)}`;
- const tooltipPortalDiv = document.getElementById("tooltip-portal-div");
-
- const ideMessenger = useContext(IdeMessengerContext);
-
- return (
- <>
-
-
{
- ideMessenger.ide.runCommand(props.children);
- setClicked(true);
- setTimeout(() => setClicked(false), 2000);
- ideMessenger.post("copyText", { text: props.children });
- }}
- >
- {clicked ? (
-
- ) : (
-
- )}
-
-
-
- {props.children}
-
-
-
-
- {tooltipPortalDiv &&
- ReactDOM.createPortal(
-
- Copy to terminal
- ,
- tooltipPortalDiv,
- )}
- >
- );
-}
diff --git a/gui/src/pages/onboarding/DefaultModelConfigForm.tsx b/gui/src/pages/onboarding/DefaultModelConfigForm.tsx
deleted file mode 100644
index 9c3940bec..000000000
--- a/gui/src/pages/onboarding/DefaultModelConfigForm.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { useContext, useState } from "react";
-import { useDispatch } from "react-redux";
-import styled from "styled-components";
-import { Input, lightGray } from "../../components";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-import { setDefaultModel } from "../../redux/slices/stateSlice";
-import { models } from "../AddNewModel/configs/models";
-import { providers } from "../AddNewModel/configs/providers";
-import { StyledButton } from "./components";
-import { useCompleteOnboarding } from "./utils";
-
-const HelperText = styled.p`
- font-size: 0.8rem;
- color: ${lightGray};
- margin-top: 0.25rem;
-`;
-
-function DefaultModelConfigForm() {
- const dispatch = useDispatch();
-
- const ideMessenger = useContext(IdeMessengerContext);
-
- const [mistralApiKey, setMistralApiKey] = useState("");
- const [anthropicApiKey, setAnthropicApiKey] = useState("");
-
- const { completeOnboarding } = useCompleteOnboarding();
-
- const isFormComplete = !!mistralApiKey && !!anthropicApiKey;
-
- const { anthropic, mistral } = providers;
- const { claude35Sonnet: chatModel, codestral: autocompleteModel } = models;
-
- async function handleSubmit(e) {
- e.preventDefault();
-
- const chatModelConfig = {
- model: chatModel.params.model,
- provider: anthropic.provider,
- apiKey: anthropicApiKey,
- title: chatModel.params.title,
- };
-
- const autocompleteModelConfig = {
- title: autocompleteModel.params.title,
- provider: mistral.provider,
- model: autocompleteModel.params.model,
- apiKey: mistralApiKey,
- };
-
- ideMessenger.post("config/addModel", { model: chatModelConfig });
-
- dispatch(setDefaultModel({ title: chatModelConfig.title, force: true }));
-
- await ideMessenger.request("addAutocompleteModel", {
- model: autocompleteModelConfig,
- });
-
- ideMessenger.post("showTutorial", undefined);
-
- completeOnboarding();
- }
-
- return (
-
- );
-}
-
-export default DefaultModelConfigForm;
diff --git a/gui/src/pages/onboarding/LocalOnboarding.tsx b/gui/src/pages/onboarding/LocalOnboarding.tsx
deleted file mode 100644
index 04611c553..000000000
--- a/gui/src/pages/onboarding/LocalOnboarding.tsx
+++ /dev/null
@@ -1,229 +0,0 @@
-import { ArrowLeftIcon } from "@heroicons/react/24/outline";
-import { ONBOARDING_LOCAL_MODEL_TITLE } from "core/config/onboarding";
-import { useContext, useEffect, useState } from "react";
-import { useNavigate } from "react-router-dom";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-import { CheckMarkHeader } from "./CheckMarkHeader";
-import { StyledButton } from "./components";
-import { CopyToTerminalButton } from "./CopyToTerminalButton";
-import { useCompleteOnboarding } from "./utils";
-
-type OllamaConnectionStatuses =
- | "waiting_to_download"
- | "downloading"
- | "verified";
-
-enum DefaultLocalModels {
- Chat = "llama3",
- Autocomplete = "starcoder2:3b",
- Embeddings = "nomic-embed-text",
-}
-
-const OLLAMA_DOWNLOAD_URL = "https://ollama.com/download";
-const REFETCH_MODELS_INTERVAL_MS = 1000;
-
-function LocalOnboarding() {
- const navigate = useNavigate();
- const ideMessenger = useContext(IdeMessengerContext);
-
- const [downloadedOllamaModels, setDownloadedOllamaModels] = useState<
- string[] | undefined
- >(undefined);
-
- const [ollamaConnectionStatus, setOllamaConnectionStatus] =
- useState("waiting_to_download");
-
- const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false);
-
- const { completeOnboarding } = useCompleteOnboarding();
-
- const isOllamaConnected = ollamaConnectionStatus === "verified";
-
- function isModelDownloaded(model: string) {
- if (!downloadedOllamaModels) {
- return false;
- }
-
- return downloadedOllamaModels.some(
- (ollamaModel) => ollamaModel.startsWith(model), // We use `startsWith` to ignore trailing tags like `:latest`
- );
- }
-
- function renderOllamaConnectionStatus(status: OllamaConnectionStatuses) {
- switch (status) {
- case "waiting_to_download":
- return (
-
- );
-
- case "downloading":
- return Checking for connection to Ollama...
;
-
- case "verified":
- return <>>;
-
- default:
- return <>>;
- }
- }
-
- /**
- * The first time we detect that a chat model has been loaded,
- * we send an empty request to load it
- */
- useEffect(() => {
- if (!hasLoadedChatModel && isModelDownloaded(DefaultLocalModels.Chat)) {
- ideMessenger.post("llm/complete", {
- completionOptions: {},
- prompt: "",
- title: ONBOARDING_LOCAL_MODEL_TITLE,
- });
-
- setHasLoadedChatModel(true);
- }
- }, [downloadedOllamaModels]);
-
- /**
- * Sets up an interval that runs every `REFETCH_MODELS_INTERVAL_MS`
- * to fetch the list of downloaded models and update state.
- */
- useEffect(() => {
- const fetchDownloadedModels = async () => {
- const models = await ideMessenger.request("llm/listModels", {
- title: ONBOARDING_LOCAL_MODEL_TITLE,
- });
-
- if (Array.isArray(models)) {
- // If we got a response, the connection has been verified
- if (!isOllamaConnected) {
- setOllamaConnectionStatus("verified");
- }
-
- setDownloadedOllamaModels(models);
- }
- };
-
- // Immediately invoke to try to minimize jank if a user already has
- // the models installed. A better fix would be to not load the onboarding
- // steps until we've first checked if the user already has the models installed.
- fetchDownloadedModels();
-
- const interval = setInterval(
- fetchDownloadedModels,
- REFETCH_MODELS_INTERVAL_MS,
- );
-
- return () => {
- clearInterval(interval);
- };
- }, []);
-
- return (
-
-
-
navigate(-1)}
- className="inline-block cursor-pointer"
- />
-
-
-
Set up your local LLM
-
-
-
- 1. Download and start Ollama
-
-
- {renderOllamaConnectionStatus(ollamaConnectionStatus)}
-
-
-
-
- 2. Download a model for chat
-
- {!isModelDownloaded(DefaultLocalModels.Chat) && (
-
-
- We recommend using {DefaultLocalModels.Chat}, the
- latest open-source model trained by Meta.
-
-
-
- {` ollama run ${DefaultLocalModels.Chat}`}
-
-
- )}
-
-
-
-
- 3. Download a model for tab autocomplete
-
-
- {!isModelDownloaded(DefaultLocalModels.Autocomplete) && (
-
-
- We recommend using {DefaultLocalModels.Autocomplete},
- a state-of-the-art 3B parameter autocomplete model trained by
- Hugging Face.
-
-
-
- {`ollama run ${DefaultLocalModels.Autocomplete}`}
-
-
- )}
-
-
-
-
- 4. Download a model for embeddings
-
-
- {!isModelDownloaded(DefaultLocalModels.Embeddings) && (
-
-
- We recommend using {DefaultLocalModels.Embeddings}, a
- 8192 context-length that outperforms OpenAI ada-002{" "}
- and text-embedding-3-small
- on both short and long context tasks.
-
-
-
- {`ollama pull ${DefaultLocalModels.Embeddings}`}
-
-
- )}
-
-
-
-
- Complete onboarding
-
-
-
- );
-}
-
-export default LocalOnboarding;
diff --git a/gui/src/pages/onboarding/Onboarding.tsx b/gui/src/pages/onboarding/Onboarding.tsx
deleted file mode 100644
index a1de9a528..000000000
--- a/gui/src/pages/onboarding/Onboarding.tsx
+++ /dev/null
@@ -1,223 +0,0 @@
-import {
- CheckBadgeIcon,
- Cog6ToothIcon,
- ComputerDesktopIcon,
- GiftIcon,
-} from "@heroicons/react/24/outline";
-import { ToCoreFromIdeOrWebviewProtocol } from "core/protocol/core";
-import { useContext, useEffect, useState } from "react";
-import { useDispatch } from "react-redux";
-import { useNavigate } from "react-router-dom";
-import { lightGray } from "../../components";
-import ConfirmationDialog from "../../components/dialogs/ConfirmationDialog";
-import GitHubSignInButton from "../../components/modelSelection/quickSetup/GitHubSignInButton";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-import {
- setDialogMessage,
- setShowDialog,
-} from "../../redux/slices/uiStateSlice";
-import { isJetBrains } from "../../util";
-import { FREE_TRIAL_LIMIT_REQUESTS, hasPassedFTL } from "../../util/freeTrial";
-import { Div, StyledButton } from "./components";
-import { isNewUserOnboarding, useCompleteOnboarding } from "./utils";
-import { setLocalStorage } from "../../util/localStorage";
-import { usePostHog } from "posthog-js/react";
-
-type OnboardingMode =
- ToCoreFromIdeOrWebviewProtocol["completeOnboarding"][0]["mode"];
-
-function Onboarding() {
- const navigate = useNavigate();
- const dispatch = useDispatch();
- const posthog = usePostHog();
- const ideMessenger = useContext(IdeMessengerContext);
-
- const [hasSignedIntoGh, setHasSignedIntoGh] = useState(false);
- const [selectedOnboardingMode, setSlectedOnboardingMode] = useState<
- OnboardingMode | undefined
- >(undefined);
-
- const { completeOnboarding } = useCompleteOnboarding();
-
- function onSubmit() {
- ideMessenger.post("completeOnboarding", {
- mode: selectedOnboardingMode,
- });
-
- /**
- * "completeOnboarding" above will update the config with our
- * new embeddings provider. If it's not the default local provider,
- * we need to re-index the codebase.
- */
- if (selectedOnboardingMode !== "local") {
- ideMessenger.post("index/forceReIndex", undefined);
- }
-
- switch (selectedOnboardingMode) {
- case "local":
- navigate("/localOnboarding");
- break;
-
- case "apiKeys":
- navigate("/apiKeysOnboarding");
- break;
-
- case "freeTrial":
- completeOnboarding();
- break;
-
- default:
- break;
- }
- }
-
- useEffect(() => {
- if (isNewUserOnboarding()) {
- posthog.capture("Onboarding Step", { status: "Started" });
- setLocalStorage("onboardingStatus", "Started");
- }
- }, []);
-
- return (
-
-
-
Welcome to Continue
-
- Let's find the setup that works best for you. You can update your
- configuration after onboarding by clicking the
-
- icon in the bottom-right corner of Continue.
-
-
-
-
- {(!hasPassedFTL() || isJetBrains()) && (
-
setSlectedOnboardingMode("freeTrial")}
- >
-
-
- Free trial
-
-
- Start your free trial of {FREE_TRIAL_LIMIT_REQUESTS} requests by
- signing into GitHub.
-
-
-
-
- Chat: Llama 3 with Ollama, LM Studio, etc.
-
-
- Embeddings: Nomic Embed
-
-
- Autocomplete: Starcoder2 3B
-
-
-
- {!hasSignedIntoGh && (
-
- setHasSignedIntoGh(true)}
- >
-
- )}
-
- )}
-
setSlectedOnboardingMode("local")}
- >
-
-
- Local models
-
-
- No code will leave your computer, but less powerful models are used.
-
-
-
-
- Chat: Llama 3 with Ollama, LM Studio, etc.
-
-
- Embeddings: Nomic Embed
-
-
- Autocomplete: Starcoder2 3B
-
-
-
-
-
setSlectedOnboardingMode("apiKeys")}
- >
-
-
- Best experience
-
-
- Start with the most powerful models available, or customize your own
- configuration.
-
-
-
-
- Chat: Claude 3.5 Sonnet
-
-
- Embeddings: Voyage Code 2
-
-
- Autocomplete: Codestral
-
-
-
-
-
-
-
-
{
- dispatch(setShowDialog(true));
- dispatch(
- setDialogMessage(
- {
- completeOnboarding();
- }}
- />,
- ),
- );
- }}
- >
- Skip
-
-
- Continue
-
-
-
-
- );
-}
-
-export default Onboarding;
diff --git a/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx b/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx
deleted file mode 100644
index 45f667182..000000000
--- a/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-import { Transition } from "@headlessui/react";
-import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/24/outline";
-import { ModelProvider } from "core";
-import { TRIAL_FIM_MODEL } from "core/config/onboarding";
-import { Fragment, useContext, useState } from "react";
-import { useNavigate } from "react-router-dom";
-import { Button, Input, SecondaryButton } from "../../components";
-import GitHubSignInButton from "../../components/modelSelection/quickSetup/GitHubSignInButton";
-import {
- StyledListbox,
- StyledListboxButton,
- StyledListboxOption,
- StyledListboxOptions,
-} from "../../components/modelSelection/quickSetup/StyledListbox";
-import { IdeMessengerContext } from "../../context/IdeMessenger";
-import { useCompleteOnboarding } from "./utils";
-
-interface AutocompleteOption {
- provider: ModelProvider;
- title: string;
- icon?: string;
-}
-
-const AUTOCOMPLETE_PROVIDER_OPTIONS: AutocompleteOption[] = [
- {
- provider: "free-trial",
- title: "Free Trial (Codestral)",
- // icon: "fireworks.png",
- },
- {
- provider: "fireworks",
- title: "Fireworks AI",
- // icon: "fireworks.png",
- },
- {
- provider: "ollama",
- title: "Ollama",
- icon: "ollama.png",
- },
-];
-
-interface AutocompleteModelDropdownProps {
- selectedProvider: AutocompleteOption;
- setSelectedProvider: any;
-}
-
-function AutocompleteModelDropdown({
- selectedProvider,
- setSelectedProvider,
-}: AutocompleteModelDropdownProps) {
- return (
-
-
-
-
- {window.vscMediaUrl && selectedProvider.icon && (
-
- )}
- {selectedProvider.title}
-
-
-
-
-
-
-
- {AUTOCOMPLETE_PROVIDER_OPTIONS.map((option, index) => (
-
- `relative cursor-default select-none py-2 pl-10 pr-4 ${
- active ? "bg-amber-100 text-amber-900" : "text-gray-900"
- }`
- }
- value={option}
- >
- {({ selected }) => (
- <>
- {window.vscMediaUrl && option.icon && (
-
- )}
- {option.title}
-
- {selected ? (
-
-
-
- ) : null}
- >
- )}
-
- ))}
-
-
-
-
- );
-}
-
-function ApiKeyAutocompleteOnboarding() {
- const ideMessenger = useContext(IdeMessengerContext);
- const navigate = useNavigate();
-
- const [selectedProvider, setSelectedProvider] = useState(
- AUTOCOMPLETE_PROVIDER_OPTIONS[0],
- );
-
- const [apiKeyValue, setApiKeyValue] = useState("");
-
- const { completeOnboarding } = useCompleteOnboarding();
-
- return (
-
-
Autocomplete Model
-
- Tab autocomplete requires a separate model. Currently we are supporting
- free usage by signing in with GitHub. Alternatively, select another
- option from the dropdown.
-
-
-
-
-
-
-
-
- {selectedProvider.provider === "ollama" && (
-
- {
- navigate("/localOnboarding");
- }}
- >
- Set up Ollama
-
-
- )}
- {selectedProvider.provider === "free-trial" && (
-
-
Sign in to GitHub to try autocomplete for free
-
{
- await ideMessenger.request("addAutocompleteModel", {
- model: {
- title: "Autocomplete Trial",
- provider: "free-trial",
- model: TRIAL_FIM_MODEL,
- },
- });
-
- completeOnboarding();
- }}
- >
-
- )}
- {selectedProvider.provider === "fireworks" && (
-
-
Paste your API key
- {
- ideMessenger.post("openUrl", "https://fireworks.ai/api-keys");
- }}
- >
- Get API Key
-
- {
- setApiKeyValue(e.target.value);
- }}
- />
- {
- await ideMessenger.request("addAutocompleteModel", {
- model: {
- title: "Fireworks Autocomplete",
- provider: "fireworks",
- model: "starcoder-7b",
- apiKey: apiKeyValue,
- },
- });
-
- completeOnboarding();
- }}
- >
- Save
-
-
- )}
-
- );
-}
-
-export default ApiKeyAutocompleteOnboarding;
diff --git a/gui/src/pages/onboarding/components.ts b/gui/src/pages/onboarding/components.ts
deleted file mode 100644
index 243606722..000000000
--- a/gui/src/pages/onboarding/components.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import styled from "styled-components";
-import {
- Button,
- defaultBorderRadius,
- lightGray,
- vscForeground,
-} from "../../components";
-
-export const StyledButton = styled(Button)<{ blurColor?: string }>`
- background-color: transparent;
- color: ${vscForeground};
- border: 1px solid ${lightGray}cc;
-
- &:hover {
- border: 1px solid ${lightGray};
- background-color: ${lightGray}22;
- }
-`;
-
-export const Div = styled.div<{
- selected: boolean;
-}>`
- border: 1px solid ${lightGray};
- border-radius: ${defaultBorderRadius};
- transition: all 0.2s;
- padding-left: 16px;
- padding-right: 16px;
-
- &:hover {
- ${(props) => (props.selected ? "" : `background-color: ${lightGray}22;`)}
- box-shadow: 0 0 4px 0px ${lightGray};
- cursor: pointer;
- }
-
- ${(props) =>
- props.selected &&
- `
- background-color: ${lightGray}44;
- box-shadow: 0 0 4px 0px ${lightGray};
- `}
-`;
diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts
index 0d6671162..8fa71ca61 100644
--- a/gui/src/redux/slices/uiStateSlice.ts
+++ b/gui/src/redux/slices/uiStateSlice.ts
@@ -1,4 +1,9 @@
import { PayloadAction, createSlice } from "@reduxjs/toolkit";
+import {
+ defaultOnboardingCardState,
+ OnboardingCardState,
+} from "../../components/OnboardingCard";
+
type UiState = {
bottomMessage: JSX.Element | undefined;
bottomMessageCloseTimeout: NodeJS.Timeout | undefined;
@@ -6,6 +11,7 @@ type UiState = {
showDialog: boolean;
dialogMessage: string | JSX.Element | undefined;
dialogEntryOn: boolean;
+ onboardingCard: OnboardingCardState;
};
export const uiStateSlice = createSlice({
@@ -17,8 +23,15 @@ export const uiStateSlice = createSlice({
dialogMessage: "",
dialogEntryOn: false,
displayBottomMessageOnBottom: true,
+ onboardingCard: defaultOnboardingCardState,
} as UiState,
reducers: {
+ setOnboardingCard: (
+ state,
+ action: PayloadAction>,
+ ) => {
+ state.onboardingCard = { ...state.onboardingCard, ...action.payload };
+ },
setBottomMessage: (
state,
action: PayloadAction,
@@ -59,6 +72,7 @@ export const uiStateSlice = createSlice({
});
export const {
+ setOnboardingCard,
setBottomMessage,
setBottomMessageCloseTimeout,
setDialogMessage,
@@ -66,4 +80,5 @@ export const {
setShowDialog,
setDisplayBottomMessageOnBottom,
} = uiStateSlice.actions;
+
export default uiStateSlice.reducer;
diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts
index a4e96a194..663c8e7bc 100644
--- a/gui/src/util/index.ts
+++ b/gui/src/util/index.ts
@@ -1,5 +1,5 @@
-import { getLocalStorage } from "./localStorage";
import _ from "lodash";
+import { getLocalStorage } from "./localStorage";
type Platform = "mac" | "linux" | "windows" | "unknown";
diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts
index 1eecda363..69461cc3c 100644
--- a/gui/src/util/localStorage.ts
+++ b/gui/src/util/localStorage.ts
@@ -1,9 +1,10 @@
import { JSONContent } from "@tiptap/react";
import { IndexingProgressUpdate } from "core";
-import { OnboardingStatus } from "../pages/onboarding/utils";
+import { OnboardingStatus } from "../components/OnboardingCard";
type LocalStorageTypes = {
onboardingStatus?: OnboardingStatus;
+ hasDismissedOnboardingCard: boolean;
mainTextEntryCounter: number;
ide: "vscode" | "jetbrains";
ftc: number;
@@ -12,8 +13,6 @@ type LocalStorageTypes = {
inputHistory: JSONContent[];
extensionVersion: string;
indexingState: IndexingProgressUpdate;
- signedInToGh: boolean;
- isOnboardingInProgress: boolean;
showTutorialCard: boolean;
shownProfilesIntroduction: boolean;
disableIndexing: boolean;
diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs
index 6dcf5d87b..26c9495f5 100644
--- a/gui/tailwind.config.cjs
+++ b/gui/tailwind.config.cjs
@@ -1,5 +1,5 @@
/** @type {import('tailwindcss').Config} */
-const colors = require("tailwindcss/colors");
+const defaultTheme = require("tailwindcss/defaultTheme");
module.exports = {
content: [
@@ -8,11 +8,18 @@ module.exports = {
"./src/*.{js,ts,jsx,tsx}",
],
theme: {
- extend: {},
- colors: {
- ...colors, // This spreads all default Tailwind colors
- "vsc-background": "rgb(var(--vsc-background) / )",
- "secondary-dark": "rgb(var(--secondary-dark) / )",
+ screens: {
+ xs: "425px",
+ ...defaultTheme.screens,
+ },
+ extend: {
+ animation: {
+ "spin-slow": "spin 30s linear infinite",
+ },
+ colors: {
+ "vsc-background": "rgb(var(--vsc-background) / )",
+ "secondary-dark": "rgb(var(--secondary-dark) / )",
+ },
},
},
plugins: [],
diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts
index 3a47980bc..261eaf090 100644
--- a/packages/openai-adapters/src/index.ts
+++ b/packages/openai-adapters/src/index.ts
@@ -68,6 +68,11 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi {
...config,
apiBase: "https://api.together.xyz/v1/",
});
+ case "sambanova":
+ return new OpenAIApi({
+ ...config,
+ apiBase: "https://api.sambanova.ai/v1/",
+ });
default:
throw new Error(`Unsupported LLM API format: ${config.provider}`);
}
diff --git a/packages/openai-adapters/test/main.test.ts b/packages/openai-adapters/test/main.test.ts
index c4615a05b..77cae38ec 100644
--- a/packages/openai-adapters/test/main.test.ts
+++ b/packages/openai-adapters/test/main.test.ts
@@ -204,6 +204,12 @@ const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [
apiKey: process.env.TOGETHER_API_KEY!,
chatOnly: true,
},
+ {
+ provider: "sambanova",
+ model: "Meta-Llama-3.1-8B-Instruct",
+ apiKey: process.env.SAMBANOVA_API_KEY!,
+ chatOnly: true,
+ },
];
const FIM_TESTS: LlmApiConfig[] = [